@parcha/agentrun-serve 0.1.0-beta.32 → 0.1.0-beta.33

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 (163) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +78 -46
  3. package/dist/adapters.d.ts +0 -3
  4. package/dist/adapters.js +0 -7
  5. package/dist/agents.d.ts +1 -1
  6. package/dist/api-only.d.ts +14 -0
  7. package/dist/api-only.js +33 -0
  8. package/dist/archil-routes.d.ts +1 -1
  9. package/dist/box-egress-vm.d.ts +0 -8
  10. package/dist/box-egress-vm.js +0 -10
  11. package/dist/box-egress.d.ts +0 -4
  12. package/dist/box-egress.js +1 -16
  13. package/dist/box-paths.d.ts +25 -2
  14. package/dist/box-paths.js +79 -11
  15. package/dist/box-relay.d.ts +0 -11
  16. package/dist/box-relay.js +0 -20
  17. package/dist/box-settings.d.ts +46 -0
  18. package/dist/box-settings.js +107 -0
  19. package/dist/boxes.d.ts +4 -1
  20. package/dist/browser-cost.js +2 -1
  21. package/dist/browser-person.d.ts +0 -2
  22. package/dist/browser-person.js +0 -2
  23. package/dist/budget.d.ts +0 -4
  24. package/dist/budget.js +0 -7
  25. package/dist/cap.d.ts +0 -7
  26. package/dist/cap.js +0 -22
  27. package/dist/cli.js +23 -8
  28. package/dist/computers.d.ts +1 -1
  29. package/dist/console/assets/index-Dn0ngwG9.js +535 -0
  30. package/dist/console/assets/index-DvW6Aled.css +1 -0
  31. package/dist/console/index.html +2 -2
  32. package/dist/daytona-api.d.ts +0 -11
  33. package/dist/daytona-api.js +1 -82
  34. package/dist/docker-host-addresses.d.ts +37 -0
  35. package/dist/docker-host-addresses.js +110 -0
  36. package/dist/files.d.ts +0 -8
  37. package/dist/files.js +0 -17
  38. package/dist/github-connection.d.ts +1 -1
  39. package/dist/github-connection.js +1 -1
  40. package/dist/harness-install.d.ts +23 -0
  41. package/dist/harness-install.js +99 -4
  42. package/dist/harness.d.ts +4 -3
  43. package/dist/harness.js +16 -1
  44. package/dist/import.js +52 -13
  45. package/dist/learn/secrets.d.ts +2 -1
  46. package/dist/learn/secrets.js +19 -6
  47. package/dist/learned-workflow.d.ts +5 -4
  48. package/dist/learned-workflow.js +6 -3
  49. package/dist/learning-routes.d.ts +9 -46
  50. package/dist/learning-routes.js +25 -29
  51. package/dist/learning-run.d.ts +4 -231
  52. package/dist/learning-run.js +7 -651
  53. package/dist/live/translate.js +1 -1
  54. package/dist/mcp-gateway.d.ts +0 -3
  55. package/dist/mcp-gateway.js +0 -13
  56. package/dist/mcp-probe.d.ts +2 -2
  57. package/dist/mcp-probe.js +2 -2
  58. package/dist/mcp-servers-store.js +1 -1
  59. package/dist/openapi.js +3 -3
  60. package/dist/page.js +3 -1
  61. package/dist/paid-calls.js +3 -2
  62. package/dist/pause.d.ts +0 -2
  63. package/dist/pause.js +1 -8
  64. package/dist/place.d.ts +0 -5
  65. package/dist/place.js +0 -10
  66. package/dist/print.d.ts +2 -1
  67. package/dist/print.js +4 -2
  68. package/dist/run-db.d.ts +0 -2
  69. package/dist/run-db.js +0 -4
  70. package/dist/run-learning-served.d.ts +38 -0
  71. package/dist/run-learning-served.js +9 -0
  72. package/dist/run-secrets.d.ts +33 -0
  73. package/dist/run-secrets.js +53 -0
  74. package/dist/run-timeline-served.js +5 -2
  75. package/dist/run-view.d.ts +5 -9
  76. package/dist/run-view.js +4 -22
  77. package/dist/runner/adapter-loop.d.ts +8 -2
  78. package/dist/runner/adapter-loop.js +44 -12
  79. package/dist/runner/adapter-run-spec.d.ts +8 -0
  80. package/dist/runner/adapter-run-spec.js +6 -5
  81. package/dist/runner/adapters/pi.d.ts +4 -0
  82. package/dist/runner/adapters/pi.js +4 -1
  83. package/dist/runner/beside.js +19 -8
  84. package/dist/runner/claim-secrets.js +1 -1
  85. package/dist/runner/cli-run-spec.js +15 -1
  86. package/dist/runner/journal-kinds.d.ts +6 -0
  87. package/dist/runner/live-ticker.d.ts +1 -1
  88. package/dist/runner/live-ticker.js +28 -4
  89. package/dist/runner/loop-contract.d.ts +3 -2
  90. package/dist/runner/main.d.ts +11 -4
  91. package/dist/runner/main.js +39 -10
  92. package/dist/runner/mcp-claim.d.ts +1 -1
  93. package/dist/runner/mcp-claim.js +1 -1
  94. package/dist/runner/model-route.js +21 -2
  95. package/dist/runner/redact.d.ts +8 -2
  96. package/dist/runner/redact.js +11 -2
  97. package/dist/runner/workflow-spec.js +5 -9
  98. package/dist/runs-over-store.d.ts +1 -1
  99. package/dist/runs-over-store.js +16 -5
  100. package/dist/seal-key.d.ts +54 -15
  101. package/dist/seal-key.js +272 -84
  102. package/dist/sealed-settings.d.ts +2 -2
  103. package/dist/sealed-settings.js +3 -10
  104. package/dist/secrets.d.ts +2 -10
  105. package/dist/secrets.js +21 -17
  106. package/dist/server-secrets-store.js +1 -1
  107. package/dist/server-secrets.js +3 -0
  108. package/dist/server.d.ts +10 -6
  109. package/dist/server.js +89 -41
  110. package/dist/store/index.d.ts +1 -1
  111. package/dist/store/index.js +1 -1
  112. package/dist/store/open.d.ts +12 -2
  113. package/dist/store/open.js +23 -3
  114. package/dist/store/postgres/migrate.js +18 -1
  115. package/dist/store/sqlite/store.js +23 -8
  116. package/dist/store/store.d.ts +3 -0
  117. package/dist/store-reads/journal.d.ts +16 -0
  118. package/dist/store-reads/journal.js +82 -6
  119. package/dist/store-view.js +38 -5
  120. package/dist/tool-keys.d.ts +4 -3
  121. package/dist/tool-keys.js +7 -4
  122. package/dist/tools.d.ts +1 -1
  123. package/dist/tools.js +4 -1
  124. package/dist/trigger-schedule.js +2 -1
  125. package/dist/trigger-secrets-shown.js +5 -1
  126. package/dist/workspace/computer-deps.d.ts +29 -0
  127. package/dist/workspace/computer-deps.js +48 -1
  128. package/dist/workspace/computer-for-claim.d.ts +7 -3
  129. package/dist/workspace/computer-for-claim.js +1 -1
  130. package/dist/workspace/computer-providers.d.ts +6 -2
  131. package/dist/workspace/computer-providers.js +1 -1
  132. package/dist/workspace/index.d.ts +1 -1
  133. package/dist/workspace/index.js +1 -1
  134. package/dist/workspace.d.ts +0 -3
  135. package/dist/workspace.js +0 -3
  136. package/launcher/agentrun-serve +6 -33
  137. package/package.json +14 -14
  138. package/templates/inbound-lead/agent.md +1 -1
  139. package/templates/kyb/agent.md +1 -1
  140. package/dist/app.d.ts +0 -5
  141. package/dist/app.js +0 -514
  142. package/dist/bounds.d.ts +0 -26
  143. package/dist/bounds.js +0 -137
  144. package/dist/console/assets/index-35-7aeIZ.js +0 -519
  145. package/dist/console/assets/index-Cejbov-Y.css +0 -1
  146. package/dist/content-filter.d.ts +0 -7
  147. package/dist/content-filter.js +0 -23
  148. package/dist/disk.d.ts +0 -33
  149. package/dist/disk.js +0 -85
  150. package/dist/door-line.d.ts +0 -23
  151. package/dist/door-line.js +0 -83
  152. package/dist/harness-app.d.ts +0 -69
  153. package/dist/harness-app.js +0 -1162
  154. package/dist/request-start.d.ts +0 -27
  155. package/dist/request-start.js +0 -381
  156. package/dist/run-box.d.ts +0 -205
  157. package/dist/run-box.js +0 -661
  158. package/dist/run-holder.d.ts +0 -52
  159. package/dist/run-holder.js +0 -139
  160. package/dist/runs.d.ts +0 -1200
  161. package/dist/runs.js +0 -4103
  162. package/dist/served-only.d.ts +0 -5
  163. package/dist/served-only.js +0 -12
