@foldrun/core 24.8.0 → 24.9.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/dist/src/engine-common.d.ts +91 -0
- package/dist/src/engine-common.js +160 -0
- package/dist/src/engine-compact.d.ts +61 -0
- package/dist/src/engine-compact.js +293 -0
- package/dist/src/engine-loop.d.ts +2 -42
- package/dist/src/engine-loop.js +219 -156
- package/dist/src/engine-mcp.d.ts +63 -0
- package/dist/src/engine-mcp.js +275 -0
- package/dist/src/engine-tools.d.ts +11 -0
- package/dist/src/runner.js +3 -2
- package/dist/src/script-tools.d.ts +3 -1
- package/dist/src/script-tools.js +34 -6
- package/dist/src/step-exec.d.ts +6 -0
- package/dist/src/step-exec.js +43 -2
- package/package.json +2 -1
- package/src/engine-common.ts +202 -0
- package/src/engine-compact.ts +288 -0
- package/src/engine-loop.ts +194 -188
- package/src/engine-mcp.ts +281 -0
- package/src/engine-tools.ts +4 -0
- package/src/runner.ts +3 -2
- package/src/script-tools.ts +27 -4
- package/src/step-exec.ts +49 -2
package/dist/src/engine-loop.js
CHANGED
|
@@ -34,94 +34,14 @@
|
|
|
34
34
|
// not summarise a full context yet: the model's own stop reason comes back
|
|
35
35
|
// on the result, as it does from the SDK.
|
|
36
36
|
import crypto from "node:crypto";
|
|
37
|
-
import {
|
|
37
|
+
import { killGroups } from "./engine-tools.js";
|
|
38
|
+
import { connectMcp } from "./engine-mcp.js";
|
|
39
|
+
import { SUMMARIZATION_SYSTEM_PROMPT, compacted, cutPoints, estimateTokens, fileLists, findCut, isContextOverflow, previousSummary, summaryRequest } from "./engine-compact.js";
|
|
40
|
+
import { DEFAULT_MAX_TOKENS, readOptions, decide, after, emptyUsage, addUsage } from "./engine-common.js";
|
|
38
41
|
const DEFAULT_BASE = "https://api.anthropic.com";
|
|
39
42
|
const API_VERSION = "2023-06-01";
|
|
40
|
-
const DEFAULT_MAX_TOKENS = 16_000;
|
|
41
43
|
const MODEL_TRIES = 4;
|
|
42
44
|
const RETRY_AFTER_CAP_MS = 30_000;
|
|
43
|
-
/** The tier names an agent may write, where the environment names no model
|
|
44
|
-
* for them. The SDK's binary resolves these itself; here it is said. */
|
|
45
|
-
const TIER_DEFAULTS = {
|
|
46
|
-
haiku: "claude-haiku-5-5",
|
|
47
|
-
sonnet: "claude-sonnet-5-5",
|
|
48
|
-
opus: "claude-opus-5-5",
|
|
49
|
-
};
|
|
50
|
-
function hookFns(hooks, event) {
|
|
51
|
-
const groups = hooks?.[event];
|
|
52
|
-
return (groups ?? []).flatMap((g) => g.hooks ?? []);
|
|
53
|
-
}
|
|
54
|
-
/** The SDK's options, as this engine reads them. What it cannot honour it
|
|
55
|
-
* refuses here, before a model call is paid for. */
|
|
56
|
-
function readOptions(options) {
|
|
57
|
-
const env = options.env ?? process.env;
|
|
58
|
-
const names = Array.isArray(options.tools) ? options.tools.map(String) : [];
|
|
59
|
-
const unsupported = names.filter((n) => !ENGINE_TOOLS[n]);
|
|
60
|
-
if (unsupported.length) {
|
|
61
|
-
throw new Error(`the foldrun engine has no tool named ${unsupported.join(", ")} yet — it has ${Object.keys(ENGINE_TOOLS).join(", ")}. Run this agent on the default engine.`);
|
|
62
|
-
}
|
|
63
|
-
const servers = Object.keys(options.mcpServers ?? {});
|
|
64
|
-
if (servers.length) {
|
|
65
|
-
throw new Error(`the foldrun engine does not connect MCP servers yet (${servers.join(", ")}) — run this agent on the default engine.`);
|
|
66
|
-
}
|
|
67
|
-
if (options.agents && Object.keys(options.agents).length) {
|
|
68
|
-
throw new Error("the foldrun engine does not run sub-agents yet — run this agent on the default engine.");
|
|
69
|
-
}
|
|
70
|
-
const sandbox = options.sandbox;
|
|
71
|
-
// Never read from `env`: that is where a tenant's secrets live.
|
|
72
|
-
if (names.includes("Bash") && sandbox?.enabled !== false && options.engineHostShell !== true) {
|
|
73
|
-
throw new Error("the foldrun engine has no OS sandbox for the shell on this host — run the step in a container.");
|
|
74
|
-
}
|
|
75
|
-
const model = String(options.model ?? "");
|
|
76
|
-
if (!model)
|
|
77
|
-
throw new Error("the foldrun engine needs a model");
|
|
78
|
-
// Tools the host brings, as EngineTool objects: they sit beside the
|
|
79
|
-
// built-in ones and go through canUseTool and the hooks like them.
|
|
80
|
-
// foldrun code's cloud_agents is one. A name may not shadow a built-in.
|
|
81
|
-
const extra = [];
|
|
82
|
-
for (const t of Array.isArray(options.extraTools) ? options.extraTools : []) {
|
|
83
|
-
const tool = t;
|
|
84
|
-
if (!tool || typeof tool.name !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(tool.name) || typeof tool.run !== "function" || typeof tool.input_schema !== "object") {
|
|
85
|
-
throw new Error("extraTools: each needs a name (letters, digits, _ and -), an input_schema and a run function");
|
|
86
|
-
}
|
|
87
|
-
if (ENGINE_TOOLS[tool.name] || extra.some((x) => x.name === tool.name))
|
|
88
|
-
throw new Error(`extraTools: ${tool.name} is already a tool`);
|
|
89
|
-
extra.push({ name: tool.name, description: String(tool.description ?? ""), input_schema: tool.input_schema, readOnly: tool.readOnly === true, run: tool.run });
|
|
90
|
-
}
|
|
91
|
-
return {
|
|
92
|
-
cwd: String(options.cwd ?? process.cwd()),
|
|
93
|
-
env,
|
|
94
|
-
shellEnv: options.shellEnv && typeof options.shellEnv === "object" ? options.shellEnv : env,
|
|
95
|
-
model: env[`ANTHROPIC_DEFAULT_${model.toUpperCase()}_MODEL`] || TIER_DEFAULTS[model] || model,
|
|
96
|
-
systemPrompt: typeof options.systemPrompt === "string" ? options.systemPrompt : "",
|
|
97
|
-
tools: [...names.map((n) => ENGINE_TOOLS[n]), ...extra],
|
|
98
|
-
maxTurns: typeof options.maxTurns === "number" && options.maxTurns > 0 ? options.maxTurns : null,
|
|
99
|
-
partial: options.includePartialMessages === true,
|
|
100
|
-
pre: hookFns(options.hooks, "PreToolUse"),
|
|
101
|
-
post: hookFns(options.hooks, "PostToolUse"),
|
|
102
|
-
canUseTool: typeof options.canUseTool === "function" ? options.canUseTool : null,
|
|
103
|
-
outer: options.abortController?.signal ?? null,
|
|
104
|
-
history: readHistory(options.history),
|
|
105
|
-
};
|
|
106
|
-
}
|
|
107
|
-
/** An earlier conversation, checked: user and assistant turns that
|
|
108
|
-
* alternate, starting with the user's, each a list of content blocks. A
|
|
109
|
-
* turn that is not one is refused, not sent half-right to the model. */
|
|
110
|
-
function readHistory(raw) {
|
|
111
|
-
if (raw == null)
|
|
112
|
-
return [];
|
|
113
|
-
if (!Array.isArray(raw))
|
|
114
|
-
throw new Error("history must be a list of turns");
|
|
115
|
-
return raw.map((t, i) => {
|
|
116
|
-
const role = t?.role;
|
|
117
|
-
const content = t?.content;
|
|
118
|
-
if (role !== (i % 2 === 0 ? "user" : "assistant"))
|
|
119
|
-
throw new Error(`history turn ${i + 1} must be the ${i % 2 === 0 ? "user's" : "model's"}`);
|
|
120
|
-
if (!Array.isArray(content) || !content.every((b) => b && typeof b.type === "string"))
|
|
121
|
-
throw new Error(`history turn ${i + 1} has no content blocks`);
|
|
122
|
-
return { role: String(role), content: content };
|
|
123
|
-
});
|
|
124
|
-
}
|
|
125
45
|
function requestHeaders(env) {
|
|
126
46
|
const headers = { "content-type": "application/json", "anthropic-version": API_VERSION };
|
|
127
47
|
if (env.ANTHROPIC_API_KEY)
|
|
@@ -164,8 +84,9 @@ export function endOf(stopReason, calls) {
|
|
|
164
84
|
return { subtype: "error_unknown_stop", error: `the model stopped for a reason this engine does not know (${stopReason ?? "none given"}) — the step did not finish` };
|
|
165
85
|
}
|
|
166
86
|
}
|
|
167
|
-
export function buildRequest(o, messages) {
|
|
168
|
-
|
|
87
|
+
export function buildRequest(o, messages, cache = true, maxTokens) {
|
|
88
|
+
// A one-off request (a summary) writes nothing to the cache.
|
|
89
|
+
const mark = cache ? { cache_control: { type: "ephemeral" } } : {};
|
|
169
90
|
const tools = o.tools.map((t, i) => ({
|
|
170
91
|
name: t.name,
|
|
171
92
|
description: t.description,
|
|
@@ -181,7 +102,7 @@ export function buildRequest(o, messages) {
|
|
|
181
102
|
const asked = Number(o.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS);
|
|
182
103
|
return {
|
|
183
104
|
model: o.model,
|
|
184
|
-
max_tokens: Number.isFinite(asked) && asked > 0 ? asked : DEFAULT_MAX_TOKENS,
|
|
105
|
+
max_tokens: Math.min(maxTokens ?? Infinity, Number.isFinite(asked) && asked > 0 ? asked : DEFAULT_MAX_TOKENS),
|
|
185
106
|
...(o.systemPrompt ? { system: [{ type: "text", text: o.systemPrompt, ...mark }] } : {}),
|
|
186
107
|
...(tools.length ? { tools } : {}),
|
|
187
108
|
messages: sent,
|
|
@@ -217,7 +138,7 @@ async function openStream(o, body, signal) {
|
|
|
217
138
|
lastError = `the model endpoint answered ${res.status}: ${text}`;
|
|
218
139
|
const retryable = res.status === 408 || res.status === 409 || res.status === 429 || res.status >= 500;
|
|
219
140
|
if (!retryable)
|
|
220
|
-
throw new Error(lastError);
|
|
141
|
+
throw Object.assign(new Error(lastError), { status: res.status });
|
|
221
142
|
const after = Number(res.headers.get("retry-after"));
|
|
222
143
|
if (attempt < MODEL_TRIES)
|
|
223
144
|
await sleep(Math.min(RETRY_AFTER_CAP_MS, Number.isFinite(after) && after > 0 ? after * 1000 : 1000 * 2 ** (attempt - 1)), signal);
|
|
@@ -234,39 +155,43 @@ async function openStream(o, body, signal) {
|
|
|
234
155
|
async function* sse(res) {
|
|
235
156
|
const decoder = new TextDecoder();
|
|
236
157
|
let buffer = "";
|
|
158
|
+
// SSE ends a line with CRLF, LF or a bare CR (WHATWG). Every one becomes
|
|
159
|
+
// LF here; a CR at the end of a chunk waits for the next, in case it is
|
|
160
|
+
// the first half of a CRLF split across them.
|
|
161
|
+
let held = "";
|
|
237
162
|
for await (const chunk of res.body) {
|
|
238
|
-
|
|
239
|
-
|
|
163
|
+
let text = held + decoder.decode(chunk, { stream: true });
|
|
164
|
+
held = text.endsWith("\r") ? "\r" : "";
|
|
165
|
+
if (held)
|
|
166
|
+
text = text.slice(0, -1);
|
|
167
|
+
buffer += text.replace(/\r\n?/g, "\n");
|
|
168
|
+
for (let at = buffer.indexOf("\n\n"); at >= 0; at = buffer.indexOf("\n\n")) {
|
|
240
169
|
const frame = buffer.slice(0, at);
|
|
241
|
-
buffer = buffer.slice(at
|
|
242
|
-
const data = frame.split(
|
|
170
|
+
buffer = buffer.slice(at + 2);
|
|
171
|
+
const data = frame.split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5).replace(/^ /, "")).join("\n");
|
|
243
172
|
if (!data || data === "[DONE]")
|
|
244
173
|
continue;
|
|
174
|
+
let parsed;
|
|
245
175
|
try {
|
|
246
|
-
|
|
176
|
+
parsed = JSON.parse(data);
|
|
247
177
|
}
|
|
248
178
|
catch {
|
|
249
|
-
//
|
|
179
|
+
// A frame that is not JSON may be a lost piece of the reply: a reply
|
|
180
|
+
// missing words would otherwise pass as whole (Codex, 22 Nov 2026).
|
|
181
|
+
throw new Error("the model stream sent a frame that is not JSON — the reply cannot be trusted whole");
|
|
250
182
|
}
|
|
183
|
+
yield parsed;
|
|
251
184
|
}
|
|
252
185
|
}
|
|
253
186
|
}
|
|
254
|
-
const emptyUsage = () => ({ input_tokens: 0, output_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 });
|
|
255
|
-
function addUsage(into, u) {
|
|
256
|
-
if (!u)
|
|
257
|
-
return;
|
|
258
|
-
// The closing delta repeats the counts it knows; one that leaves the input
|
|
259
|
-
// side at zero is not saying the input was free.
|
|
260
|
-
for (const k of Object.keys(into)) {
|
|
261
|
-
const v = u[k];
|
|
262
|
-
if (typeof v === "number" && (v > 0 || k === "output_tokens"))
|
|
263
|
-
into[k] = v;
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
187
|
/** One model call: yields the raw stream events, returns the whole turn. */
|
|
267
|
-
async function* modelTurn(o, messages, signal) {
|
|
268
|
-
const res = await openStream(o, buildRequest(o, messages), signal);
|
|
188
|
+
async function* modelTurn(o, messages, signal, cache = true, maxTokens, track) {
|
|
189
|
+
const res = await openStream(o, buildRequest(o, messages, cache, maxTokens), signal);
|
|
269
190
|
const turn = { id: "", model: o.model, content: [], stopReason: null, usage: emptyUsage(), malformed: new Set() };
|
|
191
|
+
// A caller that must count what a stream that breaks part-way had
|
|
192
|
+
// already reported (a summary request) reads it here.
|
|
193
|
+
if (track)
|
|
194
|
+
track.turn = turn;
|
|
270
195
|
const partialJson = new Map();
|
|
271
196
|
const open = new Set();
|
|
272
197
|
let stopped = false;
|
|
@@ -341,45 +266,6 @@ async function* modelTurn(o, messages, signal) {
|
|
|
341
266
|
turn.content = turn.content.filter(Boolean);
|
|
342
267
|
return turn;
|
|
343
268
|
}
|
|
344
|
-
/** May this call run, and with what input? The order the SDK kept, which
|
|
345
|
-
* step-exec's checks are written against: every PreToolUse hook first — a
|
|
346
|
-
* deny ends it, an allow carries the input the hook settled on and skips
|
|
347
|
-
* the question below — then canUseTool, where confinement lives. */
|
|
348
|
-
async function decide(o, name, id, input, sessionId, signal) {
|
|
349
|
-
let current = input;
|
|
350
|
-
let allowed = false;
|
|
351
|
-
for (const hook of o.pre) {
|
|
352
|
-
const out = await hook({ hook_event_name: "PreToolUse", session_id: sessionId, cwd: o.cwd, tool_name: name, tool_input: current, tool_use_id: id }, id, { signal });
|
|
353
|
-
const d = out?.hookSpecificOutput;
|
|
354
|
-
if (!d)
|
|
355
|
-
continue;
|
|
356
|
-
if (d.permissionDecision === "deny")
|
|
357
|
-
return { input: current, refusal: d.permissionDecisionReason || `${name} was refused` };
|
|
358
|
-
if (d.updatedInput)
|
|
359
|
-
current = d.updatedInput;
|
|
360
|
-
if (d.permissionDecision === "allow")
|
|
361
|
-
allowed = true;
|
|
362
|
-
}
|
|
363
|
-
if (!allowed && o.canUseTool) {
|
|
364
|
-
const r = await o.canUseTool(name, current, { signal, toolUseID: id });
|
|
365
|
-
if (r.behavior === "deny")
|
|
366
|
-
return { input: current, refusal: r.message || `${name} was refused` };
|
|
367
|
-
if (r.updatedInput)
|
|
368
|
-
current = r.updatedInput;
|
|
369
|
-
}
|
|
370
|
-
return { input: current, refusal: null };
|
|
371
|
-
}
|
|
372
|
-
/** After a call: tell the PostToolUse hooks, and collect what they add. */
|
|
373
|
-
async function after(o, name, id, input, outcome, sessionId, signal) {
|
|
374
|
-
const added = [];
|
|
375
|
-
for (const hook of o.post) {
|
|
376
|
-
const out = await hook({ hook_event_name: "PostToolUse", session_id: sessionId, cwd: o.cwd, tool_name: name, tool_input: input, tool_response: outcome.text, tool_use_id: id }, id, { signal });
|
|
377
|
-
const context = out?.hookSpecificOutput?.additionalContext;
|
|
378
|
-
if (context)
|
|
379
|
-
added.push(context);
|
|
380
|
-
}
|
|
381
|
-
return added;
|
|
382
|
-
}
|
|
383
269
|
async function* run(prompt, o, signal, interrupted) {
|
|
384
270
|
const sessionId = crypto.randomUUID();
|
|
385
271
|
const startedAt = Date.now();
|
|
@@ -405,13 +291,157 @@ async function* run(prompt, o, signal, interrupted) {
|
|
|
405
291
|
permission_denials: [],
|
|
406
292
|
session_id: sessionId,
|
|
407
293
|
});
|
|
408
|
-
|
|
294
|
+
// The step's MCP servers, connected before the first model call: their
|
|
295
|
+
// tools sit after the built-in and host ones (engine-mcp.ts). One that
|
|
296
|
+
// does not start refuses the step here, before anything is paid for.
|
|
297
|
+
let mcp = null;
|
|
409
298
|
try {
|
|
299
|
+
if (Object.keys(o.mcpServers).length) {
|
|
300
|
+
mcp = await connectMcp(o.mcpServers, { env: o.env, toolEnv: o.shellEnv, cwd: o.cwd, signal });
|
|
301
|
+
for (const t of mcp.tools) {
|
|
302
|
+
if (byName.has(t.name))
|
|
303
|
+
throw new Error(`the MCP tool ${t.name} has the name of a tool the step already has`);
|
|
304
|
+
byName.set(t.name, t);
|
|
305
|
+
}
|
|
306
|
+
o.tools = [...o.tools, ...mcp.tools];
|
|
307
|
+
if (mcp.instructions.length) {
|
|
308
|
+
o.systemPrompt = [o.systemPrompt, "# MCP Server Instructions", ...mcp.instructions.map((i) => `## ${i.server}\n${i.text}`)].filter(Boolean).join("\n\n");
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
// A tool the step was granted that its server does not offer: the step
|
|
312
|
+
// would run without it, and the model be told it has none.
|
|
313
|
+
const missing = o.mcpGranted.filter((g) => mcp?.owner.get(g.name) !== g.server).map((g) => g.name);
|
|
314
|
+
if (missing.length)
|
|
315
|
+
throw new Error(`granted but not offered by its MCP server: ${missing.join(", ")}`);
|
|
316
|
+
yield { type: "system", subtype: "init", session_id: sessionId, cwd: o.cwd, model: o.model, tools: o.tools.map((t) => t.name), mcp_servers: mcp?.servers ?? [], engine: "foldrun" };
|
|
317
|
+
// ---- Compaction (engine-compact.ts). What the context holds is the last
|
|
318
|
+
// turn's own count (everything it was sent, and its reply) plus an
|
|
319
|
+
// estimate of what has been added since; before any turn, an estimate of
|
|
320
|
+
// it all.
|
|
321
|
+
let measured = null;
|
|
322
|
+
const filesRead = new Set();
|
|
323
|
+
const filesChanged = new Set();
|
|
324
|
+
let autoCompaction = o.compaction !== false;
|
|
325
|
+
const contextNow = () => {
|
|
326
|
+
if (measured)
|
|
327
|
+
return measured.tokens + messages.slice(measured.at).reduce((n, m) => n + estimateTokens(m), 0);
|
|
328
|
+
const fixed = Math.ceil((o.systemPrompt.length + JSON.stringify(o.tools.map((t) => [t.name, t.description, t.input_schema])).length) / 4);
|
|
329
|
+
return fixed + messages.reduce((n, m) => n + estimateTokens(m), 0);
|
|
330
|
+
};
|
|
331
|
+
/** Summarise the older part and go on from the summary and the newest
|
|
332
|
+
* part. False, with the reason, when there is nothing to cut or the
|
|
333
|
+
* summary did not come back whole. */
|
|
334
|
+
// `asked`: a summary was asked for (and paid for) and did not come back.
|
|
335
|
+
async function* compactNow(trigger, before) {
|
|
336
|
+
if (o.compaction === false)
|
|
337
|
+
return { ok: false, why: "compaction is off" };
|
|
338
|
+
const room = o.compaction.contextWindow - o.compaction.reserveTokens;
|
|
339
|
+
// The kept part leaves room for the summary (a few thousand tokens).
|
|
340
|
+
// After an overflow the real window is smaller than assumed: the kept
|
|
341
|
+
// part is held to the keep budget itself.
|
|
342
|
+
let cut = findCut(messages, o.compaction.keepRecentTokens, trigger === "overflow" ? o.compaction.keepRecentTokens : Math.max(0, room - 4_096));
|
|
343
|
+
if (cut < 1)
|
|
344
|
+
return { ok: false, why: "there was nothing older to summarise" };
|
|
345
|
+
// A summary of a few words makes no room and is not worth paying for:
|
|
346
|
+
// a later cut is tried (the newest message is always kept).
|
|
347
|
+
const older = (c) => messages.slice(0, c).reduce((n, m) => n + estimateTokens(m), 0);
|
|
348
|
+
for (const later of cutPoints(messages))
|
|
349
|
+
if (later > cut && older(cut) < 1_024)
|
|
350
|
+
cut = later;
|
|
351
|
+
if (older(cut) < 1_024)
|
|
352
|
+
return { ok: false, why: "there was too little older to summarise" };
|
|
353
|
+
const ask = { ...o, systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, tools: [], partial: false };
|
|
354
|
+
// The request itself must fit: the conversation's text is held to the
|
|
355
|
+
// window less the reply's reserve and the prompts, newest part kept.
|
|
356
|
+
const request = [{ role: "user", content: [{ type: "text", text: summaryRequest(messages.slice(0, cut), previousSummary(messages), Math.max(4_000, (room - 3_000) * 4)) }] }];
|
|
357
|
+
let reply;
|
|
358
|
+
const track = {};
|
|
359
|
+
try {
|
|
360
|
+
// Its reply is held to the window's reserve: input and output must fit.
|
|
361
|
+
const stream = modelTurn(ask, request, signal, false, o.compaction.reserveTokens, track);
|
|
362
|
+
for (;;) {
|
|
363
|
+
const step = await stream.next();
|
|
364
|
+
if (step.done) {
|
|
365
|
+
reply = step.value;
|
|
366
|
+
break;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
catch (err) {
|
|
371
|
+
// What the endpoint had counted before the stream broke was paid for.
|
|
372
|
+
const spent = track.turn?.usage;
|
|
373
|
+
if (spent && Object.values(spent).some((n) => n > 0)) {
|
|
374
|
+
for (const k of Object.keys(total))
|
|
375
|
+
total[k] += spent[k];
|
|
376
|
+
yield { type: "system", subtype: "compact_failed", session_id: sessionId, error: `the summary request failed: ${err.message}`, model: track.turn.model, usage: { ...spent } };
|
|
377
|
+
}
|
|
378
|
+
if (signal.aborted)
|
|
379
|
+
throw err;
|
|
380
|
+
return { ok: false, asked: true, why: `the summary request failed: ${err.message}` };
|
|
381
|
+
}
|
|
382
|
+
// Paid for like any turn: in the total, and reported with what it
|
|
383
|
+
// came to so the step's cost and budget count it (step-exec).
|
|
384
|
+
for (const k of Object.keys(total))
|
|
385
|
+
total[k] += reply.usage[k];
|
|
386
|
+
const summary = reply.content.filter((b) => b.type === "text").map((b) => String(b.text ?? "")).join("\n").trim();
|
|
387
|
+
if (reply.stopReason !== "end_turn" || reply.content.some((b) => b.type === "tool_use") || !summary) {
|
|
388
|
+
const why = `the summary did not come back whole (stop reason ${reply.stopReason ?? "none"})`;
|
|
389
|
+
yield { type: "system", subtype: "compact_failed", session_id: sessionId, error: why, model: reply.model, usage: { ...reply.usage } };
|
|
390
|
+
return { ok: false, asked: true, why };
|
|
391
|
+
}
|
|
392
|
+
const next = compacted(summary + fileLists(filesRead, filesChanged), messages.slice(cut));
|
|
393
|
+
messages.splice(0, messages.length, ...next);
|
|
394
|
+
measured = null;
|
|
395
|
+
yield {
|
|
396
|
+
type: "system",
|
|
397
|
+
subtype: "compact_boundary",
|
|
398
|
+
session_id: sessionId,
|
|
399
|
+
compact_metadata: { trigger, pre_tokens: before, post_tokens: contextNow(), summarized_messages: cut },
|
|
400
|
+
model: reply.model,
|
|
401
|
+
usage: { ...reply.usage },
|
|
402
|
+
// The conversation as it now stands, so a caller that keeps one
|
|
403
|
+
// (foldrun code) goes on from it rather than the whole history.
|
|
404
|
+
conversation: messages.map((m) => ({ role: m.role, content: [...m.content] })),
|
|
405
|
+
};
|
|
406
|
+
return { ok: true };
|
|
407
|
+
}
|
|
408
|
+
// Set when a request was refused as too long and compacted: the same
|
|
409
|
+
// request is asked again once, not compacted again and again.
|
|
410
|
+
let overflowed = false;
|
|
410
411
|
for (;;) {
|
|
411
412
|
if (o.maxTurns !== null && turns >= o.maxTurns) {
|
|
412
413
|
yield result("error_max_turns", null);
|
|
413
414
|
return;
|
|
414
415
|
}
|
|
416
|
+
// Not on the retry after an overflow (that request is asked again as
|
|
417
|
+
// compacted), and not while the model's own turn is being continued
|
|
418
|
+
// (pause_turn): the conversation must end on a user turn to be cut.
|
|
419
|
+
if (autoCompaction && !overflowed && o.compaction !== false && messages.at(-1)?.role === "user") {
|
|
420
|
+
const now = contextNow();
|
|
421
|
+
if (now > o.compaction.contextWindow - o.compaction.reserveTokens) {
|
|
422
|
+
let done;
|
|
423
|
+
try {
|
|
424
|
+
done = yield* compactNow("auto", now);
|
|
425
|
+
}
|
|
426
|
+
catch (err) {
|
|
427
|
+
if (interrupted() || signal.aborted)
|
|
428
|
+
return;
|
|
429
|
+
throw err;
|
|
430
|
+
}
|
|
431
|
+
if (interrupted() || signal.aborted)
|
|
432
|
+
return;
|
|
433
|
+
// A summary asked for and not given is not asked for again before
|
|
434
|
+
// every turn after: the request goes as it is, and the endpoint says
|
|
435
|
+
// if it is too long. Nothing to cut yet costs nothing: looked at
|
|
436
|
+
// again next turn.
|
|
437
|
+
if (!done.ok && done.asked)
|
|
438
|
+
autoCompaction = false;
|
|
439
|
+
// A summary that could not bring the context under the line will
|
|
440
|
+
// not by summarising again before every turn.
|
|
441
|
+
if (done.ok && contextNow() > o.compaction.contextWindow - o.compaction.reserveTokens)
|
|
442
|
+
autoCompaction = false;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
415
445
|
let turn;
|
|
416
446
|
try {
|
|
417
447
|
const stream = modelTurn(o, messages, signal);
|
|
@@ -429,9 +459,21 @@ async function* run(prompt, o, signal, interrupted) {
|
|
|
429
459
|
// knows why and reports it. Anything else is the step's failure.
|
|
430
460
|
if (interrupted() || signal.aborted)
|
|
431
461
|
return;
|
|
462
|
+
// The endpoint said the prompt does not fit (a model with a smaller
|
|
463
|
+
// window than assumed): compact and ask again — once per request.
|
|
464
|
+
if (!overflowed && o.compaction !== false && messages.at(-1)?.role === "user" && isContextOverflow(err.status, err.message)) {
|
|
465
|
+
overflowed = true;
|
|
466
|
+
const done = yield* compactNow("overflow", contextNow());
|
|
467
|
+
if (interrupted() || signal.aborted)
|
|
468
|
+
return;
|
|
469
|
+
if (!done.ok)
|
|
470
|
+
throw new Error(`${err.message} — and the conversation could not be compacted: ${done.why}`);
|
|
471
|
+
continue;
|
|
472
|
+
}
|
|
432
473
|
throw err;
|
|
433
474
|
}
|
|
434
475
|
turns++;
|
|
476
|
+
overflowed = false;
|
|
435
477
|
for (const k of Object.keys(total))
|
|
436
478
|
total[k] += turn.usage[k];
|
|
437
479
|
const text = turn.content.filter((b) => b.type === "text").map((b) => String(b.text ?? "")).join("\n").trim();
|
|
@@ -443,7 +485,15 @@ async function* run(prompt, o, signal, interrupted) {
|
|
|
443
485
|
parent_tool_use_id: null,
|
|
444
486
|
session_id: sessionId,
|
|
445
487
|
};
|
|
446
|
-
|
|
488
|
+
// A paused turn's continuation is the same turn: joined to it, so the
|
|
489
|
+
// conversation still alternates (what foldrun code keeps, and a cut).
|
|
490
|
+
const prev = messages[messages.length - 1];
|
|
491
|
+
if (prev?.role === "assistant")
|
|
492
|
+
prev.content = [...prev.content, ...turn.content];
|
|
493
|
+
else
|
|
494
|
+
messages.push({ role: "assistant", content: turn.content });
|
|
495
|
+
// The turn's own count: all it was sent, and its reply.
|
|
496
|
+
measured = { tokens: turn.usage.input_tokens + turn.usage.cache_read_input_tokens + turn.usage.cache_creation_input_tokens + turn.usage.output_tokens, at: messages.length };
|
|
447
497
|
if (interrupted())
|
|
448
498
|
return;
|
|
449
499
|
const calls = turn.content.filter((b) => b.type === "tool_use");
|
|
@@ -478,6 +528,14 @@ async function* run(prompt, o, signal, interrupted) {
|
|
|
478
528
|
catch (err) {
|
|
479
529
|
outcome = { text: `${p.tool.name} failed: ${err.message}`, isError: true };
|
|
480
530
|
}
|
|
531
|
+
// For a summary's file lists: what ran, as the hooks left it, and did not fail.
|
|
532
|
+
const file = p.decision.input.file_path;
|
|
533
|
+
if (!outcome.isError && typeof file === "string") {
|
|
534
|
+
if (p.tool.name === "Read")
|
|
535
|
+
filesRead.add(file);
|
|
536
|
+
else if (p.tool.name === "Write" || p.tool.name === "Edit")
|
|
537
|
+
filesChanged.add(file);
|
|
538
|
+
}
|
|
481
539
|
const context = await after(o, p.tool.name, String(p.block.id), p.decision.input, outcome, sessionId, signal);
|
|
482
540
|
return { outcome, context };
|
|
483
541
|
};
|
|
@@ -504,12 +562,15 @@ async function* run(prompt, o, signal, interrupted) {
|
|
|
504
562
|
}
|
|
505
563
|
if (interrupted())
|
|
506
564
|
return;
|
|
507
|
-
const results = planned.map((p, i) =>
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
565
|
+
const results = planned.map((p, i) => {
|
|
566
|
+
const { text, isError, parts } = done[i].outcome;
|
|
567
|
+
// An image a tool returned (an MCP server's screenshot) goes to the
|
|
568
|
+
// model as an image, in its place among the text.
|
|
569
|
+
const content = parts
|
|
570
|
+
? parts.map((p) => p.type === "text" ? { type: "text", text: p.text } : { type: "image", source: { type: "base64", media_type: p.mediaType, data: p.data } })
|
|
571
|
+
: text;
|
|
572
|
+
return { type: "tool_result", tool_use_id: String(p.block.id), content, ...(isError ? { is_error: true } : {}) };
|
|
573
|
+
});
|
|
513
574
|
const context = done.flatMap((d) => d.context);
|
|
514
575
|
const content = [...results, ...context.map((c) => ({ type: "text", text: c }))];
|
|
515
576
|
messages.push({ role: "user", content });
|
|
@@ -518,8 +579,10 @@ async function* run(prompt, o, signal, interrupted) {
|
|
|
518
579
|
}
|
|
519
580
|
finally {
|
|
520
581
|
// However the loop ended — an answer, a stop, a consumer that walked
|
|
521
|
-
// away — nothing a command started outlives the step
|
|
582
|
+
// away — nothing a command started outlives the step, and no MCP server
|
|
583
|
+
// it started either.
|
|
522
584
|
killGroups(ctx);
|
|
585
|
+
await mcp?.close();
|
|
523
586
|
}
|
|
524
587
|
}
|
|
525
588
|
/** The foldrun engine, as executeStep's model loop. */
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|
2
|
+
import type { EngineTool, ToolOutcome } from "./engine-tools.ts";
|
|
3
|
+
type Json = Record<string, unknown>;
|
|
4
|
+
/** The server a granted name belongs to: `mcp__<server>`, `mcp__<server>__*`
|
|
5
|
+
* (the runner grants a whole server so) or `mcp__<server>__<tool>`. Matched
|
|
6
|
+
* against the step's own server names, the longest first, so a server named
|
|
7
|
+
* `sales__eu` is not read as `sales`. */
|
|
8
|
+
export declare function grantedServer(name: string, servers: string[]): {
|
|
9
|
+
server: string;
|
|
10
|
+
tool: string | null;
|
|
11
|
+
} | null;
|
|
12
|
+
/** A server as the SDK's `mcpServers` option holds it. */
|
|
13
|
+
export interface McpSpec {
|
|
14
|
+
type?: string;
|
|
15
|
+
name?: string;
|
|
16
|
+
instance?: {
|
|
17
|
+
connect(t: Transport): Promise<void>;
|
|
18
|
+
};
|
|
19
|
+
command?: string;
|
|
20
|
+
args?: string[];
|
|
21
|
+
env?: Record<string, string>;
|
|
22
|
+
url?: string;
|
|
23
|
+
headers?: Record<string, string>;
|
|
24
|
+
/** Milliseconds one call may take; below 1000 is ignored, as in the SDK. */
|
|
25
|
+
timeout?: number;
|
|
26
|
+
/** The SDK's per-tool permission policy — refused here (checkMcpSpecs). */
|
|
27
|
+
tools?: unknown;
|
|
28
|
+
}
|
|
29
|
+
/** Refused before a model call is paid for: a server this loop cannot connect. */
|
|
30
|
+
export declare function checkMcpSpecs(servers: Record<string, unknown>, engine: string): Record<string, McpSpec>;
|
|
31
|
+
export interface McpConnection {
|
|
32
|
+
tools: EngineTool[];
|
|
33
|
+
/** Which server offered each tool, by its full name. */
|
|
34
|
+
owner: Map<string, string>;
|
|
35
|
+
/** What each server told its client to tell the model (MCP `instructions`),
|
|
36
|
+
* which the SDK put in the system prompt; so does the loop. */
|
|
37
|
+
instructions: {
|
|
38
|
+
server: string;
|
|
39
|
+
text: string;
|
|
40
|
+
}[];
|
|
41
|
+
servers: {
|
|
42
|
+
name: string;
|
|
43
|
+
status: "connected";
|
|
44
|
+
}[];
|
|
45
|
+
close(): Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
/** A call's result as the loop hands it on: its text and images in the
|
|
48
|
+
* order the server gave them (a caption stays beside its picture), the text
|
|
49
|
+
* cut to a size, marked an error when the server says it is one. */
|
|
50
|
+
export declare function outcomeOf(result: Json): ToolOutcome;
|
|
51
|
+
/** Connect every server and list its tools. All or none: one that fails
|
|
52
|
+
* closes the rest and refuses the step, naming it. */
|
|
53
|
+
/** `env` is the step's options' environment (where MCP_TOOL_TIMEOUT is
|
|
54
|
+
* read, as the SDK read it); `toolEnv` is what a tool's process starts
|
|
55
|
+
* from — the loop's shellEnv, which a caller keeps apart from the model's
|
|
56
|
+
* credentials. */
|
|
57
|
+
export declare function connectMcp(servers: Record<string, McpSpec>, ctx: {
|
|
58
|
+
env: Record<string, string | undefined>;
|
|
59
|
+
toolEnv: Record<string, string | undefined>;
|
|
60
|
+
cwd: string;
|
|
61
|
+
signal: AbortSignal;
|
|
62
|
+
}): Promise<McpConnection>;
|
|
63
|
+
export {};
|