fascicle 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/README.md +27 -1
  3. package/dist/AGENTS.md +71 -94
  4. package/dist/a2a.d.ts +358 -0
  5. package/dist/a2a.js +2234 -0
  6. package/dist/a2a.js.map +1 -0
  7. package/dist/acp.d.ts +120 -9
  8. package/dist/acp.js +927 -154
  9. package/dist/acp.js.map +1 -1
  10. package/dist/adapters-DYFauXE1.js +1147 -0
  11. package/dist/adapters-DYFauXE1.js.map +1 -0
  12. package/dist/adapters.d.ts +124 -36
  13. package/dist/adapters.js +1 -1
  14. package/dist/agents.d.ts +2 -2
  15. package/dist/agents.js +1 -1
  16. package/dist/{core-BH7sWpEG.js → core-xTtRZqdb.js} +217 -99
  17. package/dist/core-xTtRZqdb.js.map +1 -0
  18. package/dist/diagram_bin.js +1 -1
  19. package/dist/durable-CgU0kO2H.d.ts +144 -0
  20. package/dist/{engine-fOjYHcv6.js → engine-B_Yl7acj.js} +128 -42
  21. package/dist/engine-B_Yl7acj.js.map +1 -0
  22. package/dist/index.d.ts +9 -136
  23. package/dist/index.js +6 -5
  24. package/dist/index.js.map +1 -1
  25. package/dist/{invoke-7iu8db6V.js → invoke-Bbk0RuVL.js} +3 -3
  26. package/dist/{invoke-7iu8db6V.js.map → invoke-Bbk0RuVL.js.map} +1 -1
  27. package/dist/{leading_system-BeQUSAim.js → leading_system-m-x7HzbQ.js} +16 -4
  28. package/dist/leading_system-m-x7HzbQ.js.map +1 -0
  29. package/dist/mcp-D1hN5ywq.js +662 -0
  30. package/dist/mcp-D1hN5ywq.js.map +1 -0
  31. package/dist/mcp.d.ts +115 -5
  32. package/dist/mcp.js +2 -2
  33. package/dist/otel.d.ts +1 -1
  34. package/dist/stdio.d.ts +1 -1
  35. package/dist/stdio.js +2 -2
  36. package/dist/testing.d.ts +7 -5
  37. package/dist/testing.js +618 -318
  38. package/dist/testing.js.map +1 -1
  39. package/dist/{types-BUXt_zgJ.d.ts → types-BtRpSctv.d.ts} +38 -5
  40. package/dist/{types-Dk9tLpUq.d.ts → types-CDTW7XWB.d.ts} +2 -2
  41. package/dist/ui.d.ts +2 -2
  42. package/dist/viewer.js +2 -2
  43. package/dist/web.d.ts +1 -1
  44. package/package.json +17 -5
  45. package/dist/adapters-CpKpDk7r.js +0 -461
  46. package/dist/adapters-CpKpDk7r.js.map +0 -1
  47. package/dist/core-BH7sWpEG.js.map +0 -1
  48. package/dist/engine-fOjYHcv6.js.map +0 -1
  49. package/dist/leading_system-BeQUSAim.js.map +0 -1
  50. package/dist/mcp-CHJ88HiG.js +0 -262
  51. package/dist/mcp-CHJ88HiG.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"a2a.js","names":["rest_of"],"sources":["../src/a2a/parts.ts","../src/a2a/task_status.ts","../src/a2a/errors.ts","../src/a2a/to_task_events.ts","../src/a2a/task_runner.ts","../src/a2a/admission.ts","../src/a2a/http.ts","../src/a2a/sdk_loader.ts","../src/a2a/task_records.ts","../src/a2a/a2a_agent.ts","../src/a2a/remote_task.ts","../src/a2a/scoped_fetch.ts","../src/a2a/a2a_step.ts","../src/a2a/serve_a2a.ts","../src/a2a/sqlite_task_store.ts"],"sourcesContent":["/**\n * Building and reading A2A parts.\n *\n * A part holds exactly one of text, raw bytes, a URL, or a JSON value. The\n * SDK's types are protobuf-shaped, so the content sits under a `$case`, and\n * raw bytes are a `Buffer`. Nothing here needs an SDK value: a part is plain\n * data, which is what lets the mapper in to_task_events.ts stay pure.\n *\n * `to_plain` and `from_plain` carry a value that may hold raw bytes through\n * JSON, for the stores a task record and a checkpoint are kept in.\n */\n\nimport type { Part } from '@a2a-js/sdk'\nimport { is_record } from '#schema'\nimport type { A2aFile } from './types.js'\n\nconst BYTES = '$bytes'\n\n/**\n * A text part.\n */\nexport function text_part(text: string): Part {\n return { content: { $case: 'text', value: text }, metadata: undefined, filename: '', mediaType: 'text/plain' }\n}\n\n/**\n * A data part holding any JSON value.\n */\nexport function data_part(value: unknown): Part {\n return { content: { $case: 'data', value }, metadata: undefined, filename: '', mediaType: 'application/json' }\n}\n\n/**\n * The default `to_parts`: a string as a text part, nothing for a flow that\n * returns nothing, and anything else as a data part.\n */\nexport function output_parts(output: unknown): Part[] {\n if (typeof output === 'string') return [text_part(output)]\n if (output === undefined || output === null) return []\n return [data_part(output)]\n}\n\n/**\n * The text parts among `parts`, joined with `separator`.\n */\nexport function text_of(parts: ReadonlyArray<Part>, separator = ''): string {\n const texts: string[] = []\n for (const part of parts) {\n if (part.content?.$case === 'text') texts.push(part.content.value)\n }\n return texts.join(separator)\n}\n\n/**\n * The values of the data parts among `parts`, in order.\n */\nexport function data_of(parts: ReadonlyArray<Part>): unknown[] {\n const values: unknown[] = []\n for (const part of parts) {\n if (part.content?.$case === 'data') values.push(part.content.value)\n }\n return values\n}\n\n/**\n * The file parts among `parts` (the ones that carry bytes or a URL), with\n * bytes as base64 so that they survive a trip through a store.\n */\nexport function files_of(parts: ReadonlyArray<Part>): A2aFile[] {\n const files: A2aFile[] = []\n for (const part of parts) {\n const base = { filename: part.filename, media_type: part.mediaType }\n if (part.content?.$case === 'url') files.push({ ...base, url: part.content.value })\n if (part.content?.$case === 'raw') {\n files.push({ ...base, base64: Buffer.from(part.content.value).toString('base64') })\n }\n }\n return files\n}\n\n/**\n * A copy of `value` that JSON can hold, with every run of raw bytes written\n * as `{ $bytes: <base64> }`.\n */\nexport function to_plain(value: unknown): unknown {\n if (value instanceof Uint8Array) return { [BYTES]: Buffer.from(value).toString('base64') }\n if (Array.isArray(value)) return value.map(to_plain)\n if (!is_record(value)) return value\n return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, to_plain(inner)]))\n}\n\n/**\n * The inverse of `to_plain`: every `{ $bytes }` it wrote becomes a `Buffer`\n * again.\n */\nexport function from_plain(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(from_plain)\n if (!is_record(value)) return value\n const bytes = value[BYTES]\n if (typeof bytes === 'string' && Object.keys(value).length === 1) return Buffer.from(bytes, 'base64')\n return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, from_plain(inner)]))\n}\n","/**\n * How a run's resting place reads as an A2A task status.\n *\n * A drive that rests, and a task record that has fallen behind its run, both\n * need the same translation: done is `COMPLETED`, a client gate is\n * `INPUT_REQUIRED` with the gate's question, an external gate is `WORKING`\n * with a note that names the gate, and a failure is `FAILED`. Keeping it in\n * one place is what keeps `GetTask` and a live stream telling the same story.\n *\n * The gate a status belongs to rides in its message's metadata, as\n * `metadata.fascicle.gate`, beside the gate's `deadline_at` when it set one.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { Message, Part, Task, TaskState, TaskStatus } from '@a2a-js/sdk'\nimport type { AgentExecutionEvent } from '@a2a-js/sdk/server'\nimport type { SchemaIssue } from '#core'\nimport { is_record } from '#schema'\nimport { data_part, text_part } from './parts.js'\nimport type { A2aServerSdk } from './sdk_loader.js'\n\nexport type Wire = A2aServerSdk['wire']\n\nexport type TaskIds = { readonly task_id: string; readonly context_id: string }\n\n/**\n * Where a run stands, as far as a task's status is concerned.\n */\nexport type Rest =\n | { readonly kind: 'done'; readonly output: unknown }\n | { readonly kind: 'suspended'; readonly id: string; readonly payload: unknown; readonly deadline_at?: number }\n | { readonly kind: 'refused'; readonly gate: string; readonly issues: ReadonlyArray<SchemaIssue> }\n | { readonly kind: 'failed'; readonly error: unknown }\n | { readonly kind: 'canceled' }\n | { readonly kind: 'running' }\n\n/**\n * The hooks that decide how a status reads, each with its default applied.\n */\nexport type StatusHooks = {\n readonly gates: (gate: string) => 'client' | 'external'\n readonly to_question: (gate: string, payload: unknown) => string | ReadonlyArray<Part>\n readonly to_failure: (err: unknown) => string\n}\n\n/**\n * The default `to_question`: a line that names the gate, then the gate's\n * payload as a data part, so the client sees what the run is asking about.\n */\nexport function default_question(gate: string, payload: unknown): ReadonlyArray<Part> {\n const line = text_part(`Waiting for input at \"${gate}\".`)\n return payload === undefined ? [line] : [line, data_part(payload)]\n}\n\n/**\n * The default `to_failure`: one line that says the task failed and nothing\n * about why.\n *\n * A failed task's status goes to whoever sent the message, and an error's\n * text can hold a connection string or a path that shouldn't leave the\n * server. The error itself goes to the agent's own trajectory or stderr.\n */\nexport function default_failure(): string {\n return 'The agent could not finish the task.'\n}\n\n/**\n * A `to_failure` that sends the error's own message, for an agent whose\n * callers are trusted with it.\n */\nexport function failure_message(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/**\n * Whether a task has ended, in a state no message or event can move it from.\n */\nexport function is_terminal(wire: Wire, task: Task): boolean {\n const state = task.status?.state\n return (\n state === wire.TaskState.TASK_STATE_COMPLETED ||\n state === wire.TaskState.TASK_STATE_FAILED ||\n state === wire.TaskState.TASK_STATE_CANCELED ||\n state === wire.TaskState.TASK_STATE_REJECTED\n )\n}\n\n/**\n * The gate a task's status belongs to, read from its message's metadata.\n */\nexport function gate_of(task: Task): string | undefined {\n const fascicle: unknown = task.status?.message?.metadata?.['fascicle']\n const gate = is_record(fascicle) ? fascicle['gate'] : undefined\n return typeof gate === 'string' ? gate : undefined\n}\n\n/**\n * A message from the agent on a task.\n */\nfunction agent_message(\n wire: Wire,\n ids: TaskIds,\n parts: ReadonlyArray<Part>,\n metadata?: Record<string, unknown>,\n): Message {\n return {\n messageId: randomUUID(),\n contextId: ids.context_id,\n taskId: ids.task_id,\n role: wire.Role.ROLE_AGENT,\n parts: [...parts],\n metadata,\n extensions: [],\n referenceTaskIds: [],\n }\n}\n\n/**\n * A status stamped now, which is what `ListTasks` orders tasks by.\n */\nexport function status_of(state: TaskState, message?: Message): TaskStatus {\n return { state, message, timestamp: new Date().toISOString() }\n}\n\n/**\n * Wrap a status as the bus event that carries it.\n */\nexport function status_event(ids: TaskIds, status: TaskStatus): AgentExecutionEvent {\n return {\n kind: 'statusUpdate',\n data: { taskId: ids.task_id, contextId: ids.context_id, status, metadata: undefined },\n }\n}\n\n/**\n * The metadata that ties a status to its gate.\n */\nfunction gate_metadata(gate: string, deadline_at?: number): Record<string, unknown> {\n return { fascicle: deadline_at === undefined ? { gate } : { gate, deadline_at } }\n}\n\n/**\n * The status of a run that waits at a gate: the client's question, or a note\n * that the run waits on something A2A doesn't carry.\n */\nfunction gate_status(\n wire: Wire,\n hooks: StatusHooks,\n ids: TaskIds,\n rest: Extract<Rest, { readonly kind: 'suspended' }>,\n): TaskStatus {\n const metadata = gate_metadata(rest.id, rest.deadline_at)\n if (hooks.gates(rest.id) === 'external') {\n const note = [text_part(`Waiting on \"${rest.id}\", which this agent's clients don't answer.`)]\n return status_of(wire.TaskState.TASK_STATE_WORKING, agent_message(wire, ids, note, metadata))\n }\n const question = hooks.to_question(rest.id, rest.payload)\n const parts = typeof question === 'string' ? [text_part(question)] : question\n return status_of(wire.TaskState.TASK_STATE_INPUT_REQUIRED, agent_message(wire, ids, parts, metadata))\n}\n\n/**\n * One line for each issue a gate's schema raised, with the path it sits at.\n */\nfunction issue_lines(issues: ReadonlyArray<SchemaIssue>): string {\n return issues\n .map((issue) => {\n const path = (issue.path ?? []).map(String).join('.')\n return path === '' ? issue.message : `${path}: ${issue.message}`\n })\n .join('; ')\n}\n\n/**\n * The task status for where a run rests, or `undefined` for a run that's\n * still being driven, which changes nothing by itself.\n */\nexport function status_for(wire: Wire, hooks: StatusHooks, ids: TaskIds, rest: Rest): TaskStatus | undefined {\n const state = wire.TaskState\n switch (rest.kind) {\n case 'done':\n return status_of(state.TASK_STATE_COMPLETED)\n case 'suspended':\n return gate_status(wire, hooks, ids, rest)\n case 'refused': {\n const text = `The answer to \"${rest.gate}\" was refused: ${issue_lines(rest.issues)}`\n const message = agent_message(wire, ids, [text_part(text)], gate_metadata(rest.gate))\n return status_of(state.TASK_STATE_INPUT_REQUIRED, message)\n }\n case 'failed':\n return status_of(state.TASK_STATE_FAILED, agent_message(wire, ids, [text_part(hooks.to_failure(rest.error))]))\n case 'canceled':\n return status_of(state.TASK_STATE_CANCELED, agent_message(wire, ids, [text_part('The task was canceled.')]))\n default:\n return undefined\n }\n}\n","/**\n * Typed errors for the A2A adapter.\n *\n * Listed alongside src/acp/errors.ts in the `no-class` rule ignores:\n * `instanceof` branching is how callers tell a missing optional peer apart\n * from a remote task that didn't complete.\n */\n\nexport class a2a_sdk_missing_error extends Error {\n readonly kind = 'a2a_sdk_missing_error' as const;\n constructor(\n message = '@a2a-js/sdk is required for fascicle/a2a; install it: pnpm add @a2a-js/sdk',\n ) {\n super(message)\n this.name = 'a2a_sdk_missing_error'\n }\n}\n\n/**\n * What an `a2a_error` knows about the task it came from.\n */\nexport type A2aErrorDetail = {\n /** The task's state as A2A spells it, such as `TASK_STATE_FAILED`. */\n readonly state?: string | undefined\n /** The text of the task's status message, when it had one. */\n readonly status_text?: string | undefined\n readonly task_id?: string | undefined\n}\n\n/**\n * A task that came to rest somewhere other than `COMPLETED`, or a call the\n * adapter can't carry out. `state` and `status_text` are set when a remote\n * task ended failed, rejected, canceled, or waiting for credentials.\n */\nexport class a2a_error extends Error {\n readonly kind = 'a2a_error' as const;\n readonly state: string | undefined;\n readonly status_text: string | undefined;\n readonly task_id: string | undefined;\n constructor(message: string, detail: A2aErrorDetail = {}) {\n super(message)\n this.name = 'a2a_error'\n this.state = detail.state\n this.status_text = detail.status_text\n this.task_id = detail.task_id\n }\n}\n","/**\n * Maps a drive's events onto A2A task events.\n *\n * A drive runs with `record_chunks`, so each `model_call` records\n * `model_chunk` events carrying the engine's `StreamChunk`, the same source\n * fascicle/ui and the ACP mapper read. This half of a task does no I/O and\n * holds no SDK value, so a flow author can wrap `to_task_events` in their\n * own `to_events` and add to what it returns, as long as every event still\n * reaches it: a `step_replayed` mutes the step it names, and the step speaks\n * again once its span ends, or sooner, once the drive has passed every gate\n * the event names. From there on the step is doing new work. An `a2a_step`\n * is the case that needs it: its span stays open across the remote\n * question, and the text that follows the answer is the remote agent's\n * next round, which no client has read.\n *\n * Text goes into one artifact for each drive, in chunks. A2A marks the last\n * chunk of an artifact, and no chunk knows it's the last, so the mapper\n * holds the newest one back until the next arrives. `end_task_events` sends\n * the one it still holds once the drive has come to rest, with the output's\n * parts behind it when the drive has some.\n *\n * Reasoning and tool calls map to nothing, because A2A has no thought\n * channel and no tool card, and neither do spans, `cost`, or `emit` events.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { Part } from '@a2a-js/sdk'\nimport type { AgentExecutionEvent } from '@a2a-js/sdk/server'\nimport type { TrajectoryEvent } from '#core'\nimport { is_record } from '#schema'\nimport { text_part } from './parts.js'\nimport type { A2aMapperOptions, A2aMapperState } from './types.js'\n\n/**\n * Create the state for one drive's events, routing every model call's text\n * to the drive's artifact unless `stream` says otherwise.\n */\nexport function create_a2a_mapper_state(options: A2aMapperOptions): A2aMapperState {\n return {\n task_id: options.task_id,\n context_id: options.context_id,\n artifact_id: options.artifact_id ?? randomUUID(),\n stream: options.stream ?? (() => 'artifact'),\n replaying: new Map(),\n pending: undefined,\n sent: 0,\n }\n}\n\n/**\n * One chunk of the drive's artifact. Every chunk after the first appends.\n */\nfunction artifact_update(state: A2aMapperState, parts: Part[], last: boolean): AgentExecutionEvent {\n const append = state.sent > 0\n state.sent += 1\n return {\n kind: 'artifactUpdate',\n data: {\n taskId: state.task_id,\n contextId: state.context_id,\n artifact: {\n artifactId: state.artifact_id,\n name: '',\n description: '',\n parts,\n metadata: undefined,\n extensions: [],\n },\n append,\n lastChunk: last,\n metadata: undefined,\n },\n }\n}\n\n/**\n * The text of a `model_chunk` event's text chunk, or `undefined` for a chunk\n * of any other kind.\n */\nfunction chunk_text(chunk: unknown): string | undefined {\n if (!is_record(chunk) || chunk['kind'] !== 'text') return undefined\n const text = chunk['text']\n return typeof text === 'string' ? text : undefined\n}\n\n/**\n * Hold `text` back as the newest chunk, and send the one held before it.\n */\nfunction hold(state: A2aMapperState, text: string): AgentExecutionEvent[] {\n const before = state.pending\n state.pending = text\n return before === undefined ? [] : [artifact_update(state, [text_part(before)], false)]\n}\n\n/**\n * Whether a step is running again in a span that hasn't ended.\n */\nfunction is_replaying(state: A2aMapperState, step_id: string): boolean {\n for (const replayed of state.replaying.values()) {\n if (replayed.step_id === step_id) return true\n }\n return false\n}\n\n/**\n * The gates a `step_replayed` event says are still ahead of the drive.\n */\nfunction gates_of(event: TrajectoryEvent): Set<string> {\n const ids: unknown = event['suspend_ids']\n return new Set(Array.isArray(ids) ? ids.filter((id): id is string => typeof id === 'string') : [])\n}\n\n/**\n * Note that the drive has passed `gate`, and let every step speak that was\n * waiting on no other. A replay that named no gate waits for its span.\n */\nfunction pass_gate(state: A2aMapperState, gate: string): void {\n for (const [span_id, replayed] of state.replaying) {\n if (replayed.gates.delete(gate) && replayed.gates.size === 0) state.replaying.delete(span_id)\n }\n}\n\n/**\n * Mute the step a `step_replayed` event names, for as long as its span runs\n * or until the drive has passed the gates the event names.\n */\nfunction start_replay(event: TrajectoryEvent, state: A2aMapperState): void {\n const span_id = event.span_id\n const step_id = event['step_id']\n if (typeof span_id !== 'string' || typeof step_id !== 'string') return\n state.replaying.set(span_id, { step_id, gates: gates_of(event) })\n}\n\n/**\n * Take in the end of a span: a replay that ran in it is over, and a gate\n * that it was has been passed. A gate's span ends without an error only\n * when the gate took its answer.\n */\nfunction end_span(event: TrajectoryEvent, state: A2aMapperState): void {\n if (typeof event.span_id === 'string') state.replaying.delete(event.span_id)\n const ended = event['id']\n if (typeof ended === 'string' && event['error'] === undefined) pass_gate(state, ended)\n}\n\n/**\n * Map one run event to zero or more task events. Only a `model_chunk` that\n * carries text produces any, and it produces the chunk before it. The\n * function does no I/O.\n */\nexport function to_task_events(event: TrajectoryEvent, state: A2aMapperState): AgentExecutionEvent[] {\n if (event.kind === 'step_replayed') start_replay(event, state)\n if (event.kind === 'span_end') end_span(event, state)\n const step_id = event['step_id']\n if (event.kind !== 'model_chunk' || typeof step_id !== 'string') return []\n const text = chunk_text(event['chunk'])\n if (text === undefined || text === '') return []\n if (is_replaying(state, step_id) || state.stream(step_id) !== 'artifact') return []\n return hold(state, text)\n}\n\n/**\n * Close the drive's artifact once the drive has come to rest: the chunk the\n * mapper still holds goes out as the last one, with `parts` behind it. A\n * drive that streamed no text sends `parts` as its whole artifact, and one\n * with neither sends nothing.\n */\nexport function end_task_events(state: A2aMapperState, parts: ReadonlyArray<Part> = []): AgentExecutionEvent[] {\n const held = state.pending === undefined ? [] : [text_part(state.pending)]\n state.pending = undefined\n const closing = [...held, ...parts]\n return closing.length === 0 ? [] : [artifact_update(state, closing, true)]\n}\n\n/**\n * Whether the drive has streamed any text into its artifact.\n */\nexport function has_streamed(state: A2aMapperState): boolean {\n return state.pending !== undefined || state.sent > 0\n}\n","/**\n * Drives the durable run behind each A2A task.\n *\n * A task is a durable run, and the task id is the run id. A message with no\n * task starts a run, a message for a task that waits at a client gate\n * resumes it with the client's answer, and an outside event resumes it\n * through `resume`. Every drive records model chunks, maps the run's events\n * onto the task's event bus, and can be aborted by a cancel. Where the drive\n * comes to rest decides the task's state (see task_status.ts).\n *\n * The SDK's request handler owns the bus and writes each event to the task\n * store as the request reads it. A drive that the SDK didn't start (an\n * outside event) writes its events through the SDK's `ResultManager`\n * instead, and publishes them on a bus of its own as well, for a client\n * that subscribes while it runs.\n *\n * One drive at a time holds a task in this process. The handle it holds is\n * what a cancel aborts, what `close` waits for, and what makes a second\n * message find the task working. A drive lets go only once its resting\n * status has reached the task store, so a `GetTask` that lands in between\n * reads the record as the drive left it and not as its run alone suggests.\n *\n * A cancel can land in a process that doesn't hold the drive. That process\n * can only mark the record `CANCELED`, so every drive reads its own task's\n * record on an interval and aborts itself once the record says so.\n *\n * A failed task tells its caller only what `to_failure` makes of the error.\n * The error itself goes to the config's `trajectory` as an\n * `a2a_task_failed` event, or to stderr when the config has none, so the\n * people who run the agent can always read why a task failed.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { Message, Part, Task, TaskStatus } from '@a2a-js/sdk'\nimport type {\n AgentExecutionEvent,\n AgentExecutor,\n ExecutionEventBusManager,\n RequestContext,\n ServerCallContext,\n TaskStore,\n} from '@a2a-js/sdk/server'\nimport { aborted_error, resume_validation_error } from '#core'\nimport type { DurableOutcome, DurableRunOptions, DurableRuns, TrajectoryEvent, TrajectoryLogger } from '#core'\nimport { a2a_error } from './errors.js'\nimport { data_of, files_of, text_of } from './parts.js'\nimport type { A2aServerSdk } from './sdk_loader.js'\nimport type { TaskRecords } from './task_records.js'\nimport { is_terminal, status_event, status_for, status_of } from './task_status.js'\nimport type { Rest, StatusHooks, TaskIds } from './task_status.js'\nimport { create_a2a_mapper_state, end_task_events, has_streamed, to_task_events } from './to_task_events.js'\nimport type { A2aAgentConfig, A2aHistoryEntry, A2aResumeOptions, A2aTurn, A2aUser } from './types.js'\n\n/**\n * One task's hold on this process: the drive that has it, or the message\n * that's about to start one.\n */\nexport type Hold = {\n readonly abort: AbortController\n /** Set by a cancel, so the drive ends the task `CANCELED` however it settles. */\n canceled: boolean\n /** Set once a drive has taken the hold a message was admitted with. */\n taken: boolean\n readonly settled: Promise<void>\n readonly release: () => void\n}\n\nexport type Holds = Map<string, Hold>\n\n/**\n * The room each request for a new task has reserved, by the request's\n * context. A reservation counts against `max_drives` from the moment the\n * request is let in, and the drive gives it back as it takes its hold, so a\n * burst of requests can't all find room before any of them has a hold.\n */\nexport type Slots = WeakMap<ServerCallContext, () => void>\n\nexport type TaskRunnerConfig<i, o> = {\n readonly sdk: A2aServerSdk\n readonly config: A2aAgentConfig<i, o>\n readonly runs: DurableRuns\n readonly records: TaskRecords\n readonly holds: Holds\n readonly slots: Slots\n readonly hooks: StatusHooks\n readonly to_parts: (output: unknown) => ReadonlyArray<Part>\n readonly buses: ExecutionEventBusManager\n}\n\nexport type TaskRunner = {\n readonly executor: AgentExecutor\n readonly resume: (\n task_id: string,\n resume_data: Readonly<Record<string, unknown>>,\n options?: A2aResumeOptions,\n ) => Promise<void>\n /** Aborts every drive and waits for each one to settle. */\n readonly close: () => Promise<void>\n}\n\ntype Publish = (event: AgentExecutionEvent) => void\n\ntype Begin<o> = (options: DurableRunOptions) => Promise<DurableOutcome<o>>\n\nconst DEFAULT_HISTORY_LIMIT = 20\nconst MAX_HISTORY_LIMIT = 100\n\n// How long a drive waits for its resting status to reach the task store\n// before it lets go of the task anyway.\nconst SAVE_WAIT_MS = 2_000\n\n// How often a drive reads its task's record for a cancel from elsewhere.\nconst DEFAULT_CANCEL_POLL_MS = 2_000\n\n/**\n * Take a hold on `task_id` for a drive, or for a message on its way to one.\n */\nexport function take_hold(holds: Holds, task_id: string): Hold {\n const { promise, resolve } = Promise.withResolvers<void>()\n const hold: Hold = {\n abort: new AbortController(),\n canceled: false,\n taken: false,\n settled: promise,\n release: () => {\n if (holds.get(task_id) === hold) holds.delete(task_id)\n resolve()\n },\n }\n holds.set(task_id, hold)\n return hold\n}\n\n/**\n * A logger that hands every event of a drive to `on_event`, spans included,\n * and passes each call on to the config's own logger when it has one.\n */\nfunction drive_logger(on_event: (event: TrajectoryEvent) => void, sink: TrajectoryLogger | undefined): TrajectoryLogger {\n return {\n record: (event) => {\n sink?.record(event)\n on_event(event)\n },\n start_span: (name, meta) => {\n const span_id = sink?.start_span(name, meta) ?? `${name}:${randomUUID().slice(0, 8)}`\n on_event({ kind: 'span_start', span_id, name, ...meta })\n return span_id\n },\n end_span: (span_id, meta) => {\n sink?.end_span(span_id, meta)\n on_event({ kind: 'span_end', span_id, ...meta })\n },\n }\n}\n\n/**\n * A gate's refusal of its answer, read from the error a drive threw, or\n * `undefined` for any other error. `durable` has already put the run back at\n * the gate by the time the error surfaces.\n */\nfunction refusal_of(err: unknown): Rest | undefined {\n if (!(err instanceof resume_validation_error) || err.suspend_id === undefined) return undefined\n return { kind: 'refused', gate: err.suspend_id, issues: err.issues }\n}\n\n/**\n * The trajectory event for a drive that failed: the task it belongs to, and\n * the error's message, name, and stack, none of which the caller is sent.\n */\nfunction failure_event(ids: TaskIds, err: unknown): TrajectoryEvent {\n const known = err instanceof Error\n return {\n kind: 'a2a_task_failed',\n task_id: ids.task_id,\n context_id: ids.context_id,\n error: known ? err.message : String(err),\n ...(known ? { error_name: err.name } : {}),\n ...(known && err.stack !== undefined ? { error_stack: err.stack } : {}),\n }\n}\n\n/**\n * The caller behind a request, as a flow sees them.\n */\nfunction user_of(context: ServerCallContext): A2aUser {\n return { name: context.user?.userName ?? '', authenticated: context.user?.isAuthenticated ?? false }\n}\n\n/**\n * The two sides of one earlier task: what the user opened it with, and the\n * text it ended with (its artifacts' text, or else its status message).\n */\nfunction exchange_of(sdk: A2aServerSdk, task: Task): A2aHistoryEntry[] {\n const opened = task.history.find((message) => message.role === sdk.wire.Role.ROLE_USER)\n const reply =\n task.artifacts.map((artifact) => text_of(artifact.parts)).filter((text) => text !== '').join('\\n') ||\n text_of(task.status?.message?.parts ?? [], '\\n')\n const entries: A2aHistoryEntry[] = []\n if (opened !== undefined) entries.push({ task_id: task.id, role: 'user', text: text_of(opened.parts, '\\n') })\n if (reply !== '') entries.push({ task_id: task.id, role: 'agent', text: reply })\n return entries\n}\n\n/**\n * Build the runner that drives tasks for one agent.\n */\nexport function task_runner<i, o>(deps: TaskRunnerConfig<i, o>): TaskRunner {\n const { sdk, config, runs, records, holds, slots, hooks, buses } = deps\n const state = sdk.wire.TaskState\n const store: TaskStore = records.store\n const cancel_poll_ms = config.cancel_poll_ms ?? DEFAULT_CANCEL_POLL_MS\n\n let shutting_down = false\n\n // Tell the server side why a drive failed, whatever the caller is told. A\n // drive that `close` aborted says so in one line on stderr, since the stack\n // of a shutdown that the operator asked for points at nothing.\n const report_failure = (ids: TaskIds, err: unknown, hold: Hold): void => {\n const event = failure_event(ids, err)\n if (config.trajectory !== undefined) {\n config.trajectory.record(event)\n return\n }\n const by_close = shutting_down && hold.abort.signal.aborted\n const detail = !by_close && typeof event['error_stack'] === 'string' ? event['error_stack'] : String(event['error'])\n process.stderr.write(`a2a_agent: task ${ids.task_id} failed: ${detail}\\n`)\n }\n\n // Read the task's record every `cancel_poll_ms` while a drive runs, and\n // abort the drive once the record is CANCELED, which only a cancel that\n // another process took can have made it. Returns what stops the reads.\n const watch_for_cancel = (ids: TaskIds, hold: Hold, context: ServerCallContext): (() => void) => {\n if (!(cancel_poll_ms > 0)) return () => {}\n let stopped = false\n let timer: ReturnType<typeof setTimeout> | undefined\n const check = async (): Promise<void> => {\n // A store that can't be read now is read again at the next tick, and\n // the drive is no worse off than it is with the check turned off.\n const task = await store.load(ids.task_id, context).catch(() => undefined)\n if (stopped) return\n if (task?.status?.state === state.TASK_STATE_CANCELED) {\n hold.canceled = true\n hold.abort.abort(new aborted_error('the task was canceled in another process'))\n return\n }\n wait()\n }\n const wait = (): void => {\n timer = setTimeout(() => {\n void check()\n }, cancel_poll_ms)\n timer.unref()\n }\n wait()\n return () => {\n stopped = true\n clearTimeout(timer)\n }\n }\n\n // The earlier exchanges of a context, oldest first, from the most recent\n // tasks the caller has in it.\n const history_of = async (ids: TaskIds, context: ServerCallContext): Promise<A2aHistoryEntry[]> => {\n const limit = Math.min(MAX_HISTORY_LIMIT, Math.max(0, Math.trunc(config.history_limit ?? DEFAULT_HISTORY_LIMIT)))\n if (limit === 0) return []\n const listed = await store.list(\n {\n tenant: context.tenant ?? '',\n contextId: ids.context_id,\n status: state.TASK_STATE_UNSPECIFIED,\n // One more than the limit, since the turn's own task may be among them.\n pageSize: Math.min(MAX_HISTORY_LIMIT, limit + 1),\n pageToken: '',\n statusTimestampAfter: undefined,\n includeArtifacts: true,\n },\n context,\n )\n const earlier = listed.tasks.filter((task) => task.id !== ids.task_id).slice(0, limit)\n return earlier.toReversed().flatMap((task) => exchange_of(sdk, task))\n }\n\n const turn_of = async (ids: TaskIds, message: Message, context: ServerCallContext): Promise<A2aTurn> => ({\n task_id: ids.task_id,\n context_id: ids.context_id,\n text: text_of(message.parts, '\\n'),\n data: data_of(message.parts),\n files: files_of(message.parts),\n message,\n history: await history_of(ids, context),\n user: user_of(context),\n })\n\n const input_of = (turn: A2aTurn): i => {\n if (config.to_input !== undefined) return config.to_input(turn)\n // A2aAgentConfig allows a missing `to_input` only when the flow takes a string.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return turn.text as i\n }\n\n const answer_of = (turn: A2aTurn, gate: string): unknown => {\n if (config.to_resume !== undefined) return config.to_resume(turn, gate)\n return turn.data.length > 0 ? turn.data[0] : turn.text\n }\n\n // Run one drive and publish what it comes to. Resolves the status the\n // drive rested on, or `undefined` when another process holds the run.\n const drive = async (\n ids: TaskIds,\n hold: Hold,\n context: ServerCallContext,\n publish: Publish,\n begin: Begin<o>,\n ): Promise<TaskStatus | undefined> => {\n const mapper = create_a2a_mapper_state({ ...ids, stream: config.stream })\n const to_events = config.to_events ?? to_task_events\n const logger = drive_logger((event) => {\n for (const mapped of to_events(event, mapper)) publish(mapped)\n }, config.trajectory)\n let rest: Rest | undefined\n const unwatch = watch_for_cancel(ids, hold, context)\n try {\n const outcome = await begin({\n record_chunks: true,\n trajectory: logger,\n abort: hold.abort.signal,\n install_signal_handlers: false,\n })\n if (outcome.kind !== 'busy') rest = outcome\n } catch (err) {\n rest = refusal_of(err) ?? { kind: 'failed', error: err }\n } finally {\n unwatch()\n }\n if (hold.canceled) rest = { kind: 'canceled' }\n if (rest?.kind === 'failed') report_failure(ids, rest.error, hold)\n // Text that streamed is the output already, unless the output is more\n // than text, in which case its parts close the artifact.\n const parts = rest?.kind === 'done' && !(has_streamed(mapper) && typeof rest.output === 'string') ? deps.to_parts(rest.output) : []\n for (const closing of end_task_events(mapper, parts)) publish(closing)\n const status = rest === undefined ? undefined : status_for(sdk.wire, hooks, ids, rest)\n if (status === undefined) return undefined\n const saved = records.saved(ids.task_id, status, SAVE_WAIT_MS)\n publish(status_event(ids, status))\n await saved\n return status\n }\n\n // Let go of a task whose drive has rested. A task that ended elsewhere\n // while this process drove it (a cancel on another host) still has a run,\n // which the load deletes.\n const finish = async (ids: TaskIds, context: ServerCallContext, hold: Hold): Promise<void> => {\n try {\n await store.load(ids.task_id, context)\n } finally {\n hold.release()\n }\n }\n\n const execute = async (request: RequestContext, bus: Parameters<AgentExecutor['execute']>[1]): Promise<void> => {\n const ids: TaskIds = { task_id: request.taskId, context_id: request.contextId }\n const hold = holds.get(ids.task_id) ?? take_hold(holds, ids.task_id)\n hold.taken = true\n // The hold counts from here on, so the room the request reserved is free.\n slots.get(request.context)?.()\n const publish: Publish = (event) => {\n bus.publish(event)\n }\n const message = request.userMessage\n const opening: Task = request.task ?? {\n id: ids.task_id,\n contextId: ids.context_id,\n status: status_of(state.TASK_STATE_SUBMITTED),\n artifacts: [],\n history: [message],\n metadata: undefined,\n }\n try {\n publish({ kind: 'task', data: opening })\n publish(status_event(ids, status_of(state.TASK_STATE_WORKING)))\n await drive(ids, hold, request.context, publish, async (options) => {\n const turn = await turn_of(ids, message, request.context)\n if (request.task === undefined) return runs.start(ids.task_id, config.flow, input_of(turn), options)\n const run = await runs.get(ids.task_id)\n const data = run?.kind === 'suspended' ? { [run.id]: answer_of(turn, run.id) } : {}\n return runs.resume(ids.task_id, config.flow, data, options)\n })\n } finally {\n await finish(ids, request.context, hold)\n }\n }\n\n const cancel = async (task_id: string, bus: Parameters<AgentExecutor['cancelTask']>[1]): Promise<void> => {\n const hold = holds.get(task_id)\n if (hold !== undefined) {\n hold.canceled = true\n hold.abort.abort(new aborted_error('the task was canceled'))\n await hold.settled\n return\n }\n // No drive holds the task, so it waits at a client gate with its bus\n // kept open, and the cancel is this one event.\n const sighting = records.seen.get(task_id)\n const ids: TaskIds = { task_id, context_id: sighting?.context_id ?? '' }\n const status = status_for(sdk.wire, hooks, ids, { kind: 'canceled' })\n if (status !== undefined) bus.publish(status_event(ids, status))\n if (sighting !== undefined) buses.cleanupByTaskId(task_id, sighting.context)\n }\n\n // Wait until no drive holds the task, then load it, and repeat when a\n // drive took it during the load.\n const load_free = async (task_id: string, context: ServerCallContext): Promise<Task | undefined> => {\n for (;;) {\n const held = holds.get(task_id)\n if (held !== undefined) {\n await held.settled\n continue\n }\n const task = await store.load(task_id, context)\n if (!holds.has(task_id)) return task\n }\n }\n\n const resume: TaskRunner['resume'] = async (task_id, resume_data, options = {}) => {\n const user = options.user\n const context =\n user === undefined\n ? (records.seen.get(task_id)?.context ?? new sdk.server.ServerCallContext())\n : new sdk.server.ServerCallContext({ user: { isAuthenticated: user.authenticated, userName: user.name } })\n const task = await load_free(task_id, context)\n if (task === undefined) {\n throw new a2a_error(\n `no task ${task_id} to resume: check the id, and pass \\`user\\` when the task belongs to an authenticated caller`,\n { task_id },\n )\n }\n if (is_terminal(sdk.wire, task)) return\n const ids: TaskIds = { task_id, context_id: task.contextId }\n const hold = take_hold(holds, task_id)\n hold.taken = true\n // The drive gets a bus even when no client holds one open. A client can\n // then subscribe to the task while it runs, and a cancel reaches the\n // drive: for a task with no bus the SDK writes CANCELED by itself and\n // never asks the executor, so the flow would run on.\n const bus = buses.createOrGetByTaskId(task_id, context)\n const writer = new sdk.server.ResultManager(store, context)\n let writes: Promise<void> = Promise.resolve()\n const publish: Publish = (event) => {\n writes = writes.then(() => writer.processEvent(event))\n bus.publish(event)\n }\n try {\n publish(status_event(ids, status_of(state.TASK_STATE_WORKING)))\n const status = await drive(ids, hold, context, publish, (run_options) =>\n runs.resume(task_id, config.flow, resume_data, run_options),\n )\n await writes\n // A bus stays open only for a task that waits on its client.\n if (status?.state !== state.TASK_STATE_INPUT_REQUIRED) {\n bus.finished()\n buses.cleanupByTaskId(task_id, context)\n }\n } finally {\n await finish(ids, context, hold)\n }\n }\n\n const close = async (): Promise<void> => {\n shutting_down = true\n const open = [...holds.values()]\n for (const hold of open) hold.abort.abort(new aborted_error('the agent closed while the task was running'))\n await Promise.all(open.map((hold) => hold.settled))\n }\n\n return { executor: { execute, cancelTask: cancel }, resume, close }\n}\n","/**\n * A thin wrapper around the SDK's request handler that refuses a message\n * its task can't take.\n *\n * The SDK appends a message to its task's history before it calls the\n * executor, so a message for a task that's working would be recorded and\n * then go nowhere. This wrapper looks first. A message with no task passes\n * through, and so does one for a task that's missing or terminal, which the\n * SDK refuses in its own words. A message for a live task is admitted only\n * when the task waits at a client gate and nothing in this process holds\n * it, and it takes the task's hold as it's admitted, so a second answer to\n * the same gate finds the task working. Anything else is refused with\n * `UnsupportedOperationError` before the SDK has recorded a thing.\n */\n\nimport type { SendMessageRequest } from '@a2a-js/sdk'\nimport type { A2ARequestHandler, ServerCallContext, TaskStore } from '@a2a-js/sdk/server'\nimport type { DurableRuns } from '#core'\nimport type { A2aServerSdk } from './sdk_loader.js'\nimport { is_terminal } from './task_status.js'\nimport { take_hold } from './task_runner.js'\nimport type { Hold, Holds } from './task_runner.js'\n\nexport type AdmissionConfig = {\n readonly sdk: A2aServerSdk\n readonly inner: A2ARequestHandler\n readonly store: TaskStore\n readonly runs: DurableRuns\n readonly holds: Holds\n readonly gates: (gate: string) => 'client' | 'external'\n}\n\n/**\n * Give back a hold that no drive took, which happens when the SDK refused\n * the message after it was admitted.\n */\nfunction give_back(hold: Hold | undefined): void {\n if (hold !== undefined && !hold.taken) hold.release()\n}\n\n/**\n * Wrap `config.inner` so that `SendMessage` and `SendStreamingMessage`\n * refuse a message its task isn't waiting for. Every other method passes\n * straight through.\n */\nexport function admitting_handler(config: AdmissionConfig): A2ARequestHandler {\n const { sdk, inner, store, runs, holds } = config\n\n const refuse = (task_id: string, why: string): never => {\n throw new sdk.errors.UnsupportedOperationError(`Task ${task_id} can't take a message: ${why}`)\n }\n\n // Take the task's hold for a message it can take, or throw. Resolves\n // `undefined` for a message the SDK decides on by itself.\n const admit = async (params: SendMessageRequest, context: ServerCallContext): Promise<Hold | undefined> => {\n const task_id = params.message?.taskId\n if (!task_id) return undefined\n const task = await store.load(task_id, context)\n if (task === undefined || is_terminal(sdk.wire, task)) return undefined\n if (holds.has(task_id)) return refuse(task_id, \"it's working, so wait until it asks for input\")\n const hold = take_hold(holds, task_id)\n try {\n const run = await runs.get(task_id)\n if (run === undefined) return refuse(task_id, 'it has no run left to resume')\n if (run.kind !== 'suspended') return refuse(task_id, \"it's working, so wait until it asks for input\")\n if (config.gates(run.id) !== 'client') {\n return refuse(task_id, `it waits on \"${run.id}\", which this agent's clients don't answer`)\n }\n return hold\n } catch (err) {\n hold.release()\n throw err\n }\n }\n\n return {\n getAgentCard: () => inner.getAgentCard(),\n getAuthenticatedExtendedAgentCard: (params, context) => inner.getAuthenticatedExtendedAgentCard(params, context),\n sendMessage: async (params, context) => {\n const hold = await admit(params, context)\n try {\n return await inner.sendMessage(params, context)\n } finally {\n give_back(hold)\n }\n },\n sendMessageStream: async function* (params, context) {\n const hold = await admit(params, context)\n try {\n yield* inner.sendMessageStream(params, context)\n } finally {\n give_back(hold)\n }\n },\n getTask: (params, context) => inner.getTask(params, context),\n cancelTask: (params, context) => inner.cancelTask(params, context),\n createTaskPushNotificationConfig: (params, context) => inner.createTaskPushNotificationConfig(params, context),\n getTaskPushNotificationConfig: (params, context) => inner.getTaskPushNotificationConfig(params, context),\n listTaskPushNotificationConfigs: (params, context) => inner.listTaskPushNotificationConfigs(params, context),\n deleteTaskPushNotificationConfig: (params, context) => inner.deleteTaskPushNotificationConfig(params, context),\n resubscribe: (params, context) => inner.resubscribe(params, context),\n listTasks: (params, context) => inner.listTasks(params, context),\n }\n}\n","/**\n * The agent as a web `fetch` handler: the card, and JSON-RPC over HTTP.\n *\n * It follows the SDK's own Express `jsonRpcHandler` step for step, minus\n * Express. Each request's context carries the caller, the `A2A-Version`\n * header, and the `A2A-Extensions` header, and the version is checked\n * against the card before the body goes to the SDK, since the SDK's\n * transport handler doesn't check it.\n *\n * A streaming method answers with server-sent events, one `data:` frame for\n * each JSON-RPC response. Its first result is awaited before the response\n * commits to a stream, so an error that comes before the stream starts goes\n * back as a plain JSON-RPC error. A client that disconnects stops the stream\n * it was reading and nothing else: the handler keeps reading the task's\n * events, because the SDK writes each one to the task store as it's read,\n * and A2A keeps a dropped connection apart from a cancel.\n *\n * Three answers sit outside JSON-RPC, because they're about the request and\n * not the method: 401 for a caller `authenticate` refuses, 413 for a body\n * over the limit, and 429 for a new task while the agent is at capacity.\n */\n\nimport type { AgentCard } from '@a2a-js/sdk'\nimport type { A2ARequestHandler, ServerCallContext } from '@a2a-js/sdk/server'\nimport { is_record } from '#schema'\nimport type { A2aServerSdk } from './sdk_loader.js'\nimport type { A2aUser } from './types.js'\n\nexport type HttpConfig = {\n readonly sdk: A2aServerSdk\n readonly card: AgentCard\n readonly handler: A2ARequestHandler\n readonly authenticate: ((request: Request) => A2aUser | null | Promise<A2aUser | null>) | undefined\n readonly rpc_path: string\n readonly max_body_bytes: number\n /**\n * Reserve room for one more task, for the request behind `context`.\n * Returns what gives the room back, or `undefined` when the agent is full.\n */\n readonly reserve: (context: ServerCallContext) => (() => void) | undefined\n /** Whether the agent has closed. */\n readonly is_closed: () => boolean\n}\n\ntype RpcResponse = { readonly jsonrpc: string; readonly id: string | number | null; readonly error?: unknown }\n\nconst CARD_PATH = '/.well-known/agent-card.json'\nconst CARD_MAX_AGE_SECONDS = 300\nconst JSON_TYPE = 'application/json'\nconst STARTS_A_TASK: ReadonlySet<unknown> = new Set(['SendMessage', 'SendStreamingMessage'])\n// JSON-RPC's own codes for a body that isn't JSON and for a server fault.\nconst PARSE_ERROR = -32700\nconst INTERNAL_ERROR = -32603\n\n/**\n * A JSON response.\n */\nfunction json(body: unknown, status = 200, headers: Record<string, string> = {}): Response {\n return new Response(JSON.stringify(body), { status, headers: { 'content-type': JSON_TYPE, ...headers } })\n}\n\n/**\n * A plain refusal that isn't JSON-RPC, with the reason in its body. The\n * body has no `error` field, which a JSON-RPC client would read as an error\n * object and find empty.\n */\nfunction refusal(status: number, message: string, headers: Record<string, string> = {}): Response {\n return json({ message }, status, headers)\n}\n\n/**\n * Read a request's body as text, or `undefined` once it passes `limit`\n * bytes. A declared length over the limit is refused without reading.\n */\nasync function read_body(request: Request, limit: number): Promise<string | undefined> {\n if (Number(request.headers.get('content-length') ?? 0) > limit) return undefined\n if (request.body === null) return ''\n const decoder = new TextDecoder()\n let text = ''\n let size = 0\n for await (const chunk of request.body) {\n size += chunk.byteLength\n if (size > limit) return undefined\n text += decoder.decode(chunk, { stream: true })\n }\n return text + decoder.decode()\n}\n\n/**\n * Whether a JSON-RPC body is a message that would start a task (one that\n * names no task of its own).\n */\nfunction starts_a_task(body: unknown): boolean {\n if (!is_record(body) || !STARTS_A_TASK.has(body['method'])) return false\n const params = body['params']\n const message = is_record(params) ? params['message'] : undefined\n return !(is_record(message) && typeof message['taskId'] === 'string' && message['taskId'] !== '')\n}\n\n/**\n * The id of a JSON-RPC request, for the error that answers it.\n */\nfunction id_of(body: unknown): string | number | null {\n const id = is_record(body) ? body['id'] : null\n return typeof id === 'string' || typeof id === 'number' ? id : null\n}\n\n/**\n * Whether a value is the stream of responses a streaming method returns.\n */\nfunction is_stream(value: unknown): value is AsyncGenerator<RpcResponse, void, undefined> {\n return typeof value === 'object' && value !== null && Symbol.asyncIterator in value\n}\n\n/**\n * Build the fetch handler for one agent.\n */\nexport function http_handler(config: HttpConfig): (request: Request) => Promise<Response> {\n const { sdk, card, handler } = config\n const transport = new sdk.server.JsonRpcTransportHandler(handler)\n const card_body = JSON.stringify(sdk.wire.AgentCard.toJSON(card))\n\n const error_response = (id: string | number | null, err: unknown): RpcResponse => ({\n jsonrpc: '2.0',\n id,\n error: sdk.server.JsonRpcTransportHandler.mapToJSONRPCError(err),\n })\n\n // Send a stream's responses as server-sent events. The pump keeps reading\n // after the client has gone, so the SDK still records what the task does.\n const event_stream = (\n first: RpcResponse | undefined,\n rest: AsyncIterator<RpcResponse>,\n id: string | number | null,\n headers: Record<string, string>,\n ): Response => {\n const encoder = new TextEncoder()\n let open = true\n const body = new ReadableStream<Uint8Array>({\n start: (controller) => {\n const send = (frame: string): void => {\n if (open) controller.enqueue(encoder.encode(frame))\n }\n const pump = async (): Promise<void> => {\n try {\n if (first !== undefined) send(sdk.wire.formatSSEEvent(first))\n for (let next = await rest.next(); next.done !== true; next = await rest.next()) {\n send(sdk.wire.formatSSEEvent(next.value))\n }\n } catch (err) {\n send(sdk.wire.formatSSEErrorEvent(error_response(id, err)))\n }\n if (open) controller.close()\n open = false\n }\n void pump()\n },\n cancel: () => {\n open = false\n },\n })\n return new Response(body, { status: 200, headers: { ...sdk.wire.SSE_HEADERS, ...headers } })\n }\n\n // An absent `A2A-Version` header reads as 0.3, which is the SDK's rule.\n const context_for = (request: Request, user: A2aUser): ServerCallContext => {\n const version = request.headers.get(sdk.wire.A2A_VERSION_HEADER)\n return new sdk.server.ServerCallContext({\n requestedExtensions: sdk.wire.Extensions.parseServiceParameter(\n request.headers.get(sdk.wire.HTTP_EXTENSION_HEADER) ?? undefined,\n ),\n user: { isAuthenticated: user.authenticated, userName: user.name },\n ...(version === null ? {} : { requestedVersion: version }),\n state: new Map<string, unknown>([[sdk.server.STATE_HEADERS_KEY, Object.fromEntries(request.headers)]]),\n })\n }\n\n // Hand a parsed body to the SDK and shape whatever comes back.\n const dispatch = async (body: unknown, context: ServerCallContext): Promise<Response> => {\n const id = id_of(body)\n try {\n sdk.server.validateVersion(context.requestedVersion, card, 'JSONRPC')\n } catch (err) {\n return json(error_response(id, err))\n }\n // The transport handler validates the body's shape itself.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const result = await transport.handle(body as Record<string, unknown>, context)\n const activated = context.activatedExtensions\n const headers: Record<string, string> =\n activated === undefined ? {} : { [sdk.wire.HTTP_EXTENSION_HEADER]: activated.join(',') }\n if (!is_stream(result)) return json(result, 200, headers)\n let first: IteratorResult<RpcResponse, void>\n try {\n first = await result.next()\n } catch (err) {\n return json(error_response(id, err), 200, headers)\n }\n return event_stream(first.done === true ? undefined : first.value, result, id, headers)\n }\n\n const rpc = async (request: Request): Promise<Response> => {\n const user = config.authenticate === undefined ? { name: '', authenticated: false } : await config.authenticate(request)\n if (user === null) return refusal(401, 'unauthorized')\n // A body with no JSON content type is refused, a missing one included.\n // A web page can post such a body to localhost without the browser\n // asking first, and it can't post one that says it's JSON.\n const type = request.headers.get('content-type') ?? ''\n if (type.split(';', 1)[0]?.trim().toLowerCase() !== JSON_TYPE) {\n const unsupported = new sdk.errors.ContentTypeNotSupportedError(\n `Unsupported Content-Type \"${type}\"; expected ${JSON_TYPE}.`,\n )\n return json(error_response(null, unsupported))\n }\n const text = await read_body(request, config.max_body_bytes)\n if (text === undefined) return refusal(413, `the request body is over ${config.max_body_bytes} bytes`)\n let body: unknown\n try {\n body = JSON.parse(text)\n } catch {\n return json({ jsonrpc: '2.0', id: null, error: { code: PARSE_ERROR, message: 'Invalid JSON payload.' } })\n }\n const context = context_for(request, user)\n // The room is reserved in the same step that finds it, with no await\n // between, so requests that arrive together can't all find the last of it.\n const release = starts_a_task(body) ? config.reserve(context) : () => {}\n if (release === undefined) {\n return refusal(429, 'the agent is running as many tasks as it takes at once: try again shortly', {\n 'retry-after': '1',\n })\n }\n try {\n return await dispatch(body, context)\n } catch (err) {\n const mapped = error_response(id_of(body), err)\n const fault = is_record(mapped.error) && mapped.error['code'] === INTERNAL_ERROR\n return json(mapped, fault ? 500 : 200)\n } finally {\n // A request the SDK refused before any drive began still holds its room.\n release()\n }\n }\n\n return async (request) => {\n if (config.is_closed()) return refusal(503, 'the agent has closed')\n const path = new URL(request.url).pathname\n if (path === CARD_PATH) {\n if (request.method !== 'GET') return refusal(405, 'the agent card takes GET', { allow: 'GET' })\n return new Response(card_body, {\n status: 200,\n headers: { 'content-type': JSON_TYPE, 'cache-control': `public, max-age=${CARD_MAX_AGE_SECONDS}` },\n })\n }\n if (path !== config.rpc_path) return refusal(404, `nothing is served at ${path}`)\n if (request.method !== 'POST') return refusal(405, 'JSON-RPC takes POST', { allow: 'POST' })\n return rpc(request)\n }\n}\n","/**\n * Lazy loaders for the optional `@a2a-js/sdk` peer.\n *\n * The adapter needs SDK values (the request handler, the JSON-RPC transport,\n * the client factory, the wire enums), so it imports the SDK dynamically\n * instead of statically. A consumer can import `fascicle/a2a` without the\n * SDK installed and only pays for it when they serve a flow or call a remote\n * agent. A missing peer surfaces as a typed `a2a_sdk_missing_error` that\n * says how to install it, the way src/acp/sdk_loader.ts and\n * src/mcp/sdk_loader.ts do for theirs.\n *\n * The SDK publishes each entry point as a bundle of its own, so the server\n * half and the client half load apart, and a flow that only calls a remote\n * agent never loads the request handler.\n */\n\nimport { a2a_sdk_missing_error } from './errors.js'\n\n/**\n * Throw the typed missing-peer error for a failed import of the SDK.\n */\nfunction missing(err: unknown): never {\n const detail = err instanceof Error ? err.message : String(err)\n throw new a2a_sdk_missing_error(\n `@a2a-js/sdk is required for fascicle/a2a; install it: pnpm add @a2a-js/sdk (cause: ${detail})`,\n )\n}\n\n/**\n * Dynamically imports what serving needs of `@a2a-js/sdk`: the wire types'\n * codecs and enums, the server, and the protocol's errors. Throws a typed\n * `a2a_sdk_missing_error` when the optional peer is not installed.\n */\nexport async function load_a2a_server() {\n try {\n const [wire, server, errors] = await Promise.all([\n import('@a2a-js/sdk'),\n import('@a2a-js/sdk/server'),\n import('@a2a-js/sdk/errors'),\n ])\n return { wire, server, errors }\n } catch (err: unknown) {\n return missing(err)\n }\n}\n\n/**\n * Dynamically imports what calling a remote agent needs of `@a2a-js/sdk`:\n * the wire enums and the client. Throws a typed `a2a_sdk_missing_error` when\n * the optional peer is not installed.\n */\nexport async function load_a2a_client() {\n try {\n const [wire, client] = await Promise.all([import('@a2a-js/sdk'), import('@a2a-js/sdk/client')])\n return { wire, client }\n } catch (err: unknown) {\n return missing(err)\n }\n}\n\nexport type A2aServerSdk = Awaited<ReturnType<typeof load_a2a_server>>\nexport type A2aClientSdk = Awaited<ReturnType<typeof load_a2a_client>>\n","/**\n * The task store the agent hands to the SDK: the caller's store, with the\n * runs kept in step behind it.\n *\n * Task records and runs live in two stores that can't share a transaction,\n * so the runs are the source of truth and every `load` brings the record up\n * to date. A task that isn't terminal takes on whatever its run did since\n * (another process drove it, or an outside event called `runs.resume`\n * directly), which keeps `GetTask` honest and repairs a record that a crash\n * left behind between the two writes. A task this process is driving is left\n * alone, since its own events are on their way.\n *\n * A terminal task needs no run. `FAILED` is final in A2A, while `durable`\n * would drive a failed run again at the next event, so the task's state\n * wins: a `save` that makes a task terminal deletes its run, and so does a\n * `load` that finds one. The run store only ever holds live tasks.\n *\n * A terminal task doesn't change either. A drive that another process\n * canceled runs on to its next resting place, and the SDK drops the status it\n * publishes there but would still fold its artifacts into the record. The\n * SDK loads a task before every write to it, so once a load has seen a task\n * ended, the store refuses every later `save` of it.\n *\n * `list` answers from the same records, so it brings each task on its page\n * up to date the way `load` does. The inner store applies a status filter\n * to the states it has stored, so a filtered `list` first brings up to date\n * the tasks the filter could misplace: the ones stored in a state a task\n * can still leave, up to `STALE_SCAN_LIMIT` of them in each such state.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { ListTasksRequest, Part, Task, TaskStatus } from '@a2a-js/sdk'\nimport type { ServerCallContext, TaskStore } from '@a2a-js/sdk/server'\nimport type { DurableRunState, DurableRuns } from '#core'\nimport { gate_of, is_terminal, status_for } from './task_status.js'\nimport type { Rest, StatusHooks, Wire } from './task_status.js'\n\n/** Where a task was last seen, and who it belongs to. */\nexport type Sighting = { readonly context: ServerCallContext; readonly context_id: string }\n\nexport type TaskRecordsConfig = {\n readonly wire: Wire\n readonly inner: TaskStore\n readonly runs: DurableRuns\n readonly hooks: StatusHooks\n readonly to_parts: (output: unknown) => ReadonlyArray<Part>\n /** Whether this process is driving a task right now. */\n readonly is_live: (task_id: string) => boolean\n}\n\nexport type TaskRecords = {\n readonly store: TaskStore\n /**\n * Who each task this process has touched belongs to, until the task ends\n * or enough other tasks have been touched since.\n */\n readonly seen: ReadonlyMap<string, Sighting>\n /**\n * Resolves once a task is saved in `status`, or after `timeout_ms` when no\n * save comes, which is what happens when nothing reads the task's events.\n * Resolves at once for a task the store has seen ended.\n */\n readonly saved: (task_id: string, status: TaskStatus, timeout_ms: number) => Promise<void>\n}\n\n// How many finished tasks the store remembers, so that loading one again\n// doesn't ask the run store to delete what's already gone, and so that a\n// late write can't change it.\nconst REMEMBERED_LIMIT = 10_000\n\n// How many live tasks the store remembers the owner of. Each sighting holds\n// a request's context, headers included, so a task that a client walked\n// away from can't keep one for the life of the process.\nconst SEEN_LIMIT = 10_000\n\n// How many stored tasks a filtered `list` brings up to date in each state a\n// task can still leave, most recently changed first. It bounds what one\n// request costs: three list calls, and a task load and a run read for each\n// task. It is also the largest page the SDK lets a store be asked for.\nexport const STALE_SCAN_LIMIT = 100\n\ntype Waiter = { readonly status: TaskStatus; readonly resolve: () => void }\n\n/**\n * Where a stored run stands, in the terms a task status is built from.\n */\nfunction rest_of(state: DurableRunState): Rest {\n if (state.kind === 'failed') return { kind: 'failed', error: new Error(state.error) }\n return state\n}\n\n/**\n * Whether a task's record already says what its run does, so that a load\n * leaves it alone. A waiting task matches its run when both name the same\n * gate, and a working one matches a run that's being driven.\n */\nfunction is_current(wire: Wire, task: Task, rest: Rest, next: TaskStatus | undefined): boolean {\n if (next === undefined) return task.status?.state !== wire.TaskState.TASK_STATE_INPUT_REQUIRED\n if (rest.kind !== 'suspended') return false\n return task.status?.state === next.state && gate_of(task) === rest.id\n}\n\n/**\n * Add a task id to a set of remembered ones, emptying the set first once it\n * has grown to its limit. Forgetting costs a repeated store call, never a\n * wrong answer, since the next load of the task remembers it again.\n */\nfunction remember(ids: Set<string>, task_id: string): void {\n if (ids.size >= REMEMBERED_LIMIT) ids.clear()\n ids.add(task_id)\n}\n\n/**\n * Note where a task was last seen, as the newest sighting, and forget the\n * oldest one once more than `limit` are held. A forgotten task is still\n * served: `resume` then needs `user` for a task that belongs to someone.\n */\nexport function sight(seen: Map<string, Sighting>, task_id: string, sighting: Sighting, limit: number): void {\n seen.delete(task_id)\n seen.set(task_id, sighting)\n if (seen.size <= limit) return\n for (const oldest of seen.keys()) {\n seen.delete(oldest)\n return\n }\n}\n\n/**\n * Wrap `config.inner` so that its task records follow their runs.\n */\nexport function task_records(config: TaskRecordsConfig): TaskRecords {\n const { wire, inner, runs, hooks } = config\n const seen = new Map<string, Sighting>()\n const ended = new Set<string>()\n const dropped = new Set<string>()\n const waiters = new Map<string, Set<Waiter>>()\n\n const drop_run = async (task_id: string): Promise<void> => {\n if (dropped.has(task_id)) return\n if (await runs.delete(task_id)) remember(dropped, task_id)\n }\n\n const settle = async (task: Task): Promise<void> => {\n if (!is_terminal(wire, task)) return\n seen.delete(task.id)\n remember(ended, task.id)\n await drop_run(task.id)\n }\n\n const announce = (task: Task): void => {\n for (const waiter of waiters.get(task.id) ?? []) {\n const same = waiter.status.state === task.status?.state && waiter.status.timestamp === task.status.timestamp\n if (same) waiter.resolve()\n }\n }\n\n const write = async (task: Task, context: ServerCallContext): Promise<void> => {\n if (ended.has(task.id)) return\n await inner.save(task, context)\n sight(seen, task.id, { context, context_id: task.contextId }, SEEN_LIMIT)\n announce(task)\n await settle(task)\n }\n\n // Bring a record up to date with its run: a new status, the output as an\n // artifact when the run finished, and the status message in the history,\n // which is where the SDK puts one.\n const reconcile = async (task: Task, context: ServerCallContext): Promise<Task> => {\n const state = await runs.get(task.id)\n if (state === undefined) return task\n const rest = rest_of(state)\n const ids = { task_id: task.id, context_id: task.contextId }\n const next = status_for(wire, hooks, ids, rest)\n if (is_current(wire, task, rest, next)) return task\n const status = next ?? { state: wire.TaskState.TASK_STATE_WORKING, message: undefined, timestamp: new Date().toISOString() }\n const parts = rest.kind === 'done' ? config.to_parts(rest.output) : []\n const artifact = { artifactId: randomUUID(), name: '', description: '', parts: [...parts], metadata: undefined, extensions: [] }\n const updated: Task = {\n ...task,\n status,\n artifacts: parts.length === 0 ? task.artifacts : [...task.artifacts, artifact],\n history: status.message === undefined ? task.history : [...task.history, status.message],\n }\n await write(updated, context)\n return updated\n }\n\n const load: TaskStore['load'] = async (task_id, context) => {\n const task = await inner.load(task_id, context)\n if (task === undefined) return undefined\n if (is_terminal(wire, task)) {\n await settle(task)\n return task\n }\n sight(seen, task_id, { context, context_id: task.contextId }, SEEN_LIMIT)\n return config.is_live(task_id) ? task : reconcile(task, context)\n }\n\n // A listed task as its run has it now. The whole record is loaded, since\n // a page may come without artifacts and a reconcile writes the record\n // back. The page's own choice about artifacts holds for the answer.\n const refresh = async (listed: Task, with_artifacts: boolean, context: ServerCallContext): Promise<Task> => {\n if (is_terminal(wire, listed) || config.is_live(listed.id)) return listed\n const loaded = await load(listed.id, context)\n if (loaded === undefined) return listed\n return with_artifacts ? loaded : { ...loaded, artifacts: [] }\n }\n\n // Bring up to date the stored tasks that a status filter could hide or\n // wrongly show, and resolve the ids it read. A terminal record never\n // changes, so only a task stored as submitted, working, or waiting can be\n // in the wrong place. The scan keeps the request's tenant and context and\n // drops its time window, since a task that catches up gets a new timestamp.\n const catch_up = async (params: ListTasksRequest, context: ServerCallContext): Promise<Set<string>> => {\n const open = [wire.TaskState.TASK_STATE_SUBMITTED, wire.TaskState.TASK_STATE_WORKING, wire.TaskState.TASK_STATE_INPUT_REQUIRED]\n const pages = await Promise.all(\n open.map((status) =>\n inner.list(\n { ...params, status, pageSize: STALE_SCAN_LIMIT, pageToken: '', statusTimestampAfter: undefined, includeArtifacts: false },\n context,\n ),\n ),\n )\n const stale = pages.flatMap((page) => page.tasks).filter((task) => !config.is_live(task.id))\n await Promise.all(stale.map((task) => load(task.id, context)))\n return new Set(stale.map((task) => task.id))\n }\n\n const list: TaskStore['list'] = async (params, context) => {\n const filtered = params.status !== wire.TaskState.TASK_STATE_UNSPECIFIED\n const current = filtered ? await catch_up(params, context) : new Set<string>()\n const page = await inner.list(params, context)\n const tasks = await Promise.all(\n page.tasks.map(async (task) => (current.has(task.id) ? task : refresh(task, params.includeArtifacts === true, context))),\n )\n // A task past the scan's limit can still catch up here, into a state\n // the filter didn't ask for, and then it has no place on the page.\n return { ...page, tasks: filtered ? tasks.filter((task) => task.status?.state === params.status) : tasks }\n }\n\n const store: TaskStore = { load, save: write, list }\n\n const saved = (task_id: string, status: TaskStatus, timeout_ms: number): Promise<void> => {\n // The store refuses every save of a task it has seen ended, so no save is coming.\n if (ended.has(task_id)) return Promise.resolve()\n const { promise, resolve } = Promise.withResolvers<void>()\n const waiting = waiters.get(task_id) ?? new Set<Waiter>()\n waiters.set(task_id, waiting)\n const waiter: Waiter = { status, resolve }\n waiting.add(waiter)\n const timer = setTimeout(resolve, timeout_ms)\n timer.unref()\n return promise.finally(() => {\n clearTimeout(timer)\n waiting.delete(waiter)\n if (waiting.size === 0) waiters.delete(task_id)\n })\n }\n\n return { store, seen, saved }\n}\n","/**\n * a2a_agent: a flow as an Agent2Agent (A2A) v1.0 agent, with its handlers\n * ready and nothing listening.\n *\n * It loads the SDK, builds the card, and wires an executor over durable\n * runs into the SDK's `DefaultRequestHandler`, which holds the protocol's\n * rules (terminal tasks, history, owner scoping, and error shapes). Two thin\n * layers sit around the SDK's parts: a task store that keeps each record in\n * step with its run (task_records.ts), and a request handler that refuses a\n * message its task isn't waiting for (admission.ts).\n *\n * The agent is logic without process glue, the way `acp_agent` is. `fetch`\n * is a web handler, so the agent runs under `serve_a2a` or under whatever\n * framework a caller already has, and `request_handler` covers the REST and\n * gRPC bindings that this module leaves out. It owns no process, so it\n * leaves the signals alone, and `close` leaves the stores to the caller who\n * opened them.\n */\n\nimport type { AgentCard } from '@a2a-js/sdk'\nimport type { ServerCallContext } from '@a2a-js/sdk/server'\nimport { memory_store } from '#adapters'\nimport { describe, durable } from '#core'\nimport { admitting_handler } from './admission.js'\nimport { http_handler } from './http.js'\nimport { output_parts } from './parts.js'\nimport { load_a2a_server } from './sdk_loader.js'\nimport { task_records } from './task_records.js'\nimport { task_runner } from './task_runner.js'\nimport type { Holds, Slots } from './task_runner.js'\nimport { default_failure, default_question } from './task_status.js'\nimport type { StatusHooks } from './task_status.js'\nimport type { A2aAgent, A2aAgentConfig, A2aCard } from './types.js'\n\nconst DEFAULT_MODES = ['text/plain', 'application/json']\nconst DEFAULT_MAX_BODY_BYTES = 1_048_576\nconst DEFAULT_MAX_DRIVES = 8\n\n/**\n * The SDK's agent card for a config's card: one JSON-RPC interface at the\n * card's URL, streaming on, and push notifications and the extended card off.\n */\nfunction agent_card(card: A2aCard): AgentCard {\n return {\n name: card.name,\n description: card.description,\n supportedInterfaces: [{ url: card.url, protocolBinding: 'JSONRPC', tenant: '', protocolVersion: '1.0' }],\n provider: card.provider === undefined ? undefined : { ...card.provider },\n version: card.version ?? '0.0.0',\n documentationUrl: card.documentation_url,\n capabilities: { streaming: true, pushNotifications: false, extensions: [], extendedAgentCard: false },\n securitySchemes: { ...card.security_schemes },\n securityRequirements: [...(card.security_requirements ?? [])],\n defaultInputModes: [...(card.input_modes ?? DEFAULT_MODES)],\n defaultOutputModes: [...(card.output_modes ?? DEFAULT_MODES)],\n skills: card.skills.map((skill) => ({\n id: skill.id,\n name: skill.name,\n description: skill.description,\n tags: [...(skill.tags ?? [])],\n examples: [...(skill.examples ?? [])],\n inputModes: [...(skill.input_modes ?? [])],\n outputModes: [...(skill.output_modes ?? [])],\n securityRequirements: [],\n })),\n signatures: [],\n iconUrl: card.icon_url,\n }\n}\n\n/**\n * Warn on stderr about the steps that every answer to a gate runs again. A\n * resumed drive replays the flow from its input, so a model call before a\n * gate that no `checkpoint` holds bills again each time a client answers.\n */\nfunction warn_about_replays<i, o>(config: A2aAgentConfig<i, o>): void {\n const replays = describe.replays(config.flow)\n if (replays.length === 0) return\n const names = replays.map((hint) => `${hint.id} (before ${hint.gates.join(', ')})`).join('; ')\n process.stderr.write(\n `a2a_agent: ${config.card.name} runs these steps again on every answer to a gate, so wrap each in checkpoint(): ${names}\\n`,\n )\n}\n\n/**\n * Build an A2A agent over `config.flow`, with its handlers ready and\n * nothing listening.\n *\n * Every task is a durable run in `config.runs`, over `memory_store` when\n * the caller gives none, so a task that outlives the process is a choice of\n * store and not a second code path. Throws `a2a_sdk_missing_error` when the\n * `@a2a-js/sdk` peer isn't installed.\n */\nexport async function a2a_agent<i, o>(config: A2aAgentConfig<i, o>): Promise<A2aAgent> {\n const sdk = await load_a2a_server()\n const card = agent_card(config.card)\n const runs = config.runs ?? durable({ store: memory_store() })\n const holds: Holds = new Map()\n const slots: Slots = new WeakMap()\n const custom_parts = config.to_parts\n // The run stored this output from the config's own flow.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const to_parts = custom_parts === undefined ? output_parts : (output: unknown) => custom_parts(output as o)\n const hooks: StatusHooks = {\n gates: config.gates ?? (() => 'client'),\n to_question: config.to_question ?? default_question,\n to_failure: config.to_failure ?? default_failure,\n }\n const records = task_records({\n wire: sdk.wire,\n inner: config.task_store ?? new sdk.server.InMemoryTaskStore(),\n runs,\n hooks,\n to_parts,\n is_live: (task_id) => holds.has(task_id),\n })\n const buses = new sdk.server.DefaultExecutionEventBusManager()\n const runner = task_runner({ sdk, config, runs, records, holds, slots, hooks, to_parts, buses })\n const request_handler = admitting_handler({\n sdk,\n inner: new sdk.server.DefaultRequestHandler(card, records.store, runner.executor, buses),\n store: records.store,\n runs,\n holds,\n gates: hooks.gates,\n })\n const max_drives = config.max_drives ?? DEFAULT_MAX_DRIVES\n let closed = false\n let reserved = 0\n warn_about_replays(config)\n\n // Room for one more task, taken as the request is let in. The check and\n // the count are one synchronous step, and the drive gives the room back\n // once its hold counts instead.\n const reserve = (context: ServerCallContext): (() => void) | undefined => {\n if (holds.size + reserved >= max_drives) return undefined\n reserved += 1\n let held = true\n const release = (): void => {\n if (!held) return\n held = false\n reserved -= 1\n }\n slots.set(context, release)\n return release\n }\n\n return {\n fetch: http_handler({\n sdk,\n card,\n handler: request_handler,\n authenticate: config.authenticate,\n rpc_path: config.rpc_path ?? '/',\n max_body_bytes: config.max_body_bytes ?? DEFAULT_MAX_BODY_BYTES,\n reserve,\n is_closed: () => closed,\n }),\n resume: runner.resume,\n request_handler,\n card,\n close: async () => {\n closed = true\n await runner.close()\n },\n }\n}\n","/**\n * One message to a remote A2A agent, and what its task comes to.\n *\n * `a2a_step` sends each round through here. The message goes out as a\n * stream when the remote agent's card says it can stream, and as a blocking\n * `SendMessage` otherwise. Either way a task that's still working when the\n * call returns is polled with `GetTask`, on a backoff that starts at half a\n * second and stops growing at five, until it rests.\n *\n * While a stream is read, each text chunk of the task's artifacts is\n * recorded as a `model_chunk` event under the step's id when the run asked\n * for chunks, so every consumer that shows a model call's text shows the\n * remote agent's too. Each change of the task's status becomes an `emit`\n * event with the state and the status message's text, and so does the id of\n * the task a round opens.\n *\n * A round ends in one of two ways the flow can go on from: the task\n * completed, or it asked a question. A task that failed, was rejected or\n * canceled, or wants credentials throws `a2a_error`. An abort stops the\n * stream, asks the remote agent to cancel the task (best effort), and\n * throws the abort's reason.\n *\n * What a round resolves is plain JSON, bytes included, because `a2a_step`\n * keeps it in a checkpoint.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { Artifact, Message, Part, SendMessageRequest, StreamResponse, Task, TaskState } from '@a2a-js/sdk'\nimport type { Client } from '@a2a-js/sdk/client'\nimport { aborted_error } from '#core'\nimport type { RunContext } from '#core'\nimport { a2a_error } from './errors.js'\nimport { data_of, text_of, to_plain } from './parts.js'\nimport type { A2aClientSdk } from './sdk_loader.js'\n\n/** A remote agent, reached: the SDK, a client for it, and whether it streams. */\nexport type Remote = {\n readonly sdk: A2aClientSdk\n readonly client: Client\n readonly streams: boolean\n}\n\n/** What one round sends: the parts, and the task and context they continue. */\nexport type Outgoing = {\n readonly round: number\n readonly parts: ReadonlyArray<Part>\n readonly task_id?: string | undefined\n readonly context_id?: string | undefined\n}\n\n/** Where a round came to rest, as plain JSON. */\nexport type Round =\n | {\n readonly kind: 'completed'\n readonly task_id: string\n readonly context_id: string\n /** The task's artifacts, through `to_plain`. */\n readonly artifacts: unknown\n }\n | {\n readonly kind: 'question'\n readonly task_id: string\n readonly context_id: string\n readonly text: string\n readonly data: ReadonlyArray<unknown>\n }\n\n/** What a round has seen of its task so far. */\ntype Seen = {\n task_id: string\n context_id: string\n state: TaskState | undefined\n status: Message | undefined\n /** A reply that came as a bare message, with no task behind it. */\n reply: Message | undefined\n readonly artifacts: Map<string, Artifact>\n}\n\nconst FIRST_POLL_MS = 500\nconst MAX_POLL_MS = 5_000\n// How long an aborted round waits for the remote agent to take its cancel.\nconst CANCEL_WAIT_MS = 5_000\n\n/**\n * The request that carries `outgoing` as one user message.\n */\nfunction request_for(remote: Remote, outgoing: Outgoing): SendMessageRequest {\n return {\n tenant: '',\n message: {\n messageId: randomUUID(),\n contextId: outgoing.context_id ?? '',\n taskId: outgoing.task_id ?? '',\n role: remote.sdk.wire.Role.ROLE_USER,\n parts: [...outgoing.parts],\n metadata: undefined,\n extensions: [],\n referenceTaskIds: [],\n },\n configuration: undefined,\n metadata: undefined,\n }\n}\n\n/**\n * Take a whole task as the latest word on it.\n */\nfunction see_task(seen: Seen, task: Task): void {\n seen.task_id = task.id\n seen.context_id = task.contextId\n seen.state = task.status?.state\n seen.status = task.status?.message\n seen.artifacts.clear()\n for (const artifact of task.artifacts) seen.artifacts.set(artifact.artifactId, artifact)\n}\n\n/**\n * Fold one chunk of an artifact into what the round has of it, the way the\n * task itself does: a chunk that appends adds its parts, and any other\n * replaces the artifact.\n */\nfunction see_artifact(seen: Seen, artifact: Artifact, append: boolean): void {\n const held = seen.artifacts.get(artifact.artifactId)\n const parts = append && held !== undefined ? [...held.parts, ...artifact.parts] : artifact.parts\n seen.artifacts.set(artifact.artifactId, { ...(held ?? artifact), ...artifact, parts })\n}\n\n/**\n * Whether a task is still on its way somewhere, so the round keeps asking.\n */\nfunction is_working(remote: Remote, state: TaskState | undefined): boolean {\n const states = remote.sdk.wire.TaskState\n return state === states.TASK_STATE_WORKING || state === states.TASK_STATE_SUBMITTED\n}\n\n/**\n * Wait `ms`, or reject with the signal's reason as soon as it aborts.\n */\nfunction pause(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const on_abort = (): void => {\n clearTimeout(timer)\n reject(signal.reason instanceof Error ? signal.reason : new aborted_error('aborted', { reason: signal.reason }))\n }\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', on_abort)\n resolve()\n }, ms)\n if (signal.aborted) on_abort()\n else signal.addEventListener('abort', on_abort, { once: true })\n })\n}\n\n/**\n * Where the round rests, given the last the task said: a completion, a\n * question, or an `a2a_error` for anything the flow can't go on from.\n */\nfunction rest_of(remote: Remote, seen: Seen): Round {\n const { task_id, context_id } = seen\n if (seen.reply !== undefined) {\n const artifact: Artifact = {\n artifactId: seen.reply.messageId,\n name: '',\n description: '',\n parts: seen.reply.parts,\n metadata: undefined,\n extensions: [],\n }\n return { kind: 'completed', task_id, context_id, artifacts: to_plain([artifact]) }\n }\n const states = remote.sdk.wire.TaskState\n if (seen.state === states.TASK_STATE_COMPLETED) {\n return { kind: 'completed', task_id, context_id, artifacts: to_plain([...seen.artifacts.values()]) }\n }\n const parts = seen.status?.parts ?? []\n if (seen.state === states.TASK_STATE_INPUT_REQUIRED) {\n return { kind: 'question', task_id, context_id, text: text_of(parts, '\\n'), data: data_of(parts) }\n }\n const state = seen.state === undefined ? 'TASK_STATE_UNSPECIFIED' : remote.sdk.wire.taskStateToJSON(seen.state)\n const status_text = text_of(parts, '\\n')\n throw new a2a_error(\n `the remote task ${task_id} ended in ${state}${status_text === '' ? '' : `: ${status_text}`}`,\n { state, status_text, task_id },\n )\n}\n\n/**\n * Send one message to the remote agent and resolve where its task rests.\n */\nexport async function send_round(remote: Remote, step_id: string, outgoing: Outgoing, ctx: RunContext): Promise<Round> {\n const { client } = remote\n const options = { signal: ctx.abort }\n const seen: Seen = {\n task_id: outgoing.task_id ?? '',\n context_id: outgoing.context_id ?? '',\n state: undefined,\n status: undefined,\n reply: undefined,\n artifacts: new Map(),\n }\n\n const see_status = (state: TaskState | undefined, message: Message | undefined): void => {\n seen.state = state\n seen.status = message\n ctx.emit({\n step_id,\n a2a_status: {\n task_id: seen.task_id,\n state: state === undefined ? 'TASK_STATE_UNSPECIFIED' : remote.sdk.wire.taskStateToJSON(state),\n text: text_of(message?.parts ?? [], '\\n'),\n },\n })\n }\n\n const see_chunk = (artifact: Artifact, append: boolean): void => {\n see_artifact(seen, artifact, append)\n const text = text_of(artifact.parts)\n if (!ctx.streaming || text === '') return\n ctx.trajectory.record({ kind: 'model_chunk', step_id, chunk: { kind: 'text', text, step_index: 0 } })\n }\n\n // Say which remote task the round opened, once, so that whoever watches\n // the run can find the task on the other side.\n let announced = outgoing.task_id !== undefined\n const announce = (): void => {\n if (announced || seen.task_id === '') return\n announced = true\n ctx.emit({ step_id, a2a_task: { task_id: seen.task_id, context_id: seen.context_id } })\n }\n\n const see = (event: StreamResponse): void => {\n const payload = event.payload\n if (payload === undefined) return\n if (payload.$case === 'task') {\n see_task(seen, payload.value)\n announce()\n }\n if (payload.$case === 'message') seen.reply = payload.value\n if (payload.$case === 'statusUpdate') {\n seen.task_id = payload.value.taskId\n see_status(payload.value.status?.state, payload.value.status?.message)\n }\n if (payload.$case === 'artifactUpdate' && payload.value.artifact !== undefined) {\n see_chunk(payload.value.artifact, payload.value.append)\n }\n }\n\n const exchange = async (): Promise<void> => {\n const request = request_for(remote, outgoing)\n if (remote.streams) {\n for await (const event of client.sendMessageStream(request, options)) see(event)\n } else {\n const answer = await client.sendMessage(request, options)\n if ('messageId' in answer) seen.reply = answer\n else see_task(seen, answer)\n announce()\n }\n let wait_ms = FIRST_POLL_MS\n while (seen.reply === undefined && is_working(remote, seen.state)) {\n await pause(wait_ms, ctx.abort)\n wait_ms = Math.min(MAX_POLL_MS, wait_ms * 2)\n see_task(seen, await client.getTask({ tenant: '', id: seen.task_id, historyLength: undefined }, options))\n }\n }\n\n try {\n await exchange()\n } catch (err) {\n if (!ctx.abort.aborted) throw err\n if (seen.task_id !== '') {\n const cancel = client.cancelTask(\n { tenant: '', id: seen.task_id, metadata: undefined },\n { signal: AbortSignal.timeout(CANCEL_WAIT_MS) },\n )\n // Best effort: the remote agent may be gone, or the task already over.\n await cancel.catch(() => {})\n }\n const reason: unknown = ctx.abort.reason\n throw reason instanceof Error ? reason : new aborted_error('aborted', { reason })\n }\n return rest_of(remote, seen)\n}\n","/**\n * The fetch that `a2a_step` hands the A2A client, which adds the config's\n * headers only to requests bound for the origin of the configured URL.\n */\n\ntype Headers_source =\n | Readonly<Record<string, string>>\n | (() => Promise<Readonly<Record<string, string>>>)\n | undefined\n\n/**\n * Wrap `inner` so the headers go with a request only when it is bound for the\n * origin of `base_url`.\n *\n * The headers are usually credentials, and the agent's card chooses the URL\n * that messages are sent to. A card that names another origin would otherwise\n * be handed the caller's token, so a request to any other origin goes out\n * without them, and the headers function isn't run for it.\n */\nexport function scoped_fetch(base_url: string, source: Headers_source, inner: typeof fetch = fetch): typeof fetch {\n const home = new URL(base_url).origin\n return async (input, init) => {\n const target = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url\n if (source === undefined || new URL(target, base_url).origin !== home) return inner(input, init)\n const extra = typeof source === 'function' ? await source() : source\n const headers = new Headers(init?.headers)\n for (const [name, value] of Object.entries(extra)) headers.set(name, value)\n return inner(input, { ...init, headers })\n }\n}\n","/**\n * a2a_step: a step that hands its input to a remote A2A agent and resolves\n * what the agent's task produced.\n *\n * The step is a leaf that streams text much as a model call does, so it's\n * marked `side_effect`, and under `run.stream` or `record_chunks` the remote\n * agent's text arrives as `model_chunk` events under the step's id.\n *\n * A remote question becomes a local `suspend`, which is what lets agents\n * chain: a Fascicle agent that calls another and gets a question surfaces it\n * as its own, all the way up to whoever runs the outermost flow. When the\n * remote task stops at `INPUT_REQUIRED`, the step suspends the local run at\n * a gate named `<step id>_<round>`, with the remote question as the gate's\n * payload, and a resume hands the answer to the same remote task as its\n * next message. The step builds this from public composites inside its own\n * body. Each round's send runs inside a `checkpoint`, so a replay doesn't\n * send it again, and each gate is a `suspend` that the step calls through\n * `ctx.call`. That needs a checkpoint store, which `durable` gives every\n * drive. Without one a remote question throws `a2a_error`, since a resume\n * would otherwise open a second remote task.\n *\n * A round's checkpoint is keyed by the step id, the round, and a digest of\n * what the round sends. Under one checkpoint store, a second call that\n * sends the same thing gets the first call's reply and doesn't reach the\n * remote agent.\n *\n * The card is read once for each step value, on first use, and the step\n * streams when the card says the agent can and `stream` doesn't say\n * otherwise.\n */\n\nimport { createHash } from 'node:crypto'\nimport type { Artifact, Part } from '@a2a-js/sdk'\nimport { assert_valid_step_id, checkpoint, step, suspend } from '#core'\nimport type { AnySchema, RunContext, Step } from '#core'\nimport { a2a_error } from './errors.js'\nimport { data_of, data_part, from_plain, text_of, text_part } from './parts.js'\nimport { send_round } from './remote_task.js'\nimport type { Outgoing, Remote, Round } from './remote_task.js'\nimport { load_a2a_client } from './sdk_loader.js'\nimport { scoped_fetch } from './scoped_fetch.js'\nimport type { A2aRequest, A2aResult, A2aStepConfig } from './types.js'\n\ntype Question = Extract<Round, { readonly kind: 'question' }>\n\n// A gate's answer is whatever the caller resumes with: the remote agent is\n// the one that judges it.\nconst ANY_ANSWER: AnySchema = {\n '~standard': { version: 1, vendor: 'fascicle', validate: (value) => ({ value }) },\n}\n\n/**\n * The parts a request sends: its text, then its data.\n */\nfunction request_parts(input: A2aRequest): Part[] {\n if (typeof input === 'string') return [text_part(input)]\n const parts: Part[] = []\n if (input.text !== undefined) parts.push(text_part(input.text))\n if (input.data !== undefined) parts.push(data_part(input.data))\n return parts\n}\n\n/**\n * The parts an answer to a remote question sends: a string as text, and\n * anything else as data.\n */\nfunction answer_parts(answer: unknown): Part[] {\n return typeof answer === 'string' ? [text_part(answer)] : [data_part(answer)]\n}\n\n/**\n * The checkpoint key of one round's send. It carries a digest of what the\n * round sends, so a step that runs for several inputs in one run keeps each\n * input's rounds apart.\n */\nfunction round_key(step_id: string, outgoing: Outgoing): string {\n const sent = JSON.stringify([outgoing.task_id ?? '', outgoing.context_id ?? '', outgoing.parts])\n const digest = createHash('sha256').update(sent).digest('hex').slice(0, 16)\n return `a2a_step:${step_id}:${outgoing.round}:${digest}`\n}\n\n/**\n * What the step resolves for a completed round.\n */\nfunction result_of(round: Extract<Round, { readonly kind: 'completed' }>): A2aResult {\n // `send_round` wrote these artifacts through `to_plain`.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const artifacts = from_plain(round.artifacts) as Artifact[]\n const parts = artifacts.flatMap((artifact) => artifact.parts)\n return {\n task_id: round.task_id,\n context_id: round.context_id,\n text: text_of(parts),\n data: data_of(parts),\n artifacts,\n }\n}\n\n/**\n * Reach the remote agent: read its card, and build a client that sends the\n * config's headers with every request to the configured URL's origin, the\n * card's included.\n */\nasync function connect(config: A2aStepConfig): Promise<Remote> {\n const sdk = await load_a2a_client()\n const fetch_with_headers = scoped_fetch(config.url, config.headers)\n const factory = new sdk.client.ClientFactory({\n transports: [new sdk.client.JsonRpcTransportFactory({ fetchImpl: fetch_with_headers })],\n cardResolver: new sdk.client.DefaultAgentCardResolver({ fetchImpl: fetch_with_headers }),\n })\n const client = await factory.createFromUrl(config.url)\n const card = await client.getAgentCard()\n return { sdk, client, streams: config.stream ?? card.capabilities?.streaming === true }\n}\n\n/**\n * Build a step that sends its input to the A2A agent at `config.url` as one\n * message and resolves the task's artifacts.\n *\n * A string input is the message's text. An object's `text` and `data`\n * become a text part and a data part, and its `context_id` continues a\n * conversation with the remote agent. A task that ends failed, rejected,\n * canceled, or waiting for credentials throws `a2a_error` with the state\n * and the status text, and an abort cancels the remote task before the step\n * throws.\n */\nexport function a2a_step(config: A2aStepConfig): Step<A2aRequest, A2aResult> {\n assert_valid_step_id(config.id, 'a2a_step id', 'put the label in name')\n const step_id = config.id\n let remote: Promise<Remote> | undefined\n\n // One connection for the step value, made on first use. A failed one is\n // forgotten, so the next run tries again.\n const reach = (): Promise<Remote> => {\n remote ??= connect(config).catch((err: unknown) => {\n remote = undefined\n throw err\n })\n return remote\n }\n\n const send = checkpoint(\n step(`${step_id}_send`, async (outgoing: Outgoing, ctx: RunContext) => send_round(await reach(), step_id, outgoing, ctx)),\n { key: (outgoing) => round_key(step_id, outgoing), name: `${step_id} send` },\n )\n\n const gates = new Map<number, Step<Question, unknown>>()\n const gate_for = (round: number): Step<Question, unknown> => {\n const built =\n gates.get(round) ??\n suspend<Question, unknown, unknown>({\n id: `${step_id}_${round}`,\n name: `${step_id} question ${round}`,\n on: () => {},\n resume_schema: ANY_ANSWER,\n combine: (_question, answer) => answer,\n })\n gates.set(round, built)\n return built\n }\n\n const ask = async (input: A2aRequest, ctx: RunContext): Promise<A2aResult> => {\n let outgoing: Outgoing = {\n round: 1,\n parts: request_parts(input),\n context_id: typeof input === 'string' ? undefined : input.context_id,\n }\n for (;;) {\n const round = await ctx.call(send, outgoing)\n if (round.kind === 'completed') return result_of(round)\n if (ctx.checkpoint_store === undefined) {\n throw new a2a_error(\n `the remote agent asked a question (${JSON.stringify(round.text)}) and step \"${step_id}\" has no checkpoint store to wait with: drive the flow with durable(), or pass checkpoint_store to run()`,\n { state: 'TASK_STATE_INPUT_REQUIRED', status_text: round.text, task_id: round.task_id },\n )\n }\n const answer = await ctx.call(gate_for(outgoing.round), round)\n outgoing = {\n round: outgoing.round + 1,\n parts: answer_parts(answer),\n task_id: round.task_id,\n context_id: round.context_id,\n }\n }\n }\n\n const inner = step(step_id, ask, {\n side_effect: true,\n ...(config.name === undefined ? {} : { name: config.name }),\n ...(config.description === undefined ? {} : { description: config.description }),\n })\n return { ...inner, config: Object.freeze({ remote: 'a2a', url: config.url }) }\n}\n","/**\n * Process glue for serving a flow as an A2A agent over `node:http`.\n *\n * Binds `a2a_agent` to a real server: each request becomes a web `Request`\n * with its body streamed, and the agent's `Response` is piped back out,\n * server-sent events included. The server binds to `127.0.0.1` unless\n * `host` says otherwise, so reaching the network is a choice someone makes.\n *\n * SIGTERM and SIGINT stop new connections, close the agent (which aborts\n * every drive and waits for each to settle), dispose the engine, and exit\n * with the signal's code. The handlers are one-shot, so a second Ctrl-C\n * falls through to Node's default and kills the process outright when a\n * shutdown hangs.\n *\n * Stdout isn't the protocol here, so unlike `serve_acp`, the console stays\n * where it is.\n *\n * Excluded from mutation testing as process glue (see stryker.config.mjs);\n * the spawn test in `__tests__/e2e/` exercises it for real.\n */\n\nimport { createServer } from 'node:http'\nimport type { IncomingMessage, Server, ServerResponse } from 'node:http'\nimport type { AddressInfo } from 'node:net'\nimport { constants } from 'node:os'\nimport { Readable } from 'node:stream'\nimport { a2a_agent } from './a2a_agent.js'\nimport type { A2aAgent, A2aServer, ServeA2aConfig } from './types.js'\n\nconst DEFAULT_HOST = '127.0.0.1'\n\n/**\n * The web `Request` for a Node request, with its body streamed and its\n * signal aborted when the connection closes before the response has ended.\n */\nfunction web_request(incoming: IncomingMessage, outgoing: ServerResponse, base: string): Request {\n const gone = new AbortController()\n outgoing.on('close', () => {\n if (!outgoing.writableFinished) gone.abort()\n })\n const headers = new Headers()\n for (const [name, value] of Object.entries(incoming.headers)) {\n if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(', ') : value)\n }\n const has_body = incoming.method !== 'GET' && incoming.method !== 'HEAD'\n return new Request(new URL(incoming.url ?? '/', base), {\n method: incoming.method ?? 'GET',\n headers,\n signal: gone.signal,\n ...(has_body ? { body: Readable.toWeb(incoming), duplex: 'half' } : {}),\n })\n}\n\n/**\n * Write a web `Response` out through a Node response, a chunk at a time, so\n * a stream reaches the client as it's produced.\n */\nasync function send(response: Response, outgoing: ServerResponse): Promise<void> {\n outgoing.writeHead(response.status, Object.fromEntries(response.headers))\n if (response.body === null) {\n outgoing.end()\n return\n }\n const reader = response.body.getReader()\n outgoing.on('close', () => {\n void reader.cancel().catch(() => {})\n })\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n outgoing.write(value)\n }\n outgoing.end()\n}\n\n/**\n * Answer one Node request with the agent's `fetch`. A handler that throws\n * answers 500, or just ends a response that has already begun.\n */\nasync function answer(agent: A2aAgent, incoming: IncomingMessage, outgoing: ServerResponse, base: string): Promise<void> {\n try {\n await send(await agent.fetch(web_request(incoming, outgoing, base)), outgoing)\n } catch {\n if (outgoing.headersSent) {\n outgoing.end()\n return\n }\n outgoing.writeHead(500, { 'content-type': 'application/json' })\n // No `error` field: a JSON-RPC client would read one as an error object.\n outgoing.end('{\"message\":\"internal error\"}')\n }\n}\n\n/**\n * Start listening, and resolve once the server has its address.\n */\nfunction listen(server: Server, port: number, host: string): Promise<AddressInfo> {\n return new Promise((resolve, reject) => {\n server.once('error', reject)\n server.listen(port, host, () => {\n server.off('error', reject)\n // A server that listens on a port has an address record, never a pipe's path.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n resolve(server.address() as AddressInfo)\n })\n })\n}\n\n/**\n * Serve a flow as an A2A agent over `node:http` until `close`, SIGTERM, or\n * SIGINT. Resolves the address it bound, the agent's `resume` for outside\n * events, and a `close` that stops taking connections, closes the agent, and\n * disposes the engine. A signal does the same, then exits with the signal's\n * code.\n */\nexport async function serve_a2a<i, o>(config: ServeA2aConfig<i, o>): Promise<A2aServer> {\n const agent = await a2a_agent(config)\n const host = config.host ?? DEFAULT_HOST\n let base = `http://${host}`\n const server = createServer((incoming, outgoing) => {\n void answer(agent, incoming, outgoing, base)\n })\n const address = await listen(server, config.port, host)\n base = `http://${address.family === 'IPv6' ? `[${address.address}]` : address.address}:${address.port}`\n\n let closing: Promise<void> | undefined\n const shut_down = async (): Promise<void> => {\n const stopped = new Promise<void>((resolve) => {\n server.close(() => {\n resolve()\n })\n })\n await agent.close()\n // Streams that a closed agent no longer feeds would hold the server open.\n server.closeAllConnections()\n await stopped\n await config.engine?.dispose()\n }\n const on_signal = (signal: NodeJS.Signals): void => {\n void close().finally(() => process.exit(128 + constants.signals[signal]))\n }\n const close = (): Promise<void> => {\n process.off('SIGTERM', on_signal)\n process.off('SIGINT', on_signal)\n closing ??= shut_down()\n return closing\n }\n process.once('SIGTERM', on_signal)\n process.once('SIGINT', on_signal)\n return { url: base, resume: agent.resume, close }\n}\n","/**\n * A SQLite-backed `TaskStore` for the A2A SDK, on `node:sqlite`.\n *\n * Task records are what `GetTask` and `ListTasks` answer from, and\n * `ListTasks` filters by context, state, and time and pages with a cursor,\n * which is a query SQL answers without trying. The store keeps one row per\n * task in a table of its own, so it can share a file with `sqlite_store`\n * from `fascicle/adapters`, which keeps the runs behind the tasks. The two\n * can't share a transaction, so the runs stay the source of truth, and the\n * agent repairs a task record a crash left behind when it next loads it.\n *\n * Rows are scoped the way the SDK's `InMemoryTaskStore` scopes them: by the\n * request's tenant and by the caller's name, so one caller can't read or\n * list another's tasks. A page comes back newest first, by the time of each\n * task's status and then by id, and the cursor is the last row's pair.\n *\n * `node:sqlite` is loaded when the store is built, so importing\n * `fascicle/a2a` never loads it.\n */\n\nimport type { DatabaseSync, SQLInputValue } from 'node:sqlite'\nimport type { ListTasksRequest, ListTasksResponse, Task } from '@a2a-js/sdk'\nimport type { ServerCallContext, TaskStore } from '@a2a-js/sdk/server'\nimport { from_plain, to_plain } from './parts.js'\nimport { load_a2a_server } from './sdk_loader.js'\nimport type { SqliteTaskStoreConfig } from './types.js'\n\nconst DEFAULT_TIMEOUT_MS = 5_000\nconst DEFAULT_PAGE_SIZE = 50\n\nconst SCHEMA = `\n CREATE TABLE IF NOT EXISTS a2a_tasks (\n tenant TEXT NOT NULL,\n owner TEXT NOT NULL,\n id TEXT NOT NULL,\n context_id TEXT NOT NULL,\n state INTEGER NOT NULL,\n status_at TEXT NOT NULL,\n status_ms INTEGER,\n task TEXT NOT NULL,\n PRIMARY KEY (tenant, owner, id)\n ) WITHOUT ROWID;\n CREATE INDEX IF NOT EXISTS a2a_tasks_by_time ON a2a_tasks (tenant, owner, status_at DESC, id DESC);\n CREATE INDEX IF NOT EXISTS a2a_tasks_by_context ON a2a_tasks (tenant, owner, context_id);\n`\n\ntype Scope = { readonly tenant: string; readonly owner: string }\n\ntype Cursor = { readonly status_at: string; readonly id: string }\n\ntype Filter = { readonly where: string; readonly values: SQLInputValue[] }\n\n/**\n * Whose rows a call may touch: the request's tenant and the caller's name,\n * with every unauthenticated caller in one shared scope, as in the SDK's own\n * stores.\n */\nfunction scope_of(context: ServerCallContext): Scope {\n const name = context.user?.userName\n return { tenant: context.tenant ?? '', owner: name === undefined || name === '' ? 'unknown' : name }\n}\n\n/**\n * Parse a stored row back into a task, or `undefined` for a row that holds\n * anything else.\n */\nfunction task_of(row: Record<string, unknown> | undefined): Task | undefined {\n const text = row?.['task']\n if (typeof text !== 'string') return undefined\n // The store wrote this row from a Task, and `from_plain` gives its bytes back.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return from_plain(JSON.parse(text)) as Task\n}\n\n/**\n * The epoch milliseconds of an ISO timestamp, or `null` when it isn't one.\n */\nfunction millis(timestamp: string | undefined): number | null {\n const at = timestamp === undefined ? Number.NaN : Date.parse(timestamp)\n return Number.isNaN(at) ? null : at\n}\n\n/**\n * Encode the last row of a page as the cursor for the next one.\n */\nfunction encode_cursor(cursor: Cursor): string {\n return Buffer.from(`${cursor.status_at}|${cursor.id}`).toString('base64')\n}\n\n/**\n * Read a page token back, or throw the SDK's `RequestMalformedError` for a\n * token this store didn't write.\n */\nasync function decode_cursor(token: string): Promise<Cursor> {\n const [status_at, ...rest] = Buffer.from(token, 'base64').toString('utf8').split('|')\n if (status_at === undefined || rest.length === 0) {\n const { errors } = await load_a2a_server()\n throw new errors.RequestMalformedError('Invalid page token format.')\n }\n return { status_at, id: rest.join('|') }\n}\n\n/**\n * The conditions a list request puts on the caller's rows, before paging.\n */\nfunction filter_of(params: ListTasksRequest, scope: Scope): Filter {\n const where = ['tenant = ?', 'owner = ?']\n const values: SQLInputValue[] = [scope.tenant, scope.owner]\n if (params.contextId) {\n where.push('context_id = ?')\n values.push(params.contextId)\n }\n // 0 is TASK_STATE_UNSPECIFIED, which filters nothing.\n if (params.status) {\n where.push('state = ?')\n values.push(params.status)\n }\n const after = millis(params.statusTimestampAfter)\n if (after !== null) {\n where.push('status_ms > ?')\n values.push(after)\n }\n return { where: where.join(' AND '), values }\n}\n\n/**\n * Open the database at `path` in WAL mode with a busy timeout, and make the\n * task table when it isn't there.\n */\nfunction open_tasks(config: SqliteTaskStoreConfig): DatabaseSync {\n const { DatabaseSync } = process.getBuiltinModule('node:sqlite')\n const db = new DatabaseSync(config.path)\n const timeout_ms = config.timeout_ms ?? DEFAULT_TIMEOUT_MS\n db.exec(`PRAGMA busy_timeout = ${Math.max(0, Math.trunc(timeout_ms))}`)\n db.exec('PRAGMA journal_mode = WAL')\n db.exec(SCHEMA)\n return db\n}\n\n/**\n * Build a `TaskStore` over a SQLite database, for `a2a_agent`'s\n * `task_store`. It can share its file with a `sqlite_store`. `close` closes\n * the database.\n */\nexport function sqlite_task_store(config: SqliteTaskStoreConfig): TaskStore & { readonly close: () => void } {\n const db = open_tasks(config)\n const select = db.prepare('SELECT task FROM a2a_tasks WHERE tenant = ? AND owner = ? AND id = ?')\n const upsert = db.prepare(\n `INSERT INTO a2a_tasks (tenant, owner, id, context_id, state, status_at, status_ms, task)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (tenant, owner, id) DO UPDATE SET\n context_id = excluded.context_id, state = excluded.state, status_at = excluded.status_at,\n status_ms = excluded.status_ms, task = excluded.task`,\n )\n\n return {\n load: async (task_id, context) => {\n const { tenant, owner } = scope_of(context)\n return task_of(select.get(tenant, owner, task_id))\n },\n save: async (task, context) => {\n const { tenant, owner } = scope_of(context)\n const timestamp = task.status?.timestamp\n upsert.run(\n tenant,\n owner,\n task.id,\n task.contextId,\n task.status?.state ?? 0,\n timestamp ?? '',\n millis(timestamp),\n JSON.stringify(to_plain(task)),\n )\n },\n list: async (params, context): Promise<ListTasksResponse> => {\n const page_size = params.pageSize ?? DEFAULT_PAGE_SIZE\n const filter = filter_of(params, scope_of(context))\n const total = db.prepare(`SELECT COUNT(*) AS n FROM a2a_tasks WHERE ${filter.where}`).get(...filter.values)\n const cursor = params.pageToken ? await decode_cursor(params.pageToken) : undefined\n const paged = cursor === undefined ? '' : ' AND (status_at, id) < (?, ?)'\n const rows = db\n .prepare(\n `SELECT status_at, id, task FROM a2a_tasks WHERE ${filter.where}${paged}\n ORDER BY status_at DESC, id DESC LIMIT ?`,\n )\n .all(...filter.values, ...(cursor === undefined ? [] : [cursor.status_at, cursor.id]), page_size + 1)\n const page = rows.slice(0, page_size)\n const last = page.at(-1)\n const tasks = page.flatMap((row) => {\n const task = task_of(row)\n if (task === undefined) return []\n return [params.includeArtifacts === true ? task : { ...task, artifacts: [] }]\n })\n return {\n tasks,\n nextPageToken:\n rows.length > page_size && last !== undefined\n ? encode_cursor({ status_at: String(last['status_at']), id: String(last['id']) })\n : '',\n pageSize: page_size,\n totalSize: Number(total?.['n'] ?? 0),\n }\n },\n close: () => {\n db.close()\n },\n }\n}\n"],"mappings":";;;;;;;;AAgBA,MAAM,QAAQ;;;;AAKd,SAAgB,UAAU,MAAoB;CAC5C,OAAO;EAAE,SAAS;GAAE,OAAO;GAAQ,OAAO;EAAK;EAAG,UAAU,KAAA;EAAW,UAAU;EAAI,WAAW;CAAa;AAC/G;;;;AAKA,SAAgB,UAAU,OAAsB;CAC9C,OAAO;EAAE,SAAS;GAAE,OAAO;GAAQ;EAAM;EAAG,UAAU,KAAA;EAAW,UAAU;EAAI,WAAW;CAAmB;AAC/G;;;;;AAMA,SAAgB,aAAa,QAAyB;CACpD,IAAI,OAAO,WAAW,UAAU,OAAO,CAAC,UAAU,MAAM,CAAC;CACzD,IAAI,WAAW,KAAA,KAAa,WAAW,MAAM,OAAO,CAAC;CACrD,OAAO,CAAC,UAAU,MAAM,CAAC;AAC3B;;;;AAKA,SAAgB,QAAQ,OAA4B,YAAY,IAAY;CAC1E,MAAM,QAAkB,CAAC;CACzB,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,SAAS,UAAU,QAAQ,MAAM,KAAK,KAAK,QAAQ,KAAK;CAEnE,OAAO,MAAM,KAAK,SAAS;AAC7B;;;;AAKA,SAAgB,QAAQ,OAAuC;CAC7D,MAAM,SAAoB,CAAC;CAC3B,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,SAAS,UAAU,QAAQ,OAAO,KAAK,KAAK,QAAQ,KAAK;CAEpE,OAAO;AACT;;;;;AAMA,SAAgB,SAAS,OAAuC;CAC9D,MAAM,QAAmB,CAAC;CAC1B,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,OAAO;GAAE,UAAU,KAAK;GAAU,YAAY,KAAK;EAAU;EACnE,IAAI,KAAK,SAA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,OAAO,YAAY,MAAM,cAAc,OAAO,SAAS,IAAI,KAAA;GAC1E,MAAM,QAAQ,WAAW,KAAA,IAAY,KAAK;GAC1C,MAAM,OAAO,GACV,QACC,mDAAmD,OAAO,QAAQ,MAAM;oDAE1E,CAAC,CACA,IAAI,GAAG,OAAO,QAAQ,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,CAAC,OAAO,WAAW,OAAO,EAAE,GAAI,YAAY,CAAC;GACtG,MAAM,OAAO,KAAK,MAAM,GAAG,SAAS;GACpC,MAAM,OAAO,KAAK,GAAG,EAAE;GAMvB,OAAO;IACL,OANY,KAAK,SAAS,QAAQ;KAClC,MAAM,OAAO,QAAQ,GAAG;KACxB,IAAI,SAAS,KAAA,GAAW,OAAO,CAAC;KAChC,OAAO,CAAC,OAAO,qBAAqB,OAAO,OAAO;MAAE,GAAG;MAAM,WAAW,CAAC;KAAE,CAAC;IAC9E,CAEM;IACJ,eACE,KAAK,SAAS,aAAa,SAAS,KAAA,IAChC,cAAc;KAAE,WAAW,OAAO,KAAK,YAAY;KAAG,IAAI,OAAO,KAAK,KAAK;IAAE,CAAC,IAC9E;IACN,UAAU;IACV,WAAW,OAAO,QAAQ,QAAQ,CAAC;GACrC;EACF;EACA,aAAa;GACX,GAAG,MAAM;EACX;CACF;AACF"}
