@foldrun/core 24.11.0 → 24.13.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.
@@ -111,6 +111,10 @@ export declare const DEPLOY_BLOCK_MODES: readonly ["none", "secrets", "security"
111
111
  export type DeployBlockMode = (typeof DEPLOY_BLOCK_MODES)[number];
112
112
  /** The workspace's own AGENTS.md, else the account's, else none. */
113
113
  export declare function deployBlockMode(files: DeployFile[], accountKeys: Record<string, unknown>): DeployBlockMode;
114
+ /** Own keys off on this platform (models.byok, 22 Nov 2026): every
115
+ * `provider:` in the files is a refusal — nothing deploys that would run on
116
+ * an endpoint the platform does not meter. Nothing where they are allowed. */
117
+ export declare function ownKeyBlockers(tenant: string, files: DeployFile[]): DeployIssue[];
114
118
  /** The findings `mode` turns into refusals, as deploy issues. */
115
119
  export declare function deployBlockers(files: DeployFile[], mode: DeployBlockMode, options?: ScanOptions): DeployIssue[];
116
120
  export declare function deployWarnings(files: DeployFile[]): DeployIssue[];
@@ -43,6 +43,7 @@ import { languageProblem } from "./language.js";
43
43
  import { localeProblems } from "./locale.js";
44
44
  import { entriesNoFollow } from "./paths.js";
45
45
  import { filterIgnored, findingFingerprint, ruleForWhere, scanFiles, scanRule, STRICT_FRONTMATTER_PATH } from "./scan.js";
46
+ import { platform } from "./platform.js";
46
47
  /** Directories a deploy never reads out of a source tree. */
47
48
  // `.cache` is what a run's tools leave in an agent's folder (HOME is that
48
49
  // folder): logs and font caches, never authored.
@@ -311,6 +312,17 @@ function blockersFor(tenant, given) {
311
312
  .map(([n]) => n);
312
313
  return deployBlockers(files, mode, { accountNetwork: account.network, outwardTools });
313
314
  }
315
+ /** Own keys off on this platform (models.byok, 22 Nov 2026): every
316
+ * `provider:` in the files is a refusal — nothing deploys that would run on
317
+ * an endpoint the platform does not meter. Nothing where they are allowed. */
318
+ export function ownKeyBlockers(tenant, files) {
319
+ if (platform.ownModelKeys?.(tenant) ?? true)
320
+ return [];
321
+ return scanFiles(files, { only: ["config/own-model-key"], ownModelKeys: false }).map((f) => ({
322
+ where: `${f.file}${f.line ? `:${f.line}` : ""}`,
323
+ message: `${f.message} [${f.rule}]`,
324
+ }));
325
+ }
314
326
  /** The findings `mode` turns into refusals, as deploy issues. */
315
327
  export function deployBlockers(files, mode, options = {}) {
316
328
  if (mode === "none")
@@ -777,7 +789,7 @@ export function planDeploy(tenant, workspace, files, opts = {}) {
777
789
  // deploy_block: (FOL-58) turns the scanner's findings into refusals —
778
790
  // scanned with what the Checks page passes too: the account's network:
779
791
  // and the library's outward tools (Codex review).
780
- issues: [...deployIssues(files), ...blockersFor(tenant, files)],
792
+ issues: [...deployIssues(files), ...blockersFor(tenant, files), ...ownKeyBlockers(tenant, files)],
781
793
  warnings: deployWarnings(files),
782
794
  blockedBy: runsInFlight(tenant, workspace),
783
795
  };
@@ -29,12 +29,33 @@ export type CanUseTool = (name: string, input: Json, extra: {
29
29
  behavior: "deny";
30
30
  message: string;
31
31
  }>;
32
+ /** What the loop needs of a local sandbox — LocalSandbox has it. */
33
+ export interface SandboxWalls {
34
+ /** How to run `command` inside, with `env` as its environment: LAUNCHER
35
+ * -c line, started with exactly the env given back. */
36
+ launch(command: string, env: Record<string, string | undefined>): Promise<{
37
+ line: string;
38
+ env: Record<string, string>;
39
+ token?: string;
40
+ }>;
41
+ /** Whether a long-lived process launched with `token` still runs under
42
+ * the walls as they are now (false: stop it). */
43
+ fresh?(token: string): boolean;
44
+ /** Call `listener` with the new token whenever a launch finds the
45
+ * protections changed; returns how to stop listening. */
46
+ onChange?(listener: (token: string) => void | Promise<void>): () => void;
47
+ canRead(file: string): boolean;
48
+ canWrite(file: string): boolean;
49
+ }
32
50
  export interface LoopOptions {
33
51
  cwd: string;
34
52
  env: Record<string, string | undefined>;
35
53
  /** What the tools (Bash) get; `env` when not given. foldrun code passes
36
54
  * the person's own environment here, so the model key stays with the loop. */
37
55
  shellEnv: Record<string, string | undefined>;
56
+ /** The walls on a person's own machine (local-sandbox.ts): every command
57
+ * runs through `wrap`, the file tools ask canRead / canWrite. */
58
+ localSandbox: SandboxWalls | null;
38
59
  model: string;
39
60
  systemPrompt: string;
40
61
  tools: EngineTool[];
@@ -62,8 +62,18 @@ export function readOptions(options, engine = "foldrun") {
62
62
  throw new Error(`the ${engine} engine does not run sub-agents yet — run this agent on the default engine.`);
63
63
  }
64
64
  const sandbox = options.sandbox;
65
+ const walls = options.localSandbox;
66
+ const localSandbox = walls && typeof walls.launch === "function" && typeof walls.canRead === "function" && typeof walls.canWrite === "function"
67
+ ? walls
68
+ : null;
69
+ if (walls && !localSandbox)
70
+ throw new Error("localSandbox: needs launch, canRead and canWrite");
71
+ // Inside the walls the tools' environment is said outright: falling back
72
+ // to `env` would hand every command the model's key.
73
+ if (localSandbox && !(options.shellEnv && typeof options.shellEnv === "object"))
74
+ throw new Error("localSandbox: give shellEnv, the environment commands run with");
65
75
  // Never read from `env`: that is where a tenant's secrets live.
66
- if (names.includes("Bash") && sandbox?.enabled !== false && options.engineHostShell !== true) {
76
+ if (names.includes("Bash") && !localSandbox && sandbox?.enabled !== false && options.engineHostShell !== true) {
67
77
  throw new Error(`the ${engine} engine has no OS sandbox for the shell on this host — run the step in a container.`);
68
78
  }
69
79
  const model = String(options.model ?? "");
@@ -86,6 +96,7 @@ export function readOptions(options, engine = "foldrun") {
86
96
  cwd: String(options.cwd ?? process.cwd()),
87
97
  env,
88
98
  shellEnv: options.shellEnv && typeof options.shellEnv === "object" ? options.shellEnv : env,
99
+ localSandbox,
89
100
  model: env[`ANTHROPIC_DEFAULT_${model.toUpperCase()}_MODEL`] || TIER_DEFAULTS[model] || model,
90
101
  systemPrompt: typeof options.systemPrompt === "string" ? options.systemPrompt : "",
91
102
  tools: [...names.map((n) => ENGINE_TOOLS[n]), ...extra],
@@ -286,7 +286,11 @@ async function* run(prompt, o, signal, interrupted) {
286
286
  .filter((t) => typeof t === "string" && t.trim() !== "")
287
287
  .map((t) => ({ type: "text", text: t.slice(0, 20_000) }));
288
288
  };
289
- const ctx = { cwd: o.cwd, env: o.shellEnv, signal, reads: new Map(), groups: new Set() };
289
+ const ctx = { cwd: o.cwd, env: o.shellEnv, signal, reads: new Map(), groups: new Set(), sandbox: o.localSandbox };
290
+ // Inside the walls, what a command left running (a server in the
291
+ // background) holds the rules it started under: when a later launch finds
292
+ // them changed, it is ended before that launch goes ahead.
293
+ const unwatch = o.localSandbox?.onChange?.(() => killGroups(ctx));
290
294
  // An earlier conversation comes first (foldrun code's local turns carry
291
295
  // theirs, 19 Nov 2026); the prompt is always the newest user turn.
292
296
  if (o.history.length % 2 !== 0)
@@ -313,7 +317,7 @@ async function* run(prompt, o, signal, interrupted) {
313
317
  let mcp = null;
314
318
  try {
315
319
  if (Object.keys(o.mcpServers).length) {
316
- mcp = await connectMcp(o.mcpServers, { env: o.env, toolEnv: o.shellEnv, cwd: o.cwd, signal });
320
+ mcp = await connectMcp(o.mcpServers, { env: o.env, toolEnv: o.shellEnv, cwd: o.cwd, signal, sandbox: o.localSandbox });
317
321
  for (const t of mcp.tools) {
318
322
  if (byName.has(t.name))
319
323
  throw new Error(`the MCP tool ${t.name} has the name of a tool the step already has`);
@@ -612,6 +616,7 @@ async function* run(prompt, o, signal, interrupted) {
612
616
  // away — nothing a command started outlives the step, and no MCP server
613
617
  // it started either.
614
618
  killGroups(ctx);
619
+ unwatch?.();
615
620
  await mcp?.close();
616
621
  }
617
622
  }
@@ -44,6 +44,9 @@ export interface McpConnection {
44
44
  }[];
45
45
  close(): Promise<void>;
46
46
  }
47
+ import type { SandboxWalls } from "./engine-common.ts";
48
+ /** A program and its arguments as one shell line, each word quoted. */
49
+ export declare function shellLine(command: string, args: string[]): string;
47
50
  /** A call's result as the loop hands it on: its text and images in the
48
51
  * order the server gave them (a caption stays beside its picture), the text
49
52
  * cut to a size, marked an error when the server says it is one. */
@@ -59,5 +62,6 @@ export declare function connectMcp(servers: Record<string, McpSpec>, ctx: {
59
62
  toolEnv: Record<string, string | undefined>;
60
63
  cwd: string;
61
64
  signal: AbortSignal;
65
+ sandbox?: Pick<SandboxWalls, "launch" | "fresh" | "onChange"> | null;
62
66
  }): Promise<McpConnection>;
63
67
  export {};
@@ -67,7 +67,12 @@ export function checkMcpSpecs(servers, engine) {
67
67
  }
68
68
  return out;
69
69
  }
70
- function transportFor(s, env, cwd) {
70
+ import { LAUNCHER, killTree } from "./local-sandbox.js";
71
+ /** A program and its arguments as one shell line, each word quoted. */
72
+ export function shellLine(command, args) {
73
+ return [command, ...args].map((w) => `'${w.replaceAll("'", `'\\''`)}'`).join(" ");
74
+ }
75
+ function transportFor(s, env, cwd, wrapped) {
71
76
  if (s.type === "sdk") {
72
77
  const [client, server] = InMemoryTransport.createLinkedPair();
73
78
  return { client, server };
@@ -82,6 +87,15 @@ function transportFor(s, env, cwd) {
82
87
  for (const [k, v] of Object.entries(env))
83
88
  if (typeof v === "string")
84
89
  base[k] = v;
90
+ // Inside the walls (a person's machine), the server starts as the
91
+ // sandbox's wrapping of its command line, so it and what it starts
92
+ // stay inside them.
93
+ // Its variables, the spec's too, ride inside (launch); `env` here is
94
+ // the launcher's own few, so none of them touches the program that
95
+ // puts the walls up.
96
+ if (wrapped !== undefined) {
97
+ return { client: new StdioClientTransport({ command: LAUNCHER, args: ["-c", wrapped], env: base, cwd, stderr: "ignore" }) };
98
+ }
85
99
  return { client: new StdioClientTransport({ command: s.command, args: s.args ?? [], env: { ...base, ...(s.env ?? {}) }, cwd, stderr: "ignore" }) };
86
100
  }
87
101
  const url = new URL(s.url);
@@ -193,9 +207,45 @@ export async function connectMcp(servers, ctx) {
193
207
  const envTimeout = Number(ctx.env.MCP_TOOL_TIMEOUT);
194
208
  try {
195
209
  for (const [name, s] of Object.entries(servers)) {
196
- const t = transportFor(s, ctx.toolEnv, ctx.cwd);
210
+ let wrapped;
211
+ if (ctx.sandbox && s.type === "stdio") {
212
+ // The server's environment (the step's, then what the spec names)
213
+ // is set again inside; the launcher starts with the walls' own.
214
+ wrapped = await ctx.sandbox.launch(shellLine(s.command, s.args ?? []), { ...ctx.toolEnv, ...(s.env ?? {}) });
215
+ if (!wrapped?.line)
216
+ throw new Error(`MCP server ${name}: the sandbox gave no command line`);
217
+ // A long-lived server inside the walls must be stoppable when they
218
+ // change: without a token and a way to check it, it does not start.
219
+ if (!wrapped.token || typeof ctx.sandbox.fresh !== "function" || typeof ctx.sandbox.onChange !== "function")
220
+ throw new Error(`MCP server ${name}: this sandbox cannot tell a long-lived server when its rules change, so it is not started`);
221
+ }
222
+ else if (ctx.sandbox && (s.type === "http" || s.type === "sse")) {
223
+ // This process would make that connection itself, past the walls'
224
+ // proxy and its address checks: not offered inside the walls.
225
+ 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`);
226
+ }
227
+ const t = wrapped ? transportFor(s, wrapped.env, ctx.cwd, wrapped.line) : transportFor(s, ctx.toolEnv, ctx.cwd);
197
228
  const client = new Client({ name: "foldrun-engine", version: "1.0.0" });
198
229
  open.push({ client, transport: t.client, server: t.server });
230
+ const sandboxToken = wrapped?.token;
231
+ // Any launch that finds the protections changed stops this server at
232
+ // once, not only its own next call.
233
+ if (sandboxToken !== undefined && ctx.sandbox?.onChange) {
234
+ const transport = t.client;
235
+ const stop = ctx.sandbox.onChange(async (now) => {
236
+ if (now === sandboxToken)
237
+ return;
238
+ stop();
239
+ // Ended, with all it started, before the launch that saw the
240
+ // change goes ahead.
241
+ // The tree is read and ended while the server still holds it:
242
+ // closed first, its children would be orphaned out of reach.
243
+ const pid = transport.pid ?? null;
244
+ if (pid)
245
+ killTree(pid);
246
+ await client.close().catch(() => undefined);
247
+ });
248
+ }
199
249
  let listed;
200
250
  if (ctx.signal.aborted)
201
251
  throw new Error(`the MCP server ${name} did not start: connect: stopped`);
@@ -260,6 +310,16 @@ export async function connectMcp(servers, ctx) {
260
310
  // Run beside other reads only when the server says it changes nothing.
261
311
  readOnly: tool.annotations?.readOnlyHint === true,
262
312
  run: async (input, toolCtx) => {
313
+ // A server inside the walls holds the write rules it started
314
+ // under: once git's protections have changed it is stopped, and
315
+ // the call refused, rather than run with the old ones.
316
+ if (sandboxToken !== undefined && ctx.sandbox?.fresh && !ctx.sandbox.fresh(sandboxToken)) {
317
+ const pid = t.client.pid ?? null;
318
+ if (pid)
319
+ killTree(pid);
320
+ await client.close().catch(() => undefined);
321
+ 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 };
322
+ }
263
323
  const result = await client.callTool({ name: tool.name, arguments: input }, undefined, { signal: toolCtx.signal, timeout, maxTotalTimeout: timeout });
264
324
  return outcomeOf(result);
265
325
  },
@@ -11,6 +11,9 @@ export interface ToolContext {
11
11
  * left something in the background has returned, but what it left is
12
12
  * still the step's: the loop ends every group when the step ends. */
13
13
  groups: Set<number>;
14
+ /** On a person's machine, the walls (local-sandbox.ts): commands run
15
+ * through `wrap`; the file tools refuse what canRead / canWrite refuse. */
16
+ sandbox?: import("./engine-common.ts").SandboxWalls | null;
14
17
  }
15
18
  /** End everything the session's commands started and left running. */
16
19
  export declare function killGroups(ctx: ToolContext): void;
@@ -72,6 +75,10 @@ type MatchJob = {
72
75
  type MatchResult = {
73
76
  out: string[];
74
77
  total: number;
78
+ seen?: Record<string, {
79
+ id: string;
80
+ n: number;
81
+ }>;
75
82
  } | {
76
83
  timedOut: true;
77
84
  } | {