@@ -113,11 +113,13 @@ export function bookingOfAnswer(records, given) {
113
113
  /** A host check's refusal as the cap's rule reads it (AdapterRunSpec.cap.park). */
114
114
  const refusalOf = (refusal) => ({ message: refusal.refuse, forGood: refusal.forGood ?? true, ...(refusal.figures ? { figures: refusal.figures } : {}) });
115
115
  /** The record on `root` of the run's Harness: what the journal holds already read once, and every call a crash or a
116
- * fault left with a start and no end ended interrupted (the CLI never runs it again: its own resume says so). */
117
- async function openCliRecord(harness, journal, context) {
116
+ * fault left with a start and no end ended interrupted (the CLI never runs it again: its own resume says so). Each entry
117
+ * it writes carries when it was written (`at`, ms, from the loop's clock `now`), as pi's own entries carry their
118
+ * message's timestamp: the Timeline dates its rows by them. */
119
+ async function openCliRecord(harness, journal, context, now) {
118
120
  const root = await harness.root(context);
119
121
  const append = async (kind, data) => {
120
- await harness.commit((tx) => tx.appendEntry(root.id, { kind, data: data }), context);
122
+ await harness.commit((tx) => tx.appendEntry(root.id, { kind, data: { ...data, at: now() } }), context);
121
123
  };
122
124
  // Each call started on the record: whether it has its end; and each end, by call id.
123
125
  const started = new Map();
@@ -182,7 +184,7 @@ async function openCliRecord(harness, journal, context) {
182
184
  input: (input, origin) => inTurn(async () => {
183
185
  if (personWritten)
184
186
  return;
185
- await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input }] }), context);
187
+ await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] }), context);
186
188
  personWritten = true;
187
189
  }),
188
190
  async start(callId, tool, input, replaySafe) {
@@ -211,12 +213,12 @@ async function openCliRecord(harness, journal, context) {
211
213
  await harness.commit(async (tx) => {
212
214
  if (await tx.submissionByRequest(root.id, requestId))
213
215
  return;
214
- const asked = await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "person", text: prompt }, model: [{ role: "user", content: prompt }] });
216
+ const asked = await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "person", text: prompt }, model: [{ role: "user", content: prompt, timestamp: now() }] });
215
217
  if (status !== "completed") {
216
218
  await tx.createSubmission({ type: "input", conversationId: root.id, requestId, status: "unanswered", entry: asked.id, reason: `the end-of-run turn ended ${status}` });
217
219
  return;
218
220
  }
219
- const answered = await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "model", text: said }, model: [{ role: "assistant", content: [{ type: "text", text: said }] }] });
221
+ const answered = await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "model", text: said }, model: [{ role: "assistant", content: [{ type: "text", text: said }], timestamp: now() }] });
220
222
  await tx.createSubmission({ type: "input", conversationId: root.id, requestId, status: "done", entry: asked.id, answer: answered.id });
221
223
  }, context);
222
224
  }),
@@ -242,6 +244,9 @@ function adapterLoop(specOf, options, deps) {
242
244
  };
243
245
  let stopped = () => { };
244
246
  const stopping = new Promise((resolve) => (stopped = resolve));
247
+ /** Aborted by any stop of the run (AdapterRun.stopped, with the claim's signal). */
248
+ const stopAbort = new AbortController();
249
+ void stopping.then(() => stopAbort.abort(new Error("the run was stopped")));
245
250
  let parked = () => { };
246
251
  const parking = new Promise((resolve) => (parked = resolve));
247
252
  let finished;
@@ -325,6 +330,14 @@ function adapterLoop(specOf, options, deps) {
325
330
  /** The raises this claim has: the state the ones before left (the kernel cap's takeRaises, in arrival order), the rows
326
331
  * to take in the raise entry's commit, whether any resumes a paused run, and the budget it answered. */
327
332
  const raising = { takes: [], resumes: false, resuming: false };
333
+ /** The cap the run is held to after a raise: the newest raise entry's (read from the run's root when a claim opens, then
334
+ * each one this claim's raise commit lands), else none and the spec's figure (its launch's) holds. The spec gives the
335
+ * launch's cap and nothing more (a raise is a command row, all the server writes), so this is the one place a raise
336
+ * reaches every admission (runCap's capUsd) and every park (the pending budget's cap), on this claim and any later
337
+ * one, another runner's included. */
338
+ let raisedCapUsd;
339
+ /** The run's cap now: the newest raise's, else the spec's. */
340
+ const capNow = () => raisedCapUsd ?? specNow?.runCap.capUsd();
328
341
  /** The pass's MCP (spec.mcp), until the pass ends; and whether a command row came since its credentials were last made
329
342
  * fresh (a parked token may have expired meanwhile). */
330
343
  let mcp;
@@ -442,6 +455,9 @@ function adapterLoop(specOf, options, deps) {
442
455
  throw error;
443
456
  }
444
457
  await landed;
458
+ // The raise holds from here, at every admission and park: once its entry is in, never before.
459
+ if (data.capUsd > 0)
460
+ raisedCapUsd = data.capUsd;
445
461
  }
