@foldrun/core 0.6.0 → 0.7.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.
Files changed (80) hide show
  1. package/dist/index.d.ts +3 -0
  2. package/dist/index.js +3 -0
  3. package/dist/src/agent-import.d.ts +21 -0
  4. package/dist/src/agent-import.js +116 -0
  5. package/dist/src/api-tools.js +14 -2
  6. package/dist/src/approvals.d.ts +8 -1
  7. package/dist/src/approvals.js +10 -5
  8. package/dist/src/completions.js +1 -0
  9. package/dist/src/confine.d.ts +1 -0
  10. package/dist/src/confine.js +33 -4
  11. package/dist/src/deploy.d.ts +9 -0
  12. package/dist/src/deploy.js +31 -3
  13. package/dist/src/evals.js +22 -5
  14. package/dist/src/host-env.d.ts +14 -0
  15. package/dist/src/host-env.js +26 -0
  16. package/dist/src/install-helper.d.ts +17 -0
  17. package/dist/src/install-helper.js +134 -0
  18. package/dist/src/install-tool.d.ts +128 -0
  19. package/dist/src/install-tool.js +133 -0
  20. package/dist/src/model-credential.d.ts +16 -0
  21. package/dist/src/model-credential.js +40 -0
  22. package/dist/src/model-env.d.ts +17 -0
  23. package/dist/src/model-env.js +57 -0
  24. package/dist/src/package.d.ts +67 -0
  25. package/dist/src/package.js +594 -0
  26. package/dist/src/platform.d.ts +5 -0
  27. package/dist/src/platform.js +1 -0
  28. package/dist/src/provider-health.js +3 -0
  29. package/dist/src/run-container.d.ts +5 -0
  30. package/dist/src/run-container.js +66 -13
  31. package/dist/src/runner.d.ts +204 -0
  32. package/dist/src/runner.js +257 -36
  33. package/dist/src/runtime.d.ts +77 -0
  34. package/dist/src/runtime.js +230 -5
  35. package/dist/src/script-tools.d.ts +2 -0
  36. package/dist/src/script-tools.js +3 -1
  37. package/dist/src/secrets.d.ts +5 -0
  38. package/dist/src/secrets.js +37 -6
  39. package/dist/src/starter.d.ts +12 -0
  40. package/dist/src/starter.js +36 -4
  41. package/dist/src/step-exec.d.ts +11 -2
  42. package/dist/src/step-exec.js +52 -5
  43. package/dist/src/storage.d.ts +7 -1
  44. package/dist/src/storage.js +14 -1
  45. package/dist/src/store.d.ts +20 -0
  46. package/dist/src/store.js +89 -8
  47. package/dist/src/tool-names.d.ts +3 -1
  48. package/dist/src/tool-names.js +4 -2
  49. package/dist/src/tool-test.js +8 -1
  50. package/dist/src/zip.d.ts +17 -0
  51. package/dist/src/zip.js +184 -0
  52. package/index.ts +3 -0
  53. package/package.json +1 -1
  54. package/src/agent-import.ts +154 -0
  55. package/src/api-tools.ts +16 -1
  56. package/src/approvals.ts +10 -3
  57. package/src/completions.ts +1 -0
  58. package/src/confine.ts +36 -5
  59. package/src/deploy.ts +28 -3
  60. package/src/evals.ts +21 -3
  61. package/src/host-env.ts +27 -0
  62. package/src/install-helper.ts +143 -0
  63. package/src/install-tool.ts +154 -0
  64. package/src/model-credential.ts +41 -0
  65. package/src/model-env.ts +66 -0
  66. package/src/package.ts +664 -0
  67. package/src/platform.ts +6 -0
  68. package/src/provider-health.ts +3 -0
  69. package/src/run-container.ts +65 -12
  70. package/src/runner.ts +264 -36
  71. package/src/runtime.ts +235 -5
  72. package/src/script-tools.ts +5 -1
  73. package/src/secrets.ts +34 -6
  74. package/src/starter.ts +42 -4
  75. package/src/step-exec.ts +56 -8
  76. package/src/storage.ts +13 -0
  77. package/src/store.ts +85 -7
  78. package/src/tool-names.ts +4 -2
  79. package/src/tool-test.ts +8 -1
  80. package/src/zip.ts +189 -0
@@ -3,6 +3,7 @@
3
3
  // fail without failing the flow. A direct agent run is a one-step ad-hoc
4
4
  // flow, so there is a single execution path.
5
5
  import fs from "node:fs";
6
+ import os from "node:os";
6
7
  import path from "node:path";
7
8
  import matter from "gray-matter";
8
9
  import { knownPrice, executeStep, extractJson, stepCeiling, stepCeilingFor } from "./step-exec.js";
@@ -11,8 +12,8 @@ import { resolveAgentPath } from "./confine.js";
11
12
  import { browserPodLine, podLossDecision, RERAN_ON_FULL } from "./browser-pod.js";
12
13
  import { eventUrl } from "./webhook.js";
13
14
  import { runStepInContainer, sizeLimits, killRunSandboxes } from "./run-container.js";
14
- import { hostSafeEnv } from "./host-env.js";
15
- import { resolveModelCredential, credentialLine } from "./model-credential.js";
15
+ import { hostSafeEnv, platformApiUrl } from "./host-env.js";
16
+ import { resolveModelCredential, credentialLine, accountModelBlock, isClaudeLoginToken } from "./model-credential.js";
16
17
  import { validateSchema, describeSchemaErrors, looksLikeSchema } from "./json-schema.js";
