Skip to content

@helix-agents/a2a ​

A2A (Agent2Agent) protocol 1.0 support for Helix Agents: the pieces every A2A surface shares (the wire codec, a Helix task's A2A state, and the attempt-safe projection of a task's stream into A2A events), the host in front of an app's chat route (createAgentHost), and the attach to a live task (attachTask). The client (connectAgent) and the A2A transport come in later releases (the A2A design's R1 phase).

Every schema is a lazy getter, so importing the package builds nothing: it is safe on Cloudflare Workers. It depends on @helix-agents/core and zod only.

Installation ​

bash
npm install @helix-agents/a2a

The wire codec ​

Zod schemas for A2A 1.0's JSON shape, mirroring the normative specification/a2a.proto at A2A tag v1.0.1 (a test checks them against a pinned copy of that file):

SchemaA2A type
taskSchema()Task (id, status required)
taskStatusSchema()TaskStatus (state required)
messageSchema()Message (messageId, role and at least one part required)
partSchema()Part: exactly one of text, raw (base64), url or data
artifactSchema()Artifact (artifactId and at least one part required)
taskStatusUpdateEventSchema()TaskStatusUpdateEvent (no final in 1.0: a stream ends when it closes)
taskArtifactUpdateEventSchema()TaskArtifactUpdateEvent (append, lastChunk)
streamResponseSchema()StreamResponse: exactly one of task, message, statusUpdate, artifactUpdate

TASK_STATES and ROLES list the enum values (TASK_STATE_*, ROLE_*), isTerminalTaskState names the terminal states, A2A_METHODS the JSON-RPC method names (SendMessage, GetTask, …) and A2A_HEADERS the A2A-Extensions and A2A-Version headers.

Unknown fields are ignored, as the specification says implementations SHOULD ("Unrecognized Fields"): a 0.3 kind is dropped, while a 0.3 file part (no 1.0 content field) is refused, and so are 0.3's lowercase enum spellings.

Values. data and metadata hold JSON values only: a function, a bigint, NaN, a class instance or a cycle is refused. raw is base64, standard or URL-safe, padded or not, and is read as standard and padded. A timestamp is an RFC 3339 date-time; an offset is read as its Z form. null for an optional field is unset, except in data, where it is a JSON null.

taskStateOf ​

typescript
import { taskStateOf } from '@helix-agents/a2a';

taskStateOf({ run, stopRecorded, unansweredCalls }); // 'TASK_STATE_WORKING' | 'TASK_STATE_INPUT_REQUIRED' | …

The A2A state of a task, from its latest run (run.status, run.endReason), whether a stop is recorded for it, and how many calls of the tree's committed suspension are unanswered:

  • WORKING: running; suspended with nothing unanswered; or a recorded stop not yet ended (it wins over INPUT_REQUIRED);
  • INPUT_REQUIRED: suspended with at least one unanswered call;
  • COMPLETED / FAILED: the run completed / failed (an abort ends failed);
  • CANCELED: the run interrupted, or its task ended by another task (superseded, abandoned, rewound).

SUBMITTED and REJECTED are never derived.

createTaskProjector ​

typescript
import { committedResponseReader, createTaskProjector, taskRunsReader } from '@helix-agents/a2a';

