@foldrun/core 24.8.1 → 24.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 ?? "";