@foldrun/core 24.10.0 → 24.12.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.
@@ -137,11 +137,17 @@ export declare function readAgentsMd(dir: string): {
137
137
  * the two can never disagree about what an agent needs.
138
138
  */
139
139
  export declare function agentRuntimeSpec(tenant: string, workspace: string, agentDir: string): RuntimeSpec | null;
140
- /** Every distinct runtime a workspace's agents need, with who needs it. */
140
+ /** The node disk one agent's steps may write: its `size:` class's, or its
141
+ * own `resources: disk` over it — the figure the runner gives its pod. */
142
+ export declare function agentDisk(agentDir: string): string;
143
+ /** Every distinct runtime a workspace's agents need, with who needs it and
144
+ * `disk`, the most node disk any of those agents' steps may write (a
145
+ * runtime built for them has at least that much room to be built in). */
141
146
  export declare function workspaceRuntimePlan(tenant: string, workspace: string): {
142
147
  fingerprint: string;
143
148
  spec: RuntimeSpec;
144
149
  agents: string[];
150
+ disk: string;
145
151
  }[];
146
152
  /**
147
153
  * The calendar a set of frontmatter asks for, with no cascade around it —
@@ -20,7 +20,7 @@ import { resolveAgentPath } from "./confine.js";
20
20
  import { browserPodLine, podLossDecision, RERAN_ON_FULL } from "./browser-pod.js";
21
21
  import { eventUrl } from "./webhook.js";
22
22
  import { runStepInContainer, resolveResources, memoryGiB, heldCores, killRunSandboxes, classDisk } from "./run-container.js";
23
- import { readResources, hasOverride } from "./resources.js";
23
+ import { readResources, hasOverride, anyMemoryMi } from "./resources.js";
24
24
  import { hostSafeEnv, platformApiUrl } from "./host-env.js";
25
25
  import { resolveModelCredential, credentialLine, accountModelBlock, isClaudeLoginToken, isModelEnvName, DECLARED_ENV_PREFIX } from "./model-credential.js";
26
26
  import { parseJudge } from "./judge-verdict.js";
@@ -484,19 +484,42 @@ export function agentRuntimeSpec(tenant, workspace, agentDir) {
484
484
  .map(toolRuntime);
485
485
  return mergeRuntimes(ownRuntime(front, agentDir, tenant), ...tools);
486
486
  }
487
- /** Every distinct runtime a workspace's agents need, with who needs it. */
487
+ /** The node disk one agent's steps may write: its `size:` class's, or its
488
+ * own `resources: disk` over it — the figure the runner gives its pod. */
489
+ export function agentDisk(agentDir) {
490
+ const file = path.join(agentDir, "agent.md");
491
+ let front = {};
492
+ try {
493
+ // The step's own parser: it lifts `guardrail: { resources: … }` to the
494
+ // top, so both spellings of a disk override count here as they do there.
495
+ if (fs.existsSync(file))
496
+ front = configMatter(fs.readFileSync(file, "utf8")).data;
497
+ }
498
+ catch {
499
+ /* frontmatter that does not parse: the class default, as `check` reports it */
500
+ }
501
+ const size = front.size === "small" ? "small" : front.size === "heavy" ? "heavy" : "large";
502
+ return resolveResources(size, readResources(front.resources).value).disk ?? classDisk(size);
503
+ }
504
+ /** Every distinct runtime a workspace's agents need, with who needs it and
505
+ * `disk`, the most node disk any of those agents' steps may write (a
506
+ * runtime built for them has at least that much room to be built in). */
488
507
  export function workspaceRuntimePlan(tenant, workspace) {
489
508
  const byFp = new Map();
490
509
  const agentsRoot = path.join(workspaceDir(tenant, workspace), "agents");
491
510
  if (!fs.existsSync(agentsRoot))
492
511
  return [];
493
512
  for (const name of fs.readdirSync(agentsRoot).sort()) {
494
- const spec = agentRuntimeSpec(tenant, workspace, path.join(agentsRoot, name));
513
+ const dir = path.join(agentsRoot, name);
514
+ const spec = agentRuntimeSpec(tenant, workspace, dir);
495
515
  if (!spec)
496
516
  continue;
497
517
  const fp = fingerprint(spec);
498
- const entry = byFp.get(fp) ?? { fingerprint: fp, spec, agents: [] };
518
+ const disk = agentDisk(dir);
519
+ const entry = byFp.get(fp) ?? { fingerprint: fp, spec, agents: [], disk };
499
520
  entry.agents.push(name);
521
+ if (anyMemoryMi(disk) > anyMemoryMi(entry.disk))
522
+ entry.disk = disk;
500
523
  byFp.set(fp, entry);
501
524
  }
502
525
  return [...byFp.values()];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "24.10.0",
3
+ "version": "24.12.0",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
@@ -35,7 +35,8 @@
35
35
  "./tool-names",
36
36
  "./scan",
37
37
  "./snapshot-archive",
38
- "./engine-loop"
38
+ "./engine-loop",
39
+ "./local-sandbox"
39
40
  ]
40
41
  },
