@parcha/agentrun-serve 0.1.0-beta.48 → 0.1.0-beta.50

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 (170) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +236 -26
  3. package/dist/agent-delete.d.ts +36 -12
  4. package/dist/agent-delete.js +213 -30
  5. package/dist/agents-store.d.ts +6 -2
  6. package/dist/agents-store.js +18 -5
  7. package/dist/agents.d.ts +8 -1
  8. package/dist/agents.js +14 -4
  9. package/dist/answer-json.d.ts +2 -2
  10. package/dist/answer-json.js +3 -4
  11. package/dist/api-only.d.ts +7 -10
  12. package/dist/api-only.js +9 -11
  13. package/dist/archil-routes.d.ts +1 -1
  14. package/dist/archil-routes.js +4 -3
  15. package/dist/browser-sessions.d.ts +56 -0
  16. package/dist/browser-sessions.js +117 -0
  17. package/dist/compute-cost.d.ts +101 -0
  18. package/dist/compute-cost.js +250 -0
  19. package/dist/computer-routes.d.ts +4 -15
  20. package/dist/computer-routes.js +6 -10
  21. package/dist/console/assets/index-D0mr9wfZ.css +1 -0
  22. package/dist/console/assets/index-D7G6o-1E.js +720 -0
  23. package/dist/console/index.html +2 -2
  24. package/dist/errors.d.ts +4 -1
  25. package/dist/errors.js +15 -5
  26. package/dist/eval-previous.d.ts +52 -0
  27. package/dist/eval-previous.js +164 -0
  28. package/dist/file-types.d.ts +2 -0
  29. package/dist/file-types.js +3 -1
  30. package/dist/harness.js +2 -1
  31. package/dist/import.js +4 -3
  32. package/dist/learn/check.d.ts +16 -4
  33. package/dist/learn/check.js +30 -26
  34. package/dist/learn/promote.d.ts +7 -1
  35. package/dist/learn/promote.js +47 -0
  36. package/dist/learn/repick.d.ts +43 -0
  37. package/dist/learn/repick.js +202 -0
  38. package/dist/learn/workflow-draft.d.ts +4 -0
  39. package/dist/learn/workflow-draft.js +10 -7
  40. package/dist/learned-workflow.d.ts +2 -0
  41. package/dist/learned-workflow.js +19 -2
  42. package/dist/learning-setting.d.ts +13 -0
  43. package/dist/learning-setting.js +23 -1
  44. package/dist/llms.txt +1 -1
  45. package/dist/openapi.js +180 -14
  46. package/dist/paid-calls.d.ts +17 -7
  47. package/dist/paid-calls.js +15 -9
  48. package/dist/run-launch.d.ts +2 -2
  49. package/dist/run-launch.js +2 -1
  50. package/dist/run-learning-served.d.ts +1 -1
  51. package/dist/run-timeline-served.js +5 -3
  52. package/dist/run-usage.d.ts +125 -0
  53. package/dist/run-usage.js +394 -0
  54. package/dist/runner/adapter-loop.d.ts +4 -0
  55. package/dist/runner/adapter-loop.js +66 -21
  56. package/dist/runner/adapter-run-spec.d.ts +8 -3
  57. package/dist/runner/adapter-run-spec.js +13 -6
  58. package/dist/runner/big-writes.d.ts +33 -0
  59. package/dist/runner/big-writes.js +105 -0
  60. package/dist/runner/cli-run-spec.js +14 -6
  61. package/dist/runner/conformance/harness.d.ts +2 -0
  62. package/dist/runner/conformance/harness.js +18 -4
  63. package/dist/runner/feedback-round.d.ts +29 -1
  64. package/dist/runner/feedback-round.js +54 -3
  65. package/dist/runner/held.d.ts +4 -1
  66. package/dist/runner/journal-kinds.d.ts +3 -1
  67. package/dist/runner/learning-end.js +54 -18
  68. package/dist/runner/loop-contract.d.ts +3 -0
  69. package/dist/runner/metrics.d.ts +4 -0
  70. package/dist/runner/metrics.js +9 -0
  71. package/dist/runner/monid-run.js +2 -2
  72. package/dist/runner/promotion.js +8 -2
  73. package/dist/runner/reflect-hook.js +3 -2
  74. package/dist/runner/run-child-host.d.ts +15 -2
  75. package/dist/runner/run-child-host.js +24 -8
  76. package/dist/runner/run-child.js +3 -0
  77. package/dist/runner/save-slots.d.ts +9 -0
  78. package/dist/runner/save-slots.js +91 -0
  79. package/dist/runs-over-store.d.ts +3 -2
  80. package/dist/runs-over-store.js +9 -7
  81. package/dist/sdk/runs.d.ts +3 -4
  82. package/dist/sdk/runs.js +10 -7
  83. package/dist/sdk/runtimes.d.ts +19 -0
  84. package/dist/sdk/runtimes.js +23 -0
  85. package/dist/sdk/schema.d.ts +14 -8
  86. package/dist/sdk/schema.js +18 -6
  87. package/dist/server.d.ts +7 -3
  88. package/dist/server.js +223 -100
  89. package/dist/store/agent-body.d.ts +2 -3
  90. package/dist/store/agent-body.js +3 -2
  91. package/dist/store/index.d.ts +2 -2
  92. package/dist/store/index.js +1 -1
  93. package/dist/store/journal/storage.js +1 -1
  94. package/dist/store/open.d.ts +1 -1
  95. package/dist/store/open.js +1 -1
  96. package/dist/store/postgres/migrations/0021_purged.sql +13 -0
  97. package/dist/store/postgres/migrations/0022_computer_intervals.sql +27 -0
  98. package/dist/store/postgres/migrations/0023_computer_interval_resources.sql +14 -0
  99. package/dist/store/schema.d.ts +20 -1
  100. package/dist/store/schema.js +60 -5
  101. package/dist/store/sqlite/connection.d.ts +4 -1
  102. package/dist/store/sqlite/connection.js +5 -0
  103. package/dist/store/sqlite/run-patch.d.ts +8 -3
  104. package/dist/store/sqlite/run-patch.js +15 -7
  105. package/dist/store/sqlite/store.d.ts +2 -1
  106. package/dist/store/sqlite/store.js +279 -68
  107. package/dist/store/sqlite/worker.d.ts +9 -0
  108. package/dist/store/sqlite/worker.js +18 -1
  109. package/dist/store/store.d.ts +149 -9
  110. package/dist/store/store.js +63 -0
  111. package/dist/store-reads/analytics.js +2 -1
  112. package/dist/store-reads/cap.d.ts +17 -7
  113. package/dist/store-reads/cap.js +54 -4
  114. package/dist/store-reads/decisions.d.ts +21 -0
  115. package/dist/store-reads/decisions.js +22 -0
  116. package/dist/store-reads/journal.d.ts +8 -2
  117. package/dist/store-reads/journal.js +27 -8
  118. package/dist/store-reads/learning.d.ts +1 -1
  119. package/dist/store-reads/learning.js +5 -2
  120. package/dist/store-reads/runs.js +2 -0
  121. package/dist/store-reads/stats.js +4 -2
  122. package/dist/store-view.d.ts +12 -1
  123. package/dist/store-view.js +98 -38
  124. package/dist/template-eval.d.ts +15 -1
  125. package/dist/template-eval.js +92 -13
  126. package/dist/templates.d.ts +1 -1
  127. package/dist/templates.js +4 -3
  128. package/dist/timeline/labels.js +17 -0
  129. package/dist/tool-list.js +1 -0
  130. package/dist/tools.d.ts +6 -2
  131. package/dist/tools.js +22 -1
  132. package/dist/trigger-targets.d.ts +28 -9
  133. package/dist/trigger-targets.js +19 -16
  134. package/dist/triggers.d.ts +2 -1
  135. package/dist/triggers.js +5 -2
  136. package/dist/validate.d.ts +4 -2
  137. package/dist/validate.js +13 -3
  138. package/dist/viewer-credential.d.ts +3 -4
  139. package/dist/viewer-credential.js +6 -4
  140. package/dist/web-fake.d.ts +25 -0
  141. package/dist/web-fake.js +38 -1
  142. package/dist/web-save.d.ts +75 -0
  143. package/dist/web-save.js +235 -0
  144. package/dist/workspace/archil-claim.d.ts +5 -2
  145. package/dist/workspace/archil-claim.js +5 -2
  146. package/dist/workspace/archil-disk.d.ts +10 -1
  147. package/dist/workspace/archil-disk.js +19 -1
  148. package/dist/workspace/archil.d.ts +3 -0
  149. package/dist/workspace/archil.js +101 -16
  150. package/dist/workspace/computer-for-claim.d.ts +19 -1
  151. package/dist/workspace/computer-for-claim.js +88 -20
  152. package/dist/workspace/computer-intervals.d.ts +26 -0
  153. package/dist/workspace/computer-intervals.js +58 -0
  154. package/dist/workspace/computer-janitor.d.ts +7 -3
  155. package/dist/workspace/computer-janitor.js +14 -6
  156. package/dist/workspace/computer-kept.d.ts +7 -2
  157. package/dist/workspace/computer-kept.js +9 -2
  158. package/dist/workspace/pieced.d.ts +14 -0
  159. package/dist/workspace/pieced.js +23 -0
  160. package/dist/workspace/resolve-computer.d.ts +7 -4
  161. package/dist/workspace/resolve-computer.js +21 -32
  162. package/dist/workspace/run-disk.js +32 -12
  163. package/dist/workspace/run-end-computers.d.ts +1 -0
  164. package/dist/workspace/run-end-computers.js +4 -1
  165. package/dist/workspace/run-workspace.d.ts +1 -1
  166. package/dist/workspace/run-workspace.js +11 -6
  167. package/package.json +10 -10
  168. package/templates/README.md +36 -7
  169. package/dist/console/assets/index-CTGegcKt.css +0 -1
  170. package/dist/console/assets/index-D1Se6mgG.js +0 -715
