@spunto/build 0.30.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -185,27 +185,32 @@ The JSON Schema is shipped as `@spunto/build/agent-contract/schema.json`, genera
185
185
  table the reader validates with. The conformance suite drives a runner like the platform does and
186
186
  checks every line and the order of events (simple turn, tool, interrupt, resume, limit, title,
187
187
  files). `@spunto/build/agent-contract/fake-agent.mjs` is a whole runner in 46 lines with no SDK
188
- that passes it. The Claude and Codex runners (`./agent-runners`) carry their adapters next to them
189
- and are meant to be **bundled** (esbuild, `platform: node`, `format: esm`) before being run.
188
+ that passes it.
190
189
 
191
- ### `@spunto/build/agent-stream` — reading an agent session as it happens
190
+ The runner's side of the seam is here too, and nothing harness-specific with it: the shell that
191
+ starts a runner (`runnerCommand`, `AGENT_NODE` under `AGENT_HOME`), the variables a runner is
192
+ handed (`RUNNER_ENV`, `OPTIONS_ENV`, `STREAM_ENV`, `MCP_ENV`), and the shape of what an app lets a
193
+ task choose (`AgentCatalog`, checked by `agentOptionsError`).
194
+
195
+ **No harness lives in this package** (since 0.32.0). Spunto's own runners — Claude Code, Codex,
196
+ Mistral Vibe, with their adapters, the install scripts of their SDKs and their catalogs of models —
197
+ are [`@spunto/agent-runners`](../agent-runners/README.md), imported by the apps that *are* those
198
+ harnesses and never by a control plane.
192
199
 
193
- Since the contract (`agent-v1`), what is left here is the writing side of a session and the
194
- **legacy dialects** — the CLI's `claude-stream`, the runners' former `claude-runner` /
195
- `codex-runner` — for sessions that began on them.
200
+ ### `@spunto/build/agent-stream` — reading an agent session as it happens
196
201
 
197
- One adapter per harness dialect, one vocabulary out. A CLI's JSON output is an output format, not
198
- an API; adapters normalise into a small set of event types so stored history doesn't date the first
199
- time a vendor reshuffles a field.
202
+ The platform's side of a session that speaks the contract (`agent-v1`): how to write a turn, an
203
+ interrupt or a title request to it, how to read its stdout into stored events (`parseLines`, which
204
+ keeps each event's `source`), and how to sum what it consumed (`summarizeUsage`). Nothing here knows
205
+ which harness is on the other end: every harness's own output is read by its runner, in the machine.
200
206
 
201
- Here for the reason that inverts the rest of the package: **nothing has forked this yet.** Putting
202
- it in the shared package now costs nothing and means the second product never writes its own.
207
+ Tokens of a message still being written (`message.delta`) are **not** events: `foldDraft(protocol,
208
+ lines, previous)` folds them into the one transient text block in flight — closed by the finished
209
+ message, never stored. Where the draft lives between two reads is the caller's business.
203
210
 
204
- Tokens of a message still being written (Claude's `stream_event` lines, from
205
- `includePartialMessages`) are **not** events: `parseStreamLine` reads them as nothing, and
206
- `foldDraft(protocol, lines, previous)` folds them into the one transient text block in flight —
207
- closed by the finished message, never stored. Where the draft lives between two reads is the
208
- caller's business.
211
+ The harnesses' own dialects (Claude Code's `stream-json`, the runners' former `claude-runner` /
212
+ `codex-runner`) were read here until 0.31.0; they are gone, with `applyProtocol`, the title probe of
213
+ Claude's transcript and `PROJECT_AGENT_PROTOCOLS`.
209
214
 
210
215
  ### `@spunto/build/terminal` — the half of a persistent terminal that is a string
211
216
 
@@ -303,8 +308,7 @@ imports them.
303
308
 
304
309
  Concretely: **no platform I/O**. No database, no Docker socket, no WebSocket. This package produces
305
310
  strings and parses strings. Its only network calls are outbound HTTP on the caller's behalf — a
306
- public extension registry, and a model vendor's catalogue endpoint when you hand
307
- `resolveContextWindow` a credential — and it holds no credential of its own. Configuration arrives
311
+ public extension registry — and it holds no credential of its own. Configuration arrives
308
312
  as function parameters, never read from the environment, so that one control plane can scope a
309
313
  setting per organization and another per process without either shape leaking in here.
310
314
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spunto/build",
3
- "version": "0.30.0",
3
+ "version": "0.32.0",
4
4
  "description": "Spunto's shared Build engine — the devcontainer image protocol and VS Code extension registry clients, with no database, no HTTP framework and no UI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -87,14 +87,7 @@
87
87
  },
88
88
  "./sandbox-agent/agent.mjs": "./src/sandbox-agent/agent.mjs",
