@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.
@@ -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 ?? "";