@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
@@ -53,7 +53,7 @@ import { answerAsServed } from "../answer-json.js";
53
53
  import { reserveFor, stepAndAnswerFor, wrappingUp, wrapUpText } from "../wrap-up.js";
54
54
  import { LEARNED_CARD_FIELDS, LEARNED_CLIP, LEARNED_WORKFLOW_TOOL, learnedApprovedTools } from "../learned-workflow.js";
55
55
  import { warnHoldShort } from "../print.js";
56
- import { feedbackAsk, feedbackOf, pendingFeedbackOf } from "./feedback-round.js";
56
+ import { feedbackAsk, feedbackOf, jobEndOpen, pendingFeedbackOf } from "./feedback-round.js";
57
57
  import { handbackText, servedAnswerOf, servedAnswerText, WORKFLOW_FIRST, WORKFLOW_FIRST_CALL } from "./workflow-first.js";
58
58
  /** The end of a harness's own call (Claude Code's WebSearch) the gate held and then let run: the host ran nothing of it,
59
59
  * and the harness's next call runs it. */
@@ -1391,7 +1391,15 @@ function adapterLoop(specOf, options, deps) {
1391
1391
  const decisionsOf = () => (decisionsOpen ??= sessions.open(DECISION_SESSION).then((w) => theCap().decisions(w, flushed)).then((d) => (decisionsReady = d)));
1392
1392
  let paidReady;
1393
1393
  let paidOpen;
1394
- const paidOf = () => (paidOpen ??= sessions.open(TOOL_SESSION).then((w) => theCap().tools(w, flushed)).then((p) => (paidReady = p)));
1394
+ // The run's cap is its spec's (theCap): a paid step asked while the spec is still built (a computer's time, metered
1395
+ // from its create, compute-cost.ts) waits for it, and fails as the spec's build does. `capJudges` says whether it
1396
+ // can judge now, so a caller inside the build never waits on itself.
1397
+ let capJudges = false;
1398
+ let specBuilt;
1399
+ let specFailed;
1400
+ const specSet = new Promise((resolve, reject) => ((specBuilt = resolve), (specFailed = reject)));
1401
+ specSet.catch(() => undefined);
1402
+ const paidOf = () => (paidOpen ??= specSet.then(() => sessions.open(TOOL_SESSION)).then((w) => theCap().tools(w, flushed)).then((p) => (paidReady = p)));
1395
1403
  /** The pause of a paid call the cap refused (ledger.pause), set once the claim's booking is: below. */
1396
1404
  let pauseFor;
1397
1405
  const ledger = {
@@ -1414,6 +1422,7 @@ function adapterLoop(specOf, options, deps) {
1414
1422
  await pauseFor?.(refusal);
1415
1423
  },
1416
1424
  flush: () => deps.flush(),
1425
+ judges: () => capJudges,
1417
1426
  };
1418
1427
  // A phase of the host's, on the run's timeline while its step runs. Said before the root exists (the claim's computer
1419
1428
  // waiting on its image build, inside specOf), it makes the root then, the row in its creating commit (above), so a
@@ -1455,6 +1464,8 @@ function adapterLoop(specOf, options, deps) {
1455
1464
  spec = await specOf(claim, runOf);
1456
1465
  }
1457
1466
  catch (error) {
1467
+ // A paid step that waited on the spec (paidOf) fails with it: nothing was booked.
1468
+ specFailed(error);
1458
1469
  if (error instanceof Fenced)
1459
1470
  return await interrupted("its claim was lost while its MCP credentials were made fresh");
1460
1471
  if (error instanceof McpClaimRefused)
@@ -1479,6 +1490,9 @@ function adapterLoop(specOf, options, deps) {
1479
1490
  mcp = spec.mcp;
1480
1491
  specNow = spec;
1481
1492
  specKnown = true;
1493
+ // The run's cap can judge from here: a paid step that waited on the spec goes on.
1494
+ capJudges = true;
1495
+ specBuilt();
1482
1496
  // The spec's resources are the pass's from here: a claim lost in any write below still lets them go (closeSession).
1483
1497
  releaseNow = spec.release;
1484
1498
  // A root a phase made while the spec was built (on this claim or an earlier one lost before this point) took none
@@ -2302,7 +2316,14 @@ function adapterLoop(specOf, options, deps) {
2302
2316
  // CLI's look-back has no submission until it ends: its record's lookingBack, below). Read before the session
2303
2317
  // opens, so its first request is already learning's.
2304
2318
  const lookingBackOpen = (await harness.inspect(context)).submissions.filter((one) => one.type === "input" && Number(one.conversationId) === Number(ROOT_CONVERSATION_ID)).at(-1)?.requestId?.startsWith(REFLECT_PREFIX) === true;
2305
- reflecting = lookingBackOpen;
2319
+ // The job's end an earlier claim kept for its look-back, with no run end after it (feedback-round.ts jobEndOpen):
2320
+ // its runner was lost after keeping it, maybe before the look-back's first ask (no input in flight then). The job
2321
+ // ended there too: this pass runs no job turn, and the run ends on that end at its time (jobEndKept), never on one
2322
+ // worked out again now, which would move the end every reader served. A follow-up's turn after the run's last end
2323
+ // has kept none, so it is never taken for one.
2324
+ const rootFound = await harness.conversation(ROOT_CONVERSATION_ID, context);
2325
+ const jobKept = rootFound ? jobEndOpen(await entriesOf(gate.journal, rootFound.id, context)) : false;
2326
+ reflecting = lookingBackOpen || jobKept;
2306
2327
  // The MCP tools are host tools like any other (mcp.tools, wrapped above): every harness gets them on its own channel
2307
2328
  // for host tools, each call through the gate before its intent.
2308
2329
  session = await spec.adapter.open({ ...spec.session, tools, deferCatalog: deferred }, io);
@@ -2662,7 +2683,8 @@ function adapterLoop(specOf, options, deps) {
2662
2683
  }, context);
2663
2684
  }
2664
2685
  }
2665
- if (firstToServe && !followedUp && !firstUnplaced && session.state === "new") {
2686
+ // Never again for a job whose end is kept (jobKept): what the workflow did is in that end.
2687
+ if (firstToServe && !followedUp && !firstUnplaced && !jobKept && session.state === "new") {
2666
2688
  let release;
2667
2689
  servingFirst = new Promise((resolve) => (release = resolve));
2668
2690
  try {
@@ -2700,9 +2722,10 @@ function adapterLoop(specOf, options, deps) {
2700
2722
  }
2701
2723
  }
2702
2724
  const placed = served !== undefined || followedUp || (session.state !== "idle" && !firstUnplaced);
2703
- // The end-of-run turn found open (lookingBackOpen), with no turn of this claim's sent before it: never recovered as
2704
- // the job's; the run goes to its end-of-run step, on the job's end the claim that asked it kept (jobEndKept).
2705
- const lookingBack = lookingBackOpen && !followedUp && served === undefined;
2725
+ // The end-of-run turn found open (lookingBackOpen), or the job's end found kept before that turn's first ask
2726
+ // (jobKept), with no turn of this claim's sent before it: never recovered as the job's; the run goes to its
2727
+ // end-of-run step, on the job's end the claim that kept it kept (jobEndKept).
2728
+ const lookingBack = (lookingBackOpen || jobKept) && !followedUp && served === undefined;
2706
2729
  if (served || followedUp || firstUnplaced || lookingBack) {
2707
2730
  // The workflow answered, or handed back and its handback is the turn; the follow-up is the turn this claim runs,
2708
2731
  // or there is none.
@@ -2733,8 +2756,16 @@ function adapterLoop(specOf, options, deps) {
2733
2756
  let parkOn;
2734
2757
  /** The ask_person call the run waits on in its claim, while it does. */
2735
2758
  let waitingOn;
2759
+ /** When the job's end was, once it is kept (keepJobEnd): the look-back after it never moves it, and its end is
2760
+ * written at that time. A grade's round keeps the end the run had when the grade opened it (feedbackNow.kept). */
2761
+ let keptAt;
2736
2762
  if (alone && lookingBack)
2737
- ({ end: data, failedWith } = await jobEndKept(root));
2763
+ ({ end: data, failedWith, endedAt: keptAt } = await jobEndKept(root));
2764
+ else if (alone && feedbackNow?.kept) {
2765
+ const { endedAt, ...end } = feedbackNow.kept;
2766
+ data = end;
2767
+ keptAt = endedAt;
2768
+ }
2738
2769
  else if (alone)
2739
2770
  data = { state: "ended" };
2740
2771
  else
@@ -2969,14 +3000,19 @@ function adapterLoop(specOf, options, deps) {
2969
3000
  // The run's status is how its job's own turn ended (`data`), whatever the step spends after it: learning spend that
2970
3001
  // takes the run past its cap is the learning's (askEndOfRun reads overCap after each of its turns), never the run's.
2971
3002
  // That end is kept before the step's first ask, so a claim that finds its turn open ends the run on it (jobEndKept).
3003
+ // Kept with its time: from then on every reader serves it, and the run's end is written at it (writeEnd `keptAt`).
2972
3004
  if (!lookingBack)
2973
- await keepJobEnd(harness, root, spec, data, failedWith);
2974
- const step = await endOfRunStep(claim, spec, data.state === "failed" ? "failed" : "completed", overCap);
3005
+ keptAt = await keepJobEnd(harness, root, spec, data, failedWith, keptAt);
3006
+ const step = await endOfRunStep(claim, spec, data.state === "failed" ? "failed" : "completed", overCap, keptAt);
3007
+ // A stop or cancel the runner took during the step (one that raced the read refusing it, its row written while the
3008
+ // run still read as going on) cuts the look-back alone: the run ends on its job's end, the row taken by that end.
3009
+ if (step.kind === "stopped" && keptAt !== undefined)
3010
+ return await writeEnd(harness, root, gate, data, [step.commandId], await cutRows(claim, spec, "stopped-looking"), failedWith, keptAt);
2975
3011
  if (step.kind === "stopped")
2976
3012
  return await writeEnd(harness, root, gate, stopEnd(stopReason?.kind === "command" ? stopReason.cancel : undefined), [step.commandId], await cutRows(claim, spec, "stopped-looking"));
2977
3013
  if (step.kind === "interrupted")
2978
3014
  return await interrupted(stopReason?.kind ?? "its claim's signal aborted");
2979
- return await writeEnd(harness, root, gate, data, [], step.also, failedWith);
3015
+ return await writeEnd(harness, root, gate, data, [], step.also, failedWith, keptAt);
2980
3016
  }
2981
3017
  }
2982
3018
  catch (error) {
@@ -3361,13 +3397,16 @@ function adapterLoop(specOf, options, deps) {
3361
3397
  }
3362
3398
  /** How the job's own turn ended (`data`, and a CLI's error answer `failedWith`), as this claim decided it, kept on the
3363
3399
  * root before the end-of-run step asks its first turn (KINDS.jobEnd), for a run with a step to ask (stepOf). Its
3364
- * summary is cut of every secret the runner holds, as every summary is when served. */
3365
- async function keepJobEnd(on, conversation, spec, data, failedWith) {
3400
+ * summary is cut of every secret the runner holds, as every summary is when served. Kept with its time, `at` (a grade's
3401
+ * round keeps the end it found) or now, which it answers; with no step to ask, nothing is kept and `at` comes back. */
3402
+ async function keepJobEnd(on, conversation, spec, data, failedWith, at) {
3366
3403
  if (!stepOf(spec))
3367
- return;
3404
+ return at;
3368
3405
  const end = data.summary !== undefined && deps.redact ? { ...data, summary: deps.redact(data.summary) } : data;
3369
- const kept = { end, ...(failedWith !== undefined ? { failedWith } : {}) };
3406
+ const endedAt = at ?? now();
3407
+ const kept = { end, ...(failedWith !== undefined ? { failedWith } : {}), endedAt };
3370
3408
  await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.jobEnd, data: kept }), context);
3409
+ return endedAt;
3371
3410
  }
3372
3411
  /** The job's end for a claim that found the end-of-run turn open (lookingBackOpen): the newest keepJobEnd kept (a
3373
3412
  * follow-up's round keeps its own), never worked out again. */
@@ -3537,7 +3576,7 @@ function adapterLoop(specOf, options, deps) {
3537
3576
  * came during it; `interrupted` when the claim was lost or the runner is closing (no end is written, and the next claim
3538
3577
  * asks it again). A step that throws on its own writes the end without rows: the run's end never waits on it. `over`:
3539
3578
  * the claim's overCap, read after each turn the step asks (askEndOfRun). */
3540
- async function endOfRunStep(claim, spec, outcome, over) {
3579
+ async function endOfRunStep(claim, spec, outcome, over, endedAt) {
3541
3580
  const cut = () => {
3542
3581
  if (stopReason?.kind === "command")
3543
3582
  return { kind: "stopped", commandId: stopReason.commandId };
@@ -3559,7 +3598,7 @@ function adapterLoop(specOf, options, deps) {
3559
3598
  void harness?.closed.then(() => closed.abort(new Error("the Session closed")), () => closed.abort(new Error("the Session closed")));
3560
3599
  const signal = AbortSignal.any([deps.signal, stopAbort.signal, closed.signal]);
3561
3600
  try {
3562
- const rows = await step({ runId: claim.runId, agentId: spec.agentId, claim, outcome, signal, ask: (prompt, opts) => askEndOfRun(claim, over, prompt, opts.deadlineMs, opts.again === true, opts.round ?? 1, opts.keep, opts.step), keptOf: await keptOf(claim) });
3601
+ const rows = await step({ runId: claim.runId, agentId: spec.agentId, claim, outcome, ...(endedAt !== undefined ? { endedAt } : {}), signal, ask: (prompt, opts) => askEndOfRun(claim, over, prompt, opts.deadlineMs, opts.again === true, opts.round ?? 1, opts.keep, opts.step), keptOf: await keptOf(claim) });
3563
3602
  // A replay's or a shadow's grader verdict (runner/compare-end.ts), on its root before its end: its metrics carry it
3564
3603
  // (workflow-first.ts pathMetrics), where the check and the audit read it.
3565
3604
  const on = harness;
@@ -3884,8 +3923,11 @@ function adapterLoop(specOf, options, deps) {
3884
3923
  /** The end commit: an `agentrun.end` entry carrying the run row's final patch (the spec's end patch in it), the rows
3885
3924
  * staged with it (the end-of-run step's), and the rows it takes. */
3886
3925
  /** `failedWith`: a CLI turn's own error (record "loop"), cut of every secret the runner holds: written in the end's
3887
- * commit, right before the end, as pi's own error answer (cliErrorAnswer), main's error row for a CLI's turn. */
3888
- async function writeEnd(on, conversation, theGate, base, take, also = [], failedWith) {
3926
+ * commit, right before the end, as pi's own error answer (cliErrorAnswer), main's error row for a CLI's turn.
3927
+ * `keptAt`: the end is the job's, kept before its look-back (keepJobEnd), and every reader served it while the run
3928
+ * looked back: it is written at that time, and a stop or cancel taken here cut the look-back alone, never the end
3929
+ * (the store refuses one still waiting: RunPatch.keepsEnd). */
3930
+ async function writeEnd(on, conversation, theGate, base, take, also = [], failedWith, keptAt) {
3889
3931
  // A person's stop of a run that holds its computer ends its agent, not the hold (computer-held.ts): the end, and the
3890
3932
  // computer's release after it, wait for the owner's release or the hold's lapse, the owner's calls still answered.
3891
3933
  // A cancel, a lost claim or a shutdown meanwhile ends the wait; a cancel's end is then the run's, taking both rows.
@@ -3896,7 +3938,8 @@ function adapterLoop(specOf, options, deps) {
3896
3938
  await heldNow.heldAtEnd(Promise.race([heldCut, aborted, on.closed]), heldWords.stopped(heldNow.minutes));
3897
3939
  const later = laterStop;
3898
3940
  if (later?.kind === "command" && later.cancel) {
3899
- base = { ...base, ...stopEnd(true) };
3941
+ if (keptAt === undefined)
3942
+ base = { ...base, ...stopEnd(true) };
3900
3943
  take = [...take, later.commandId];
3901
3944
  }
3902
3945
  }
@@ -3915,9 +3958,11 @@ function adapterLoop(specOf, options, deps) {
3915
3958
  const lateStop = late?.kind === "command" && !take.includes(late.commandId) ? late : undefined;
3916
3959
  if (lateStop)
3917
3960
  take = [...take, lateStop.commandId];
3918
- const data = { ...base, ...(patch.outcome !== undefined ? { outcome: patch.outcome } : {}), ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd, ...(patch.costUpperBound ? { costUpperBound: true } : {}) } : {}), ...(patch.metrics !== undefined ? { metrics: patch.metrics } : {}), ...(lateStop ? stopEnd(lateStop.cancel) : {}) };
3961
+ // An end that keeps the job's takes it too, and stays the job's.
3962
+ const data = { ...base, ...(patch.outcome !== undefined ? { outcome: patch.outcome } : {}), ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd, ...(patch.costUpperBound ? { costUpperBound: true } : {}) } : {}), ...(patch.metrics !== undefined ? { metrics: patch.metrics } : {}), ...(lateStop && keptAt === undefined ? stopEnd(lateStop.cancel) : {}) };
3919
3963
  const run = {
3920
3964
  state: data.state,
3965
+ ...(keptAt !== undefined ? { endedAt: keptAt, keepsEnd: true } : {}),
3921
3966
  // An end's summary is its own: with none, a wait's summary the row still says (a question's, a hand-over's: HELD_WAITS
3922
3967
  // and the park's) goes, so an ended run never reads as waiting on its person.
3923
3968
  ...(data.summary ? { summary: data.summary } : {}),
@@ -11,6 +11,7 @@ import type { Store } from "../store/store.js";
11
11
  import { type ArgumentsOf, type Permission, type RunFiles, type SettingFrom, type ToolEffect } from "../tool-gate.js";
12
12
  import { loadToolSettings } from "../tool-plane.js";
13
13
  import { type EmailFake, type ToolHost } from "../tools.js";
14
+ import type { SaveSlots } from "../web-save.js";
14
15
  import type { WebFake } from "../web-fake.js";
15
16
  import { type HostToolCtx } from "../host-tools.js";
16
17
  import { type LearnedWorkflow } from "../learning.js";
@@ -108,8 +109,8 @@ export interface AdapterSpecDeps {
108
109
  readonly computerDeps: ComputerDeps;
109
110
  /** A Mode 2 claim's Archil disk (a test's fake); absent, the real disk the Archil settings name. */
110
111
  readonly makeArchilDisk?: ArchilClaimOptions["makeDisk"];
111
- /** The Archil mount credential's control plane, for a test's loopback fake (archilControlFake): its base URL and the
112
- * fetch to call it with, spread into the claim's mount. Absent, the real control plane the mount credential names. No
112
+ /** Archil's control plane, for a test's loopback fake (archilControlFake): its base URL and the fetch to call it with,
113
+ * the claim's control (where the run's disk is read and its mount credential minted). Absent, the region's own. No
113
114
  * test ever reaches the real Archil control plane. */
114
115
  readonly mountControl?: {
115
116
  readonly baseUrl?: string;
@@ -155,8 +156,10 @@ export interface AdapterSpecDeps {
155
156
  * on purpose does not wait out MODEL_RETRY's two and a half minutes. No environment variable, flag or setting maps onto
156
157
  * it; absent, MODEL_RETRY and MODEL_STREAM. */
157
158
  readonly modelRetry?: Pick<AdapterLoopOptions, "retry" | "stream">;
159
+ /** web_save's download slots (ToolHost.saveSlots): in a run's own process, its runner's (run-child.ts). */
160
+ readonly saveSlots?: SaveSlots;
158
161
  }
159
- /** One run's template eval fakes (template-eval.ts, from its case). `web`: its web_search and web_fetch answer from the
162
+ /** One run's template eval fakes (template-eval.ts, from its case). `web`: its web_search, web_fetch and web_save answer from the
160
163
  * case, and its harness's own search is never offered (web-fake.ts, fakedPlane). `now`: its clock, the date and time it
161
164
  * is told wherever it reads "now" (environment.ts environmentLine, claude-agent's turn date); absent, the real clock.
162
165
  * `monid`: its monid endpoints answer as monid unreachable does, never sent (monid-run.ts monidForClaim). `email`: the
@@ -347,6 +350,8 @@ export declare function buildToolHost(opts: {
347
350
  readonly own?: readonly string[];
348
351
  /** A runner on another host than its server: where the run's viewers answer, under its run's key (claimLiveAt). */
349
352
  readonly liveAt?: RunnerLive;
353
+ /** web_save's download slots (AdapterSpecDeps.saveSlots). */
354
+ readonly saveSlots?: SaveSlots;
350
355
  }): ToolHost;
351
356
  /** Where the claim's viewers answer on a runner on another host than its server (live-reach.ts runnerLiveOf), under the
352
357
  * claim's run's own proof key (liveForRun); none on the server's machine. In a run's own process its runner's
@@ -293,10 +293,11 @@ async function adapterSpec(launch, run, deps, claim, holds, runner) {
293
293
  // a 24 h ttl as the safety net if revoke never comes (revoke normally runs at the run's end, below). A run with no
294
294
  // mounting computer never mints one.
295
295
  // The mint is lazy (archil-claim.ts token(), k2's run-tools.ts): only a mounting computer asks for it, so a Mode 2 run
296
- // with no computer makes no control-plane call. mountControl (a test's loopback control-plane fake) is spread into the
297
- // mount, so no test reaches the real control plane. MOUNT_TTL_MS is the credential's safety net (its computer's 24 h bound), not its lifetime.
298
- // The disk is the run's (run-disk.ts): its launch record's, else its agent's, made on its first run that needs one.
299
- : await archilWhereHeld({ settings: archilSettings, keys: deps.store.sealedKeys, sealKey: deps.sealKey, signal: run.signal ?? new AbortController().signal, env: deps.env, mount: { runId: claim.runId, epoch: claim.epoch, ttlMs: MOUNT_TTL_MS, ...(deps.mountControl ?? {}) }, run: { agentId: runRow.agentId, ...(launch.archilDisk ? { launch: launch.archilDisk } : {}), store: deps.store }, ...(deps.makeArchilDisk ? { makeDisk: deps.makeArchilDisk } : {}) });
296
+ // with no computer mints nothing. mountControl (a test's loopback control-plane fake) is the claim's control, so no
297
+ // test reaches the real control plane. MOUNT_TTL_MS is the credential's safety net (its computer's 24 h bound), not its lifetime.
298
+ // The disk is the run's (run-disk.ts): its launch record's, else its agent's, made on its first run that needs one,
299
+ // and read at Archil at every claim.
300
+ : await archilWhereHeld({ settings: archilSettings, keys: deps.store.sealedKeys, sealKey: deps.sealKey, signal: run.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: runRow.agentId, ...(launch.archilDisk ? { launch: launch.archilDisk } : {}), store: deps.store }, ...(deps.makeArchilDisk ? { makeDisk: deps.makeArchilDisk } : {}) });
300
301
  // Each resource is held the moment it exists (spec-holds.ts): a throw after it lets it go.
301
302
  holds.hold({ archil });
302
303
  // The run's Workspace at the claim: Mode 1 the run's local folder (made here, the server's start made it before); Mode 2
@@ -359,7 +360,7 @@ async function adapterSpec(launch, run, deps, claim, holds, runner) {
359
360
  // claim's is a new one whatever ended the earlier claim (a lost runner, a server's stop, a park past its keep). The
360
361
  // computer a park kept, attached again, brings its mount credential with it (inheritMount): none is minted. A
361
362
  // recording of its screen (computer.record) goes in the run's recordings folder, beside its folder, said on its timeline.
362
- { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, recordings: { folder: recordingsFolder(deps.data, runRow.agentId, claim.runId), say: (words) => run.phase?.(words) }, hadComputer: () => hadComputer(deps.journal(claim), context), stopRun: stopRunWith((refusal) => run.ledger.pause(refusal)), ...(claimSignal ? { signal: claimSignal } : {}), ...(archil ? { revokeMount: () => archil.revoke(), inheritMount: () => archil.inherit() } : {}), ...(run.phase ? { onImageWait: (making, image) => run.phase?.(imageWaitWords(making, image)), onStarting: (said) => run.phase?.(computerStartingWords(said)), onConnected: (said) => run.phase?.(computerReadyWords(said)), onComputerNote: (words) => run.phase?.(words) } : {}) });
363
+ { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, recordings: { folder: recordingsFolder(deps.data, runRow.agentId, claim.runId), say: (words) => run.phase?.(words) }, hadComputer: () => hadComputer(deps.journal(claim), context), stopRun: stopRunWith((refusal) => run.ledger.pause(refusal)), ...(run.ledger ? { compute: { ledger: { paid: run.ledger.paid, pause: (refusal) => run.ledger.pause(refusal), judges: () => run.ledger.judges?.() ?? true }, env: deps.env } } : {}), ...(claimSignal ? { signal: claimSignal } : {}), ...(archil ? { revokeMount: () => archil.revoke(), inheritMount: () => archil.inherit() } : {}), ...(run.phase ? { onImageWait: (making, image) => run.phase?.(imageWaitWords(making, image)), onStarting: (said) => run.phase?.(computerStartingWords(said)), onConnected: (said) => run.phase?.(computerReadyWords(said)), onComputerNote: (words) => run.phase?.(words) } : {}) });
363
364
  // The run's shell is its computer's (600 s) where one mounts its folder; with none, Archil's serverless exec in Mode 2
364
365
  // (295 s), and in Mode 1 none at all: no bash family, its folder being one of this server's own (run-tools.ts).
365
366
  // A desktop's or a phone's hold (the person's take-over) wraps its ports: a call made while the person holds it waits,
@@ -573,13 +574,18 @@ async function adapterSpec(launch, run, deps, claim, holds, runner) {
573
574
  // Harness is open before the session, and at the run's end (the browser tool's reconcile and release hang off these). The
574
575
  // adapter loop runs them from the spec's `lifecycle` (adapter-loop.ts hostLifecycle).
575
576
  const life = hostLifecycle();
577
+ // The claim's computers' time booked up to now before the run's end or park is written (compute-cost.ts), so the end's
578
+ // cost holds it: the release that deletes them comes after the end.
579
+ const settleComputers = computer.settle;
580
+ if (settleComputers)
581
+ life.register.beforeRelease(() => settleComputers());
576
582
  // The ToolHost the non-hand tools (browser, web, MCP, decisions, monid) bind through (buildToolHost, the one the CLI
577
583
  // spec builds too), on the claim's keys and the run's one ledger and redactor.
578
584
  // An agent whose computer is a browser the claim started gets the browser tool on that one session (tools.ts).
579
585
  const claimBrowser = computer.computer?.kind === "browser" ? computer.computer.browser : undefined;
580
586
  const fakes = deps.evalFakes?.(runRow.agentId);
581
587
  const liveAt = await claimLiveAt(deps, claim.runId);
582
- const host = { ...buildToolHost({ root, workspace: ws.workspace, claim, env: toolEnv, run, store: deps.store, sealKey: deps.sealKey, life, redact: cut, launch, toolSettings: body.toolSettings, ...(fakes ? { fakes } : {}), ...reach, ...(liveAt ? { liveAt } : {}) }), ...(claimBrowser ? { browserComputer: claimBrowser } : {}) };
588
+ const host = { ...buildToolHost({ root, workspace: ws.workspace, claim, env: toolEnv, run, store: deps.store, sealKey: deps.sealKey, life, redact: cut, launch, toolSettings: body.toolSettings, ...(fakes ? { fakes } : {}), ...reach, ...(liveAt ? { liveAt } : {}), ...(deps.saveSlots ? { saveSlots: deps.saveSlots } : {}) }), ...(claimBrowser ? { browserComputer: claimBrowser } : {}) };
583
589
  gate.askedOn(host);
584
590
  // The run's tools. The hands (read/write/edit/bash and the background tools) are the kernel registry's over the run's
585
591
  // Workspace and computer (runTools.hostTools); the gate is the adapter loop's own (spec.gate), so they run as asked.
@@ -938,6 +944,7 @@ export function buildToolHost(opts) {
938
944
  ...(email ? { emailFake: email } : {}),
939
945
  ...(opts.loopback ? { calendarLoopback: true } : {}),
940
946
  ...(opts.own ? { serverOwn: opts.own } : {}),
947
+ ...(opts.saveSlots ? { saveSlots: opts.saveSlots } : {}),
941
948
  // The run's directory and its per-claim environment: the hands come from runTools, so the non-hand tools get the run's
942
949
  // environment only.
943
950
  where: { root, work: root, ref: { id: claim.runId } },
@@ -0,0 +1,33 @@
1
+ import { type SaveSlots } from "../web-save.js";
2
+ import type { Pieces } from "../workspace/pieced.js";
3
+ import { type Workspace } from "../workspace/workspace.js";
4
+ export type { Pieces, PullPiece, WritePieces } from "../workspace/pieced.js";
5
+ export { piecedWorkspace } from "../workspace/pieced.js";
6
+ /** The most bytes one piece carries over the channel: well under its MAX_FRAME (32 MiB). A write of at most this many
7
+ * bytes crosses as one call, as before. */
8
+ export declare const PIECE_BYTES: number;
9
+ /** The most bytes one pieced write may have: web_save's cap. */
10
+ export declare const BIG_WRITE_MAX: number;
11
+ /** How long the runner waits for one piece before the write fails. */
12
+ export declare const PIECE_MS = 60000;
13
+ /** The most pieced writes a runner assembles at once, across its runs: with BIG_WRITE_MAX, what they hold in memory. */
14
+ export declare const BIG_WRITES = 4;
15
+ /** The most pieced writes one run may have held or waiting at once: its waiters live in the runner. */
16
+ export declare const BIG_WRITES_PER_RUN = 8;
17
+ /** The runner's one gate for pieced writes. */
18
+ export declare const BIG_WRITE_SLOTS: SaveSlots;
19
+ export type BigWritesOptions = {
20
+ /** Default BIG_WRITE_SLOTS. */
21
+ readonly gate?: SaveSlots;
22
+ /** Default PIECE_BYTES. */
23
+ readonly piece?: number;
24
+ /** Default PIECE_MS. */
25
+ readonly pieceMs?: number;
26
+ };
27
+ /** One run's pieced writes on its runner: `pieces(ws)` is what is handed beside `ws`; `close()`, called when the run's
28
+ * channel ends (or its claim is released), lets every wait and hold of the run go. */
29
+ export interface RunBigWrites {
30
+ pieces(ws: Workspace): Pieces;
31
+ close(): void;
32
+ }
33
+ export declare function runBigWrites(options?: BigWritesOptions): RunBigWrites;
@@ -0,0 +1,105 @@
1
+ // A Workspace write bigger than a channel frame, from a run's own process. In Mode 2 the run's process holds its runner's
2
+ // Workspace of the run's folder by handle (held.ts archil, archil-claim.ts archilWhereHeld), and a call carries all its
3
+ // arguments in one frame of the run's channel (run-channel.ts MAX_FRAME): a write of a file past that would fail after
4
+ // the bytes were made (web_save's download, up to SAVE_MAX_BYTES). So a write of more than one piece does not cross as one
5
+ // call: the runner, handed the length, pulls the bytes from the run's process a piece at a time, each piece of exactly
6
+ // the length it asked for, into one buffer allocated at that length, and makes the one atomic write itself, on the same
7
+ // Workspace the run's process would have written through. A piece that is not the length asked, a length past
8
+ // BIG_WRITE_MAX, the run's signal, a piece not answered in PIECE_MS, or the run's channel ending writes nothing.
9
+ //
10
+ // The runner holds each assembled file in memory until its write returns, so it bounds them: at most BIG_WRITES at once
11
+ // across its runs (BIG_WRITE_SLOTS, a gate of its own, never web_save's download slots, so a run that holds a download
12
+ // slot never waits on itself), the rest waiting under their call's signal, and at most BIG_WRITES_PER_RUN held or waiting
13
+ // per run. Every wait and hold of a run is let go when its channel ends (save-slots.ts does the same for its slots). The
14
+ // runner only copies bytes and calls the Workspace: it reads nothing of them and dials nothing.
15
+ import { ClaimRefused } from "./loop-contract.js";
16
+ import { ChannelClosed } from "./run-channel.js";
17
+ import { saveSlots, SAVE_MAX_BYTES } from "../web-save.js";
18
+ import { WorkspaceError } from "../workspace/workspace.js";
19
+ export { piecedWorkspace } from "../workspace/pieced.js";
20
+ const MIB = 1024 * 1024;
21
+ /** The most bytes one piece carries over the channel: well under its MAX_FRAME (32 MiB). A write of at most this many
22
+ * bytes crosses as one call, as before. */
23
+ export const PIECE_BYTES = 8 * MIB;
24
+ /** The most bytes one pieced write may have: web_save's cap. */
25
+ export const BIG_WRITE_MAX = SAVE_MAX_BYTES;
26
+ /** How long the runner waits for one piece before the write fails. */
27
+ export const PIECE_MS = 60_000;
28
+ /** The most pieced writes a runner assembles at once, across its runs: with BIG_WRITE_MAX, what they hold in memory. */
29
+ export const BIG_WRITES = 4;
30
+ /** The most pieced writes one run may have held or waiting at once: its waiters live in the runner. */
31
+ export const BIG_WRITES_PER_RUN = 8;
32
+ /** The runner's one gate for pieced writes. */
33
+ export const BIG_WRITE_SLOTS = saveSlots(BIG_WRITES);
34
+ /** `work`'s answer, or `signal`'s reason as soon as it aborts. */
35
+ function until(work, signal) {
36
+ if (signal.aborted)
37
+ return Promise.reject(signal.reason);
38
+ return new Promise((resolve, reject) => {
39
+ const abort = () => reject(signal.reason);
40
+ signal.addEventListener("abort", abort, { once: true });
41
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
42
+ });
43
+ }
44
+ export function runBigWrites(options = {}) {
45
+ const gate = options.gate ?? BIG_WRITE_SLOTS;
46
+ const piece = options.piece ?? PIECE_BYTES;
47
+ const pieceMs = options.pieceMs ?? PIECE_MS;
48
+ /** Each write of the run, waiting or held: aborted when the run's channel ends. */
49
+ const live = new Set();
50
+ let closed = false;
51
+ const writeOn = (ws) => async (path, size, pull, signal) => {
52
+ if (closed)
53
+ throw new ChannelClosed("the run's channel ended");
54
+ if (typeof path !== "string")
55
+ throw new TypeError("a pieced write names its path");
56
+ if (!Number.isSafeInteger(size) || size < 0)
57
+ throw new TypeError("a pieced write's size is a whole number of bytes");
58
+ // Before anything is taken or allocated.
59
+ if (size > BIG_WRITE_MAX)
60
+ throw new WorkspaceError("TOO_LARGE", `a write from a run's process is at most ${BIG_WRITE_MAX} bytes, not ${size}`, { path });
61
+ if (typeof pull !== "function")
62
+ throw new TypeError("a pieced write is pulled through a function");
63
+ if (signal !== undefined && !(signal instanceof AbortSignal))
64
+ throw new TypeError("a pieced write runs under the call's signal");
65
+ if (live.size >= BIG_WRITES_PER_RUN)
66
+ throw new ClaimRefused(`this run already has ${BIG_WRITES_PER_RUN} big writes held or waiting`);
67
+ const left = new AbortController();
68
+ live.add(left);
69
+ const under = signal ? AbortSignal.any([signal, left.signal]) : left.signal;
70
+ try {
71
+ const release = await gate.take(under);
72
+ try {
73
+ const bytes = new Uint8Array(size);
74
+ for (let at = 0; at < size;) {
75
+ const want = Math.min(piece, size - at);
76
+ const got = await until(Promise.resolve().then(() => pull(at, want)), AbortSignal.any([under, AbortSignal.timeout(pieceMs)]));
77
+ if (!(got instanceof Uint8Array) || got.length !== want) {
78
+ throw new WorkspaceError("REFUSED", `the piece at ${at} of a write is ${got instanceof Uint8Array ? `${got.length} bytes` : "not bytes"}, not the ${want} asked for: nothing was written`, { path });
79
+ }
80
+ bytes.set(got, at);
81
+ at += want;
82
+ }
83
+ // The run's end while the last piece came: nothing is written for it.
84
+ under.throwIfAborted();
85
+ await ws.write(path, bytes);
86
+ }
87
+ finally {
88
+ release();
89
+ }
90
+ }
91
+ finally {
92
+ live.delete(left);
93
+ }
94
+ };
95
+ return {
96
+ pieces: (ws) => ({ write: writeOn(ws), piece }),
97
+ close() {
98
+ if (closed)
99
+ return;
100
+ closed = true;
101
+ for (const write of live)
102
+ write.abort(new ChannelClosed("the run's channel ended"));
103
+ },
104
+ };
105
+ }
@@ -342,10 +342,11 @@ async function cliSpec(launch, run, deps, claim, holds) {
342
342
  ? undefined
343
343
  // The run's mount credential, minted per run (account key from the server's environment first, then the sealed row),
344
344
  // named for the run and this claim's epoch; revoke at the run's end (below). mountControl (a test's loopback control-plane
345
- // fake) is spread into the mount, so no test reaches the real control plane. TODO(k2 lazy mint): the mint moves into
345
+ // fake) is the claim's control, so no test reaches the real control plane. TODO(k2 lazy mint): the mint moves into
346
346
  // computerForClaim (a mounting computer only), with the ttl the run's lifetime bound (not this fixed figure). As pi does.
347
- // The disk is the run's (run-disk.ts): its launch record's, else its agent's, made on its first run that needs one.
348
- : await archilWhereHeld({ settings: archilSettings, keys: deps.store.sealedKeys, sealKey: deps.sealKey, signal: run.signal ?? new AbortController().signal, env: deps.env, mount: { runId: claim.runId, epoch: claim.epoch, ttlMs: MOUNT_TTL_MS, ...(deps.mountControl ?? {}) }, run: { agentId: runRow.agentId, ...(launch.archilDisk ? { launch: launch.archilDisk } : {}), store: deps.store }, ...(deps.makeArchilDisk ? { makeDisk: deps.makeArchilDisk } : {}) });
347
+ // The disk is the run's (run-disk.ts): its launch record's, else its agent's, made on its first run that needs one,
348
+ // and read at Archil at every claim.
349
+ : await archilWhereHeld({ settings: archilSettings, keys: deps.store.sealedKeys, sealKey: deps.sealKey, signal: run.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: runRow.agentId, ...(launch.archilDisk ? { launch: launch.archilDisk } : {}), store: deps.store }, ...(deps.makeArchilDisk ? { makeDisk: deps.makeArchilDisk } : {}) });
349
350
  // Each resource is held the moment it exists (spec-holds.ts): a throw after it lets it go. The claim's Archil keys go
350
351
  // from memory last, once nothing more reads the disk.
351
352
  holds.hold({ archil, keys: archil });
@@ -389,7 +390,7 @@ async function cliSpec(launch, run, deps, claim, holds) {
389
390
  // Whether an earlier claim made the run a computer of its own is the run's journal's to say (hadComputer), as the pi
390
391
  // spec asks it. The computer a park kept, attached again, brings its mount credential with it (inheritMount). Its
391
392
  // screen's recording (computer.record) goes in the run's recordings folder, as the pi spec's does.
392
- { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, refuseKind: cliRefusesKind, recordings: { folder: recordingsFolder(deps.data, runRow.agentId, claim.runId), say: (words) => run.phase?.(words) }, hadComputer: () => hadComputer(deps.journal(claim), context), stopRun: stopRunWith((refusal) => run.ledger.pause(refusal)), ...(claimSignal ? { signal: claimSignal } : {}), ...(archil ? { revokeMount: () => archil.revoke(), inheritMount: () => archil.inherit() } : {}), ...(run.phase ? { onImageWait: (making, image) => run.phase?.(imageWaitWords(making, image)), onStarting: (said) => run.phase?.(computerStartingWords(said)), onConnected: (said) => run.phase?.(computerReadyWords(said)), onComputerNote: (words) => run.phase?.(words) } : {}) });
393
+ { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, refuseKind: cliRefusesKind, recordings: { folder: recordingsFolder(deps.data, runRow.agentId, claim.runId), say: (words) => run.phase?.(words) }, hadComputer: () => hadComputer(deps.journal(claim), context), stopRun: stopRunWith((refusal) => run.ledger.pause(refusal)), ...(run.ledger ? { compute: { ledger: { paid: run.ledger.paid, pause: (refusal) => run.ledger.pause(refusal), judges: () => run.ledger.judges?.() ?? true }, env: deps.env } } : {}), ...(claimSignal ? { signal: claimSignal } : {}), ...(archil ? { revokeMount: () => archil.revoke(), inheritMount: () => archil.inherit() } : {}), ...(run.phase ? { onImageWait: (making, image) => run.phase?.(imageWaitWords(making, image)), onStarting: (said) => run.phase?.(computerStartingWords(said)), onConnected: (said) => run.phase?.(computerReadyWords(said)), onComputerNote: (words) => run.phase?.(words) } : {}) });
393
394
  holds.hold({ computer });
394
395
  const loopComputer = loopComputerOf(computer.computer, computer.held, computer.made);
395
396
  const heldComputer = heldSpecOf(launch, loopComputer);
@@ -573,6 +574,13 @@ async function cliSpec(launch, run, deps, claim, holds) {
573
574
  let learnedTool;
574
575
  let webTools = [];
575
576
  let life;
577
+ // The claim's computers' time booked up to now before the run's end or park is written (compute-cost.ts), so the end's
578
+ // cost holds it: the release that deletes them comes after the end.
579
+ const settleComputers = computer.settle;
580
+ if (settleComputers) {
581
+ life = hostLifecycle();
582
+ life.register.beforeRelease(() => settleComputers());
583
+ }
576
584
  // The keys the claim hands the run (its web tools and its learned workflow's call nodes run on them): never learned
577
585
  // (learningEndOfRun).
578
586
  let handedKeys = [];
@@ -620,9 +628,9 @@ async function cliSpec(launch, run, deps, claim, holds) {
620
628
  if (launch.plane && Object.keys(launch.plane).length)
621
629
  toolEnv[TOOL_PLANE_ENV] = JSON.stringify(launch.plane);
622
630
  if (webNames.length) {
623
- life = hostLifecycle();
631
+ life ??= hostLifecycle();
624
632
  const liveAt = await claimLiveAt(deps, claim.runId);
625
- const host = buildToolHost({ root, workspace: ws.workspace, claim, env: toolEnv, run, store: deps.store, sealKey: deps.sealKey, life, redact: held, launch, toolSettings: body.toolSettings, ...(fakes ? { fakes } : {}), ...reach, ...(liveAt ? { liveAt } : {}) });
633
+ const host = buildToolHost({ root, workspace: ws.workspace, claim, env: toolEnv, run, store: deps.store, sealKey: deps.sealKey, life, redact: held, launch, toolSettings: body.toolSettings, ...(fakes ? { fakes } : {}), ...reach, ...(liveAt ? { liveAt } : {}), ...(deps.saveSlots ? { saveSlots: deps.saveSlots } : {}) });
626
634
  gate.askedOn(host);
627
635
  webTools = await webHostTools(host, granted, ctx);
628
636
  }
@@ -25,6 +25,8 @@ export declare function suiteTools(countFile?: string): {
25
25
  ran: Record<ToolName, number>;
26
26
  letSlowGo: () => void;
27
27
  slowStarted: Promise<void>;
28
+ holdAsked: () => undefined;
29
+ letAskedGo: () => void;
28
30
  };
29
31
  /** Catalog tools (an MCP server's, by wire name) that do nothing, enough of them to pass DEFER_CATALOG_OVER: a run with that
30
32
  * many has its catalog deferred (not listed) and is offered tools_search and tools_call, which the meta cases need. */
@@ -87,6 +87,10 @@ export function suiteTools(countFile) {
87
87
  const slowGate = new Promise((resolve) => (letGo = resolve));
88
88
  let slowStarted = () => { };
89
89
  const started = new Promise((resolve) => (slowStarted = resolve));
90
+ // Held (holdAsked), an approved `asked` call runs until the suite lets it go (letAskedGo), so its run cannot end first.
91
+ let askedGate;
92
+ let letAskedGoNow = () => { };
93
+ const holdAsked = () => void (askedGate = new Promise((resolve) => (letAskedGoNow = resolve)));
90
94
  const tool = (name, replaySafe, ask, run) => ({ name, replaySafe, ask, run });
91
95
  const tools = {
92
96
  effect: tool("effect", false, false, async () => {
@@ -103,12 +107,14 @@ export function suiteTools(countFile) {
103
107
  await Promise.race([slowGate, new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }))]);
104
108
  return signal.aborted ? "cut" : "slow done";
105
109
  }),
106
- asked: tool("asked", false, true, async () => {
110
+ asked: tool("asked", false, true, async (_args, signal) => {
107
111
  ran.asked += 1;
112
+ if (askedGate)
113
+ await Promise.race([askedGate, new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }))]);
108
114
  return "asked done";
109
115
  }),
110
116
  };
111
- return { tools, ran, letSlowGo: () => letGo(), slowStarted: started };
117
+ return { tools, ran, letSlowGo: () => letGo(), slowStarted: started, holdAsked, letAskedGo: () => letAskedGoNow() };
112
118
  }
113
119
  /** Catalog tools (an MCP server's, by wire name) that do nothing, enough of them to pass DEFER_CATALOG_OVER: a run with that
114
120
  * many has its catalog deferred (not listed) and is offered tools_search and tools_call, which the meta cases need. */
@@ -1022,12 +1028,20 @@ const CASES = [
1022
1028
  title: "a double-clicked approval runs the call once: the first answers it, and the store refuses the second (one answer per approval)",
1023
1029
  async body(subject, t) {
1024
1030
  const w = await world(subject, t);
1025
- const { tools, ran } = suiteTools();
1031
+ const { tools, ran, holdAsked, letAskedGo } = suiteTools();
1032
+ // The approved call is held until the second click is answered, so the run cannot end first: a run that ended
1033
+ // refuses any command as final (RunFinal) before the one-answer index is reached, which is not this case.
1034
+ holdAsked();
1026
1035
  await w.start("runner-a", { script: [{ call: "asked" }, { say: "done" }], tools, hooks: quiet });
1027
1036
  await w.ended("parked");
1028
1037
  const callId = await w.askedCall();
1029
1038
  const first = await sendCommand(w.server, RUN, { kind: "approve", body: { approval: callId } });
1030
- await assert.rejects(sendCommand(w.server, RUN, { kind: "approve", body: { approval: callId } }), AnswerTaken, "a second answer to one approval is never written: the store says it is answered already");
1039
+ try {
1040
+ await assert.rejects(sendCommand(w.server, RUN, { kind: "approve", body: { approval: callId } }), AnswerTaken, "a second answer to one approval is never written: the store says it is answered already");
1041
+ }
1042
+ finally {
1043
+ letAskedGo();
1044
+ }
1031
1045
  await w.ended("ended");
1032
1046
  assert.equal(ran.asked, 1, "the call ran once");
1033
1047
  assert.equal((await w.commandRow(first.id)).refused, null, "the first approve answered it");
@@ -2,15 +2,43 @@ import { type Grade } from "../learn/promote.js";
2
2
  import type { RunPath } from "../learning-cost.js";
3
3
  import { type RunLaunch } from "../run-launch.js";
4
4
  import { type Command, type Store } from "../store/store.js";
5
+ import { type EndData } from "./journal-kinds.js";
5
6
  export declare const FEEDBACK_ROUNDS: readonly ["correction"];
6
7
  export type FeedbackRound = (typeof FEEDBACK_ROUNDS)[number];
8
+ /** The end a run's look-back keeps: how its job ended (its state, summary and outcome) and when. While the run looks
9
+ * back (its end-of-run step, a fresh run's or a grade's feedback round) every reader serves this end, and the look-back's
10
+ * own end writes it again at the same time (adapter-loop.ts writeEnd `keptAt`): a look-back never undoes or moves its
11
+ * run's end. */
12
+ export interface KeptEnd {
13
+ readonly state: EndData["state"];
14
+ readonly summary?: string;
15
+ readonly outcome?: EndData["outcome"];
16
+ readonly endedAt: number;
17
+ }
7
18
  /** A feedback round, as its steer's body carries it (`feedback`) and its FEEDBACK entry keeps it: the round, whether the
8
- * grade said right, and the grade's words (`text`). */
19
+ * grade said right, the grade's words (`text`), and the end the run had when the grade opened it again (`kept`). */
9
20
  export interface FeedbackData {
10
21
  readonly round: FeedbackRound;
11
22
  readonly correct: boolean;
12
23
  readonly text: string;
24
+ readonly kept?: KeptEnd;
13
25
  }
26
+ /** 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
27
+ * job ended and its look-back is under way, whether or not that look-back has asked anything yet. A follow-up's turn
28
+ * keeps none until its own job's end is kept, so a turn after the run's last end reads false. */
29
+ export declare function jobEndOpen(entries: readonly {
30
+ readonly kind: string;
31
+ }[]): boolean;
32
+ /** The end run's look-back keeps while it runs, from the run's root `entries` and its command rows, else undefined (no
33
+ * look-back under way, or one whose job's end was never kept):
34
+ * - 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;
35
+ * - else the end a grade's round kept, from its FEEDBACK entry newer than the run's last end;
36
+ * - else from the round's steer the grade wrote, not taken yet (the run opened again, no runner on it yet).
37
+ * 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. */
38
+ export declare function keptEndOf(entries: readonly {
39
+ readonly kind: string;
40
+ readonly data?: unknown;
41
+ }[], commands: readonly Pick<Command, "kind" | "body" | "takenAt" | "refused">[]): KeptEnd | undefined;
14
42
  /** What a grade asks for: `correction` for a graded run the agent finished when the grade has words, else none
15
43
  * (undefined): a run its learned workflow answered alone opens none, right or wrong (its grade is kept). A replay run
16
44
  * is never graded. */