446
462
  const steer = async (command) => {
447
463
  // Handed over before the session is open: placed once it is, its outcome the real one (never taken and then dropped).
@@ -570,7 +586,8 @@ function adapterLoop(specOf, options, deps) {
570
586
  const theCap = () => {
571
587
  if (!specNow?.runCap)
572
588
  throw new Error("the run's spec gives no cap (AdapterRunSpec.runCap)");
573
- return (capBuilt ??= runCap({ sessions, ...specNow.runCap }));
589
+ // The cap each admission reads is the run's now (capNow): a raise taken on this claim or an earlier one.
590
+ return (capBuilt ??= runCap({ sessions, ...specNow.runCap, capUsd: capNow }));
574
591
  };
575
592
  const flushed = { flush: () => deps.flush() };
576
593
  const earlierDecisions = sessionSpendOf(await sessions.read(DECISION_SESSION)).spentUsd;
@@ -621,7 +638,7 @@ function adapterLoop(specOf, options, deps) {
621
638
  return;
622
639
  passGate.expect(writesEntry(kind, test), { run: { summary } }).catch(() => undefined);
623
640
  };
624
- const runOf = { harness, registry, setModels: (given) => (models = given), ledger, ...(deps.redact ? { redact: deps.redact } : {}), signal: deps.signal, phase, rowSummaryOn };
641
+ const runOf = { harness, registry, setModels: (given) => (models = given), ledger, ...(deps.redact ? { redact: deps.redact } : {}), signal: deps.signal, stopped: AbortSignal.any([deps.signal, stopAbort.signal]), phase, rowSummaryOn };
625
642
  // The spec, its MCP claim step among it (mcpForClaim, before the session opens). A refusal there ends the run in its
626
643
  // words with nothing sent; a claim lost during its refresh ends the loop with nothing more written. A claim the spec
627
644
  // refuses (ClaimRefused: a handed sign-in that won't read back) ends the run in its words too.
@@ -636,6 +653,10 @@ function adapterLoop(specOf, options, deps) {
636
653
  return await writeEnd(harness, await harness.root(context), gate, { state: "failed", summary: error.message }, []);
637
654
  if (error instanceof ClaimRefused)
638
655
  return await writeEnd(harness, await harness.root(context), gate, { state: "failed", summary: error.message }, []);
656
+ // A person's stop while the spec was built (it waited on a harness's install): the run ends stopped, in the stop's
657
+ // words, its row taken; the work it waited on goes on for the next run.
658
+ if (stopReason?.kind === "command")
659
+ return await writeEnd(harness, await harness.root(context), gate, { state: "stopped", summary: endedBy(stopReason.cancel) }, [stopReason.commandId]);
639
660
  throw error;
640
661
  }
641
662
  mcp = spec.mcp;
@@ -678,7 +699,7 @@ function adapterLoop(specOf, options, deps) {
678
699
  // reaches pi: pi stores the refused turn only after it, so a claim lost in between leaves the pause, and the next
679
700
  // claim resumes the run parked (an unanswered pause), never ends it as a failed turn. One that cannot land (the
680
701
  // journal sealed) is left to the turn's end, as before.
681
- const park = spec.cap?.park(refusalOf(answer));
702
+ const park = spec.cap?.park(refusalOf(answer), raisedCapUsd ?? spec.cap.capUsd);
682
703
  if (park?.outcome === "parked" && !pausedAtRefusal && harness && gate && !gate.sealed) {
683
704
  const on = gate;
684
705
  // From here a raise row waits for the next claim (raise): one taken now would answer no pause this claim
@@ -712,7 +733,7 @@ function adapterLoop(specOf, options, deps) {
712
733
  await booking.bookCut();
713
734
  const gateOf = preIntentGate(spec, hooks);
714
735
  // A CLI's run: the loop keeps its visible record (record: "loop"), every call a crash or a fault left open ended.
715
- const record = spec.record === "loop" ? await openCliRecord(harness, gate.journal, context) : undefined;
736
+ const record = spec.record === "loop" ? await openCliRecord(harness, gate.journal, context, now) : undefined;
716
737
  cliRecord = record;
717
738
  const tools = [...spec.session.tools, ...(mcp?.tools ?? [])].map((tool) => ({
718
739
  ...tool,
@@ -828,6 +849,10 @@ function adapterLoop(specOf, options, deps) {
828
849
  }, context), now);
829
850
  await computerNow.up();
830
851
  }
852
+ // The cap a raise left the run at, from its root (the newest raise entry), before any request of this claim: a
853
+ // claim that takes over a raised run (a resume, another runner's) holds it to the raise, never the launch's cap.
854
+ if (spec.cap)
855
+ raisedCapUsd = (await raiseStateOf()).lastRaise?.to ?? raisedCapUsd;
831
856
  // A run brought back from a park: the raises its claim has are taken together, once its delivery is done. So is a
832
857
  // run whose journal still holds an unanswered budget pause, whatever its row said at the claim: a resumed claim lost
833
858
  // before its raise entry landed leaves the run running, its pause unanswered and its raises untaken.
@@ -855,6 +880,13 @@ function adapterLoop(specOf, options, deps) {
855
880
  // again on the same budget; its next refusal (a raise short of the need) parks it anew through the cap's rule.
856
881
  await deps.delivered;
857
882
  raising.resuming = false;
883
+ // A person's stop or cancel that woke the parked run is its end, before any park again: given back parked on
884
+ // the same budget, its stop untaken, the run would be claimed again at every poll and never end (#2204). It
885
+ // ends as a stop does mid-turn: in the stop's words, its row taken, with what the end-of-run step keeps of a
886
+ // cut run.
887
+ if (stopReason?.kind === "command") {
888
+ return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(stopReason.cancel) }, [stopReason.commandId], await cutRows(claim, spec, "stopped"));
889
+ }
858
890
  const paused = raising.budget;
859
891
  const resumes = raising.resumes;
860
892
  await takeRaises();
@@ -897,7 +929,7 @@ function adapterLoop(specOf, options, deps) {
897
929
  }
898
930
  if (follow) {
899
931
  const theRoot = root;
900
- await harness.commit((tx) => tx.appendEntry(theRoot.id, { kind: KINDS.message, data: { role: "person", text: follow.text, origin: { kind: "server", reason: "approval" } } }), context);
932
+ await harness.commit((tx) => tx.appendEntry(theRoot.id, { kind: KINDS.message, data: { role: "person", text: follow.text, origin: { kind: "server", reason: "approval" }, at: now() } }), context);
901
933
  await session.send(follow.text, { id: `agentrun:approval:${follow.callIds[0]}` });
902
934
  followedUp = true;
903
935
  }
@@ -993,7 +1025,7 @@ function adapterLoop(specOf, options, deps) {
993
1025
  // A turn the host's check refused: what that does to the run is the cap's rule (parkOf), as on main. A refusal a
994
1026
  // raise could fix parks the run on a raise; one no raise could fix (or a check with no cap) fails it, in the
995
1027
  // check's own words, never as a run with no answer.
996
- const park = spec.cap?.park(refusalOf(refused));
1028
+ const park = spec.cap?.park(refusalOf(refused), raisedCapUsd ?? spec.cap.capUsd);
997
1029
  if (park?.outcome === "parked" && pausedAtRefusal) {
998
1030
  // Its pause and the run parked landed before pi heard of the refusal.
999
1031
  await releaseHost(harness);
@@ -2,11 +2,13 @@ import type { Context } from "@earendil-works/chord";
2
2
  import { type CapModel } from "@parcha/agentrun-kernel/kernel/cap";
3
3
  import type { HostTool, Wire } from "@parcha/agentrun-kernel";
4
4
  import type { Approvals } from "../approvals.js";
5
+ import type { installSettled } from "../harness-install.js";
5
6
  import type { LiveHandover, LiveViewerStore } from "../browser-live.js";
6
7
  import type { PinnedModel, Tier } from "../model.js";
7
8
  import { type RunLaunch } from "../run-launch.js";
8
9
  import type { Store } from "../store/store.js";
9
10
  import { type Permission, type RunFiles, type SettingFrom } from "../tool-gate.js";
11
+ import { loadToolSettings } from "../tool-plane.js";
10
12
  import { type ToolHost } from "../tools.js";
11
13
  import { type HostToolCtx } from "../host-tools.js";
12
14
  import { type LearnedWorkflow } from "../learning.js";
@@ -87,6 +89,9 @@ export interface AdapterSpecDeps {
87
89
  readonly baseUrl?: string;
88
90
  readonly fetch?: typeof fetch;
89
91
  };
92
+ /** How a CLI run's claim waits for its harness's first-use install (harness-install.ts installSettled); a test wraps it
93
+ * to see the claim reach the wait. Absent, installSettled itself. */
94
+ readonly installSettled?: typeof installSettled;
90
95
  /** A test runner's fake GitHub API, where the GitHub App's installation tokens are minted (runner/github-app.ts). Absent,
91
96
  * https://api.github.com: the CLI's runner never sets it, and no environment variable, flag or setting maps onto it. */
92
97
  readonly githubApi?: string;
@@ -145,6 +150,9 @@ export declare function adapterRunGate(store: Pick<Store, "settings">, claim: Pi
145
150
  }, root: RunFiles): Promise<NonNullable<AdapterRunSpec["gate"]> & {
146
151
  readonly permissions: RunPermissions;
147
152
  }>;
153
+ /** The server's tool settings from the store now; a read that throws is unread (no value of it said). A workflow's call
154
+ * and model nodes read theirs through it too (workflow-spec.ts callPolicyOf), so both gates fail closed alike. */
155
+ export declare function storeSettings(store: Pick<Store, "settings">): Promise<Awaited<ReturnType<typeof loadToolSettings>>>;
148
156
  /** pi's spec for a claimed run. What it makes for the run (its Archil mount credential, its Workspace, its computer, its
149
157
  * tools) is held until the spec's release; a build that throws part-way lets go what it made by then (spec-holds.ts). */
150
158
  export declare function adapterRunSpecFromLaunch(launch: RunLaunch, run: AdapterRun, deps: AdapterSpecDeps, claim: Claim): Promise<AdapterRunSpec>;
@@ -27,7 +27,7 @@ import { COMPUTER_ROOT, runFolder } from "../workspace/paths.js";
27
27
  import { runTools, withKindTools } from "../workspace/run-tools.js";
28
28
  import { INPUTS_DIR, UPLOADS_DIR, Uploads } from "../uploads.js";
29
29
  import { handedSignInReadsBack, signInReads } from "../sign-ins-store.js";
30
- import { UNREADABLE_SIGN_IN } from "../runs.js";
30
+ import { UNREADABLE_SIGN_IN } from "../run-view.js";
31
31
  import { claimSecrets, withModelKeys } from "./claim-secrets.js";
32
32
  import { mcpForClaim } from "./mcp-run.js";
33
33
  import { join } from "node:path";
@@ -93,8 +93,9 @@ export async function adapterRunGate(store, claim, revision, root) {
93
93
  const permissions = { policy: (tool) => gate.policy(tool), denyFrom: (tool) => gate.denyFrom(tool), refresh: async () => { current = await storeSettings(store); } };
94
94
  return Object.assign(decide, { askedAs: (tool) => gate.askedAs(tool), permissions });
95
95
  }
96
- /** The server's tool settings from the store now; a read that throws is unread (no value of it said). */
97
- async function storeSettings(store) {
96
+ /** The server's tool settings from the store now; a read that throws is unread (no value of it said). A workflow's call
97
+ * and model nodes read theirs through it too (workflow-spec.ts callPolicyOf), so both gates fail closed alike. */
98
+ export async function storeSettings(store) {
98
99
  try {
99
100
  return await loadToolSettings(store);
100
101
  }
@@ -235,12 +236,12 @@ async function adapterSpec(launch, run, deps, claim, holds) {
235
236
  ...(launch.capMode === "strict" ? { mode: "strict" } : {}),
236
237
  };
237
238
  // The run's cap figure and what a refusal does to it (parkOf, with the kernel's raise rule): present only when the run
238
- // has a cap.
239
+ // has a cap. A park names the cap the loop holds the run to then (a raise's, else this one).
239
240
  const cap = capUsd === undefined
240
241
  ? undefined
241
242
  : {
242
243
  capUsd,
243
- park: (refusal) => parkOf(refusal, capUsd),
244
+ park: (refusal, capNow) => parkOf(refusal, capNow),
244
245
  checkRaise,
245
246
  followUpOf: (raised) => followUpOf(raised),
246
247
  };
@@ -3,6 +3,7 @@ import type { Models } from "@earendil-works/pi-ai";
3
3
  import { type Extension, type Harness, type Registry } from "@earendil-works/pi-durable";
4
4
  import type { AgentAdapter, SessionIO, Wire } from "@parcha/agentrun-kernel";
5
5
  import { type ProviderPolicy } from "@parcha/agentrun-kernel/host";
6
+ import { CALL_REFUSED } from "@parcha/pi-durable-agent/timeline";
6
7
  /** What the adapter loop lends pi for one claim: the run's Harness, its registry, and where pi's models go. */
7
8
  export interface PiRun {
8
9
  readonly harness: Harness;
@@ -94,6 +95,9 @@ export declare function refusalWords(): {
94
95
  text: string;
95
96
  }[];
96
97
  isError: true;
98
+ details: {
99
+ [CALL_REFUSED]: true;
100
+ };
97
101
  } | undefined;
98
102
  readonly held: number;
99
103
  };
@@ -7,6 +7,7 @@ import { randomBytes } from "node:crypto";
7
7
  import { DEFAULT_HARNESS } from "../../harness.js";
8
8
  import { sessionProvider } from "../../port-models.js";
9
9
  import { KINDS } from "../journal-kinds.js";
10
+ import { CALL_REFUSED } from "@parcha/pi-durable-agent/timeline";
10
11
  const PROVIDER = "agentrun-session";
11
12
  const INPUT_REQUEST = "agentrun:input";
12
13
  /** pi as an AgentAdapter for one claim's run. */
@@ -227,7 +228,9 @@ export function refusalWords() {
227
228
  const blocked = result.diagnostics?.some((diagnostic) => diagnostic.code === "blocked");
228
229
  if (text === undefined || !blocked)
229
230
  return undefined;
230
- return { output: [{ type: "text", text }], isError: true };
231
+ // Marked refused in its details (which the model never reads): its Timeline rows say it was refused, never that it
232
+ // ran and failed.
233
+ return { output: [{ type: "text", text }], isError: true, details: { [CALL_REFUSED]: true } };
231
234
  },
232
235
  get held() {
233
236
  return words.size;
@@ -14,17 +14,28 @@ export async function runnerBeside(dataDir, { loops, env } = {}) {
14
14
  // The server's store, the runner's one way in (main.ts openRunnerStore, store/open.ts): Postgres when this process's
15
15
  // AGENTRUN_STORE_URL secret names one, else SQLite in the data directory; a schema it does not know is RunnerRefused.
16
16
  const { store } = await openRunnerStore(dataDir, process.env, (message) => void process.stderr.write(`agentrun-serve runner: ${message}\n`), undefined);
17
- // The server's seal key (seal-key.ts): the one handed over (read through secrets.js, which moves it out of the
18
- // environment as it loads), else the one the server keeps under the config home. A runner never starts without it: it
19
- // seals the live-viewer tokens, and there is no stand-in key.
17
+ // The server's seal key (seal-key.ts), booted the one way and checked against the store: the one handed over (read
18
+ // through secrets.js, which moves it out of the environment as it loads), else the one in the data directory. A runner
19
+ // never starts without it, nor with a key that is not the store's: it seals the live-viewer tokens, and there is no
20
+ // stand-in key.
20
21
  const { bootSealKey } = await import("../seal-key.js");
21
- const sealKey = bootSealKey().key;
22
+ let seal;
23
+ try {
24
+ seal = await bootSealKey(store, dataDir, { role: "runner" });
25
+ }
26
+ catch (error) {
27
+ await store.close();
28
+ throw error;
29
+ }
22
30
  // The beside-runner sees the server's environment as a separate runner would (runEnv, not withoutFaux): so an API run on
23
31
  // a --faux server reaches the faux gateway and its computers. The run's claim-time computer is composed once, the one way
24
- // (workspace/computer-deps.ts computerDepsFrom), from that same environment.
32
+ // (workspace/computer-deps.ts computerDepsFrom), from that same environment; a Docker computer's mounts by where this
33
+ // process's Docker has the data directory (box-paths.ts), read once.
25
34
  const runs = env ?? runEnv(process.env);
26
- const computers = computerDepsFrom({ env: runs, store, sealKey });
27
- const createLoop = dispatchRunner({ env: runs, data: dataDir, journal: (claim) => store.journal(claim), store, sealKey, routeOf, computerForClaim: computers.computerForClaim, computerDeps: computers.computerDeps });
35
+ const { dockerPathsForRuns } = await import("../box-paths.js");
36
+ const { hostAddressesOnce } = await import("../docker-host-addresses.js");
37
+ const computers = computerDepsFrom({ env: runs, store, sealKey: seal.key, dockerPaths: () => dockerPathsForRuns(runs, dataDir), hostAddresses: () => hostAddressesOnce(runs) });
38
+ const createLoop = dispatchRunner({ env: runs, data: dataDir, journal: (claim) => store.journal(claim), store, sealKey: seal.key, routeOf, computerForClaim: computers.computerForClaim, computerDeps: computers.computerDeps });
28
39
  const runner = startRunner({ store, createLoop, ...(loops !== undefined ? { loops } : {}) });
29
- return { runner, close: async () => { await runner.close(); await store.close(); } };
40
+ return { runner, close: async () => { await runner.close(); await store.close(); seal.release(); } };
30
41
  }
@@ -7,7 +7,7 @@
7
7
  // other per-claim secret; they come through mcp-claim.ts, which already opens them from the store under the claim.)
8
8
  import { decisionKeysFor } from "../decisions.js";
9
9
  import { GATEWAY_KEY_ENV, PROVIDER_KEYS } from "../model.js";
10
- import { keysFor, needsOf, RUN_SECRETS } from "../runs.js";
10
+ import { keysFor, needsOf, RUN_SECRETS } from "../run-secrets.js";
11
11
  import { DECISION_KEYS, withoutSecrets } from "../secrets.js";
12
12
  import { getSealedKey } from "../server-keys.js";
13
13
  import { handsParallel } from "../tool-plane.js";
@@ -19,6 +19,8 @@ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
19
19
  import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
20
20
  import { checkRaise, followUpOf, parkOf } from "@parcha/agentrun-kernel/kernel/cap";
21
21
  import { thinkingFor } from "../adapters.js";
22
+ import { installDirOf, installingWords, installSettled } from "../harness-install.js";
23
+ import { HarnessUnavailable } from "../provider.js";
22
24
  import { effortGuidance } from "../effort-guidance.js";
23
25
  import { environmentLine } from "../environment.js";
24
26
  import { harnessOf } from "../harness-table.js";
@@ -225,6 +227,17 @@ async function cliSpec(launch, run, deps, claim, holds) {
225
227
  holdClaimed(redact, claimed);
226
228
  const env = cliRunEnv(deps.env, deps.data, claimed);
227
229
  const chosen = await modelsOf(entry, env, modelAskOf(launch.model, body.model));
230
+ // A harness that installs on first use, whose install is running now (the server started it at an agent's save, or a
231
+ // run's start): the claim waits for it, bounded by the install's own limit, saying so on the run's timeline, and runs on
232
+ // it. A stop of the run ends the wait at once (the install goes on). An install that failed fails the run in its own
233
+ // words; with none running, the adapter says what is missing, as before.
234
+ if (entry.installs && entry.pins) {
235
+ const installs = entry.installs;
236
+ const waitOn = run.stopped ?? run.signal;
237
+ const settled = await (deps.installSettled ?? installSettled)(installs, installDirOf(deps.data, name), await entry.pins(), { ...(waitOn ? { signal: waitOn } : {}), onWait: () => run.phase?.(installingWords(installs.label)) });
238
+ if (typeof settled === "object")
239
+ throw new HarnessUnavailable(settled.failed, "install");
240
+ }
228
241
  const built = await entry.adapter(env, { model: chosen.model, models: chosen.models, unpriced: chosen.unpriced, ...(native.length ? { skills: native } : {}) });
229
242
  // The harness's own session options, its private directory and its working directory (SessionIO's dir and cwd, which
230
243
  // every CLI adapter reads), set on its open here, so the loop lends the session nothing of its own. A turn that ends on
@@ -260,7 +273,8 @@ async function cliSpec(launch, run, deps, claim, holds) {
260
273
  ? undefined
261
274
  : {
262
275
  capUsd,
263
- park: (refusal) => parkOf(refusal, capUsd),
276
+ // A park names the cap the loop holds the run to then (a raise's, else this one).
277
+ park: (refusal, capNow) => parkOf(refusal, capNow),
264
278
  checkRaise,
265
279
  followUpOf: (raised) => followUpOf(raised),
266
280
  };
@@ -118,12 +118,16 @@ export interface CallStartData {
118
118
  readonly input: unknown;
119
119
  /** May run again after a crash (it changes nothing outside the run): the tool registry's own flag. */
120
120
  readonly replaySafe: boolean;
121
+ /** When it was written (ms, the loop's clock): the Timeline dates the call's row by it. */
122
+ readonly at?: number;
121
123
  }
122
124
  export type CallStatus = "done" | "failed" | "refused" | "interrupted";
123
125
  export interface CallEndData {
124
126
  readonly callId: string;
125
127
  readonly status: CallStatus;
126
128
  readonly output?: unknown;
129
+ /** When it was written (ms, the loop's clock): the Timeline dates the result's row by it. */
130
+ readonly at?: number;
127
131
  }
128
132
  /** What a call that already ended answers when it is asked for again (a parked call's resume, a CLI's re-issue of its id):
129
133
  * its recorded output; for one a crash cut with none, the kernel's words for an outcome not known (INTERRUPTED_TEXT);
@@ -145,6 +149,8 @@ export interface MessageData {
145
149
  * answer's output tokens when known. The loop reads it as pi's stopReason (loop.ts cutLast). */
146
150
  readonly stopReason?: "length";
147
151
  readonly outputTokens?: number;
152
+ /** When it was written (ms, the loop's clock): the Timeline dates the message's row by it. */
153
+ readonly at?: number;
148
154
  }
149
155
  /** What an approval costs, as main's card shows it (tool-gate.ts ApprovalPrice): dollars, or "not metered". */
150
156
  export type ApprovalPrice = number | "not metered";
@@ -12,7 +12,7 @@ export interface LiveTicker {
12
12
  /** Stops ticking at once and writes nothing more, what is pending included: a runner killed (a crash) lets nothing go. */
13
13
  stop(): void;
14
14
  }
15
- /** Wraps `createLoop` so its loops' held states reach run_live, batched per tick. */
15
+ /** Wraps `createLoop` so its loops' held states reach run_live, batched per tick, cut by each loop's redactor. */
16
16
  export declare function withLiveTicker(store: {
17
17
  readonly live: Live;
18
18
  }, createLoop: LoopFactory, options?: LiveTickerOptions): LiveTicker;
@@ -1,7 +1,26 @@
1
- /** Wraps `createLoop` so its loops' held states reach run_live, batched per tick. */
1
+ import { redactedAnswer, redactedLive, redactedOutput } from "../key-refusal.js";
2
+ /** A run's held state as the live view keeps it, under `values`, every secret value the run's one redactor holds. A
3
+ * running tool's id and name are cut whole (redactedAnswer). Its args by a workflow output's rule (redactedOutput): every
4
+ * string, property names included; a number whose digits hold a held value or that equals one, withheld; an object two of
5
+ * whose names come out the same once cut, withheld whole, never one value dropped over the other. What is still
6
+ * streaming (the tool's output, the partial answer) by redactedLive: a tail as long as a held value's widest form is held
7
+ * back, so a secret half streamed at a tick shows none of itself; the settled record replaces it whole once it ends. */
8
+ function cutHeld(state, values) {
9
+ if (values.length === 0)
10
+ return state;
11
+ const tools = state.tools.map((tool) => ({
12
+ callId: redactedAnswer(tool.callId, values),
13
+ name: redactedAnswer(tool.name, values),
14
+ ...(tool.args !== undefined ? { args: redactedOutput(tool.args, values) } : {}),
15
+ ...(tool.output !== undefined ? { output: redactedLive(tool.output, values) } : {}),
16
+ }));
17
+ return { tools, ...(state.partial ? { partial: { text: redactedLive(state.partial.text, values) } } : {}) };
18
+ }
19
+ /** Wraps `createLoop` so its loops' held states reach run_live, batched per tick, cut by each loop's redactor. */
2
20
  export function withLiveTicker(store, createLoop, options = {}) {
3
21
  const tickMs = options.tickMs ?? 250;
4
22
  /** The newest held-state reader of each run since the last tick, with the claim it was reported under. */
23
+ // Each with its loop's redactor's values (LoopDeps.redact, the runner's one), read at each tick: a claim can hold more.
5
24
  const changed = new Map();
6
25
  /** The ticker's writes, one after another: a run's drop never lands before a put already on its way. */
7
26
  let writing = Promise.resolve();
@@ -22,7 +41,7 @@ export function withLiveTicker(store, createLoop, options = {}) {
22
41
  writing = writing.then(async () => {
23
42
  if (stopped)
24
43
  return;
25
- const rows = [...changed.values()].map(({ claim, read }) => ({ claim, state: stateOf(read) }));
44
+ const rows = [...changed.values()].map(({ claim, read, values }) => ({ claim, state: cutHeld(stateOf(read), values()) }));
26
45
  changed.clear();
27
46
  if (rows.length > 0)
28
47
  await store.live.put(rows).catch(() => undefined);
@@ -43,12 +62,17 @@ export function withLiveTicker(store, createLoop, options = {}) {
43
62
  changed.delete(claim.runId);
44
63
  };
45
64
  deps.signal.addEventListener("abort", onAbort, { once: true });
65
+ // The run's one redactor: a running tool's args and output and a partial answer can quote a secret the runner holds
66
+ // (a key its claim opened), and the live view is read by people and consoles. A loop given none (never one the runner
67
+ // makes) has no live view: its held state is never written uncut. Nor has a loop whose redactor does not know its
68
+ // values (a bare function): a value still streaming, a number or an object's names cannot be cut by text alone.
69
+ const values = deps.redact?.heldValues;
46
70
  const loop = createLoop({
47
71
  ...deps,
48
72
  live: (read) => {
49
- if (!claim || closed || deps.signal.aborted)
73
+ if (!claim || closed || deps.signal.aborted || values === undefined)
50
74
  return;
51
- changed.set(claim.runId, { claim, read });
75
+ changed.set(claim.runId, { claim, read, values });
52
76
  },
53
77
  });
54
78
  return {
@@ -1,4 +1,5 @@
1
1
  import type { AlsoRow, Claim, Command, Journal } from "../store/store.js";
2
+ import type { Redact } from "./redact.js";
2
3
  export type { AlsoRow, Claim, Command, Journal };
3
4
  /** Why a run ends failed when the answer it would end on was cut at the model's output limit (stopReason "length"): the
4
5
  * answer is unfinished, so the run never reads ended. `tokens`: what the cut answer used, when its harness says. */
@@ -134,8 +135,8 @@ export interface LoopDeps {
134
135
  * journal. Absent: not reported. */
135
136
  live?: (read: () => HeldState | undefined) => void;
136
137
  /** The runner's one redactor (redact.ts): an error's text the loop writes to its run's end goes through it, so no
137
- * secret the runner holds is stored. Absent: none cut. */
138
- redact?: (text: string) => string;
138
+ * secret the runner holds is stored, and its values cut the run's live view (live-ticker.ts). Absent: none cut. */
139
+ redact?: Redact;
139
140
  }
140
141
  /** A run's held state: what pi shows before it stores it. The live view (live/stream.ts) streams it beside the stored
141
142
  * commits' events, in the door's vocabulary (a running tool's tool_execution_start, a partial's message_update). */
@@ -10,7 +10,7 @@ export interface RunnerProcessOptions {
10
10
  /** This runner's name in the runs it claims, its lines and its heartbeat. Default runner.ts runnerName(). */
11
11
  name?: string;
12
12
  /** Each claimed run's loop; default the runner's dispatch over the store (runnerLoop). */
13
- createLoop?: LoopFactory | ((store: Store) => LoopFactory);
13
+ createLoop?: LoopFactory | ((store: Store, sealKey: Buffer) => LoopFactory);
14
14
  onEvent?: (event: RunnerEvent) => void;
15
15
  /** For tests: the clock the heartbeat is written by. Default Date.now. */
16
16
  now?: () => number;
@@ -49,10 +49,17 @@ export declare function openRunnerStore(dataDir: string, env: NodeJS.ProcessEnv,
49
49
  * but not enumerable, as secrets.ts withSecrets makes them: code that reads one by name (the model route) finds it, and
50
50
  * a spread of the object or a spawn given it carries none. */
51
51
  export declare function runEnv(env?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
52
+ /** The beside-runner's environment (the CLI start's server-and-runner): runEnv of `env` with every test switch this
53
+ * process inherited taken out (AGENTRUN_SERVE_FAUX*, the harness table: a leftover in a shell would otherwise reach a
54
+ * run without --faux, as the server's own withoutFaux keeps it from the server), then `switches`, the ones this start
55
+ * enabled (server.ts fauxEnvOf). Deleted from runEnv's result, never spread: its secrets are non-enumerable and a spread
56
+ * drops them. */
57
+ export declare function besideRunEnv(env: NodeJS.ProcessEnv, switches: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
52
58
  /** The runner's loop for every run: the dispatch over the store (createDispatchLoop), each run's harness loop picked by
53
59
  * its launch (harness-loops.ts resolveRunnerLoop), with the data directory, the run environment (runEnv), the store's
54
- * journal, the seal key and the model route. Refused in words with no seal key. */
55
- export declare function runnerLoop(store: Store, dataDir: string, env?: NodeJS.ProcessEnv): LoopFactory;
60
+ * journal, the seal key and the model route. `booted`: the seal key startRunnerProcess booted against the store (else
61
+ * this process's, as it was handed or booted). Refused in words with no seal key. */
62
+ export declare function runnerLoop(store: Store, dataDir: string, env?: NodeJS.ProcessEnv, booted?: Buffer): LoopFactory;
56
63
  /** Where runner `name` writes its heartbeat in `dataDir`. */
57
64
  export declare const heartbeatFile: (dataDir: string, name: string) => string;
58
65
  /** Whether runner `name`'s heartbeat in `dataDir` is fresh: younger than twice the renew interval. */
@@ -69,7 +76,7 @@ export declare function checkRunner(options: {
69
76
  /** Opens the store as a runner and starts claiming runs. */
70
77
  export declare function startRunnerProcess(options: RunnerProcessOptions): Promise<RunnerProcess>;
71
78
  /** Marks `make` as a function of the store (startRunnerProcess gives it the store it opens). */
72
- export declare function ofStore(make: (store: Store) => LoopFactory): (store: Store) => LoopFactory;
79
+ export declare function ofStore(make: (store: Store, sealKey: Buffer) => LoopFactory): (store: Store, sealKey: Buffer) => LoopFactory;
73
80
  /** The runner process's arguments: `--data D [--loops N] [--name N]`, or `--check --data D [--name N]`. Each option with
74
81
  * a value is also taken as `--option=value` (the bin hands a data directory that starts with "-" so, never read as an
75
82
  * option); an empty one is refused like a missing one. */
@@ -9,7 +9,12 @@
9
9
  // lease lapses); then 0. Bad arguments exit 2, a store schema it does not know 3, anything else 1.
10
10
  import { mkdirSync, statSync, utimesSync, writeFileSync } from "node:fs";
11
11
  import { join } from "node:path";
12
- import { SECRET_NAMES, secret } from "../secrets.js";
12
+ import { dockerPathsForRuns } from "../box-paths.js";
13
+ import { hostAddressesOnce } from "../docker-host-addresses.js";
14
+ import { HARNESS_TABLE_ENV } from "../harness-table.js";
15
+ import { FAUX_PREFIX } from "../model.js";
16
+ import { bootSealKey } from "../seal-key.js";
17
+ import { handedSecret, SECRET_NAMES, secret } from "../secrets.js";
13
18
  import { migrationsIn, openStore, SchemaVersionUnknown, storePlace, storeTarget } from "../store/index.js";
14
19
  import { SCHEMA_VERSION } from "../store/schema.js";
15
20
  import { SEAL_KEY_ENV, sealKeyOf } from "../tool-keys.js";
@@ -68,17 +73,31 @@ export function runEnv(env = process.env) {
68
73
  }
69
74
  return out;
70
75
  }
76
+ /** The beside-runner's environment (the CLI start's server-and-runner): runEnv of `env` with every test switch this
77
+ * process inherited taken out (AGENTRUN_SERVE_FAUX*, the harness table: a leftover in a shell would otherwise reach a
78
+ * run without --faux, as the server's own withoutFaux keeps it from the server), then `switches`, the ones this start
79
+ * enabled (server.ts fauxEnvOf). Deleted from runEnv's result, never spread: its secrets are non-enumerable and a spread
80
+ * drops them. */
81
+ export function besideRunEnv(env, switches) {
82
+ const out = runEnv(env);
83
+ for (const name of Object.keys(out))
84
+ if (name.startsWith(FAUX_PREFIX) || name === HARNESS_TABLE_ENV)
85
+ delete out[name];
86
+ return Object.assign(out, switches);
87
+ }
71
88
  /** The runner's loop for every run: the dispatch over the store (createDispatchLoop), each run's harness loop picked by
72
89
  * its launch (harness-loops.ts resolveRunnerLoop), with the data directory, the run environment (runEnv), the store's
73
- * journal, the seal key and the model route. Refused in words with no seal key. */
74
- export function runnerLoop(store, dataDir, env = process.env) {
75
- const sealKey = sealKeyOf(secret(SEAL_KEY_ENV) ?? env[SEAL_KEY_ENV]);
90
+ * journal, the seal key and the model route. `booted`: the seal key startRunnerProcess booted against the store (else
91
+ * this process's, as it was handed or booted). Refused in words with no seal key. */
92
+ export function runnerLoop(store, dataDir, env = process.env, booted) {
93
+ const sealKey = booted ?? sealKeyOf(secret(SEAL_KEY_ENV) ?? env[SEAL_KEY_ENV]);
76
94
  if (!sealKey)
77
95
  throw new RunnerRefused(`A runner needs the server's seal key (${SEAL_KEY_ENV}): start it through the server's launcher, which hands it over.`);
78
96
  const runs = runEnv(env);
79
97
  // The run's computer at its claim, composed once (workspace/computer-deps.ts): none for the runner's place, a box's
80
- // computer by the agent's setting, its keys read from the run environment first, then the store's sealed rows.
81
- const computers = computerDepsFrom({ env: runs, store, sealKey });
98
+ // computer by the agent's setting, its keys read from the run environment first, then the store's sealed rows; a
99
+ // Docker computer's mounts by where this process's Docker has the data directory (box-paths.ts), read once.
100
+ const computers = computerDepsFrom({ env: runs, store, sealKey, dockerPaths: () => dockerPathsForRuns(runs, dataDir), hostAddresses: () => hostAddressesOnce(runs) });
82
101
  const deps = {
83
102
  env: runs, data: dataDir, journal: (claim) => store.journal(claim), store, sealKey, routeOf,
84
103
  computerForClaim: computers.computerForClaim, computerDeps: computers.computerDeps,
@@ -126,13 +145,20 @@ export function checkRunner(options) {
126
145
  /** Opens the store as a runner and starts claiming runs. */
127
146
  export async function startRunnerProcess(options) {
128
147
  const warn = options.warn ?? ((message) => void process.stderr.write(`agentrun-serve runner: ${message}\n`));
129
- const { store, kind, schema } = await openRunnerStore(options.dataDir, options.env ?? process.env, warn, options.storeUrl);
148
+ const env = options.env ?? process.env;
149
+ const { store, kind, schema } = await openRunnerStore(options.dataDir, env, warn, options.storeUrl);
130
150
  let runner;
151
+ let seal;
131
152
  try {
153
+ // The server's seal key, booted the one way the server boots it (seal-key.ts): the one handed over, else the one in
154
+ // this data directory, checked against what the store records. A runner on a store whose secrets another key sealed
155
+ // (another machine's key on a shared Postgres, a lost key file) is refused in the server's words; a runner never makes
156
+ // or records a key.
157
+ seal = await bootSealKey(store, options.dataDir, { given: handedSecret(SEAL_KEY_ENV) ?? env[SEAL_KEY_ENV], role: "runner" });
132
158
  const name = options.name ?? runnerName();
133
- const made = options.createLoop ?? ofStore((opened) => runnerLoop(opened, options.dataDir));
159
+ const made = options.createLoop ?? ofStore((opened, sealKey) => runnerLoop(opened, options.dataDir, undefined, sealKey));
134
160
  // A factory of the store (marked by ofStore) is given the store; a loop factory is used as is.
135
- const createLoop = isStoreFactory(made) ? made(store) : made;
161
+ const createLoop = isStoreFactory(made) ? made(store, seal.key) : made;
136
162
  runner = startRunner({
137
163
  store,
138
164
  createLoop,
@@ -143,16 +169,19 @@ export async function startRunnerProcess(options) {
143
169
  });
144
170
  }
145
171
  catch (error) {
172
+ seal?.release();
146
173
  await store.close();
147
174
  throw error;
148
175
  }
149
176
  let closing;
177
+ const held = seal;
150
178
  return {
151
179
  runner,
152
180
  store: { kind, schema },
153
181
  close: () => (closing ??= (async () => {
154
182
  await runner.close();
155
183
  await store.close();
184
+ held.release();
156
185
  })()),
157
186
  };
158
187
  }
@@ -262,7 +291,7 @@ export async function runnerMain(argv, env = process.env) {
262
291
  name: runnerOf,
263
292
  env,
264
293
  ...(args.loops ? { loops: args.loops } : {}),
265
- createLoop: ofStore((store) => runnerLoop(store, args.dataDir, env)),
294
+ createLoop: ofStore((store, sealKey) => runnerLoop(store, args.dataDir, env, sealKey)),
266
295
  onEvent: (event) => {
267
296
  if (event.type === "error")
268
297
  return void console.error(`Runner ${runnerOf}: ${event.step}${event.runId ? ` ${event.runId}` : ""}: ${event.message}`);