@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
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// What any loop behind executeStep reads the same way (engine-loop.ts
|
|
2
|
+
// today): the SDK's options, what it refuses before a model call is paid
|
|
3
|
+
// for, the permission order every tool call goes through, and token usage.
|
|
4
|
+
// One copy, so a second loop (a bake-off, FOL-213) cannot hold a hook,
|
|
5
|
+
// limit or confinement check differently. Internal: not part of
|
|
6
|
+
// @foldrun/core's public API.
|
|
7
|
+
|
|
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";
|
|
11
|
+
|
|
12
|
+
export const DEFAULT_MAX_TOKENS = 16_000;
|
|
13
|
+
|
|
14
|
+
export interface Usage {
|
|
15
|
+
input_tokens: number;
|
|
16
|
+
output_tokens: number;
|
|
17
|
+
cache_creation_input_tokens: number;
|
|
18
|
+
cache_read_input_tokens: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const emptyUsage = (): Usage => ({ input_tokens: 0, output_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 });
|
|
22
|
+
|
|
23
|
+
export function addUsage(into: Usage, u: Partial<Record<keyof Usage, unknown>> | undefined): void {
|
|
24
|
+
if (!u) return;
|
|
25
|
+
// The closing delta repeats the counts it knows; one that leaves the input
|
|
26
|
+
// side at zero is not saying the input was free.
|
|
27
|
+
for (const k of Object.keys(into) as (keyof Usage)[]) {
|
|
28
|
+
const v = u[k];
|
|
29
|
+
if (typeof v === "number" && (v > 0 || k === "output_tokens")) into[k] = v;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The tier names an agent may write, where the environment names no model
|
|
34
|
+
* for them. The SDK's binary resolves these itself; here it is said. */
|
|
35
|
+
export const TIER_DEFAULTS: Record<string, string> = {
|
|
36
|
+
haiku: "claude-haiku-5-5",
|
|
37
|
+
sonnet: "claude-sonnet-5-5",
|
|
38
|
+
opus: "claude-opus-5-5",
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export type Json = Record<string, unknown>;
|
|
42
|
+
export type Block = Json & { type: string };
|
|
43
|
+
export type HookFn = (input: Json, toolUseId?: string, extra?: { signal: AbortSignal }) => Promise<Json | undefined> | Json | undefined;
|
|
44
|
+
export type CanUseTool = (name: string, input: Json, extra: { signal: AbortSignal; toolUseID: string }) =>
|
|
45
|
+
Promise<{ behavior: "allow"; updatedInput?: Json } | { behavior: "deny"; message: string }>;
|
|
46
|
+
|
|
47
|
+
export interface LoopOptions {
|
|
48
|
+
cwd: string;
|
|
49
|
+
env: Record<string, string | undefined>;
|
|
50
|
+
/** What the tools (Bash) get; `env` when not given. foldrun code passes
|
|
51
|
+
* the person's own environment here, so the model key stays with the loop. */
|
|
52
|
+
shellEnv: Record<string, string | undefined>;
|
|
53
|
+
model: string;
|
|
54
|
+
systemPrompt: string;
|
|
55
|
+
tools: EngineTool[];
|
|
56
|
+
maxTurns: number | null;
|
|
57
|
+
partial: boolean;
|
|
58
|
+
pre: HookFn[];
|
|
59
|
+
post: HookFn[];
|
|
60
|
+
canUseTool: CanUseTool | null;
|
|
61
|
+
outer: AbortSignal | null;
|
|
62
|
+
/** The conversation so far, before this prompt: earlier user turns, the
|
|
63
|
+
* model's replies and tool results, as the loop yielded them. */
|
|
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;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function hookFns(hooks: unknown, event: string): HookFn[] {
|
|
76
|
+
const groups = (hooks as Record<string, { hooks?: HookFn[] }[] | undefined> | undefined)?.[event];
|
|
77
|
+
return (groups ?? []).flatMap((g) => g.hooks ?? []);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The SDK's options, as this engine reads them. What it cannot honour it
|
|
81
|
+
* refuses here, before a model call is paid for. */
|
|
82
|
+
/** `engine` names the loop in what it refuses. */
|
|
83
|
+
export function readOptions(options: Json, engine = "foldrun"): LoopOptions {
|
|
84
|
+
const env = (options.env as Record<string, string | undefined> | undefined) ?? process.env;
|
|
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__"));
|
|
91
|
+
const unsupported = names.filter((n) => !ENGINE_TOOLS[n]);
|
|
92
|
+
if (unsupported.length) {
|
|
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.`);
|
|
94
|
+
}
|
|
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 });
|
|
104
|
+
}
|
|
105
|
+
if (options.agents && Object.keys(options.agents as Json).length) {
|
|
106
|
+
throw new Error(`the ${engine} engine does not run sub-agents yet — run this agent on the default engine.`);
|
|
107
|
+
}
|
|
108
|
+
const sandbox = options.sandbox as { enabled?: boolean } | undefined;
|
|
109
|
+
// Never read from `env`: that is where a tenant's secrets live.
|
|
110
|
+
if (names.includes("Bash") && sandbox?.enabled !== false && options.engineHostShell !== true) {
|
|
111
|
+
throw new Error(`the ${engine} engine has no OS sandbox for the shell on this host — run the step in a container.`);
|
|
112
|
+
}
|
|
113
|
+
const model = String(options.model ?? "");
|
|
114
|
+
if (!model) throw new Error(`the ${engine} engine needs a model`);
|
|
115
|
+
// Tools the host brings, as EngineTool objects: they sit beside the
|
|
116
|
+
// built-in ones and go through canUseTool and the hooks like them.
|
|
117
|
+
// foldrun code's cloud_agents is one. A name may not shadow a built-in.
|
|
118
|
+
const extra: EngineTool[] = [];
|
|
119
|
+
for (const t of Array.isArray(options.extraTools) ? (options.extraTools as unknown[]) : []) {
|
|
120
|
+
const tool = t as Partial<EngineTool> | null;
|
|
121
|
+
if (!tool || typeof tool.name !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(tool.name) || typeof tool.run !== "function" || typeof tool.input_schema !== "object") {
|
|
122
|
+
throw new Error("extraTools: each needs a name (letters, digits, _ and -), an input_schema and a run function");
|
|
123
|
+
}
|
|
124
|
+
if (ENGINE_TOOLS[tool.name] || extra.some((x) => x.name === tool.name)) throw new Error(`extraTools: ${tool.name} is already a tool`);
|
|
125
|
+
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 });
|
|
126
|
+
}
|
|
127
|
+
return {
|
|
128
|
+
cwd: String(options.cwd ?? process.cwd()),
|
|
129
|
+
env,
|
|
130
|
+
shellEnv: options.shellEnv && typeof options.shellEnv === "object" ? (options.shellEnv as Record<string, string | undefined>) : env,
|
|
131
|
+
model: env[`ANTHROPIC_DEFAULT_${model.toUpperCase()}_MODEL`] || TIER_DEFAULTS[model] || model,
|
|
132
|
+
systemPrompt: typeof options.systemPrompt === "string" ? options.systemPrompt : "",
|
|
133
|
+
tools: [...names.map((n) => ENGINE_TOOLS[n]), ...extra],
|
|
134
|
+
maxTurns: typeof options.maxTurns === "number" && options.maxTurns > 0 ? options.maxTurns : null,
|
|
135
|
+
partial: options.includePartialMessages === true,
|
|
136
|
+
pre: hookFns(options.hooks, "PreToolUse"),
|
|
137
|
+
post: hookFns(options.hooks, "PostToolUse"),
|
|
138
|
+
canUseTool: typeof options.canUseTool === "function" ? (options.canUseTool as CanUseTool) : null,
|
|
139
|
+
outer: (options.abortController as AbortController | undefined)?.signal ?? null,
|
|
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
|
+
),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** An earlier conversation, checked: user and assistant turns that
|
|
150
|
+
* alternate, starting with the user's, each a list of content blocks. A
|
|
151
|
+
* turn that is not one is refused, not sent half-right to the model. */
|
|
152
|
+
export function readHistory(raw: unknown): { role: string; content: Block[] }[] {
|
|
153
|
+
if (raw == null) return [];
|
|
154
|
+
if (!Array.isArray(raw)) throw new Error("history must be a list of turns");
|
|
155
|
+
return raw.map((t, i) => {
|
|
156
|
+
const role = (t as Json)?.role;
|
|
157
|
+
const content = (t as Json)?.content;
|
|
158
|
+
if (role !== (i % 2 === 0 ? "user" : "assistant")) throw new Error(`history turn ${i + 1} must be the ${i % 2 === 0 ? "user's" : "model's"}`);
|
|
159
|
+
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`);
|
|
160
|
+
return { role: String(role), content: content as Block[] };
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export interface Decision {
|
|
165
|
+
input: Json;
|
|
166
|
+
refusal: string | null;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** May this call run, and with what input? The order the SDK kept, which
|
|
170
|
+
* step-exec's checks are written against: every PreToolUse hook first — a
|
|
171
|
+
* deny ends it, an allow carries the input the hook settled on and skips
|
|
172
|
+
* the question below — then canUseTool, where confinement lives. */
|
|
173
|
+
export async function decide(o: LoopOptions, name: string, id: string, input: Json, sessionId: string, signal: AbortSignal): Promise<Decision> {
|
|
174
|
+
let current = input;
|
|
175
|
+
let allowed = false;
|
|
176
|
+
for (const hook of o.pre) {
|
|
177
|
+
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 });
|
|
178
|
+
const d = (out as { hookSpecificOutput?: { permissionDecision?: string; permissionDecisionReason?: string; updatedInput?: Json } } | undefined)?.hookSpecificOutput;
|
|
179
|
+
if (!d) continue;
|
|
180
|
+
if (d.permissionDecision === "deny") return { input: current, refusal: d.permissionDecisionReason || `${name} was refused` };
|
|
181
|
+
if (d.updatedInput) current = d.updatedInput;
|
|
182
|
+
if (d.permissionDecision === "allow") allowed = true;
|
|
183
|
+
}
|
|
184
|
+
if (!allowed && o.canUseTool) {
|
|
185
|
+
const r = await o.canUseTool(name, current, { signal, toolUseID: id });
|
|
186
|
+
if (r.behavior === "deny") return { input: current, refusal: r.message || `${name} was refused` };
|
|
187
|
+
if (r.updatedInput) current = r.updatedInput;
|
|
188
|
+
}
|
|
189
|
+
return { input: current, refusal: null };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** After a call: tell the PostToolUse hooks, and collect what they add. */
|
|
193
|
+
export async function after(o: LoopOptions, name: string, id: string, input: Json, outcome: ToolOutcome, sessionId: string, signal: AbortSignal): Promise<string[]> {
|
|
194
|
+
const added: string[] = [];
|
|
195
|
+
for (const hook of o.post) {
|
|
196
|
+
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 });
|
|
197
|
+
const context = (out as { hookSpecificOutput?: { additionalContext?: string } } | undefined)?.hookSpecificOutput?.additionalContext;
|
|
198
|
+
if (context) added.push(context);
|
|
199
|
+
}
|
|
200
|
+
return added;
|
|
201
|
+
}
|
|
202
|
+
|
|
@@ -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
|
+
}
|