@foldrun/core 24.8.1 → 24.9.1

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.
@@ -37,6 +37,8 @@
37
37
  import crypto from "node:crypto";
38
38
  import type { QueryFn, QueryLike } from "./step-exec.ts";
39
39
  import { killGroups, type EngineTool, type ToolContext, type ToolOutcome } from "./engine-tools.ts";
40
+ import { connectMcp, type McpConnection } from "./engine-mcp.ts";
41
+ import { SUMMARIZATION_SYSTEM_PROMPT, compacted, cutPoints, estimateTokens, fileLists, findCut, isContextOverflow, previousSummary, summaryRequest } from "./engine-compact.ts";
40
42
  import { DEFAULT_MAX_TOKENS, readOptions, decide, after, emptyUsage, addUsage, type Json, type Block, type LoopOptions, type Decision, type Usage } from "./engine-common.ts";
41
43
 
42
44
  /** Which loop runs a step's turns. */
@@ -87,8 +89,9 @@ export function endOf(stopReason: string | null, calls: number): { subtype: stri
87
89
  }
88
90
  }
89
91
 
90
- export function buildRequest(o: Pick<LoopOptions, "model" | "systemPrompt" | "tools" | "env">, messages: { role: string; content: Block[] }[]): Json {
91
- const mark = { cache_control: { type: "ephemeral" } };
92
+ export function buildRequest(o: Pick<LoopOptions, "model" | "systemPrompt" | "tools" | "env">, messages: { role: string; content: Block[] }[], cache = true, maxTokens?: number): Json {
93
+ // A one-off request (a summary) writes nothing to the cache.
94
+ const mark = cache ? { cache_control: { type: "ephemeral" } } : {};
92
95
  const tools = o.tools.map((t, i) => ({
93
96
  name: t.name,
94
97
  description: t.description,
@@ -103,7 +106,7 @@ export function buildRequest(o: Pick<LoopOptions, "model" | "systemPrompt" | "to
103
106
  const asked = Number(o.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS);
104
107
  return {
105
108
  model: o.model,
106
- max_tokens: Number.isFinite(asked) && asked > 0 ? asked : DEFAULT_MAX_TOKENS,
109
+ max_tokens: Math.min(maxTokens ?? Infinity, Number.isFinite(asked) && asked > 0 ? asked : DEFAULT_MAX_TOKENS),
107
110
  ...(o.systemPrompt ? { system: [{ type: "text", text: o.systemPrompt, ...mark }] } : {}),
108
111
  ...(tools.length ? { tools } : {}),
109
112
  messages: sent,
@@ -137,7 +140,7 @@ async function openStream(o: LoopOptions, body: Json, signal: AbortSignal): Prom
137
140
  const text = (await res.text().catch(() => "")).slice(0, 500);
138
141
  lastError = `the model endpoint answered ${res.status}: ${text}`;
139
142
  const retryable = res.status === 408 || res.status === 409 || res.status === 429 || res.status >= 500;
140
- if (!retryable) throw new Error(lastError);
143
+ if (!retryable) throw Object.assign(new Error(lastError), { status: res.status });
141
144
  const after = Number(res.headers.get("retry-after"));
142
145
  if (attempt < MODEL_TRIES) await sleep(Math.min(RETRY_AFTER_CAP_MS, Number.isFinite(after) && after > 0 ? after * 1000 : 1000 * 2 ** (attempt - 1)), signal);
143
146
  } else if (attempt < MODEL_TRIES) {
@@ -190,9 +193,12 @@ interface Turn {
190
193
  }
191
194
 
192
195
  /** One model call: yields the raw stream events, returns the whole turn. */
193
- async function* modelTurn(o: LoopOptions, messages: { role: string; content: Block[] }[], signal: AbortSignal): AsyncGenerator<Json, Turn> {
194
- const res = await openStream(o, buildRequest(o, messages), signal);
196
+ async function* modelTurn(o: LoopOptions, messages: { role: string; content: Block[] }[], signal: AbortSignal, cache = true, maxTokens?: number, track?: { turn?: Turn }): AsyncGenerator<Json, Turn> {
197
+ const res = await openStream(o, buildRequest(o, messages, cache, maxTokens), signal);
195
198
  const turn: Turn = { id: "", model: o.model, content: [], stopReason: null, usage: emptyUsage(), malformed: new Set() };
199
+ // A caller that must count what a stream that breaks part-way had
200
+ // already reported (a summary request) reads it here.
201
+ if (track) track.turn = turn;
196
202
  const partialJson = new Map<number, string>();
197
203
  const open = new Set<number>();
198
204
  let stopped = false;
@@ -274,14 +280,140 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
274
280
  session_id: sessionId,
275
281
  });
276
282
 
277
- yield { type: "system", subtype: "init", session_id: sessionId, cwd: o.cwd, model: o.model, tools: o.tools.map((t) => t.name), mcp_servers: [], engine: "foldrun" };
278
-
283
+ // The step's MCP servers, connected before the first model call: their
284
+ // tools sit after the built-in and host ones (engine-mcp.ts). One that
285
+ // does not start refuses the step here, before anything is paid for.
286
+ let mcp: McpConnection | null = null;
279
287
  try {
288
+ if (Object.keys(o.mcpServers).length) {
289
+ mcp = await connectMcp(o.mcpServers, { env: o.env, toolEnv: o.shellEnv, cwd: o.cwd, signal });
290
+ for (const t of mcp.tools) {
291
+ if (byName.has(t.name)) throw new Error(`the MCP tool ${t.name} has the name of a tool the step already has`);
292
+ byName.set(t.name, t);
293
+ }
294
+ o.tools = [...o.tools, ...mcp.tools];
295
+ if (mcp.instructions.length) {
296
+ o.systemPrompt = [o.systemPrompt, "# MCP Server Instructions", ...mcp.instructions.map((i) => `## ${i.server}\n${i.text}`)].filter(Boolean).join("\n\n");
297
+ }
298
+ }
299
+ // A tool the step was granted that its server does not offer: the step
300
+ // would run without it, and the model be told it has none.
301
+ const missing = o.mcpGranted.filter((g) => mcp?.owner.get(g.name) !== g.server).map((g) => g.name);
302
+ if (missing.length) throw new Error(`granted but not offered by its MCP server: ${missing.join(", ")}`);
303
+
304
+ yield { type: "system", subtype: "init", session_id: sessionId, cwd: o.cwd, model: o.model, tools: o.tools.map((t) => t.name), mcp_servers: mcp?.servers ?? [], engine: "foldrun" };
305
+
306
+ // ---- Compaction (engine-compact.ts). What the context holds is the last
307
+ // turn's own count (everything it was sent, and its reply) plus an
308
+ // estimate of what has been added since; before any turn, an estimate of
309
+ // it all.
310
+ let measured: { tokens: number; at: number } | null = null;
311
+ const filesRead = new Set<string>();
312
+ const filesChanged = new Set<string>();
313
+ let autoCompaction = o.compaction !== false;
314
+ const contextNow = (): number => {
315
+ if (measured) return measured.tokens + messages.slice(measured.at).reduce((n, m) => n + estimateTokens(m), 0);
316
+ const fixed = Math.ceil((o.systemPrompt.length + JSON.stringify(o.tools.map((t) => [t.name, t.description, t.input_schema])).length) / 4);
317
+ return fixed + messages.reduce((n, m) => n + estimateTokens(m), 0);
318
+ };
319
+ /** Summarise the older part and go on from the summary and the newest
320
+ * part. False, with the reason, when there is nothing to cut or the
321
+ * summary did not come back whole. */
322
+ // `asked`: a summary was asked for (and paid for) and did not come back.
323
+ async function* compactNow(trigger: "auto" | "overflow", before: number): AsyncGenerator<Json, { ok: boolean; asked?: boolean; why?: string }> {
324
+ if (o.compaction === false) return { ok: false, why: "compaction is off" };
325
+ const room = o.compaction.contextWindow - o.compaction.reserveTokens;
326
+ // The kept part leaves room for the summary (a few thousand tokens).
327
+ // After an overflow the real window is smaller than assumed: the kept
328
+ // part is held to the keep budget itself.
329
+ let cut = findCut(messages, o.compaction.keepRecentTokens, trigger === "overflow" ? o.compaction.keepRecentTokens : Math.max(0, room - 4_096));
330
+ if (cut < 1) return { ok: false, why: "there was nothing older to summarise" };
331
+ // A summary of a few words makes no room and is not worth paying for:
332
+ // a later cut is tried (the newest message is always kept).
333
+ const older = (c: number) => messages.slice(0, c).reduce((n, m) => n + estimateTokens(m), 0);
334
+ for (const later of cutPoints(messages)) if (later > cut && older(cut) < 1_024) cut = later;
335
+ if (older(cut) < 1_024) return { ok: false, why: "there was too little older to summarise" };
336
+ const ask = { ...o, systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, tools: [], partial: false };
337
+ // The request itself must fit: the conversation's text is held to the
338
+ // window less the reply's reserve and the prompts, newest part kept.
339
+ const request = [{ role: "user", content: [{ type: "text", text: summaryRequest(messages.slice(0, cut), previousSummary(messages), Math.max(4_000, (room - 3_000) * 4)) }] }];
340
+ let reply: Turn;
341
+ const track: { turn?: Turn } = {};
342
+ try {
343
+ // Its reply is held to the window's reserve: input and output must fit.
344
+ const stream = modelTurn(ask, request, signal, false, o.compaction.reserveTokens, track);
345
+ for (;;) {
346
+ const step = await stream.next();
347
+ if (step.done) { reply = step.value; break; }
348
+ }
349
+ } catch (err) {
350
+ // What the endpoint had counted before the stream broke was paid for.
351
+ const spent = track.turn?.usage;
352
+ if (spent && Object.values(spent).some((n) => n > 0)) {
353
+ for (const k of Object.keys(total) as (keyof Usage)[]) total[k] += spent[k];
354
+ yield { type: "system", subtype: "compact_failed", session_id: sessionId, error: `the summary request failed: ${(err as Error).message}`, model: track.turn!.model, usage: { ...spent } };
355
+ }
356
+ if (signal.aborted) throw err;
357
+ return { ok: false, asked: true, why: `the summary request failed: ${(err as Error).message}` };
358
+ }
359
+ // Paid for like any turn: in the total, and reported with what it
360
+ // came to so the step's cost and budget count it (step-exec).
361
+ for (const k of Object.keys(total) as (keyof Usage)[]) total[k] += reply.usage[k];
362
+ const summary = reply.content.filter((b) => b.type === "text").map((b) => String(b.text ?? "")).join("\n").trim();
363
+ if (reply.stopReason !== "end_turn" || reply.content.some((b) => b.type === "tool_use") || !summary) {
364
+ const why = `the summary did not come back whole (stop reason ${reply.stopReason ?? "none"})`;
365
+ yield { type: "system", subtype: "compact_failed", session_id: sessionId, error: why, model: reply.model, usage: { ...reply.usage } };
366
+ return { ok: false, asked: true, why };
367
+ }
368
+ const next = compacted(summary + fileLists(filesRead, filesChanged), messages.slice(cut));
369
+ messages.splice(0, messages.length, ...next);
370
+ measured = null;
371
+ yield {
372
+ type: "system",
373
+ subtype: "compact_boundary",
374
+ session_id: sessionId,
375
+ compact_metadata: { trigger, pre_tokens: before, post_tokens: contextNow(), summarized_messages: cut },
376
+ model: reply.model,
377
+ usage: { ...reply.usage },
378
+ // The conversation as it now stands, so a caller that keeps one
379
+ // (foldrun code) goes on from it rather than the whole history.
380
+ conversation: messages.map((m) => ({ role: m.role, content: [...m.content] })),
381
+ };
382
+ return { ok: true };
383
+ }
384
+
385
+ // Set when a request was refused as too long and compacted: the same
386
+ // request is asked again once, not compacted again and again.
387
+ let overflowed = false;
280
388
  for (;;) {
281
389
  if (o.maxTurns !== null && turns >= o.maxTurns) {
282
390
  yield result("error_max_turns", null);
283
391
  return;
284
392
  }
393
+ // Not on the retry after an overflow (that request is asked again as
394
+ // compacted), and not while the model's own turn is being continued
395
+ // (pause_turn): the conversation must end on a user turn to be cut.
396
+ if (autoCompaction && !overflowed && o.compaction !== false && messages.at(-1)?.role === "user") {
397
+ const now = contextNow();
398
+ if (now > o.compaction.contextWindow - o.compaction.reserveTokens) {
399
+ let done: { ok: boolean; asked?: boolean; why?: string };
400
+ try {
401
+ done = yield* compactNow("auto", now);
402
+ } catch (err) {
403
+ if (interrupted() || signal.aborted) return;
404
+ throw err;
405
+ }
406
+ if (interrupted() || signal.aborted) return;
407
+ // A summary asked for and not given is not asked for again before
408
+ // every turn after: the request goes as it is, and the endpoint says
409
+ // if it is too long. Nothing to cut yet costs nothing: looked at
410
+ // again next turn.
411
+ if (!done.ok && done.asked) autoCompaction = false;
412
+ // A summary that could not bring the context under the line will
413
+ // not by summarising again before every turn.
414
+ if (done.ok && contextNow() > o.compaction.contextWindow - o.compaction.reserveTokens) autoCompaction = false;
415
+ }
416
+ }
285
417
  let turn: Turn;
286
418
  try {
287
419
  const stream = modelTurn(o, messages, signal);
@@ -297,9 +429,19 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
297
429
  // An interrupt we were asked for ends the loop quietly: the caller
298
430
  // knows why and reports it. Anything else is the step's failure.
299
431
  if (interrupted() || signal.aborted) return;
432
+ // The endpoint said the prompt does not fit (a model with a smaller
433
+ // window than assumed): compact and ask again — once per request.
434
+ if (!overflowed && o.compaction !== false && messages.at(-1)?.role === "user" && isContextOverflow((err as { status?: number }).status, (err as Error).message)) {
435
+ overflowed = true;
436
+ const done = yield* compactNow("overflow", contextNow());
437
+ if (interrupted() || signal.aborted) return;
438
+ if (!done.ok) throw new Error(`${(err as Error).message} — and the conversation could not be compacted: ${done.why}`);
439
+ continue;
440
+ }
300
441
  throw err;
301
442
  }
302
443
  turns++;
444
+ overflowed = false;
303
445
  for (const k of Object.keys(total) as (keyof Usage)[]) total[k] += turn.usage[k];
304
446
  const text = turn.content.filter((b) => b.type === "text").map((b) => String(b.text ?? "")).join("\n").trim();
305
447
  if (text) lastText = text;
@@ -309,7 +451,13 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
309
451
  parent_tool_use_id: null,
310
452
  session_id: sessionId,
311
453
  };
312
- messages.push({ role: "assistant", content: turn.content });
454
+ // A paused turn's continuation is the same turn: joined to it, so the
455
+ // conversation still alternates (what foldrun code keeps, and a cut).
456
+ const prev = messages[messages.length - 1];
457
+ if (prev?.role === "assistant") prev.content = [...prev.content, ...turn.content];
458
+ else messages.push({ role: "assistant", content: turn.content });
459
+ // The turn's own count: all it was sent, and its reply.
460
+ measured = { tokens: turn.usage.input_tokens + turn.usage.cache_read_input_tokens + turn.usage.cache_creation_input_tokens + turn.usage.output_tokens, at: messages.length };
313
461
  if (interrupted()) return;
314
462
 
315
463
  const calls = turn.content.filter((b) => b.type === "tool_use");
@@ -346,6 +494,12 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
346
494
  } catch (err) {
347
495
  outcome = { text: `${p.tool.name} failed: ${(err as Error).message}`, isError: true };
348
496
  }
497
+ // For a summary's file lists: what ran, as the hooks left it, and did not fail.
498
+ const file = p.decision.input.file_path;
499
+ if (!outcome.isError && typeof file === "string") {
500
+ if (p.tool.name === "Read") filesRead.add(file);
501
+ else if (p.tool.name === "Write" || p.tool.name === "Edit") filesChanged.add(file);
502
+ }
349
503
  const context = await after(o, p.tool.name, String(p.block.id), p.decision.input, outcome, sessionId, signal);
350
504
  return { outcome, context };
351
505
  };
@@ -369,12 +523,15 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
369
523
  }
370
524
  if (interrupted()) return;
371
525
 
372
- const results: Block[] = planned.map((p, i) => ({
373
- type: "tool_result",
374
- tool_use_id: String(p.block.id),
375
- content: done[i].outcome.text,
376
- ...(done[i].outcome.isError ? { is_error: true } : {}),
377
- }));
526
+ const results: Block[] = planned.map((p, i) => {
527
+ const { text, isError, parts } = done[i].outcome;
528
+ // An image a tool returned (an MCP server's screenshot) goes to the
529
+ // model as an image, in its place among the text.
530
+ const content = parts
531
+ ? parts.map((p) => p.type === "text" ? { type: "text", text: p.text } : { type: "image", source: { type: "base64", media_type: p.mediaType, data: p.data } })
532
+ : text;
533
+ return { type: "tool_result", tool_use_id: String(p.block.id), content, ...(isError ? { is_error: true } : {}) };
534
+ });
378
535
  const context = done.flatMap((d) => d.context);
379
536
  const content: Block[] = [...results, ...context.map((c) => ({ type: "text", text: c }))];
380
537
  messages.push({ role: "user", content });
@@ -382,8 +539,10 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
382
539
  }
383
540
  } finally {
384
541
  // However the loop ended — an answer, a stop, a consumer that walked
385
- // away — nothing a command started outlives the step.
542
+ // away — nothing a command started outlives the step, and no MCP server
543
+ // it started either.
386
544
  killGroups(ctx);
545
+ await mcp?.close();
387
546
  }
388
547
  }
389
548
 
@@ -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/ops-log.ts CHANGED
@@ -198,7 +198,7 @@ export function opsBoundaryInstalled(): boolean {
198
198
  return boundary() !== null;
199
199
  }
200
200
 
201
- function readable(level: OpsLevel, line: Record<string, unknown>, detail?: string): string {
201
+ function readable(line: Record<string, unknown>, detail?: string): string {
202
202
  const parts = Object.entries(line)
203
203
  .filter(([k]) => k !== "ops" && k !== "level" && k !== "event")
204
204
  .map(([k, v]) => `${k}=${Array.isArray(v) ? v.join(",") : String(v)}`);
@@ -213,7 +213,7 @@ function emit(level: OpsLevel, line: Record<string, unknown>, detail?: string):
213
213
  }
214
214
  // No boundary: a laptop, a test, `next dev` — the reader is the person
215
215
  // whose content it is, so the error's own words come along.
216
- const text = readable(level, line, detail);
216
+ const text = readable(line, detail);
217
217
  if (level === "info") console.log(text);
218
218
  else if (level === "warn") console.warn(text);
219
219
  else console.error(text);
package/src/providers.ts CHANGED
@@ -778,16 +778,16 @@ export function readBrowseSession(raw: unknown, key: "vendor_session" | "session
778
778
  return { error: `${at} is a block — what the vendor's own session is asked for: proxy, captcha, stealth, region, timeout, keep, record, block, options.` };
779
779
  }
780
780
  const out: BrowseSession = {};
781
- const bool = (k: string, v: unknown) => (v === true || v === "true" ? true : v === false || v === "false" ? false : undefined);
781
+ const bool = (v: unknown) => (v === true || v === "true" ? true : v === false || v === "false" ? false : undefined);
782
782
  for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
783
783
  if (!(SESSION_KEYS as readonly string[]).includes(k)) return { error: `${at}.${k}: is not a session setting. They are ${SESSION_KEYS.join(", ")}.` };
784
784
  if (v === undefined || v === null || v === "") continue;
785
785
  if (k === "captcha" || k === "stealth" || k === "record") {
786
- const b = bool(k, v);
786
+ const b = bool(v);
787
787
  if (b === undefined) return { error: `${at}.${k} is true or false, not ${JSON.stringify(v)}.` };
788
788
  out[k] = b;
789
789
  } else if (k === "proxy") {
790
- const b = bool(k, v);
790
+ const b = bool(v);
791
791
  if (b !== undefined) { out.proxy = b; continue; }
792
792
  if (typeof v !== "object" || Array.isArray(v)) return { error: `${at}.proxy is true, false, or a block: country, state, city — or own: a secret holding your proxy's URL.` };
793
793
  const p: { country?: string; state?: string; city?: string; own?: string } = {};
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