@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,116 +0,0 @@
1
- /**
2
- * Agent apps (RFC 0048): what it takes to run a harness in a machine, on both sides of the seam.
3
- *
4
- * An agent app is three things, and this module is where they meet:
5
- *
6
- * - a **feature** the platform injects into the image of every project that picks the app — it
7
- * installs a private Node and the harness's **official SDK** (with the binary the SDK drives)
8
- * under `/opt/spunto/agents/<id>`. Shipped by the platform itself (`localScript`), so an app
9
- * never waits on a registry release;
10
- * - a **runner**, a `.mjs` entry of ours (`claude.mjs`, `codex.mjs`, `mistral.mjs`) with its harness's
11
- * adapter next to it (`claude/adapter.ts`, `codex/adapter.ts`, `mistral/adapter.ts`). The caller **bundles** the two into one
12
- * file (esbuild, `platform: node`, `format: esm`) and writes it into the machine at the moment a
13
- * session starts. Not baked: a runner fix reaches the next session, not the next rebuild;
14
- * - the **Spunto agent contract** (`agent-v1`, `../agent-contract`), which is how the platform
15
- * writes the runner's stdin and reads its stdout — the same for every app.
16
- *
17
- * The runner contract, identical for every app (docs/agent-contract.md):
18
- *
19
- * <node> <runner>.mjs run [--model <id>] [--resume <session id>]
20
- * stdin one JSON object per line: {"type":"user","text"} · {"type":"interrupt","id"} ·
21
- * {"type":"title","id","description"} (`RunnerInput`); closed ⇒ end after the turn
22
- * env SPUNTO_AGENT_OPTIONS — the task's parameters (`./catalogs.ts`), one JSON object
23
- * stdout our vocabulary, one JSON object per line, each event with its harness message as `source`
24
- * exit 0 = the input closed and the last turn ended; ≠ 0 = the session could not run, and its
25
- * last line is a failed `session.ended` saying why
26
- *
27
- * Pure like the rest of the package: what a caller gets is *where* a runner entry is, and the shell
28
- * that starts it. Bundling and reading the file are the caller's I/O.
29
- */
30
-
31
- import type { AgentProtocol } from "../agent-stream/agent-stream"
32
-
33
- import { AGENT_HOME } from "./features"
34
-
35
- /** The Node every runner runs on — the private one the features install. */
36
- export const AGENT_NODE = `${AGENT_HOME}/node/bin/node`
37
-
38
- export type AgentHarnessId = "claude" | "codex" | "mistral"
39
-
40
- export type AgentHarness = {
41
- id: AgentHarnessId
42
- /** The catalog id of the feature the platform injects (`AVAILABLE_FEATURES`, `localScript`). */
43
- featureId: string
44
- /** How the platform talks to the runner — the contract, for every app. */
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
- /** The runner's entry, a file of this package — to be bundled with what it imports. */
53
- runnerFile: URL
54
- /** Where the harness looks for user-level skills (RFC 0033), as shell evaluated in the machine. */
55
- skillDirs: string[]
56
- }
57
-
58
- export const AGENT_HARNESSES: Record<AgentHarnessId, AgentHarness> = {
59
- claude: {
60
- id: "claude",
61
- featureId: "spunto-agent-claude",
62
- protocol: "agent-v1",
63
- legacyProtocol: "claude-runner",
64
- runnerFile: new URL("./claude.mjs", import.meta.url),
65
- skillDirs: ["${CLAUDE_CONFIG_DIR:-$HOME/.claude}/skills"],
66
- },
67
- codex: {
68
- id: "codex",
69
- featureId: "spunto-agent-codex",
70
- protocol: "agent-v1",
71
- legacyProtocol: "codex-runner",
72
- runnerFile: new URL("./codex.mjs", import.meta.url),
73
- skillDirs: ["${CODEX_HOME:-$HOME/.codex}/skills"],
74
- },
75
- mistral: {
76
- id: "mistral",
77
- featureId: "spunto-agent-mistral",
78
- protocol: "agent-v1",
79
- legacyProtocol: "agent-v1",
80
- runnerFile: new URL("./mistral.mjs", import.meta.url),
81
- skillDirs: ["${VIBE_HOME:-$HOME/.vibe}/skills"],
82
- },
83
- }
84
-
85
- /** The variable a runner's text travels in, base64 — see `runnerCommand`. */
86
- export const RUNNER_ENV = "SPUNTO_AGENT_RUNNER"
87
-
88
- /**
89
- * The shell that starts a session: write the runner out of `$SPUNTO_AGENT_RUNNER` (base64, set by
90
- * the caller in the command's environment), then `exec` it on the feature's Node so the session
91
- * *is* the runner — stdin, signals and exit code included.
92
- *
93
- * The text rides in the environment rather than in the command because the command is what the
94
- * platform shows ("what the platform ran"): eight kilobytes of base64 there would bury the one line
95
- * worth reading. `--model` is appended by the platform like for any harness; `resume` adds the
96
- * session the platform read off the stream, passed as `$SPUNTO_TASK_SESSION_ID`.
97
- *
98
- * Only the app's id is needed (it names the file): the platform calls this for apps it learns of by
99
- * their manifest, outside this package (RFC 0057).
100
- */
101
- export function runnerCommand(harness: Pick<AgentHarness, "id"> | { id: string }, opts: { resume?: boolean } = {}): string {
102
- const file = `"$HOME/.spunto/agents/${harness.id}.mjs"`
103
- return [
104
- `mkdir -p "$HOME/.spunto/agents" && printf %s "$${RUNNER_ENV}" | base64 -d > ${file} && unset ${RUNNER_ENV} &&`,
105
- `exec ${AGENT_NODE} ${file} run${opts.resume ? ` --resume "$SPUNTO_TASK_SESSION_ID"` : ""}`,
106
- ].join(" ")
107
- }
108
-
109
- /** The harness an injected feature id belongs to, if any. */
110
- export function harnessOfFeature(featureId: string): AgentHarness | null {
111
- return Object.values(AGENT_HARNESSES).find((h) => h.featureId === featureId) ?? null
112
- }
113
-
114
- export { AGENT_FEATURE_SCRIPTS, AGENT_HOME, AGENT_NODE_VERSION, MISTRAL_VIBE_VERSION } from "./features"
115
- export { AGENT_CATALOGS, MCP_ENV, OPTIONS_ENV, STREAM_ENV, agentOptionsError } from "./catalogs"
116
- export type { AgentCatalog, AgentMcpServer, AgentModel, AgentParam, AgentParamValue } from "./catalogs"
@@ -1,219 +0,0 @@
1
- /**
2
- * Mistral Vibe's dialect, read into our vocabulary — the **Agent Client Protocol** (ACP) that
3
- * `vibe-acp` speaks on stdio: the `session/update` notifications of a turn, and the answer to its
4
- * `session/prompt`. Written against what Vibe 3.0.4 printed on 2026-10-31, against the real API
5
- * (`test/fixtures/fake-vibe-acp.mjs` replays those messages, shortened, never reshaped).
6
- *
7
- * Lives with the Mistral runner (RFC 0048 § 9): the runner bundles it and prints the contract.
8
- *
9
- * What ACP is like, and why the translator keeps state:
10
- *
11
- * - text arrives in **chunks** (`agent_message_chunk`, `agent_thought_chunk`), each naming the
12
- * message it belongs to (`messageId`). A finished `message` / `thinking` is printed when the
13
- * message is over — another one starts, a tool is called, the turn ends — with the chunks joined
14
- * as its `source`. Under `SPUNTO_AGENT_STREAM`, each chunk is also a `message.delta`;
15
- * - a tool is a `tool_call` (`in_progress`, with its `rawInput`) then a `tool_call_update` that
16
- * settles it (`completed` / `failed`) — the pair is our `tool.call` / `tool.result`;
17
- * - usage is restated by Vibe after every step (`usage_update`: how full the window is, how large
18
- * it is, the session's cost), and the turn's answer carries the **session's** running token
19
- * totals (measured: the second turn's `inputTokens` include the first's, a resumed session's
20
- * too). So it is one `usage` of scope `session` per turn, the latest winning;
21
- * - the turn's end is the answer to `session/prompt`: a `stopReason`, or a JSON-RPC error.
22
- */
23
-
24
- import { clip } from "../../agent-contract/vocabulary"
25
-
26
- type Obj = Record<string, unknown>
27
- export type ContractLine = Record<string, unknown>
28
-
29
- function obj(value: unknown): Obj {
30
- return value && typeof value === "object" && !Array.isArray(value) ? (value as Obj) : {}
31
- }
32
-
33
- function num(value: unknown): number | null {
34
- return typeof value === "number" && Number.isFinite(value) ? value : null
35
- }
36
-
37
- function str(value: unknown): string | null {
38
- return typeof value === "string" && value ? value : null
39
- }
40
-
41
- /** The text of an ACP tool's `content` (its `content` blocks of text; diffs are the call's, not its output). */
42
- function contentText(content: unknown): string {
43
- if (!Array.isArray(content)) return ""
44
- return content
45
- .map((c) => obj(c))
46
- .filter((c) => c.type === "content" && obj(c.content).type === "text")
47
- .map((c) => String(obj(c.content).text ?? ""))
48
- .join("\n")
49
- }
50
-
51
- /** A tool's name as the agent knows it: Vibe's own (`bash`, `write_file`…), else ACP's kind. */
52
- function toolName(update: Obj): string {
53
- return str(obj(update._meta).tool_name) ?? str(update.kind) ?? str(update.title) ?? "tool"
54
- }
55
-
56
- /** Vibe's application error codes (`vibe/acp/exceptions.py`) the contract has a word for. */
57
- const RATE_LIMITED = -31001
58
-
59
- export type MistralTranslator = {
60
- /** One `session/update` notification's `update`. */
61
- update(update: Obj): ContractLine[]
62
- /** The answer to `session/prompt` — `{ result }` or `{ error }` — which ends the turn. */
63
- ended(response: Obj): ContractLine[]
64
- /** What Vibe said of the window last: how full, how large (for `session.started`). */
65
- readonly window: { used: number | null; size: number | null }
66
- /** The session's model, once the runner has set it — named on each turn's `usage`. */
67
- model: string | null
68
- /** The human's turn, as sent: Vibe's first "title" is a copy of it, said before the echo. */
69
- prompted(text: string): void
70
- }
71
-
72
- export function mistralTranslator(opts: { stream?: boolean } = {}): MistralTranslator {
73
- /** The text being written: one message (or thought) at a time, by `messageId`. */
74
- let open: { kind: "message" | "thinking"; id: string | null; text: string; update: Obj } | null = null
75
- /** Tool calls already settled — an update after the result says nothing new. */
76
- const settled = new Set<string>()
77
- /** The human's own words this session, to tell Vibe's own title from a copy of the prompt. */
78
- const said: string[] = []
79
- let lastTitle: string | null = null
80
- const window = { used: null as number | null, size: null as number | null }
81
- let costUsd: number | null = null
82
-
83
- function flush(): ContractLine[] {
84
- if (!open) return []
85
- const { kind, text, update } = open
86
- open = null
87
- const clipped = clip(text)
88
- if (!clipped.text.trim()) return []
89
- // The chunks joined: what Vibe wrote, in one piece — the event's own words.
90
- const source = { ...update, content: { type: "text", text } }
91
- return kind === "message"
92
- ? [{ type: "message", role: "assistant", text: clipped.text, truncated: clipped.truncated, source }]
93
- : [{ type: "thinking", text: clipped.text, truncated: clipped.truncated, source }]
94
- }
95
-
96
- function chunk(kind: "message" | "thinking", update: Obj): ContractLine[] {
97
- const text = typeof obj(update.content).text === "string" ? (obj(update.content).text as string) : ""
98
- const id = str(update.messageId)
99
- const out: ContractLine[] = []
100
- const fresh = !open || open.kind !== kind || open.id !== id
101
- if (fresh) {
102
- out.push(...flush())
103
- open = { kind, id, text: "", update }
104
- }
105
- open!.text += text
106
- if (kind === "message" && opts.stream && text) out.push({ type: "message.delta", text, ...(fresh ? { start: true } : {}) })
107
- return out
108
- }
109
-
110
- function result(update: Obj, id: string): ContractLine[] {
111
- settled.add(id)
112
- const raw = update.rawOutput
113
- const text = contentText(update.content) || (typeof raw === "string" ? raw : raw === undefined ? "" : JSON.stringify(raw))
114
- const { text: output, truncated } = clip(text)
115
- return [{ type: "tool.result", callId: id, isError: update.status === "failed", output, truncated, source: update }]
116
- }
117
-
118
- const self: MistralTranslator = {
119
- window,
120
- model: null,
121
- prompted(text) {
122
- said.push(text)
123
- },
124
- update(update) {
125
- switch (update.sessionUpdate) {
126
- case "agent_message_chunk":
127
- return chunk("message", update)
128
- case "agent_thought_chunk":
129
- return chunk("thinking", update)
130
- case "user_message_chunk": {
131
- // The human's own turn, echoed: the platform already has it. Kept to read the title by.
132
- const text = obj(update.content).text
133
- if (typeof text === "string") said.push(text)
134
- return []
135
- }
136
- case "tool_call": {
137
- const id = str(update.toolCallId)
138
- const { text: input, truncated } = clip(update.rawInput ?? { title: update.title })
139
- const out: ContractLine[] = [...flush(), { type: "tool.call", callId: id, name: toolName(update), input, truncated, source: update }]
140
- if (id && (update.status === "completed" || update.status === "failed")) out.push(...result(update, id))
141
- return out
142
- }
143
- case "tool_call_update": {
144
- const id = str(update.toolCallId)
145
- if (!id || settled.has(id) || (update.status !== "completed" && update.status !== "failed")) return []
146
- return [...flush(), ...result(update, id)]
147
- }
148
- case "plan": {
149
- const steps = (Array.isArray(update.entries) ? update.entries : [])
150
- .map((e) => obj(e))
151
- .map((e) => ({ text: clip(e.content).text, status: typeof e.status === "string" ? e.status : "pending" }))
152
- .filter((s) => s.text)
153
- return steps.length > 0 ? [...flush(), { type: "plan", steps, source: update }] : []
154
- }
155
- case "usage_update": {
156
- window.used = num(update.used) ?? window.used
157
- window.size = num(update.size) ?? window.size
158
- const cost = obj(update.cost)
159
- if (cost.currency === "USD" && num(cost.amount) !== null) costUsd = num(cost.amount)
160
- return []
161
- }
162
- case "session_info_update": {
163
- // Vibe names a session after the first prompt until it has a title of its own: only the
164
- // latter is a name worth saying (the platform already has the prompt's).
165
- // latter is a name worth saying (the platform already has the prompt's). Measured: the
166
- // provisional one is the whole prompt, then « … ».
167
- const title = str(update.title)?.replace(/\s+/g, " ").trim().slice(0, 200) ?? null
168
- const stem = title?.replace(/(…|\.\.\.)$/, "").trim()
169
- if (!title || !stem || title === lastTitle || said.some((s) => s.replace(/\s+/g, " ").trim().startsWith(stem))) return []
170
- lastTitle = title
171
- return [{ type: "session.title", title, source: update }]
172
- }
173
- // The session's slash commands, its mode, its options: Vibe's UI state, not the session's.
174
- case "available_commands_update":
175
- case "current_mode_update":
176
- case "config_option_update":
177
- return []
178
- }
179
- return [...flush(), { type: "raw", json: update }]
180
- },
181
- ended(response) {
182
- const out = flush()
183
- const error = response.error ? obj(response.error) : null
184
- if (error) {
185
- const message = clip(str(error.message) ?? "Mistral Vibe failed the turn.").text
186
- const limit = error.code === RATE_LIMITED ? { kind: "rate", status: 429, message, resetsAt: null } : null
187
- out.push({ type: "session.ended", status: "failed", stopReason: null, summary: message, ...(limit ? { limit } : {}), source: response })
188
- return out
189
- }
190
- const res = obj(response.result)
191
- const usage = obj(res.usage)
192
- if (Object.keys(usage).length > 0 || window.used !== null) {
193
- out.push({
194
- type: "usage",
195
- scope: "session",
196
- model: self.model,
197
- inputTokens: num(usage.inputTokens),
198
- outputTokens: num(usage.outputTokens),
199
- cacheReadTokens: num(usage.cachedReadTokens),
200
- contextTokens: window.used,
201
- contextWindow: window.size,
202
- costUsd,
203
- source: response,
204
- })
205
- }
206
- const stopReason = str(res.stopReason)
207
- if (stopReason === "end_turn") {
208
- out.push({ type: "session.ended", status: "succeeded", stopReason, summary: "", source: response })
209
- } else {
210
- // `cancelled` (an interrupt), `max_tokens`, `max_turn_requests`, `refusal`: the turn did
211
- // not finish its work, whatever the reason — the same reading as Claude's and Codex's.
212
- const summary = stopReason === "cancelled" ? "Interrupted." : `Mistral Vibe stopped the turn (${stopReason ?? "no reason given"}).`
213
- out.push({ type: "session.ended", status: "failed", stopReason, summary, source: response })
214
- }
215
- return out
216
- },
217
- }
218
- return self
219
- }