@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.
@@ -0,0 +1,281 @@
1
+ // MCP servers on foldrun's own loop (FOL-213): every tool beyond the six
2
+ // file and shell tools reaches a step as an MCP server — foldrun's own, made
3
+ // in this process (createSdkMcpServer: `foldrun_scripts` with `web` search,
4
+ // fetch and browse; agents, apis, a2a, install, ask, peers, history), and an
5
+ // agent's own `mcpServers:` (stdio, http, sse). The SDK connected them inside
6
+ // the Claude Code binary; this connects them here, so the loop offers the
7
+ // same tools under the same names.
8
+ //
9
+ // What stays where it was:
10
+ // - the tools run where they always ran — the browser pod, the egress
11
+ // proxy and its search door, the vault's site-bound secrets are behind
12
+ // the server, not in this file;
13
+ // - each tool is offered as `mcp__<server>__<tool>`, the SDK's name, so
14
+ // step-exec's grant (`mcpNames`), limits, hooks and the run record read
15
+ // it as before, and every call goes through the loop's permission order
16
+ // (engine-common.ts decide/after);
17
+ // - a server that does not connect refuses the step by name. The SDK went
18
+ // on without its tools; a step that runs without a tool it was given is
19
+ // the failure this engine refuses to have.
20
+
21
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
22
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
23
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
24
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
25
+ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
26
+ import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
27
+ import type { EngineTool, ToolOutcome } from "./engine-tools.ts";
28
+
29
+ type Json = Record<string, unknown>;
30
+
31
+ /** The server a granted name belongs to: `mcp__<server>`, `mcp__<server>__*`
32
+ * (the runner grants a whole server so) or `mcp__<server>__<tool>`. Matched
33
+ * against the step's own server names, the longest first, so a server named
34
+ * `sales__eu` is not read as `sales`. */
35
+ export function grantedServer(name: string, servers: string[]): { server: string; tool: string | null } | null {
36
+ for (const s of [...servers].sort((a, b) => b.length - a.length)) {
37
+ const head = `mcp__${s}`;
38
+ if (name === head || name === `${head}__*`) return { server: s, tool: null };
39
+ if (name.startsWith(`${head}__`) && name.length > head.length + 2) return { server: s, tool: name };
40
+ }
41
+ return null;
42
+ }
43
+
44
+ /** A server as the SDK's `mcpServers` option holds it. */
45
+ export interface McpSpec {
46
+ type?: string;
47
+ name?: string;
48
+ instance?: { connect(t: Transport): Promise<void> };
49
+ command?: string;
50
+ args?: string[];
51
+ env?: Record<string, string>;
52
+ url?: string;
53
+ headers?: Record<string, string>;
54
+ /** Milliseconds one call may take; below 1000 is ignored, as in the SDK. */
55
+ timeout?: number;
56
+ /** The SDK's per-tool permission policy — refused here (checkMcpSpecs). */
57
+ tools?: unknown;
58
+ }
59
+
60
+ /** Longest a call may run when its server names no timeout: the step's own
61
+ * timeout ends it sooner (the loop's signal). */
62
+ const DEFAULT_CALL_MS = 24 * 60 * 60 * 1000;
63
+ /** The longest a timer holds (2^31 − 1 ms, ~24.8 days); past it Node fires at once. */
64
+ const MAX_TIMER_MS = 2_147_483_647;
65
+ const CONNECT_MS = 60_000;
66
+ /** The most text one call hands the model; the rest is said to be cut. */
67
+ const MAX_TEXT = 100_000;
68
+ const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
69
+
70
+ /** Refused before a model call is paid for: a server this loop cannot connect. */
71
+ export function checkMcpSpecs(servers: Record<string, unknown>, engine: string): Record<string, McpSpec> {
72
+ // No prototype: a server named __proto__ is a server, not a prototype.
73
+ const out: Record<string, McpSpec> = Object.create(null);
74
+ for (const [name, raw] of Object.entries(servers)) {
75
+ const s = (raw ?? {}) as McpSpec;
76
+ const type = s.type ?? "stdio";
77
+ const ok =
78
+ (type === "sdk" && typeof s.instance?.connect === "function") ||
79
+ (type === "stdio" && typeof s.command === "string" && !!s.command) ||
80
+ ((type === "http" || type === "sse") && typeof s.url === "string" && !!s.url);
81
+ if (!ok) throw new Error(`the ${engine} engine cannot connect the MCP server ${name} (type ${type}) — run this agent on the default engine.`);
82
+ if (!/^[A-Za-z0-9_-]+$/.test(name)) throw new Error(`the MCP server name ${name} has characters a tool name cannot hold (letters, digits, _ and -)`);
83
+ // The SDK honours a per-tool always_deny / always_ask; this loop would
84
+ // offer such a tool like any other, so it refuses the spec instead.
85
+ if (Array.isArray(s.tools) && s.tools.length) throw new Error(`the ${engine} engine does not apply per-tool permission policies (MCP server ${name}) — run this agent on the default engine.`);
86
+ out[name] = { ...s, type };
87
+ }
88
+ return out;
89
+ }
90
+
91
+ export interface McpConnection {
92
+ tools: EngineTool[];
93
+ /** Which server offered each tool, by its full name. */
94
+ owner: Map<string, string>;
95
+ /** What each server told its client to tell the model (MCP `instructions`),
96
+ * which the SDK put in the system prompt; so does the loop. */
97
+ instructions: { server: string; text: string }[];
98
+ servers: { name: string; status: "connected" }[];
99
+ close(): Promise<void>;
100
+ }
101
+
102
+ function transportFor(s: McpSpec, env: Record<string, string | undefined>, cwd: string): { client: Transport; server?: Transport } {
103
+ if (s.type === "sdk") {
104
+ const [client, server] = InMemoryTransport.createLinkedPair();
105
+ return { client, server };
106
+ }
107
+ if (s.type === "stdio") {
108
+ // The step's environment, as the SDK gave it: already the allowlisted
109
+ // one (host-env.ts: the clock, the proxy that is the way out, declared
110
+ // secrets), never this process's. Then what the spec names. The MCP
111
+ // library adds PATH, HOME, SHELL, TERM, USER and LOGNAME from this
112
+ // process where the step has none: names a program needs, no secrets.
113
+ const base: Record<string, string> = {};
114
+ for (const [k, v] of Object.entries(env)) if (typeof v === "string") base[k] = v;
115
+ return { client: new StdioClientTransport({ command: s.command!, args: s.args ?? [], env: { ...base, ...(s.env ?? {}) }, cwd, stderr: "ignore" }) };
116
+ }
117
+ const url = new URL(s.url!);
118
+ const requestInit = { headers: s.headers ?? {} };
119
+ // SSE is the older MCP transport (deprecated in the SDK); still accepted,
120
+ // because an agent may name a server that has nothing newer.
121
+ return { client: s.type === "sse" ? new SSEClientTransport(url, { requestInit }) : new StreamableHTTPClientTransport(url, { requestInit }) };
122
+ }
123
+
124
+ /** A call's result as the loop hands it on: its text and images in the
125
+ * order the server gave them (a caption stays beside its picture), the text
126
+ * cut to a size, marked an error when the server says it is one. */
127
+ export function outcomeOf(result: Json): ToolOutcome {
128
+ const parts: ({ type: "text"; text: string } | { type: "image"; data: string; mediaType: string })[] = [];
129
+ const add = (text: string) => parts.push({ type: "text", text });
130
+ for (const c of (Array.isArray(result.content) ? result.content : []) as Json[]) {
131
+ if (c.type === "text" && typeof c.text === "string") add(c.text);
132
+ else if (c.type === "image" && typeof c.data === "string" && typeof c.mimeType === "string") parts.push({ type: "image", data: c.data, mediaType: c.mimeType });
133
+ else if (c.type === "resource") {
134
+ const r = (c.resource ?? {}) as Json;
135
+ add(typeof r.text === "string" ? r.text : `[resource ${String(r.uri ?? "")}${r.mimeType ? ` (${String(r.mimeType)})` : ""}]`);
136
+ } else if (c.type === "resource_link") add(`[resource ${String(c.uri ?? "")}]`);
137
+ else if (c.type === "audio") add("[audio — not shown]");
138
+ }
139
+ if (!parts.some((p) => p.type === "text") && result.structuredContent !== undefined) add(JSON.stringify(result.structuredContent));
140
+ if (!parts.length && "toolResult" in result) add(typeof result.toolResult === "string" ? result.toolResult : JSON.stringify(result.toolResult));
141
+ // One budget across every text part, in order, the newline between two
142
+ // counted; a part past it is dropped, not kept empty.
143
+ let left = MAX_TEXT;
144
+ let cut = 0;
145
+ const kept: typeof parts = [];
146
+ let any = false;
147
+ for (const p of parts) {
148
+ if (p.type !== "text") { kept.push(p); continue; }
149
+ const sep = any ? 1 : 0;
150
+ const room = left - sep;
151
+ // An empty part still fits when only its newline does.
152
+ if (room < 0 || (room === 0 && p.text.length > 0)) { cut += p.text.length; continue; }
153
+ if (p.text.length > room) {
154
+ let end = room;
155
+ // Never half a character: a cut between a surrogate pair drops both.
156
+ if (/[\uD800-\uDBFF]/.test(p.text[end - 1] ?? "")) end--;
157
+ cut += p.text.length - end;
158
+ p.text = p.text.slice(0, end);
159
+ }
160
+ left -= p.text.length + sep;
161
+ any = true;
162
+ kept.push(p);
163
+ }
164
+ parts.length = 0;
165
+ parts.push(...kept);
166
+ if (cut) add(`[cut: ${cut} more characters]`);
167
+ const texts = parts.filter((p) => p.type === "text") as { text: string }[];
168
+ const text = texts.map((p) => p.text).join("\n");
169
+ const hasImage = parts.some((p) => p.type === "image");
170
+ return { text, isError: result.isError === true, ...(hasImage ? { parts } : {}) };
171
+ }
172
+
173
+ /** A promise held to a time and a signal — the MCP client waits for a
174
+ * transport to start before its own timeout begins (an SSE server that
175
+ * never sends its endpoint would hold the step open forever). */
176
+ function bounded<T>(work: Promise<T>, ms: number, signal: AbortSignal, what: string): Promise<T> {
177
+ return new Promise<T>((resolve, reject) => {
178
+ const done = () => { clearTimeout(timer); signal.removeEventListener("abort", onAbort); };
179
+ const onAbort = () => { done(); reject(new Error(`${what}: stopped`)); };
180
+ const timer = setTimeout(() => { done(); reject(new Error(`${what}: no answer in ${Math.round(ms / 1000)} s`)); }, ms);
181
+ // Handled first, so the work failing after a stop is never unhandled.
182
+ work.then((v) => { done(); resolve(v); }, (e) => { done(); reject(e); });
183
+ if (signal.aborted) return onAbort();
184
+ signal.addEventListener("abort", onAbort, { once: true });
185
+ });
186
+ }
187
+
188
+ /** Connect every server and list its tools. All or none: one that fails
189
+ * closes the rest and refuses the step, naming it. */
190
+ /** `env` is the step's options' environment (where MCP_TOOL_TIMEOUT is
191
+ * read, as the SDK read it); `toolEnv` is what a tool's process starts
192
+ * from — the loop's shellEnv, which a caller keeps apart from the model's
193
+ * credentials. */
194
+ export async function connectMcp(servers: Record<string, McpSpec>, ctx: { env: Record<string, string | undefined>; toolEnv: Record<string, string | undefined>; cwd: string; signal: AbortSignal }): Promise<McpConnection> {
195
+ const open: { client: Client; transport: Transport; server?: Transport }[] = [];
196
+ const close = async () => {
197
+ await Promise.all(open.map(async (o) => {
198
+ // A streamable HTTP server that gave a session is told it is over
199
+ // (DELETE), so it is not left holding one; then the local side closes.
200
+ if (o.transport instanceof StreamableHTTPClientTransport && o.transport.sessionId) {
201
+ await bounded(o.transport.terminateSession(), 5_000, new AbortController().signal, "end session").catch(() => undefined);
202
+ }
203
+ await o.client.close().catch(() => undefined);
204
+ await o.server?.close().catch(() => undefined);
205
+ }));
206
+ };
207
+ const tools: EngineTool[] = [];
208
+ const owner = new Map<string, string>();
209
+ const instructions: { server: string; text: string }[] = [];
210
+ const envTimeout = Number(ctx.env.MCP_TOOL_TIMEOUT);
211
+ try {
212
+ for (const [name, s] of Object.entries(servers)) {
213
+ const t = transportFor(s, ctx.toolEnv, ctx.cwd);
214
+ const client = new Client({ name: "foldrun-engine", version: "1.0.0" });
215
+ open.push({ client, transport: t.client, server: t.server });
216
+ let listed: { name: string; description?: string; inputSchema?: Json; annotations?: { readOnlyHint?: boolean } }[];
217
+ if (ctx.signal.aborted) throw new Error(`the MCP server ${name} did not start: connect: stopped`);
218
+ try {
219
+ const started = (async () => {
220
+ if (t.server) await s.instance!.connect(t.server);
221
+ await client.connect(t.client, { timeout: CONNECT_MS, signal: ctx.signal });
222
+ const found: typeof listed = [];
223
+ // A server that offers no tools says so in its capabilities.
224
+ if (!client.getServerCapabilities()?.tools) return found;
225
+ let cursor: string | undefined;
226
+ do {
227
+ let page;
228
+ try {
229
+ page = await client.listTools(cursor ? { cursor } : undefined, { timeout: CONNECT_MS, signal: ctx.signal });
230
+ } catch (err) {
231
+ // Some say they have tools and answer tools/list with "method
232
+ // not found" when they have none (the Agent SDK's in-process
233
+ // server with an empty list): no tools, not a failed start.
234
+ if ((err as { code?: number }).code === -32601 && !cursor) return found;
235
+ throw err;
236
+ }
237
+ found.push(...(page.tools as typeof listed));
238
+ cursor = page.nextCursor;
239
+ } while (cursor);
240
+ // Each page replaced the client's output-schema checks with its
241
+ // own: give it every page's, so a tool on page one is still checked.
242
+ (client as unknown as { cacheToolMetadata?(t: unknown[]): void }).cacheToolMetadata?.(found);
243
+ return found;
244
+ })();
245
+ listed = await bounded(started, CONNECT_MS, ctx.signal, "connect");
246
+ } catch (err) {
247
+ throw new Error(`the MCP server ${name} did not start: ${(err as Error).message}`);
248
+ }
249
+ // The server's own timeout, else MCP_TOOL_TIMEOUT, as the SDK read them.
250
+ const told = client.getInstructions();
251
+ if (typeof told === "string" && told.trim()) instructions.push({ server: name, text: told.trim() });
252
+ const timeout = Math.min(MAX_TIMER_MS, typeof s.timeout === "number" && s.timeout >= 1000 ? s.timeout : envTimeout >= 1000 ? envTimeout : DEFAULT_CALL_MS);
253
+ for (const tool of listed) {
254
+ const full = `mcp__${name}__${tool.name}`;
255
+ if (!TOOL_NAME.test(full)) throw new Error(`the MCP server ${name} offers a tool whose full name ${full} is not one a model accepts (at most 64 letters, digits, _ and -)`);
256
+ if (owner.has(full)) throw new Error(`two MCP servers offer a tool named ${full} (${owner.get(full)} and ${name})`);
257
+ // A name that reads as another server's (sales offering eu__find
258
+ // beside a server sales__eu) would be granted by the wrong server:
259
+ // the step is refused rather than guess.
260
+ const readAs = grantedServer(full, Object.keys(servers));
261
+ if (readAs?.server !== name) throw new Error(`the MCP tool ${full} from ${name} reads as server ${readAs?.server ?? "none"}'s — rename the server or the tool`);
262
+ owner.set(full, name);
263
+ tools.push({
264
+ name: full,
265
+ description: tool.description ?? "",
266
+ input_schema: tool.inputSchema ?? { type: "object" },
267
+ // Run beside other reads only when the server says it changes nothing.
268
+ readOnly: tool.annotations?.readOnlyHint === true,
269
+ run: async (input, toolCtx) => {
270
+ const result = await client.callTool({ name: tool.name, arguments: input }, undefined, { signal: toolCtx.signal, timeout, maxTotalTimeout: timeout });
271
+ return outcomeOf(result as Json);
272
+ },
273
+ });
274
+ }
275
+ }
276
+ } catch (err) {
277
+ await close();
278
+ throw err;
279
+ }
280
+ return { tools, owner, instructions, servers: Object.keys(servers).map((name) => ({ name, status: "connected" as const })), close };
281
+ }
@@ -55,6 +55,10 @@ export function killGroups(ctx: ToolContext): void {
55
55
  export interface ToolOutcome {
56
56
  text: string;
57
57
  isError?: boolean;
58
+ /** When the tool returned images (an MCP server's screenshot): its text and
59
+ * images in their order, sent to the model so. `text` is still the whole
60
+ * text, for the record and the hooks. */
61
+ parts?: ({ type: "text"; text: string } | { type: "image"; data: string; mediaType: string })[];
58
62
  }
59
63
 
60
64
  export interface EngineTool {
package/src/runner.ts CHANGED
@@ -151,7 +151,7 @@ export function unbindMcpHeaders(
151
151
  grant: EgressGrant,
152
152
  ): Record<string, McpServerConfig> {
153
153
  const known = Object.fromEntries(bound.filter((n) => n in values).map((n) => [n, values[n]]));
154
- const out: Record<string, McpServerConfig> = {};
154
+ const out: Record<string, McpServerConfig> = Object.create(null);
155
155
  for (const [name, server] of Object.entries(servers)) {
156
156
  if (server.type !== "http") {
157
157
  out[name] = server;
@@ -1237,7 +1237,8 @@ export function agentContext(
1237
1237
  // MCP servers an agent connects to. `mcpServers:` is Claude Code's spelling
1238
1238
  // for the inline form; a `type: mcp` tool file is the shared form. Both end
1239
1239
  // up here, and both reach the model as ordinary MCP tools.
1240
- const mcpServers: Record<string, McpServerConfig> = {};
1240
+ // No prototype: a server an agent names __proto__ is a server.
1241
+ const mcpServers: Record<string, McpServerConfig> = Object.create(null);
1241
1242
  const mcpNames: string[] = [];
1242
1243
 
1243
1244
  // What the granted tools' programs need — merged into this step's runtime
@@ -182,6 +182,8 @@ export function runScript(
182
182
  libraryScripts: string,
183
183
  interpreters: Record<string, string>,
184
184
  exec: ExecutionContext | null,
185
+ /** A stop for the call (the MCP request's): the script ends with it. */
186
+ signal?: AbortSignal,
185
187
  ): Promise<{ code: number | null; out: string }> {
186
188
  // An inline-code tool has no file yet: write it inside the agent's own
187
189
  // directory — already an allowed root — and run it like any other script.
@@ -285,11 +287,31 @@ export function runScript(
285
287
  // base and gets what the agent declared, by name — see host-env.ts.
286
288
  // In a run container `env` already carries the container's whole
287
289
  // environment, which is the boundary, so nothing is lost there.
290
+ const ownGroup = process.platform !== "win32" && !process.stdout.isTTY && !process.stdin.isTTY;
288
291
  const child = spawn(cmd, args, {
289
292
  cwd,
290
293
  env: workspaceLinkEnv({ ...hostSafeEnv(), ...env }, cwd),
291
294
  timeout: timeoutFor(spec),
295
+ // Unattended (no terminal: the platform, a schedule), a script leads
296
+ // its own process group, so a stop ends what it started too — a
297
+ // leftover child could otherwise write over a retry's output. At a
298
+ // terminal it stays in this process's group, so Ctrl-C reaches it.
299
+ detached: ownGroup,
292
300
  });
301
+ // A stopped step stops its script: the call's stop kills it (its group
302
+ // when it has one). A container run's script is not followed — as on
303
+ // the SDK path before.
304
+ const stop = () => {
305
+ stopped = true;
306
+ try {
307
+ if (ownGroup && child.pid) process.kill(-child.pid, "SIGKILL");
308
+ else child.kill("SIGKILL");
309
+ } catch { /* already gone */ }
310
+ };
311
+ let stopped = false;
312
+ if (signal?.aborted) stop();
313
+ else signal?.addEventListener("abort", stop, { once: true });
314
+ child.on("close", () => signal?.removeEventListener("abort", stop));
293
315
  let out = "";
294
316
  const append = (chunk: Buffer) => {
295
317
  if (out.length < MAX_OUTPUT) out += chunk.toString();
@@ -301,9 +323,10 @@ export function runScript(
301
323
  resolve({
302
324
  code,
303
325
  out:
304
- out.length > MAX_OUTPUT
326
+ (stopped ? "stopped: the step was stopped\n" : "") +
327
+ (out.length > MAX_OUTPUT
305
328
  ? `${out.slice(0, MAX_OUTPUT)}\n…[truncated]`
306
- : out || "(no output)",
329
+ : out || "(no output)"),
307
330
  }),
308
331
  );
309
332
  });
@@ -445,12 +468,12 @@ export function buildScriptTools(
445
468
  `Credentials it needs are already in its environment.` +
446
469
  (spec.guide ? `\n\nHow to use it (from its tool.md):\n${spec.guide}` : ""),
447
470
  shape,
448
- async (args) => {
471
+ async (args, extra) => {
449
472
  const started = Date.now();
450
473
  const values = Object.fromEntries(
451
474
  Object.entries(args ?? {}).map(([k, v]) => [k, v === undefined ? "" : String(v)]),
452
475
  );
453
- const { code, out } = await runScript(agentDir, spec, values, env, libraryScripts, interpreters, exec);
476
+ const { code, out } = await runScript(agentDir, spec, values, env, libraryScripts, interpreters, exec, (extra as { signal?: AbortSignal } | undefined)?.signal);
454
477
  // The arguments, on the record. Without them a run says a script was
455
478
  // called and not what it was asked to do — and for a script that
456
479
  // writes to someone else's system, "it ran" is not an account of what
package/src/step-exec.ts CHANGED
@@ -28,6 +28,7 @@ import { hostSafeEnv } from "./host-env.ts";
28
28
  import { validateSchema, describeSchemaErrors, looksLikeSchema } from "./json-schema.ts";
29
29
  import { CallCounter, callKeysFor, REFUSALS_BEFORE_STOP, type Limits } from "./limits.ts";
30
30
  import { classifyCall, podAt, readPodEvents, type BrowserPodOutcome, type CallKind, type ClassifyContext } from "./browser-pod.ts";
31
+ import { grantedServer } from "./engine-mcp.ts";
31
32
 
32
33
  export interface ExecUsage {
33
34
  inputTokens: number;
@@ -113,6 +114,12 @@ export interface ExecOptions {
113
114
  * Only for a person's own machine, on their word; a run container is
114
115
  * its own boundary and needs nothing said (`sandboxBash: false`). */
115
116
  engineHostShell?: boolean;
117
+ /** foldrun's loop: the model's context window in tokens, when it is not
118
+ * the 200k the loop assumes — compaction starts 16k short of it. */
119
+ contextWindow?: number;
120
+ /** foldrun's loop: false turns compaction off (a step that must see its
121
+ * whole conversation, or fail). */
122
+ compaction?: false;
116
123
  agentDir: string;
117
124
  workspaceRoot: string;
118
125
  libraryRoot: string;
@@ -401,6 +408,16 @@ async function executeStepInner(opts: ExecOptions, runQuery: QueryFn): Promise<E
401
408
  // its own list, a path outside the workspace, a shell command — names the
402
409
  // agent that tried, not just the step.
403
410
  const subagentNames = new Map<string, string>();
411
+ // An MCP tool is granted when the server it belongs to is. Its server is
412
+ // read against the step's own server names, the longest first: with
413
+ // servers `sales` and `sales__eu`, `mcp__sales__eu__find` is sales__eu's,
414
+ // and granting `sales` does not grant it. A name no server of the step's
415
+ // claims falls back to the prefix it always matched on.
416
+ const serverNames = Object.keys(opts.mcpServers ?? {});
417
+ const fromGrantedMcp = (toolName: string): boolean => {
418
+ const g = grantedServer(toolName, serverNames);
419
+ return g ? g.tool !== null && opts.mcpNames.includes(g.server) : opts.mcpNames.some((n) => toolName.startsWith(`mcp__${n}__`));
420
+ };
404
421
  // `limits:` — this step's counts. A new step, a retry of one, or a
405
422
  // fan-out instance each start from zero.
406
423
  const counter = new CallCounter(opts.limits);
@@ -492,6 +509,10 @@ async function executeStepInner(opts: ExecOptions, runQuery: QueryFn): Promise<E
492
509
  // path (the CLI on someone's laptop, and the host executor) keeps it,
493
510
  // because there a shell escape reaches the real machine.
494
511
  ...(opts.engineHostShell ? { engineHostShell: true } : {}),
512
+ // foldrun's loop only: the model's context window for compaction, or
513
+ // compaction off (engine-compact.ts). The SDK compacts by its own rules.
514
+ ...(opts.contextWindow ? { contextWindow: opts.contextWindow } : {}),
515
+ ...(opts.compaction === false ? { compaction: false } : {}),
495
516
  sandbox: {
496
517
  enabled: opts.sandboxBash !== false,
497
518
  // Must stay false. Auto-allowing bash because it's sandboxed skips
@@ -581,7 +602,7 @@ async function executeStepInner(opts: ExecOptions, runQuery: QueryFn): Promise<E
581
602
  : isFilesystemTool(hookInput.tool_name)
582
603
  ? checkPaths(hookInput.tool_name, v.input, { agentDir, workspaceRoot, libraryRoot, configWrites: opts.configWrites })
583
604
  : { ok: true as const };
584
- const granted = opts.allowed.includes(hookInput.tool_name) || opts.mcpNames.some((n) => hookInput.tool_name.startsWith(`mcp__${n}__`));
605
+ const granted = opts.allowed.includes(hookInput.tool_name) || fromGrantedMcp(hookInput.tool_name);
585
606
  // The sub-agent guard read the ORIGINAL input: a rewrite of a
586
607
  // delegation could otherwise swap subagent_type for one this
587
608
  // step never declared (or the SDK's general-purpose).
@@ -633,7 +654,7 @@ async function executeStepInner(opts: ExecOptions, runQuery: QueryFn): Promise<E
633
654
  const via = options?.agentID ? (subagentNames.get(options.agentID) ?? "subagent") : undefined;
634
655
  // The toolset was already narrowed to what the agent declared, so
635
656
  // anything outside it is a denial with a reason the model can act on.
636
- const fromGrantedServer = opts.mcpNames.some((n) => toolName.startsWith(`mcp__${n}__`));
657
+ const fromGrantedServer = fromGrantedMcp(toolName);
637
658
  // A call the hook counted and this refuses never ran: give it back.
638
659
  const refund = () => { if (counter.active) counter.refund(callKeysFor(toolName, input, opts.toolOwners)); };
639
660
  if (!opts.allowed.includes(toolName) && !fromGrantedServer) {
@@ -808,6 +829,32 @@ async function executeStepInner(opts: ExecOptions, runQuery: QueryFn): Promise<E
808
829
  // The session is up: the first model call is timed from here, not from
809
830
  // before the SDK and its MCP servers started.
810
831
  if (message.type === "system" && (message as { subtype?: string }).subtype === "init") loopStartedAt = Date.now();
832
+ if (message.type === "system" && (message as { subtype?: string }).subtype === "compact_boundary") {
833
+ // The conversation neared the model's context window; its older part
834
+ // was summarised (foldrun's loop: engine-compact.ts; the SDK: its own).
835
+ const meta = (message as { compact_metadata?: { trigger?: string; pre_tokens?: number; post_tokens?: number } }).compact_metadata;
836
+ 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)" : ""}`);
837
+ }
838
+ if (message.type === "system" && (message as { subtype?: string }).subtype === "compact_failed") {
839
+ emit("info", `could not compact the conversation: ${String((message as { error?: unknown }).error ?? "no reason given")}`);
840
+ }
841
+ // A summary request (foldrun's loop) is a model call like any turn: its
842
+ // tokens are in the step's cost, and its budget, whether or not the
843
+ // summary was used.
844
+ const compactUsage = message.type === "system" && /^compact_(boundary|failed)$/.test(String((message as { subtype?: string }).subtype))
845
+ ? (message as { usage?: Record<string, number | undefined> }).usage
846
+ : undefined;
847
+ if (compactUsage) {
848
+ turns.set(`compaction-${anonymousTurns++}`, { u: compactUsage, price: priceOf(message) });
849
+ if (ceiling) {
850
+ spentUsd = turnsTotal();
851
+ if (spentUsd >= ceiling) {
852
+ 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"})`);
853
+ status = "failed";
854
+ break;
855
+ }
856
+ }
857
+ }
811
858
  if (message.type === "stream_event") {
812
859
  const ev = (message as { event?: { type?: string; message?: { id?: string }; usage?: { output_tokens?: number }; delta?: { stop_reason?: string | null } } }).event;
813
860
  const agentKey = (message as { parent_tool_use_id?: string | null }).parent_tool_use_id ?? "";