17
18
  import { EGRESS_ENV, MODEL_KEY_NAME, addGrant, hostOf, placeholderNames, proxyModelEnv, unsubstitute } from "./egress.js";
18
19
  import { explainRefusal, isRefusalStatus, refusalFromLine, supplyNote } from "./refusal.js";
@@ -42,8 +43,10 @@ import { startTranslator, translatorSpecFor } from "./translator.js";
42
43
  import { providerPreset } from "./providers.js";
43
44
  import { buildScriptTools, parseScripts } from "./script-tools.js";
44
45
  import { libraryDir, libraryTools, libraryMemoryIndex } from "./library.js";
45
- import { fingerprint, mergeRuntimes, parseRuntime, prepareRuntime } from "./runtime.js";
46
- import { materializeFiles, harvestFiles } from "./storage.js";
46
+ import { fingerprint, mergeRuntimes, parseRuntime, prepareRuntime, stepInstallEnv } from "./runtime.js";
47
+ import { buildInstallTool, INSTALL_TOOL } from "./install-tool.js";
48
+ import { dataRoot } from "./paths.js";
49
+ import { materializeFiles, harvestFiles, storageBaseline } from "./storage.js";
47
50
  import { chooseExecutor, ensureImage } from "./container.js";
48
51
  import { stampBundle } from "./okf.js";
49
52
  import { readBrowseSettings, readSearchSettings, resolveSearch, searchSettingsEnv, webConfig, browseSessionProblems } from "./providers.js";
@@ -614,7 +617,7 @@ export function resolveDocLinks(text, workspaceRoot) {
614
617
  return hit ? `\`${hit}\`` : whole;
615
618
  });
616
619
  }
