@spunto/build 0.30.0 → 0.31.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
@@ -190,22 +190,19 @@ and are meant to be **bundled** (esbuild, `platform: node`, `format: esm`) befor
190
190
 
191
191
  ### `@spunto/build/agent-stream` — reading an agent session as it happens
192
192
 
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.
196
-
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.
200
-
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.
203
-
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.
193
+ The platform's side of a session that speaks the contract (`agent-v1`): how to write a turn, an
194
+ interrupt or a title request to it, how to read its stdout into stored events (`parseLines`, which
195
+ keeps each event's `source`), and how to sum what it consumed (`summarizeUsage`). Nothing here knows
196
+ which harness is on the other end: every harness's own output is read by its runner, in the machine.
197
+
198
+ Tokens of a message still being written (`message.delta`) are **not** events: `foldDraft(protocol,
199
+ lines, previous)` folds them into the one transient text block in flight — closed by the finished
200
+ message, never stored. Where the draft lives between two reads is the caller's business.
201
+
202
+ The harnesses' own dialects (Claude Code's `stream-json`, the runners' former `claude-runner` /
203
+ `codex-runner`) were read here until 0.31.0; they are gone, with `applyProtocol`, the title probe of
204
+ Claude's transcript and `PROJECT_AGENT_PROTOCOLS`. Claude's context windows and usage limits moved
205
+ next to its runner (`agent-runners/claude/`).
209
206
 
210
207
  ### `@spunto/build/terminal` — the half of a persistent terminal that is a string
211
208
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spunto/build",
3
- "version": "0.30.0",
3
+ "version": "0.31.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",
@@ -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
+ * (`../agent-runners/claude/turn-limit.ts` 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()),
@@ -3,32 +3,22 @@
3
3
  * `--output-format stream-json --verbose` shapes.
4
4
  *
5
5
  * Lives with the Claude runner (RFC 0048 § 9): the runner bundles it and prints the contract
6
- * (`claudeContractLines`), so the platform reads no Claude line of a session started since. The
7
- * platform's legacy reader (`../../agent-stream`) still imports `adaptClaudeJson` for the
8
- * conversations that began on the CLI or on the runner's old dialect, until they end.
6
+ * (`claudeContractLines`): the platform reads no Claude line, ever.
9
7
  *
10
8
  * Written against output measured in a real worker, not against a spec: the shapes below are what
11
9
  * the CLI emitted, and the tests replay recorded samples so a change in that output shows up as a
12
10
  * failing test rather than as an empty timeline.
13
11
  */
14
12
 
15
- import { SUBAGENT_STATUSES, clip, type NormalizedEvent } from "../../agent-contract/vocabulary"
16
- import { contextWindowOf } from "../../agent-stream/model-window"
17
- import { claudeTurnLimit, resetFromText, type TurnLimit } from "../../agent-stream/turn-limit"
13
+ import { SUBAGENT_STATUSES, cleanTitle, clip, type NormalizedEvent } from "../../agent-contract/vocabulary"
14
+
15
+ export { cleanTitle }
16
+ import { contextWindowOf } from "./model-window"
17
+ import { claudeTurnLimit, resetFromText, type TurnLimit } from "./turn-limit"
18
18
 
19
19
  /** Marks the `control_request`s that ask the CLI for a title, and so the `control_response`s that answer. */
20
20
  export const TITLE_REQUEST_PREFIX = "spunto-title-"
21
21
 