package/dist/acp.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { c as Step, h as TrajectoryLogger, m as TrajectoryEvent } from "./types-BUXt_zgJ.js";
2
- import { M as Tool, N as ToolApprovalHandler } from "./types-Dk9tLpUq.js";
1
+ import { c as Step, h as TrajectoryLogger, m as TrajectoryEvent, n as CheckpointStore } from "./types-BtRpSctv.js";
2
+ import { M as Tool, N as ToolApprovalHandler } from "./types-CDTW7XWB.js";
3
3
  import { AgentApp, ClientCapabilities, ContentBlock, SessionUpdate } from "@agentclientprotocol/sdk";
4
4
  /**
5
5
  * Where a model call's streamed text goes: the reply, the collapsed thought
@@ -81,13 +81,22 @@ type AcpStoredSession = {
81
81
  readonly updated_at: string;
82
82
  readonly history: ReadonlyArray<AcpHistoryEntry>;
83
83
  readonly usage: AcpSessionUsage;
84
+ /**
85
+ * How many of the session's turns the store keeps as the client saw them,
86
+ * which `session/load` replays. Left out by a store that keeps none, and a
87
+ * load of that session replays the history's text instead.
88
+ */
89
+ readonly turns?: number | undefined;
84
90
  };
85
91
  /** What `session/list` reports of a stored session, without its history. */
