@agents-js/a2a-client
v0.4.0
Published
A2A client transport, AG-UI adapter, target registry, session view-model, and discovery helpers for agents-js consumers.
Maintainers
Readme
@agents-js/a2a-client
A2A client transport, AG-UI adapter, target registry, session view-model, and discovery helpers for agents-js consumers.
Installation
bun add @agents-js/a2a-clientAPI
Classes
A2AClientControllerA2AClientProvider— Event-driven A2A client provider -- the Provider layer for A2A communication. Orchestrates turn execution (send, stream, resume), target resolution, and event emission. Delegates all protocol I...AgentRegistry— Agent registry that resolves-namereferences to A2A endpoints. Reads agent entries from a JSON config file and fetches + caches agent cards from the resolved URLs.kind: "acp"entries are pars...AgentRegistryConfigError— Thrown when the registry config file cannot be read or parsed.AGUIStreamError— Thrown by {parseAguiSseStream} / {AGUITransport} when the server-sent event stream is malformed, emits an invalid AG-UI event, or is torn down unexpectedly.AguiToA2ATransportAdapter— Adapts an {AGUITransport} so it can sit behind the existingA2AClientProviderand session reducer without them knowing about the underlying protocol. Semantic bridging: - `sendMessageStream(param...AGUITransport— Native AG-UI client transport. This is a parallel surface to {A2ATransport}, not a subtype. AG-UI has no task lifecycle, so the task-shaped methods onA2ATransporthave no AG-UI counterpart. ...AGUIUnsupportedOperationError— Thrown by {AguiToA2ATransportAdapter} when a caller invokes an A2A task-shaped method that has no AG-UI counterpart (e.g.getTask,cancelTask, push-notification config). AG-UI has no task lifec...PeerSyncError— Thrown when a peer's sync endpoint is unreachable, non-200, or returns an invalid payload.SdkA2ATransport— Default A2A transport implementation backed by the A2A SDK. Handles HTTP/SSE communication with A2A agents: target resolution via agent card discovery, message sending (immediate and streaming), ta...
Functions
adaptTarget— Orchestrates the probe → auth → transform pipeline for a given TargetAdapter. 1. Constructs the probe URL from baseUrl + adapter.probePath 2. Calls adapter.authHeader (if defined) to get an Authori...applyJsonPatch— Apply an array of JSON Patch (RFC 6902) operations to a state object immutably. Returns a new state object with all operations applied. The input state is not modified. Throws descriptive errors fo...autoRegister— Idempotent auto-registration. Writes a v2 record foroptions.name, replacing any prior entry with the same name. Synthesizes provenance (gateway_id,source=auto-reg,registered_at, `agent_i...buildA2ADelegationFramingText— Build the framing prompt that wraps a remote agent's response so the receiving LLM recognizes it as "the answer from ``" rather than ambient context. Without this framing, Claude tends to ignore an...buildAcpElicitationResponseMetadatabuildSyncPayload— Produce the wire payload this gateway would serve at its sync endpoint. Three filters apply, in order: 1.source !== "sync"— loop prevention on the send side; we never re-serve records we receiv...collectTextPartscreateA2AMentionMiddlewarecreateDebugFetchcreateInitialSessionStatecreateSharedAgentRegistrycreateSyncEndpointHandler— Build a(req: Request) => Promise<Response | null>compatible withUniversalA2AServerOptions.additionalFetch. The gateway wires this into its existing fetch hook so the sync endpoint lives on t...describeSessionStatus— Map an {A2ASessionState} to a polished, protocol-neutral {SessionStatusViewModel} suitable for rendering in UI clients (Raycast, web-ui, Obsidian plugin, terminal CLIs, etc.). Discriminator priorit...escapeA2ADelegationInnerText— Escape a delegated agent's response so it cannot break out of the outer<a2a-delegation-response>markers. Rewrites any literal occurrences of the open or close tags insideinnerTextwith zero-...extractA2AResponseTextextractAcpAuthRequiredMetadataextractAcpElicitationMetadataextractLatestAgentMessageextractLatestAgentTextextractMessageTextfetchPeerRecords— GET the peer gateway's sync endpoint and return the records it serves. Throws {PeerSyncError} on network failure, non-2xx, or malformed payload.groupDiscoveredTargets— Group/dedupe a raw list of discovered targets byname, picking a canonicalpreferredentry per group under the configured policy. The function is pure and opt-in — passing nooptions(or{}...isTerminalTaskStatemergeRecords— Pure-function merge surface — exported for white-box tests of the matrix.normalizeAgentTargetInputnormalizeHeadersoriginCardFallback— Returns an origin-level variant ofnormalizedwhen the base path is non-empty. Used as a resolution fallback for the common misuse pattern where the caller passes a JSON-RPC endpoint URL (e.g. `h...parseAgentMentions— Extracts-namementions from text content. Returns an array of {ParsedMention} objects describing each valid mention found. Email addresses (e.g.user.com) are NOT matched because the@must ...parseDispatchDirective— Parses a@-name payloaddispatch directive from the user text. Unlike `` which are annotations that can appear anywhere,@@is a deterministic routing directive: the entire message is consumed ...randomUuid— Secure-context-safe RFC 4122 v4 UUID generator. Browsers only exposecrypto.randomUUID()in secure contexts (HTTPS origins orlocalhost/127.0.0.1). Serving the reference web-ui over plain H...readAgentRegistryRecords— Read the v2 record shape, applying v1→v2 migration in-memory. Returns an empty map when the file is absent or unparsable (fails open).reduceA2ASessionStateresolveSharedAgentRegistryPathserializeRecords— Build the on-disk JSON payload from a record map, preserving v2 shape. Exported so the sync module can write the merged state using the same serializer autoRegister uses — one source of truth for t...startRegistrySync— Wire auto-registration and peer-sync into a gateway startup path. Returns immediately — auto-registration is fire-and-forget. ```ts const sync = startRegistrySync({ name: "my-gateway", url: baseUrl...stripMention— Removes a previously-parsed mention from the source text. Returns the text with the mention'sfullMatchremoved at the correct position. Trailing whitespace immediately after the mention is colla...summarizeCapabilitiessyncFromPeer— Pull-sync from a single peer. Fetches the peer's sync endpoint, drops self-originated records, merges the rest into the local registry, and writes the result to disk. Returns a {SyncSummary} descri...truncateText
Interfaces
A2AAbortSendEvent— Send was aborted by anAbortSignalbefore any transport request was issued. Emitted instead oferrorwhen {SendTurnOptions.signal} is already aborted on entry tosendTurn/resumeTurn, or whe...A2AAbortStreamEvent— Send/resume stream was aborted by anAbortSignalmid-flight. Emitted when the abort fires after the streaming connection opened but before it reaches a terminal task state. Distinguishes user-ini...A2AAgentEntry— A registry entry describing a remote A2A agent reachable over HTTP.A2AAuthRequiredState— Lightweight typed view of an active auth-required prompt for UI consumers. EachauthMethods[]entry carries the protocol-level method id alongside optional human-presentable fields.linkis the...A2AAvailableCommandsUpdatedEvent— The set of slash-commands currently available from the harness. Replaces state wholesale on receipt.A2ACancellationFailedEvent— Remote-sidecancelTaskrejected. The correspondingerrorevent carries the underlying transport message; this event lets consumers distinguish cancellation-failure from a generic operation error.A2ACancellationRequestedEvent— Local cancellation was requested by the caller. Useful for UI consumers that want to render a "canceling..." state before a remote-cancel result (cancellation.succeeded/cancellation.failed) l...A2ACancellationSucceededEvent— Remote-sidecancelTaskcompleted successfully. UI consumers can use this to confirm to the user that the remote agent actually accepted the cancellation, vs falling back to local-only teardown (w...A2AClientControllerOptionsA2ACustomEventA2ADebugRecordEventA2ADelegationFramingTemplate— Declarative template for the delegation framing prompt. Consumers (tests, host integrations, alternatebuildResponseBlockimplementations) should import this rather than rebuild the literal strin...A2AErrorEventA2AMentionDispatchErrorA2AMentionDispatchOptionsA2AMentionDispatchSuccessA2AMentionResponseBlockOptionsA2AMessageCompletedEventA2AMessageDeltaEvent— A partial message update. Note ontextvsdeltasemantics: -textcarries the accumulated message text (all content so far). -delta(AG-UI spec alias) carries the incremental c...A2AMessageEndEventA2AMessageStartEvent— Signals the start of a new message. Theroleunion is widened beyond the AG-UI spec to keep"agent"as an agents-js-local alias for"assistant"(pre-existing semantics). All spec values (`"de...A2AModeChangedEvent— Mode transition reported by the harness (e.g. plan→execute, model swap). ACPcurrent_mode_updatecarries only the newmodeId; the available-modes list lives in session metadata.A2APlanUpdatedEvent— The agent's structured todo-list. ACPplannotifications always carry the FULL set of entries; receivers replace state wholesale.A2AReasoningEncryptedEvent— Encrypted reasoning payload.datais the agents-js legacy field carrying the encrypted value. The AG-UI spec shape usessubtype,entityId, andencryptedValue. When an emitter populates the ...A2AReasoningEndEventA2AReasoningMessageChunkEvent— Streams an incremental reasoning chunk. Emitters should populate bothtext(agents-js legacy) anddelta(AG-UI spec alias) with the same value during the transition window.A2AReasoningMessageContentEvent— Streams a full reasoning content block. Emitters should populate bothtext(agents-js legacy) anddelta(AG-UI spec alias) with the same value during the transition window.A2AReasoningMessageEndEventA2AReasoningMessageStartEventA2AReasoningStartEventA2ARequestSentEvent— Lifecycle signals for streaming/non-streaming sends. Lifecycle events are pure diagnostics: they never participate intranscript/pendingAgentText/ task-state transitions. UI consumers can re...A2ARunErrorEvent— AG-UI spec: signals that an agent run failed. Emitted alongside the existing agents-jserrorevent during the transition window.runId/threadIdare populated when an in-flight turn context is...A2ARunFinishedEvent— AG-UI spec: signals the successful completion of an agent run. Emitted alongside the existing agents-jsmessage.completedevent during the transition window. SharesrunId/threadIdwith the pr...A2ARunStartedEvent— AG-UI spec: signals the start of an agent run (one user turn). Emitted alongside the existing agents-jsturn.startedevent during the transition window.runIdis unique per turn;threadIdis ...A2ASessionInfoUpdatedEvent— Session-level metadata mutation from ACPsession_info_update. Both fields use three-state semantics: omitted (undefined) → no change,null→ explicit clear, string → replacement. Receivers me...A2ASessionStateA2ASessionUpdatedEventA2AStepFinishedEventA2AStepStartedEventA2AStreamClosedEvent— Stream closed cleanly (terminal task state reached or generator exhausted).A2AStreamFirstEventEvent— First event has been received from the stream (or first response from non-streaming).A2AStreamIdleEvent— Stream has been silent for the configured idle threshold without reaching a terminal state. UI consumers should surface a user-facing "no stream event for N seconds" warning. Idle timer clears on e...A2AStreamLastEventEvent— A new event has arrived; useful for clients that want to track last-activity.A2AStreamOpenedEventA2ATargetResolvedEventA2ATaskArtifactUpdatedEventA2ATaskStatusUpdatedEventA2ATaskUpdatedEventA2AToolCallArgsEvent— Incremental JSON argument chunk for a tool call. Emitters should populate bothargsChunk(agents-js legacy) anddelta(AG-UI spec alias) with the same value during the transition window.A2AToolCallEndEvent— Marks the end of a tool call. Emitted once pertoolCallIdafter alltool_call.argsevents and when the underlying tool call reaches a terminal state (completed or failed). Carries the final ACP...A2AToolCallProgressEvent— Non-terminal mid-call update. ACPtool_call_updatenotifications carry status transitions (pending→in_progress) and/or payload mutations (content/locations/raw I/O) without ending the call....A2AToolCallStartEvent— Marks the start of a tool call. Emitted once pertoolCallIdbefore anytool_call.argsortool_call.endevent. Carries the full ACPToolCallpayload forwarded from the wire so receivers can ...A2ATransport— Transport interface for A2A protocol I/O. This is the Transport port in the Ports & Adapters architecture. The default implementation is {SdkA2ATransport} (HTTP/SSE via the A2A SDK). Implement ...A2ATurnStartedEventA2AUsageUpdatedEvent— Token-budget telemetry.size= total context window tokens,used= consumed so far,cost= structuredCostfrom the SDK ({ amount, currency }) preserved verbatim —nullis a valid harne...ACPA2AElicitationACPA2AElicitationResponseACPA2AElicitationSchemaACPAgentEntry— A registry entry describing a locally spawnable ACP harness.ActiveToolCall— Snapshot of a single in-flight or recently-completed tool call. Mirrored on session state so the TUI can render an inline status row that swaps in place as the call progresses. Optional fields mirr...AdaptedTarget— Result of a successful adapt flow.AdaptTargetContext— Context passed to TargetAdapter hooks during card adaptation.AdaptTargetOptions— Options for adaptTarget. Allows injecting a custom fetch for testing.AgentMentionRegistryAgentRegistryOptions— Options for constructing an {AgentRegistry}.AgentRegistryRecord— Full v2 on-disk record shape.AgentsJsRegistrySyncPayload— Wire-format payload served by the sync endpoint and consumed by peers. Records are typed as the wire shape —kind="acp"and the operator- controlled launch fields (command,args,env, `work...AgentTargetInputAGUIRunResult— Result of a single AG-UIrunAgentcall.AGUITransportOptions— Options for constructing an {AGUITransport}.AutoRegisterA2AOptions— Transport-a2a auto-reg options.AutoRegisterACPOptions— Transport-acp auto-reg options.AutoRegisterOptionsBase— Options shared by all {autoRegister} calls.CancelTaskOptions— Options for {A2AClientController.cancelTask}. WhentaskIdis omitted, the controller defaults to the active session'staskIdif present, falling back toresumableTaskId. This matches what UI ...CapabilitySummaryCreateA2AMentionMiddlewareOptionsDebugRecordDiscoveredTarget— Input shape consumed by {groupDiscoveredTargets}. Wraps a registry record with the optional probe-derived reachability + error reason. Consumers produce these fromAgentRegistry.list()results pa...DiscoveredTargetGroup— Output of {groupDiscoveredTargets} — one bucket per unique agent name. Thepreferredentry is the canonical pick under the configured policy;alternatescarries the rest of the duplicates (gate...FetchPeerRecordsOptions— Options for {fetchPeerRecords}.GroupDiscoveredTargetsOptions— Behavior knobs for {groupDiscoveredTargets}. All flags default tofalseso the helper is a pass-through unless callers opt in.JsonPatchOperation— A single JSON Patch (RFC 6902) operation.NormalizedAgentTargetInputParsedDispatchDirectiveParsedMention— Pure functions for parsing-namementions from text content. Agent names are alphanumeric + hyphens (e.g.knowledge-compiler,code-reviewer). A mention is valid when preceded by whitespace or...ProbeResultRegistrySyncHandle— Handle returned by {startRegistrySync}.ResolvedAgentTargetResumeTurnOptionsSendTurnOptionsSharedAgentRegistrySharedAgentRegistryOptionsStartRegistrySyncOptions— Options for {startRegistrySync}.SyncEndpointHandlerOptions— Options for {createSyncEndpointHandler}.SyncFromPeerOptions— Options for {syncFromPeer}.SyncLogger— Logger shape — compatible withconsoleand the gateway's A2ALogger subset we use.SyncSummary— Summary returned by {syncFromPeer}. Each record surfaces in exactly one array + one action.TargetAdapter— Adapter interface for non-standard A2A agents. Implement this to teachadaptTargethow to: 1. Find the agent card at a non-standard path (probePath) 2. Optionally authenticate the probe (`authH...TargetInspectionTranscriptEntry
Types
A2AEventA2AEventListenerA2ASendResultA2AStreamEvent— AG-UI event types that may appear in SSE streams alongside standard A2A events.ACPA2AElicitationContentValueAgentActorType— Who or what is behind an agent. Governance classifier; distinct from transportkind.AgentEntry— A single entry from the registry config file (discriminated onkind).AgentKind— Kind of agent transport —a2aentries are routable over HTTP A2A;acpentries describe a spawnable ACP harness.AgentMentionMapAgentMentionResolverAgentRegistrySource— How a registry record got here on this gateway.AgentTargetModeAutoRegisterOptionsCancelTaskResult— Result of {A2AClientController.cancelTask}.outcomedistinguishes: -"canceled"— the transport'scancelTaskcall resolved successfully.taskcarries the resulting Task (typically with stat...FetchLikeRawAgentCard— Raw card shape returned by a non-standard agent probe endpoint. Kept as a loose record to avoid over-constraining what Agent Zero returns.SessionStatusSessionStatusAction— Re-export for convenience — consumers can override action labels.SessionStatusViewModel— Re-export for convenience — consumers can override action labels.StartupLogger— Console-shaped logger subset used by {startRegistrySync}.SyncAction— Why a single record changed (or did not change) during a sync merge.TargetInspectionStatusTargetReachability— Per-target health/probe status as seen by a UI client. Discovery implementations can map their own probe results to this triplet:online(target responded),offline(probe failed),unknown(p...
Constants
A2A_DELEGATION_FRAMING_TEMPLATE— Canonical framing template used bydefaultBuildResponseBlock. Exported so the framing-contract regression test can assert against the exact strings, and so downstream consumers that emit equivale...A2A_DELEGATION_RESPONSE_CLOSE_TAG— Outer close-tag for the A2A delegation framing. Paired withA2A_DELEGATION_RESPONSE_OPEN_TAG.A2A_DELEGATION_RESPONSE_OPEN_TAG— Outer open-tag for the A2A delegation framing. Consumers (tests, host integrations, alternatebuildResponseBlockimplementations) should import this constant rather than hardcode the string.ACP_A2A_AUTH_REQUIRED_METADATA_KEYACP_A2A_ELICITATION_METADATA_KEYACP_A2A_ELICITATION_RESPONSE_METADATA_KEYAGENTS_JS_REGISTRY_WELL_KNOWN_PATH— Well-known path the peer sync endpoint is mounted at.
Exports
parseAguiSseStreamtype A2AClientControllerOptions
Dependencies
@agentclientprotocol/sdk@a2a-js/sdk@agents-js/a2a@agents-js/agui-types@agents-js/validation
License
MIT
