@foldrun/core 24.8.1 → 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 +16 -0
- package/dist/src/engine-common.js +22 -4
- package/dist/src/engine-compact.d.ts +61 -0
- package/dist/src/engine-compact.js +293 -0
- package/dist/src/engine-loop.d.ts +1 -1
- package/dist/src/engine-loop.js +199 -15
- 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 +30 -4
- package/src/engine-compact.ts +288 -0
- package/src/engine-loop.ts +175 -16
- 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/runner.js
CHANGED
|
@@ -90,7 +90,7 @@ export { localDate } from "./clock.js";
|
|
|
90
90
|
* name and the proxy fills it, as for an http tool. */
|
|
91
91
|
export function unbindMcpHeaders(servers, bound, values, grant) {
|
|
92
92
|
const known = Object.fromEntries(bound.filter((n) => n in values).map((n) => [n, values[n]]));
|
|
93
|
-
const out =
|
|
93
|
+
const out = Object.create(null);
|
|
94
94
|
for (const [name, server] of Object.entries(servers)) {
|
|
95
95
|
if (server.type !== "http") {
|
|
96
96
|
out[name] = server;
|
|
@@ -1086,7 +1086,8 @@ grantsOnly = false) {
|
|
|
1086
1086
|
// MCP servers an agent connects to. `mcpServers:` is Claude Code's spelling
|
|
1087
1087
|
// for the inline form; a `type: mcp` tool file is the shared form. Both end
|
|
1088
1088
|
// up here, and both reach the model as ordinary MCP tools.
|
|
1089
|
-
|
|
1089
|
+
// No prototype: a server an agent names __proto__ is a server.
|
|
1090
|
+
const mcpServers = Object.create(null);
|
|
1090
1091
|
const mcpNames = [];
|
|
1091
1092
|
// What the granted tools' programs need — merged into this step's runtime
|
|
1092
1093
|
// below. The tool is the unit of code, so its dependencies live in tool.md
|
|
@@ -47,7 +47,9 @@ export declare function commandFor(spec: ScriptSpec, abs: string, overrides?: Re
|
|
|
47
47
|
cmd: string;
|
|
48
48
|
args: string[];
|
|
49
49
|
};
|
|
50
|
-
export declare function runScript(cwd: string, spec: ScriptSpec, values: Record<string, string>, env: Record<string, string>, libraryScripts: string, interpreters: Record<string, string>, exec: ExecutionContext | null
|
|
50
|
+
export declare function runScript(cwd: string, spec: ScriptSpec, values: Record<string, string>, env: Record<string, string>, libraryScripts: string, interpreters: Record<string, string>, exec: ExecutionContext | null,
|
|
51
|
+
/** A stop for the call (the MCP request's): the script ends with it. */
|
|
52
|
+
signal?: AbortSignal): Promise<{
|
|
51
53
|
code: number | null;
|
|
52
54
|
out: string;
|
|
53
55
|
}>;
|
package/dist/src/script-tools.js
CHANGED
|
@@ -126,7 +126,9 @@ function containerInterpreter(abs) {
|
|
|
126
126
|
};
|
|
127
127
|
return byExt[path.extname(abs).toLowerCase()] ?? abs;
|
|
128
128
|
}
|
|
129
|
-
export function runScript(cwd, spec, values, env, libraryScripts, interpreters, exec
|
|
129
|
+
export function runScript(cwd, spec, values, env, libraryScripts, interpreters, exec,
|
|
130
|
+
/** A stop for the call (the MCP request's): the script ends with it. */
|
|
131
|
+
signal) {
|
|
130
132
|
// An inline-code tool has no file yet: write it inside the agent's own
|
|
131
133
|
// directory — already an allowed root — and run it like any other script.
|
|
132
134
|
// Materialised per call rather than per build, so an edit to the tool's
|
|
@@ -228,11 +230,36 @@ export function runScript(cwd, spec, values, env, libraryScripts, interpreters,
|
|
|
228
230
|
// base and gets what the agent declared, by name — see host-env.ts.
|
|
229
231
|
// In a run container `env` already carries the container's whole
|
|
230
232
|
// environment, which is the boundary, so nothing is lost there.
|
|
233
|
+
const ownGroup = process.platform !== "win32" && !process.stdout.isTTY && !process.stdin.isTTY;
|
|
231
234
|
const child = spawn(cmd, args, {
|
|
232
235
|
cwd,
|
|
233
236
|
env: workspaceLinkEnv({ ...hostSafeEnv(), ...env }, cwd),
|
|
234
237
|
timeout: timeoutFor(spec),
|
|
238
|
+
// Unattended (no terminal: the platform, a schedule), a script leads
|
|
239
|
+
// its own process group, so a stop ends what it started too — a
|
|
240
|
+
// leftover child could otherwise write over a retry's output. At a
|
|
241
|
+
// terminal it stays in this process's group, so Ctrl-C reaches it.
|
|
242
|
+
detached: ownGroup,
|
|
235
243
|
});
|
|
244
|
+
// A stopped step stops its script: the call's stop kills it (its group
|
|
245
|
+
// when it has one). A container run's script is not followed — as on
|
|
246
|
+
// the SDK path before.
|
|
247
|
+
const stop = () => {
|
|
248
|
+
stopped = true;
|
|
249
|
+
try {
|
|
250
|
+
if (ownGroup && child.pid)
|
|
251
|
+
process.kill(-child.pid, "SIGKILL");
|
|
252
|
+
else
|
|
253
|
+
child.kill("SIGKILL");
|
|
254
|
+
}
|
|
255
|
+
catch { /* already gone */ }
|
|
256
|
+
};
|
|
257
|
+
let stopped = false;
|
|
258
|
+
if (signal?.aborted)
|
|
259
|
+
stop();
|
|
260
|
+
else
|
|
261
|
+
signal?.addEventListener("abort", stop, { once: true });
|
|
262
|
+
child.on("close", () => signal?.removeEventListener("abort", stop));
|
|
236
263
|
let out = "";
|
|
237
264
|
const append = (chunk) => {
|
|
238
265
|
if (out.length < MAX_OUTPUT)
|
|
@@ -243,9 +270,10 @@ export function runScript(cwd, spec, values, env, libraryScripts, interpreters,
|
|
|
243
270
|
child.on("error", (err) => resolve({ code: null, out: `failed to start: ${err.message}` }));
|
|
244
271
|
child.on("close", (code) => resolve({
|
|
245
272
|
code,
|
|
246
|
-
out:
|
|
247
|
-
|
|
248
|
-
|
|
273
|
+
out: (stopped ? "stopped: the step was stopped\n" : "") +
|
|
274
|
+
(out.length > MAX_OUTPUT
|
|
275
|
+
? `${out.slice(0, MAX_OUTPUT)}\n…[truncated]`
|
|
276
|
+
: out || "(no output)"),
|
|
249
277
|
}));
|
|
250
278
|
});
|
|
251
279
|
}
|
|
@@ -356,10 +384,10 @@ readable = () => false) {
|
|
|
356
384
|
const shape = scriptArgShape(spec.args);
|
|
357
385
|
return tool(spec.name, `${spec.description || `Run ${spec.run}.`} Runs the workspace script ${spec.run}; returns its output. ` +
|
|
358
386
|
`Credentials it needs are already in its environment.` +
|
|
359
|
-
(spec.guide ? `\n\nHow to use it (from its tool.md):\n${spec.guide}` : ""), shape, async (args) => {
|
|
387
|
+
(spec.guide ? `\n\nHow to use it (from its tool.md):\n${spec.guide}` : ""), shape, async (args, extra) => {
|
|
360
388
|
const started = Date.now();
|
|
361
389
|
const values = Object.fromEntries(Object.entries(args ?? {}).map(([k, v]) => [k, v === undefined ? "" : String(v)]));
|
|
362
|
-
const { code, out } = await runScript(agentDir, spec, values, env, libraryScripts, interpreters, exec);
|
|
390
|
+
const { code, out } = await runScript(agentDir, spec, values, env, libraryScripts, interpreters, exec, extra?.signal);
|
|
363
391
|
// The arguments, on the record. Without them a run says a script was
|
|
364
392
|
// called and not what it was asked to do — and for a script that
|
|
365
393
|
// writes to someone else's system, "it ran" is not an account of what
|
package/dist/src/step-exec.d.ts
CHANGED
|
@@ -82,6 +82,12 @@ export interface ExecOptions {
|
|
|
82
82
|
* Only for a person's own machine, on their word; a run container is
|
|
83
83
|
* its own boundary and needs nothing said (`sandboxBash: false`). */
|
|
84
84
|
engineHostShell?: boolean;
|
|
85
|
+
/** foldrun's loop: the model's context window in tokens, when it is not
|
|
86
|
+
* the 200k the loop assumes — compaction starts 16k short of it. */
|
|
87
|
+
contextWindow?: number;
|
|
88
|
+
/** foldrun's loop: false turns compaction off (a step that must see its
|
|
89
|
+
* whole conversation, or fail). */
|
|
90
|
+
compaction?: false;
|
|
85
91
|
agentDir: string;
|
|
86
92
|
workspaceRoot: string;
|
|
87
93
|
libraryRoot: string;
|
package/dist/src/step-exec.js
CHANGED
|
@@ -24,6 +24,7 @@ import { hostSafeEnv } from "./host-env.js";
|
|
|
24
24
|
import { validateSchema, describeSchemaErrors, looksLikeSchema } from "./json-schema.js";
|
|
25
25
|
import { CallCounter, callKeysFor, REFUSALS_BEFORE_STOP } from "./limits.js";
|
|
26
26
|
import { classifyCall, podAt, readPodEvents } from "./browser-pod.js";
|
|
27
|
+
import { grantedServer } from "./engine-mcp.js";
|
|
27
28
|
/** The four counts from one SDK usage object (snake_case, as the API
|
|
28
29
|
* reports it). The API counts fresh input apart from the cache's; here
|
|
29
30
|
* `inputTokens` is all of it, as it always was on the record, and the
|
|
@@ -186,6 +187,16 @@ async function executeStepInner(opts, runQuery) {
|
|
|
186
187
|
// its own list, a path outside the workspace, a shell command — names the
|
|
187
188
|
// agent that tried, not just the step.
|
|
188
189
|
const subagentNames = new Map();
|
|
190
|
+
// An MCP tool is granted when the server it belongs to is. Its server is
|
|
191
|
+
// read against the step's own server names, the longest first: with
|
|
192
|
+
// servers `sales` and `sales__eu`, `mcp__sales__eu__find` is sales__eu's,
|
|
193
|
+
// and granting `sales` does not grant it. A name no server of the step's
|
|
194
|
+
// claims falls back to the prefix it always matched on.
|
|
195
|
+
const serverNames = Object.keys(opts.mcpServers ?? {});
|
|
196
|
+
const fromGrantedMcp = (toolName) => {
|
|
197
|
+
const g = grantedServer(toolName, serverNames);
|
|
198
|
+
return g ? g.tool !== null && opts.mcpNames.includes(g.server) : opts.mcpNames.some((n) => toolName.startsWith(`mcp__${n}__`));
|
|
199
|
+
};
|
|
189
200
|
// `limits:` — this step's counts. A new step, a retry of one, or a
|
|
190
201
|
// fan-out instance each start from zero.
|
|
191
202
|
const counter = new CallCounter(opts.limits);
|
|
@@ -274,6 +285,10 @@ async function executeStepInner(opts, runQuery) {
|
|
|
274
285
|
// path (the CLI on someone's laptop, and the host executor) keeps it,
|
|
275
286
|
// because there a shell escape reaches the real machine.
|
|
276
287
|
...(opts.engineHostShell ? { engineHostShell: true } : {}),
|
|
288
|
+
// foldrun's loop only: the model's context window for compaction, or
|
|
289
|
+
// compaction off (engine-compact.ts). The SDK compacts by its own rules.
|
|
290
|
+
...(opts.contextWindow ? { contextWindow: opts.contextWindow } : {}),
|
|
291
|
+
...(opts.compaction === false ? { compaction: false } : {}),
|
|
277
292
|
sandbox: {
|
|
278
293
|
enabled: opts.sandboxBash !== false,
|
|
279
294
|
// Must stay false. Auto-allowing bash because it's sandboxed skips
|
|
@@ -368,7 +383,7 @@ async function executeStepInner(opts, runQuery) {
|
|
|
368
383
|
: isFilesystemTool(hookInput.tool_name)
|
|
369
384
|
? checkPaths(hookInput.tool_name, v.input, { agentDir, workspaceRoot, libraryRoot, configWrites: opts.configWrites })
|
|
370
385
|
: { ok: true };
|
|
371
|
-
const granted = opts.allowed.includes(hookInput.tool_name) ||
|
|
386
|
+
const granted = opts.allowed.includes(hookInput.tool_name) || fromGrantedMcp(hookInput.tool_name);
|
|
372
387
|
// The sub-agent guard read the ORIGINAL input: a rewrite of a
|
|
373
388
|
// delegation could otherwise swap subagent_type for one this
|
|
374
389
|
// step never declared (or the SDK's general-purpose).
|
|
@@ -427,7 +442,7 @@ async function executeStepInner(opts, runQuery) {
|
|
|
427
442
|
const via = options?.agentID ? (subagentNames.get(options.agentID) ?? "subagent") : undefined;
|
|
428
443
|
// The toolset was already narrowed to what the agent declared, so
|
|
429
444
|
// anything outside it is a denial with a reason the model can act on.
|
|
430
|
-
const fromGrantedServer =
|
|
445
|
+
const fromGrantedServer = fromGrantedMcp(toolName);
|
|
431
446
|
// A call the hook counted and this refuses never ran: give it back.
|
|
432
447
|
const refund = () => { if (counter.active)
|
|
433
448
|
counter.refund(callKeysFor(toolName, input, opts.toolOwners)); };
|
|
@@ -610,6 +625,32 @@ async function executeStepInner(opts, runQuery) {
|
|
|
610
625
|
// before the SDK and its MCP servers started.
|
|
611
626
|
if (message.type === "system" && message.subtype === "init")
|
|
612
627
|
loopStartedAt = Date.now();
|
|
628
|
+
if (message.type === "system" && message.subtype === "compact_boundary") {
|
|
629
|
+
// The conversation neared the model's context window; its older part
|
|
630
|
+
// was summarised (foldrun's loop: engine-compact.ts; the SDK: its own).
|
|
631
|
+
const meta = message.compact_metadata;
|
|
632
|
+
emit("info", `compacted the conversation${meta?.pre_tokens ? ` from about ${meta.pre_tokens.toLocaleString("en")} tokens` : ""}${meta?.post_tokens ? ` to about ${meta.post_tokens.toLocaleString("en")}` : ""}${meta?.trigger === "overflow" ? " (the model said it was too long)" : ""}`);
|
|
633
|
+
}
|
|
634
|
+
if (message.type === "system" && message.subtype === "compact_failed") {
|
|
635
|
+
emit("info", `could not compact the conversation: ${String(message.error ?? "no reason given")}`);
|
|
636
|
+
}
|
|
637
|
+
// A summary request (foldrun's loop) is a model call like any turn: its
|
|
638
|
+
// tokens are in the step's cost, and its budget, whether or not the
|
|
639
|
+
// summary was used.
|
|
640
|
+
const compactUsage = message.type === "system" && /^compact_(boundary|failed)$/.test(String(message.subtype))
|
|
641
|
+
? message.usage
|
|
642
|
+
: undefined;
|
|
643
|
+
if (compactUsage) {
|
|
644
|
+
turns.set(`compaction-${anonymousTurns++}`, { u: compactUsage, price: priceOf(message) });
|
|
645
|
+
if (ceiling) {
|
|
646
|
+
spentUsd = turnsTotal();
|
|
647
|
+
if (spentUsd >= ceiling) {
|
|
648
|
+
emit("error", `over budget — this step reached $${spentUsd.toFixed(4)} of its $${ceiling.toFixed(4)} ceiling mid-turn and was stopped (${opts.budgetNote ?? "budget: in the flow file"})`);
|
|
649
|
+
status = "failed";
|
|
650
|
+
break;
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
}
|
|
613
654
|
if (message.type === "stream_event") {
|
|
614
655
|
const ev = message.event;
|
|
615
656
|
const agentKey = message.parent_tool_use_id ?? "";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@foldrun/core",
|
|
3
|
-
"version": "24.
|
|
3
|
+
"version": "24.9.0",
|
|
4
4
|
"description": "Agents are just folders. The format, the runner, the checks.",
|
|
5
5
|
"license": "FSL-1.1-ALv2",
|
|
6
6
|
"type": "module",
|
|
@@ -61,6 +61,7 @@
|
|
|
61
61
|
},
|
|
62
62
|
"dependencies": {
|
|
63
63
|
"@anthropic-ai/claude-agent-sdk": "^0.3.296",
|
|
64
|
+
"@modelcontextprotocol/sdk": "1.32.1",
|
|
64
65
|
"gray-matter": "^4.0.3",
|
|
65
66
|
"zod": "4.6.7"
|
|
66
67
|
},
|
package/src/engine-common.ts
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
// @foldrun/core's public API.
|
|
7
7
|
|
|
8
8
|
import { ENGINE_TOOLS, type EngineTool, type ToolOutcome } from "./engine-tools.ts";
|
|
9
|
+
import { checkMcpSpecs, grantedServer, type McpSpec } from "./engine-mcp.ts";
|
|
10
|
+
import { COMPACTION_DEFAULTS, MIN_CONTEXT_WINDOW, compactionFor } from "./engine-compact.ts";
|
|
9
11
|
|
|
10
12
|
export const DEFAULT_MAX_TOKENS = 16_000;
|
|
11
13
|
|
|
@@ -60,6 +62,14 @@ export interface LoopOptions {
|
|
|
60
62
|
/** The conversation so far, before this prompt: earlier user turns, the
|
|
61
63
|
* model's replies and tool results, as the loop yielded them. */
|
|
62
64
|
history: { role: string; content: Block[] }[];
|
|
65
|
+
/** The step's MCP servers (engine-mcp.ts), connected when the loop starts. */
|
|
66
|
+
mcpServers: Record<string, McpSpec>;
|
|
67
|
+
/** MCP tools the step was granted by name, with the server each names:
|
|
68
|
+
* each must be offered by that server once connected, or the step is refused. */
|
|
69
|
+
mcpGranted: { name: string; server: string }[];
|
|
70
|
+
/** Compaction (engine-compact.ts): the model's context window, and false
|
|
71
|
+
* when the caller turned it off (`compaction: false`). */
|
|
72
|
+
compaction: { contextWindow: number; reserveTokens: number; keepRecentTokens: number } | false;
|
|
63
73
|
}
|
|
64
74
|
|
|
65
75
|
export function hookFns(hooks: unknown, event: string): HookFn[] {
|
|
@@ -72,14 +82,25 @@ export function hookFns(hooks: unknown, event: string): HookFn[] {
|
|
|
72
82
|
/** `engine` names the loop in what it refuses. */
|
|
73
83
|
export function readOptions(options: Json, engine = "foldrun"): LoopOptions {
|
|
74
84
|
const env = (options.env as Record<string, string | undefined> | undefined) ?? process.env;
|
|
75
|
-
const
|
|
85
|
+
const listed = Array.isArray(options.tools) ? (options.tools as unknown[]).map(String) : [];
|
|
86
|
+
// A granted MCP tool (`mcp__<server>__<tool>`, what the runner lists for
|
|
87
|
+
// web, apis, scripts, a2a, ask…) comes from its server, connected when the
|
|
88
|
+
// loop starts; its server must be one of the step's.
|
|
89
|
+
const mcpGranted = listed.filter((n) => n.startsWith("mcp__"));
|
|
90
|
+
const names = listed.filter((n) => !n.startsWith("mcp__"));
|
|
76
91
|
const unsupported = names.filter((n) => !ENGINE_TOOLS[n]);
|
|
77
92
|
if (unsupported.length) {
|
|
78
93
|
throw new Error(`the ${engine} engine has no tool named ${unsupported.join(", ")} yet — it has ${Object.keys(ENGINE_TOOLS).join(", ")}. Run this agent on the default engine.`);
|
|
79
94
|
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
95
|
+
// MCP servers: checked here, connected when the loop starts (engine-mcp.ts).
|
|
96
|
+
const mcpServers = checkMcpSpecs((options.mcpServers as Json | undefined) ?? {}, engine);
|
|
97
|
+
// A whole server granted (`mcp__crm`, `mcp__crm__*`) needs only the
|
|
98
|
+
// server; a tool granted by name must be offered by it once connected.
|
|
99
|
+
const mcpTools: { name: string; server: string }[] = [];
|
|
100
|
+
for (const n of mcpGranted) {
|
|
101
|
+
const g = grantedServer(n, Object.keys(mcpServers));
|
|
102
|
+
if (!g) throw new Error(`the tool ${n} was granted, but the step has no MCP server for it`);
|
|
103
|
+
if (g.tool) mcpTools.push({ name: g.tool, server: g.server });
|
|
83
104
|
}
|
|
84
105
|
if (options.agents && Object.keys(options.agents as Json).length) {
|
|
85
106
|
throw new Error(`the ${engine} engine does not run sub-agents yet — run this agent on the default engine.`);
|
|
@@ -117,6 +138,11 @@ export function readOptions(options: Json, engine = "foldrun"): LoopOptions {
|
|
|
117
138
|
canUseTool: typeof options.canUseTool === "function" ? (options.canUseTool as CanUseTool) : null,
|
|
118
139
|
outer: (options.abortController as AbortController | undefined)?.signal ?? null,
|
|
119
140
|
history: readHistory(options.history),
|
|
141
|
+
mcpServers,
|
|
142
|
+
mcpGranted: mcpTools,
|
|
143
|
+
compaction: options.compaction === false ? false : compactionFor(
|
|
144
|
+
typeof options.contextWindow === "number" && Number.isFinite(options.contextWindow) && options.contextWindow >= MIN_CONTEXT_WINDOW ? Math.floor(options.contextWindow) : COMPACTION_DEFAULTS.contextWindow,
|
|
145
|
+
),
|
|
120
146
|
};
|
|
121
147
|
}
|
|
122
148
|
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
// Compaction for foldrun's own loop (FOL-213): a conversation nearing the
|
|
2
|
+
// model's context window has its older part summarised, so a long session
|
|
3
|
+
// goes on instead of failing with "the conversation filled the model's
|
|
4
|
+
// context window".
|
|
5
|
+
//
|
|
6
|
+
// The approach and the summary prompts are Pi's (earendil-works/pi,
|
|
7
|
+
// packages/coding-agent, core/compaction), ported to the loop's
|
|
8
|
+
// Anthropic-shaped messages:
|
|
9
|
+
// - keep the newest ~20k tokens as they are;
|
|
10
|
+
// - cut only at a user turn or a model turn — never between a tool call
|
|
11
|
+
// and its result, which must follow it;
|
|
12
|
+
// - the model writes a structured checkpoint (Goal, Constraints, Progress,
|
|
13
|
+
// Decisions, Next steps, Critical context) of everything before the cut;
|
|
14
|
+
// a later compaction updates the earlier summary rather than summarising
|
|
15
|
+
// a summary;
|
|
16
|
+
// - the files read and changed are listed after it, from the calls that
|
|
17
|
+
// actually ran (the input as the hooks left it, and only calls that did
|
|
18
|
+
// not fail) — not from what the model asked for.
|
|
19
|
+
//
|
|
20
|
+
// Pi is under the MIT licence:
|
|
21
|
+
//
|
|
22
|
+
// MIT License
|
|
23
|
+
//
|
|
24
|
+
// Copyright (c) 2025 Mario Zechner
|
|
25
|
+
//
|
|
26
|
+
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
27
|
+
// of this software and associated documentation files (the "Software"), to deal
|
|
28
|
+
// in the Software without restriction, including without limitation the rights
|
|
29
|
+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
30
|
+
// copies of the Software, and to permit persons to whom the Software is
|
|
31
|
+
// furnished to do so, subject to the following conditions:
|
|
32
|
+
//
|
|
33
|
+
// The above copyright notice and this permission notice shall be included in all
|
|
34
|
+
// copies or substantial portions of the Software.
|
|
35
|
+
//
|
|
36
|
+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
37
|
+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
38
|
+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
39
|
+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
40
|
+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
41
|
+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
42
|
+
// SOFTWARE.
|
|
43
|
+
|
|
44
|
+
type Json = Record<string, unknown>;
|
|
45
|
+
type Block = Json & { type: string };
|
|
46
|
+
export type Message = { role: string; content: Block[] };
|
|
47
|
+
|
|
48
|
+
/** What the loop uses unless a caller says otherwise: Pi's defaults, and
|
|
49
|
+
* the context window of the Claude models foldrun's tiers name. A model
|
|
50
|
+
* with a smaller window is still caught when the endpoint says the prompt
|
|
51
|
+
* is too long (the loop compacts then and asks again, once). */
|
|
52
|
+
export const COMPACTION_DEFAULTS = { contextWindow: 200_000, reserveTokens: 16_384, keepRecentTokens: 20_000 };
|
|
53
|
+
/** The smallest window compaction will work in. */
|
|
54
|
+
export const MIN_CONTEXT_WINDOW = 8_192;
|
|
55
|
+
|
|
56
|
+
/** Pi's numbers for a large window; a small one keeps a quarter for the
|
|
57
|
+
* reply and summarises down to about a third of it. */
|
|
58
|
+
export function compactionFor(contextWindow: number): { contextWindow: number; reserveTokens: number; keepRecentTokens: number } {
|
|
59
|
+
return {
|
|
60
|
+
contextWindow,
|
|
61
|
+
reserveTokens: Math.min(COMPACTION_DEFAULTS.reserveTokens, Math.floor(contextWindow / 4)),
|
|
62
|
+
keepRecentTokens: Math.min(COMPACTION_DEFAULTS.keepRecentTokens, Math.floor(contextWindow * 0.3)),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export const SUMMARY_PREFIX = "The conversation history before this point was compacted into the following summary:\n\n<summary>\n";
|
|
67
|
+
const SUMMARY_SUFFIX = "\n</summary>";
|
|
68
|
+
|
|
69
|
+
export const SUMMARIZATION_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.
|
|
70
|
+
|
|
71
|
+
Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;
|
|
72
|
+
|
|
73
|
+
const FORMAT = `## Goal
|
|
74
|
+
[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]
|
|
75
|
+
|
|
76
|
+
## Constraints & Preferences
|
|
77
|
+
- [Any constraints, preferences, or requirements mentioned by user]
|
|
78
|
+
- [Or "(none)" if none were mentioned]
|
|
79
|
+
|
|
80
|
+
## Progress
|
|
81
|
+
### Done
|
|
82
|
+
- [x] [Completed tasks/changes]
|
|
83
|
+
|
|
84
|
+
### In Progress
|
|
85
|
+
- [ ] [Current work]
|
|
86
|
+
|
|
87
|
+
### Blocked
|
|
88
|
+
- [Issues preventing progress, if any]
|
|
89
|
+
|
|
90
|
+
## Key Decisions
|
|
91
|
+
- **[Decision]**: [Brief rationale]
|
|
92
|
+
|
|
93
|
+
## Next Steps
|
|
94
|
+
1. [Ordered list of what should happen next]
|
|
95
|
+
|
|
96
|
+
## Critical Context
|
|
97
|
+
- [Any data, examples, or references needed to continue]
|
|
98
|
+
- [Or "(none)" if not applicable]
|
|
99
|
+
|
|
100
|
+
Keep each section concise. Preserve exact file paths, function names, and error messages.`;
|
|
101
|
+
|
|
102
|
+
const SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
|
|
103
|
+
|
|
104
|
+
Use this EXACT format:
|
|
105
|
+
|
|
106
|
+
${FORMAT}`;
|
|
107
|
+
|
|
108
|
+
const UPDATE_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
|
|
109
|
+
|
|
110
|
+
Update the existing structured summary with new information. RULES:
|
|
111
|
+
- PRESERVE all existing information from the previous summary
|
|
112
|
+
- ADD new progress, decisions, and context from the new messages
|
|
113
|
+
- UPDATE the Progress section: move items from "In Progress" to "Done" when completed
|
|
114
|
+
- UPDATE "Next Steps" based on what was accomplished
|
|
115
|
+
- PRESERVE exact file paths, function names, and error messages
|
|
116
|
+
- If something is no longer relevant, you may remove it
|
|
117
|
+
|
|
118
|
+
Use this EXACT format:
|
|
119
|
+
|
|
120
|
+
${FORMAT}`;
|
|
121
|
+
|
|
122
|
+
const IMAGE_CHARS = 4800;
|
|
123
|
+
const TOOL_RESULT_MAX_CHARS = 2000;
|
|
124
|
+
/** A message's own words in the summarising request, at most. */
|
|
125
|
+
const MESSAGE_MAX_CHARS = 20_000;
|
|
126
|
+
|
|
127
|
+
const isSummaryBlock = (b: Block | undefined): boolean => b?.type === "text" && String(b.text ?? "").startsWith(SUMMARY_PREFIX);
|
|
128
|
+
|
|
129
|
+
function blockChars(b: Block): number {
|
|
130
|
+
if (b.type === "text") return String(b.text ?? "").length;
|
|
131
|
+
if (b.type === "thinking") return String(b.thinking ?? "").length;
|
|
132
|
+
if (b.type === "image") return IMAGE_CHARS;
|
|
133
|
+
if (b.type === "tool_use") return String(b.name ?? "").length + JSON.stringify(b.input ?? {}).length;
|
|
134
|
+
if (b.type === "tool_result") {
|
|
135
|
+
const c = b.content;
|
|
136
|
+
return typeof c === "string" ? c.length : Array.isArray(c) ? (c as Block[]).reduce((n, x) => n + blockChars(x), 0) : 0;
|
|
137
|
+
}
|
|
138
|
+
return JSON.stringify(b).length;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Tokens a message comes to, by four characters a token: an overestimate,
|
|
142
|
+
* which is the safe side here. */
|
|
143
|
+
export function estimateTokens(m: Message): number {
|
|
144
|
+
return Math.ceil(m.content.reduce((n, b) => n + blockChars(b), 0) / 4);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Every place a cut may go, after the first message. */
|
|
148
|
+
export function cutPoints(messages: Message[]): number[] {
|
|
149
|
+
const cuts: number[] = [];
|
|
150
|
+
for (let j = 1; j < messages.length; j++) if (isCutPoint(messages[j])) cuts.push(j);
|
|
151
|
+
return cuts;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** A message may begin the kept part when it is a model turn or a user turn
|
|
155
|
+
* that answers no tool call: a tool result must stay after its call. */
|
|
156
|
+
function isCutPoint(m: Message): boolean {
|
|
157
|
+
if (m.role === "assistant") return true;
|
|
158
|
+
return m.role === "user" && !m.content.some((b) => b.type === "tool_result");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Where the kept part starts: walking back from the newest message until
|
|
162
|
+
* `keep` tokens are behind, then forward to the first place a cut may go.
|
|
163
|
+
* When even the newest messages come to less than `keep`, everything from
|
|
164
|
+
* the first place a cut may go is kept (a large first message is what
|
|
165
|
+
* gets summarised). A kept part larger than `maxKeep` moves to a later
|
|
166
|
+
* cut, so a summary actually makes room. -1 when there is nowhere to cut. */
|
|
167
|
+
export function findCut(messages: Message[], keep: number, maxKeep = Infinity): number {
|
|
168
|
+
const cuts = cutPoints(messages);
|
|
169
|
+
if (!cuts.length) return -1;
|
|
170
|
+
// Each message's estimate once; what is kept from j on is suffix[j].
|
|
171
|
+
const suffix = new Array<number>(messages.length + 1).fill(0);
|
|
172
|
+
for (let i = messages.length - 1; i >= 0; i--) suffix[i] = suffix[i + 1] + estimateTokens(messages[i]);
|
|
173
|
+
const tail = (j: number) => suffix[j];
|
|
174
|
+
let chosen = cuts[0];
|
|
175
|
+
let acc = 0;
|
|
176
|
+
for (let i = messages.length - 1; i >= 1; i--) {
|
|
177
|
+
acc += estimateTokens(messages[i]);
|
|
178
|
+
if (acc >= keep) {
|
|
179
|
+
// The nearest cut at or after it; past the last one (one large tool
|
|
180
|
+
// result alone over the budget), the call with its result, as Pi does.
|
|
181
|
+
chosen = cuts.find((j) => j >= i) ?? cuts[cuts.length - 1];
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
for (const j of cuts) if (j > chosen && tail(chosen) > maxKeep) chosen = j;
|
|
186
|
+
return chosen;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function truncate(text: string, max: number): string {
|
|
190
|
+
if (text.length <= max) return text;
|
|
191
|
+
let end = max;
|
|
192
|
+
if (/[\uD800-\uDBFF]/.test(text[end - 1] ?? "")) end--;
|
|
193
|
+
return `${text.slice(0, end)}\n\n[... ${text.length - end} more characters truncated]`;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function textOf(c: unknown): string {
|
|
197
|
+
if (typeof c === "string") return c;
|
|
198
|
+
if (!Array.isArray(c)) return "";
|
|
199
|
+
return (c as Block[]).map((b) => (b.type === "text" ? String(b.text ?? "") : b.type === "image" ? "[image]" : "")).filter(Boolean).join("\n");
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** The conversation as text, so the summarising model reads it rather than
|
|
203
|
+
* continuing it. Thinking is left out; tool results are cut to 2,000
|
|
204
|
+
* characters each; the earlier summary's own block is left to the update
|
|
205
|
+
* prompt. */
|
|
206
|
+
export function serializeConversation(messages: Message[], maxChars = Infinity): string {
|
|
207
|
+
const parts: string[] = [];
|
|
208
|
+
messages.forEach((m, at) => {
|
|
209
|
+
if (m.role === "user") {
|
|
210
|
+
const said: string[] = [];
|
|
211
|
+
m.content.forEach((b, k) => {
|
|
212
|
+
if (b.type === "tool_result") {
|
|
213
|
+
const t = textOf(b.content);
|
|
214
|
+
if (t) parts.push(`[Tool result${b.is_error ? " (error)" : ""}]: ${truncate(t, TOOL_RESULT_MAX_CHARS)}`);
|
|
215
|
+
} else if (b.type === "text") {
|
|
216
|
+
// The earlier summary is the update prompt's, not conversation —
|
|
217
|
+
// only where compaction puts it: the first block of the first turn.
|
|
218
|
+
if (!(at === 0 && k === 0 && isSummaryBlock(b))) said.push(String(b.text ?? ""));
|
|
219
|
+
} else if (b.type === "image") said.push("[image]");
|
|
220
|
+
});
|
|
221
|
+
// The cap is the message's, across its blocks.
|
|
222
|
+
if (said.join("").trim()) parts.push(`[User]: ${truncate(said.join("\n"), MESSAGE_MAX_CHARS)}`);
|
|
223
|
+
} else if (m.role === "assistant") {
|
|
224
|
+
const text = m.content.filter((b) => b.type === "text").map((b) => String(b.text ?? "")).join("\n").trim();
|
|
225
|
+
if (text) parts.push(`[Assistant]: ${truncate(text, MESSAGE_MAX_CHARS)}`);
|
|
226
|
+
const calls = m.content.filter((b) => b.type === "tool_use").map((b) => {
|
|
227
|
+
const args = Object.entries((b.input ?? {}) as Json).map(([k, v]) => `${k}=${JSON.stringify(v)}`).join(", ");
|
|
228
|
+
return `${String(b.name)}(${args})`;
|
|
229
|
+
});
|
|
230
|
+
if (calls.length) parts.push(`[Assistant tool calls]: ${truncate(calls.join("; "), MESSAGE_MAX_CHARS)}`);
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
// Still too long for the summarising request: the newest part is kept,
|
|
234
|
+
// what is cut is said.
|
|
235
|
+
let text = parts.join("\n\n");
|
|
236
|
+
if (text.length > maxChars) {
|
|
237
|
+
let start = text.length - maxChars;
|
|
238
|
+
if (/[\uDC00-\uDFFF]/.test(text[start] ?? "")) start++;
|
|
239
|
+
text = `[... the first ${start} characters of the conversation are left out]\n\n${text.slice(start)}`;
|
|
240
|
+
}
|
|
241
|
+
return text;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** The earlier summary, when the conversation starts with one. */
|
|
245
|
+
export function previousSummary(messages: Message[]): string | null {
|
|
246
|
+
const first = messages[0]?.content[0];
|
|
247
|
+
if (!first || !isSummaryBlock(first)) return null;
|
|
248
|
+
const t = String(first.text);
|
|
249
|
+
return t.slice(SUMMARY_PREFIX.length, t.endsWith(SUMMARY_SUFFIX) ? t.length - SUMMARY_SUFFIX.length : undefined);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** The text the summarising model is sent. */
|
|
253
|
+
export function summaryRequest(toSummarize: Message[], earlier: string | null, maxChars = Infinity): string {
|
|
254
|
+
// The earlier summary counts against the same budget: at most half of
|
|
255
|
+
// it, the conversation the rest.
|
|
256
|
+
const prior = earlier && Number.isFinite(maxChars) ? truncate(earlier, Math.floor(maxChars / 2)) : earlier;
|
|
257
|
+
const left = Number.isFinite(maxChars) ? Math.max(1_000, maxChars - (prior?.length ?? 0)) : Infinity;
|
|
258
|
+
let text = `<conversation>\n${serializeConversation(toSummarize, left)}\n</conversation>\n\n`;
|
|
259
|
+
if (prior) text += `<previous-summary>\n${prior}\n</previous-summary>\n\n`;
|
|
260
|
+
return text + (earlier ? UPDATE_PROMPT : SUMMARIZATION_PROMPT);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** The files the summary lists after it: read only, and changed. */
|
|
264
|
+
export function fileLists(read: Set<string>, changed: Set<string>): string {
|
|
265
|
+
const readOnly = [...read].filter((f) => !changed.has(f)).sort();
|
|
266
|
+
const sections: string[] = [];
|
|
267
|
+
if (readOnly.length) sections.push(`<read-files>\n${readOnly.join("\n")}\n</read-files>`);
|
|
268
|
+
if (changed.size) sections.push(`<modified-files>\n${[...changed].sort().join("\n")}\n</modified-files>`);
|
|
269
|
+
return sections.length ? `\n\n${sections.join("\n\n")}` : "";
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** The conversation after compaction: the summary, then the kept part. The
|
|
273
|
+
* summary leads the first user turn (the turns must alternate, starting
|
|
274
|
+
* with the user's): it joins the kept part's first message when that is
|
|
275
|
+
* the user's, or comes before it as its own when the kept part opens on a
|
|
276
|
+
* model turn. */
|
|
277
|
+
export function compacted(summary: string, kept: Message[]): Message[] {
|
|
278
|
+
const block: Block = { type: "text", text: `${SUMMARY_PREFIX}${summary}${SUMMARY_SUFFIX}` };
|
|
279
|
+
if (kept[0]?.role === "user") return [{ role: "user", content: [block, ...kept[0].content] }, ...kept.slice(1)];
|
|
280
|
+
return [{ role: "user", content: [block] }, ...kept];
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** An endpoint's refusal that means the prompt did not fit: a 400 or 413
|
|
284
|
+
* that says so. Any other status is not, whatever its words. */
|
|
285
|
+
export function isContextOverflow(status: number | undefined, message: string): boolean {
|
|
286
|
+
if (status !== 400 && status !== 413) return false;
|
|
287
|
+
return /prompt is too long|input is too long|maximum context length|context length exceeded|(exceeds?|exceeded) (the )?(model's )?(maximum )?context( window| length)?|too many (input )?tokens/i.test(message);
|
|
288
|
+
}
|