22
- /** One line, no runs of whitespace, bounded — a title goes in a list row and in a page header. */
23
- export function cleanTitle(value: unknown): string | null {
24
- if (typeof value !== "string") return null
25
- const title = value.replace(/\s+/g, " ").trim().slice(0, MAX_TITLE).trim()
26
- return title || null
27
- }
28
-
29
- /** Longest name we keep. The column allows 200; a harness that writes an essay gets cut. */
30
- const MAX_TITLE = 200
31
-
32
22
  export function adaptClaudeJson(obj: Record<string, unknown>): NormalizedEvent[] {
33
23
  const type = obj.type
34
24
 
@@ -22,18 +22,9 @@
22
22
  * Pure functions: the clock is always a parameter.
23
23
  */
24
24
 
25
- export const TURN_LIMIT_KINDS = ["usage", "rate", "overloaded"] as const
26
- export type TurnLimitKind = (typeof TURN_LIMIT_KINDS)[number]
27
-
28
- export type TurnLimit = {
29
- kind: TurnLimitKind
30
- /** The HTTP status the harness reported, when it did (429, 529). */
31
- status: number | null
32
- /** What the harness said, as it said it — shown to a human, never parsed again. */
33
- message: string
34
- /** When the limit lifts, ISO 8601, if the line said so in a form we can trust. */
35
- resetsAt: string | null
36
- }
25
+ import type { TurnLimit, TurnLimitKind } from "../../agent-contract/vocabulary"
26
+
27
+ export type { TurnLimit, TurnLimitKind }
37
28
 
38
29
  const USAGE_TEXT =
39
30
  /usage limit|session limit|weekly limit|opus limit|(?:5|five)[- ]hour limit|limit reached|out of extra usage|hit your limit/i
@@ -30,7 +30,7 @@
30
30
 
31
31
  import { createInterface } from "node:readline"
32
32
  import { claudeTranslator } from "./claude/adapter"
33
- import { resolveContextWindow } from "../agent-stream/model-window"
33
+ import { resolveContextWindow } from "./claude/model-window"
34
34
 
35
35
  const SDK = process.env.SPUNTO_CLAUDE_SDK || "/opt/spunto/agents/claude/node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs"
36
36
 
@@ -3,8 +3,7 @@
3
3
  * (`ThreadEvent`). Written against the SDK's own types (0.164.0).
4
4
  *
5
5
  * Lives with the Codex runner (RFC 0048 § 9): the runner bundles it and prints the contract
6
- * (`codexContractLines`). The platform's legacy reader still imports `adaptCodex` for sessions
7
- * started on the runner's old dialect, until they end.
6
+ * (`codexContractLines`): the platform reads no Codex line, ever.
8
7
  *
9
8
  * Codex works per **turn**, not per session: `turn.completed` is a hand-back the way Claude's
10
9
  * `result` is, so it ends the turn here too. Its usage is the turn's sum, which is why it is filed
@@ -43,12 +43,6 @@ export type AgentHarness = {
43
43
  featureId: string
44
44
  /** How the platform talks to the runner — the contract, for every app. */
45
45
  protocol: AgentProtocol
46
- /**
47
- * What this app's runner printed before the contract, and so how a session it started then is
48
- * still read, until it ends (RFC 0048 § 9: a session keeps the dialect it began on). An app born
49
- * on the contract (Mistral) has no such past: `agent-v1`.
50
- */
51
- legacyProtocol: AgentProtocol
52
46
  /** The runner's entry, a file of this package — to be bundled with what it imports. */
53
47
  runnerFile: URL
54
48
  /** Where the harness looks for user-level skills (RFC 0033), as shell evaluated in the machine. */
@@ -60,7 +54,6 @@ export const AGENT_HARNESSES: Record<AgentHarnessId, AgentHarness> = {
60
54
  id: "claude",
61
55
  featureId: "spunto-agent-claude",
62
56
  protocol: "agent-v1",
63
- legacyProtocol: "claude-runner",
64
57
  runnerFile: new URL("./claude.mjs", import.meta.url),
65
58
  skillDirs: ["${CLAUDE_CONFIG_DIR:-$HOME/.claude}/skills"],
66
59
  },
@@ -68,7 +61,6 @@ export const AGENT_HARNESSES: Record<AgentHarnessId, AgentHarness> = {
68
61
  id: "codex",
69
62
  featureId: "spunto-agent-codex",
70
63
  protocol: "agent-v1",
71
- legacyProtocol: "codex-runner",
72
64
  runnerFile: new URL("./codex.mjs", import.meta.url),
73
65
  skillDirs: ["${CODEX_HOME:-$HOME/.codex}/skills"],
74
66
  },
@@ -76,7 +68,6 @@ export const AGENT_HARNESSES: Record<AgentHarnessId, AgentHarness> = {
76
68
  id: "mistral",
77
69
  featureId: "spunto-agent-mistral",
78
70
  protocol: "agent-v1",
79
- legacyProtocol: "agent-v1",
80
71
  runnerFile: new URL("./mistral.mjs", import.meta.url),
81
72
  skillDirs: ["${VIBE_HOME:-$HOME/.vibe}/skills"],
82
73
  },
@@ -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 (`../agent-runners`), 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
@@ -1,9 +1,8 @@
1
1
  // What the agent is writing *right now*, before it has finished saying it.
2
2
  //
3
3
  // The vocabulary (`agent-stream.ts`) is made of finished facts: a message lands once, whole. A
4
- // harness that streams tokens says the same message a second time, piecemeal, ahead of it —
5
- // Claude's `stream_event` lines (`includePartialMessages` in the Agent SDK,
6
- // `--include-partial-messages` on the CLI). Those pieces are **not events**: storing one row per
4
+ // runner whose harness streams tokens says the same message a second time, piecemeal, ahead of
5
+ // it — the contract's `message.delta` lines. Those pieces are **not events**: storing one row per
7
6
  // token would bury a session under thousands of rows that the finished message then repeats in
8
7
  // full. So they fold into one transient value instead — the draft — which the finished message
9
8
  // replaces the moment it lands, and which nothing persists.
@@ -29,17 +28,6 @@ function append(draft: AgentDraft | null, text: string): AgentDraft {
29
28
  return next.length > MAX_DRAFT ? { text: next.slice(0, MAX_DRAFT), truncated: true } : { text: next, truncated: false }
30
29
  }
31
30
 
32
- /** Claude's dialects print token deltas; Codex's prints the message so far on `item.updated`; the contract, `message.delta`. */
33
- function streamsPartials(protocol: AgentProtocol): boolean {
34
- return (
35
- protocol === "agent-v1" ||
36
- protocol === "claude-runner" ||
37
- protocol === "claude-stream" ||
38
- protocol === "claude-json" ||
39
- protocol === "codex-runner"
40
- )
41
- }
42
-
43
31
  /** What closes a draft in the contract: the finished text, or anything that comes after it in the turn. */
44
32
  const CLOSES_DRAFT = new Set(["message", "thinking", "tool.call", "tool.result", "session.ended"])
45
33
 
@@ -72,85 +60,12 @@ function foldContract(lines: string[], draft: AgentDraft | null): AgentDraft | n
72
60
  return current
73
61
  }
74
62
 
75
- /**
76
- * Codex: an `agent_message` item carries its whole text so far, not a delta — `item.started` and
77
- * `item.updated` *are* the draft, `item.completed` (stored as the `message`) or the end of the
78
- * turn closes it. Whether the SDK sends updates of a message mid-write is its business; the runner
79
- * prints every event it gets, so this costs nothing when it does not.
80
- */
81
- function foldCodex(lines: string[], draft: AgentDraft | null): AgentDraft | null {
82
- let current = draft
83
- for (const line of lines) {
84
- const trimmed = line.trim()
85
- if (!trimmed.startsWith("{")) continue
86
- if (!trimmed.includes('"agent_message"') && !trimmed.includes('"turn.')) continue
87
- let obj: Record<string, unknown>
88
- try {
89
- const parsed = JSON.parse(trimmed)
90
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue
91
- obj = parsed as Record<string, unknown>
92
- } catch {
93
- continue
94
- }
95
- if (obj.type === "turn.completed" || obj.type === "turn.failed") {
96
- current = null
97
- continue
98
- }
99
- const item = (obj.item ?? {}) as Record<string, unknown>
100
- if (item.type !== "agent_message") continue
101
- if (obj.type === "item.completed") current = null
102
- else if ((obj.type === "item.started" || obj.type === "item.updated") && typeof item.text === "string")
103
- current = item.text ? append(null, item.text) : null
104
- }
105
- return current
106
- }
107
-
108
63
  /**
109
64
  * Fold whole lines of a session's stdout into the draft, starting from `draft` (the value left
110
- * by the previous read). Lines that say nothing about the text in flight leave it as it was.
111
- *
112
- * - a text block starting opens a fresh draft — one draft is one block, as one stored `message`
113
- * is one block;
114
- * - a `text_delta` grows it;
115
- * - the finished `assistant` message, or the turn's `result`, closes it: from there on the
116
- * timeline has the real thing.
117
- *
118
- * A subagent's partials (`parent_tool_use_id` set) are skipped: what it writes is not what the
119
- * session says to the reader, and interleaving it would garble the draft of the main thread.
65
+ * by the previous read). Lines that say nothing about the text in flight leave it as it was; a
66
+ * session that does not speak the contract has no draft.
120
67
  */
121
68
  export function foldDraft(protocol: AgentProtocol, lines: string[], draft: AgentDraft | null): AgentDraft | null {
122
- if (!streamsPartials(protocol)) return null
123
- if (protocol === "agent-v1") return foldContract(lines, draft)
124
- if (protocol === "codex-runner") return foldCodex(lines, draft)
125
- let current = draft
126
- for (const line of lines) {
127
- const trimmed = line.trim()
128
- // Cheap pre-filter: most lines are not about the draft, and some carry megabytes.
129
- if (!trimmed.startsWith("{")) continue
130
- if (!trimmed.includes('"stream_event"') && !trimmed.includes('"assistant"') && !trimmed.includes('"result"')) continue
131
- let obj: Record<string, unknown>
132
- try {
133
- const parsed = JSON.parse(trimmed)
134
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue
135
- obj = parsed as Record<string, unknown>
136
- } catch {
137
- continue
138
- }
139
- if (obj.parent_tool_use_id) continue
140
-
141
- if (obj.type === "assistant" || obj.type === "result") {
142
- current = null
143
- continue
144
- }
145
- if (obj.type !== "stream_event") continue
146
- const event = (obj.event ?? {}) as Record<string, unknown>
147
- if (event.type === "content_block_start") {
148
- const block = (event.content_block ?? {}) as Record<string, unknown>
149
- if (block.type === "text") current = append(null, typeof block.text === "string" ? block.text : "")
150
- } else if (event.type === "content_block_delta") {
151
- const delta = (event.delta ?? {}) as Record<string, unknown>
152
- if (delta.type === "text_delta" && typeof delta.text === "string") current = append(current, delta.text)
153
- }
154
- }
155
- return current
69
+ if (protocol !== "agent-v1") return null
70
+ return foldContract(lines, draft)
156
71
  }
@@ -1,44 +1,29 @@
1
- // Reading an agent session as it happens: one adapter per harness dialect, one vocabulary out.
1
+ // Reading an agent session as it happens: the Spunto agent contract (`agent-v1`) in, our
2
+ // vocabulary out, and how to write to a session.
2
3
  //
3
- // A task's harness is launched with a prompt on stdin and nothing else agreed — that poverty is
4
- // what lets the command hold Claude Code, Codex, or a shell script. Streaming needs strictly more
5
- // than that, so the extra knowledge lives here and nowhere else.
6
- //
7
- // **The vocabulary is what gets stored, never the harness's own shape.** A CLI's JSON output is an
8
- // output format, not an API; persisting it would date the history the first time the vendor
9
- // reshuffles a field. Adapters translate into the small set of event types below, and anything
10
- // unmapped becomes `raw` rather than being dropped.
11
- //
12
- // It lives in this package for a reason that inverts the rest of it: **nothing has forked this
13
- // yet.** Every other module here was extracted after two copies had already drifted. This one is
14
- // 700 lines of third-party output parsing that exactly one product has today — putting it in the
15
- // shared package now costs nothing and means the second product never writes its own.
4
+ // **The vocabulary is what gets stored, never the harness's own shape.** Every harness is read by
5
+ // its agent app's runner, in the machine (`../agent-runners`); nothing here knows which one it was.
16
6
 
17
7
  export {
18
8
  AGENT_PROTOCOLS,
19
- applyProtocol,
20
- cleanTitle,
21
9
  interruptLine,
22
10
  isInteractive,
23
- isRunner,
24
11
  parseLines,
25
- parseSessionTitle,
26
12
  parseStreamLine,
27
- PROJECT_AGENT_PROTOCOLS,
28
- readsTitleOutOfBand,
29
- sessionTitleProbe,
30
13
  sessionTitleRequestLine,
31
14
  splitCompleteLines,
32
15
  summarizeUsage,
33
16
  TASK_EVENT_TYPES,
34
17
  userTurnLine,
35
18
  } from "./agent-stream"
36
- // The text block a streaming harness is still writing — folded from its partial messages, never stored.
19
+ // The text block a streaming harness is still writing — folded from `message.delta`, never stored.
37
20
  export { foldDraft } from "./draft"
38
21
  export type { AgentDraft } from "./draft"
39
- // Turns that ended on a usage/rate limit rather than on finished work, and when the limit lifts.
40
- export { claudeTurnLimit, resetFromText, TURN_LIMIT_KINDS } from "./turn-limit"
41
- export type { TurnLimit, TurnLimitKind } from "./turn-limit"
22
+ // A session's name, as it is kept: one line, bounded.
23
+ export { cleanTitle } from "../agent-contract/vocabulary"
24
+ // Turns that ended on a usage/rate limit rather than on finished work.
25
+ export { TURN_LIMIT_KINDS } from "../agent-contract/vocabulary"
26
+ export type { TurnLimit, TurnLimitKind } from "../agent-contract/vocabulary"
42
27
 
43
28
  export type {
44
29
  AgentProtocol,
@@ -49,17 +34,3 @@ export type {
49
34
  TaskEventType,
50
35
  UsageInput,
51
36
  } from "./agent-stream"
52
-
53
- // Model context windows. `liveContextWindow`/`resolveContextWindow` take a credential as a
54
- // *parameter* and ask the model vendor's own API — the package still reads no environment and
55
- // holds no key of its own, but it is the one place here that talks to something other than a
56
- // public registry, and it does so on the caller's behalf. `resetModelWindowCache` exists for
57
- // tests: the lookup memoises per process.
58
- export {
59
- apiModelId,
60
- contextWindowOf,
61
- liveContextWindow,
62
- resetModelWindowCache,
63
- resolveContextWindow,
64
- } from "./model-window"
65
- export type { ModelCredential } from "./model-window"
package/src/spec/index.ts CHANGED
@@ -102,9 +102,8 @@ export const SpecProjectSchema = z.object({
102
102
  sharedVolumes: z.array(SpecSharedVolumeSchema).optional(),
103
103
 
104
104
  /** Spunto Cloud — how delegated work runs and reports. Meaningless to a product without tasks. */
105
- taskAgentCommand: z.string().optional(),
106
- taskAgentProtocol: z.enum(["none", "claude-json", "claude-stream", "jsonl"]).optional(),
107
- taskFollowUpCommand: z.string().optional(),
105
+ // `taskAgentCommand`, `taskAgentProtocol` and `taskFollowUpCommand` — the harness typed by hand,
106
+ // before agent apps — are gone (2026-11-24): an older file that has them still parses, without them.
108
107
  taskValidateCommand: z.string().optional(),
109
108
  taskCancelCommand: z.string().optional(),
110
109
  taskReviewMode: z.enum(["stop", "keep"]).optional(),