86
92
  type AcpSessionSummary = Pick<AcpStoredSession, 'id' | 'cwd' | 'additional_directories' | 'title' | 'updated_at'>;
87
93
  /**
88
94
  * Where an agent keeps its sessions between processes.
89
- * `filesystem_session_store` keeps one JSON file for each, and any other
90
- * store needs only these three functions.
95
+ * `filesystem_session_store` keeps one JSON file for each, and
96
+ * `checkpoint_session_store` keeps them in any `CheckpointStore`. A store of
97
+ * your own needs only `save`, `load`, and `list`. Each of the other three
98
+ * adds one thing: `delete` lets a client delete a thread, and `save_turn`
99
+ * with `load_turns` lets a loaded thread come back with its tool cards.
91
100
  */
92
101
  type AcpSessionStore = {
93
102
  /** Keeps the session, in place of any earlier copy with its id. */
@@ -96,7 +105,26 @@ type AcpSessionStore = {
96
105
  readonly load: (id: string) => Promise<AcpStoredSession | undefined>;
97
106
  /** Every session the store holds, in any order. */
98
107
  readonly list: () => Promise<ReadonlyArray<AcpSessionSummary>>;
108
+ /**
109
+ * Removes the session and every turn kept for it, and resolves for an id
110
+ * the store doesn't hold. With it, the agent answers `session/delete`.
111
+ */
112
+ readonly delete?: ((id: string) => Promise<void>) | undefined;
113
+ /**
114
+ * Keeps turn `index` of a session as the client saw it: the prompt, then
115
+ * every update the turn sent. The agent calls it before the `save` that
116
+ * counts the turn, so a turn the count doesn't reach was never finished.
117
+ */
118
+ readonly save_turn?: ((id: string, index: number, updates: ReadonlyArray<SessionUpdate>) => Promise<void>) | undefined;
119
+ /** The first `count` turns kept for a session, oldest first, each as `save_turn` was given it. */
120
+ readonly load_turns?: ((id: string, count: number) => Promise<ReadonlyArray<ReadonlyArray<SessionUpdate>>>) | undefined;
99
121
  };
122
+ /**
123
+ * A session store with every optional part, which is what
124
+ * `filesystem_session_store` and `checkpoint_session_store` build: one that
125
+ * can delete a session and keeps each turn as the client saw it.
126
+ */
127
+ type AcpFullSessionStore = { readonly [key in keyof AcpSessionStore]-?: NonNullable<AcpSessionStore[key]>; };
100
128
  /**
101
129
  * Everything a flow sees of one prompt turn. `text` joins the prompt's text
102
130
  * blocks, writes a resource link or an embedded resource as its URI, and
@@ -134,6 +162,28 @@ type AcpModel = {
134
162
  */
135
163
  readonly context_window?: number | undefined;
136
164
  };
