@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.
@@ -12,6 +12,9 @@ export declare function credentialLine(c: ModelCredential): {
12
12
  type: "info" | "error";
13
13
  text: string;
14
14
  };
15
+ /** Why a step or a call that names its own model endpoint (`provider:`)
16
+ * is refused where a platform admin turned own keys off (models.byok). */
17
+ export declare const OWN_KEYS_OFF = "this platform runs every model call on foldrun's models, so an agent or project cannot name its own model endpoint \u2014 remove `provider:` from the agent or AGENTS.md (a platform admin can allow own keys: setting models.byok)";
15
18
  /** The account vault names the account's own model key lives under. */
16
19
  export declare const ACCOUNT_MODEL_SECRETS: {
17
20
  readonly provider: "FOLDRUN_MODEL_PROVIDER";
@@ -63,6 +63,9 @@ export function credentialLine(c) {
63
63
  // /api/account/model, or `foldrun account model set`). A provider: block at any
64
64
  // level still wins; this is what a step falls to when none names one, before
65
65
  // the platform's own credential.
66
+ /** Why a step or a call that names its own model endpoint (`provider:`)
67
+ * is refused where a platform admin turned own keys off (models.byok). */
68
+ export const OWN_KEYS_OFF = "this platform runs every model call on foldrun's models, so an agent or project cannot name its own model endpoint — remove `provider:` from the agent or AGENTS.md (a platform admin can allow own keys: setting models.byok)";
66
69
  /** The account vault names the account's own model key lives under. */
67
70
  export const ACCOUNT_MODEL_SECRETS = {
68
71
  provider: "FOLDRUN_MODEL_PROVIDER",
@@ -9,7 +9,7 @@ import { accountDir, workspaceDir, parseProvider, providerEnvFor } from "./store
9
9
  import { readAgentsMd } from "./runner.js";
10
10
  import { getSecret } from "./secrets.js";
11
11
  import { platform, hostUrlProblem } from "./platform.js";
12
- import { accountModelBlock, isClaudeLoginToken } from "./model-credential.js";
12
+ import { accountModelBlock, isClaudeLoginToken, OWN_KEYS_OFF } from "./model-credential.js";
13
13
  import { providerPreset } from "./providers.js";
14
14
  import { startTranslator, translatorSpecFor } from "./translator.js";
15
15
  import { supplyProviderBlock } from "./model-supply.js";
@@ -32,8 +32,15 @@ export const NO_MODEL_KEY = "no model key: this account runs on its own API key,
32
32
  * it, so a judge or a draft works on any key a run works on (FOL-16).
33
33
  */
34
34
  export function accountModelEnv(tenant, workspace, platformEnv) {
35
- const written = readAgentsMd(workspaceDir(tenant, workspace))?.data?.provider ??
35
+ const writtenBlock = readAgentsMd(workspaceDir(tenant, workspace))?.data?.provider ??
36
36
  readAgentsMd(accountDir(tenant))?.data?.provider;
37
+ // Own keys as the platform admin allows them (models.byok), as a step
38
+ // takes them (runner.ts): off, a written block is refused and the stored
39
+ // key never read.
40
+ const ownKeys = platform.ownModelKeys?.(tenant) ?? true;
41
+ if (writtenBlock && !ownKeys)
42
+ throw new ModelKeyError(OWN_KEYS_OFF, 403);
43
+ const written = writtenBlock;
37
44
  // foldrun's models, the same rung a step takes (runner.ts agentContext):
38
45
  // after the written blocks, before the account's stored key; chosen but
39
46
  // refused fails here, never onto the stored key or the operator's.
@@ -60,7 +67,7 @@ export function accountModelEnv(tenant, workspace, platformEnv) {
60
67
  tenant,
61
68
  };
62
69
  }
63
- const raw = written ?? accountModelBlock((name) => getSecret(tenant, name)?.value ?? null);
70
+ const raw = written ?? (ownKeys ? accountModelBlock((name) => getSecret(tenant, name)?.value ?? null) : undefined);
64
71
  const spec = parseProvider(raw);
65
72
  if (!spec?.baseUrl) {
66
73
  if (!platform.platformKeyAllowed(tenant))
@@ -159,6 +159,13 @@ export interface PlatformHooks {
159
159
  * operator's accounts do so; every customer brings their own API key.
160
160
  * Default: yes — a laptop or a self-hosted install is its own operator. */
161
161
  platformKeyAllowed(tenant: string): boolean;
162
+ /** May this account's steps run on a model key or endpoint of its own —
163
+ * the account's stored key (Settings → Models) or a `provider:` block in
164
+ * its files (BYOK)? A platform admin decides, for the whole install
165
+ * (setting models.byok, 22 Nov 2026: off unless turned on). No: a stored
166
+ * key is never used, and a step whose files name a provider: is refused
167
+ * before it starts. Absent: yes — a laptop runs on what it is given. */
168
+ ownModelKeys?(tenant: string): boolean;
162
169
  /** foldrun's models (3 Nov 2026): whether this account chose to run on
163
170
  * the platform's own key for a provider, and whether it can now. Asked
164
171
  * only where no provider: block of the account's own says otherwise.
@@ -18,6 +18,7 @@
18
18
  // It reads the same provider block a run reads, resolved the same way, so a
19
19
  // pass here means a run would reach the same place with the same key.
20
20
  import { accountModelBlock } from "./model-credential.js";
21
+ import { platform } from "./platform.js";
21
22
  import fs from "node:fs";
22
23
  import path from "node:path";
23
24
  import { configMatter } from "./matter.js";
@@ -187,6 +188,10 @@ function frontmatterOf(file) {
187
188
  export function providersInUse(tenant) {
188
189
  const out = [];
189
190
  const seen = new Set();
191
+ // Own keys off on this platform (models.byok): nothing of the account's
192
+ // is used, so nothing is probed (or spent) on its behalf.
193
+ if (!(platform.ownModelKeys?.(tenant) ?? true))
194
+ return out;
190
195
  const add = (raw, workspace, declaredIn) => {
191
196
  const spec = parseProvider(raw);
192
197
  if (!spec || !spec.baseUrl)
@@ -22,7 +22,7 @@ import { eventUrl } from "./webhook.js";
22
22
  import { runStepInContainer, resolveResources, memoryGiB, heldCores, killRunSandboxes, classDisk } from "./run-container.js";
23
23
  import { readResources, hasOverride, anyMemoryMi } from "./resources.js";
24
24
  import { hostSafeEnv, platformApiUrl } from "./host-env.js";
25
- import { resolveModelCredential, credentialLine, accountModelBlock, isClaudeLoginToken, isModelEnvName, DECLARED_ENV_PREFIX } from "./model-credential.js";
25
+ import { resolveModelCredential, credentialLine, accountModelBlock, isClaudeLoginToken, isModelEnvName, DECLARED_ENV_PREFIX, OWN_KEYS_OFF } from "./model-credential.js";
26
26
  import { parseJudge } from "./judge-verdict.js";
27
27
  import { validateSchema, describeSchemaErrors, looksLikeSchema } from "./json-schema.js";
28
28
  import { EGRESS_ENV, MODEL_KEY_NAME, addGrant, grantModelKey, hostOf, placeholderNames, proxyModelEnv, unsubstitute } from "./egress.js";
@@ -1303,18 +1303,29 @@ grantsOnly = false) {
1303
1303
  // agent's own block wins over the workspace's, like everything else here.
1304
1304
  // Then the account's own model key (Settings → Models), when it set one:
1305
1305
  // an account that brings its key need not write a block anywhere.
1306
- const fileBlock = front.provider ?? workspaceFrontmatter(agentDir, tenant).provider;
1306
+ const writtenBlock = front.provider ?? workspaceFrontmatter(agentDir, tenant).provider;
1307
+ // Own keys (BYOK) as the platform admin allows them (models.byok): off,
1308
+ // a written provider: block refuses the step and a stored key is never
1309
+ // read — every call goes through foldrun's models.
1310
+ const ownKeys = platform.ownModelKeys?.(tenant) ?? true;
1311
+ const fileBlock = ownKeys ? writtenBlock : undefined;
1307
1312
  // foldrun's models (3 Nov 2026): an account that chose the platform's key
1308
1313
  // for a provider runs on it here, between its written blocks (which still
1309
1314
  // win) and its stored key. Chosen but not to be had now — refused, and
1310
1315
  // the step fails with why (runStep); it never falls to the stored key.
1311
- const supply = fileBlock ? { kind: "none" } : platform.modelSupply?.(tenant) ?? { kind: "none" };
1316
+ const supply = fileBlock
1317
+ ? { kind: "none" }
1318
+ : writtenBlock
1319
+ ? { kind: "refused", reason: OWN_KEYS_OFF }
1320
+ : platform.modelSupply?.(tenant) ?? { kind: "none" };
1312
1321
  const providerBlock = fileBlock ??
1313
1322
  (supply.kind === "foldrun"
1314
1323
  ? supplyProviderBlock(supply.provider, supply.tiers, supply.via)
1315
1324
  : supply.kind === "refused"
1316
1325
  ? undefined
1317
- : accountModelBlock((name) => getSecret(tenant, name)?.value ?? null));
1326
+ : ownKeys
1327
+ ? accountModelBlock((name) => getSecret(tenant, name)?.value ?? null)
1328
+ : undefined);
1318
1329
  let providerEnv = {};
1319
1330
  let providerLabel = null;
1320
1331
  // Secret values pulled into the provider block, name → value. Kept apart
@@ -2458,7 +2469,7 @@ conversation) {
2458
2469
  // Chosen, but not to be had now: failed with why, before a sandbox —
2459
2470
  // never onto the account's stored key or the operator's.
2460
2471
  if (supply.kind === "refused") {
2461
- push("error", `foldrun's models: ${supply.reason} — or switch this account back to its own key (Settings → Models, \`foldrun account model use own\`)`);
2472
+ push("error", platform.ownModelKeys?.(tenant) ?? true ? `foldrun's models: ${supply.reason} — or switch this account back to its own key (Settings → Models, \`foldrun account model use own\`)` : `foldrun's models: ${supply.reason}`);
2462
2473
  step.status = "failed";
2463
2474
  save();
2464
2475
  return;
@@ -59,6 +59,11 @@ export interface ScanOptions {
59
59
  model: string;
60
60
  on: string;
61
61
  } | null;
62
+ /** May this account's files name their own model endpoint (`provider:`)?
63
+ * False where a platform admin turned own keys off (models.byok): each
64
+ * one is config/own-model-key, an error, so the deploy is refused.
65
+ * Absent (the CLI offline, a laptop): yes. */
66
+ ownModelKeys?: boolean;
62
67
  }
63
68
  export declare const OWASP_URL = "https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026";
64
69
  export declare const SCAN_RULES: readonly ScanRule[];
package/dist/src/scan.js CHANGED
@@ -260,6 +260,15 @@ export const SCAN_RULES = [
260
260
  "The step still runs, at the nearest level the model has, and the step's log says so. Write the level it has, or choose " +
261
261
  "a provider whose model has the one you want (Settings → Models).",
262
262
  },
263
+ {
264
+ id: "config/own-model-key",
265
+ category: "config",
266
+ level: "error",
267
+ title: "A model endpoint of its own, where this platform runs every call on its own models",
268
+ help: "This platform's admin turned own model keys off (setting models.byok), so every model call goes through foldrun's models. " +
269
+ "An agent's or a project's `provider:` block names an endpoint and key of its own, which would run unmetered. Remove the " +
270
+ "block: the agent then runs on the account's choice in Settings → Models.",
271
+ },
263
272
  {
264
273
  id: "config/output-fitted",
265
274
  category: "config",
@@ -1236,6 +1245,19 @@ export function scanFiles(files, options = {}) {
1236
1245
  // A workspace that names its own provider: does not run on the account's
1237
1246
  // choice, so the account's models say nothing about its efforts.
1238
1247
  const ownWorkspaceProvider = Boolean(workspaceMd && frontOf(workspaceMd.content, "AGENTS.md")?.provider);
1248
+ // Own keys off on this platform (models.byok): every provider: is refused.
1249
+ if (options.ownModelKeys === false) {
1250
+ const lineOf = (content) => {
1251
+ const i = content.split("\n").findIndex((l) => /^provider\s*:/.test(l));
1252
+ return i >= 0 ? i + 1 : 1;
1253
+ };
1254
+ const say = (file, content) => push("config/own-model-key", file, lineOf(content), `config/own-model-key ${file}`, "provider: names a model endpoint of its own, and this platform runs every model call on its own models (own keys are off) — remove it; the agent runs on the account's choice in Settings → Models.");
1255
+ for (const a of agents)
1256
+ if (a.data.provider)
1257
+ say(a.file, files.find((f) => f.path === a.file)?.content ?? "");
1258
+ if (workspaceMd && ownWorkspaceProvider)
1259
+ say(workspaceMd.path, workspaceMd.content);
1260
+ }
1239
1261
  if (options.effortRunsAs && !ownWorkspaceProvider)
1240
1262
  scanEfforts(agents, flows, options.effortRunsAs, push);
1241
1263
  if (options.outputCeiling && !ownWorkspaceProvider)
@@ -504,7 +504,7 @@ secrets: [CRM_TOKEN] # keys the agent uses itself; a tool's own come with
504
504
  limits: {web.search: 40, crm: 20, calls: 300} # per step; a call past a limit is refused, never run
505
505
  network: [api.example.com] # sites its sandbox may reach, added to the trusted list; open | trusted | none
506
506
  timezone: Australia/Sydney # the calendar it works to — IANA name or UTC+10
507
- provider: {} # BYOK for this agent; account-wide: \`foldrun account model set\`
507
+ provider: {} # BYOK for this agent, where the platform allows own keys (models.byok); account-wide: \`foldrun account model set\`
508
508
  permissionMode: plan # plan first, act once approved
509
509
  runtime: # only if scripts need packages
510
510
  packages: [requests]
@@ -31,7 +31,11 @@ export function checkOptions(tenant, workspace) {
31
31
  // AGENTS.md, or the older project.md, as the runner reads it (Codex review).
32
32
  const accountKeys = readAgentsMdKeys(accountDir(tenant));
33
33
  const accountNetwork = accountKeys.network;
34
- return { outwardTools, accountNetwork, ...effortCheck(tenant, accountKeys.provider) };
34
+ // Own keys as the platform admin set them (models.byok): off, a provider:
35
+ // in these files is an error, so the deploy, a save and the Checks page
36
+ // all refuse it as the runner would.
37
+ const ownModelKeys = platform.ownModelKeys?.(tenant) ?? true;
38
+ return { outwardTools, accountNetwork, ...effortCheck(tenant, accountKeys.provider), ...(ownModelKeys ? {} : { ownModelKeys: false }) };
35
39
  }
36
40
  /**
37
41
  * What an effort level runs at on the account's choice, for
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "24.11.0",
3
+ "version": "24.13.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
  }
package/src/deploy.ts CHANGED
@@ -57,6 +57,7 @@ import { languageProblem } from "./language.ts";
57
57
  import { localeProblems } from "./locale.ts";
58
58
  import { entriesNoFollow } from "./paths.ts";
59
59
  import { filterIgnored, findingFingerprint, ruleForWhere, scanFiles, scanRule, STRICT_FRONTMATTER_PATH, type ScanFinding, type ScanOptions } from "./scan.ts";
60
+ import { platform } from "./platform.ts";
60
61
 
61
62
  /** Directories a deploy never reads out of a source tree. */
62
63
  // `.cache` is what a run's tools leave in an agent's folder (HOME is that
@@ -372,6 +373,17 @@ function blockersFor(tenant: string, given: DeployFile[]): DeployIssue[] {
372
373
  return deployBlockers(files, mode, { accountNetwork: account.network, outwardTools });
373
374
  }
374
375
 
376
+ /** Own keys off on this platform (models.byok, 22 Nov 2026): every
377
+ * `provider:` in the files is a refusal — nothing deploys that would run on
378
+ * an endpoint the platform does not meter. Nothing where they are allowed. */
379
+ export function ownKeyBlockers(tenant: string, files: DeployFile[]): DeployIssue[] {
380
+ if (platform.ownModelKeys?.(tenant) ?? true) return [];
381
+ return scanFiles(files, { only: ["config/own-model-key"], ownModelKeys: false }).map((f) => ({
382
+ where: `${f.file}${f.line ? `:${f.line}` : ""}`,
383
+ message: `${f.message} [${f.rule}]`,
384
+ }));
385
+ }
386
+
375
387
  /** The findings `mode` turns into refusals, as deploy issues. */
376
388
  export function deployBlockers(files: DeployFile[], mode: DeployBlockMode, options: ScanOptions = {}): DeployIssue[] {
377
389
  if (mode === "none") return [];
@@ -783,7 +795,7 @@ export function planDeploy(tenant: string, workspace: string, files: DeployFile[
783
795
  // deploy_block: (FOL-58) turns the scanner's findings into refusals —
784
796
  // scanned with what the Checks page passes too: the account's network:
785
797
  // and the library's outward tools (Codex review).
786
- issues: [...deployIssues(files), ...blockersFor(tenant, files)],
798
+ issues: [...deployIssues(files), ...blockersFor(tenant, files), ...ownKeyBlockers(tenant, files)],
787
799
  warnings: deployWarnings(files),
788
800
  blockedBy: runsInFlight(tenant, workspace),
789
801
  };
@@ -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
  },