@foldrun/core 19.3.0 → 20.1.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 (56) hide show
  1. package/dist/src/browser-pod.js +4 -0
  2. package/dist/src/completions.js +1 -0
  3. package/dist/src/egress.d.ts +5 -1
  4. package/dist/src/input-text.d.ts +48 -0
  5. package/dist/src/input-text.js +212 -0
  6. package/dist/src/limits.js +2 -1
  7. package/dist/src/manifest.d.ts +6 -1
  8. package/dist/src/manifest.js +8 -5
  9. package/dist/src/ops-log.js +21 -6
  10. package/dist/src/platform.d.ts +23 -0
  11. package/dist/src/platform.js +1 -0
  12. package/dist/src/records.d.ts +11 -0
  13. package/dist/src/run-container.d.ts +11 -7
  14. package/dist/src/run-container.js +50 -11
  15. package/dist/src/run-inputs.d.ts +6 -1
  16. package/dist/src/run-inputs.js +10 -2
  17. package/dist/src/run-output-refusal.d.ts +3 -0
  18. package/dist/src/run-output-refusal.js +16 -0
  19. package/dist/src/run-outputs.d.ts +134 -0
  20. package/dist/src/run-outputs.js +521 -0
  21. package/dist/src/runner.d.ts +1 -0
  22. package/dist/src/runner.js +59 -11
  23. package/dist/src/secrets.d.ts +15 -1
  24. package/dist/src/secrets.js +34 -15
  25. package/dist/src/starter.js +1 -1
  26. package/dist/src/step-state.d.ts +10 -0
  27. package/dist/src/step-state.js +93 -0
  28. package/dist/src/store.d.ts +25 -4
  29. package/dist/src/store.js +15 -4
  30. package/dist/src/text-tool.d.ts +177 -0
  31. package/dist/src/text-tool.js +220 -0
  32. package/dist/src/tool-names.d.ts +3 -1
  33. package/dist/src/tool-names.js +4 -2
  34. package/dist/src/workspace-revisions.js +11 -0
  35. package/package.json +1 -1
  36. package/src/browser-pod.ts +3 -0
  37. package/src/completions.ts +1 -0
  38. package/src/egress.ts +5 -2
  39. package/src/input-text.ts +215 -0
  40. package/src/limits.ts +2 -1
  41. package/src/manifest.ts +12 -5
  42. package/src/ops-log.ts +22 -6
  43. package/src/platform.ts +22 -0
  44. package/src/records.ts +11 -0
  45. package/src/run-container.ts +49 -11
  46. package/src/run-inputs.ts +10 -2
  47. package/src/run-output-refusal.ts +20 -0
  48. package/src/run-outputs.ts +597 -0
  49. package/src/runner.ts +55 -10
  50. package/src/secrets.ts +58 -16
  51. package/src/starter.ts +1 -1
  52. package/src/step-state.ts +97 -0
  53. package/src/store.ts +32 -4
  54. package/src/text-tool.ts +267 -0
  55. package/src/tool-names.ts +4 -2
  56. package/src/workspace-revisions.ts +11 -0
package/src/runner.ts CHANGED
@@ -29,6 +29,7 @@ import { validateSchema, describeSchemaErrors, looksLikeSchema } from "./json-sc
29
29
  import { EGRESS_ENV, MODEL_KEY_NAME, addGrant, grantModelKey, hostOf, placeholderNames, proxyModelEnv, unsubstitute, type EgressGrant } from "./egress.ts";
30
30
  import { SUPPLY_TITLES, supplyProviderBlock, type SupplyAnswer } from "./model-supply.ts";
31
31
  import type { StepSupply } from "./store.ts";
32
+ import { archiveRunOutputs, noteRefused } from "./run-outputs.ts";
32
33
  import { explainRefusal, isRefusalStatus, refusalFromLine, supplyNote, type SupplyState } from "./refusal.ts";
33
34
  import { platform } from "./platform.ts";
34
35
  import { healthKey } from "./secret-health.ts";