165
+ /**
166
+ * How a user logs in to an agent from the client. With it, the agent offers
167
+ * a login method in `initialize`, and refuses to start, load, or resume a
168
+ * session with `auth_required` until `ready` says yes, which is the error a
169
+ * client answers by offering the login.
170
+ */
171
+ type AcpAuth = {
172
+ /** What the client shows for the login. */
173
+ readonly name: string;
174
+ readonly description?: string | undefined;
175
+ /** Whether the agent can start a session now, asked as each session starts. */
176
+ readonly ready: () => boolean | Promise<boolean>;
177
+ /** What the user has to do when `ready` says no, which is the message of every refusal. */
178
+ readonly instructions: string;
179
+ /**
180
+ * The arguments that run the agent's own command as a login in a terminal,
181
+ * offered only to a client that says it can run one.
182
+ */
183
+ readonly terminal_args?: ReadonlyArray<string> | undefined;
184
+ /** Forgets a stored login. With it, the agent offers `logout`. */
185
+ readonly logout?: (() => Promise<void>) | undefined;
186
+ };
137
187
  /**
138
188
  * A session as its flow builder sees it, made once per `session/new`.
139
189
  */
@@ -210,9 +260,11 @@ type WorkspaceToolsOptions = {
210
260
  type ServeAcpCommon<i, o> = {
211
261
  /**
212
262
  * The flow each prompt turn runs, or a function that builds one per
213
- * session, for a flow whose tools or approval handler close over it.
263
+ * session, for a flow whose tools or approval handler close over it. The
264
+ * function may return a promise, for a builder that has to wait on
265
+ * something first.
214
266
  */
215
- readonly flow: Step<i, o> | ((session: AcpSession) => Step<i, o>);
267
+ readonly flow: Step<i, o> | ((session: AcpSession) => Step<i, o> | Promise<Step<i, o>>);
216
268
  /** Reported to the client as `agentInfo.name`. */
217
269
  readonly name: string;
218
270
  /** Reported to the client as `agentInfo.version`; default: `'0.0.0'`. */
@@ -278,9 +330,17 @@ type ServeAcpCommon<i, o> = {
278
330
  * session after each turn and each mode switch, and a client can list its
279
331
  * threads (`session/list`), load one back with its messages
280
332
  * (`session/load`), or pick one up without them (`session/resume`).
281
- * Without one, sessions live in memory and end with the process.
333
+ * Without one, sessions live in memory and end with the process. A store
334
+ * with `delete` adds `session/delete`, and one that keeps turns replays a
335
+ * loaded thread as the client saw it, tool cards included.
282
336
  */
283
337
  readonly session_store?: AcpSessionStore | undefined;
338
+ /**
339
+ * How a user logs in from the client. Without it the agent offers no login
340
+ * and never answers `auth_required`, so the provider's key has to be in
341
+ * the environment the client launches the agent with.
342
+ */
343
+ readonly auth?: AcpAuth | undefined;
284
344
  /** Where each model call's text goes, by its `step_id`; default: `'message'`. */
285
345
  readonly stream?: ((step_id: string) => AcpStreamRoute) | undefined;
286
346
  /** Maps each run event to the updates sent to the client; default: `to_session_updates`. */
@@ -315,6 +375,57 @@ type ServeAcpConfig<i, o> = ServeAcpCommon<i, o> & ([string] extends [i] ? {
315
375
  * before it can overwrite the first client's capabilities.
316
376
  */
317
377
  export declare function acp_agent<i, o>(config: ServeAcpConfig<i, o>): Promise<AgentApp>;
378
+ type ApiKeyLoginConfig = {
379
+ /** What the client shows for the login, such as `'OpenRouter API key'`. */
380
+ readonly name: string;
381
+ /** The environment variable read first, such as `'OPENROUTER_API_KEY'`. */
382
+ readonly variable: string;
383
+ /** Where a key entered at the terminal is kept. */
384
+ readonly file: string;
385
+ /** The environment `variable` is read from, which an entry point passes as `process.env`. */
386
+ readonly env: Readonly<Record<string, string | undefined>>;
387
+ };
388
+ /**
389
+ * The terminal a login reads the key from. `process.stdin` and
390
+ * `process.stderr` fit it, and stderr is the output to use, since stdout
391
+ * belongs to whoever launched the command.
392
+ */
393
+ type LoginTerminal = {
394
+ readonly input: {
395
+ readonly isTTY?: boolean | undefined;
396
+ readonly setRawMode?: ((raw: boolean) => unknown) | undefined;
397
+ readonly on: (event: 'data', listener: (chunk: Buffer | string) => void) => unknown;
398
+ readonly off: (event: 'data', listener: (chunk: Buffer | string) => void) => unknown;
399
+ readonly resume?: (() => unknown) | undefined;
400
+ readonly pause?: (() => unknown) | undefined;
401
+ };
402
+ readonly output: {
403
+ readonly write: (text: string) => unknown;
404
+ };
405
+ };
406
+ type ApiKeyLogin = {
407
+ /** The key now: the variable when it's set, and the file otherwise. */
408
+ readonly key: () => string | undefined;
409
+ /** The login for `serve_acp`'s `auth`, with a terminal login under `--login`. */
410
+ readonly auth: AcpAuth;
411
+ /**
412
+ * Reads a key at the terminal without echoing it, writes the file, and
413
+ * resolves with the process's exit code: 0 once the key is kept, and 1
414
+ * when the input isn't a terminal or no key was entered.
415
+ */
416
+ readonly run: (terminal: LoginTerminal) => Promise<number>;
417
+ };
418
+ /**
419
+ * Build a login that keeps one API key: `key` reads it, `auth` goes to
420
+ * `serve_acp`, and `run` is the terminal login the agent's entry point runs
421
+ * under `--login`.
422
+ */
423
+ export declare function api_key_login(config: ApiKeyLoginConfig): ApiKeyLogin;
424
+ /**
425
+ * Build a session store that keeps its sessions in `store`, with their
426
+ * turns, and can delete them.
427
+ */
428
+ export declare function checkpoint_session_store(store: CheckpointStore): AcpFullSessionStore;
318
429
  /**
319
430
  * Typed errors for the ACP adapter.
320
431
  *
@@ -340,7 +451,7 @@ type FilesystemSessionStoreConfig = {
340
451
  * Build a session store that keeps one JSON file for each session under
341
452
  * `root_dir`.
342
453
  */
343
- export declare function filesystem_session_store(config: FilesystemSessionStoreConfig): AcpSessionStore;
454
+ export declare function filesystem_session_store(config: FilesystemSessionStoreConfig): AcpFullSessionStore;
344
455
  /**
345
456
  * Create the state for one prompt turn's events, routing every model call's
346
457
  * text to the reply unless `stream` says otherwise.
@@ -362,5 +473,5 @@ export declare function to_session_updates(event: TrajectoryEvent, state: AcpMap
362
473
  * workspace tools' within the session.
363
474
  */
364
475
  export declare function workspace_tools(session: AcpSession, options?: WorkspaceToolsOptions): ReadonlyArray<Tool>;
365
- export type { AcpHistoryEntry, AcpMapperOptions, AcpMapperState, AcpMode, AcpModel, AcpSession, AcpSessionStore, AcpSessionSummary, AcpSessionUsage, AcpStoredSession, AcpStreamRoute, AcpTurn, FilesystemSessionStoreConfig, ServeAcpConfig, WorkspaceToolsOptions };
476
+ export type { AcpAuth, AcpFullSessionStore, AcpHistoryEntry, AcpMapperOptions, AcpMapperState, AcpMode, AcpModel, AcpSession, AcpSessionStore, AcpSessionSummary, AcpSessionUsage, AcpStoredSession, AcpStreamRoute, AcpTurn, ApiKeyLogin, ApiKeyLoginConfig, FilesystemSessionStoreConfig, LoginTerminal, ServeAcpConfig, WorkspaceToolsOptions };
366
477
  //# sourceMappingURL=acp.d.ts.map