@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
@@ -0,0 +1,521 @@
1
+ // Run outputs in the blob store (FOL-126, phase 5).
2
+ //
3
+ // What a run's agents leave in outputs/ used to be copied, when the run
4
+ // finished, to runs/<id>/outputs/<agent>/ on the shared volume (runner.ts,
5
+ // archive()). Now, where a backend is registered and the operator has turned
6
+ // `runs.outputs_store` on, each agent's outputs are PUBLISHED instead:
7
+ //
8
+ // files ──► BlobStore (content-addressed, create-only; pinned while uploading)
9
+ // ──► one manifest per run + agent ({ v:1, kind:"run-output", files })
10
+ // ──► one RunOutputStore record (the commit) + a permanent pin on the manifest
11
+ //
12
+ // It follows the publish protocol of publish.ts (pin → upload → manifest →
13
+ // commit) but NOT its head: a workspace head is a mutable compare-and-set
14
+ // pointer, and a run's outputs are immutable and belong to one run. So the
15
+ // commit is an idempotent upsert keyed by (tenant, workspace, run, agent), and
16
+ // the pin (holder kind "run", id outputs:<run>:<agent>:<manifest>) is what
17
+ // keeps the sweeper's hands off while the run exists. Deleting the run, its
18
+ // workspace or its account drops the record and the pin; the sweeper then
19
+ // collects the objects.
20
+ //
21
+ // Limits are a setting, not a surprise: a file over `runs.output_file_mb`, or
22
+ // outputs past `runs.output_run_mb` for the whole run, are REFUSED — not
23
+ // published, and not kept on the volume either (the volume goes away at
24
+ // cutover). Each is written on the run (RunRecord.outputsRefused) and in the
25
+ // step's trail, and shown on the run page.
26
+ //
27
+ // TEMPORARY (remove at the EFS cutover, FOL-126 phase 9): when publishing
28
+ // fails with an error (the store is down, the database refuses), the outputs
29
+ // are copied to the volume as before and the failure is logged
30
+ // (`run_outputs.fallback`). A laptop or an install with no backend always
31
+ // uses the volume: it is a local disk there, not the thing being retired.
32
+ //
33
+ // Reads (`listRunOutputs`, `openRunOutput`) ask the records first and the
34
+ // volume second, per agent, so a run archived either way stays readable
35
+ // whatever the setting is now.
36
+ import fs from "node:fs";
37
+ import { Readable } from "node:stream";
38
+ import path from "node:path";
39
+ import crypto from "node:crypto";
40
+ import { dataRoot } from "./paths.js";
41
+ import { BlobNotFound } from "./blob-store.js";
42
+ import { PUBLISH_PIN_TTL_MS, noPins } from "./blob-pins.js";
43
+ import { MAX_MANIFEST_FILES, MODE_EXEC, MODE_FILE, assertManifest, assertManifestPath, blobObjectKey, canonicalManifest, manifestId, manifestObjectKey, sha256Hex, } from "./manifest.js";
44
+ import { BlobMissing, loadManifest } from "./publish.js";
45
+ import { opsError } from "./ops-log.js";
46
+ import { refusalText } from "./run-output-refusal.js";
47
+ export { refusalText };
48
+ import { listRunOutputsOnVolume, registerRunRemovedHook, runOutputPathOnVolume } from "./store.js";
49
+ const SAFE = /^[A-Za-z0-9][A-Za-z0-9._@-]{0,120}$/;
50
+ function safeName(v, what) {
51
+ if (!SAFE.test(v))
52
+ throw new Error(`illegal ${what}: ${v}`);
53
+ return v;
54
+ }
55
+ /** Files under <data>/.run-outputs/<tenant>/<workspace>/<run>/<agent>.json.
56
+ * For an install that has a blob store but no database (and for the tests):
57
+ * the database one is platform's run-outputs-pg.ts. */
58
+ export function localRunOutputStore(root = path.join(dataRoot(), ".run-outputs")) {
59
+ const dir = (t, w, r) => path.join(root, safeName(t, "tenant"), safeName(w, "workspace"), safeName(r, "run"));
60
+ const readDir = (d) => {
61
+ if (!fs.existsSync(d))
62
+ return [];
63
+ const out = [];
64
+ for (const f of fs.readdirSync(d)) {
65
+ if (!f.endsWith(".json"))
66
+ continue;
67
+ try {
68
+ out.push(JSON.parse(fs.readFileSync(path.join(d, f), "utf8")));
69
+ }
70
+ catch {
71
+ // a torn write is not a record
72
+ }
73
+ }
74
+ return out;
75
+ };
76
+ const allIn = (base) => (fs.existsSync(base) ? fs.readdirSync(base).flatMap((r) => readDir(path.join(base, r))) : []);
77
+ return {
78
+ kind: "local",
79
+ async put(rec) {
80
+ const d = dir(rec.tenant, rec.workspace, rec.runId);
81
+ fs.mkdirSync(d, { recursive: true });
82
+ const file = path.join(d, `${safeName(rec.agent, "agent")}.json`);
83
+ let prev = null;
84
+ try {
85
+ prev = JSON.parse(fs.readFileSync(file, "utf8"));
86
+ }
87
+ catch {
88
+ // none
89
+ }
90
+ const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
91
+ fs.writeFileSync(tmp, JSON.stringify(rec));
92
+ fs.renameSync(tmp, file);
93
+ return prev;
94
+ },
95
+ async list(t, w, r) {
96
+ return readDir(dir(t, w, r));
97
+ },
98
+ async drop({ tenant, workspace, runId }) {
99
+ safeName(tenant, "tenant");
100
+ if (workspace && runId) {
101
+ const d = dir(tenant, workspace, runId);
102
+ const had = readDir(d);
103
+ fs.rmSync(d, { recursive: true, force: true });
104
+ return had;
105
+ }
106
+ const base = workspace ? path.join(root, tenant, safeName(workspace, "workspace")) : path.join(root, tenant);
107
+ const had = workspace ? allIn(base) : fs.existsSync(base) ? fs.readdirSync(base).flatMap((w) => allIn(path.join(base, w))) : [];
108
+ fs.rmSync(base, { recursive: true, force: true });
109
+ return had;
110
+ },
111
+ bytes(t, w) {
112
+ const base = path.join(root, safeName(t, "tenant"), safeName(w, "workspace"));
113
+ return allIn(base).reduce((n, r) => n + r.bytes, 0);
114
+ },
115
+ async move(t, from, to) {
116
+ const a = path.join(root, safeName(t, "tenant"), safeName(from, "workspace"));
117
+ const b = path.join(root, t, safeName(to, "workspace"));
118
+ fs.rmSync(b, { recursive: true, force: true });
119
+ if (!fs.existsSync(a))
120
+ return;
121
+ fs.renameSync(a, b);
122
+ for (const rec of allIn(b)) {
123
+ rec.workspace = to;
124
+ const f = path.join(b, rec.runId, `${rec.agent}.json`);
125
+ fs.writeFileSync(f, JSON.stringify(rec));
126
+ }
127
+ },
128
+ };
129
+ }
130
+ let backend = null;
131
+ /** Where run outputs are published, or null (every run archives to the volume). */
132
+ export function setRunOutputsBackend(b) {
133
+ backend = b;
134
+ registerRunRemovedHook(b ? runDeleted : null);
135
+ }
136
+ export const runOutputsBackend = () => backend;
137
+ function safeCall(fn, fallback) {
138
+ try {
139
+ return fn();
140
+ }
141
+ catch {
142
+ return fallback;
143
+ }
144
+ }
145
+ /** Publishing is on: a backend is registered and the operator has said so. */
146
+ export const runOutputsOn = () => !!backend && safeCall(backend.enabled, false);
147
+ const pinsOf = (b) => b.pins ?? noPins;
148
+ /** The permanent pin on one record's manifest. The manifest id is part of the
149
+ * holder, so a re-archive (a resumed run) can pin the new manifest before it
150
+ * releases the old one. */
151
+ export function outputsHolder(runId, agent, manifest) {
152
+ return { kind: "run", id: `outputs:${runId}:${agent}:${manifest.slice(0, 16)}` };
153
+ }
154
+ const releaseRecords = async (b, recs) => {
155
+ for (const r of recs)
156
+ await pinsOf(b).release(r.tenant, outputsHolder(r.runId, r.agent, r.manifest));
157
+ };
158
+ // ------------------------------------------------------------------ publishing
159
+ /** How many files are in flight at once, and so at most this many buffered. */
160
+ const UPLOAD_CONCURRENCY = 4;
161
+ const MAX_REFUSALS_ON_RECORD = 100;
162
+ function walk(root) {
163
+ const out = [];
164
+ const rec = (dir, rel) => {
165
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
166
+ const abs = path.join(dir, e.name);
167
+ const r = rel ? `${rel}/${e.name}` : e.name;
168
+ if (e.isDirectory())
169
+ rec(abs, r);
170
+ else if (e.isFile()) {
171
+ const st = fs.lstatSync(abs);
172
+ out.push({ rel: r, abs, size: st.size, mode: st.mode & 0o111 ? MODE_EXEC : MODE_FILE });
173
+ }
174
+ // symlinks, sockets and the like are not outputs (the volume copy skipped them too)
175
+ }
176
+ };
177
+ rec(root, "");
178
+ return out.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
179
+ }
180
+ /**
181
+ * Publish one agent's outputs of one run. Returns the record (null: nothing
182
+ * was kept — no files, or every one refused) and what was refused. Throws when
183
+ * the store or the database fails; the caller decides what that means
184
+ * (archiveRunOutputs: the temporary volume fallback). Idempotent: the same
185
+ * files again are the same manifest and the same record.
186
+ */
187
+ export async function publishRunOutputs(b, tenant, workspace, runId, agent, dir) {
188
+ safeName(agent, "agent");
189
+ const fileMax = b.fileMaxBytes();
190
+ const runMax = b.runMaxBytes();
191
+ const refused = [];
192
+ // What the run's other agents already hold counts against the run's cap.
193
+ const others = (await b.store.list(tenant, workspace, runId)).filter((r) => r.agent !== agent);
194
+ let used = others.reduce((n, r) => n + r.bytes, 0);
195
+ const kept = [];
196
+ const lower = new Map();
197
+ for (const c of walk(dir)) {
198
+ const refuse = (reason, limit) => refused.push({ agent, path: c.rel, bytes: c.size, reason, ...(limit !== undefined ? { limit } : {}) });
199
+ try {
200
+ assertManifestPath(c.rel, "run-output");
201
+ }
202
+ catch {
203
+ refuse("name");
204
+ continue;
205
+ }
206
+ const folded = c.rel.toLowerCase();
207
+ if (lower.has(folded)) {
208
+ refuse("name");
209
+ continue;
210
+ }
211
+ if (kept.length >= MAX_MANIFEST_FILES) {
212
+ refuse("count", MAX_MANIFEST_FILES);
213
+ continue;
214
+ }
215
+ if (fileMax > 0 && c.size > fileMax) {
216
+ refuse("file-cap", fileMax);
217
+ continue;
218
+ }
219
+ if (runMax > 0 && used + c.size > runMax) {
220
+ refuse("run-cap", runMax);
221
+ continue;
222
+ }
223
+ lower.set(folded, c.rel);
224
+ used += c.size;
225
+ kept.push(c);
226
+ }
227
+ if (!kept.length)
228
+ return { record: null, refused };
229
+ const pins = pinsOf(b);
230
+ const publishHolder = { kind: "publish", id: `outputs:${runId}:${agent}` };
231
+ // No prototype: an output may be named anything legal, `__proto__` too
232
+ // (review, 12 Nov 2026: a plain object dropped it silently).
233
+ const files = Object.create(null);
234
+ let pinnedRun = null;
235
+ let id = null;
236
+ try {
237
+ // Pin BEFORE the objects exist: a sweeper that looks now sees the pin.
238
+ // Read each file once for its hash (a file can only be named by its
239
+ // bytes), then upload; at most UPLOAD_CONCURRENCY buffers are live.
240
+ let next = 0;
241
+ const lane = async () => {
242
+ for (;;) {
243
+ const i = next++;
244
+ if (i >= kept.length)
245
+ return;
246
+ const c = kept[i];
247
+ const body = fs.readFileSync(c.abs);
248
+ // Grew since it was measured (an agent still writing): same rule, same cap.
249
+ if (fileMax > 0 && body.length > fileMax) {
250
+ refused.push({ agent, path: c.rel, bytes: body.length, reason: "file-cap", limit: fileMax });
251
+ continue;
252
+ }
253
+ const sha = sha256Hex(body);
254
+ // Pin each blob before its put; a repeat extends the lease.
255
+ await pins.pinBlobs(tenant, [sha], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
256
+ await b.blobs.putIfAbsent(blobObjectKey(tenant, sha), body);
257
+ files[c.rel] = { sha, size: body.length, mode: c.mode };
258
+ }
259
+ };
260
+ await Promise.all(Array.from({ length: Math.min(UPLOAD_CONCURRENCY, kept.length) }, lane));
261
+ if (!Object.keys(files).length)
262
+ return { record: null, refused };
263
+ const manifest = { v: 1, kind: "run-output", files };
264
+ assertManifest(manifest);
265
+ id = manifestId(manifest);
266
+ await pins.pinManifests(tenant, [id], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
267
+ await b.blobs.putIfAbsent(manifestObjectKey(tenant, id), Buffer.from(canonicalManifest(manifest)));
268
+ // The permanent pin lands before the commit: whatever happens next, a
269
+ // record never names a manifest nothing holds.
270
+ pinnedRun = outputsHolder(runId, agent, id);
271
+ await pins.pinManifests(tenant, [id], pinnedRun);
272
+ const record = {
273
+ tenant,
274
+ workspace,
275
+ runId,
276
+ agent,
277
+ manifest: id,
278
+ files: Object.keys(files).length,
279
+ bytes: Object.values(files).reduce((n, f) => n + f.size, 0),
280
+ at: new Date().toISOString(),
281
+ };
282
+ const prev = await b.store.put(record);
283
+ if (prev && prev.manifest !== id)
284
+ await pins.release(tenant, outputsHolder(runId, agent, prev.manifest));
285
+ return { record, refused };
286
+ }
287
+ catch (err) {
288
+ // The pin was taken for a commit that did not happen: let go, unless the
289
+ // record that stands names this very manifest (a repeat that failed late).
290
+ if (pinnedRun && id) {
291
+ try {
292
+ const cur = (await b.store.list(tenant, workspace, runId)).find((r) => r.agent === agent);
293
+ if (!cur || cur.manifest !== id)
294
+ await pins.release(tenant, pinnedRun);
295
+ }
296
+ catch {
297
+ // an unknown state keeps the pin: leaking an object is safe, losing one is not
298
+ }
299
+ }
300
+ throw err;
301
+ }
302
+ finally {
303
+ await pins.release(tenant, publishHolder).catch(() => { });
304
+ }
305
+ }
306
+ /** The caller's note on the run: what was refused, on the record, in the
307
+ * step's trail. Mutates `run` (the caller saves it). */
308
+ export function noteRefused(run, refused) {
309
+ if (!refused.length)
310
+ return;
311
+ const have = run.outputsRefused ?? [];
312
+ const seen = new Set(have.map((r) => `${r.agent}\u0000${r.path}`));
313
+ const fresh = refused.filter((r) => !seen.has(`${r.agent}\u0000${r.path}`));
314
+ if (!fresh.length)
315
+ return;
316
+ run.outputsRefused = [...have, ...fresh].slice(0, MAX_REFUSALS_ON_RECORD);
317
+ run.outputsRefusedCount = (run.outputsRefusedCount ?? have.length) + fresh.length;
318
+ const last = run.steps.findLast((s) => s.status !== "pending") ?? run.steps[0];
319
+ for (const r of fresh.slice(0, 20)) {
320
+ last?.events.push({ t: new Date().toISOString(), type: "error", text: `outputs: ${refusalText(r)}` });
321
+ }
322
+ if (fresh.length > 20)
323
+ last?.events.push({ t: new Date().toISOString(), type: "error", text: `outputs: ${fresh.length - 20} more files were not kept` });
324
+ }
325
+ /**
326
+ * runner.ts archive() for one agent: publish when it is on, else (or when it
327
+ * fails) say "volume" and the caller copies the folder as before.
328
+ */
329
+ export async function archiveRunOutputs(tenant, workspace, runId, agent, dir) {
330
+ const b = backend;
331
+ if (!b || !runOutputsOn())
332
+ return { where: "volume" };
333
+ try {
334
+ const r = await publishRunOutputs(b, tenant, workspace, runId, agent, dir);
335
+ return { where: "store", refused: r.refused };
336
+ }
337
+ catch (err) {
338
+ // TEMPORARY (EFS cutover, FOL-126 phase 9): an error publishing is not a
339
+ // reason to lose the run's outputs while the volume still exists. Remove
340
+ // this branch with the volume; then a failed publish fails the archive.
341
+ opsError("run_outputs.fallback", err, { tenant, workspace, run: runId, agent });
342
+ return { where: "volume" };
343
+ }
344
+ }
345
+ // --------------------------------------------------------------------- reading
346
+ /** loadManifest reads blobs only; there is no revision store behind a run's outputs. */
347
+ const readDeps = (b) => ({ blobs: b.blobs, revisions: undefined });
348
+ async function recordsOf(tenant, workspace, runId) {
349
+ if (!backend)
350
+ return [];
351
+ try {
352
+ return await backend.store.list(tenant, workspace, runId);
353
+ }
354
+ catch (err) {
355
+ opsError("run_outputs.list_failed", err, { tenant, workspace, run: runId });
356
+ throw err;
357
+ }
358
+ }
359
+ /** What a run archived, from the store and from the volume (an agent the store
360
+ * has wins). Sorted by agent, then path. */
361
+ export async function listRunOutputs(tenant, workspace, runId) {
362
+ const recs = await recordsOf(tenant, workspace, runId);
363
+ const out = [];
364
+ for (const r of recs) {
365
+ const m = await loadManifest(readDeps(backend), tenant, r.manifest);
366
+ for (const [p, e] of Object.entries(m.files))
367
+ out.push({ agent: r.agent, path: p, bytes: e.size });
368
+ }
369
+ const mine = new Set(recs.map((r) => r.agent));
370
+ for (const f of listRunOutputsOnVolume(tenant, workspace, runId))
371
+ if (!mine.has(f.agent))
372
+ out.push(f);
373
+ return out.sort((a, b) => a.agent.localeCompare(b.agent) || a.path.localeCompare(b.path));
374
+ }
375
+ /** One archived output, or null when the name escapes the archive or names
376
+ * nothing — the API serves only what this returns. */
377
+ export async function openRunOutput(tenant, workspace, runId, agent, rel) {
378
+ if (!agent || !rel || agent.includes("/") || agent.includes("\\") || agent.startsWith("."))
379
+ return null;
380
+ const rec = (await recordsOf(tenant, workspace, runId)).find((r) => r.agent === agent);
381
+ if (rec && backend) {
382
+ const m = await loadManifest(readDeps(backend), tenant, rec.manifest);
383
+ const e = m.files[rel.normalize("NFC")];
384
+ if (!e)
385
+ return null;
386
+ const key = blobObjectKey(tenant, e.sha);
387
+ const blobs = backend.blobs;
388
+ // A blob that is gone is an explicit failure (never an empty file); heading
389
+ // here makes it one error before any byte is sent.
390
+ if (!(await blobs.head(key)))
391
+ throw new BlobMissing(`${agent}/${rel}`, e.sha);
392
+ return {
393
+ size: e.size,
394
+ // Pull-driven: a chunk is fetched only when the reader asks for one,
395
+ // and a cancelled download stops the blob read (review, 12 Nov 2026:
396
+ // the eager loop buffered whole files for slow or gone clients).
397
+ read: (range) => {
398
+ let reader = null;
399
+ return new ReadableStream({
400
+ async pull(c) {
401
+ try {
402
+ reader ??= (await blobs.get(key, range ? { range } : undefined)).getReader();
403
+ const { done, value } = await reader.read();
404
+ if (done)
405
+ c.close();
406
+ else
407
+ c.enqueue(value);
408
+ }
409
+ catch (err) {
410
+ c.error(err instanceof BlobNotFound ? new BlobMissing(`${agent}/${rel}`, e.sha) : err);
411
+ }
412
+ },
413
+ async cancel(reason) {
414
+ await reader?.cancel(reason).catch(() => { });
415
+ },
416
+ });
417
+ },
418
+ };
419
+ }
420
+ const file = runOutputPathOnVolume(tenant, workspace, runId, agent, rel);
421
+ if (!file)
422
+ return null;
423
+ const size = fs.statSync(file).size;
424
+ return {
425
+ size,
426
+ // Node's own bridge keeps the file stream paused until the reader pulls.
427
+ read: (range) => Readable.toWeb(fs.createReadStream(file, range ? { start: range.start, end: range.end } : undefined)),
428
+ };
429
+ }
430
+ /** The whole file as bytes (a small one: a test, a preview). */
431
+ export async function readRunOutput(tenant, workspace, runId, agent, rel) {
432
+ const o = await openRunOutput(tenant, workspace, runId, agent, rel);
433
+ if (!o)
434
+ return null;
435
+ const chunks = [];
436
+ const reader = o.read().getReader();
437
+ for (;;) {
438
+ const { done, value } = await reader.read();
439
+ if (done)
440
+ break;
441
+ chunks.push(Buffer.from(value));
442
+ }
443
+ return Buffer.concat(chunks);
444
+ }
445
+ // ------------------------------------------------------------------- lifecycle
446
+ /** A run is deleted: its records and their pins go. Throws when the store
447
+ * cannot be reached (deleteRun's caller retries in the background). */
448
+ export async function dropRunOutputs(tenant, workspace, runId) {
449
+ const b = backend;
450
+ if (!b)
451
+ return;
452
+ await releaseRecords(b, await b.store.drop({ tenant, workspace, runId }));
453
+ }
454
+ /** A workspace is deleted: every run's records of it. */
455
+ export async function dropWorkspaceOutputs(tenant, workspace) {
456
+ const b = backend;
457
+ if (!b)
458
+ return;
459
+ await releaseRecords(b, await b.store.drop({ tenant, workspace }));
460
+ }
461
+ /** An account is deleted. Its pins are released by dropTenantRevisions (all pins
462
+ * of the account); the records go here. */
463
+ export async function dropTenantOutputs(tenant) {
464
+ await backend?.store.drop({ tenant });
465
+ }
466
+ /** A workspace was renamed: the records follow (the pins are not keyed by
467
+ * it). What the new name held belonged to a workspace that no longer
468
+ * exists: those records go first, and their pins with them (the database
469
+ * store does both in its move too; the file store did not — review, 12 Nov
470
+ * 2026). */
471
+ export async function moveWorkspaceOutputs(tenant, from, to) {
472
+ const b = backend;
473
+ if (!b)
474
+ return;
475
+ await releaseRecords(b, await b.store.drop({ tenant, workspace: to }));
476
+ await b.store.move(tenant, from, to);
477
+ }
478
+ /** What a workspace's runs hold in the store, in bytes: counted with the run
479
+ * history on the usage statement, where the volume's `runs/` folder was. A
480
+ * store that cannot say, or cannot be reached, counts 0 (a statement must not fail). */
481
+ export function runOutputBytes(tenant, workspace) {
482
+ try {
483
+ return backend?.store.bytes?.(tenant, workspace) ?? 0;
484
+ }
485
+ catch (err) {
486
+ opsError("run_outputs.bytes_failed", err, { tenant, workspace }, "warn");
487
+ return 0;
488
+ }
489
+ }
490
+ const background = new Set();
491
+ /** Wait for the retries a sync caller started (tests, process end). */
492
+ export async function settleRunOutputs() {
493
+ while (background.size)
494
+ await Promise.allSettled([...background]);
495
+ }
496
+ /** deleteRun cannot wait: do it now, and on a failure try again 1, 2, 4, 8 s
497
+ * later, then say so (`run_outputs.drop_failed`; the blobs stay until a human looks). */
498
+ export function runDeleted(tenant, workspace, runId) {
499
+ if (!backend)
500
+ return;
501
+ const b = backend;
502
+ // The records dropped are kept across the retries: a release that fails
503
+ // after the drop must not leave the next try with nothing to release
504
+ // (review, 12 Nov 2026).
505
+ let dropped = null;
506
+ const p = (async () => {
507
+ for (let attempt = 0;; attempt++) {
508
+ try {
509
+ dropped ??= await b.store.drop({ tenant, workspace, runId });
510
+ return await releaseRecords(b, dropped);
511
+ }
512
+ catch (err) {
513
+ if (attempt >= 4)
514
+ return opsError("run_outputs.drop_failed", err, { tenant, workspace, run: runId });
515
+ await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt));
516
+ }
517
+ }
518
+ })();
519
+ const q = p.finally(() => background.delete(q));
520
+ background.add(q);
521
+ }
@@ -358,6 +358,7 @@ grantsOnly?: boolean): {
358
358
  timeoutSec: number;
359
359
  } | null;
360
360
  peers: boolean;
361
+ textTool: boolean;
361
362
  runtime: {
362
363
  log: string[];
363
364
  error: string | null;