@@ -15,6 +15,51 @@ import { RunFinal } from "../store/store.js";
15
15
  import { KINDS } from "./journal-kinds.js";
16
16
  import { commandRequest } from "./loop.js";
17
17
  export const FEEDBACK_ROUNDS = ["correction"];
18
+ const END_STATES = ["ended", "stopped", "failed"];
19
+ const OUTCOMES = ["completed", "escalated", "stopped", "cancelled"];
20
+ /** A kept end as a steer's body or a journal entry holds it, else undefined. */
21
+ function keptOf(value) {
22
+ const kept = value;
23
+ if (!kept || typeof kept !== "object" || !END_STATES.includes(kept.state) || typeof kept.endedAt !== "number")
24
+ return undefined;
25
+ if (kept.summary !== undefined && typeof kept.summary !== "string")
26
+ return undefined;
27
+ if (kept.outcome !== undefined && !OUTCOMES.includes(kept.outcome))
28
+ return undefined;
29
+ return { state: kept.state, ...(kept.summary !== undefined ? { summary: kept.summary } : {}), ...(kept.outcome !== undefined ? { outcome: kept.outcome } : {}), endedAt: kept.endedAt };
30
+ }
31
+ /** The end run `run` has now, as a grade's round keeps it: only one a round opens again (reopenableWhere: ended, or
32
+ * stopped by a person), with its end time. */
33
+ function keptEndOfRow(run) {
34
+ if (run.endedAt === null || !(run.state === "ended" || (run.state === "stopped" && run.outcome === "stopped")))
35
+ return undefined;
36
+ return { state: run.state, ...(run.summary !== null ? { summary: run.summary } : {}), ...(run.outcome !== null ? { outcome: run.outcome } : {}), endedAt: run.endedAt };
37
+ }
38
+ /** Whether the run's root `entries` hold a job's end kept for its look-back (KINDS.jobEnd) with no run end after it: the
39
+ * job ended and its look-back is under way, whether or not that look-back has asked anything yet. A follow-up's turn
40
+ * keeps none until its own job's end is kept, so a turn after the run's last end reads false. */
41
+ export function jobEndOpen(entries) {
42
+ return entries.findLastIndex((entry) => entry.kind === KINDS.jobEnd) > entries.findLastIndex((entry) => entry.kind === KINDS.end);
43
+ }
44
+ /** The end run's look-back keeps while it runs, from the run's root `entries` and its command rows, else undefined (no
45
+ * look-back under way, or one whose job's end was never kept):
46
+ * - the job's end its claim kept before the end-of-run step (KINDS.jobEnd, with its time), newer than the run's last end;
47
+ * - else the end a grade's round kept, from its FEEDBACK entry newer than the run's last end;
48
+ * - else from the round's steer the grade wrote, not taken yet (the run opened again, no runner on it yet).
49
+ * A follow-up's own turn keeps none until its job's end is kept: its run reads as going on, as main's does. */
50
+ export function keptEndOf(entries, commands) {
51
+ const last = (kind) => entries.findLastIndex((entry) => entry.kind === kind);
52
+ const end = last(KINDS.end);
53
+ if (jobEndOpen(entries)) {
54
+ const data = entries[last(KINDS.jobEnd)].data;
55
+ return keptOf(data?.end && data.endedAt !== undefined ? { ...data.end, endedAt: data.endedAt } : undefined);
56
+ }
57
+ const fed = last(KINDS.feedback);
58
+ if (fed > end)
59
+ return keptOf(entries[fed].data?.kept);
60
+ const steer = commands.find((command) => command.kind === "steer" && command.takenAt === null && command.refused === null && feedbackOf(command.body)?.kept !== undefined);
61
+ return steer ? feedbackOf(steer.body).kept : undefined;
62
+ }
18
63
  /** What a grade asks for: `correction` for a graded run the agent finished when the grade has words, else none
19
64
  * (undefined): a run its learned workflow answered alone opens none, right or wrong (its grade is kept). A replay run
20
65
  * is never graded. */