617
- function agentContext(agentDir, tenant, tags = [],
620
+ export function agentContext(agentDir, tenant, tags = [],
618
621
  /** Who is running, so scripts can stamp what they write with its provenance. */
619
622
  identity = {},
620
623
  /** The flow's own `timezone:`, when this step belongs to one. Between the
@@ -1000,7 +1003,10 @@ grantsOnly = false) {
1000
1003
  //
1001
1004
  // The URL sits in git; the token is a ${SECRET} resolved server-side. An
1002
1005
  // agent's own block wins over the workspace's, like everything else here.
1003
- const providerBlock = front.provider ?? workspaceFrontmatter(agentDir, tenant).provider;
1006
+ // Then the account's own model key (Settings → Model), when it set one:
1007
+ // an account that brings its key need not write a block anywhere.
1008
+ const fileBlock = front.provider ?? workspaceFrontmatter(agentDir, tenant).provider;
1009
+ const providerBlock = fileBlock ?? accountModelBlock((name) => getSecret(tenant, name)?.value ?? null);
1004
1010
  let providerEnv = {};
1005
1011
  let providerLabel = null;
1006
1012
  // Secret values pulled into the provider block, name → value. Kept apart
@@ -1151,6 +1157,9 @@ grantsOnly = false) {
1151
1157
  // one — the `websearch` library tool reads it. Not a secret; rides with
1152
1158
  // the clock so it reaches scripts, the sandbox and verify alike.
1153
1159
  ...(process.env.FOLDRUN_SEARCH_URL ? { FOLDRUN_SEARCH_URL: process.env.FOLDRUN_SEARCH_URL } : {}),
1160
+ // Where this install's own API answers (host-env.ts platformApiUrl), so a
1161
+ // script calls `$FOLDRUN_API_URL/workspaces/…` instead of naming a host.
1162
+ ...(platformApiUrl() ? { FOLDRUN_API_URL: platformApiUrl() } : {}),
1154
1163
  // Whose index our web search asks when the agent named a search API.
1155
1164
  // Unset means the account's own engine. The name, never the key.
1156
1165
  ...(searchChoice.shape === "direct" && searchChoice.provider
@@ -1228,7 +1237,18 @@ grantsOnly = false) {
1228
1237
  parts.push(`# Clock\n\nToday is ${clockEnv.FOLDRUN_DATE} (${timezone}). Use this date for anything you ` +
1229
1238
  `write or check — it is the workspace's calendar, not the container's clock.`);
1230
1239
  if (scriptTools.promptLines.length) {
1231
- parts.push(`# Tools from scripts\n\nCall these directly — they run workspace scripts for you:\n\n${scriptTools.promptLines.join("\n")}`);
1240
+ parts.push(`# Tools from scripts\n\nCall these directly — they run workspace scripts for you. Each is called by its full name, ` +
1241
+ `\`mcp__foldrun_scripts__<name>\` (\`web\` is \`mcp__foldrun_scripts__web\`); a bare name is refused:\n\n${scriptTools.promptLines.join("\n")}`);
1242
+ }
1243
+ // The web tool's own description lists every action, so an agent whose
1244
+ // search or fetch a model provider answers called web action=search,
1245
+ // was refused, and only then used WebSearch — eight refusals in one
1246
+ // reddit-desk validator step on 6 Oct 2026. Say it before the first call.
1247
+ if (builtins.length) {
1248
+ const named = builtins.map((b) => b.split("="));
1249
+ parts.push(`# Web search and fetch on this run\n\n` +
1250
+ named.map(([action, tool]) => `- To ${action}, call **${tool}** directly. \`web\` with action=${action} is switched off on this run.`).join("\n") +
1251
+ `\n\nThe web tool's other actions work as usual.`);
1232
1252
  }
1233
1253
  if (declared.length) {
1234
1254
  parts.push(`# Secrets\n\nAvailable to your scripts as environment variables: ${declared.join(", ")}. ` +
@@ -1237,7 +1257,13 @@ grantsOnly = false) {
1237
1257
  parts.push("Write deliverables for people to workspace/storage/ (kept and downloadable); write working text for later steps to outputs/; " +
1238
1258
  "what the next run needs goes to workspace/state/. Paths are relative to your agent directory, or start with workspace/ " +
1239
1259
  "for the workspace root (workspace/storage/ and the older ../../storage/ are the same place). There is no /tmp for you: a " +
1240
- "directory a tool made outside the workspace, such as a checkout, is reached only through that tool.");
1260
+ "directory a tool made outside the workspace, such as a checkout, is reached only through that tool. " +
1261
+ // 45 refusals in 34 runs (6–7 Oct 2026), nearly all an agent rewriting
1262
+ // a plan or draft an earlier run left: the Write tool refuses a file
1263
+ // that exists and has not been Read in this step, before any hook of
1264
+ // ours can see the call. Said once here instead of learned per step.
1265
+ "To replace a file that already exists, Read it first — Write refuses a file you have not Read in this step (a new file needs no Read). " +
1266
+ "Built-in tools are capitalised: Read, Write, Edit, Glob, Grep, Bash.");
1241
1267
  // The run's one-line summary is the first meaningful line of the last step
1242
1268
  // that produced a result — read, never declared (runSummary in store.ts).
1243
1269
  // That convention was load-bearing and unstated: it decides the runs-list
@@ -1299,6 +1325,13 @@ grantsOnly = false) {
1299
1325
  // names it (FOLDRUN_WEB_BUILTIN) rather than asking our engine.
1300
1326
  if (toolName === "web" && !ref.linked) {
1301
1327
  allowed.push(...providerWebTools);
1328
+ // web writes what it found to files and says "Read that file" — a
1329
+ // screenshot, a crawl, a page saved whole. An agent granted web alone
1330
+ // was told to Read and refused it (blog-desk claim-checker, 7 Oct
1331
+ // 2026: "Read is disabled for this session"). Reading is confined to
1332
+ // the workspace like every file tool; disallowedTools still removes it.
1333
+ if (!allowed.includes("Read"))
1334
+ allowed.push("Read");
1302
1335
  continue;
1303
1336
  }
1304
1337
  // Resolution order: built-in group, exact SDK name, then your own tools.
@@ -1328,6 +1361,9 @@ grantsOnly = false) {
1328
1361
  if (available[toolName])
1329
1362
  shadowed.push(toolName);
1330
1363
  }
1364
+ else if (toolName === "install") {
1365
+ // Granted to every agent anyway (below); naming it is harmless.
1366
+ }
1331
1367
  else if (BUILTIN_TOOLS.has(toolName)) {
1332
1368
  allowed.push(toolName);
1333
1369
  if (available[toolName])
@@ -1391,6 +1427,10 @@ grantsOnly = false) {
1391
1427
  // what it exposes, which is the unit a person actually reasons about anyway.
1392
1428
  for (const name of mcpNames)
1393
1429
  allowed.push(`mcp__${name}`, `mcp__${name}__*`);
1430
+ // install — every agent may install what it finds it needs mid-step (apt,
1431
+ // pip, npm), declared or not (install-tool.ts). Granted by default; taken
1432
+ // away by disallowedTools: [install], and absent in plan mode (read-only).
1433
+ allowed.push(INSTALL_TOOL);
1394
1434
  // Claude Code's spellings, so an agent written for it mostly runs here.
1395
1435
  // `permissionMode: plan` is its read-only mode; ours is the `read` group.
1396
1436
  if (front.permissionMode === "plan") {
@@ -1398,6 +1438,8 @@ grantsOnly = false) {
1398
1438
  allowed.push(...TOOL_MAP.read, ...apiTools.toolNames, ...scriptTools.toolNames);
1399
1439
  }
1400
1440
  const denied = refNames(front.disallowedTools);
1441
+ if (denied.includes("install"))
1442
+ denied.push(INSTALL_TOOL);
1401
1443
  const finalAllowed = allowed.filter((t) => !denied.includes(t));
1402
1444
  return {
1403
1445
  front,
@@ -1600,6 +1642,40 @@ async function terminalAsk(question, options) {
1600
1642
  rl.close();
1601
1643
  }
1602
1644
  }
1645
+ /**
1646
+ * What the person at the gate said, framed for the step's prompt — or "".
1647
+ *
1648
+ * The note is the freshest instruction the step has — later than the flow
1649
+ * file, aimed at this exact run. When the gate asked a question (ask:), the
1650
+ * note IS the answer and is framed as one.
1651
+ *
1652
+ * Both halves go through resolveDocLinks for the same reason the
1653
+ * instruction does: this is authored text on its way to becoming a prompt,
1654
+ * and the rule is that ALL of it expands. A person answering "which list?"
1655
+ * with [[dead-ends]] was sending the model two literal brackets — the one
1656
+ * reference syntax the workspace teaches, and the one place it silently did
1657
+ * nothing. The previous step's results are NOT resolved, deliberately: that
1658
+ * is model output, and a model that happens to emit [[brackets]] must not
1659
+ * thereby name a file.
1660
+ *
1661
+ * An ask: gate approved with no note still says so. It used to add nothing,
1662
+ * so the step never learned its question had been answered: gbp-desk's
1663
+ * rivals sender, told "a plain approval means all offices", saw no answer
1664
+ * at all and stopped BLOCKED (run-muu6r18y-417e, 2026-10-05).
1665
+ */
1666
+ export function operatorBlock(step, workspaceRoot) {
1667
+ const ask = step.ask ? resolveDocLinks(step.ask, workspaceRoot) : "";
1668
+ if (step.approvalNote) {
1669
+ const note = resolveDocLinks(step.approvalNote, workspaceRoot);
1670
+ return step.ask
1671
+ ? `\n\n<operator_answer>\nThis step asked a human: ${ask}\nTheir answer:\n${note}\n</operator_answer>`
1672
+ : `\n\n<operator_guidance>\nThe human who approved this step added:\n${note}\n</operator_guidance>`;
1673
+ }
1674
+ if (step.ask && step.approvedAt) {
1675
+ return `\n\n<operator_answer>\nThis step asked a human: ${ask}\nTheir answer: they approved it with no note — a plain yes.\n</operator_answer>`;
1676
+ }
1677
+ return "";
1678
+ }
1603
1679
  async function runStep(agentDir, tenant, step, context, save, modelOverride, tags = [], effortOverride, runId,
1604
1680
  /** What the previous group returned as DATA (an `output: json` step's
1605
1681
  * value), beside the prose in `context`. Undefined when nothing did. */
@@ -1641,6 +1717,7 @@ stepIndex) {
1641
1717
  // cover a script's own stdout.
1642
1718
  let redactions = [];
1643
1719
  let fileDir = null;
1720
+ let installDir = null;
1644
1721
  let disposeRuntime;
1645
1722
  // Can this step's tools act outside the workspace? Set once its context is
1646
1723
  // read; the verdict at the end of this function reads it.
@@ -1784,6 +1861,26 @@ stepIndex) {
1784
1861
  const line = credentialLine(credential);
1785
1862
  push(line.type, line.text);
1786
1863
  }
1864
+ // A hosted platform runs only its operator's accounts on its own model
1865
+ // credential; every other account brings its own API key. Refused here,
1866
+ // before a sandbox is rented, with what to do about it — not run on the
1867
+ // operator's key, and not failed later by a provider.
1868
+ if (!platform.platformKeyAllowed(tenant)) {
1869
+ const own = Object.values(providerSecrets).concat(Object.values(providerEnv));
1870
+ if (!providerLabel) {
1871
+ push("error", `no model key: this account runs on its own API key, and none is set. Add one in Settings → Model ` +
1872
+ `(or \`foldrun model set <provider> --key …\`), or write a provider: block in AGENTS.md`);
1873
+ step.status = "failed";
1874
+ save();
1875
+ return;
1876
+ }
1877
+ if (own.some((v) => isClaudeLoginToken(v))) {
1878
+ push("error", "model key: a Claude login token (sk-ant-oat…) cannot be used here — use an API key from your provider");
1879
+ step.status = "failed";
1880
+ save();
1881
+ return;
1882
+ }
1883
+ }
1787
1884
  for (const w of providerWarnings)
1788
1885
  push("error", w);
1789
1886
  // A level that wrote a language nobody can read was skipped, not obeyed.
@@ -1958,28 +2055,7 @@ stepIndex) {
1958
2055
  // happening to contain brackets.
1959
2056
  prompt += `\n\n<event>\nThis step waited for an external event. What arrived:\n${step.eventPayload}\n</event>`;
1960
2057
  }
1961
- if (step.approvalNote) {
1962
- // The person at the gate said something while letting the run through.
1963
- // That is the freshest instruction the step has — later than the flow
1964
- // file, aimed at this exact run. When the gate asked a question
1965
- // (ask:), the note IS the answer and is framed as one.
1966
- //
1967
- // Both halves go through resolveDocLinks for the same reason the
1968
- // instruction above does: this is authored text on its way to becoming
1969
- // a prompt, and the rule is that ALL of it expands. A person answering
1970
- // "which list?" with [[dead-ends]] was sending the model two literal
1971
- // brackets — the one reference syntax the workspace teaches, and the
1972
- // one place it silently did nothing.
1973
- //
1974
- // What is NOT resolved, deliberately: the previous step's results
1975
- // above. That is model output, not something a person wrote, and a
1976
- // model that happens to emit [[brackets]] must not thereby name a file.
1977
- const ask = step.ask ? resolveDocLinks(step.ask, workspaceRoot) : "";
1978
- const note = resolveDocLinks(step.approvalNote, workspaceRoot);
1979
- prompt += step.ask
1980
- ? `\n\n<operator_answer>\nThis step asked a human: ${ask}\nTheir answer:\n${note}\n</operator_answer>`
1981
- : `\n\n<operator_guidance>\nThe human who approved this step added:\n${note}\n</operator_guidance>`;
1982
- }
2058
+ prompt += operatorBlock(step, workspaceRoot);
1983
2059
  if (step.delegate?.length) {
1984
2060
  // The chooser's contract. The allowed set comes from the flow file;
1985
2061
  // the runner parses exactly this shape back out of the result, so the
@@ -2023,6 +2099,9 @@ stepIndex) {
2023
2099
  // watched on both paths, because a refusal reads the same from a pod
2024
2100
  // and from this process.
2025
2101
  let lastRefusal = "";
2102
+ // The step's model connection was cut (isModelConnectionLost): the
2103
+ // platform's side going away under the step, not the step failing.
2104
+ let lastDrop = "";
2026
2105
  // And WHY it refused, in words, when anything on the way saw the
2027
2106
  // headers that say so: the translator here, the egress proxy over
2028
2107
  // there. Kept apart from `lastRefusal` — that one decides whether to
@@ -2031,6 +2110,8 @@ stepIndex) {
2031
2110
  const pushWatching = (type, text, extra) => {
2032
2111
  if (type === "error" && isProviderRefusal(text))
2033
2112
  lastRefusal = text;
2113
+ if (type === "error" && isModelConnectionLost(text))
2114
+ lastDrop = text;
2034
2115
  const why = refusalFromLine(text);
2035
2116
  if (why)
2036
2117
  refusalWhy = why;
@@ -2317,6 +2398,7 @@ stepIndex) {
2317
2398
  lastArgs = a;
2318
2399
  return runIsolated(a);
2319
2400
  };
2401
+ let attemptFrom = step.events.length;
2320
2402
  let outcome = await runTracked(firstArgs);
2321
2403
  step.sandbox = null; // whatever happens next starts its own
2322
2404
  // A 401 from a token that rotated mid-step is not a broken key: the
@@ -2355,6 +2437,48 @@ stepIndex) {
2355
2437
  outcome = await runTracked(again);
2356
2438
  outcome = withEarlierTiming(outcome, previous);
2357
2439
  }
2440
+ // The model connection was cut under the step — the egress proxy or the
2441
+ // worker went away (6 Oct 2026: a worker restarted every 4.5 minutes and
2442
+ // every desk running failed on "Connection refused"). That is the
2443
+ // platform's fault, so the step runs again, whatever its `retry:` —
2444
+ // unless it can act outside the workspace and its tools already ran:
2445
+ // the post may be up, and a second attempt would post it again.
2446
+ for (let n = 1; n <= DROP_RETRIES && outcome.status === "failed" && lastDrop; n++) {
2447
+ if (!dropRetrySafe(canActOutward, step.events.slice(attemptFrom))) {
2448
+ push("info", `the model connection dropped after this step's tools ran — not retried: they can act outside the workspace, and another attempt could repeat what they did`);
2449
+ break;
2450
+ }
2451
+ const wait = Math.round(retryBaseMs() * 2 * n);
2452
+ push("info", `the model connection dropped (${lastDrop.slice(0, 80)}) — the platform's side, not the step's; running the step again in ${Math.round(wait / 1000)}s (${n} of ${DROP_RETRIES})`);
2453
+ await sleep(wait);
2454
+ lastDrop = "";
2455
+ lastRefusal = "";
2456
+ attemptFrom = step.events.length;
2457
+ const previous = outcome.timing;
2458
+ const again = isolatedArgs(platformModelEnv());
2459
+ await lease?.commit();
2460
+ outcome = withEarlierTiming(await runTracked(again), previous);
2461
+ }
2462
+ // The model wrote its tool call out as text — `<invoke name="…">` in
2463
+ // its last message — and stopped. Nothing ran, so nothing was done:
2464
+ // seo-digest's editor three times (27 Sep, 4 and 5 Oct 2026), its own
2465
+ // retry included, because the retry asked the same way. Run it once
2466
+ // more with that said plainly, on the same safety rule as a dropped
2467
+ // connection: never again after an outward tool already ran.
2468
+ for (let n = 1; n <= TEXT_CALL_RETRIES && wroteToolCallAsText(attemptText(outcome.result, step.events.slice(attemptFrom))); n++) {
2469
+ if (!dropRetrySafe(canActOutward, step.events.slice(attemptFrom))) {
2470
+ push("info", "the model wrote a tool call as text instead of making it — not run again: this step's tools can act outside the workspace and already ran");
2471
+ break;
2472
+ }
2473
+ push("info", `the model wrote a tool call as text instead of making it, so nothing ran — running the step again with a note (${n} of ${TEXT_CALL_RETRIES})`);
2474
+ attemptFrom = step.events.length;
2475
+ lastRefusal = "";
2476
+ const previous = outcome.timing;
2477
+ const base = isolatedArgs(platformModelEnv());
2478
+ const again = { ...base, input: { ...base.input, prompt: `${base.input.prompt}\n\n${TEXT_CALL_NOTE}` } };
2479
+ await lease?.commit();
2480
+ outcome = withEarlierTiming(await runTracked(again), previous);
2481
+ }
2358
2482
  // The second supply, tried exactly once, and only when the primary
2359
2483
  // refused over money/auth/limits rather than the work failing. The
2360
2484
  // retry is a fresh sandbox — the failed one is gone, and driveRun's
@@ -2508,6 +2632,20 @@ stepIndex) {
2508
2632
  // finally — once, however many attempts follow.
2509
2633
  const mat = materializeFileSecrets(agentDir, stepSecrets);
2510
2634
  fileDir = mat.dir;
2635
+ // install: pip and npm land in a directory of this step's own, gone in
2636
+ // the finally; apt has no helper on a bare host and says so.
2637
+ installDir = allowed.includes(INSTALL_TOOL) ? fs.mkdtempSync(path.join(os.tmpdir(), "foldrun-step-")) : null;
2638
+ const installEnv = installDir ? stepInstallEnv(installDir, { ...process.env, ...mat.env }) : {};
2639
+ const installTools = installDir
2640
+ ? buildInstallTool({
2641
+ dir: installDir,
2642
+ socket: null,
2643
+ cacheRoot: path.join(dataRoot(), tenant, ".runtimes"),
2644
+ python: mat.env.VIRTUAL_ENV ? path.join(mat.env.VIRTUAL_ENV, "bin", "python") : "python3",
2645
+ env: { ...hostSafeEnv(), ...mat.env, ...installEnv },
2646
+ emit: (type, text) => push(type, text),
2647
+ })
2648
+ : null;
2511
2649
  const attemptInProcess = (modelEnv) => executeStep({
2512
2650
  agentDir,
2513
2651
  workspaceRoot,
@@ -2527,6 +2665,7 @@ stepIndex) {
2527
2665
  ...(historyTools.server ? { foldrun_history: historyTools.server } : {}),
2528
2666
  ...(deskTools.server ? { foldrun_desks: deskTools.server } : {}),
2529
2667
  ...(askTools ? { foldrun_ask: askTools.server } : {}),
2668
+ ...(installTools ? { foldrun_install: installTools.server } : {}),
2530
2669
  ...mcpServers,
2531
2670
  },
2532
2671
  // Declared secrets reach the agent's scripts as env vars; the model
@@ -2534,7 +2673,7 @@ stepIndex) {
2534
2673
  // the allowlisted host environment, not process.env: the SDK's
2535
2674
  // Bash tool runs with this, and on a platform process.env holds
2536
2675
  // every tenant's root key and the datastore credentials.
2537
- env: { ...hostSafeEnv(), ...clockEnv, ...(testRun ? testModeEnv() : {}), ...mat.env, ...modelEnv },
2676
+ env: { ...hostSafeEnv(), ...clockEnv, ...(testRun ? testModeEnv() : {}), ...mat.env, ...installEnv, ...modelEnv },
2538
2677
  timeoutSec: step.timeout,
2539
2678
  budgetUsd: stepBudgetUsd,
2540
2679
  budgetNote: stepBudgetNote,
@@ -2647,6 +2786,8 @@ stepIndex) {
2647
2786
  finally {
2648
2787
  try {
2649
2788
  cleanupFileSecrets(fileDir);
2789
+ if (installDir)
2790
+ fs.rmSync(installDir, { recursive: true, force: true });
2650
2791
  }
2651
2792
  catch {
2652
2793
  // best-effort — a leftover scratch file is swept with the run's outputs
@@ -2804,8 +2945,12 @@ function platformFallbackEnv() {
2804
2945
  */
2805
2946
  const CREDENTIAL_ROTATION_WAIT_MS = 90_000;
2806
2947
  const CREDENTIAL_POLL_MS = 2_000;
2807
- function isAuthRefusal(text) {
2808
- return /API Error: 401|access token has (been revoked|expired)/i.test(text);
2948
+ /** A refusal of the credential itself, in any of the wordings Claude Code
2949
+ * has used. "Failed to authenticate: OAuth token revoked" (9 Oct 2026, a
2950
+ * step started one second before the 09:07:52Z refresh) matched none of the
2951
+ * older two, so the step failed instead of waiting for the new token. */
2952
+ export function isAuthRefusal(text) {
2953
+ return /API Error: 401|access token has (been revoked|expired)|OAuth token (has )?(been )?(revoked|expired)|Failed to authenticate/i.test(text);
2809
2954
  }
2810
2955
  /**
2811
2956
  * Wait, briefly, for the mounted credential to become one we have not
@@ -2848,6 +2993,44 @@ function isProviderRefusal(text) {
2848
2993
  // precisely what the fallback provider is for.
2849
2994
  return /API Error: (401|402|403|429|5\d\d)|credits?\b|quota|billing|insufficient|overloaded|(weekly|daily|monthly|usage) limit|rate.?limit(ed)?\b.*resets?\b|limit\b.*\bresets?\b/i.test(text);
2850
2995
  }
2996
+ /** A step's own model connection cut: the egress proxy or the worker it
2997
+ * runs through went away. Only the run's final error, never a tool's — a
2998
+ * WebFetch that could not connect is the step's business, not ours. */
2999
+ export function isModelConnectionLost(text) {
3000
+ return /^Claude Code returned an error result: API Error: (Connection (refused|dropped|error)|.*\b(ECONNREFUSED|ECONNRESET|socket hang up)\b)/i.test(text);
3001
+ }
3002
+ /** A tool call written out as text rather than made: the model's last
3003
+ * message holds `<invoke name=…>` / `<function_calls>` markup. Only the tail
3004
+ * counts — a reply that quotes such markup mid-way and goes on is fine. */
3005
+ export function wroteToolCallAsText(text) {
3006
+ const tail = text.slice(-1500);
3007
+ const open = tail.search(/<(?:antml:)?(?:invoke|function_calls)\b[^>]*>/);
3008
+ if (open < 0)
3009
+ return false;
3010
+ // Quoted mid-reply and then the reply carries on: not a stalled call.
3011
+ const after = tail.slice(open).replace(/<\/(?:antml:)?(?:invoke|function_calls)>/g, "\u0000");
3012
+ const lastClose = after.lastIndexOf("\u0000");
3013
+ return lastClose < 0 || after.slice(lastClose + 1).trim().length < 200;
3014
+ }
3015
+ /** What an attempt said last: its result, or — when it ended without one —
3016
+ * the error that carried the model's final text. */
3017
+ function attemptText(result, events) {
3018
+ if (result && result.trim())
3019
+ return result;
3020
+ const lastError = [...events].reverse().find((e) => e.type === "error");
3021
+ return lastError?.text ?? "";
3022
+ }
3023
+ /** Runs again after a tool call written as text. */
3024
+ export const TEXT_CALL_RETRIES = 1;
3025
+ export const TEXT_CALL_NOTE = "Note from the platform: your last attempt ended by writing a tool call out as text (an <invoke …> block), so it was not run and nothing happened. " +
3026
+ "Make every tool call as a real tool call — never type its markup into your message.";
3027
+ /** How many times a step whose model connection was cut runs again. */
3028
+ export const DROP_RETRIES = 2;
3029
+ /** May a step whose connection dropped run again? Yes, unless its tools can
3030
+ * act outward and one ran in this attempt (actedThenFailedCheck's rule). */
3031
+ export function dropRetrySafe(canActOutward, attemptEvents) {
3032
+ return !(canActOutward && attemptEvents.some((e) => e.type === "tool"));
3033
+ }
2851
3034
  /** How many times a busy provider is given another moment, and the longest
2852
3035
  * any one wait may be. Three is the industry's habit and the point where
2853
3036
  * waiting longer stops being kinder than failing. */
@@ -3412,6 +3595,33 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
3412
3595
  //
3413
3596
  // Runs on resume too — a parked run's container is long gone, and the
3414
3597
  // one it comes back in needs the same files the first one had.
3598
+ //
3599
+ // A run re-driven after its worker died is the exception to "the store
3600
+ // is newer than the disk": a park harvests before it parks, a crash does
3601
+ // not, so what this run's finished steps wrote to storage/ is only on
3602
+ // disk, and materializing first wrote the store's older copy over it.
3603
+ // On 6 Oct 2026 a worker restart put reddit-desk's 2 Oct post back over
3604
+ // that morning's draft, and a rerun from the validator would have
3605
+ // posted it a second time. So a run that has been here before (its
3606
+ // baseline is on disk) stores what it changed first; files it did not
3607
+ // touch still come fresh from the store.
3608
+ const baselineFile = path.join(runRoot, "runs", run.id, "storage-baseline.json");
3609
+ if (fs.existsSync(baselineFile)) {
3610
+ try {
3611
+ const changedFrom = JSON.parse(fs.readFileSync(baselineFile, "utf8"));
3612
+ const { saved } = await harvestFiles(tenant, workspace, `run:${run.id}`, { changedFrom });
3613
+ if (saved.length) {
3614
+ run.steps[0]?.events.push({
3615
+ t: new Date().toISOString(),
3616
+ type: "info",
3617
+ text: `files: kept ${saved.join(", ")} written before the run was picked up again`,
3618
+ });
3619
+ }
3620
+ }
3621
+ catch {
3622
+ // the materialize below still runs; at worst this is the old behaviour
3623
+ }
3624
+ }
3415
3625
  try {
3416
3626
  const brought = await materializeFiles(tenant, workspace);
3417
3627
  if (brought.length) {
@@ -3421,6 +3631,8 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
3421
3631
  text: `files: ${brought.length} brought into the workspace`,
3422
3632
  });
3423
3633
  }
3634
+ fs.mkdirSync(path.dirname(baselineFile), { recursive: true });
3635
+ fs.writeFileSync(baselineFile, JSON.stringify(storageBaseline(tenant, workspace)));
3424
3636
  }
3425
3637
  catch (err) {
3426
3638
  // A file store that is down must not take the run with it: most flows
@@ -3877,7 +4089,7 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
3877
4089
  save();
3878
4090
  if (freshGroup.every((s) => s.status !== "pending")) {
3879
4091
  // everything in this group was rejected
3880
- if (freshGroup.some((s) => s.status === "failed" && !s.optional)) {
4092
+ if (freshGroup.some((s) => s.status === "failed" && !s.optional && !s.carriedFrom)) {
3881
4093
  run.status = "failed";
3882
4094
  break;
3883
4095
  }
@@ -4099,8 +4311,13 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
4099
4311
  effort: step.effort,
4100
4312
  timeout: step.timeout,
4101
4313
  // The rescuer inherits the contract, not just the job: a step
4102
- // that promised data still owes data when someone else does it.
4314
+ // that promised data still owes data when someone else does it,
4315
+ // and a step that had to pass a check still has to pass it — a
4316
+ // rescue whose result stood unchecked was a way round the very
4317
+ // check that failed (found 7 Oct 2026, adding rescuers to
4318
+ // medium-desk).
4103
4319
  output: step.output,
4320
+ ...(step.verify ? { verify: step.verify } : {}),
4104
4321
  attempts: 0,
4105
4322
  status: "pending",
4106
4323
  events: [],
@@ -4136,7 +4353,11 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
4136
4353
  }
4137
4354
  save();
4138
4355
  }
4139
- const requiredFailed = freshGroup.some((s) => s.status === "failed" && !s.optional);
4356
+ // A step carried into a re-run failed in the run it came from, not
4357
+ // here: the person chose to start after it. Counting it stopped
4358
+ // fix-desk's "re-run from the verifier" (run-muwfi5jn-4217) in under
4359
+ // a second, before the one step it was asked to run.
4360
+ const requiredFailed = freshGroup.some((s) => s.status === "failed" && !s.optional && !s.carriedFrom);
4140
4361
  if (requiredFailed) {
4141
4362
  run.status = "failed";
4142
4363
  break;
@@ -3,6 +3,12 @@ export interface RuntimeSpec {
3
3
  packages: string[];
4
4
  node?: string | boolean;
5
5
  npm: string[];
6
+ /** Debian packages the step needs from the operating system — a library's
7
+ * headers for a pip package that compiles (`libcairo2-dev`), a C compiler
8
+ * (`build-essential`), a program (`ffmpeg`). Installed with apt by the run
9
+ * pod's root start-up, before anything model-directed runs, from a .deb
10
+ * cache on the runtime volume (SYSTEM_INSTALL_SH); verified here. */
11
+ system?: string[];
6
12
  /** Declared entries that are not valid requirements. Kept so the run can
7
13
  * SAY they were dropped: silently discarding `pandas>=2` and then failing
8
14
  * the script with "no module named pandas" is the least debuggable outcome
@@ -13,6 +19,14 @@ export interface RuntimeSpec {
13
19
  * from the same argv as its packages — and said so in the build log. */
14
20
  ignored?: string[];
15
21
  }
22
+ export declare const PIP_REQUIREMENT: RegExp;
23
+ /** npm's own shape: an optional @scope, then a name, then an optional @range. */
24
+ export declare const NPM_REQUIREMENT: RegExp;
25
+ /** A Debian package name as policy defines it: lowercase letters, digits,
26
+ * `+`, `-` and `.`, starting with a letter or digit, two or more characters.
27
+ * Like the two above, a guard first: it can never begin with a dash, so it
28
+ * can never become an apt option, and it holds no shell characters. */
29
+ export declare const DEB_PACKAGE: RegExp;
16
30
  export declare function parseRuntime(raw: unknown): RuntimeSpec | null;
17
31
  /**
18
32
  * Several declarations, one environment.
@@ -90,4 +104,67 @@ export declare function checkEntry(root: string, spec: RuntimeSpec): string | nu
90
104
  * moment a cache grows — so it costs nothing on the hot path.
91
105
  */
92
106
  export declare function pruneRuntimes(cacheRoot: string, keep: string): string[];
107
+ /**
108
+ * An installer's failure, said so that the first line is the cause.
109
+ *
110
+ * Until 11 Oct 2026 a failure was the installer's last 500 characters, and
111
+ * the run log shows a message's first line: a pycairo build that died for
112
+ * want of a C compiler read, in full, `uv pip install failed: files.` — the
113
+ * tail end of a setuptools deprecation notice. The cause was on the last
114
+ * line of 4 KB nobody saw. So: find the cause and the package it hit, say
115
+ * the fix when it is one we know, then the last lines of the log for the rest.
116
+ */
117
+ export declare function summarizeInstallFailure(what: string, out: string): string;
118
+ /** Sets $FOLDRUN_SYSTEM_PACKAGES from the step's input.json (its merged
119
+ * runtime spec) — the run pod's and the docker entry's first line. */
120
+ export declare const SYSTEM_FROM_INPUT_SH = "FOLDRUN_SYSTEM_PACKAGES=\"$(node -e 'try{const r=JSON.parse(require(\"fs\").readFileSync(\"/opt/runner/job/input.json\",\"utf8\")).runtime;process.stdout.write(((r&&r.system)||[]).join(\" \"))}catch(e){}')\"";
121
+ /** Where a run container's root start-up records the system install. */
122
+ export declare const SYSTEM_STATUS_FILE = "/opt/runner/job/system-install.json";
123
+ export declare const SYSTEM_LOG_FILE = "/opt/runner/job/system-install.log";
124
+ /**
125
+ * The root start-up's half of `runtime: system:` — one shell snippet, used by
126
+ * the k8s run pod, the docker entry and the deploy-time warm pod alike.
127
+ * Reads the package names from $FOLDRUN_SYSTEM_PACKAGES (space-separated,
128
+ * each re-checked against DEB_PACKAGE's shape here too, so nothing else can
129
+ * ride in), installs them with apt as root BEFORE the drop to the agent user,
130
+ * and writes SYSTEM_STATUS_FILE for prepareRuntime to read.
131
+ *
132
+ * The first step to need a package set installs it with apt (the .debs kept
133
+ * in `<cache>/.apt/archives`) and then saves the files those packages added,
134
+ * with their dpkg records, as a snapshot: `<cache>/.apt/snapshots/<key>.tar`.
135
+ * Every later step restores the snapshot instead — measured 11 Oct 2026 in a
136
+ * gVisor run pod on the NFS cache: build-essential, pkg-config, python3-dev,
137
+ * libcairo2-dev and libpango1.0-dev (154 packages, 432 MB) took 23-30 s
138
+ * through apt and 0.76 s from the snapshot, gcc and pkg-config working after.
139
+ * The key is the package set AND a checksum of the image's own dpkg status,
140
+ * so a new runner image never restores files built against the old one. A
141
+ * snapshot is written under a temporary name and renamed, so two pods
142
+ * building it at once cannot leave a torn one; a restore that fails falls
143
+ * back to apt, and prepareRuntime verifies the result either way. Unused for
144
+ * 30 days, one is pruned. Package lists stay per pod: two pods updating one
145
+ * lists directory on a shared volume would corrupt it.
146
+ */
147
+ export declare function systemInstallSh(cacheDir: string, logDir?: string): string;
148
+ /**
149
+ * Are the declared system packages on this machine? The install happened in
150
+ * the container's root start-up (systemInstallSh); this only reads the
151
+ * result. Without dpkg (a laptop, macOS) there is nothing to check against
152
+ * and nothing this process could install: say so and carry on.
153
+ */
154
+ export declare function checkSystemPackages(pkgs: string[]): {
155
+ log: string[];
156
+ error: string | null;
157
+ };
93
158
  export declare function prepareRuntime(tenant: string, spec: RuntimeSpec | null): PreparedRuntime;
159
+ /** Where the root start-up's install helper listens, inside a run container. */
160
+ export declare const INSTALL_SOCKET = "/opt/runner/job/install.sock";
161
+ /**
162
+ * What a step installs for itself mid-run (the `install` tool) lands under
163
+ * one per-step directory: pip packages in `<dir>/py` (`uv pip install
164
+ * --target`), npm packages in `<dir>/npm` (`npm install --prefix`). Both are
165
+ * on the step's paths from its first turn, so a tool installed by one call is
166
+ * found by the next — `ffmpeg`, `import manim`, `require("sharp")`. Inside a
167
+ * run container the directory is the container's own filesystem and goes
168
+ * when the container does.
169
+ */
170
+ export declare function stepInstallEnv(dir: string, base: Record<string, string | undefined>): Record<string, string>;