[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6RVFRNG694YHVXKQ4Y9FQRV":3,"skill-same:01M6RVFRNG694YHVXKQ4Y9FQRV":121},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":47,"repositoryHtmlUrl":48,"repositoryHomepageUrl":6,"ownerHtmlUrl":49,"ownerBlogUrl":50,"ownerDescription":51,"updatedAt":52,"install":53,"resources":66},"01M6RVFRNG694YHVXKQ4Y9FQRV","a2x-client-integration",null,"Integrates `@a2x\u002Fsdk` **client-side** into a TypeScript application — call remote A2A agents from a Node.js CLI, Express\u002FFastify backend, Next.js server action, or background worker. Covers `A2XClient`, the `AuthProvider` fallback chain, `AuthScheme` handling, token persistence, SSE streaming consumption, and error mapping. Use when the user says things like \"call an A2A agent\", \"use A2XClient\", \"consume an a2x agent\", \"add a2x client\", \"authenticate against an a2x agent\", \"stream from an a2x agent\", or wants to embed remote agent access into their own app.","planetarium\u002Fa2x","planetarium","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F4195773?v=4","01M6RVBZQPB0XARHVGE5M46XKA","Planetarium","01M6RVBZVN4RM8F815F054MGF1",2,"MIT","https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fskills\u002Fa2x-client-integration\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"a2x client integration","integration","client","worker","when","remote","fastify","error","chain","app","express","cli","token","next","sse streaming","node","access","server","streaming","typescript","2026-11-10 10:12:30",false,"---\nname: a2x-client-integration\ndescription: Integrates `@a2x\u002Fsdk` **client-side** into a TypeScript application — call remote A2A agents from a Node.js CLI, Express\u002FFastify backend, Next.js server action, or background worker. Covers `A2XClient`, the `AuthProvider` fallback chain, `AuthScheme` handling, token persistence, SSE streaming consumption, and error mapping. Use when the user says things like \"call an A2A agent\", \"use A2XClient\", \"consume an a2x agent\", \"add a2x client\", \"authenticate against an a2x agent\", \"stream from an a2x agent\", or wants to embed remote agent access into their own app.\n---\n\n# a2x-client-integration\n\nConsume remote A2A agents from any TypeScript application using `@a2x\u002Fsdk` (via the `@a2x\u002Fsdk\u002Fclient` subpath).\n\nThe server side is covered by the companion [`a2x-integration`](..\u002Fa2x-agent-integration\u002FSKILL.md) skill — this skill focuses exclusively on the **caller** side: fetching the agent card, authenticating dynamically against the agent's declared security schemes, sending messages, streaming SSE events, and surviving token expiry.\n\nThe `a2x` CLI (`packages\u002Fcli\u002Fsrc\u002Fcli-auth-provider.ts` + `packages\u002Fcli\u002Fsrc\u002Ftoken-store.ts`) is the reference implementation. This skill follows it while hardening documented integration patterns where the CLI's local compatibility format has known limits, such as duplicate auth-scheme classes in one requirement group.\n\n---\n\n## Before You Start\n\n**IMPORTANT**: `@a2x\u002Fsdk` evolves quickly. Before writing code:\n\n1. Install the latest `@a2x\u002Fsdk` (never hardcode versions).\n2. Read actual type definitions from `node_modules\u002F@a2x\u002Fsdk\u002Fdist\u002Fclient\u002Findex.d.ts` to confirm the current API surface.\n3. If a class or export referenced in this skill is missing, search `node_modules\u002F@a2x\u002Fsdk` for the closest equivalent — the normalization logic and `AuthProvider` contract have been stable, but scheme class names may shift.\n\n---\n\n## Wiki Reference\n\nThis skill uses a wiki-style structure. Detailed reference material is in the `wiki\u002F` directory:\n\n| Topic | File | Description |\n|-------|------|-------------|\n| **Client Architecture** | [wiki\u002Fclient-architecture.md](.\u002Fwiki\u002Fclient-architecture.md) | How `A2XClient` resolves, authenticates, sends, streams |\n| **Agent Card Resolution** | [wiki\u002Fagent-card-resolution.md](.\u002Fwiki\u002Fagent-card-resolution.md) | Well-known paths, protocol version detection, endpoint URL |\n| **Auth Provider Contract** | [wiki\u002Fauth-provider.md](.\u002Fwiki\u002Fauth-provider.md) | `AuthProvider` interface, OR-of-ANDs normalization, lifecycle |\n| **Auth Schemes** | [wiki\u002Fauth-schemes.md](.\u002Fwiki\u002Fauth-schemes.md) | Every built-in `AuthScheme` class — how to feed each one |\n| **Fallback Chain** | [wiki\u002Fauth-fallback-chain.md](.\u002Fwiki\u002Fauth-fallback-chain.md) | **Stored → Interactive → Refresh** chain from the CLI reference |\n| **Token Persistence** | [wiki\u002Ftoken-persistence.md](.\u002Fwiki\u002Ftoken-persistence.md) | File-based store pattern, credential extraction, security notes |\n| **OAuth2 Device Code** | [wiki\u002Foauth2-device-code.md](.\u002Fwiki\u002Foauth2-device-code.md) | Full device-code polling loop for headless clients |\n| **Streaming** | [wiki\u002Fstreaming.md](.\u002Fwiki\u002Fstreaming.md) | `sendMessageStream`, SSE parsing, cancellation, terminal states |\n| **Error Handling** | [wiki\u002Ferror-handling.md](.\u002Fwiki\u002Ferror-handling.md) | JSON-RPC error codes, auth-required refresh, connection errors |\n\n### Host-Environment Guides\n\n| Environment | File |\n|-------------|------|\n| **Node.js CLI (interactive)** | [wiki\u002Fhost-cli.md](.\u002Fwiki\u002Fhost-cli.md) |\n| **Backend service (non-interactive)** | [wiki\u002Fhost-backend.md](.\u002Fwiki\u002Fhost-backend.md) |\n| **Next.js server action \u002F route handler** | [wiki\u002Fhost-nextjs.md](.\u002Fwiki\u002Fhost-nextjs.md) |\n| **Browser (SPA)** | [wiki\u002Fhost-browser.md](.\u002Fwiki\u002Fhost-browser.md) |\n\n---\n\n## Workflow\n\n### Step 0 — Analyze the Host Project\n\nBefore any implementation:\n\n1. Read `package.json` to identify the package manager, runtime (Node vs. browser), and existing HTTP\u002FUI framework.\n2. Determine the **host environment** — this drives how you implement `AuthProvider.provide()`:\n   - **Interactive CLI** — prompt user on stdin (device-code flow, prompts for keys). See [wiki\u002Fhost-cli.md](.\u002Fwiki\u002Fhost-cli.md).\n   - **Backend service \u002F cron \u002F worker** — credentials come from env vars or a secret manager. No prompting. See [wiki\u002Fhost-backend.md](.\u002Fwiki\u002Fhost-backend.md).\n   - **Next.js server action \u002F route handler** — credentials come from the session \u002F request headers. No prompting. See [wiki\u002Fhost-nextjs.md](.\u002Fwiki\u002Fhost-nextjs.md).\n   - **Browser** — credentials come from a login flow (redirect-based OAuth or an upstream proxy). See [wiki\u002Fhost-browser.md](.\u002Fwiki\u002Fhost-browser.md).\n3. Identify which remote agent(s) the user is calling and which **security schemes** those agents advertise (`GET \u002F.well-known\u002Fagent.json` → `securitySchemes` \u002F `security` \u002F `securityRequirements`). The right `AuthProvider` implementation is driven by this.\n\n---\n\n### Step 1 — Install the Package\n\n```bash\n# Use the project's package manager\nnpm install @a2x\u002Fsdk\n```\n\nOnly the **client** subpath and the root types are needed on the caller side:\n\n```typescript\nimport {\n  A2XClient,\n  getAgentEndpointUrl,\n  resolveAgentCard,\n} from '@a2x\u002Fsdk\u002Fclient';\nimport type { SendMessageParams, Task, TaskStatusUpdateEvent, TaskArtifactUpdateEvent } from '@a2x\u002Fsdk';\n```\n\nYou do **not** need to install any LLM provider SDK (`@google\u002Fgenai`, `@anthropic-ai\u002Fsdk`, `openai`) — those are only required for agent servers.\n\nAfter installation, verify the expected exports exist:\n\n```bash\ngrep -rE \"^export\" node_modules\u002F@a2x\u002Fsdk\u002Fdist\u002Fclient\u002Findex.d.ts 2>\u002Fdev\u002Fnull\n```\n\nLook for:\n\n| Export | Purpose |\n|--------|---------|\n| `A2XClient` | Client class |\n| `AuthProvider` (type) | Interface you implement |\n| `AuthScheme`, `ApiKeyAuthScheme`, `HttpBearerAuthScheme`, … | Scheme classes the SDK hands to your provider |\n| `resolveAgentCard` | Standalone card fetcher |\n| `normalizeRequirements`, `normalizeScheme` | Exposed for advanced cases |\n\n---\n\n### Step 2 — Pick an AuthProvider Strategy\n\n`AuthProvider` is the integration point between the SDK and the host application. The SDK never decides **how** credentials are obtained — it only calls your provider with the normalized OR-of-ANDs requirement list and expects a resolved group back.\n\nMap your host environment to a pattern:\n\n| Environment | `provide()` behavior | `refresh()` behavior |\n|-------------|----------------------|----------------------|\n| Interactive CLI | Prompt the user; persist result to `~\u002F.a2x\u002Ftokens.json` | Clear stored token, re-prompt |\n| Backend service | Read from env \u002F secret manager | Throw (let the call fail) or re-read |\n| Next.js route | Read from session cookie \u002F headers | Trigger re-auth redirect upstream |\n| Browser | Read from in-memory auth store; `window.location` redirect for OAuth | Trigger re-auth redirect |\n\nThe [CLI reference implementation](.\u002Fwiki\u002Fauth-fallback-chain.md) composes the three steps into one chain:\n\n1. **Stored credentials first** — try cached values; if they match a requirement group, use them.\n2. **Interactive fallback** — if none match, prompt the user for a group they can satisfy.\n3. **Refresh on `auth-required`** — when a task-creating response reports the protocol-level `auth-required` state, clear the cache and re-run the interactive step.\n\nPick the subset that makes sense for your host. Backend services typically skip step 2 entirely.\n\n---\n\n### Step 3 — Implement the Provider\n\nCreate a file appropriate to the host (e.g. `src\u002Flib\u002Fa2a-auth.ts` for a backend, `src\u002Fcli\u002Fauth-provider.ts` for a CLI).\n\nMinimal non-interactive (backend) shape — read credentials from env:\n\n```typescript\nimport type { AuthProvider } from '@a2x\u002Fsdk\u002Fclient';\nimport {\n  AuthScheme,\n  ApiKeyAuthScheme,\n  HttpBearerAuthScheme,\n} from '@a2x\u002Fsdk\u002Fclient';\n\nconst API_KEY_ENV_BY_SLOT: Record\u003Cstring, string> = {\n  'header:x-api-key': 'AGENT_API_KEY',\n  'header:x-tenant-key': 'AGENT_TENANT_API_KEY',\n};\n\nfunction apiKeySlot(scheme: ApiKeyAuthScheme): string {\n  const name = scheme.params.location === 'header'\n    ? scheme.params.name.toLowerCase()\n    : scheme.params.name;\n  return `${scheme.params.location}:${name}`;\n}\n\nexport class EnvAuthProvider implements AuthProvider {\n  async provide(requirements: AuthScheme[][]): Promise\u003CAuthScheme[]> {\n    \u002F\u002F Pick the first group we can satisfy from env.\n    for (const group of requirements) {\n      const credentials = group.map((scheme) => this.readCredential(scheme));\n      if (credentials.every(\n        (value): value is string => typeof value === 'string' && value.length > 0,\n      )) {\n        group.forEach((scheme, index) => scheme.setCredential(credentials[index]!));\n        return group;\n      }\n    }\n    throw new Error(\n      'No configured credentials match the agent security requirements',\n    );\n  }\n\n  private readCredential(scheme: AuthScheme): string | undefined {\n    if (scheme instanceof ApiKeyAuthScheme) {\n      const envName = API_KEY_ENV_BY_SLOT[apiKeySlot(scheme)];\n      return envName ? process.env[envName] : undefined;\n    }\n    if (scheme instanceof HttpBearerAuthScheme) {\n      return process.env.AGENT_BEARER_TOKEN;\n    }\n    return undefined;\n  }\n}\n```\n\nMap every API-key location\u002Fname pair separately; one AND group may require multiple API keys. The current SDK has known requirement-normalization and credential-destination gaps ([#237](https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fissues\u002F237)): reject partial AND groups yourself, do not combine schemes that compete for `Authorization` or the same API-key destination, and do not rely on multiple cookie API keys composing. OAuth schemes expose the flow catalogue as `params.scopes`, but selected security-requirement values are not preserved on normalized scheme instances. Configure the exact requested scopes in host policy, verify them against the raw approved card before constructing the client, and request only that configured set. Treat identity endpoints and scopes advertised by an agent card as untrusted until the exact card URL, resolved agent endpoint, HTTPS identity endpoints, client identity, audience\u002Fresource, and scopes match one host policy tuple. The backend and OAuth wiki pages show the pattern.\n\nFor an interactive CLI, follow [wiki\u002Fhost-cli.md](.\u002Fwiki\u002Fhost-cli.md) — it reproduces the full fallback chain including the OAuth2 device-code polling loop.\n\n---\n\n### Step 4 — Wire Up `A2XClient`\n\n```typescript\nimport {\n  A2XClient,\n  getAgentEndpointUrl,\n  resolveAgentCard,\n} from '@a2x\u002Fsdk\u002Fclient';\nimport type { SendMessageParams } from '@a2x\u002Fsdk';\nimport crypto from 'node:crypto';\n\nfunction exactHttpsUrl(raw: string | undefined, label: string): string {\n  if (!raw) throw new Error(`${label} is required`);\n  const url = new URL(raw);\n  if (\n    url.protocol !== 'https:' || url.username || url.password ||\n    url.search || url.hash\n  ) throw new Error(`${label} must be an exact credential-free HTTPS URL`);\n  return url.toString();\n}\nfunction requireJsonRpcEndpoint(card: unknown, version: '0.3' | '1.0'): string {\n  if (version === '1.0') {\n    const interfaces = (card as {\n      supportedInterfaces?: Array\u003C{ url: string; protocolBinding?: string }>;\n    }).supportedInterfaces ?? [];\n    const jsonRpc = interfaces.find(entry =>\n      entry.protocolBinding?.toUpperCase() === 'JSONRPC'\n    );\n    if (!jsonRpc) throw new Error('AgentCard has no JSON-RPC interface');\n    return jsonRpc.url;\n  }\n  return getAgentEndpointUrl(card as Parameters\u003Ctypeof getAgentEndpointUrl>[0], version);\n}\nconst AGENT_CARD_URL = exactHttpsUrl(\n  process.env.AGENT_CARD_URL,\n  'AGENT_CARD_URL',\n);\nif (!new URL(AGENT_CARD_URL).pathname.endsWith('.json')) {\n  throw new Error('AGENT_CARD_URL must name one exact JSON document');\n}\nconst EXPECTED_AGENT_ENDPOINT = exactHttpsUrl(\n  process.env.AGENT_ENDPOINT_URL,\n  'AGENT_ENDPOINT_URL',\n);\nconst noRedirectFetch: typeof fetch = (input, init) =>\n  fetch(input, { ...init, redirect: 'error' });\nconst resolved = await resolveAgentCard(AGENT_CARD_URL, {\n  fetch: noRedirectFetch,\n});\nconst endpoint = exactHttpsUrl(\n  requireJsonRpcEndpoint(resolved.card, resolved.version),\n  'AgentCard endpoint',\n);\nif (endpoint !== EXPECTED_AGENT_ENDPOINT) {\n  throw new Error(`AgentCard endpoint is not approved: ${endpoint}`);\n}\n\nconst client = new A2XClient(resolved.card, {\n  headers: { 'User-Agent': 'my-app\u002F1.0' },\n  authProvider: new EnvAuthProvider(),\n  extensions: ['https:\u002F\u002Fexample.com\u002Fmy-a2a-extension\u002Fv1'],\n  fetch: noRedirectFetch,\n});\n\nconst params: SendMessageParams = {\n  message: {\n    messageId: crypto.randomUUID(),\n    role: 'user',\n    parts: [{ text: 'Hello' }],\n  },\n};\n\nconst task = await client.sendMessage(params);\nconsole.log(task.status?.state, task.artifacts);\n```\n\n`AGENT_CARD_URL` and `EXPECTED_AGENT_ENDPOINT` must be exact HTTPS deployment-policy values; validate credentials\u002Fhash\u002Fquery and the exact `.json` card path as shown in [the backend preflight](.\u002Fwiki\u002Fhost-backend.md#client-lifetime). `A2XClient` transparently handles:\n\n- Fetching `\u002F.well-known\u002Fagent.json` (tries `agent.json` then `agent-card.json`)\n- Detecting protocol version (v0.3 vs. v1.0) from the card structure\n- Normalizing security requirements into `AuthScheme[][]` and calling your provider\n- Formatting the message body per protocol version\n- Activating requested A2A extensions through `X-A2A-Extensions`\n- Retrying a task-creating call once when its result is `auth-required` and `authProvider.refresh()` exists\n\nAn HTTP 401 is a transport failure and is surfaced as `InternalError`; it does not invoke `refresh()` automatically.\n\n---\n\n### Step 5 — Stream (Optional)\n\n```typescript\nconst stream = client.sendMessageStream(params);\n\nfor await (const event of stream) {\n  if ('status' in event) {\n    console.log('status →', event.status.state);\n  } else {\n    \u002F\u002F artifact-update event\n    for (const part of event.artifact.parts) {\n      if ('text' in part) process.stdout.write(part.text);\n    }\n  }\n}\n```\n\nCancellation via `AbortSignal`:\n\n```typescript\nconst ac = new AbortController();\nsetTimeout(() => ac.abort(), 30_000);\n\nfor await (const event of client.sendMessageStream(params, ac.signal)) { \u002F* … *\u002F }\n```\n\nSee [wiki\u002Fstreaming.md](.\u002Fwiki\u002Fstreaming.md) for SSE format details, terminal-state detection, and error handling during a stream.\n\n---\n\n### Step 6 — Enable x402 Payments (Optional)\n\n`A2XClient` can run the payer-side x402 flow transparently. Install the optional payment peers, provide a viem `LocalAccount`, and always set a per-requirement authorization ceiling:\n\n```bash\nnpm install @a2x\u002Fsdk @x402\u002Fcore @x402\u002Fevm viem\n```\n\n```typescript\nconst paidClient = new A2XClient(resolved.card, {\n  fetch: noRedirectFetch,\n  authProvider: new EnvAuthProvider(),\n  x402: {\n    signer,\n    maxAmount: 10_000n,\n    \u002F\u002F This receives the complete accepts[] envelope before offer selection.\n    onPaymentRequired: async (required) => confirmEnvelopeWithUser(required),\n  },\n});\n```\n\n`maxAmount` is expressed in the asset's atomic units and applies to each selected requirement (or each new batch deposit); it is not an aggregate wallet budget across calls. The default selector chooses an affordable EVM `exact` offer. Enable `allowUpto` only with explicit consent because it authorizes a charge up to the advertised maximum. To use `batch-settlement`, provide `batchSettlement` storage and opt in with `allowBatchSettlement`; route each payer through a durable single-owner queue\u002Factor for the full sign → submit → reconcile lifecycle.\n\n`onPaymentRequired` currently receives the live envelope. Treat it as read-only: mutation can change later selection or signing. Likewise, a custom `selectRequirement` must not mutate candidates and should return one supplied entry; see the payer-isolation bug [#241](https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fissues\u002F241). Drive the [low-level manual flow](https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fpackages\u002Fa2x\u002Fdocs\u002Fguides\u002Fadvanced\u002Fx402-payments.md#low-level-signx402payment) when the user must approve the exact selected offer. A custom selector is itself explicit scheme consent: it bypasses `allowUpto` and `allowBatchSettlement`, although `maxAmount` still filters offers and batch selection still requires `batchSettlement`. Never embed a service private key in a browser bundle; use a user-owned restricted signer or a backend payer. See the [x402 payments guide](https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fpackages\u002Fa2x\u002Fdocs\u002Fguides\u002Fadvanced\u002Fx402-payments.md) for reconciliation and recovery requirements.\n\n---\n\n### Step 7 — Verify\n\n1. **Build check** — Run the project's type-check (`tsc --noEmit`).\n2. **Agent card fetch** — manually or via the built-in resolver:\n   ```typescript\n   console.log(resolved.version, resolved.card);\n   ```\n3. **Send a message** — confirm the round-trip works with your `AuthProvider`.\n4. **Simulate token expiry** — make the server return an `auth-required` unary task or an `auth-required` status as the first stream event, then confirm `refresh()` is invoked and the request is retried.\n5. **Try with the `a2x` CLI** for a sanity check against the same agent:\n   ```bash\n   a2x a2a agent-card \u003CAGENT_CARD_URL>\n   a2x a2a send \u003CAGENT_CARD_URL> \"ping\"\n   ```\n\n---\n\n## The Authentication Fallback Chain (Reference)\n\nThe CLI in this repo implements a three-step fallback that every interactive client should follow. Full walkthrough in [wiki\u002Fauth-fallback-chain.md](.\u002Fwiki\u002Fauth-fallback-chain.md); summary:\n\n```\nprovide(requirements)\n  │\n  ├─ 1. Stored credentials?           ─ yes →  match every credential slot    → return group\n  │                                             (scheme.setCredential from cache)\n  │                                   ─ no  ↓\n  ├─ 2. Interactive resolution\n  │     • If 1 group → use it\n  │     • If >1 groups → ask user to pick\n  │     • For each scheme in the group → prompt \u002F device-code \u002F etc.\n  │     • Save resolved credentials to the store\n  │     ↓\n  └─ return group\n\n\nrefresh(schemes)  ← SDK calls this after an auth-required task\u002Fevent\n  • Clear stored credentials for this validated policy tuple\n  • Re-run interactive resolution for the same schemes\n  • Save the new values\n  • Return the (same) scheme instances, now holding new credentials\n```\n\nThree properties are load-bearing:\n\n1. **Persist a unique credential-slot key.** Key each slot by requirement-group index, scheme index, class, and public parameters, nested under the validated card\u002Fendpoint\u002Fidentity-policy key. A valid group can contain two API-key schemes with different names.\n2. **Scheme instances are mutated, not replaced.** `AuthProvider` returns the same instances the SDK handed in — only `setCredential()` has been called. The SDK will then call `applyToRequest(ctx)` on each.\n3. **Credential extraction goes through `applyToRequest`.** The stored credential isn't exposed directly on the scheme; the CLI recovers it by running `applyToRequest` against a dummy context and reading the resulting `Authorization` \u002F header \u002F query value back out. This keeps the provider agnostic of each scheme's private state.\n\nSee [wiki\u002Ftoken-persistence.md](.\u002Fwiki\u002Ftoken-persistence.md) for the `extractCredential` helper and [wiki\u002Fauth-schemes.md](.\u002Fwiki\u002Fauth-schemes.md) for per-scheme handling.\n\n---\n\n## Key Classes and Their Contracts\n\n| Class \u002F Type | Where | Contract |\n|-------------|-------|----------|\n| `A2XClient` | `@a2x\u002Fsdk\u002Fclient` | One instance per remote agent; caches the resolved card and auth schemes; optionally activates extensions and runs x402 payments |\n| `AuthProvider` | `@a2x\u002Fsdk\u002Fclient` | `provide(req[][])` → `AuthScheme[]`; optional `refresh(schemes)` |\n| `AuthScheme` (base) | `@a2x\u002Fsdk\u002Fclient` | `setCredential(string): this`; `applyToRequest(ctx): void` |\n| `ApiKeyAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `params: { name, location }`; header \u002F query \u002F cookie placement |\n| `HttpBearerAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `Authorization: Bearer \u003Ctoken>` |\n| `HttpBasicAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `Authorization: Basic \u003Cbase64>` |\n| `OAuth2DeviceCodeAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `params: { deviceAuthorizationUrl, tokenUrl, scopes, refreshUrl? }` |\n| `OAuth2AuthorizationCodeAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `params: { authorizationUrl, tokenUrl, scopes, refreshUrl?, pkceRequired? }` |\n| `OAuth2ClientCredentialsAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `params: { tokenUrl, scopes, refreshUrl? }` |\n| `OAuth2ImplicitAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `params: { authorizationUrl, scopes, refreshUrl? }` |\n| `OAuth2PasswordAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `params: { tokenUrl, scopes, refreshUrl? }` |\n| `OpenIdConnectAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `params: { openIdConnectUrl }` |\n| `resolveAgentCard` | `@a2x\u002Fsdk\u002Fclient` | Standalone card fetcher; tries well-known paths |\n| `normalizeRequirements` | `@a2x\u002Fsdk\u002Fclient` | Low-level; expose if you want to inspect requirements without a client |\n\n---\n\n## What This Skill Does NOT Cover\n\n- **Server-side integration** — how to expose an A2A agent. See [`a2x-integration`](..\u002Fa2x-agent-integration\u002FSKILL.md).\n- **Agent authoring** — writing `LlmAgent`, tools, providers. See [`a2x-integration\u002Fwiki\u002Ftools-and-agents.md`](..\u002Fa2x-agent-integration\u002Fwiki\u002Ftools-and-agents.md).\n- **Merchant-side x402 policy** — pricing, verification, settlement, and durable merchant state. See the [x402 payments guide](https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fpackages\u002Fa2x\u002Fdocs\u002Fguides\u002Fadvanced\u002Fx402-payments.md).\n- **CLI usage** — use the packaged `a2x` CLI and its `a2a`, `wallet`, and `x402` command help.\n\n---\n\n## After Applying\n\nRemind the user to:\n\n1. Set any environment variables the `AuthProvider` needs (API keys, bearer tokens, OAuth client IDs).\n2. Audit the token storage location if they enabled persistence. The reference CLI writes a plaintext `0600` file and creates its directory as `0700` when absent, but it does not repair an existing directory's mode; production applications should prefer an OS keychain or secret manager.\n3. Add a **connection error** path distinct from an **auth** path — the SDK throws `InternalError` for HTTP-level failures and typed `A2AError` subclasses (e.g. `TaskNotFoundError`) for protocol-level failures, while protocol-level task authentication failures surface as `auth-required` state (not a thrown error). See [wiki\u002Ferror-handling.md](.\u002Fwiki\u002Ferror-handling.md).\n4. Consider retry \u002F backoff for `getTask`. Reconcile `cancelTask` after an ambiguous transport failure because the first cancellation may already have succeeded; never automatically retry `sendMessage` without an application-level idempotency strategy.\n","# a2x-client-integration\n\nConsume remote A2A agents from any TypeScript application using `@a2x\u002Fsdk` (via the `@a2x\u002Fsdk\u002Fclient` subpath).\n\nThe server side is covered by the companion [`a2x-integration`](..\u002Fa2x-agent-integration\u002FSKILL.md) skill — this skill focuses exclusively on the **caller** side: fetching the agent card, authenticating dynamically against the agent's declared security schemes, sending messages, streaming SSE events, and surviving token expiry.\n\nThe `a2x` CLI (`packages\u002Fcli\u002Fsrc\u002Fcli-auth-provider.ts` + `packages\u002Fcli\u002Fsrc\u002Ftoken-store.ts`) is the reference implementation. This skill follows it while hardening documented integration patterns where the CLI's local compatibility format has known limits, such as duplicate auth-scheme classes in one requirement group.\n\n---\n\n## Before You Start\n\n**IMPORTANT**: `@a2x\u002Fsdk` evolves quickly. Before writing code:\n\n1. Install the latest `@a2x\u002Fsdk` (never hardcode versions).\n2. Read actual type definitions from `node_modules\u002F@a2x\u002Fsdk\u002Fdist\u002Fclient\u002Findex.d.ts` to confirm the current API surface.\n3. If a class or export referenced in this skill is missing, search `node_modules\u002F@a2x\u002Fsdk` for the closest equivalent — the normalization logic and `AuthProvider` contract have been stable, but scheme class names may shift.\n\n---\n\n## Wiki Reference\n\nThis skill uses a wiki-style structure. Detailed reference material is in the `wiki\u002F` directory:\n\n| Topic | File | Description |\n|-------|------|-------------|\n| **Client Architecture** | [wiki\u002Fclient-architecture.md](.\u002Fwiki\u002Fclient-architecture.md) | How `A2XClient` resolves, authenticates, sends, streams |\n| **Agent Card Resolution** | [wiki\u002Fagent-card-resolution.md](.\u002Fwiki\u002Fagent-card-resolution.md) | Well-known paths, protocol version detection, endpoint URL |\n| **Auth Provider Contract** | [wiki\u002Fauth-provider.md](.\u002Fwiki\u002Fauth-provider.md) | `AuthProvider` interface, OR-of-ANDs normalization, lifecycle |\n| **Auth Schemes** | [wiki\u002Fauth-schemes.md](.\u002Fwiki\u002Fauth-schemes.md) | Every built-in `AuthScheme` class — how to feed each one |\n| **Fallback Chain** | [wiki\u002Fauth-fallback-chain.md](.\u002Fwiki\u002Fauth-fallback-chain.md) | **Stored → Interactive → Refresh** chain from the CLI reference |\n| **Token Persistence** | [wiki\u002Ftoken-persistence.md](.\u002Fwiki\u002Ftoken-persistence.md) | File-based store pattern, credential extraction, security notes |\n| **OAuth2 Device Code** | [wiki\u002Foauth2-device-code.md](.\u002Fwiki\u002Foauth2-device-code.md) | Full device-code polling loop for headless clients |\n| **Streaming** | [wiki\u002Fstreaming.md](.\u002Fwiki\u002Fstreaming.md) | `sendMessageStream`, SSE parsing, cancellation, terminal states |\n| **Error Handling** | [wiki\u002Ferror-handling.md](.\u002Fwiki\u002Ferror-handling.md) | JSON-RPC error codes, auth-required refresh, connection errors |\n\n### Host-Environment Guides\n\n| Environment | File |\n|-------------|------|\n| **Node.js CLI (interactive)** | [wiki\u002Fhost-cli.md](.\u002Fwiki\u002Fhost-cli.md) |\n| **Backend service (non-interactive)** | [wiki\u002Fhost-backend.md](.\u002Fwiki\u002Fhost-backend.md) |\n| **Next.js server action \u002F route handler** | [wiki\u002Fhost-nextjs.md](.\u002Fwiki\u002Fhost-nextjs.md) |\n| **Browser (SPA)** | [wiki\u002Fhost-browser.md](.\u002Fwiki\u002Fhost-browser.md) |\n\n---\n\n## Workflow\n\n### Step 0 — Analyze the Host Project\n\nBefore any implementation:\n\n1. Read `package.json` to identify the package manager, runtime (Node vs. browser), and existing HTTP\u002FUI framework.\n2. Determine the **host environment** — this drives how you implement `AuthProvider.provide()`:\n   - **Interactive CLI** — prompt user on stdin (device-code flow, prompts for keys). See [wiki\u002Fhost-cli.md](.\u002Fwiki\u002Fhost-cli.md).\n   - **Backend service \u002F cron \u002F worker** — credentials come from env vars or a secret manager. No prompting. See [wiki\u002Fhost-backend.md](.\u002Fwiki\u002Fhost-backend.md).\n   - **Next.js server action \u002F route handler** — credentials come from the session \u002F request headers. No prompting. See [wiki\u002Fhost-nextjs.md](.\u002Fwiki\u002Fhost-nextjs.md).\n   - **Browser** — credentials come from a login flow (redirect-based OAuth or an upstream proxy). See [wiki\u002Fhost-browser.md](.\u002Fwiki\u002Fhost-browser.md).\n3. Identify which remote agent(s) the user is calling and which **security schemes** those agents advertise (`GET \u002F.well-known\u002Fagent.json` → `securitySchemes` \u002F `security` \u002F `securityRequirements`). The right `AuthProvider` implementation is driven by this.\n\n---\n\n### Step 1 — Install the Package\n\n```bash\n# Use the project's package manager\nnpm install @a2x\u002Fsdk\n```\n\nOnly the **client** subpath and the root types are needed on the caller side:\n\n```typescript\nimport {\n  A2XClient,\n  getAgentEndpointUrl,\n  resolveAgentCard,\n} from '@a2x\u002Fsdk\u002Fclient';\nimport type { SendMessageParams, Task, TaskStatusUpdateEvent, TaskArtifactUpdateEvent } from '@a2x\u002Fsdk';\n```\n\nYou do **not** need to install any LLM provider SDK (`@google\u002Fgenai`, `@anthropic-ai\u002Fsdk`, `openai`) — those are only required for agent servers.\n\nAfter installation, verify the expected exports exist:\n\n```bash\ngrep -rE \"^export\" node_modules\u002F@a2x\u002Fsdk\u002Fdist\u002Fclient\u002Findex.d.ts 2>\u002Fdev\u002Fnull\n```\n\nLook for:\n\n| Export | Purpose |\n|--------|---------|\n| `A2XClient` | Client class |\n| `AuthProvider` (type) | Interface you implement |\n| `AuthScheme`, `ApiKeyAuthScheme`, `HttpBearerAuthScheme`, … | Scheme classes the SDK hands to your provider |\n| `resolveAgentCard` | Standalone card fetcher |\n| `normalizeRequirements`, `normalizeScheme` | Exposed for advanced cases |\n\n---\n\n### Step 2 — Pick an AuthProvider Strategy\n\n`AuthProvider` is the integration point between the SDK and the host application. The SDK never decides **how** credentials are obtained — it only calls your provider with the normalized OR-of-ANDs requirement list and expects a resolved group back.\n\nMap your host environment to a pattern:\n\n| Environment | `provide()` behavior | `refresh()` behavior |\n|-------------|----------------------|----------------------|\n| Interactive CLI | Prompt the user; persist result to `~\u002F.a2x\u002Ftokens.json` | Clear stored token, re-prompt |\n| Backend service | Read from env \u002F secret manager | Throw (let the call fail) or re-read |\n| Next.js route | Read from session cookie \u002F headers | Trigger re-auth redirect upstream |\n| Browser | Read from in-memory auth store; `window.location` redirect for OAuth | Trigger re-auth redirect |\n\nThe [CLI reference implementation](.\u002Fwiki\u002Fauth-fallback-chain.md) composes the three steps into one chain:\n\n1. **Stored credentials first** — try cached values; if they match a requirement group, use them.\n2. **Interactive fallback** — if none match, prompt the user for a group they can satisfy.\n3. **Refresh on `auth-required`** — when a task-creating response reports the protocol-level `auth-required` state, clear the cache and re-run the interactive step.\n\nPick the subset that makes sense for your host. Backend services typically skip step 2 entirely.\n\n---\n\n### Step 3 — Implement the Provider\n\nCreate a file appropriate to the host (e.g. `src\u002Flib\u002Fa2a-auth.ts` for a backend, `src\u002Fcli\u002Fauth-provider.ts` for a CLI).\n\nMinimal non-interactive (backend) shape — read credentials from env:\n\n```typescript\nimport type { AuthProvider } from '@a2x\u002Fsdk\u002Fclient';\nimport {\n  AuthScheme,\n  ApiKeyAuthScheme,\n  HttpBearerAuthScheme,\n} from '@a2x\u002Fsdk\u002Fclient';\n\nconst API_KEY_ENV_BY_SLOT: Record\u003Cstring, string> = {\n  'header:x-api-key': 'AGENT_API_KEY',\n  'header:x-tenant-key': 'AGENT_TENANT_API_KEY',\n};\n\nfunction apiKeySlot(scheme: ApiKeyAuthScheme): string {\n  const name = scheme.params.location === 'header'\n    ? scheme.params.name.toLowerCase()\n    : scheme.params.name;\n  return `${scheme.params.location}:${name}`;\n}\n\nexport class EnvAuthProvider implements AuthProvider {\n  async provide(requirements: AuthScheme[][]): Promise\u003CAuthScheme[]> {\n    \u002F\u002F Pick the first group we can satisfy from env.\n    for (const group of requirements) {\n      const credentials = group.map((scheme) => this.readCredential(scheme));\n      if (credentials.every(\n        (value): value is string => typeof value === 'string' && value.length > 0,\n      )) {\n        group.forEach((scheme, index) => scheme.setCredential(credentials[index]!));\n        return group;\n      }\n    }\n    throw new Error(\n      'No configured credentials match the agent security requirements',\n    );\n  }\n\n  private readCredential(scheme: AuthScheme): string | undefined {\n    if (scheme instanceof ApiKeyAuthScheme) {\n      const envName = API_KEY_ENV_BY_SLOT[apiKeySlot(scheme)];\n      return envName ? process.env[envName] : undefined;\n    }\n    if (scheme instanceof HttpBearerAuthScheme) {\n      return process.env.AGENT_BEARER_TOKEN;\n    }\n    return undefined;\n  }\n}\n```\n\nMap every API-key location\u002Fname pair separately; one AND group may require multiple API keys. The current SDK has known requirement-normalization and credential-destination gaps ([#237](https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fissues\u002F237)): reject partial AND groups yourself, do not combine schemes that compete for `Authorization` or the same API-key destination, and do not rely on multiple cookie API keys composing. OAuth schemes expose the flow catalogue as `params.scopes`, but selected security-requirement values are not preserved on normalized scheme instances. Configure the exact requested scopes in host policy, verify them against the raw approved card before constructing the client, and request only that configured set. Treat identity endpoints and scopes advertised by an agent card as untrusted until the exact card URL, resolved agent endpoint, HTTPS identity endpoints, client identity, audience\u002Fresource, and scopes match one host policy tuple. The backend and OAuth wiki pages show the pattern.\n\nFor an interactive CLI, follow [wiki\u002Fhost-cli.md](.\u002Fwiki\u002Fhost-cli.md) — it reproduces the full fallback chain including the OAuth2 device-code polling loop.\n\n---\n\n### Step 4 — Wire Up `A2XClient`\n\n```typescript\nimport {\n  A2XClient,\n  getAgentEndpointUrl,\n  resolveAgentCard,\n} from '@a2x\u002Fsdk\u002Fclient';\nimport type { SendMessageParams } from '@a2x\u002Fsdk';\nimport crypto from 'node:crypto';\n\nfunction exactHttpsUrl(raw: string | undefined, label: string): string {\n  if (!raw) throw new Error(`${label} is required`);\n  const url = new URL(raw);\n  if (\n    url.protocol !== 'https:' || url.username || url.password ||\n    url.search || url.hash\n  ) throw new Error(`${label} must be an exact credential-free HTTPS URL`);\n  return url.toString();\n}\nfunction requireJsonRpcEndpoint(card: unknown, version: '0.3' | '1.0'): string {\n  if (version === '1.0') {\n    const interfaces = (card as {\n      supportedInterfaces?: Array\u003C{ url: string; protocolBinding?: string }>;\n    }).supportedInterfaces ?? [];\n    const jsonRpc = interfaces.find(entry =>\n      entry.protocolBinding?.toUpperCase() === 'JSONRPC'\n    );\n    if (!jsonRpc) throw new Error('AgentCard has no JSON-RPC interface');\n    return jsonRpc.url;\n  }\n  return getAgentEndpointUrl(card as Parameters\u003Ctypeof getAgentEndpointUrl>[0], version);\n}\nconst AGENT_CARD_URL = exactHttpsUrl(\n  process.env.AGENT_CARD_URL,\n  'AGENT_CARD_URL',\n);\nif (!new URL(AGENT_CARD_URL).pathname.endsWith('.json')) {\n  throw new Error('AGENT_CARD_URL must name one exact JSON document');\n}\nconst EXPECTED_AGENT_ENDPOINT = exactHttpsUrl(\n  process.env.AGENT_ENDPOINT_URL,\n  'AGENT_ENDPOINT_URL',\n);\nconst noRedirectFetch: typeof fetch = (input, init) =>\n  fetch(input, { ...init, redirect: 'error' });\nconst resolved = await resolveAgentCard(AGENT_CARD_URL, {\n  fetch: noRedirectFetch,\n});\nconst endpoint = exactHttpsUrl(\n  requireJsonRpcEndpoint(resolved.card, resolved.version),\n  'AgentCard endpoint',\n);\nif (endpoint !== EXPECTED_AGENT_ENDPOINT) {\n  throw new Error(`AgentCard endpoint is not approved: ${endpoint}`);\n}\n\nconst client = new A2XClient(resolved.card, {\n  headers: { 'User-Agent': 'my-app\u002F1.0' },\n  authProvider: new EnvAuthProvider(),\n  extensions: ['https:\u002F\u002Fexample.com\u002Fmy-a2a-extension\u002Fv1'],\n  fetch: noRedirectFetch,\n});\n\nconst params: SendMessageParams = {\n  message: {\n    messageId: crypto.randomUUID(),\n    role: 'user',\n    parts: [{ text: 'Hello' }],\n  },\n};\n\nconst task = await client.sendMessage(params);\nconsole.log(task.status?.state, task.artifacts);\n```\n\n`AGENT_CARD_URL` and `EXPECTED_AGENT_ENDPOINT` must be exact HTTPS deployment-policy values; validate credentials\u002Fhash\u002Fquery and the exact `.json` card path as shown in [the backend preflight](.\u002Fwiki\u002Fhost-backend.md#client-lifetime). `A2XClient` transparently handles:\n\n- Fetching `\u002F.well-known\u002Fagent.json` (tries `agent.json` then `agent-card.json`)\n- Detecting protocol version (v0.3 vs. v1.0) from the card structure\n- Normalizing security requirements into `AuthScheme[][]` and calling your provider\n- Formatting the message body per protocol version\n- Activating requested A2A extensions through `X-A2A-Extensions`\n- Retrying a task-creating call once when its result is `auth-required` and `authProvider.refresh()` exists\n\nAn HTTP 401 is a transport failure and is surfaced as `InternalError`; it does not invoke `refresh()` automatically.\n\n---\n\n### Step 5 — Stream (Optional)\n\n```typescript\nconst stream = client.sendMessageStream(params);\n\nfor await (const event of stream) {\n  if ('status' in event) {\n    console.log('status →', event.status.state);\n  } else {\n    \u002F\u002F artifact-update event\n    for (const part of event.artifact.parts) {\n      if ('text' in part) process.stdout.write(part.text);\n    }\n  }\n}\n```\n\nCancellation via `AbortSignal`:\n\n```typescript\nconst ac = new AbortController();\nsetTimeout(() => ac.abort(), 30_000);\n\nfor await (const event of client.sendMessageStream(params, ac.signal)) { \u002F* … *\u002F }\n```\n\nSee [wiki\u002Fstreaming.md](.\u002Fwiki\u002Fstreaming.md) for SSE format details, terminal-state detection, and error handling during a stream.\n\n---\n\n### Step 6 — Enable x402 Payments (Optional)\n\n`A2XClient` can run the payer-side x402 flow transparently. Install the optional payment peers, provide a viem `LocalAccount`, and always set a per-requirement authorization ceiling:\n\n```bash\nnpm install @a2x\u002Fsdk @x402\u002Fcore @x402\u002Fevm viem\n```\n\n```typescript\nconst paidClient = new A2XClient(resolved.card, {\n  fetch: noRedirectFetch,\n  authProvider: new EnvAuthProvider(),\n  x402: {\n    signer,\n    maxAmount: 10_000n,\n    \u002F\u002F This receives the complete accepts[] envelope before offer selection.\n    onPaymentRequired: async (required) => confirmEnvelopeWithUser(required),\n  },\n});\n```\n\n`maxAmount` is expressed in the asset's atomic units and applies to each selected requirement (or each new batch deposit); it is not an aggregate wallet budget across calls. The default selector chooses an affordable EVM `exact` offer. Enable `allowUpto` only with explicit consent because it authorizes a charge up to the advertised maximum. To use `batch-settlement`, provide `batchSettlement` storage and opt in with `allowBatchSettlement`; route each payer through a durable single-owner queue\u002Factor for the full sign → submit → reconcile lifecycle.\n\n`onPaymentRequired` currently receives the live envelope. Treat it as read-only: mutation can change later selection or signing. Likewise, a custom `selectRequirement` must not mutate candidates and should return one supplied entry; see the payer-isolation bug [#241](https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fissues\u002F241). Drive the [low-level manual flow](https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fpackages\u002Fa2x\u002Fdocs\u002Fguides\u002Fadvanced\u002Fx402-payments.md#low-level-signx402payment) when the user must approve the exact selected offer. A custom selector is itself explicit scheme consent: it bypasses `allowUpto` and `allowBatchSettlement`, although `maxAmount` still filters offers and batch selection still requires `batchSettlement`. Never embed a service private key in a browser bundle; use a user-owned restricted signer or a backend payer. See the [x402 payments guide](https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fpackages\u002Fa2x\u002Fdocs\u002Fguides\u002Fadvanced\u002Fx402-payments.md) for reconciliation and recovery requirements.\n\n---\n\n### Step 7 — Verify\n\n1. **Build check** — Run the project's type-check (`tsc --noEmit`).\n2. **Agent card fetch** — manually or via the built-in resolver:\n   ```typescript\n   console.log(resolved.version, resolved.card);\n   ```\n3. **Send a message** — confirm the round-trip works with your `AuthProvider`.\n4. **Simulate token expiry** — make the server return an `auth-required` unary task or an `auth-required` status as the first stream event, then confirm `refresh()` is invoked and the request is retried.\n5. **Try with the `a2x` CLI** for a sanity check against the same agent:\n   ```bash\n   a2x a2a agent-card \u003CAGENT_CARD_URL>\n   a2x a2a send \u003CAGENT_CARD_URL> \"ping\"\n   ```\n\n---\n\n## The Authentication Fallback Chain (Reference)\n\nThe CLI in this repo implements a three-step fallback that every interactive client should follow. Full walkthrough in [wiki\u002Fauth-fallback-chain.md](.\u002Fwiki\u002Fauth-fallback-chain.md); summary:\n\n```\nprovide(requirements)\n  │\n  ├─ 1. Stored credentials?           ─ yes →  match every credential slot    → return group\n  │                                             (scheme.setCredential from cache)\n  │                                   ─ no  ↓\n  ├─ 2. Interactive resolution\n  │     • If 1 group → use it\n  │     • If >1 groups → ask user to pick\n  │     • For each scheme in the group → prompt \u002F device-code \u002F etc.\n  │     • Save resolved credentials to the store\n  │     ↓\n  └─ return group\n\n\nrefresh(schemes)  ← SDK calls this after an auth-required task\u002Fevent\n  • Clear stored credentials for this validated policy tuple\n  • Re-run interactive resolution for the same schemes\n  • Save the new values\n  • Return the (same) scheme instances, now holding new credentials\n```\n\nThree properties are load-bearing:\n\n1. **Persist a unique credential-slot key.** Key each slot by requirement-group index, scheme index, class, and public parameters, nested under the validated card\u002Fendpoint\u002Fidentity-policy key. A valid group can contain two API-key schemes with different names.\n2. **Scheme instances are mutated, not replaced.** `AuthProvider` returns the same instances the SDK handed in — only `setCredential()` has been called. The SDK will then call `applyToRequest(ctx)` on each.\n3. **Credential extraction goes through `applyToRequest`.** The stored credential isn't exposed directly on the scheme; the CLI recovers it by running `applyToRequest` against a dummy context and reading the resulting `Authorization` \u002F header \u002F query value back out. This keeps the provider agnostic of each scheme's private state.\n\nSee [wiki\u002Ftoken-persistence.md](.\u002Fwiki\u002Ftoken-persistence.md) for the `extractCredential` helper and [wiki\u002Fauth-schemes.md](.\u002Fwiki\u002Fauth-schemes.md) for per-scheme handling.\n\n---\n\n## Key Classes and Their Contracts\n\n| Class \u002F Type | Where | Contract |\n|-------------|-------|----------|\n| `A2XClient` | `@a2x\u002Fsdk\u002Fclient` | One instance per remote agent; caches the resolved card and auth schemes; optionally activates extensions and runs x402 payments |\n| `AuthProvider` | `@a2x\u002Fsdk\u002Fclient` | `provide(req[][])` → `AuthScheme[]`; optional `refresh(schemes)` |\n| `AuthScheme` (base) | `@a2x\u002Fsdk\u002Fclient` | `setCredential(string): this`; `applyToRequest(ctx): void` |\n| `ApiKeyAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `params: { name, location }`; header \u002F query \u002F cookie placement |\n| `HttpBearerAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `Authorization: Bearer \u003Ctoken>` |\n| `HttpBasicAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `Authorization: Basic \u003Cbase64>` |\n| `OAuth2DeviceCodeAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `params: { deviceAuthorizationUrl, tokenUrl, scopes, refreshUrl? }` |\n| `OAuth2AuthorizationCodeAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `params: { authorizationUrl, tokenUrl, scopes, refreshUrl?, pkceRequired? }` |\n| `OAuth2ClientCredentialsAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `params: { tokenUrl, scopes, refreshUrl? }` |\n| `OAuth2ImplicitAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `params: { authorizationUrl, scopes, refreshUrl? }` |\n| `OAuth2PasswordAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `params: { tokenUrl, scopes, refreshUrl? }` |\n| `OpenIdConnectAuthScheme` | `@a2x\u002Fsdk\u002Fclient` | `params: { openIdConnectUrl }` |\n| `resolveAgentCard` | `@a2x\u002Fsdk\u002Fclient` | Standalone card fetcher; tries well-known paths |\n| `normalizeRequirements` | `@a2x\u002Fsdk\u002Fclient` | Low-level; expose if you want to inspect requirements without a client |\n\n---\n\n## What This Skill Does NOT Cover\n\n- **Server-side integration** — how to expose an A2A agent. See [`a2x-integration`](..\u002Fa2x-agent-integration\u002FSKILL.md).\n- **Agent authoring** — writing `LlmAgent`, tools, providers. See [`a2x-integration\u002Fwiki\u002Ftools-and-agents.md`](..\u002Fa2x-agent-integration\u002Fwiki\u002Ftools-and-agents.md).\n- **Merchant-side x402 policy** — pricing, verification, settlement, and durable merchant state. See the [x402 payments guide](https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fpackages\u002Fa2x\u002Fdocs\u002Fguides\u002Fadvanced\u002Fx402-payments.md).\n- **CLI usage** — use the packaged `a2x` CLI and its `a2a`, `wallet`, and `x402` command help.\n\n---\n\n## After Applying\n\nRemind the user to:\n\n1. Set any environment variables the `AuthProvider` needs (API keys, bearer tokens, OAuth client IDs).\n2. Audit the token storage location if they enabled persistence. The reference CLI writes a plaintext `0600` file and creates its directory as `0700` when absent, but it does not repair an existing directory's mode; production applications should prefer an OS keychain or secret manager.\n3. Add a **connection error** path distinct from an **auth** path — the SDK throws `InternalError` for HTTP-level failures and typed `A2AError` subclasses (e.g. `TaskNotFoundError`) for protocol-level failures, while protocol-level task authentication failures surface as `auth-required` state (not a thrown error). See [wiki\u002Ferror-handling.md](.\u002Fwiki\u002Ferror-handling.md).\n4. Consider retry \u002F backoff for `getTask`. Reconcile `cancelTask` after an ambiguous transport failure because the first cancellation may already have succeeded; never automatically retry `sendMessage` without an application-level idempotency strategy.\n",{"name":5,"description":7},"main","979177bdf83f9694f14e4767069aa284ca283cc2","skills\u002Fa2x-client-integration",3,"https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x","https:\u002F\u002Fgithub.com\u002Fplanetarium","https:\u002F\u002Fplanetariumhq.com\u002F","We bring freedom and moddability to massively multiplayer games with decentralization and open source technology.","2026-11-06 21:12:05",{"source":8,"skillName":5,"commands":54,"prompt":64,"zipAvailable":65},[55,58,61],{"tool":56,"command":57},"npx","npx skills add planetarium\u002Fa2x --skill a2x-client-integration",{"tool":59,"command":60},"bunx","bunx skills add planetarium\u002Fa2x --skill a2x-client-integration",{"tool":62,"command":63},"pnpm","pnpm dlx skills add planetarium\u002Fa2x --skill a2x-client-integration","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fskills\u002Fa2x-client-integration\u002FSKILL.md",true,[67,73,77,81,85,89,93,97,101,105,109,113,117],{"path":68,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":71,"sourceHtmlUrl":72},"wiki\u002Fagent-card-resolution.md","REFERENCE","参考文档",6159,"https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fskills\u002Fa2x-client-integration\u002Fwiki\u002Fagent-card-resolution.md",{"path":74,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":75,"sourceHtmlUrl":76},"wiki\u002Fauth-fallback-chain.md",12674,"https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fskills\u002Fa2x-client-integration\u002Fwiki\u002Fauth-fallback-chain.md",{"path":78,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":79,"sourceHtmlUrl":80},"wiki\u002Fauth-provider.md",8376,"https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fskills\u002Fa2x-client-integration\u002Fwiki\u002Fauth-provider.md",{"path":82,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":83,"sourceHtmlUrl":84},"wiki\u002Fauth-schemes.md",7700,"https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fskills\u002Fa2x-client-integration\u002Fwiki\u002Fauth-schemes.md",{"path":86,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":87,"sourceHtmlUrl":88},"wiki\u002Fclient-architecture.md",7458,"https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fskills\u002Fa2x-client-integration\u002Fwiki\u002Fclient-architecture.md",{"path":90,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":91,"sourceHtmlUrl":92},"wiki\u002Ferror-handling.md",8636,"https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fskills\u002Fa2x-client-integration\u002Fwiki\u002Ferror-handling.md",{"path":94,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":95,"sourceHtmlUrl":96},"wiki\u002Fhost-backend.md",21131,"https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fskills\u002Fa2x-client-integration\u002Fwiki\u002Fhost-backend.md",{"path":98,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":99,"sourceHtmlUrl":100},"wiki\u002Fhost-browser.md",11605,"https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fskills\u002Fa2x-client-integration\u002Fwiki\u002Fhost-browser.md",{"path":102,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":103,"sourceHtmlUrl":104},"wiki\u002Fhost-cli.md",15758,"https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fskills\u002Fa2x-client-integration\u002Fwiki\u002Fhost-cli.md",{"path":106,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":107,"sourceHtmlUrl":108},"wiki\u002Fhost-nextjs.md",18651,"https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fskills\u002Fa2x-client-integration\u002Fwiki\u002Fhost-nextjs.md",{"path":110,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":111,"sourceHtmlUrl":112},"wiki\u002Foauth2-device-code.md",19849,"https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fskills\u002Fa2x-client-integration\u002Fwiki\u002Foauth2-device-code.md",{"path":114,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":115,"sourceHtmlUrl":116},"wiki\u002Fstreaming.md",11527,"https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fskills\u002Fa2x-client-integration\u002Fwiki\u002Fstreaming.md",{"path":118,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":119,"sourceHtmlUrl":120},"wiki\u002Ftoken-persistence.md",12817,"https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fskills\u002Fa2x-client-integration\u002Fwiki\u002Ftoken-persistence.md",[122,143,161,174,192,211],{"skillNo":123,"name":124,"nameZh":6,"description":125,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":126,"categories":127,"keywords":128,"publishedAt":39},"01M6RVF6VMM81YBJJ5WF16HP32","a2x-integration","Integrates the @a2x\u002Fsdk (A2A Agent-to-Agent protocol) into TypeScript projects, including paid merchant agents using x402. Supports Next.js App Router, Next.js Pages Router, Express, NestJS, and zero-framework quick start. Use when the user wants to add A2A agent capabilities, an a2x endpoint, or MerchantGate-based payments using @a2x\u002Fsdk.","https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fskills\u002Fa2x-agent-integration\u002FSKILL.md",[],[129,20,38,130,131,132,133,134,135,136,137,138,32,29,28,139,140,141,142,23],"a2x integration","capabilities","framework","payments","start","endpoint","projects","router","x402","agent-to-agent","quick start","add","quick","merchant",{"skillNo":144,"name":145,"nameZh":6,"description":146,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":147,"categories":148,"keywords":149,"publishedAt":39},"01M6RVEHQ768BSWM2N3HHZYBYB","weather-report","Produce a compact weather report for a specified city. Use when the user asks about the weather, forecast, or temperature for a named city.","https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fsamples\u002Fnextjs-skill\u002Fskills\u002Fweather-report\u002FSKILL.md",[],[150,151,152,153,154,155,156,157,158,159,23,160],"weather report","report","weather","user","use","compact","about","temperature","for","forecast","produce",{"skillNo":162,"name":163,"nameZh":6,"description":164,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":165,"categories":166,"keywords":167,"publishedAt":39},"01M6RVECTSTYJ3ZSF2BY2ZS96H","recipe-suggest","Suggest recipes based on a small list of ingredients the user already has. Use when the user lists ingredients and asks what they can cook, or mentions pantry, fridge, or leftover ingredients.","https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fsamples\u002Fnextjs-skill\u002Fskills\u002Frecipe-suggest\u002FSKILL.md",[],[168,169,170,171,153,154,172,173,23],"recipe suggest","recipe","cook","list","recipes","can",{"skillNo":175,"name":176,"nameZh":6,"description":177,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":178,"categories":179,"keywords":180,"publishedAt":39},"01M6RVE9MDP4KGW7R1QDYAAZNB","valid-simple","A minimal skill used by unit tests. Used when parser\u002Floader coverage requires the smallest possible valid SKILL.md.","https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fpackages\u002Fa2x\u002Fsrc\u002F__tests__\u002Ffixtures\u002Fskills\u002Fvalid-simple\u002FSKILL.md",[],[181,182,183,184,185,186,187,188,189,190,191,23],"valid simple","simple","valid","valid skill","unit tests","minimal skill","parser","coverage","minimal","tests","unit",{"skillNo":193,"name":194,"nameZh":6,"description":195,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":196,"categories":197,"keywords":198,"publishedAt":39},"01M6RVE4X94SZDP7XBT0ZWQ1P4","valid-full","A skill exercising every frontmatter feature the SDK supports.","https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fpackages\u002Fa2x\u002Fsrc\u002F__tests__\u002Ffixtures\u002Fskills\u002Fvalid-full\u002FSKILL.md",[],[199,183,200,201,190,202,203,204,205,206,158,207,208,187,209,210],"full","valid full","read","feature","false","advanced","sonnet","true","frontmatter","sdk","Bash","verify",{"skillNo":212,"name":213,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":214,"categories":215,"keywords":216,"publishedAt":39},"01M6RVDMQSZ2FWRD5X71XBKEA2","invalid-no-frontmatter","https:\u002F\u002Fgithub.com\u002Fplanetarium\u002Fa2x\u002Fblob\u002Fmain\u002Fpackages\u002Fa2x\u002Fsrc\u002F__tests__\u002Ffixtures\u002Fskills\u002Finvalid-no-frontmatter\u002FSKILL.md",[],[217,218,207,219],"invalid","no frontmatter","invalid no frontmatter"]