89
89
  "./sandbox-agent/bootstrap.sh": "./src/sandbox-agent/bootstrap.sh",
90
- "./sandbox-agent/runner.sh": "./src/sandbox-agent/runner.sh",
91
- "./agent-runners": {
92
- "types": "./src/agent-runners/index.ts",
93
- "import": "./src/agent-runners/index.ts"
94
- },
95
- "./agent-runners/claude.mjs": "./src/agent-runners/claude.mjs",
96
- "./agent-runners/codex.mjs": "./src/agent-runners/codex.mjs",
97
- "./agent-runners/mistral.mjs": "./src/agent-runners/mistral.mjs"
90
+ "./sandbox-agent/runner.sh": "./src/sandbox-agent/runner.sh"
98
91
  },
99
92
  "files": [
100
93
  "src",
@@ -5,6 +5,7 @@
5
5
  export {
6
6
  AGENT_CONTRACT_VERSION,
7
7
  agentContractSchema,
8
+ cleanTitle,
8
9
  clip,
9
10
  contractLineProblem,
10
11
  isTransient,
@@ -14,8 +15,13 @@ export {
14
15
  SUBAGENT_STATUSES,
15
16
  TASK_EVENT_TYPES,
16
17
  TRANSIENT_TYPES,
18
+ TURN_LIMIT_KINDS,
17
19
  } from "./vocabulary"
18
- export type { NormalizedEvent, RunnerInput, SourcedEvent, TaskEventType, TransientType } from "./vocabulary"
20
+ export type { NormalizedEvent, RunnerInput, SourcedEvent, TaskEventType, TransientType, TurnLimit, TurnLimitKind } from "./vocabulary"
21
+
22
+ // The runner's side of it: how the platform starts one, what reaches it, what an app lets a task choose.
23
+ export { AGENT_HOME, AGENT_NODE, MCP_ENV, OPTIONS_ENV, RUNNER_ENV, STREAM_ENV, agentOptionsError, runnerCommand } from "./runner"
24
+ export type { AgentCatalog, AgentMcpServer, AgentModel, AgentParam, AgentParamValue } from "./runner"
19
25
 
20
26
  export { CONFORMANCE_PROMPTS, CONFORMANCE_SCENARIOS, runConformance } from "./conformance"
21
27
  export type { ConformanceOptions, ConformanceResult, ConformanceScenario, RunnerProcess, StartRunner } from "./conformance"
@@ -0,0 +1,124 @@
1
+ /**
2
+ * The runner contract (RFC 0048), seen from the platform: how a session of an agent app is started,
3
+ * what reaches it in its environment, and the shape of what an app lets a task choose. Every
4
+ * harness is the same here — which one it is, its SDK and its runner live with the app
5
+ * (`@spunto/agent-runners` for Spunto's own: Claude Code, Codex, Mistral Vibe), never in the
6
+ * platform.
7
+ *
8
+ * <node> <runner>.mjs run [--model <id>] [--resume <session id>]
9
+ * stdin one JSON object per line: {"type":"user","text"} · {"type":"interrupt","id"} ·
10
+ * {"type":"title","id","description"} (`RunnerInput`); closed ⇒ end after the turn
11
+ * env SPUNTO_AGENT_OPTIONS — the task's parameters, one JSON object
12
+ * stdout our vocabulary (`./vocabulary.ts`), one JSON object per line
13
+ * exit 0 = the input closed and the last turn ended; ≠ 0 = the session could not run, and its
14
+ * last line is a failed `session.ended` saying why
15
+ *
16
+ * Pure: what a caller gets is the shell that starts a runner. Fetching it and writing it into the
17
+ * machine are the caller's I/O.
18
+ */
19
+
20
+ /** Where an agent app's feature installs its harness — and the private Node its runner runs on. */
21
+ export const AGENT_HOME = "/opt/spunto/agents"
22
+
23
+ /** The Node every runner runs on — the private one the features install. */
24
+ export const AGENT_NODE = `${AGENT_HOME}/node/bin/node`
25
+
26
+ /** The variable a runner's text travels in, base64 — see `runnerCommand`. */
27
+ export const RUNNER_ENV = "SPUNTO_AGENT_RUNNER"
28
+
29
+ /** The variable a task's chosen parameters reach the runner in, as one JSON object. */
30
+ export const OPTIONS_ENV = "SPUNTO_AGENT_OPTIONS"
31
+
32
+ /**
33
+ * `"1"` when the session should stream the tokens of a message as they are written (partial
34
+ * messages, folded into the draft by `foldDraft`). Set by the platform behind the org flag
35
+ * `token-streaming`; absent, a runner prints finished messages only — the system before it.
36
+ */
37
+ export const STREAM_ENV = "SPUNTO_AGENT_STREAM"
38
+
39
+ /**
40
+ * The variable the org's MCP servers reach the runner in (RFC 0049): a JSON array of
41
+ * `{ name, path }`, `path` being the platform's gateway for that server, resolved by the runner
42
+ * against `SPUNTO_API_URL` and called with `SPUNTO_WORKER_TOKEN`. No vendor token, no harness shape.
43
+ */
44
+ export const MCP_ENV = "SPUNTO_AGENT_MCP"
45
+
46
+ export type AgentMcpServer = { name: string; path: string }
47
+
48
+ /**
49
+ * The shell that starts a session: write the runner out of `$SPUNTO_AGENT_RUNNER` (base64, set by
50
+ * the caller in the command's environment), then `exec` it on the feature's Node so the session
51
+ * *is* the runner — stdin, signals and exit code included.
52
+ *
53
+ * The text rides in the environment rather than in the command because the command is what the
54
+ * platform shows ("what the platform ran"): eight kilobytes of base64 there would bury the one line
55
+ * worth reading. `--model` is appended by the platform like for any harness; `resume` adds the
56
+ * session the platform read off the stream, passed as `$SPUNTO_TASK_SESSION_ID`.
57
+ *
58
+ * Only the app's id is needed (it names the file): the platform calls this for apps it learns of by
59
+ * their manifest (RFC 0057).
60
+ */
61
+ export function runnerCommand(harness: { id: string }, opts: { resume?: boolean } = {}): string {
62
+ const file = `"$HOME/.spunto/agents/${harness.id}.mjs"`
63
+ return [
64
+ `mkdir -p "$HOME/.spunto/agents" && printf %s "$${RUNNER_ENV}" | base64 -d > ${file} && unset ${RUNNER_ENV} &&`,
65
+ `exec ${AGENT_NODE} ${file} run${opts.resume ? ` --resume "$SPUNTO_TASK_SESSION_ID"` : ""}`,
66
+ ].join(" ")
67
+ }
68
+
69
+ // ── What an app lets a task choose ────────────────────────────────────────────
70
+ //
71
+ // Its models, and **its own parameters** — effort, reasoning, web search… The platform knows none
72
+ // of them by name: it shows what an app declares, checks a task's choice against it
73
+ // (`agentOptionsError`), and hands the choice to the runner (`OPTIONS_ENV`), the only code that
74
+ // knows what a parameter means to its SDK.
75
+
76
+ export type AgentParamValue = { value: string; label: string; description?: string }
77
+
78
+ /** A parameter an app defines. A choice among values — the one shape both SDKs need today. */
79
+ export type AgentParam = {
80
+ id: string
81
+ label: string
82
+ description?: string
83
+ values: AgentParamValue[]
84
+ }
85
+
86
+ export type AgentModel = {
87
+ value: string
88
+ label: string
89
+ description?: string
90
+ /** What the harness runs when no model is picked. */
91
+ default?: boolean
92
+ /** Values of a parameter this model allows, when it does not take all of them. */
93
+ params?: Record<string, string[]>
94
+ /** What this model runs with when the parameter is left unset — shown as the chip's placeholder. */
95
+ paramDefaults?: Record<string, string>
96
+ }
97
+
98
+ export type AgentCatalog = {
99
+ models: AgentModel[]
100
+ params: AgentParam[]
101
+ }
102
+
103
+
104
+ /**
105
+ * Why these options cannot run under this catalog and model — or null when they can. An unknown
106
+ * parameter, a value the parameter does not have, or one the model does not take. A model the
107
+ * catalog does not list (typed by hand) is held to the parameter's values only: the catalog cannot
108
+ * speak for it.
109
+ */
110
+ export function agentOptionsError(catalog: AgentCatalog, model: string | null | undefined, options: Record<string, string>): string | null {
111
+ const known = model ? catalog.models.find((m) => m.value === model) : undefined
112
+ for (const [id, value] of Object.entries(options)) {
113
+ const param = catalog.params.find((p) => p.id === id)
114
+ if (!param) return `Unknown parameter "${id}" — this harness takes ${catalog.params.map((p) => p.id).join(", ") || "none"}.`
115
+ if (!param.values.some((v) => v.value === value)) {
116
+ return `"${value}" is not a value of ${param.label} — one of ${param.values.map((v) => v.value).join(", ")}.`
117
+ }
118
+ const allowed = known?.params?.[id]
119
+ if (allowed && !allowed.includes(value)) {
120
+ return `${known!.label} does not take ${param.label} "${value}" — one of ${allowed.join(", ")}.`
121
+ }
122
+ }
123
+ return null
124
+ }
@@ -23,7 +23,35 @@
23
23
  * Pure: no I/O, no clock.
24
24
  */
25
25
 
26
- import { TURN_LIMIT_KINDS } from "../agent-stream/turn-limit"
26
+
27
+ /** One line, no runs of whitespace, bounded — a title goes in a list row and in a page header. */
28
+ export function cleanTitle(value: unknown): string | null {
29
+ if (typeof value !== "string") return null
30
+ const title = value.replace(/\s+/g, " ").trim().slice(0, MAX_TITLE).trim()
31
+ return title || null
32
+ }
33
+
34
+ /** Longest name we keep. The column allows 200; a harness that writes an essay gets cut. */
35
+ const MAX_TITLE = 200
36
+
37
+ /**
38
+ * Why a turn ended on a limit rather than on finished work: `usage` (the plan's quota, back at a
39
+ * time the harness usually knows), `rate` (a burst limit, seconds to minutes), `overloaded` (the
40
+ * vendor's API, later). Which harness message is which is the runner's reading
41
+ * (`claude/turn-limit.ts` of `@spunto/agent-runners` for Claude).
42
+ */
43
+ export const TURN_LIMIT_KINDS = ["usage", "rate", "overloaded"] as const
44
+ export type TurnLimitKind = (typeof TURN_LIMIT_KINDS)[number]
45
+
46
+ export type TurnLimit = {
47
+ kind: TurnLimitKind
48
+ /** The HTTP status the harness reported, when it did (429, 529). */
49
+ status: number | null
50
+ /** What the harness said, as it said it — shown to a human, never parsed again. */
51
+ message: string
52
+ /** When the limit lifts, ISO 8601, when the runner could tell. */
53
+ resetsAt: string | null
54
+ }
27
55
 
28
56
  /** Bumped only for a change an existing runner would not survive. Additive changes keep it. */
29
57
  export const AGENT_CONTRACT_VERSION = 1
@@ -133,7 +161,7 @@ function describe(schema: Record<string, unknown>): string {
133
161
  return typeof schema.type === "string" ? `a ${schema.type}` : "valid"
134
162
  }
135
163
 
136
- /** `limit` — the turn ended because the account ran out, not the work (`../agent-stream/turn-limit.ts`). */
164
+ /** `limit` — the turn ended because the account ran out, not the work (`TURN_LIMIT_KINDS`). */
137
165
  const LIMIT = object({
138
166
  kind: req(oneOf(TURN_LIMIT_KINDS)),
139
167
  status: nullable(num()),
@@ -1,40 +1,28 @@
1
1
  /**
2
2
  * Reading an agent session as it happens (RFC 0020, phase 1).
3
3
  *
4
- * Since RFC 0048 § 9 a session started under an agent app speaks **our** contract (`agent-v1`, read
5
- * by `../agent-contract`): the runner normalised its harness's output before it left the machine,
6
- * and nothing here knows which harness it was. What remains in this file is everything around that
7
- * reader — how to write to a session, how to sum what it consumed — and the **legacy dialects**:
8
- * the harnesses' own shapes, normalised here, for the sessions that started on them (the CLI of a
9
- * task delegated before agent apps, a runner's previous dialect) and for spunto-lite.
4
+ * Since RFC 0048 § 9 a session speaks **our** contract (`agent-v1`, read by `../agent-contract`):
5
+ * the runner of its agent app normalised its harness's output before it left the machine, and
6
+ * nothing here knows which harness it was. What this file adds around that reader is how to write
7
+ * to a session and how to sum what it consumed.
8
+ *
9
+ * The harnesses' own dialects (Claude Code's `stream-json`, Codex's events) used to be read here
10
+ * too, for the tasks delegated before agent apps and the runners' first sessions. Retired on
11
+ * 2026-11-24, once no task alive spoke them: what a harness prints is its runner's business, in the
12
+ * machine (`@spunto/agent-runners` for Spunto's own apps), never the platform's.
10
13
  *
11
14
  * Two rules the rest of the code depends on:
12
15
  *
13
- * 1. **Our vocabulary is the stored one.** A harness's JSON shape is an output format, not an
14
- * API; storing it would date the history. Adapters translate into the small set below, and
15
- * anything unmapped becomes `raw` rather than being dropped — same escape hatch as
16
- * `tasks.meta`, which has already earned its keep twice.
17
- * 2. **A malformed line is never fatal.** This parses the output of a third-party CLI on a read
18
- * path. Garbage in a line costs that line, not the task.
16
+ * 1. **Our vocabulary is the stored one.** Anything the reader cannot place becomes `raw` rather
17
+ * than being dropped.
18
+ * 2. **A malformed line is never fatal.** Garbage in a line costs that line, not the task.
19
19
  *
20
20
  * Pure functions only: no database, no worker, no clock beyond what a caller passes in. The
21
21
  * ingestion loop lives in task-events.service.ts.
22
22
  */
23
23
 
24
- import {
25
- clip,
26
- readContractLine,
27
- TASK_EVENT_TYPES,
28
- type NormalizedEvent,
29
- type TaskEventType,
30
- type RunnerInput,
31
- type SourcedEvent,
32
- } from "../agent-contract/vocabulary"
33
- import { adaptClaudeJson, cleanTitle, TITLE_REQUEST_PREFIX } from "../agent-runners/claude/adapter"
34
- import { adaptCodex } from "../agent-runners/codex/adapter"
35
- import { contextWindowOf } from "./model-window"
24
+ import { readContractLine, type NormalizedEvent, type RunnerInput, type SourcedEvent } from "../agent-contract/vocabulary"
36
25
 
37
- export { cleanTitle }
38
26
  export { TASK_EVENT_TYPES } from "../agent-contract/vocabulary"
39
27
  export type { NormalizedEvent, RunnerInput, SourcedEvent, TaskEventType } from "../agent-contract/vocabulary"
40
28
 
@@ -42,239 +30,58 @@ export type { NormalizedEvent, RunnerInput, SourcedEvent, TaskEventType } from "
42
30
  * How a session is read.
43
31
  *
44
32
  * - `agent-v1` — **the Spunto agent contract** (`../agent-contract`): what every agent app's runner
45
- * prints since the normalisation moved into the runner (RFC 0048 § 9). The one dialect a new
46
- * session speaks; read by one strict reader, with no adapter of anyone's.
47
- * - `claude-runner`, `codex-runner` — what those runners printed before: their harness's own
48
- * dialect, normalised here. Kept for the sessions that started on it, until they end.
49
- * - `claude-stream`, `claude-json`, `jsonl`, `none` — the CLI dialects of a task delegated before
50
- * agent apps (`LEGACY_CLI`), and what spunto-lite's `spunto.json` still names.
33
+ * prints (RFC 0048 § 9), read by one strict reader with no adapter of anyone's;
34
+ * - `none` — nothing to read: a task with no session, or one whose session began before the
35
+ * contract and has ended (its history is already stored, in our vocabulary).
51
36
  */
52
- export const AGENT_PROTOCOLS = ["none", "claude-json", "claude-stream", "jsonl", "claude-runner", "codex-runner", "agent-v1"] as const
37
+ export const AGENT_PROTOCOLS = ["none", "agent-v1"] as const
53
38
  export type AgentProtocol = (typeof AGENT_PROTOCOLS)[number]
54
39
 
55
- /**
56
- * What a **project** can be set to by hand (`projects.taskAgentProtocol`). The `*-runner` dialects
57
- * are not in it: they belong to an agent app (RFC 0048) and come with the app's runner, never with
58
- * a command someone typed.
59
- */
60
- export const PROJECT_AGENT_PROTOCOLS = ["none", "claude-json", "claude-stream", "jsonl"] as const
61
-
62
- /**
63
- * A runner of an agent app (RFC 0048, `../agent-runners`): our own process in the machine, driving a
64
- * harness through its official SDK. Its stdin speaks **our** contract (`RunnerInput`), whatever the
65
- * harness — and so does its stdout, since `agent-v1`.
66
- */
67
- export function isRunner(protocol: AgentProtocol): boolean {
68
- return protocol === "agent-v1" || protocol === "claude-runner" || protocol === "codex-runner"
69
- }
70
-
71
40
  function runnerLine(input: RunnerInput): string {
72
41
  return `${JSON.stringify(input)}\n`
73
42
  }
74
43
 
75
- /** Claude's dialect, whichever way it reaches us — the CLI's `stream-json` or the SDK's messages (the same shapes). */
76
- function speaksClaude(protocol: AgentProtocol): boolean {
77
- return protocol === "claude-json" || protocol === "claude-stream" || protocol === "claude-runner"
78
- }
79
-
80
- /**
81
- * The command actually run, given the project's harness and its protocol.
82
- *
83
- * The platform appends the flags rather than asking the project to, because getting them wrong is
84
- * silent: a missing `--verbose` makes Claude Code refuse `stream-json` outright, and a missing
85
- * `--output-format` produces prose that parses into nothing at all.
86
- *
87
- * Left alone when the command already names an output format — a project whose harness is a
88
- * pipeline, or who wants different flags, keeps full control by saying so.
89
- */
90
- export function applyProtocol(command: string, protocol: AgentProtocol): string {
91
- if (protocol !== "claude-json" && protocol !== "claude-stream") return command
92
- if (/--output-format/.test(command)) return command
93
- const flags = ["--output-format stream-json --verbose"]
94
- // Interactive mode. `--input-format stream-json` is what keeps the harness alive between
95
- // turns — it reads instructions as a stream instead of exiting after one prompt — which is the
96
- // precondition for both answering it mid-flight and interrupting it. Measured in a worker
97
- // before it was built: two turns, one session id, and an interrupt the process survives.
98
- if (protocol === "claude-stream") flags.push("--input-format stream-json")
99
- return `${command} ${flags.join(" ")}`
100
- }
101
-
102
44
  /** Does this protocol keep the harness alive, listening on stdin, between turns? */
103
45
  export function isInteractive(protocol: AgentProtocol): boolean {
104
- return protocol === "claude-stream" || isRunner(protocol)
46
+ return protocol === "agent-v1"
105
47
  }
106
48
 
107
49
  /**
108
- * One turn of the conversation, as the harness expects it on stdin.
50
+ * One turn of the conversation, as the runner expects it on stdin (`RunnerInput`).
109
51
  *
110
52
  * Newline-terminated and emitted as a single write: under PIPE_BUF that is atomic, which is what
111
53
  * stops two messages from interleaving into one unparseable line.
112
54
  */
113
55
  export function userTurnLine(protocol: AgentProtocol, text: string): string {
114
- if (isRunner(protocol)) return runnerLine({ type: "user", text })
115
- if (protocol !== "claude-stream") return `${text}\n`
116
- return `${JSON.stringify({ type: "user", message: { role: "user", content: [{ type: "text", text }] } })}\n`
56
+ if (protocol === "agent-v1") return runnerLine({ type: "user", text })
57
+ return `${text}\n`
117
58
  }
118
59
 
119
- /**
120
- * Stop what the harness is doing, without killing it.
121
- *
122
- * Measured: Claude Code answers a `control_request`/`interrupt` with a `control_response`
123
- * success, ends the turn with `result/error_during_execution`, and **stays alive** — so the next
124
- * message is a normal turn rather than a resume.
125
- */
60
+ /** Stop what the harness is doing, without killing it — or null for a session that cannot be told. */
126
61
  export function interruptLine(protocol: AgentProtocol, requestId: string): string | null {
127
- if (isRunner(protocol)) return runnerLine({ type: "interrupt", id: requestId })
128
- if (protocol !== "claude-stream") return null
129
- return `${JSON.stringify({ type: "control_request", request_id: requestId, request: { subtype: "interrupt" } })}\n`
62
+ if (protocol !== "agent-v1") return null
63
+ return runnerLine({ type: "interrupt", id: requestId })
130
64
  }
131
65
 
132
66
  /**
133
- * Ask the harness to **name the conversation**, or null for a dialect that cannot be asked.
134
- *
135
- * Claude Code used to do this on its own within seconds of the first turn, headless included —
136
- * that title is what `sessionTitleProbe` reads. Measured on 2.1.296 (October 2026), it no longer
137
- * does for a session driven over `--input-format stream-json`: the transcript gets `atis-latch`
138
- * and `last-prompt` lines and never an `ai-title`, so every task kept its placeholder. What it
139
- * still answers is the SDK's own `generate_session_title` control request — the call its
140
- * TypeScript SDK makes — with `{"title":…}` in a `control_response` on stdout, and `persist`
141
- * writes the same `ai-title` line to the transcript as before.
142
- *
143
- * Asking is not naming: the harness still picks the words, from the human's prompt (the
144
- * `description`), exactly as it would have unprompted. Nothing of ours ends up in the title.
145
- *
146
- * The request id carries `TITLE_REQUEST_PREFIX` so the answer can be told apart from every other
147
- * `control_response` (an interrupt's, say) without keeping state between write and read.
67
+ * Ask the session to **name the conversation**, or null when it cannot be asked. The runner
68
+ * answers — if its harness can name a conversation at all — with a `session.title` line; the
69
+ * harness picks the words, from the human's prompt (`description`), nothing of ours.
148
70
  */
149
71
  export function sessionTitleRequestLine(protocol: AgentProtocol, requestId: string, description: string): string | null {
150
- if (protocol !== "claude-stream" && protocol !== "claude-runner" && protocol !== "agent-v1") return null
72
+ if (protocol !== "agent-v1") return null
151
73
  const text = description.trim()
152
74
  if (!text) return null
153
- // A runner is asked with the contract's own verb, and answers — if its harness can name a
154
- // conversation at all — with a `session.title` line (`agent-v1`), or, on the old Claude runner,
155
- // with the very `control_response` the CLI would have printed.
156
- if (isRunner(protocol)) return runnerLine({ type: "title", id: `${TITLE_REQUEST_PREFIX}${requestId}`, description: text })
157
- return `${JSON.stringify({
158
- type: "control_request",
159
- request_id: `${TITLE_REQUEST_PREFIX}${requestId}`,
160
- request: { subtype: "generate_session_title", description: text, persist: true },
161
- })}\n`
162
- }
163
-
164
- /**
165
- * A shell that prints the line where the harness wrote **the name it gave the conversation**, or
166
- * null for a dialect that has no such thing.
167
- *
168
- * This exists because Claude Code names its own conversations — the title you see in the terminal
169
- * and in `/resume` — but does **not** put that name on stdout: measured in a worker, a
170
- * `--output-format stream-json` session emits `system/init`, `assistant`, `user` and `result`,
171
- * and nothing else. The name is written to the session transcript, as one
172
- * `{"type":"ai-title","aiTitle":…}` line per revision. So the only way to have it is to go and
173
- * read it, once, out of band — which is why this returns a *shell* rather than a parser: it runs
174
- * in the worker, where the transcript is.
175
- *
176
- * Deliberately not a `--name` handed to the harness (the flag exists): a task created without a
177
- * title has no name to impose, and imposing the prompt's first line would just be our own
178
- * placeholder read back to us.
179
- *
180
- * Found by file name rather than by rebuilding the per-directory path Claude Code derives from
181
- * the cwd: that encoding is an internal detail, `find` by session id is not. A harness run with
182
- * `--no-session-persistence` writes no transcript, and then this finds nothing — which is a
183
- * normal answer, not an error.
184
- *
185
- * Since Claude Code 2.1.296 an interactive session only writes that line once asked
186
- * (`sessionTitleRequestLine`); a one-shot `claude-json` run has no stdin to be asked on.
187
- *
188
- * `jsonl` gets no probe on purpose: a harness speaking our vocabulary says the name in band,
189
- * `{"type":"session.title","title":"…"}`, and pays nothing for it.
190
- */
191
- export function sessionTitleProbe(protocol: AgentProtocol, sessionId: string): string | null {
192
- if (!readsTitleOutOfBand(protocol)) return null
193
- // The id comes from the harness's own output, and it is about to be interpolated into a shell
194
- // run inside the worker. Nothing outside this alphabet has any business in a session id, and
195
- // refusing is cheaper than trusting a CLI's field to be what it was yesterday. It also means
196
- // the single quotes below are enough: the set excludes the quote itself.
197
- if (!/^[A-Za-z0-9._-]{1,128}$/.test(sessionId)) return null
198
- return [
199
- `root="\${CLAUDE_CONFIG_DIR:-$HOME/.claude}/projects"`,
200
- `f=$(find "$root" -name '${sessionId}.jsonl' -type f 2>/dev/null | head -1)`,
201
- `[ -n "$f" ] || exit 0`,
202
- // The last few candidates, not just the last one: the pattern is a substring match on a file
203
- // the agent itself can write into (a tool result quoting these very lines would match), so
204
- // the reader below takes the last line that is actually a title record.
205
- `grep -a '"type":"ai-title"' "$f" | tail -5`,
206
- ].join("\n")
75
+ return runnerLine({ type: "title", id: requestId, description: text })
207
76
  }
208
77
 
209
78
  /**
210
- * Does this dialect's name have to be fetched, rather than read off the stream? Asked *before* a
211
- * session id is looked up, so a harness that says its name in band pays nothing for the question.
212
- */
213
- export function readsTitleOutOfBand(protocol: AgentProtocol): boolean {
214
- return speaksClaude(protocol)
215
- }
216
-
217
- /**
218
- * The name, out of what the probe printed. Newest first, and the first line that is really a
219
- * title record wins — see the `tail -5` above.
220
- */
221
- export function parseSessionTitle(protocol: AgentProtocol, output: string): { title: string; source: string } | null {
222
- if (!readsTitleOutOfBand(protocol)) return null
223
- const lines = output.split("\n").map((l) => l.trim()).filter(Boolean)
224
- for (let i = lines.length - 1; i >= 0; i--) {
225
- let parsed: unknown
226
- try {
227
- parsed = JSON.parse(lines[i])
228
- } catch {
229
- continue
230
- }
231
- if (!parsed || typeof parsed !== "object") continue
232
- const obj = parsed as Record<string, unknown>
233
- if (obj.type !== "ai-title") continue
234
- const title = cleanTitle(obj.aiTitle)
235
- if (title) return { title, source: lines[i] }
236
- }
237
- return null
238
- }
239
-
240
- /**
241
- * Parse one line of a harness's stream into zero or more normalized events.
242
- *
243
- * Zero is a normal answer: a blank line, a line of prose from a harness that also logs to stdout,
244
- * or an event type we deliberately have no use for.
79
+ * Parse one line of a session's stream into zero or more normalized events. Zero is a normal
80
+ * answer: a blank line, or a session with nothing to read.
245
81
  */
246
82
  export function parseStreamLine(protocol: AgentProtocol, line: string): NormalizedEvent[] {
247
- if (protocol === "agent-v1") return readContractLine(line).map(({ source: _s, ...event }) => event)
248
- const trimmed = line.trim()
249
- if (!trimmed) return []
250
- let parsed: unknown
251
- try {
252
- parsed = JSON.parse(trimmed)
253
- } catch {
254
- // Not JSON. A harness that also writes human lines to stdout is common enough (a banner, a
255
- // warning) that this must not be an error — but it must not be invisible either.
256
- return [{ type: "raw", payload: { text: clip(trimmed).text } }]
257
- }
258
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return []
259
- const obj = parsed as Record<string, unknown>
260
- if (speaksClaude(protocol)) return adaptClaudeJson(obj)
261
- if (protocol === "codex-runner") return adaptCodex(obj)
262
- return adaptPassthrough(obj)
263
- }
264
-
265
- /**
266
- * `jsonl` — the project's harness already speaks our vocabulary. The escape hatch that means a
267
- * home-made agent has nothing to learn beyond one page of documentation, and the thing that keeps
268
- * the vocabulary honest: it is a format someone can write to, not just one we read from.
269
- */
270
- function adaptPassthrough(obj: Record<string, unknown>): NormalizedEvent[] {
271
- const type = typeof obj.type === "string" ? obj.type : null
272
- if (!type) return [{ type: "raw", payload: { json: obj } }]
273
- if (!(TASK_EVENT_TYPES as readonly string[]).includes(type)) {
274
- return [{ type: "raw", payload: { json: obj } }]
275
- }
276
- const { type: _t, ...payload } = obj
277
- return [{ type: type as TaskEventType, payload }]
83
+ if (protocol !== "agent-v1") return []
84
+ return readContractLine(line).map(({ source: _s, ...event }) => event)
278
85
  }
279
86
 
280
87
  function num(value: unknown): number | null {
@@ -343,9 +150,9 @@ export function summarizeUsage(input: UsageInput): SessionUsage | null {
343
150
  (typeof latestCall?.model === "string" ? latestCall.model : null) ??
344
151
  (typeof started?.model === "string" ? started.model : null),
345
152
  contextTokens: num(latestCall?.contextTokens),
346
- // Read off the line that opened the session; older events predate the field, so the model
347
- // string is re-read as a fallback rather than leaving the meter blank on a live task.
348
- contextWindow: num(started?.contextWindow) ?? contextWindowOf(started?.model as string | undefined),
153
+ // Read off the line that opened the session: the runner says it, the platform never guesses
154
+ // it from a model's name. Unknown (a session from before the field) leaves the meter out.
155
+ contextWindow: num(started?.contextWindow),
349
156
  inputTokens: measured ? calls.inputTokens : fallback("inputTokens"),
350
157
  outputTokens: measured ? calls.outputTokens : fallback("outputTokens"),
351
158
  cacheReadTokens: measured ? calls.cacheReadTokens : fallback("cacheReadTokens"),
@@ -359,12 +166,11 @@ export function summarizeUsage(input: UsageInput): SessionUsage | null {
359
166
  /**
360
167
  * Parse whole lines, keeping each event attached to the line it was derived from.
361
168
  *
362
- * The pairing lives here, next to the adapters, because it is the thing that makes normalization
363
- * reversible: `type`/`payload` is our reading of the line, `source` is the line. Get the reading
364
- * wrong and the line is still there to read again.
169
+ * The pairing is what makes the projection replayable: `type`/`payload` is our reading of the
170
+ * line, `source` the harness message the runner read it from (RFC 0020).
365
171
  *
366
172
  * `budget` bounds how many events one pass may produce, so a runaway session cannot blow past the
367
- * per-task ceiling in a single chunk. An adapter that throws costs its line, not the pass.
173
+ * per-task ceiling in a single chunk. A line the reader throws on costs that line, not the pass.
368
174
  */
369
175
  export function parseLines(protocol: AgentProtocol, lines: string[], budget: number): SourcedEvent[] {
370
176
  const out: SourcedEvent[] = []
@@ -372,8 +178,8 @@ export function parseLines(protocol: AgentProtocol, lines: string[], budget: num
372
178
  if (out.length >= budget) break
373
179
  let events: SourcedEvent[]
374
180
  try {
375
- // The contract carries each event's source itself; every other dialect's source is its line.
376
- events = protocol === "agent-v1" ? readContractLine(line) : parseStreamLine(protocol, line).map((e) => ({ ...e, source: line.trim() }))
181
+ // The contract carries each event's source itself.
182
+ events = protocol === "agent-v1" ? readContractLine(line) : []
377
183
  } catch (err) {
378
184
  console.warn(`[tasks] agent stream adapter threw: ${err}`)
379
185
  continue