@@ -45,6 +46,7 @@ import { DELEGATE_TOOL, gatherSubagents, ownSandbox, subagentPrompt, subagentToo
45
46
  import { DELEGATE_SERVER, buildDelegateTools, delegatePromptLine, delegateToolNames, localDelegateChannel, readCopyBack } from "./delegate-tools.ts";
46
47
  import type { DelegationResult } from "./operator.ts";
47
48
  import type { StepDelegation } from "./store.ts";
49
+ import { TEXT_SERVER, TEXT_TOOL, buildTextTools, textPromptLine } from "./text-tool.ts";
48
50
  import { ASK_TOOL, PEER_TOOLS, applyOperatorEvent, askPromptLine, askTimeoutSec, buildAskTool, buildPeerTools, inboxReader, localPeerBus, peersPromptLine, type PeerInfo } from "./operator.ts";
49
51
  import { sendPlainNotification } from "./notify.ts";
50
52
  import { TOOL_MAP, BUILTIN_TOOLS, ownToolNames, toolRefs, legacyUseNames, legacyUseError, retiredToolNames, retiredToolError } from "./tool-names.ts";
@@ -118,6 +120,7 @@ import { fingerprint, mergeRuntimes, parseRuntime, prepareRuntime, stepInstallEn
118
120
  import { buildInstallTool, INSTALL_TOOL } from "./install-tool.ts";
119
121
  import { dataRoot } from "./paths.ts";
120
122
  import { materializeFiles, harvestFiles, storageBaseline } from "./storage.ts";
123
+ import { readStorageBaseline, writeStorageBaseline } from "./step-state.ts";
121
124
  import { chooseExecutor, ensureImage } from "./container.ts";
122
125
  import { stampBundle } from "./okf.ts";
123
126
  import type { McpServerConfig } from "@anthropic-ai/claude-agent-sdk";
@@ -128,6 +131,7 @@ import { resolveRegion, deriveLocale, localeProse, regionName, type RegionChoice
128
131
  import { trimChars } from "./paths.ts";
129
132
  import { earlierTurns, conversationBlock, type RunContext, type RunInput } from "./conversation.ts";
130
133
  import { inputsNote, type RunInputFile } from "./run-inputs.ts";
134
+ import { textCandidates } from "./input-text.ts";
131
135
  import { resolveClock, localDate, type ClockChoice } from "./clock.ts";
132
136
 
133
137
  export { localDate } from "./clock.ts";
@@ -1772,6 +1776,7 @@ export function agentContext(
1772
1776
  let wantDesks = false;
1773
1777
  let wantAsk = false;
1774
1778
  let wantPeers = false;
1779
+ let wantText = false;
1775
1780
 
1776
1781
  for (const ref of toolRefs(front)) {
1777
1782
  const toolName = ref.name;
@@ -1804,13 +1809,14 @@ export function agentContext(
1804
1809
  } else if (TOOL_MAP[toolName]) {
1805
1810
  allowed.push(...TOOL_MAP[toolName]);
1806
1811
  if (available[toolName]) shadowed.push(toolName);
1807
- } else if (toolName === "search" || toolName === "history" || toolName === "desks" || toolName === "ask" || toolName === "peers") {
1812
+ } else if (toolName === "search" || toolName === "history" || toolName === "desks" || toolName === "ask" || toolName === "peers" || toolName === "text") {
1808
1813
  // The platform's own groups, served in-process — built below, once
1809
1814
  // the roots and the records are known.
1810
1815
  if (toolName === "search") wantSearch = true;
1811
1816
  else if (toolName === "history") wantHistory = true;
1812
1817
  else if (toolName === "ask") wantAsk = true;
1813
1818
  else if (toolName === "peers") wantPeers = true;
1819
+ else if (toolName === "text") wantText = true;
1814
1820
  else wantDesks = true;
1815
1821
  if (available[toolName]) shadowed.push(toolName);
1816
1822
  } else if (toolName === "install") {
@@ -1875,6 +1881,14 @@ export function agentContext(
1875
1881
  // prompt's line are the step's (runStep).
1876
1882
  const peers = wantPeers;
1877
1883
  if (peers) allowed.push(...PEER_TOOLS);
1884
+ // tools: [text] — extract_text, through the extraction service behind the
1885
+ // step's egress proxy. The server is the step's (it needs the step's roots
1886
+ // and, in a pod, the lease address); here the grant and the prompt's line.
1887
+ const textTool = wantText;
1888
+ if (textTool) {
1889
+ allowed.push(TEXT_TOOL);
1890
+ parts.add("text", `# Files as text\n\n${textPromptLine()}`);
1891
+ }
1878
1892
  if (searchTools.promptLines.length || historyTools.promptLines.length || deskTools.promptLines.length) {
1879
1893
  parts.add("finding", `# Finding things\n\n${[...searchTools.promptLines, ...historyTools.promptLines, ...deskTools.promptLines].join("\n")}`);
1880
1894
  }
@@ -1896,6 +1910,7 @@ export function agentContext(
1896
1910
  }
1897
1911
  const denied: string[] = refNames(front.disallowedTools);
1898
1912
  if (denied.includes("install")) denied.push(INSTALL_TOOL);
1913
+ if (denied.includes("text")) denied.push(TEXT_TOOL);
1899
1914
  const finalAllowed = allowed.filter((t) => !denied.includes(t));
1900
1915
  readsFiles = canReadBack(finalAllowed);
1901
1916
  const prompt = parts.assemble();
@@ -1945,6 +1960,7 @@ export function agentContext(
1945
1960
  deskTools,
1946
1961
  ask,
1947
1962
  peers,
1963
+ textTool,
1948
1964
  // `spec` is the MERGED declaration — the agent's own block or its
1949
1965
  // workspace's, plus every granted tool's. The isolated path builds its
1950
1966
  // runtime from this; passing the agent's frontmatter alone silently drops
@@ -2378,6 +2394,16 @@ async function runStep(
2378
2394
  answer = answer
2379
2395
  .split("\n")
2380
2396
  .filter((line) => {
2397
+ // `write: <path> => <text>` / `bytes: <path> => <n>`: the step leaves a
2398
+ // file in its outputs/ (n bytes of "x"), so what archive() does with a
2399
+ // run's outputs is testable end to end.
2400
+ const w = /^(write|bytes): (\S+) => (.*)$/.exec(line);
2401
+ if (w) {
2402
+ const target = path.join(agentDir, "outputs", w[2]!);
2403
+ fs.mkdirSync(path.dirname(target), { recursive: true });
2404
+ fs.writeFileSync(target, w[1] === "write" ? w[3]! : "x".repeat(Number(w[3])));
2405
+ return false;
2406
+ }
2381
2407
  const m = /^call: (\S+) (.*?) => (.*)$/.exec(line);
2382
2408
  if (!m) return true;
2383
2409
  const id = `toolu_stub${(step.calls?.length ?? 0) + 1}`;
@@ -2439,6 +2465,7 @@ async function runStep(
2439
2465
  fallbackEnv, apiWarnings, searchRoots, historyDigest, deskDigest, searchTools, historyTools, deskTools,
2440
2466
  ask,
2441
2467
  peers,
2468
+ textTool,
2442
2469
  translator, fallbackTranslator,
2443
2470
  outward,
2444
2471
  supply,
@@ -2848,6 +2875,7 @@ async function runStep(
2848
2875
  ...(consults.length ? ["foldrun_agents"] : []),
2849
2876
  ...(ask ? ["foldrun_ask"] : []),
2850
2877
  ...(peers ? ["foldrun_peers"] : []),
2878
+ ...(textTool ? [TEXT_SERVER] : []),
2851
2879
  ];
2852
2880
  if (peers) {
2853
2881
  // The colleagues' contract, in the prompt the step reads: who runs
@@ -3138,6 +3166,8 @@ async function runStep(
3138
3166
  ...(peers && stepIndex !== undefined && stepIndex >= 0 ? { agent: step.agent, peers: siblings } : {}),
3139
3167
  // sandbox: own sub-agents: the only names the delegate door takes.
3140
3168
  ...(delegates.length ? { delegates: delegates.map((d) => d.name) } : {}),
3169
+ // tools: [text] — the only leases the proxy serves the /text door on.
3170
+ ...(textTool ? { text: true } : {}),
3141
3171
  });
3142
3172
  // foldrun's models need the proxy: it holds the platform's key and
3143
3173
  // meters each call. No lease (no FOLDRUN_EGRESS_URL) — refused, and
@@ -3395,7 +3425,7 @@ async function runStep(
3395
3425
  // Its file tools inside the sandbox get the same allowance (FOL-96).
3396
3426
  configWrites: step.approve === true && Boolean(step.approvedAt),
3397
3427
  // A snapshot step is told where its folder is, and what comes back.
3398
- prompt: `${prompt}${snapshotId ? `\n\n${SNAPSHOT_NOTE}` : ""}${stepInputs ? `\n\n${inputsNote(stepInputs)}` : ""}`,
3428
+ prompt: `${prompt}${snapshotId ? `\n\n${SNAPSHOT_NOTE}` : ""}${stepInputs ? `\n\n${inputsNote(stepInputs, platform.extractText ? { textBeside: textCandidates(stepInputs).map((f) => f.path) } : undefined)}` : ""}`,
3399
3429
  model,
3400
3430
  effort,
3401
3431
  systemPrompt,
@@ -3412,6 +3442,7 @@ async function runStep(
3412
3442
  runtime: runtime.spec,
3413
3443
  consults,
3414
3444
  ...(peers ? { peers: { self: step.agent, siblings } } : {}),
3445
+ ...(textTool ? { text: true } : {}),
3415
3446
  ...(subagents.length ? { subagents } : {}),
3416
3447
  ...(delegates.length ? { delegates } : {}),
3417
3448
  timeoutSec: step.timeout,
@@ -3865,6 +3896,11 @@ async function runStep(
3865
3896
  const peerChannel = peerBus && stepIndex !== undefined && stepIndex >= 0 ? peerBus.channelFor({ agent: step.agent, step: stepIndex }, siblings) : null;
3866
3897
  const peerTools = peers ? buildPeerTools({ channel: peerChannel, self: step.agent, siblings, emit: push }) : null;
3867
3898
  const localInbox = peerChannel ? inboxReader(peerChannel, push) : undefined;
3899
+ // tools: [text] — no proxy in this process, so no extraction service:
3900
+ // the tool is there and says so, rather than going missing.
3901
+ const textTools = textTool
3902
+ ? buildTextTools({ egress: null, agentDir, workspaceRoot, libraryRoot: libraryDir(tenant), emit: (type, t) => push(type, t) })
3903
+ : null;
3868
3904
  // sandbox: own sub-agents, here: no proxy between the step and this
3869
3905
  // process, so the job is handed to the drive loop directly.
3870
3906
  const delegateTools = delegates.length && delegateJob
@@ -3931,6 +3967,7 @@ async function runStep(
3931
3967
  ...(deskTools.server ? { foldrun_desks: deskTools.server } : {}),
3932
3968
  ...(askTools ? { foldrun_ask: askTools.server } : {}),
3933
3969
  ...(peerTools ? { foldrun_peers: peerTools.server } : {}),
3970
+ ...(textTools ? { [TEXT_SERVER]: textTools.server } : {}),
3934
3971
  ...(delegateTools?.server ? { foldrun_delegate: delegateTools.server } : {}),
3935
3972
  ...(a2aTools?.server ? { foldrun_a2a: a2aTools.server } : {}),
3936
3973
  ...(installTools ? { foldrun_install: installTools.server } : {}),
@@ -4939,11 +4976,18 @@ function driveRunInner(
4939
4976
  };
4940
4977
 
4941
4978
  // Archive what a run produced, so history survives the next run's reset.
4942
- const archive = () => {
4979
+ // Where a backend is registered and `runs.outputs_store` is on, each agent's
4980
+ // outputs are published to the blob store (run-outputs.ts) and what could
4981
+ // not be kept is written on the run; otherwise (a laptop, the setting off, or
4982
+ // — TEMPORARILY, until the EFS cutover — a publish that failed) the folder is
4983
+ // copied to the volume as before.
4984
+ const archive = async () => {
4943
4985
  for (const agent of new Set(run.steps.map((s) => s.agent))) {
4944
4986
  const from = path.join(runRoot, "agents", agent, "outputs");
4945
4987
  if (!fs.existsSync(from) || fs.readdirSync(from).length === 0) continue;
4946
- copyTreeBytes(from, path.join(runRoot, "runs", run.id, "outputs", agent));
4988
+ const done = await archiveRunOutputs(tenant, workspace, run.id, agent, from);
4989
+ if (done.where === "store") noteRefused(run, done.refused);
4990
+ else copyTreeBytes(from, path.join(runRoot, "runs", run.id, "outputs", agent));
4947
4991
  }
4948
4992
  };
4949
4993
 
@@ -5062,10 +5106,12 @@ function driveRunInner(
5062
5106
  // posted it a second time. So a run that has been here before (its
5063
5107
  // baseline is on disk) stores what it changed first; files it did not
5064
5108
  // touch still come fresh from the store.
5065
- const baselineFile = path.join(runRoot, "runs", run.id, "storage-baseline.json");
5066
- if (fs.existsSync(baselineFile)) {
5109
+ // A baseline that cannot be READ is not "never here": materializing
5110
+ // then would be the 6 Oct overwrite again. The error stands and the
5111
+ // step fails as any store fault does (review, 12 Nov 2026).
5112
+ const changedFrom = await readStorageBaseline(runRoot, tenant, workspace, run.id);
5113
+ if (changedFrom) {
5067
5114
  try {
5068
- const changedFrom = JSON.parse(fs.readFileSync(baselineFile, "utf8")) as Record<string, string>;
5069
5115
  const { saved } = await harvestFiles(tenant, workspace, `run:${run.id}`, { changedFrom });
5070
5116
  if (saved.length) {
5071
5117
  run.steps[0]?.events.push({
@@ -5087,8 +5133,7 @@ function driveRunInner(
5087
5133
  text: `files: ${brought.length} brought into the workspace`,
5088
5134
  });
5089
5135
  }
5090
- fs.mkdirSync(path.dirname(baselineFile), { recursive: true });
5091
- fs.writeFileSync(baselineFile, JSON.stringify(storageBaseline(tenant, workspace)));
5136
+ await writeStorageBaseline(runRoot, tenant, workspace, run.id, storageBaseline(tenant, workspace));
5092
5137
  } catch (err) {
5093
5138
  // A file store that is down must not take the run with it: most flows
5094
5139
  // never touch storage/, and the ones that do will fail their own verify.
@@ -6399,7 +6444,7 @@ function driveRunInner(
6399
6444
  // failure too.
6400
6445
  try {
6401
6446
  stampMemories();
6402
- archive();
6447
+ await archive();
6403
6448
  } catch {
6404
6449
  // never let bookkeeping fail a run that already finished
6405
6450
  }
package/src/secrets.ts CHANGED
@@ -128,7 +128,7 @@ interface StoredSecret {
128
128
  v?: 2;
129
129
  }
130
130
 
131
- type SecretsFile = Record<string, StoredSecret>;
131
+ export type SecretsFile = Record<string, StoredSecret>;
132
132
 
133
133
  // ------------------------------------------------------------ binding
134
134
  //
@@ -251,8 +251,45 @@ function openRecord(tenant: string, workspace: string | undefined, name: string,
251
251
  return requireBound() ? null : decrypt(tenant, rec);
252
252
  }
253
253
 
254
+ // ------------------------------------------------------------ where a vault lives
255
+ //
256
+ // A vault scope (an account's, or one workspace's) is its secrets.json — or,
257
+ // on a platform that has registered a store and moved that scope, rows in its
258
+ // database (FOL-126 phase 6: the last thing the egress pod needs the shared
259
+ // volume for). The records are the same sealed records either way: the store
260
+ // never sees a value. A scope is served from exactly one place — a store
261
+ // that says `on` for it is the only thing read and written, so a secret
262
+ // deleted there cannot come back from a file left behind.
263
+
264
+ export interface VaultStore {
265
+ /** Is this scope (workspace undefined: the account's) served from the store? */
266
+ on(tenant: string, workspace?: string): boolean;
267
+ read(tenant: string, workspace?: string): SecretsFile;
268
+ /** mutateVaultFile's contract: `change` gets what is stored now and returns
269
+ * the new contents, or null to leave them; one writer at a time per scope
270
+ * (the callback may run again if another writer got in first), all or
271
+ * nothing; returns what is stored after. Throws the same "busy" error. */
272
+ mutate(tenant: string, workspace: string | undefined, change: (all: SecretsFile) => SecretsFile | null): SecretsFile;
273
+ /** The workspaces of this account whose scope is in the store. */
274
+ workspaces(tenant: string): string[];
275
+ }
276
+
277
+ let vaultStore: VaultStore | null = null;
278
+ /** Register (or, with null, remove) the platform's vault store. None: files. */
279
+ export function setVaultStore(store: VaultStore | null): void {
280
+ vaultStore = store;
281
+ }
282
+ const inStore = (tenant: string, workspace?: string): VaultStore | null => (vaultStore?.on(tenant, workspace) ? vaultStore : null);
283
+
254
284
  function read(tenant: string, workspace?: string): SecretsFile {
255
- return readFile(secretsFile(tenant, workspace));
285
+ const store = inStore(tenant, workspace);
286
+ return store ? store.read(tenant, workspace) : readFile(secretsFile(tenant, workspace));
287
+ }
288
+
289
+ /** Change one vault scope safely, wherever it lives (see mutateVaultFile). */
290
+ function mutateVault(tenant: string, workspace: string | undefined, change: (all: SecretsFile) => SecretsFile | null): SecretsFile {
291
+ const store = inStore(tenant, workspace);
292
+ return store ? store.mutate(tenant, workspace, change) : mutateVaultFile(secretsFile(tenant, workspace), change);
256
293
  }
257
294
 
258
295
  // ------------------------------------------------------------ safe writes
@@ -401,7 +438,7 @@ export function setSecret(
401
438
  }
402
439
  if (value.length > 8192) throw new Error("secret too long");
403
440
  const wanted = limitFor(workspace, limit);
404
- mutateVaultFile(secretsFile(tenant, workspace), (all) => {
441
+ mutateVault(tenant, workspace, (all) => {
405
442
  // A new value keeps the sites the old one was bound to: binding is a
406
443
  // property of the credential's use, not of its current value, and a
407
444
  // rotation that silently unbound it would put the new value in pods.
@@ -441,7 +478,7 @@ export function setSecretSites(tenant: string, name: string, sites: string[], wo
441
478
  if (!SITE.test(site)) throw new Error(`"${site}" is not a site — a domain like api.example.com or *.example.com, no scheme, path or port`);
442
479
  }
443
480
  let found = false;
444
- mutateVaultFile(secretsFile(tenant, workspace), (all) => {
481
+ mutateVault(tenant, workspace, (all) => {
445
482
  const rec = all[name];
446
483
  if (!rec) return null;
447
484
  found = true;
@@ -630,7 +667,7 @@ export function setSecretWorkspaces(
630
667
  const clean = cleanWorkspaceList(workspaces);
631
668
  const expected = opts.ifWorkspaces === undefined ? undefined : cleanWorkspaceList(opts.ifWorkspaces);
632
669
  let found = false;
633
- mutateVaultFile(secretsFile(tenant), (all) => {
670
+ mutateVault(tenant, undefined, (all) => {
634
671
  const rec = all[name];
635
672
  if (!rec) return null;
636
673
  found = true;
@@ -676,9 +713,8 @@ function withWorkspaces(tenant: string, name: string, rec: StoredSecret, workspa
676
713
  export function retargetSecretWorkspaces(tenant: string, from: string, to: string | null): { changed: string[]; failed: string[] } {
677
714
  const changed: string[] = [];
678
715
  const failed: string[] = [];
679
- const file = secretsFile(tenant);
680
- if (!fs.existsSync(file)) return { changed, failed };
681
- mutateVaultFile(file, (all) => {
716
+ if (!inStore(tenant) && !fs.existsSync(secretsFile(tenant))) return { changed, failed };
717
+ mutateVault(tenant, undefined, (all) => {
682
718
  changed.length = 0;
683
719
  failed.length = 0;
684
720
  const staged: typeof all = {};
@@ -714,7 +750,7 @@ export function retargetSecretWorkspaces(tenant: string, from: string, to: strin
714
750
  }
715
751
 
716
752
  export function deleteSecret(tenant: string, name: string, workspace?: string) {
717
- mutateVaultFile(secretsFile(tenant, workspace), (all) => {
753
+ mutateVault(tenant, workspace, (all) => {
718
754
  if (!(name in all)) return null;
719
755
  delete all[name];
720
756
  return all;
@@ -817,6 +853,11 @@ function secretFiles(tenant: string): { file: string; workspace?: string }[] {
817
853
  if (fs.existsSync(f)) out.push({ file: f, workspace: entry.name });
818
854
  }
819
855
  }
856
+ // Scopes in the platform's store have no file; they are named by where
857
+ // the file would be (the result's `file` is a label, never opened).
858
+ for (const workspace of vaultStore?.workspaces(tenant) ?? []) {
859
+ if (!out.some((x) => x.workspace === workspace)) out.push({ file: secretsFile(tenant, workspace), workspace });
860
+ }
820
861
  return out;
821
862
  }
822
863
 
@@ -856,7 +897,7 @@ export function rotateMasterKey(
856
897
 
857
898
  for (const { file, workspace } of secretFiles(tenant)) {
858
899
  let count = 0;
859
- mutateVaultFile(file, (all) => {
900
+ mutateVault(tenant, workspace, (all) => {
860
901
  const next: SecretsFile = {};
861
902
  for (const [name, rec] of Object.entries(all)) {
862
903
  // A record under the ACCOUNT's key is not under the install key, so
@@ -1043,7 +1084,7 @@ export function replaceOAuth2RefreshToken(tenant: string, name: string, workspac
1043
1084
  const next = OAUTH2_PREFIX + JSON.stringify({ ...config, refresh_token: refreshToken });
1044
1085
  for (const scope of workspace ? [workspace, undefined] : [undefined]) {
1045
1086
  let replaced = false;
1046
- mutateVaultFile(secretsFile(tenant, scope), (all) => {
1087
+ mutateVault(tenant, scope, (all) => {
1047
1088
  const rec = all[name];
1048
1089
  if (rec && openRecord(tenant, scope, name, rec) === usedValue) {
1049
1090
  // Built whole, not spread over the old record: a spread kept a stale
@@ -1192,6 +1233,7 @@ function workspacesWithSecrets(tenant: string): string[] {
1192
1233
  }
1193
1234
  for (const n of names) if (fs.existsSync(path.join(base, n, "secrets.json"))) out.add(n);
1194
1235
  }
1236
+ for (const n of vaultStore?.workspaces(tenant) ?? []) out.add(n);
1195
1237
  return [...out];
1196
1238
  }
1197
1239
 
@@ -1641,7 +1683,7 @@ export function setClientCertSecret(tenant: string, name: string, config: Client
1641
1683
  // step: a value set over a secret keeps its site binding, and a wildcard
1642
1684
  // one would present the certificate to a whole domain.
1643
1685
  const wanted = limitFor(workspace, limit);
1644
- mutateVaultFile(secretsFile(tenant, workspace), (all) => {
1686
+ mutateVault(tenant, workspace, (all) => {
1645
1687
  const sites = all[name]?.sites;
1646
1688
  if (wanted !== undefined) assertWorkspacesExist(wanted, limit.exists);
1647
1689
  const workspaces = wanted !== undefined ? (wanted ?? undefined) : all[name]?.workspaces;
@@ -1895,8 +1937,8 @@ export function sealVaultBindings(tenant: string): { sealed: number; unreadable:
1895
1937
  assertSafeName(tenant, "tenant");
1896
1938
  let sealed = 0;
1897
1939
  const unreadable: string[] = [];
1898
- for (const { file, workspace } of secretFiles(tenant)) {
1899
- mutateVaultFile(file, (all) => {
1940
+ for (const { workspace } of secretFiles(tenant)) {
1941
+ mutateVault(tenant, workspace, (all) => {
1900
1942
  const plain = new Map<string, string>();
1901
1943
  const bad: string[] = [];
1902
1944
  for (const [name, rec] of Object.entries(all)) {
@@ -1937,10 +1979,10 @@ export function rewrapTenantSecrets(tenant: string): { moved: number; unreadable
1937
1979
  let moved = 0;
1938
1980
  const unreadable: string[] = [];
1939
1981
 
1940
- for (const { file, workspace } of secretFiles(tenant)) {
1982
+ for (const { workspace } of secretFiles(tenant)) {
1941
1983
  // Under the vault's lock: every pod runs this at boot, and a save made
1942
1984
  // between our read and our write must not be lost.
1943
- mutateVaultFile(file, (all) => {
1985
+ mutateVault(tenant, workspace, (all) => {
1944
1986
  const plain = new Map<string, string>();
1945
1987
  const unreadableHere: string[] = [];
1946
1988
  for (const [name, rec] of Object.entries(all)) {
package/src/starter.ts CHANGED
@@ -502,7 +502,7 @@ model: default # fast | default | max
502
502
  effort: low # how hard to think about it
503
503
  size: large # small | large | heavy — the sandbox it rents
504
504
  resources: { memory: 4Gi } # optional: cpu, memory, disk in numbers, over the size class
505
- tools: [web, read, ask, peers, my-folder-tool] # built-ins and your own tools/, one list; \`ask\` lets it ask you mid-step, \`peers\` lets it message the steps running beside it
505
+ tools: [web, read, ask, peers, text, my-folder-tool] # built-ins and your own tools/, one list; \`ask\` lets it ask you mid-step, \`peers\` lets it message the steps running beside it, \`text\` reads images, PDFs, office files and recordings as text
506
506
  disallowedTools: [Bash] # subtract from what it would otherwise have
507
507
  skills: [house-style] # from skills/
508
508
  hooks: [no-force-push] # from hooks/ or the library: code at every tool call
@@ -0,0 +1,97 @@
1
+ // What a step was handed and started from, kept beside its run (FOL-126 phase 7).
2
+ //
3
+ // Three small records, all platform-owned and never staged into a sandbox:
4
+ // handed-in the hash of every file a driver put in the pod (copy-back diff)
5
+ // base the revisions the stage-in started from (RunBase)
6
+ // storage the storage/ index as it was when the run first materialized it
7
+ // (its existence is "this run has been here before" — a worker
8
+ // that picks a run up again stores what it changed first)
9
+ //
10
+ // With a database and `runs.step_state_store` on they are rows (records port,
11
+ // table run_step_state), deleted with the run, the workspace and the account.
12
+ // Otherwise they are files under runs/<id>/, as before. Reads look at rows
13
+ // first whatever the switch says, then at the file, so turning it off — or on —
14
+ // mid-run loses nothing; a write with the switch off removes the key's row
15
+ // first, so the file written is the one read. A row that cannot be read is an error, not "none":
16
+ // "none" means "start again from scratch", and that is not what a database
17
+ // that is down means.
18
+
19
+ import fs from "node:fs";
20
+ import path from "node:path";
21
+ import { records } from "./records.ts";
22
+
23
+ export type StepStateKind = "handed-in" | "base" | "storage";
24
+
25
+ const SAFE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/;
26
+ const okIds = (runId: string, ref: string) => SAFE.test(runId) && (ref === "" || SAFE.test(ref));
27
+
28
+ /** The rows' port for this run, or null: it is files (no database, the workspace
29
+ * not moved yet, no tenant known). */
30
+ function port(tenant: string | undefined, workspace: string) {
31
+ if (!tenant) return null;
32
+ const p = records(tenant, workspace);
33
+ return p?.async?.stepGet ? p : null;
34
+ }
35
+
36
+ /** Stored as a row? False: the caller writes the file. */
37
+ export async function putStepState(tenant: string | undefined, workspace: string, runId: string, kind: StepStateKind, ref: string, data: unknown): Promise<boolean> {
38
+ const p = port(tenant, workspace);
39
+ if (!p || !tenant || !p.async?.stepPut || !okIds(runId, ref)) return false;
40
+ if (!safeOn(p)) {
41
+ // Switched off with a row already there: reads look at rows first, so
42
+ // the old row would shadow the file the caller is about to write (a
43
+ // resumed run's storage baseline is rewritten each time — review, 12 Nov
44
+ // 2026). The row goes; a failure here is an error, not a quiet stale read.
45
+ await p.async.stepDrop?.(tenant, workspace, runId, kind, ref);
46
+ return false;
47
+ }
48
+ await p.async.stepPut(tenant, workspace, runId, kind, ref, data);
49
+ return true;
50
+ }
51
+ const safeOn = (p: { stepStateOn?(): boolean }): boolean => {
52
+ try {
53
+ return p.stepStateOn?.() === true;
54
+ } catch {
55
+ return false;
56
+ }
57
+ };
58
+
59
+ /** The row, or undefined (look at the file). */
60
+ export async function getStepState(tenant: string | undefined, workspace: string, runId: string, kind: StepStateKind, ref: string): Promise<unknown | undefined> {
61
+ const p = port(tenant, workspace);
62
+ if (!p || !tenant || !p.async?.stepGet || !okIds(runId, ref)) return undefined;
63
+ return p.async.stepGet(tenant, workspace, runId, kind, ref);
64
+ }
65
+
66
+ /** Forget rows (a step's copy-out is done). Files are the caller's. */
67
+ export async function dropStepState(tenant: string | undefined, workspace: string, runId: string, kind: StepStateKind, ref: string | null): Promise<void> {
68
+ const p = port(tenant, workspace);
69
+ if (!p || !tenant || !p.async?.stepDrop || !okIds(runId, ref ?? "")) return;
70
+ await p.async.stepDrop(tenant, workspace, runId, kind, ref);
71
+ }
72
+
73
+ // ------------------------------------------------------------ storage baseline
74
+
75
+ const baselineFile = (workspaceRoot: string, runId: string): string => path.join(workspaceRoot, "runs", runId, "storage-baseline.json");
76
+
77
+ const asHashes = (v: unknown): Record<string, string> | undefined => (v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, string>) : undefined);
78
+
79
+ /** The storage index this run first materialized, or undefined: it has not been here. */
80
+ export async function readStorageBaseline(workspaceRoot: string, tenant: string | undefined, workspace: string, runId: string): Promise<Record<string, string> | undefined> {
81
+ const row = asHashes(await getStepState(tenant, workspace, runId, "storage", ""));
82
+ if (row) return row;
83
+ const file = baselineFile(workspaceRoot, runId);
84
+ if (!fs.existsSync(file)) return undefined;
85
+ try {
86
+ return asHashes(JSON.parse(fs.readFileSync(file, "utf8")));
87
+ } catch {
88
+ return undefined;
89
+ }
90
+ }
91
+
92
+ export async function writeStorageBaseline(workspaceRoot: string, tenant: string | undefined, workspace: string, runId: string, hashes: Record<string, string>): Promise<void> {
93
+ if (await putStepState(tenant, workspace, runId, "storage", "", hashes)) return;
94
+ const file = baselineFile(workspaceRoot, runId);
95
+ fs.mkdirSync(path.dirname(file), { recursive: true });
96
+ fs.writeFileSync(file, JSON.stringify(hashes));
97
+ }
package/src/store.ts CHANGED
@@ -3911,6 +3911,16 @@ export interface PriceSnapshot {
3911
3911
  values: Record<string, number>;
3912
3912
  }
3913
3913
 
3914
+ export interface RefusedOutput {
3915
+ agent: string;
3916
+ /** Relative to that agent's outputs/. */
3917
+ path: string;
3918
+ bytes: number;
3919
+ reason: "file-cap" | "run-cap" | "name" | "count";
3920
+ /** The cap in bytes that was exceeded (the count for "count"). */
3921
+ limit?: number;
3922
+ }
3923
+
3914
3924
  export interface RunRecord {
3915
3925
  id: string;
3916
3926
  flow: string; // flow name, or "adhoc:<agent>" for direct agent runs
@@ -3978,6 +3988,12 @@ export interface RunRecord {
3978
3988
  * the agents decided was worth remembering, listed so a person can review
3979
3989
  * the lesson without diffing the folder. */
3980
3990
  memoryWrites?: string[];
3991
+ /** Files a run's agents left in outputs/ that were NOT kept, and why (FOL-126
3992
+ * phase 5): over the per-file or per-run size cap, a name the store cannot
3993
+ * hold, or too many files. Shown on the run page and listed by /files. At
3994
+ * most 100 are named; `outputsRefusedCount` is the whole number. */
3995
+ outputsRefused?: RefusedOutput[];
3996
+ outputsRefusedCount?: number;
3981
3997
  /** The workspace's deployed commit when the run was created — which
3982
3998
  * version of the files it ran (FOL-54 step 4). Absent for a workspace
3983
3999
  * never deployed, and before 19 Oct 2026. */
@@ -4132,6 +4148,9 @@ export function deleteRun(tenant: string, workspace: string, runId: string, opts
4132
4148
  if (prior?.inputs?.length) {
4133
4149
  void import("./storage.ts").then((m) => m.releaseRunInputs(tenant, workspace, runId)).catch(() => {});
4134
4150
  }
4151
+ // Outputs published to the blob store (run-outputs.ts) are records and pins,
4152
+ // not files under dir: they go in the background, retried.
4153
+ onRunRemoved?.(tenant, workspace, runId);
4135
4154
  if (!had) return true;
4136
4155
  // The retention window's prune (`pruned`) is policy, not a person erasing
4137
4156
  // history: no per-run ledger note. The charge stands either way.
@@ -4139,6 +4158,12 @@ export function deleteRun(tenant: string, workspace: string, runId: string, opts
4139
4158
  return true;
4140
4159
  }
4141
4160
 
4161
+ /** run-outputs.ts registers here (it imports this module). */
4162
+ let onRunRemoved: ((tenant: string, workspace: string, runId: string) => void) | null = null;
4163
+ export function registerRunRemovedHook(fn: typeof onRunRemoved) {
4164
+ onRunRemoved = fn;
4165
+ }
4166
+
4142
4167
  /** ledger.ts registers here — store cannot import it without a cycle, and
4143
4168
  * money must not depend on one. */
4144
4169
  let onRunDeleted: ((tenant: string, workspace: string, runId: string) => void) | undefined;
@@ -4154,14 +4179,17 @@ export interface RunOutputFile {
4154
4179
  }
4155
4180
 
4156
4181
  /**
4157
- * What a run archived: every file its agents left in outputs/, copied under
4158
- * runs/<id>/outputs/<agent>/ when the run finished (runner.ts, archive()).
4182
+ * What a run archived ON THE VOLUME: every file its agents left in outputs/,
4183
+ * copied under runs/<id>/outputs/<agent>/ when the run finished (runner.ts,
4184
+ * archive()). Where run outputs are published to the blob store (FOL-126
4185
+ * phase 5, run-outputs.ts) this is only the fallback and the laptop's copy;
4186
+ * callers use run-outputs.ts listRunOutputs, which asks both.
4159
4187
  *
4160
4188
  * Per agent, not per step — the archive is a copy of each agent's folder,
4161
4189
  * and the record cannot say which step wrote which file. An agent that
4162
4190
  * steps twice in one run shows the same files against both steps.
4163
4191
  */
4164
- export function listRunOutputs(tenant: string, workspace: string, runId: string): RunOutputFile[] {
4192
+ export function listRunOutputsOnVolume(tenant: string, workspace: string, runId: string): RunOutputFile[] {
4165
4193
  const root = path.join(workspaceDir(tenant, workspace), "runs", runId, "outputs");
4166
4194
  if (!fs.existsSync(root)) return [];
4167
4195
  const out: RunOutputFile[] = [];
@@ -4181,7 +4209,7 @@ export function listRunOutputs(tenant: string, workspace: string, runId: string)
4181
4209
 
4182
4210
  /** The absolute path of one archived output, or null when the name escapes
4183
4211
  * the archive or names nothing — the API serves only what this returns. */
4184
- export function runOutputPath(
4212
+ export function runOutputPathOnVolume(
4185
4213
  tenant: string,
4186
4214
  workspace: string,
4187
4215
  runId: string,