@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.
@@ -1,355 +0,0 @@
1
- #!/usr/bin/env node
2
- // The Mistral runner (RFC 0048): same contract as `claude.mjs` and `codex.mjs`, over **Mistral
3
- // Vibe**, which has no Node SDK — so the runner is an ACP client (Agent Client Protocol, JSON-RPC
4
- // 2.0 on stdio) of `vibe-acp`, the binary the `spunto-agent-mistral` feature installs. Bundled
5
- // with its adapter by the platform, like every runner.
6
- //
7
- // node mistral.mjs run [--model <alias>] [--resume <session id>]
8
- // stdin {"type":"user","text"} · {"type":"interrupt","id"} · {"type":"title",…} (ignored:
9
- // Vibe names its sessions itself, and the runner says so when it does) ; closed = the
10
- // session ends after its turn
11
- // stdout **our** vocabulary (`agent-v1`): each `session/update` and each turn's answer read
12
- // here (`./mistral/adapter.ts`), with the ACP message itself as `source`
13
- // env SPUNTO_AGENT_OPTIONS — the task's parameters (`./catalogs.ts`): `{"thinking":"high"}`
14
- // SPUNTO_AGENT_MCP — the org's MCP servers, through the platform's gateway (RFC 0049)
15
- // SPUNTO_AGENT_STREAM — "1": also print each chunk of a message as it is written
16
- // exit 0 once the input is closed and the last turn is over, 1 when the session could not run
17
- //
18
- // One `vibe-acp` process is the whole session: it stays alive between turns, a message sent during
19
- // a turn waits for it to end (ACP runs one prompt at a time), and an interrupt is ACP's own
20
- // `session/cancel` — the tool in flight is stopped, the turn ends `cancelled`, the session listens.
21
- //
22
- // Credentials: `MISTRAL_API_KEY` as a secret, read by Vibe itself — or a `vibe --setup` done by
23
- // hand in the machine's terminal, which Vibe keeps in `~/.vibe`.
24
-
25
- import { spawn } from "node:child_process"
26
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
27
- import { homedir } from "node:os"
28
- import { join } from "node:path"
29
- import { createInterface } from "node:readline"
30
- import { mistralTranslator } from "./mistral/adapter"
31
-
32
- const ACP = process.env.SPUNTO_VIBE_ACP || "/opt/spunto/agents/mistral/bin/vibe-acp"
33
-
34
- function out(obj) {
35
- process.stdout.write(`${JSON.stringify(obj)}\n`)
36
- }
37
-
38
- /** A failure the platform can read: the turn ends, failed, saying why — then a non-zero exit. */
39
- function fail(message) {
40
- out({ type: "session.ended", status: "failed", stopReason: null, summary: message })
41
- child?.kill()
42
- process.exit(1)
43
- }
44
-
45
- function parseArgs(argv) {
46
- const [verb, ...rest] = argv
47
- if (verb !== "run") fail(`mistral runner: unknown verb "${verb ?? ""}" (expected "run")`)
48
- const args = {}
49
- for (let i = 0; i < rest.length; i++) {
50
- const flag = rest[i]
51
- if (flag === "--model" || flag === "--resume") {
52
- const value = rest[++i]
53
- if (value) args[flag.slice(2)] = value
54
- } else {
55
- fail(`mistral runner: unknown flag "${flag}"`)
56
- }
57
- }
58
- return args
59
- }
60
-
61
- let child = null
62
- const args = parseArgs(process.argv.slice(2))
63
-
64
- /** The task's parameters. Checked by the platform against the catalog; read defensively all the same. */
65
- function readOptions() {
66
- try {
67
- const parsed = JSON.parse(process.env.SPUNTO_AGENT_OPTIONS || "{}")
68
- return parsed && typeof parsed === "object" ? parsed : {}
69
- } catch {
70
- return {}
71
- }
72
- }
73
- const params = readOptions()
74
-
75
- /**
76
- * The org's MCP servers (RFC 0049), as ACP's `mcpServers`: Streamable HTTP servers on the
77
- * platform's gateway, with the machine's identity as the bearer — never the vendor's token.
78
- */
79
- function readMcpServers() {
80
- let listed
81
- try {
82
- listed = JSON.parse(process.env.SPUNTO_AGENT_MCP || "[]")
83
- } catch {
84
- return []
85
- }
86
- const api = (process.env.SPUNTO_API_URL || "").replace(/\/$/, "")
87
- const token = process.env.SPUNTO_WORKER_TOKEN
88
- if (!Array.isArray(listed) || !api || !token) return []
89
- return listed
90
- .filter((s) => s && typeof s.name === "string" && typeof s.path === "string")
91
- .map((s) => ({ type: "http", name: s.name, url: `${api}${s.path}`, headers: [{ name: "Authorization", value: `Bearer ${token}` }] }))
92
- }
93
-
94
- /**
95
- * Trust the task's checkout, as Vibe's own prompt would on a first run: an untrusted folder's
96
- * `AGENTS.md`, `.vibe/` config and skills are ignored — the session would not behave like the CLI
97
- * in that repository. Nobody is there to answer the prompt, and the machine is the task's.
98
- */
99
- function trustCwd(cwd) {
100
- try {
101
- const home = process.env.VIBE_HOME || join(homedir(), ".vibe")
102
- const file = join(home, "trusted_folders.toml")
103
- const text = existsSync(file) ? readFileSync(file, "utf8") : ""
104
- const entry = JSON.stringify(cwd)
105
- if (text.includes(entry)) return
106
- mkdirSync(home, { recursive: true })
107
- const list = /^trusted\s*=\s*\[/m
108
- writeFileSync(file, list.test(text) ? text.replace(list, (m) => `${m}${entry}, `) : `trusted = [${entry}]\n${text}`)
109
- } catch (err) {
110
- process.stderr.write(`mistral runner: could not trust ${cwd}: ${err?.message ?? err}\n`)
111
- }
112
- }
113
-
114
- /**
115
- * A session being resumed is the platform's to hold, so any `vibe-acp` still holding it is let go.
116
- * Measured: after the API restarted, it resumed a task's session in a new runner while the old one
117
- * still ran — and Vibe opens a session once (an OS lock, `logs/session/active/<id>.lock`), so the
118
- * new one failed on "Session is already open". The holder is named in the lease's diagnostic file;
119
- * it is stopped only if it is a Vibe (a pid can be reused), and its runner exits with it.
120
- */
121
- async function releaseSession(id) {
122
- const home = process.env.VIBE_HOME || join(homedir(), ".vibe")
123
- const lease = join(home, "logs", "session", "active", `${id}.lock.json`)
124
- let pid
125
- try {
126
- pid = JSON.parse(readFileSync(lease, "utf8")).process_id
127
- } catch {
128
- return
129
- }
130
- if (!Number.isInteger(pid) || pid === process.pid) return
131
- try {
132
- if (!readFileSync(`/proc/${pid}/cmdline`, "utf8").includes("vibe")) return
133
- process.kill(pid, "SIGTERM")
134
- } catch {
135
- return // gone already
136
- }
137
- process.stderr.write(`mistral runner: stopped the Vibe (pid ${pid}) still holding session ${id}\n`)
138
- for (let i = 0; i < 50; i++) {
139
- try {
140
- process.kill(pid, 0)
141
- } catch {
142
- return
143
- }
144
- await new Promise((resolve) => setTimeout(resolve, 100))
145
- }
146
- try {
147
- process.kill(pid, "SIGKILL")
148
- } catch {}
149
- }
150
-
151
- const cwd = process.cwd()
152
- trustCwd(cwd)
153
- if (args.resume) await releaseSession(args.resume)
154
-
155
- // `vibe-acp`, or a test double of it (`.mjs`, run on this Node).
156
- child = /\.m?js$/.test(ACP)
157
- ? spawn(process.execPath, [ACP], { stdio: ["pipe", "pipe", "pipe"] })
158
- : spawn(ACP, [], { stdio: ["pipe", "pipe", "pipe"] })
159
-
160
- // Vibe logs freely on stderr; the tail is kept to say why, should it die.
161
- let stderrTail = ""
162
- child.stderr.on("data", (d) => {
163
- stderrTail = (stderrTail + d).slice(-4000)
164
- })
165
- child.on("error", (err) => {
166
- fail(`mistral runner: could not start Mistral Vibe at ${ACP} — is the project's image built with the Mistral app's feature? (${err?.message ?? err})`)
167
- })
168
- let closing = false
169
- child.on("exit", (code) => {
170
- if (closing) return
171
- const tail = stderrTail.trim().split("\n").slice(-5).join("\n")
172
- fail(`mistral runner: Mistral Vibe exited (${code}) during the session${tail ? `: ${tail}` : ""}`)
173
- })
174
-
175
- // ── JSON-RPC over the child's stdio ─────────────────────────────────────────────────────────────
176
-
177
- let nextId = 0
178
- const waiting = new Map()
179
- /**
180
- * `session/update`s are dropped until the first turn: while Vibe replays a loaded session's history
181
- * (`session/load` — the platform has it), and while the runner sets the session up (a model change
182
- * is announced as a pseudo tool call, `checkpoint-model-change`, which no one asked for).
183
- */
184
- let quiet = true
185
- const translate = mistralTranslator({ stream: process.env.SPUNTO_AGENT_STREAM === "1" })
186
-
187
- function send(message) {
188
- child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`)
189
- }
190
-
191
- /** A request; resolves with the whole response, `{ result }` or `{ error }`. */
192
- function request(method, params) {
193
- const id = ++nextId
194
- send({ id, method, params })
195
- return new Promise((resolve) => waiting.set(id, resolve))
196
- }
197
-
198
- /** Vibe asking the client: permissions are granted (nobody is there to answer), the rest refused. */
199
- function answer(message) {
200
- if (message.method === "session/request_permission") {
201
- const options = Array.isArray(message.params?.options) ? message.params.options : []
202
- const pick = options.find((o) => o.kind === "allow_always") ?? options.find((o) => o.kind === "allow_once")
203
- send({ id: message.id, result: { outcome: pick ? { outcome: "selected", optionId: pick.optionId } : { outcome: "cancelled" } } })
204
- return
205
- }
206
- send({ id: message.id, error: { code: -32601, message: `${message.method} is not offered by the Spunto runner` } })
207
- }
208
-
209
- createInterface({ input: child.stdout, crlfDelay: Infinity }).on("line", (line) => {
210
- let message
211
- try {
212
- message = JSON.parse(line)
213
- } catch {
214
- return
215
- }
216
- if (!message || typeof message !== "object") return
217
- if (message.method && message.id !== undefined && message.id !== null) return answer(message)
218
- if (message.method === "session/update") {
219
- const update = message.params?.update
220
- // Only the window's figures are kept from the setup: they are the session's own.
221
- if (update && (!quiet || update.sessionUpdate === "usage_update")) for (const l of translate.update(update)) out(l)
222
- return
223
- }
224
- if (message.method) return // other notifications (`_vibe/…` extensions): Vibe's UI, not the session
225
- const resolve = waiting.get(message.id)
226
- if (resolve) {
227
- waiting.delete(message.id)
228
- resolve(message)
229
- }
230
- })
231
-
232
- // ── The session ─────────────────────────────────────────────────────────────────────────────────
233
-
234
- const init = await request("initialize", {
235
- protocolVersion: 1,
236
- // No file system, no terminal: Vibe uses its own tools in the machine, where the task's work is.
237
- clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
238
- clientInfo: { name: "spunto", title: "Spunto", version: "agent-v1" },
239
- })
240
- if (init.error) fail(`mistral runner: Mistral Vibe refused to start: ${init.error.message}`)
241
-
242
- const mcpServers = readMcpServers()
243
- let sessionId = args.resume ?? null
244
- let opened
245
- if (args.resume) {
246
- opened = await request("session/load", { sessionId: args.resume, cwd, mcpServers })
247
- } else {
248
- opened = await request("session/new", { cwd, mcpServers })
249
- sessionId = opened.result?.sessionId ?? null
250
- }
251
- if (opened.error || !sessionId) {
252
- const why = opened.error?.message ?? "no session id"
253
- const hint = opened.error?.code === -32000 ? " — set MISTRAL_API_KEY in your secrets, or run `vibe --setup` in the machine's terminal" : ""
254
- fail(`mistral runner: Mistral Vibe could not ${args.resume ? `resume session ${args.resume}` : "open a session"}: ${why}${hint}`)
255
- }
256
-
257
- /** The current value of one of the session's options (`model`, `thinking`, `mode`). */
258
- let configOptions = opened.result?.configOptions ?? []
259
- const optionValue = (id) => configOptions.find((o) => o?.id === id)?.currentValue ?? null
260
-
261
- async function setOption(configId, value, what) {
262
- const res = await request("session/set_config_option", { sessionId, configId, value })
263
- if (res.error) {
264
- const choices = configOptions.find((o) => o?.id === configId)?.options?.map((o) => o.value) ?? []
265
- fail(`mistral runner: ${what} "${value}" is not available here${choices.length ? ` — one of ${choices.join(", ")}` : ""} (${res.error.message})`)
266
- }
267
- configOptions = res.result?.configOptions ?? configOptions
268
- }
269
-
270
- // A task runs unattended in a disposable machine: every tool call approved, what
271
- // `bypassPermissions` is to Claude. Vibe's own name for it.
272
- await setOption("mode", "auto-approve", "Mode")
273
- if (args.model && optionValue("model") !== args.model) await setOption("model", args.model, "Model")
274
- // Vibe keeps a model's thinking level in its config: set on every session that asks for one.
275
- if (typeof params.thinking === "string" && params.thinking) await setOption("thinking", params.thinking, "Thinking")
276
-
277
- const model = optionValue("model") ?? args.model ?? null
278
- translate.model = model
279
-
280
- let announced = false
281
- function announce() {
282
- if (announced) return
283
- announced = true
284
- quiet = false
285
- out({ type: "session.started", harness: "mistral", model, sessionId, cwd, contextWindow: translate.window.size })
286
- }
287
-
288
- const pending = []
289
- let closed = false
290
- let inFlight = false
291
- let wake = null
292
-
293
- createInterface({ input: process.stdin, crlfDelay: Infinity })
294
- .on("line", (line) => {
295
- let msg
296
- try {
297
- msg = JSON.parse(line)
298
- } catch {
299
- return
300
- }
301
- if (!msg || typeof msg !== "object") return
302
- if (msg.type === "user" && typeof msg.text === "string") {
303
- pending.push(msg.text)
304
- wake?.()
305
- } else if (msg.type === "interrupt" && inFlight) {
306
- cancel()
307
- }
308
- })
309
- .on("close", () => {
310
- closed = true
311
- wake?.()
312
- })
313
-
314
- /**
315
- * ACP's cancel, a notification. Said again every second until the turn answers: one that lands
316
- * before Vibe has started the turn would otherwise be lost, and the turn would run to its end.
317
- */
318
- function cancel() {
319
- const again = () => {
320
- if (!inFlight) return clearInterval(timer)
321
- send({ method: "session/cancel", params: { sessionId } })
322
- }
323
- const timer = setInterval(again, 1000)
324
- again()
325
- }
326
-
327
- for (;;) {
328
- if (pending.length === 0) {
329
- if (closed) break
330
- await new Promise((resolve) => (wake = resolve))
331
- wake = null
332
- continue
333
- }
334
- const text = pending.shift()
335
- announce()
336
- translate.prompted(text)
337
- inFlight = true
338
- const response = await request("session/prompt", { sessionId, prompt: [{ type: "text", text }] })
339
- inFlight = false
340
- for (const l of translate.ended(response)) out(l)
341
- }
342
-
343
- closing = true
344
- child.stdin.end()
345
- await new Promise((resolve) => {
346
- const timer = setTimeout(() => {
347
- child.kill()
348
- resolve()
349
- }, 5000)
350
- child.once("exit", () => {
351
- clearTimeout(timer)
352
- resolve()
353
- })
354
- })
355
- process.exit(0)
@@ -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
- }