@arnilo/prism-hosts 0.13.1 → 0.14.1
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.
- package/CHANGELOG.md +6 -0
- package/a2a/README.md +195 -0
- package/a2a/src/card.ts +208 -0
- package/a2a/src/codec.ts +523 -0
- package/a2a/src/connect.ts +415 -0
- package/a2a/src/errors.ts +87 -0
- package/a2a/src/index.ts +40 -0
- package/a2a/src/limits.ts +43 -0
- package/a2a/src/pending.ts +28 -0
- package/a2a/src/proxy.ts +526 -0
- package/a2a/src/serve.ts +886 -0
- package/acp/README.md +3 -1
- package/acp/src/limits.ts +3 -16
- package/acp/src/mapper.ts +26 -5
- package/acp/src/serve.ts +6 -5
- package/ag-ui/README.md +2 -1
- package/ag-ui/src/a2ui.ts +8 -31
- package/ag-ui/src/ag-ui-mapper.ts +27 -1
- package/ag-ui/src/encrypted-value.ts +3 -3
- package/ag-ui/src/handler.ts +4 -4
- package/ag-ui/src/index.ts +0 -33
- package/ag-ui/src/limits.ts +5 -88
- package/ag-ui/src/projectors.ts +8 -6
- package/ag-ui/src/renderer/bind.ts +2 -1
- package/channels/README.md +61 -5
- package/channels/src/discord-gateway.ts +354 -0
- package/channels/src/discord.ts +873 -0
- package/channels/src/index.ts +4 -2
- package/channels/src/limits.ts +3 -19
- package/channels/src/pairing.ts +1 -2
- package/channels/src/runtime-turn.ts +10 -2
- package/channels/src/signal.ts +11 -19
- package/channels/src/slack.ts +854 -0
- package/channels/src/telegram.ts +22 -44
- package/channels/src/types.ts +5 -2
- package/devtools/README.md +1 -1
- package/driver-process/src/driver.ts +3 -1
- package/driver-process/src/testing.ts +1 -1
- package/driver-process/src/turn.ts +5 -1
- package/evals/README.md +11 -7
- package/evals/src/calibration.ts +5 -13
- package/evals/src/compare-experiments.ts +1 -2
- package/evals/src/comparison.ts +7 -25
- package/evals/src/curate.ts +3 -9
- package/evals/src/dataset.ts +0 -2
- package/evals/src/index.ts +3 -20
- package/evals/src/injection.ts +33 -6
- package/evals/src/judge.ts +9 -13
- package/evals/src/limits.ts +0 -17
- package/evals/src/rubric-judge.ts +5 -10
- package/evals/src/scenario-runner.ts +8 -4
- package/evals/src/scenarios.ts +5 -5
- package/evals/src/score.ts +3 -5
- package/evals/src/stats.ts +0 -2
- package/evals/src/threshold.ts +3 -3
- package/evals/src/toolless-session.ts +7 -3
- package/evals/src/trace.ts +8 -14
- package/evals/src/trajectory.ts +45 -11
- package/evals/src/types.ts +2 -2
- package/evals/src/user-simulator.ts +1 -7
- package/evals/src/util.ts +3 -9
- package/headless/README.md +20 -1
- package/headless/src/authority.ts +14 -1
- package/headless/src/errors.ts +3 -1
- package/headless/src/index.ts +10 -1
- package/headless/src/limits.ts +2 -2
- package/headless/src/pending.ts +4 -3
- package/headless/src/recover.ts +126 -0
- package/headless/src/resume.ts +1 -1
- package/host-builder/data/api.json +1276 -1365
- package/host-builder/data/errors.json +199 -185
- package/host-builder/data/examples/a2a-client.ts +125 -0
- package/host-builder/data/examples/a2a-server.ts +133 -0
- package/host-builder/data/examples/autonomous-coding-loop.ts +1 -1
- package/host-builder/data/examples/build-workflow.ts +2 -2
- package/host-builder/data/examples/caveman-ponytail.ts +1 -1
- package/host-builder/data/examples/channel-discord.ts +176 -0
- package/host-builder/data/examples/channel-slack.ts +146 -0
- package/host-builder/data/examples/continue-after-failure.ts +80 -0
- package/host-builder/data/examples/custom-adapter.ts +1 -1
- package/host-builder/data/examples/decision-models.ts +1 -1
- package/host-builder/data/examples/define-package.ts +1 -1
- package/host-builder/data/examples/delegate.ts +74 -9
- package/host-builder/data/examples/durable-loops-and-approvals.ts +11 -10
- package/host-builder/data/examples/governance-deny.ts +1 -1
- package/host-builder/data/examples/guardrail-content.ts +126 -0
- package/host-builder/data/examples/headless-host.ts +1 -1
- package/host-builder/data/examples/long-running-job.ts +129 -0
- package/host-builder/data/examples/long-term-memory.ts +1 -1
- package/host-builder/data/examples/mcp-oauth.ts +197 -0
- package/host-builder/data/examples/mcp-trust.ts +1 -1
- package/host-builder/data/examples/memory-and-wiki.ts +2 -2
- package/host-builder/data/examples/memory-system.ts +19 -9
- package/host-builder/data/examples/model-router-aggregate-budgets.ts +1 -1
- package/host-builder/data/examples/parallel-tools.ts +70 -0
- package/host-builder/data/examples/remote-agent.ts +1 -1
- package/host-builder/data/examples/serve-tools.ts +1 -1
- package/host-builder/data/examples/session-memory.ts +18 -16
- package/host-builder/data/examples/side-call.ts +1 -1
- package/host-builder/data/examples/sqlite-resume.ts +1 -1
- package/host-builder/data/examples/structured-output.ts +57 -0
- package/host-builder/data/examples.json +14 -4
- package/host-builder/skills/prism-host-builder/SKILL.md +1 -1
- package/host-builder/skills/prism-host-builder/references/choosing.md +14 -10
- package/host-builder/skills/prism-host-builder/references/pitfalls.md +5 -3
- package/host-builder/skills/prism-host-builder/references/recipes.md +5 -5
- package/host-builder/skills/prism-host-builder/references/verification.md +1 -1
- package/host-builder/src/check/runner.ts +2 -3
- package/host-builder/src/server.ts +2 -2
- package/mcp-server/README.md +3 -3
- package/mcp-server/src/bounds.ts +3 -3
- package/mcp-server/src/serve-tools.ts +2 -9
- package/mcp-server/src/serve.ts +2 -4
- package/mcp-server/src/server.ts +10 -20
- package/package.json +12 -6
- package/remote/README.md +7 -4
- package/remote/src/channel.ts +6 -2
- package/remote/src/connect.ts +9 -3
- package/remote/src/errors.ts +3 -1
- package/remote/src/limits.ts +3 -13
- package/remote/src/mirror.ts +2 -1
- package/remote/src/pending.ts +4 -3
- package/remote/src/protocol.ts +3 -0
- package/remote/src/serve.ts +43 -5
- package/remote/src/session-proxy.ts +28 -5
- package/remote/src/testing.ts +3 -1
- package/remote/src/wire.ts +74 -14
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.14.1] - 2026-11-23
|
|
6
|
+
|
|
7
|
+
- `./host-builder`: the version-exact API index (`data/api.json`) is regenerated for `@arnilo/prism` 0.14.1. It adds `CredentialContext.sessionId` and `principal`, the `credentials.resolve(ref, request)` overload, and the request-aware `refSource` / `optionalRefSource`. No runtime change.
|
|
8
|
+
|
|
9
|
+
## [0.14.0] - 2026-11-23
|
|
10
|
+
|
|
5
11
|
Consolidate ten host and driver workspaces into `@arnilo/prism-hosts` subpaths. Preserve library exports, protocol caps, authentication, sandboxing and both executable bins. Host-builder indexes and the installer use bundle specifiers. Versions remain in lockstep with the kernel.
|
|
6
12
|
|
|
7
13
|
### ./mcp-server history
|
package/a2a/README.md
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
# @arnilo/prism-hosts/a2a
|
|
2
|
+
|
|
3
|
+
Host library for the [A2A protocol](https://a2a-protocol.org) 1.0, JSON-RPC binding: `serveA2A` serves one Prism `Agent` to agents built on other frameworks, and `connectA2A` calls such an agent as a local `Agent`.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
bun add @arnilo/prism @arnilo/prism-hosts
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
This is a host library, not a native package: import it in the host; do not add it to an agent's manifest or `packages` list. It registers no tools, skills, commands, hooks, slots, or services, and importing it opens no socket and starts no timer.
|
|
12
|
+
|
|
13
|
+
## What it does
|
|
14
|
+
|
|
15
|
+
`serveA2A(agent, options)` returns a web handler `(request: Request) => Promise<Response>`. Mount it on any server that speaks `Request`/`Response`, for example `Bun.serve({ fetch: handle })`. It constructs no agent.
|
|
16
|
+
|
|
17
|
+
- `GET /.well-known/agent-card.json` serves the Agent Card. `capabilities` is filled from what the handler implements: `streaming: true`, `pushNotifications: false`, `extendedAgentCard: false`, and the Prism decisions extension.
|
|
18
|
+
- `POST` to the path of the card's JSONRPC interface serves these methods:
|
|
19
|
+
|
|
20
|
+
| Method | What runs |
|
|
21
|
+
| --- | --- |
|
|
22
|
+
| `SendMessage` | `session.stream(input)` (or `session.resume(decisions)` on a task that waits for input); answers once the task is terminal or interrupted. `configuration.returnImmediately: true` answers with the `TASK_STATE_WORKING` task as soon as the run starts. |
|
|
23
|
+
| `SendStreamingMessage` | Same, as SSE. The first frame is the task; then `artifactUpdate` frames carry assistant text deltas (`append: true` after the first chunk) and a final `statusUpdate` closes the stream. |
|
|
24
|
+
| `GetTask` | The task snapshot. `historyLength` adds up to that many stored user and assistant messages of the context (capped by `limits.maxHistory`). |
|
|
25
|
+
| `CancelTask` | `session.abort()` on a working task, then answers the `TASK_STATE_CANCELED` task. |
|
|
26
|
+
| `SubscribeToTask` | A task snapshot, then the live frames of a working task until it ends. |
|
|
27
|
+
|
|
28
|
+
Every call runs through `session.stream` / `session.resume`, so approvals, hooks, guardrails, and run limits apply. The handler never dispatches a tool itself.
|
|
29
|
+
|
|
30
|
+
### Contexts and tasks
|
|
31
|
+
|
|
32
|
+
- A `contextId` is one session: `agent.session({ id: contextId, create: true, ownership })`. A message without `contextId` gets a new one.
|
|
33
|
+
- A task is one run plus every resume that continues it. Its id is issued by the server and names its context and run.
|
|
34
|
+
- The handler keeps a bounded in-process task registry. A task suspended for input survives a restart: `GetTask` or a follow-up message reads the suspension back from the session. A settled task that is no longer in the registry answers `-32001` TaskNotFound.
|
|
35
|
+
- A context runs one task at a time, and refuses a new task while one of its tasks waits for decisions (`-32602`). Answer the decisions, or reject them, first.
|
|
36
|
+
|
|
37
|
+
### Run status → task state
|
|
38
|
+
|
|
39
|
+
| Run | Task state |
|
|
40
|
+
| --- | --- |
|
|
41
|
+
| `completed`, or `stopped` for any reason but `denied` | `TASK_STATE_COMPLETED` |
|
|
42
|
+
| `stopped` with `stopReason: "denied"` | `TASK_STATE_REJECTED` |
|
|
43
|
+
| `suspended` | `TASK_STATE_INPUT_REQUIRED` |
|
|
44
|
+
| `failed` | `TASK_STATE_FAILED` (the redacted error message in `status.message`) |
|
|
45
|
+
| aborted by `CancelTask` | `TASK_STATE_CANCELED` |
|
|
46
|
+
|
|
47
|
+
`TASK_STATE_AUTH_REQUIRED` is never emitted.
|
|
48
|
+
|
|
49
|
+
### Approvals: `TASK_STATE_INPUT_REQUIRED`
|
|
50
|
+
|
|
51
|
+
A run that suspends reports `TASK_STATE_INPUT_REQUIRED`. `status.message.parts` holds one `data` part per pending decision: `{ approvalId, kind, toolName?, reason, elicitationSchema? }`. The reason is already redacted by the kernel.
|
|
52
|
+
|
|
53
|
+
The peer answers with a follow-up `SendMessage` on the same `taskId` that lists the Prism decisions extension in `message.extensions` and carries one `data` part `{ decisions: [{ approvalId, outcome, reason?, elicitation? }] }`. `outcome` is `allow_once`, `allow_for_run`, `reject_once`, or `reject_for_run`. The handler calls `session.resume(decisions)`.
|
|
54
|
+
|
|
55
|
+
```json
|
|
56
|
+
{
|
|
57
|
+
"messageId": "m-2",
|
|
58
|
+
"role": "ROLE_USER",
|
|
59
|
+
"taskId": "<task id>",
|
|
60
|
+
"extensions": ["https://prism.arnilo.dev/a2a/extensions/decisions/v1"],
|
|
61
|
+
"parts": [{ "data": { "decisions": [{ "approvalId": "<approval id>", "outcome": "allow_once" }] } }]
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
A follow-up without decisions answers `-32602` and the task stays `TASK_STATE_INPUT_REQUIRED`. `CancelTask` on a waiting task answers `-32002`: send reject decisions instead. `modifiedArguments` is refused unless `allowModifiedArguments: true`, and the kernel re-gates it.
|
|
66
|
+
|
|
67
|
+
### Parts
|
|
68
|
+
|
|
69
|
+
| Part | Becomes |
|
|
70
|
+
| --- | --- |
|
|
71
|
+
| `text` | a text block |
|
|
72
|
+
| `data` (other than decisions) | one canonical-JSON text block |
|
|
73
|
+
| `raw` with `image/*` | an image block, only if the model declares `image` input |
|
|
74
|
+
| `raw` with `audio/*` | an audio block, only if the model declares `audio` |
|
|
75
|
+
| `raw` with `application/pdf` or `text/*` | a document block, only if the model declares `document` |
|
|
76
|
+
| other `raw` | a file block, only if the model declares `file` |
|
|
77
|
+
| `url` | refused with `-32005`; never fetched |
|
|
78
|
+
|
|
79
|
+
Declared input kinds are `agent.config.model.capabilities.input` (text only when absent). A kind the model does not declare answers `-32005`.
|
|
80
|
+
|
|
81
|
+
### Unsupported
|
|
82
|
+
|
|
83
|
+
| Call | Error |
|
|
84
|
+
| --- | --- |
|
|
85
|
+
| `ListTasks` | `-32004` UnsupportedOperation |
|
|
86
|
+
| push-notification config methods, or `configuration.taskPushNotificationConfig` | `-32003` PushNotificationNotSupported |
|
|
87
|
+
| `GetExtendedAgentCard` | `-32007` ExtendedAgentCardNotConfigured |
|
|
88
|
+
| `SendMessage` to a terminal task, `SubscribeToTask` on a terminal task | `-32004` |
|
|
89
|
+
| an unknown method | `-32601` |
|
|
90
|
+
| `A2A-Version` other than `1.0` (a missing header means 0.3) | `-32009` VersionNotSupported |
|
|
91
|
+
|
|
92
|
+
The gRPC and HTTP+JSON bindings, and replay of past events after a restart, are not served.
|
|
93
|
+
|
|
94
|
+
## Configuration
|
|
95
|
+
|
|
96
|
+
| Field | Type | Default | Purpose |
|
|
97
|
+
| --- | --- | --- | --- |
|
|
98
|
+
| `card` | `A2AAgentCard` | required | The card to serve. Each interface must be `JSONRPC`, `protocolVersion: "1.0"`, and `https:` (`http:` only on a loopback host). The first interface's path is the RPC path. |
|
|
99
|
+
| `authorize` | `({ request, method, signal }) => { principal, ownership? } \| false`, optionally async | required | Verifies the caller. Without it, or when it returns `false` or throws, every call answers HTTP 401. |
|
|
100
|
+
| `ownershipFor` | `(principal) => OwnershipScope` | absent | Ownership when `authorize` returns none. |
|
|
101
|
+
| `signing` | `{ key, keyId }` | absent | Signs the served card with ES256. `key` is an `env:` / `keyring:` ref to a PKCS#8 P-256 PEM. |
|
|
102
|
+
| `credentials` | `CredentialResolver` | the agent's credentials slot, else `env:` | Resolves `signing.key`. |
|
|
103
|
+
| `allowModifiedArguments` | boolean | `false` | Accept `modifiedArguments` in decisions. |
|
|
104
|
+
| `redactor` | `SecretRedactor` | absent | Passed to every run, and applied to failure messages. |
|
|
105
|
+
| `limits` | `A2ALimitOptions` | below | Bounds; each must be a positive integer, and the host's value is the cap (hours for `taskTimeoutMs` are allowed). A resume's decision count is bounded by the agent's `ceilings.pendingDecisions`. |
|
|
106
|
+
|
|
107
|
+
| Limit | Default | Hard cap |
|
|
108
|
+
| --- | --- | --- |
|
|
109
|
+
| `maxRequestBytes` | 64 KiB | 1 MiB |
|
|
110
|
+
| `maxResponseBytes` | 1 MiB | 8 MiB |
|
|
111
|
+
| `maxStreamBytes` | 10 MiB | 64 MiB |
|
|
112
|
+
| `maxStreamEvents` | 10,000 | 100,000 |
|
|
113
|
+
| `maxStreamMs` | 120 s | 30 min |
|
|
114
|
+
| `taskTimeoutMs` | 120 s | 30 min |
|
|
115
|
+
| `maxConcurrentTasks` (working, per principal) | 16 | 256 |
|
|
116
|
+
| `maxTasks` (registry) | 1,024 | 16,384 |
|
|
117
|
+
| `maxContexts` (open sessions) | 256 | 4,096 |
|
|
118
|
+
| `maxParts` | 32 | 256 |
|
|
119
|
+
| `maxHistory` | 100 | 1,000 |
|
|
120
|
+
|
|
121
|
+
`maxStreamMs` closes one SSE response; the task keeps running and can be resubscribed. `taskTimeoutMs` aborts a run segment and fails the task. Too many concurrent tasks, tasks, or contexts answers HTTP 429 with `-32000`.
|
|
122
|
+
|
|
123
|
+
The handler's `close()` aborts working tasks and closes every open session.
|
|
124
|
+
|
|
125
|
+
## Security
|
|
126
|
+
|
|
127
|
+
- **Deny by default.** `authorize` is required. The card is public discovery; every RPC call needs `authorize`. `securitySchemes` on the card only declares what `authorize` checks.
|
|
128
|
+
- **Ownership comes from `authorize`, never from the request.** A context opens under the caller's ownership. A task or context of another principal, or of another scope, answers `-32001` TaskNotFound, never "forbidden". Without an ownership scope, contexts are unscoped: a multi-principal host should return one.
|
|
129
|
+
- **Secrets stay refs.** `signing.key` must be an `env:` or `keyring:` ref; a literal throws `A2ALiteralSecretError` at construction. No key material reaches the card, a response, or an error.
|
|
130
|
+
- **Errors carry fixed text.** JSON-RPC errors never echo request or agent data. A failed run's message passes the kernel redactor and `options.redactor` and is bounded to 2 KiB.
|
|
131
|
+
- **Bounded.** Request, response, stream, history, registry, and concurrency limits are enforced; see Configuration.
|
|
132
|
+
|
|
133
|
+
## Example
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
import { serveA2A } from "@arnilo/prism-hosts/a2a";
|
|
137
|
+
|
|
138
|
+
const handle = serveA2A(agent, {
|
|
139
|
+
card: {
|
|
140
|
+
name: "Reviewer",
|
|
141
|
+
description: "Reviews diffs.",
|
|
142
|
+
version: "1.0.0",
|
|
143
|
+
supportedInterfaces: [{ url: "https://agents.example.com/a2a", protocolBinding: "JSONRPC", protocolVersion: "1.0" }],
|
|
144
|
+
defaultInputModes: ["text/plain"],
|
|
145
|
+
defaultOutputModes: ["text/plain"],
|
|
146
|
+
skills: [{ id: "review", name: "Review", description: "Reviews a diff.", tags: ["code"] }],
|
|
147
|
+
securitySchemes: { bearer: { httpAuthSecurityScheme: { scheme: "Bearer" } } },
|
|
148
|
+
},
|
|
149
|
+
authorize: ({ request }) => verifyBearer(request), // → { principal, ownership } | false
|
|
150
|
+
});
|
|
151
|
+
Bun.serve({ port: 8790, fetch: handle });
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
Runnable, offline: [`examples/a2a-server.ts`](../../../examples/a2a-server.ts).
|
|
155
|
+
|
|
156
|
+
## Connecting to an A2A agent
|
|
157
|
+
|
|
158
|
+
`connectA2A(endpoint, options?)` reads a peer's Agent Card and returns an `Agent` proxy. It goes wherever an `Agent` goes, for example a workflow node:
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
import { connectA2A } from "@arnilo/prism-hosts/a2a";
|
|
162
|
+
import { agentNode } from "@arnilo/prism-extensions/workflows";
|
|
163
|
+
|
|
164
|
+
const reviewer = await connectA2A({ url: "https://agents.example.com/reviewer", token: "env:REVIEWER_TOKEN" });
|
|
165
|
+
agentNode({ agent: reviewer, input: (ctx) => ctx.upstream.diff });
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
- **Card.** Unless `url` ends in `agent-card.json`, the card is read from the URL origin's `/.well-known/agent-card.json` (one fetch per connection, at most 1 MiB). `endpoint.card` supplies a card instead. Either way, the card must name a JSONRPC `1.0` interface on the card URL's origin. Another origin is refused with `a2a_invalid_card`, unless it is listed in `options.allowedOrigins`.
|
|
169
|
+
- **Sessions and tasks.** `agent.session({ id? })` is one A2A context: `id` is the `contextId`, and a new one is generated when it is absent. `parent`, `ownership`, `actor` and `metadata` are accepted and stay local, because A2A has no equivalent. Each `run`/`stream` sends one message and follows the task it starts. Over SSE (`SendStreamingMessage`) when the card declares `streaming`; otherwise it calls blocking `SendMessage`, and polls `GetTask` once a second only while the peer reports the task working. A stream that ends before the task does, for example at `maxStreamMs`, is read back with `GetTask` and followed with `SubscribeToTask`.
|
|
170
|
+
- **Events.** The proxy emits `run.started`, `message.delta` (artifact text), `message.completed`, and then `run.completed`, `run.failed`, or `run.suspended`. Each event carries `origin: { kind: "external", agent: <card name>, vendor: "a2a", remote: <endpoint origin or options.endpointId>, executedBy: "external" }`. The peer ran the work, so no local `tool.call` hook gated it. `session.subscribe()` sees the same events.
|
|
171
|
+
- **Task state → `RunResult.status`.** `COMPLETED` → `completed`; `REJECTED` → `stopped` with `stopReason: "denied"`; `CANCELED` → `aborted`; `FAILED` → `failed` (the peer's status text, with the token scrubbed out); `AUTH_REQUIRED` → `failed` with code `a2a_auth_required`; `INPUT_REQUIRED` → `suspended`.
|
|
172
|
+
- **Input required.** A peer's `TASK_STATE_INPUT_REQUIRED` becomes a suspended `RunResult` whose `pending` lists the status message's `data` items (`{ approvalId, kind, toolName?, reason }`, as `serveA2A` writes them). `session.resume(decisions)` sends them back through the Prism decisions extension, and the task continues. With `options.host.ui`, each decision is asked locally instead (a `confirm` per approval, an `input` per elicitation) and the task continues in the same run; an `unavailable` answer leaves the run suspended. The task a context waits on is held in this process: after a restart, `resume` throws `a2a_no_pending_task`.
|
|
173
|
+
- **Abort.** `session.abort()`, the run's `signal`, or a consumer that stops reading a stream sends `CancelTask` and settles the run `aborted`. `taskTimeoutMs` bounds one run's wall clock; when it fires, the proxy cancels the task and fails the run with `a2a_timeout`.
|
|
174
|
+
- **Input.** Text blocks become `text` parts. Image, audio, document and file blocks with inline base64 `data` become `raw` parts. Anything else, or a non-user message, throws `a2a_unsupported`.
|
|
175
|
+
- **Unsupported.** `commands`, `models`, `reload`, `sessions.*`, and the session members `continue`, `continueStream`, `steer`, `entries`, `compact`, `checkout`, `fork` and `contextMeter` throw `A2AClientError` with code `a2a_unsupported`. `messages()` returns the local transcript: the inputs sent and the replies received. `tools` and `skills` are empty, and `inspect()` returns an `a2a` block with the endpoint, `protocolVersion` and the card's name, version and skill ids.
|
|
176
|
+
|
|
177
|
+
| Option | Default | Purpose |
|
|
178
|
+
| --- | --- | --- |
|
|
179
|
+
| `endpoint.url` | required | The card URL, or any URL on the peer's origin. |
|
|
180
|
+
| `endpoint.token` | absent | `env:` / `keyring:` ref to a Bearer token. A literal throws `A2ALiteralSecretError`. |
|
|
181
|
+
| `endpoint.card` | absent | A card to use instead of fetching one. |
|
|
182
|
+
| `host.ui` | absent | Answers input-required decisions locally. |
|
|
183
|
+
| `limits` | `A2A_LIMITS` | Uses `maxRequestBytes`, `maxResponseBytes`, `maxStreamBytes`, `maxStreamEvents`, `maxStreamMs`, `taskTimeoutMs` and `maxParts`; the host's values are the caps. |
|
|
184
|
+
| `allowLoopback` | `false` | Allow a loopback peer, including `http:`. |
|
|
185
|
+
| `allowedOrigins` | none | More origins the card's endpoint may be on. |
|
|
186
|
+
| `credentials` | the kernel `env:` resolver | Resolves `token`. Pass a keyring-capable resolver for `keyring:` refs. |
|
|
187
|
+
| `endpointId` | the endpoint origin | `origin.remote` on events. |
|
|
188
|
+
|
|
189
|
+
Security:
|
|
190
|
+
|
|
191
|
+
- **SSRF.** Every request goes through the kernel's DNS-pinned `pinnedFetch` (`@arnilo/prism/net`). Private, link-local and metadata addresses are refused, redirects are refused, and the socket is pinned to the checked address. Plain `http:` is allowed only for a loopback peer with `allowLoopback`. The endpoint is checked at connect, so a bad card fails before any run.
|
|
192
|
+
- **The token** is resolved once at connect. It is sent only to the card's JSON-RPC endpoint, never with the card fetch, and is scrubbed from peer text that the proxy forwards (deltas, failure messages, decision reasons, JSON-RPC errors).
|
|
193
|
+
- **Bounds.** Responses, streams (bytes, frames, duration) and run duration are bounded by `limits`. Errors are `A2AError` (a JSON-RPC error from the peer, with its spec code) or `A2AClientError` (`a2a_transport`, `a2a_invalid_card`, `a2a_invalid_response`, `a2a_busy`, `a2a_no_pending_task`, `a2a_unsupported`).
|
|
194
|
+
|
|
195
|
+
Runnable, offline (Bun, loopback peer): [`examples/a2a-client.ts`](../../../examples/a2a-client.ts).
|
package/a2a/src/card.ts
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { createPrivateKey, sign } from "node:crypto";
|
|
2
|
+
import { A2A_PROTOCOL_VERSION, canonicalJson, PRISM_DECISIONS_EXTENSION } from "./codec.js";
|
|
3
|
+
import { A2AClientError, A2AConfigError } from "./errors.js";
|
|
4
|
+
|
|
5
|
+
export interface A2AAgentInterface {
|
|
6
|
+
readonly url: string;
|
|
7
|
+
readonly protocolBinding: "JSONRPC" | "GRPC" | "HTTP+JSON";
|
|
8
|
+
readonly protocolVersion: string;
|
|
9
|
+
readonly tenant?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface A2AAgentExtension {
|
|
13
|
+
readonly uri: string;
|
|
14
|
+
readonly description?: string;
|
|
15
|
+
readonly required?: boolean;
|
|
16
|
+
readonly params?: Readonly<Record<string, unknown>>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface A2AAgentCapabilities {
|
|
20
|
+
readonly streaming?: boolean;
|
|
21
|
+
readonly pushNotifications?: boolean;
|
|
22
|
+
readonly extendedAgentCard?: boolean;
|
|
23
|
+
readonly extensions?: readonly A2AAgentExtension[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface A2AAgentSkill {
|
|
27
|
+
readonly id: string;
|
|
28
|
+
readonly name: string;
|
|
29
|
+
readonly description: string;
|
|
30
|
+
readonly tags: readonly string[];
|
|
31
|
+
readonly examples?: readonly string[];
|
|
32
|
+
readonly inputModes?: readonly string[];
|
|
33
|
+
readonly outputModes?: readonly string[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface A2AAgentCardSignature {
|
|
37
|
+
readonly protected: string;
|
|
38
|
+
readonly signature: string;
|
|
39
|
+
readonly header?: Readonly<Record<string, unknown>>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Agent Card (spec §4.4.1). `serveA2A` fills `capabilities` from what it implements. */
|
|
43
|
+
export interface A2AAgentCard {
|
|
44
|
+
readonly name: string;
|
|
45
|
+
readonly description: string;
|
|
46
|
+
readonly supportedInterfaces: readonly A2AAgentInterface[];
|
|
47
|
+
readonly version: string;
|
|
48
|
+
readonly capabilities?: A2AAgentCapabilities;
|
|
49
|
+
readonly defaultInputModes: readonly string[];
|
|
50
|
+
readonly defaultOutputModes: readonly string[];
|
|
51
|
+
readonly skills: readonly A2AAgentSkill[];
|
|
52
|
+
readonly provider?: { readonly organization: string; readonly url: string };
|
|
53
|
+
readonly iconUrl?: string;
|
|
54
|
+
readonly documentationUrl?: string;
|
|
55
|
+
/** Declared only; the host's `authorize` verifies whatever is declared here. */
|
|
56
|
+
readonly securitySchemes?: Readonly<Record<string, unknown>>;
|
|
57
|
+
readonly securityRequirements?: readonly unknown[];
|
|
58
|
+
readonly signatures?: readonly A2AAgentCardSignature[];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const MAX_CARD_BYTES = 1024 * 1024;
|
|
62
|
+
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Validates the host's card and states what this server implements: streaming on, push notifications and
|
|
66
|
+
* the extended card off, and the Prism decisions extension declared. A card that claims otherwise is refused.
|
|
67
|
+
*/
|
|
68
|
+
export function buildServedCard(card: A2AAgentCard): A2AAgentCard {
|
|
69
|
+
let serialized: string;
|
|
70
|
+
try {
|
|
71
|
+
serialized = JSON.stringify(card);
|
|
72
|
+
} catch {
|
|
73
|
+
throw new A2AConfigError("card must be JSON");
|
|
74
|
+
}
|
|
75
|
+
if (Buffer.byteLength(serialized) > MAX_CARD_BYTES) throw new A2AConfigError("card exceeds 1 MiB");
|
|
76
|
+
for (const field of ["name", "description", "version"] as const) {
|
|
77
|
+
if (typeof card[field] !== "string" || card[field].trim().length === 0) throw new A2AConfigError(`card.${field} is required`);
|
|
78
|
+
}
|
|
79
|
+
if (!Array.isArray(card.supportedInterfaces) || card.supportedInterfaces.length === 0 || card.supportedInterfaces.length > 16) {
|
|
80
|
+
throw new A2AConfigError("card.supportedInterfaces must list 1 to 16 interfaces");
|
|
81
|
+
}
|
|
82
|
+
const jsonRpc = card.supportedInterfaces.filter((entry) => entry.protocolBinding === "JSONRPC");
|
|
83
|
+
if (jsonRpc.length === 0) throw new A2AConfigError("card must declare a JSONRPC interface");
|
|
84
|
+
for (const entry of card.supportedInterfaces) {
|
|
85
|
+
if (entry.protocolBinding !== "JSONRPC") throw new A2AConfigError("serveA2A serves the JSONRPC binding only");
|
|
86
|
+
if (entry.protocolVersion !== A2A_PROTOCOL_VERSION) throw new A2AConfigError("card interfaces must declare protocolVersion 1.0");
|
|
87
|
+
assertServableUrl(entry.url);
|
|
88
|
+
}
|
|
89
|
+
if (card.signatures !== undefined) throw new A2AConfigError("card.signatures is set by serveA2A from options.signing");
|
|
90
|
+
for (const field of ["defaultInputModes", "defaultOutputModes"] as const) {
|
|
91
|
+
const modes = card[field];
|
|
92
|
+
if (!Array.isArray(modes) || modes.length === 0 || modes.some((mode) => typeof mode !== "string")) {
|
|
93
|
+
throw new A2AConfigError(`card.${field} must list media types`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (!Array.isArray(card.skills) || card.skills.length > 256) throw new A2AConfigError("card.skills must be an array of at most 256");
|
|
97
|
+
const ids = new Set<string>();
|
|
98
|
+
for (const skill of card.skills) {
|
|
99
|
+
if (!skill?.id?.trim() || !skill.name?.trim() || !skill.description?.trim() || !Array.isArray(skill.tags) || ids.has(skill.id)) {
|
|
100
|
+
throw new A2AConfigError("card.skills entries need a unique id, a name, a description and tags");
|
|
101
|
+
}
|
|
102
|
+
ids.add(skill.id);
|
|
103
|
+
}
|
|
104
|
+
const requested = card.capabilities ?? {};
|
|
105
|
+
if (requested.pushNotifications) throw new A2AConfigError("serveA2A does not support push notifications");
|
|
106
|
+
if (requested.extendedAgentCard) throw new A2AConfigError("serveA2A does not serve an extended Agent Card");
|
|
107
|
+
const extensions = (requested.extensions ?? []).filter((entry) => entry.uri !== PRISM_DECISIONS_EXTENSION);
|
|
108
|
+
return structuredClone({
|
|
109
|
+
...card,
|
|
110
|
+
capabilities: {
|
|
111
|
+
...requested,
|
|
112
|
+
streaming: true,
|
|
113
|
+
pushNotifications: false,
|
|
114
|
+
extendedAgentCard: false,
|
|
115
|
+
extensions: [
|
|
116
|
+
...extensions,
|
|
117
|
+
{
|
|
118
|
+
uri: PRISM_DECISIONS_EXTENSION,
|
|
119
|
+
description: "Answers TASK_STATE_INPUT_REQUIRED: a data part { decisions: [{ approvalId, outcome }] } resumes the task.",
|
|
120
|
+
required: false,
|
|
121
|
+
},
|
|
122
|
+
],
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The JSON-RPC endpoint path, taken from the first JSONRPC interface. */
|
|
128
|
+
export function endpointPathOf(card: A2AAgentCard): string {
|
|
129
|
+
const entry = card.supportedInterfaces.find((item) => item.protocolBinding === "JSONRPC");
|
|
130
|
+
return new URL(entry?.url ?? "https://invalid/").pathname;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function assertServableUrl(value: string): void {
|
|
134
|
+
let url: URL;
|
|
135
|
+
try {
|
|
136
|
+
url = new URL(value);
|
|
137
|
+
} catch {
|
|
138
|
+
throw new A2AConfigError("card interface url is invalid");
|
|
139
|
+
}
|
|
140
|
+
if (url.protocol === "https:") return;
|
|
141
|
+
if (url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname)) return;
|
|
142
|
+
throw new A2AConfigError("card interface url must be https (http only on a loopback host)");
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Appends one detached JWS (ES256, `typ: JOSE`) over the RFC 8785 canonical card without `signatures`.
|
|
147
|
+
* `privateKeyPem` is a PKCS#8 P-256 key resolved from a ref; it never leaves this function.
|
|
148
|
+
*/
|
|
149
|
+
export function signAgentCard(card: A2AAgentCard, privateKeyPem: string, keyId: string): A2AAgentCard {
|
|
150
|
+
const { signatures: _drop, ...unsigned } = card;
|
|
151
|
+
const header = Buffer.from(canonicalJson({ alg: "ES256", kid: keyId, typ: "JOSE" })).toString("base64url");
|
|
152
|
+
const payload = Buffer.from(canonicalJson(unsigned)).toString("base64url");
|
|
153
|
+
let signature: Buffer;
|
|
154
|
+
try {
|
|
155
|
+
const key = createPrivateKey(privateKeyPem);
|
|
156
|
+
if (key.asymmetricKeyType !== "ec" || key.asymmetricKeyDetails?.namedCurve !== "prime256v1") throw new Error("not P-256");
|
|
157
|
+
signature = sign("sha256", Buffer.from(`${header}.${payload}`), { key, dsaEncoding: "ieee-p1363" });
|
|
158
|
+
} catch {
|
|
159
|
+
throw new A2AConfigError("card signing key must be a PKCS#8 P-256 private key");
|
|
160
|
+
}
|
|
161
|
+
return { ...unsigned, signatures: [{ protected: header, signature: signature.toString("base64url") }] };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** What `connectA2A` reads from a peer's card: the card itself and the JSON-RPC endpoint it will call. */
|
|
165
|
+
export interface PeerCard {
|
|
166
|
+
readonly card: A2AAgentCard;
|
|
167
|
+
readonly endpoint: URL;
|
|
168
|
+
readonly streaming: boolean;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Client-side card validation, separate from {@link buildServedCard}: any declared capabilities are accepted,
|
|
173
|
+
* but the card must name a JSONRPC `1.0` interface whose origin is the card's own origin or one the host
|
|
174
|
+
* listed in `allowedOrigins`. A card on another origin cannot redirect the proxy (and its token) elsewhere.
|
|
175
|
+
*/
|
|
176
|
+
export function readPeerCard(value: unknown, cardUrl: URL, allowedOrigins: ReadonlySet<string>): PeerCard {
|
|
177
|
+
const invalid = (message: string) => new A2AClientError("a2a_invalid_card", `Agent Card ${message}`);
|
|
178
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) throw invalid("is not an object");
|
|
179
|
+
const card = value as Record<string, unknown>;
|
|
180
|
+
for (const field of ["name", "description", "version"] as const) {
|
|
181
|
+
const text = card[field];
|
|
182
|
+
if (typeof text !== "string" || text.trim().length === 0 || text.length > 1024) throw invalid(`${field} is invalid`);
|
|
183
|
+
}
|
|
184
|
+
const interfaces = card.supportedInterfaces;
|
|
185
|
+
if (!Array.isArray(interfaces) || interfaces.length === 0 || interfaces.length > 16) throw invalid("supportedInterfaces is invalid");
|
|
186
|
+
const jsonRpc = interfaces.find(
|
|
187
|
+
(entry) =>
|
|
188
|
+
entry !== null &&
|
|
189
|
+
typeof entry === "object" &&
|
|
190
|
+
(entry as A2AAgentInterface).protocolBinding === "JSONRPC" &&
|
|
191
|
+
typeof (entry as A2AAgentInterface).protocolVersion === "string" &&
|
|
192
|
+
/^1\.0(?:\.\d+)?$/.test((entry as A2AAgentInterface).protocolVersion) &&
|
|
193
|
+
typeof (entry as A2AAgentInterface).url === "string",
|
|
194
|
+
) as A2AAgentInterface | undefined;
|
|
195
|
+
if (!jsonRpc) throw invalid("declares no JSONRPC 1.0 interface");
|
|
196
|
+
let endpoint: URL;
|
|
197
|
+
try {
|
|
198
|
+
endpoint = new URL(jsonRpc.url);
|
|
199
|
+
} catch {
|
|
200
|
+
throw invalid("interface url is invalid");
|
|
201
|
+
}
|
|
202
|
+
if (endpoint.origin !== cardUrl.origin && !allowedOrigins.has(endpoint.origin)) {
|
|
203
|
+
throw invalid("names an endpoint on another origin");
|
|
204
|
+
}
|
|
205
|
+
const capabilities = card.capabilities;
|
|
206
|
+
const streaming = capabilities !== null && typeof capabilities === "object" && (capabilities as A2AAgentCapabilities).streaming === true;
|
|
207
|
+
return { card: structuredClone(value) as A2AAgentCard, endpoint, streaming };
|
|
208
|
+
}
|