const projector = createTaskProjector({
  taskId,
  contextId,
  agentId, // the task's own agent: its text is the response
  tier: 0, // 1 when the client activated the Helix profile
  taskRunIds: taskRunsReader({ store, taskId }), // the task's own runs
  renderCommittedResponse: committedResponseReader({ store, sessionId, taskId }),
});
const events = await projector.push(chunk, { sequence: reader.currentSequence }); // A2AProjectedEvent[]
  • Tier 0: the response artifact (the agent's reply text) and the output artifact (outputArtifactEvent: a JSON DataPart for a structured output, a text part for a plain reply), as TaskArtifactUpdateEvents.
  • Tier 1: plus typed notice items (A2AProjectionNoticeData): tool and sub-agent lifecycle, state-patch notices, ctx.emit events and attempt_superseded, each stamped with its attemptId.
  • Attempt-safe: a superseded model attempt's text never reaches the response. A step whose attempt is replaced (core AttemptTracker), a step_discarded, a stream_resync and a run_interrupted replace the response (append: false) with the reply re-rendered from the committed rows. An interrupt keeps the stopped step's partial reply, committed after its step_discarded marker and before run_interrupted, so it survives.
  • Positions: every chunk is pushed with its stream sequence, and a replace renders the rows committed before that chunk, so a replay, or a reader behind the run, shows no text twice. Positions only go up (gaps are fine): a missing, invalid, repeated or lower one rejects with validation_error. After a rejected push, start a new projector.
  • The task's own runs: a chunk of the task's agent from another run, or with no runId, is dropped (logger.warn once, a2a.projection.chunk_without_run), except that a replace trigger with no runId still replaces. taskRunIds may answer a promise: taskRunsReader({ store, taskId }) reads a run's task from the store, where it is committed before the run's first chunk, so a run that joins a live task is never missed. Await each push.
  • Attach: initial: { afterSequence, parts } starts from what is shown at a position; responseReplace() is a full response replace of what was pushed so far, for a subscriber that attaches mid-stream; responseText() is the text a client holding every event shows.

committedResponseReader ​

committedResponseReader({ store, sessionId, taskId }) is the renderCommittedResponse of a task served from its session store: the task's reply as committed before a position. It reads the store on each replace, and never shows rows a later truncation or a later task put in the place of the task's own (committedRowsEnd is the rule alone, over a task's commits). It needs the runs a task-planning runtime records (runtime-js, the CF Durable Object) and rejects with validation_error without them. Two commits at one stream position are ordered by the store's clock.

pendingCallPart(call) builds the DataPart of one pending call for an INPUT_REQUIRED status message, from a call reference the host already encoded.

createAgentHost ​

createAgentHost(config) returns an AgentHost (fetch(request, env?)) that serves A2A's chat requests through the app's own chat route:

RequestOperation
POST /chat/:contextIdchat.send
GET /chat/:contextIdchat.attach

config (AgentHostConfig):

  • authorize (required): the app's access control, (request, { operation, contextId?, taskId?, env?, claimed? }) => { principal, userId? } | Refusal. It runs first, on a body that is parsed and size-capped, and before any store read. A throw answers exactly as unauthenticated (and is logged). 'public' serves without access control, on purpose. claimed.userId is what the caller asserts; nothing uses it unless this hook returns it. principal is @helix-agents/core's Principal ({ id, ...claims }), re-exported here: the type a Cloudflare Durable Object's handle(principal, request, trace) takes.
  • resolveContext (default: the context id is the session id; null: not found).
  • admit (AdmitContext → AdmitDecision): which of the caller's keys an entry takes. Absent (and for each flag left out): its initialState is taken, its context pieces are user-level only, and a state patch is refused.
  • chat (ChatMount, required): the chat route, (request, { operation, sessionId, principal, userId?, admitted }) => Response, with handleChatStream behind it. Pass admitted on.
  • maxRequestBytes (default core DEFAULT_MAX_REQUEST_BYTES), logger.

A request goes through one order: the route, authorize, the caller's keys, resolveContext, admit, then the mount. Every answer that is not the mount's is rendered by the host from a typed refusal (Refusal: unauthenticated, forbidden, not_found, invalid; its reason is for the log only) or a typed error; a hook never builds a Response.

The keys the host decides, HOST_DECIDED_KEYS (with LINEAGE_KEYS), are always the host's, never the caller's: a caller's value of a lineage key is refused (validation_error), and the body the mount is given holds none of the others from the caller. That body names the host's session as both id and sessionId, and the user as userId, so a mount copied from a stock route serves the host's session. The URL the mount is given names it too, on every route: its /chat/:id segment is the host's session, and its query holds none of the keys the host decides.

The host forwards the reply, not state. A 2xx event stream from the mount loses its data-state-patch events, and a 2xx JSON answer its top-level state (answered null); everything else is forwarded as the mount answered it. State and usage reach A2A callers with the projections (stateProjection, usageProjection) in a later release.

A typed error a hook throws (resolveContext, admit, chat) is answered with its code and status only: its text stays in the log, and the answer's detail is a fixed message.

attachTask ​

attachTask({ source, taskId, contextId, agentId, signal?, maxHoldMs?, pollMs?, livenessCheckMs?, logger? }) is a subscriber's attach to a live task, an async iterable of TaskAttachEvents: one full replace of the response from the committed rows, then what streams after that commit, until the task ends. A task that has ended yields its status alone. It rejects typed, also while iterating.

  • Waiting for input: the stream stays open (closesStream(state): only a terminal state closes it). An attach that yields nothing for maxHoldMs (default 5 minutes) ends with AttachHeldError (transport_stream_drop, retryable), and the client attaches again; a new attach starts with a full replace.
  • A reader a cleanup truncated is attached again, and a live task gets a new replace when its reply or position moved.
  • A task another task's entry ended (a rewind, a superseding or abandoning entry) ends as its own terminal status, and none of the other task's text is shown.
  • A paused task: what its stream takes before the attach reads the task again (a run that resumes it and ends, or a stop settled for it) is still shown, and then the end.

storeTaskAttachSource({ store, streamManager, sessionId, taskId, reconcile? }) is its TaskAttachSource over a session store and its stream manager, in the store's own process (reconcile: the executor's reconcileSession, where it has one). A store client without the task reads (a Worker's client of a Durable Object) is refused framework_not_supported, and so, at its first read, is a session that writes into another session's stream or has none.

Replacing an artifact ​

TaskArtifactUpdateEvent.append is defined for true only; the specification does not say what append: false means for an artifact id the client already holds. This package treats it as a replace, as the official JavaScript SDK does (@a2a-js/sdk, src/server/result_manager.ts), and follows the specification if it later defines it.

Not decided yet ​

  • Where tier-1 notices ride on the wire: in a status update's message, or in an artifact or metadata of their own. It is decided with the Helix profile, with the A2A methods; the notice type stays the same either way.

The specification's sections disagree on whether INPUT_REQUIRED closes a stream; the attach keeps it open (closesStream, above).

Released under the MIT License.