@spunto/build 0.31.0 → 0.33.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.
@@ -1,192 +0,0 @@
1
- /**
2
- * How big a session's context window is.
3
- *
4
- * Split out of `agent-stream.ts` because this is not a fact about a dialect. Which harness wrote
5
- * the numbers is that file's problem; "how full is this window" outlives the harness, and it has
6
- * two answers of very different quality:
7
- *
8
- * 1. **The catalogue below** — a table, and therefore already wrong on the day a model ships.
9
- * It costs nothing: no credential, no network, no latency. It is the floor, not the answer.
10
- * 2. **The Models API** — `GET /v1/models/{id}` → `max_input_tokens`, the model's own answer
11
- * about itself. Used whenever the task's secrets carry an Anthropic credential of either
12
- * kind (`ANTHROPIC_API_KEY`, or a subscription token — see `ModelCredential`), which is
13
- * exactly where a session's credentials already live, and memoised per process because a
14
- * model's window does not move.
15
- *
16
- * Neither of them guesses. A model in neither source is worth `null`, and the panel then shows a
17
- * token count with no percentage — the rule this file inherits from the meter it feeds: a
18
- * percentage against a window we invented is worse than no percentage, because the token count
19
- * is still true and a wrong bar is not.
20
- *
21
- * **Why the catalogue is not a pattern match.** It used to be one — `/claude|opus|sonnet|haiku/`
22
- * → 200K, with the `[1m]` suffix as the only way to reach 1M. That reads as a safe default and
23
- * is not one: every current Claude model except Haiku 4.5 carries a 1M window, so the regex
24
- * answered 200K for a session with five times that room, and the meter pegged at 100% somewhere
25
- * around a fifth of the way in. Worse, the escape hatch never fired: `[1m]` is how Claude Code
26
- * spells the *opt-in* to a long window, and a model whose 1M is native (Opus 5 and the whole
27
- * 4.6-and-later line — 1M is both its default and its maximum) is spelled plainly. Measured from
28
- * a real `system/init` line: `"model":"claude-opus-5"`, no suffix, 1M of room, 200K on the bar.
29
- *
30
- * So: exact ids, `null` for anything else, and a live lookup for the cases a table cannot cover.
31
- */
32
-
33
- /** A Claude Code session opened on the long-context *variant* of its model — `claude-opus-5[1m]`. */
34
- const LONG_CONTEXT_SUFFIX = "[1m]"
35
-
36
- /**
37
- * Windows by exact API id, in tokens.
38
- *
39
- * Exact, because a family prefix is precisely how the previous guess went wrong. A model missing
40
- * from here is not assumed into a neighbour's window — it gets `null` and the Models API is asked
41
- * instead. That is the property worth keeping as models keep shipping: the next generation reads
42
- * as unknown, never as 200K.
43
- */
44
- const WINDOWS: Record<string, number> = {
45
- // 1M native — no opt-in, no suffix, nothing to detect in the stream.
46
- "claude-fable-5-2": 1_000_000,
47
- "claude-fable-5-1": 1_000_000,
48
- "claude-fable-5": 1_000_000,
49
- "claude-mythos-5-2": 1_000_000,
50
- "claude-mythos-5-1": 1_000_000,
51
- "claude-mythos-5": 1_000_000,
52
- "claude-mythos-preview": 1_000_000,
53
- "claude-opus-5-5": 1_000_000,
54
- "claude-opus-5": 1_000_000,
55
- "claude-opus-4-8": 1_000_000,
56
- "claude-opus-4-7": 1_000_000,
57
- "claude-opus-4-6": 1_000_000,
58
- "claude-sonnet-5": 1_000_000,
59
- "claude-sonnet-4-6": 1_000_000,
60
- // 200K — the generation the old default was written against, plus Haiku, which stayed there.
61
- "claude-haiku-4-5": 200_000,
62
- "claude-opus-4-5": 200_000,
63
- "claude-opus-4-1": 200_000,
64
- "claude-opus-4-0": 200_000,
65
- "claude-opus-4": 200_000,
66
- "claude-sonnet-4-5": 200_000,
67
- "claude-sonnet-4-0": 200_000,
68
- "claude-sonnet-4": 200_000,
69
- "claude-3-7-sonnet": 200_000,
70
- "claude-3-5-sonnet": 200_000,
71
- "claude-3-5-haiku": 200_000,
72
- "claude-3-haiku": 200_000,
73
- "claude-3-opus": 200_000,
74
- }
75
-
76
- /**
77
- * The API id inside whatever a harness wrote, so one catalogue covers every spelling of a model.
78
- *
79
- * Claude Code adds `[1m]`, Bedrock prefixes `anthropic.` (sometimes behind a region), Vertex
80
- * separates the snapshot with `@`, and a pinned id carries a trailing date. None of that changes
81
- * which model ran.
82
- */
83
- export function apiModelId(model: string): string {
84
- return model
85
- .trim()
86
- .toLowerCase()
87
- .replaceAll(LONG_CONTEXT_SUFFIX, "")
88
- .replace(/^(?:[a-z]{2}\.)?anthropic\./, "")
89
- .replace(/@.*$/, "")
90
- .replace(/-v\d+:\d+$/, "")
91
- .replace(/-\d{8}$/, "")
92
- .trim()
93
- }
94
-
95
- /**
96
- * The window a model string implies, from the catalogue alone — no credential, no network.
97
- *
98
- * `null` for anything unrecognised, which now includes any model newer than this table: see the
99
- * header. Kept as the synchronous fallback for `summarizeUsage`, which reduces events that were
100
- * stored before any of this existed.
101
- */
102
- export function contextWindowOf(model: string | null | undefined): number | null {
103
- if (typeof model !== "string" || !model) return null
104
- if (model.includes(LONG_CONTEXT_SUFFIX)) return 1_000_000
105
- return WINDOWS[apiModelId(model)] ?? null
106
- }
107
-
108
- const MODELS_ENDPOINT = "https://api.anthropic.com/v1/models"
109
- /** A read path polled every two seconds waits for nothing; the catalogue answers if this does not. */
110
- const LOOKUP_TIMEOUT_MS = 4_000
111
- /** A window is immutable, so a hit is kept for the life of the process. A miss is retried later. */
112
- const MISS_TTL_MS = 10 * 60_000
113
-
114
- const memo = new Map<string, { window: number | null; at: number }>()
115
-
116
- /** Only for tests — the memo is process-wide on purpose. */
117
- export function resetModelWindowCache(): void {
118
- memo.clear()
119
- }
120
-
121
- /**
122
- * How a task's session authenticates against Anthropic, because the two kinds do not use the
123
- * same header and sending both at once is rejected outright.
124
- *
125
- * - `api-key` — `ANTHROPIC_API_KEY`, on `x-api-key`.
126
- * - `oauth` — a subscription credential (`CLAUDE_CODE_OAUTH_TOKEN`, `ANTHROPIC_AUTH_TOKEN`), on
127
- * `Authorization: Bearer` **plus** the `oauth-2025-04-20` beta header. Converting one to the
128
- * other is a header change, not a value swap, which is exactly why this is a tagged union and
129
- * not a string: a token sent as `x-api-key` fails, quietly, as a 401 that looks like a
130
- * revoked key.
131
- */
132
- export type ModelCredential = { kind: "api-key" | "oauth"; value: string }
133
-
134
- function authHeaders(credential: ModelCredential): Record<string, string> {
135
- return credential.kind === "oauth"
136
- ? { authorization: `Bearer ${credential.value}`, "anthropic-beta": "oauth-2025-04-20" }
137
- : { "x-api-key": credential.value }
138
- }
139
-
140
- /**
141
- * Ask the Models API what the model's window is.
142
- *
143
- * `max_input_tokens` is the field; there is no `context_window` in the response. Every failure
144
- * mode — no network, a key that was revoked, a model id the API does not serve, a token whose
145
- * scopes do not reach this endpoint, a 429 — resolves to `null` rather than throwing: this is
146
- * called while ingesting a session, and a session must not stop streaming because a catalogue
147
- * lookup did not come back.
148
- */
149
- export async function liveContextWindow(model: string, credential: ModelCredential): Promise<number | null> {
150
- const id = apiModelId(model)
151
- if (!id) return null
152
-
153
- const hit = memo.get(id)
154
- if (hit && (hit.window !== null || Date.now() - hit.at < MISS_TTL_MS)) return hit.window
155
-
156
- let window: number | null = null
157
- try {
158
- const res = await fetch(`${MODELS_ENDPOINT}/${encodeURIComponent(id)}`, {
159
- headers: { ...authHeaders(credential), "anthropic-version": "2023-06-01" },
160
- signal: AbortSignal.timeout(LOOKUP_TIMEOUT_MS),
161
- })
162
- if (res.ok) {
163
- const body = (await res.json()) as { max_input_tokens?: unknown }
164
- const max = Number(body?.max_input_tokens)
165
- if (Number.isFinite(max) && max > 0) window = Math.trunc(max)
166
- }
167
- } catch {
168
- // Left as null. The catalogue is the fallback and the caller already knows that.
169
- }
170
- memo.set(id, { window, at: Date.now() })
171
- return window
172
- }
173
-
174
- /**
175
- * The window to record for a session that opened on `model`, best source first.
176
- *
177
- * The `[1m]` suffix wins outright: it is a statement about *this session* (the harness opted it
178
- * into a long window), where the catalogue and the API both report a property of the model. For
179
- * everything else the API's `max_input_tokens` is preferred over the table, and the table is the
180
- * fallback — including when the task carries no Anthropic credential at all, which is an ordinary
181
- * case and not an error.
182
- */
183
- export async function resolveContextWindow(
184
- model: string | null | undefined,
185
- credential: ModelCredential | null | undefined,
186
- ): Promise<number | null> {
187
- if (typeof model !== "string" || !model) return null
188
- if (model.includes(LONG_CONTEXT_SUFFIX)) return 1_000_000
189
- const catalogued = contextWindowOf(model)
190
- if (!credential?.value) return catalogued
191
- return (await liveContextWindow(model, credential)) ?? catalogued
192
- }
@@ -1,188 +0,0 @@
1
- /**
2
- * A turn that ended because the **account** ran out, not because the work did.
3
- *
4
- * Measured on 2026-10-17, when every running task of an org stopped within the same three minutes:
5
- * Claude Code ends the turn with a `result` that says `subtype: "success"` — and, next to it,
6
- * `is_error: true`, `api_error_status: 429`, `api_error: "usage_limit_reached"` and, as `result`,
7
- * the sentence the terminal would have printed (« You've hit your session limit · resets 9pm
8
- * (UTC) »). Read as a success, that put every task in review as if it had finished, and someone
9
- * had to type "continue" into each conversation once the quota came back.
10
- *
11
- * Three kinds, because they do not wait the same way:
12
- *
13
- * - `usage` — the plan's quota (five-hour session limit, weekly limit, out of extra usage). Comes
14
- * back at a time the harness usually knows (`resetsAt`), and not a minute before;
15
- * - `rate` — a 429 that is not a quota: a burst limit on an API key. Seconds to minutes;
16
- * - `overloaded` — the API's 529. The CLI already retried on its own before giving up, so this
17
- * is a "later", not a "never".
18
- *
19
- * Anything else that ends a turn on an API error (a 401, a 500, an invalid request) is **not** a
20
- * limit: waiting would not fix it, and pretending it might would hide it behind a countdown.
21
- *
22
- * Pure functions: the clock is always a parameter.
23
- */
24
-
25
- import type { TurnLimit, TurnLimitKind } from "../../agent-contract/vocabulary"
26
-
27
- export type { TurnLimit, TurnLimitKind }
28
-
29
- const USAGE_TEXT =
30
- /usage limit|session limit|weekly limit|opus limit|(?:5|five)[- ]hour limit|limit reached|out of extra usage|hit your limit/i
31
- const RATE_TEXT = /rate[ _-]?limit|too many requests|\b429\b/i
32
- const OVERLOADED_TEXT = /overloaded|\b529\b/i
33
-
34
- /**
35
- * The limit a Claude Code stream line reports, or null.
36
- *
37
- * Read off three shapes, all recorded on 2026-10-17 (see `turn-limit.test.ts`):
38
- *
39
- * - the `result` that ends the turn — what decides the task, but it carries no reset time;
40
- * - the synthetic assistant message just before it (`model: "<synthetic>"`,
41
- * `is_api_error_message: true`), which does: `api_error_params.rate_limit_info.resetsAt`,
42
- * in unix seconds;
43
- * - the older single-string form, `Claude AI usage limit reached|<unix seconds>`.
44
- *
45
- * A `result` that is not an error is never a limit, whatever its text says: an agent that writes
46
- * "I hit the rate limit of the GitHub API" in its summary has finished its turn.
47
- */
48
- export function claudeTurnLimit(obj: Record<string, unknown>): TurnLimit | null {
49
- if (obj.type === "result") {
50
- const failed = obj.is_error === true || (typeof obj.subtype === "string" && obj.subtype !== "success")
51
- if (!failed) return null
52
- return classify({
53
- status: num(obj.api_error_status),
54
- code: str(obj.api_error),
55
- text: str(obj.result) ?? "",
56
- resetsAt: null,
57
- })
58
- }
59
-
60
- if (obj.type === "assistant") {
61
- const message = (obj.message ?? {}) as Record<string, unknown>
62
- const synthetic = obj.is_api_error_message === true || message.model === "<synthetic>"
63
- if (!synthetic) return null
64
- const params = (obj.api_error_params ?? {}) as Record<string, unknown>
65
- const info = (params.rate_limit_info ?? {}) as Record<string, unknown>
66
- const content = Array.isArray(message.content) ? message.content : []
67
- const text = content
68
- .map((b) => (b && typeof b === "object" && (b as Record<string, unknown>).type === "text" ? str((b as Record<string, unknown>).text) : null))
69
- .filter(Boolean)
70
- .join("\n")
71
- return classify({
72
- status: num(obj.api_error_status),
73
- code: str(obj.api_error) ?? str(obj.error),
74
- text,
75
- resetsAt: epochToIso(info.resetsAt),
76
- })
77
- }
78
-
79
- return null
80
- }
81
-
82
- function classify(input: { status: number | null; code: string | null; text: string; resetsAt: string | null }): TurnLimit | null {
83
- const { status, code, text } = input
84
- // The old one-line form carries its own reset: `Claude AI usage limit reached|1760000000`.
85
- const piped = /\|(\d{10})\s*$/.exec(text)
86
- const message = (piped ? text.slice(0, piped.index) : text).trim().slice(0, 500)
87
- const resetsAt = input.resetsAt ?? (piped ? epochToIso(Number(piped[1])) : null)
88
-
89
- let kind: TurnLimitKind | null = null
90
- if (code === "usage_limit_reached" || USAGE_TEXT.test(text)) kind = "usage"
91
- else if (status === 529 || code === "overloaded_error" || OVERLOADED_TEXT.test(text)) kind = "overloaded"
92
- else if (status === 429 || code === "rate_limit" || code === "rate_limit_error" || RATE_TEXT.test(text)) kind = "rate"
93
- if (!kind) return null
94
- return { kind, status, message, resetsAt }
95
- }
96
-
97
- /**
98
- * When the limit lifts, read out of the sentence the harness printed — « resets 9pm (UTC) »,
99
- * « resets 9:30pm (Europe/Paris) », « resets Oct 20, 5am (UTC) » — relative to `now` (the moment
100
- * the line was written, not the moment it is read).
101
- *
102
- * The fallback for a turn whose structured reset time we never saw. A time with no date is the
103
- * next one at or after `now`; a zone we cannot resolve is a null, not a guess — a countdown to the
104
- * wrong hour is worse than "unknown", which the caller already knows how to wait out.
105
- */
106
- export function resetFromText(text: string, now: Date): string | null {
107
- const m =
108
- /resets?\s+(?:at\s+)?(?:([A-Za-z]{3,9})\.?\s+(\d{1,2}),?\s+(?:at\s+)?)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\s*(?:\(([^)]+)\))?/i.exec(text)
109
- if (!m) return null
110
- const [, monthName, dayText, hourText, minuteText, meridiem, zoneText] = m
111
- let hour = Number(hourText)
112
- const minute = minuteText ? Number(minuteText) : 0
113
- if (!meridiem && !minuteText) return null // « resets 3 » is not a time
114
- if (meridiem) {
115
- if (hour < 1 || hour > 12) return null
116
- hour = (hour % 12) + (meridiem.toLowerCase() === "pm" ? 12 : 0)
117
- }
118
- if (hour > 23 || minute > 59) return null
119
- const zone = zoneText?.trim() || "UTC"
120
- if (!isZone(zone)) return null
121
-
122
- const today = partsIn(now.getTime(), zone)
123
- if (monthName && dayText) {
124
- const month = MONTHS.indexOf(monthName.slice(0, 3).toLowerCase())
125
- if (month < 0) return null
126
- // Same year, unless that date is already well behind us — then it is next year's.
127
- let at = zonedToUtc(today.year, month, Number(dayText), hour, minute, zone)
128
- if (at < now.getTime() - 24 * 3600_000) at = zonedToUtc(today.year + 1, month, Number(dayText), hour, minute, zone)
129
- return new Date(at).toISOString()
130
- }
131
- let at = zonedToUtc(today.year, today.month, today.day, hour, minute, zone)
132
- if (at <= now.getTime()) at = zonedToUtc(today.year, today.month, today.day + 1, hour, minute, zone)
133
- return new Date(at).toISOString()
134
- }
135
-
136
- const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]
137
-
138
- function isZone(zone: string): boolean {
139
- try {
140
- new Intl.DateTimeFormat("en-US", { timeZone: zone })
141
- return true
142
- } catch {
143
- return false
144
- }
145
- }
146
-
147
- /** Wall-clock fields of an instant in a zone. `month` is 0-based, like `Date.UTC`. */
148
- function partsIn(t: number, zone: string): { year: number; month: number; day: number; hour: number; minute: number } {
149
- const parts = new Intl.DateTimeFormat("en-US", {
150
- timeZone: zone,
151
- hourCycle: "h23",
152
- year: "numeric",
153
- month: "numeric",
154
- day: "numeric",
155
- hour: "numeric",
156
- minute: "numeric",
157
- }).formatToParts(new Date(t))
158
- const get = (type: string) => Number(parts.find((p) => p.type === type)?.value ?? 0)
159
- return { year: get("year"), month: get("month") - 1, day: get("day"), hour: get("hour"), minute: get("minute") }
160
- }
161
-
162
- /** The instant a wall-clock time in `zone` names. Two passes settle a DST edge. */
163
- function zonedToUtc(year: number, month: number, day: number, hour: number, minute: number, zone: string): number {
164
- const wanted = Date.UTC(year, month, day, hour, minute)
165
- let guess = wanted
166
- for (let i = 0; i < 2; i++) {
167
- const p = partsIn(guess, zone)
168
- const seen = Date.UTC(p.year, p.month, p.day, p.hour, p.minute)
169
- guess += wanted - seen
170
- }
171
- return guess
172
- }
173
-
174
- function epochToIso(value: unknown): string | null {
175
- const n = num(value)
176
- // Seconds since the epoch, sanity-bounded (2020 – 2100): a field that changed unit would
177
- // otherwise produce a reset in 1970 or in the year 50 000.
178
- if (n === null || n < 1_577_836_800 || n > 4_102_444_800) return null
179
- return new Date(n * 1000).toISOString()
180
- }
181
-
182
- function num(value: unknown): number | null {
183
- return typeof value === "number" && Number.isFinite(value) ? value : null
184
- }
185
-
186
- function str(value: unknown): string | null {
187
- return typeof value === "string" && value ? value : null
188
- }
@@ -1,245 +0,0 @@
1
- #!/usr/bin/env node
2
- // The Claude runner (RFC 0048): written into the machine by the platform when a session starts —
3
- // one file, **bundled** with its adapter by the platform (esbuild) so there is nothing to install —
4
- // and run with the Node the `spunto-agent-claude` feature put in the image. It drives Claude
5
- // through the official Agent SDK the same feature installed.
6
- //
7
- // The Spunto agent contract, the same for every agent app (docs/agent-contract.md, `../agent-contract`):
8
- //
9
- // node claude.mjs run [--model <id>] [--resume <session id>]
10
- // stdin one JSON object per line — {"type":"user","text"} · {"type":"interrupt","id"} ·
11
- // {"type":"title","id","description"} ; closed = the session ends after its turn
12
- // stdout **our** vocabulary, one JSON object per line (`agent-v1`): each SDK message is read
13
- // here (`./claude/adapter.ts`) and printed as the events it means, with the message
14
- // itself as `source` — the platform has no Claude reader for it
15
- // env SPUNTO_AGENT_OPTIONS — the task's parameters, as declared by the app's catalog
16
- // (`./catalogs.ts`): `{"effort":"high"}`
17
- // SPUNTO_AGENT_MCP — the org's MCP servers (RFC 0049), in the platform's words:
18
- // `[{"name":"linear","path":"/api/mcp-gateway/…"}]`, reached through the platform's
19
- // gateway with the machine's own identity (`SPUNTO_WORKER_TOKEN`), and reconnected
20
- // before each turn after the first, so a server's new tools reach a running session
21
- // SPUNTO_AGENT_STREAM — "1": also print the tokens of a message as they are written
22
- // (`stream_event` lines), set behind the org flag `token-streaming`
23
- // exit 0 once the input is closed and the last turn is over, 1 when the session could not run
24
- //
25
- // Credentials are not this file's business: whatever the member set as secrets (an
26
- // `ANTHROPIC_API_KEY`) reaches the SDK's binary through the environment, untouched. The one thing
27
- // the runner does with that key itself is ask the Models API how large the session's window is
28
- // (`resolveContextWindow`) — an API key only, never a subscription token, which is the rule the
29
- // platform followed when it asked on the session's behalf.
30
-
31
- import { createInterface } from "node:readline"
32
- import { claudeTranslator } from "./claude/adapter"
33
- import { resolveContextWindow } from "./claude/model-window"
34
-
35
- const SDK = process.env.SPUNTO_CLAUDE_SDK || "/opt/spunto/agents/claude/node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs"
36
-
37
- function out(obj) {
38
- process.stdout.write(`${JSON.stringify(obj)}\n`)
39
- }
40
-
41
- /** A failure the platform can read: the turn ends, failed, saying why — then a non-zero exit. */
42
- function fail(message) {
43
- out({ type: "session.ended", status: "failed", stopReason: null, summary: message })
44
- process.exit(1)
45
- }
46
-
47
- /** How the window is asked about: an API key, the only credential the platform ever used for it. */
48
- const apiKey = process.env.ANTHROPIC_API_KEY?.trim()
49
- const credential = apiKey ? { kind: "api-key", value: apiKey } : null
50
-
51
- /**
52
- * Print one SDK message as the contract. The line that opens the session carries the model's own
53
- * window when the Models API answers (the adapter only knows a table), so it is measured here, once
54
- * per session, before the line goes out — the platform no longer asks anyone on a session's behalf.
55
- */
56
- const translate = claudeTranslator()
57
- async function emit(message) {
58
- for (const line of translate(message)) {
59
- if (line.type === "session.started" && typeof line.model === "string") {
60
- const measured = await resolveContextWindow(line.model, credential).catch(() => null)
61
- if (measured !== null) line.contextWindow = measured
62
- }
63
- out(line)
64
- }
65
- }
66
-
67
- function parseArgs(argv) {
68
- const [verb, ...rest] = argv
69
- if (verb !== "run") fail(`claude runner: unknown verb "${verb ?? ""}" (expected "run")`)
70
- const args = {}
71
- for (let i = 0; i < rest.length; i++) {
72
- const flag = rest[i]
73
- if (flag === "--model" || flag === "--resume") {
74
- const value = rest[++i]
75
- if (value) args[flag.slice(2)] = value
76
- } else {
77
- fail(`claude runner: unknown flag "${flag}"`)
78
- }
79
- }
80
- return args
81
- }
82
-
83
- /** The human's turns, as the async iterable the SDK reads its prompt from. Ends when stdin does. */
84
- function inputQueue() {
85
- const pending = []
86
- let wake = null
87
- let closed = false
88
- return {
89
- push(message) {
90
- pending.push(message)
91
- wake?.()
92
- },
93
- close() {
94
- closed = true
95
- wake?.()
96
- },
97
- async *[Symbol.asyncIterator]() {
98
- for (;;) {
99
- if (pending.length > 0) {
100
- yield pending.shift()
101
- continue
102
- }
103
- if (closed) return
104
- await new Promise((resolve) => (wake = resolve))
105
- wake = null
106
- }
107
- },
108
- }
109
- }
110
-
111
- const args = parseArgs(process.argv.slice(2))
112
-
113
- /** The task's parameters. Checked by the platform against the catalog; read defensively all the same. */
114
- function readOptions() {
115
- try {
116
- const parsed = JSON.parse(process.env.SPUNTO_AGENT_OPTIONS || "{}")
117
- return parsed && typeof parsed === "object" ? parsed : {}
118
- } catch {
119
- return {}
120
- }
121
- }
122
- const params = readOptions()
123
-
124
- /**
125
- * The org's MCP servers (RFC 0049), as the SDK's `mcpServers`. Each is the platform's gateway, not
126
- * the vendor's server: the machine shows its own identity and never holds the vendor's token. One
127
- * that can't be reached (no API URL, no identity) is left out rather than failing the session.
128
- */
129
- function readMcpServers() {
130
- let listed
131
- try {
132
- listed = JSON.parse(process.env.SPUNTO_AGENT_MCP || "[]")
133
- } catch {
134
- return {}
135
- }
136
- const api = (process.env.SPUNTO_API_URL || "").replace(/\/$/, "")
137
- const token = process.env.SPUNTO_WORKER_TOKEN
138
- if (!Array.isArray(listed) || !api || !token) return {}
139
- const servers = {}
140
- for (const s of listed) {
141
- if (!s || typeof s.name !== "string" || typeof s.path !== "string") continue
142
- servers[s.name] = { type: "http", url: `${api}${s.path}`, headers: { Authorization: `Bearer ${token}` } }
143
- }
144
- return servers
145
- }
146
- const mcpServers = readMcpServers()
147
-
148
- let sdk
149
- try {
150
- sdk = await import(SDK)
151
- } catch (err) {
152
- fail(`claude runner: the Agent SDK is not installed at ${SDK} — is the project's image built with the Claude app's feature? (${err?.message ?? err})`)
153
- }
154
-
155
- const input = inputQueue()
156
- const session = sdk.query({
157
- prompt: input,
158
- options: {
159
- cwd: process.cwd(),
160
- ...(args.model ? { model: args.model } : {}),
161
- ...(args.resume ? { resume: args.resume } : {}),
162
- ...(typeof params.effort === "string" ? { effort: params.effort } : {}),
163
- // Added to the servers Claude Code reads from its settings (`.mcp.json`, `~/.claude.json`).
164
- ...(Object.keys(mcpServers).length ? { mcpServers } : {}),
165
- // A task runs unattended in a disposable machine — what `--dangerously-skip-permissions` did.
166
- permissionMode: "bypassPermissions",
167
- allowDangerouslySkipPermissions: true,
168
- // Claude Code's own system prompt, CLAUDE.md, settings and skills: the session must behave
169
- // exactly like the CLI it replaces, not like a bare SDK agent.
170
- systemPrompt: { type: "preset", preset: "claude_code" },
171
- settingSources: ["user", "project", "local"],
172
- // The tokens of a message as they are written (`stream_event` lines), when the org streams
173
- // them. Never stored — the platform folds them into the draft the cockpit shows until the
174
- // whole message lands.
175
- includePartialMessages: process.env.SPUNTO_AGENT_STREAM === "1",
176
- // A one-line « what it is doing now » for each subagent every ~30 s (`task_progress.summary`),
177
- // written by a fork of the subagent on its own prompt cache — what the cockpit shows on the
178
- // subagent's row while it runs. Without it the row says only the tool it last used.
179
- agentProgressSummaries: true,
180
- stderr: (line) => process.stderr.write(line),
181
- },
182
- })
183
-
184
- /**
185
- * The gateway's servers are connected once, when the process starts, and the session lives as long
186
- * as the task: a server redeployed with new tools since would stay invisible until the task ends.
187
- * So before a turn that comes after the session went idle, each is reconnected — which lists its
188
- * tools again (~30 ms each, measured with the SDK 0.3.310). Never during a turn: that could cut a
189
- * call in flight. A server that fails to reconnect keeps the tools it had.
190
- */
191
- let idle = false
192
- let ahead = Promise.resolve()
193
- async function refreshMcpServers() {
194
- if (!idle) return
195
- idle = false
196
- await Promise.all(
197
- Object.keys(mcpServers).map((name) =>
198
- session.reconnectMcpServer(name).catch((err) => process.stderr.write(`claude runner: reconnecting ${name} failed: ${err?.message ?? err}\n`)),
199
- ),
200
- )
201
- }
202
-
203
- createInterface({ input: process.stdin, crlfDelay: Infinity })
204
- .on("line", (line) => {
205
- let msg
206
- try {
207
- msg = JSON.parse(line)
208
- } catch {
209
- return
210
- }
211
- if (!msg || typeof msg !== "object") return
212
- if (msg.type === "user" && typeof msg.text === "string") {
213
- const turn = { type: "user", message: { role: "user", content: [{ type: "text", text: msg.text }] }, parent_tool_use_id: null }
214
- // Chained, so that a turn refreshed between two others still goes in the order it was sent.
215
- ahead = ahead.then(refreshMcpServers).then(() => input.push(turn))
216
- } else if (msg.type === "interrupt") {
217
- session.interrupt().catch((err) => process.stderr.write(`claude runner: interrupt failed: ${err?.message ?? err}\n`))
218
- } else if (msg.type === "title" && typeof msg.description === "string") {
219
- // Asked of the SDK (Claude names the conversation from the human's words), and said in band.
220
- if (typeof session.generateSessionTitle !== "function") return
221
- session
222
- .generateSessionTitle(msg.description, { persist: true })
223
- .then((title) => {
224
- const clean = typeof title === "string" ? title.replace(/\s+/g, " ").trim().slice(0, 200) : ""
225
- if (clean) out({ type: "session.title", title: clean })
226
- })
227
- .catch((err) => process.stderr.write(`claude runner: title failed: ${err?.message ?? err}\n`))
228
- }
229
- })
230
- .on("close", () => input.close())
231
-
232
- // The SDK also throws after a failed `result` it has just yielded; that result already said why,
233
- // and a second one would end the turn twice in the timeline.
234
- let lastType = null
235
- try {
236
- for await (const message of session) {
237
- await emit(message)
238
- lastType = message?.type ?? null
239
- if (lastType === "result") idle = true
240
- }
241
- } catch (err) {
242
- if (lastType === "result") process.exit(1)
243
- fail(`claude runner: ${err?.message ?? err}`)
244
- }
245
- process.exit(0)