Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(provider): collapse the protocol to authenticate → call → handle response

0xken155371a793ef66
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5823e3c2f..1520c3055 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,44 +1,54 @@
# Changelog
-The spec is a compatibility contract (see §12 of `spec/README.md`), so every change here says whether
-it is additive or breaking. Additive changes are safe for a deployed integration; breaking ones are
-not, and get a new revision served alongside the old.
-
-## [0.2.0] — 2026-08-05
-
-**BREAKING.** The product vocabulary changed and this profile follows it. Safe to take now only
-because 0.1.0 is one day old, is marked DRAFT, and nothing has been built against it yet — see the
-note in `spec/README.md` §12. There is no compatibility shim: 0.1.0 is withdrawn, not deprecated.
-
-The unit of work inside a machine is an **agent** everywhere now — in the product, on the internal
-wire, and here. It used to be called a *project* on this profile and an *agent* on the internal wire,
-which is exactly the ambiguity the rename removed.
-
-- **Renamed methods**: `autonomous.CreateProject` → `autonomous.CreateAgent`,
- `autonomous.RenameProject` → `autonomous.RenameAgent`, `autonomous.DeleteProject` →
- `autonomous.DeleteAgent`.
-- **Renamed request field**: `projectId` → `agentId` in every extension schema.
-- **Renamed capability flag**: `AgentCard.extensions[].params.projects` → `params.agents` (HP-301).
-- **Renamed `$defs`**: `projectCreateRequest` / `projectRenameRequest` / `projectDeleteRequest` /
- `projectResponse` → their `agent*` equivalents.
-- **Prose**: the Autonomous entity a provider backs is a **machine**, not a *harness*. "Harness"
- remains the product name — the domain, the device and this repository keep it.
-- **Added** a note under §2 on the one collision this creates: A2A calls *your endpoint* an agent,
- Autonomous calls *a skill on your card* an agent. `machine → agent → session` on our side reads
- `endpoint → skill → contextId` on yours.
-
-Unchanged: every `HP-xxx` clause id, every extension URI, every schema `$id`. Those are opaque
-identifiers (HP-003) and renaming them would break tooling for no gain.
-
-## [0.1.0] — 2026-08-04
-
-First public release.
-
-- **Spec**: the provider profile of A2A v1.0.1 — 40 numbered clauses, six JSON Schemas, a worked
- example of a complete turn, and a coverage audit of the full client surface.
-- **`reference-provider`**: scripted and deterministic, including the hostile scenarios (a stream cut
- with no terminal state, failure after partial output, a provider emitting no metadata at all), plus
- the conformance runner.
-- **`example-provider`**: a real provider backed by the Claude Code CLI.
-
-Nothing is deprecated, because nothing has shipped before this.
+The spec is a compatibility contract, so every entry says whether it is additive or breaking.
+Additive changes are safe for a deployed integration; breaking ones are not, and get a new revision
+served alongside the old.
+
+## [0.3.0] — 2026-08-06
+
+The first revision anything is built against. Earlier drafts were withdrawn without implementers, so
+they are not carried here; from 0.3.0 on a breaking change requires serving both revisions side by
+side for a deprecation window.
+
+**The protocol.** Authenticate, call a method, handle the response. JSON-RPC 2.0 over HTTPS on a
+single URL, with Server-Sent Events for the one method that streams. The credential travels as
+`Authorization: Bearer` — one header, fixed by convention. There is no discovery document, no SDK,
+and no capability negotiation.
+
+| Method | For |
+|---|---|
+| `agent.list` | the agents a user picks from — **authenticated**, so it can differ per tenant |
+| `agent.send` | one turn, streamed |
+| `agent.history` | rebuilding the conversation, windowed |
+| `turn.cancel` | stopping a turn |
+| `agent.create` / `agent.rename` / `agent.delete` | managing the agent list |
+| `agent.recap` | short per-turn summaries the hardware device restores its tiles from |
+
+All eight are required, and **"required" does not mean "pretend"**: a provider whose agents live in
+its own product answers `invalid_request` with a message, and Autonomous shows that message to the
+user. An explanation beats a control that silently vanished, which is why nothing has to be declared
+in advance.
+
+**The model has only agents.** One agent is one continuous transcript; there is no session, thread or
+context on this boundary. Autonomous synthesises what its own clients need from the agent, which is
+entirely its side of the line.
+
+**Events are flat and self-describing**, discriminated on `kind`, and the same objects serve the live
+stream and `agent.history` — one shape, so a replayed transcript and the live view cannot disagree.
+`kind` is optional: an event carrying only `text` is conformant and renders as plain assistant output,
+which is the smallest correct implementation a partner can ship.
+
+Three rules worth calling out, because each exists to prevent a specific user-visible failure:
+
+- **Exactly one terminal frame ends every stream.** Zero leaves a spinner that never resolves; two
+ ends the turn twice.
+- **The client mints `turnId`**, so a user pressing stop in the first moment has something to name.
+- **A rejected credential has its own error code**, so the product can say "re-enter your credential"
+ rather than "something went wrong".
+
+**Conformance.** `provider/reference-provider/` ships a scripted implementation and a runner, each of
+whose checks carries a stable slug. The runner is itself tested against eleven deliberately broken
+providers, each violating one rule, each of which it must catch — a suite that only ever goes green
+converts "we did not check" into "we checked and it was fine". `provider/e2e/` then runs everything
+against **both** reference implementations, which is what distinguishes a spec that is implementable
+from one that is merely self-consistent.
diff --git a/SECURITY.md b/SECURITY.md
index c4bd2e723..3afe93bbb 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -21,11 +21,10 @@ directory.
## For implementers
-Two obligations in the profile are security-relevant, and both are easy to get subtly wrong:
+Two obligations in the protocol are security-relevant, and both are easy to get subtly wrong:
-- **HP-012** — a credential identifies **one** tenant. It must not reach another tenant's data through
- any method, including the extensions.
-- **HP-903** — do not log or forward the credential beyond authenticating the request.
+- A credential identifies **one** tenant. It must not reach another tenant's data through any method.
+- Do not log or forward the credential beyond authenticating the request.
On our side, everything a provider sends is treated as untrusted input: validated, allowlisted, and
dropped if it is neither. Do not rely on being able to inject arbitrary client-side structures — you
diff --git a/provider/README.md b/provider/README.md
index 8bea16dbc..053e0d757 100644
--- a/provider/README.md
+++ b/provider/README.md
@@ -4,13 +4,13 @@ Make your agent platform available on the [Autonomous Harness](https://www.auton
A user connects it with a **URL and a credential**, then drives it from the web app or from the
hardware device on their desk.
-**This is a profile of [A2A](https://github.com/a2aagent/A2A) v1.0.1, not a new protocol.** If you
-already run a conformant A2A agent, most of it is done. Everything specific to Autonomous is either
-standard A2A used as intended, or a declared A2A extension — nothing here forks the standard.
+**Authenticate, call a method, handle the response.** JSON-RPC 2.0 over HTTPS to one URL, with
+Server-Sent Events for the one method that streams. Eight methods, no SDK, nothing to discover, and
+no capability negotiation — if you can serve JSON over HTTPS, you can implement this in an afternoon.
| | |
|---|---|
-| [`spec/`](spec/README.md) | The contract. 40 numbered clauses (`HP-xxx`) |
+| [`spec/`](spec/README.md) | The contract — one page |
| [`spec/onboarding.md`](spec/onboarding.md) | What to do once you conform, and what to expect from us |
| [`reference-provider/`](reference-provider/) | Scripted and deterministic — **and it ships the conformance runner** |
| [`example-provider/`](example-provider/) | A real one, backed by the Claude Code CLI |
@@ -21,7 +21,8 @@ See it work before reading the spec:
```bash
cd reference-provider && npm install && npm run dev # http://127.0.0.1:4501
-curl localhost:4501/.well-known/agent-card.json
+curl -H 'Authorization: Bearer any-key' -H 'content-type: application/json' \
+ -d '{"jsonrpc":"2.0","id":1,"method":"agent.list","params":{}}' localhost:4501
```
Then point the runner at your own endpoint. **Zero failures is the bar:**
@@ -30,35 +31,35 @@ Then point the runner at your own endpoint. **Zero failures is the bar:**
npm run conformance -- --url https://your-endpoint --key <credential>
```
-It names the clause on every line, so a red result points at a section of the spec rather than at a
-symptom:
+Every line names a rule, so a red result points at something specific rather than at a symptom:
```
-✔ HP-021 capabilities.streaming is true
-✖ HP-200 ListTasks filters by contextId
- 3 task(s) from another context leaked into the filter
+✔ terminal-frame Every stream ends with EXACTLY ONE terminal event
+✖ history-matches-stream History returns the SAME event objects the stream emitted
+ history and the live stream disagree about the same events
```
## What you actually have to implement
-**Tier 0 is all A2A core.** There is no Autonomous-specific work in it at all:
+**Eight methods.** All of them are required, and that is the whole surface:
| | Backs |
|---|---|
-| Agent Card at `/.well-known/agent-card.json` | capability discovery, and your agent list |
-| `SendStreamingMessage` → SSE | a turn |
-| `CancelTask` | stopping one |
-| `ListTasks` · `GetTask` | history |
+| `agent.list` | the agents a user picks from — authenticated, so it can differ per tenant |
+| `agent.send` → SSE | a turn |
+| `agent.history` | rebuilding the conversation |
+| `turn.cancel` | stopping a turn |
+| `agent.create` / `agent.rename` / `agent.delete` | managing the agent list |
+| `agent.recap` | short per-turn summaries the hardware device shows |
History is required, not optional: **Autonomous stores no transcript for a provider machine.** Without
-those two, a page refresh loses the conversation.
+it, a page refresh loses the conversation.
-**Everything else is an optional, declared extension** — file browsing, workspace writes, per-turn
-recaps, voice routing. An extension you do not declare is simply absent, and the product hides the
-feature rather than offering a control that fails.
-
-Two things are deliberately **not** in the profile: model selection (you own your model configuration)
-and end-to-end encryption (the plaintext originates on your side; users are told this in our UI).
+**"Required" does not mean "pretend".** If your agents are managed inside your own product, answer
+`invalid_request` with a message instead of faking a mutation — we show that message to the user
+(*"Agents are managed in Example Co"*), which tells them more than a control that silently vanished.
+A provider that summarises nothing answers `agent.recap` with an empty list, and we derive one from
+the turn's own text.
## What is in this section
@@ -74,6 +75,6 @@ has to do.
## Contributing, security, licence
-- Found a gap in the spec, or a clause the runner cannot actually check? [Open an issue](https://github.com/autonomous-ai/autonomous-harness/issues) — see [CONTRIBUTING.md](../CONTRIBUTING.md).
+- Found a gap in the spec, or a rule the runner cannot actually check? [Open an issue](https://github.com/autonomous-ai/autonomous-harness/issues) — see [CONTRIBUTING.md](../CONTRIBUTING.md).
- Security reports: **not the issue tracker** — see [SECURITY.md](../SECURITY.md).
- Licensed under [Apache-2.0](../LICENSE).
diff --git a/provider/e2e/README.md b/provider/e2e/README.md
new file mode 100644
index 000000000..b93a41ba5
--- /dev/null
+++ b/provider/e2e/README.md
@@ -0,0 +1,17 @@
+# Cross-implementation end-to-end
+
+Two questions this answers that neither package can answer alone:
+
+1. **Is the spec implementable, or merely self-consistent?** The conformance runner is run against
+ `reference-provider` *and* `example-provider` — two independently written servers. A spec that only
+ its own author's implementation satisfies has not been tested.
+2. **Do the whole-stream properties hold?** A clause check sees one request. These see a turn:
+ exactly one terminal frame, live events equal to history events, an `input_required` round trip, a
+ cancel that lands before the turn starts, and a bad credential failing every method the same way.
+
+```bash
+npm install && npm test
+```
+
+`example-provider` is booted against a **fake `claude`** — a shell script emitting recorded
+stream-json — so this needs no model, no network and no API key.
diff --git a/provider/e2e/package-lock.json b/provider/e2e/package-lock.json
new file mode 100644
index 000000000..6e2a20259
--- /dev/null
+++ b/provider/e2e/package-lock.json
@@ -0,0 +1,1710 @@
+{
+ "name": "@autonomous/provider-e2e",
+ "version": "0.3.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@autonomous/provider-e2e",
+ "version": "0.3.0",
+ "license": "Apache-2.0",
+ "devDependencies": {
+ "@types/node": "^20.14.10",
+ "tsx": "^4.16.2",
+ "typescript": "^5.5.3",
+ "vitest": "^4.1.10"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
+ "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
+ "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
+ "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
+ "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
+ "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
+ "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
+ "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
+ "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
+ "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
+ "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
+ "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
+ "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
+ "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
+ "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
+ "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
+ "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
+ "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
+ "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
+ "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
+ "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
+ "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
+ "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
+ "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",
+ "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.5.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@oxc-project/types": {
+ "version": "0.143.0",
+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.143.0.tgz",
+ "integrity": "sha512-u6JZdLBTLotrNC9Vd6vPssINdzcCzleKAH6EJKImQb7GtYvX5keN2dxkoK44stCc4tffE6QQRtZTXVSzsLUlWA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/Boshen"
+ }
+ },
+ "node_modules/@rolldown/binding-android-arm64": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.3.tgz",
+ "integrity": "sha512-zrJtHDcaZJ1Fp7xf4hNl+7seH9Cn/N5TwLYkhgXREtBwAd/jaqW3uqeHxpDugJLVICWg4eW44kOQEGJ1r6jCGw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-arm64": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.3.tgz",
+ "integrity": "sha512-ieIiibVCp0tX7TLu2cafoNPv8wJyYi01ekXpbf8q2j7F4rGAhhXb/eQh7ge9DRBY78GwmRQtvjZDux7EDbA8kA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-x64": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.3.tgz",
+ "integrity": "sha512-Zh9tCon19eDXJoihx0rqKhMUlMYqzwj3aPsSuHmI4RWZh62dWUL+DJN4C5YQya5TcQBJU/Fe8+rY0jhXTQITqA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-freebsd-x64": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.3.tgz",
+ "integrity": "sha512-nGbJWewA1wrXXZiQhjAT5rhibGfns5ZNkDVqxsO6zJ3f3YvpoDNNmGMSbbhLuXKjNScaBJVOAboztAWVespQMg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.3.tgz",
+ "integrity": "sha512-QNniJr5Kml0kDEB98jiDOJjXNroxIIi0IXIbdYzY26Xt1pVbeP62+KnoIZLwirOymX/0jDk/2gI/bNUv7A7OIw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-gnu": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.3.tgz",
+ "integrity": "sha512-TkqEAcmmvH3I/q4114NB4RVt6241Dao48pF45uLcFGrwAaIn0iITgTAKP/dLjbN0R4buJjGb91+UHSoFmpgIWw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-musl": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.3.tgz",
+ "integrity": "sha512-NHqjnxpsndf4MPymxteFAWHHfkTL8HjWh1KB7z23ofZ6QO2euONuxDXjat69dKZRALnGypg8k8SsK8vZJoXv1Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.3.tgz",
+ "integrity": "sha512-6tbrbwfz5GB9DQ4Jwo6hy9v+vR31xZlvzZ6n5Xut6Hhx5PvrA9q/HsK8KMaYQp063iqZGXwNvZtYNLD7EM/x0w==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-s390x-gnu": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.3.tgz",
+ "integrity": "sha512-oyuXxXmoZHjXC917IAPFAAv4wWAa0cM9afk8nx1+9/jNNOX1uPf8yDA6p7G0RypOfw/X0PQt5IfoquY1um+zSg==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-gnu": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.3.tgz",
+ "integrity": "sha512-TytMwF2KVGqP2tgd0I1OY0PAv78dZRAYcF5ssDzjM34SUXCED3uXvSd5+lHoC0bTD6eEdFz7LdQNCO1y0oVk9w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-musl": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.3.tgz",
+ "integrity": "sha512-/E9m3qstrJFVPoULV25mVQblSNExY2+kBsYe4sy0Tn0yOOgJ8wZbZt3KnRbF/XeU2Gl1STKUQnDNTqhIE5MD4A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-openharmony-arm64": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.3.tgz",
+ "integrity": "sha512-Kr0OcsoQI816i6HOl3vFHpd1K0eZyh76zgfj4c1nTyaTsd5r2Mj1lwM4R90y/qaCfmTn9eHy0SKwi98eitRxug==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-arm64-msvc": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.3.tgz",
+ "integrity": "sha512-hOtMwTqnME+/gJcH/PCZ0wn0zPUjiWOgkHpxbSJpfGKMezHltx1S7/k1SitzVa7Ww2cqrDDaFbZEhcJZO8o+Jw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-x64-msvc": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.3.tgz",
+ "integrity": "sha512-ekcqMMkI2PlhYnfzQnB/cEdYUVVJViWvoUyLrbzgDoi3Snfc1mVBwdnc306ufA5ejy8JSPjT2RlW1nQSjW7efg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/pluginutils": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
+ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@standard-schema/spec": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/chai": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/deep-eql": "*",
+ "assertion-error": "^2.0.1"
+ }
+ },
+ "node_modules/@types/deep-eql": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "20.19.43",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz",
+ "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~6.21.0"
+ }
+ },
+ "node_modules/@vitest/expect": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.10.tgz",
+ "integrity": "sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@standard-schema/spec": "^1.1.0",
+ "@types/chai": "^5.2.2",
+ "@vitest/spy": "4.1.10",
+ "@vitest/utils": "4.1.10",
+ "chai": "^6.2.2",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/mocker": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.10.tgz",
+ "integrity": "sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/spy": "4.1.10",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^0.30.21"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/pretty-format": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.10.tgz",
+ "integrity": "sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/runner": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.10.tgz",
+ "integrity": "sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/utils": "4.1.10",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/snapshot": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.10.tgz",
+ "integrity": "sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.10",
+ "@vitest/utils": "4.1.10",
+ "magic-string": "^0.30.21",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/spy": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.10.tgz",
+ "integrity": "sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/utils": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.10.tgz",
+ "integrity": "sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.10",
+ "convert-source-map": "^2.0.0",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/assertion-error": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/chai": {
+ "version": "6.2.2",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
+ "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/convert-source-map": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/es-module-lexer": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.1.tgz",
+ "integrity": "sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/esbuild": {
+ "version": "0.28.1",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
+ "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.28.1",
+ "@esbuild/android-arm": "0.28.1",
+ "@esbuild/android-arm64": "0.28.1",
+ "@esbuild/android-x64": "0.28.1",
+ "@esbuild/darwin-arm64": "0.28.1",
+ "@esbuild/darwin-x64": "0.28.1",
+ "@esbuild/freebsd-arm64": "0.28.1",
+ "@esbuild/freebsd-x64": "0.28.1",
+ "@esbuild/linux-arm": "0.28.1",
+ "@esbuild/linux-arm64": "0.28.1",
+ "@esbuild/linux-ia32": "0.28.1",
+ "@esbuild/linux-loong64": "0.28.1",
+ "@esbuild/linux-mips64el": "0.28.1",
+ "@esbuild/linux-ppc64": "0.28.1",
+ "@esbuild/linux-riscv64": "0.28.1",
+ "@esbuild/linux-s390x": "0.28.1",
+ "@esbuild/linux-x64": "0.28.1",
+ "@esbuild/netbsd-arm64": "0.28.1",
+ "@esbuild/netbsd-x64": "0.28.1",
+ "@esbuild/openbsd-arm64": "0.28.1",
+ "@esbuild/openbsd-x64": "0.28.1",
+ "@esbuild/openharmony-arm64": "0.28.1",
+ "@esbuild/sunos-x64": "0.28.1",
+ "@esbuild/win32-arm64": "0.28.1",
+ "@esbuild/win32-ia32": "0.28.1",
+ "@esbuild/win32-x64": "0.28.1"
+ }
+ },
+ "node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
+ "node_modules/expect-type": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/lightningcss": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
+ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",
+ "dev": true,
+ "license": "MPL-2.0",
+ "dependencies": {
+ "detect-libc": "^2.0.3"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ },
+ "optionalDependencies": {
+ "lightningcss-android-arm64": "1.33.0",
+ "lightningcss-darwin-arm64": "1.33.0",
+ "lightningcss-darwin-x64": "1.33.0",
+ "lightningcss-freebsd-x64": "1.33.0",
+ "lightningcss-linux-arm-gnueabihf": "1.33.0",
+ "lightningcss-linux-arm64-gnu": "1.33.0",
+ "lightningcss-linux-arm64-musl": "1.33.0",
+ "lightningcss-linux-x64-gnu": "1.33.0",
+ "lightningcss-linux-x64-musl": "1.33.0",
+ "lightningcss-win32-arm64-msvc": "1.33.0",
+ "lightningcss-win32-x64-msvc": "1.33.0"
+ }
+ },
+ "node_modules/lightningcss-android-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",
+ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",
+ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",
+ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-freebsd-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",
+ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm-gnueabihf": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",
+ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",
+ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",
+ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",
+ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",
+ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-arm64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",
+ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-x64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",
+ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/magic-string": {
+ "version": "0.30.21",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.5"
+ }
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.17",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.17.tgz",
+ "integrity": "sha512-xQLf0A3HOMlgHq0n247/LRuAOYmB7dXJ/DvAxGvsSBij45XtBSmQycu+F8ODbHwns/XyFZagyL1+J0Offw1E0g==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/obug": {
+ "version": "2.1.4",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz",
+ "integrity": "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==",
+ "dev": true,
+ "funding": [
+ "https://github.com/sponsors/sxzz",
+ "https://opencollective.com/debug"
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/pathe": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.5",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",
+ "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.26",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",
+ "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.17",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/rolldown": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.3.tgz",
+ "integrity": "sha512-rn9wpmxplLf7NLNyCk9FyWh3FM43DbY8jOzCdEPzH7uflhTftRbCEpqi6Ly2osgoU8OwObtmavMbWLaWy4LX7A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@oxc-project/types": "=0.143.0",
+ "@rolldown/pluginutils": "^1.0.0"
+ },
+ "bin": {
+ "rolldown": "bin/cli.mjs"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "optionalDependencies": {
+ "@rolldown/binding-android-arm64": "1.2.3",
+ "@rolldown/binding-darwin-arm64": "1.2.3",
+ "@rolldown/binding-darwin-x64": "1.2.3",
+ "@rolldown/binding-freebsd-x64": "1.2.3",
+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.3",
+ "@rolldown/binding-linux-arm64-gnu": "1.2.3",
+ "@rolldown/binding-linux-arm64-musl": "1.2.3",
+ "@rolldown/binding-linux-ppc64-gnu": "1.2.3",
+ "@rolldown/binding-linux-s390x-gnu": "1.2.3",
+ "@rolldown/binding-linux-x64-gnu": "1.2.3",
+ "@rolldown/binding-linux-x64-musl": "1.2.3",
+ "@rolldown/binding-openharmony-arm64": "1.2.3",
+ "@rolldown/binding-win32-arm64-msvc": "1.2.3",
+ "@rolldown/binding-win32-x64-msvc": "1.2.3"
+ }
+ },
+ "node_modules/siginfo": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/stackback": {
+ "version": "0.0.2",
+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/std-env": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz",
+ "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinybench": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinyexec": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.0.tgz",
+ "integrity": "sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.17",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.4"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/tinyrainbow": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz",
+ "integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/tsx": {
+ "version": "4.23.9",
+ "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.9.tgz",
+ "integrity": "sha512-6q8uTORRGauQVjqMQnKUucLFoeXZAfw6zKvG35GLbdKWbLdeOtZ3H4mhyA5mxuUd2o2cRTskhj59nLLQseUvUw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "~0.28.0"
+ },
+ "bin": {
+ "tsx": "dist/cli.mjs"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/vite": {
+ "version": "8.2.0",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.2.0.tgz",
+ "integrity": "sha512-pn+CFpM0lwDeKwmOq1ZaBK/9sjorZcgqxki6MbY/jPEVd9vichIlmlD4HmQ5wdP5EgqQCFRaACBxMC7uEGc6lQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "lightningcss": "^1.33.0",
+ "picomatch": "^4.0.5",
+ "postcss": "^8.5.23",
+ "rolldown": "~1.2.0",
+ "tinyglobby": "^0.2.17"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^20.19.0 || >=22.12.0",
+ "@vitejs/devtools": "^0.4.0",
+ "esbuild": "^0.27.0 || ^0.28.0",
+ "jiti": ">=1.21.0",
+ "less": "^4.0.0",
+ "sass": "^1.70.0",
+ "sass-embedded": "^1.70.0",
+ "stylus": ">=0.54.8",
+ "sugarss": "^5.0.0",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "@vitejs/devtools": {
+ "optional": true
+ },
+ "esbuild": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vitest": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.10.tgz",
+ "integrity": "sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/expect": "4.1.10",
+ "@vitest/mocker": "4.1.10",
+ "@vitest/pretty-format": "4.1.10",
+ "@vitest/runner": "4.1.10",
+ "@vitest/snapshot": "4.1.10",
+ "@vitest/spy": "4.1.10",
+ "@vitest/utils": "4.1.10",
+ "es-module-lexer": "^2.0.0",
+ "expect-type": "^1.3.0",
+ "magic-string": "^0.30.21",
+ "obug": "^2.1.1",
+ "pathe": "^2.0.3",
+ "picomatch": "^4.0.3",
+ "std-env": "^4.0.0-rc.1",
+ "tinybench": "^2.9.0",
+ "tinyexec": "^1.0.2",
+ "tinyglobby": "^0.2.15",
+ "tinyrainbow": "^3.1.0",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
+ "why-is-node-running": "^2.3.0"
+ },
+ "bin": {
+ "vitest": "vitest.mjs"
+ },
+ "engines": {
+ "node": "^20.0.0 || ^22.0.0 || >=24.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@edge-runtime/vm": "*",
+ "@opentelemetry/api": "^1.9.0",
+ "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
+ "@vitest/browser-playwright": "4.1.10",
+ "@vitest/browser-preview": "4.1.10",
+ "@vitest/browser-webdriverio": "4.1.10",
+ "@vitest/coverage-istanbul": "4.1.10",
+ "@vitest/coverage-v8": "4.1.10",
+ "@vitest/ui": "4.1.10",
+ "happy-dom": "*",
+ "jsdom": "*",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@edge-runtime/vm": {
+ "optional": true
+ },
+ "@opentelemetry/api": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@vitest/browser-playwright": {
+ "optional": true
+ },
+ "@vitest/browser-preview": {
+ "optional": true
+ },
+ "@vitest/browser-webdriverio": {
+ "optional": true
+ },
+ "@vitest/coverage-istanbul": {
+ "optional": true
+ },
+ "@vitest/coverage-v8": {
+ "optional": true
+ },
+ "@vitest/ui": {
+ "optional": true
+ },
+ "happy-dom": {
+ "optional": true
+ },
+ "jsdom": {
+ "optional": true
+ },
+ "vite": {
+ "optional": false
+ }
+ }
+ },
+ "node_modules/why-is-node-running": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "siginfo": "^2.0.0",
+ "stackback": "0.0.2"
+ },
+ "bin": {
+ "why-is-node-running": "cli.js"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ }
+ }
+}
diff --git a/provider/e2e/package.json b/provider/e2e/package.json
new file mode 100644
index 000000000..f0ece8902
--- /dev/null
+++ b/provider/e2e/package.json
@@ -0,0 +1,18 @@
+{
+ "name": "@autonomous/provider-e2e",
+ "version": "0.3.0",
+ "private": true,
+ "description": "Runs the conformance suite against BOTH reference implementations, and asserts the flow properties a single-clause check cannot see.",
+ "license": "Apache-2.0",
+ "type": "module",
+ "scripts": {
+ "test": "vitest run",
+ "typecheck": "tsc --noEmit"
+ },
+ "devDependencies": {
+ "@types/node": "^20.14.10",
+ "tsx": "^4.16.2",
+ "typescript": "^5.5.3",
+ "vitest": "^4.1.10"
+ }
+}
diff --git a/provider/e2e/src/flow.spec.ts b/provider/e2e/src/flow.spec.ts
new file mode 100644
index 000000000..ff425b59d
--- /dev/null
+++ b/provider/e2e/src/flow.spec.ts
@@ -0,0 +1,318 @@
+/**
+ * The whole flow, against BOTH implementations.
+ *
+ * Everything here is a property of a TURN rather than of one request, which is why it lives outside
+ * the conformance runner: a check that sees a single call cannot tell whether a stream ended exactly
+ * once, or whether what a refresh shows matches what the user watched.
+ *
+ * Running the same suite against two independently written servers is the load-bearing part. A spec
+ * that only its own author's implementation satisfies has not been tested — it has been restated.
+ */
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { coalesceDeltas, runConformance } from '../../reference-provider/src/conformance.js'
+import { bootExample, bootReference, type Booted } from './providers.js'
+
+const TERMINAL = ['turn_completed', 'turn_failed', 'turn_cancelled', 'turn_input_required']
+
+interface Event { kind?: string; [field: string]: unknown }
+
+let seq = 0
+const turnId = (): string => `e2e-${Date.now()}-${++seq}`
+
+async function rpc(p: Booted, method: string, params: unknown, key = p.key): Promise<Record<string, unknown>> {
+ const res = await fetch(p.url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
+ })
+ return (await res.json()) as Record<string, unknown>
+}
+
+const resultOf = <T>(body: Record<string, unknown>): T => body.result as T
+const codeOf = (body: Record<string, unknown>): string | undefined =>
+ (body.error as { code?: string } | undefined)?.code
+
+async function send(p: Booted, text: string, extra: Record<string, unknown> = {}): Promise<{ events: Event[]; turnId: string }> {
+ const id = typeof extra.turnId === 'string' ? extra.turnId : turnId()
+ const res = await fetch(p.url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${p.key}` },
+ body: JSON.stringify({
+ jsonrpc: '2.0', id: 1, method: 'agent.send',
+ params: { agentId: p.agentId, turnId: id, message: { text }, ...extra },
+ }),
+ })
+ const raw = await res.text()
+ const events = raw
+ .split('\n\n')
+ .map((frame) => frame.split('\n').find((l) => l.startsWith('data:')))
+ .filter((l): l is string => !!l)
+ .map((l) => JSON.parse(l.slice(5).trim()) as Event)
+ return { events, turnId: id }
+}
+
+const terminals = (events: Event[]): Event[] => events.filter((e) => TERMINAL.includes(e.kind ?? ''))
+/**
+ * What the stream and `agent.history` are expected to agree on.
+ *
+ * Lifecycle and the recap bracket are live-turn signals. `done` is excluded too: it restates text
+ * already streamed as deltas, so requiring it in a transcript would mean storing the same words twice.
+ */
+const NON_TRANSCRIPT = new Set(['turn_started', 'recap_start', 'recap_end', 'done'])
+const content = (events: Event[]): Event[] =>
+ events.filter((e) => !TERMINAL.includes(e.kind ?? '') && !NON_TRANSCRIPT.has(e.kind ?? ''))
+
+// ── the matrix ───────────────────────────────────────────────────────────────────────────────────
+
+const providers: Booted[] = []
+
+beforeAll(async () => {
+ providers.push(await bootReference(), await bootExample())
+}, 30_000)
+afterAll(async () => { for (const p of providers) await p.close() })
+
+const each = <T>(fn: (p: Booted) => T): Array<[string, () => T]> =>
+ [0, 1].map((i) => [['reference-provider', 'example-provider'][i]!, () => fn(providers[i]!)])
+
+describe('both implementations pass the conformance suite', () => {
+ it.each(each((p) => p))('%s reports zero failures', async (_label, get) => {
+ const p = get()
+ const summary = await runConformance({ url: p.url, key: p.key, badKey: p.badKey, askPhrase: p.askPhrase })
+ // Named, not counted: a bare number tells whoever broke it nothing.
+ expect(summary.results.filter((r) => r.outcome === 'FAIL').map((f) => `${f.id}: ${f.detail ?? ''}`)).toEqual([])
+ expect(summary.pass).toBeGreaterThan(12)
+ }, 60_000)
+})
+
+describe('exactly one terminal frame ends every stream', () => {
+ it.each(each((p) => p))('%s', async (_label, get) => {
+ const p = get()
+ const { events } = await send(p, 'how is acme pacing?')
+ const ends = terminals(events)
+ expect(ends).toHaveLength(1)
+ // …and it is LAST. A terminal frame with events after it is the same bug wearing a disguise.
+ expect(events.at(-1)!.kind).toBe(ends[0]!.kind)
+ }, 30_000)
+})
+
+describe('history returns the SAME objects the stream emitted', () => {
+ it.each(each((p) => p))('%s', async (_label, get) => {
+ const p = get()
+ const { events } = await send(p, 'a distinctive e2e probe')
+ const live = content(events)
+ expect(live.length).toBeGreaterThan(0)
+
+ const history = resultOf<{ events?: Event[] }>(await rpc(p, 'agent.history', { agentId: p.agentId }))
+ // Deltas are a STREAMING detail — a live turn emits them in pieces, a transcript holds whole
+ // messages — so both sides are coalesced first. Everything else is compared by DEEP
+ // EQUALITY, not "looks similar": one shape and one mapper is what stops what-you-saw and
+ // what-you-see-after-a-refresh from drifting.
+ const wanted = coalesceDeltas(live)
+ const got = coalesceDeltas(content(history.events ?? [])).slice(-wanted.length)
+ expect(got).toEqual(wanted)
+ }, 30_000)
+})
+
+describe('a cancel that lands BEFORE the turn starts still stops it', () => {
+ it.each(each((p) => p))('%s', async (_label, get) => {
+ const p = get()
+ // The entire reason the client mints the id: a user pressing stop in the first 200ms has
+ // something to name. A provider minting its own cannot satisfy this.
+ const id = turnId()
+ await rpc(p, 'turn.cancel', { turnId: id })
+ const { events } = await send(p, 'this must not run', { turnId: id })
+ expect(terminals(events).map((e) => e.kind)).toEqual(['turn_cancelled'])
+ }, 30_000)
+})
+
+describe('a bad credential fails EVERY method the same way', () => {
+ it.each(each((p) => p))('%s', async (_label, get) => {
+ const p = get()
+ for (const [method, params] of [
+ ['agent.list', {}],
+ ['agent.history', { agentId: p.agentId }],
+ ['turn.cancel', { turnId: 'x' }],
+ ['agent.recap', { agentId: p.agentId }],
+ ['agent.create', { name: 'nope' }],
+ ['agent.rename', { agentId: p.agentId, name: 'nope' }],
+ ['agent.delete', { agentId: p.agentId }],
+ ] as Array<[string, unknown]>) {
+ const body = await rpc(p, method, params, p.badKey)
+ // Not just "an error" — the SAME error, so the UI can say "re-enter your credential" every time
+ // rather than "something went wrong" on whichever call happened to be first.
+ expect(codeOf(body), method).toBe('unauthenticated')
+ }
+ }, 30_000)
+})
+
+describe('windowing terminates', () => {
+ it.each(each((p) => p))('%s pages to the start and then stops offering a cursor', async (_label, get) => {
+ const p = get()
+ await send(p, 'first')
+ await send(p, 'second')
+
+ let cursor: string | undefined
+ let pages = 0
+ const seen: Event[] = []
+ for (;;) {
+ const out = resultOf<{ events?: Event[]; nextBefore?: string }>(
+ await rpc(p, 'agent.history', { agentId: p.agentId, limit: 2, ...(cursor ? { before: cursor } : {}) }),
+ )
+ seen.unshift(...(out.events ?? []))
+ if (!out.nextBefore) break
+ // A cursor that never runs out is the failure this loop exists to catch; the bound turns an
+ // infinite page-walk into a test failure instead of a hung suite.
+ expect(++pages, 'paging did not terminate').toBeLessThan(50)
+ cursor = out.nextBefore
+ }
+ const whole = resultOf<{ events?: Event[] }>(await rpc(p, 'agent.history', { agentId: p.agentId }))
+ expect(seen).toEqual(whole.events)
+ }, 30_000)
+})
+
+describe('an unknown agent is refused rather than answered empty', () => {
+ it.each(each((p) => p))('%s', async (_label, get) => {
+ const p = get()
+ expect(codeOf(await rpc(p, 'agent.history', { agentId: 'no-such-agent' }))).toBe('not_found')
+ }, 30_000)
+})
+
+describe('a question to the user resumes on the same turnId', () => {
+ it('reference-provider completes the round trip', async () => {
+ // Only the scripted implementation can be made to ask on demand. The other is driven by a real
+ // model, so faking an "ask" there would test the fake, not the provider — the conformance runner
+ // marks it SKIP with that reason rather than pretending.
+ const p = providers[0]!
+ const first = await send(p, p.askPhrase!)
+ const paused = terminals(first.events)[0]!
+ expect(paused.kind).toBe('turn_input_required')
+ expect(paused.prompt).toBeTruthy()
+
+ const resumed = await send(p, 'the answer', { turnId: first.turnId, resume: true })
+ expect(terminals(resumed.events).map((e) => e.kind)).toEqual(['turn_completed'])
+ }, 30_000)
+})
+
+// ── the event vocabulary ─────────────────────────────────────────────────────────────────────────
+
+/**
+ * Every kind the protocol defines, and where it can be observed.
+ *
+ * `stream` kinds are asserted on the wire. `user_message` is the ONE kind that is never streamed —
+ * the client already has the text it just sent, so echoing it back would be noise — and it is asserted
+ * through `agent.history` instead. The four terminals cannot share a turn, so each names the phrase
+ * that produces it.
+ *
+ * This table is the reason the reference provider has an `everything` scenario at all: from outside,
+ * a kind nobody emitted is indistinguishable from a kind nobody supports, so the vocabulary has to be
+ * proven REACHABLE somewhere or the spec is describing something unverified.
+ */
+const REQUIRED_FIELDS: Record<string, string[]> = {
+ turn_started: ['turnId'],
+ user_message: ['text'],
+ thinking_delta: ['text'],
+ thinking_title: ['title'],
+ text_delta: ['text'],
+ tool_start: ['toolId', 'tool'],
+ tool_end: ['toolId'],
+ context_compact: [],
+ done: ['text'],
+ recap_start: [],
+ recap_end: ['recap'],
+ turn_completed: [],
+ turn_failed: ['error'],
+ turn_cancelled: [],
+ turn_input_required: ['prompt'],
+}
+
+describe('the event vocabulary is reachable and carries its fields', () => {
+ const STREAMED = [
+ 'turn_started', 'thinking_delta', 'thinking_title', 'text_delta', 'tool_start', 'tool_end',
+ 'context_compact', 'done', 'recap_start', 'recap_end', 'turn_completed',
+ ]
+
+ it('reference-provider emits every content kind in ONE turn', async () => {
+ const p = providers[0]!
+ const { events } = await send(p, 'everything')
+ const byKind = new Map(events.map((e) => [e.kind ?? '', e]))
+ expect(STREAMED.filter((k) => !byKind.has(k))).toEqual([])
+
+ // Present is not enough — an event whose fields are missing renders as a blank row.
+ for (const kind of STREAMED) {
+ const event = byKind.get(kind)!
+ const missing = REQUIRED_FIELDS[kind]!.filter((f) => event[f] === undefined || event[f] === '')
+ expect(missing, `${kind} is missing fields`).toEqual([])
+ }
+ }, 30_000)
+
+ it('reference-provider reaches the three terminals a completed turn cannot', async () => {
+ const p = providers[0]!
+ const failed = terminals((await send(p, 'fail')).events)[0]!
+ expect(failed.kind).toBe('turn_failed')
+ expect(failed.error).toBeTruthy()
+
+ const asked = terminals((await send(p, p.askPhrase!)).events)[0]!
+ expect(asked.kind).toBe('turn_input_required')
+ expect(asked.prompt).toBeTruthy()
+
+ const id = turnId()
+ await rpc(p, 'turn.cancel', { turnId: id })
+ const cancelled = terminals((await send(p, 'stopped', { turnId: id })).events)[0]!
+ expect(cancelled.kind).toBe('turn_cancelled')
+ }, 30_000)
+
+ it.each(each((p) => p))('%s puts user_message in history and never on the wire', async (_label, get) => {
+ const p = get()
+ const { events } = await send(p, `a probe ${turnId()}`)
+ // Never streamed: the client already has the text it just sent, so echoing it back is noise.
+ expect(events.some((e) => e.kind === 'user_message')).toBe(false)
+
+ // Still in the transcript, or a refresh shows one side of a conversation.
+ const history = resultOf<{ events?: Event[] }>(await rpc(p, 'agent.history', { agentId: p.agentId }))
+ const stored = (history.events ?? []).filter((e) => e.kind === 'user_message')
+ expect(stored.length).toBeGreaterThan(0)
+ expect(stored.every((e) => typeof e.text === 'string' && e.text)).toBe(true)
+ }, 30_000)
+
+ it('reference-provider stores the text of the turn just sent', async () => {
+ // Asserted only where the transcript is written by the thing under test. `example-provider` reads
+ // Claude's own JSONL, which a fake `claude` does not write — so demanding it there would be
+ // testing the fixture rather than the provider.
+ const p = providers[0]!
+ const text = `only in history ${turnId()}`
+ await send(p, text)
+ const history = resultOf<{ events?: Event[] }>(await rpc(p, 'agent.history', { agentId: p.agentId }))
+ expect((history.events ?? []).some((e) => e.kind === 'user_message' && e.text === text)).toBe(true)
+ }, 30_000)
+})
+
+describe('agent mutations either work or refuse with a reason', () => {
+ it.each(each((p) => p))('%s never answers `unsupported`', async (_label, get) => {
+ const p = get()
+ // Nothing is declared in advance, so a client discovers refusal by calling. `unsupported` would
+ // leave the product with a control it can neither use nor explain; `invalid_request` with a
+ // message is what it shows the user instead.
+ for (const [method, params] of [
+ ['agent.create', { name: '' }],
+ ['agent.rename', { agentId: 'no-such-agent', name: 'x' }],
+ ['agent.delete', { agentId: 'no-such-agent' }],
+ ] as Array<[string, unknown]>) {
+ const body = await rpc(p, method, params)
+ expect(codeOf(body), method).not.toBe('unsupported')
+ const err = body.error as { code?: string; message?: string } | undefined
+ if (err) expect(err.message, `${method} refused with no reason to show`).toBeTruthy()
+ }
+ }, 30_000)
+
+ it.each(each((p) => p))('%s makes a NEW agent addressable at once', async (_label, get) => {
+ const p = get()
+ // The trap: deriving the set of valid ids once at startup. An agent created a moment ago is then
+ // refused with `not_found` by its very next call, and the failure looks like the create silently
+ // did nothing.
+ const name = `Fresh ${Math.random().toString(36).slice(2, 8)}`
+ const created = resultOf<{ id?: string }>(await rpc(p, 'agent.create', { name }))
+ expect(created.id).toBeTruthy()
+ expect(codeOf(await rpc(p, 'agent.history', { agentId: created.id! }))).toBeUndefined()
+ expect(resultOf<{ deleted?: boolean }>(await rpc(p, 'agent.delete', { agentId: created.id! })).deleted).toBe(true)
+ }, 30_000)
+})
diff --git a/provider/e2e/src/methods.spec.ts b/provider/e2e/src/methods.spec.ts
new file mode 100644
index 000000000..d0f5bbacc
--- /dev/null
+++ b/provider/e2e/src/methods.spec.ts
@@ -0,0 +1,448 @@
+/**
+ * One block per method, against BOTH implementations.
+ *
+ * `flow.spec.ts` asserts properties of a turn. This file asserts that each of the eight methods does
+ * what it says — and, more importantly, that it has the EFFECT it claims. A rename that returns the
+ * new name and leaves `agent.list` untouched passes any test that only reads the response, and the
+ * user sees the old name until they reload. So every mutation here is checked through a second call.
+ *
+ * Both implementations are driven, because a protocol only one author's server satisfies has not been
+ * tested — it has been restated.
+ */
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { bootExample, bootReference, type Booted } from './providers.js'
+
+const TERMINAL = ['turn_completed', 'turn_failed', 'turn_cancelled', 'turn_input_required']
+
+interface Event { kind?: string; [field: string]: unknown }
+
+let seq = 0
+const turnId = (): string => `m-${Date.now()}-${++seq}`
+
+async function rpc(p: Booted, method: string, params: unknown, key = p.key): Promise<Record<string, unknown>> {
+ const res = await fetch(p.url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
+ })
+ return (await res.json()) as Record<string, unknown>
+}
+
+const resultOf = <T>(body: Record<string, unknown>): T => body.result as T
+const errorOf = (body: Record<string, unknown>): { code?: string; message?: string } | undefined =>
+ body.error as { code?: string; message?: string } | undefined
+const codeOf = (body: Record<string, unknown>): string | undefined => errorOf(body)?.code
+
+const parseFrames = (raw: string): Event[] =>
+ raw
+ .split('\n\n')
+ .map((frame) => frame.split('\n').find((l) => l.startsWith('data:')))
+ .filter((l): l is string => !!l)
+ .map((l) => JSON.parse(l.slice(5).trim()) as Event)
+
+async function send(
+ p: Booted,
+ text: string,
+ extra: Record<string, unknown> = {},
+): Promise<{ events: Event[]; turnId: string; status: number; contentType: string }> {
+ const id = typeof extra.turnId === 'string' ? extra.turnId : turnId()
+ const res = await fetch(p.url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${p.key}` },
+ body: JSON.stringify({
+ jsonrpc: '2.0', id: 1, method: 'agent.send',
+ params: { agentId: p.agentId, turnId: id, message: { text }, ...extra },
+ }),
+ })
+ const contentType = res.headers.get('content-type') ?? ''
+ const raw = await res.text()
+ return {
+ events: contentType.includes('text/event-stream') ? parseFrames(raw) : [],
+ turnId: id,
+ status: res.status,
+ contentType,
+ }
+}
+
+/**
+ * Send, and run `whileRunning` the moment the FIRST event lands.
+ *
+ * A `turn.cancel` fired before the provider has begun is a different code path (and already covered
+ * elsewhere). To test the interruption of a running turn the turn has to be provably running, and
+ * sleeping for an arbitrary number of milliseconds is how that test becomes flaky on a loaded CI box.
+ * Waiting for real output is deterministic.
+ */
+async function sendAndInterrupt(
+ p: Booted,
+ text: string,
+ whileRunning: (turnId: string) => Promise<void>,
+ extra: Record<string, unknown> = {},
+): Promise<{ events: Event[]; turnId: string }> {
+ const id = typeof extra.turnId === 'string' ? extra.turnId : turnId()
+ const res = await fetch(p.url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${p.key}` },
+ body: JSON.stringify({
+ jsonrpc: '2.0', id: 1, method: 'agent.send',
+ params: { agentId: p.agentId, turnId: id, message: { text }, ...extra },
+ }),
+ })
+ const reader = res.body!.getReader()
+ const decoder = new TextDecoder()
+ const events: Event[] = []
+ let buffer = ''
+ let fired = false
+ for (;;) {
+ const { done, value } = await reader.read()
+ if (done) break
+ buffer += decoder.decode(value, { stream: true })
+ const frames = buffer.split('\n\n')
+ buffer = frames.pop() ?? ''
+ for (const frame of frames) {
+ const line = frame.split('\n').find((l) => l.startsWith('data:'))
+ if (line) events.push(JSON.parse(line.slice(5).trim()) as Event)
+ }
+ if (!fired && events.length) {
+ fired = true
+ await whileRunning(id)
+ }
+ }
+ return { events, turnId: id }
+}
+
+const terminals = (events: Event[]): Event[] => events.filter((e) => TERMINAL.includes(e.kind ?? ''))
+const kinds = (events: Event[]): string[] => events.map((e) => e.kind ?? '(none)')
+const historyOf = async (p: Booted, agentId: string, params: Record<string, unknown> = {}): Promise<Event[]> =>
+ resultOf<{ events?: Event[] }>(await rpc(p, 'agent.history', { agentId, ...params })).events ?? []
+
+// ── the matrix ───────────────────────────────────────────────────────────────────────────────────
+
+const providers: Booted[] = []
+
+beforeAll(async () => {
+ providers.push(await bootReference(), await bootExample())
+}, 30_000)
+afterAll(async () => { for (const p of providers) await p.close() })
+
+const each = <T>(fn: (p: Booted) => T): Array<[string, () => T]> =>
+ [0, 1].map((i) => [['reference-provider', 'example-provider'][i]!, () => fn(providers[i]!)])
+
+// ── agent.list ───────────────────────────────────────────────────────────────────────────────────
+
+describe('agent.list', () => {
+ it.each(each((p) => p))('%s returns stable, well-formed, non-empty entries', async (_label, get) => {
+ const p = get()
+ const first = resultOf<{ agents: Array<{ id: string; name: string; description?: string }> }>(
+ await rpc(p, 'agent.list', {}),
+ )
+ expect(first.agents.length).toBeGreaterThan(0)
+ for (const agent of first.agents) {
+ expect(typeof agent.id, JSON.stringify(agent)).toBe('string')
+ expect(agent.id).toBeTruthy()
+ expect(agent.name).toBeTruthy()
+ }
+ // Stable across calls: Autonomous refuses to send to an agent the LATEST list does not contain,
+ // so an id that churns makes every agent unaddressable at random.
+ const second = resultOf<{ agents: Array<{ id: string }> }>(await rpc(p, 'agent.list', {}))
+ expect(second.agents.map((a) => a.id)).toEqual(first.agents.map((a) => a.id))
+ }, 30_000)
+
+ it.each(each((p) => p))('%s does not leak the whole list to an unauthenticated caller', async (_label, get) => {
+ const p = get()
+ const res = await fetch(p.url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'agent.list', params: {} }),
+ })
+ const body = (await res.json()) as Record<string, unknown>
+ expect(codeOf(body)).toBe('unauthenticated')
+ // 401 too, so a client that never parses the body can still tell this from an outage.
+ expect(res.status).toBe(401)
+ expect(body.result).toBeUndefined()
+ }, 30_000)
+})
+
+// ── agent.send ───────────────────────────────────────────────────────────────────────────────────
+
+describe('agent.send', () => {
+ it.each(each((p) => p))('%s opens with turn_started carrying the turnId it was given', async (_label, get) => {
+ const p = get()
+ const { events, turnId: id } = await send(p, 'how is acme pacing?')
+ expect(events[0]!.kind).toBe('turn_started')
+ // Echoing the CLIENT's id back is what makes an out-of-band cancel addressable. A provider that
+ // mints its own would still stream correctly and be uncancellable.
+ expect(events[0]!.turnId).toBe(id)
+ }, 30_000)
+
+ it.each(each((p) => p))('%s refuses a send with no turnId rather than inventing one', async (_label, get) => {
+ const p = get()
+ const body = await rpc(p, 'agent.send', { agentId: p.agentId, message: { text: 'no id' } })
+ expect(codeOf(body)).toBe('invalid_request')
+ }, 30_000)
+
+ it.each(each((p) => p))('%s rejects a bad credential BEFORE opening a stream', async (_label, get) => {
+ const p = get()
+ const res = await fetch(p.url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${p.badKey}` },
+ body: JSON.stringify({
+ jsonrpc: '2.0', id: 1, method: 'agent.send',
+ params: { agentId: p.agentId, turnId: turnId(), message: { text: 'hi' } },
+ }),
+ })
+ // A stream that opens and then fails is far worse than a refusal: the client has already told the
+ // user the turn is running, and has to take it back.
+ expect(res.headers.get('content-type') ?? '').not.toContain('text/event-stream')
+ expect(codeOf((await res.json()) as Record<string, unknown>)).toBe('unauthenticated')
+ }, 30_000)
+
+ it.each(each((p) => p))('%s appends to the transcript instead of replacing it', async (_label, get) => {
+ const p = get()
+ const before = (await historyOf(p, p.agentId)).length
+ await send(p, 'first of two')
+ const between = (await historyOf(p, p.agentId)).length
+ await send(p, 'second of two')
+ const after = (await historyOf(p, p.agentId)).length
+ expect(between).toBeGreaterThan(before)
+ expect(after).toBeGreaterThan(between)
+ }, 30_000)
+})
+
+// ── turn.cancel ──────────────────────────────────────────────────────────────────────────────────
+
+describe('turn.cancel', () => {
+ it.each(each((p) => p))('%s stops a turn that is ALREADY RUNNING', async (_label, get) => {
+ const p = get()
+ // The early-cancel path is covered in flow.spec.ts. This is the other one: a turn that has begun
+ // producing output and must actually be interrupted, not merely marked. A provider whose cancel
+ // only sets a flag it never checks passes the early case and fails this one.
+ const { events } = await sendAndInterrupt(p, p.slowPhrase, async (id) => {
+ const body = await rpc(p, 'turn.cancel', { turnId: id })
+ expect(resultOf<{ cancelled?: boolean }>(body).cancelled).toBe(true)
+ })
+ const ends = terminals(events)
+ expect(ends).toHaveLength(1)
+ expect(ends[0]!.kind).toBe('turn_cancelled')
+ // …and it is last, so the stream really closed rather than being abandoned mid-frame.
+ expect(events.at(-1)!.kind).toBe('turn_cancelled')
+ }, 60_000)
+
+ it.each(each((p) => p))('%s accepts a cancel for a turn it has never heard of', async (_label, get) => {
+ const p = get()
+ // The client mints `turnId` before sending, so "unknown turn" is a legitimate, expected state —
+ // not an error to report at the user.
+ const body = await rpc(p, 'turn.cancel', { turnId: `never-existed-${turnId()}` })
+ expect(codeOf(body)).toBeUndefined()
+ expect(resultOf<{ cancelled?: boolean }>(body).cancelled).toBe(true)
+ }, 30_000)
+
+ it.each(each((p) => p))('%s refuses a cancel with no turnId rather than guessing', async (_label, get) => {
+ const p = get()
+ // Guessing here means stopping somebody else's turn.
+ expect(codeOf(await rpc(p, 'turn.cancel', {}))).toBe('invalid_request')
+ }, 30_000)
+})
+
+// ── agent.history ────────────────────────────────────────────────────────────────────────────────
+
+describe('agent.history', () => {
+ it.each(each((p) => p))('%s keeps each agent’s transcript to itself', async (_label, get) => {
+ const p = get()
+ const marker = `isolation probe ${turnId()}`
+ await send(p, marker)
+ const other = await historyOf(p, p.otherAgentId)
+ // One tenant's agents are not one transcript. A shared store keyed by the wrong thing shows the
+ // user another agent's conversation, which is a data-leak class of bug, not a cosmetic one.
+ expect(other.some((e) => typeof e.text === 'string' && e.text.includes(marker))).toBe(false)
+ }, 30_000)
+
+ it.each(each((p) => p))('%s omits nextBefore when the whole transcript was asked for', async (_label, get) => {
+ const p = get()
+ await send(p, 'give me something to read back')
+ const body = await rpc(p, 'agent.history', { agentId: p.agentId })
+ const result = resultOf<Record<string, unknown>>(body)
+ // Its ABSENCE is the client's only signal that it reached the start. Present-and-meaningless
+ // makes an unwindowed read look like the first page of a longer one.
+ expect('nextBefore' in result).toBe(false)
+ expect(Array.isArray(result.events)).toBe(true)
+ }, 30_000)
+
+ it.each(each((p) => p))('%s windows from the NEWEST end', async (_label, get) => {
+ const p = get()
+ await send(p, 'older turn')
+ await send(p, 'newest turn')
+ const whole = await historyOf(p, p.agentId)
+ expect(whole.length).toBeGreaterThan(1)
+ const windowed = await historyOf(p, p.agentId, { limit: 1 })
+ expect(windowed).toHaveLength(1)
+ // The user is looking at the bottom of a conversation, so a window that starts at the TOP shows
+ // them the beginning of a chat they have already read.
+ expect(windowed[0]).toEqual(whole.at(-1))
+ }, 30_000)
+
+ it.each(each((p) => p))('%s never returns a terminal or lifecycle frame as transcript', async (_label, get) => {
+ const p = get()
+ await send(p, 'a turn with a full lifecycle')
+ const stored = new Set(kinds(await historyOf(p, p.agentId)))
+ // These are live-turn signals. A transcript that replays them makes a refreshed page re-run the
+ // turn's UI: a spinner that opens, a "done" that fires again.
+ for (const kind of [...TERMINAL, 'turn_started', 'recap_start', 'recap_end']) {
+ expect(stored.has(kind), `${kind} leaked into history`).toBe(false)
+ }
+ }, 30_000)
+
+ it.each(each((p) => p))('%s refuses an unknown agent instead of answering empty', async (_label, get) => {
+ const p = get()
+ // Empty and "no such agent" are different sentences: one says the conversation is new, the other
+ // says the id is wrong.
+ expect(codeOf(await rpc(p, 'agent.history', { agentId: `ghost-${turnId()}` }))).toBe('not_found')
+ }, 30_000)
+})
+
+// ── agent.recap ──────────────────────────────────────────────────────────────────────────────────
+
+describe('agent.recap', () => {
+ it.each(each((p) => p))('%s answers with an object, never `unsupported`', async (_label, get) => {
+ const p = get()
+ const body = await rpc(p, 'agent.recap', { agentId: p.agentId })
+ // A provider that summarises nothing says so by answering with no `recap`, and Autonomous derives
+ // one from the turn's own text. `unsupported` would leave the device with a blank tile and no
+ // reason for it.
+ expect(codeOf(body)).toBeUndefined()
+ expect(resultOf<{ agentId?: string }>(body).agentId).toBe(p.agentId)
+ }, 30_000)
+
+ it.each(each((p) => p))('%s hands back a headline it can render, tagged with its turn', async (_label, get) => {
+ const p = get()
+ // Produce something to summarise first: `recap` is the reference provider's scripted recap turn,
+ // and any completed turn gives the Claude-backed one an excerpt to store.
+ await send(p, 'recap')
+ const out = resultOf<{ recap?: unknown; text?: unknown; turnId?: unknown }>(
+ await rpc(p, 'agent.recap', { agentId: p.agentId }),
+ )
+ // The device renders this on a round 466px screen; a recap with no headline is a blank tile.
+ expect(typeof out.recap).toBe('string')
+ expect(String(out.recap).trim()).toBeTruthy()
+ if (out.text !== undefined) expect(typeof out.text).toBe('string')
+ // Tagged with its turn, so a client asking the instant a turn ends can tell THIS turn's summary
+ // from the previous one's — the pull is scoped to an agent and cannot be scoped to a turn.
+ expect(typeof out.turnId).toBe('string')
+ }, 30_000)
+
+ it.each(each((p) => p))('%s returns the LAST recap, not an older one', async (_label, get) => {
+ const p = get()
+ // The whole point of the method after `n` went away. Two summarised turns in a row must leave the
+ // second one on the tile — a provider returning its oldest, or its first-stored, passes every
+ // other assertion here and shows the user yesterday's work.
+ await send(p, 'recap')
+ const first = resultOf<{ turnId?: string }>(await rpc(p, 'agent.recap', { agentId: p.agentId }))
+ const second = await send(p, 'recap')
+ const after = resultOf<{ turnId?: string }>(await rpc(p, 'agent.recap', { agentId: p.agentId }))
+
+ expect(after.turnId).not.toBe(first.turnId)
+ expect(after.turnId).toBe(second.turnId)
+ }, 30_000)
+
+ it.each(each((p) => p))('%s says nothing rather than something stale for a fresh agent', async (_label, get) => {
+ const p = get()
+ const created = resultOf<{ id: string }>(await rpc(p, 'agent.create', { name: `Recap Probe ${Date.now()}${++seq}` }))
+ const out = resultOf<Record<string, unknown>>(await rpc(p, 'agent.recap', { agentId: created.id }))
+ // ABSENT, not empty-string: the device shows no tile at all rather than a blank one.
+ expect(out.recap).toBeUndefined()
+ await rpc(p, 'agent.delete', { agentId: created.id })
+ }, 30_000)
+})
+
+// ── agent.create / rename / delete ───────────────────────────────────────────────────────────────
+
+describe('agent.create', () => {
+ it.each(each((p) => p))('%s puts the new agent in agent.list', async (_label, get) => {
+ const p = get()
+ const name = `Created ${Date.now()}${++seq}`
+ const created = resultOf<{ id: string; name: string }>(await rpc(p, 'agent.create', { name }))
+ expect(created.name).toBe(name)
+
+ // The response is not the point — the LIST is what the user sees. A create that returns an agent
+ // and does not persist it looks like it worked until the next reload.
+ const listed = resultOf<{ agents: Array<{ id: string; name: string }> }>(await rpc(p, 'agent.list', {})).agents
+ expect(listed.find((a) => a.id === created.id)?.name).toBe(name)
+
+ await rpc(p, 'agent.delete', { agentId: created.id })
+ }, 30_000)
+
+ it.each(each((p) => p))('%s refuses an empty name with a reason, not `unsupported`', async (_label, get) => {
+ const p = get()
+ const err = errorOf(await rpc(p, 'agent.create', { name: ' ' }))
+ expect(err?.code).toBe('invalid_request')
+ // Nothing is declared in advance, so the message IS the explanation the UI shows.
+ expect(err?.message).toBeTruthy()
+ }, 30_000)
+
+ it.each(each((p) => p))('%s never hands out a duplicate id for a duplicate name', async (_label, get) => {
+ const p = get()
+ // The two implementations resolve this differently — one derives a fresh id, the other refuses —
+ // and both are conformant. What neither may do is return an id that already belongs to another
+ // agent, which would silently alias two workspaces onto one.
+ const name = `Twice ${Date.now()}${++seq}`
+ const first = resultOf<{ id: string }>(await rpc(p, 'agent.create', { name }))
+ const second = await rpc(p, 'agent.create', { name })
+ const created: string[] = [first.id]
+ if (second.result) {
+ const id = resultOf<{ id: string }>(second).id
+ expect(id).not.toBe(first.id)
+ created.push(id)
+ } else {
+ expect(codeOf(second)).toBe('invalid_request')
+ expect(errorOf(second)?.message).toBeTruthy()
+ }
+ for (const id of created) await rpc(p, 'agent.delete', { agentId: id })
+ }, 30_000)
+})
+
+describe('agent.rename', () => {
+ it.each(each((p) => p))('%s changes the name in agent.list and keeps the id', async (_label, get) => {
+ const p = get()
+ const created = resultOf<{ id: string }>(await rpc(p, 'agent.create', { name: `Before ${Date.now()}${++seq}` }))
+ const after = `After ${Date.now()}${++seq}`
+ const renamed = resultOf<{ id: string; name: string }>(await rpc(p, 'agent.rename', { agentId: created.id, name: after }))
+
+ // The id is the addressing key. Renaming it would silently orphan the transcript and every
+ // reference the client already holds.
+ expect(renamed.id).toBe(created.id)
+ const listed = resultOf<{ agents: Array<{ id: string; name: string }> }>(await rpc(p, 'agent.list', {})).agents
+ expect(listed.find((a) => a.id === created.id)?.name).toBe(after)
+
+ await rpc(p, 'agent.delete', { agentId: created.id })
+ }, 30_000)
+
+ it.each(each((p) => p))('%s refuses an unknown agent with a reason', async (_label, get) => {
+ const p = get()
+ const err = errorOf(await rpc(p, 'agent.rename', { agentId: `ghost-${turnId()}`, name: 'x' }))
+ expect(err?.code).toBe('invalid_request')
+ expect(err?.message).toBeTruthy()
+ }, 30_000)
+})
+
+describe('agent.delete', () => {
+ it.each(each((p) => p))('%s removes it from the list AND makes it unaddressable', async (_label, get) => {
+ const p = get()
+ const created = resultOf<{ id: string }>(await rpc(p, 'agent.create', { name: `Doomed ${Date.now()}${++seq}` }))
+ expect(resultOf<{ deleted?: boolean }>(await rpc(p, 'agent.delete', { agentId: created.id })).deleted).toBe(true)
+
+ const listed = resultOf<{ agents: Array<{ id: string }> }>(await rpc(p, 'agent.list', {})).agents
+ expect(listed.map((a) => a.id)).not.toContain(created.id)
+
+ // Gone from the list but still answering is the worse half of this bug: the agent is invisible in
+ // the UI and still reachable by anyone holding the id.
+ expect(codeOf(await rpc(p, 'agent.history', { agentId: created.id }))).toBe('not_found')
+ const after = await send(p, 'anyone there?', { agentId: created.id })
+ expect(after.contentType).not.toContain('text/event-stream')
+ }, 30_000)
+
+ it.each(each((p) => p))('%s refuses to delete an agent it does not have', async (_label, get) => {
+ const p = get()
+ // Answering `{deleted:true}` for an id that never existed makes a failed delete indistinguishable
+ // from a successful one.
+ expect(codeOf(await rpc(p, 'agent.delete', { agentId: `ghost-${turnId()}` }))).toBe('invalid_request')
+ }, 30_000)
+})
diff --git a/provider/e2e/src/providers.ts b/provider/e2e/src/providers.ts
new file mode 100644
index 000000000..9f6c551e9
--- /dev/null
+++ b/provider/e2e/src/providers.ts
@@ -0,0 +1,196 @@
+/**
+ * Booting each implementation on an ephemeral port, with everything it needs faked out.
+ *
+ * `example-provider` normally spawns the real `claude`. Here it gets a shell script that echoes
+ * recorded stream-json instead, so this suite needs no model, no network and no API key — and stays
+ * deterministic, which a suite asserting exact event sequences has to be.
+ */
+import { chmodSync, mkdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import type { AddressInfo } from 'node:net'
+
+import { start as startReference } from '../../reference-provider/src/server.js'
+import { createProviderServer as createExample } from '../../example-provider/src/server.js'
+import type { Config } from '../../example-provider/src/config.js'
+
+export interface Booted {
+ /** Shown in test names, so a failure says WHICH implementation broke. */
+ label: string
+ url: string
+ /** A credential this provider accepts. */
+ key: string
+ /** A credential it must reject, so the `credential-rejected` checks have something to hit. */
+ badKey: string
+ /** A prompt that makes it ask the user something, or undefined when it cannot. */
+ askPhrase?: string
+ /** An agent id that exists on it. */
+ agentId: string
+ /** A SECOND agent id, for asserting one agent's transcript never leaks into another's. */
+ otherAgentId: string
+ /** Text that makes this provider take long enough to cancel mid-turn. */
+ slowPhrase: string
+ close: () => Promise<void>
+}
+
+const CLAUDE_SESSION = 'e2e-session'
+
+const textLine = (text: string): unknown => ({
+ type: 'stream_event',
+ session_id: CLAUDE_SESSION,
+ event: { type: 'content_block_delta', delta: { type: 'text_delta', text } },
+})
+const toolLines = (): unknown[] => [
+ {
+ type: 'assistant',
+ session_id: CLAUDE_SESSION,
+ message: { role: 'assistant', content: [{ type: 'tool_use', id: 'c1', name: 'Read', input: { path: 'note.txt' } }] },
+ },
+ {
+ type: 'user',
+ session_id: CLAUDE_SESSION,
+ message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'c1', content: 'the note' }] },
+ },
+]
+const resultLine = (): unknown => ({ type: 'result', session_id: CLAUDE_SESSION, subtype: 'success', result: 'ok' })
+
+/** The word that makes the fake `claude` hang, so a cancel has a running turn to interrupt. */
+export const SLOW_PHRASE = 'TAKE-YOUR-TIME'
+
+/**
+ * The three transcript lines one turn leaves behind, matching what the stream emitted.
+ *
+ * The tool id is the same on both sides ON PURPOSE: `agent.history` must hand back the objects the
+ * stream emitted, and a transcript that renamed the id would fail that comparison for a reason that
+ * is nobody's bug. It only has to be unique WITHIN a turn, which it is.
+ */
+const TRANSCRIPT_LINES = [
+ { type: 'assistant', message: { role: 'assistant', content: [{ type: 'tool_use', id: 'c1', name: 'Read', input: { path: 'note.txt' } }] } },
+ { type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'c1', content: 'the note' }] } },
+ { type: 'assistant', message: { role: 'assistant', content: [{ type: 'text', text: 'Acme is at 118% of pace.' }] } },
+]
+
+/**
+ * A `claude` that prints a fixed, tool-using turn, records it, and exits.
+ *
+ * **It writes the transcript, because a real `claude` does.** Without that, `agent.history` for this
+ * implementation is a static fixture: it never grows, so "the transcript appends across turns", "the
+ * newest window is the newest turn" and "the user's own message is stored" would all be asserting
+ * against a file nobody wrote. The provider reads Claude's JSONL rather than keeping its own store,
+ * so the only faithful fake is one that leaves the same trail behind.
+ */
+function fakeClaude(root: string, projects: string): string {
+ const path = join(root, 'claude.sh')
+ // Order matters: the transcript records the tool first, so the stream must too.
+ const stream = [...toolLines(), textLine('Acme is at '), textLine('118% of pace.'), resultLine()]
+ writeFileSync(path, [
+ '#!/bin/sh',
+ // Reading stdin serves three purposes. It drains the frame the provider writes the user's message
+ // to — without that the script can exit before the write lands and node raises EPIPE — it lets ONE
+ // turn opt into hanging so `turn.cancel` meets a genuinely in-flight process, and the frame is
+ // itself a valid transcript `user` line, so it is appended verbatim exactly as claude records it.
+ 'input=$(cat)',
+ `case "$input" in *${SLOW_PHRASE}*) sleep 30 ;; esac`,
+ // Single-quoted, so none of the JSON above or below may contain an apostrophe — it would end the
+ // shell string and the script would fail as an EMPTY HISTORY rather than as a syntax error. Keep
+ // the fixture text plain.
+ ...stream.map((l) => `echo '${JSON.stringify(l)}'`),
+ // The project directory is the absolute cwd with every non-alphanumeric character replaced by a
+ // dash — the same lossy mangling `jsonl.ts` does, reproduced here rather than passed in, so each
+ // agent lands in its own directory the way a real run would.
+ // Two traps in one line. `pwd -P`, not `$PWD`: the parent's PWD is inherited through the
+ // environment and still points at wherever vitest was started, so using it writes every agent's
+ // transcript into one directory named after the test runner. And `printf '%s'` around it, because
+ // piping `pwd` straight into `tr` feeds it the trailing NEWLINE too — which `tr -c` faithfully
+ // turns into one more dash, producing a directory the provider will never look in.
+ `dir="${projects}/$(printf '%s' "$(pwd -P)" | tr -c 'a-zA-Z0-9' '-')"`,
+ 'mkdir -p "$dir"',
+ `file="$dir/${CLAUDE_SESSION}.jsonl"`,
+ 'printf \'%s\\n\' "$input" >> "$file"',
+ ...TRANSCRIPT_LINES.map((l) => `printf '%s\\n' '${JSON.stringify(l)}' >> "$file"`),
+ '',
+ ].join('\n'))
+ chmodSync(path, 0o755)
+ return path
+}
+
+export async function bootReference(): Promise<Booted> {
+ // STEP_DELAY_MS is deliberately NOT forced to 0 here. `server.ts` reads it once at module load, so
+ // setting it now would be a no-op that reads like a guarantee — and the mid-turn cancel test needs
+ // the opposite guarantee anyway: a turn slow enough to still be running when the cancel lands.
+ const s = await startReference(0)
+ return {
+ label: 'reference-provider',
+ url: s.url,
+ key: 'e2e',
+ badKey: 'bad-key',
+ askPhrase: 'ask me',
+ agentId: 'alpha',
+ otherAgentId: 'beta',
+ // Every scripted step pauses for STEP_DELAY_MS, so the default turn is comfortably long enough
+ // to be interrupted once its first event has arrived.
+ slowPhrase: 'everything',
+ close: s.close,
+ }
+}
+
+export async function bootExample(): Promise<Booted> {
+ // realpath'd, because `os.tmpdir()` on macOS hands back `/var/folders/…` while the shell resolves
+ // the same directory to `/private/var/folders/…`. The provider mangles the configured path and the
+ // fake claude mangles its actual one; unless those are the same string they name two different
+ // project directories and every history read comes back empty. `loadConfig` resolves paths for this
+ // exact reason, and the harness builds its config by hand, so it has to do the same.
+ const rawRoot = join(tmpdir(), `provider-e2e-${process.pid}-${Math.random().toString(36).slice(2)}`)
+ mkdirSync(rawRoot, { recursive: true })
+ const root = realpathSync(rawRoot)
+ const cwd = join(root, 'agent')
+ // Its OWN directory, not a second name for the first one. Two agents sharing a cwd would share a
+ // transcript, and a per-agent isolation test against that fixture would pass for the wrong reason.
+ const secondCwd = join(root, 'agent-two')
+ const projects = join(root, 'projects')
+ mkdirSync(cwd, { recursive: true })
+ mkdirSync(secondCwd, { recursive: true })
+ mkdirSync(projects, { recursive: true })
+
+ const config: Config = {
+ agents: [
+ { id: 'scratch', name: 'Scratch', description: 'e2e agent', cwd },
+ { id: 'second', name: 'Second', description: 'a second agent, so scoping has something to get wrong', cwd: secondCwd },
+ ],
+ workspaceRoot: root,
+ agentsFile: join(root, 'agents.json'),
+ claudeBin: fakeClaude(root, projects),
+ model: 'e2e-model',
+ port: 0,
+ stateFile: join(root, 'state.json'),
+ claudeProjectsDir: projects,
+ recapModel: 'e2e-recap',
+ // Excerpts the turn instead of spawning a second claude — same code path into the stream.
+ recapDisabled: true,
+ }
+
+ const { server, deps } = createExample(config)
+ // The fake claude reports the session id on its stream, but history is read per AGENT — so bind it
+ // up front, exactly as a first real turn would.
+ for (const id of ['scratch', 'second']) {
+ deps.store.ensureAgent(id)
+ deps.store.setClaudeSession(id, CLAUDE_SESSION)
+ }
+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))
+ const { port } = server.address() as AddressInfo
+ return {
+ label: 'example-provider',
+ url: `http://127.0.0.1:${port}`,
+ key: 'e2e',
+ badKey: 'bad-key',
+ // It has no scripted "ask" path — a real Claude decides that, so the check is honestly skipped
+ // rather than faked into passing.
+ agentId: 'scratch',
+ otherAgentId: 'second',
+ slowPhrase: SLOW_PHRASE,
+ close: async () => {
+ await new Promise<void>((r) => server.close(() => r()))
+ rmSync(root, { recursive: true, force: true })
+ },
+ }
+}
diff --git a/provider/e2e/tsconfig.json b/provider/e2e/tsconfig.json
new file mode 100644
index 000000000..fe82d03ff
--- /dev/null
+++ b/provider/e2e/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "strict": true,
+ "noEmit": true,
+ "skipLibCheck": true,
+ "allowImportingTsExtensions": false,
+ "types": ["node"]
+ },
+ "include": ["src/**/*.ts", "../reference-provider/src/**/*.ts", "../example-provider/src/**/*.ts"]
+}
diff --git a/provider/example-provider/README.md b/provider/example-provider/README.md
index 37e676688..558e834ad 100644
--- a/provider/example-provider/README.md
+++ b/provider/example-provider/README.md
@@ -7,18 +7,18 @@
> a real repository. `agents.example.json` ships pointing at `/tmp/example-provider-scratch` on
> purpose.
-A **real** A2A provider for the Autonomous machine provider profile
-(`../spec/README.md`), backed by the local `claude` CLI.
+A **real** provider for the Autonomous machine provider protocol (`../spec/README.md`), backed by the
+local `claude` CLI.
-Where `apps/reference-provider` is scripted and deterministic, this one runs an actual agent. That is
-the point: it answers the question a scripted provider cannot — **does the profile survive a real
+Where `reference-provider` is scripted and deterministic, this one runs an actual agent. That is the
+point: it answers the question a scripted provider cannot — **does the protocol survive a real
agent?** Real agents stream partial tokens, call tools, resume sessions, and keep history in their own
format.
| | `reference-provider` | `example-provider` |
|---|---|---|
| Replies | scripted | a real Claude turn |
-| Job | conformance target, hostile scenarios, CI | prove the profile survives a real agent |
+| Job | conformance target, hostile scenarios, CI | prove the protocol survives a real agent |
| Determinism | total | none — **keep it out of CI** |
## Run it
@@ -32,28 +32,29 @@ npm run dev # http://127.0.0.1:4502
```bash
curl -N localhost:4502 \
- -H 'content-type: application/json' -H 'x-api-key: demo' \
- -d '{"jsonrpc":"2.0","id":1,"method":"SendStreamingMessage",
- "params":{"message":{"role":"ROLE_USER","messageId":"m1",
- "parts":[{"text":"what files are here?"}]}}}'
+ -H 'content-type: application/json' -H 'authorization: Bearer demo' \
+ -d '{"jsonrpc":"2.0","id":1,"method":"agent.send",
+ "params":{"agentId":"scratch","turnId":"t-1",
+ "message":{"text":"what files are here?"}}}'
```
| Env | Default |
|---|---|
| `AGENTS_FILE` | `./agents.json` |
| `CLAUDE_PATH` | resolved via `which claude`, then the usual install locations |
-| `CLAUDE_MODEL` | `claude-sonnet-5`. Pinned, not left to the CLI default: a provider owns its model choice, and Autonomous never sends one (spec §9) |
+| `CLAUDE_MODEL` | `claude-sonnet-5`. Pinned, not left to the CLI default: a provider owns its model choice, and Autonomous never sends one |
| `PORT` | `4502` |
| `STATE_FILE` | `./sessions.json` |
-| `WORKSPACE_ROOT` | `/tmp/example-provider-scratch` — where `autonomous.CreateAgent` puts a new agent's directory |
+| `WORKSPACE_ROOT` | `/tmp/example-provider-scratch` — where `agent.create` puts a new agent's directory |
| `CLAUDE_PROJECTS_DIR` | `~/.claude/projects` |
| `CLAUDE_RECAP_MODEL` | `claude-haiku-4-5-20251001` — the per-turn recap is a one-line headline, not the work, so it gets a small model |
| `RECAP_DISABLED` | unset. `1` skips the recap model entirely and excerpts the turn instead |
## How it works
-**Agents come from `agents.json`** — `[{ id, name, description, cwd }]`. Each becomes an
-`AgentCard.skills[]` entry; `cwd` is where `claude` is spawned.
+**Agents come from `agents.json`** — `[{ id, name, description, cwd }]`. Each becomes an `agent.list`
+entry; `cwd` is where `claude` is spawned. `agent.create` / `agent.rename` / `agent.delete` really
+mutate that file, so an agent created a moment ago is addressable by its very next `agent.send`.
**One turn = one `claude` process**, invoked the way `apps/agent-node/brain` does it:
@@ -65,31 +66,28 @@ claude --print --verbose --output-format stream-json --input-format stream-json
The user's message is passed **verbatim** — no wrapper text, no prepended hints.
**History comes from Claude's own transcripts** at
-`~/.claude/projects/<mangled-cwd>/<sessionId>.jsonl`, so `GetTask` and `ListTasks` cost this provider
-nothing. A pleasant side effect: **a turn typed straight into a terminal shows up in the session list
-too** — it just does not stream live, since this app implements no `SubscribeToTask`.
+`~/.claude/projects/<mangled-cwd>/<sessionId>.jsonl`, so `agent.history` costs this provider nothing to
+store. A pleasant side effect: **a turn typed straight into a terminal shows up in the transcript
+too** — it just does not stream live, since nothing was watching when it ran.
-`GetTask` returns one TURN, which is not what a client opening a chat wants: a conversation is many
-turns, and a long one should arrive a page at a time. That is `autonomous.GetContextHistory`
-(`context-history`, HP-304) — a whole context, newest window first, `before` walking backwards. It
-reads the transcript whole rather than per-task, so nothing can fall into the gap between two turns'
-time windows, and a window's left edge is snapped back to a real user prompt so a page can never begin
-between a tool call and its result.
+One agent is one Claude session, resumed on every turn, so the whole transcript is one file. A long
+one arrives a page at a time: `agent.history` takes `limit` and an opaque `before` cursor and walks
+backwards, and stops offering a cursor once the start is reached.
-**One mapper, two callers.** `src/mapper.ts` is the only place Claude's shape becomes A2A. Stdout
-events and JSONL lines carry the same Anthropic message shape, so writing two parsers is the reliable
-way to make the live view and the post-refresh view disagree.
+**One mapper, two callers.** `src/mapper.ts` is the only place Claude's shape becomes a provider
+event. Stdout lines and JSONL lines carry the same Anthropic message shape, so writing two parsers is
+the reliable way to make the live view and the post-refresh view disagree about the same turn — which
+is exactly what `agent.history` returning the stream's own objects forbids.
**Recaps are generated per TURN**, on the turn's own stream and just before its terminal event, by a
disposable one-shot `claude --print` (`src/recap.ts`). The turn therefore stays open while the summary
-is written — deliberately, and announced: a `recap_start` part goes out before the wait and a
-`recap_end` after it (HP-212), so the client can say "preparing a recap" instead of showing a stall.
+is written — deliberately, and announced: `recap_start` goes out before the wait and `recap_end` after
+it, so the client can say "preparing a recap" instead of showing a stall.
-The alternative — close the stream, summarise afterwards, let the client pull it with
-`autonomous.GetRecap` — is what this used to do, and it cannot work: that method is scoped to an AGENT
-and takes no task id, so a client asking the instant a turn ends gets either nothing or the PREVIOUS
-turn's headline. The recap is still persisted as well, because a device restoring its tiles after a
-reboot has no stream to read.
+The recap is pushed on the turn's OWN stream and also persisted for `agent.recap`. Both, not either: the stream serves the client watching this turn,
+and the persisted copy serves a device restoring its tiles after a reboot, which has no stream to
+read. Pushing is what makes the recap unambiguously THIS turn's — the pull is scoped to an agent and
+takes no turn id, so a client asking the instant a turn ends can only get the previous one.
Four details are load-bearing:
@@ -99,7 +97,7 @@ Four details are load-bearing:
`metadata.title` — the first user message — is the wrong one. A device tile that echoes the user's
own prompt back at them is worse than no tile.
- **The caps are re-applied after the model answers.** A model asked for 15 words will sometimes give
- 40, and `recapEntry.recap` is capped at 200 characters by the schema. Nothing ever appends an
+ 40, and `recap` is capped at 200 characters. Nothing ever appends an
ellipsis: the tile renders on a small round display, where a line advertising its own truncation
reads worse than one that simply ends.
@@ -112,13 +110,12 @@ and must never be able to retroactively fail a turn that succeeded.
## What it does not do
-- **No `INPUT_REQUIRED`.** With permissions skipped, Claude never asks, so HP-104 stays demonstrated
- only by `reference-provider`'s scripted path.
-- **No `SubscribeToTask`** — deliberately out of scope.
-- **No session writes.** `workspace-write` is declared with `params: { agents: true, sessions: false }`:
- creating an agent is ours to do, but retitling or deleting a session would mean editing the user's
- own Claude transcripts under `~/.claude`.
-- **No images.** Refused loudly rather than dropped silently (HP-106).
+- **No `turn_input_required`.** With permissions skipped, Claude never asks, so that path stays
+ demonstrated only by `reference-provider`'s scripted one.
+- **`agent.delete` leaves the directory alone.** Removing an agent from the list is reversible;
+ deleting whatever work it produced is not, and an example provider is the last place to be
+ destructive.
+- **No images.** Refused loudly rather than dropped silently.
## Verification
@@ -132,11 +129,10 @@ Conformance, against a running instance:
```bash
cd ../reference-provider
npx tsx src/conformance.ts --url http://127.0.0.1:4502 --key demo --bad-key bad-key
-# 21 passed · 0 failed · 2 manual · 10 not verifiable from outside
```
-**That result is the headline.** The conformance runner was written against a scripted provider; a
-real Claude-backed one passing it is what validates the profile, the runner, and this app at once.
+**Zero failures is the headline.** The conformance runner was written against a scripted provider; a
+real Claude-backed one passing it is what validates the protocol, the runner, and this app at once.
## Two real bugs the fixtures caught
@@ -154,8 +150,7 @@ And one the **conformance suite** caught against the live agent:
3. **macOS `/tmp` is a symlink to `/private/tmp`**, and Claude records the resolved path. A configured
`/tmp/x` made this provider look in `-tmp-x` while Claude had written `-private-tmp-x`, so every
- history read came back empty and HP-201 failed. `agents.json` paths are now `realpath`-resolved at
- load.
+ history read came back empty. `agents.json` paths are now `realpath`-resolved at load.
All three are pinned by tests, and all three tests were mutation-checked.
@@ -163,12 +158,12 @@ All three are pinned by tests, and all three tests were mutation-checked.
| File | Role |
|---|---|
-| `src/types.ts` | the A2A subset, copied from `reference-provider` — apps do not import each other |
+| `src/types.ts` | the wire surface, copied from `reference-provider` — the apps do not import each other |
| `src/config.ts` | `agents.json` loading and validation; resolves the `claude` binary |
-| `src/agentCard.ts` | the card, built **from** the agent list |
+| `src/agents.ts` | the agent list, read from config on every call so a new agent is instantly addressable |
| `src/claude.ts` | spawn, stdin frame, stdout lines, process-group kill |
-| `src/mapper.ts` | **the** Claude → A2A mapping, shared by the live and history paths |
+| `src/mapper.ts` | **the** Claude → provider-event mapping, shared by the live and history paths |
| `src/jsonl.ts` | transcript discovery, reading and time-slicing |
-| `src/sessions.ts` | `contextId ↔ claudeSessionId`, task windows, and persisted per-turn recaps |
+| `src/sessions.ts` | `agentId ↔ claudeSessionId` — one agent is one Claude session — plus turn windows and persisted per-turn recaps |
| `src/recap.ts` | the per-turn recap one-shot, its caps, and the no-model fallback |
-| `src/server.ts` | JSON-RPC + SSE, with HP-xxx clause references inline |
+| `src/server.ts` | JSON-RPC + SSE |
diff --git a/provider/example-provider/src/agentCard.ts b/provider/example-provider/src/agentCard.ts
deleted file mode 100644
index 4c05acd58..000000000
--- a/provider/example-provider/src/agentCard.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-/**
- * The Agent Card — HP-020 … HP-023.
- *
- * Unlike the reference provider's static card, this one is built FROM `agents.json`: the skills are
- * whatever directories the operator configured. The card is the whole capability negotiation, so
- * everything this provider can do has to be visible here (HP-001).
- */
-import type { AgentEntry } from './config.js'
-
-export const EXT = {
- WORKSPACE_FILES: 'https://harness.autonomous.ai/api/a2a/ext/workspace-files',
- WORKSPACE_WRITE: 'https://harness.autonomous.ai/api/a2a/ext/workspace-write',
- SESSION_RECAP: 'https://harness.autonomous.ai/api/a2a/ext/session-recap',
- CONTEXT_HISTORY: 'https://harness.autonomous.ai/api/a2a/ext/context-history',
- VOICE: 'https://harness.autonomous.ai/api/a2a/ext/voice',
-} as const
-
-/**
- * Declared here:
- * - `workspace-files` — the agent has a real working directory, so a file tree is meaningful.
- * - `session-recap` — Claude's transcripts give us recent turns for free.
- *
- * - `workspace-write` — agents only. A new agent is a new directory under WORKSPACE_ROOT, which
- * is why that root is separate from the agent directories themselves: creating one must never
- * be able to write outside it.
- *
- * NOT declared:
- * - `voice` — Autonomous routes from skills[] by default; overriding buys nothing here.
- */
-export function buildAgentCard(agents: AgentEntry[]): Record<string, unknown> {
- return {
- name: 'Claude (example provider)',
- description:
- 'A real A2A provider backed by the local Claude Code CLI. Each skill is a configured working directory.',
- version: '0.1.0',
-
- // HP-021 — non-negotiable. Claude streams tokens and so does this provider.
- capabilities: { streaming: true, pushNotifications: false },
-
- // HP-011 — APIKey in a header is one of the two schemes Autonomous supports.
- securitySchemes: { apiKey: { type: 'apiKey', in: 'header', name: 'x-api-key' } },
-
- defaultInputModes: ['text/plain'],
- defaultOutputModes: ['text/plain'],
-
- // HP-023 — the agent list the user sees. `cwd` stays server-side: it is a filesystem path and
- // nothing the client needs.
- skills: agents.map((a) => ({ id: a.id, name: a.name, description: a.description })),
-
- // HP-022 — implemented-but-undeclared must read as absent, so this list is the contract.
- extensions: [
- { uri: EXT.WORKSPACE_FILES, description: 'Browse and read files in the agent working directory.' },
- { uri: EXT.SESSION_RECAP, description: 'Recent turn summaries, from Claude transcripts.' },
- { uri: EXT.CONTEXT_HISTORY, description: 'A whole conversation in one call, paged newest-first.' },
- {
- uri: EXT.WORKSPACE_WRITE,
- description: 'Create and remove agents. Each one is a directory under the workspace root.',
- // `sessions: false` — deleting or retitling a Claude transcript would mean writing into
- // ~/.claude, which is the user's own history and not ours to edit.
- params: { agents: true, sessions: false },
- },
- ],
- }
-}
diff --git a/provider/example-provider/src/agents.ts b/provider/example-provider/src/agents.ts
new file mode 100644
index 000000000..129c41261
--- /dev/null
+++ b/provider/example-provider/src/agents.ts
@@ -0,0 +1,19 @@
+/**
+ * The agent list, and where the credential goes.
+ *
+ * There is nothing to discover: one URL, one credential header, eight methods. `agent.list` IS how a
+ * client learns what this provider offers, and because it is authenticated, two credentials can
+ * legitimately see two different lists — which is exactly why the list was never something a public
+ * document could carry.
+ *
+ * Read from `config` on every call rather than snapshotted, so an agent created a moment ago is
+ * addressable by its very next `agent.send`.
+ */
+import type { Config } from './config.js'
+import type { Agent } from './types.js'
+
+export const CREDENTIAL_HEADER = 'authorization'
+
+/** The agent list, from configuration, scoped to the tenant the credential selects. */
+export const agentsOf = (config: Config): Agent[] =>
+ config.agents.map((a) => ({ id: a.id, name: a.name, ...(a.description ? { description: a.description } : {}) }))
diff --git a/provider/example-provider/src/config.ts b/provider/example-provider/src/config.ts
index 079da5443..ff71e57ef 100644
--- a/provider/example-provider/src/config.ts
+++ b/provider/example-provider/src/config.ts
@@ -1,8 +1,8 @@
/**
* Configuration: the agent list, and how to reach the `claude` binary.
*
- * The agent list is the ONLY per-deployment state. Each entry becomes an `AgentCard.skills[]` entry
- * (HP-023) and carries the working directory `claude` is spawned in.
+ * The agent list is the ONLY per-deployment state. Each entry becomes an `agent.list` entry
+ * and carries the working directory `claude` is spawned in.
*/
import { execFileSync } from 'node:child_process'
import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
@@ -21,7 +21,7 @@ export interface AgentEntry {
export interface Config {
agents: AgentEntry[]
/**
- * Where `autonomous.CreateAgent` puts a new agent's directory.
+ * Where `agent.create` puts a new agent's directory.
*
* Deliberately its own setting rather than "the parent of the first agent": creating an agent is a
* write, and a write needs a root it cannot escape. Everything created lands under here.
@@ -90,7 +90,7 @@ export function loadAgents(file: string): AgentEntry[] {
// RESOLVE SYMLINKS. Claude records the fully-resolved path, and the transcript directory name is
// derived from it — on macOS `/tmp` is a symlink to `/private/tmp`, so a configured `/tmp/x`
// would look for `-tmp-x` while Claude wrote `-private-tmp-x`, and every history read would come
- // back empty. The conformance suite caught exactly this (HP-201).
+ // back empty. The conformance suite caught exactly this.
return { id: e.id, name: e.name.trim(), description: e.description?.trim() ?? '', cwd: realpathSync(resolve(e.cwd)) }
})
}
diff --git a/provider/example-provider/src/jsonl.spec.ts b/provider/example-provider/src/jsonl.spec.ts
index 96eb62e0d..c147cd240 100644
--- a/provider/example-provider/src/jsonl.spec.ts
+++ b/provider/example-provider/src/jsonl.spec.ts
@@ -99,7 +99,7 @@ describe('listSessions', () => {
})
})
-describe('sliceByTime — one A2A task out of a whole Claude session', () => {
+describe('sliceByTime — one turn out of a whole Claude session', () => {
const lines = [
userLine('turn one', '2026-08-04T09:00:00Z'),
assistantLine('reply one', '2026-08-04T09:00:05Z'),
@@ -122,7 +122,7 @@ describe('agent cwd resolution', () => {
it('resolves symlinks, because Claude records the resolved path', () => {
// REGRESSION: on macOS `/tmp` is a symlink to `/private/tmp`. Configuring `/tmp/x` made this
// provider look in `-tmp-x` while Claude wrote `-private-tmp-x`, so every history read came back
- // empty and HP-201 failed against a live agent.
+ // empty and `agent.history` came back empty against a live agent.
const real = join(root, 'real-dir')
const link = join(root, 'link-dir')
mkdirSync(real, { recursive: true })
diff --git a/provider/example-provider/src/jsonl.ts b/provider/example-provider/src/jsonl.ts
index 1c20a71c9..c3b2ef89a 100644
--- a/provider/example-provider/src/jsonl.ts
+++ b/provider/example-provider/src/jsonl.ts
@@ -9,7 +9,7 @@
* by `-`. **It is lossy and not reversible** — never try to un-mangle it; the real working directory
* is carried on the `cwd` field of the lines themselves.
*
- * This is why `GetTask`/`ListTasks` are Tier 0 in the profile and cost this provider nothing: the
+ * This is why `agent.history` is required and costs this provider nothing to store: the
* history already exists on disk. A turn typed straight into a terminal lands here too, so it shows
* up in the session list — it just does not stream live (this app implements no SubscribeToTask).
*
diff --git a/provider/example-provider/src/mapper.spec.ts b/provider/example-provider/src/mapper.spec.ts
index db1dec3d4..94d0a02fc 100644
--- a/provider/example-provider/src/mapper.spec.ts
+++ b/provider/example-provider/src/mapper.spec.ts
@@ -11,28 +11,28 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
-import { messageToParts, pairToolNames, sessionIdOf, streamLineToOutcome, toolResultText, type StreamLine } from './mapper.js'
-import type { Part } from './types.js'
+import { messageToEvents, pairToolNames, sessionIdOf, streamLineToOutcome, toolResultText, type StreamLine } from './mapper.js'
+import type { ProviderEvent } from './types.js'
const FIXTURE = join(import.meta.dirname, '__fixtures__', 'real-turn.jsonl')
-function replay(): { parts: Part[]; sessionId?: string; done?: { failed: boolean; detail?: string } } {
+function replay(): { events: ProviderEvent[]; sessionId?: string; done?: { failed: boolean; detail?: string } } {
const lines = readFileSync(FIXTURE, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l) as StreamLine)
- const parts: Part[] = []
+ const events: ProviderEvent[] = []
let sessionId: string | undefined
let done: { failed: boolean; detail?: string } | undefined
for (const line of lines) {
sessionId ??= sessionIdOf(line)
const outcome = streamLineToOutcome(line)
- if (outcome.kind === 'parts') parts.push(...outcome.parts)
+ if (outcome.kind === 'events') events.push(...outcome.events)
if (outcome.kind === 'done') done = { failed: outcome.failed, detail: outcome.detail }
}
- return { parts: pairToolNames(parts), sessionId, done }
+ return { events: pairToolNames(events), sessionId, done }
}
-const kindsOf = (parts: Part[]): Record<string, number> =>
- parts.reduce<Record<string, number>>((acc, p) => {
- const k = p.metadata?.['autonomous.ai/kind'] ?? '(none)'
+const kindsOf = (events: ProviderEvent[]): Record<string, number> =>
+ events.reduce<Record<string, number>>((acc, p) => {
+ const k = p.kind ?? '(none)'
acc[k] = (acc[k] ?? 0) + 1
return acc
}, {})
@@ -42,38 +42,38 @@ describe('replaying a real recorded turn', () => {
expect(replay().sessionId).toMatch(/^[0-9a-f-]{36}$/)
})
- it('produces a terminal outcome, so HP-102 can be satisfied', () => {
+ it('produces a terminal outcome, so every stream can end exactly once', () => {
const { done } = replay()
expect(done).toBeDefined()
expect(done!.failed).toBe(false)
})
it('emits assistant text', () => {
- const text = replay().parts.filter((p) => p.metadata?.['autonomous.ai/kind'] === 'text_delta').map((p) => p.text).join('')
+ const text = replay().events.filter((p) => p.kind === 'text_delta').map((p) => p.text).join('')
expect(text).toContain('note.txt')
})
it('does NOT swallow every event — regression on the session_id early-return', () => {
// The bug produced exactly zero parts. Any non-trivial count proves the line is still reachable.
- expect(replay().parts.length).toBeGreaterThan(3)
+ expect(replay().events.length).toBeGreaterThan(3)
})
it('emits each tool exactly once — regression on the double tool_use', () => {
- const kinds = kindsOf(replay().parts)
+ const kinds = kindsOf(replay().events)
expect(kinds.tool_start).toBe(1)
expect(kinds.tool_end).toBe(1)
})
it('carries the tool arguments, not the empty ones from content_block_start', () => {
- const start = replay().parts.find((p) => p.metadata?.['autonomous.ai/kind'] === 'tool_start')
- expect(start?.metadata?.['autonomous.ai/tool']).toBe('Read')
- expect(JSON.stringify(start?.metadata?.['autonomous.ai/toolInput'])).toContain('note.txt')
+ const start = replay().events.find((p) => p.kind === 'tool_start')
+ expect(start?.tool).toBe('Read')
+ expect(JSON.stringify(start?.input)).toContain('note.txt')
})
it('pairs a tool_end back to its tool name, which the result block does not carry', () => {
- const end = replay().parts.find((p) => p.metadata?.['autonomous.ai/kind'] === 'tool_end')
- expect(end?.metadata?.['autonomous.ai/tool']).toBe('Read')
- expect(end?.metadata?.['autonomous.ai/toolCallId']).toBeTruthy()
+ const end = replay().events.find((p) => p.kind === 'tool_end')
+ expect(end?.tool).toBe('Read')
+ expect(end?.toolId).toBeTruthy()
})
it('ignores the line types that carry no conversation', () => {
@@ -84,9 +84,9 @@ describe('replaying a real recorded turn', () => {
})
})
-describe('messageToParts — the shape shared by stdout and JSONL', () => {
+describe('messageToEvents — the shape shared by stdout and JSONL', () => {
it('maps thinking, text, tool_use and tool_result', () => {
- const parts = messageToParts({
+ const parts = messageToEvents({
role: 'assistant',
content: [
{ type: 'thinking', thinking: 'weighing it up' },
@@ -98,24 +98,33 @@ describe('messageToParts — the shape shared by stdout and JSONL', () => {
})
it('marks a failed tool result and keeps its id', () => {
- const parts = messageToParts({
+ const events = messageToEvents({
role: 'user',
content: [{ type: 'tool_result', tool_use_id: 'c1', is_error: true, content: 'boom' }],
})
- expect(parts[0]!.metadata?.['autonomous.ai/isError']).toBe(true)
- expect(parts[0]!.metadata?.['autonomous.ai/toolCallId']).toBe('c1')
+ // Note the INVERSION at the boundary: Claude says `is_error: true`, the wire says `ok: false`.
+ expect(events[0]!.ok).toBe(false)
+ expect(events[0]!.toolId).toBe('c1')
+ })
+
+ it('a tool result that did NOT fail is ok:true, not merely un-flagged', () => {
+ const events = messageToEvents({
+ role: 'user',
+ content: [{ type: 'tool_result', tool_use_id: 'c2', content: 'fine' }],
+ })
+ expect(events[0]!.ok).toBe(true)
})
it('skips unknown block types instead of throwing', () => {
// Claude's format is internal and can gain block types; a new one must degrade to "not
// rendered", never to a broken turn.
- expect(() => messageToParts({ role: 'assistant', content: [{ type: 'something_new_in_2027' }] })).not.toThrow()
- expect(messageToParts({ role: 'assistant', content: [{ type: 'something_new_in_2027' }] })).toEqual([])
+ expect(() => messageToEvents({ role: 'assistant', content: [{ type: 'something_new_in_2027' }] })).not.toThrow()
+ expect(messageToEvents({ role: 'assistant', content: [{ type: 'something_new_in_2027' }] })).toEqual([])
})
it('tolerates a missing or non-array content', () => {
- expect(messageToParts(undefined)).toEqual([])
- expect(messageToParts({ role: 'assistant' })).toEqual([])
+ expect(messageToEvents(undefined)).toEqual([])
+ expect(messageToEvents({ role: 'assistant' })).toEqual([])
})
it('normalises tool result content given as blocks or as a string', () => {
diff --git a/provider/example-provider/src/mapper.ts b/provider/example-provider/src/mapper.ts
index 07849fe76..194a228fd 100644
--- a/provider/example-provider/src/mapper.ts
+++ b/provider/example-provider/src/mapper.ts
@@ -1,5 +1,5 @@
/**
- * Claude → A2A. **The single place** Claude's shape becomes the wire format.
+ * Claude → the provider protocol. **The single place** Claude's shape becomes the wire format.
*
* Two callers, one mapper:
* - the LIVE path, reading `--output-format stream-json` off the spawned process's stdout, and
@@ -9,10 +9,12 @@
* way to make the live view and the post-refresh view disagree, so there is exactly one here; only
* the live path adds partial-token deltas on top.
*
- * Metadata keys are defined by `../spec/README.md` §7 and validated by
- * `docs/specs/schema/part-metadata.json`.
+ * Event kinds and fields are defined by `../../spec/README.md` §8 and validated by
+ * `../../spec/schema/event.json`. Note there is no envelope any more: an event is one flat,
+ * self-describing object, and the SAME objects serve the live stream and `agent.history` —
+ * which is precisely why there is one mapper and not two.
*/
-import type { Part, PartMetadata } from './types.js'
+import type { ProviderEvent } from './types.js'
/** An Anthropic content block as it appears in both stdout events and JSONL lines. */
export interface ContentBlock {
@@ -32,21 +34,16 @@ export interface AnthropicMessage {
content?: unknown
}
-export const meta = (kind: NonNullable<PartMetadata['autonomous.ai/kind']>, extra: PartMetadata = {}): PartMetadata => ({
- 'autonomous.ai/kind': kind,
- ...extra,
-})
-
/**
* Does this message BEGIN a turn?
*
- * A real user prompt carries a `user_message` part. A `user`-role message carrying only tool results
+ * A real user prompt carries a `user_message` event. A `user`-role message carrying only tool results
* does NOT — it is the middle of an assistant's turn, wearing the user role because that is how the
- * Anthropic format returns tool output. HP-304 snaps a history window back to one of these so a page
- * can never start between a `tool_start` and its `tool_end`.
+ * Anthropic format returns tool output. A history window snaps back to one of these so a page can
+ * never start between a `tool_start` and its `tool_end`.
*/
-export const isTurnStart = (parts: Part[]): boolean =>
- parts.some((p) => p.metadata?.['autonomous.ai/kind'] === 'user_message')
+export const isTurnStart = (events: ProviderEvent[]): boolean =>
+ events.some((e) => e.kind === 'user_message')
/** Tool results arrive as a string or as an array of text blocks; normalise to one string. */
export function toolResultText(content: unknown): string {
@@ -69,58 +66,56 @@ function summarise(tool: string, output: string, isError: boolean): string {
}
/**
- * Map one Anthropic message to Parts.
+ * Map one Anthropic message to events.
*
* Unknown block types are SKIPPED, never thrown on: Claude's internal format is not a contract we
* control, and a new block type must degrade to "not rendered", not to a broken turn.
*/
-export function messageToParts(message: AnthropicMessage | undefined): Part[] {
+export function messageToEvents(message: AnthropicMessage | undefined): ProviderEvent[] {
const blocks = message?.content
if (typeof blocks === 'string') {
- return blocks.trim() ? [{ text: blocks, metadata: meta(message?.role === 'user' ? 'user_message' : 'text_delta') }] : []
+ return blocks.trim() ? [{ kind: message?.role === 'user' ? 'user_message' : 'text_delta', text: blocks }] : []
}
if (!Array.isArray(blocks)) return []
- const parts: Part[] = []
+ const events: ProviderEvent[] = []
for (const raw of blocks) {
const block = raw as ContentBlock
switch (block.type) {
case 'text':
if (block.text?.trim()) {
- parts.push({ text: block.text, metadata: meta(message?.role === 'user' ? 'user_message' : 'text_delta') })
+ events.push({ kind: message?.role === 'user' ? 'user_message' : 'text_delta', text: block.text })
}
break
case 'thinking':
if (block.thinking?.trim()) {
- parts.push({ text: block.thinking, metadata: meta('thinking_delta') })
+ events.push({ kind: 'thinking_delta', text: block.thinking })
}
break
case 'tool_use':
- parts.push({
- text: '',
- metadata: meta('tool_start', {
- 'autonomous.ai/toolCallId': block.id ?? '',
- 'autonomous.ai/tool': block.name ?? 'tool',
- 'autonomous.ai/toolInput': block.input,
- }),
+ events.push({
+ kind: 'tool_start',
+ toolId: block.id ?? '',
+ tool: block.name ?? 'tool',
+ input: block.input,
})
break
case 'tool_result': {
const output = toolResultText(block.content)
const isError = block.is_error === true
- parts.push({
- text: output.length > MAX_OUTPUT ? `${output.slice(0, MAX_OUTPUT)}…` : output,
- metadata: meta('tool_end', {
- 'autonomous.ai/toolCallId': block.tool_use_id ?? '',
- // The tool NAME lives on the matching tool_use block, not here. Callers that have the
- // pairing fill it in; on its own the result only knows the id.
- 'autonomous.ai/tool': '',
- 'autonomous.ai/isError': isError,
- 'autonomous.ai/summary': summarise('tool', output, isError),
- }),
+ events.push({
+ kind: 'tool_end',
+ toolId: block.tool_use_id ?? '',
+ // The tool NAME lives on the matching tool_use block, not here. Callers that have the
+ // pairing fill it in; on its own the result only knows the id.
+ tool: '',
+ // `ok: false` is the failure signal. Note the inversion from Claude's `is_error`.
+ ok: !isError,
+ output: output.length > MAX_OUTPUT ? `${output.slice(0, MAX_OUTPUT)}…` : output,
+ summary: summarise('tool', output, isError),
})
break
}
@@ -130,37 +125,25 @@ export function messageToParts(message: AnthropicMessage | undefined): Part[] {
break
}
}
- return parts
+ return events
}
/**
- * Fill in tool names on `tool_end` parts by pairing them with earlier `tool_start` parts.
+ * Fill in tool names on `tool_end` events by pairing them with earlier `tool_start` events.
*
* Necessary because a `tool_result` block carries only `tool_use_id`. Run this over a whole
- * transcript, or over the accumulated parts of a live turn.
+ * transcript, or over the accumulated events of a live turn.
*/
-export function pairToolNames(parts: Part[]): Part[] {
+export function pairToolNames(events: ProviderEvent[]): ProviderEvent[] {
const names = new Map<string, string>()
- for (const p of parts) {
- const m = p.metadata
- if (m?.['autonomous.ai/kind'] === 'tool_start' && m['autonomous.ai/toolCallId']) {
- names.set(m['autonomous.ai/toolCallId'], m['autonomous.ai/tool'] ?? 'tool')
- }
+ for (const e of events) {
+ if (e.kind === 'tool_start' && e.toolId) names.set(e.toolId, e.tool ?? 'tool')
}
- return parts.map((p) => {
- const m = p.metadata
- if (m?.['autonomous.ai/kind'] !== 'tool_end') return p
- const id = m['autonomous.ai/toolCallId'] ?? ''
- const tool = names.get(id)
- if (!tool) return p
- return {
- ...p,
- metadata: {
- ...m,
- 'autonomous.ai/tool': tool,
- 'autonomous.ai/summary': summarise(tool, p.text ?? '', m['autonomous.ai/isError'] === true),
- },
- }
+ return events.map((e) => {
+ if (e.kind !== 'tool_end') return e
+ const tool = names.get(e.toolId ?? '')
+ if (!tool) return e
+ return { ...e, tool, summary: summarise(tool, e.output ?? '', e.ok === false) }
})
}
@@ -182,7 +165,7 @@ export interface StreamLine {
}
export type StreamOutcome =
- | { kind: 'parts'; parts: Part[] }
+ | { kind: 'events'; events: ProviderEvent[] }
| { kind: 'done'; failed: boolean; detail?: string }
| { kind: 'ignore' }
@@ -211,10 +194,10 @@ export function streamLineToOutcome(line: StreamLine): StreamOutcome {
if (event?.type === 'content_block_delta') {
const delta = event.delta
if (delta?.type === 'text_delta' && delta.text) {
- return { kind: 'parts', parts: [{ text: delta.text, metadata: meta('text_delta') }] }
+ return { kind: 'events', events: [{ kind: 'text_delta', text: delta.text }] }
}
if (delta?.type === 'thinking_delta' && delta.thinking) {
- return { kind: 'parts', parts: [{ text: delta.thinking, metadata: meta('thinking_delta') }] }
+ return { kind: 'events', events: [{ kind: 'thinking_delta', text: delta.thinking }] }
}
return { kind: 'ignore' }
}
@@ -229,13 +212,13 @@ export function streamLineToOutcome(line: StreamLine): StreamOutcome {
// Deltas already covered text and thinking; take only the tool calls.
const blocks = Array.isArray(line.message?.content) ? (line.message?.content as ContentBlock[]) : []
const tools = blocks.filter((b) => b.type === 'tool_use')
- return tools.length ? { kind: 'parts', parts: messageToParts({ role: 'assistant', content: tools }) } : { kind: 'ignore' }
+ return tools.length ? { kind: 'events', events: messageToEvents({ role: 'assistant', content: tools }) } : { kind: 'ignore' }
}
case 'user': {
const blocks = Array.isArray(line.message?.content) ? (line.message?.content as ContentBlock[]) : []
const results = blocks.filter((b) => b.type === 'tool_result')
- return results.length ? { kind: 'parts', parts: messageToParts({ role: 'user', content: results }) } : { kind: 'ignore' }
+ return results.length ? { kind: 'events', events: messageToEvents({ role: 'user', content: results }) } : { kind: 'ignore' }
}
case 'result':
diff --git a/provider/example-provider/src/recap.ts b/provider/example-provider/src/recap.ts
index 7d3ca7c86..4e2b8d621 100644
--- a/provider/example-provider/src/recap.ts
+++ b/provider/example-provider/src/recap.ts
@@ -1,5 +1,5 @@
/**
- * Per-turn recap — the `session-recap` extension's actual content (HP-302).
+ * Per-turn recap — what `agent.recap` hands back, and what rides the turn's own stream.
*
* The schema calls `recap` a *"headline-style summary of what the turn accomplished"*, and that is a
* different thing from the session title: the title is what the user ASKED, the recap is what the
diff --git a/provider/example-provider/src/server.spec.ts b/provider/example-provider/src/server.spec.ts
index dd995047c..a6030b463 100644
--- a/provider/example-provider/src/server.spec.ts
+++ b/provider/example-provider/src/server.spec.ts
@@ -1,13 +1,14 @@
/**
* The wire, end to end: a real HTTP server, a fake `claude`, and a transcript on disk.
*
- * Two things are pinned here that nothing else can pin:
- * - **HP-212** — the recap rides the turn's OWN stream, immediately before the terminal event. Its
- * position is the whole point: a recap that arrives after the stream closes cannot say which turn
- * it belongs to.
- * - **HP-304** — paging a context. The windows are asserted with exact indices, because the
- * turn-snapping rule (a page may be LONGER than `limit`) is easy to "fix" into a plain slice and
- * only a concrete expectation notices.
+ * Three things are pinned here that nothing else can pin:
+ * - The recap rides the turn's OWN stream, immediately before the terminal frame. Its position is
+ * the whole point: a recap that arrives after the stream closes cannot say which turn it belongs
+ * to.
+ * - The events `agent.history` returns are the ones the stream emitted. Two shapes is how the live
+ * view and the post-refresh view drift apart.
+ * - Windowing a transcript. The cursor is asserted concretely, because "page backwards" is easy to
+ * implement as something that never terminates.
*/
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { chmodSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
@@ -17,12 +18,16 @@ import type { AddressInfo } from 'node:net'
import { createProviderServer } from './server.js'
import { projectDir } from './jsonl.js'
import type { Config } from './config.js'
-import type { Message, Part } from './types.js'
+import type { ProviderEvent } from './types.js'
const ROOT = join(tmpdir(), `example-provider-spec-${process.pid}`)
const AGENT_CWD = join(ROOT, 'agent')
const PROJECTS = join(ROOT, 'projects')
const CLAUDE_SESSION = 'sess-1'
+const TERMINAL = ['turn_completed', 'turn_failed', 'turn_cancelled', 'turn_input_required']
+
+let turnSeq = 0
+const nextTurnId = (): string => `t-${++turnSeq}`
/** A `claude` that prints the given stream-json lines and exits. */
function fakeClaude(name: string, lines: unknown[]): string {
@@ -48,12 +53,9 @@ const resultLine = (failed = false): unknown => ({
function config(claudeBin: string): Config {
return {
- // Three, because the bug this file has to keep out only appears with more than one: a provider
- // that cannot tell which skill a turn belongs to files every conversation under the first.
agents: [
{ id: 'scratch', name: 'Scratch', description: 'test agent', cwd: AGENT_CWD },
{ id: 'agent-2', name: 'Second', description: 'second agent', cwd: AGENT_CWD },
- { id: 'agent-3', name: 'Third', description: 'third agent', cwd: AGENT_CWD },
],
workspaceRoot: ROOT,
agentsFile: join(ROOT, 'agents.json'),
@@ -69,15 +71,11 @@ function config(claudeBin: string): Config {
}
}
-interface SseEvent {
- taskId?: string
- contextId?: string
- status?: { state?: string; message?: Message }
- final?: boolean
-}
-
/** Boot, run one request against it, shut down. Port 0 so tests never collide. */
-async function withServer<T>(claudeBin: string, fn: (port: number, deps: ReturnType<typeof createProviderServer>['deps']) => Promise<T>): Promise<T> {
+async function withServer<T>(
+ claudeBin: string,
+ fn: (port: number, deps: ReturnType<typeof createProviderServer>['deps']) => Promise<T>,
+): Promise<T> {
const { server, deps } = createProviderServer(config(claudeBin))
await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))
const { port } = server.address() as AddressInfo
@@ -91,7 +89,7 @@ async function withServer<T>(claudeBin: string, fn: (port: number, deps: ReturnT
async function rpc<T = Record<string, unknown>>(port: number, method: string, params: unknown): Promise<T> {
const res = await fetch(`http://127.0.0.1:${port}/`, {
method: 'POST',
- headers: { 'content-type': 'application/json', 'x-api-key': 'test-key' },
+ headers: { 'content-type': 'application/json', authorization: 'Bearer test-key' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
})
const body = (await res.json()) as { result?: T; error?: unknown }
@@ -99,24 +97,33 @@ async function rpc<T = Record<string, unknown>>(port: number, method: string, pa
return body.result as T
}
+async function rpcError(port: number, method: string, params: unknown): Promise<string> {
+ const res = await fetch(`http://127.0.0.1:${port}/`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: 'Bearer test-key' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
+ })
+ const body = (await res.json()) as { error?: { code?: string } }
+ return body.error?.code ?? '(no error)'
+}
+
/** Run a turn and collect every SSE event, in order. */
-async function runTurn(port: number, text: string, opts: { contextId?: string; agentId?: string } = {}): Promise<SseEvent[]> {
+async function runTurn(
+ port: number,
+ text: string,
+ opts: { agentId?: string; turnId?: string; attachments?: unknown[] } = {},
+): Promise<ProviderEvent[]> {
const res = await fetch(`http://127.0.0.1:${port}/`, {
method: 'POST',
- headers: { 'content-type': 'application/json', 'x-api-key': 'test-key' },
+ headers: { 'content-type': 'application/json', authorization: 'Bearer test-key' },
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
- method: 'SendStreamingMessage',
+ method: 'agent.send',
params: {
- message: {
- role: 'ROLE_USER',
- messageId: 'm1',
- parts: [{ text }],
- ...(opts.contextId ? { contextId: opts.contextId } : {}),
- // HP-107 — the skill selector A2A has no field for.
- ...(opts.agentId ? { metadata: { 'autonomous.ai/agentId': opts.agentId } } : {}),
- },
+ agentId: opts.agentId ?? 'scratch',
+ turnId: opts.turnId ?? nextTurnId(),
+ message: { text, ...(opts.attachments ? { attachments: opts.attachments } : {}) },
},
}),
})
@@ -125,11 +132,10 @@ async function runTurn(port: number, text: string, opts: { contextId?: string; a
.split('\n\n')
.map((frame) => frame.split('\n').find((l) => l.startsWith('data:')))
.filter((l): l is string => !!l)
- .map((l) => JSON.parse(l.slice(5).trim()) as SseEvent)
+ .map((l) => JSON.parse(l.slice(5).trim()) as ProviderEvent)
}
-const kindsOf = (ev: SseEvent): string[] =>
- (ev.status?.message?.parts ?? []).map((p: Part) => p.metadata?.['autonomous.ai/kind'] ?? '')
+const kinds = (events: ProviderEvent[]): string[] => events.map((e) => e.kind ?? '(none)')
beforeAll(() => {
mkdirSync(AGENT_CWD, { recursive: true })
@@ -137,115 +143,131 @@ beforeAll(() => {
})
afterAll(() => rmSync(ROOT, { recursive: true, force: true }))
-describe('SendStreamingMessage — the recap rides the stream (HP-212)', () => {
- it('brackets the wait with recap_start/recap_end, then ends terminal', async () => {
- const bin = fakeClaude('claude-ok.sh', [textLine('Acme is at 118% of pacing. Nothing else changed.'), resultLine()])
- const events = await withServer(bin, (port) => runTurn(port, 'how is acme pacing?'))
-
- // The order IS the contract: start announces a wait the client cannot otherwise see, end closes
- // it, and the terminal event comes last so HP-102 still reads a terminal state at the tail.
- const kinds = events.flatMap(kindsOf)
- expect(kinds.filter((k) => k === 'recap_start')).toHaveLength(1)
- expect(kinds.filter((k) => k === 'recap_end')).toHaveLength(1)
- expect(events.findIndex((e) => kindsOf(e).includes('recap_start'))).toBe(events.length - 3)
- expect(events.findIndex((e) => kindsOf(e).includes('recap_end'))).toBe(events.length - 2)
-
- const last = events.at(-1)!
- expect(last.status?.state).toBe('TASK_STATE_COMPLETED')
- expect(last.final).toBe(true)
-
- const end = events.at(-2)!
- expect(end.status?.state).toBe('TASK_STATE_WORKING') // must not end the turn twice
- const part = end.status!.message!.parts[0]!
- expect(part.metadata?.['autonomous.ai/recap']).toBe('Acme is at 118% of pacing.')
- expect(part.text).toContain('Nothing else changed.')
+describe('agents', () => {
+ it('serves no descriptor — there is nothing to discover', async () => {
+ await withServer(fakeClaude('claude-desc.sh', [resultLine()]), async (port) => {
+ // The endpoint that used to exist is gone rather than deprecated: a client still fetching it
+ // must fail loudly at integration time instead of reading a stale document.
+ expect((await fetch(`http://127.0.0.1:${port}/.well-known/autonomous-provider.json`)).status).toBe(404)
+ })
})
- it('gives a FAILED turn neither half — a headline would read like an accomplishment', async () => {
- const bin = fakeClaude('claude-fail.sh', [textLine('Started, then hit an error.'), resultLine(true)])
- const events = await withServer(bin, (port) => runTurn(port, 'do the thing'))
-
- const kinds = events.flatMap(kindsOf)
- expect(kinds).not.toContain('recap_start')
- expect(kinds).not.toContain('recap_end')
- expect(events.at(-1)?.status?.state).toBe('TASK_STATE_FAILED')
- expect(events.at(-1)?.final).toBe(true)
+ it('lists agents on an authenticated call — the list is per-credential, so it cannot be public', async () => {
+ await withServer(fakeClaude('claude-list.sh', [resultLine()]), async (port) => {
+ const out = await rpc<{ agents: Array<{ id: string }> }>(port, 'agent.list', {})
+ expect(out.agents.map((a) => a.id)).toEqual(['scratch', 'agent-2'])
+ })
})
- it('closes the indicator even when a silent turn produces no headline', async () => {
- const bin = fakeClaude('claude-silent.sh', [resultLine()])
- const events = await withServer(bin, (port) => runTurn(port, 'be quiet'))
-
- // A `recap_start` without its `recap_end` leaves the client spinning forever, so the end must be
- // there — carrying no headline, which is how it says "nothing to show".
- const kinds = events.flatMap(kindsOf)
- expect(kinds).toContain('recap_start')
- expect(kinds).toContain('recap_end')
- expect(events.at(-2)!.status!.message!.parts[0]!.metadata?.['autonomous.ai/recap']).toBeUndefined()
- expect(events.at(-1)?.status?.state).toBe('TASK_STATE_COMPLETED')
+ it('rejects a bad credential distinguishably from an outage', async () => {
+ await withServer(fakeClaude('claude-auth.sh', [resultLine()]), async (port) => {
+ const res = await fetch(`http://127.0.0.1:${port}/`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: 'Bearer bad-key' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'agent.list', params: {} }),
+ })
+ expect(res.status).toBe(401)
+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe('unauthenticated')
+ })
})
- it('still persists the recap, so GetRecap keeps working for a device with no stream', async () => {
- const bin = fakeClaude('claude-persist.sh', [textLine('Shipped the pacing alert. Details follow.'), resultLine()])
- const entries = await withServer(bin, async (port) => {
- await runTurn(port, 'ship it')
- const out = await rpc<{ entries: Array<{ recap: string; taskId?: string }> }>(port, 'autonomous.GetRecap', { agentId: 'scratch', n: 2 })
- return out.entries
+ it('refuses a send to an agent it does not have', async () => {
+ await withServer(fakeClaude('claude-ghost.sh', [resultLine()]), async (port) => {
+ expect(await rpcError(port, 'agent.send', { agentId: 'ghost', turnId: 't', message: { text: 'hi' } }))
+ .toBe('not_found')
})
- expect(entries).toHaveLength(1)
- expect(entries[0]!.recap).toBe('Shipped the pacing alert.')
- // The pull carries the taskId, which is what lets a client tell THIS turn's recap from the last one.
- expect(entries[0]!.taskId).toBeTruthy()
})
})
-describe('which skill a turn belongs to (HP-107 / HP-204)', () => {
- interface WireTask { id: string; contextId?: string; metadata?: { agentId?: string } }
-
- it('files the turn under the skill the client named, not the first one', async () => {
- // The bug: with no selector the provider falls back to agents[0], so EVERY conversation on a
- // multi-skill provider is attributed to the first skill — and the client, whose session list is
- // scoped to one agent, shows the other agents as empty however much the user talked to them.
- const bin = fakeClaude('claude-agent2.sh', [textLine('Done for the second agent.'), resultLine()])
- const tasks = await withServer(bin, async (port) => {
- await runTurn(port, 'hello agent two', { agentId: 'agent-2' })
- const out = await rpc<{ tasks: WireTask[] }>(port, 'ListTasks', {})
- return out.tasks
+describe('a turn on the wire', () => {
+ it('opens with turn_started and closes with exactly one terminal frame', async () => {
+ const bin = fakeClaude('claude-basic.sh', [textLine('hello there'), resultLine()])
+ await withServer(bin, async (port) => {
+ const events = await runTurn(port, 'hi')
+ expect(events[0]!.kind).toBe('turn_started')
+ expect(events.filter((e) => TERMINAL.includes(e.kind ?? ''))).toHaveLength(1)
+ expect(events.at(-1)!.kind).toBe('turn_completed')
+ expect(kinds(events)).toContain('text_delta')
+ })
+ })
+
+ it('refuses image attachments LOUDLY rather than discarding them', async () => {
+ // Silent loss reads to the user as the agent ignoring what they sent.
+ const bin = fakeClaude('claude-img.sh', [resultLine()])
+ await withServer(bin, async (port) => {
+ const events = await runTurn(port, 'what is this?', { attachments: [{ mediaType: 'image/png', data: 'AAA' }] })
+ expect(events.at(-1)!.kind).toBe('turn_failed')
+ expect(events.at(-1)!.error?.message).toMatch(/image/i)
})
- expect(tasks).toHaveLength(1)
- expect(tasks[0]!.metadata?.agentId).toBe('agent-2')
})
- it('keeps a follow-up on its task’s original skill, whatever the selector says', async () => {
- const bin = fakeClaude('claude-followup.sh', [textLine('First.'), resultLine()])
- const tasks = await withServer(bin, async (port) => {
- const first = await runTurn(port, 'start here', { agentId: 'agent-3' })
- const contextId = first[0]!.contextId!
- // Same conversation, a different skill named. Moving a live context between skills mid-thread
- // would split one chat across two agents in the session list.
- await runTurn(port, 'and again', { contextId, agentId: 'scratch' })
- const out = await rpc<{ tasks: WireTask[] }>(port, 'ListTasks', { contextId })
- return out.tasks
+ it('a cancel BEFORE the turn starts stops it — the point of a client-minted turnId', async () => {
+ const bin = fakeClaude('claude-cancel.sh', [textLine('should never run'), resultLine()])
+ await withServer(bin, async (port) => {
+ const turnId = nextTurnId()
+ await rpc(port, 'turn.cancel', { turnId })
+ const events = await runTurn(port, 'hi', { turnId })
+ expect(events.at(-1)!.kind).toBe('turn_cancelled')
+ expect(kinds(events)).not.toContain('text_delta')
})
- expect(tasks).toHaveLength(2)
- expect(tasks.map((t) => t.metadata?.agentId)).toEqual(['agent-3', 'agent-3'])
})
- it('still answers a plain A2A client that names no skill at all', async () => {
- // HP-107 is a MAY. The conformance runner sends no metadata, and a turn must not fail for it.
- const bin = fakeClaude('claude-noselector.sh', [textLine('Fine.'), resultLine()])
- const tasks = await withServer(bin, async (port) => {
- await runTurn(port, 'no selector')
- const out = await rpc<{ tasks: WireTask[] }>(port, 'ListTasks', {})
- return out.tasks
+ it('accepts a cancel for a turn it has never seen', async () => {
+ await withServer(fakeClaude('claude-c2.sh', [resultLine()]), async (port) => {
+ expect(await rpc<{ cancelled: boolean }>(port, 'turn.cancel', { turnId: 'never' })).toEqual({ cancelled: true })
})
- expect(tasks[0]!.metadata?.agentId).toBe('scratch')
})
})
-describe('autonomous.GetContextHistory — a whole context, paged (HP-304)', () => {
- const CONTEXT = 'ctx-history'
- const TURNS = 6 // → 12 messages: user, assistant, user, assistant, …
+describe('the recap rides the stream', () => {
+ it('brackets the wait with recap_start/recap_end, then ends terminal', async () => {
+ const bin = fakeClaude('claude-recap.sh', [textLine('Rebuilt the index across four shards.'), resultLine()])
+ await withServer(bin, async (port) => {
+ const events = await runTurn(port, 'rebuild it')
+ const order = kinds(events)
+ const start = order.indexOf('recap_start')
+ const end = order.indexOf('recap_end')
+ expect(start).toBeGreaterThan(-1)
+ expect(end).toBeGreaterThan(start)
+ // Both BEFORE the terminal frame: a recap after the stream closes cannot say which turn it is.
+ expect(order.indexOf('turn_completed')).toBeGreaterThan(end)
+ })
+ })
+
+ it('gives a FAILED turn neither half — a headline would read like an accomplishment', async () => {
+ const bin = fakeClaude('claude-fail.sh', [textLine('starting'), resultLine(true)])
+ await withServer(bin, async (port) => {
+ const order = kinds(await runTurn(port, 'go'))
+ expect(order).not.toContain('recap_start')
+ expect(order).not.toContain('recap_end')
+ expect(order.at(-1)).toBe('turn_failed')
+ })
+ })
+
+ it('closes the indicator even when a silent turn produces no headline', async () => {
+ // A recap_start with no recap_end leaves the client spinning forever.
+ const bin = fakeClaude('claude-silent.sh', [resultLine()])
+ await withServer(bin, async (port) => {
+ const order = kinds(await runTurn(port, 'say nothing'))
+ expect(order.filter((k) => k === 'recap_start')).toHaveLength(1)
+ expect(order.filter((k) => k === 'recap_end')).toHaveLength(1)
+ })
+ })
+
+ it('still persists the recap, so agent.recap keeps working for a device with no stream', async () => {
+ const bin = fakeClaude('claude-persist.sh', [textLine('Fixed the rollback path.'), resultLine()])
+ await withServer(bin, async (port) => {
+ await runTurn(port, 'fix it')
+ const out = await rpc<{ recap?: string; turnId?: string }>(port, 'agent.recap', { agentId: 'scratch' })
+ expect(out.recap).toBeTruthy()
+ // The turnId is what lets a client tell THIS turn's recap from the previous one's.
+ expect(out.turnId).toBeTruthy()
+ })
+ })
+})
+
+describe('history', () => {
+ const TURNS = 6 // → 12 events: user, assistant, user, assistant, …
/** A transcript of `TURNS` complete turns, written where the provider looks for it. */
function writeTranscript(): void {
@@ -267,79 +289,110 @@ describe('autonomous.GetContextHistory — a whole context, paged (HP-304)', ()
writeFileSync(join(dir, `${CLAUDE_SESSION}.jsonl`), `${lines.join('\n')}\n`)
}
- /** A server whose store already knows this context — no turn needs to run. */
+ /** A server whose store already knows this agent's Claude session — no turn needs to run. */
async function withHistory<T>(fn: (port: number) => Promise<T>): Promise<T> {
writeTranscript()
return withServer(fakeClaude('claude-unused.sh', [resultLine()]), async (port, deps) => {
- deps.store.ensureContext(CONTEXT, 'scratch')
- deps.store.setClaudeSession(CONTEXT, CLAUDE_SESSION)
+ deps.store.ensureAgent('scratch')
+ deps.store.setClaudeSession('scratch', CLAUDE_SESSION)
return fn(port)
})
}
- interface HistoryResult {
- contextId: string
- messages: Message[]
- hasMore?: boolean
- oldestCursor?: string | null
- staleCursor?: boolean
- }
+ interface History { agentId: string; events: ProviderEvent[]; nextBefore?: string; truncated?: boolean }
- it('returns the WHOLE context — many turns, not the one GetTask would give', async () => {
- const out = await withHistory((port) => rpc<HistoryResult>(port, 'autonomous.GetContextHistory', { contextId: CONTEXT }))
- expect(out.messages).toHaveLength(TURNS * 2)
- expect(out.messages[0]!.messageId).toBe('u0')
- expect(out.messages.at(-1)!.messageId).toBe('a5')
- // No `limit` asked → the paging fields must be ABSENT, not false. Their absence is how a client
- // tells a complete answer from a windowed one.
- expect('hasMore' in out).toBe(false)
- expect('oldestCursor' in out).toBe(false)
+ it('returns the agent’s WHOLE transcript when no window is asked for', async () => {
+ const out = await withHistory((port) => rpc<History>(port, 'agent.history', { agentId: 'scratch' }))
+ expect(out.events).toHaveLength(TURNS * 2)
+ expect(out.events[0]).toMatchObject({ kind: 'user_message', text: 'question 0' })
+ expect(out.events.at(-1)).toMatchObject({ kind: 'text_delta', text: 'answer 5' })
+ // No `limit` asked → no cursor. Its absence is how a client tells a complete answer from a window.
+ expect('nextBefore' in out).toBe(false)
})
- it('windows to the NEWEST messages and snaps the edge back to a turn start', async () => {
- const out = await withHistory((port) =>
- rpc<HistoryResult>(port, 'autonomous.GetContextHistory', { contextId: CONTEXT, limit: 3 }))
- // limit 3 lands mid-turn at index 9 (an assistant reply); snapping back to index 8 makes the
- // window 4 long. Longer than asked, and deliberately so — see HP-304.
- expect(out.messages.map((m) => m.messageId)).toEqual(['u4', 'a4', 'u5', 'a5'])
- expect(out.hasMore).toBe(true)
- expect(out.oldestCursor).toBe('u4')
+ it('windows to the NEWEST events and hands back a cursor', async () => {
+ const out = await withHistory((port) => rpc<History>(port, 'agent.history', { agentId: 'scratch', limit: 4 }))
+ expect(out.events).toHaveLength(4)
+ expect(out.events[0]).toMatchObject({ text: 'question 4' })
+ expect(out.nextBefore).toBeTruthy()
})
- it('pages older with `before`, without overlapping the page already held', async () => {
- const out = await withHistory((port) =>
- rpc<HistoryResult>(port, 'autonomous.GetContextHistory', { contextId: CONTEXT, limit: 3, before: 'u4' }))
- expect(out.messages.map((m) => m.messageId)).toEqual(['u2', 'a2', 'u3', 'a3'])
- expect(out.hasMore).toBe(true)
- expect(out.oldestCursor).toBe('u2')
+ it('pages older with the cursor, without repeating the page already held', async () => {
+ await withHistory(async (port) => {
+ const first = await rpc<History>(port, 'agent.history', { agentId: 'scratch', limit: 4 })
+ const older = await rpc<History>(port, 'agent.history', { agentId: 'scratch', limit: 4, before: first.nextBefore })
+ expect(older.events).toHaveLength(4)
+ expect(older.events.at(-1)).not.toEqual(first.events[0])
+ expect(older.events[0]).toMatchObject({ text: 'question 2' })
+ })
})
- it('reports no further pages once the oldest turn is in the window', async () => {
- const out = await withHistory((port) =>
- rpc<HistoryResult>(port, 'autonomous.GetContextHistory', { contextId: CONTEXT, limit: 3, before: 'u2' }))
- expect(out.messages.map((m) => m.messageId)).toEqual(['u0', 'a0', 'u1', 'a1'])
- expect(out.hasMore).toBe(false)
- expect(out.oldestCursor).toBe('u0')
+ it('omits the cursor once the oldest event is in the window — otherwise paging never ends', async () => {
+ const out = await withHistory((port) => rpc<History>(port, 'agent.history', { agentId: 'scratch', limit: 100 }))
+ expect(out.events).toHaveLength(TURNS * 2)
+ expect(out.nextBefore).toBeUndefined()
})
- it('flags a cursor that is no longer in the transcript instead of erroring', async () => {
- const out = await withHistory((port) =>
- rpc<HistoryResult>(port, 'autonomous.GetContextHistory', { contextId: CONTEXT, limit: 3, before: 'compacted-away' }))
- expect(out.staleCursor).toBe(true)
- expect(out.messages).toEqual([])
- expect(out.hasMore).toBe(false)
- expect(out.oldestCursor).toBeNull()
+ it('clamps an absurd limit rather than trusting the caller', async () => {
+ const out = await withHistory((port) => rpc<History>(port, 'agent.history', { agentId: 'scratch', limit: 10_000 }))
+ expect(out.events).toHaveLength(TURNS * 2)
})
- it('clamps an absurd limit rather than trusting the caller', async () => {
- const out = await withHistory((port) =>
- rpc<HistoryResult>(port, 'autonomous.GetContextHistory', { contextId: CONTEXT, limit: 10_000 }))
- expect(out.messages).toHaveLength(TURNS * 2)
- expect(out.hasMore).toBe(false)
+ it('refuses an unknown agent rather than answering empty', async () => {
+ await withHistory(async (port) => {
+ expect(await rpcError(port, 'agent.history', { agentId: 'ghost' })).toBe('not_found')
+ })
+ })
+
+ it('an agent that has never run has an empty transcript, not an error', async () => {
+ await withHistory(async (port) => {
+ const out = await rpc<History>(port, 'agent.history', { agentId: 'agent-2' })
+ expect(out.events).toEqual([])
+ })
+ })
+})
+
+describe('the method surface', () => {
+ it('answers every method it defines — there are no optional ones to decline', async () => {
+ await withServer(fakeClaude('claude-surface.sh', [resultLine()]), async (port) => {
+ // Nothing is declared anywhere, so this list IS the surface. `agent.send` is exercised
+ // throughout the file; the rest are checked here for "not refused outright".
+ for (const method of ['agent.list', 'agent.history', 'turn.cancel', 'agent.recap']) {
+ expect(await rpcError(port, method, { agentId: 'scratch', turnId: 't-surface' })).not.toBe('unsupported')
+ }
+ })
+ })
+
+ it('creates, renames and deletes agents, and refuses with a REASON rather than `unsupported`', async () => {
+ await withServer(fakeClaude('claude-crud.sh', [resultLine()]), async (port) => {
+ const created = await rpc<{ id: string; name: string }>(port, 'agent.create', { name: 'Made In A Test' })
+ expect(created.id).toBe('made-in-a-test')
+ // Addressable IMMEDIATELY: the list is read from config on every call, never snapshotted.
+ expect(await rpcError(port, 'agent.history', { agentId: created.id })).toBe('(no error)')
+
+ const renamed = await rpc<{ id: string; name: string }>(port, 'agent.rename', { agentId: created.id, name: 'Renamed' })
+ expect(renamed).toMatchObject({ id: created.id, name: 'Renamed' })
+ expect((await rpc<{ deleted: boolean }>(port, 'agent.delete', { agentId: created.id })).deleted).toBe(true)
+
+ // A provider that cannot mutate says so with a message the UI shows the user. `unsupported`
+ // would leave the product with a control it can neither use nor explain.
+ expect(await rpcError(port, 'agent.rename', { agentId: 'ghost', name: 'x' })).toBe('invalid_request')
+ })
})
- it('refuses an unknown context rather than guessing one', async () => {
- await expect(withHistory((port) =>
- rpc(port, 'autonomous.GetContextHistory', { contextId: 'ctx-nope' }))).rejects.toThrow(/-32602|Invalid params/)
+ it('rejects an unknown method', async () => {
+ await withServer(fakeClaude('claude-cap3.sh', [resultLine()]), async (port) => {
+ expect(await rpcError(port, 'nonsense.method', {})).toBe('unsupported')
+ })
+ })
+
+ it('no longer answers the methods this revision removed', async () => {
+ await withServer(fakeClaude('claude-gone.sh', [resultLine()]), async (port) => {
+ // `workspace.*` and `voice.route` were unreachable from the product and are gone. If the web
+ // ever grows a file browser they come back as new methods, not as re-enabled capabilities.
+ for (const method of ['workspace.list', 'workspace.read', 'voice.route']) {
+ expect(await rpcError(port, method, { agentId: 'scratch', transcript: 'hi' })).toBe('unsupported')
+ }
+ })
})
})
diff --git a/provider/example-provider/src/server.ts b/provider/example-provider/src/server.ts
index 1bd8b6c13..e2475042d 100644
--- a/provider/example-provider/src/server.ts
+++ b/provider/example-provider/src/server.ts
@@ -1,50 +1,53 @@
/**
- * A real A2A provider backed by the local `claude` CLI.
+ * A real provider backed by the local `claude` CLI.
*
- * Conforms to `../spec/README.md`; clause IDs (HP-xxx) appear inline. The shape
- * deliberately mirrors `apps/reference-provider/src/server.ts` so the two can be read side by side —
- * that one is scripted, this one is real.
+ * Conforms to `../../spec/README.md`. The shape deliberately mirrors
+ * `reference-provider/src/server.ts` so the two can be read side by side — that one is scripted, this
+ * one is real.
+ *
+ * One agent is one continuous transcript, so one agent maps to one Claude session, resumed on every
+ * turn. There is no session or context here to bridge.
*
* ⚠ Runs Claude with `--dangerously-skip-permissions`. See README.md before pointing it anywhere.
*/
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
-import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
-import { join, normalize, relative, resolve as resolvePath } from 'node:path'
-import { buildAgentCard, EXT } from './agentCard.js'
+import { agentsOf, CREDENTIAL_HEADER } from './agents.js'
import { runTurn } from './claude.js'
import { loadConfig, type AgentEntry, type Config } from './config.js'
import { createAgent, deleteAgent, renameAgent, WorkspaceError } from './workspace.js'
-import { epoch, readTranscript, sliceByTime, type TranscriptLine } from './jsonl.js'
+import { readTranscript, type TranscriptLine } from './jsonl.js'
import { summariseTurn } from './recap.js'
-import { isTurnStart, messageToParts, meta, pairToolNames, sessionIdOf, streamLineToOutcome } from './mapper.js'
-import { SessionStore, type TaskRecord } from './sessions.js'
-import {
- isTerminal,
- RpcErrors,
- TaskState,
- type JsonRpcError,
- type JsonRpcRequest,
- type Message,
- type Part,
- type TaskStateValue,
- type TaskStatusUpdateEvent,
-} from './types.js'
+import { messageToEvents, pairToolNames, sessionIdOf, streamLineToOutcome } from './mapper.js'
+import { SessionStore } from './sessions.js'
+import type { ErrorCode, ProviderEvent, RpcRequest } from './types.js'
+
+/** How long a cancel waits for the send it belongs to. Generous: the client sends within a tick. */
+export const EARLY_CANCEL_TTL_MS = 10 * 60_000
interface Deps {
config: Config
store: SessionStore
- /** Rebuilt whenever the agent list changes — the card IS the capability surface (HP-001). */
- card: Record<string, unknown>
- /** taskId → abort, so CancelTask can stop a running claude (HP-103). */
+ /** turnId → abort, so `turn.cancel` can stop a running claude. */
running: Map<string, AbortController>
+ /**
+ * Turns cancelled BEFORE they started → when the cancel arrived.
+ *
+ * A cancel for a not-yet-started turn must be honoured, which is what makes a client-minted
+ * `turnId` worth anything: a user who presses stop in the first 200 ms would otherwise be
+ * acknowledged by the API and ignored by the engine.
+ *
+ * Timed, because an entry is otherwise only removed by a matching `agent.send` that may never
+ * arrive — a client cancelling turns it never sends would grow this forever.
+ */
+ cancelledEarly: Map<string, number>
}
export function createProviderServer(config: Config): { server: Server; deps: Deps } {
const deps: Deps = {
config,
store: new SessionStore(config.stateFile),
- card: buildAgentCard(config.agents),
running: new Map(),
+ cancelledEarly: new Map(),
}
const server = createServer((req, res) => {
void handle(req, res, deps).catch((err) => {
@@ -59,33 +62,28 @@ export function createProviderServer(config: Config): { server: Server; deps: De
async function handle(req: IncomingMessage, res: ServerResponse, deps: Deps): Promise<void> {
const url = new URL(req.url ?? '/', 'http://localhost')
- // HP-020 — unauthenticated: a client must be able to read the security scheme before satisfying it.
- if (req.method === 'GET' && url.pathname === '/.well-known/agent-card.json') {
- sendJson(res, 200, deps.card)
- return
- }
if (req.method !== 'POST' || url.pathname !== '/') {
sendJson(res, 404, { error: 'not found' })
return
}
- let rpc: JsonRpcRequest
+ let rpc: RpcRequest
try {
- rpc = JSON.parse(await readBody(req)) as JsonRpcRequest
+ rpc = JSON.parse(await readBody(req)) as RpcRequest
} catch {
- sendRpcError(res, null, RpcErrors.PARSE_ERROR)
+ sendError(res, null, 'invalid_request', 'body is not JSON')
return
}
if (!rpc || typeof rpc.method !== 'string') {
- sendRpcError(res, rpc?.id ?? null, RpcErrors.INVALID_REQUEST)
+ sendError(res, rpc?.id ?? null, 'invalid_request', 'no method')
return
}
- // HP-011 / HP-013. This example has no user database: any non-empty key is a tenant, except the
- // literal `bad-key`, which exists so the conformance runner's --bad-key probe has something to hit.
- const credential = header(req, 'x-api-key')
+ // This example has no user database: any non-empty key is a tenant, except the literal `bad-key`,
+ // which exists so the conformance runner's --bad-key probe has something to hit.
+ const credential = bearer(header(req, CREDENTIAL_HEADER))
if (!credential || credential === 'bad-key') {
- sendRpcError(res, rpc.id ?? null, RpcErrors.UNAUTHENTICATED)
+ sendError(res, rpc.id ?? null, 'unauthenticated', 'credential rejected')
return
}
@@ -93,133 +91,76 @@ async function handle(req: IncomingMessage, res: ServerResponse, deps: Deps): Pr
const id = rpc.id ?? null
switch (rpc.method) {
- case 'SendStreamingMessage': return sendStreamingMessage(res, deps, params)
- case 'GetTask': return getTask(res, deps, params, id)
- case 'ListTasks': return listTasks(res, deps, params, id)
- case 'CancelTask': return cancelTask(res, deps, params, id)
-
- // ── Extensions (HP-310: always `autonomous.<Verb>`) ────────────────────────────────────────
- case 'autonomous.ListFiles': return listFiles(res, deps, params, id)
- case 'autonomous.ReadFile': return readFile(res, deps, params, id)
- case 'autonomous.GetRecap': return getRecap(res, deps, params, id)
- case 'autonomous.GetContextHistory': return getContextHistory(res, deps, params, id)
-
- // `workspace-write` — agents only; the card declares params.sessions: false.
- case 'autonomous.CreateAgent':
- case 'autonomous.RenameAgent':
- case 'autonomous.DeleteAgent':
- return workspaceWrite(res, deps, rpc.method, params, id)
-
- // HP-311 — undeclared extension methods MUST be rejected, or the Agent Card means nothing.
- // Session writes would mean editing the user's own Claude transcripts under ~/.claude.
- case 'autonomous.SetSessionTitle':
- case 'autonomous.DeleteSession':
- case 'autonomous.RouteVoice':
- sendRpcError(res, id, RpcErrors.METHOD_NOT_FOUND)
- return
+ case 'agent.list': return sendResult(res, id, { agents: agentsOf(deps.config) })
+ case 'agent.send': return agentSend(res, deps, params)
+ case 'agent.history': return agentHistory(res, deps, params, id)
+ case 'turn.cancel': return turnCancel(res, deps, params, id)
+ case 'agent.recap': return getRecap(res, deps, params, id)
+ case 'agent.create':
+ case 'agent.rename':
+ case 'agent.delete':
+ return mutateAgent(res, deps, rpc.method, params, id)
default:
- sendRpcError(res, id, RpcErrors.METHOD_NOT_FOUND)
+ sendError(res, id, 'unsupported', `unknown method ${rpc.method}`)
}
}
-// ── Agent selection ──────────────────────────────────────────────────────────────────────────────
+const agentById = (deps: Deps, id: string): AgentEntry | undefined => deps.config.agents.find((a) => a.id === id)
-/**
- * Which configured agent a message targets.
- *
- * HP-107 — A2A carries no "which skill" selector on a Message, so the profile puts one in
- * `Message.metadata` as `autonomous.ai/agentId`. Falling back to the first configured agent keeps
- * plain A2A clients (including the conformance runner) working — but it is only ever a fallback: a
- * client that sends nothing gets every conversation filed under the same skill.
- */
-function pickAgent(deps: Deps, message: Message | undefined): AgentEntry {
- const requested = (message as { metadata?: Record<string, unknown> } | undefined)?.metadata?.['autonomous.ai/agentId']
- if (typeof requested === 'string') {
- const found = deps.config.agents.find((a) => a.id === requested)
- if (found) return found
- }
- return deps.config.agents[0]!
-}
+// ── agent.send ───────────────────────────────────────────────────────────────────────────────────
-function agentById(deps: Deps, id: string): AgentEntry | undefined {
- return deps.config.agents.find((a) => a.id === id)
-}
+async function agentSend(res: ServerResponse, deps: Deps, params: Record<string, unknown>): Promise<void> {
+ const agentId = typeof params.agentId === 'string' ? params.agentId : ''
+ const turnId = typeof params.turnId === 'string' ? params.turnId : ''
+ const message = (params.message ?? {}) as { text?: unknown; attachments?: unknown }
+ const text = typeof message.text === 'string' ? message.text.trim() : ''
-// ── SendStreamingMessage (HP-100 … HP-106) ───────────────────────────────────────────────────────
+ if (!turnId) { sendError(res, null, 'invalid_request', 'turnId is required'); return }
+ const agent = agentById(deps, agentId)
+ if (!agent) { sendError(res, null, 'not_found', `no agent ${agentId}`); return }
+ if (!text) { sendError(res, null, 'invalid_request', 'message.text is required'); return }
-async function sendStreamingMessage(res: ServerResponse, deps: Deps, params: Record<string, unknown>): Promise<void> {
- const incoming = params.message as Message | undefined
- if (!incoming || !Array.isArray(incoming.parts)) {
- sendRpcError(res, null, RpcErrors.INVALID_PARAMS)
- return
- }
+ const record = deps.store.ensureAgent(agent.id)
- // HP-106 — images travel as standard Parts. Claude Code's stream-json input does accept image
- // blocks, but wiring that is beyond this example, so refuse LOUDLY rather than drop them silently.
- if (incoming.parts.some((p) => p.raw && p.mediaType?.startsWith('image/'))) {
- openSse(res)
- const taskId = deps.store.nextTaskId()
- writeSse(res, {
- taskId,
- contextId: incoming.contextId ?? 'ctx-image-refused',
- status: {
- state: TaskState.FAILED,
- message: agentMessage(taskId, incoming.contextId ?? '', [{ text: 'This example provider cannot process image attachments.' }]),
- },
- final: true,
- })
- res.end()
- return
- }
+ const emit = (event: ProviderEvent): void => writeSse(res, event)
- const text = incoming.parts.map((p) => p.text ?? '').join('').trim()
- if (!text) {
- sendRpcError(res, null, RpcErrors.INVALID_PARAMS)
- return
- }
+ openSse(res)
- // HP-101 — a follow-up carries the existing taskId; a new chat carries only a contextId.
- const resuming = typeof incoming.taskId === 'string' ? deps.store.task(incoming.taskId) : undefined
- if (incoming.taskId && !resuming) {
- sendRpcError(res, null, RpcErrors.TASK_NOT_FOUND)
+ // A cancel that arrived before this turn started still has to stop it.
+ if (deps.cancelledEarly.delete(turnId)) {
+ emit({ kind: 'turn_cancelled' })
+ res.end()
return
}
- if (resuming && isTerminal(resuming.state)) {
- sendRpcError(res, null, { code: -32004, message: 'Task is in a terminal state' })
+
+ // Images travel as attachments. Claude Code's stream-json input does accept image blocks, but wiring
+ // that is beyond this example, so refuse LOUDLY rather than drop them silently: silent loss reads to
+ // the user as the agent ignoring what they sent.
+ if (Array.isArray(message.attachments) && message.attachments.length) {
+ emit({ kind: 'turn_started', turnId, agentId: agent.id, at: new Date().toISOString() })
+ emit({
+ kind: 'turn_failed',
+ error: { code: 'unsupported', message: 'This example provider cannot process image attachments.' },
+ })
+ res.end()
return
}
- const contextId = resuming?.contextId ?? (typeof incoming.contextId === 'string' && incoming.contextId ? incoming.contextId : `ctx-${Date.now()}`)
- // Which skill runs this turn, most specific first. A conversation belongs to ONE skill for its
- // whole life: the context was bound to one when it was created, and honouring a selector that
- // disagrees would split a single chat across two agents in the client's session list — the client
- // scopes that list to one agent, so half the thread would simply vanish from each.
- const known = deps.store.context(contextId)
- const agent =
- (resuming ? agentById(deps, resuming.agentId) : undefined)
- ?? (known ? agentById(deps, known.agentId) : undefined)
- ?? pickAgent(deps, incoming)
- const context = deps.store.ensureContext(contextId, agent.id)
-
- const taskId = deps.store.nextTaskId()
const startedAt = Date.now()
- deps.store.createTask({
- taskId,
- contextId,
+ deps.store.createTurn({
+ turnId,
agentId: agent.id,
- state: TaskState.WORKING,
startedAt,
title: text.length > 80 ? `${text.slice(0, 77)}…` : text,
})
const controller = new AbortController()
- deps.running.set(taskId, controller)
+ deps.running.set(turnId, controller)
- openSse(res)
- writeSse(res, { taskId, contextId, status: { state: TaskState.WORKING } })
+ emit({ kind: 'turn_started', turnId, agentId: agent.id, at: new Date(startedAt).toISOString() })
- const collected: Part[] = []
+ const collected: ProviderEvent[] = []
let sawResult = false
let failed = false
let failDetail: string | undefined
@@ -230,19 +171,19 @@ async function sendStreamingMessage(res: ServerResponse, deps: Deps, params: Rec
claudeBin: deps.config.claudeBin,
cwd: agent.cwd,
text,
- resumeSessionId: context.claudeSessionId,
+ resumeSessionId: record.claudeSessionId,
model: deps.config.model,
signal: controller.signal,
},
(line) => {
const sid = sessionIdOf(line)
- if (sid) deps.store.setClaudeSession(contextId, sid)
+ if (sid) deps.store.setClaudeSession(agent.id, sid)
const outcome = streamLineToOutcome(line)
- if (outcome.kind === 'parts') {
+ if (outcome.kind === 'events') {
// Pair tool names across everything seen so far, so a tool_end is not left anonymous.
- const paired = pairToolNames([...collected, ...outcome.parts]).slice(collected.length)
- collected.push(...outcome.parts)
- writeSse(res, { taskId, contextId, status: { state: TaskState.WORKING, message: agentMessage(taskId, contextId, paired) } })
+ const paired = pairToolNames([...collected, ...outcome.events]).slice(collected.length)
+ collected.push(...outcome.events)
+ for (const event of paired) emit(event)
return
}
if (outcome.kind === 'done') {
@@ -255,45 +196,43 @@ async function sendStreamingMessage(res: ServerResponse, deps: Deps, params: Rec
)
const { killed } = await handle.done
- deps.running.delete(taskId)
+ deps.running.delete(turnId)
- // HP-102 — a terminal state on EVERY stream. A process that dies without emitting `result` is
- // still a finished turn from the client's point of view, and must be reported as failed rather
- // than leaving the stream hanging.
- let finalState: TaskStateValue = TaskState.COMPLETED
- let finalText: string | undefined
+ // Exactly one terminal frame on EVERY stream. A process that dies without emitting
+ // `result` is still a finished turn from the client's point of view, and must be reported as failed
+ // rather than leaving the stream hanging.
+ let terminal: ProviderEvent = { kind: 'turn_completed' }
if (killed) {
- finalState = TaskState.CANCELED
+ terminal = { kind: 'turn_cancelled' }
} else if (failed) {
- finalState = TaskState.FAILED
- finalText = failDetail ?? 'claude reported an error'
+ terminal = { kind: 'turn_failed', error: { code: 'internal', message: failDetail ?? 'claude reported an error' } }
} else if (!sawResult) {
- finalState = TaskState.FAILED
- finalText = `claude exited without a result${stderr.trim() ? `: ${stderr.trim().slice(0, 500)}` : ''}`
+ terminal = {
+ kind: 'turn_failed',
+ error: { code: 'internal', message: `claude exited without a result${stderr.trim() ? `: ${stderr.trim().slice(0, 500)}` : ''}` },
+ }
}
- deps.store.finishTask(taskId, finalState)
-
- // HP-212 — summarise BEFORE the terminal event, on the stream that is still open, so the recap is
- // unambiguously THIS turn's. The turn therefore stays open for as long as the one-shot takes.
- // That cost buys correctness the pull cannot give: `autonomous.GetRecap` is scoped to an AGENT and
- // takes no task id, so a client asking the instant a turn ends either gets nothing (this turn is
- // not summarised yet) or the PREVIOUS turn's headline. Only a turn that actually completed gets
- // one — summarising a failure produces a headline that reads like an accomplishment.
- if (finalState === TaskState.COMPLETED) await recapTurn(deps, res, taskId, contextId, agent, collected)
-
- writeSse(res, {
- taskId,
- contextId,
- status: { state: finalState, ...(finalText ? { message: agentMessage(taskId, contextId, [{ text: finalText }]) } : {}) },
- final: true,
- })
+ deps.store.finishTurn(turnId, terminal.kind !== 'turn_completed')
+
+ // Summarise BEFORE the terminal frame, on the stream that is still open, so the recap is
+ // unambiguously THIS turn's. The turn therefore stays open for as long as the one-shot takes. That
+ // cost buys correctness the pull cannot give: `agent.recap` is scoped to an AGENT and takes no turn
+ // id, so a client asking the instant a turn ends either gets nothing (this turn is not summarised
+ // yet) or the PREVIOUS turn's headline. Only a turn that actually completed gets one — summarising
+ // a failure produces a headline that reads like an accomplishment.
+ if (terminal.kind === 'turn_completed') await recapTurn(deps, res, turnId, agent, collected)
+
+ // The final assistant text, so a client has one authoritative result to render.
+ const finalText = collected.filter((e) => e.kind === 'text_delta').map((e) => e.text ?? '').join('')
+ if (terminal.kind === 'turn_completed' && finalText) emit({ kind: 'done', text: finalText })
+
+ emit(terminal)
if (!res.destroyed) res.end()
}
/**
- * Summarise one finished turn: push it on the still-open stream (HP-212) AND persist it on the task
- * (HP-302).
+ * Summarise one finished turn: push it on the still-open stream AND persist it.
*
* Both, not either. The stream serves the client watching this turn; the persisted copy serves a
* device restoring its tiles after a reboot, which has no stream to read.
@@ -301,30 +240,16 @@ async function sendStreamingMessage(res: ServerResponse, deps: Deps, params: Rec
async function recapTurn(
deps: Deps,
res: ServerResponse,
- taskId: string,
- contextId: string,
+ turnId: string,
agent: AgentEntry,
- parts: Part[],
+ events: ProviderEvent[],
): Promise<void> {
// The assistant's own words only — thinking and tool output are not what the turn accomplished.
- const turnText = parts
- .filter((p) => p.metadata?.['autonomous.ai/kind'] === 'text_delta')
- .map((p) => p.text ?? '')
- .join('')
-
- // Non-terminal on purpose, both of them: the terminal event is still to come, and HP-102 is
- // satisfied by the LAST event. Emitting either as terminal would end the turn twice.
- const emit = (part: Part): void => {
- writeSse(res, {
- taskId,
- contextId,
- status: { state: TaskState.WORKING, message: agentMessage(taskId, contextId, [part]) },
- })
- }
+ const turnText = events.filter((e) => e.kind === 'text_delta').map((e) => e.text ?? '').join('')
// Announced BEFORE the wait, not after it: summarising is seconds of real time during which the
// turn has stopped speaking, and without this the client has nothing to show for it.
- emit({ text: '', metadata: meta('recap_start') })
+ writeSse(res, { kind: 'recap_start' })
let recap: Awaited<ReturnType<typeof summariseTurn>> = null
try {
@@ -335,325 +260,144 @@ async function recapTurn(
model: deps.config.recapModel,
disabled: deps.config.recapDisabled,
})
- if (recap) deps.store.setRecap(taskId, recap.recap, recap.body)
+ if (recap) deps.store.setRecap(turnId, recap.recap, recap.body)
} catch (err) {
// A recap is a nicety. It must never be able to retroactively fail a turn that succeeded, so the
- // terminal event goes out either way — the caller emits it after this returns.
- console.warn(`[example-provider] recap failed for ${taskId}:`, err instanceof Error ? err.message : String(err))
+ // terminal frame goes out either way — the caller emits it after this returns.
+ console.warn(`[example-provider] recap failed for ${turnId}:`, err instanceof Error ? err.message : String(err))
}
- // ALWAYS, even with nothing to say (HP-212). A `recap_start` with no `recap_end` leaves the client
+ // ALWAYS, even with nothing to say. A `recap_start` with no `recap_end` leaves the client
// spinning on an indicator that will never close — worse than never having opened one.
- emit(recap
- ? { text: recap.body, metadata: meta('recap_end', { 'autonomous.ai/recap': recap.recap }) }
- : { text: '', metadata: meta('recap_end') })
+ writeSse(res, recap ? { kind: 'recap_end', recap: recap.recap, text: recap.body } : { kind: 'recap_end' })
}
-// ── History (HP-200 … HP-202) ────────────────────────────────────────────────────────────────────
+// ── agent.history ────────────────────────────────────────────────────────────────────────────────
+
+const MAX_HISTORY_LIMIT = 500
/**
- * HP-201 — the turn's messages, read back out of Claude's own transcript.
- *
- * Note the slice: the JSONL holds the whole SESSION, while an A2A task is one TURN, so the task's
- * timestamp window selects its share. A task still running has no end bound yet.
+ * The agent's transcript, read back out of Claude's own JSONL and mapped by the SAME mapper the live
+ * path uses. Writing a second parser is the reliable way to make the live view and the post-refresh
+ * view disagree.
*/
-function getTask(res: ServerResponse, deps: Deps, params: Record<string, unknown>, id: string | number | null): void {
- const taskId = typeof params.taskId === 'string' ? params.taskId : ''
- const record = deps.store.task(taskId)
- if (!record) {
- sendRpcError(res, id, RpcErrors.TASK_NOT_FOUND)
- return
- }
- sendRpcResult(res, id, taskToWire(deps, record))
+function transcriptEvents(deps: Deps, agent: AgentEntry): ProviderEvent[] {
+ const sessionId = deps.store.agent(agent.id)?.claudeSessionId
+ if (!sessionId) return []
+ const lines: TranscriptLine[] = readTranscript(deps.config.claudeProjectsDir, agent.cwd, sessionId)
+ return pairToolNames(lines.flatMap((line) => messageToEvents(line.message)))
}
-/** HP-200 — grouping by contextId is what backs the session list. */
-function listTasks(res: ServerResponse, deps: Deps, params: Record<string, unknown>, id: string | number | null): void {
- const contextId = typeof params.contextId === 'string' ? params.contextId : undefined
- const tasks = deps.store.tasks(contextId).map((t) => taskToWire(deps, t, { history: false }))
- sendRpcResult(res, id, { tasks })
-}
+function agentHistory(res: ServerResponse, deps: Deps, params: Record<string, unknown>, id: RpcRequest['id']): void {
+ const agent = agentById(deps, String(params.agentId ?? ''))
+ if (!agent) { sendError(res, id ?? null, 'not_found', 'no such agent'); return }
-/**
- * Transcript lines → A2A Messages.
- *
- * Tool names are paired across the WHOLE run rather than inside one line: a `tool_result` lands on a
- * different transcript line than its `tool_use`, so pairing line by line leaves every `tool_end`
- * anonymous. Lines that map to nothing renderable (an image block, a bare stop) are dropped.
- */
-function linesToMessages(lines: TranscriptLine[], contextId: string, taskId?: string): Message[] {
- const perLine = lines.map((line) => messageToParts(line.message))
- const paired = pairToolNames(perLine.flat())
- const out: Message[] = []
- let cut = 0
- for (const [index, parts] of perLine.entries()) {
- const mine = paired.slice(cut, cut + parts.length)
- cut += parts.length
- if (!mine.length) continue
- const line = lines[index]!
- out.push({
- role: line.type === 'user' ? 'ROLE_USER' : 'ROLE_AGENT',
- messageId: line.uuid ?? '',
- ...(taskId ? { taskId } : {}),
- contextId,
- parts: mine,
- })
- }
- return out
-}
+ const all = transcriptEvents(deps, agent)
+ const rawLimit = typeof params.limit === 'number' ? params.limit : Number(params.limit)
+ const limit = Number.isFinite(rawLimit) && rawLimit > 0 ? Math.min(Math.floor(rawLimit), MAX_HISTORY_LIMIT) : undefined
+ const before = typeof params.before === 'string' && params.before ? params.before : undefined
-function taskToWire(deps: Deps, record: TaskRecord, opts: { history?: boolean } = {}): Record<string, unknown> {
- const withHistory = opts.history !== false
- let history: Message[] = []
- if (withHistory) {
- const context = deps.store.context(record.contextId)
- const agent = agentById(deps, record.agentId)
- if (context?.claudeSessionId && agent) {
- const lines = sliceByTime(
- readTranscript(deps.config.claudeProjectsDir, agent.cwd, context.claudeSessionId),
- record.startedAt - 5_000, // Claude timestamps the line slightly before we record the task
- record.endedAt ? record.endedAt + 5_000 : undefined,
- )
- history = linesToMessages(lines, record.contextId, record.taskId)
- }
- }
- return {
- id: record.taskId,
- contextId: record.contextId,
- status: { state: record.state },
- history,
- // `startedAt`/`endedAt` so a client can order and date a session from real events. Without them
- // it can only stamp "now" on every row, which sorts a session list at random (HP-220: omit
- // rather than invent — a task still running genuinely has no end).
- metadata: {
- title: record.title,
- agentId: record.agentId,
- startedAt: new Date(record.startedAt).toISOString(),
- ...(record.endedAt ? { endedAt: new Date(record.endedAt).toISOString() } : {}),
- },
- }
-}
+ // The cursor is an INDEX into this agent's transcript, opaque to the client. It is derived rather
+ // than stored on the event, because the objects handed back must be the ones the stream emitted.
+ const cutoff = before ? Number(before.replace(/^evt_/, '')) : all.length
+ const eligible = all.slice(0, Number.isFinite(cutoff) ? cutoff : all.length)
-/** HP-103 — cancelling stops the process AND its tool subprocesses; the stream then terminates. */
-function cancelTask(res: ServerResponse, deps: Deps, params: Record<string, unknown>, id: string | number | null): void {
- const taskId = typeof params.taskId === 'string' ? params.taskId : ''
- const record = deps.store.task(taskId)
- if (!record) {
- sendRpcError(res, id, RpcErrors.TASK_NOT_FOUND)
- return
- }
- if (isTerminal(record.state)) {
- sendRpcError(res, id, RpcErrors.TASK_NOT_CANCELABLE)
+ if (!limit) {
+ sendResult(res, id ?? null, { agentId: agent.id, events: eligible, truncated: false })
return
}
- deps.running.get(taskId)?.abort()
- deps.running.delete(taskId)
- deps.store.finishTask(taskId, TaskState.CANCELED)
- sendRpcResult(res, id, taskToWire(deps, deps.store.task(taskId)!, { history: false }))
-}
-
-// ── Extension: workspace-files (HP-300) ──────────────────────────────────────────────────────────
-
-/** Resolve a wire path inside the agent's cwd, or throw. Path traversal is the obvious attack here. */
-function safeJoin(root: string, rel: string): string {
- const target = resolvePath(root, normalize(rel))
- const inside = relative(root, target)
- if (inside.startsWith('..') || resolvePath(root, inside) !== target) throw new Error('path escapes the agent directory')
- return target
+ const startAt = Math.max(0, eligible.length - limit)
+ sendResult(res, id ?? null, {
+ agentId: agent.id,
+ events: eligible.slice(startAt),
+ // Present only when older events remain. Its ABSENCE is how the client knows it reached the start.
+ ...(startAt > 0 ? { nextBefore: `evt_${startAt}` } : {}),
+ truncated: false,
+ })
}
-function listFiles(res: ServerResponse, deps: Deps, params: Record<string, unknown>, id: string | number | null): void {
- const agent = agentById(deps, String(params.agentId ?? ''))
- if (!agent) { sendRpcError(res, id, RpcErrors.INVALID_PARAMS); return }
- let dir: string
- try {
- dir = params.path ? safeJoin(agent.cwd, String(params.path)) : agent.cwd
- } catch {
- sendRpcError(res, id, RpcErrors.INVALID_PARAMS)
- return
+// ── turn.cancel ──────────────────────────────────────────────────────────────────────────────────
+
+/** Always accepted: the client mints `turnId` before sending and may well cancel first. */
+function turnCancel(res: ServerResponse, deps: Deps, params: Record<string, unknown>, id: RpcRequest['id']): void {
+ const turnId = typeof params.turnId === 'string' ? params.turnId : ''
+ if (!turnId) { sendError(res, id ?? null, 'invalid_request', 'turnId is required'); return }
+ const live = deps.running.get(turnId)
+ if (live) {
+ // Kills the process group, so the tools it started die with it.
+ live.abort()
+ deps.running.delete(turnId)
+ } else {
+ // Swept here, the one place it can grow: a send that has not arrived within the window is not
+ // coming, and an unmatched cancel must not be a slow memory leak.
+ const now = Date.now()
+ for (const [id, at] of deps.cancelledEarly) if (now - at > EARLY_CANCEL_TTL_MS) deps.cancelledEarly.delete(id)
+ deps.cancelledEarly.set(turnId, now)
}
- if (!existsSync(dir) || !statSync(dir).isDirectory()) { sendRpcError(res, id, RpcErrors.INVALID_PARAMS); return }
- const files = readdirSync(dir, { withFileTypes: true })
- .filter((e) => !e.name.startsWith('.'))
- .slice(0, 500)
- .map((e) => {
- const node: Record<string, unknown> = { name: e.name, type: e.isDirectory() ? 'dir' : 'file' }
- if (!e.isDirectory()) { try { node.size = statSync(join(dir, e.name)).size } catch { /* ignore */ } }
- return node
- })
- sendRpcResult(res, id, { files })
+ sendResult(res, id ?? null, { cancelled: true })
}
-const MAX_FILE_BYTES = 512 * 1024
+// ── agent.recap ──────────────────────────────────────────────────────────────────────────────────
-function readFile(res: ServerResponse, deps: Deps, params: Record<string, unknown>, id: string | number | null): void {
+function getRecap(res: ServerResponse, deps: Deps, params: Record<string, unknown>, id: RpcRequest['id']): void {
const agent = agentById(deps, String(params.agentId ?? ''))
- const path = typeof params.path === 'string' ? params.path : ''
- if (!agent || !path) { sendRpcError(res, id, RpcErrors.INVALID_PARAMS); return }
- let file: string
- try {
- file = safeJoin(agent.cwd, path)
- } catch {
- sendRpcError(res, id, RpcErrors.INVALID_PARAMS)
- return
- }
- if (!existsSync(file) || !statSync(file).isFile()) { sendRpcError(res, id, RpcErrors.INVALID_PARAMS); return }
- const raw = readFileSync(file, 'utf8')
- const truncated = raw.length > MAX_FILE_BYTES
- // Truncation is REPORTED, never silent — the same rule HP-203 sets for transcripts.
- sendRpcResult(res, id, { path, content: truncated ? raw.slice(0, MAX_FILE_BYTES) : raw, ...(truncated ? { truncated: true } : {}) })
+ if (!agent) { sendError(res, id ?? null, 'not_found', 'no such agent'); return }
+ // NO `recap` field before anything has been summarised: the device then shows nothing rather than
+ // stale text. What goes out is the same object `recap_end` pushes on the turn's own stream.
+ const last = deps.store.lastRecap(agent.id)
+ sendResult(res, id ?? null, {
+ agentId: agent.id,
+ ...(last ? {
+ recap: last.recap!,
+ ...(last.body ? { text: last.body } : {}),
+ // The turnId is what lets a client tell THIS turn's recap from the previous one's.
+ turnId: last.turnId,
+ } : {}),
+ })
}
-/** HP-301 — agent create / rename / delete, all contained under the workspace root. */
-function workspaceWrite(
+// ── agent.create / rename / delete ───────────────────────────────────────────────────────────────
+
+/**
+ * An agent here IS a directory, so these really do write to disk.
+ *
+ * A provider whose agents are managed elsewhere is free to answer `invalid_request` with a message
+ * instead — that message is shown to the user, which beats a control that silently does nothing.
+ */
+function mutateAgent(
res: ServerResponse,
deps: Deps,
method: string,
params: Record<string, unknown>,
- id: string | number | null,
+ id: RpcRequest['id'],
): void {
try {
- if (method === 'autonomous.CreateAgent') {
+ if (method === 'agent.create') {
const entry = createAgent(deps.config, String(params.name ?? ''), String(params.description ?? ''))
- // The card is BUILT from the agent list, so it has to be rebuilt for the new agent to be
- // discoverable at all — the card is the capability surface (HP-001).
- deps.card = buildAgentCard(deps.config.agents)
- sendRpcResult(res, id, { id: entry.id, name: entry.name, description: entry.description })
+ sendResult(res, id ?? null, { id: entry.id, name: entry.name, description: entry.description ?? '' })
return
}
- if (method === 'autonomous.RenameAgent') {
+ if (method === 'agent.rename') {
const entry = renameAgent(deps.config, String(params.agentId ?? ''), String(params.name ?? ''))
- deps.card = buildAgentCard(deps.config.agents)
- sendRpcResult(res, id, { id: entry.id, name: entry.name, description: entry.description })
+ sendResult(res, id ?? null, { id: entry.id, name: entry.name, description: entry.description ?? '' })
return
}
deleteAgent(deps.config, String(params.agentId ?? ''))
- deps.card = buildAgentCard(deps.config.agents)
- sendRpcResult(res, id, { ok: true })
+ sendResult(res, id ?? null, { deleted: true })
} catch (err) {
- if (err instanceof WorkspaceError) { sendRpcError(res, id, { code: -32602, message: err.message }); return }
+ if (err instanceof WorkspaceError) { sendError(res, id ?? null, 'invalid_request', err.message); return }
throw err
}
}
-// ── Extension: session-recap (HP-302) ────────────────────────────────────────────────────────────
-
-/**
- * Recent turns for the device's tiles.
- *
- * Served from the task records, which is what makes these PER TURN — the unit HP-302 asks for. An
- * earlier version listed recent *sessions* and used each one's title, which was wrong twice over:
- * a session is not a turn, and a title is what the user ASKED rather than what the turn accomplished.
- *
- * `contextId` is the A2A context the client minted, never Claude's own session id. A client uses it
- * to reopen the conversation, so handing back an id we never issued would simply not resolve.
- */
-function getRecap(res: ServerResponse, deps: Deps, params: Record<string, unknown>, id: string | number | null): void {
- const agent = agentById(deps, String(params.agentId ?? ''))
- if (!agent) { sendRpcError(res, id, RpcErrors.INVALID_PARAMS); return }
- const n = Math.max(1, Math.min(5, Number(params.n) || 2))
- // Empty until a turn has been summarised — which the schema calls correct. The device shows
- // nothing rather than resurrecting stale text.
- const entries = deps.store.recentRecaps(agent.id, n).map((t) => ({
- recap: t.recap!,
- body: t.body,
- contextId: t.contextId,
- taskId: t.taskId,
- timestamp: new Date(t.endedAt ?? t.startedAt).toISOString(),
- }))
- sendRpcResult(res, id, { agentId: agent.id, entries })
-}
-
-// ── Extension: context-history (HP-304) ──────────────────────────────────────────────────────────
-
-/** The window ceiling. The client asks for 60; this only stops a caller asking for the moon. */
-const MAX_HISTORY_LIMIT = 500
-
-/**
- * A whole context's transcript, optionally windowed.
- *
- * Why this exists next to `GetTask`: a task is one TURN, but a client opening a chat wants the
- * CONTEXT, which is many turns. Reading the transcript whole also removes the per-task time-window
- * slicing, so nothing can fall into a gap between two turns' windows.
- */
-function getContextHistory(res: ServerResponse, deps: Deps, params: Record<string, unknown>, id: string | number | null): void {
- const contextId = typeof params.contextId === 'string' ? params.contextId : ''
- const context = contextId ? deps.store.context(contextId) : undefined
- const agent = context ? agentById(deps, context.agentId) : undefined
- if (!context || !agent) {
- sendRpcError(res, id, RpcErrors.INVALID_PARAMS)
- return
- }
-
- // No claude session id yet = a context nobody has spoken in. Empty is the correct answer.
- const all = linesToMessages(
- context.claudeSessionId ? readTranscript(deps.config.claudeProjectsDir, agent.cwd, context.claudeSessionId) : [],
- contextId,
- )
-
- // No `limit` = the complete transcript, and then NONE of the paging fields are emitted: their
- // absence is exactly how the client tells a windowed answer from a whole one.
- const raw = params.limit
- const limit = typeof raw === 'number' && raw > 0 ? Math.min(Math.floor(raw), MAX_HISTORY_LIMIT) : undefined
- if (!limit) {
- sendRpcResult(res, id, { contextId, messages: all })
- return
- }
-
- let end = all.length
- const before = typeof params.before === 'string' && params.before ? params.before : undefined
- if (before) {
- const at = all.findIndex((m) => m.messageId === before)
- if (at < 0) {
- // The cursor is no longer in the transcript — a compaction moved it out from under the client
- // between requests. Say so instead of erroring or quietly answering a different window: the
- // client's recovery is a full reload, and it can only do that if it is told.
- sendRpcResult(res, id, { contextId, messages: [], hasMore: false, oldestCursor: null, staleCursor: true })
- return
- }
- end = at // exclusive — the client already holds this one
- }
-
- const start = snapToTurnStart(all, Math.max(0, end - limit))
- const oldestCursor = all[start]?.messageId || null
- sendRpcResult(res, id, {
- contextId,
- messages: all.slice(start, end),
- // A page we cannot name a cursor for is a page the client could never ask for; promising one
- // would loop it on the same window forever. Claude always writes a uuid, so this is a guard
- // rather than a case.
- hasMore: start > 0 && !!oldestCursor,
- oldestCursor,
- })
-}
-
-/**
- * Walk the window's left edge back to the message that STARTS a turn.
- *
- * Without this a page can begin between a `tool_start` and its `tool_end`, and the client renders a
- * result with no call above it. The cost is that a window may come back longer than `limit` — which
- * is why HP-304 calls `limit` a floor rather than a count.
- */
-function snapToTurnStart(messages: Message[], from: number): number {
- for (let i = from; i > 0; i--) {
- if (isTurnStart(messages[i]!.parts)) return i
- }
- return 0
-}
-
// ── Wire helpers ─────────────────────────────────────────────────────────────────────────────────
-function agentMessage(taskId: string, contextId: string, parts: Part[]): Message {
- return { role: 'ROLE_AGENT', messageId: `m-${Date.now()}-${Math.round(epoch(undefined))}`, taskId, contextId, parts }
-}
-
function openSse(res: ServerResponse): void {
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' })
}
-function writeSse(res: ServerResponse, event: TaskStatusUpdateEvent): void {
- if (res.destroyed) return
- res.write(`event: status-update\ndata: ${JSON.stringify(event)}\n\n`)
+function writeSse(res: ServerResponse, event: ProviderEvent): void {
+ if (!res.destroyed) res.write(`data: ${JSON.stringify(event)}\n\n`)
}
function sendJson(res: ServerResponse, status: number, body: unknown): void {
@@ -662,12 +406,21 @@ function sendJson(res: ServerResponse, status: number, body: unknown): void {
res.end(payload)
}
-function sendRpcResult(res: ServerResponse, id: string | number | null, result: unknown): void {
- sendJson(res, 200, { jsonrpc: '2.0', id, result })
+const sendResult = (res: ServerResponse, id: RpcRequest['id'], result: unknown): void =>
+ sendJson(res, 200, { jsonrpc: '2.0', id: id ?? null, result })
+
+/** `unauthenticated` also carries HTTP 401, so a client that never parses the body can still tell a
+ * rejected credential from an outage. */
+function sendError(res: ServerResponse, id: RpcRequest['id'], code: ErrorCode, message?: string): void {
+ const status = code === 'unauthenticated' ? 401 : 200
+ sendJson(res, status, { jsonrpc: '2.0', id: id ?? null, error: { code, ...(message ? { message } : {}) } })
}
-function sendRpcError(res: ServerResponse, id: string | number | null, error: JsonRpcError): void {
- sendJson(res, error.code === RpcErrors.UNAUTHENTICATED.code ? 401 : 200, { jsonrpc: '2.0', id, error })
+/** `Authorization: Bearer <credential>` — one header, by convention rather than by declaration. */
+function bearer(value: string | undefined): string | undefined {
+ if (!value) return undefined
+ const match = /^Bearer\s+(.+)$/i.exec(value.trim())
+ return match ? match[1] : value
}
function header(req: IncomingMessage, name: string): string | undefined {
@@ -676,47 +429,28 @@ function header(req: IncomingMessage, name: string): string | undefined {
}
async function readBody(req: IncomingMessage): Promise<string> {
- const chunks: Buffer[] = []
- let size = 0
- for await (const chunk of req) {
- size += (chunk as Buffer).length
- if (size > 5 * 1024 * 1024) throw new Error('body too large')
- chunks.push(chunk as Buffer)
- }
- return Buffer.concat(chunks).toString('utf8')
+ let body = ''
+ for await (const chunk of req) body += chunk
+ return body
}
// ── Entry point ──────────────────────────────────────────────────────────────────────────────────
export function start(config = loadConfig(), port = config.port): Promise<{ url: string; close: () => Promise<void> }> {
- const { server, deps } = createProviderServer(config)
+ const { server } = createProviderServer(config)
return new Promise((resolve) => {
- server.listen(port, () => {
- const address = server.address()
- const actual = typeof address === 'object' && address ? address.port : port
- resolve({
- url: `http://127.0.0.1:${actual}`,
- close: () =>
- new Promise<void>((done) => {
- for (const c of deps.running.values()) c.abort()
- server.close(() => done())
- }),
- })
+ server.listen(port, '127.0.0.1', () => {
+ const addr = server.address()
+ const url = `http://127.0.0.1:${typeof addr === 'object' && addr ? addr.port : port}`
+ resolve({ url, close: () => new Promise<void>((r) => server.close(() => r())) })
})
})
}
if (process.argv[1] && import.meta.url === `file://${process.argv[1]}`) {
- try {
- const config = loadConfig()
- void start(config).then(({ url }) => {
- console.log(`[example-provider] listening on ${url}`)
- console.log(`[example-provider] claude: ${config.claudeBin}`)
- console.log(`[example-provider] agents: ${config.agents.map((a) => `${a.id} → ${a.cwd}`).join(', ')}`)
- console.log('[example-provider] ⚠ running with --dangerously-skip-permissions')
- })
- } catch (err) {
- console.error(`[example-provider] ${err instanceof Error ? err.message : String(err)}`)
- process.exit(1)
- }
+ const config = loadConfig()
+ void start(config).then(({ url }) => {
+ console.log(`[example-provider] ${url} · POST / with \`Authorization: Bearer <credential>\``)
+ console.log(`[example-provider] ${config.agents.length} agent(s): ${config.agents.map((a) => a.id).join(', ')}`)
+ })
}
diff --git a/provider/example-provider/src/sessions.ts b/provider/example-provider/src/sessions.ts
index 7ed502e2e..5b5b1597a 100644
--- a/provider/example-provider/src/sessions.ts
+++ b/provider/example-provider/src/sessions.ts
@@ -1,50 +1,47 @@
/**
* The identity bridge, persisted to `sessions.json`.
*
- * The client mints `contextId` (HP-101); Claude assigns its own session id on the first turn. One
- * map bridges them so `--resume` works across turns and across restarts of this process.
+ * One agent is one continuous transcript, so one agent maps to **one Claude session**, resumed on
+ * every turn with `--resume`. That is the whole bridge: agentId → claudeSessionId, surviving restarts
+ * of this process.
*
- * Task records exist because A2A's `taskId` is one TURN while Claude's transcript is a whole
- * SESSION. The timestamp window is what lets `GetTask` slice one turn back out of the JSONL.
+ * Turn records exist because a recap is per-TURN while Claude's transcript is a whole session. The
+ * timestamp window on each record is what lets a turn be sliced back out of the JSONL.
*/
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
import { dirname } from 'node:path'
-import type { TaskStateValue } from './types.js'
-export interface TaskRecord {
- taskId: string
- contextId: string
+export interface TurnRecord {
+ turnId: string
agentId: string
- state: TaskStateValue
startedAt: number
endedAt?: number
- /** First user text of the turn — the session title projection (spec §10.4). */
+ failed?: boolean
+ /** First user text of the turn. */
title: string
/**
- * Headline of what this turn ACCOMPLISHED (HP-302). Absent until the turn has been summarised, and
+ * Headline of what this turn ACCOMPLISHED. Absent until the turn has been summarised, and
* absent forever on a turn that failed — deliberately NOT the same thing as `title`, which is what
* the user asked.
*/
recap?: string
- /** The fuller summary behind the headline; `recapEntry.body` on the wire. */
+ /** The fuller summary behind the headline; `text` on the wire. */
body?: string
}
-export interface ContextRecord {
- contextId: string
+export interface AgentRecord {
agentId: string
/** Absent until Claude reports one on the first turn. */
claudeSessionId?: string
}
interface StateFile {
- contexts: Record<string, ContextRecord>
- tasks: Record<string, TaskRecord>
+ agents: Record<string, AgentRecord>
+ turns: Record<string, TurnRecord>
}
export class SessionStore {
- private state: StateFile = { contexts: {}, tasks: {} }
- private seq = 0
+ private state: StateFile = { agents: {}, turns: {} }
constructor(private readonly file: string) {
this.load()
@@ -54,16 +51,11 @@ export class SessionStore {
if (!existsSync(this.file)) return
try {
const parsed = JSON.parse(readFileSync(this.file, 'utf8')) as Partial<StateFile>
- this.state = { contexts: parsed.contexts ?? {}, tasks: parsed.tasks ?? {} }
- // Continue the id sequence past anything already on disk, so a restart cannot reuse an id.
- for (const id of Object.keys(this.state.tasks)) {
- const n = Number(id.replace(/^task-/, ''))
- if (Number.isFinite(n)) this.seq = Math.max(this.seq, n)
- }
+ this.state = { agents: parsed.agents ?? {}, turns: parsed.turns ?? {} }
} catch {
// A corrupt state file must not stop the provider from serving new turns; history for the
- // affected contexts is lost, which is visible, whereas refusing to boot is not.
- this.state = { contexts: {}, tasks: {} }
+ // affected agents is lost, which is visible, whereas refusing to boot is not.
+ this.state = { agents: {}, turns: {} }
}
}
@@ -75,79 +67,70 @@ export class SessionStore {
renameSync(tmp, this.file)
}
- nextTaskId(): string {
- return `task-${++this.seq}`
+ agent(agentId: string): AgentRecord | undefined {
+ return this.state.agents[agentId]
}
- context(contextId: string): ContextRecord | undefined {
- return this.state.contexts[contextId]
- }
-
- ensureContext(contextId: string, agentId: string): ContextRecord {
- const existing = this.state.contexts[contextId]
+ ensureAgent(agentId: string): AgentRecord {
+ const existing = this.state.agents[agentId]
if (existing) return existing
- const created: ContextRecord = { contextId, agentId }
- this.state.contexts[contextId] = created
+ const created: AgentRecord = { agentId }
+ this.state.agents[agentId] = created
this.save()
return created
}
- setClaudeSession(contextId: string, claudeSessionId: string): void {
- const ctx = this.state.contexts[contextId]
- if (!ctx || ctx.claudeSessionId === claudeSessionId) return
- ctx.claudeSessionId = claudeSessionId
+ setClaudeSession(agentId: string, claudeSessionId: string): void {
+ const record = this.state.agents[agentId]
+ if (!record || record.claudeSessionId === claudeSessionId) return
+ record.claudeSessionId = claudeSessionId
this.save()
}
- createTask(task: TaskRecord): void {
- this.state.tasks[task.taskId] = task
+ createTurn(turn: TurnRecord): void {
+ this.state.turns[turn.turnId] = turn
this.save()
}
- finishTask(taskId: string, state: TaskStateValue): void {
- const task = this.state.tasks[taskId]
- if (!task) return
- task.state = state
- task.endedAt = Date.now()
+ finishTurn(turnId: string, failed: boolean): void {
+ const turn = this.state.turns[turnId]
+ if (!turn) return
+ turn.failed = failed
+ turn.endedAt = Date.now()
this.save()
}
- task(taskId: string): TaskRecord | undefined {
- return this.state.tasks[taskId]
+ turn(turnId: string): TurnRecord | undefined {
+ return this.state.turns[turnId]
}
- /** Newest first. Filtered by context when given one. */
- tasks(contextId?: string): TaskRecord[] {
- return Object.values(this.state.tasks)
- .filter((t) => !contextId || t.contextId === contextId)
+ /** Newest first, for one agent. */
+ turns(agentId: string): TurnRecord[] {
+ return Object.values(this.state.turns)
+ .filter((t) => t.agentId === agentId)
.sort((a, b) => b.startedAt - a.startedAt)
}
- /** Contexts belonging to one agent, used to answer ListTasks scoped to an agent. */
- contextsForAgent(agentId: string): ContextRecord[] {
- return Object.values(this.state.contexts).filter((c) => c.agentId === agentId)
- }
-
- /** Attach a summary to a finished turn. Persisted, because HP-302 says "persisted". */
- setRecap(taskId: string, recap: string, body: string): void {
- const task = this.state.tasks[taskId]
- if (!task || !recap) return
- task.recap = recap
- task.body = body
+ /** Attach a summary to a finished turn. Persisted, so a device restoring tiles has no stream to need. */
+ setRecap(turnId: string, recap: string, body: string): void {
+ const turn = this.state.turns[turnId]
+ if (!turn || !recap) return
+ turn.recap = recap
+ turn.body = body
this.save()
}
/**
* The most recent SUMMARISED turns for one agent, newest first.
*
- * Per TURN, not per session: HP-302 is "short persisted per-turn summaries", and a session can
- * hold dozens of turns. Turns still running, and turns that failed, carry no recap and are simply
- * not here — an empty array before anything has been summarised is the correct answer.
+ * Turns still running, and turns that failed, carry no recap and are simply not here — an empty
+ * array before anything has been summarised is the correct answer, and the device then shows
+ * nothing rather than stale text.
*/
- recentRecaps(agentId: string, n: number): TaskRecord[] {
- return Object.values(this.state.tasks)
+ /** The agent's LAST summarised turn. The device shows one tile per agent; there is nothing to page. */
+ lastRecap(agentId: string): TurnRecord | undefined {
+ return Object.values(this.state.turns)
.filter((t) => t.agentId === agentId && !!t.recap)
- .sort((a, b) => (b.endedAt ?? b.startedAt) - (a.endedAt ?? a.startedAt))
- .slice(0, n)
+ .sort((a, b) => (b.endedAt ?? b.startedAt) - (a.endedAt ?? a.startedAt))[0]
}
}
diff --git a/provider/example-provider/src/types.ts b/provider/example-provider/src/types.ts
index 5067f9d4b..6a45b237d 100644
--- a/provider/example-provider/src/types.ts
+++ b/provider/example-provider/src/types.ts
@@ -1,144 +1,91 @@
/**
- * The subset of A2A this reference implementation uses, plus the `autonomous.ai/*` metadata defined by
- * `../spec/README.md`.
+ * The wire types, as `../../spec/README.md` defines them.
*
* Deliberately hand-written rather than generated: a partner reading this file should be able to see
- * the entire wire surface without installing anything.
+ * the entire wire surface without installing anything. Kept in step with
+ * `reference-provider/src/types.ts` by hand rather than shared through a package, so that copying
+ * this directory gives you something that compiles on its own.
*/
-export const TaskState = {
- SUBMITTED: 'TASK_STATE_SUBMITTED',
- WORKING: 'TASK_STATE_WORKING',
- COMPLETED: 'TASK_STATE_COMPLETED',
- FAILED: 'TASK_STATE_FAILED',
- CANCELED: 'TASK_STATE_CANCELED',
- REJECTED: 'TASK_STATE_REJECTED',
- INPUT_REQUIRED: 'TASK_STATE_INPUT_REQUIRED',
- AUTH_REQUIRED: 'TASK_STATE_AUTH_REQUIRED',
-} as const
-
-export type TaskStateValue = (typeof TaskState)[keyof typeof TaskState]
-
-/** States after which a task accepts no further messages (A2A: "terminal"). */
-export const TERMINAL_STATES: readonly TaskStateValue[] = [
- TaskState.COMPLETED,
- TaskState.FAILED,
- TaskState.CANCELED,
- TaskState.REJECTED,
-]
-
-export const isTerminal = (s: TaskStateValue): boolean => TERMINAL_STATES.includes(s)
-
-/** HP-210: every Autonomous-specific key is namespaced. Unknown keys in the namespace are ignored. */
-export interface PartMetadata {
- 'autonomous.ai/kind'?:
- | 'user_message'
- | 'thinking_delta'
- | 'thinking_title'
- | 'text_delta'
- | 'tool_start'
- | 'tool_end'
- | 'context_compact'
- | 'done'
- | 'recap_start'
- | 'recap_end'
- 'autonomous.ai/thinkingId'?: string
- 'autonomous.ai/toolCallId'?: string
- 'autonomous.ai/parentToolCallId'?: string
- 'autonomous.ai/tool'?: string
- 'autonomous.ai/toolInput'?: unknown
- 'autonomous.ai/isError'?: boolean
- 'autonomous.ai/summary'?: string
- 'autonomous.ai/durationSeconds'?: number
- 'autonomous.ai/title'?: string
- /**
- * `recap_end` only (HP-212): the headline. The Part's own `text` carries the fuller body.
- * ABSENT on a `recap_end` means the turn produced no recap — the phase is over, show nothing.
- */
- 'autonomous.ai/recap'?: string
- 'autonomous.ai/compacted'?: {
- userMessages?: number
- assistantMessages?: number
- toolUses?: number
- contexts?: number
- }
+export const EVENT_KINDS = [
+ 'turn_started',
+ 'user_message',
+ 'thinking_title',
+ 'thinking_delta',
+ 'text_delta',
+ 'tool_start',
+ 'tool_end',
+ 'context_compact',
+ 'done',
+ 'recap_start',
+ 'recap_end',
+] as const
+
+/** Exactly ONE of these ends every stream. */
+export const TERMINAL_KINDS = ['turn_completed', 'turn_failed', 'turn_cancelled', 'turn_input_required'] as const
+
+export type EventKind = (typeof EVENT_KINDS)[number] | (typeof TERMINAL_KINDS)[number]
+
+export const isTerminalKind = (kind: string | undefined): boolean =>
+ !!kind && (TERMINAL_KINDS as readonly string[]).includes(kind)
+
+/** Codes are STRINGS, and `unauthenticated` is its own so the UI can say the right sentence. */
+export type ErrorCode =
+ | 'unauthenticated'
+ | 'not_found'
+ | 'unsupported'
+ | 'invalid_request'
+ | 'rate_limited'
+ | 'internal'
+
+export interface ProviderErrorBody {
+ code: ErrorCode
+ message?: string
}
-export interface Part {
+/**
+ * One event: flat, self-describing, and readable without the events before it.
+ *
+ * `kind` is optional ON PURPOSE — an event carrying only `text` is conformant and renders as plain
+ * assistant output. The same objects serve the live stream and `agent.history`,
+ * which is why there is one event type here and not two.
+ */
+export interface ProviderEvent {
+ kind?: EventKind
text?: string
- /** base64 — HP-106 carries image attachments here with `mediaType`. */
- raw?: string
- filename?: string
- mediaType?: string
- url?: string
- metadata?: PartMetadata
-}
-
-export type Role = 'ROLE_USER' | 'ROLE_AGENT'
-
-export interface Message {
- role: Role
- messageId: string
- parts: Part[]
- taskId?: string
- contextId?: string
+ turnId?: string
+ agentId?: string
+ at?: string
+ title?: string
+ thinkingId?: string
+ toolId?: string
+ tool?: string
+ input?: unknown
+ ok?: boolean
+ output?: string
+ summary?: string
+ durationSeconds?: number
+ recap?: string
+ prompt?: string
+ error?: ProviderErrorBody
}
-export interface Artifact {
- artifactId: string
- name?: string
- parts: Part[]
-}
-
-export interface TaskStatus {
- state: TaskStateValue
- message?: Message
-}
-
-export interface Task {
+export interface Agent {
id: string
- contextId: string
- status: TaskStatus
- history: Message[]
- artifacts?: Artifact[]
- /** Not A2A core — used to derive a session title (spec §10.4). */
- metadata?: { title?: string }
+ name: string
+ description?: string
}
-export interface TaskStatusUpdateEvent {
- taskId: string
- contextId: string
- status: TaskStatus
- final?: boolean
-}
-
-export interface TaskArtifactUpdateEvent {
- taskId: string
- contextId: string
- artifact: Artifact
-}
-
-export interface JsonRpcRequest {
- jsonrpc: '2.0'
+/** JSON-RPC 2.0 — the only envelope, on one URL. */
+export interface RpcRequest {
+ jsonrpc?: string
id?: string | number | null
- method: string
+ method?: string
params?: Record<string, unknown>
}
-export interface JsonRpcError {
- code: number
- message: string
- data?: unknown
+export interface RecapEntry {
+ recap: string
+ body?: string
+ turnId?: string
}
-
-/** JSON-RPC reserved codes plus the A2A-flavoured ones this implementation raises. */
-export const RpcErrors = {
- PARSE_ERROR: { code: -32700, message: 'Parse error' },
- INVALID_REQUEST: { code: -32600, message: 'Invalid request' },
- METHOD_NOT_FOUND: { code: -32601, message: 'Method not found' },
- INVALID_PARAMS: { code: -32602, message: 'Invalid params' },
- INTERNAL: { code: -32603, message: 'Internal error' },
- UNAUTHENTICATED: { code: -32001, message: 'Unauthenticated' },
- TASK_NOT_FOUND: { code: -32002, message: 'Task not found' },
- TASK_NOT_CANCELABLE: { code: -32003, message: 'Task not cancelable' },
-} as const
diff --git a/provider/example-provider/src/workspace.ts b/provider/example-provider/src/workspace.ts
index 9fe62a236..659d9e16e 100644
--- a/provider/example-provider/src/workspace.ts
+++ b/provider/example-provider/src/workspace.ts
@@ -1,5 +1,5 @@
/**
- * `workspace-write` — creating and removing agents (HP-301).
+ * Creating and removing agents, for `agent.create` / `agent.rename` / `agent.delete`.
*
* An agent here IS a directory. Creating one therefore means writing to disk, so the only rule that
* really matters is the containment check: everything lands under `workspaceRoot` and nothing may
diff --git a/provider/reference-provider/README.md b/provider/reference-provider/README.md
index 4e34db417..aaa58d5ee 100644
--- a/provider/reference-provider/README.md
+++ b/provider/reference-provider/README.md
@@ -1,10 +1,9 @@
# reference-provider
-A minimal, deterministic implementation of the **Autonomous machine provider profile**
-(`../spec/README.md`) — an A2A agent that Autonomous can attach to as a `provider`
-machine.
+A minimal, deterministic implementation of the **Autonomous machine provider protocol**
+(`../spec/README.md`) — an endpoint Autonomous can attach to as a `provider` machine.
-It runs no model. Every reply is scripted, which is the point: it exists to prove the spec is
+It runs no model. Every reply is scripted, which is the point: it exists to prove the protocol is
implementable, to give the backend client something real to talk to, and to be the target the
conformance suite runs against.
@@ -15,18 +14,17 @@ conformance suite runs against.
```bash
npm install
-npm run dev # http://127.0.0.1:4501
-curl localhost:4501/.well-known/agent-card.json
+npm run dev # http://127.0.0.1:4319
```
-Send a turn (any non-empty `x-api-key` is accepted except the literal `bad-key`):
+Any non-empty credential is accepted except the literal `bad-key`:
```bash
-curl -N localhost:4501 \
- -H 'content-type: application/json' -H 'x-api-key: demo' \
- -d '{"jsonrpc":"2.0","id":1,"method":"SendStreamingMessage",
- "params":{"message":{"role":"ROLE_USER","messageId":"m1",
- "parts":[{"text":"did acme blow through budget?"}]}}}'
+curl -N localhost:4319 \
+ -H 'content-type: application/json' -H 'authorization: Bearer demo' \
+ -d '{"jsonrpc":"2.0","id":1,"method":"agent.send",
+ "params":{"agentId":"alpha","turnId":"t-1",
+ "message":{"text":"did acme blow through budget?"}}}'
```
`STEP_DELAY_MS` (default 20) controls the pause between streamed steps; the tests set it to 0.
@@ -39,21 +37,17 @@ the failure modes their integration will actually hit.
| Say this | What happens | Why it's here |
|---|---|---|
-| *(anything else)* | thinking → tool call → text → `COMPLETED` | the full-fidelity turn |
-| `plain` | one text part, **no metadata at all** | HP-211 — a bare provider is conformant |
-| `ask me` | parks in `INPUT_REQUIRED` | HP-104 — answer arrives on the same `taskId` |
-| `fail` | emits output, then `FAILED` | failure after partial output |
-| `die` | stream cut with **no terminal state** | deliberately violates HP-102, so the client can be hardened |
-| `compact` | reports `context_compact` | the provider compacted its own context (spec §9) |
-| *(image attachment)* | `FAILED` with a clear message | HP-106 — silent discarding is a violation |
-
-Credential `bad-key` fails every call with HTTP 401 + `-32001`, for exercising HP-013.
-
-## What it deliberately does NOT declare
-
-`workspace-files` and `workspace-write` are absent from the agent card. That is not an oversight — it
-exercises the degradation path, where the client must hide those features rather than offer controls
-that fail (HP-022).
+| *(anything else)* | thinking → tool call → text → `turn_completed` | the full-fidelity turn |
+| `everything` | every content kind in one turn | proves the vocabulary is reachable — from outside, a kind nobody emits is indistinguishable from one nobody supports |
+| `plain` | one event with **no `kind` at all** | a bare provider is conformant |
+| `ask me` | ends with `turn_input_required` | the answer arrives on the same `turnId` |
+| `fail` | emits output, then `turn_failed` | failure after partial output |
+| `die` | stream cut with **no terminal frame** | deliberately breaks the one-terminal rule, so the client can be hardened |
+| `compact` | reports `context_compact` | the provider compacted its own context |
+| `recap` | `recap_start` / `recap_end` around the summary | the recap pushed on the turn's own stream |
+
+Credential `bad-key` fails every call with HTTP 401 and `unauthenticated`, so the runner's `--bad-key`
+probe has something to hit.
## Conformance suite
@@ -62,58 +56,59 @@ Point it at **any** provider endpoint — yours, or someone else's:
```bash
npm run conformance -- --url https://agent.example.com --key <credential>
-# two optional flags unlock three more clauses:
-# --bad-key <invalid credential> → HP-013 (a rejection must be distinguishable from an outage)
-# --ask-phrase "<prompt>" → HP-103, HP-104 (cancel, and the INPUT_REQUIRED round trip)
+# two optional flags unlock four more checks:
+# --bad-key <invalid credential> → a rejection must be distinguishable from an outage
+# --ask-phrase "<prompt>" → the turn_input_required round trip
```
-Against this reference provider: **22 passed · 0 failed · 2 need manual review · 9 not verifiable from outside**.
+Against this reference provider: **19 passed · 0 failed · 2 need manual review · 5 not verifiable
+from outside**.
Two rules it follows, both deliberate:
-- **Nothing is skipped silently.** A clause that genuinely cannot be checked from outside — tenant
- isolation, the 5 MB transcript ceiling, whether the credential gets logged — is reported as SKIP
- **with the reason printed**. A suite that claims to check everything while quietly checking half of
- it is worse than no suite at all.
-- **An undeclared extension is a SKIP, not a failure.** Absence is a legitimate answer (HP-022).
-
-Output names the clause, so a red line points at a section of the spec rather than at a symptom:
+- **Nothing is skipped silently.** A rule that genuinely cannot be checked from outside — tenant
+ isolation, the truncation flag, whether the credential gets logged — is reported as SKIP **with the
+ reason printed**. A suite that claims to check everything while quietly checking half of it is worse
+ than no suite at all.
+- **Every check has a stable `id` slug.** The slug is what the tests match on; the title is what a
+ partner reads. Rewording a title must never break the suite that proves the suite works.
```
-✖ HP-200 ListTasks filters by contextId
- 3 task(s) from another context leaked into the filter
+✔ terminal-frame Every stream ends with EXACTLY ONE terminal event
+✖ history-matches-stream History returns the SAME event objects the stream emitted
+ history and the live stream disagree about the same events
```
-Extension checks are **real calls**, not stubs: `autonomous.GetRecap` is invoked and its response
-validated (including the 200-character ceiling the device renders under). `workspace-write` is probed
-**non-destructively** — empty params must yield `-32602` (invalid params) rather than `-32601` (method
-not found), which proves the method exists without a conformance runner mutating someone's live
-workspace.
+Checks are **real calls**, not stubs. `agent.recap` is invoked and its response validated. The
+mutations are probed **non-destructively** — `agent.create` with an empty name — which proves the
+method is reachable, and distinguishes a provider that declines with a reason (conformant, and the
+reason is shown to the user) from one that answers `unsupported` (not).
-The suite itself has been mutation-tested. Six deliberate breaks, each turning exactly one clause red:
-`streaming: false` → HP-021 · a mistyped extension URI → HP-003 · ignoring the `contextId` filter →
-HP-200 · an unrecognised metadata kind → HP-210 · answering an **undeclared** extension method →
-HP-311 · a recap longer than 200 characters → HP-302.
+**The suite is itself tested against deliberate breaks** — see `conformance.spec.ts`. Eleven broken
+providers, each violating exactly one rule, each of which the runner must catch: a stream with no
+terminal frame and one with two · `agent.send` answering with ordinary JSON instead of SSE · a bad
+credential being accepted · a bad credential getting a list back instead of an error · an empty agent
+list · tool events with no id · an early cancel ignored · history disagreeing with the stream · an
+unknown method being answered · an unknown request field being fatal. A runner that only ever goes
+green converts "we did not check" into "we checked and it was fine".
## Tests
```bash
-npm test # 30 tests — provider + the conformance runner itself
+npm test # 48 tests — provider + the conformance runner itself
npm run typecheck
```
-Each test names the clause it pins. When the spec changes, these should be the first thing to go red.
-The suite has been mutation-tested: dropping `final` on terminal states, silently discarding images,
-and allowing a finished task to be cancelled each turn it red.
+Each test names the rule it pins. When the spec changes, these should be the first thing to go red.
## Layout
| File | Role |
|---|---|
-| `src/types.ts` | the A2A subset used here, plus the `autonomous.ai/*` metadata — hand-written so the whole wire surface is readable in one file |
-| `src/agentCard.ts` | the entire capability negotiation (HP-020 … HP-023) |
+| `src/types.ts` | the whole wire surface, hand-written so it is readable in one file |
+| `src/agents.ts` | the agent list and the mutations on it — ids derived on read, never snapshotted |
| `src/scenarios.ts` | the scripted turns, happy and hostile |
-| `src/store.ts` | in-memory tasks — note that **history lives here**, which is why `GetTask`/`ListTasks` are Tier 0 |
-| `src/server.ts` | JSON-RPC dispatch and SSE, with HP-xxx clause references inline |
+| `src/store.ts` | in-memory transcripts — note that **history lives here**, which is why `agent.history` is required |
+| `src/server.ts` | JSON-RPC dispatch and SSE |
| `src/conformance.ts` | the runner partners point at their own endpoint |
-| `src/conformance.spec.ts` | regression cover for the runner — including that it **reports** an unreachable endpoint instead of throwing, and never reports PASS for a clause it did not actually check |
+| `src/conformance.spec.ts` | regression cover for the runner — including that it **reports** an unreachable endpoint instead of throwing, and never reports PASS for a rule it did not actually check |
diff --git a/provider/reference-provider/src/agentCard.ts b/provider/reference-provider/src/agentCard.ts
deleted file mode 100644
index bd3b00b45..000000000
--- a/provider/reference-provider/src/agentCard.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * The Agent Card — HP-020 through HP-023.
- *
- * This is the whole capability negotiation. A client reads this and knows what the provider can do;
- * nothing else in the protocol advertises capability (HP-001).
- */
-
-export const AGENT_CARD = {
- name: 'Autonomous Reference Provider',
- description:
- 'A minimal, deterministic provider used to validate the machine provider profile. It runs no model — every reply is scripted.',
- version: '0.1.0',
-
- // HP-021: non-negotiable. The product renders assistant output token by token.
- capabilities: { streaming: true, pushNotifications: false },
-
- // HP-011: APIKey and HTTPAuth bearer are the schemes Autonomous supports today.
- securitySchemes: {
- apiKey: { type: 'apiKey', in: 'header', name: 'x-api-key' },
- },
-
- defaultInputModes: ['text/plain', 'image/png', 'image/jpeg'],
- defaultOutputModes: ['text/plain'],
-
- // HP-023: skills are the agent list shown to the user.
- skills: [
- {
- id: 'acme-reporting',
- name: 'Acme reporting',
- description: "Acme's ad accounts — spend, pacing, and alerting.",
- },
- {
- id: 'globex-q3',
- name: 'Globex Q3',
- description: 'Quarterly rollup for Globex.',
- },
- ],
-
- // HP-022: implemented-but-undeclared MUST be treated as absent, so this list is the contract.
- // `workspace-files` and `workspace-write` are deliberately NOT declared — the reference provider
- // exercises the degradation path as well as the happy path.
- extensions: [
- {
- uri: 'https://harness.autonomous.ai/api/a2a/ext/session-recap',
- description: 'Short per-turn summaries for device tile restore.',
- },
- ],
-} as const
-
-export type AgentCard = typeof AGENT_CARD
-
-/** Skill ids, for validating an agent reference without trusting the caller. */
-export const SKILL_IDS: readonly string[] = AGENT_CARD.skills.map((s) => s.id)
diff --git a/provider/reference-provider/src/agents.ts b/provider/reference-provider/src/agents.ts
new file mode 100644
index 000000000..6676495dd
--- /dev/null
+++ b/provider/reference-provider/src/agents.ts
@@ -0,0 +1,59 @@
+/**
+ * The agent list, and the mutations on it.
+ *
+ * There is no discovery document: `agent.list` IS how a client learns what this provider offers, and
+ * it is authenticated, so two credentials can legitimately see two different lists.
+ *
+ * The list is MUTABLE, and that matters more than it looks. An earlier version derived the set of
+ * valid ids once at module load; the moment `agent.create` could add one, that snapshot was stale and
+ * a send to the freshly created agent came back `not_found`. Ids are derived on read here for exactly
+ * that reason — there is no second list to fall out of step.
+ */
+import type { Agent } from './types.js'
+
+export const CREDENTIAL_HEADER = 'authorization'
+
+/** Two to start with, so agent scoping has something to get wrong. */
+let agents: Agent[] = [
+ { id: 'alpha', name: 'Alpha', description: 'The default agent' },
+ { id: 'beta', name: 'Beta', description: 'A second agent, for scoping' },
+]
+
+export const listAgents = (): Agent[] => agents.map((a) => ({ ...a }))
+
+export const hasAgent = (id: string): boolean => agents.some((a) => a.id === id)
+
+export class AgentError extends Error {}
+
+export function createAgent(name: string, description?: string): Agent {
+ const clean = name.trim()
+ if (!clean) throw new AgentError('name is required')
+ const base = clean.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'agent'
+ let id = base
+ for (let n = 2; hasAgent(id); n++) id = `${base}-${n}`
+ const created: Agent = { id, name: clean, ...(description ? { description } : {}) }
+ agents.push(created)
+ return created
+}
+
+export function renameAgent(id: string, name: string): Agent {
+ const clean = name.trim()
+ if (!clean) throw new AgentError('name is required')
+ const found = agents.find((a) => a.id === id)
+ if (!found) throw new AgentError(`no agent ${id}`)
+ found.name = clean
+ return { ...found }
+}
+
+export function deleteAgent(id: string): void {
+ if (!hasAgent(id)) throw new AgentError(`no agent ${id}`)
+ agents = agents.filter((a) => a.id !== id)
+}
+
+/** Test seam: the list is module state, and one test's `agent.create` must not leak into the next. */
+export function resetAgents(): void {
+ agents = [
+ { id: 'alpha', name: 'Alpha', description: 'The default agent' },
+ { id: 'beta', name: 'Beta', description: 'A second agent, for scoping' },
+ ]
+}
diff --git a/provider/reference-provider/src/conformance.spec.ts b/provider/reference-provider/src/conformance.spec.ts
index 4a8597ad5..12c67731d 100644
--- a/provider/reference-provider/src/conformance.spec.ts
+++ b/provider/reference-provider/src/conformance.spec.ts
@@ -1,12 +1,19 @@
-// The conformance runner is the artifact partners are told to trust, so it needs the same regression
-// cover as the provider itself. Without this it only ran when somebody remembered to run it by hand.
+// Two questions about the conformance runner, and the second is the one that matters.
//
-// These tests boot the reference provider in-process and run the real suite against it.
+// 1. Does the reference provider pass its own suite? (If not, the spec and the reference disagree.)
+// 2. **Does the suite actually CATCH anything?** A runner that only ever goes green is worse than no
+// runner: it converts "we did not check" into "we checked and it was fine". So every rule worth
+// asserting gets a deliberately broken provider aimed at it, and the check must fail.
+//
+// The runner is the artifact partners are told to trust, so it needs the same regression cover as the
+// provider itself. Rows below name a check by its `id` SLUG, never by its title — a reworded title
+// must not break this file.
+import { createServer, type Server, type ServerResponse } from 'node:http'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
process.env.STEP_DELAY_MS = '0'
const { start } = await import('./server.js')
-const { runConformance, CHECKS } = await import('./conformance.js')
+const { runConformance } = await import('./conformance.js')
let base: string
let stop: () => Promise<void>
@@ -18,65 +25,165 @@ beforeAll(async () => {
}, 30_000)
afterAll(async () => { await stop() })
-const FULL = { key: 'conformance', badKey: 'bad-key', askPhrase: 'ask me something' }
+const FULL = { key: 'conformance', badKey: 'bad-key', askPhrase: 'ask me' }
describe('the runner against a conformant provider', () => {
it('reports zero failures', async () => {
const summary = await runConformance({ url: base, ...FULL })
const failures = summary.results.filter((r) => r.outcome === 'FAIL')
- expect(failures.map((f) => `${f.id}: ${f.detail}`)).toEqual([])
- expect(summary.pass).toBeGreaterThan(20)
- }, 30_000)
+ // Named, not counted: a bare count tells whoever broke it nothing.
+ expect(failures.map((f) => `${f.id}: ${f.detail ?? ''}`)).toEqual([])
+ expect(summary.pass).toBeGreaterThan(12)
+ })
- it('gives every skipped clause a reason — nothing is dropped silently', async () => {
- const summary = await runConformance({ url: base, ...FULL })
- const mute = summary.results.filter((r) => (r.outcome === 'SKIP' || r.outcome === 'WARN') && !r.detail?.trim())
- expect(mute.map((m) => m.id)).toEqual([])
- }, 30_000)
+ it('states a reason for every skip and every manual review', async () => {
+ // The rule the runner is built on: nothing is silently skipped. A SKIP without a reason is
+ // indistinguishable from a check nobody wrote.
+ const summary = await runConformance({ url: base, key: 'conformance' })
+ const mute = summary.results.filter((r) => (r.outcome === 'SKIP' || r.outcome === 'WARN') && !r.detail)
+ expect(mute.map((r) => r.id)).toEqual([])
+ })
- it('treats an undeclared extension as SKIP, never as FAIL', async () => {
- // The reference provider declares session-recap only, so workspace-files/-write/voice are absent.
- const summary = await runConformance({ url: base, ...FULL })
- const byId = new Map(summary.results.map((r) => [r.id, r]))
- for (const id of ['HP-300', 'HP-301', 'HP-303']) {
- expect(byId.get(id)?.outcome, `${id} should skip when undeclared`).toBe('SKIP')
- }
- // …and the one that IS declared must be genuinely exercised, not waved through.
- expect(byId.get('HP-302')?.outcome).toBe('PASS')
- }, 30_000)
-
- it('has a unique, non-empty id and title for every check', () => {
- const ids = CHECKS.map((c) => c.id)
- expect(new Set(ids).size).toBe(ids.length)
- expect(CHECKS.filter((c) => !c.title.trim())).toEqual([])
+ it('unlocks more checks when given a bad key and an ask phrase', async () => {
+ const bare = await runConformance({ url: base, key: 'conformance' })
+ const full = await runConformance({ url: base, ...FULL })
+ expect(full.pass).toBeGreaterThan(bare.pass)
})
-})
-describe('the runner degrades honestly when it is given less', () => {
- it('skips the credential clause instead of guessing when --bad-key is absent', async () => {
- const summary = await runConformance({ url: base, key: 'conformance', askPhrase: FULL.askPhrase })
- const hp013 = summary.results.find((r) => r.id === 'HP-013')
- expect(hp013?.outcome).toBe('SKIP')
- expect(hp013?.detail).toMatch(/--bad-key/)
- expect(summary.fail).toBe(0)
- }, 30_000)
-
- it('skips the cancel and input-required clauses when --ask-phrase is absent', async () => {
- const summary = await runConformance({ url: base, key: 'conformance', badKey: FULL.badKey })
- for (const id of ['HP-103', 'HP-104']) {
- const r = summary.results.find((x) => x.id === id)
- expect(r?.outcome, id).toBe('SKIP')
- expect(r?.detail, id).toMatch(/--ask-phrase/)
- }
+ it('exits non-zero-worthy only on FAIL, never on SKIP or WARN', async () => {
+ const summary = await runConformance({ url: base, ...FULL })
expect(summary.fail).toBe(0)
- }, 30_000)
+ // Skips and warnings are expected and MUST NOT be treated as failures — otherwise a provider that
+ // legitimately refuses a mutation, or one on loopback, looks non-conformant.
+ expect(summary.skip + summary.warn).toBeGreaterThan(0)
+ })
})
-describe('the runner fails loudly against a provider that is not there', () => {
- it('does not report success when the endpoint is unreachable', async () => {
- // A conformance suite that goes green against a dead URL is worse than no suite.
- const summary = await runConformance({ url: 'http://127.0.0.1:1', ...FULL })
+describe('an unreachable endpoint is reported, not thrown', () => {
+ it('fails rather than crashing', async () => {
+ // A runner that crashes when the provider is down is useless at exactly the moment it is needed.
+ const summary = await runConformance({ url: 'http://127.0.0.1:1', key: 'k' })
+ expect(summary.results.find((r) => r.id === 'reachable')?.outcome).toBe('FAIL')
expect(summary.fail).toBeGreaterThan(0)
- expect(summary.results.find((r) => r.id === 'HP-020')?.outcome).toBe('FAIL')
- }, 30_000)
+ })
+})
+
+// ── the negative matrix ──────────────────────────────────────────────────────────────────────────
+
+type Reply = Record<string, unknown> & { __sse?: { events: unknown[] }; __json?: true; __error?: string }
+type Mutate = (method: string, params: Record<string, unknown>) => Reply | undefined
+
+/** A minimally-correct provider, so each case below breaks exactly ONE rule. */
+const baseline: Mutate = (method) => {
+ if (method === 'agent.list') return { agents: [{ id: 'a', name: 'A' }] }
+ if (method === 'agent.history') return { agentId: 'a', events: [] }
+ if (method === 'turn.cancel') return { cancelled: true }
+ if (method === 'agent.recap') return { agentId: 'a' }
+ if (method === 'agent.create') return { __error: 'invalid_request' }
+ if (method === 'agent.delete') return { deleted: true }
+ if (method === 'agent.send') return { __sse: { events: [{ kind: 'text_delta', text: 'hi' }, { kind: 'turn_completed' }] } }
+ if (method.startsWith('agent.') || method.startsWith('turn.')) return { __error: 'unsupported' }
+ return {}
+}
+
+function json(res: ServerResponse, body: unknown): void {
+ const payload = JSON.stringify(body)
+ res.writeHead(200, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) })
+ res.end(payload)
+}
+
+async function failuresOf(mutate: Mutate): Promise<string[]> {
+ const summary = await runOf(mutate)
+ return summary.results.filter((r) => r.outcome === 'FAIL').map((r) => r.id)
+}
+
+async function runOf(mutate: Mutate): Promise<Awaited<ReturnType<typeof runConformance>>> {
+ const server: Server = createServer((req, res) => {
+ void (async () => {
+ let body = ''
+ for await (const chunk of req) body += chunk
+ const rpc = JSON.parse(body || '{}') as { method?: string; params?: Record<string, unknown>; id?: unknown }
+ const out = mutate(rpc.method ?? '', rpc.params ?? {})
+ if (out?.__error) return json(res, { jsonrpc: '2.0', id: rpc.id ?? null, error: { code: out.__error } })
+ if (out?.__sse) {
+ // `__json` answers agent.send as ordinary JSON, which is the whole point of that one row.
+ if (out.__json) return json(res, { jsonrpc: '2.0', id: rpc.id ?? null, result: { events: out.__sse.events } })
+ res.writeHead(200, { 'content-type': 'text/event-stream' })
+ for (const e of out.__sse.events) res.write(`data: ${JSON.stringify(e)}\n\n`)
+ return res.end()
+ }
+ return json(res, { jsonrpc: '2.0', id: rpc.id ?? null, result: out ?? {} })
+ })()
+ })
+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))
+ const addr = server.address()
+ const url = `http://127.0.0.1:${typeof addr === 'object' && addr ? addr.port : 0}`
+ const summary = await runConformance({ url, key: 'k', badKey: 'bad-key' })
+ await new Promise<void>((r) => server.close(() => r()))
+ return summary
+}
+
+describe('the suite catches deliberate violations', () => {
+ // Each row: what is broken, and the check slug that must notice. Other checks failing too is
+ // expected — the fake is minimal — so this asserts CONTAINMENT, not an exact set.
+ const cases: Array<[string, string, Mutate]> = [
+ ['a stream with no terminal frame', 'terminal-frame', (m, p) =>
+ (m === 'agent.send' ? { __sse: { events: [{ kind: 'text_delta', text: 'hi' }] } } : baseline(m, p))],
+ ['a stream with TWO terminal frames', 'terminal-frame', (m, p) =>
+ (m === 'agent.send' ? { __sse: { events: [{ kind: 'turn_completed' }, { kind: 'turn_completed' }] } } : baseline(m, p))],
+ ['agent.send answering with ordinary JSON instead of SSE', 'streams-sse', (m, p) =>
+ (m === 'agent.send' ? { __sse: { events: [{ kind: 'turn_completed' }] }, __json: true } : baseline(m, p))],
+ ['a bad credential being accepted', 'credential-rejected', baseline],
+ ['a bad credential getting a list back instead of an error', 'agent-list-authenticated', baseline],
+ ['an empty agent list', 'agent-list', (m, p) => (m === 'agent.list' ? { agents: [] } : baseline(m, p))],
+ ['tool events with no toolId', 'tool-pairing', (m, p) =>
+ (m === 'agent.send' ? { __sse: { events: [{ kind: 'tool_start', tool: 'x' }, { kind: 'turn_completed' }] } } : baseline(m, p))],
+ ['an early cancel being ignored', 'early-cancel', baseline],
+ ['history disagreeing with the stream', 'history-matches-stream', (m, p) =>
+ (m === 'agent.history' ? { agentId: 'a', events: [{ kind: 'text_delta', text: 'DIFFERENT' }] } : baseline(m, p))],
+ ['an unknown method being answered instead of refused', 'unknown-method', (m, p) =>
+ (m === 'agent.nonexistentMethod' ? { ok: true } : baseline(m, p))],
+ ['an unknown request field being fatal', 'unknown-fields', (m, p) =>
+ (m === 'agent.list' && p.somethingFromALaterRevision ? { __error: 'invalid_request' } : baseline(m, p))],
+ ]
+
+ it.each(cases)('catches %s as %s', async (_label, slug, mutate) => {
+ expect(await failuresOf(mutate)).toContain(slug)
+ }, 20_000)
+})
+
+describe('the runner does not leave state behind in a live tenant', () => {
+ it('deletes the agent a lax provider creates from its empty-name probe', async () => {
+ // `agent-mutations` probes with an EMPTY name, expecting a refusal. A provider that accepts it has
+ // just created an agent nobody asked for — and this runner is pointed at production endpoints with
+ // real credentials, so it has to clean up after itself rather than quietly adding a row to
+ // somebody's product.
+ const calls: Array<{ method: string; params: Record<string, unknown> }> = []
+ const lax: Mutate = (method, params) => {
+ calls.push({ method, params })
+ if (method === 'agent.create') return { id: 'accidentally-created', name: '' }
+ return baseline(method, params)
+ }
+ const summary = await runOf(lax)
+
+ const deleted = calls.find((c) => c.method === 'agent.delete')
+ expect(deleted, 'the accidentally-created agent was never deleted').toBeTruthy()
+ expect(deleted!.params.agentId).toBe('accidentally-created')
+
+ // Reported as a WARN, not a pass: loose validation is still worth telling the partner about.
+ const mutations = summary.results.find((r) => r.id === 'agent-mutations')!
+ expect(mutations.outcome).toBe('WARN')
+ expect(mutations.detail).toContain('accidentally-created')
+ }, 20_000)
+
+ it('says so LOUDLY when the agent it created cannot be cleaned up', async () => {
+ // Worst case: accepted the empty name and answered with no id. Nothing can be deleted, so the
+ // partner has to be told by hand rather than left with an orphan they never hear about.
+ const noId: Mutate = (method, params) =>
+ (method === 'agent.create' ? { name: '' } : baseline(method, params))
+ const summary = await runOf(noId)
+ const mutations = summary.results.find((r) => r.id === 'agent-mutations')!
+ expect(mutations.outcome).toBe('WARN')
+ expect(mutations.detail).toMatch(/cannot be cleaned up|by hand/i)
+ }, 20_000)
})
diff --git a/provider/reference-provider/src/conformance.ts b/provider/reference-provider/src/conformance.ts
index 1e33e347c..4730357c4 100644
--- a/provider/reference-provider/src/conformance.ts
+++ b/provider/reference-provider/src/conformance.ts
@@ -1,23 +1,21 @@
/**
- * Conformance runner for the machine provider profile (`../spec/README.md`).
+ * Conformance runner for the Autonomous machine provider protocol (`../../spec/README.md`).
*
- * Point it at ANY provider endpoint. It asserts one check per normative clause and names the clause in
- * its output, so a red line points at a section of the spec rather than at a symptom:
+ * Point it at ANY provider endpoint:
*
* npm run conformance -- --url https://agent.example.com --key <credential>
*
* Two design rules, both load-bearing:
*
- * 1. **Nothing is silently skipped.** A clause that cannot be verified from outside (tenant isolation,
- * the 5 MB transcript ceiling, rate limiting) is reported as SKIP *with the reason*. A suite that
- * claims to check everything while quietly checking half of it is worse than no suite.
- * 2. **Extension checks are conditional on the Agent Card.** An undeclared extension is not a failure
- * (HP-022) — it is a SKIP, because absence is a legitimate answer.
+ * 1. **Nothing is silently skipped.** A rule that cannot be verified from outside (tenant isolation,
+ * truncation, rate limiting) is reported as SKIP *with the reason*. A suite that claims to check
+ * everything while quietly checking half of it is worse than no suite.
+ * 2. **Every check has a stable `id` slug** — `terminal-frame`, `credential-rejected`,
+ * `history-matches-stream`. The slug is what the tests match on; the title is what a partner
+ * reads. Rewording a title must never break the suite that proves the suite works.
*
* Zero dependencies, like the rest of this package.
*/
-import { AGENT_CARD } from './agentCard.js'
-
type Outcome = 'PASS' | 'FAIL' | 'SKIP' | 'WARN'
interface Result {
@@ -27,13 +25,16 @@ interface Result {
interface Ctx {
url: string
- /** Set when the agent card could not be fetched at all — every check reports rather than throwing. */
- cardError?: string
key: string
badKey?: string
- /** Phrase that makes the provider enter INPUT_REQUIRED, if it has one. */
+ /** Phrase that makes the provider ask the user something, if it has one. */
askPhrase?: string
- card: Record<string, unknown>
+ /** Resolved once, so every check addresses a real agent instead of guessing an id. */
+ agentId?: string
+ /** Set when the endpoint could not be reached at all — every check reports rather than throwing. */
+ unreachable?: string
+ /** Every event kind seen anywhere in this run, for the vocabulary check at the end. */
+ seenKinds: Set<string>
}
interface Check {
@@ -47,61 +48,62 @@ const fail = (detail: string): Result => ({ outcome: 'FAIL', detail })
const skip = (detail: string): Result => ({ outcome: 'SKIP', detail })
const warn = (detail: string): Result => ({ outcome: 'WARN', detail })
-const EXT = {
- FILES: 'https://harness.autonomous.ai/api/a2a/ext/workspace-files',
- WRITE: 'https://harness.autonomous.ai/api/a2a/ext/workspace-write',
- RECAP: 'https://harness.autonomous.ai/api/a2a/ext/session-recap',
- VOICE: 'https://harness.autonomous.ai/api/a2a/ext/voice',
-} as const
-
-const KNOWN_EXTENSIONS: string[] = Object.values(EXT)
-
-/** Scope an extension probe to a real agent without guessing an id. */
-const firstSkillId = (ctx: Ctx): string | undefined =>
- ((ctx.card.skills ?? []) as Array<{ id?: string }>)[0]?.id
-
-const KNOWN_KINDS = [
- 'user_message', 'thinking_delta', 'thinking_title', 'text_delta',
- 'tool_start', 'tool_end', 'context_compact', 'done', 'recap_start', 'recap_end',
+/** The published vocabulary. A kind outside it is ignored by clients, never fatal. */
+const CONTENT_KINDS = [
+ 'user_message', 'thinking_delta', 'thinking_title', 'text_delta', 'tool_start', 'tool_end',
+ 'context_compact', 'done', 'recap_start', 'recap_end',
]
-
-const TERMINAL = ['TASK_STATE_COMPLETED', 'TASK_STATE_FAILED', 'TASK_STATE_CANCELED', 'TASK_STATE_REJECTED']
+const TERMINAL_KINDS = ['turn_completed', 'turn_failed', 'turn_cancelled', 'turn_input_required']
+const ALL_KINDS = ['turn_started', ...CONTENT_KINDS, ...TERMINAL_KINDS]
// ── wire helpers ─────────────────────────────────────────────────────────────────────────────────
-interface SseEvent {
- taskId?: string
- contextId?: string
- status?: { state?: string; message?: { parts?: Array<{ text?: string; metadata?: Record<string, unknown> }> } }
- final?: boolean
-}
+interface Event { kind?: string; [field: string]: unknown }
+
+let turnSeq = 0
+/** The CLIENT mints these, which is what makes an early cancel possible at all. */
+const mintTurnId = (): string => `conf-${Date.now()}-${++turnSeq}`
+
+/**
+ * One header, fixed by convention. There is no discovery document to ask where the credential goes —
+ * `Authorization: Bearer` is near-universal, and the alternative was a whole unauthenticated round
+ * trip whose only job was to say "use this header".
+ */
+const authHeaders = (key: string): Record<string, string> =>
+ ({ 'content-type': 'application/json', authorization: `Bearer ${key}` })
async function rpc(ctx: Ctx, method: string, params: unknown, key = ctx.key): Promise<Response> {
return fetch(ctx.url, {
method: 'POST',
- headers: { 'content-type': 'application/json', [authHeader(ctx)]: key },
+ headers: authHeaders(key),
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
})
}
-/** The card declares where the credential goes; do not assume a header name (HP-011). */
-function authHeader(ctx: Ctx): string {
- const schemes = (ctx.card.securitySchemes ?? {}) as Record<string, { type?: string; in?: string; name?: string }>
- for (const s of Object.values(schemes)) {
- if (s.type === 'apiKey' && s.in === 'header' && s.name) return s.name
- }
- return 'authorization'
+const body = async (res: Response): Promise<Record<string, unknown>> => {
+ try { return (await res.json()) as Record<string, unknown> } catch { return {} }
+}
+
+const errorCode = async (res: Response): Promise<string | undefined> => {
+ const b = await body(res)
+ const err = b.error as { code?: unknown } | undefined
+ return typeof err?.code === 'string' ? err.code : undefined
}
-async function stream(ctx: Ctx, text: string, extra: Record<string, unknown> = {}): Promise<{ res: Response; events: SseEvent[] }> {
- const res = await rpc(ctx, 'SendStreamingMessage', {
- message: { role: 'ROLE_USER', messageId: `conf-${Date.now()}`, parts: [{ text }], ...extra },
+async function send(
+ ctx: Ctx,
+ text: string,
+ extra: Record<string, unknown> = {},
+): Promise<{ res: Response; events: Event[]; turnId: string }> {
+ const turnId = typeof extra.turnId === 'string' ? extra.turnId : mintTurnId()
+ const res = await rpc(ctx, 'agent.send', {
+ agentId: ctx.agentId, turnId, message: { text }, ...extra,
})
- return { res, events: await drain(res) }
+ return { res, events: await drain(ctx, res), turnId }
}
-async function drain(res: Response): Promise<SseEvent[]> {
- const events: SseEvent[] = []
+async function drain(ctx: Ctx, res: Response): Promise<Event[]> {
+ const events: Event[] = []
if (!res.body) return events
const reader = res.body.getReader()
const decoder = new TextDecoder()
@@ -114,399 +116,438 @@ async function drain(res: Response): Promise<SseEvent[]> {
const frames = buffer.split('\n\n')
buffer = frames.pop() ?? ''
for (const frame of frames) {
- const line = frame.split('\n').find((l) => l.startsWith('data: '))
- if (line) { try { events.push(JSON.parse(line.slice(6)) as SseEvent) } catch { /* skip unparsable */ } }
+ const line = frame.split('\n').find((l) => l.startsWith('data:'))
+ if (!line) continue
+ try {
+ const event = JSON.parse(line.slice(5).trim()) as Event
+ if (typeof event.kind === 'string') ctx.seenKinds.add(event.kind)
+ events.push(event)
+ } catch { /* skip unparsable */ }
}
}
- } catch { /* an aborted stream is itself a finding — HP-102 reports it */ }
+ } catch { /* an aborted stream is itself a finding — `terminal-frame` reports it */ }
return events
}
-const declares = (ctx: Ctx, uri: string): boolean =>
- ((ctx.card.extensions ?? []) as Array<{ uri?: string }>).some((e) => e.uri === uri)
+const terminals = (events: Event[]): Event[] => events.filter((e) => TERMINAL_KINDS.includes(e.kind ?? ''))
-const body = async (res: Response): Promise<Record<string, unknown>> => {
- try { return (await res.json()) as Record<string, unknown> } catch { return {} }
+/** Content events only — what both the stream and `agent.history` are expected to agree on. */
+const NON_TRANSCRIPT = new Set(['turn_started', 'recap_start', 'recap_end', 'done'])
+const content = (events: Event[]): Event[] =>
+ events.filter((e) => !TERMINAL_KINDS.includes(e.kind ?? '') && !NON_TRANSCRIPT.has(e.kind ?? ''))
+
+/**
+ * Merge adjacent same-kind deltas, concatenating their text.
+ *
+ * `history-matches-stream` compares a stream against a transcript, and deltas are a STREAMING detail:
+ * a live turn emits `text_delta "Acme is at "` then `text_delta "118% of pace."`, while a provider
+ * reading its own stored transcript legitimately has one complete message. Comparing raw would fail
+ * every delta-streaming provider for doing exactly what streaming means. Coalescing first compares
+ * what the user actually ends up seeing.
+ */
+export function coalesceDeltas(events: Event[]): Event[] {
+ const out: Event[] = []
+ for (const event of events) {
+ const prev = out.at(-1)
+ const mergeable = event.kind === 'text_delta' || event.kind === 'thinking_delta'
+ if (prev && mergeable && prev.kind === event.kind) {
+ out[out.length - 1] = { ...prev, text: `${prev.text ?? ''}${event.text ?? ''}` }
+ continue
+ }
+ out.push(event)
+ }
+ return out
}
+const down = (ctx: Ctx): Result | null => (ctx.unreachable ? fail(ctx.unreachable) : null)
+const noAgent = (ctx: Ctx): Result | null =>
+ (ctx.agentId ? null : fail('no agent to address — `agent-list` must pass first'))
+
// ── checks ───────────────────────────────────────────────────────────────────────────────────────
export const CHECKS: Check[] = [
+ // ── Transport and authentication ───────────────────────────────────────────────────────────────
{
- id: 'HP-003',
- title: 'Declared extension URIs are byte-exact',
- run: (ctx) => {
- const declared = ((ctx.card.extensions ?? []) as Array<{ uri?: string }>).map((e) => e.uri ?? '')
- const ours = declared.filter((u) => u.includes('autonomous.ai'))
- const wrong = ours.filter((u) => !KNOWN_EXTENSIONS.includes(u))
- if (!ours.length) return skip('no Autonomous extensions declared — nothing to compare')
- return wrong.length
- ? fail(`not byte-exact: ${wrong.join(', ')}`)
- : pass(`${ours.length} declared, all exact`)
- },
- },
- {
- id: 'HP-010',
- title: 'Endpoint is reachable over HTTPS',
- run: (ctx) =>
- ctx.url.startsWith('https://')
- ? pass()
- : warn('endpoint is not HTTPS — acceptable for local testing, a violation in production'),
+ id: 'reachable',
+ title: 'The endpoint answers JSON-RPC at a single URL',
+ run: (ctx) => down(ctx) ?? pass(ctx.url),
},
{
- id: 'HP-011',
- title: 'Agent Card declares a supported security scheme',
+ id: 'https',
+ title: 'The endpoint is HTTPS at a stable, publicly resolvable URL',
run: (ctx) => {
- const schemes = Object.values((ctx.card.securitySchemes ?? {}) as Record<string, { type?: string }>)
- if (!schemes.length) return fail('no securitySchemes declared')
- const supported = schemes.filter((s) => s.type === 'apiKey' || s.type === 'http')
- return supported.length
- ? pass(schemes.map((s) => s.type).join(', '))
- : fail(`only unsupported schemes declared (${schemes.map((s) => s.type).join(', ')}); Autonomous supports APIKey and HTTPAuth today`)
+ if (ctx.url.startsWith('https://')) return pass()
+ if (/^http:\/\/(127\.0\.0\.1|localhost|\[::1\])/.test(ctx.url)) {
+ return warn('plain HTTP on loopback — fine for this run, but production MUST be HTTPS')
+ }
+ return fail(`not HTTPS: ${ctx.url}`)
},
},
{
- id: 'HP-012',
- title: 'Credential is scoped to one tenant',
- run: () => skip('not verifiable from outside — needs two tenants\' credentials and knowledge of provider internals'),
- },
- {
- id: 'HP-013',
- title: 'A rejected credential is distinguishable from an outage',
+ id: 'credential-rejected',
+ title: 'A rejected credential answers `unauthenticated`, never a generic failure',
run: async (ctx) => {
- if (!ctx.badKey) return skip('pass --bad-key <value> with a credential known to be invalid to run this')
- const res = await rpc(ctx, 'ListTasks', {}, ctx.badKey)
- const b = await body(res)
- const err = b.error as { code?: number } | undefined
- if (res.status === 401 || err) return pass(`status ${res.status}${err?.code ? `, code ${err.code}` : ''}`)
- return fail('an invalid credential was accepted, or failed indistinguishably from a generic error')
+ const found = down(ctx); if (found) return found
+ if (!ctx.badKey) return skip('pass --bad-key <deliberately invalid credential> to check this')
+ const res = await rpc(ctx, 'agent.list', {}, ctx.badKey)
+ const code = await errorCode(res)
+ if (code === 'unauthenticated') return pass()
+ if (res.ok && !code) return fail('a bad credential was ACCEPTED')
+ return fail(`answered ${code ?? `HTTP ${res.status}`} — the product cannot then tell "wrong credential" from "provider down"`)
},
},
{
- id: 'HP-020',
- title: 'Agent Card served at /.well-known/agent-card.json',
- run: (ctx) => {
- if (ctx.cardError) return fail(ctx.cardError)
- return ctx.card.name ? pass(String(ctx.card.name)) : fail('card missing or unparsable')
- },
+ id: 'tenant-isolation',
+ title: 'The credential is scoped to exactly one tenant',
+ run: () => skip('not verifiable from outside — needs a second tenant\'s credential and a manual check that neither can see the other'),
},
+
+ // ── Agents ─────────────────────────────────────────────────────────────────────────────────────
{
- id: 'HP-021',
- title: 'capabilities.streaming is true',
- run: (ctx) => {
- const caps = (ctx.card.capabilities ?? {}) as { streaming?: boolean }
- return caps.streaming === true ? pass() : fail('a non-streaming provider cannot be used; output is rendered token by token')
+ id: 'agent-list',
+ title: 'agent.list returns at least one well-formed agent',
+ run: async (ctx) => {
+ const found = down(ctx); if (found) return found
+ const res = await rpc(ctx, 'agent.list', {})
+ const result = (await body(res)).result as { agents?: unknown } | undefined
+ const agents = result?.agents
+ if (!Array.isArray(agents)) return fail('no `agents` array in the result')
+ if (!agents.length) return fail('empty list — a provider with no agent concept MUST return exactly one entry for the whole workspace; an empty list reads to the user as a broken machine')
+ const bad = agents.filter((a) => {
+ const agent = a as { id?: unknown; name?: unknown }
+ return typeof agent?.id !== 'string' || !agent.id || typeof agent?.name !== 'string' || !agent.name
+ })
+ return bad.length ? fail(`${bad.length} agent(s) missing a string id or name`) : pass(`${agents.length} agent(s)`)
},
},
{
- id: 'HP-022',
- title: 'Extensions are declared by URI, unknown ones tolerated',
- run: (ctx) => {
- const declared = (ctx.card.extensions ?? []) as Array<{ uri?: string }>
- if (!Array.isArray(declared)) return fail('extensions is not an array')
- const missingUri = declared.filter((e) => typeof e.uri !== 'string')
- return missingUri.length ? fail(`${missingUri.length} extension entr(ies) without a uri`) : pass(`${declared.length} declared`)
+ id: 'agent-list-authenticated',
+ title: 'agent.list REJECTS a bad credential rather than returning an empty list',
+ run: async (ctx) => {
+ const found = down(ctx); if (found) return found
+ if (!ctx.badKey) return skip('pass --bad-key to check this')
+ const res = await rpc(ctx, 'agent.list', {}, ctx.badKey)
+ const code = await errorCode(res)
+ if (code === 'unauthenticated') return pass()
+ const agents = ((await body(res)).result as { agents?: unknown } | undefined)?.agents
+ if (Array.isArray(agents)) {
+ return fail('an invalid credential got a list back — an empty one reads to the user as "you have no agents" instead of "your credential is wrong"')
+ }
+ return fail(`answered ${code ?? `HTTP ${res.status}`}, expected \`unauthenticated\``)
},
},
{
- id: 'HP-023',
- title: 'skills[] is a non-empty agent list',
- run: (ctx) => {
- const skills = (ctx.card.skills ?? []) as Array<{ id?: string; name?: string }>
- if (!skills.length) return fail('no skills — the client would show no agents at all')
- const unnamed = skills.filter((s) => !s.id || !s.name)
- return unnamed.length ? fail(`${unnamed.length} skill(s) missing id or name`) : pass(`${skills.length} skill(s)`)
+ id: 'agent-mutations',
+ title: 'agent.create / rename / delete either work or refuse with a reason',
+ run: async (ctx) => {
+ const found = down(ctx); if (found) return found
+ // There is no capability to declare, so a provider whose agents live in its own product is
+ // conformant — it answers `invalid_request` with a message the UI shows the user, which beats a
+ // greyed-out button with no explanation. What is NOT conformant is silence or `unsupported`.
+ //
+ // An EMPTY name is the probe on purpose: a conformant provider refuses it, so the usual outcome
+ // is that nothing is created. This runner is pointed at LIVE endpoints with real credentials,
+ // and must not leave anything behind in somebody's tenant.
+ const res = await rpc(ctx, 'agent.create', { name: '' })
+ const b = await body(res)
+ const err = b.error as { code?: string; message?: string } | undefined
+ if (err?.code === 'unsupported') {
+ return fail('agent.create answered `unsupported` — refuse with `invalid_request` and a message the user can act on instead')
+ }
+ if (err?.code === 'invalid_request') {
+ return err.message
+ ? pass(`refuses with a reason: "${err.message}"`)
+ : warn('refuses, but carries no message — the UI then shows a failure with nothing to explain it')
+ }
+ if (b.result === undefined) return fail(`answered ${err?.code ?? `HTTP ${res.status}`}`)
+
+ // It accepted the empty name, so an agent now exists that nobody asked for. Remove it before
+ // reporting: a conformance run that quietly adds rows to a partner's product is not a test, it
+ // is a side effect.
+ const created = (b.result as { id?: unknown }).id
+ if (typeof created !== 'string' || !created) {
+ return warn('an EMPTY name was accepted and the response carried no id, so the agent it created CANNOT be cleaned up — delete it by hand')
+ }
+ const cleanup = await errorCode(await rpc(ctx, 'agent.delete', { agentId: created }))
+ return cleanup
+ ? fail(`an empty name was accepted as agent "${created}", and deleting it answered ${cleanup} — that agent is now orphaned in this tenant`)
+ : warn(`an EMPTY name was accepted; the agent it created ("${created}") was deleted again. Mutations are reachable but the validation is loose`)
},
},
{
- id: 'HP-100',
- title: 'SendStreamingMessage returns Server-Sent Events',
+ id: 'unknown-method',
+ title: 'An unknown method is refused with `unsupported`',
run: async (ctx) => {
- const { res } = await stream(ctx, 'conformance: hello')
- const ct = res.headers.get('content-type') ?? ''
- return ct.includes('text/event-stream') ? pass(ct) : fail(`content-type was "${ct}", expected text/event-stream`)
+ const found = down(ctx); if (found) return found
+ const res = await rpc(ctx, 'agent.nonexistentMethod', {})
+ const code = await errorCode(res)
+ return code === 'unsupported'
+ ? pass()
+ : fail(`an invented method answered ${code ?? `HTTP ${res.status}`}, expected \`unsupported\``)
},
},
+
+ // ── Sending a turn ─────────────────────────────────────────────────────────────────────────────
{
- id: 'HP-101',
- title: 'A new chat opens on a fresh contextId',
+ id: 'streams-sse',
+ title: 'agent.send streams Server-Sent Events',
run: async (ctx) => {
- const { events } = await stream(ctx, 'conformance: new chat', { contextId: `conf-ctx-${Date.now()}` })
- if (!events.length) return fail('no events received')
- const ids = new Set(events.map((e) => e.contextId).filter(Boolean))
- return ids.size === 1 ? pass([...ids][0]) : fail(`stream spanned ${ids.size} contextIds; expected exactly one`)
+ const found = down(ctx) ?? noAgent(ctx); if (found) return found
+ const res = await rpc(ctx, 'agent.send', { agentId: ctx.agentId, turnId: mintTurnId(), message: { text: 'hello' } })
+ const type = res.headers.get('content-type') ?? ''
+ if (!type.includes('text/event-stream')) {
+ void res.body?.cancel()
+ return fail(`content-type is "${type}" — a non-streaming provider is unusable, the product renders output as it arrives`)
+ }
+ const events = await drain(ctx, res)
+ return events.length ? pass(`${events.length} event(s)`) : fail('stream carried no events')
},
},
{
- id: 'HP-102',
- title: 'Every stream ends with a terminal task state',
+ id: 'terminal-frame',
+ title: 'Every stream ends with EXACTLY ONE terminal event',
run: async (ctx) => {
- const { events } = await stream(ctx, 'conformance: terminal state')
- if (!events.length) return fail('no events received')
- const last = events[events.length - 1]!
- return TERMINAL.includes(last.status?.state ?? '')
- ? pass(last.status?.state)
- : fail(`stream ended on "${last.status?.state}" — a client cannot tell a finished turn from a dropped one`)
+ const found = down(ctx) ?? noAgent(ctx); if (found) return found
+ const { events } = await send(ctx, 'hello')
+ const ends = terminals(events)
+ if (ends.length === 1) {
+ return events.at(-1)?.kind === ends[0]!.kind
+ ? pass(ends[0]!.kind)
+ : fail(`terminal event ${ends[0]!.kind} was not last — ${events.at(-1)?.kind} followed it`)
+ }
+ return ends.length === 0
+ ? fail('stream ended with NO terminal event — clients must treat the turn as failed and the user sees a spinner that never resolves')
+ : fail(`${ends.length} terminal events: ${ends.map((e) => e.kind).join(', ')}`)
},
},
{
- id: 'HP-103',
- title: 'CancelTask stops a task and reports CANCELED',
+ id: 'cancel-supported',
+ title: 'turn.cancel is implemented',
run: async (ctx) => {
- if (!ctx.askPhrase) return skip('pass --ask-phrase <text> with a prompt that parks the agent, so there is something to cancel')
- const { events } = await stream(ctx, ctx.askPhrase)
- const taskId = events[0]?.taskId
- if (!taskId) return fail('no taskId observed, so cancellation cannot be tested')
- const res = await rpc(ctx, 'CancelTask', { taskId })
+ const found = down(ctx); if (found) return found
+ const res = await rpc(ctx, 'turn.cancel', { turnId: mintTurnId() })
const b = await body(res)
- const state = ((b.result ?? {}) as { status?: { state?: string } }).status?.state
- return state === 'TASK_STATE_CANCELED' ? pass() : fail(`CancelTask returned state "${state}"`)
+ const code = (b.error as { code?: unknown } | undefined)?.code
+ if (code === 'unsupported') return fail('turn.cancel is required — a user with no way to stop a runaway turn is the failure this exists for')
+ return b.result !== undefined ? pass() : fail(`answered ${typeof code === 'string' ? code : `HTTP ${res.status}`}`)
},
},
{
- id: 'HP-104',
- title: 'INPUT_REQUIRED pauses the task and accepts an answer on the same taskId',
+ id: 'early-cancel',
+ title: 'A client-minted turnId is honoured — cancel BEFORE the turn starts stops it',
run: async (ctx) => {
- if (!ctx.askPhrase) return skip('pass --ask-phrase <text> with a prompt that makes the agent ask a question')
- const { events } = await stream(ctx, ctx.askPhrase)
- const last = events[events.length - 1]
- if (last?.status?.state !== 'TASK_STATE_INPUT_REQUIRED') {
- return fail(`--ask-phrase did not produce INPUT_REQUIRED (ended on "${last?.status?.state}")`)
- }
- if (last.final) return fail('INPUT_REQUIRED was marked final; it is not a terminal state')
- const resumed = await drain(
- await rpc(ctx, 'SendStreamingMessage', {
- message: { role: 'ROLE_USER', messageId: `conf-answer-${Date.now()}`, taskId: last.taskId, parts: [{ text: 'yes' }] },
- }),
- )
- const end = resumed[resumed.length - 1]
- return TERMINAL.includes(end?.status?.state ?? '')
- ? pass('paused, answered, completed')
- : fail(`answering on the same taskId did not resume the task (ended on "${end?.status?.state}")`)
+ const found = down(ctx) ?? noAgent(ctx); if (found) return found
+ // The whole reason the client mints the id: a user who presses stop in the first 200ms has
+ // something to name. A provider that mints its own cannot satisfy this.
+ const turnId = mintTurnId()
+ await rpc(ctx, 'turn.cancel', { turnId })
+ const { events } = await send(ctx, 'hello', { turnId })
+ const ends = terminals(events)
+ if (ends.length === 1 && ends[0]!.kind === 'turn_cancelled') return pass()
+ return fail(`a turn cancelled before it began ended as ${ends[0]?.kind ?? 'nothing'} — the API accepted the cancel and the engine ignored it`)
},
},
{
- id: 'HP-105',
- title: 'Assistant output arrives as Parts on status updates',
+ id: 'input-required',
+ title: 'A question to the user pauses the turn and resumes on the same turnId',
run: async (ctx) => {
- const { events } = await stream(ctx, 'conformance: say something')
- const parts = events.flatMap((e) => e.status?.message?.parts ?? [])
- return parts.length ? pass(`${parts.length} part(s)`) : fail('the turn produced no Parts at all')
+ const found = down(ctx); if (found) return found
+ if (!ctx.askPhrase) return skip('pass --ask-phrase "<prompt that makes the agent ask>" to check this')
+ const missing = noAgent(ctx); if (missing) return missing
+ const first = await send(ctx, ctx.askPhrase)
+ const paused = terminals(first.events)[0]
+ if (paused?.kind !== 'turn_input_required') {
+ return fail(`expected turn_input_required, got ${paused?.kind ?? 'no terminal event'}`)
+ }
+ if (typeof paused.prompt !== 'string' || !paused.prompt) return fail('turn_input_required carried no prompt to show the user')
+ const resumed = await send(ctx, 'the answer', { turnId: first.turnId, resume: true })
+ const end = terminals(resumed.events)[0]
+ return end && end.kind !== 'turn_input_required'
+ ? pass(`resumed and ended as ${end.kind}`)
+ : fail('resuming the same turnId did not continue the turn')
},
},
{
- id: 'HP-106',
- title: 'Image attachments are accepted or refused loudly',
+ id: 'attachments',
+ title: 'Image attachments are accepted, or the turn fails loudly',
run: async (ctx) => {
+ const found = down(ctx) ?? noAgent(ctx); if (found) return found
const png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='
- const { events } = await stream(ctx, 'conformance: describe this image', {
- parts: [{ text: 'conformance: describe this image' }, { raw: png, mediaType: 'image/png' }],
+ const res = await rpc(ctx, 'agent.send', {
+ agentId: ctx.agentId,
+ turnId: mintTurnId(),
+ message: { text: 'what is this?', attachments: [{ mediaType: 'image/png', data: png }] },
})
- const last = events[events.length - 1]
- const state = last?.status?.state ?? ''
- if (state === 'TASK_STATE_FAILED') return pass('refused explicitly')
- if (TERMINAL.includes(state)) {
- return warn('the turn completed — verify by hand that the image was actually used; silently discarding it violates HP-106 and cannot be detected from outside')
+ if (!res.headers.get('content-type')?.includes('text/event-stream')) {
+ void res.body?.cancel()
+ return fail('an attachment made the provider refuse to stream at all')
}
- return fail(`ended on "${state}"`)
+ const ends = terminals(await drain(ctx, res))
+ if (!ends.length) return fail('no terminal event')
+ return warn(`turn ended as ${ends[0]!.kind}. Whether the image was READ or silently discarded cannot be seen from outside — confirm by hand that a provider which cannot accept images fails the turn instead of ignoring them`)
},
},
+
+ // ── History ────────────────────────────────────────────────────────────────────────────────────
{
- id: 'HP-200',
- title: 'ListTasks filters by contextId',
+ id: 'history',
+ title: 'agent.history returns the agent transcript',
run: async (ctx) => {
- const ctxId = `conf-list-${Date.now()}`
- await stream(ctx, 'conformance: first', { contextId: ctxId })
- await stream(ctx, 'conformance: second', { contextId: ctxId })
- const b = await body(await rpc(ctx, 'ListTasks', { contextId: ctxId }))
- const tasks = ((b.result ?? {}) as { tasks?: Array<{ contextId?: string }> }).tasks
- if (!Array.isArray(tasks)) return fail('ListTasks did not return a tasks array')
- if (tasks.length < 2) return fail(`expected at least 2 tasks in the context, saw ${tasks.length}`)
- const foreign = tasks.filter((t) => t.contextId !== ctxId)
- return foreign.length ? fail(`${foreign.length} task(s) from another context leaked into the filter`) : pass(`${tasks.length} task(s)`)
+ const found = down(ctx) ?? noAgent(ctx); if (found) return found
+ const res = await rpc(ctx, 'agent.history', { agentId: ctx.agentId })
+ const events = ((await body(res)).result as { events?: unknown } | undefined)?.events
+ return Array.isArray(events)
+ ? pass(`${events.length} event(s)`)
+ : fail('no `events` array — Autonomous stores no transcript for a provider machine, so a page refresh loses the conversation without this')
},
},
{
- id: 'HP-201',
- title: 'GetTask returns the task with its history',
+ id: 'history-matches-stream',
+ title: 'History returns the SAME event objects the stream emitted',
run: async (ctx) => {
- const { events } = await stream(ctx, 'conformance: history please')
- const taskId = events[0]?.taskId
- if (!taskId) return fail('no taskId observed')
- const b = await body(await rpc(ctx, 'GetTask', { taskId }))
- const task = b.result as { history?: unknown[]; status?: { state?: string } } | undefined
- if (!task) return fail('GetTask returned no task')
- return Array.isArray(task.history) && task.history.length
- ? pass(`${task.history.length} message(s)`)
- : fail('GetTask returned no history — a page refresh would lose the conversation')
+ const found = down(ctx) ?? noAgent(ctx); if (found) return found
+ const { events } = await send(ctx, 'a distinctive conformance probe')
+ const live = content(events)
+ if (!live.length) return skip('the turn emitted no content events to compare')
+
+ const res = await rpc(ctx, 'agent.history', { agentId: ctx.agentId })
+ const stored = ((await body(res)).result as { events?: Event[] } | undefined)?.events ?? []
+ // Deltas are coalesced on BOTH sides first — see `coalesceDeltas`.
+ const wanted = coalesceDeltas(live)
+ const got = coalesceDeltas(content(stored)).slice(-wanted.length)
+ return JSON.stringify(got) === JSON.stringify(wanted)
+ ? pass(`${wanted.length} event(s) match`)
+ : fail(`history and the live stream disagree — one shape and one mapper is what stops "what you saw" and "what you see after a refresh" from drifting.\n live: ${JSON.stringify(wanted)}\n history: ${JSON.stringify(got)}`)
},
},
{
- id: 'HP-202',
- title: 'GetTask returns the whole transcript in one response',
+ id: 'history-paging',
+ title: 'History windows with limit/before and hands back a cursor',
run: async (ctx) => {
- const { events } = await stream(ctx, 'conformance: whole transcript')
- const taskId = events[0]?.taskId
- if (!taskId) return fail('no taskId observed')
- const b = await body(await rpc(ctx, 'GetTask', { taskId }))
- const task = (b.result ?? {}) as Record<string, unknown>
- const paging = ['nextPageToken', 'hasMore', 'cursor'].filter((k) => k in task)
- return paging.length
- ? fail(`response carries paging field(s) ${paging.join(', ')}; pagination is not part of this revision`)
+ const found = down(ctx) ?? noAgent(ctx); if (found) return found
+ const all = ((await body(await rpc(ctx, 'agent.history', { agentId: ctx.agentId }))).result as { events?: Event[] })?.events ?? []
+ if (all.length < 2) return skip(`only ${all.length} event(s) in the transcript — send a few turns first`)
+
+ const first = (await body(await rpc(ctx, 'agent.history', { agentId: ctx.agentId, limit: 1 }))).result as
+ { events?: Event[]; nextBefore?: unknown } | undefined
+ if ((first?.events ?? []).length !== 1) return fail(`limit: 1 returned ${(first?.events ?? []).length} events`)
+ if (typeof first?.nextBefore !== 'string') {
+ return fail('no `nextBefore` although older events exist — the client cannot page and simply stops')
+ }
+ const older = (await body(await rpc(ctx, 'agent.history', { agentId: ctx.agentId, limit: 1, before: first.nextBefore }))).result as
+ { events?: Event[] } | undefined
+ const olderEvents = older?.events ?? []
+ if (!olderEvents.length) return fail('paging with the returned cursor came back empty')
+ return JSON.stringify(olderEvents[0]) === JSON.stringify(first.events?.[0])
+ ? fail('the cursor returned the SAME event again — paging would never terminate')
: pass()
},
},
{
- id: 'HP-203',
- title: 'Oversized transcripts are marked, never silently truncated',
- run: () => skip('not verifiable without a session large enough to cross the 5 MB ceiling'),
- },
- {
- id: 'HP-210',
- title: 'Part metadata uses recognised autonomous.ai/* keys',
- run: async (ctx) => {
- const { events } = await stream(ctx, 'conformance: metadata check')
- const metas = events.flatMap((e) => e.status?.message?.parts ?? []).map((p) => p.metadata).filter(Boolean) as Record<string, unknown>[]
- if (!metas.length) return skip('this provider emits no metadata — conformant under HP-211, nothing to validate')
- const kinds = metas.map((m) => m['autonomous.ai/kind']).filter(Boolean) as string[]
- const bad = kinds.filter((k) => !KNOWN_KINDS.includes(k))
- return bad.length ? fail(`unrecognised kind(s): ${[...new Set(bad)].join(', ')}`) : pass(`${kinds.length} kind(s), all recognised`)
- },
- },
- {
- id: 'HP-211',
- title: 'A provider emitting no metadata is still conformant',
- run: () => skip('a property of the client, not of the provider — asserted by the client test suite'),
- },
- {
- id: 'HP-220',
- title: 'Statistics are omitted rather than fabricated',
- run: () => skip('not verifiable from outside — a wrong count is indistinguishable from a right one'),
+ id: 'transcript-truncation',
+ title: 'An oversized transcript is marked, not silently truncated',
+ run: () => skip('not verifiable from outside — needs a transcript past the ceiling; confirm by hand that `truncated: true` appears rather than the tail simply going missing'),
},
+
+ // ── The event vocabulary ───────────────────────────────────────────────────────────────────────
{
- id: 'HP-300',
- title: 'workspace-files: autonomous.ListFiles and autonomous.ReadFile',
- run: async (ctx) => {
- if (!declares(ctx, EXT.FILES)) return skip('not declared — absence is a legitimate answer (HP-022)')
- const agentId = firstSkillId(ctx)
- if (!agentId) return fail('extension declared but the card exposes no skill to scope a call to')
- const b = await body(await rpc(ctx, 'autonomous.ListFiles', { agentId }))
- const err = b.error as { code?: number } | undefined
- if (err?.code === -32601) return fail('declared in the Agent Card but autonomous.ListFiles is not implemented')
- if (err) return fail(`autonomous.ListFiles returned error ${err.code}`)
- const files = ((b.result ?? {}) as { files?: unknown }).files
- return Array.isArray(files) ? pass(`${files.length} entr(ies)`) : fail('response has no `files` array')
+ id: 'event-kinds',
+ title: 'Every event kind emitted is one this protocol defines',
+ run: (ctx) => {
+ const found = down(ctx); if (found) return found
+ if (!ctx.seenKinds.size) return fail('no kinds seen at all across the whole run')
+ const unknown = [...ctx.seenKinds].filter((k) => !ALL_KINDS.includes(k))
+ const covered = ALL_KINDS.filter((k) => ctx.seenKinds.has(k))
+ // Emitting only SOME kinds is correct — a provider that never uses tools never emits tool events.
+ // Whether all fourteen are reachable at all is asserted in the e2e suite, which can drive a
+ // provider it controls; from outside, an un-emitted kind is indistinguishable from an unused one.
+ if (unknown.length) {
+ return warn(`unrecognised, and therefore ignored by clients: ${unknown.join(', ')}. Covered ${covered.length}/${ALL_KINDS.length}`)
+ }
+ return pass(`${covered.length}/${ALL_KINDS.length} kinds exercised: ${covered.join(', ')}`)
},
},
{
- id: 'HP-301',
- title: 'workspace-write: mutation methods exist',
+ id: 'bare-text',
+ title: 'An event with no `kind` is conformant and renders as plain text',
run: async (ctx) => {
- if (!declares(ctx, EXT.WRITE)) return skip('not declared — absence is a legitimate answer (HP-022)')
- // Probe WITHOUT mutating: call with deliberately missing params and require "invalid params"
- // rather than "method not found". Running a real create/delete against someone's live workspace
- // is not something a conformance runner gets to do.
- const b = await body(await rpc(ctx, 'autonomous.RenameAgent', {}))
- const err = b.error as { code?: number } | undefined
- if (err?.code === -32601) return fail('declared in the Agent Card but autonomous.RenameAgent is not implemented')
- if (err?.code === -32602) return pass('method present (probed non-destructively with empty params)')
- return warn(`probe returned ${err ? `error ${err.code}` : 'a result'} — verify the mutation methods by hand; the runner will not mutate a live workspace`)
+ const found = down(ctx) ?? noAgent(ctx); if (found) return found
+ const { events } = await send(ctx, 'plain')
+ const bare = events.find((e) => e.kind === undefined && typeof e.text === 'string')
+ return bare
+ ? pass('provider emitted a bare {text} event')
+ : skip('this provider always sets `kind`, which is allowed — a bare {text} event is a permission, not an obligation. Autonomous accepts either')
},
},
{
- id: 'HP-302',
- title: 'session-recap: autonomous.GetRecap',
+ id: 'tool-pairing',
+ title: 'tool_start and tool_end carry a toolId and pair up',
run: async (ctx) => {
- if (!declares(ctx, EXT.RECAP)) return skip('not declared — absence is a legitimate answer (HP-022)')
- const agentId = firstSkillId(ctx)
- if (!agentId) return fail('extension declared but the card exposes no skill to scope a call to')
- const b = await body(await rpc(ctx, 'autonomous.GetRecap', { agentId, n: 2 }))
- const err = b.error as { code?: number } | undefined
- if (err?.code === -32601) return fail('declared in the Agent Card but autonomous.GetRecap is not implemented')
- if (err) return fail(`autonomous.GetRecap returned error ${err.code}`)
- const result = (b.result ?? {}) as { entries?: unknown }
- if (!Array.isArray(result.entries)) return fail('response has no `entries` array')
- const overlong = (result.entries as Array<{ recap?: string }>).filter((e) => (e.recap?.length ?? 0) > 200)
- return overlong.length
- ? fail(`${overlong.length} recap(s) exceed the 200-character ceiling the device renders`)
- : pass(`${result.entries.length} entr(ies)`)
+ const found = down(ctx) ?? noAgent(ctx); if (found) return found
+ const { events } = await send(ctx, 'hello')
+ const tools = events.filter((e) => e.kind === 'tool_start' || e.kind === 'tool_end')
+ if (!tools.length) return skip('this turn used no tools')
+ const missing = tools.filter((e) => typeof e.toolId !== 'string' || !e.toolId)
+ if (missing.length) return fail(`${missing.length} tool event(s) without a toolId — an unpaired call renders as a row that never resolves`)
+ const starts = tools.filter((e) => e.kind === 'tool_start').map((e) => e.toolId)
+ const unique = new Set(starts)
+ return unique.size === starts.length
+ ? pass(`${starts.length} tool call(s)`)
+ : fail('a toolId was reused within one turn — tools can overlap, so ids must be unique')
},
},
{
- id: 'HP-303',
- title: 'voice: autonomous.RouteVoice',
+ id: 'recap',
+ title: 'agent.recap returns the agent’s last recap, or nothing',
run: async (ctx) => {
- if (!declares(ctx, EXT.VOICE)) return skip('not declared — Autonomous routes from skills[] by default')
- const b = await body(await rpc(ctx, 'autonomous.RouteVoice', { transcript: 'conformance probe' }))
- const err = b.error as { code?: number } | undefined
- if (err?.code === -32601) return fail('declared in the Agent Card but autonomous.RouteVoice is not implemented')
- if (err) return fail(`autonomous.RouteVoice returned error ${err.code}`)
- const result = (b.result ?? {}) as { agentId?: unknown }
- return 'agentId' in result
- ? pass(result.agentId === null ? 'declined, routing handed back' : String(result.agentId))
- : fail('response has no `agentId` (use null to decline)')
- },
- },
- {
- id: 'HP-310',
- title: 'Extension methods are namespaced autonomous.<Verb>',
- run: (ctx) => {
- const declared = ((ctx.card.extensions ?? []) as Array<{ uri?: string }>).map((e) => e.uri ?? '')
- const ours = declared.filter((u) => KNOWN_EXTENSIONS.includes(u))
- return ours.length
- ? pass('verified indirectly — every extension probe above uses the autonomous.* namespace')
- : skip('no Autonomous extensions declared')
+ const found = down(ctx) ?? noAgent(ctx); if (found) return found
+ const res = await rpc(ctx, 'agent.recap', { agentId: ctx.agentId })
+ const b = await body(res)
+ const code = (b.error as { code?: unknown } | undefined)?.code
+ if (code === 'unsupported') {
+ return fail('agent.recap answered `unsupported` — a provider that summarises nothing answers with no `recap`, and Autonomous then excerpts the turn itself')
+ }
+ const result = b.result as { recap?: unknown; text?: unknown; turnId?: unknown } | undefined
+ if (!result || typeof result !== 'object') return fail('no result object')
+ // ABSENT is a legitimate answer, not a failure — the same convention `recap_end` uses.
+ if (result.recap === undefined) return pass('nothing summarised yet — Autonomous derives a recap from the turn text instead')
+ if (typeof result.recap !== 'string' || !result.recap.trim()) {
+ return fail('`recap` is present but not a usable headline — the device renders it on a tile, and a blank one is worse than none')
+ }
+ if (result.text !== undefined && typeof result.text !== 'string') return fail('`text` is present but not a string')
+ return typeof result.turnId === 'string'
+ ? pass(`"${result.recap}"`)
+ : warn('carries no turnId — a client asking the instant a turn ends can then receive the PREVIOUS turn\'s summary with no way to tell')
},
},
{
- id: 'HP-311',
- title: 'An UNDECLARED extension method is rejected with -32601',
- run: async (ctx) => {
- const undeclared = ([
- [EXT.FILES, 'autonomous.ListFiles'],
- [EXT.WRITE, 'autonomous.CreateAgent'],
- [EXT.RECAP, 'autonomous.GetRecap'],
- [EXT.VOICE, 'autonomous.RouteVoice'],
- ] as const).filter(([uri]) => !declares(ctx, uri))
- if (!undeclared.length) return skip('this provider declares every extension — nothing undeclared to probe')
- const answered: string[] = []
- for (const [, method] of undeclared) {
- const b = await body(await rpc(ctx, method, {}))
- const err = b.error as { code?: number } | undefined
- if (err?.code !== -32601) answered.push(method)
- }
- return answered.length
- ? fail(`answered undeclared method(s): ${answered.join(', ')} — the Agent Card becomes untrustworthy`)
- : pass(`${undeclared.length} undeclared method(s) correctly rejected`)
- },
+ id: 'no-fabricated-stats',
+ title: 'Statistics are omitted rather than fabricated',
+ run: () => skip('not verifiable from outside — a plausible number and a true one look identical. Confirm by hand that counts and timestamps nobody recorded are absent rather than guessed'),
},
+
+ // ── Forward compatibility and operations ───────────────────────────────────────────────────────
{
- id: 'HP-400',
- title: 'An unknown method is rejected without breaking the connection',
+ id: 'unknown-fields',
+ title: 'Unrecognised request fields are ignored, not fatal',
run: async (ctx) => {
- const res = await rpc(ctx, 'ConformanceNoSuchMethod', {})
+ const found = down(ctx); if (found) return found
+ const res = await rpc(ctx, 'agent.list', { somethingFromALaterRevision: true, nested: { x: 1 } })
const b = await body(res)
- const err = b.error as { code?: number } | undefined
- if (!err) return fail('an unknown method was not rejected')
- // Prove the endpoint still works afterwards.
- const after = await rpc(ctx, 'ListTasks', {})
- return after.ok ? pass(`code ${err.code}, endpoint still healthy`) : fail('the endpoint stopped responding after an unknown method')
+ return b.result !== undefined
+ ? pass()
+ : fail('an unknown field broke the call — a client on a newer revision would then fail against you entirely')
},
},
{
- id: 'HP-900',
- title: 'All traffic over TLS',
- run: (ctx) => (ctx.url.startsWith('https://') ? pass() : warn('plain HTTP — acceptable locally, a violation in production')),
+ id: 'rate-limiting',
+ title: 'Rate limiting per machine',
+ run: () => skip('not verifiable without flooding a real endpoint, which a conformance run must not do'),
},
{
- id: 'HP-902',
- title: 'Rate limiting',
- run: () => skip('enforced by Autonomous on its side, not a provider obligation to demonstrate'),
- },
- {
- id: 'HP-903',
+ id: 'credential-not-logged',
title: 'The credential is not logged or forwarded',
- run: () => skip('not verifiable from outside — covered by the onboarding review, not by this runner'),
+ run: () => skip('not verifiable from outside — needs a code and log review at the provider'),
},
]
@@ -521,19 +562,24 @@ export interface RunSummary {
}
export async function runConformance(opts: { url: string; key: string; badKey?: string; askPhrase?: string }): Promise<RunSummary> {
- const base = opts.url.replace(/\/+$/, '')
- // An unreachable or malformed endpoint must be REPORTED, not thrown. A conformance runner that
- // crashes when the provider is down is useless at exactly the moment it is most needed.
- let card: Record<string, unknown> = {}
- let cardError: string | undefined
+ const ctx: Ctx = {
+ url: opts.url.replace(/\/+$/, ''),
+ key: opts.key,
+ badKey: opts.badKey,
+ askPhrase: opts.askPhrase,
+ seenKinds: new Set(),
+ }
+
+ // Resolve one real agent up front, so no check has to guess an id. An unreachable or malformed
+ // endpoint must be REPORTED, not thrown: a runner that crashes when the provider is down is useless
+ // at exactly the moment it is most needed.
try {
- const cardRes = await fetch(`${base}/.well-known/agent-card.json`)
- if (cardRes.ok) card = (await cardRes.json()) as Record<string, unknown>
- else cardError = `agent card responded ${cardRes.status}`
+ const b = await body(await rpc(ctx, 'agent.list', {}))
+ const id = (b.result as { agents?: Array<{ id?: unknown }> } | undefined)?.agents?.[0]?.id
+ if (typeof id === 'string') ctx.agentId = id
} catch (err) {
- cardError = `could not reach ${base} — ${err instanceof Error ? err.message : String(err)}`
+ ctx.unreachable = `could not reach ${ctx.url} — ${err instanceof Error ? err.message : String(err)}`
}
- const ctx: Ctx = { url: base, key: opts.key, badKey: opts.badKey, askPhrase: opts.askPhrase, card, cardError }
const results: RunSummary['results'] = []
for (const check of CHECKS) {
@@ -558,14 +604,15 @@ export async function runConformance(opts: { url: string; key: string; badKey?:
const MARK: Record<Outcome, string> = { PASS: '✔', FAIL: '✖', SKIP: '–', WARN: '!' }
export function format(summary: RunSummary): string {
+ const width = Math.max(...summary.results.map((r) => r.id.length))
const lines = summary.results.map((r) => {
- const head = `${MARK[r.outcome]} ${r.id.padEnd(7)} ${r.title}`
- return r.detail ? `${head}\n ${r.detail}` : head
+ const head = `${MARK[r.outcome]} ${r.id.padEnd(width)} ${r.title}`
+ return r.detail ? `${head}\n ${r.detail}` : head
})
lines.push('')
lines.push(`${summary.pass} passed · ${summary.fail} failed · ${summary.warn} need manual review · ${summary.skip} not verifiable from outside`)
if (summary.skip || summary.warn) {
- lines.push('Every skipped and manual clause states its reason above — nothing was checked silently.')
+ lines.push('Every skipped and manual check states its reason above — nothing was checked silently.')
}
return lines.join('\n')
}
@@ -576,20 +623,17 @@ function arg(name: string): string | undefined {
}
if (process.argv[1] && import.meta.url === `file://${process.argv[1]}`) {
- const url = arg('url') ?? 'http://127.0.0.1:4501'
+ const url = arg('url') ?? 'http://127.0.0.1:4319'
const key = arg('key') ?? 'conformance'
const badKey = arg('bad-key')
const askPhrase = arg('ask-phrase')
console.log(`Machine provider conformance — ${url}`)
- console.log(`Spec: spec/README.md · ${CHECKS.length} clauses\n`)
+ console.log(`Spec: spec/README.md · ${CHECKS.length} checks\n`)
const summary = await runConformance({ url, key, badKey, askPhrase })
console.log(format(summary))
if (!badKey || !askPhrase) {
- console.log('\nTip: --bad-key <invalid credential> and --ask-phrase <prompt that makes the agent ask> unlock 3 more clauses.')
+ console.log('\nTip: --bad-key <invalid credential> and --ask-phrase <prompt that makes the agent ask> unlock 4 more checks.')
}
process.exit(summary.fail ? 1 : 0)
}
-
-/** Re-exported so the reference provider's own agent card can be diffed against expectations in tests. */
-export { AGENT_CARD }
diff --git a/provider/reference-provider/src/scenarios.ts b/provider/reference-provider/src/scenarios.ts
index 8310e28d6..117dd2dd5 100644
--- a/provider/reference-provider/src/scenarios.ts
+++ b/provider/reference-provider/src/scenarios.ts
@@ -3,15 +3,14 @@
*
* The point of this file is the HOSTILE cases, not the happy one. A reference implementation that only
* demonstrates success teaches a partner nothing about the failure modes their integration will
- * actually hit, and gives the backend client (phase 5) nothing to harden against.
+ * actually hit, and gives the backend client nothing to harden against.
*/
-import { TaskState, type Part, type TaskStateValue } from './types.js'
+import type { ProviderEvent } from './types.js'
export type Step =
- | { kind: 'parts'; parts: Part[] }
- /** Terminal or intermediate state transition. */
- | { kind: 'state'; state: TaskStateValue; text?: string }
- /** Abort the HTTP response mid-frame, without a terminal state. Violates HP-102 on purpose. */
+ /** One event on the stream. */
+ | { kind: 'event'; event: ProviderEvent }
+ /** Abort the HTTP response mid-frame, with NO terminal event. Breaks the one-terminal rule on purpose. */
| { kind: 'die' }
export interface Scenario {
@@ -22,64 +21,36 @@ export interface Scenario {
steps: Step[]
}
-const meta = (kind: NonNullable<Part['metadata']>['autonomous.ai/kind'], extra: Part['metadata'] = {}): Part['metadata'] => ({
- 'autonomous.ai/kind': kind,
- ...extra,
-})
+const ev = (event: ProviderEvent): Step => ({ kind: 'event', event })
-/** The full-fidelity turn: thinking, a tool call, assistant text, completion. */
+/** The full-fidelity turn: thinking, a tool call, assistant text, a recap, completion. */
const RICH: Step[] = [
- { kind: 'parts', parts: [{ text: 'Checking pacing…', metadata: meta('thinking_delta', { 'autonomous.ai/thinkingId': 't1' }) }] },
- { kind: 'parts', parts: [{ text: '', metadata: meta('thinking_title', { 'autonomous.ai/thinkingId': 't1', 'autonomous.ai/title': 'Checking the budget data' }) }] },
- {
- kind: 'parts',
- parts: [
- {
- text: '',
- metadata: meta('tool_start', {
- 'autonomous.ai/toolCallId': 'c7',
- 'autonomous.ai/tool': 'query_spend',
- 'autonomous.ai/toolInput': { account: 'acme', window: '7d' },
- }),
- },
- ],
- },
- {
- kind: 'parts',
- parts: [
- {
- text: '7 rows',
- metadata: meta('tool_end', {
- 'autonomous.ai/toolCallId': 'c7',
- 'autonomous.ai/tool': 'query_spend',
- 'autonomous.ai/isError': false,
- 'autonomous.ai/summary': 'Returned 7 rows',
- 'autonomous.ai/durationSeconds': 1.4,
- }),
- },
- ],
- },
- { kind: 'parts', parts: [{ text: 'Acme is at 118% of pacing this week.', metadata: meta('text_delta') }] },
- { kind: 'state', state: TaskState.COMPLETED },
+ ev({ kind: 'thinking_delta', text: 'Checking pacing…', thinkingId: 't1' }),
+ ev({ kind: 'thinking_title', title: 'Checking the budget data', thinkingId: 't1' }),
+ ev({ kind: 'tool_start', toolId: 'c7', tool: 'query_spend', input: { account: 'acme', window: '7d' } }),
+ ev({ kind: 'tool_end', toolId: 'c7', tool: 'query_spend', ok: true, output: '7 rows', summary: 'Returned 7 rows', durationSeconds: 1.4 }),
+ ev({ kind: 'text_delta', text: 'Acme is at 118% of pacing this week.' }),
+ ev({ kind: 'done', text: 'Acme is at 118% of pacing this week.' }),
+ ev({ kind: 'turn_completed' }),
]
export const SCENARIOS: Scenario[] = [
{
id: 'plain',
trigger: 'plain',
- description: 'HP-211 — a provider that emits NO autonomous.ai/* metadata is conformant. Renders as plain text.',
+ description: 'An event with no `kind` at all is conformant. Renders as plain assistant text.',
steps: [
- { kind: 'parts', parts: [{ text: 'Plain text reply, no metadata at all.' }] },
- { kind: 'state', state: TaskState.COMPLETED },
+ { kind: 'event', event: { text: 'Plain text reply, no kind at all.' } },
+ ev({ kind: 'turn_completed' }),
],
},
{
id: 'ask',
trigger: 'ask me',
- description: 'HP-104 — the agent needs an answer. Enters INPUT_REQUIRED and waits for a message on the same taskId.',
+ description: 'The agent needs an answer. Ends the stream with turn_input_required and waits for a resumed send on the same turnId.',
steps: [
- { kind: 'parts', parts: [{ text: 'Which account did you mean?', metadata: meta('text_delta') }] },
- { kind: 'state', state: TaskState.INPUT_REQUIRED, text: 'Which account did you mean?' },
+ ev({ kind: 'text_delta', text: 'Which account did you mean?' }),
+ ev({ kind: 'turn_input_required', prompt: 'Which account did you mean?' }),
],
},
{
@@ -87,35 +58,56 @@ export const SCENARIOS: Scenario[] = [
trigger: 'fail',
description: 'A turn that fails partway through, after already emitting output.',
steps: [
- { kind: 'parts', parts: [{ text: 'Starting the query…', metadata: meta('text_delta') }] },
- { kind: 'state', state: TaskState.FAILED, text: 'Upstream data warehouse refused the connection.' },
+ ev({ kind: 'text_delta', text: 'Starting the query…' }),
+ ev({ kind: 'turn_failed', error: { code: 'internal', message: 'Upstream data warehouse refused the connection.' } }),
],
},
{
id: 'die',
trigger: 'die',
- description: 'The stream is cut without a terminal state — an HP-102 violation, present so the client can be hardened against it.',
+ description: 'The stream is cut with NO terminal event — present so the client can be hardened against it and so the conformance runner can be shown catching it.',
steps: [
- { kind: 'parts', parts: [{ text: 'Working on it…', metadata: meta('text_delta') }] },
+ ev({ kind: 'text_delta', text: 'Working on it…' }),
{ kind: 'die' },
],
},
{
id: 'compact',
trigger: 'compact',
- description: 'The provider compacted its own context and reports it. Autonomous never asks for this (spec §9).',
+ description: 'The provider compacted its own context and reports it. Autonomous never asks for this.',
+ steps: [
+ ev({ kind: 'context_compact', text: 'Compacted earlier turns to stay within context.' }),
+ ev({ kind: 'text_delta', text: 'Where were we?' }),
+ ev({ kind: 'turn_completed' }),
+ ],
+ },
+ {
+ id: 'recap',
+ trigger: 'recap',
+ description: 'The recap pushed on the turn’s own stream, bracketed so the client can show the wait.',
+ steps: [
+ ev({ kind: 'text_delta', text: 'Rebuilt the index.' }),
+ ev({ kind: 'done', text: 'Rebuilt the index.' }),
+ ev({ kind: 'recap_start' }),
+ ev({ kind: 'recap_end', recap: 'Rebuilt the index', text: 'Rebuilt the search index across 4 shards.' }),
+ ev({ kind: 'turn_completed' }),
+ ],
+ },
+ {
+ id: 'full',
+ trigger: 'everything',
+ description: 'Every content kind this protocol defines, in one turn. Exists so the e2e suite can assert the vocabulary is REACHABLE — from outside, a kind nobody emitted is indistinguishable from a kind nobody supports.',
steps: [
- {
- kind: 'parts',
- parts: [
- {
- text: 'Compacted earlier turns to stay within context.',
- metadata: meta('context_compact', { 'autonomous.ai/compacted': { userMessages: 12, assistantMessages: 12, toolUses: 41 } }),
- },
- ],
- },
- { kind: 'parts', parts: [{ text: 'Where were we?', metadata: meta('text_delta') }] },
- { kind: 'state', state: TaskState.COMPLETED },
+ ev({ kind: 'thinking_delta', text: 'Working out what to check…', thinkingId: 'f1' }),
+ ev({ kind: 'thinking_title', title: 'Planning the checks', thinkingId: 'f1' }),
+ ev({ kind: 'tool_start', toolId: 'f7', tool: 'query_spend', input: { account: 'acme', window: '7d' } }),
+ ev({ kind: 'tool_end', toolId: 'f7', tool: 'query_spend', ok: true, output: '7 rows', summary: 'Returned 7 rows', durationSeconds: 1.4 }),
+ ev({ kind: 'context_compact', text: 'Compacted earlier turns to stay within context.' }),
+ ev({ kind: 'text_delta', text: 'Acme is at 118% of pacing this week.' }),
+ ev({ kind: 'done', text: 'Acme is at 118% of pacing this week.' }),
+ ev({ kind: 'recap_start' }),
+ ev({ kind: 'recap_end', recap: 'Acme is over pace', text: 'Acme is at 118% of pacing this week.' }),
+ ev({ kind: 'turn_completed' }),
],
},
{
@@ -131,7 +123,14 @@ export function pickScenario(userText: string): Scenario {
return SCENARIOS.find((s) => s.trigger !== null && t.includes(s.trigger)) ?? SCENARIOS[SCENARIOS.length - 1]!
}
-/** Credential that makes every call fail authentication, for exercising HP-013. */
+/** The answer to `ask`, once the client resumes the same turn. */
+export const RESUMED: Step[] = [
+ { kind: 'event', event: { kind: 'text_delta', text: 'Acme, then. It is at 118% of pacing.' } },
+ { kind: 'event', event: { kind: 'done', text: 'Acme is at 118% of pacing.' } },
+ { kind: 'event', event: { kind: 'turn_completed' } },
+]
+
+/** Credential that makes every call fail authentication, for exercising the `credential-rejected` check. */
export const REJECTED_CREDENTIAL = 'bad-key'
/** Any other non-empty credential is accepted — this provider has no real user database. */
diff --git a/provider/reference-provider/src/server.spec.ts b/provider/reference-provider/src/server.spec.ts
index 84b4fa766..f671cb4d7 100644
--- a/provider/reference-provider/src/server.spec.ts
+++ b/provider/reference-provider/src/server.spec.ts
@@ -1,13 +1,10 @@
-// The reference provider IS the executable reading of the spec, so these tests are written as clause
-// checks: each name states the HP-xxx it pins. When the spec changes, these are the first thing that
-// should go red.
-import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
+// The reference provider IS the executable reading of the spec, so each test names the rule it pins.
+// When the spec changes, these are the first thing that should go red.
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
// Read at module load in server.ts — must be set before the import below.
process.env.STEP_DELAY_MS = '0'
const { start } = await import('./server.js')
-const { resetIds } = await import('./store.js')
-const { TaskState } = await import('./types.js')
let base: string
let stop: () => Promise<void>
@@ -18,16 +15,17 @@ beforeAll(async () => {
stop = s.close
})
afterAll(async () => { await stop() })
-beforeEach(() => { resetIds() })
const KEY = 'test-key'
+let seq = 0
+const turnId = (): string => `t-${++seq}`
-interface SseEvent { taskId: string; contextId: string; status: { state: string; message?: { parts: Array<{ text?: string; metadata?: Record<string, unknown> }> } }; final?: boolean }
+interface Event { kind?: string; [field: string]: unknown }
async function rpc(method: string, params: unknown, key: string = KEY): Promise<Response> {
return fetch(base, {
method: 'POST',
- headers: { 'content-type': 'application/json', 'x-api-key': key },
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
})
}
@@ -37,8 +35,8 @@ async function rpc(method: string, params: unknown, key: string = KEY): Promise<
const json = async (res: Response): Promise<any> => res.json()
/** Drains an SSE response into parsed events. Returns whatever arrived, even on an aborted stream. */
-async function drain(res: Response): Promise<SseEvent[]> {
- const events: SseEvent[] = []
+async function drain(res: Response): Promise<Event[]> {
+ const events: Event[] = []
if (!res.body) return events
const reader = res.body.getReader()
const decoder = new TextDecoder()
@@ -51,215 +49,281 @@ async function drain(res: Response): Promise<SseEvent[]> {
const frames = buffer.split('\n\n')
buffer = frames.pop() ?? ''
for (const frame of frames) {
- const line = frame.split('\n').find((l) => l.startsWith('data: '))
- if (line) events.push(JSON.parse(line.slice(6)) as SseEvent)
+ const line = frame.split('\n').find((l) => l.startsWith('data:'))
+ if (line) events.push(JSON.parse(line.slice(5).trim()) as Event)
}
}
} catch { /* an aborted stream is a valid outcome here — see the `die` test */ }
return events
}
-const userMessage = (text: string, extra: Record<string, unknown> = {}): unknown => ({
- message: { role: 'ROLE_USER', messageId: 'm-user', parts: [{ text }], ...extra },
-})
-
-const send = async (text: string, extra: Record<string, unknown> = {}): Promise<SseEvent[]> =>
- drain(await rpc('SendStreamingMessage', userMessage(text, extra)))
+const send = async (text: string, extra: Record<string, unknown> = {}): Promise<Event[]> =>
+ drain(await rpc('agent.send', { agentId: 'alpha', turnId: turnId(), message: { text }, ...extra }))
-const kinds = (events: SseEvent[]): string[] =>
- events.flatMap((e) => e.status.message?.parts.map((p) => p.metadata?.['autonomous.ai/kind'] as string) ?? []).filter(Boolean)
+const kinds = (events: Event[]): string[] => events.map((e) => e.kind ?? '(none)')
+const TERMINAL = ['turn_completed', 'turn_failed', 'turn_cancelled', 'turn_input_required']
-describe('agent card (HP-020 … HP-023)', () => {
- it('is served unauthenticated at the well-known path', async () => {
- const res = await fetch(`${base}/.well-known/agent-card.json`)
- expect(res.status).toBe(200)
- const card = await json(res)
- expect(card.name).toBeTruthy()
- expect(card.securitySchemes.apiKey).toBeTruthy()
+describe('there is nothing to discover', () => {
+ it('serves no descriptor — one URL, one credential header, eight methods', async () => {
+ // The endpoint that used to exist is gone rather than deprecated: a client that still fetches it
+ // must fail loudly at integration time, not read a stale document.
+ expect((await fetch(`${base}/.well-known/autonomous-provider.json`)).status).toBe(404)
})
- it('declares streaming, which HP-021 makes mandatory', async () => {
- const card = await json(await fetch(`${base}/.well-known/agent-card.json`))
- expect(card.capabilities.streaming).toBe(true)
- })
-
- it('exposes skills as the agent list and declares its extensions by exact URI', async () => {
- const card = await json(await fetch(`${base}/.well-known/agent-card.json`))
- expect(card.skills.length).toBeGreaterThan(0)
- expect(card.extensions.map((e: { uri: string }) => e.uri)).toContain('https://harness.autonomous.ai/api/a2a/ext/session-recap')
- // Undeclared extensions must read as absent — the reference provider leaves these out on purpose.
- expect(card.extensions.map((e: { uri: string }) => e.uri)).not.toContain('https://harness.autonomous.ai/api/a2a/ext/workspace-files')
+ it('answers every method it defines, and refuses everything else', async () => {
+ // Nothing is declared anywhere, so this list IS the surface. A method missing from it is a bug in
+ // the provider, not an undeclared optional feature. Driven against a THROWAWAY agent, because the
+ // loop really does rename and delete what it is pointed at.
+ const scratch = (await json(await rpc('agent.create', { name: 'Surface Probe' }))).result.id
+ const methods = ['agent.list', 'agent.send', 'agent.history', 'turn.cancel', 'agent.recap', 'agent.create', 'agent.rename', 'agent.delete']
+ const unsupported: string[] = []
+ for (const method of methods) {
+ const name = method === 'agent.create' ? 'Surface Probe Two' : 'Surface Probe Renamed'
+ const res = await rpc(method, { agentId: scratch, turnId: turnId(), name, message: { text: 'hi' } })
+ if (res.headers.get('content-type')?.includes('text/event-stream')) { await drain(res); continue }
+ if ((await json(res)).error?.code === 'unsupported') unsupported.push(method)
+ }
+ expect(unsupported).toEqual([])
+ await rpc('agent.delete', { agentId: 'surface-probe-two' })
})
})
-describe('authentication (HP-011 … HP-013)', () => {
+describe('authentication', () => {
it('rejects a missing credential with 401, not a generic failure', async () => {
const res = await fetch(base, {
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ListTasks', params: {} }),
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'agent.list', params: {} }),
})
expect(res.status).toBe(401)
- expect((await json(res)).error.code).toBe(-32001)
+ expect((await json(res)).error.code).toBe('unauthenticated')
})
it('rejects the known-bad credential distinguishably from an outage', async () => {
- const res = await rpc('ListTasks', {}, 'bad-key')
- expect(res.status).toBe(401)
+ const res = await rpc('agent.list', {}, 'bad-key')
+ expect((await json(res)).error.code).toBe('unauthenticated')
+ })
+})
+
+describe('agents', () => {
+ it('lists agents on an authenticated call — two credentials may legitimately see two lists', async () => {
+ const { result } = await json(await rpc('agent.list', {}))
+ expect(result.agents.map((a: { id: string }) => a.id)).toEqual(['alpha', 'beta'])
+ })
+
+ it('refuses a send to an agent it does not have', async () => {
+ const res = await rpc('agent.send', { agentId: 'ghost', turnId: turnId(), message: { text: 'hi' } })
+ expect((await json(res)).error.code).toBe('not_found')
+ })
+
+ it('creates, renames and deletes — and a FRESHLY created agent can be sent to at once', async () => {
+ // The trap this pins: an earlier version derived the set of valid ids once at module load, so an
+ // agent created a moment ago was refused with `not_found` by its very next send.
+ const created = (await json(await rpc('agent.create', { name: 'Fresh One', description: 'made in a test' }))).result
+ expect(created.id).toBeTruthy()
+
+ const events = await drain(await rpc('agent.send', { agentId: created.id, turnId: turnId(), message: { text: 'hello' } }))
+ expect(events.at(-1)!.kind).toBe('turn_completed')
+
+ const renamed = (await json(await rpc('agent.rename', { agentId: created.id, name: 'Renamed' }))).result
+ expect(renamed).toMatchObject({ id: created.id, name: 'Renamed' })
+
+ expect((await json(await rpc('agent.delete', { agentId: created.id }))).result.deleted).toBe(true)
+ const after = (await json(await rpc('agent.list', {}))).result.agents.map((a: { id: string }) => a.id)
+ expect(after).not.toContain(created.id)
+ })
+
+ it('refuses a mutation with a REASON rather than `unsupported`', async () => {
+ // There is no capability to declare, so refusal has to carry the explanation itself — that message
+ // is what the UI shows instead of a greyed-out button nobody can account for.
+ const { error } = await json(await rpc('agent.rename', { agentId: 'ghost', name: 'x' }))
+ expect(error.code).toBe('invalid_request')
+ expect(error.message).toContain('ghost')
})
})
-describe('streaming a turn (HP-100 … HP-105)', () => {
- it('opens with WORKING and closes with a terminal state marked final', async () => {
- const events = await send('did acme blow through budget?')
- expect(events[0]!.status.state).toBe(TaskState.WORKING)
- const last = events[events.length - 1]!
- expect(last.status.state).toBe(TaskState.COMPLETED)
- expect(last.final).toBe(true)
+describe('streaming a turn', () => {
+ it('opens with turn_started and closes with exactly one terminal event', async () => {
+ const events = await send('hello')
+ expect(events[0]!.kind).toBe('turn_started')
+ expect(events.filter((e) => TERMINAL.includes(e.kind ?? ''))).toHaveLength(1)
+ expect(events.at(-1)!.kind).toBe('turn_completed')
})
- it('carries thinking, tool and text kinds in Part.metadata', async () => {
- const seen = kinds(await send('check pacing'))
- expect(seen).toContain('thinking_delta')
- expect(seen).toContain('thinking_title')
- expect(seen).toContain('tool_start')
- expect(seen).toContain('tool_end')
- expect(seen).toContain('text_delta')
+ it('carries thinking, tool and text kinds as first-class fields', async () => {
+ const events = await send('hello')
+ expect(kinds(events)).toEqual(expect.arrayContaining(['thinking_delta', 'thinking_title', 'tool_start', 'tool_end', 'text_delta', 'done']))
})
- it('correlates tool_start and tool_end by the same toolCallId', async () => {
- const events = await send('check pacing')
- const ids = events
- .flatMap((e) => e.status.message?.parts ?? [])
- .filter((p) => ['tool_start', 'tool_end'].includes(p.metadata?.['autonomous.ai/kind'] as string))
- .map((p) => p.metadata?.['autonomous.ai/toolCallId'])
- expect(ids).toHaveLength(2)
- expect(ids[0]).toBe(ids[1])
+ it('correlates tool_start and tool_end by the same toolId', async () => {
+ const events = await send('hello')
+ const startId = events.find((e) => e.kind === 'tool_start')!.toolId
+ const endId = events.find((e) => e.kind === 'tool_end')!.toolId
+ expect(startId).toBeTruthy()
+ expect(endId).toBe(startId)
})
- it('a provider emitting NO metadata is still conformant (HP-211)', async () => {
- const events = await send('plain please')
- expect(kinds(events)).toHaveLength(0)
- expect(events[events.length - 1]!.status.state).toBe(TaskState.COMPLETED)
- const text = events.flatMap((e) => e.status.message?.parts.map((p) => p.text) ?? []).join('')
- expect(text).toContain('Plain text')
+ it('a provider emitting NO kind is still conformant', async () => {
+ const events = await send('plain')
+ const bare = events.find((e) => e.kind === undefined)
+ expect(bare?.text).toBe('Plain text reply, no kind at all.')
})
- it('reports FAILED after already emitting output, rather than going silent', async () => {
- const events = await send('make this fail')
+ it('reports turn_failed after already emitting output, rather than going silent', async () => {
+ const events = await send('fail')
expect(kinds(events)).toContain('text_delta')
- expect(events[events.length - 1]!.status.state).toBe(TaskState.FAILED)
+ expect(events.at(-1)!.kind).toBe('turn_failed')
+ expect((events.at(-1)!.error as { code: string }).code).toBe('internal')
})
- it('refuses image attachments loudly instead of discarding them (HP-106)', async () => {
- const events = await send('look at this', {
- parts: [{ text: 'look at this' }, { raw: 'aGk=', mediaType: 'image/png' }],
- })
- const last = events[events.length - 1]!
- expect(last.status.state).toBe(TaskState.FAILED)
- expect(last.status.message?.parts[0]?.text).toMatch(/image/i)
+ it('brackets a pushed recap and persists it for the pull', async () => {
+ const events = await send('recap')
+ expect(kinds(events)).toEqual(expect.arrayContaining(['recap_start', 'recap_end']))
+ const { result } = await json(await rpc('agent.recap', { agentId: 'alpha' }))
+ // The SAME object the stream just pushed — one shape for a recap, however it is fetched.
+ expect(result).toMatchObject({ agentId: 'alpha', recap: 'Rebuilt the index' })
+ // The turnId is what lets a client tell THIS turn's recap from the previous one's.
+ expect(typeof result.turnId).toBe('string')
})
})
-describe('input required (HP-104)', () => {
- it('pauses in INPUT_REQUIRED and resumes when answered on the same taskId', async () => {
- const first = await send('ask me something')
- const pause = first[first.length - 1]!
- expect(pause.status.state).toBe(TaskState.INPUT_REQUIRED)
- expect(pause.final).toBeFalsy() // INPUT_REQUIRED is not terminal
-
- const resumed = await drain(
- await rpc('SendStreamingMessage', {
- message: { role: 'ROLE_USER', messageId: 'm-answer', taskId: pause.taskId, parts: [{ text: 'the acme one' }] },
- }),
- )
- expect(resumed[resumed.length - 1]!.status.state).toBe(TaskState.COMPLETED)
- expect(resumed[0]!.taskId).toBe(pause.taskId)
- })
-
- it('refuses a message aimed at an already-terminal task', async () => {
- const done = await send('plain')
- const res = await rpc('SendStreamingMessage', {
- message: { role: 'ROLE_USER', messageId: 'm-late', taskId: done[0]!.taskId, parts: [{ text: 'more' }] },
- })
- expect((await json(res)).error.message).toMatch(/terminal/i)
+describe('the full event vocabulary', () => {
+ it('emits every content kind in one turn', async () => {
+ // From outside a provider, a kind nobody emitted is indistinguishable from a kind nobody supports.
+ // This scenario exists so the vocabulary can be proven REACHABLE somewhere.
+ const events = await send('everything')
+ const seen = new Set(kinds(events))
+ const streamed = ['turn_started', 'thinking_delta', 'thinking_title', 'tool_start', 'tool_end',
+ 'context_compact', 'text_delta', 'done', 'recap_start', 'recap_end', 'turn_completed']
+ expect(streamed.filter((k) => !seen.has(k))).toEqual([])
+ })
+
+ it('carries user_message through history — the one kind that is never streamed', async () => {
+ // The client already has the text it just sent, so echoing it back mid-stream would be noise. It
+ // still belongs in the transcript, or a refresh shows one side of a conversation.
+ await send('everything, twice over')
+ const { result } = await json(await rpc('agent.history', { agentId: 'alpha' }))
+ expect(result.events.some((e: Event) => e.kind === 'user_message' && e.text === 'everything, twice over')).toBe(true)
+ })
+
+ it('reaches the three terminal kinds a completed turn cannot', async () => {
+ expect((await send('fail')).at(-1)!.kind).toBe('turn_failed')
+ expect((await send('ask me')).at(-1)!.kind).toBe('turn_input_required')
+ const id = turnId()
+ await rpc('turn.cancel', { turnId: id })
+ const cancelled = await drain(await rpc('agent.send', { agentId: 'alpha', turnId: id, message: { text: 'hello' } }))
+ expect(cancelled.at(-1)!.kind).toBe('turn_cancelled')
+ })
+})
+
+describe('input required', () => {
+ it('ends the stream with turn_input_required and resumes on the same turnId', async () => {
+ const id = turnId()
+ const first = await drain(await rpc('agent.send', { agentId: 'alpha', turnId: id, message: { text: 'ask me' } }))
+ const paused = first.at(-1)!
+ expect(paused.kind).toBe('turn_input_required')
+ expect(paused.prompt).toBeTruthy()
+
+ const resumed = await drain(await rpc('agent.send', { agentId: 'alpha', turnId: id, resume: true, message: { text: 'Acme' } }))
+ expect(resumed.at(-1)!.kind).toBe('turn_completed')
+ expect(kinds(resumed)).toContain('text_delta')
})
})
-describe('cancellation (HP-103)', () => {
- it('cancels an in-flight task and reports CANCELED', async () => {
- const started = await send('ask me something') // parks in INPUT_REQUIRED, so still cancelable
- const taskId = started[0]!.taskId
- const res = await rpc('CancelTask', { taskId })
- expect((await json(res)).result.status.state).toBe(TaskState.CANCELED)
+describe('cancellation', () => {
+ it('is always accepted, even for a turn that does not exist yet', async () => {
+ const { result } = await json(await rpc('turn.cancel', { turnId: 'never-started' }))
+ expect(result.cancelled).toBe(true)
})
- it('refuses to cancel a task that already finished', async () => {
- const done = await send('plain')
- const res = await rpc('CancelTask', { taskId: done[0]!.taskId })
- expect((await json(res)).error.code).toBe(-32003)
+ it('a cancel BEFORE the turn starts stops it — the point of a client-minted turnId', async () => {
+ // Without this the client's whole reason for minting the id (being able to stop in the first
+ // 200ms) is honoured by the API and ignored by the engine.
+ const id = turnId()
+ await rpc('turn.cancel', { turnId: id })
+ const events = await drain(await rpc('agent.send', { agentId: 'alpha', turnId: id, message: { text: 'hello' } }))
+ expect(events.filter((e) => TERMINAL.includes(e.kind ?? ''))).toHaveLength(1)
+ expect(events.at(-1)!.kind).toBe('turn_cancelled')
})
- it('reports an unknown task as not found, not as not-cancelable', async () => {
- const res = await rpc('CancelTask', { taskId: 'task-does-not-exist' })
- expect((await json(res)).error.code).toBe(-32002)
+ it('refuses a cancel with no turnId rather than guessing which turn was meant', async () => {
+ expect((await json(await rpc('turn.cancel', {}))).error.code).toBe('invalid_request')
})
})
-describe('history (HP-200 … HP-202)', () => {
- it('GetTask returns the whole transcript in one response', async () => {
- const events = await send('check pacing')
- const res = await rpc('GetTask', { taskId: events[0]!.taskId })
- const task = (await json(res)).result
- expect(task.history.length).toBeGreaterThan(1)
- expect(task.status.state).toBe(TaskState.COMPLETED)
+describe('history', () => {
+ it('returns the SAME event objects the stream emitted', async () => {
+ const live = (await send('plain')).filter((e) => !TERMINAL.includes(e.kind ?? '') && e.kind !== 'turn_started')
+ const { result } = await json(await rpc('agent.history', { agentId: 'alpha' }))
+ const tail = result.events.slice(-live.length)
+ expect(tail).toEqual(live)
})
- it('derives a session title from the first user message', async () => {
- const events = await send('did acme blow through budget?')
- const task = (await json(await rpc('GetTask', { taskId: events[0]!.taskId }))).result
- expect(task.metadata.title).toContain('acme')
+ it('stores the user’s own message, so a refresh shows both sides', async () => {
+ await send('a distinctive probe')
+ const { result } = await json(await rpc('agent.history', { agentId: 'alpha' }))
+ expect(result.events.some((e: Event) => e.kind === 'user_message' && e.text === 'a distinctive probe')).toBe(true)
})
- it('ListTasks groups several turns under one contextId', async () => {
- const a = await send('first question', { contextId: 'ctx-shared' })
- await send('second question', { contextId: 'ctx-shared' })
- await send('unrelated', { contextId: 'ctx-other' })
+ it('never stores lifecycle or recap events — they are live-turn signals, not transcript', async () => {
+ await send('recap')
+ const { result } = await json(await rpc('agent.history', { agentId: 'alpha' }))
+ const stored = new Set(result.events.map((e: Event) => e.kind))
+ for (const k of [...TERMINAL, 'turn_started', 'recap_start', 'recap_end']) expect(stored.has(k)).toBe(false)
+ })
+
+ it('windows with limit and pages backwards with the returned cursor', async () => {
+ await send('hello')
+ const first = (await json(await rpc('agent.history', { agentId: 'alpha', limit: 1 }))).result
+ expect(first.events).toHaveLength(1)
+ expect(typeof first.nextBefore).toBe('string')
- const listed = (await json(await rpc('ListTasks', { contextId: 'ctx-shared' }))).result.tasks
- expect(listed).toHaveLength(2)
- expect(listed.every((t: { contextId: string }) => t.contextId === 'ctx-shared')).toBe(true)
- expect(listed.map((t: { id: string }) => t.id)).toContain(a[0]!.taskId)
+ const older = (await json(await rpc('agent.history', { agentId: 'alpha', limit: 1, before: first.nextBefore }))).result
+ expect(older.events).toHaveLength(1)
+ expect(older.events[0]).not.toEqual(first.events[0])
})
- it('reports an unknown task rather than an empty one', async () => {
- const res = await rpc('GetTask', { taskId: 'nope' })
- expect((await json(res)).error.code).toBe(-32002)
+ it('omits nextBefore once the start of the transcript is reached', async () => {
+ // Its ABSENCE is how a client knows to stop paging; a cursor that always comes back never ends.
+ const all = (await json(await rpc('agent.history', { agentId: 'beta' }))).result
+ expect(all.nextBefore).toBeUndefined()
+ })
+
+ it('keeps each agent’s transcript separate', async () => {
+ await drain(await rpc('agent.send', { agentId: 'beta', turnId: turnId(), message: { text: 'beta only' } }))
+ const alpha = (await json(await rpc('agent.history', { agentId: 'alpha' }))).result
+ expect(alpha.events.some((e: Event) => e.text === 'beta only')).toBe(false)
+ })
+
+ it('refuses an unknown agent rather than answering empty', async () => {
+ expect((await json(await rpc('agent.history', { agentId: 'ghost' }))).error.code).toBe('not_found')
})
})
-describe('hostile: a stream that dies without a terminal state', () => {
- it('violates HP-102 on purpose, so the client can be hardened against it', async () => {
- const events = await send('die now')
- expect(events.length).toBeGreaterThan(0)
- const last = events[events.length - 1]!
- expect(last.final).toBeFalsy()
- expect([TaskState.COMPLETED, TaskState.FAILED, TaskState.CANCELED]).not.toContain(last.status.state)
+describe('hostile: a stream that dies without a terminal event', () => {
+ it('breaks the one-terminal rule on purpose, so the client can be hardened against it', async () => {
+ const events = await send('die')
+ expect(kinds(events)).toContain('text_delta')
+ expect(events.filter((e) => TERMINAL.includes(e.kind ?? ''))).toHaveLength(0)
})
})
describe('protocol errors', () => {
it('rejects an unknown method', async () => {
- const res = await rpc('NoSuchMethod', {})
- expect((await json(res)).error.code).toBe(-32601)
+ expect((await json(await rpc('nonsense.method', {}))).error.code).toBe('unsupported')
})
it('rejects a malformed body', async () => {
const res = await fetch(base, {
method: 'POST',
- headers: { 'content-type': 'application/json', 'x-api-key': KEY },
- body: '{ not json',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${KEY}` },
+ body: '{not json',
})
- expect((await json(res)).error.code).toBe(-32700)
+ expect((await json(res)).error.code).toBe('invalid_request')
+ })
+
+ it('ignores unknown request fields rather than failing', async () => {
+ const { result } = await json(await rpc('agent.list', { fromALaterRevision: true }))
+ expect(result.agents).toBeTruthy()
})
})
diff --git a/provider/reference-provider/src/server.ts b/provider/reference-provider/src/server.ts
index de7b5b81b..071de4077 100644
--- a/provider/reference-provider/src/server.ts
+++ b/provider/reference-provider/src/server.ts
@@ -1,40 +1,32 @@
/**
- * Reference provider for the Autonomous machine provider profile.
+ * Reference provider for the Autonomous machine provider protocol.
*
- * See `../spec/README.md`. Clause IDs (HP-xxx) in the comments below point at the
- * requirement each block satisfies, so this file doubles as a worked reading of the spec.
+ * See `../../spec/README.md`. This file doubles as a worked reading of it.
*
- * Zero runtime dependencies on purpose: node:http and nothing else. A partner should be able to read
+ * Zero runtime dependencies on purpose: `node:http` and nothing else. A partner should be able to read
* this end to end and know exactly what their own endpoint has to do.
+ *
+ * There is no discovery step and nothing to declare: one URL, one credential header, eight methods.
*/
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
-import { AGENT_CARD, SKILL_IDS } from './agentCard.js'
-import { credentialAccepted, pickScenario, type Step } from './scenarios.js'
-import { nextId, TaskStore } from './store.js'
-import {
- isTerminal,
- RpcErrors,
- TaskState,
- type JsonRpcError,
- type JsonRpcRequest,
- type Message,
- type Task,
- type TaskStatusUpdateEvent,
-} from './types.js'
-
-/** Pause between streamed steps. 0 in tests; a small value locally so streaming is visible. */
+import { AgentError, CREDENTIAL_HEADER, createAgent, deleteAgent, hasAgent, listAgents, renameAgent } from './agents.js'
+import { credentialAccepted, pickScenario, RESUMED, type Step } from './scenarios.js'
+import { Store } from './store.js'
+import type { ErrorCode, ProviderEvent, RpcRequest } from './types.js'
+
+/** Pause between streamed events. 0 in tests; a small value locally so streaming is visible. */
const STEP_DELAY_MS = Number(process.env.STEP_DELAY_MS ?? 20)
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))
export interface ProviderServer {
server: Server
- store: TaskStore
+ store: Store
url: string
close: () => Promise<void>
}
-export function createProviderServer(store = new TaskStore()): Server {
+export function createProviderServer(store = new Store()): Server {
return createServer((req, res) => {
void handle(req, res, store).catch((err) => {
// Never leak a stack to the wire; a provider's internal errors are its own business.
@@ -45,311 +37,227 @@ export function createProviderServer(store = new TaskStore()): Server {
})
}
-async function handle(req: IncomingMessage, res: ServerResponse, store: TaskStore): Promise<void> {
+async function handle(req: IncomingMessage, res: ServerResponse, store: Store): Promise<void> {
const url = new URL(req.url ?? '/', 'http://localhost')
- // HP-020 — the agent card is unauthenticated: a client must be able to discover the security
- // scheme before it can possibly satisfy it.
- if (req.method === 'GET' && url.pathname === '/.well-known/agent-card.json') {
- sendJson(res, 200, AGENT_CARD)
- return
- }
-
if (req.method !== 'POST' || url.pathname !== '/') {
sendJson(res, 404, { error: 'not found' })
return
}
- let rpc: JsonRpcRequest
+ let rpc: RpcRequest
try {
- rpc = JSON.parse(await readBody(req)) as JsonRpcRequest
+ rpc = JSON.parse(await readBody(req)) as RpcRequest
} catch {
- sendRpcError(res, null, RpcErrors.PARSE_ERROR)
+ sendError(res, null, 'invalid_request', 'body is not JSON')
return
}
if (!rpc || typeof rpc.method !== 'string') {
- sendRpcError(res, rpc?.id ?? null, RpcErrors.INVALID_REQUEST)
+ sendError(res, rpc?.id ?? null, 'invalid_request', 'no method')
return
}
- // HP-011/HP-012 — the credential arrives in the header the agent card declared, and identifies one
- // tenant. HP-013: a rejection is its own signal, never a generic failure.
- const credential = header(req, AGENT_CARD.securitySchemes.apiKey.name)
- if (!credentialAccepted(credential)) {
- sendRpcError(res, rpc.id ?? null, RpcErrors.UNAUTHENTICATED)
+ // The credential identifies one tenant. A rejection is its own error code, never a generic failure:
+ // "your credential is wrong" and "the provider is down" need different words in front of the user.
+ if (!credentialAccepted(bearer(header(req, CREDENTIAL_HEADER)))) {
+ sendError(res, rpc.id ?? null, 'unauthenticated', 'credential rejected')
return
}
+ const id = rpc.id ?? null
const params = rpc.params ?? {}
switch (rpc.method) {
- case 'SendStreamingMessage':
- await sendStreamingMessage(res, store, params)
+ case 'agent.list':
+ sendResult(res, id, { agents: listAgents() })
return
- case 'SendMessage':
- sendMessageSync(res, store, params, rpc.id ?? null)
+ case 'agent.send':
+ await agentSend(res, store, params)
return
- case 'GetTask':
- getTask(res, store, params, rpc.id ?? null)
+ case 'agent.history':
+ agentHistory(res, store, params, id)
return
- case 'ListTasks':
- listTasks(res, store, params, rpc.id ?? null)
+ case 'turn.cancel':
+ turnCancel(res, store, params, id)
return
- case 'CancelTask':
- cancelTask(res, store, params, rpc.id ?? null)
+ case 'agent.recap':
+ agentRecap(res, store, params, id)
return
-
- // ── Extension methods (HP-310: always `autonomous.<Verb>`) ─────────────────────────────────
- // HP-311: an extension method whose URI is not in AgentCard.extensions MUST be rejected with
- // -32601. Answering an undeclared method would make the card untrustworthy.
- case 'autonomous.GetRecap':
- if (!declaresExtension(EXT.SESSION_RECAP)) { sendRpcError(res, rpc.id ?? null, RpcErrors.METHOD_NOT_FOUND); return }
- getRecap(res, store, params, rpc.id ?? null)
+ case 'agent.create':
+ case 'agent.rename':
+ case 'agent.delete':
+ mutateAgent(res, rpc.method, params, id)
return
- case 'autonomous.ListFiles':
- case 'autonomous.ReadFile':
- // `workspace-files` is deliberately NOT declared by this provider — see agentCard.ts.
- sendRpcError(res, rpc.id ?? null, RpcErrors.METHOD_NOT_FOUND)
- return
- case 'autonomous.CreateAgent':
- case 'autonomous.RenameAgent':
- case 'autonomous.DeleteAgent':
- case 'autonomous.SetSessionTitle':
- case 'autonomous.DeleteSession':
- // `workspace-write` is deliberately NOT declared either.
- sendRpcError(res, rpc.id ?? null, RpcErrors.METHOD_NOT_FOUND)
- return
- case 'autonomous.RouteVoice':
- sendRpcError(res, rpc.id ?? null, RpcErrors.METHOD_NOT_FOUND)
- return
-
default:
- sendRpcError(res, rpc.id ?? null, RpcErrors.METHOD_NOT_FOUND)
+ sendError(res, id, 'unsupported', `unknown method ${rpc.method}`)
}
}
-const EXT = {
- WORKSPACE_FILES: 'https://harness.autonomous.ai/api/a2a/ext/workspace-files',
- WORKSPACE_WRITE: 'https://harness.autonomous.ai/api/a2a/ext/workspace-write',
- SESSION_RECAP: 'https://harness.autonomous.ai/api/a2a/ext/session-recap',
- VOICE: 'https://harness.autonomous.ai/api/a2a/ext/voice',
-} as const
-
-const declaresExtension = (uri: string): boolean =>
- (AGENT_CARD.extensions as ReadonlyArray<{ uri: string }>).some((e) => e.uri === uri)
+// ── agent.send ───────────────────────────────────────────────────────────────────────────────────
/**
- * HP-302 — `autonomous.GetRecap`. Headline-style summaries of recent turns, for the device's tiles.
+ * Stream Server-Sent Events, one JSON object per `data:` frame.
*
- * `recap` is what the turn ACCOMPLISHED, so it comes from the ASSISTANT's own words. It is emphatically
- * not `metadata.title`, which is the first user message — i.e. what was ASKED. An earlier version
- * returned the title, which made the device tile read the user's own prompt back at them.
- *
- * A real provider would summarise with a model. This one is scripted and must stay deterministic, so
- * it excerpts instead: headline = the reply's opening sentence, body = the reply. That is honest, and
- * it demonstrates the two-field shape a client renders (tile + tap-to-read).
- *
- * An empty array is the correct answer before anything has been summarised: the device shows nothing
- * rather than resurrecting stale text.
+ * The response is opened before any work happens: the whole point is that partial output reaches the
+ * user while the turn runs.
*/
-function getRecap(res: ServerResponse, store: TaskStore, params: Record<string, unknown>, id: string | number | null): void {
+async function agentSend(res: ServerResponse, store: Store, params: Record<string, unknown>): Promise<void> {
const agentId = typeof params.agentId === 'string' ? params.agentId : ''
- if (!SKILL_IDS.includes(agentId)) {
- sendRpcError(res, id, RpcErrors.INVALID_PARAMS)
- return
- }
- const n = Math.max(1, Math.min(5, Number(params.n) || 2))
- const entries = store
- .list()
- .filter((t) => t.status.state === TaskState.COMPLETED) // a failed turn accomplished nothing
- .map((t) => ({ task: t, said: assistantTextOf(t) }))
- .filter((e) => !!e.said)
- .slice(0, n)
- .map((e) => ({
- recap: firstSentence(e.said).slice(0, 200), // `recapEntry.recap` is capped at 200 by the schema
- body: e.said.slice(0, 2000),
- contextId: e.task.contextId,
- taskId: e.task.id,
- }))
- sendRpcResult(res, id, { agentId, entries })
-}
+ const turnId = typeof params.turnId === 'string' ? params.turnId : ''
+ const message = (params.message ?? {}) as { text?: unknown }
+ const text = typeof message.text === 'string' ? message.text : ''
-/** Everything the assistant said in a turn, flattened to the one line a tile renders. */
-function assistantTextOf(task: Task): string {
- return task.history
- .filter((m) => m.role === 'ROLE_AGENT')
- .flatMap((m) => m.parts)
- .filter((p) => (p.metadata?.['autonomous.ai/kind'] ?? 'text_delta') === 'text_delta')
- .map((p) => p.text ?? '')
- .join('')
- .replace(/\s+/g, ' ')
- .trim()
-}
+ // These are stream-level errors, so they are answered as JSON before the stream opens rather than
+ // as an event inside it — a client that asked for a nonexistent agent has no turn to fail.
+ if (!turnId) { sendError(res, null, 'invalid_request', 'turnId is required'); return }
+ if (!hasAgent(agentId)) { sendError(res, null, 'not_found', `no agent ${agentId}`); return }
-function firstSentence(text: string): string {
- const match = /[.!?](\s|$)/.exec(text)
- return match ? text.slice(0, match.index + 1) : text
-}
+ const resume = params.resume === true
+ const steps: Step[] = resume ? RESUMED : pickScenario(text).steps
-// ── SendStreamingMessage (HP-100 … HP-106) ───────────────────────────────────────────────────────
+ res.writeHead(200, {
+ 'content-type': 'text/event-stream',
+ 'cache-control': 'no-cache',
+ connection: 'keep-alive',
+ })
-async function sendStreamingMessage(res: ServerResponse, store: TaskStore, params: Record<string, unknown>): Promise<void> {
- const incoming = params.message as Message | undefined
- if (!incoming || !Array.isArray(incoming.parts)) {
- sendRpcError(res, null, RpcErrors.INVALID_PARAMS)
- return
+ const emit = (event: ProviderEvent): void => {
+ store.append(agentId, event)
+ res.write(`data: ${JSON.stringify(event)}\n\n`)
}
- // HP-106 — images ride as standard Parts. This provider cannot process them, so it says so rather
- // than silently discarding, which would read to the user as the agent ignoring what they sent.
- const images = incoming.parts.filter((p) => p.raw && p.mediaType?.startsWith('image/'))
-
- // HP-101 — a follow-up carries the existing taskId; a new chat carries only a fresh contextId.
- const resuming = typeof incoming.taskId === 'string' ? store.get(incoming.taskId) : undefined
- if (incoming.taskId && !resuming) {
- sendRpcError(res, null, RpcErrors.TASK_NOT_FOUND)
- return
- }
- if (resuming && isTerminal(resuming.status.state)) {
- // A2A: terminal tasks accept no further messages.
- sendRpcError(res, null, { code: -32004, message: 'Task is in a terminal state' })
+ // A cancel that arrived BEFORE this turn started still has to stop it. Checking here is what makes
+ // a client-minted `turnId` worth anything: a user who presses stop in the first 200ms would
+ // otherwise be ignored by the engine while the API said "cancelled".
+ if (store.takeEarlyCancel(turnId)) {
+ emit({ kind: 'turn_cancelled' })
+ res.end()
return
}
- const contextId = resuming?.contextId ?? (typeof incoming.contextId === 'string' ? incoming.contextId : nextId('ctx'))
- const task = resuming ?? store.create(contextId, incoming)
- if (resuming) store.append(task.id, incoming)
-
- const controller = new AbortController()
- store.register(task.id, controller)
-
- openSse(res)
- const userText = incoming.parts.map((p) => p.text ?? '').join(' ')
+ const abort = new AbortController()
+ store.register(turnId, abort)
- // HP-102 — every stream ends with a terminal state. The one exception is the `die` scenario, which
- // exists precisely so a client can be hardened against providers that get this wrong.
- const steps: Step[] = images.length
- ? [{ kind: 'state', state: TaskState.FAILED, text: 'This provider cannot process image attachments.' }]
- : pickScenario(userText).steps
+ emit({ kind: 'turn_started', turnId, agentId, at: new Date().toISOString() })
+ // The user's own message belongs in the transcript — a refresh must show the conversation, not one
+ // side of it. Appended rather than emitted: the client already has the text it just sent.
+ if (text) store.append(agentId, { kind: 'user_message', text })
try {
- store.setState(task.id, TaskState.WORKING)
- writeSse(res, statusEvent(task, TaskState.WORKING))
-
for (const step of steps) {
- if (controller.signal.aborted) break
- await sleep(STEP_DELAY_MS)
- if (controller.signal.aborted) break
-
+ if (abort.signal.aborted) {
+ emit({ kind: 'turn_cancelled' })
+ res.end()
+ return
+ }
if (step.kind === 'die') {
- res.destroy() // no terminal state, mid-stream — deliberately non-conformant
+ // The one-terminal-frame rule violated ON PURPOSE: the socket dies with no terminal event, so
+ // a client can be hardened against it and the conformance runner can be shown catching it.
+ res.destroy()
return
}
- if (step.kind === 'parts') {
- writeSse(res, {
- taskId: task.id,
- contextId: task.contextId,
- status: {
- state: TaskState.WORKING,
- message: { role: 'ROLE_AGENT', messageId: nextId('m'), taskId: task.id, contextId: task.contextId, parts: step.parts },
- },
- })
- store.append(task.id, { role: 'ROLE_AGENT', messageId: nextId('m'), taskId: task.id, contextId: task.contextId, parts: step.parts })
- continue
+ emit(step.event)
+ if (step.event.kind === 'turn_input_required') store.pause(turnId, agentId)
+ if (step.event.kind === 'recap_end' && step.event.recap) {
+ store.pushRecap(agentId, { recap: step.event.recap, text: step.event.text, turnId })
}
- // step.kind === 'state'
- const message: Message | undefined = step.text
- ? { role: 'ROLE_AGENT', messageId: nextId('m'), taskId: task.id, contextId: task.contextId, parts: [{ text: step.text }] }
- : undefined
- store.setState(task.id, step.state, message)
- writeSse(res, {
- taskId: task.id,
- contextId: task.contextId,
- status: { state: step.state, ...(message ? { message } : {}) },
- final: isTerminal(step.state),
- })
- // INPUT_REQUIRED is not terminal, but it does end this stream: the answer arrives as a new
- // request carrying the same taskId (HP-104).
- break
- }
-
- if (controller.signal.aborted) {
- writeSse(res, { taskId: task.id, contextId: task.contextId, status: { state: TaskState.CANCELED }, final: true })
+ await sleep(STEP_DELAY_MS)
}
+ res.end()
} finally {
- store.release(task.id)
- if (!res.destroyed) res.end()
+ store.release(turnId)
}
}
-// ── Non-streaming and read methods ───────────────────────────────────────────────────────────────
+// ── agent.history ────────────────────────────────────────────────────────────────────────────────
-function sendMessageSync(res: ServerResponse, store: TaskStore, params: Record<string, unknown>, id: string | number | null): void {
- const incoming = params.message as Message | undefined
- if (!incoming || !Array.isArray(incoming.parts)) {
- sendRpcError(res, id, RpcErrors.INVALID_PARAMS)
- return
- }
- const contextId = typeof incoming.contextId === 'string' ? incoming.contextId : nextId('ctx')
- const task = store.create(contextId, incoming)
- store.setState(task.id, TaskState.COMPLETED, {
- role: 'ROLE_AGENT',
- messageId: nextId('m'),
- taskId: task.id,
- contextId,
- parts: [{ text: 'Non-streaming reply.' }],
+/**
+ * One agent's transcript, windowed, in the SAME event objects the stream emitted. There is nothing to
+ * translate on the way out, which is exactly the property that keeps a replayed transcript and the
+ * live view from disagreeing.
+ */
+function agentHistory(res: ServerResponse, store: Store, params: Record<string, unknown>, id: RpcRequest['id']): void {
+ const agentId = typeof params.agentId === 'string' ? params.agentId : ''
+ if (!hasAgent(agentId)) { sendError(res, id ?? null, 'not_found', `no agent ${agentId}`); return }
+ const limit = typeof params.limit === 'number' && params.limit > 0 ? Math.floor(params.limit) : undefined
+ const before = typeof params.before === 'string' && params.before ? params.before : undefined
+
+ const window = store.history(agentId, limit, before)
+ sendResult(res, id ?? null, {
+ agentId,
+ events: window.events,
+ // Present only when older events remain. Its ABSENCE is how a client knows it reached the start.
+ ...(window.nextBefore ? { nextBefore: window.nextBefore } : {}),
+ // This provider never truncates, so it says so rather than omitting the field: the rule is about
+ // never truncating SILENTLY.
+ truncated: false,
})
- sendRpcResult(res, id, store.get(task.id))
}
-/** HP-201 — the full transcript in one response. Pagination is not part of this revision (HP-202). */
-function getTask(res: ServerResponse, store: TaskStore, params: Record<string, unknown>, id: string | number | null): void {
- const taskId = typeof params.taskId === 'string' ? params.taskId : ''
- const task = store.get(taskId)
- if (!task) {
- sendRpcError(res, id, RpcErrors.TASK_NOT_FOUND)
- return
- }
- sendRpcResult(res, id, task)
+// ── turn.cancel ──────────────────────────────────────────────────────────────────────────────────
+
+/** Always accepted, including for a turn that has not started (see `Store.cancel`). */
+function turnCancel(res: ServerResponse, store: Store, params: Record<string, unknown>, id: RpcRequest['id']): void {
+ const turnId = typeof params.turnId === 'string' ? params.turnId : ''
+ if (!turnId) { sendError(res, id ?? null, 'invalid_request', 'turnId is required'); return }
+ store.cancel(turnId)
+ sendResult(res, id ?? null, { cancelled: true })
}
-/** HP-200 — grouping by contextId is what backs the session list. */
-function listTasks(res: ServerResponse, store: TaskStore, params: Record<string, unknown>, id: string | number | null): void {
- const contextId = typeof params.contextId === 'string' ? params.contextId : undefined
- sendRpcResult(res, id, { tasks: store.list(contextId) })
+// ── agent.recap ──────────────────────────────────────────────────────────────────────────────────
+
+function agentRecap(res: ServerResponse, store: Store, params: Record<string, unknown>, id: RpcRequest['id']): void {
+ const agentId = typeof params.agentId === 'string' ? params.agentId : ''
+ if (!hasAgent(agentId)) { sendError(res, id ?? null, 'not_found', `no agent ${agentId}`); return }
+ // NO `recap` field is correct before any turn has been summarised — the device then shows nothing
+ // rather than resurrecting stale text. The object spread out here is the same one `recap_end`
+ // pushes on a turn's own stream.
+ const entry = store.lastRecap(agentId)
+ sendResult(res, id ?? null, { agentId, ...(entry ?? {}) })
}
-/** HP-103 — after a successful cancel the stream terminates and the task reports CANCELED. */
-function cancelTask(res: ServerResponse, store: TaskStore, params: Record<string, unknown>, id: string | number | null): void {
- const taskId = typeof params.taskId === 'string' ? params.taskId : ''
- const task = store.get(taskId)
- if (!task) {
- sendRpcError(res, id, RpcErrors.TASK_NOT_FOUND)
- return
- }
- if (!store.cancel(taskId)) {
- sendRpcError(res, id, RpcErrors.TASK_NOT_CANCELABLE)
- return
+// ── agent.create / rename / delete ───────────────────────────────────────────────────────────────
+
+/**
+ * Mutations on the agent list.
+ *
+ * A provider whose agents are managed elsewhere answers `invalid_request` with a message instead —
+ * that message is shown to the user, which is more useful than a control that is silently missing.
+ * This one really mutates, so the conformance runner has something to exercise.
+ */
+function mutateAgent(res: ServerResponse, method: string, params: Record<string, unknown>, id: RpcRequest['id']): void {
+ try {
+ if (method === 'agent.create') {
+ return sendResult(res, id ?? null, createAgent(String(params.name ?? ''), params.description as string | undefined))
+ }
+ if (method === 'agent.rename') {
+ return sendResult(res, id ?? null, renameAgent(String(params.agentId ?? ''), String(params.name ?? '')))
+ }
+ deleteAgent(String(params.agentId ?? ''))
+ sendResult(res, id ?? null, { deleted: true })
+ } catch (err) {
+ if (err instanceof AgentError) { sendError(res, id ?? null, 'invalid_request', err.message); return }
+ throw err
}
- sendRpcResult(res, id, store.get(taskId))
}
-// ── Wire helpers ─────────────────────────────────────────────────────────────────────────────────
+// ── plumbing ─────────────────────────────────────────────────────────────────────────────────────
-function statusEvent(task: Task, state: TaskStatusUpdateEvent['status']['state']): TaskStatusUpdateEvent {
- return { taskId: task.id, contextId: task.contextId, status: { state } }
+/** `Authorization: Bearer <credential>` — one header, by convention rather than by declaration. */
+function bearer(value: string | undefined): string | undefined {
+ if (!value) return undefined
+ const match = /^Bearer\s+(.+)$/i.exec(value.trim())
+ return match ? match[1] : value
}
-function openSse(res: ServerResponse): void {
- res.writeHead(200, {
- 'content-type': 'text/event-stream',
- 'cache-control': 'no-cache',
- connection: 'keep-alive',
- })
+function header(req: IncomingMessage, name: string): string | undefined {
+ const v = req.headers[name.toLowerCase()]
+ return Array.isArray(v) ? v[0] : v
}
-function writeSse(res: ServerResponse, event: TaskStatusUpdateEvent): void {
- if (res.destroyed) return
- res.write(`event: status-update\ndata: ${JSON.stringify(event)}\n\n`)
+async function readBody(req: IncomingMessage): Promise<string> {
+ let body = ''
+ for await (const chunk of req) body += chunk
+ return body
}
function sendJson(res: ServerResponse, status: number, body: unknown): void {
@@ -358,61 +266,31 @@ function sendJson(res: ServerResponse, status: number, body: unknown): void {
res.end(payload)
}
-function sendRpcResult(res: ServerResponse, id: string | number | null, result: unknown): void {
- sendJson(res, 200, { jsonrpc: '2.0', id, result })
-}
-
-function sendRpcError(res: ServerResponse, id: string | number | null, error: JsonRpcError): void {
- // JSON-RPC transports errors in the body with HTTP 200; an authentication failure additionally
- // deserves a real 401 so ordinary HTTP tooling sees it.
- const status = error.code === RpcErrors.UNAUTHENTICATED.code ? 401 : 200
- sendJson(res, status, { jsonrpc: '2.0', id, error })
-}
-
-function header(req: IncomingMessage, name: string): string | undefined {
- const v = req.headers[name.toLowerCase()]
- return Array.isArray(v) ? v[0] : v
-}
+const sendResult = (res: ServerResponse, id: RpcRequest['id'], result: unknown): void =>
+ sendJson(res, 200, { jsonrpc: '2.0', id: id ?? null, result })
-async function readBody(req: IncomingMessage): Promise<string> {
- const chunks: Buffer[] = []
- let size = 0
- for await (const chunk of req) {
- size += (chunk as Buffer).length
- if (size > 5 * 1024 * 1024) throw new Error('body too large')
- chunks.push(chunk as Buffer)
- }
- return Buffer.concat(chunks).toString('utf8')
+/**
+ * `unauthenticated` also carries HTTP 401, so a client that never parses the body can still tell a
+ * rejected credential from an outage.
+ */
+function sendError(res: ServerResponse, id: RpcRequest['id'], code: ErrorCode, message?: string): void {
+ const status = code === 'unauthenticated' ? 401 : 200
+ sendJson(res, status, { jsonrpc: '2.0', id: id ?? null, error: { code, ...(message ? { message } : {}) } })
}
-// ── Entry point ──────────────────────────────────────────────────────────────────────────────────
-
-/** Starts on an ephemeral port when `port` is 0 — how the tests use it. */
-export function start(port = Number(process.env.PORT ?? 4501)): Promise<ProviderServer> {
- const store = new TaskStore()
+/** Boot on an ephemeral port. Used by the tests and by the e2e harness. */
+export async function start(port = 0): Promise<ProviderServer> {
+ const store = new Store()
const server = createProviderServer(store)
- return new Promise((resolve) => {
- server.listen(port, () => {
- const address = server.address()
- const actual = typeof address === 'object' && address ? address.port : port
- resolve({
- server,
- store,
- url: `http://127.0.0.1:${actual}`,
- close: () =>
- new Promise<void>((done) => {
- store.clear()
- server.close(() => done())
- }),
- })
- })
- })
+ await new Promise<void>((r) => server.listen(port, '127.0.0.1', r))
+ const addr = server.address()
+ const url = `http://127.0.0.1:${typeof addr === 'object' && addr ? addr.port : port}`
+ return { server, store, url, close: () => new Promise<void>((r) => server.close(() => r())) }
}
-// Only auto-start when run directly, so importing this module in a test does not bind a port.
-if (process.argv[1] && import.meta.url === `file://${process.argv[1]}`) {
- void start().then(({ url }) => {
- console.log(`[reference-provider] listening on ${url}`)
- console.log(`[reference-provider] agent card: ${url}/.well-known/agent-card.json`)
+// `npm run dev` / `npm start`
+if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/^.*?(?=\/src|\/dist)/, ''))) {
+ void start(Number(process.env.PORT ?? 4319)).then(({ url }) => {
+ console.log(`[reference-provider] ${url} · POST / with \`Authorization: Bearer <credential>\``)
})
}
diff --git a/provider/reference-provider/src/store.spec.ts b/provider/reference-provider/src/store.spec.ts
new file mode 100644
index 000000000..679ad1d14
--- /dev/null
+++ b/provider/reference-provider/src/store.spec.ts
@@ -0,0 +1,49 @@
+// The early-cancel bookkeeping, which is the one piece of state here that a client can grow without
+// ever completing a turn: `turn.cancel` is deliberately accepted for a turnId nobody has sent, and
+// that entry is otherwise only removed by a matching `agent.send`.
+import { describe, expect, it, vi } from 'vitest'
+
+const { EARLY_CANCEL_TTL_MS, Store } = await import('./store.js')
+
+describe('a cancel that arrives before the send', () => {
+ it('still stops the turn when the send follows', () => {
+ const store = new Store()
+ store.cancel('t-1')
+ expect(store.takeEarlyCancel('t-1')).toBe(true)
+ // Taken, not merely read: a second send with the same id is a new turn.
+ expect(store.takeEarlyCancel('t-1')).toBe(false)
+ })
+
+ it('is forgotten once the send it belongs to is clearly never coming', () => {
+ // Without this the map is a slow leak — a client cancelling turns it never sends grows it for the
+ // lifetime of the process, and nothing in the protocol stops it doing so.
+ vi.useFakeTimers()
+ try {
+ const store = new Store()
+ store.cancel('t-old')
+
+ vi.advanceTimersByTime(EARLY_CANCEL_TTL_MS + 1)
+ // The sweep runs on write, which is the only moment the map can grow.
+ store.cancel('t-new')
+
+ expect(store.takeEarlyCancel('t-old')).toBe(false)
+ // …and the sweep is not indiscriminate: the cancel that just arrived still works.
+ expect(store.takeEarlyCancel('t-new')).toBe(true)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('keeps an entry that is merely old, not expired', () => {
+ vi.useFakeTimers()
+ try {
+ const store = new Store()
+ store.cancel('t-1')
+ vi.advanceTimersByTime(EARLY_CANCEL_TTL_MS - 1_000)
+ store.cancel('t-2')
+ expect(store.takeEarlyCancel('t-1')).toBe(true)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+})
diff --git a/provider/reference-provider/src/store.ts b/provider/reference-provider/src/store.ts
index 97811478a..066e484e7 100644
--- a/provider/reference-provider/src/store.ts
+++ b/provider/reference-provider/src/store.ts
@@ -1,86 +1,143 @@
/**
- * In-memory task store.
+ * In-memory state.
*
- * A real provider would persist this; the shape is what matters. Note that HISTORY LIVES HERE — the
- * Autonomous backend keeps no transcript for a provider machine, which is why `GetTask` and `ListTasks`
- * are Tier 0 rather than optional (HP-200, HP-201).
+ * A real provider would persist this; the shape is what matters. Note that THE TRANSCRIPT LIVES HERE —
+ * the Autonomous backend keeps none for a provider machine, which is why `agent.history` is required
+ * rather than optional.
+ *
+ * One agent is one continuous transcript (spec §1). There is no session, thread or context here, and
+ * adding one back is the single most likely way to drift from the spec.
*/
-import { isTerminal, TaskState, type Message, type Task, type TaskStateValue } from './types.js'
+import { isTerminalKind, type ProviderEvent, type RecapEntry } from './types.js'
+
+/** How long a cancel waits for the send it belongs to. Generous: the client sends within a tick. */
+export const EARLY_CANCEL_TTL_MS = 10 * 60_000
/** Deterministic ids: tests must not depend on a clock or a random source. */
let seq = 0
export const nextId = (prefix: string): string => `${prefix}-${++seq}`
export const resetIds = (): void => { seq = 0 }
-export class TaskStore {
- private tasks = new Map<string, Task>()
- /** taskId → abort for an in-flight stream, so CancelTask can actually stop one (HP-103). */
+interface Stored {
+ /** Monotonic, and the only source of the `before` cursor. Never exposed as a field on the event. */
+ seq: number
+ event: ProviderEvent
+}
+
+export interface Window {
+ events: ProviderEvent[]
+ /** Omitted once the start of the transcript is reached. */
+ nextBefore?: string
+}
+
+export class Store {
+ private transcripts = new Map<string, Stored[]>()
+ private recaps = new Map<string, RecapEntry[]>()
+ /** turnId → abort for an in-flight stream, so `turn.cancel` can actually stop one. */
private inFlight = new Map<string, AbortController>()
+ /**
+ * Turns cancelled BEFORE they started → when the cancel arrived.
+ *
+ * A cancel for a not-yet-started turn must be accepted AND must make that turn terminate
+ * immediately if it later begins. Without this the client's whole reason for minting `turnId` itself
+ * — being able to cancel in the first 200ms — would be honoured by the API and ignored by the engine.
+ *
+ * It holds the ARRIVAL TIME rather than just the id because an entry is otherwise only ever removed
+ * by a matching `agent.send` that may never come: a client cancelling turns it never sends grows
+ * this forever. Swept on write, which is the only moment it can grow.
+ */
+ private cancelledEarly = new Map<string, number>()
+ /** turnId → agentId for a turn paused on `turn_input_required`, so a resume knows where it belongs. */
+ private paused = new Map<string, string>()
+ private counter = 0
- create(contextId: string, first: Message): Task {
- const task: Task = {
- id: nextId('task'),
- contextId,
- status: { state: TaskState.SUBMITTED },
- history: [first],
- metadata: { title: titleFrom(first) },
- }
- this.tasks.set(task.id, task)
- return task
+ append(agentId: string, event: ProviderEvent): void {
+ // Lifecycle and recap events are live-turn signals, not transcript content. Storing them would
+ // make `agent.history` disagree with what a client renders from the stream.
+ // `done` restates text already streamed as deltas — storing it would put the same words in the
+ // transcript twice, and a client replaying would render the answer, then render it again.
+ if (isTerminalKind(event.kind) || event.kind === 'turn_started'
+ || event.kind === 'recap_start' || event.kind === 'recap_end' || event.kind === 'done') return
+ const list = this.transcripts.get(agentId) ?? []
+ list.push({ seq: ++this.counter, event })
+ this.transcripts.set(agentId, list)
}
- get(taskId: string): Task | undefined {
- return this.tasks.get(taskId)
+ /**
+ * A window of one agent's transcript, oldest-first within the window.
+ *
+ * `before` is opaque to the client and is our `seq` — which is why it is stored beside the event
+ * rather than on it: the event objects handed back MUST be the ones the stream emitted.
+ */
+ history(agentId: string, limit?: number, before?: string): Window {
+ const all = this.transcripts.get(agentId) ?? []
+ const cutoff = before ? Number(before.replace(/^evt_/, '')) : Infinity
+ const eligible = all.filter((s) => s.seq < cutoff)
+ if (!limit) return { events: eligible.map((s) => s.event) }
+ const slice = eligible.slice(-limit)
+ const window: Window = { events: slice.map((s) => s.event) }
+ // Only when something older remains. Its ABSENCE is how the client knows it reached the start.
+ if (slice.length && eligible.length > slice.length) window.nextBefore = `evt_${slice[0]!.seq}`
+ return window
}
- /** Newest first. `contextId` filters to one session (HP-200). */
- list(contextId?: string): Task[] {
- const all = [...this.tasks.values()]
- const filtered = contextId ? all.filter((t) => t.contextId === contextId) : all
- return filtered.reverse()
+ pushRecap(agentId: string, entry: RecapEntry): void {
+ this.recaps.set(agentId, [entry, ...(this.recaps.get(agentId) ?? [])].slice(0, 5))
}
- append(taskId: string, message: Message): void {
- this.tasks.get(taskId)?.history.push(message)
+ /** The LAST one. The device shows a single tile per agent, so there is no history to page through. */
+ lastRecap(agentId: string): RecapEntry | undefined {
+ return (this.recaps.get(agentId) ?? [])[0]
}
- setState(taskId: string, state: TaskStateValue, message?: Message): void {
- const task = this.tasks.get(taskId)
- if (!task) return
- task.status = { state, ...(message ? { message } : {}) }
+ register(turnId: string, controller: AbortController): void {
+ this.inFlight.set(turnId, controller)
}
- register(taskId: string, controller: AbortController): void {
- this.inFlight.set(taskId, controller)
+ release(turnId: string): void {
+ this.inFlight.delete(turnId)
}
- release(taskId: string): void {
- this.inFlight.delete(taskId)
+ pause(turnId: string, agentId: string): void {
+ this.paused.set(turnId, agentId)
+ }
+
+ resumeOf(turnId: string): string | undefined {
+ const agentId = this.paused.get(turnId)
+ if (agentId) this.paused.delete(turnId)
+ return agentId
+ }
+
+ /** True when this turn was cancelled before it began, and clears the flag. */
+ takeEarlyCancel(turnId: string): boolean {
+ return this.cancelledEarly.delete(turnId)
}
/**
- * Returns false when the task cannot be cancelled — already terminal, or unknown. The caller maps
- * that onto TASK_NOT_CANCELABLE / TASK_NOT_FOUND rather than pretending it worked.
+ * Always succeeds. A cancel for an unknown turn is remembered rather than refused, because the
+ * client mints `turnId` before sending and may well cancel first.
*/
- cancel(taskId: string): boolean {
- const task = this.tasks.get(taskId)
- if (!task || isTerminal(task.status.state)) return false
- this.inFlight.get(taskId)?.abort()
- this.inFlight.delete(taskId)
- task.status = { state: TaskState.CANCELED }
- return true
+ cancel(turnId: string): void {
+ const live = this.inFlight.get(turnId)
+ if (live) {
+ live.abort()
+ this.inFlight.delete(turnId)
+ return
+ }
+ // A send that has not arrived within the window was never coming. Sweeping here — the one place
+ // the map can grow — keeps an unmatched cancel from being a slow memory leak.
+ const now = Date.now()
+ for (const [id, at] of this.cancelledEarly) if (now - at > EARLY_CANCEL_TTL_MS) this.cancelledEarly.delete(id)
+ this.cancelledEarly.set(turnId, now)
}
clear(): void {
for (const c of this.inFlight.values()) c.abort()
this.inFlight.clear()
- this.tasks.clear()
+ this.transcripts.clear()
+ this.recaps.clear()
+ this.cancelledEarly.clear()
+ this.paused.clear()
+ this.counter = 0
}
}
-
-/** Session title = the first user message, truncated (spec §10.4). */
-function titleFrom(message: Message): string {
- const text = message.parts.map((p) => p.text ?? '').join(' ').trim()
- if (!text) return 'Untitled'
- return text.length > 80 ? `${text.slice(0, 77)}…` : text
-}
diff --git a/provider/reference-provider/src/types.ts b/provider/reference-provider/src/types.ts
index 5067f9d4b..d5dbf3454 100644
--- a/provider/reference-provider/src/types.ts
+++ b/provider/reference-provider/src/types.ts
@@ -1,144 +1,94 @@
/**
- * The subset of A2A this reference implementation uses, plus the `autonomous.ai/*` metadata defined by
- * `../spec/README.md`.
+ * The wire types, as `../../spec/README.md` defines them.
*
* Deliberately hand-written rather than generated: a partner reading this file should be able to see
* the entire wire surface without installing anything.
+ *
+ * An event is one flat, self-describing object discriminated on `kind`, and the SAME objects serve
+ * both the `agent.send` stream and `agent.history` — which is why there is exactly one event
+ * type here and not two.
*/
-export const TaskState = {
- SUBMITTED: 'TASK_STATE_SUBMITTED',
- WORKING: 'TASK_STATE_WORKING',
- COMPLETED: 'TASK_STATE_COMPLETED',
- FAILED: 'TASK_STATE_FAILED',
- CANCELED: 'TASK_STATE_CANCELED',
- REJECTED: 'TASK_STATE_REJECTED',
- INPUT_REQUIRED: 'TASK_STATE_INPUT_REQUIRED',
- AUTH_REQUIRED: 'TASK_STATE_AUTH_REQUIRED',
-} as const
-
-export type TaskStateValue = (typeof TaskState)[keyof typeof TaskState]
-
-/** States after which a task accepts no further messages (A2A: "terminal"). */
-export const TERMINAL_STATES: readonly TaskStateValue[] = [
- TaskState.COMPLETED,
- TaskState.FAILED,
- TaskState.CANCELED,
- TaskState.REJECTED,
-]
-
-export const isTerminal = (s: TaskStateValue): boolean => TERMINAL_STATES.includes(s)
-
-/** HP-210: every Autonomous-specific key is namespaced. Unknown keys in the namespace are ignored. */
-export interface PartMetadata {
- 'autonomous.ai/kind'?:
- | 'user_message'
- | 'thinking_delta'
- | 'thinking_title'
- | 'text_delta'
- | 'tool_start'
- | 'tool_end'
- | 'context_compact'
- | 'done'
- | 'recap_start'
- | 'recap_end'
- 'autonomous.ai/thinkingId'?: string
- 'autonomous.ai/toolCallId'?: string
- 'autonomous.ai/parentToolCallId'?: string
- 'autonomous.ai/tool'?: string
- 'autonomous.ai/toolInput'?: unknown
- 'autonomous.ai/isError'?: boolean
- 'autonomous.ai/summary'?: string
- 'autonomous.ai/durationSeconds'?: number
- 'autonomous.ai/title'?: string
- /**
- * `recap_end` only (HP-212): the headline. The Part's own `text` carries the fuller body.
- * ABSENT on a `recap_end` means the turn produced no recap — the phase is over, show nothing.
- */
- 'autonomous.ai/recap'?: string
- 'autonomous.ai/compacted'?: {
- userMessages?: number
- assistantMessages?: number
- toolUses?: number
- contexts?: number
- }
+/** Content kinds. Terminal kinds are separate — see `TERMINAL_KINDS`. */
+export const EVENT_KINDS = [
+ 'turn_started',
+ 'user_message',
+ 'thinking_title',
+ 'thinking_delta',
+ 'text_delta',
+ 'tool_start',
+ 'tool_end',
+ 'context_compact',
+ 'done',
+ 'recap_start',
+ 'recap_end',
+] as const
+
+/** Exactly ONE of these ends every stream. */
+export const TERMINAL_KINDS = ['turn_completed', 'turn_failed', 'turn_cancelled', 'turn_input_required'] as const
+
+export type EventKind = (typeof EVENT_KINDS)[number] | (typeof TERMINAL_KINDS)[number]
+
+export const isTerminalKind = (kind: string | undefined): boolean =>
+ !!kind && (TERMINAL_KINDS as readonly string[]).includes(kind)
+
+/** Codes are STRINGS, and `unauthenticated` is its own so the UI can say the right sentence. */
+export type ErrorCode =
+ | 'unauthenticated'
+ | 'not_found'
+ | 'unsupported'
+ | 'invalid_request'
+ | 'rate_limited'
+ | 'internal'
+
+export interface ProviderError {
+ code: ErrorCode
+ message?: string
}
-export interface Part {
+/**
+ * One event.
+ *
+ * `kind` is optional ON PURPOSE: an event carrying only `text` is conformant and renders as plain
+ * assistant output. That is the simplest correct implementation a partner can ship, and
+ * making `kind` required here would quietly outlaw it.
+ */
+export interface ProviderEvent {
+ kind?: EventKind
text?: string
- /** base64 — HP-106 carries image attachments here with `mediaType`. */
- raw?: string
- filename?: string
- mediaType?: string
- url?: string
- metadata?: PartMetadata
-}
-
-export type Role = 'ROLE_USER' | 'ROLE_AGENT'
-
-export interface Message {
- role: Role
- messageId: string
- parts: Part[]
- taskId?: string
- contextId?: string
+ turnId?: string
+ agentId?: string
+ at?: string
+ title?: string
+ thinkingId?: string
+ toolId?: string
+ tool?: string
+ input?: unknown
+ ok?: boolean
+ output?: string
+ summary?: string
+ durationSeconds?: number
+ recap?: string
+ prompt?: string
+ error?: ProviderError
}
-export interface Artifact {
- artifactId: string
- name?: string
- parts: Part[]
-}
-
-export interface TaskStatus {
- state: TaskStateValue
- message?: Message
-}
-
-export interface Task {
+export interface Agent {
id: string
- contextId: string
- status: TaskStatus
- history: Message[]
- artifacts?: Artifact[]
- /** Not A2A core — used to derive a session title (spec §10.4). */
- metadata?: { title?: string }
-}
-
-export interface TaskStatusUpdateEvent {
- taskId: string
- contextId: string
- status: TaskStatus
- final?: boolean
-}
-
-export interface TaskArtifactUpdateEvent {
- taskId: string
- contextId: string
- artifact: Artifact
+ name: string
+ description?: string
}
-export interface JsonRpcRequest {
- jsonrpc: '2.0'
+/** JSON-RPC 2.0 — the only envelope, on one URL. */
+export interface RpcRequest {
+ jsonrpc?: string
id?: string | number | null
- method: string
+ method?: string
params?: Record<string, unknown>
}
-export interface JsonRpcError {
- code: number
- message: string
- data?: unknown
+export interface RecapEntry {
+ recap: string
+ text?: string
+ turnId?: string
}
-
-/** JSON-RPC reserved codes plus the A2A-flavoured ones this implementation raises. */
-export const RpcErrors = {
- PARSE_ERROR: { code: -32700, message: 'Parse error' },
- INVALID_REQUEST: { code: -32600, message: 'Invalid request' },
- METHOD_NOT_FOUND: { code: -32601, message: 'Method not found' },
- INVALID_PARAMS: { code: -32602, message: 'Invalid params' },
- INTERNAL: { code: -32603, message: 'Internal error' },
- UNAUTHENTICATED: { code: -32001, message: 'Unauthenticated' },
- TASK_NOT_FOUND: { code: -32002, message: 'Task not found' },
- TASK_NOT_CANCELABLE: { code: -32003, message: 'Task not cancelable' },
-} as const
diff --git a/provider/spec/README.md b/provider/spec/README.md
index fdc41cd09..63c36a64f 100644
--- a/provider/spec/README.md
+++ b/provider/spec/README.md
@@ -1,600 +1,361 @@
-# Harness Provider Protocol (A2A profile)
+# Autonomous machine provider protocol
-**Status:** DRAFT, revision **0.2.0**. Public but not yet implemented by anyone outside Autonomous,
-so it is still changing. Treat §12 as binding from 0.2.0 onward.
+A **provider** backs an Autonomous *machine* with your agent platform instead of a CLI running on the
+user's own computer. This document is the whole contract.
-**Audience:** a third party who wants their agent platform to appear as a `provider` machine in the
-Autonomous product — reachable from the web app and from the Harness device.
+**Authenticate, call a method, handle the response.** JSON-RPC 2.0 over HTTPS POST to one URL, with
+Server-Sent Events for the one method that streams. No WebSocket, nothing long-lived, no SDK, and
+nothing to discover — the eight methods below are the entire surface.
-**What this document is:** a *profile* of the Agent2Agent (A2A) protocol, not a new protocol. If you
-already run a conformant A2A agent, most of Tier 0 is already done. Everything Autonomous-specific is
-expressed as declared A2A extensions or as metadata on standard objects — nothing here forks A2A.
+```http
+POST / HTTP/1.1
+Host: agent.example.com
+Authorization: Bearer <credential>
+Content-Type: application/json
-**Related:** `onboarding.md` in this folder — what to do once your endpoint conforms.
-The `reference-provider/` and `example-provider/` packages in this repository are working
-implementations of everything below.
-
----
-
-## 1. Target revision
-
-This profile targets **A2A v1.0.1** (`github.com/a2aagent/A2A`, released 2026-05-28), the current
-stable release under Linux Foundation governance.
-
-A2A v1.0 ships official SDKs in **Python, JavaScript, Java, Go and .NET**. Autonomous therefore
-publishes **no SDK of its own** — use the one for your stack. What Autonomous publishes instead is
-this profile, a reference implementation, and a conformance runner you can point at your own endpoint.
+{"jsonrpc":"2.0","id":1,"method":"agent.list","params":{}}
+```
+```jsonc
+{"jsonrpc":"2.0","id":1,"result":{"agents":[{"id":"seo","name":"SEO Analyst"}]}}
+```
-> **HP-001** An implementation MUST declare its A2A protocol support through its Agent Card. Clients
-> MUST NOT infer capability from anything else — the card is the single source of truth.
+Field names are camelCase. Ids are strings. Timestamps are ISO-8601 UTC.
-> **HP-002** A provider MUST implement A2A v1.0 or later. Autonomous pins to v1.0.1 and will state a
-> new pin, with a deprecation window, before requiring anything newer.
+---
-> **HP-004** A provider SHOULD serve a **signed Agent Card** (A2A v1.0), so Autonomous can verify the
-> card was issued by the domain owner rather than merely served from it. Because the card is this
-> profile's single source of truth for capability (HP-001), signing it is the one control that makes
-> that trust verifiable. Expect this to become a MUST in a future revision; providers onboarding now
-> should plan for it.
+## The model
-### Canonical base
+```
+machine one provider endpoint + one credential ← what the user creates and pays for
+ └── agent one working unit inside it ← what the user picks and talks to
+ └── turn one user message until the agent stops
+```
-Everything this profile publishes lives under **`https://harness.autonomous.ai/api/a2a/`**:
+**There are only agents.** A provider has no session, thread, or conversation concept here: **one
+agent is one continuous transcript.** Autonomous presents a session to its own clients and synthesises
+it from the agent — entirely our side of the line, and nothing you need to model.
-| Path | What |
+| Autonomous concept | On your side |
|---|---|
-| `ext/<name>` | extension identifier URIs, used verbatim in `AgentCard.extensions` |
-| `schema/<name>.json` | the JSON Schemas accompanying this document |
-
-> **HP-003** Extension URIs are opaque identifiers and MUST be sent byte-for-byte as written in §8.
-> A provider MUST NOT normalise, shorten, or re-host them; a mismatched URI means the extension is
-> undeclared (HP-022).
-
-Note that the `Part.metadata` key prefix is `autonomous.ai/` — a short reverse-DNS **key namespace**,
-deliberately not a URL. It appears on every part of every streamed event, and the Harness device
-renders under a tight frame budget, so the prefix is kept short on purpose.
-
----
-
-## 2. Object mapping
-
-| Autonomous concept | A2A concept | Notes |
-|---|---|---|
-| **machine** | one A2A agent endpoint | The credential the user supplies selects *which* workspace/tenant on the provider side |
-| **agent** — one working unit inside a machine | `AgentCard.skills[]` entry | Read-only in Tier 0. **Not** the A2A sense of "agent" — see the note below |
-| **session** (a chat thread) | `contextId` | Starting a new chat mints a new `contextId`; no call is required |
-| **turn** (one user message until the agent stops) | `taskId` | Task lifecycle *is* turn lifecycle |
-| **turn start / end** | `TASK_STATE_WORKING` → `COMPLETED` / `FAILED` / `CANCELED` | |
-| **permission prompt / question to the user** | `TASK_STATE_INPUT_REQUIRED` | Native A2A. No extension |
-| **credential rejected** | `TASK_STATE_AUTH_REQUIRED` | Distinguishable from an outage, so the UI can say "re-enter credential" |
-
-> **One word, two meanings — read this before implementing.** A2A calls *your whole endpoint* an
-> agent: that is what an `AgentCard` describes. Autonomous calls *one working unit inside a machine*
-> an agent, and those map to the **skills** on your card. So a single A2A agent (you) exposes many
-> Autonomous agents (your skills). The product model is **machine → agent → session**; on your side
-> that reads **endpoint → skill → `contextId`**.
+| machine | your endpoint; the credential selects *which* tenant |
+| agent | an entry in `agent.list` |
+| turn | one `agent.send` call and the stream it returns |
+| a question to the user | a `turn_input_required` frame, answered by a resumed `agent.send` |
+| credential rejected | the `unauthenticated` error code |
---
-## 3. Transport and authentication
+## Authentication
-> **HP-010** The endpoint MUST be reachable over HTTPS at a stable, publicly resolvable URL. The URL
-> is registered by Autonomous, not supplied by end users.
+The credential is pasted by the end user into the Autonomous web app and sent on every request as
+`Authorization: Bearer <credential>`. One header, fixed by convention: there is no descriptor to name
+a different one.
-> **HP-011** The provider MUST declare its authentication requirement using standard A2A
-> `securitySchemes`. `APIKey` and `HTTPAuth` (bearer) are the schemes Autonomous supports today.
-> OAuth2 and OpenIdConnect are reserved for a later revision and MUST NOT be relied on.
+It identifies **one tenant**, and must not grant access beyond that tenant.
-> **HP-012** The credential is supplied by the end user in the Autonomous web app and presented by the
-> Autonomous backend on every request. The provider MUST treat it as identifying **one tenant/user**
-> on its side and MUST NOT grant it access beyond that tenant.
-
-> **HP-013** A rejected credential MUST surface as `TASK_STATE_AUTH_REQUIRED` on a task, or as the
-> A2A-standard authentication error on a non-task call — never as a generic failure. The product
-> distinguishes "your credential is wrong" from "the provider is down", and cannot do so without this.
+A rejected credential must answer the `unauthenticated` error code, never a generic failure — the
+product says a different sentence for "your credential is wrong" than for "the provider is down", and
+cannot tell them apart otherwise.
---
-## 4. Agent Card (HP-0xx)
-
-> **HP-020** The provider MUST serve an Agent Card at `/.well-known/agent-card.json`.
+## The eight methods
-> **HP-021** `capabilities.streaming` MUST be `true`. A non-streaming provider is not usable: the
-> product renders assistant output token by token.
+All eight are required. There is nothing to declare, and no capability negotiation.
-> **HP-022** Every Autonomous extension the provider implements MUST be listed in
-> `AgentCard.extensions` by its exact URI (§8). An extension that is implemented but undeclared MUST
-> be treated by clients as absent.
-
-> **HP-023** `skills[]` is the agent list. Each skill's `name` and `description` are shown to the
-> user. A provider with no meaningful agent concept SHOULD expose exactly one skill representing the
-> whole workspace.
+| Method | Params | Result |
+|---|---|---|
+| `agent.list` | — | `{ agents: [{ id, name, description? }] }` |
+| `agent.send` | `{ agentId, turnId, message, resume? }` | **SSE** — see below |
+| `agent.history` | `{ agentId, limit?, before? }` | `{ agentId, events, nextBefore?, truncated? }` |
+| `turn.cancel` | `{ turnId }` | `{ cancelled: true }` |
+| `agent.create` | `{ name, description? }` | `{ id, name, description? }` |
+| `agent.rename` | `{ agentId, name }` | `{ id, name, description? }` |
+| `agent.delete` | `{ agentId }` | `{ deleted: true }` |
+| `agent.recap` | `{ agentId }` | `{ agentId, recap?, text?, turnId? }` |
+
+**"Required" does not mean "pretend".** If your agents are managed inside your own product, do not
+implement a fake mutation — answer `invalid_request` with a message, and Autonomous shows that message
+to the user: *"Agents are managed in Example Co."* An explanation the user can read beats a control
+that is silently missing, which is why nothing has to be declared in advance. Likewise, a provider
+that summarises nothing answers `agent.recap` with no `recap`, and Autonomous derives one from the
+turn's own text instead.
+
+Ignore request fields you do not recognise rather than failing on them, so a client on a newer
+revision still works against you. Reject a method you do not implement with `unsupported`.
+
+### `agent.list`
+
+Authenticated, returning the agents this credential's tenant may use. `id` is stable and opaque to us;
+`name` and `description` are shown to the user.
+
+A provider with no meaningful agent concept returns **exactly one** entry for the whole workspace —
+never an empty list, which reads to the user as a broken machine. An id that disappears between calls
+is treated as deleted, and Autonomous refuses to send to an agent the latest list does not contain.
+
+### `agent.send`
+
+```jsonc
+// → agent.send
+{ "agentId": "seo",
+ "turnId": "t_01J8Z…",
+ "message": { "text": "how is acme pacing?",
+ "attachments": [{ "mediaType": "image/png", "data": "<base64>" }] } }
+```
-Schema for the extension entries: `schema/agent-card.ext.json`.
+Returns `Content-Type: text/event-stream`, one JSON object per `data:` frame. Streaming is not
+optional — the product renders assistant output as it arrives.
----
+`turnId` is minted by the **client** and must be used as given: it is how a turn is cancelled. A
+provider that mints its own leaves an early cancel with nothing to name — the user presses stop, and
+there is no id to send yet.
-## 5. Messaging (HP-1xx)
+Attachments are optional to support. A provider that cannot read images must **fail the turn** with a
+clear message rather than silently discarding them; silent loss reads to the user as the agent
+ignoring what they sent.
-> **HP-100** The provider MUST implement `SendStreamingMessage` and return Server-Sent Events.
+### The two stream guarantees
-> **HP-101** A message that begins a new chat carries a fresh `contextId` and no `taskId`. A follow-up
-> within the same chat carries the existing `contextId`.
+**It ends, exactly once.** Every stream ends with one terminal frame — `turn_completed`, `turn_failed`,
+`turn_cancelled` or `turn_input_required`. None leaves the web spinning forever; two ends the turn
+twice.
-> **HP-102** The provider MUST emit a terminal task state on every stream. A stream that ends without
-> one is a protocol violation; clients will treat the turn as failed.
+**What is inside is renderable.** The kinds below, discriminated on `kind`. An unrecognised kind is
+ignored, never fatal, so a later revision may add one. An event with **no `kind` at all** but with
+`text` is conformant and renders as plain assistant output — the smallest correct provider streams
+`{"text":"…"}` then `{"kind":"turn_completed"}`.
-> **HP-103** The provider MUST implement `CancelTask`. After a successful cancel, the corresponding
-> SSE stream MUST terminate and the task MUST report `TASK_STATE_CANCELED`.
+### `turn.cancel`
-> **HP-104** When the agent needs an answer from the user (a permission prompt, a clarifying
-> question), the provider MUST enter `TASK_STATE_INPUT_REQUIRED` and MUST accept a subsequent Message
-> carrying the same `taskId` as the answer.
+Always accepted, including for a turn that has not started yet — which must then terminate
+immediately if it later begins. After a successful cancel the stream terminates with `turn_cancelled`.
-> **HP-105** Assistant output MUST be delivered as `TaskStatusUpdateEvent` messages containing `Part`
-> objects. Files produced by the turn SHOULD be delivered as `Artifact` via
-> `TaskArtifactUpdateEvent`.
+### `agent.history`
-> **HP-106** A user message MAY carry image attachments. These travel as standard A2A `Part` objects
-> using `raw` (base64) with `mediaType`, alongside the text part — no Autonomous extension is
-> involved. A provider that cannot accept images MUST fail the task with a clear message rather than
-> silently discarding them; silent loss reads to the user as the agent ignoring what they sent.
+Transcripts live **entirely on your side**. Autonomous stores none for a provider machine, which is
+why this is required: without it a page refresh loses the conversation.
-> **HP-107** A client MAY name the skill a turn belongs to in `Message.metadata` as
-> `autonomous.ai/agentId`, matching an `AgentCard.skills[].id`. A2A has no skill selector on a
-> Message, so without this a provider serving more than one skill can only guess — and a provider
-> that guesses "the first one" attributes every conversation to the same skill no matter which one
-> the user picked. A provider MAY ignore the field and choose its own skill; it MUST NOT fail a turn
-> because of it.
->
-> The field selects a skill only when there is nothing more specific: a turn continuing an existing
-> `contextId`, or carrying a `taskId`, keeps the skill that conversation already belongs to, whatever
-> the field says. A conversation belongs to one skill for its whole life — the client's session list
-> is scoped to a single agent (HP-204), so a thread that changed skill mid-way would lose half its
-> turns from each agent's list.
+Returns that agent's transcript newest-last, in the **same event objects the stream emitted** — one
+shape, so a replayed transcript and the live view cannot disagree about what happened. A provider that
+stores its own richer form converts on the way out.
----
+Streamed **deltas may be coalesced**: `text_delta "Acme is at "` then `text_delta "118% of pace."` may
+come back as one `text_delta "Acme is at 118% of pace."`. Deltas are a streaming detail. Everything
+else — the kinds, their order, the tool ids, the fields — must survive, because that is what a client
+renders from. `turn_started`, the terminal frames, the recap bracket and `done` are live-turn signals
+and need not appear at all; `done` in particular restates text already streamed.
-## 6. History (HP-2xx)
+With `limit`, the response is a window ending at the newest event, or at `before` when supplied, plus
+`nextBefore` — an opaque cursor naming the next older window, omitted once the start is reached.
+Clients never construct a cursor. Without `limit`, the whole transcript comes back and `nextBefore` is
+omitted. A transcript you truncate must carry `truncated: true`; silent truncation is a violation.
-Chat history lives **entirely on the provider side**. Autonomous stores no transcript for a `provider`
-machine — there is no database to fall back on. This is why the two methods below are required rather
-than recommended: without them, a page refresh loses the conversation.
+```jsonc
+// → agent.history { "agentId": "seo", "limit": 200 }
+{ "agentId": "seo",
+ "events": [ { "kind": "user_message", "text": "how is acme pacing?" },
+ { "kind": "text_delta", "text": "Acme is at 118%." } ],
+ "nextBefore": "evt_8841",
+ "truncated": false }
+```
-> **HP-200** The provider MUST implement `ListTasks`, and MUST support grouping/filtering by
-> `contextId`. This backs the session list.
+### `agent.recap`
-> **HP-201** The provider MUST implement `GetTask`, returning the full message history of the task.
-> This backs the transcript view.
+The agent's **last** recap — one short summary, used to restore the physical device's tile after a
+reboot, since it has no stream to read. There is no history to page through: the device shows one tile
+per agent.
-> **HP-202** The provider MUST return the complete transcript in a single `GetTask` response.
-> `GetTask` itself is never paged; a provider that wants windowing declares `context-history`
-> (HP-304), which pages a whole context rather than a turn. See §10.1.
+```jsonc
+// → agent.recap { "agentId": "seo" }
+{ "agentId": "seo",
+ "recap": "Acme is over pace",
+ "text": "Acme is at 118% of pacing this week.",
+ "turnId": "t_01J8Z" }
+```
-> **HP-203** A transcript exceeding **5 MB** serialized MAY be truncated by the provider, which MUST
-> then mark the response so the client can tell the user the view is partial. Silent truncation is a
-> violation.
+**This is the same object `recap_end` carries**, so a recap has one shape whether it was pushed on a
+turn's stream or pulled here. An **absent `recap` means nothing has been summarised yet** — the same
+convention, and the correct answer for a provider that does not summarise at all.
-> **HP-204** A task SHOULD carry `metadata.agentId` — the `AgentCard.skills[].id` whose skill ran it.
-> The client's model is machine → agent → session, so its session list is always scoped to ONE agent;
-> a task that does not say which skill it belongs to cannot be placed in that list, and selecting an
-> agent then shows either every conversation on the machine or none of them. A provider serving a
-> single skill MAY omit it: with one skill there is nothing to disambiguate.
+`turnId` is optional but strongly recommended: this method is scoped to an **agent** and cannot be
+scoped to a turn, so a client asking the instant a turn ends otherwise receives the previous turn's
+summary with no way to tell.
---
-## 7. Event vocabulary on `Part.metadata`
-
-A2A core has no representation for thinking, tool calls, or the fine structure the product renders.
-This profile defines a namespace on `Part.metadata`.
-
-> **HP-210** Autonomous-specific metadata MUST be namespaced under keys beginning `autonomous.ai/`.
-> Clients MUST ignore unknown keys in that namespace rather than failing.
-
-> **HP-211** A provider that emits no `autonomous.ai/*` metadata is conformant. Its output renders as
-> plain assistant text. Richness is opt-in.
+## Asking the user something
-The recognised event kinds — declared here **independently** of any Autonomous internal type, so that
-this contract does not inherit an internal shape:
-
-| `autonomous.ai/kind` | Meaning |
-|---|---|
-| `user_message` | the user's own turn, replayed in history |
-| `thinking_delta` | a chunk of reasoning text |
-| `thinking_title` | a short label for a reasoning block |
-| `text_delta` | a chunk of assistant output |
-| `tool_start` | a tool invocation began |
-| `tool_end` | a tool invocation finished (with output, error flag, summary) |
-| `context_compact` | the provider compacted its own context |
-| `done` | the turn's final result text |
-| `recap_start` | the turn is being summarised (HP-212) |
-| `recap_end` | the summary, or its absence — the recap phase is over (HP-212) |
-
-Turn lifecycle (`turn_started` / `turn_ended`) is **not** metadata — it is derived from A2A task
-states, per HP-102.
-
-> **HP-212** A provider MAY deliver the turn's recap in-stream, as a **pair** of parts on non-terminal
-> status events emitted after the turn's output and **before** the terminal event:
->
-> - `recap_start` — summarising has begun. Carries no content; it exists so the client can show a
-> "preparing a recap" indicator and hold its busy state open for a wait it cannot otherwise see.
-> - `recap_end` — the phase is over. The headline travels in `autonomous.ai/recap` (≤ 200 chars) and
-> the fuller body as the Part's own `text`, meaning exactly what `recapEntry.recap` and
-> `recapEntry.body` mean in HP-302. **`autonomous.ai/recap` absent means no recap was produced** —
-> a turn that said nothing, or a summariser that failed. The client then clears its indicator and
-> paints nothing.
->
-> A provider that emits `recap_start` MUST emit a matching `recap_end` before the terminal event, even
-> when there is no recap: an indicator that is opened and never closed is worse than no indicator.
-> A client that receives a `recap_end` MUST prefer it over `autonomous.GetRecap`, because it is
-> unambiguously **this** turn's recap.
->
-> The problem this solves: `autonomous.GetRecap` is scoped to an AGENT and takes no task id, so a
-> client asking for "the latest recap" the moment a turn ends can only guess — and if the provider
-> has not finished summarising yet, the newest entry it holds is the PREVIOUS turn's. Pushing the
-> recap on the turn's own stream removes the guess. The cost is honest and bounded: the terminal event
-> waits for the summary, so the turn stays open for as long as summarising takes — which is precisely
-> what `recap_start` lets the client explain to the user. A provider that would rather close the turn
-> immediately simply emits neither kind and keeps HP-302 alone.
->
-> This does NOT replace HP-302: a device restoring its tiles after a reboot has no stream to read, so
-> a provider that pushes SHOULD also persist.
-
-Schema: `schema/part-metadata.json`.
-
----
+When the agent needs an answer — a permission prompt, a clarifying question — end the stream with
+`turn_input_required` carrying a `prompt`, and accept a later `agent.send` with the **same `turnId`**
+and `resume: true` as the answer, continuing the same turn.
-## 8. Extensions (HP-3xx)
+The stream ends rather than being held open, deliberately: a human decision has no time bound, and an
+HTTP request whose duration a user controls is a connection leak on both sides.
-Each extension is optional and MUST be declared per HP-022. A client hides the corresponding feature
-entirely when an extension is absent, rather than offering a control that fails.
-
-| URI | Adds |
-|---|---|
-| `https://harness.autonomous.ai/api/a2a/ext/workspace-files` | browse and read files in an agent |
-| `https://harness.autonomous.ai/api/a2a/ext/workspace-write` | create / rename / delete agents and sessions |
-| `https://harness.autonomous.ai/api/a2a/ext/session-recap` | short persisted per-turn summaries (used by the device) |
-| `https://harness.autonomous.ai/api/a2a/ext/context-history` | a whole context's transcript in one call, optionally windowed |
-| `https://harness.autonomous.ai/api/a2a/ext/voice` | provider-side routing of a spoken task to an agent |
-
-### 8.1 Method naming
-
-Extension methods travel on the **same JSON-RPC endpoint** as A2A core — there is no second URL.
-
-> **HP-310** Extension methods MUST be named `autonomous.<Verb>`. The prefix keeps them from ever
-> colliding with a current or future A2A core method name, and makes it obvious in a log which calls
-> are profile extensions rather than standard A2A.
-
-> **HP-311** A provider MUST reject a call to an extension method it has not declared, with JSON-RPC
-> `-32601` (method not found). Answering a method the Agent Card does not advertise contradicts
-> HP-022 and leaves the client unable to trust the card.
-
-### 8.2 The extensions
-
-> **HP-300** `workspace-files` — read-only file access, scoped to an agent.
-> Methods: **`autonomous.ListFiles`** (`{ agentId, path? }` → `{ files }`) and
-> **`autonomous.ReadFile`** (`{ agentId, path }` → `{ path, content, truncated? }`).
-> Schema: `schema/ext-workspace-files.json`.
-
-> **HP-301** `workspace-write` — mutations on agents and sessions. Methods:
-> **`autonomous.CreateAgent`**, **`autonomous.RenameAgent`**, **`autonomous.DeleteAgent`**,
-> **`autonomous.SetSessionTitle`**, **`autonomous.DeleteSession`**.
-> `AgentCard.extensions[].params` declares which halves are supported: `{ agents: bool, sessions: bool }`.
-> A provider declaring this extension MUST enforce that every operation stays inside the tenant
-> identified by the credential. Schema: `schema/ext-workspace-write.json`.
-
-> **HP-302** `session-recap` — short persisted per-turn summaries.
-> Method: **`autonomous.GetRecap`** (`{ agentId, n? }` → `{ agentId, entries }`).
-> Used to restore the device's tiles after a reboot; the device shows nothing rather than stale text
-> when this is absent. An empty `entries` array is correct before any turn has been summarised.
-> Schema: `schema/ext-session-recap.json`.
-
-> **HP-303** `voice` — the provider chooses which agent a transcribed spoken task belongs to.
-> Method: **`autonomous.RouteVoice`** (`{ transcript, candidateAgentIds? }` → `{ agentId, confidence?, reason? }`).
-> **Optional and rarely needed**: Autonomous can route from `skills[]` names and descriptions without
-> provider help, and does so by default. Declare this only to override that routing with your own.
-> A `agentId` of `null` declines and hands routing back to Autonomous.
-> Schema: `schema/ext-voice.json`.
-
-> **HP-304** `context-history` — one context's transcript in a single call, optionally windowed.
-> Method: **`autonomous.GetContextHistory`** (`{ contextId, limit?, before? }` →
-> `{ contextId, messages, hasMore?, oldestCursor?, staleCursor?, truncated? }`).
-> `GetTask` (HP-201) returns one TURN, but a client opening a chat wants the whole CONTEXT — without
-> this it must call `ListTasks` then `GetTask` once per turn, each at full size. `limit` absent means
-> the complete transcript, and the provider MUST then omit the three paging fields entirely; that
-> absence is how a client tells a windowed response from a whole one. Paging runs backwards only:
-> `before` is a `messageId` the client already holds (exclusive), taken from the previous response's
-> `oldestCursor`. `messages` is ALWAYS oldest-first so a page can be prepended as received. A window's
-> start MUST be snapped back to a turn boundary so it never splits a tool call from its result — which
-> is why a window may be LONGER than `limit`, and why `limit` is a floor rather than a count. A
-> `before` that is no longer in the transcript MUST answer `staleCursor: true` with empty `messages`
-> rather than an error, so the client can reload instead of showing a broken chat.
-> Schema: `schema/ext-context-history.json`.
+```
+client provider
+ │── agent.send {turnId: t1} ──────────►│
+ │◄── … events … │
+ │◄── turn_input_required {prompt} ─────│ stream closes
+ │ │
+ │── agent.send {turnId: t1, resume} ──►│ same turn continues
+ │◄── … events … │
+ │◄── turn_completed ───────────────────│
+```
---
-## 9. Out of scope
+## The event vocabulary
-Deliberate omissions. Listed so their absence is a decision on record and not a gap:
+One flat, self-describing object per frame. Every event must be readable without the frames before it
+— that is what lets the same objects serve the live stream and `agent.history`.
-| Not in this profile | Why |
-|---|---|
-| Model / effort selection | The provider owns its own model configuration. Reaching into it from the Autonomous UI would fight the provider's own surface and expose a control we cannot honour consistently. No model picker is shown for `provider` machines |
-| Agent login flows | The provider owns authentication. The credential field in the Autonomous UI is the entire story |
-| Explicit context compaction | The provider manages its own context window. Autonomous never asks a provider to compact; the `context_compact` event kind (§7) exists only so a provider can *report* that it did |
-| End-to-end encryption | `provider` machines are **not** end-to-end encrypted. Plaintext already originates at the provider, so E2EE between the user and the provider would hide content from Autonomous, not from the provider. Users are shown this explicitly. Providers are onboarded under a data-processing agreement, which is the control that replaces the cryptographic one |
-
-Additionally, a set of frames exists on the Autonomous data plane that **never crosses this boundary**:
-live speaking-presence indicators, client-count bookkeeping, machine metadata and revocation, and
-device pairing. These are handled entirely inside Autonomous. A provider neither sends nor receives
-them, and MUST NOT attempt to.
-
-> **HP-400** A provider MUST ignore any frame it does not recognise rather than failing the stream.
-> Autonomous replies `UNSUPPORTED` on behalf of a provider for any capability the Agent Card does not
-> declare, so an undeclared feature never reaches the provider at all.
+| `kind` | Fields | Meaning |
+|---|---|---|
+| `turn_started` | `turnId`, `agentId`, `at?` | the turn is underway |
+| `user_message` | `text` | the user's own turn, replayed in history |
+| `thinking_title` | `title` (or `text`), `thinkingId?` | a short label for a reasoning block |
+| `thinking_delta` | `text`, `thinkingId?` | a chunk of reasoning |
+| `text_delta` | `text` | a chunk of assistant output |
+| `tool_start` | `toolId`, `tool`, `title?`, `input?` | a tool invocation began |
+| `tool_end` | `toolId`, `tool?`, `ok?`, `output?`, `summary?`, `durationSeconds?` | it finished |
+| `context_compact` | `text?` | the provider compacted its own context |
+| `done` | `text` | the turn's final result text |
+| `recap_start` | — | summarising has begun |
+| `recap_end` | `recap?`, `text?` | summarising is over |
+| `turn_completed` | — | terminal |
+| `turn_failed` | `error` | terminal |
+| `turn_cancelled` | — | terminal |
+| `turn_input_required` | `prompt` | terminal; the turn is paused, not over |
+
+`tool_start` and `tool_end` must carry the same `toolId`, unique within the turn — tools can overlap,
+so pairing by position is not available, and an event without one is dropped rather than rendered as a
+row that never resolves. `ok: false` marks failure; **absent `ok` is not a failure**, it is the
+provider not saying.
+
+Statistics are omitted rather than fabricated. A message count nobody counted, or a timestamp nobody
+recorded, is worse than an absent field — the client hides what it did not receive.
+
+Schema: `schema/event.json`.
+
+### The recap phase
+
+A turn may be summarised in-stream, as a **pair** emitted after the output and before the terminal
+frame:
+
+- `recap_start` — summarising has begun. Carries nothing; it exists so the client can show an
+ indicator and hold its busy state open for a wait it cannot otherwise see.
+- `recap_end` — the phase is over. The headline travels in `recap` (≤ 200 characters), the fuller body
+ in `text`. **An absent `recap` means no recap was produced** — a turn that said nothing, or a
+ summariser that failed. The client clears its indicator and paints nothing.
+
+`recap_start` without a matching `recap_end` before the terminal frame leaves an indicator open
+forever, which is worse than never opening one.
+
+A pushed recap is unambiguously **this** turn's, which `agent.recap` cannot promise. A provider that
+pushes should also persist, for the device restoring its tiles.
---
-## 10. Field projections and resolved gaps
-
-The Autonomous client requires fields A2A does not carry. Each is resolved here so implementers do not
-have to guess. **Most are synthesised by the Autonomous backend — the provider burden is small.**
-
-### 10.1 Transcript pagination
-
-The Autonomous client can request a windowed transcript (a limit plus a cursor). A2A `GetTask` has no
-equivalent — and it is scoped to one TURN besides, while the client is opening a whole CONTEXT.
-
-**Resolution:** the `context-history` extension (HP-304). It takes `{ contextId, limit?, before? }`
-and answers `{ messages, hasMore?, oldestCursor?, staleCursor? }` — deliberately the same field names
-the Autonomous client already sends and reads, so nothing has to be translated in the middle.
-
-A provider that does not declare it is still fully conformant: HP-202 stands unchanged, and a client
-falls back to `ListTasks` + `GetTask` per turn at full size. What that fallback cannot do is page —
-so a long conversation arrives whole or not at all, which is exactly what the 5 MB ceiling of HP-203
-was there to bound.
-
-### 10.2 `engine`
-
-The client models an engine as one of eight local CLIs. A provider machine is none of them.
-
-**Resolution:** the field is **omitted** for provider-backed agents. The client treats an absent
-engine as provider-backed and skips every engine-specific branch. Providers MUST NOT invent a value.
+## Errors
-### 10.3 Skill → agent projection
+JSON-RPC error objects whose `code` is a **string**:
-| Client field | Source |
-|---|---|
-| `id` | the skill's id |
-| `name`, `description` | the skill's `name`, `description` |
-| `userId` | **synthesised** by the backend — the Autonomous owner of the machine |
-| `status` | **synthesised** — constant `active` |
-| `createdAt`, `updatedAt` | **synthesised** — the machine's own timestamps unless the skill carries better |
-| `engine` | omitted (§10.2) |
-
-### 10.4 Task → session-list item projection
+```jsonc
+{ "jsonrpc": "2.0", "id": 1, "error": { "code": "unauthenticated", "message": "…" } }
+```
-| Client field | Source |
+| Code | Meaning |
|---|---|
-| `id` | `contextId` |
-| `title` | task metadata title, else the first user message truncated |
-| `timestamp`, `lastActivity` | task timestamps |
-| `messageCount` | best-effort; **omitted when unknown**, and the client hides the count rather than showing zero |
-| `participants` | not modelled by A2A; the client omits it |
+| `unauthenticated` | the credential is missing, wrong or revoked |
+| `not_found` | no such agent or turn |
+| `unsupported` | a method this provider does not implement |
+| `invalid_request` | malformed parameters, or a mutation this provider declines |
+| `rate_limited` | back off and retry |
+| `internal` | anything else |
-> **HP-220** A provider MUST NOT fabricate `messageCount` or similar statistics. Omission is correct;
-> a wrong number is worse than a missing one.
+Only `unauthenticated` is load-bearing — it must be distinguishable, and it should carry HTTP 401 so a
+client that never parses the body can tell a rejected credential from an outage. `message` is shown to
+the user wherever one is present, so write it for them.
---
-## 11. Security (HP-9xx)
+## Security
-> **HP-900** All traffic MUST be over TLS.
+All traffic over TLS. The endpoint must be at a stable, publicly resolvable HTTPS URL the owner can
+copy out of your product — no IP literals, no tunnels that move.
-> **HP-901** Everything a provider sends is **untrusted input** to the Autonomous web UI and to the
-> physical device screen. The Autonomous backend validates and allowlists every frame crossing this
-> boundary; a provider MUST NOT rely on being able to inject arbitrary client-side structures.
-> Non-conforming frames are dropped and logged, and a stream that repeats the violation is closed.
+Everything a provider sends is **untrusted input** to the Autonomous web UI and to the physical device
+screen. The Autonomous backend validates and allowlists every frame crossing this boundary;
+non-conforming frames are dropped and logged, and a stream that repeats the violation is closed.
-> **HP-902** Providers are rate limited per machine. Sustained excess closes the stream.
+Providers are rate limited per machine; sustained excess closes the stream. Do not log or transmit the
+supplied credential beyond what is required to authenticate the request.
-> **HP-903** A provider MUST NOT log or transmit the supplied credential beyond what is required to
-> authenticate the request.
+Optional fields and new event kinds may be added over time. A published field is never renamed,
+removed, retyped, or reinterpreted.
---
-## 12. Versioning
-
-This document is a **compatibility contract, not ordinary prose.** The same discipline the Autonomous
-codebase applies to its own launcher/daemon contract applies here.
+## Conformance
-> **HP-910** Optional fields MAY be added to a published revision.
+`reference-provider/` contains a scripted implementation and a runner. Point it at your endpoint:
-> **HP-911** A published field MUST NOT be renamed, removed, retyped, or reinterpreted. Any of those
-> requires a new revision.
-
-> **HP-912** When a new revision exists, providers and clients MUST be able to negotiate through the
-> Agent Card. A revision MUST be served alongside its predecessor for a deprecation window; removing
-> support without one breaks deployed integrations.
+```bash
+npm run conformance -- --url https://agent.example.com --key <credential> \
+ --bad-key <deliberately invalid> --ask-phrase "<prompt that makes it ask>"
+```
-**0.1.0 → 0.2.0 was an exception, and the only one.** It renamed published fields (`projectId` →
-`agentId`) and dropped 0.1.0 rather than serving both, which is precisely what HP-911 and HP-912
-forbid. It was taken because 0.1.0 was one day old and had no implementers — there was no deployed
-integration for the rule to protect. From 0.2.0 on there is, so the rule binds: a rename now means a
-0.3.0 served alongside 0.2.0 for a deprecation window. If you are reading this because you already
-implemented 0.1.0, contact us — that is a case we did not think existed.
+**Pass condition: zero failures.** Warnings and skips are expected and are printed with their reasons
+— read them, do not just count them. Five things cannot be verified from outside and are human review:
+tenant isolation, the truncation flag, fabricated statistics, rate limiting, and credential handling.
---
-## Appendix A — Clause index
-
-| Range | Area |
-|---|---|
-| HP-001 … HP-004 | Target revision and canonical base |
-| HP-010 … HP-013 | Transport and authentication |
-| HP-020 … HP-023 | Agent Card |
-| HP-100 … HP-107 | Messaging |
-| HP-200 … HP-204 | History |
-| HP-210 … HP-220 | Event vocabulary and projections |
-| HP-300 … HP-311 | Extensions |
-| HP-400 | Unknown frames |
-| HP-900 … HP-903 | Security |
-| HP-910 … HP-912 | Versioning |
+## Appendix A — A worked turn
-Tier 0 (required for any provider) is: HP-003, HP-010–013, HP-020–023, HP-100–105, HP-200–203, HP-900–903,
-HP-910–912. Everything in HP-3xx is optional.
+```jsonc
+// → POST / {"jsonrpc":"2.0","id":1,"method":"agent.send","params":
+// {"agentId":"seo","turnId":"t_01J8Z","message":{"text":"how is acme pacing?"}}}
-## Appendix B — Conformance
+// ← 200 text/event-stream
+data: {"kind":"turn_started","turnId":"t_01J8Z","agentId":"seo","at":"2026-08-06T09:12:44Z"}
-The conformance suite asserts one check per clause ID and names the failing ID in its output, so a red
-result points at a section of this document rather than at a symptom. See phase 6 of the
-implementation plan.
+data: {"kind":"thinking_title","title":"Checking pacing"}
-## Appendix C — Coverage of the Autonomous client surface
+data: {"kind":"tool_start","toolId":"c1","tool":"query","title":"acme · last 30d"}
-Every operation the Autonomous client can issue, and where it lands in this profile. This table is the
-audit artifact: **an entry that is neither Tier 0, nor an extension, nor explicitly out of scope is a
-gap in the spec.** Re-run this audit whenever the client gains an operation.
+data: {"kind":"tool_end","toolId":"c1","tool":"query","ok":true,"summary":"1 row"}
-| Client operation | Disposition |
-|---|---|
-| `message` | Tier 0 — HP-100 |
-| `cancel` | Tier 0 — HP-103 |
-| `permission_response` | Tier 0 — HP-104 (answer to `INPUT_REQUIRED`) |
-| `question_response` | Tier 0 — HP-104 |
-| `new_chat` | Tier 0 — no call; mint a fresh `contextId` (§2) |
-| `agents_list` | Tier 0 — `AgentCard.skills` (HP-023) |
-| `sessions_list` | Tier 0 — `ListTasks` (HP-200) |
-| `session_get` | Tier 0 — `GetTask` (HP-201); whole-context and paged via `context-history` (HP-304) when declared |
-| `agent_files` | Extension — `workspace-files` (HP-300) |
-| `agent_read_file` | Extension — `workspace-files` (HP-300) |
-| `agent_create` | Extension — `workspace-write` (HP-301) |
-| `agent_update` (rename) | Extension — `workspace-write` (HP-301) |
-| `agent_delete` | Extension — `workspace-write` (HP-301) |
-| `session_update_title` | Extension — `workspace-write` (HP-301) |
-| `session_delete` | Extension — `workspace-write` (HP-301) |
-| `agent_recent` | Extension — `session-recap` (HP-302) |
-| `voice_route` | Extension — `voice` (HP-303); Autonomous routes from `skills[]` by default |
-| `agent_update` (model) | **Out of scope** — §9, provider owns model configuration |
-| `models_list` | **Out of scope** — §9 |
-| `compact` | **Out of scope** — §9, provider owns its context window |
-| `claude_login_start` / `_submit` / `_status` | **Out of scope** — §9, provider owns authentication |
-| `e2ee_pairings_list` / `_pairing_unpair` / `_pairings_unpair_all` / `e2ee_browser_link_create` | **Out of scope** — §9, no E2EE for `provider` |
-| `speaking` | **Never crosses this boundary** — ephemeral presence, fanned out inside Autonomous |
-| `__clients`, `machine_meta`, `machine_revoked`, `device_e2ee_pair` | **Never crosses this boundary** — Autonomous-internal control frames |
-
-### Client-operation coverage — how to re-run this audit
-
-Autonomous re-runs this audit whenever its client gains an operation: every one must appear above as
-Tier 0, as a named extension, or as explicitly out of scope. An operation absent from this table is an
-unresolved gap, not an implicit "no" — if you find one, say so rather than guessing.
-
-### Event-kind coverage
-
-The ten kinds in §7 (`user_message`, `thinking_delta`, `thinking_title`, `text_delta`, `tool_start`,
-`tool_end`, `context_compact`, `done`, `recap_start`, `recap_end`) cover the client's full render
-vocabulary. Turn lifecycle (`turn_started` / `turn_ended`) is carried by A2A task states per HP-102 and
-is deliberately not a metadata kind. Nothing in the client's vocabulary is unrepresented.
-
-`recap_start` / `recap_end` are the two kinds that are not raw turn output: they are the summary OF the
-turn. They exist as kinds because the alternative — asking for it afterwards with
-`autonomous.GetRecap` — cannot say WHICH turn it wants, and because the wait between them is real time
-the user is watching (HP-212).
+data: {"kind":"text_delta","text":"Acme is at "}
----
+data: {"kind":"text_delta","text":"118% of pace."}
-## Appendix D — Worked example
-
-One complete turn, end to end. Every field the Autonomous client needs is derivable from what appears
-here; this example exists to prove that, and doubles as the shortest path to understanding the
-profile.
-
-**1. Discovery.** `GET https://agent.example.com/.well-known/agent-card.json`
-
-```json
-{
- "name": "Example Marketing Agent",
- "description": "Answers questions about ad spend and builds reporting queries.",
- "version": "1.0.0",
- "capabilities": { "streaming": true },
- "securitySchemes": { "apiKey": { "type": "apiKey", "in": "header", "name": "x-api-key" } },
- "skills": [
- { "id": "acme-reporting", "name": "Acme reporting", "description": "Acme's ad accounts" }
- ],
- "extensions": [
- { "uri": "https://harness.autonomous.ai/api/a2a/ext/session-recap" }
- ]
-}
-```
+data: {"kind":"done","text":"Acme is at 118% of pace."}
-The client now shows one agent ("Acme reporting"). No file browser, no rename — those extensions
-are absent. No model picker either; that is out of scope for every provider (§9).
-
-**2. The user types a message.** Autonomous calls `SendStreamingMessage` with the user's credential in
-the declared header, a fresh `contextId`, and no `taskId` (a new chat):
-
-```json
-{
- "message": {
- "role": "ROLE_USER",
- "messageId": "m-1",
- "contextId": "ctx-91af",
- "parts": [{ "text": "did acme blow through budget this week?" }]
- }
-}
-```
+data: {"kind":"recap_start"}
-**3. The provider streams SSE.** Abridged to one event per kind:
+data: {"kind":"recap_end","recap":"Acme at 118% of pace","text":"Acme is pacing 18% ahead…"}
+data: {"kind":"turn_completed"}
```
-event: status-update
-data: {"taskId":"task-77","contextId":"ctx-91af","status":{"state":"TASK_STATE_WORKING"}}
-
-event: status-update
-data: {"taskId":"task-77","status":{"state":"TASK_STATE_WORKING","message":{"role":"ROLE_AGENT",
- "parts":[{"text":"Checking pacing…","metadata":{"autonomous.ai/kind":"thinking_delta",
- "autonomous.ai/thinkingId":"t1"}}]}}}
-
-event: status-update
-data: {"taskId":"task-77","status":{"state":"TASK_STATE_WORKING","message":{"role":"ROLE_AGENT",
- "parts":[{"text":"","metadata":{"autonomous.ai/kind":"tool_start",
- "autonomous.ai/toolCallId":"c7","autonomous.ai/tool":"query_spend",
- "autonomous.ai/toolInput":{"account":"acme","window":"7d"}}}]}}}
-
-event: status-update
-data: {"taskId":"task-77","status":{"state":"TASK_STATE_WORKING","message":{"role":"ROLE_AGENT",
- "parts":[{"text":"7 rows","metadata":{"autonomous.ai/kind":"tool_end",
- "autonomous.ai/toolCallId":"c7","autonomous.ai/tool":"query_spend",
- "autonomous.ai/isError":false,"autonomous.ai/summary":"Returned 7 rows",
- "autonomous.ai/durationSeconds":1.4}}]}}}
-
-event: status-update
-data: {"taskId":"task-77","status":{"state":"TASK_STATE_WORKING","message":{"role":"ROLE_AGENT",
- "parts":[{"text":"Acme is at 118% of pacing.","metadata":{"autonomous.ai/kind":"text_delta"}}]}}}
-
-event: status-update
-data: {"taskId":"task-77","status":{"state":"TASK_STATE_COMPLETED"},"final":true}
-```
-
-A provider that emitted only the two `text_delta`-shaped parts with **no** metadata at all would also
-be conformant (HP-211) — the turn would simply render as plain text.
-**4. What the client reconstructs.** `TASK_STATE_WORKING` opens the turn and the terminal state closes
-it (HP-102); no metadata kind is involved. Reloading the page calls `GetTask("task-77")`, and the
-same parts rebuild the transcript:
+The same objects, minus the lifecycle and recap frames, are what `agent.history` returns for that
+agent.
+
+## Appendix B — The smallest conformant provider
+
+```jsonc
+// agent.list → { "agents": [{ "id": "main", "name": "Tiny" }] }
+// agent.history → { "agentId": "main", "events": [] }
+// turn.cancel → { "cancelled": true }
+// agent.recap → { "agentId": "main" }
+// agent.create → error { "code": "invalid_request", "message": "Agents are managed in Tiny" }
+// agent.rename → the same
+// agent.delete → the same
+// agent.send → SSE:
+// data: {"text":"Hello."}
+// data: {"kind":"turn_completed"}
+```
-| Client field | Derived from |
-|---|---|
-| session id | `contextId` = `ctx-91af` |
-| title | task metadata title, else the first user message truncated (§10.4) |
-| timestamp | task timestamps |
-| events | the `Part` sequence above, keyed by `autonomous.ai/kind` |
-| status | terminal task state → `idle`; `TASK_STATE_FAILED` → `error` |
-| engine | omitted (§10.2) |
-| messageCount | not sent; the client hides the count rather than showing zero (HP-220) |
-| hasMore / cursors | absent — v1 returns the whole transcript (HP-202) |
-
-**5. If the agent needs an answer.** Instead of completing, the provider emits
-`TASK_STATE_INPUT_REQUIRED` with a question in the message. Autonomous renders it, and the user's
-answer returns as a new Message carrying **the same `taskId`** (HP-104). The task then resumes and
-completes as above.
+Everything richer than this is opt-in.
diff --git a/provider/spec/onboarding.md b/provider/spec/onboarding.md
index ec5462472..d5b5ba2e3 100644
--- a/provider/spec/onboarding.md
+++ b/provider/spec/onboarding.md
@@ -8,14 +8,14 @@ What to do once your endpoint implements the profile in `README.md`, and what to
| | |
|---|---|
-| A public HTTPS endpoint | HP-010. Not an IP address, not a tunnel, not "we'll expose it later" |
-| An Agent Card at `/.well-known/agent-card.json` | HP-020 |
-| A test credential | So the checks below run against a real tenant rather than a stub |
+| A public HTTPS endpoint | Not an IP address, not a tunnel, not "we'll expose it later". The machine's OWNER types this URL into our web app, so it has to be one you can publish in your own product |
+| A test credential | So the checks below run against a real tenant rather than a stub. It travels as `Authorization: Bearer` — there is nothing to configure and nothing to declare |
| A named technical contact | Your endpoint backs every machine connected to it; when it goes down, they all go down at once |
-**You do not need an SDK from us.** A2A v1.0 ships official SDKs for Python, JavaScript, Java, Go and
-.NET — use the one for your stack. What this repository gives you instead is the contract, a working
-reference implementation, and a runner that tells you when you are done.
+**There is no SDK, and you do not need one.** The whole protocol is eight JSON-RPC methods over
+HTTPS — smaller than a client library for it would be. This repository gives you the contract, a
+scripted reference implementation, `example-provider/` as copyable prior art, and a runner that tells
+you when you are done.
---
@@ -29,23 +29,25 @@ npm run conformance -- --url https://your-endpoint --key <test credential> \
**Zero failures is the bar.** Warnings and skips are expected, and each prints its reason.
-The two extra flags unlock three more clauses that need knowledge only you have: a credential you know
-to be invalid (HP-013), and a prompt that reliably makes your agent ask the user something
-(HP-103, HP-104).
+The two extra flags unlock four more checks that need knowledge only you have: a credential you know
+to be invalid, and a prompt that reliably makes your agent ask the user something.
If you are debugging your implementation by emailing us, something has gone wrong — the runner is
meant to answer that question without us.
### Read the skips, do not just count them
-Four clauses cannot be verified from outside and become a written question instead:
+Six things cannot be verified from outside and become a written question instead. Each is named by
+the check that skipped:
-| Clause | What we will ask you |
+| Check | What we will ask you |
|---|---|
-| **HP-012** | How a credential is scoped — one credential must not reach another tenant's data |
-| **HP-203** | What happens to a transcript over the size ceiling: marked, or silently truncated |
-| **HP-220** | Whether any statistic is estimated rather than measured — omission is correct, a wrong number is not |
-| **HP-903** | Whether the credential we send is written to logs or forwarded anywhere |
+| `tenant-isolation` | How a credential is scoped — one credential must not reach another tenant's data |
+| `transcript-truncation` | What happens to a transcript over your size ceiling: marked, or silently truncated |
+| `no-fabricated-stats` | Whether any statistic is estimated rather than measured — omission is correct, a wrong number is not |
+| `credential-not-logged` | Whether the credential we send is written to logs or forwarded anywhere |
+| `attachments` | What an image attachment does — the runner can see the turn succeed, but not whether the image was read or quietly dropped |
+| `agent-mutations` | Whether tenant scoping is enforced on **every** mutation, not only on the message path. (Declining to mutate at all is fine — answer `invalid_request` with a message we can show the user) |
---
@@ -55,22 +57,19 @@ Four clauses cannot be verified from outside and become a written question inste
- Written answers to the four questions above.
- Your technical contact and an escalation path.
-We review the endpoint's TLS configuration, its declared `securitySchemes`, and how it handles the
-credential. Expect a conversation about data handling before anything is switched on: a provider
+We review the endpoint's TLS configuration and how you handle the credential. Expect a conversation about data handling before anything is switched on: a provider
machine is **not end-to-end encrypted** — the plaintext originates on your side, and users are told
so plainly in our UI.
-We will also ask you to plan for a **signed Agent Card** (HP-004). The card is this profile's single
-source of truth for capability, so signing it is what makes that trust verifiable.
-
---
## 4. What happens next
-1. We add your endpoint to our provider registry, initially in staging.
-2. We soak it against real traffic on a small number of machines — a full turn, cancellation, an
- `INPUT_REQUIRED` round trip, a page refresh rebuilding the transcript, your endpoint going away and
- coming back, and a revoked credential reporting as *re-enter credential* rather than an outage.
+1. We stage your endpoint against a small number of machines.
+2. We soak it against real traffic — a full turn, cancellation (including a cancel in the first
+ moment, which is what a client-minted `turnId` buys), a `turn_input_required` round trip resumed on the same
+ `turnId`, a page refresh rebuilding the transcript, your endpoint going away and coming back, and
+ a revoked credential reporting as *re-enter credential* rather than an outage.
3. It becomes selectable in the product.
"It worked once" is not a soak. One outage on your side takes down every machine behind it
@@ -80,7 +79,7 @@ simultaneously, and that blast radius is why this step exists.
## 5. If you stop
-Tell us and we will stop offering your endpoint to new machines while existing ones keep working,
+Tell us and we will stop offering your endpoint for new machines while existing ones keep working,
notify their owners with a date, and delete the stored credentials at the end of it. Existing
machines are then marked with a specific reason — never a generic failure.
diff --git a/provider/spec/schema/agent-card.ext.json b/provider/spec/schema/agent-card.ext.json
deleted file mode 100644
index 1264acf64..000000000
--- a/provider/spec/schema/agent-card.ext.json
+++ /dev/null
@@ -1,78 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "$id": "https://harness.autonomous.ai/api/a2a/schema/agent-card.ext.json",
- "title": "Autonomous extension entries in an A2A Agent Card",
- "description": "Constrains the `extensions` array of a standard A2A AgentCard to the URIs this profile recognises. Entries with other URIs are permitted and ignored. See HP-022 in the spec (spec/README.md).",
- "type": "object",
- "properties": {
- "extensions": {
- "type": "array",
- "items": { "$ref": "#/$defs/extensionEntry" }
- }
- },
- "$defs": {
- "extensionEntry": {
- "type": "object",
- "required": ["uri"],
- "properties": {
- "uri": { "type": "string", "format": "uri" },
- "description": { "type": "string" },
- "required": {
- "type": "boolean",
- "description": "A2A-standard field. Autonomous extensions are never required of the client; a provider MUST NOT set this to true for a https://harness.autonomous.ai/api/a2a/ext/* URI."
- },
- "params": { "type": "object" }
- },
- "allOf": [
- {
- "if": {
- "properties": {
- "uri": { "enum": ["https://harness.autonomous.ai/api/a2a/ext/workspace-write"] }
- },
- "required": ["uri"]
- },
- "then": {
- "properties": {
- "params": {
- "type": "object",
- "properties": {
- "agents": {
- "type": "boolean",
- "description": "Provider accepts agent create/rename/delete. Default false."
- },
- "sessions": {
- "type": "boolean",
- "description": "Provider accepts session title-change/delete. Default false."
- }
- }
- }
- }
- }
- }
- ]
- },
- "recognisedUris": {
- "enum": [
- "https://harness.autonomous.ai/api/a2a/ext/workspace-files",
- "https://harness.autonomous.ai/api/a2a/ext/workspace-write",
- "https://harness.autonomous.ai/api/a2a/ext/session-recap",
- "https://harness.autonomous.ai/api/a2a/ext/voice"
- ]
- }
- },
- "examples": [
- {
- "extensions": [
- {
- "uri": "https://harness.autonomous.ai/api/a2a/ext/workspace-files",
- "description": "Browse and read files in an agent."
- },
- {
- "uri": "https://harness.autonomous.ai/api/a2a/ext/workspace-write",
- "params": { "agents": false, "sessions": true }
- }
- ]
- },
- { "extensions": [] }
- ]
-}
diff --git a/provider/spec/schema/event.json b/provider/spec/schema/event.json
new file mode 100644
index 000000000..8ba8dbaa2
--- /dev/null
+++ b/provider/spec/schema/event.json
@@ -0,0 +1,97 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://harness.autonomous.ai/api/provider/schema/event.json",
+ "title": "A provider event",
+ "description": "One flat, self-describing object. The SAME shape is used in two places: each `data:` frame of an `agent.send` stream, and each entry of `agent.history.events`. That is deliberate — one schema pins both, so a replayed transcript and the live view cannot disagree about the same event. An event MUST be readable without the events before it. A provider that emits no `kind` at all is conformant: `{\"text\": \"…\"}` renders as plain assistant output. Clients ignore an unrecognised `kind` rather than failing.",
+ "type": "object",
+ "properties": {
+ "kind": {
+ "description": "Absent means plain assistant text. Unrecognised values are ignored, not rejected.",
+ "enum": [
+ "turn_started",
+ "user_message",
+ "thinking_title",
+ "thinking_delta",
+ "text_delta",
+ "tool_start",
+ "tool_end",
+ "context_compact",
+ "done",
+ "recap_start",
+ "recap_end",
+ "turn_completed",
+ "turn_failed",
+ "turn_cancelled",
+ "turn_input_required"
+ ]
+ },
+ "text": {
+ "type": "string",
+ "description": "The event's text. Its meaning follows `kind`: assistant output for text_delta, reasoning for thinking_delta, the final result for done, the recap body for recap_end. With no `kind` at all it is plain assistant output."
+ },
+ "turnId": { "type": "string", "description": "On turn_started, echoing the client-minted id." },
+ "agentId": { "type": "string", "description": "On turn_started." },
+ "at": { "type": "string", "format": "date-time", "description": "ISO-8601 UTC. Omit rather than invent one." },
+ "title": { "type": "string", "description": "thinking_title: the label for a reasoning block. `text` is accepted as a fallback." },
+ "thinkingId": { "type": "string", "description": "Groups thinking_delta chunks with their thinking_title." },
+ "toolId": {
+ "type": "string",
+ "description": "REQUIRED on tool_start and tool_end, and unique within the turn. Tools can overlap, so pairing by position is not available; an event without one is dropped, because an unpaired call renders as a row that never resolves."
+ },
+ "tool": { "type": "string", "description": "The tool's display name." },
+ "input": { "description": "tool_start: whatever the tool was called with. Any JSON." },
+ "ok": {
+ "type": "boolean",
+ "description": "tool_end: false marks failure. ABSENT is not failure — it is the provider not saying."
+ },
+ "output": { "type": "string", "description": "tool_end: the tool's output. `text` is accepted as a fallback." },
+ "summary": { "type": "string", "description": "tool_end: a one-line description of what the tool did." },
+ "durationSeconds": { "type": "number", "minimum": 0, "description": "tool_end. Omit rather than fabricate." },
+ "recap": {
+ "type": "string",
+ "maxLength": 200,
+ "description": "recap_end: the headline. ABSENT means no recap was produced — a turn that said nothing, or a summariser that failed — and the client then clears its indicator and paints nothing."
+ },
+ "prompt": {
+ "type": "string",
+ "description": "REQUIRED on turn_input_required: what to ask the user. The answer arrives as a resumed agent.send on the same turnId."
+ },
+ "error": { "$ref": "#/$defs/error", "description": "On turn_failed." }
+ },
+ "allOf": [
+ {
+ "if": { "properties": { "kind": { "const": "tool_start" } }, "required": ["kind"] },
+ "then": { "required": ["toolId"] }
+ },
+ {
+ "if": { "properties": { "kind": { "const": "tool_end" } }, "required": ["kind"] },
+ "then": { "required": ["toolId"] }
+ },
+ {
+ "if": { "properties": { "kind": { "const": "turn_input_required" } }, "required": ["kind"] },
+ "then": { "required": ["prompt"] }
+ },
+ {
+ "if": { "properties": { "kind": { "const": "done" } }, "required": ["kind"] },
+ "then": { "required": ["text"] }
+ }
+ ],
+ "$defs": {
+ "error": {
+ "type": "object",
+ "required": ["code"],
+ "properties": {
+ "code": { "$ref": "#/$defs/errorCode" },
+ "message": { "type": "string" }
+ }
+ },
+ "errorCode": {
+ "description": "Codes are STRINGS. `unauthenticated` is its own code because 'your credential is wrong' and 'the provider is down' need different words in front of the user, and once collapsed the distinction cannot be recovered.",
+ "enum": ["unauthenticated", "not_found", "unsupported", "invalid_request", "rate_limited", "internal"]
+ },
+ "terminalKinds": {
+ "description": "Exactly ONE of these ends every stream. Not referenced by validation — a single event cannot express a whole-stream rule — but named here so implementers and the conformance runner share one list.",
+ "enum": ["turn_completed", "turn_failed", "turn_cancelled", "turn_input_required"]
+ }
+ }
+}
diff --git a/provider/spec/schema/ext-context-history.json b/provider/spec/schema/ext-context-history.json
deleted file mode 100644
index 9c1a450b4..000000000
--- a/provider/spec/schema/ext-context-history.json
+++ /dev/null
@@ -1,81 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "$id": "https://harness.autonomous.ai/api/a2a/ext/context-history",
- "title": "Extension: context-history",
- "description": "A whole conversation's transcript, in one call and optionally windowed (HP-304). `GetTask` returns one TURN; a client opening a chat wants the CONTEXT, which is many turns, and for a long one it wants only the newest slice. Without this extension a client must fall back to HP-201/HP-202 and pull every turn separately at full size. Each $defs entry carries its own examples.",
- "type": "object",
- "$defs": {
- "historyRequest": {
- "type": "object",
- "required": ["contextId"],
- "properties": {
- "contextId": {
- "type": "string",
- "description": "The A2A context — the id the CLIENT minted, never the provider's own internal session id."
- },
- "limit": {
- "type": "integer",
- "minimum": 1,
- "maximum": 500,
- "description": "Window size. ABSENT means the complete transcript, and the provider then MUST omit hasMore/oldestCursor/staleCursor entirely — that absence is what tells the client this response is not windowed. A window may come back LONGER than `limit`: see oldestCursor."
- },
- "before": {
- "type": "string",
- "description": "A `messageId` — the oldest message the client already holds, taken from a previous response's `oldestCursor`. The window returned ends immediately BEFORE it (exclusive), so pages never overlap. Paging is backwards-only; there is no `after` (live turns arrive on the stream instead). Honoured only together with `limit`."
- }
- },
- "examples": [
- { "contextId": "ctx-91af", "limit": 60 },
- { "contextId": "ctx-91af", "limit": 60, "before": "b3f2c1d0-5a44-4e1b-9c77-2f0a1e6d8b31" },
- { "contextId": "ctx-91af" }
- ]
- },
- "historyResponse": {
- "type": "object",
- "required": ["contextId", "messages"],
- "properties": {
- "contextId": { "type": "string" },
- "messages": {
- "type": "array",
- "description": "Standard A2A Messages, ALWAYS oldest-first, so a client prepends a page exactly as received. An empty array is a legitimate answer for a context that has not spoken yet.",
- "items": { "type": "object" }
- },
- "hasMore": {
- "type": "boolean",
- "description": "Older messages exist before this window. Omitted when the request carried no `limit`."
- },
- "oldestCursor": {
- "type": ["string", "null"],
- "description": "The `messageId` of the window's FIRST message — pass it back as `before` to page older. Null when nothing older remains. Because the window start is snapped back to a real turn boundary (so a window never splits a tool call from its result), the returned window MAY contain more messages than `limit` asked for; `limit` is a floor, not an exact count."
- },
- "staleCursor": {
- "type": "boolean",
- "description": "The `before` cursor is no longer in the transcript — typically a compaction moved it out from under the client. The provider MUST then answer with empty `messages`, `hasMore: false` and `oldestCursor: null` rather than an error, and the client reloads the context from the newest page. Omitted when false."
- },
- "truncated": {
- "type": "boolean",
- "description": "Content was dropped to stay under the HP-203 size ceiling. Silent truncation is a violation (HP-203), so this MUST be set whenever anything was cut."
- }
- },
- "examples": [
- {
- "contextId": "ctx-91af",
- "messages": [
- { "role": "ROLE_USER", "messageId": "b3f2c1d0-5a44-4e1b-9c77-2f0a1e6d8b31", "parts": [{ "text": "How is Acme pacing?" }] },
- { "role": "ROLE_AGENT", "messageId": "7c1e9a22-08d3-4f5a-bb90-1d6e4c2f7a55", "parts": [{ "text": "Acme is at 118% of pacing.", "metadata": { "autonomous.ai/kind": "text_delta" } }] }
- ],
- "hasMore": true,
- "oldestCursor": "b3f2c1d0-5a44-4e1b-9c77-2f0a1e6d8b31"
- },
- {
- "contextId": "ctx-91af",
- "messages": [],
- "hasMore": false,
- "oldestCursor": null,
- "staleCursor": true
- },
- { "contextId": "ctx-91af", "messages": [] }
- ]
- }
- }
-}
diff --git a/provider/spec/schema/ext-session-recap.json b/provider/spec/schema/ext-session-recap.json
deleted file mode 100644
index fe46b2271..000000000
--- a/provider/spec/schema/ext-session-recap.json
+++ /dev/null
@@ -1,68 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "$id": "https://harness.autonomous.ai/api/a2a/ext/session-recap",
- "title": "Extension: session-recap",
- "description": "Short persisted per-turn summaries for an agent. The Harness device restores its tiles from these after a reboot; without the extension the device shows nothing rather than stale text (HP-302). Each $defs entry carries its own examples.",
- "type": "object",
- "$defs": {
- "recapRequest": {
- "type": "object",
- "required": ["agentId"],
- "properties": {
- "agentId": { "type": "string" },
- "n": {
- "type": "integer",
- "minimum": 1,
- "maximum": 5,
- "default": 2,
- "description": "How many recent turns to return, most recent first."
- }
- },
- "examples": [
- { "agentId": "acme-reporting", "n": 2 },
- { "agentId": "acme-reporting" }
- ]
- },
- "recapEntry": {
- "type": "object",
- "required": ["recap"],
- "properties": {
- "recap": {
- "type": "string",
- "maxLength": 200,
- "description": "Headline-style summary of what the turn accomplished. Kept short because it renders on a small round display readable across a room."
- },
- "body": { "type": "string", "maxLength": 2000 },
- "contextId": { "type": "string" },
- "taskId": { "type": "string" },
- "timestamp": { "type": "string", "format": "date-time" }
- },
- "examples": [
- { "recap": "Flagged Acme overspend at 118% of pacing", "contextId": "ctx-91af", "timestamp": "2026-08-03T09:14:00Z" },
- { "recap": "Built weekly budget alert query" }
- ]
- },
- "recapResponse": {
- "type": "object",
- "required": ["agentId", "entries"],
- "properties": {
- "agentId": { "type": "string" },
- "entries": {
- "type": "array",
- "items": { "$ref": "#/$defs/recapEntry" },
- "description": "Empty until at least one turn has been summarised. An empty array is correct; fabricated or full-text entries are not."
- }
- },
- "examples": [
- {
- "agentId": "acme-reporting",
- "entries": [
- { "recap": "Flagged Acme overspend at 118% of pacing", "contextId": "ctx-91af", "timestamp": "2026-08-03T09:14:00Z" },
- { "recap": "Built weekly budget alert query", "contextId": "ctx-77bc" }
- ]
- },
- { "agentId": "acme-reporting", "entries": [] }
- ]
- }
- }
-}
diff --git a/provider/spec/schema/ext-voice.json b/provider/spec/schema/ext-voice.json
deleted file mode 100644
index b20e4d533..000000000
--- a/provider/spec/schema/ext-voice.json
+++ /dev/null
@@ -1,45 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "$id": "https://harness.autonomous.ai/api/a2a/ext/voice",
- "title": "Extension: voice",
- "description": "Provider-side routing of a transcribed spoken task to one of its agents. RARELY NEEDED (HP-303): Autonomous routes from AgentCard skills[] names and descriptions by default. Declare this only to override that routing with provider-side knowledge the card cannot express. Each $defs entry carries its own examples.",
- "type": "object",
- "$defs": {
- "routeRequest": {
- "type": "object",
- "required": ["transcript"],
- "properties": {
- "transcript": {
- "type": "string",
- "minLength": 1,
- "description": "What the user said, already transcribed by Autonomous."
- },
- "candidateAgentIds": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Optional shortlist. When present the provider MUST choose from it or decline."
- }
- },
- "examples": [
- { "transcript": "check whether acme blew through budget this week" },
- { "transcript": "pull the weekly numbers", "candidateAgentIds": ["acme-reporting", "globex-reporting"] }
- ]
- },
- "routeResponse": {
- "type": "object",
- "required": ["agentId"],
- "properties": {
- "agentId": {
- "type": ["string", "null"],
- "description": "The chosen agent, or null to decline and let Autonomous fall back to its own routing."
- },
- "confidence": { "type": "number", "minimum": 0, "maximum": 1 },
- "reason": { "type": "string", "maxLength": 500 }
- },
- "examples": [
- { "agentId": "acme-reporting", "confidence": 0.86, "reason": "Names the Acme account and asks about pacing." },
- { "agentId": null, "reason": "No agent clearly matches." }
- ]
- }
- }
-}
diff --git a/provider/spec/schema/ext-workspace-files.json b/provider/spec/schema/ext-workspace-files.json
deleted file mode 100644
index 6b406c320..000000000
--- a/provider/spec/schema/ext-workspace-files.json
+++ /dev/null
@@ -1,77 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "$id": "https://harness.autonomous.ai/api/a2a/ext/workspace-files",
- "title": "Extension: workspace-files",
- "description": "Read-only file browsing for an agent. Declared in AgentCard.extensions (HP-300). Absent means the client hides the file browser entirely. Each $defs entry carries its own examples so they validate against the shape they illustrate, not against a permissive root.",
- "type": "object",
- "$defs": {
- "fileNode": {
- "type": "object",
- "required": ["name", "type"],
- "properties": {
- "name": { "type": "string" },
- "type": { "enum": ["file", "dir"] },
- "size": { "type": "integer", "minimum": 0 },
- "children": {
- "type": "array",
- "items": { "$ref": "#/$defs/fileNode" },
- "description": "Present on directories. A provider MAY return a shallow tree and populate children lazily on a subsequent listFiles call scoped to a path."
- }
- },
- "examples": [
- { "name": "README.md", "type": "file", "size": 240 },
- { "name": "reports", "type": "dir", "children": [{ "name": "weekly.sql", "type": "file", "size": 812 }] }
- ]
- },
- "listFilesRequest": {
- "type": "object",
- "required": ["agentId"],
- "properties": {
- "agentId": { "type": "string" },
- "path": { "type": "string", "description": "Omit for the agent root." }
- },
- "examples": [
- { "agentId": "acme-reporting" },
- { "agentId": "acme-reporting", "path": "reports" }
- ]
- },
- "listFilesResponse": {
- "type": "object",
- "required": ["files"],
- "properties": {
- "files": { "type": "array", "items": { "$ref": "#/$defs/fileNode" } }
- },
- "examples": [
- {
- "files": [
- { "name": "reports", "type": "dir", "children": [{ "name": "weekly.sql", "type": "file", "size": 812 }] },
- { "name": "README.md", "type": "file", "size": 240 }
- ]
- },
- { "files": [] }
- ]
- },
- "readFileRequest": {
- "type": "object",
- "required": ["agentId", "path"],
- "properties": {
- "agentId": { "type": "string" },
- "path": { "type": "string" }
- },
- "examples": [{ "agentId": "acme-reporting", "path": "README.md" }]
- },
- "readFileResponse": {
- "type": "object",
- "required": ["path", "content"],
- "properties": {
- "path": { "type": "string" },
- "content": { "type": "string", "description": "UTF-8 text. Binary files SHOULD be refused rather than returned base64 in this revision." },
- "truncated": { "type": "boolean", "description": "Set when the provider capped the response. Silent truncation is a violation (mirrors HP-203)." }
- },
- "examples": [
- { "path": "README.md", "content": "# Acme reporting\n" },
- { "path": "reports/weekly.sql", "content": "SELECT 1", "truncated": true }
- ]
- }
- }
-}
diff --git a/provider/spec/schema/ext-workspace-write.json b/provider/spec/schema/ext-workspace-write.json
deleted file mode 100644
index 0c6433318..000000000
--- a/provider/spec/schema/ext-workspace-write.json
+++ /dev/null
@@ -1,74 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "$id": "https://harness.autonomous.ai/api/a2a/ext/workspace-write",
- "title": "Extension: workspace-write",
- "description": "Create, rename and delete agents and sessions. Declared in AgentCard.extensions with params.agents / params.sessions indicating which halves are supported (HP-301). A provider MUST enforce that every operation stays inside the tenant identified by the credential. Each $defs entry carries its own examples.",
- "type": "object",
- "$defs": {
- "agentCreateRequest": {
- "type": "object",
- "required": ["name"],
- "properties": {
- "name": { "type": "string", "minLength": 1, "maxLength": 200 },
- "description": { "type": "string", "maxLength": 2000 }
- },
- "examples": [
- { "name": "Acme weekly reporting", "description": "Budget pacing alerts" },
- { "name": "Globex Q3" }
- ]
- },
- "agentRenameRequest": {
- "type": "object",
- "required": ["agentId", "name"],
- "properties": {
- "agentId": { "type": "string" },
- "name": { "type": "string", "minLength": 1, "maxLength": 200 }
- },
- "examples": [{ "agentId": "acme-reporting", "name": "Acme reporting (2026)" }]
- },
- "agentDeleteRequest": {
- "type": "object",
- "required": ["agentId"],
- "properties": { "agentId": { "type": "string" } },
- "examples": [{ "agentId": "acme-reporting" }]
- },
- "agentResponse": {
- "type": "object",
- "required": ["id", "name"],
- "properties": {
- "id": { "type": "string" },
- "name": { "type": "string" },
- "description": { "type": "string" }
- },
- "description": "The remaining client-side agent fields (userId, status, timestamps) are synthesised by the Autonomous backend — see §10.3 of the spec. A provider MUST NOT invent them, and MUST NOT report an `engine`.",
- "examples": [
- { "id": "acme-reporting", "name": "Acme weekly reporting" },
- { "id": "globex-q3", "name": "Globex Q3", "description": "Quarterly rollup" }
- ]
- },
- "sessionUpdateTitleRequest": {
- "type": "object",
- "required": ["contextId", "title"],
- "properties": {
- "contextId": { "type": "string" },
- "title": { "type": "string", "minLength": 1, "maxLength": 500 }
- },
- "examples": [{ "contextId": "ctx-91af", "title": "Budget overrun investigation" }]
- },
- "sessionDeleteRequest": {
- "type": "object",
- "required": ["contextId"],
- "properties": { "contextId": { "type": "string" } },
- "examples": [{ "contextId": "ctx-91af" }]
- },
- "ackResponse": {
- "type": "object",
- "required": ["ok"],
- "properties": {
- "ok": { "type": "boolean" },
- "message": { "type": "string" }
- },
- "examples": [{ "ok": true }, { "ok": false, "message": "Agent not found" }]
- }
- }
-}
diff --git a/provider/spec/schema/part-metadata.json b/provider/spec/schema/part-metadata.json
deleted file mode 100644
index 200f12519..000000000
--- a/provider/spec/schema/part-metadata.json
+++ /dev/null
@@ -1,127 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "$id": "https://harness.autonomous.ai/api/a2a/schema/part-metadata.json",
- "title": "autonomous.ai/* metadata on an A2A Part",
- "description": "Optional enrichment carried on the `metadata` object of a standard A2A Part. A provider that emits none of this is conformant — its output renders as plain assistant text (HP-211). Unknown autonomous.ai/* keys MUST be ignored, not rejected (HP-210).",
- "type": "object",
- "properties": {
- "autonomous.ai/kind": {
- "enum": [
- "user_message",
- "thinking_delta",
- "thinking_title",
- "text_delta",
- "tool_start",
- "tool_end",
- "context_compact",
- "done",
- "recap_start",
- "recap_end"
- ]
- },
- "autonomous.ai/thinkingId": {
- "type": "string",
- "description": "Groups thinking_delta chunks and their thinking_title."
- },
- "autonomous.ai/toolCallId": {
- "type": "string",
- "description": "Correlates a tool_start with its tool_end."
- },
- "autonomous.ai/parentToolCallId": {
- "type": "string",
- "description": "Set when this part belongs to a nested/sub-agent call, so the client can render a tree."
- },
- "autonomous.ai/tool": {
- "type": "string",
- "description": "Tool name, for tool_start and tool_end."
- },
- "autonomous.ai/toolInput": {
- "description": "Arbitrary JSON arguments for tool_start."
- },
- "autonomous.ai/isError": {
- "type": "boolean",
- "description": "tool_end only: the tool call failed."
- },
- "autonomous.ai/summary": {
- "type": "string",
- "description": "tool_end only: one-line human summary of the result."
- },
- "autonomous.ai/durationSeconds": {
- "type": "number",
- "minimum": 0,
- "description": "tool_end only."
- },
- "autonomous.ai/title": {
- "type": "string",
- "description": "thinking_title only."
- },
- "autonomous.ai/recap": {
- "type": "string",
- "maxLength": 200,
- "description": "recap_end only (HP-212): the headline of what the turn ACCOMPLISHED, rendered on one line of a small round display. The fuller body travels as the Part's own text. Same 200-character ceiling as recapEntry.recap in ext-session-recap.json — the two carry the same value by different routes. ABSENT on a recap_end means the turn produced no recap: the phase is over and the client clears its indicator without painting a card."
- },
- "autonomous.ai/compacted": {
- "type": "object",
- "description": "context_compact only. All counts optional — omit rather than guess (HP-220). The human-readable explanation travels as the Part's own text.",
- "properties": {
- "userMessages": { "type": "integer", "minimum": 0 },
- "assistantMessages": { "type": "integer", "minimum": 0 },
- "toolUses": { "type": "integer", "minimum": 0 },
- "contexts": { "type": "integer", "minimum": 0 }
- }
- }
- },
- "allOf": [
- {
- "if": {
- "properties": { "autonomous.ai/kind": { "const": "tool_start" } },
- "required": ["autonomous.ai/kind"]
- },
- "then": { "required": ["autonomous.ai/toolCallId", "autonomous.ai/tool"] }
- },
- {
- "if": {
- "properties": { "autonomous.ai/kind": { "const": "tool_end" } },
- "required": ["autonomous.ai/kind"]
- },
- "then": { "required": ["autonomous.ai/toolCallId", "autonomous.ai/tool"] }
- },
- {
- "if": {
- "properties": { "autonomous.ai/kind": { "const": "thinking_title" } },
- "required": ["autonomous.ai/kind"]
- },
- "then": { "required": ["autonomous.ai/title"] }
- }
- ],
- "examples": [
- { "autonomous.ai/kind": "text_delta" },
- { "autonomous.ai/kind": "thinking_delta", "autonomous.ai/thinkingId": "t1" },
- { "autonomous.ai/kind": "thinking_title", "autonomous.ai/thinkingId": "t1", "autonomous.ai/title": "Checking the budget data" },
- {
- "autonomous.ai/kind": "tool_start",
- "autonomous.ai/toolCallId": "c7",
- "autonomous.ai/tool": "query_spend",
- "autonomous.ai/toolInput": { "account": "acme", "window": "7d" }
- },
- {
- "autonomous.ai/kind": "tool_end",
- "autonomous.ai/toolCallId": "c7",
- "autonomous.ai/tool": "query_spend",
- "autonomous.ai/isError": false,
- "autonomous.ai/summary": "Returned 7 rows",
- "autonomous.ai/durationSeconds": 1.4
- },
- { "autonomous.ai/kind": "done" },
- { "autonomous.ai/kind": "recap_start" },
- { "autonomous.ai/kind": "recap_end", "autonomous.ai/recap": "Flagged Acme overspend at 118% of pacing" },
- { "autonomous.ai/kind": "recap_end" },
- {
- "autonomous.ai/kind": "context_compact",
- "autonomous.ai/compacted": { "userMessages": 12, "assistantMessages": 12, "toolUses": 41 }
- },
- { "autonomous.ai/kind": "context_compact" },
- { "autonomous.ai/kind": "user_message" },
- {}
- ]
-}