@@ -28,7 +73,8 @@ export function feedbackOf(body) {
28
73
  const text = body?.text;
29
74
  if (!fed || typeof fed !== "object" || !FEEDBACK_ROUNDS.includes(fed.round) || typeof fed.correct !== "boolean" || typeof text !== "string")
30
75
  return undefined;
31
- return { round: fed.round, correct: fed.correct, text };
76
+ const kept = keptOf(fed.kept);
77
+ return { round: fed.round, correct: fed.correct, text, ...(kept ? { kept } : {}) };
32
78
  }
33
79
  /** The feedback round the run's root `entries` say its next end closes: its newest FEEDBACK entry when no end came after
34
80
  * it, else undefined. */
@@ -88,9 +134,14 @@ export async function openFeedbackRound(store, grade, label, canTurn = () => tru
88
134
  // run's route (`canTurn` false), the grade is kept and the run is not opened again, never left to fail with no key.
89
135
  if (launch && !canTurn(launch))
90
136
  return null;
91
- const feedback = { round, correct: grade.correct };
137
+ // The run's end as the grade found it: the round keeps it (the run reads it while it looks back, and its end writes it
138
+ // again), and opens the run again only at that end (`endedAt`), never at a later one a message's turn wrote meanwhile.
139
+ const kept = keptEndOfRow(run);
140
+ if (!kept)
141
+ return null;
142
+ const feedback = { round, correct: grade.correct, kept };
92
143
  try {
93
- const steer = await store.runs.reopen(grade.run, { kind: "steer", body: { text: words, feedback } });
144
+ const steer = await store.runs.reopen(grade.run, { kind: "steer", body: { text: words, feedback } }, { endedAt: kept.endedAt });
94
145
  return { round, command: steer.id };
95
146
  }
96
147
  catch (error) {
@@ -7,6 +7,7 @@ import type { ApprovalPrice, ToolEffect } from "../tool-gate.js";
7
7
  import type { OpenedAccount } from "../email/account.js";
8
8
  import type { SavedCalendar } from "../calendar/address.js";
9
9
  import type { Workspace } from "../workspace/workspace.js";
10
+ import type { Pieces } from "../workspace/pieced.js";
10
11
  import type { GithubAppAccessAt } from "./github-app.js";
11
12
  import type { HarnessInstallEntry, HarnessPins } from "../harness-install.js";
12
13
  import type { RunModelKey } from "../store/seal.js";
@@ -111,9 +112,11 @@ export interface Held {
111
112
  install(name: string, signal?: AbortSignal): Promise<void>;
112
113
  /** The claim's computer (workspace/computer-for-claim.ts), made and held by the runner. */
113
114
  computer(ask: HeldComputerAsk): Promise<unknown>;
114
- /** A Mode 2 claim: the run's folder on its Archil disk, as the runner opens it; its mount credential's revoke. */
115
+ /** A Mode 2 claim: the run's folder on its Archil disk, as the runner opens it; its mount credential's revoke. `pieces`:
116
+ * the runner's pieced write on that Workspace (big-writes.ts), what a write bigger than a piece goes through. */
115
117
  archil(): Promise<{
116
118
  readonly workspace: Workspace;
119
+ readonly pieces?: Pieces;
117
120
  revoke(): Promise<void>;
118
121
  inherit(): Promise<void>;
119
122
  release(): Promise<void>;
@@ -343,10 +343,12 @@ export interface EndData {
343
343
  readonly review?: EndReview;
344
344
  }
345
345
  /** How a run's job's own turn ended (KINDS.jobEnd): the end it gives the run (its summary cut of every secret the runner
346
- * holds), and a CLI's error answer the end writes as its error row (`failedWith`). */
346
+ * holds), a CLI's error answer the end writes as its error row (`failedWith`), and the end's time (`endedAt`): the run
347
+ * reads that end while it looks back, and its end is written at that time (feedback-round.ts KeptEnd). */
347
348
  export interface JobEndData {
348
349
  readonly end: EndData;
349
350
  readonly failedWith?: string;
351
+ readonly endedAt?: number;
350
352
  }
351
353
  /** An escalated workflow run's review as its end keeps it: the escalation's kind, the escalate node's label (else the node
352
354
  * it escalated at), and its summary (else the run's). Served as the run's `review`, `at` its end. */
@@ -22,10 +22,12 @@ import { createHash } from "node:crypto";
22
22
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
23
23
  import { isMessageRow } from "../timeline/index.js";
24
24
  import { correctionRefused, learningCommit } from "../learn/commit.js";
25
- import { checkDraft, problemWords, unstorable } from "../learn/index.js";
25
+ import { CAPS, checkDraft, problemWords, unstorable } from "../learn/index.js";
26
+ import { repickSiteOf } from "../learn/check.js";
27
+ import { repickLabelOf, repickRewrite } from "../learn/repick.js";
26
28
  import { folderAt, readLearning, readSnapshot, runMergeOf, snapshotAt, textsAt } from "../learn/folder.js";
27
29
  import { completedRun, compileStoppedOf, lastOwnRuns, compileDue, compilePrompt, compileReference, COMPILE_TRACES, DRAFT_FAILED, heldNamesOf, newCompileAttempt } from "../learn/compile.js";
28
- import { loopOf } from "../learning-setting.js";
30
+ import { loopOf, repickOf } from "../learning-setting.js";
29
31
  import { CHECK_TEXT_MAX, promotionOf, promotionsOf, recordPromotion } from "../learn/promote.js";
30
32
  import { draftDecisionProviders, draftDryRun, draftFiles, draftMcpTools, unpricedCalls, WORKFLOWS_DIR } from "../learn/workflow-draft.js";
31
33
  import { DECISION_PROVIDER_KEYS } from "../tool-plane.js";
@@ -357,25 +359,50 @@ export async function checkDraftOf(deps, input) {
357
359
  }
358
360
  const { tools, gated, deniedBy, decisions, outputSchema, workflowAdapters, manifest } = await draftTools(deps, input.runId);
359
361
  const dsl = await import("@parcha/agentrun-dsl");
362
+ // The owner's learning.repick (learning-setting.ts), read as the draft is checked: a change reaches the workflows
363
+ // compiled after it, never one main already holds. An SDK bridge's runNode is its own (it picks every model and takes
364
+ // none of the compact state rule), so an SDK agent's drafts are never rewritten.
365
+ const repick = workflowAdapters === undefined ? repickOf(await learningOfRun(deps.store, input.runId)) : undefined;
360
366
  // A draft whose text on main has a status is a person's call (retired, or waiting for their OK): never changed.
361
367
  const kept = at.snapshot.workflows.filter((item) => item.status !== "active").map((item) => item.file);
362
- const changes = [changeOf(jsonPath, json), changeOf(readmePath, readme)];
363
- const check = (dryRuns) => checkDraft({
364
- changes, refuseValues: input.refuse, tools, dsl,
368
+ const check = (text, dryRuns) => checkDraft({
369
+ changes: [changeOf(jsonPath, text), changeOf(readmePath, readme)], refuseValues: input.refuse, tools, dsl,
365
370
  ...(Object.keys(gated).length ? { gated } : {}), ...(Object.keys(deniedBy).length ? { deniedBy } : {}), ...(decisions ? { decisions } : {}),
366
371
  ...(workflowAdapters !== undefined ? { workflowAdapters } : {}), ...(kept.length ? { kept } : {}), ...(dryRuns ? { dryRuns } : {}),
372
+ ...(repick?.repick ? { repick: true } : {}),
367
373
  });
368
- const statics = check();
369
- if (statics.length)
370
- return refused(statics);
371
- const ran = check({ [jsonPath]: await draftDryRun(dsl, json, example, outputSchema) });
372
- if (ran.length)
373
- return refused(ran);
374
- const files = [{ path: jsonPath, text: json }, { path: readmePath, text: readme }];
374
+ const checked = async (text) => {
375
+ const statics = check(text);
376
+ return statics.length ? statics : check(text, { [jsonPath]: await draftDryRun(dsl, text, example, outputSchema) });
377
+ };
378
+ const problems = await checked(json);
379
+ if (problems.length)
380
+ return refused(problems);
381
+ // With learning.repick on, what is committed is the draft with its answer's re-pick reading the run's pages on its
382
+ // second pass (learn/repick.ts), through the same checks and dry run, so the digest that serves is the doc the
383
+ // promotion check replays. A re-pick the rewrite does not reach, or a rewrite they refuse (one past CAPS.file even on
384
+ // one line), leaves the draft as compiled, which the log says (the latter by rule alone).
385
+ let text = json;
386
+ const doc = repick?.repick ? JSON.parse(json) : undefined;
387
+ const site = repickSiteOf(doc);
388
+ const rewritten = repick?.repick ? repickRewrite(doc, site, repick.repick_max_chars) : undefined;
389
+ if (site && repick?.repick && !rewritten)
390
+ deps.log?.(`learning.repick: workflow ${name} is kept as compiled: its re-pick ${JSON.stringify(repickLabelOf(site))} is not one the rewrite reaches`);
391
+ if (rewritten) {
392
+ const marked = workflowText(rewritten);
393
+ const again = marked === json ? [] : await checked(marked);
394
+ if (!again.length)
395
+ text = marked;
396
+ else
397
+ deps.log?.(`learning.repick: workflow ${name} is kept as compiled; its re-pick over the run's pages failed the checks (${[...new Set(again.map((problem) => problem.rule))].join(", ")})`);
398
+ }
399
+ if (text !== json && at.texts[jsonPath] === text && at.texts[readmePath] === readme)
400
+ return { errors: [] };
401
+ const files = [{ path: jsonPath, text }, { path: readmePath, text: readme }];
375
402
  return {
376
403
  errors: [],
377
- kept: { name, files, ...((await heldOf(deps.store, json, manifest)) ? { held: [readmePath] } : {}), ...(revised ? { bases: { [jsonPath]: revised.base, [readmePath]: revised.base } } : {}) },
378
- digest: workflowDigest({ workflow: json }),
404
+ kept: { name, files, ...((await heldOf(deps.store, text, manifest)) ? { held: [readmePath] } : {}), ...(revised ? { bases: { [jsonPath]: revised.base, [readmePath]: revised.base } } : {}) },
405
+ digest: workflowDigest({ workflow: text }),
379
406
  };
380
407
  }
381
408
  /** The backend manifest is data describing existing callbacks, not a server MCP connection. */
@@ -413,17 +440,26 @@ async function describedOf(tools, store) {
413
440
  }
414
441
  /** The most of an agent's kept learning, newest first, read for a held workflow's ask since its hold (compileAskOf). */
415
442
  const HELD_ASKED_READ = 200;
416
- /** The loop's numbers (learning-setting.ts loopOf) of the revision run `runId` runs: its definition's `learning`. */
417
- async function loopOfRun(store, runId) {
443
+ /** The definition's `learning` of the revision run `runId` runs; undefined when it can't be read. */
444
+ async function learningOfRun(store, runId) {
418
445
  try {
419
446
  const run = await store.runs.get(runId);
420
447
  const revision = run ? await store.agents.revision(run.revisionId) : undefined;
421
- return loopOf(revision?.body?.learning);
448
+ return revision?.body?.learning;
422
449
  }
423
450
  catch {
424
- return loopOf(undefined);
451
+ return undefined;
425
452
  }
426
453
  }
454
+ /** The loop's numbers (learning-setting.ts loopOf) of the revision run `runId` runs: its definition's `learning`. */
455
+ async function loopOfRun(store, runId) {
456
+ return loopOf(await learningOfRun(store, runId));
457
+ }
458
+ /** A rewritten workflow.json's text: indented as JSON.stringify indents, or on one line when only that fits CAPS.file. */
459
+ const workflowText = (doc) => {
460
+ const text = `${JSON.stringify(doc, null, 2)}\n`;
461
+ return Buffer.byteLength(text) <= CAPS.file ? text : `${JSON.stringify(doc)}\n`;
462
+ };
427
463
  /** Compile once: run `runId`'s compile turn whose drafts all failed their checks is the compile's attempt, kept as a
428
464
  * promotion record of the shape a check's stop has (runner/promotion.ts stopUnchecked): a hold with nothing checked,
429
465
  * its reason (DRAFT_FAILED) naming the failed checks. A first compile's earns the one recompile, as a check's hold
@@ -42,6 +42,9 @@ export type EndOfRunTurn = (input: {
42
42
  readonly claim: Claim;
43
43
  /** How the job ended. */
44
44
  readonly outcome: "completed" | "failed";
45
+ /** When the job's end was kept (the run's `ended_at`, kept before the step looks back), in epoch milliseconds: the
46
+ * time the job answered. Absent from a loop that keeps none. */
47
+ readonly endedAt?: number;
45
48
  /** The run was cut before it could look back: by a person's stop (`stopped`), by one during the end-of-run turn
46
49
  * (`stopped-looking`), or by a fault (`faulted`). The step must not call `ask`: it returns only what a cut run keeps. */
47
50
  readonly cut?: "stopped" | "stopped-looking" | "faulted";
@@ -61,6 +61,10 @@ export declare function storedBasisOf(metrics: unknown, usd: number | null | und
61
61
  * booking's. `side`: of the model requests, those booked as side calls (another model than the session's, or the host's
62
62
  * own, as a learned workflow's node is: the proxy's `side`/`host`), which no answer of a pi run carries. */
63
63
  export declare function bookedSpend(entries: readonly EntryLike[], which: "model" | "paid" | "decisions" | "side"): BookedSpend;
64
+ /** The run's decisions whose ids are in `ids` (each booked as `decision:<id>`), as bookedSpend reads its decisions, with
65
+ * every other decision left out: the ones a vendor charged as a paid call (store-reads/decisions.ts
66
+ * parallelChargedDecisions), which the run's tools figures count beside its paid tool calls. */
67
+ export declare function bookedDecisionsOf(entries: readonly EntryLike[], ids: ReadonlySet<string>): BookedSpend;
64
68
  /** A cost of charges as a usage row or a run's cost block says it (costsofar/1, cutathold/1), by the kernel's one rule
65
69
  * (costOfParts) over `parts`, its float noise rounded off (floatNoiseOff): `usd` their sum, `upper_bound` when it counts
66
70
  * a cut request at its hold, with `so_far_usd` the charges' own figures alone and `unpriced` how many it counts at their
@@ -148,6 +148,15 @@ export function bookedSpend(entries, which) {
148
148
  }
149
149
  return { usd: unpriced ? null : known + bounded, known, bounded, unpriced, atMost, requests, unmetered, models, tokens, priced: { reported, estimated }, ...(requests > 0 && free === requests ? { free: true } : {}) };
150
150
  }
151
+ /** The run's decisions whose ids are in `ids` (each booked as `decision:<id>`), as bookedSpend reads its decisions, with
152
+ * every other decision left out: the ones a vendor charged as a paid call (store-reads/decisions.ts
153
+ * parallelChargedDecisions), which the run's tools figures count beside its paid tool calls. */
154
+ export function bookedDecisionsOf(entries, ids) {
155
+ const turnOf = (e) => `${String(e.conversationId)}:${String(e.data?.turn)}`;
156
+ const named = (e) => e.data?.model;
157
+ const kept = new Set(entries.filter((e) => e.kind === RUNNER_RECORDS.request && typeof named(e) === "string" && named(e).startsWith("decision:") && ids.has(named(e).slice("decision:".length))).map(turnOf));
158
+ return bookedSpend(entries.filter((e) => !(e.kind === RUNNER_RECORDS.request || e.kind === RUNNER_RECORDS.turn) || kept.has(turnOf(e))), "decisions");
159
+ }
151
160
  /** A sum of charges with its float noise rounded off, nothing more (as the decisions row rounds, decision-rows.ts): a
152
161
  * decision costs millionths of a dollar, so a sum rounded to the millionth would lose it. */
153
162
  const floatNoiseOff = (usd) => Math.round(usd * 1e12) / 1e12;
@@ -44,7 +44,7 @@ export function monidForClaim(pin, env, work, runId, capped = () => false, fake)
44
44
  // left as a crash leaves it: the run is stopping or its claim is going.
45
45
  const estimated = async (ledger, callId, name, at, input, signal) => {
46
46
  const client = await clientOf();
47
- const step = await paidStep(ledger, callId, { name, holdUsd: 0, basis: READ_BASIS, by: "monid" }, () => client.run({ provider: at.provider, endpoint: `/${at.endpoint}`, input, maxCost: 0 }, signal), (outcome) => {
47
+ const step = await paidStep(ledger, callId, { name, holdUsd: 0, basis: READ_BASIS, by: "monid", reported: true }, () => client.run({ provider: at.provider, endpoint: `/${at.endpoint}`, input, maxCost: 0 }, signal), (outcome) => {
48
48
  if (!("result" in outcome))
49
49
  return null;
50
50
  const usd = chargeOf(outcome.result);
@@ -88,7 +88,7 @@ export function monidForClaim(pin, env, work, runId, capped = () => false, fake)
88
88
  /** One paid step for the call `callId` of `name` on the run's ledger `ledger`: held at `held.usd`, `send` run, settled at
89
89
  * what monid says it charged; a charge above the hold stops the run (overHold). */
90
90
  const paidCall = async (ledger, callId, name, held, send) => {
91
- const paid = await paidStep(ledger, callId, { name, holdUsd: held.usd, basis: held.basis, by: "monid" }, send, (outcome) => {
91
+ const paid = await paidStep(ledger, callId, { name, holdUsd: held.usd, basis: held.basis, by: "monid", reported: true }, send, (outcome) => {
92
92
  if (!("result" in outcome))
93
93
  return null;
94
94
  const usd = chargeOf(outcome.result);
@@ -3,7 +3,7 @@ import { loopOf } from "../learning-setting.js";
3
3
  import { LEARNED_WORKFLOW_TOOL } from "../learned-workflow.js";
4
4
  import { launchBody, readLaunchBody } from "../run-launch.js";
5
5
  import { uuidv7 } from "../runs-over-store.js";
6
- import { FINAL_STATES, RunFinal, StoreConstraint } from "../store/store.js";
6
+ import { FINAL_STATES, RunFinal, RunPurged, StoreConstraint } from "../store/store.js";
7
7
  import { openRunMcpAuth, sealRunMcpAuth } from "../store/seal.js";
8
8
  import { isCliRecord, piShaped, runEntries, runTimeline } from "../store-reads/journal.js";
9
9
  import { pinAnnotations, recordedCalls, replayCalls, SKIPPED_WRITE, toolClassOf, toolWord, unmarkedWords } from "../learn/replay-calls.js";
@@ -745,7 +745,9 @@ async function handedTo(deps, launch, id) {
745
745
  /** Starts the replay of `workflow` at `digest` on agent run `of` (its launch `from`) as run `id` (the id its reserved
746
746
  * record names), with the replay's chosen `launch` (replayLaunchOf: its run launch, revision and handed credentials,
747
747
  * handedTo), whichever claim creates it. False when a run by that id exists already: another claim created it (a
748
- * relaunch and the reserving claim at once), and it is left to that one. */
748
+ * relaunch and the reserving claim at once), and it is left to that one; false too when run `of` was purged since its
749
+ * launch was read (the store refuses it, RunPurged, nothing written): the replay never starts, counted so past its
750
+ * deadline. */
749
751
  async function startReplay(deps, workflow, digest, of, from, id, launch) {
750
752
  const { store, agentId } = deps;
751
753
  const base = readLaunchBody(launch.body);
@@ -760,6 +762,10 @@ async function startReplay(deps, workflow, digest, of, from, id, launch) {
760
762
  catch (error) {
761
763
  if (error instanceof StoreConstraint && (await store.runs.get(id)))
762
764
  return false;
765
+ if (error instanceof RunPurged) {
766
+ deps.log(`workflow-first: ${workflow.name} at ${digest}: the replay ${id} is not started: the run it replays was purged`);
767
+ return false;
768
+ }
763
769
  throw error;
764
770
  }
765
771
  }
@@ -33,8 +33,9 @@ export function createReflectHook(deps) {
33
33
  return undefined;
34
34
  const now = deps.now ?? Date.now;
35
35
  // When the job answered and what it cost: as the step starts, the run's spend so far is the job's. A compile turn an
36
- // earlier claim asked first (cut by a crash or a lost claim) reads that ask's, which it kept with its prompt.
37
- let answeredAt = new Date(now()).toISOString();
36
+ // earlier claim asked first (cut by a crash or a lost claim) reads that ask's, which it kept with its prompt. A run's
37
+ // first round answered when its job's end was kept (the run's end time), never after it.
38
+ let answeredAt = new Date(round === 1 && input.endedAt !== undefined ? input.endedAt : now()).toISOString();
38
39
  let job = facts.costUsd;
39
40
  const firstAsk = (kept) => {
40
41
  if (typeof kept?.answered_at !== "string" || (typeof kept.job_cost_usd !== "number" && kept.job_cost_usd !== null))
@@ -1,8 +1,12 @@
1
1
  import { type Stats } from "node:fs";
2
+ import type { Duplex } from "node:stream";
2
3
  import type { Workspace } from "../workspace/workspace.js";
3
4
  import { type AdapterSpecDeps } from "./adapter-run-spec.js";
4
5
  import type { Held } from "./held.js";
5
6
  import { type Claim, type LoopFactory } from "./loop-contract.js";
7
+ import { Channel } from "./run-channel.js";
8
+ import { type RunBigWrites } from "./big-writes.js";
9
+ import { type SaveSlots } from "../web-save.js";
6
10
  import { type RunLaunch } from "../run-launch.js";
7
11
  /** The image's helper that starts a run's process as its slot's uid (packages/serve/runas). */
8
12
  export declare const RUNAS_HELPER = "/usr/local/bin/agentrun-runas";
@@ -118,10 +122,11 @@ interface ClaimReads {
118
122
  readonly claimed: NodeJS.ProcessEnv;
119
123
  }
120
124
  /** Held (held.ts) for one claim, on the runner: each answer the claim's own, read with the runner's seal key from the
121
- * runner's own reads of the claim; every argument from the run's process is checked or ignored. */
125
+ * runner's own reads of the claim; every argument from the run's process is checked or ignored. `bigs`: the run's pieced
126
+ * writes (big-writes.ts), let go at the claim's release and, by the caller, when the run's channel ends. */
122
127
  export declare function heldFor(deps: AdapterSpecDeps & {
123
128
  readonly sealKey: Buffer;
124
- }, reads: ClaimReads, cut: (text: string) => string, log: (line: string) => void): {
129
+ }, reads: ClaimReads, cut: (text: string) => string, log: (line: string) => void, bigs?: RunBigWrites): {
125
130
  held: Held;
126
131
  inputs(): Promise<void>;
127
132
  release(): Promise<void>;
@@ -166,4 +171,12 @@ export declare function staysInRunner(deps: Pick<AdapterSpecDeps, "store" | "dat
166
171
  /** The runner's loop factory where each run is a process of its own: a ChildLoop per claim, but for a run that stays in
167
172
  * the runner (staysInRunner). */
168
173
  export declare function childLoops(options: ChildLoopsOptions): LoopFactory;
174
+ /** The runner's side of a run's channel over `socket`. Each call of the run's process runs inside the ledger of the tool
175
+ * call it was made in (paid-calls.ts). web_save's slots are `gate`, this runner's one (save-slots.ts); the channel's end
176
+ * (the run's end, or its process gone) gives back every slot the run held or waited for, and lets go of every pieced write
177
+ * of the run's `bigs` (big-writes.ts), held or waiting. `maxFrame`: the channel's (a test's), default MAX_FRAME. */
178
+ export declare function runChannel(socket: Duplex, onClose: (why: Error) => void, gate?: SaveSlots, more?: {
179
+ readonly bigs?: RunBigWrites;
180
+ readonly maxFrame?: number;
181
+ }): Channel;
169
182
  export {};
@@ -66,6 +66,9 @@ import { heardComputerHold } from "./computer-journal.js";
66
66
  import { ClaimRefused } from "./loop-contract.js";
67
67
  import { Channel, ChannelClosed } from "./run-channel.js";
68
68
  import { registerRunErrors } from "./run-errors.js";
69
+ import { exposeSaveSlots } from "./save-slots.js";
70
+ import { runBigWrites } from "./big-writes.js";
71
+ import { SERVER_SLOTS } from "../web-save.js";
69
72
  import { readLaunchBody } from "../run-launch.js";
70
73
  import { SUBAGENT_TOOL } from "./subagent.js";
71
74
  /** The image's helper that starts a run's process as its slot's uid (packages/serve/runas). */
@@ -627,14 +630,15 @@ async function readOf(reads, method, args) {
627
630
  /** The email tools a revision may grant. */
628
631
  const grantsEmail = (granted) => granted.some((tool) => tool.startsWith("email_"));
629
632
  /** Held (held.ts) for one claim, on the runner: each answer the claim's own, read with the runner's seal key from the
630
- * runner's own reads of the claim; every argument from the run's process is checked or ignored. */
631
- export function heldFor(deps, reads, cut, log) {
633
+ * runner's own reads of the claim; every argument from the run's process is checked or ignored. `bigs`: the run's pieced
634
+ * writes (big-writes.ts), let go at the claim's release and, by the caller, when the run's channel ends. */
635
+ export function heldFor(deps, reads, cut, log, bigs = runBigWrites()) {
632
636
  const { claim, run, launch, revision, claimed } = reads;
633
637
  const sealKey = deps.sealKey;
634
638
  const store = deps.store;
635
639
  const granted = revision.body.tools ?? [];
636
640
  const keys = { store, sealKey, env: deps.env };
637
- const releases = [];
641
+ const releases = [() => bigs.close()];
638
642
  const fromGitHub = launch.inputOrigin?.kind === "trigger" && launch.inputOrigin.source === "github";
639
643
  const github = () => githubAppAccess(store, sealKey, launch.input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub, ...(launch.repo !== undefined ? { repo: launch.repo } : {}) });
640
644
  /** Mode 2's Archil claim, made once for the claim on the runner, its folder the run's. */
@@ -643,7 +647,7 @@ export function heldFor(deps, reads, cut, log) {
643
647
  const settings = await loadArchilSettings(store, deps.env);
644
648
  if (settings === undefined)
645
649
  return undefined;
646
- const made = await archilClaim({ settings, keys: store.sealedKeys, sealKey, signal: new AbortController().signal, env: deps.env, mount: { runId: claim.runId, epoch: claim.epoch, ttlMs: MOUNT_TTL_MS, ...(deps.mountControl ?? {}) }, run: { agentId: run.agentId, ...(launch.archilDisk ? { launch: launch.archilDisk } : {}), store }, ...(deps.makeArchilDisk ? { makeDisk: deps.makeArchilDisk } : {}) });
650
+ const made = await archilClaim({ settings, keys: store.sealedKeys, sealKey, signal: new AbortController().signal, env: deps.env, mount: { runId: claim.runId, epoch: claim.epoch, ttlMs: MOUNT_TTL_MS }, ...(deps.mountControl ? { control: deps.mountControl } : {}), run: { agentId: run.agentId, ...(launch.archilDisk ? { launch: launch.archilDisk } : {}), store }, ...(deps.makeArchilDisk ? { makeDisk: deps.makeArchilDisk } : {}) });
647
651
  releases.push(() => made.release());
648
652
  return made;
649
653
  })());
@@ -798,7 +802,8 @@ export function heldFor(deps, reads, cut, log) {
798
802
  return undefined;
799
803
  const ws = await openRunWorkspace({ mode: 2, agentId: run.agentId, runId: claim.runId, archil: made, log });
800
804
  releases.push(() => ws.end());
801
- return { workspace: ws.workspace, revoke: () => made.revoke(), inherit: async () => made.inherit(), release: async () => { } };
805
+ // A write bigger than the channel's frame is pulled in pieces and written here, on this Workspace (big-writes.ts).
806
+ return { workspace: ws.workspace, pieces: bigs.pieces(ws.workspace), revoke: () => made.revoke(), inherit: async () => made.inherit(), release: async () => { } };
802
807
  },
803
808
  endOfRun: async (input) => {
804
809
  // The step as the run's spec builds it in a runner (adapter-run-spec.ts), over the runner's reads of the claim: what
@@ -1009,6 +1014,16 @@ function childEnv(base, keys, extra) {
1009
1014
  delete env[name];
1010
1015
  return { ...env, ...extra, [SECRETS_FD_ENV]: "3", [SECRETS_LEN_ENV]: String(keys.length) };
1011
1016
  }
1017
+ /** The runner's side of a run's channel over `socket`. Each call of the run's process runs inside the ledger of the tool
1018
+ * call it was made in (paid-calls.ts). web_save's slots are `gate`, this runner's one (save-slots.ts); the channel's end
1019
+ * (the run's end, or its process gone) gives back every slot the run held or waited for, and lets go of every pieced write
1020
+ * of the run's `bigs` (big-writes.ts), held or waiting. `maxFrame`: the channel's (a test's), default MAX_FRAME. */
1021
+ export function runChannel(socket, onClose, gate = SERVER_SLOTS, more = {}) {
1022
+ let saves;
1023
+ const channel = new Channel(socket, { onClose: (why) => { onClose(why); saves?.(); more.bigs?.close(); }, within: withinCarried, ...(more.maxFrame ? { maxFrame: more.maxFrame } : {}) });
1024
+ saves = exposeSaveSlots(channel, gate);
1025
+ return channel;
1026
+ }
1012
1027
  function childLoop(options, slots, loopDeps) {
1013
1028
  const { deps, isolation } = options;
1014
1029
  const cut = loopDeps.redact ?? ((text) => text);
@@ -1120,7 +1135,9 @@ function childLoop(options, slots, loopDeps) {
1120
1135
  if (isolation.kind === "uid" && slot !== undefined)
1121
1136
  hold = new SlotHold(slot, isolation.helper, log);
1122
1137
  const tops = runTops(deps.data, runRow.agentId, claim.runId);
1123
- const heldSide = heldFor({ ...deps, env: claimEnv }, { claim, run: runRow, launch, revision, claimed: gatewayKey ? withGatewayKey(claimed, gatewayKey) : claimed }, cut, log);
1138
+ // The run's pieced writes (big-writes.ts): let go when its channel ends, or at the claim's release.
1139
+ const bigs = runBigWrites();
1140
+ const heldSide = heldFor({ ...deps, env: claimEnv }, { claim, run: runRow, launch, revision, claimed: gatewayKey ? withGatewayKey(claimed, gatewayKey) : claimed }, cut, log, bigs);
1124
1141
  try {
1125
1142
  let extra = {};
1126
1143
  let argv = [...(options.argv ?? childArgv())];
@@ -1151,8 +1168,7 @@ function childLoop(options, slots, loopDeps) {
1151
1168
  keyPipe.end(keys);
1152
1169
  const socket = child.stdio[4];
1153
1170
  let broke;
1154
- // Each call of the run's process runs inside the ledger of the tool call it was made in (paid-calls.ts).
1155
- channel = new Channel(socket, { onClose: (why) => void (broke ??= why), within: withinCarried });
1171
+ channel = runChannel(socket, (why) => void (broke ??= why), SERVER_SLOTS, { bigs });
1156
1172
  const bound = { claim, agentId: runRow.agentId, revisionId: runRow.revisionId };
1157
1173
  channel.expose("store", (method, args) => storeCall(deps.store, method, args, bound, log));
1158
1174
  channel.expose("journal", journalTarget(loopDeps.journal(claim), cut));
@@ -16,6 +16,7 @@ import { routeOf } from "./model-route.js";
16
16
  import { heldRedactor, processSecretRedactor } from "./redact.js";
17
17
  import { Channel } from "./run-channel.js";
18
18
  import { registerRunErrors } from "./run-errors.js";
19
+ import { remoteSaveSlots } from "./save-slots.js";
19
20
  import { runEnv } from "./main.js";
20
21
  import { carriedLedger } from "../paid-calls.js";
21
22
  import { heldHands } from "../workspace/computer-hold.js";
@@ -179,6 +180,8 @@ function childDeps(init, store, journal, held) {
179
180
  computerForClaim,
180
181
  computerDeps: {},
181
182
  installForClaim: heldInstall,
183
+ // web_save's download slots are the runner's, shared by all its runs (save-slots.ts).
184
+ saveSlots: remoteSaveSlots(channel),
182
185
  ...(init.githubApi ? { githubApi: init.githubApi } : {}),
183
186
  ...(init.githubWeb ? { githubWeb: init.githubWeb } : {}),
184
187
  ...(init.githubMcpOrigin ? { githubMcpOrigin: init.githubMcpOrigin } : {}),
@@ -0,0 +1,9 @@
1
+ import { type Channel } from "./run-channel.js";
2
+ import { type SaveSlots } from "../web-save.js";
3
+ /** The most takes one run may have held or waiting at once: a run's waiters live in the runner, so a run may not queue
4
+ * without bound. */
5
+ export declare const SAVE_SLOTS_PER_RUN = 16;
6
+ /** Exposes `gate` on the runner's side of a run's `channel`. Answers what the runner calls when that channel ends. */
7
+ export declare function exposeSaveSlots(channel: Pick<Channel, "expose">, gate: SaveSlots): () => void;
8
+ /** A run process's web_save slots: its runner's gate, taken over `channel`. */
9
+ export declare function remoteSaveSlots(channel: Pick<Channel, "call">): SaveSlots;
@@ -0,0 +1,91 @@
1
+ // web_save's download slots (web-save.ts saveSlots) across a runner's runs. Each run runs in a process of its own
2
+ // (run-child-host.ts), so a gate in that process would be one per run. The bound is per runner, the process that holds
3
+ // the claims: its one gate (web-save.ts SERVER_SLOTS) is exposed on each run's channel, and a run's web_save takes its
4
+ // slots there. The run's process is untrusted: a release frees only its own take's slot, once, and every slot a run
5
+ // holds or waits for is let go when its channel ends (its process crashed, was killed, or its run ended).
6
+ import { ClaimRefused } from "./loop-contract.js";
7
+ import { ChannelClosed } from "./run-channel.js";
8
+ import { SAVE_CONCURRENCY } from "../web-save.js";
9
+ const TARGET = "saves";
10
+ /** The most takes one run may have held or waiting at once: a run's waiters live in the runner, so a run may not queue
11
+ * without bound. */
12
+ export const SAVE_SLOTS_PER_RUN = 16;
13
+ /** Exposes `gate` on the runner's side of a run's `channel`. Answers what the runner calls when that channel ends. */
14
+ export function exposeSaveSlots(channel, gate) {
15
+ const held = new Set();
16
+ const waits = new Set();
17
+ let closed = false;
18
+ channel.expose(TARGET, async (method, args) => {
19
+ if (method !== "take")
20
+ throw new ClaimRefused(`the runner has no ${method} for a run's download slots`);
21
+ const [signal] = args;
22
+ if (!(signal instanceof AbortSignal))
23
+ throw new TypeError("a download slot is taken under the call's signal");
24
+ if (closed)
25
+ throw new ChannelClosed("the run's channel ended");
26
+ if (held.size + waits.size >= SAVE_SLOTS_PER_RUN)
27
+ throw new ClaimRefused(`this run already has ${SAVE_SLOTS_PER_RUN} web_save downloads held or waiting`);
28
+ const left = new AbortController();
29
+ waits.add(left);
30
+ let release;
31
+ try {
32
+ release = await gate.take(AbortSignal.any([signal, left.signal]));
33
+ }
34
+ finally {
35
+ waits.delete(left);
36
+ }
37
+ // Granted as the channel ended: no answer reaches the run, so the slot goes back now.
38
+ if (closed) {
39
+ release();
40
+ throw new ChannelClosed("the run's channel ended");
41
+ }
42
+ held.add(release);
43
+ // The gate's release is once only: a second call frees nothing.
44
+ return () => {
45
+ held.delete(release);
46
+ release();
47
+ };
48
+ });
49
+ return () => {
50
+ if (closed)
51
+ return;
52
+ closed = true;
53
+ for (const wait of waits)
54
+ wait.abort(new ChannelClosed("the run's channel ended"));
55
+ for (const release of held)
56
+ release();
57
+ held.clear();
58
+ };
59
+ }
60
+ /** A run process's web_save slots: its runner's gate, taken over `channel`. */
61
+ export function remoteSaveSlots(channel) {
62
+ let busy = 0;
63
+ let waiting = 0;
64
+ return {
65
+ size: SAVE_CONCURRENCY,
66
+ get busy() { return busy; },
67
+ get waiting() { return waiting; },
68
+ async take(signal) {
69
+ waiting++;
70
+ let release;
71
+ try {
72
+ release = await channel.call(TARGET, "take", [signal]);
73
+ }
74
+ finally {
75
+ waiting--;
76
+ }
77
+ if (typeof release !== "function")
78
+ throw new TypeError("the runner answered no release for a download slot");
79
+ busy++;
80
+ let done = false;
81
+ return () => {
82
+ if (done)
83
+ return;
84
+ done = true;
85
+ busy--;
86
+ // A release that cannot cross (the channel ended) is no loss: the runner frees the slot when the channel ends.
87
+ Promise.resolve(release()).catch(() => { });
88
+ };
89
+ },
90
+ };
91
+ }
@@ -24,8 +24,9 @@ export declare const WAITS_ON_A_PERSON = "The run is waiting on a person.";
24
24
  export declare function archiveRun(store: RunsStore, runId: string, archived: boolean): Promise<void>;
25
25
  /** Stops the run: one stop command row, which the run's runner reads and applies (it aborts the turn in flight, withdraws a
26
26
  * tool call waiting for approval, and ends the run stopped). A stop always lands — one command, no second path. An imported
27
- * or already-ended run has none to stop: `false`, nothing written (store.command refuses a final run, RunFinal). */
28
- export declare function stop(store: RunsStore, runId: string): Promise<boolean>;
27
+ * run, or one that reads ended (`moment.terminal`: one looking back after its job's end among them, whose end its
28
+ * look-back never undoes), has none to stop: `false`, nothing written (and store.command refuses a final run, RunFinal). */
29
+ export declare function stop(store: RunsStore, moment: RunMoment): Promise<boolean>;
29
30
  /** Cancels the run: one cancel command row, which the run's runner reads and applies (it ends the run cancelled, aborting
30
31
  * the turn in flight and cancelling a tool call waiting for approval). Returns whether a cancel was requested — the old
31
32
  * cancel's checks and their result, verbatim: an imported run, or one already ended or ending, has none to cancel (false,