41
42
  "main": "./dist/index.js",
@@ -61,6 +62,7 @@
61
62
  },
62
63
  "dependencies": {
63
64
  "@anthropic-ai/claude-agent-sdk": "^0.3.296",
65
+ "@anthropic-ai/sandbox-runtime": "0.0.83",
64
66
  "@modelcontextprotocol/sdk": "1.32.1",
65
67
  "gray-matter": "^4.0.3",
66
68
  "zod": "4.6.7"
@@ -83,5 +85,10 @@
83
85
  ],
84
86
  "publishConfig": {
85
87
  "access": "public"
88
+ },
89
+ "overrides": {
90
+ "@anthropic-ai/sandbox-runtime": {
91
+ "zod": "$zod"
92
+ }
86
93
  }
87
94
  }
@@ -44,12 +44,30 @@ export type HookFn = (input: Json, toolUseId?: string, extra?: { signal: AbortSi
44
44
  export type CanUseTool = (name: string, input: Json, extra: { signal: AbortSignal; toolUseID: string }) =>
45
45
  Promise<{ behavior: "allow"; updatedInput?: Json } | { behavior: "deny"; message: string }>;
46
46
 
47
+ /** What the loop needs of a local sandbox — LocalSandbox has it. */
48
+ export interface SandboxWalls {
49
+ /** How to run `command` inside, with `env` as its environment: LAUNCHER
50
+ * -c line, started with exactly the env given back. */
51
+ launch(command: string, env: Record<string, string | undefined>): Promise<{ line: string; env: Record<string, string>; token?: string }>;
52
+ /** Whether a long-lived process launched with `token` still runs under
53
+ * the walls as they are now (false: stop it). */
54
+ fresh?(token: string): boolean;
55
+ /** Call `listener` with the new token whenever a launch finds the
56
+ * protections changed; returns how to stop listening. */
57
+ onChange?(listener: (token: string) => void | Promise<void>): () => void;
58
+ canRead(file: string): boolean;
59
+ canWrite(file: string): boolean;
60
+ }
61
+
47
62
  export interface LoopOptions {
48
63
  cwd: string;
49
64
  env: Record<string, string | undefined>;
50
65
  /** What the tools (Bash) get; `env` when not given. foldrun code passes
51
66
  * the person's own environment here, so the model key stays with the loop. */
52
67
  shellEnv: Record<string, string | undefined>;
68
+ /** The walls on a person's own machine (local-sandbox.ts): every command
69
+ * runs through `wrap`, the file tools ask canRead / canWrite. */
70
+ localSandbox: SandboxWalls | null;
53
71
  model: string;
54
72
  systemPrompt: string;
55
73
  tools: EngineTool[];
@@ -110,8 +128,17 @@ export function readOptions(options: Json, engine = "foldrun"): LoopOptions {
110
128
  throw new Error(`the ${engine} engine does not run sub-agents yet — run this agent on the default engine.`);
111
129
  }
112
130
  const sandbox = options.sandbox as { enabled?: boolean } | undefined;
131
+ const walls = options.localSandbox as Partial<SandboxWalls> | undefined;
132
+ const localSandbox =
133
+ walls && typeof walls.launch === "function" && typeof walls.canRead === "function" && typeof walls.canWrite === "function"
134
+ ? (walls as SandboxWalls)
135
+ : null;
136
+ if (walls && !localSandbox) throw new Error("localSandbox: needs launch, canRead and canWrite");
137
+ // Inside the walls the tools' environment is said outright: falling back
138
+ // to `env` would hand every command the model's key.
139
+ if (localSandbox && !(options.shellEnv && typeof options.shellEnv === "object")) throw new Error("localSandbox: give shellEnv, the environment commands run with");
113
140
  // Never read from `env`: that is where a tenant's secrets live.
114
- if (names.includes("Bash") && sandbox?.enabled !== false && options.engineHostShell !== true) {
141
+ if (names.includes("Bash") && !localSandbox && sandbox?.enabled !== false && options.engineHostShell !== true) {
115
142
  throw new Error(`the ${engine} engine has no OS sandbox for the shell on this host — run the step in a container.`);
116
143
  }
117
144
  const model = String(options.model ?? "");
@@ -132,6 +159,7 @@ export function readOptions(options: Json, engine = "foldrun"): LoopOptions {
132
159
  cwd: String(options.cwd ?? process.cwd()),
133
160
  env,
134
161
  shellEnv: options.shellEnv && typeof options.shellEnv === "object" ? (options.shellEnv as Record<string, string | undefined>) : env,
162
+ localSandbox,
135
163
  model: env[`ANTHROPIC_DEFAULT_${model.toUpperCase()}_MODEL`] || TIER_DEFAULTS[model] || model,
136
164
  systemPrompt: typeof options.systemPrompt === "string" ? options.systemPrompt : "",
137
165
  tools: [...names.map((n) => ENGINE_TOOLS[n]), ...extra],
@@ -274,7 +274,11 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
274
274
  .filter((t): t is string => typeof t === "string" && t.trim() !== "")
275
275
  .map((t) => ({ type: "text", text: t.slice(0, 20_000) }));
276
276
  };
277
- const ctx: ToolContext = { cwd: o.cwd, env: o.shellEnv, signal, reads: new Map(), groups: new Set() };
277
+ const ctx: ToolContext = { cwd: o.cwd, env: o.shellEnv, signal, reads: new Map(), groups: new Set(), sandbox: o.localSandbox };
278
+ // Inside the walls, what a command left running (a server in the
279
+ // background) holds the rules it started under: when a later launch finds
280
+ // them changed, it is ended before that launch goes ahead.
281
+ const unwatch = o.localSandbox?.onChange?.(() => killGroups(ctx));
278
282
  // An earlier conversation comes first (foldrun code's local turns carry
279
283
  // theirs, 19 Nov 2026); the prompt is always the newest user turn.
280
284
  if (o.history.length % 2 !== 0) throw new Error("history must end with the model's turn, so the prompt is the next user turn");
@@ -302,7 +306,7 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
302
306
  let mcp: McpConnection | null = null;
303
307
  try {
304
308
  if (Object.keys(o.mcpServers).length) {
305
- mcp = await connectMcp(o.mcpServers, { env: o.env, toolEnv: o.shellEnv, cwd: o.cwd, signal });
309
+ mcp = await connectMcp(o.mcpServers, { env: o.env, toolEnv: o.shellEnv, cwd: o.cwd, signal, sandbox: o.localSandbox });
306
310
  for (const t of mcp.tools) {
307
311
  if (byName.has(t.name)) throw new Error(`the MCP tool ${t.name} has the name of a tool the step already has`);
308
312
  byName.set(t.name, t);
@@ -572,6 +576,7 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
572
576
  // away — nothing a command started outlives the step, and no MCP server
573
577
  // it started either.
574
578
  killGroups(ctx);
579
+ unwatch?.();
575
580
  await mcp?.close();
576
581
  }
577
582
  }
package/src/engine-mcp.ts CHANGED
@@ -99,7 +99,15 @@ export interface McpConnection {
99
99
  close(): Promise<void>;
100
100
  }
101
101
 
102
- function transportFor(s: McpSpec, env: Record<string, string | undefined>, cwd: string): { client: Transport; server?: Transport } {
102
+ import { LAUNCHER, killTree } from "./local-sandbox.ts";
103
+ import type { SandboxWalls } from "./engine-common.ts";
104
+
105
+ /** A program and its arguments as one shell line, each word quoted. */
106
+ export function shellLine(command: string, args: string[]): string {
107
+ return [command, ...args].map((w) => `'${w.replaceAll("'", `'\\''`)}'`).join(" ");
108
+ }
109
+
110
+ function transportFor(s: McpSpec, env: Record<string, string | undefined>, cwd: string, wrapped?: string): { client: Transport; server?: Transport } {
103
111
  if (s.type === "sdk") {
104
112
  const [client, server] = InMemoryTransport.createLinkedPair();
105
113
  return { client, server };
@@ -112,6 +120,15 @@ function transportFor(s: McpSpec, env: Record<string, string | undefined>, cwd:
112
120
  // process where the step has none: names a program needs, no secrets.
113
121
  const base: Record<string, string> = {};
114
122
  for (const [k, v] of Object.entries(env)) if (typeof v === "string") base[k] = v;
123
+ // Inside the walls (a person's machine), the server starts as the
124
+ // sandbox's wrapping of its command line, so it and what it starts
125
+ // stay inside them.
126
+ // Its variables, the spec's too, ride inside (launch); `env` here is
127
+ // the launcher's own few, so none of them touches the program that
128
+ // puts the walls up.
129
+ if (wrapped !== undefined) {
130
+ return { client: new StdioClientTransport({ command: LAUNCHER, args: ["-c", wrapped], env: base, cwd, stderr: "ignore" }) };
131
+ }
115
132
  return { client: new StdioClientTransport({ command: s.command!, args: s.args ?? [], env: { ...base, ...(s.env ?? {}) }, cwd, stderr: "ignore" }) };
116
133
  }
117
134
  const url = new URL(s.url!);
@@ -191,7 +208,7 @@ function bounded<T>(work: Promise<T>, ms: number, signal: AbortSignal, what: str
191
208
  * read, as the SDK read it); `toolEnv` is what a tool's process starts
192
209
  * from — the loop's shellEnv, which a caller keeps apart from the model's
193
210
  * 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> {
211
+ export async function connectMcp(servers: Record<string, McpSpec>, ctx: { env: Record<string, string | undefined>; toolEnv: Record<string, string | undefined>; cwd: string; signal: AbortSignal; sandbox?: Pick<SandboxWalls, "launch" | "fresh" | "onChange"> | null }): Promise<McpConnection> {
195
212
  const open: { client: Client; transport: Transport; server?: Transport }[] = [];
196
213
  const close = async () => {
197
214
  await Promise.all(open.map(async (o) => {
@@ -210,9 +227,40 @@ export async function connectMcp(servers: Record<string, McpSpec>, ctx: { env: R
210
227
  const envTimeout = Number(ctx.env.MCP_TOOL_TIMEOUT);
211
228
  try {
212
229
  for (const [name, s] of Object.entries(servers)) {
213
- const t = transportFor(s, ctx.toolEnv, ctx.cwd);
230
+ let wrapped: { line: string; env: Record<string, string>; token?: string } | undefined;
231
+ if (ctx.sandbox && s.type === "stdio") {
232
+ // The server's environment (the step's, then what the spec names)
233
+ // is set again inside; the launcher starts with the walls' own.
234
+ wrapped = await ctx.sandbox.launch(shellLine(s.command!, s.args ?? []), { ...ctx.toolEnv, ...(s.env ?? {}) });
235
+ if (!wrapped?.line) throw new Error(`MCP server ${name}: the sandbox gave no command line`);
236
+ // A long-lived server inside the walls must be stoppable when they
237
+ // change: without a token and a way to check it, it does not start.
238
+ if (!wrapped.token || typeof ctx.sandbox.fresh !== "function" || typeof ctx.sandbox.onChange !== "function") throw new Error(`MCP server ${name}: this sandbox cannot tell a long-lived server when its rules change, so it is not started`);
239
+ } else if (ctx.sandbox && (s.type === "http" || s.type === "sse")) {
240
+ // This process would make that connection itself, past the walls'
241
+ // proxy and its address checks: not offered inside the walls.
242
+ throw new Error(`MCP server ${name}: a server over ${s.type === "sse" ? "SSE" : "HTTP"} is not available inside the local sandbox — run this in the cloud, or use a stdio server`);
243
+ }
244
+ const t = wrapped ? transportFor(s, wrapped.env, ctx.cwd, wrapped.line) : transportFor(s, ctx.toolEnv, ctx.cwd);
214
245
  const client = new Client({ name: "foldrun-engine", version: "1.0.0" });
215
246
  open.push({ client, transport: t.client, server: t.server });
247
+ const sandboxToken = wrapped?.token;
248
+ // Any launch that finds the protections changed stops this server at
249
+ // once, not only its own next call.
250
+ if (sandboxToken !== undefined && ctx.sandbox?.onChange) {
251
+ const transport = t.client as { pid?: number | null };
252
+ const stop = ctx.sandbox.onChange(async (now) => {
253
+ if (now === sandboxToken) return;
254
+ stop();
255
+ // Ended, with all it started, before the launch that saw the
256
+ // change goes ahead.
257
+ // The tree is read and ended while the server still holds it:
258
+ // closed first, its children would be orphaned out of reach.
259
+ const pid = transport.pid ?? null;
260
+ if (pid) killTree(pid);
261
+ await client.close().catch(() => undefined);
262
+ });
263
+ }
216
264
  let listed: { name: string; description?: string; inputSchema?: Json; annotations?: { readOnlyHint?: boolean } }[];
217
265
  if (ctx.signal.aborted) throw new Error(`the MCP server ${name} did not start: connect: stopped`);
218
266
  try {
@@ -267,6 +315,15 @@ export async function connectMcp(servers: Record<string, McpSpec>, ctx: { env: R
267
315
  // Run beside other reads only when the server says it changes nothing.
268
316
  readOnly: tool.annotations?.readOnlyHint === true,
269
317
  run: async (input, toolCtx) => {
318
+ // A server inside the walls holds the write rules it started
319
+ // under: once git's protections have changed it is stopped, and
320
+ // the call refused, rather than run with the old ones.
321
+ if (sandboxToken !== undefined && ctx.sandbox?.fresh && !ctx.sandbox.fresh(sandboxToken)) {
322
+ const pid = (t.client as { pid?: number | null }).pid ?? null;
323
+ if (pid) killTree(pid);
324
+ await client.close().catch(() => undefined);
325
+ return { text: `the MCP server ${name} was stopped: the files this session may not write changed after it started (a git hooks path or repository). It starts again on the next step.`, isError: true };
326
+ }
270
327
  const result = await client.callTool({ name: tool.name, arguments: input }, undefined, { signal: toolCtx.signal, timeout, maxTotalTimeout: timeout });
271
328
  return outcomeOf(result as Json);
272
329
  },