@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/src/engine-loop.ts
CHANGED
|
@@ -36,130 +36,19 @@
|
|
|
36
36
|
|
|
37
37
|
import crypto from "node:crypto";
|
|
38
38
|
import type { QueryFn, QueryLike } from "./step-exec.ts";
|
|
39
|
-
import {
|
|
39
|
+
import { killGroups, type EngineTool, type ToolContext, type ToolOutcome } from "./engine-tools.ts";
|
|
40
|
+
import { connectMcp, type McpConnection } from "./engine-mcp.ts";
|
|
41
|
+
import { SUMMARIZATION_SYSTEM_PROMPT, compacted, cutPoints, estimateTokens, fileLists, findCut, isContextOverflow, previousSummary, summaryRequest } from "./engine-compact.ts";
|
|
42
|
+
import { DEFAULT_MAX_TOKENS, readOptions, decide, after, emptyUsage, addUsage, type Json, type Block, type LoopOptions, type Decision, type Usage } from "./engine-common.ts";
|
|
40
43
|
|
|
41
44
|
/** Which loop runs a step's turns. */
|
|
42
45
|
export type Engine = "sdk" | "foldrun";
|
|
43
46
|
|
|
44
47
|
const DEFAULT_BASE = "https://api.anthropic.com";
|
|
45
48
|
const API_VERSION = "2023-06-01";
|
|
46
|
-
const DEFAULT_MAX_TOKENS = 16_000;
|
|
47
49
|
const MODEL_TRIES = 4;
|
|
48
50
|
const RETRY_AFTER_CAP_MS = 30_000;
|
|
49
51
|
|
|
50
|
-
/** The tier names an agent may write, where the environment names no model
|
|
51
|
-
* for them. The SDK's binary resolves these itself; here it is said. */
|
|
52
|
-
const TIER_DEFAULTS: Record<string, string> = {
|
|
53
|
-
haiku: "claude-haiku-5-5",
|
|
54
|
-
sonnet: "claude-sonnet-5-5",
|
|
55
|
-
opus: "claude-opus-5-5",
|
|
56
|
-
};
|
|
57
|
-
|
|
58
|
-
type Json = Record<string, unknown>;
|
|
59
|
-
type Block = Json & { type: string };
|
|
60
|
-
type HookFn = (input: Json, toolUseId?: string, extra?: { signal: AbortSignal }) => Promise<Json | undefined> | Json | undefined;
|
|
61
|
-
type CanUseTool = (name: string, input: Json, extra: { signal: AbortSignal; toolUseID: string }) =>
|
|
62
|
-
Promise<{ behavior: "allow"; updatedInput?: Json } | { behavior: "deny"; message: string }>;
|
|
63
|
-
|
|
64
|
-
interface Usage {
|
|
65
|
-
input_tokens: number;
|
|
66
|
-
output_tokens: number;
|
|
67
|
-
cache_creation_input_tokens: number;
|
|
68
|
-
cache_read_input_tokens: number;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
interface LoopOptions {
|
|
72
|
-
cwd: string;
|
|
73
|
-
env: Record<string, string | undefined>;
|
|
74
|
-
/** What the tools (Bash) get; `env` when not given. foldrun code passes
|
|
75
|
-
* the person's own environment here, so the model key stays with the loop. */
|
|
76
|
-
shellEnv: Record<string, string | undefined>;
|
|
77
|
-
model: string;
|
|
78
|
-
systemPrompt: string;
|
|
79
|
-
tools: EngineTool[];
|
|
80
|
-
maxTurns: number | null;
|
|
81
|
-
partial: boolean;
|
|
82
|
-
pre: HookFn[];
|
|
83
|
-
post: HookFn[];
|
|
84
|
-
canUseTool: CanUseTool | null;
|
|
85
|
-
outer: AbortSignal | null;
|
|
86
|
-
/** The conversation so far, before this prompt: earlier user turns, the
|
|
87
|
-
* model's replies and tool results, as the loop yielded them. */
|
|
88
|
-
history: { role: string; content: Block[] }[];
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
function hookFns(hooks: unknown, event: string): HookFn[] {
|
|
92
|
-
const groups = (hooks as Record<string, { hooks?: HookFn[] }[] | undefined> | undefined)?.[event];
|
|
93
|
-
return (groups ?? []).flatMap((g) => g.hooks ?? []);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/** The SDK's options, as this engine reads them. What it cannot honour it
|
|
97
|
-
* refuses here, before a model call is paid for. */
|
|
98
|
-
function readOptions(options: Json): LoopOptions {
|
|
99
|
-
const env = (options.env as Record<string, string | undefined> | undefined) ?? process.env;
|
|
100
|
-
const names = Array.isArray(options.tools) ? (options.tools as unknown[]).map(String) : [];
|
|
101
|
-
const unsupported = names.filter((n) => !ENGINE_TOOLS[n]);
|
|
102
|
-
if (unsupported.length) {
|
|
103
|
-
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.`);
|
|
104
|
-
}
|
|
105
|
-
const servers = Object.keys((options.mcpServers as Json | undefined) ?? {});
|
|
106
|
-
if (servers.length) {
|
|
107
|
-
throw new Error(`the foldrun engine does not connect MCP servers yet (${servers.join(", ")}) — run this agent on the default engine.`);
|
|
108
|
-
}
|
|
109
|
-
if (options.agents && Object.keys(options.agents as Json).length) {
|
|
110
|
-
throw new Error("the foldrun engine does not run sub-agents yet — run this agent on the default engine.");
|
|
111
|
-
}
|
|
112
|
-
const sandbox = options.sandbox as { enabled?: boolean } | undefined;
|
|
113
|
-
// Never read from `env`: that is where a tenant's secrets live.
|
|
114
|
-
if (names.includes("Bash") && sandbox?.enabled !== false && options.engineHostShell !== true) {
|
|
115
|
-
throw new Error("the foldrun engine has no OS sandbox for the shell on this host — run the step in a container.");
|
|
116
|
-
}
|
|
117
|
-
const model = String(options.model ?? "");
|
|
118
|
-
if (!model) throw new Error("the foldrun engine needs a model");
|
|
119
|
-
// Tools the host brings, as EngineTool objects: they sit beside the
|
|
120
|
-
// built-in ones and go through canUseTool and the hooks like them.
|
|
121
|
-
// foldrun code's cloud_agents is one. A name may not shadow a built-in.
|
|
122
|
-
const extra: EngineTool[] = [];
|
|
123
|
-
for (const t of Array.isArray(options.extraTools) ? (options.extraTools as unknown[]) : []) {
|
|
124
|
-
const tool = t as Partial<EngineTool> | null;
|
|
125
|
-
if (!tool || typeof tool.name !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(tool.name) || typeof tool.run !== "function" || typeof tool.input_schema !== "object") {
|
|
126
|
-
throw new Error("extraTools: each needs a name (letters, digits, _ and -), an input_schema and a run function");
|
|
127
|
-
}
|
|
128
|
-
if (ENGINE_TOOLS[tool.name] || extra.some((x) => x.name === tool.name)) throw new Error(`extraTools: ${tool.name} is already a tool`);
|
|
129
|
-
extra.push({ name: tool.name, description: String(tool.description ?? ""), input_schema: tool.input_schema as Record<string, unknown>, readOnly: tool.readOnly === true, run: tool.run });
|
|
130
|
-
}
|
|
131
|
-
return {
|
|
132
|
-
cwd: String(options.cwd ?? process.cwd()),
|
|
133
|
-
env,
|
|
134
|
-
shellEnv: options.shellEnv && typeof options.shellEnv === "object" ? (options.shellEnv as Record<string, string | undefined>) : env,
|
|
135
|
-
model: env[`ANTHROPIC_DEFAULT_${model.toUpperCase()}_MODEL`] || TIER_DEFAULTS[model] || model,
|
|
136
|
-
systemPrompt: typeof options.systemPrompt === "string" ? options.systemPrompt : "",
|
|
137
|
-
tools: [...names.map((n) => ENGINE_TOOLS[n]), ...extra],
|
|
138
|
-
maxTurns: typeof options.maxTurns === "number" && options.maxTurns > 0 ? options.maxTurns : null,
|
|
139
|
-
partial: options.includePartialMessages === true,
|
|
140
|
-
pre: hookFns(options.hooks, "PreToolUse"),
|
|
141
|
-
post: hookFns(options.hooks, "PostToolUse"),
|
|
142
|
-
canUseTool: typeof options.canUseTool === "function" ? (options.canUseTool as CanUseTool) : null,
|
|
143
|
-
outer: (options.abortController as AbortController | undefined)?.signal ?? null,
|
|
144
|
-
history: readHistory(options.history),
|
|
145
|
-
};
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/** An earlier conversation, checked: user and assistant turns that
|
|
149
|
-
* alternate, starting with the user's, each a list of content blocks. A
|
|
150
|
-
* turn that is not one is refused, not sent half-right to the model. */
|
|
151
|
-
function readHistory(raw: unknown): { role: string; content: Block[] }[] {
|
|
152
|
-
if (raw == null) return [];
|
|
153
|
-
if (!Array.isArray(raw)) throw new Error("history must be a list of turns");
|
|
154
|
-
return raw.map((t, i) => {
|
|
155
|
-
const role = (t as Json)?.role;
|
|
156
|
-
const content = (t as Json)?.content;
|
|
157
|
-
if (role !== (i % 2 === 0 ? "user" : "assistant")) throw new Error(`history turn ${i + 1} must be the ${i % 2 === 0 ? "user's" : "model's"}`);
|
|
158
|
-
if (!Array.isArray(content) || !content.every((b) => b && typeof (b as Json).type === "string")) throw new Error(`history turn ${i + 1} has no content blocks`);
|
|
159
|
-
return { role: String(role), content: content as Block[] };
|
|
160
|
-
});
|
|
161
|
-
}
|
|
162
|
-
|
|
163
52
|
function requestHeaders(env: Record<string, string | undefined>): Record<string, string> {
|
|
164
53
|
const headers: Record<string, string> = { "content-type": "application/json", "anthropic-version": API_VERSION };
|
|
165
54
|
if (env.ANTHROPIC_API_KEY) headers["x-api-key"] = env.ANTHROPIC_API_KEY;
|
|
@@ -200,8 +89,9 @@ export function endOf(stopReason: string | null, calls: number): { subtype: stri
|
|
|
200
89
|
}
|
|
201
90
|
}
|
|
202
91
|
|
|
203
|
-
export function buildRequest(o: Pick<LoopOptions, "model" | "systemPrompt" | "tools" | "env">, messages: { role: string; content: Block[] }[]): Json {
|
|
204
|
-
|
|
92
|
+
export function buildRequest(o: Pick<LoopOptions, "model" | "systemPrompt" | "tools" | "env">, messages: { role: string; content: Block[] }[], cache = true, maxTokens?: number): Json {
|
|
93
|
+
// A one-off request (a summary) writes nothing to the cache.
|
|
94
|
+
const mark = cache ? { cache_control: { type: "ephemeral" } } : {};
|
|
205
95
|
const tools = o.tools.map((t, i) => ({
|
|
206
96
|
name: t.name,
|
|
207
97
|
description: t.description,
|
|
@@ -216,7 +106,7 @@ export function buildRequest(o: Pick<LoopOptions, "model" | "systemPrompt" | "to
|
|
|
216
106
|
const asked = Number(o.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS);
|
|
217
107
|
return {
|
|
218
108
|
model: o.model,
|
|
219
|
-
max_tokens: Number.isFinite(asked) && asked > 0 ? asked : DEFAULT_MAX_TOKENS,
|
|
109
|
+
max_tokens: Math.min(maxTokens ?? Infinity, Number.isFinite(asked) && asked > 0 ? asked : DEFAULT_MAX_TOKENS),
|
|
220
110
|
...(o.systemPrompt ? { system: [{ type: "text", text: o.systemPrompt, ...mark }] } : {}),
|
|
221
111
|
...(tools.length ? { tools } : {}),
|
|
222
112
|
messages: sent,
|
|
@@ -250,7 +140,7 @@ async function openStream(o: LoopOptions, body: Json, signal: AbortSignal): Prom
|
|
|
250
140
|
const text = (await res.text().catch(() => "")).slice(0, 500);
|
|
251
141
|
lastError = `the model endpoint answered ${res.status}: ${text}`;
|
|
252
142
|
const retryable = res.status === 408 || res.status === 409 || res.status === 429 || res.status >= 500;
|
|
253
|
-
if (!retryable) throw new Error(lastError);
|
|
143
|
+
if (!retryable) throw Object.assign(new Error(lastError), { status: res.status });
|
|
254
144
|
const after = Number(res.headers.get("retry-after"));
|
|
255
145
|
if (attempt < MODEL_TRIES) await sleep(Math.min(RETRY_AFTER_CAP_MS, Number.isFinite(after) && after > 0 ? after * 1000 : 1000 * 2 ** (attempt - 1)), signal);
|
|
256
146
|
} else if (attempt < MODEL_TRIES) {
|
|
@@ -265,18 +155,29 @@ async function openStream(o: LoopOptions, body: Json, signal: AbortSignal): Prom
|
|
|
265
155
|
async function* sse(res: Response): AsyncGenerator<Json> {
|
|
266
156
|
const decoder = new TextDecoder();
|
|
267
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 = "";
|
|
268
162
|
for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {
|
|
269
|
-
|
|
270
|
-
|
|
163
|
+
let text = held + decoder.decode(chunk, { stream: true });
|
|
164
|
+
held = text.endsWith("\r") ? "\r" : "";
|
|
165
|
+
if (held) text = text.slice(0, -1);
|
|
166
|
+
buffer += text.replace(/\r\n?/g, "\n");
|
|
167
|
+
for (let at = buffer.indexOf("\n\n"); at >= 0; at = buffer.indexOf("\n\n")) {
|
|
271
168
|
const frame = buffer.slice(0, at);
|
|
272
|
-
buffer = buffer.slice(at
|
|
273
|
-
const data = frame.split(
|
|
169
|
+
buffer = buffer.slice(at + 2);
|
|
170
|
+
const data = frame.split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5).replace(/^ /, "")).join("\n");
|
|
274
171
|
if (!data || data === "[DONE]") continue;
|
|
172
|
+
let parsed: Json;
|
|
275
173
|
try {
|
|
276
|
-
|
|
174
|
+
parsed = JSON.parse(data) as Json;
|
|
277
175
|
} catch {
|
|
278
|
-
//
|
|
176
|
+
// A frame that is not JSON may be a lost piece of the reply: a reply
|
|
177
|
+
// missing words would otherwise pass as whole (Codex, 22 Nov 2026).
|
|
178
|
+
throw new Error("the model stream sent a frame that is not JSON — the reply cannot be trusted whole");
|
|
279
179
|
}
|
|
180
|
+
yield parsed;
|
|
280
181
|
}
|
|
281
182
|
}
|
|
282
183
|
}
|
|
@@ -291,22 +192,13 @@ interface Turn {
|
|
|
291
192
|
malformed: Set<string>;
|
|
292
193
|
}
|
|
293
194
|
|
|
294
|
-
const emptyUsage = (): Usage => ({ input_tokens: 0, output_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 });
|
|
295
|
-
|
|
296
|
-
function addUsage(into: Usage, u: Partial<Record<keyof Usage, unknown>> | undefined): void {
|
|
297
|
-
if (!u) return;
|
|
298
|
-
// The closing delta repeats the counts it knows; one that leaves the input
|
|
299
|
-
// side at zero is not saying the input was free.
|
|
300
|
-
for (const k of Object.keys(into) as (keyof Usage)[]) {
|
|
301
|
-
const v = u[k];
|
|
302
|
-
if (typeof v === "number" && (v > 0 || k === "output_tokens")) into[k] = v;
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
|
|
306
195
|
/** One model call: yields the raw stream events, returns the whole turn. */
|
|
307
|
-
async function* modelTurn(o: LoopOptions, messages: { role: string; content: Block[] }[], signal: AbortSignal): AsyncGenerator<Json, Turn> {
|
|
308
|
-
const res = await openStream(o, buildRequest(o, messages), signal);
|
|
196
|
+
async function* modelTurn(o: LoopOptions, messages: { role: string; content: Block[] }[], signal: AbortSignal, cache = true, maxTokens?: number, track?: { turn?: Turn }): AsyncGenerator<Json, Turn> {
|
|
197
|
+
const res = await openStream(o, buildRequest(o, messages, cache, maxTokens), signal);
|
|
309
198
|
const turn: Turn = { id: "", model: o.model, content: [], stopReason: null, usage: emptyUsage(), malformed: new Set() };
|
|
199
|
+
// A caller that must count what a stream that breaks part-way had
|
|
200
|
+
// already reported (a summary request) reads it here.
|
|
201
|
+
if (track) track.turn = turn;
|
|
310
202
|
const partialJson = new Map<number, string>();
|
|
311
203
|
const open = new Set<number>();
|
|
312
204
|
let stopped = false;
|
|
@@ -362,45 +254,6 @@ async function* modelTurn(o: LoopOptions, messages: { role: string; content: Blo
|
|
|
362
254
|
return turn;
|
|
363
255
|
}
|
|
364
256
|
|
|
365
|
-
interface Decision {
|
|
366
|
-
input: Json;
|
|
367
|
-
refusal: string | null;
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
/** May this call run, and with what input? The order the SDK kept, which
|
|
371
|
-
* step-exec's checks are written against: every PreToolUse hook first — a
|
|
372
|
-
* deny ends it, an allow carries the input the hook settled on and skips
|
|
373
|
-
* the question below — then canUseTool, where confinement lives. */
|
|
374
|
-
async function decide(o: LoopOptions, name: string, id: string, input: Json, sessionId: string, signal: AbortSignal): Promise<Decision> {
|
|
375
|
-
let current = input;
|
|
376
|
-
let allowed = false;
|
|
377
|
-
for (const hook of o.pre) {
|
|
378
|
-
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 });
|
|
379
|
-
const d = (out as { hookSpecificOutput?: { permissionDecision?: string; permissionDecisionReason?: string; updatedInput?: Json } } | undefined)?.hookSpecificOutput;
|
|
380
|
-
if (!d) continue;
|
|
381
|
-
if (d.permissionDecision === "deny") return { input: current, refusal: d.permissionDecisionReason || `${name} was refused` };
|
|
382
|
-
if (d.updatedInput) current = d.updatedInput;
|
|
383
|
-
if (d.permissionDecision === "allow") allowed = true;
|
|
384
|
-
}
|
|
385
|
-
if (!allowed && o.canUseTool) {
|
|
386
|
-
const r = await o.canUseTool(name, current, { signal, toolUseID: id });
|
|
387
|
-
if (r.behavior === "deny") return { input: current, refusal: r.message || `${name} was refused` };
|
|
388
|
-
if (r.updatedInput) current = r.updatedInput;
|
|
389
|
-
}
|
|
390
|
-
return { input: current, refusal: null };
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
/** After a call: tell the PostToolUse hooks, and collect what they add. */
|
|
394
|
-
async function after(o: LoopOptions, name: string, id: string, input: Json, outcome: ToolOutcome, sessionId: string, signal: AbortSignal): Promise<string[]> {
|
|
395
|
-
const added: string[] = [];
|
|
396
|
-
for (const hook of o.post) {
|
|
397
|
-
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 });
|
|
398
|
-
const context = (out as { hookSpecificOutput?: { additionalContext?: string } } | undefined)?.hookSpecificOutput?.additionalContext;
|
|
399
|
-
if (context) added.push(context);
|
|
400
|
-
}
|
|
401
|
-
return added;
|
|
402
|
-
}
|
|
403
|
-
|
|
404
257
|
async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interrupted: () => boolean): AsyncGenerator<Json> {
|
|
405
258
|
const sessionId = crypto.randomUUID();
|
|
406
259
|
const startedAt = Date.now();
|
|
@@ -427,14 +280,140 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
|
|
|
427
280
|
session_id: sessionId,
|
|
428
281
|
});
|
|
429
282
|
|
|
430
|
-
|
|
431
|
-
|
|
283
|
+
// The step's MCP servers, connected before the first model call: their
|
|
284
|
+
// tools sit after the built-in and host ones (engine-mcp.ts). One that
|
|
285
|
+
// does not start refuses the step here, before anything is paid for.
|
|
286
|
+
let mcp: McpConnection | null = null;
|
|
432
287
|
try {
|
|
288
|
+
if (Object.keys(o.mcpServers).length) {
|
|
289
|
+
mcp = await connectMcp(o.mcpServers, { env: o.env, toolEnv: o.shellEnv, cwd: o.cwd, signal });
|
|
290
|
+
for (const t of mcp.tools) {
|
|
291
|
+
if (byName.has(t.name)) throw new Error(`the MCP tool ${t.name} has the name of a tool the step already has`);
|
|
292
|
+
byName.set(t.name, t);
|
|
293
|
+
}
|
|
294
|
+
o.tools = [...o.tools, ...mcp.tools];
|
|
295
|
+
if (mcp.instructions.length) {
|
|
296
|
+
o.systemPrompt = [o.systemPrompt, "# MCP Server Instructions", ...mcp.instructions.map((i) => `## ${i.server}\n${i.text}`)].filter(Boolean).join("\n\n");
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
// A tool the step was granted that its server does not offer: the step
|
|
300
|
+
// would run without it, and the model be told it has none.
|
|
301
|
+
const missing = o.mcpGranted.filter((g) => mcp?.owner.get(g.name) !== g.server).map((g) => g.name);
|
|
302
|
+
if (missing.length) throw new Error(`granted but not offered by its MCP server: ${missing.join(", ")}`);
|
|
303
|
+
|
|
304
|
+
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" };
|
|
305
|
+
|
|
306
|
+
// ---- Compaction (engine-compact.ts). What the context holds is the last
|
|
307
|
+
// turn's own count (everything it was sent, and its reply) plus an
|
|
308
|
+
// estimate of what has been added since; before any turn, an estimate of
|
|
309
|
+
// it all.
|
|
310
|
+
let measured: { tokens: number; at: number } | null = null;
|
|
311
|
+
const filesRead = new Set<string>();
|
|
312
|
+
const filesChanged = new Set<string>();
|
|
313
|
+
let autoCompaction = o.compaction !== false;
|
|
314
|
+
const contextNow = (): number => {
|
|
315
|
+
if (measured) return measured.tokens + messages.slice(measured.at).reduce((n, m) => n + estimateTokens(m), 0);
|
|
316
|
+
const fixed = Math.ceil((o.systemPrompt.length + JSON.stringify(o.tools.map((t) => [t.name, t.description, t.input_schema])).length) / 4);
|
|
317
|
+
return fixed + messages.reduce((n, m) => n + estimateTokens(m), 0);
|
|
318
|
+
};
|
|
319
|
+
/** Summarise the older part and go on from the summary and the newest
|
|
320
|
+
* part. False, with the reason, when there is nothing to cut or the
|
|
321
|
+
* summary did not come back whole. */
|
|
322
|
+
// `asked`: a summary was asked for (and paid for) and did not come back.
|
|
323
|
+
async function* compactNow(trigger: "auto" | "overflow", before: number): AsyncGenerator<Json, { ok: boolean; asked?: boolean; why?: string }> {
|
|
324
|
+
if (o.compaction === false) return { ok: false, why: "compaction is off" };
|
|
325
|
+
const room = o.compaction.contextWindow - o.compaction.reserveTokens;
|
|
326
|
+
// The kept part leaves room for the summary (a few thousand tokens).
|
|
327
|
+
// After an overflow the real window is smaller than assumed: the kept
|
|
328
|
+
// part is held to the keep budget itself.
|
|
329
|
+
let cut = findCut(messages, o.compaction.keepRecentTokens, trigger === "overflow" ? o.compaction.keepRecentTokens : Math.max(0, room - 4_096));
|
|
330
|
+
if (cut < 1) return { ok: false, why: "there was nothing older to summarise" };
|
|
331
|
+
// A summary of a few words makes no room and is not worth paying for:
|
|
332
|
+
// a later cut is tried (the newest message is always kept).
|
|
333
|
+
const older = (c: number) => messages.slice(0, c).reduce((n, m) => n + estimateTokens(m), 0);
|
|
334
|
+
for (const later of cutPoints(messages)) if (later > cut && older(cut) < 1_024) cut = later;
|
|
335
|
+
if (older(cut) < 1_024) return { ok: false, why: "there was too little older to summarise" };
|
|
336
|
+
const ask = { ...o, systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, tools: [], partial: false };
|
|
337
|
+
// The request itself must fit: the conversation's text is held to the
|
|
338
|
+
// window less the reply's reserve and the prompts, newest part kept.
|
|
339
|
+
const request = [{ role: "user", content: [{ type: "text", text: summaryRequest(messages.slice(0, cut), previousSummary(messages), Math.max(4_000, (room - 3_000) * 4)) }] }];
|
|
340
|
+
let reply: Turn;
|
|
341
|
+
const track: { turn?: Turn } = {};
|
|
342
|
+
try {
|
|
343
|
+
// Its reply is held to the window's reserve: input and output must fit.
|
|
344
|
+
const stream = modelTurn(ask, request, signal, false, o.compaction.reserveTokens, track);
|
|
345
|
+
for (;;) {
|
|
346
|
+
const step = await stream.next();
|
|
347
|
+
if (step.done) { reply = step.value; break; }
|
|
348
|
+
}
|
|
349
|
+
} catch (err) {
|
|
350
|
+
// What the endpoint had counted before the stream broke was paid for.
|
|
351
|
+
const spent = track.turn?.usage;
|
|
352
|
+
if (spent && Object.values(spent).some((n) => n > 0)) {
|
|
353
|
+
for (const k of Object.keys(total) as (keyof Usage)[]) total[k] += spent[k];
|
|
354
|
+
yield { type: "system", subtype: "compact_failed", session_id: sessionId, error: `the summary request failed: ${(err as Error).message}`, model: track.turn!.model, usage: { ...spent } };
|
|
355
|
+
}
|
|
356
|
+
if (signal.aborted) throw err;
|
|
357
|
+
return { ok: false, asked: true, why: `the summary request failed: ${(err as Error).message}` };
|
|
358
|
+
}
|
|
359
|
+
// Paid for like any turn: in the total, and reported with what it
|
|
360
|
+
// came to so the step's cost and budget count it (step-exec).
|
|
361
|
+
for (const k of Object.keys(total) as (keyof Usage)[]) total[k] += reply.usage[k];
|
|
362
|
+
const summary = reply.content.filter((b) => b.type === "text").map((b) => String(b.text ?? "")).join("\n").trim();
|
|
363
|
+
if (reply.stopReason !== "end_turn" || reply.content.some((b) => b.type === "tool_use") || !summary) {
|
|
364
|
+
const why = `the summary did not come back whole (stop reason ${reply.stopReason ?? "none"})`;
|
|
365
|
+
yield { type: "system", subtype: "compact_failed", session_id: sessionId, error: why, model: reply.model, usage: { ...reply.usage } };
|
|
366
|
+
return { ok: false, asked: true, why };
|
|
367
|
+
}
|
|
368
|
+
const next = compacted(summary + fileLists(filesRead, filesChanged), messages.slice(cut));
|
|
369
|
+
messages.splice(0, messages.length, ...next);
|
|
370
|
+
measured = null;
|
|
371
|
+
yield {
|
|
372
|
+
type: "system",
|
|
373
|
+
subtype: "compact_boundary",
|
|
374
|
+
session_id: sessionId,
|
|
375
|
+
compact_metadata: { trigger, pre_tokens: before, post_tokens: contextNow(), summarized_messages: cut },
|
|
376
|
+
model: reply.model,
|
|
377
|
+
usage: { ...reply.usage },
|
|
378
|
+
// The conversation as it now stands, so a caller that keeps one
|
|
379
|
+
// (foldrun code) goes on from it rather than the whole history.
|
|
380
|
+
conversation: messages.map((m) => ({ role: m.role, content: [...m.content] })),
|
|
381
|
+
};
|
|
382
|
+
return { ok: true };
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// Set when a request was refused as too long and compacted: the same
|
|
386
|
+
// request is asked again once, not compacted again and again.
|
|
387
|
+
let overflowed = false;
|
|
433
388
|
for (;;) {
|
|
434
389
|
if (o.maxTurns !== null && turns >= o.maxTurns) {
|
|
435
390
|
yield result("error_max_turns", null);
|
|
436
391
|
return;
|
|
437
392
|
}
|
|
393
|
+
// Not on the retry after an overflow (that request is asked again as
|
|
394
|
+
// compacted), and not while the model's own turn is being continued
|
|
395
|
+
// (pause_turn): the conversation must end on a user turn to be cut.
|
|
396
|
+
if (autoCompaction && !overflowed && o.compaction !== false && messages.at(-1)?.role === "user") {
|
|
397
|
+
const now = contextNow();
|
|
398
|
+
if (now > o.compaction.contextWindow - o.compaction.reserveTokens) {
|
|
399
|
+
let done: { ok: boolean; asked?: boolean; why?: string };
|
|
400
|
+
try {
|
|
401
|
+
done = yield* compactNow("auto", now);
|
|
402
|
+
} catch (err) {
|
|
403
|
+
if (interrupted() || signal.aborted) return;
|
|
404
|
+
throw err;
|
|
405
|
+
}
|
|
406
|
+
if (interrupted() || signal.aborted) return;
|
|
407
|
+
// A summary asked for and not given is not asked for again before
|
|
408
|
+
// every turn after: the request goes as it is, and the endpoint says
|
|
409
|
+
// if it is too long. Nothing to cut yet costs nothing: looked at
|
|
410
|
+
// again next turn.
|
|
411
|
+
if (!done.ok && done.asked) autoCompaction = false;
|
|
412
|
+
// A summary that could not bring the context under the line will
|
|
413
|
+
// not by summarising again before every turn.
|
|
414
|
+
if (done.ok && contextNow() > o.compaction.contextWindow - o.compaction.reserveTokens) autoCompaction = false;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
438
417
|
let turn: Turn;
|
|
439
418
|
try {
|
|
440
419
|
const stream = modelTurn(o, messages, signal);
|
|
@@ -450,9 +429,19 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
|
|
|
450
429
|
// An interrupt we were asked for ends the loop quietly: the caller
|
|
451
430
|
// knows why and reports it. Anything else is the step's failure.
|
|
452
431
|
if (interrupted() || signal.aborted) return;
|
|
432
|
+
// The endpoint said the prompt does not fit (a model with a smaller
|
|
433
|
+
// window than assumed): compact and ask again — once per request.
|
|
434
|
+
if (!overflowed && o.compaction !== false && messages.at(-1)?.role === "user" && isContextOverflow((err as { status?: number }).status, (err as Error).message)) {
|
|
435
|
+
overflowed = true;
|
|
436
|
+
const done = yield* compactNow("overflow", contextNow());
|
|
437
|
+
if (interrupted() || signal.aborted) return;
|
|
438
|
+
if (!done.ok) throw new Error(`${(err as Error).message} — and the conversation could not be compacted: ${done.why}`);
|
|
439
|
+
continue;
|
|
440
|
+
}
|
|
453
441
|
throw err;
|
|
454
442
|
}
|
|
455
443
|
turns++;
|
|
444
|
+
overflowed = false;
|
|
456
445
|
for (const k of Object.keys(total) as (keyof Usage)[]) total[k] += turn.usage[k];
|
|
457
446
|
const text = turn.content.filter((b) => b.type === "text").map((b) => String(b.text ?? "")).join("\n").trim();
|
|
458
447
|
if (text) lastText = text;
|
|
@@ -462,7 +451,13 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
|
|
|
462
451
|
parent_tool_use_id: null,
|
|
463
452
|
session_id: sessionId,
|
|
464
453
|
};
|
|
465
|
-
|
|
454
|
+
// A paused turn's continuation is the same turn: joined to it, so the
|
|
455
|
+
// conversation still alternates (what foldrun code keeps, and a cut).
|
|
456
|
+
const prev = messages[messages.length - 1];
|
|
457
|
+
if (prev?.role === "assistant") prev.content = [...prev.content, ...turn.content];
|
|
458
|
+
else messages.push({ role: "assistant", content: turn.content });
|
|
459
|
+
// The turn's own count: all it was sent, and its reply.
|
|
460
|
+
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 };
|
|
466
461
|
if (interrupted()) return;
|
|
467
462
|
|
|
468
463
|
const calls = turn.content.filter((b) => b.type === "tool_use");
|
|
@@ -499,6 +494,12 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
|
|
|
499
494
|
} catch (err) {
|
|
500
495
|
outcome = { text: `${p.tool.name} failed: ${(err as Error).message}`, isError: true };
|
|
501
496
|
}
|
|
497
|
+
// For a summary's file lists: what ran, as the hooks left it, and did not fail.
|
|
498
|
+
const file = p.decision.input.file_path;
|
|
499
|
+
if (!outcome.isError && typeof file === "string") {
|
|
500
|
+
if (p.tool.name === "Read") filesRead.add(file);
|
|
501
|
+
else if (p.tool.name === "Write" || p.tool.name === "Edit") filesChanged.add(file);
|
|
502
|
+
}
|
|
502
503
|
const context = await after(o, p.tool.name, String(p.block.id), p.decision.input, outcome, sessionId, signal);
|
|
503
504
|
return { outcome, context };
|
|
504
505
|
};
|
|
@@ -522,12 +523,15 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
|
|
|
522
523
|
}
|
|
523
524
|
if (interrupted()) return;
|
|
524
525
|
|
|
525
|
-
const results: Block[] = planned.map((p, i) =>
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
526
|
+
const results: Block[] = planned.map((p, i) => {
|
|
527
|
+
const { text, isError, parts } = done[i].outcome;
|
|
528
|
+
// An image a tool returned (an MCP server's screenshot) goes to the
|
|
529
|
+
// model as an image, in its place among the text.
|
|
530
|
+
const content = parts
|
|
531
|
+
? parts.map((p) => p.type === "text" ? { type: "text", text: p.text } : { type: "image", source: { type: "base64", media_type: p.mediaType, data: p.data } })
|
|
532
|
+
: text;
|
|
533
|
+
return { type: "tool_result", tool_use_id: String(p.block.id), content, ...(isError ? { is_error: true } : {}) };
|
|
534
|
+
});
|
|
531
535
|
const context = done.flatMap((d) => d.context);
|
|
532
536
|
const content: Block[] = [...results, ...context.map((c) => ({ type: "text", text: c }))];
|
|
533
537
|
messages.push({ role: "user", content });
|
|
@@ -535,8 +539,10 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
|
|
|
535
539
|
}
|
|
536
540
|
} finally {
|
|
537
541
|
// However the loop ended — an answer, a stop, a consumer that walked
|
|
538
|
-
// away — nothing a command started outlives the step
|
|
542
|
+
// away — nothing a command started outlives the step, and no MCP server
|
|
543
|
+
// it started either.
|
|
539
544
|
killGroups(ctx);
|
|
545
|
+
await mcp?.close();
|
|
540
546
|
}
|
|
541
547
|
}
|
|
542
548
|
|