@spunto/build 0.30.0 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -18
- package/package.json +2 -9
- package/src/agent-contract/index.ts +7 -1
- package/src/agent-contract/runner.ts +124 -0
- package/src/agent-contract/vocabulary.ts +30 -2
- package/src/agent-stream/agent-stream.ts +41 -235
- package/src/agent-stream/draft.ts +6 -91
- package/src/agent-stream/index.ts +10 -39
- package/src/catalogs/index.ts +0 -22
- package/src/script/local-features.ts +0 -4
- package/src/spec/index.ts +2 -3
- package/src/agent-runners/catalogs.ts +0 -183
- package/src/agent-runners/claude/adapter.ts +0 -633
- package/src/agent-runners/claude.mjs +0 -245
- package/src/agent-runners/codex/adapter.ts +0 -135
- package/src/agent-runners/codex.mjs +0 -178
- package/src/agent-runners/features.ts +0 -109
- package/src/agent-runners/index.ts +0 -116
- package/src/agent-runners/mistral/adapter.ts +0 -219
- package/src/agent-runners/mistral.mjs +0 -355
- package/src/agent-stream/model-window.ts +0 -192
- package/src/agent-stream/turn-limit.ts +0 -197
|
@@ -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 "../agent-stream/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)
|
|
@@ -1,135 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Codex's dialect, read into our vocabulary — the events of `@openai/codex-sdk`'s `runStreamed()`
|
|
3
|
-
* (`ThreadEvent`). Written against the SDK's own types (0.164.0).
|
|
4
|
-
*
|
|
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.
|
|
8
|
-
*
|
|
9
|
-
* Codex works per **turn**, not per session: `turn.completed` is a hand-back the way Claude's
|
|
10
|
-
* `result` is, so it ends the turn here too. Its usage is the turn's sum, which is why it is filed
|
|
11
|
-
* as a `call` (summed over the task) without a `contextTokens`: no single number of it is the
|
|
12
|
-
* size of the prompt last sent.
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
import { clip, type NormalizedEvent } from "../../agent-contract/vocabulary"
|
|
16
|
-
|
|
17
|
-
function num(value: unknown): number | null {
|
|
18
|
-
return typeof value === "number" && Number.isFinite(value) ? value : null
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export function adaptCodex(obj: Record<string, unknown>): NormalizedEvent[] {
|
|
22
|
-
const type = obj.type
|
|
23
|
-
if (type === "thread.started") {
|
|
24
|
-
return [{ type: "session.started", payload: { harness: "codex", model: null, sessionId: typeof obj.thread_id === "string" ? obj.thread_id : null } }]
|
|
25
|
-
}
|
|
26
|
-
if (type === "turn.started") return []
|
|
27
|
-
if (type === "turn.completed") {
|
|
28
|
-
const u = (obj.usage ?? {}) as Record<string, unknown>
|
|
29
|
-
return [
|
|
30
|
-
{
|
|
31
|
-
type: "usage",
|
|
32
|
-
payload: {
|
|
33
|
-
scope: "call",
|
|
34
|
-
model: null,
|
|
35
|
-
inputTokens: num(u.input_tokens) ?? 0,
|
|
36
|
-
outputTokens: (num(u.output_tokens) ?? 0) + (num(u.reasoning_output_tokens) ?? 0),
|
|
37
|
-
cacheReadTokens: num(u.cached_input_tokens) ?? 0,
|
|
38
|
-
cacheCreationTokens: num(u.cache_write_input_tokens) ?? 0,
|
|
39
|
-
},
|
|
40
|
-
},
|
|
41
|
-
{ type: "session.ended", payload: { status: "succeeded", stopReason: null, summary: "" } },
|
|
42
|
-
]
|
|
43
|
-
}
|
|
44
|
-
if (type === "turn.failed") {
|
|
45
|
-
const error = (obj.error ?? {}) as Record<string, unknown>
|
|
46
|
-
return [{ type: "session.ended", payload: { status: "failed", stopReason: null, summary: clip(error.message).text } }]
|
|
47
|
-
}
|
|
48
|
-
// Not an end: measured, Codex emits `error` for every retry ("Reconnecting... 2/5 (401 …)") and
|
|
49
|
-
// only the `turn.failed` that follows the last one ends the turn. Kept visible, not fatal.
|
|
50
|
-
if (type === "error") return [{ type: "raw", payload: { json: obj } }]
|
|
51
|
-
if (type !== "item.started" && type !== "item.updated" && type !== "item.completed") {
|
|
52
|
-
return [{ type: "raw", payload: { json: obj } }]
|
|
53
|
-
}
|
|
54
|
-
const item = (obj.item ?? {}) as Record<string, unknown>
|
|
55
|
-
const callId = typeof item.id === "string" ? item.id : null
|
|
56
|
-
const started = type === "item.started"
|
|
57
|
-
const completed = type === "item.completed"
|
|
58
|
-
switch (item.type) {
|
|
59
|
-
case "agent_message": {
|
|
60
|
-
if (!completed) return []
|
|
61
|
-
const { text, truncated } = clip(item.text)
|
|
62
|
-
return text ? [{ type: "message", payload: { role: "assistant", text, truncated } }] : []
|
|
63
|
-
}
|
|
64
|
-
case "reasoning": {
|
|
65
|
-
if (!completed) return []
|
|
66
|
-
const { text, truncated } = clip(item.text)
|
|
67
|
-
return text ? [{ type: "thinking", payload: { text, truncated } }] : []
|
|
68
|
-
}
|
|
69
|
-
case "command_execution": {
|
|
70
|
-
if (started) {
|
|
71
|
-
const { text: input, truncated } = clip({ command: item.command })
|
|
72
|
-
return [{ type: "tool.call", payload: { callId, name: "Bash", input, truncated } }]
|
|
73
|
-
}
|
|
74
|
-
if (!completed) return []
|
|
75
|
-
const { text: output, truncated } = clip(item.aggregated_output)
|
|
76
|
-
const failed = item.status === "failed" || (typeof item.exit_code === "number" && item.exit_code !== 0)
|
|
77
|
-
return [{ type: "tool.result", payload: { callId, isError: failed, output, truncated } }]
|
|
78
|
-
}
|
|
79
|
-
case "file_change": {
|
|
80
|
-
// Reported once, applied: the call and its outcome arrive together.
|
|
81
|
-
if (!completed) return []
|
|
82
|
-
const changes = Array.isArray(item.changes) ? item.changes : []
|
|
83
|
-
const { text: input, truncated } = clip({ changes })
|
|
84
|
-
const output = changes
|
|
85
|
-
.filter((c): c is Record<string, unknown> => !!c && typeof c === "object")
|
|
86
|
-
.map((c) => `${c.kind} ${c.path}`)
|
|
87
|
-
.join("\n")
|
|
88
|
-
return [
|
|
89
|
-
{ type: "tool.call", payload: { callId, name: "Edit", input, truncated } },
|
|
90
|
-
{ type: "tool.result", payload: { callId, isError: item.status === "failed", output, truncated: false } },
|
|
91
|
-
]
|
|
92
|
-
}
|
|
93
|
-
case "mcp_tool_call": {
|
|
94
|
-
const name = `${typeof item.server === "string" ? item.server : "mcp"}.${typeof item.tool === "string" ? item.tool : "tool"}`
|
|
95
|
-
if (started) {
|
|
96
|
-
const { text: input, truncated } = clip(item.arguments)
|
|
97
|
-
return [{ type: "tool.call", payload: { callId, name, input, truncated } }]
|
|
98
|
-
}
|
|
99
|
-
if (!completed) return []
|
|
100
|
-
const error = (item.error ?? null) as Record<string, unknown> | null
|
|
101
|
-
const { text: output, truncated } = clip(error ? error.message : (item.result as Record<string, unknown> | undefined)?.content ?? "")
|
|
102
|
-
return [{ type: "tool.result", payload: { callId, isError: !!error || item.status === "failed", output, truncated } }]
|
|
103
|
-
}
|
|
104
|
-
case "web_search": {
|
|
105
|
-
if (!started) return []
|
|
106
|
-
const { text: input, truncated } = clip({ query: item.query })
|
|
107
|
-
return [{ type: "tool.call", payload: { callId, name: "WebSearch", input, truncated } }]
|
|
108
|
-
}
|
|
109
|
-
case "todo_list": {
|
|
110
|
-
const steps = (Array.isArray(item.items) ? item.items : [])
|
|
111
|
-
.filter((t): t is Record<string, unknown> => !!t && typeof t === "object")
|
|
112
|
-
.map((t) => ({ text: clip(t.text).text, status: t.completed === true ? "completed" : "pending" }))
|
|
113
|
-
.filter((s) => s.text)
|
|
114
|
-
return steps.length > 0 ? [{ type: "plan", payload: { steps } }] : []
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
return [{ type: "raw", payload: { json: obj } }]
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
/**
|
|
121
|
-
* An `agent_message` item being written, as the contract's transient `message.delta`. Codex hands
|
|
122
|
-
* the whole text so far on `item.started` / `item.updated`, not a delta, so every one opens the
|
|
123
|
-
* draft afresh with it (`start`); the completed item, stored as the `message`, closes it.
|
|
124
|
-
*/
|
|
125
|
-
export function codexDelta(obj: Record<string, unknown>): Record<string, unknown>[] {
|
|
126
|
-
if (obj.type !== "item.started" && obj.type !== "item.updated") return []
|
|
127
|
-
const item = (obj.item ?? {}) as Record<string, unknown>
|
|
128
|
-
if (item.type !== "agent_message" || typeof item.text !== "string" || !item.text) return []
|
|
129
|
-
return [{ type: "message.delta", start: true, text: item.text }]
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/** One `ThreadEvent`, as the lines of the contract the Codex runner prints, each with the event as `source`. */
|
|
133
|
-
export function codexContractLines(event: Record<string, unknown>): Record<string, unknown>[] {
|
|
134
|
-
return [...codexDelta(event), ...adaptCodex(event).map((e) => ({ type: e.type, ...e.payload, source: event }))]
|
|
135
|
-
}
|
|
@@ -1,178 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// The Codex runner (RFC 0048): same contract as `claude.mjs`, over `@openai/codex-sdk`, installed
|
|
3
|
-
// with the `codex` binary it drives by the `spunto-agent-codex` feature. Bundled with its adapter
|
|
4
|
-
// by the platform, like every runner.
|
|
5
|
-
//
|
|
6
|
-
// node codex.mjs run [--model <id>] [--resume <thread id>]
|
|
7
|
-
// stdin {"type":"user","text"} · {"type":"interrupt","id"} · {"type":"title",…} (ignored: Codex
|
|
8
|
-
// does not name its threads) ; closed = the session ends after its turn
|
|
9
|
-
// stdout **our** vocabulary (`agent-v1`): each `ThreadEvent` read here (`./codex/adapter.ts`),
|
|
10
|
-
// with the event itself as `source`
|
|
11
|
-
// env SPUNTO_AGENT_MCP — the org's MCP servers, through the platform's gateway (RFC 0049)
|
|
12
|
-
// env SPUNTO_AGENT_OPTIONS — the task's parameters (`./catalogs.ts`):
|
|
13
|
-
// `{"reasoningEffort":"high","webSearch":"live"}`
|
|
14
|
-
// exit 0 once the input is closed and the last turn is over, 1 when the session could not run
|
|
15
|
-
//
|
|
16
|
-
// Codex works turn by turn: a message that arrives while a turn runs waits for it to end, then
|
|
17
|
-
// starts the next one in the same thread — what a "queued message" already means on the platform.
|
|
18
|
-
// An interrupt aborts the turn in flight, and the runner says so with a `turn.failed`.
|
|
19
|
-
//
|
|
20
|
-
// Credentials: `OPENAI_API_KEY` (or `CODEX_API_KEY`) as a secret, or a `codex login` done by hand in
|
|
21
|
-
// the machine's terminal (`~/.codex/auth.json`), which the binary reads on its own.
|
|
22
|
-
|
|
23
|
-
import { createInterface } from "node:readline"
|
|
24
|
-
import { codexContractLines } from "./codex/adapter"
|
|
25
|
-
|
|
26
|
-
const SDK = process.env.SPUNTO_CODEX_SDK || "/opt/spunto/agents/codex/node_modules/@openai/codex-sdk/dist/index.js"
|
|
27
|
-
|
|
28
|
-
function out(obj) {
|
|
29
|
-
process.stdout.write(`${JSON.stringify(obj)}\n`)
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/** One `ThreadEvent` (or one the runner stands in for the SDK), as the contract. */
|
|
33
|
-
function emit(event) {
|
|
34
|
-
for (const line of codexContractLines(event)) out(line)
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
function fail(message) {
|
|
38
|
-
emit({ type: "turn.failed", error: { message } })
|
|
39
|
-
process.exit(1)
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function parseArgs(argv) {
|
|
43
|
-
const [verb, ...rest] = argv
|
|
44
|
-
if (verb !== "run") fail(`codex runner: unknown verb "${verb ?? ""}" (expected "run")`)
|
|
45
|
-
const args = {}
|
|
46
|
-
for (let i = 0; i < rest.length; i++) {
|
|
47
|
-
const flag = rest[i]
|
|
48
|
-
if (flag === "--model" || flag === "--resume") {
|
|
49
|
-
const value = rest[++i]
|
|
50
|
-
if (value) args[flag.slice(2)] = value
|
|
51
|
-
} else {
|
|
52
|
-
fail(`codex runner: unknown flag "${flag}"`)
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
return args
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
const args = parseArgs(process.argv.slice(2))
|
|
59
|
-
|
|
60
|
-
/** The task's parameters. Checked by the platform against the catalog; read defensively all the same. */
|
|
61
|
-
function readOptions() {
|
|
62
|
-
try {
|
|
63
|
-
const parsed = JSON.parse(process.env.SPUNTO_AGENT_OPTIONS || "{}")
|
|
64
|
-
return parsed && typeof parsed === "object" ? parsed : {}
|
|
65
|
-
} catch {
|
|
66
|
-
return {}
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
const params = readOptions()
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* The org's MCP servers (RFC 0049), as Codex's `mcp_servers` config. Each is the platform's
|
|
73
|
-
* gateway: Codex reads the machine's identity from `SPUNTO_WORKER_TOKEN` itself
|
|
74
|
-
* (`bearer_token_env_var`), and never holds the vendor's token.
|
|
75
|
-
*/
|
|
76
|
-
function readMcpServers() {
|
|
77
|
-
let listed
|
|
78
|
-
try {
|
|
79
|
-
listed = JSON.parse(process.env.SPUNTO_AGENT_MCP || "[]")
|
|
80
|
-
} catch {
|
|
81
|
-
return {}
|
|
82
|
-
}
|
|
83
|
-
const api = (process.env.SPUNTO_API_URL || "").replace(/\/$/, "")
|
|
84
|
-
if (!Array.isArray(listed) || !api || !process.env.SPUNTO_WORKER_TOKEN) return {}
|
|
85
|
-
const servers = {}
|
|
86
|
-
for (const s of listed) {
|
|
87
|
-
if (!s || typeof s.name !== "string" || typeof s.path !== "string") continue
|
|
88
|
-
servers[s.name] = { url: `${api}${s.path}`, bearer_token_env_var: "SPUNTO_WORKER_TOKEN" }
|
|
89
|
-
}
|
|
90
|
-
return servers
|
|
91
|
-
}
|
|
92
|
-
const mcpServers = readMcpServers()
|
|
93
|
-
|
|
94
|
-
let sdk
|
|
95
|
-
try {
|
|
96
|
-
sdk = await import(SDK)
|
|
97
|
-
} catch (err) {
|
|
98
|
-
fail(`codex runner: the Codex SDK is not installed at ${SDK} — is the project's image built with the Codex app's feature? (${err?.message ?? err})`)
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
const apiKey = process.env.OPENAI_API_KEY || process.env.CODEX_API_KEY
|
|
102
|
-
const codex = new sdk.Codex({
|
|
103
|
-
...(apiKey ? { apiKey } : {}),
|
|
104
|
-
...(Object.keys(mcpServers).length ? { config: { mcp_servers: mcpServers } } : {}),
|
|
105
|
-
})
|
|
106
|
-
const threadOptions = {
|
|
107
|
-
workingDirectory: process.cwd(),
|
|
108
|
-
...(args.model ? { model: args.model } : {}),
|
|
109
|
-
...(typeof params.reasoningEffort === "string" ? { modelReasoningEffort: params.reasoningEffort } : {}),
|
|
110
|
-
...(typeof params.webSearch === "string" ? { webSearchMode: params.webSearch } : {}),
|
|
111
|
-
// A task runs unattended in a disposable machine: no approval prompt nobody would answer, and
|
|
112
|
-
// no sandbox of Codex's own inside the one the machine already is (it needs kernel features a
|
|
113
|
-
// container rarely has).
|
|
114
|
-
approvalPolicy: "never",
|
|
115
|
-
sandboxMode: "danger-full-access",
|
|
116
|
-
networkAccessEnabled: true,
|
|
117
|
-
}
|
|
118
|
-
const thread = args.resume ? codex.resumeThread(args.resume, threadOptions) : codex.startThread(threadOptions)
|
|
119
|
-
// A resumed thread is not announced by the SDK (`thread.started` only comes with a new one), and
|
|
120
|
-
// the platform learns the session id from that line — so the runner says it.
|
|
121
|
-
if (args.resume) emit({ type: "thread.started", thread_id: args.resume })
|
|
122
|
-
|
|
123
|
-
const pending = []
|
|
124
|
-
let closed = false
|
|
125
|
-
let current = null // AbortController of the turn in flight
|
|
126
|
-
let wake = null
|
|
127
|
-
|
|
128
|
-
createInterface({ input: process.stdin, crlfDelay: Infinity })
|
|
129
|
-
.on("line", (line) => {
|
|
130
|
-
let msg
|
|
131
|
-
try {
|
|
132
|
-
msg = JSON.parse(line)
|
|
133
|
-
} catch {
|
|
134
|
-
return
|
|
135
|
-
}
|
|
136
|
-
if (!msg || typeof msg !== "object") return
|
|
137
|
-
if (msg.type === "user" && typeof msg.text === "string") {
|
|
138
|
-
pending.push(msg.text)
|
|
139
|
-
wake?.()
|
|
140
|
-
} else if (msg.type === "interrupt") {
|
|
141
|
-
current?.abort()
|
|
142
|
-
}
|
|
143
|
-
})
|
|
144
|
-
.on("close", () => {
|
|
145
|
-
closed = true
|
|
146
|
-
wake?.()
|
|
147
|
-
})
|
|
148
|
-
|
|
149
|
-
let failed = false
|
|
150
|
-
for (;;) {
|
|
151
|
-
if (pending.length === 0) {
|
|
152
|
-
if (closed) break
|
|
153
|
-
await new Promise((resolve) => (wake = resolve))
|
|
154
|
-
wake = null
|
|
155
|
-
continue
|
|
156
|
-
}
|
|
157
|
-
const text = pending.shift()
|
|
158
|
-
current = new AbortController()
|
|
159
|
-
// The SDK also throws once the binary exits after a `turn.failed` it has just yielded; that line
|
|
160
|
-
// already said why, and a second one would end the turn twice in the timeline.
|
|
161
|
-
let lastType = null
|
|
162
|
-
try {
|
|
163
|
-
const { events } = await thread.runStreamed(text, { signal: current.signal })
|
|
164
|
-
for await (const event of events) {
|
|
165
|
-
emit(event)
|
|
166
|
-
lastType = event?.type ?? null
|
|
167
|
-
}
|
|
168
|
-
} catch (err) {
|
|
169
|
-
if (current.signal.aborted) {
|
|
170
|
-
emit({ type: "turn.failed", error: { message: "Interrupted." } })
|
|
171
|
-
} else if (lastType !== "turn.failed") {
|
|
172
|
-
emit({ type: "turn.failed", error: { message: `codex runner: ${err?.message ?? err}` } })
|
|
173
|
-
failed = true
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
current = null
|
|
177
|
-
}
|
|
178
|
-
process.exit(failed ? 1 : 0)
|
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
// The install scripts of the agent apps' features (RFC 0048), shipped by the platform itself like
|
|
2
|
-
// `google-cloud-cli.sh` (`../script/local-features.ts`). Root, at image build time.
|
|
3
|
-
//
|
|
4
|
-
// Each one lays down, under /opt/spunto/agents:
|
|
5
|
-
// node/ a private Node — the runner must not depend on the project's (absent from a
|
|
6
|
-
// Python image, swapped by an nvm feature that installs after this one)
|
|
7
|
-
// <id>/ the harness's official SDK, pinned, with the native binary it drives — or, for
|
|
8
|
-
// a harness with no Node SDK (Mistral Vibe, Python), the harness itself, pinned
|
|
9
|
-
// /usr/local/bin/ the harness's CLI for the humans in the terminal, unless the image has one
|
|
10
|
-
|
|
11
|
-
/** Where every agent feature installs. */
|
|
12
|
-
export const AGENT_HOME = "/opt/spunto/agents"
|
|
13
|
-
/** The private Node the features fetch — the release the sandbox bootstrap fetches too. */
|
|
14
|
-
export const AGENT_NODE_VERSION = "v24.11.1"
|
|
15
|
-
const NODE_VERSION = AGENT_NODE_VERSION
|
|
16
|
-
|
|
17
|
-
/** The pinned Mistral Vibe release, and the uv that installs it (with its own Python). */
|
|
18
|
-
export const MISTRAL_VIBE_VERSION = "3.0.4"
|
|
19
|
-
const UV_VERSION = "0.13.6"
|
|
20
|
-
|
|
21
|
-
/** The SDK, from npm, into `<id>/` — what both Node harnesses install. */
|
|
22
|
-
function npmInstall(id: string, packages: string): string {
|
|
23
|
-
return `mkdir -p "$HOME_DIR/${id}"
|
|
24
|
-
PATH="$NODE_DIR/bin:$PATH" "$NODE_DIR/bin/npm" install --prefix "$HOME_DIR/${id}" \\
|
|
25
|
-
--omit=dev --no-audit --no-fund --no-update-notifier --loglevel=error ${packages}`
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
function featureScript(p: { id: string; label: string; install: string; cli: string }): string {
|
|
29
|
-
return `#!/bin/sh
|
|
30
|
-
set -e
|
|
31
|
-
echo "[feature] ${p.id}: installing ${p.label}..."
|
|
32
|
-
|
|
33
|
-
HOME_DIR=${AGENT_HOME}
|
|
34
|
-
NODE_DIR=$HOME_DIR/node
|
|
35
|
-
mkdir -p "$HOME_DIR"
|
|
36
|
-
|
|
37
|
-
fetch() {
|
|
38
|
-
if command -v curl >/dev/null 2>&1; then curl -fsSL --retry 5 --retry-delay 2 "$1" -o "$2"
|
|
39
|
-
elif command -v wget >/dev/null 2>&1; then wget -qO "$2" "$1"
|
|
40
|
-
else echo "[feature] ${p.id}: neither curl nor wget in this image" >&2; exit 1
|
|
41
|
-
fi
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
if ! "$NODE_DIR/bin/node" -e 'process.exit(0)' 2>/dev/null; then
|
|
45
|
-
case "$(uname -m)" in
|
|
46
|
-
x86_64|amd64) ARCH=x64 ;;
|
|
47
|
-
aarch64|arm64) ARCH=arm64 ;;
|
|
48
|
-
*) echo "[feature] ${p.id}: unsupported arch $(uname -m)" >&2; exit 1 ;;
|
|
49
|
-
esac
|
|
50
|
-
echo "[feature] ${p.id}: fetching node ${NODE_VERSION} ($ARCH)"
|
|
51
|
-
fetch "https://nodejs.org/dist/${NODE_VERSION}/node-${NODE_VERSION}-linux-$ARCH.tar.gz" /tmp/_spunto_node.tgz
|
|
52
|
-
rm -rf "$NODE_DIR" && mkdir -p "$NODE_DIR"
|
|
53
|
-
tar -xzf /tmp/_spunto_node.tgz -C "$NODE_DIR" --strip-components=1
|
|
54
|
-
rm -f /tmp/_spunto_node.tgz
|
|
55
|
-
fi
|
|
56
|
-
|
|
57
|
-
${p.install}
|
|
58
|
-
chmod -R a+rX "$HOME_DIR"
|
|
59
|
-
|
|
60
|
-
${p.cli}
|
|
61
|
-
|
|
62
|
-
echo "[feature] ${p.id}: done"
|
|
63
|
-
`
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
export const AGENT_FEATURE_SCRIPTS: Record<string, string> = {
|
|
67
|
-
"spunto-agent-claude.sh": featureScript({
|
|
68
|
-
id: "claude",
|
|
69
|
-
label: "the Claude Agent SDK",
|
|
70
|
-
install: npmInstall("claude", "@anthropic-ai/claude-agent-sdk@0.3.310"),
|
|
71
|
-
// The SDK drives a native \`claude\` binary from a platform package; the same binary is the CLI.
|
|
72
|
-
cli: `if ! command -v claude >/dev/null 2>&1; then
|
|
73
|
-
for b in "$HOME_DIR"/claude/node_modules/@anthropic-ai/claude-agent-sdk-linux-*/claude; do
|
|
74
|
-
if [ -x "$b" ]; then ln -sf "$b" /usr/local/bin/claude; break; fi
|
|
75
|
-
done
|
|
76
|
-
fi`,
|
|
77
|
-
}),
|
|
78
|
-
"spunto-agent-codex.sh": featureScript({
|
|
79
|
-
id: "codex",
|
|
80
|
-
label: "the Codex SDK",
|
|
81
|
-
install: npmInstall("codex", "@openai/codex-sdk@0.164.0"),
|
|
82
|
-
cli: `if ! command -v codex >/dev/null 2>&1; then
|
|
83
|
-
printf '#!/bin/sh\\nexec %s %s "$@"\\n' "$NODE_DIR/bin/node" "$HOME_DIR/codex/node_modules/@openai/codex/bin/codex.js" > /usr/local/bin/codex
|
|
84
|
-
chmod 755 /usr/local/bin/codex
|
|
85
|
-
fi`,
|
|
86
|
-
}),
|
|
87
|
-
// Mistral Vibe has no Node SDK: the runner speaks ACP to `vibe-acp` itself (`../mistral.mjs`).
|
|
88
|
-
// Vibe is Python (≥ 3.12); uv installs it with a Python of its own, so the image's — absent, or
|
|
89
|
-
// too old — never matters, the way the private Node keeps the project's out of the runner.
|
|
90
|
-
"spunto-agent-mistral.sh": featureScript({
|
|
91
|
-
id: "mistral",
|
|
92
|
-
label: "Mistral Vibe",
|
|
93
|
-
install: `MISTRAL_DIR=$HOME_DIR/mistral
|
|
94
|
-
mkdir -p "$MISTRAL_DIR"
|
|
95
|
-
if ! "$MISTRAL_DIR/uv/uv" --version 2>/dev/null | grep -q "${UV_VERSION}"; then
|
|
96
|
-
echo "[feature] mistral: fetching uv ${UV_VERSION}"
|
|
97
|
-
fetch "https://astral.sh/uv/${UV_VERSION}/install.sh" /tmp/_spunto_uv_install.sh
|
|
98
|
-
UV_INSTALL_DIR="$MISTRAL_DIR/uv" UV_NO_MODIFY_PATH=1 sh /tmp/_spunto_uv_install.sh >/dev/null
|
|
99
|
-
rm -f /tmp/_spunto_uv_install.sh
|
|
100
|
-
fi
|
|
101
|
-
UV_PYTHON_INSTALL_DIR="$MISTRAL_DIR/python" UV_TOOL_DIR="$MISTRAL_DIR/tools" UV_TOOL_BIN_DIR="$MISTRAL_DIR/bin" \\
|
|
102
|
-
UV_CACHE_DIR=/tmp/_spunto_uv_cache UV_NO_CONFIG=1 \\
|
|
103
|
-
"$MISTRAL_DIR/uv/uv" tool install --force --managed-python --python 3.13 "mistral-vibe==${MISTRAL_VIBE_VERSION}"
|
|
104
|
-
rm -rf /tmp/_spunto_uv_cache`,
|
|
105
|
-
cli: `for b in vibe vibe-acp; do
|
|
106
|
-
if ! command -v "$b" >/dev/null 2>&1; then ln -sf "$HOME_DIR/mistral/bin/$b" "/usr/local/bin/$b"; fi
|
|
107
|
-
done`,
|
|
108
|
-
}),
|
|
109
|
-
}
|