@parcha/agentrun-serve 0.1.0-beta.42 → 0.1.0-beta.44

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 (181) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/README.md +221 -31
  3. package/dist/cli.js +42 -8
  4. package/dist/composio-preset.d.ts +4 -3
  5. package/dist/composio-preset.js +12 -4
  6. package/dist/composio-triggers.d.ts +20 -2
  7. package/dist/composio-triggers.js +183 -17
  8. package/dist/computer-lost.d.ts +11 -0
  9. package/dist/computer-lost.js +19 -0
  10. package/dist/computer-record.d.ts +10 -2
  11. package/dist/computer-record.js +50 -18
  12. package/dist/computer-setting.d.ts +1 -0
  13. package/dist/computer-setting.js +2 -2
  14. package/dist/console/assets/index-BUktRvS-.css +1 -0
  15. package/dist/console/assets/index-nB9kTfIN.js +711 -0
  16. package/dist/console/index.html +2 -2
  17. package/dist/decisions.js +0 -4
  18. package/dist/errors.d.ts +1 -0
  19. package/dist/errors.js +3 -0
  20. package/dist/harness-table.d.ts +51 -3
  21. package/dist/harness-table.js +101 -13
  22. package/dist/harness.d.ts +18 -1
  23. package/dist/harness.js +21 -9
  24. package/dist/host.d.ts +12 -10
  25. package/dist/host.js +18 -16
  26. package/dist/import-sources.js +25 -5
  27. package/dist/import-worker.d.ts +3 -0
  28. package/dist/import-worker.js +7 -5
  29. package/dist/import.d.ts +22 -1
  30. package/dist/import.js +141 -28
  31. package/dist/learn/audit.d.ts +123 -0
  32. package/dist/learn/audit.js +159 -0
  33. package/dist/learn/check.d.ts +3 -0
  34. package/dist/learn/check.js +1 -1
  35. package/dist/learn/compile.d.ts +50 -74
  36. package/dist/learn/compile.js +90 -124
  37. package/dist/learn/delete.d.ts +17 -0
  38. package/dist/learn/delete.js +44 -0
  39. package/dist/learn/folder.d.ts +9 -0
  40. package/dist/learn/folder.js +13 -2
  41. package/dist/learn/promote.d.ts +92 -200
  42. package/dist/learn/promote.js +65 -187
  43. package/dist/learn/replay-calls.d.ts +5 -0
  44. package/dist/learn/replay-calls.js +12 -1
  45. package/dist/learn/secrets.d.ts +8 -0
  46. package/dist/learn/secrets.js +12 -0
  47. package/dist/learn/skills.d.ts +4 -0
  48. package/dist/learn/skills.js +19 -5
  49. package/dist/learn/workflow-nodes.d.ts +23 -3
  50. package/dist/learn/workflow-nodes.js +30 -12
  51. package/dist/learned-nodes.d.ts +9 -34
  52. package/dist/learned-nodes.js +11 -23
  53. package/dist/learned-workflow.d.ts +6 -8
  54. package/dist/learned-workflow.js +18 -57
  55. package/dist/learning-batch.d.ts +13 -5
  56. package/dist/learning-batch.js +34 -8
  57. package/dist/learning-cost.d.ts +111 -4
  58. package/dist/learning-cost.js +120 -3
  59. package/dist/learning-evals.d.ts +2 -0
  60. package/dist/learning-evals.js +4 -3
  61. package/dist/learning-routes.d.ts +8 -0
  62. package/dist/learning-routes.js +18 -1
  63. package/dist/learning-setting.d.ts +16 -1
  64. package/dist/learning-setting.js +34 -2
  65. package/dist/learning.d.ts +1 -1
  66. package/dist/listen-first.d.ts +30 -0
  67. package/dist/listen-first.js +115 -0
  68. package/dist/llms.txt +2 -1
  69. package/dist/mcp-servers-store.d.ts +12 -12
  70. package/dist/model.d.ts +8 -4
  71. package/dist/model.js +16 -8
  72. package/dist/openapi.js +203 -87
  73. package/dist/owner.d.ts +8 -0
  74. package/dist/owner.js +11 -0
  75. package/dist/paid-calls.d.ts +6 -0
  76. package/dist/paid-calls.js +11 -1
  77. package/dist/place.d.ts +8 -3
  78. package/dist/place.js +13 -9
  79. package/dist/provider.js +15 -1
  80. package/dist/run-launch.d.ts +6 -3
  81. package/dist/run-launch.js +2 -0
  82. package/dist/run-learning-served.d.ts +1 -1
  83. package/dist/run-model-key.d.ts +64 -0
  84. package/dist/run-model-key.js +147 -0
  85. package/dist/runner/adapter-loop.d.ts +10 -0
  86. package/dist/runner/adapter-loop.js +26 -4
  87. package/dist/runner/adapter-run-spec.d.ts +6 -3
  88. package/dist/runner/adapter-run-spec.js +83 -25
  89. package/dist/runner/adapters/index.d.ts +4 -2
  90. package/dist/runner/adapters/index.js +13 -4
  91. package/dist/runner/audit.d.ts +68 -0
  92. package/dist/runner/audit.js +349 -0
  93. package/dist/runner/beside.d.ts +2 -1
  94. package/dist/runner/beside.js +6 -3
  95. package/dist/runner/claim-secrets.d.ts +49 -0
  96. package/dist/runner/claim-secrets.js +110 -1
  97. package/dist/runner/cli-run-spec.d.ts +2 -1
  98. package/dist/runner/cli-run-spec.js +44 -15
  99. package/dist/runner/commands.d.ts +3 -6
  100. package/dist/runner/feedback-round.d.ts +3 -2
  101. package/dist/runner/feedback-round.js +8 -7
  102. package/dist/runner/harness-loops.js +31 -23
  103. package/dist/runner/journal-kinds.d.ts +5 -7
  104. package/dist/runner/journal-kinds.js +0 -7
  105. package/dist/runner/learning-dispatch.d.ts +0 -16
  106. package/dist/runner/learning-dispatch.js +4 -47
  107. package/dist/runner/learning-end.d.ts +55 -13
  108. package/dist/runner/learning-end.js +128 -44
  109. package/dist/runner/learning-factory.d.ts +1 -1
  110. package/dist/runner/learning-factory.js +1 -4
  111. package/dist/runner/learning-loop.d.ts +2 -38
  112. package/dist/runner/learning-loop.js +8 -116
  113. package/dist/runner/loop-contract.d.ts +6 -0
  114. package/dist/runner/loop-contract.js +4 -0
  115. package/dist/runner/loop.js +6 -2
  116. package/dist/runner/main.d.ts +1 -0
  117. package/dist/runner/main.js +25 -8
  118. package/dist/runner/memory-claim.d.ts +9 -6
  119. package/dist/runner/memory-claim.js +12 -9
  120. package/dist/runner/promotion.d.ts +55 -54
  121. package/dist/runner/promotion.js +232 -585
  122. package/dist/runner/reflect-hook.d.ts +14 -0
  123. package/dist/runner/reflect-hook.js +28 -3
  124. package/dist/runner/runner.js +57 -4
  125. package/dist/runner/store-secrets.js +9 -5
  126. package/dist/runner/workflow-first.d.ts +6 -5
  127. package/dist/runner/workflow-first.js +17 -12
  128. package/dist/runner/workflow-spec.js +10 -2
  129. package/dist/runs-over-store.d.ts +5 -4
  130. package/dist/runs-over-store.js +13 -3
  131. package/dist/sdk/workflows.d.ts +1 -1
  132. package/dist/server.d.ts +64 -50
  133. package/dist/server.js +516 -134
  134. package/dist/store/index.d.ts +2 -2
  135. package/dist/store/index.js +1 -1
  136. package/dist/store/seal.d.ts +20 -2
  137. package/dist/store/seal.js +24 -8
  138. package/dist/store/sqlite/run-launch.d.ts +4 -1
  139. package/dist/store/sqlite/run-launch.js +12 -0
  140. package/dist/store/sqlite/store.d.ts +3 -2
  141. package/dist/store/sqlite/store.js +119 -16
  142. package/dist/store/store.d.ts +41 -3
  143. package/dist/store-reads/analytics.js +11 -1
  144. package/dist/store-reads/learning.d.ts +57 -7
  145. package/dist/store-reads/learning.js +194 -28
  146. package/dist/store-reads/loop.d.ts +4 -39
  147. package/dist/store-reads/loop.js +10 -79
  148. package/dist/store-reads/stats.js +13 -3
  149. package/dist/store-view.d.ts +5 -1
  150. package/dist/store-view.js +12 -1
  151. package/dist/telemetry.d.ts +59 -0
  152. package/dist/telemetry.js +153 -0
  153. package/dist/tool-keys-store.d.ts +1 -1
  154. package/dist/tool-keys.d.ts +2 -2
  155. package/dist/tool-plane.d.ts +12 -12
  156. package/dist/tools.d.ts +11 -11
  157. package/dist/tools.js +18 -5
  158. package/dist/trigger-adapter.d.ts +3 -0
  159. package/dist/trigger-adapters.d.ts +4 -0
  160. package/dist/trigger-adapters.js +13 -0
  161. package/dist/trigger-composio.d.ts +58 -1
  162. package/dist/trigger-composio.js +160 -6
  163. package/dist/triggers.d.ts +4 -0
  164. package/dist/triggers.js +22 -3
  165. package/dist/validate.d.ts +11 -7
  166. package/dist/validate.js +8 -7
  167. package/dist/workspace/computer-for-claim.d.ts +15 -5
  168. package/dist/workspace/computer-for-claim.js +228 -32
  169. package/dist/workspace/resolve-computer.d.ts +8 -2
  170. package/dist/workspace/resolve-computer.js +1 -1
  171. package/dist/workspace/run-tools.d.ts +1 -1
  172. package/dist/workspace/run-tools.js +14 -3
  173. package/package.json +10 -9
  174. package/dist/console/assets/index-C3gNPz58.css +0 -1
  175. package/dist/console/assets/index-DYJ_wj27.js +0 -711
  176. package/dist/learn/general.d.ts +0 -69
  177. package/dist/learn/general.js +0 -75
  178. package/dist/learn/refit.d.ts +0 -48
  179. package/dist/learn/refit.js +0 -264
  180. package/dist/runner/step-guard.d.ts +0 -62
  181. package/dist/runner/step-guard.js +0 -93
package/dist/server.js CHANGED
@@ -12,7 +12,7 @@ import { isNativeRuntime } from "./native/runtimes.js";
12
12
  import { connectNative, launchNative, updateNative, verifyConnection } from "./native/connection.js";
13
13
  // The /v2 API over the agent store in a data directory: the contract agentrun.v2/0, served on loopback with a bearer
14
14
  // token.
15
- import { createHash, randomBytes } from "node:crypto";
15
+ import { createHash, createHmac, randomBytes } from "node:crypto";
16
16
  import { chmod, lstat, mkdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises";
17
17
  import { createServer } from "node:http";
18
18
  import proxyaddr from "proxy-addr";
@@ -35,18 +35,19 @@ import { FAUX_BROWSER_ENV, NODE_TOOLS, shellTools, toolingOf, toolOf, toolsView
35
35
  import { ApiError, invalid, sentence, unsupported } from "./errors.js";
36
36
  import { deref, explain } from "./explain.js";
37
37
  import { HOME_HOST_OWNED } from "./files.js";
38
- import { DATA_ENV, readJson, syncDir, TOKEN_FILE, writeDurable } from "./server-fs.js";
38
+ import { DATA_ENV, syncDir, TOKEN_FILE, writeDurable } from "./server-fs.js";
39
39
  import { homePath, hostOwnedOf } from "./home-path.js";
40
40
  import { chooseModel, EFFORTS, FAUX_ENV, FAUX_UPSTREAM_ENV, MODEL_NODES, modelSource, THINKING_LEVELS, unpricedModels, withoutFaux } from "./model.js";
41
41
  import { DEFAULT_HARNESS, HARNESSES, harnessOfBody, harnessOffers } from "./harness.js";
42
- import { HARNESS_TABLE_ENV, harnessOf } from "./harness-table.js";
42
+ import { HARNESS_MODULES_ENV, HARNESS_TABLE_ENV, harnessIds, harnessModulesEnv, harnessOf } from "./harness-table.js";
43
43
  import { HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./harness-install.js";
44
- import { DEFAULT_PORT, healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
45
- import { IMPORT_ASKED } from "./import.js";
44
+ import { DEFAULT_PORT, healthOf, hostMemory, maxRunsOf, runsThatFit } from "./host.js";
45
+ import { DEFAULT_HOST, listenOn, minFreeMibOf, takeOver, urlOf } from "./listen-first.js";
46
+ import { IMPORT_ASKED, MAX_CANDIDATES } from "./import.js";
46
47
  import { answerStoreCall } from "./import-proxy.js";
47
48
  import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningFolderOf, learningOf, learnsOf, RUN_LEARNING_USE, seedOf } from "./learning.js";
48
49
  import { askReplay, ReplayRefused, replayView } from "./runner/promotion.js";
49
- import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, promotable, readNote, secretsShown, sendNote, statusesOf, workflowRevisions, writeNote } from "./learning-routes.js";
50
+ import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, promotable, readNote, secretsShown, sendNote, statusesOf, workflowAtDigest, workflowRevisions, writeNote } from "./learning-routes.js";
50
51
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
51
52
  import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
52
53
  import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf, resolvePlace } from "./place.js";
@@ -64,13 +65,14 @@ import { liveReachOf } from "./live-reach.js";
64
65
  import { screenWaitEnded } from "./browser-wait-ended.js";
65
66
  import { durationMs, logLine } from "./print.js";
66
67
  import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, prepareLaunch, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
67
- import { factsOverStore, momentOverStore, summaryOverStore, timelineOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
68
+ import { factsOverStore, momentOverStore, settledStatusOf, summaryOverStore, timelineOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
68
69
  import { HELD_WAITS } from "./runner/journal-kinds.js";
69
70
  import { servedTimelineRows } from "./run-timeline-served.js";
70
71
  import { servedRunDiff, servedRunLearning } from "./run-learning-served.js";
71
72
  import { agentPointers, WITHHELD_LEARNING } from "./handed-values.js";
72
73
  import { runCutValues } from "./run-cut.js";
73
74
  import { readLaunchBody } from "./run-launch.js";
75
+ import { modelKeyMisfit, modelKeyOf, modelKeyRequired, noServerKeyFor, runModelOrigin, serverKeyMissing } from "./run-model-key.js";
74
76
  import { listRunFiles as listRunFilesOverStore, readRunFile as readRunFileOverStore, runGraphView, runTimelines } from "./run-reads-over-store.js";
75
77
  import { triggerTargets } from "./trigger-targets.js";
76
78
  import { labelFilter, labelsIssues } from "./run-labels.js";
@@ -81,11 +83,15 @@ import { watchRun } from "./live/stream.js";
81
83
  import { stats as statsOverStore } from "./store-reads/stats.js";
82
84
  import { analytics as analyticsOverStore } from "./store-reads/analytics.js";
83
85
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
84
- import { openStore, sealRunMcpAuth, StoreOwned, storeTarget } from "./store/index.js";
86
+ import { openStore, openRunLaunch, sealRunLaunch, StoreOwned, storeTarget } from "./store/index.js";
85
87
  import { answerOf, logged } from "./agents.js";
86
88
  import { keepGrade } from "./runner/feedback-round.js";
89
+ import { gradeRow, notAuditableOf } from "./runner/audit.js";
90
+ import { auditsOffWords, auditWriterOf, isShadowRun, readAudits, servingLinesOf } from "./learn/audit.js";
91
+ import { auditLoopOf, COMPILE_AFTER_MAX } from "./learning-setting.js";
87
92
  import { FINAL_STATES, RUN_CHANGES_PAGE } from "./store/store.js";
88
- import { GRADE_SOURCES, GRADES_KEPT, gradeView, LABEL_MAX, promotionsOf, promotionsShown } from "./learn/promote.js";
93
+ import { championOf, GRADE_SOURCES, gradeView, LABEL_MAX, promotionsOf, promotionsShown, servingOf, shownDeep } from "./learn/promote.js";
94
+ import { workflowNodesOf } from "./learn/workflow-nodes.js";
89
95
  import { runModelRef } from "./model.js";
90
96
  import { REDACTED } from "./secret-cut.js";
91
97
  // The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
@@ -106,7 +112,7 @@ import { DRAIN_TIMEOUT } from "./runner/beside.js";
106
112
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
107
113
  import { agentLoopOverStore } from "./store-reads/loop.js";
108
114
  import { printable } from "./learn/index.js";
109
- import { agentCostOverStore, agentLearningOverStore, allInOf, costRunOf, learningCountsOverStore, learningSpendOverStore, runLearningEnd } from "./store-reads/learning.js";
115
+ import { agentCostOverStore, agentLearningOverStore, allInOf, costRunOf, learningCountsOverStore, learningSpendOverStore, runAllInOverStore, runLearningEnd, shadowSpendOf } from "./store-reads/learning.js";
110
116
  import { figuresOf, LearningBatches } from "./learning-batch.js";
111
117
  import { costCsv, learningCostQuery, RUN_PATHS } from "./learning-cost.js";
112
118
  import { evalOf, evalsOf, recordEval } from "./learning-evals.js";
@@ -133,7 +139,8 @@ import { FAUX_GITHUB, FAUX_GITHUB_FILE, startFauxGitHub } from "./github-faux.js
133
139
  import { GITHUB_API } from "./github.js";
134
140
  import { bindingOf, REPO_NAME } from "./run-repo.js";
135
141
  import { HookCut, receivePush } from "./push-handler.js";
136
- import { TRIGGER_ADAPTERS } from "./trigger-adapters.js";
142
+ import { shownTrigger, TRIGGER_ADAPTERS } from "./trigger-adapters.js";
143
+ import { SEALED_FIELD, SEALED_MASK } from "./trigger-composio.js";
137
144
  import { webhook } from "./trigger-webhook.js";
138
145
  import { SCHEME_NAMES } from "./trigger-signatures.js";
139
146
  import { permissionFrom, pinnedEffect, toolEffect } from "./tool-gate.js";
@@ -182,6 +189,12 @@ const IDEMPOTENCY_FILE = ".idempotency.json";
182
189
  * computer kind; `browser`, the browser's own), then its page, files or WebSocket. Both are served by the same code. */
183
190
  const LIVE_PATH = /^\/v2\/runs\/([^/]+)\/(computer|browser)\/live(\/.*)$/;
184
191
  const MAX_BODY = 1 << 20;
192
+ /** The starts that may begin setup's import without ending it (a worker that failed, a process that ended) before the
193
+ * owner's yes is dropped: an import that fails the same way each time is not taken up at every start for good. */
194
+ const IMPORT_STARTS = 3;
195
+ /** The heap of the worker that counts or imports this machine's sessions. A run is read whole, at most MAX_RUN_BYTES of
196
+ * files (import.ts), which this holds several times over. */
197
+ const IMPORT_HEAP_MB = 2048;
185
198
  const MAX_MESSAGE = 20_000;
186
199
  const MAX_WAIT_MS = 25_000;
187
200
  const PAGE_ROWS = 500;
@@ -202,10 +215,12 @@ const LINK_REFUSED = "A link is on the way to this path, or is the file: this se
202
215
  /** Each test switch a run's process reads, by the variable it reads it from: set only under `faux`, but the faux
203
216
  * harness's, which scripts the harnesses with or without it. */
204
217
  const FAUX_SWITCHES = [["fauxBrowser", FAUX_BROWSER_ENV], ["fauxWeb", FAUX_WEB_ENV], ["fauxJev", FAUX_JEV_ENV], ["fauxParallel", FAUX_PARALLEL_ENV], ["fauxOpenrouter", FAUX_OPENROUTER_ENV], ["fauxMonid", FAUX_MONID_ENV], ["fauxUpstream", FAUX_UPSTREAM_ENV], ["fauxExa", FAUX_EXA_ENV], ["fauxMountinfo", FAUX_MOUNTINFO_ENV]];
205
- /** The test switches a run's process gets, each module path resolved: empty outside tests. A test's in-process runner
206
- * takes the same (test/support.mjs startInProcessRunner). */
218
+ /** The switches a run's process gets, each module path resolved: the owner's harness modules (harnessModules), and the test
219
+ * switches, which are empty outside tests. A test's in-process runner takes the same (test/support.mjs
220
+ * startInProcessRunner). */
207
221
  export function fauxEnvOf(options) {
208
- const env = options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {};
222
+ // The owner's harness modules too (not a test switch): a run's process reads the same table as the server.
223
+ const env = { ...harnessModulesEnv(options.harnessModules ?? [], options.data), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}) };
209
224
  if (!options.faux)
210
225
  return env;
211
226
  env[FAUX_ENV] = resolve(options.faux);
@@ -401,6 +416,7 @@ export const ROUTES = [
401
416
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
402
417
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/cost$/, name: "getLearningCost" },
403
418
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/promotions$/, name: "listLearningPromotions" },
419
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/audits$/, name: "listLearningAudits" },
404
420
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "createLearningBatch" },
405
421
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "listLearningBatches" },
406
422
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches\/([^/]+)$/, name: "getLearningBatch" },
@@ -556,7 +572,7 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
556
572
  runtimes: ["runner"],
557
573
  /** The harnesses a revision may name (`definition.harness`), whether this server runs each, and how many at once. */
558
574
  // `keys`, what a model key would unlock, is the key rows' (listToolKeys), never served here.
559
- harnesses: harnesses.map(({ keys: _keys, ...offer }) => ({ ...offer, max_concurrent_runs: Math.min(maxRuns, runsThatFit(offer.id, memory)) })),
575
+ harnesses: harnesses.map(({ keys: _keys, ...offer }) => ({ ...offer, max_concurrent_runs: Math.min(maxRuns, runsThatFit(offer.id, memory, env)) })),
560
576
  /** The places a revision may name (`definition.place`), this host's default, and whether this server has each box. */
561
577
  places: placesOf(boxes, boxAllowOf(env)),
562
578
  models,
@@ -616,8 +632,9 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
616
632
  * (tool-keys-store.ts), never in the clear. */
617
633
  tool_keys: { routes: true, at_rest: "sealed" },
618
634
  /** /settings/mcp-servers: remote MCP servers previewed and saved, each credential sealed under the server's seal key,
619
- * which always exists (seal-key.ts), so MCP credentials are always kept sealed. */
620
- mcp_client: { transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: "sealed", harnesses: [...HARNESSES] },
635
+ * which always exists (seal-key.ts), so MCP credentials are always kept sealed. Every harness of the table runs a
636
+ * grant (runnable.ts takes one on any), a module's among them. */
637
+ mcp_client: { transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: "sealed", harnesses: [...harnessIds(env)] },
621
638
  /** This server's learning switch (`--learning`): on, a run learns when its agent says `learning: true`; off, none does. */
622
639
  learning,
623
640
  /** /settings/webhook: one URL POSTed, signed by the Standard Webhooks spec, when a run needs its person and when it
@@ -681,6 +698,9 @@ export async function startServe(options) {
681
698
  // A harness table module is the server's to name, from `harnessTable` alone, for itself and its runs: one in its own
682
699
  // environment (an operator's export, a leftover) never loads, wherever the server reads its environment.
683
700
  delete process.env[HARNESS_TABLE_ENV];
701
+ // So is the harness modules list, from `harnessModules` alone (an operator names them with --harness-module or
702
+ // AGENTRUN_SERVE_HARNESS_MODULES, which the CLI reads into the option).
703
+ delete process.env[HARNESS_MODULES_ENV];
684
704
  await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
685
705
  // Canonical once, here: a computer's mount source below it must then be its own canonical path, through no link.
686
706
  const data = await realpath(resolve(options.data));
@@ -712,8 +732,8 @@ export async function startServe(options) {
712
732
  const learningBudget = learningBudgetOf(process.env, options.learningBudget);
713
733
  // A limit on a run's requests on free models that is no whole number above 0 stops the start, naming its variable.
714
734
  freeModelRequestsOf(process.env);
715
- const minFreeMib = process.env.AGENTRUN_MIN_FREE_MB ? Number(process.env.AGENTRUN_MIN_FREE_MB) : MIN_FREE_MIB;
716
- if (!(Number.isFinite(minFreeMib) && minFreeMib >= 0))
735
+ const minFreeMib = minFreeMibOf(process.env);
736
+ if (minFreeMib === undefined)
717
737
  throw new Error("AGENTRUN_MIN_FREE_MB is a number of MiB, 0 or more");
718
738
  const minFreeBytes = options.minFreeBytes ?? minFreeMib * 2 ** 20;
719
739
  // The template packages, each checked whole (templates.ts readPackage): a broken one stops the start.
@@ -777,7 +797,11 @@ async function startHolding(options, data, checked, stops) {
777
797
  // shown nowhere.
778
798
  let secretStores;
779
799
  let triggerSettings = new Map();
780
- const base = { ...withoutFaux(process.env), [DATA_ENV]: data, ...(options.allowCodeNodes ? { [CODE_NODES_ENV]: "1" } : {}), ...(options.faux ? { [FAUX_ENV]: resolve(options.faux) } : {}), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}) };
800
+ const base = { ...withoutFaux(process.env), [DATA_ENV]: data, ...(options.allowCodeNodes ? { [CODE_NODES_ENV]: "1" } : {}), ...(options.faux ? { [FAUX_ENV]: resolve(options.faux) } : {}), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}), ...harnessModulesEnv(options.harnessModules ?? [], data) };
801
+ // The table, loaded once here: a harness module that is missing, names a built-in harness or gives half an entry refuses
802
+ // the start, in words, before anything else opens.
803
+ // The harness ids a definition may name here: the table's, the built-in ones and those the modules add.
804
+ const harnesses = harnessIds(base);
781
805
  // The one store (module A), opened here as this data root's single owner, before the settings layers that read it: its
782
806
  // owner lock holds the store to this server (the data root's own lock follows), and it refuses a data directory an
783
807
  // earlier version wrote, in words, to start fresh (no oldHomes/oldLayout checks, no migration). Every agent, run, setting and sign-in is a row; the
@@ -863,6 +887,8 @@ async function startHolding(options, data, checked, stops) {
863
887
  };
864
888
  // Aborted as close() begins: a key's check still waiting on its provider stops waiting, and its save stores nothing.
865
889
  const stopping = new AbortController();
890
+ /** The after-start seal by the events' schemas (composio-triggers.ts sealMarked), drained by stop. */
891
+ let schemaSealed = Promise.resolve();
866
892
  // This server's saved keys, read by name: handed to its own reading and its own runs, never shared with another server.
867
893
  const storedKeys = (name) => toolKeys.value(name);
868
894
  // A stored key that does not open is said once at the start, never a refusal to start.
@@ -1121,6 +1147,19 @@ async function startHolding(options, data, checked, stops) {
1121
1147
  };
1122
1148
  /** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
1123
1149
  const runComputerOf = (runId, view) => runComputerRead(store, runId, view, { context: ctx });
1150
+ /** The run read's path and costs (A8, store-reads/learning.ts runAllInOverStore): `path`; `cost.usd` its own spend, the
1151
+ * job's (its look-back and compile turns are learning's), null while unknown; what learning spent for it
1152
+ * (`learning_usd`) and the two (`all_in_usd`). A cost known only as a bound keeps its bound, and all-in is unknown. */
1153
+ const allInViewOf = async (runId, view) => {
1154
+ const cost = (view.cost ?? {});
1155
+ const own = typeof cost.usd === "number" && cost.upper_bound !== true ? cost.usd : null;
1156
+ const all = await runAllInOverStore(store, runId, own);
1157
+ if (!all)
1158
+ return {};
1159
+ // A bound stays the view's bound. Otherwise usd is the job's (runCostOf's cost_usd, the same figure the cost series
1160
+ // gives): known as it answered even when its look-back's cost is not; the row's while the run is at work.
1161
+ return { path: all.path, cost: { ...cost, ...(cost.upper_bound === true ? {} : { usd: all.usd }), learning_usd: all.learning_usd, all_in_usd: all.all_in_usd } };
1162
+ };
1124
1163
  // The agents accessor the routes call, over the one store (module A): the agents-store functions, with the run-row reads
1125
1164
  // the server makes (store-reads) under `.store`. `.request` is a thin pass-through — the store runs its own transactions,
1126
1165
  // so a call needs no outer serialization. The old Agents class and its per-agent home store are gone.
@@ -1322,6 +1361,10 @@ async function startHolding(options, data, checked, stops) {
1322
1361
  return { learns: false, why: "it is archived." };
1323
1362
  if (learning === "off")
1324
1363
  return { learns: false, why: "this server's learning is off (--learning)." };
1364
+ // A batch starts runs and sends their follow-ups with no caller's model key: none to spend on a server with none.
1365
+ const off = noServerKeyFor(env, "Learning from a CSV");
1366
+ if (off)
1367
+ return { learns: false, why: off };
1325
1368
  if (entry.revision?.kind !== "agentic" || !learnsOf(entry.revision.body.learning))
1326
1369
  return { learns: false, why: "its current revision does not say learning: true. Turn learning on first." };
1327
1370
  return { learns: true };
@@ -1351,8 +1394,9 @@ async function startHolding(options, data, checked, stops) {
1351
1394
  // Every round the run kept (a review follow-up opens a round of its own), in order: what each one learned and merged.
1352
1395
  const newest = await store.learning.proposal(runId);
1353
1396
  const ends = await Promise.all(Array.from({ length: newest?.round ?? 1 }, (_, i) => runLearningEnd(store, runId, i + 1)));
1354
- // A run still going names no path yet (its end writes it): the batch reads it as the agent's until then.
1355
- return figuresOf((await costRunOf(store, run, 0)) ?? { path: "agent", ...(await allInOf(store, run)) }, ends);
1397
+ // A run still going names no path yet (its end writes it): the batch reads it as the agent's until then. Its all-in
1398
+ // is not known while its audit's shadow run is queued or running (shadowSpendOf): the batch closes no row on it.
1399
+ return figuresOf((await costRunOf(store, run, 0)) ?? { path: "agent", ...(await allInOf(store, run)) }, ends, (await shadowSpendOf(store, runId)).open);
1356
1400
  },
1357
1401
  // A batch's reads are the learning routes' reads: the same cut, the same 403 when a sign-in can't be read here.
1358
1402
  shown: (agentId) => learningShown(agentId),
@@ -1371,6 +1415,16 @@ async function startHolding(options, data, checked, stops) {
1371
1415
  return [...serverSecrets(), ...pointers];
1372
1416
  };
1373
1417
  const learningShown = async (agentId) => secretsShown(await learningValues(agentId));
1418
+ // The agent's audit ledger on its learning folder's main (learn/audit.ts), oldest first.
1419
+ const auditsOfAgent = async (agentId) => {
1420
+ const { workspace, end } = learningFolderOf(data, agentId);
1421
+ try {
1422
+ return await readAudits(workspace);
1423
+ }
1424
+ finally {
1425
+ await end().catch(() => undefined);
1426
+ }
1427
+ };
1374
1428
  // What a run held for its owner's OK reads as it stands on its agent's learning folder's main (statusesOf).
1375
1429
  const statuses = (agentId) => statusesOf(data, agentId);
1376
1430
  const viewDepsFor = (origin) => ({ origin, serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)), statuses });
@@ -1435,9 +1489,25 @@ async function startHolding(options, data, checked, stops) {
1435
1489
  tokenUsed.set(req, id);
1436
1490
  return id !== undefined;
1437
1491
  };
1492
+ // Answered keys are kept in the data directory for the retention capabilities state, and written before the answer
1493
+ // is sent, so a client that retries after a restart gets the first answer back.
1494
+ // A key's fingerprint is an HMAC of its request's body (stable JSON) under a key derived from the server's seal key:
1495
+ // never the body, nor a bare digest of it, since a body can hold a credential (a composio trigger's config) and a short
1496
+ // or guessable one could be found from a bare digest by hashing guesses. A trigger create's answer is kept as a read
1497
+ // answers it (replayed). Entries live IDEMPOTENCY_TTL_S (a day), so one an older server wrote (the body itself as its
1498
+ // fingerprint, a composio key in its answer) can outlive an upgrade: the start rewrites each (below, after the trigger
1499
+ // engine), and says how many alone.
1500
+ const fingerprintKey = createHmac("sha256", sealKey).update("agentrun-serve idempotency fingerprint").digest();
1501
+ const fingerprintOf = (text) => createHmac("sha256", fingerprintKey).update(text).digest("hex");
1502
+ /** A kept answer as its replay sends it, by the route its key was used on: a trigger create's (POST /triggers) with its
1503
+ * source as a read answers it now (shownTrigger); every other route's as it was, a run's input above all. */
1504
+ const replayed = (path, body) => (path === "/triggers" ? shownTrigger(body) : body);
1438
1505
  const keptFile = join(data, IDEMPOTENCY_FILE);
1439
1506
  const kept = JSON.parse(await readFile(keptFile, "utf8").catch(() => "null"));
1440
1507
  const idempotency = new Map((kept?.entries ?? []).filter(([, v]) => v?.answer && Date.now() - v.at <= IDEMPOTENCY_TTL_S * 1000));
1508
+ /** How many entries the file held that the start did not keep (expired, or never answered): the file is written again
1509
+ * without them at the start, so no body an older server kept stays on disk past it. */
1510
+ const keptDropped = (kept?.entries?.length ?? 0) - idempotency.size;
1441
1511
  // A failed save rejects only its own caller: the next save starts from a settled chain and writes every kept key.
1442
1512
  let saving = Promise.resolve();
1443
1513
  const keep = () => (saving = saving
@@ -1447,7 +1517,7 @@ async function startHolding(options, data, checked, stops) {
1447
1517
  await writeFile(`${keptFile}.partial`, JSON.stringify({ version: 1, entries }), { mode: 0o600 });
1448
1518
  await rename(`${keptFile}.partial`, keptFile);
1449
1519
  }));
1450
- const host = options.host ?? "127.0.0.1";
1520
+ const host = options.host ?? DEFAULT_HOST;
1451
1521
  // Open setup (no code) only where no one else reaches the port: a loopback listener. Bound to any other address
1452
1522
  // (0.0.0.0 in the image, a LAN address), the first visit takes the printed code even with no public address.
1453
1523
  const openSetup = options.openSetup === true && isLoopback(host);
@@ -1577,6 +1647,137 @@ async function startHolding(options, data, checked, stops) {
1577
1647
  signal: stopping.signal,
1578
1648
  say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
1579
1649
  });
1650
+ // A composio trigger kept with a credential of its config in the clear (saved before the config was sealed) is sealed
1651
+ // before the first request: no answer shows it from this start on.
1652
+ // All of it under the store's secureRewrite, so no file of the store keeps the rows' old bytes (the key): when it can't
1653
+ // finish the scrub (a reader held the log back), it is said by a code alone and the next start finishes it.
1654
+ const sealing = options.store ?? store;
1655
+ const sealKept = () => composioTriggers.sealKept(async (id, source) => void (await sealing.triggers.update(id, { source })));
1656
+ await (sealing === store && store.secureRewrite ? store.secureRewrite(sealKept) : sealKept().then((rewritten) => ({ rewritten, left: undefined })))
1657
+ .then(({ left }) => {
1658
+ if (!left)
1659
+ return;
1660
+ const line = logLine("store", { condition: "store_scrub_not_done", reason: left });
1661
+ if (log)
1662
+ log(line);
1663
+ else
1664
+ process.stderr.write(`agentrun-serve: ${line}\n`);
1665
+ })
1666
+ .catch((error) => void process.stderr.write(`agentrun-serve: sealing the composio triggers' config: ${error.message}\n`));
1667
+ // Then, not waited on: a trigger kept with a value in the clear in a field only its event's schema marks, sealed once
1668
+ // the schemas are read from Composio (composio-triggers.ts sealMarked). Drained by stop before the store closes.
1669
+ /** Trigger `id`'s create answer kept under an Idempotency-Key, its fields `source` now seals (sealed_config) masked: the
1670
+ * after-start seal by the events' schemas finds fields the name rule (shownTrigger, at the start's rewrite of the
1671
+ * records) does not, and a replay must not hand one back. The file is written again when one changed. */
1672
+ const cachedMasked = async (id, source) => {
1673
+ if (maskCached(id, source).length)
1674
+ await keep();
1675
+ };
1676
+ /** The records kept under an Idempotency-Key (their slots) that answered trigger `id`'s create with a field `source`
1677
+ * keeps sealed still in the clear, each masked in the map now (not saved: the caller saves). */
1678
+ function maskCached(id, source) {
1679
+ const fields = Array.isArray(source[SEALED_FIELD]) ? source[SEALED_FIELD].filter((name) => typeof name === "string") : [];
1680
+ const changed = [];
1681
+ for (const [slot, v] of idempotency) {
1682
+ const body = v.answer?.body;
1683
+ if (!v.answer || !isObject(body) || body.id !== id || !isObject(body.source) || !isObject(body.source.config))
1684
+ continue;
1685
+ const config = { ...body.source.config };
1686
+ const hit = fields.filter((name) => Object.hasOwn(config, name) && config[name] !== SEALED_MASK);
1687
+ if (!hit.length)
1688
+ continue;
1689
+ for (const name of hit)
1690
+ config[name] = SEALED_MASK;
1691
+ idempotency.set(slot, { ...v, answer: { ...v.answer, body: { ...body, source: { ...body.source, config, [SEALED_FIELD]: fields } } } });
1692
+ changed.push(slot);
1693
+ }
1694
+ return changed;
1695
+ }
1696
+ /** The records answering trigger `id`'s create once the trigger is gone (deleted, or not read): no trigger is left to
1697
+ * say which of its fields are sealed, so every field of each answer's config is masked in the map (not saved: the
1698
+ * caller saves). A replay of a deleted trigger's create needs none of its values. */
1699
+ function maskCachedGone(id) {
1700
+ const changed = [];
1701
+ for (const [slot, v] of idempotency) {
1702
+ const body = v.answer?.body;
1703
+ if (!v.answer || !isObject(body) || body.id !== id || !isObject(body.source) || !isObject(body.source.config))
1704
+ continue;
1705
+ const names = Object.keys(body.source.config);
1706
+ if (names.every((name) => body.source.config[name] === SEALED_MASK))
1707
+ continue;
1708
+ const config = Object.fromEntries(names.map((name) => [name, SEALED_MASK]));
1709
+ idempotency.set(slot, { ...v, answer: { ...v.answer, body: { ...body, source: { ...body.source, config, [SEALED_FIELD]: names } } } });
1710
+ changed.push(slot);
1711
+ }
1712
+ return changed;
1713
+ }
1714
+ const idempotencySaid = (fields) => {
1715
+ const line = logLine("idempotency", fields);
1716
+ if (log)
1717
+ log(line);
1718
+ else
1719
+ process.stderr.write(`agentrun-serve: ${line}\n`);
1720
+ };
1721
+ const scrubSaid = ({ left }) => {
1722
+ if (!left)
1723
+ return;
1724
+ const line = logLine("store", { condition: "store_scrub_not_done", reason: left });
1725
+ if (log)
1726
+ log(line);
1727
+ else
1728
+ process.stderr.write(`agentrun-serve: ${line}\n`);
1729
+ };
1730
+ schemaSealed = composioTriggers
1731
+ // Compare-and-set on the updatedAt the trigger was read at; and no VACUUM while serving (the marker stays, the next
1732
+ // start's scrub runs it before it serves).
1733
+ .sealMarked(async (id, source, updatedAt, read) => {
1734
+ const written = (await sealing.triggers.update(id, { source }, undefined, updatedAt === undefined ? { ifSource: read } : { ifUpdatedAt: updatedAt, ifSource: read })) !== undefined;
1735
+ // Once the trigger is written its seal stands: a failed save of the cached answers is said, never thrown (the seal
1736
+ // would be undone with the value's one copy). The map holds them masked already, so the next save writes them so.
1737
+ if (written)
1738
+ await cachedMasked(id, source).catch((error) => idempotencySaid({ condition: "idempotency_not_saved", trigger: id, error: typeof error?.code === "string" ? error.code : "error" }));
1739
+ return written;
1740
+ }, async (work) => (sealing === store && store.secureRewrite ? scrubSaid(await store.secureRewrite(work, { vacuum: false })) : void (await work())))
1741
+ .catch((error) => void (stopping.signal.aborted || process.stderr.write(`agentrun-serve: sealing the composio triggers' config by their events' schemas: ${error.message}\n`)));
1742
+ // Each Idempotency-Key record an older server wrote, rewritten before the first request: its fingerprint keyed (the body
1743
+ // it held as its fingerprint is gone) and its answer as a read answers it now. Said with how many alone.
1744
+ {
1745
+ // Each record rewritten, counted once whichever of the two passes below rewrote it.
1746
+ const scrubbed = new Set();
1747
+ // Each cached create answer checked against its trigger as stored, whatever its field's name: a field sealed since
1748
+ // (by its event's schema, whose save of this file failed before a restart) is masked before the first request.
1749
+ const answered = new Set();
1750
+ for (const [slot, v] of idempotency) {
1751
+ const body = v.answer?.body;
1752
+ if (slot.startsWith("/triggers\n") && isObject(body) && typeof body.id === "string")
1753
+ answered.add(body.id);
1754
+ }
1755
+ for (const id of answered) {
1756
+ const row = await sealing.triggers.get(id).catch(() => undefined);
1757
+ // A trigger gone (deleted before this start, by a server that did not mask its answers at the delete) or not read:
1758
+ // every field of its cached answers is masked, as no trigger is left to say which are sealed.
1759
+ const slots = row && isObject(row.source) ? maskCached(id, row.source) : row ? [] : maskCachedGone(id);
1760
+ for (const slot of slots)
1761
+ scrubbed.add(slot);
1762
+ }
1763
+ for (const [slot, v] of idempotency) {
1764
+ const fingerprint = /^[0-9a-f]{64}$/.test(String(v.fingerprint)) ? v.fingerprint : fingerprintOf(String(v.fingerprint));
1765
+ const answer = v.answer && { ...v.answer, body: replayed(slot.slice(0, slot.indexOf("\n")), v.answer.body) };
1766
+ if (fingerprint === v.fingerprint && JSON.stringify(answer?.body) === JSON.stringify(v.answer?.body))
1767
+ continue;
1768
+ idempotency.set(slot, { ...v, fingerprint, ...(answer ? { answer } : {}) });
1769
+ scrubbed.add(slot);
1770
+ }
1771
+ if (scrubbed.size || keptDropped > 0)
1772
+ await keep().catch((error) => void process.stderr.write(`agentrun-serve: idempotency save: ${error.message}\n`));
1773
+ if (scrubbed.size) {
1774
+ const line = logLine("idempotency", { condition: "idempotency_records_scrubbed", count: scrubbed.size });
1775
+ if (log)
1776
+ log(line);
1777
+ else
1778
+ process.stderr.write(`agentrun-serve: ${line}\n`);
1779
+ }
1780
+ }
1580
1781
  /** What a save refused while Composio triggers use the server says to do once they are gone (composio-triggers.ts inUse). */
1581
1782
  const SAVE_AFTER_TRIGGERS = "then save the server again";
1582
1783
  /** What a save over a preset server left at Composio (ComposioDropped), removed there with the key it was made with, in
@@ -1609,18 +1810,21 @@ async function startHolding(options, data, checked, stops) {
1609
1810
  let closing = false;
1610
1811
  const workers = new Map();
1611
1812
  // Once the server closes, no worker starts: a setup still being answered then leaves its yes for the next start.
1612
- const onWorker = (task) => closing ? Promise.resolve({ stopped: true }) : new Promise((answered, failed) => {
1813
+ const onWorker = (task, projects) => closing ? Promise.resolve({ stopped: true }) : new Promise((answered, failed) => {
1613
1814
  const worker = new Worker(new URL("./import-worker.js", import.meta.url), {
1614
1815
  // The secrets this process holds (secrets.ts keeps them out of every environment, so the worker's has none), in the
1615
1816
  // worker's memory alone: what the import cuts out of everything it writes. The keys saved on the Tool keys page are
1616
1817
  // not passed; the worker reads them from the store over the port (sealed rows it opens with the seal key among these
1617
1818
  // secrets), the same cut as the CLI's import, where a saved key and the server's own of the same name may differ.
1618
- workerData: { task, data, home: options.sessionsHome?.home ?? homedir(), ...(options.sessionsHome?.temp ? { temp: options.sessionsHome.temp } : {}), secrets: Object.fromEntries(SECRET_NAMES.flatMap((name) => { const value = name === SEAL_KEY_ENV ? seal.text : secret(name); return value === undefined ? [] : [[name, value]]; })) },
1819
+ workerData: { task, data, ...(projects ? { projects } : {}), home: options.sessionsHome?.home ?? homedir(), ...(options.sessionsHome?.temp ? { temp: options.sessionsHome.temp } : {}), secrets: Object.fromEntries(SECRET_NAMES.flatMap((name) => { const value = name === SEAL_KEY_ENV ? seal.text : secret(name); return value === undefined ? [] : [[name, value]]; })) },
1619
1820
  // Started from a string (node --input-type=module -e, as a test or a `--` command may), the server's flags are given again
1620
1821
  // without that string and its type: a worker started from a file with them is refused. Otherwise the worker
1621
1822
  // inherits them as Node passes them on, which leaves out the flags a worker may not take (on Node 24 a test
1622
1823
  // runner's child holds many).
1623
1824
  ...(process.execArgv.some((arg) => arg.startsWith("--input-type")) ? { execArgv: workerArgs(process.execArgv) } : {}),
1825
+ // Its own heap, at most IMPORT_HEAP_MB whatever the machine's memory: an import that needs more ends as a failed
1826
+ // worker (said, and counted: IMPORT_STARTS), never as a process the system ends for the memory it took.
1827
+ resourceLimits: { maxOldGenerationSizeMb: IMPORT_HEAP_MB },
1624
1828
  });
1625
1829
  workers.set(worker, { task, exit: once(worker, "exit").catch(() => undefined) });
1626
1830
  let answer;
@@ -1651,7 +1855,7 @@ async function startHolding(options, data, checked, stops) {
1651
1855
  if (count)
1652
1856
  return;
1653
1857
  count = { state: "counting" };
1654
- onWorker("plan").then((answer) => void (count = "sessions" in answer ? { state: "counted", projects: answer.projects, sessions: answer.sessions } : undefined), (error) => {
1858
+ onWorker("plan").then((answer) => void (count = "sessions" in answer ? { state: "counted", projects: answer.projects, sessions: answer.sessions, candidates: answer.candidates } : undefined), (error) => {
1655
1859
  count = { state: "failed" };
1656
1860
  process.stderr.write(`agentrun-serve: the count of this machine's sessions failed: ${error.message}\n`);
1657
1861
  });
@@ -1660,25 +1864,69 @@ async function startHolding(options, data, checked, stops) {
1660
1864
  if (task === "plan")
1661
1865
  worker.postMessage("stop"); };
1662
1866
  // The owner's yes, kept until the import ends: a server stopped (or killed) mid-import goes on with it at its next start.
1867
+ // With it: the projects chosen (none named: every project), what earlier starts took, and how many starts began the
1868
+ // import and neither ended it nor were stopped (`starts`).
1663
1869
  const importAsked = join(data, IMPORT_ASKED);
1870
+ /** The yes as kept, or undefined when it cannot be read as one (a file that will not open, text that is no JSON
1871
+ * object, `projects` that is no list of ids): never taken for "every project", which only an empty file or one that
1872
+ * names no projects means. */
1873
+ const askedOf = async () => {
1874
+ const text = await readFile(importAsked, "utf8").catch(() => undefined);
1875
+ if (text === undefined)
1876
+ return undefined;
1877
+ // The yes as an earlier version's setup wrote it is empty: every project, and no earlier start took anything.
1878
+ if (!text.trim())
1879
+ return { agents: [], runs: 0, starts: 0 };
1880
+ let kept;
1881
+ try {
1882
+ kept = JSON.parse(text);
1883
+ }
1884
+ catch {
1885
+ return undefined;
1886
+ }
1887
+ if (typeof kept !== "object" || kept === null || Array.isArray(kept))
1888
+ return undefined;
1889
+ const ids = (value) => (Array.isArray(value) && value.every((id) => typeof id === "string") ? value : undefined);
1890
+ const projects = ids(kept.projects);
1891
+ if (kept.projects !== undefined && !projects)
1892
+ return undefined;
1893
+ return { ...(projects ? { projects } : {}), agents: ids(kept.agents) ?? [], runs: typeof kept.runs === "number" ? kept.runs : 0, starts: typeof kept.starts === "number" ? kept.starts : 0 };
1894
+ };
1664
1895
  let importing;
1665
- /** The import at setup as the owner's console reads it: running, done with what it took, or stopped (the next start
1666
- * goes on with it). */
1896
+ /** The import at setup as the owner's console reads it: running, done with what it took, stopped (the next start
1897
+ * goes on with it), or failed (IMPORT_STARTS starts did not end it: given up, never tried again on its own). */
1667
1898
  let importState;
1668
1899
  /** Never rejects: whatever stops it (the store held past its wait, a file) is said on stderr, and the server goes on. */
1669
1900
  const importAtSetup = () => (importing ??= (async () => {
1670
1901
  importState = { state: "running" };
1902
+ // An import that fails, or ends the process, the same way at every start would be taken up at every start for good:
1903
+ // after IMPORT_STARTS such starts the yes is dropped, and said.
1904
+ const giveUp = async (why) => {
1905
+ await rm(importAsked, { force: true }).catch(() => undefined);
1906
+ importState = { state: "failed" };
1907
+ process.stderr.write(`agentrun-serve: the import at setup was given up (${why}): run the import command where the sessions are to try again\n`);
1908
+ };
1909
+ let asked;
1671
1910
  try {
1672
- const answer = await onWorker("import");
1673
- if (!("took" in answer))
1911
+ asked = await askedOf();
1912
+ // A choice that cannot be read is never widened to every project: nothing is imported.
1913
+ if (!asked)
1914
+ return await giveUp("the record of which projects to import could not be read");
1915
+ if (asked.starts >= IMPORT_STARTS)
1916
+ return await giveUp(`${IMPORT_STARTS} starts did not end it: the server ended during each`);
1917
+ // This start counted before its worker runs, so one the process does not outlive is counted too.
1918
+ await writeDurable(importAsked, JSON.stringify({ ...asked, starts: asked.starts + 1 }));
1919
+ const answer = await onWorker("import", asked.projects);
1920
+ // Stopped by the server's close, before it took anything or between two sessions: not a start that failed.
1921
+ if (!("took" in answer)) {
1922
+ await writeDurable(importAsked, JSON.stringify(asked));
1674
1923
  return void (importState = { state: "stopped" });
1924
+ }
1675
1925
  // The whole import, every start's part of it: what earlier starts took is kept with the owner's yes.
1676
- // The yes as setup wrote it is empty: no earlier start took anything.
1677
- const before = (await readJson(importAsked));
1678
- const agents = [...new Set([...(Array.isArray(before?.agents) ? before.agents.filter((id) => typeof id === "string") : []), ...answer.took.agents])];
1679
- const runs = (typeof before?.runs === "number" ? before.runs : 0) + answer.took.runs;
1926
+ const agents = [...new Set([...asked.agents, ...answer.took.agents])];
1927
+ const runs = asked.runs + answer.took.runs;
1680
1928
  if (answer.stopped) {
1681
- await writeDurable(importAsked, JSON.stringify({ agents, runs }));
1929
+ await writeDurable(importAsked, JSON.stringify({ ...asked, agents, runs }));
1682
1930
  return void (importState = { state: "stopped" });
1683
1931
  }
1684
1932
  await rm(importAsked, { force: true });
@@ -1687,9 +1935,18 @@ async function startHolding(options, data, checked, stops) {
1687
1935
  process.stdout.write(`${logLine("import", took)}\n`);
1688
1936
  }
1689
1937
  catch (error) {
1690
- importState = { state: "stopped" };
1691
- if (!closing)
1938
+ // A worker the close ended is no failed start; another failure is, and the last one allowed gives the import up.
1939
+ if (closing) {
1940
+ importState = { state: "stopped" };
1941
+ if (asked)
1942
+ await writeDurable(importAsked, JSON.stringify(asked)).catch(() => undefined);
1943
+ }
1944
+ else if (asked && asked.starts + 1 >= IMPORT_STARTS)
1945
+ await giveUp(`${IMPORT_STARTS} starts did not end it: ${error.message}`);
1946
+ else {
1947
+ importState = { state: "stopped" };
1692
1948
  process.stderr.write(`agentrun-serve: the import at setup stopped (the next start goes on with it): ${error.message}\n`);
1949
+ }
1693
1950
  }
1694
1951
  })());
1695
1952
  // ---- helpers --------------------------------------------------------------------------------------------------------
@@ -1781,7 +2038,7 @@ async function startHolding(options, data, checked, stops) {
1781
2038
  const learning = await learningOfAgent(entry);
1782
2039
  const native = nativeOf(entry.revision?.body);
1783
2040
  const nativeStatus = native?.remote ? await new RemoteConnectors(store).status(native) : undefined;
1784
- const runs = await listRunsOverStore(store, { agent: entry.agent.id }, ctx);
2041
+ const runs = (await listRunsOverStore(store, { agent: entry.agent.id }, ctx)).filter((run) => !isShadowRun(run.id));
1785
2042
  return {
1786
2043
  ...(nativeStatus ? { nativeStatus } : {}),
1787
2044
  signIns: await signIns.view(entry.agent.id),
@@ -1830,7 +2087,8 @@ async function startHolding(options, data, checked, stops) {
1830
2087
  if (typeof key !== "string" || key.length < 1 || key.length > 255)
1831
2088
  throw new ApiError("bad_request", "Idempotency-Key is 1 to 255 characters");
1832
2089
  const slot = `${path}\n${key}`;
1833
- const fingerprint = stable(body);
2090
+ const text = stable(body);
2091
+ const fingerprint = fingerprintOf(text);
1834
2092
  const now = Date.now();
1835
2093
  for (const [k, v] of idempotency)
1836
2094
  if (now - v.at > IDEMPOTENCY_TTL_S * 1000)
@@ -1846,7 +2104,8 @@ async function startHolding(options, data, checked, stops) {
1846
2104
  idempotency.set(slot, { fingerprint, at: now });
1847
2105
  let answer;
1848
2106
  try {
1849
- answer = await work({ key: `idk_${sha256Hex(slot).slice(0, 32)}`, fingerprint: sha256Hex(fingerprint) });
2107
+ // The run's origin keeps the SHA-256 it always has: a run the store made under a key before this start compares to it.
2108
+ answer = await work({ key: `idk_${sha256Hex(slot).slice(0, 32)}`, fingerprint: sha256Hex(text) });
1850
2109
  }
1851
2110
  catch (error) {
1852
2111
  idempotency.delete(slot);
@@ -1855,7 +2114,7 @@ async function startHolding(options, data, checked, stops) {
1855
2114
  // The work happened, so the key keeps its answer in memory even when the file write fails: a retry replays it
1856
2115
  // instead of doing the work twice. Only a restart before the next good save loses it, and a run's create not even
1857
2116
  // then: the store keeps its run under the key's origin.
1858
- idempotency.set(slot, { fingerprint, at: now, answer: { status: answer.status, body: answer.body, headers: answer.headers ?? {} } });
2117
+ idempotency.set(slot, { fingerprint, at: now, answer: { status: answer.status, body: replayed(path, answer.body), headers: answer.headers ?? {} } });
1859
2118
  await keep().catch((error) => void process.stderr.write(`agentrun-serve: idempotency save: ${error.message}\n`));
1860
2119
  return answer;
1861
2120
  }
@@ -1944,7 +2203,7 @@ async function startHolding(options, data, checked, stops) {
1944
2203
  throw new ApiError("agent_not_runnable", message, { fields, details: { adapters: [...new Set(blockers.flatMap((b) => (b.adapter ? [b.adapter] : [])))], unbound, missing, code: blockers.some((b) => b.codeNodes || b.shell), ...(tier ? { tier } : {}), ...(Object.keys(decisions).length ? { decisions } : {}), ...(denied.length ? { denied } : {}), ...(asks.length ? { asks } : {}), ...named } });
1945
2204
  }
1946
2205
  /** Where a revision of `kind` naming `tools` and no place runs here: the place a new agent would be saved with. */
1947
- const fallbackPlace = (kind, tools) => defaultPlaceOf(kind, tools, boxOffers, (tool) => toolOf(tool)?.runnerOnly === true);
2206
+ const fallbackPlace = (kind, tools) => defaultPlaceOf(kind, tools, boxOffers, toolOf);
1948
2207
  /** What a save of `revision` pins of the MCP tools it grants (an agentic revision's: a workflow's nodes bind none): each
1949
2208
  * granted server listed once, now, with its saved credential (McpServersOverStore.pinListing), as `tools` each server's
1950
2209
  * listing in the harnesses' shape for the save's checks (blockersOf's `mcp`), and `pin` making the pin from them. A server
@@ -2034,7 +2293,8 @@ async function startHolding(options, data, checked, stops) {
2034
2293
  if (sdkOf(body))
2035
2294
  return { warnings: [], stamp: {} };
2036
2295
  // An agent on a harness that installs on first use starts its install, if it is not in yet: its first run waits for less.
2037
- const install = revision.kind === "agentic" ? installs[harnessOfBody(body)] : undefined;
2296
+ const harnessId = revision.kind === "agentic" ? harnessOfBody(body) : undefined;
2297
+ const install = harnessId !== undefined && Object.hasOwn(installs, harnessId) ? installs[harnessId] : undefined;
2038
2298
  if (install) {
2039
2299
  void install.ensure().catch((error) => log?.(logLine("harness_install_failed", { harness: install.entry.id, message: error.message })));
2040
2300
  }
@@ -2080,18 +2340,19 @@ async function startHolding(options, data, checked, stops) {
2080
2340
  return pinned && { monid: pinned.pin, warnings: pinned.warnings.map(({ tool, message }) => ({ field: `definition.tools[${tools.indexOf(tool)}]`, reason: PRICED_BY_USAGE, message })) };
2081
2341
  }
2082
2342
  /** POST /agents' body made into its agent, as that route makes one, with what this host still lacks for it. A new agent
2083
- * that names no place is given this server's box (place.ts newAgentPlace), stamped on its revision; one that names a
2084
- * tool the box refuses (browser) keeps the runner. */
2343
+ * that names no place is given this server's box (place.ts defaultPlaceOf), stamped on its revision, when it names no
2344
+ * tools (it gets bash) or a tool that needs a shell; one whose tools need none, or that names a tool the box refuses
2345
+ * (browser), keeps the runner. */
2085
2346
  async function createAgentOf(body, template) {
2086
2347
  let warnings = [];
2087
- const definition = checkDefinitionBody(body);
2348
+ const definition = checkDefinitionBody(body, { harnesses });
2088
2349
  const named = Array.isArray(definition.definition.tools) ? definition.definition.tools : [];
2089
- const fresh = named.some((tool) => typeof tool === "string" && toolOf(tool)?.runnerOnly) ? { reason: "" } : newAgentPlace(boxOffers);
2350
+ const place = fallbackPlace("agentic", definition.definition.tools === undefined ? NEW_AGENT_TOOLS : named);
2090
2351
  const entry = await agents.create(definition, async (revision) => {
2091
2352
  const saved = await saveable(revision);
2092
2353
  warnings = saved.warnings;
2093
2354
  return saved.stamp;
2094
- }, "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined, template);
2355
+ }, place.mode === "sandbox" ? { place, tools: NEW_AGENT_TOOLS } : undefined, template);
2095
2356
  return { entry, warnings };
2096
2357
  }
2097
2358
  /** A replay's ports for agent `entry` (runner/promotion.ts askReplay, replayView): its learning folder where this server
@@ -2361,37 +2622,89 @@ async function startHolding(options, data, checked, stops) {
2361
2622
  * tunnel's own port, say); else, with no Host, its own. Links made outside a request (the owner's, the webhooks') are
2362
2623
  * at the public URL or the server's own address. */
2363
2624
  const linkOrigin = (req) => (options.publicUrl ?? (req.headers.host ? ownOrigin(req) : url)).replace(/\/+$/, "");
2364
- /** A run body's `mcp_auth` taken out of it, before anything else reads the body: the credentials a run's caller hands
2365
- * its per_run MCP servers for this run alone (mcp-probe.ts mcpAuthOf). They never reach the run's saved body, its
2366
- * timeline, an idempotency fingerprint (a retry with a fresh credential replays its first answer) or a log: only the
2367
- * seal `sealer` makes, which seals them for the run's id into its launch row (store/seal.ts sealRunMcpAuth), bound to
2368
- * each server's origin then. The request calls `sealer` only for new work, inside its idempotent work: there each
2369
- * entry must name a saved per_run server, else 422, nothing written. A retry its key already answered replays that
2370
- * answer even when the server has since changed or gone, since it does no new work. */
2371
- function handedMcpAuth(body) {
2372
- if (body.mcp_auth === undefined)
2373
- return { body, sealer: async () => undefined };
2374
- const { mcp_auth, ...rest } = body;
2375
- const sealer = async () => {
2625
+ /** A run body's launch secrets taken out of it, before anything else reads the body: `mcp_auth`, the credentials a run's
2626
+ * caller hands its per_run MCP servers for this run alone (mcp-probe.ts mcpAuthOf), and `model_key`, the run's own model
2627
+ * key (run-model-key.ts), such as a LiteLLM virtual key minted for it. They never reach the run's saved body, its
2628
+ * timeline, an idempotency fingerprint (a retry with a fresh credential or key replays its first answer) or a log: only
2629
+ * the seal made of them, sealed for the run's id into its launch row (store/seal.ts sealRunLaunch), each MCP credential
2630
+ * bound to its server's origin then and the model key to the gateway's (AGENT_MODEL_BASE_URL). `handed` is called only
2631
+ * for new work, inside the request's idempotent work: there each mcp_auth entry must name a saved per_run server, and
2632
+ * the model key must be text, else 422, nothing written. A retry its key already answered replays that answer even
2633
+ * when the server has since changed or gone, since it does no new work. */
2634
+ function handedLaunchSecrets(body) {
2635
+ if (body.mcp_auth === undefined && body.model_key === undefined)
2636
+ return { body, handed: async () => ({}) };
2637
+ const { mcp_auth, model_key, ...rest } = body;
2638
+ const handed = async () => {
2376
2639
  const issues = [];
2377
- const handed = mcpAuthOf(mcp_auth, issues);
2640
+ const mcp = mcp_auth === undefined ? undefined : mcpAuthOf(mcp_auth, issues);
2378
2641
  const auth = {};
2379
- for (const [server, headers] of Object.entries(handed ?? {})) {
2642
+ for (const [server, headers] of Object.entries(mcp ?? {})) {
2380
2643
  const row = await getMcpServer(store, server);
2381
2644
  if (row?.auth !== "per_run")
2382
2645
  issues.push({ field: `mcp_auth.${server}`, reason: "not_an_option", message: row ? `The MCP server ${server} keeps its own credential (auth ${row.auth}): only a per_run server takes one from a run.` : `No MCP server ${server} is saved here.` });
2383
2646
  else
2384
2647
  auth[server] = { headers, origin: new URL(row.url).origin };
2385
2648
  }
2649
+ const model = model_key === undefined ? undefined : modelKeyOf(model_key, issues);
2386
2650
  if (issues.length)
2387
2651
  throw invalid(issues);
2388
- return (runId) => sealRunMcpAuth(sealKey, runId, auth);
2652
+ return { ...(mcp_auth !== undefined ? { mcp: auth } : {}), ...(model !== undefined ? { model } : {}) };
2653
+ };
2654
+ return { body: rest, handed };
2655
+ }
2656
+ /** The 422 for a model key where the run's model never takes it (run-model-key.ts modelKeyMisfit), at `model_key`. */
2657
+ const misfit = (why) => invalid([{ field: "model_key", reason: "not_an_option", message: why }]);
2658
+ /** A start's launch seal of `handed` (handedLaunchSecrets), made once the start prepared the run's launch: a model key
2659
+ * where the run's model never takes it is refused (modelKeyMisfit), and a start that hands other secrets but no key
2660
+ * is refused where the server holds no key for the run's route (serverKeyMissing). Undefined when nothing is handed:
2661
+ * the start's own check (runs-over-store keyedOrRefused) refuses that one where it has no key to spend. */
2662
+ function startSeal(handed) {
2663
+ if (handed.mcp === undefined && handed.model === undefined)
2664
+ return undefined;
2665
+ return (runId, launch, kind) => {
2666
+ const target = { kind, model: launch.model, native: Boolean(launch.native) };
2667
+ if (handed.model !== undefined) {
2668
+ const why = modelKeyMisfit(env, target);
2669
+ if (why)
2670
+ throw misfit(why);
2671
+ }
2672
+ else if (serverKeyMissing(env, target))
2673
+ throw modelKeyRequired(false);
2674
+ const origin = runModelOrigin(env);
2675
+ return sealRunLaunch(sealKey, runId, { ...(handed.mcp ? { mcp: handed.mcp } : {}), ...(handed.model !== undefined && origin ? { model: { key: handed.model, origin } } : {}) });
2676
+ };
2677
+ }
2678
+ /** A message's launch secrets for run `run` (its kind and launch as stored): what it hands replaces that part of the
2679
+ * run's, inside the write that takes the message (store LaunchSealed: a function of what the launch holds then), and a
2680
+ * part it does not hand is kept as the run holds it (none after its turn's end erased it). A model key is refused
2681
+ * where the run's model never takes it. One is required where the server holds no key for the run's route and the
2682
+ * run holds none when the message is written (its last turn ended): 422 model_key_required from inside that write,
2683
+ * which then writes nothing, so a turn never starts with no key to spend. */
2684
+ async function messageSeal(run, handed) {
2685
+ const launch = readLaunchBody((await store.runs.launch(run.id)).body);
2686
+ const target = { kind: run.kind, model: launch?.model, native: Boolean(launch?.native) };
2687
+ if (handed.model !== undefined) {
2688
+ const why = modelKeyMisfit(env, target);
2689
+ if (why)
2690
+ throw misfit(why);
2691
+ }
2692
+ const needsKey = handed.model === undefined && serverKeyMissing(env, target);
2693
+ if (handed.mcp === undefined && handed.model === undefined && !needsKey)
2694
+ return undefined;
2695
+ const origin = runModelOrigin(env);
2696
+ return (current) => {
2697
+ const held = current === null ? {} : (openRunLaunch(sealKey, run.id, current) ?? {});
2698
+ const mcp = handed.mcp ?? held.mcp;
2699
+ const model = handed.model !== undefined && origin ? { key: handed.model, origin } : held.model;
2700
+ if (!model && needsKey)
2701
+ throw modelKeyRequired(true);
2702
+ return sealRunLaunch(sealKey, run.id, { ...(mcp ? { mcp } : {}), ...(model ? { model } : {}) });
2389
2703
  };
2390
- return { body: rest, sealer };
2391
2704
  }
2392
2705
  async function createRun(req, agentId) {
2393
2706
  const entry = await needRunnableAgent(agentId);
2394
- const { body, sealer } = handedMcpAuth(await bodyOf(req));
2707
+ const { body, handed } = handedLaunchSecrets(await bodyOf(req));
2395
2708
  return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
2396
2709
  // A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
2397
2710
  const first = origin && (await agents.request(() => agents.store.runOfOrigin(origin.key)));
@@ -2401,7 +2714,7 @@ async function startHolding(options, data, checked, stops) {
2401
2714
  const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
2402
2715
  return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
2403
2716
  }
2404
- const seal = await sealer();
2717
+ const seal = startSeal(await handed());
2405
2718
  const run = await startRunOf(entry, body, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}) });
2406
2719
  // Its view from the store: the run and its launch were inserted in one transaction, so the view reads it whole.
2407
2720
  return { status: 202, body: await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${run.id}` } };
@@ -2413,7 +2726,7 @@ async function startHolding(options, data, checked, stops) {
2413
2726
  * Its first run makes the agent, a version's first run its revision; a later run of the version reuses both
2414
2727
  * (runs-over-store startInline). The answer is POST /agents/{agent_id}/runs' own: 202 and the run. */
2415
2728
  async function createInlineRun(req) {
2416
- const { body, sealer } = handedMcpAuth(await bodyOf(req));
2729
+ const { body, handed } = handedLaunchSecrets(await bodyOf(req));
2417
2730
  if (isObject(body.definition) && body.definition.native !== undefined)
2418
2731
  throw new ApiError("input_invalid", "Native references are registered only through /native/connect on the source machine; an inline definition cannot create one.");
2419
2732
  const { external, definition, skills, note, revision: pinned, ...run } = body;
@@ -2422,13 +2735,13 @@ async function startHolding(options, data, checked, stops) {
2422
2735
  ...externalIssues(external),
2423
2736
  ...(pinned !== undefined ? [{ field: "revision", reason: "not_allowed", message: "An inline run pins no revision: it runs the revision of its external version.", fix: "Remove revision." }] : []),
2424
2737
  ...runBodyIssues(run),
2425
- ...definitionBodyIssues(given),
2738
+ ...definitionBodyIssues(given, { harnesses }),
2426
2739
  // The agent's id is this server's, one per external reference, and its version is the reference's.
2427
2740
  ...["id", "version"].flatMap((key) => (isObject(definition) && definition[key] !== undefined ? [{ field: `definition.${key}`, reason: "not_allowed", message: `An inline agent's ${key} is its external reference's: the definition names none.`, fix: `Remove definition.${key}.` }] : [])),
2428
2741
  ];
2429
2742
  if (issues.length)
2430
2743
  throw invalid(issues);
2431
- const checked = checkDefinitionBody(given);
2744
+ const checked = checkDefinitionBody(given, { harnesses });
2432
2745
  const made = makeRevision(checked.definition, checked.skills ?? {}, checked.note);
2433
2746
  // A version's first run is its save: refused where POST /agents refuses the definition (one this host can never run),
2434
2747
  // its MCP tools pinned as a save pins them (a server down keeps the agent's current pin when this version grants nothing
@@ -2456,7 +2769,7 @@ async function startHolding(options, data, checked, stops) {
2456
2769
  const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
2457
2770
  return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
2458
2771
  }
2459
- const seal = await sealer();
2772
+ const seal = startSeal(await handed());
2460
2773
  const started = await startInline(store, startDeps, inline, run, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}) });
2461
2774
  return { status: 202, body: await viewOverStore(store, started.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${started.id}` } };
2462
2775
  });
@@ -2561,10 +2874,12 @@ async function startHolding(options, data, checked, stops) {
2561
2874
  // `label=<key>:<value>`, once: only the runs holding it (run-labels.ts), filtered in the store.
2562
2875
  const labels = labelFilter(url.searchParams.getAll("label"));
2563
2876
  const vd = viewDepsFor(origin);
2564
- let rows = (await listRunsOverStore(store, { ...filter, ...(labels ? { labels } : {}) }, ctx)).filter((row) => Boolean(row.archivedAt) === archived);
2877
+ // An audit's shadow run is no row of the list (learn/audit.ts): it is read by id, and its cost is its served run's.
2878
+ let rows = (await listRunsOverStore(store, { ...filter, ...(labels ? { labels } : {}) }, ctx)).filter((row) => Boolean(row.archivedAt) === archived && !isShadowRun(row.id));
2565
2879
  if (status !== null) {
2566
- // The v2 status is the run view's (store-view over the journal), per row.
2567
- const statuses = await Promise.all(rows.map((row) => viewOverStore(store, row.id, vd).then((v) => v?.status)));
2880
+ // The v2 status is the run view's (store-view over the journal), per row; a settled run's is its row's (settledStatusOf),
2881
+ // so only the runs still going are read over their journals.
2882
+ const statuses = await Promise.all(rows.map((row) => settledStatusOf(row.state) ?? viewOverStore(store, row.id, vd).then((v) => v?.status)));
2568
2883
  rows = rows.filter((_, i) => statuses[i] === status);
2569
2884
  }
2570
2885
  // summaryOverStore reads each run's view (its version, status, cost and learning among them); no versions map is needed.
@@ -2795,7 +3110,7 @@ async function startHolding(options, data, checked, stops) {
2795
3110
  throw invalid(issues);
2796
3111
  return { password: body.password, body };
2797
3112
  }
2798
- /** POST /v2/setup, POST /v2/auth/sign-in, POST /v2/auth/sign-out, POST /v2/auth/sign-out-everywhere and GET
3113
+ /** POST /v2/setup, POST /v2/setup/code, POST /v2/auth/sign-in, POST /v2/auth/sign-out, POST /v2/auth/sign-out-everywhere and GET
2799
3114
  * /v2/auth/session, answered before any credential: their own checks are the setup code (or the token), the password,
2800
3115
  * and the session. */
2801
3116
  async function ownerRoute(req, res, path, me) {
@@ -2810,13 +3125,18 @@ async function startHolding(options, data, checked, stops) {
2810
3125
  if (!byToken)
2811
3126
  fromPage(req);
2812
3127
  const { password, body } = await passwordIn(req, ["password", "code", "import"]);
2813
- if (body.import !== undefined && typeof body.import !== "boolean")
2814
- throw invalid([{ field: "import", reason: "wrong_type", message: "import is true or false" }]);
2815
- if (body.import === true && !offersImport)
3128
+ // The owner's choice: the projects to import, by the ids the offer named them with (GET /v2/setup/import's
3129
+ // candidates); `true` is every project, as before; `false`, none named or the field left out is no import.
3130
+ const named = Array.isArray(body.import) ? body.import : undefined;
3131
+ if (body.import !== undefined && typeof body.import !== "boolean" && !(named && named.length <= MAX_CANDIDATES && named.every((id) => typeof id === "string" && /^imp-[0-9a-f]{32}$/.test(id))))
3132
+ throw invalid([{ field: "import", reason: "wrong_type", message: `import is true, false, or at most ${MAX_CANDIDATES} of the project ids GET /v2/setup/import names` }]);
3133
+ const chosen = named ? [...new Set(named)] : undefined;
3134
+ const takes = body.import === true || (chosen !== undefined && chosen.length > 0);
3135
+ if (takes && !offersImport)
2816
3136
  throw invalid([{ field: "import", reason: "not_allowed", message: "Only a server on this machine (no public address, on loopback) imports its sessions at setup: run the import command where they are." }]);
2817
3137
  // The owner's yes, on the box ticked, is kept with the owner: written durably before the password, so a setup that
2818
3138
  // cannot keep it sets no owner and can be tried again, and taken back if the password is not written.
2819
- const along = body.import === true ? { keep: () => writeDurable(importAsked, ""), drop: () => rm(importAsked, { force: true }) } : undefined;
3139
+ const along = takes ? { keep: () => writeDurable(importAsked, chosen ? JSON.stringify({ projects: chosen }) : ""), drop: () => rm(importAsked, { force: true }) } : undefined;
2820
3140
  // The server's API token stands in for the code in the code field too (on Render it is in the Environment tab, the
2821
3141
  // code only in the log), compared as the header is, in constant time; a wrong one counts as a wrong code.
2822
3142
  const tokenAsCode = typeof body.code === "string" && body.code !== "" && bearer(`Bearer ${body.code}`, req);
@@ -2833,23 +3153,38 @@ async function startHolding(options, data, checked, stops) {
2833
3153
  viewers.recheck();
2834
3154
  // The count is for the offer, now answered: it stops.
2835
3155
  stopCount();
2836
- // Only on the box ticked: the owner, now set, asked for it. It runs after the answer; agents arrive as it goes.
2837
- if (body.import === true)
3156
+ // Only on a choice made: the owner, now set, asked for it. It runs after the answer; agents arrive as it goes.
3157
+ if (takes)
2838
3158
  void importAtSetup();
2839
- return send(res, 201, { signed_in: true, ...(body.import === true ? { importing: true } : {}) }, { "set-cookie": ownerCookie(req, me.session(), SESSION_S) });
3159
+ return send(res, 201, { signed_in: true, ...(takes ? { importing: true } : {}) }, { "set-cookie": ownerCookie(req, me.session(), SESSION_S) });
3160
+ }
3161
+ // A setup code to use, asked for with no credential (the person at the Setup code field, or whoever started the
3162
+ // server for them): a new one goes to the log only when the last is expired or spent; one still good is kept, so
3163
+ // this request never voids a link someone holds. The answer says which and when it runs out, never the code.
3164
+ // No origin check and no rate limit, unlike setup and sign-in: the documented caller is a bare curl, the answer
3165
+ // holds nothing secret, and all a caller gets is at most one log line per code's 30 minutes. Counting asks with
3166
+ // sign-in tries would let one visitor behind a shared proxy hold the button shut for everyone.
3167
+ case "/setup/code": {
3168
+ if (me.hasPassword())
3169
+ throw new ApiError("forbidden", "this server has its owner: sign in");
3170
+ const code = me.renewSetupCode();
3171
+ if (!code)
3172
+ throw new ApiError("forbidden", "no setup code to give: this server's setup takes no code, or its password is being set now");
3173
+ return send(res, 200, { printed: code.printed, expires_at: new Date(code.until).toISOString() });
2840
3174
  }
2841
3175
  case "/setup/import": {
2842
3176
  // No offer is an answer, `{ offer: false }`, never a 404: the console reads this on its first page, and a browser
2843
3177
  // logs every 404 as an error.
2844
3178
  // Before the owner is set, to the setup page: none on a server that cannot import, else that it can (202 while it
2845
- // counts), and then how many projects and sessions it would, or null for each when the count failed.
3179
+ // counts), and then how many projects and sessions it would and the projects to choose from (`candidates`, the
3180
+ // latest active first, at most MAX_CANDIDATES), or null for each count when the count failed.
2846
3181
  if (!me.hasPassword()) {
2847
3182
  pageRead(req);
2848
3183
  if (!offersImport)
2849
3184
  return send(res, 200, { offer: false });
2850
3185
  countSessions();
2851
3186
  if (count?.state === "counted")
2852
- return send(res, 200, { projects: count.projects, sessions: count.sessions });
3187
+ return send(res, 200, { projects: count.projects, sessions: count.sessions, candidates: count.candidates });
2853
3188
  if (count?.state === "failed")
2854
3189
  return send(res, 200, { projects: null, sessions: null });
2855
3190
  return send(res, 202, { counting: true });
@@ -2945,14 +3280,14 @@ async function startHolding(options, data, checked, stops) {
2945
3280
  const bodies = new WeakMap();
2946
3281
  /** The check of a whole body a route makes before anything else, by operation, for the body sent: what a suggested
2947
3282
  * value must pass. PUT .../definition's contract body (the definition itself) has none here. */
2948
- const definitionCheck = (creating) => (body) => definitionBodyIssues(isObject(body) ? body : {}, { creating });
3283
+ const definitionCheck = (creating) => (body) => definitionBodyIssues(isObject(body) ? body : {}, { creating, harnesses });
2949
3284
  const BODY_CHECKS = {
2950
3285
  createAgent: () => definitionCheck(true),
2951
3286
  updateDefinition: (sent) => ("definition" in sent ? definitionCheck(false) : undefined),
2952
3287
  // POST /runs' agent, given inline, is POST /agents' body inside its own: checked as that one is.
2953
3288
  createInlineRun: () => (body) => {
2954
3289
  const { definition, skills, note } = isObject(body) ? body : {};
2955
- return definitionBodyIssues({ definition, ...(skills !== undefined ? { skills } : {}), ...(note !== undefined ? { note } : {}) });
3290
+ return definitionBodyIssues({ definition, ...(skills !== undefined ? { skills } : {}), ...(note !== undefined ? { note } : {}) }, { harnesses });
2956
3291
  },
2957
3292
  };
2958
3293
  /** An operation's documented request bodies (its JSON media type's examples), each its value. */
@@ -3327,7 +3662,7 @@ async function startHolding(options, data, checked, stops) {
3327
3662
  warnings = saved.warnings;
3328
3663
  return saved.stamp;
3329
3664
  };
3330
- const edited = await agents.commit(entry, checkDefinitionBody(contract ? { definition: body } : body, { creating: false }), { check, contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
3665
+ const edited = await agents.commit(entry, checkDefinitionBody(contract ? { definition: body } : body, { creating: false, harnesses }), { check, contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
3331
3666
  reconcileComputer(id);
3332
3667
  return send(res, 200, { ...agentView(edited, linkOrigin(req), await agentExtra(edited)), warnings }, { etag: etagOf(edited) });
3333
3668
  }
@@ -3423,7 +3758,7 @@ async function startHolding(options, data, checked, stops) {
3423
3758
  const view = await viewOverStore(store, id, runReadDepsFor(linkOrigin(req)));
3424
3759
  if (!view)
3425
3760
  throw new ApiError("not_found", `no run ${id}`);
3426
- return send(res, 200, { ...view, ...(await runComputerOf(id, view)) });
3761
+ return send(res, 200, { ...view, ...(await runComputerOf(id, view)), ...(await allInViewOf(id, view)) });
3427
3762
  }
3428
3763
  case "getTimeline":
3429
3764
  await needRun(id);
@@ -3434,9 +3769,9 @@ async function startHolding(options, data, checked, stops) {
3434
3769
  const run = await needRun(id);
3435
3770
  if (run.kind === "workflow")
3436
3771
  throw unsupported("messages.steer_workflow_runs", "A workflow run takes no messages here: its workflow runs to its end, or a cancel ends it.");
3437
- const { body, sealer } = handedMcpAuth(await bodyOf(req));
3772
+ const { body, handed } = handedLaunchSecrets(await bodyOf(req));
3438
3773
  const answer = await idempotent(req, `/runs/${id}/messages`, body, async () => {
3439
- const seal = await sealer();
3774
+ const seal = await messageSeal(run, await handed());
3440
3775
  const extra = unknownFields(body, ["content"]);
3441
3776
  if (extra.length)
3442
3777
  throw invalid(extra);
@@ -3445,8 +3780,8 @@ async function startHolding(options, data, checked, stops) {
3445
3780
  throw invalid([{ field: "content", reason: content === undefined ? "missing" : "wrong_type", message: "content is a non-empty string" }]);
3446
3781
  if (content.length > MAX_MESSAGE)
3447
3782
  throw invalid([{ field: "content", reason: "too_long", message: `content is at most ${MAX_MESSAGE} characters` }]);
3448
- // Its mcp_auth replaces the run's handed credentials in the steer's own write, so the turn it starts uses them.
3449
- const { mode, messageId } = await message(store, run, content, { ...(seal ? { launchSealed: seal(run.id) } : {}), ...(options.beforeSubmit ? { beforeSubmit: options.beforeSubmit } : {}) });
3783
+ // Its mcp_auth and model_key replace the run's in the steer's own write, so the turn it starts uses them.
3784
+ const { mode, messageId } = await message(store, run, content, { ...(seal ? { launchSealed: seal } : {}), ...(options.beforeSubmit ? { beforeSubmit: options.beforeSubmit } : {}) });
3450
3785
  // The run's state after the command row is written (the run view): the runner applies the steer; the client polls.
3451
3786
  const { status, state } = await runStatusState(run.id);
3452
3787
  return { status: 202, body: { run_id: run.id, message_id: messageId, mode, status, state, poll_after_ms: 1000 } };
@@ -3523,6 +3858,8 @@ async function startHolding(options, data, checked, stops) {
3523
3858
  const m = (isObject(row.metrics) ? row.metrics : {});
3524
3859
  if (m.path === "replay")
3525
3860
  throw invalid([{ field: "run_id", reason: "not_allowed", message: "A replay run is never graded: its answer is scored against the run it replays." }]);
3861
+ if (m.path === "audit" || isShadowRun(row.id))
3862
+ throw invalid([{ field: "run_id", reason: "not_allowed", message: "An audit's shadow run is never graded: grade the run it audits." }]);
3526
3863
  const path = RUN_PATHS.includes(m.path) ? m.path : "agent";
3527
3864
  const grade = {
3528
3865
  run: row.id, correct: body.correct, ...(body.expected !== undefined ? { expected: body.expected } : {}), source: body.source ?? "feedback", at: new Date().toISOString(), path,
@@ -3530,7 +3867,12 @@ async function startHolding(options, data, checked, stops) {
3530
3867
  ...(typeof m.workflow_promotion === "number" ? { promotion: m.workflow_promotion } : {}),
3531
3868
  };
3532
3869
  // Kept with what it asks of the run's learning (runner/feedback-round.ts): nothing, or a look-back.
3533
- const kept = gradeView(await keepGrade(store, row.agentId, grade, typeof body.label === "string" ? body.label : undefined));
3870
+ // Its feedback round is a turn with no caller's model key: on the server's key for the run's route, else not opened.
3871
+ const kept = gradeView(await keepGrade(store, row.agentId, grade, typeof body.label === "string" ? body.label : undefined, (launch) => !serverKeyMissing(env, { kind: "agentic", model: launch.model, native: Boolean(launch.native) })));
3872
+ // A grade of a run its learned workflow answered alone is an audit row too (runner/audit.ts gradeRow): the hold rule
3873
+ // reads it with the shadows'. A row not written now is logged, never the grade refused.
3874
+ const said = (line) => log?.(logLine("audit", { run: row.id, said: line }));
3875
+ await gradeRow({ store, agentId: row.agentId, revisionId: row.revisionId, context: ctx, folder: () => learningFolderOf(data, row.agentId), shown: () => learningShown(row.agentId), log: said }, row, body.correct).catch((error) => said(`the grade wrote no audit row (${error?.message ?? error})`));
3534
3876
  // Its workflow's name cut as GET /runs/{id}/learning cuts it (learningShown); withheld whole when that cut can't be
3535
3877
  // read (the grade is kept by then: never a shorter cut, never a refusal of a grade it kept).
3536
3878
  const shown = await learningShown(row.agentId).catch(() => undefined);
@@ -4029,7 +4371,7 @@ async function startHolding(options, data, checked, stops) {
4029
4371
  const read = await agentCostOverStore(store, id, limit);
4030
4372
  // Each workflow's name as the other learning reads show it: one that holds a secret or a sign-in's value is cut.
4031
4373
  const shown = await learningShown(id);
4032
- const cost = { ...read, runs: read.runs.map((run) => (run.workflow === null ? run : { ...run, workflow: shown.name(run.workflow) })), workflows: read.workflows.map((one) => ({ ...one, workflow: shown.name(one.workflow) })) };
4374
+ const cost = { ...read, runs: read.runs.map((run) => (run.workflow === null ? run : { ...run, workflow: shown.name(run.workflow) })), workflows: read.workflows.map((one) => ({ ...one, workflow: shown.name(one.workflow) })), bill: { ...read.bill, revisions: read.bill.revisions.map((one) => ({ ...one, workflow: shown.name(one.workflow) })), holds: read.bill.holds.map((one) => ({ ...one, workflow: shown.name(one.workflow), reason: shown.text(one.reason) })) } };
4033
4375
  if (csv) {
4034
4376
  res.writeHead(200, { "content-type": "text/csv; charset=utf-8", "cache-control": "no-store", "x-content-type-options": "nosniff", "content-disposition": `attachment; filename="${id}-cost-per-run.csv"` });
4035
4377
  return void res.end(costCsv(cost.runs));
@@ -4037,11 +4379,52 @@ async function startHolding(options, data, checked, stops) {
4037
4379
  return send(res, 200, { agent: id, ...cost });
4038
4380
  }
4039
4381
  case "listLearningPromotions": {
4382
+ const entry = await needAgent(id);
4383
+ // Each learned workflow's promotion records, oldest first (learn/promote.ts): its check's numbers and decisions,
4384
+ // its holds (a check's, an audit's). Every text in them cut as the other learning reads cut theirs
4385
+ // (promotionsShown: a reason as well as each workflow's name). Beside what serves, each one's state, its check's
4386
+ // numbers and its audit line (learn/audit.ts servingLinesOf), at the agent's numbers.
4387
+ const records = await promotionsOf(store.settings, id);
4388
+ const shown = await learningShown(id);
4389
+ const shownRead = promotionsShown(records, shown);
4390
+ // A ledger that can't be read now leaves each audit line at no rows, never the read refused.
4391
+ const loop = auditLoopOf(entry.revision?.body?.learning);
4392
+ const lines = servingLinesOf(records, await auditsOfAgent(id).catch(() => []), loop);
4393
+ // Why its runs are never audited, when the agent can call a tool that writes (learn/audit.ts auditWriterOf, the
4394
+ // rule startAudit reads); and how many of the serving revision's runs a trigger started (never audited).
4395
+ const writer = auditWriterOf(entry.revision ?? undefined);
4396
+ const auditsOff = writer === undefined ? null : shown.text(auditsOffWords(writer));
4397
+ // The champion's own revision, read by its recorded digest at the learning commits its records name (newest
4398
+ // first), then main: never by paging the workflow's history. Its nodes with their tiers and code checks, and the
4399
+ // check it was promoted on; nodes null when no commit read holds its text (or the folder can't be read now).
4400
+ const championRead = async (workflow, digest) => {
4401
+ const champion = championOf(records, workflow);
4402
+ const record = champion?.digest === digest ? champion : undefined;
4403
+ const commits = records.filter((one) => one.workflow === workflow && one.digest === digest && one.commit).map((one) => one.commit).reverse();
4404
+ const read = await workflowAtDigest(data, id, workflow, digest, commits).catch(() => undefined);
4405
+ let doc;
4406
+ try {
4407
+ doc = read ? JSON.parse(read.text) : undefined;
4408
+ }
4409
+ catch {
4410
+ doc = undefined;
4411
+ }
4412
+ return shownDeep({ digest, commit: read?.commit ?? null, nodes: doc === undefined ? null : workflowNodesOf(doc), check: record?.check ?? null }, shown);
4413
+ };
4414
+ const serving = await Promise.all(servingOf(records).map(async (one, i) => ({
4415
+ ...shownRead.serving[i], ...lines[i], audits_off: auditsOff,
4416
+ not_auditable: one.digest === null ? 0 : await notAuditableOf(store, id, one.workflow, one.digest, loop).catch(() => 0),
4417
+ champion: one.digest === null ? null : await championRead(one.workflow, one.digest),
4418
+ })));
4419
+ return send(res, 200, { agent: id, promotions: shownRead.promotions, serving });
4420
+ }
4421
+ case "listLearningAudits": {
4040
4422
  await needAgent(id);
4041
- // Each learned workflow's promotion records, oldest first (learn/promote.ts): its replays' numbers and decisions,
4042
- // its refits, its holds. Aggregates only; every text in them cut as the other learning reads cut theirs
4043
- // (promotionsShown: a reason and a refit guard's label as well as each workflow's name).
4044
- return send(res, 200, { agent: id, ...promotionsShown(await promotionsOf(store.settings, id), await learningShown(id)) });
4423
+ // The audit ledger (learn/audit.ts audits.jsonl), oldest first: each workflow's name and every other text cut as the
4424
+ // promotions read cuts its own.
4425
+ const shown = await learningShown(id);
4426
+ const rows = await auditsOfAgent(id);
4427
+ return send(res, 200, { agent: id, audits: rows.map((row) => ({ ...row, workflow: shown.name(row.workflow), run: shown.text(row.run), shadow_run: row.shadow_run === null ? null : shown.text(row.shadow_run), digest: shown.text(row.digest) })) });
4045
4428
  }
4046
4429
  case "createLearningBatch": {
4047
4430
  await needAgent(id);
@@ -4075,7 +4458,7 @@ async function startHolding(options, data, checked, stops) {
4075
4458
  }
4076
4459
  case "getLearningLoop": {
4077
4460
  await needAgent(id);
4078
- // The loop's own record over the one store (store-reads/loop.ts): compile turns and guarded steps, aggregates only.
4461
+ // The loop's own record over the one store (store-reads/loop.ts): compile turns, aggregates only.
4079
4462
  // Names cut as the other learning reads cut them; a compile's error texts cut by its run's own cut as its run's
4080
4463
  // learning read cuts them (run-learning-served.ts), and left out when that run's handed values can't be read.
4081
4464
  const shown = await learningShown(id);
@@ -4090,8 +4473,7 @@ async function startHolding(options, data, checked, stops) {
4090
4473
  const said = (error) => shown.text(printable({ rule: "workflow", detail: error }, all).detail);
4091
4474
  return { ...one, workflow, from_notes: one.from_notes.map(shown.name), attempts: one.attempts.map(({ ok, errors }) => ({ ok, errors: errors.map(said) })), draft_errors: one.draft_errors.map(said), withheld: false };
4092
4475
  }));
4093
- const guards = read.guards.map((one) => ({ ...one, workflow: shown.name(one.workflow), node: shown.text(one.node) }));
4094
- return send(res, 200, { agent: id, completed_runs: read.completed_runs, compiles, guards });
4476
+ return send(res, 200, { agent: id, completed_runs: read.completed_runs, compiles });
4095
4477
  }
4096
4478
  case "listLearningNotes":
4097
4479
  case "listLearningLog":
@@ -4141,10 +4523,14 @@ async function startHolding(options, data, checked, stops) {
4141
4523
  if (extra.length)
4142
4524
  throw invalid(extra);
4143
4525
  const inputs = body.inputs === undefined ? "held" : body.inputs;
4144
- if (inputs !== "held" && !(typeof inputs === "number" && Number.isInteger(inputs) && inputs >= 1 && inputs <= GRADES_KEPT)) {
4145
- throw new ApiError("bad_request", `inputs is "held" (the graded inputs the revision was last decided on, the default) or a whole number from 1 to ${GRADES_KEPT}: that many of the agent's newest graded inputs.`);
4526
+ if (inputs !== "held" && !(typeof inputs === "number" && Number.isInteger(inputs) && inputs >= 1 && inputs <= COMPILE_AFTER_MAX)) {
4527
+ throw new ApiError("bad_request", `inputs is "held" (the runs the revision was last checked on, the default) or a whole number from 1 to ${COMPILE_AFTER_MAX}: that many of the agent's newest completed runs.`);
4146
4528
  }
4147
4529
  const [, , name, digest] = found.pattern.exec(path).map((part) => decodeURIComponent(part));
4530
+ // Its replay runs are started by no caller, with no model key: none to spend on a server that holds none.
4531
+ const keyless = noServerKeyFor(env, "An owner's replay");
4532
+ if (keyless)
4533
+ throw new ApiError("not_continuable", keyless);
4148
4534
  const started = await replayAsked(() => askReplay(replayAskOf(entry), name, digest, inputs));
4149
4535
  return send(res, 202, started, { location: `/v2/agents/${encodeURIComponent(id)}/learning/workflows/${encodeURIComponent(name)}/revisions/${encodeURIComponent(digest)}/replays/${started.replay}` });
4150
4536
  }
@@ -4259,6 +4645,10 @@ async function startHolding(options, data, checked, stops) {
4259
4645
  case "deleteTrigger": {
4260
4646
  // Deleted here whatever its sender says; what could not be removed there is answered (Composio's instance).
4261
4647
  const said = await triggers.remove(id);
4648
+ // Its cached create answers are masked now and saved, so no later start has to find the trigger to mask them. A
4649
+ // failed save is said by a code; the map is masked already, so a replay is too.
4650
+ if (maskCachedGone(id).length)
4651
+ await keep().catch((error) => idempotencySaid({ condition: "idempotency_not_saved", trigger: id, error: typeof error?.code === "string" ? error.code : "error" }));
4262
4652
  if (said)
4263
4653
  return send(res, 200, { deleted: true, ...said });
4264
4654
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
@@ -4312,7 +4702,9 @@ async function startHolding(options, data, checked, stops) {
4312
4702
  }
4313
4703
  })();
4314
4704
  let names;
4315
- const server = createServer((req, res) => {
4705
+ // The listener: the CLI's, bound early and answering warming until the takeover below (listen-first.ts), or a new one.
4706
+ const server = options.listener ?? createServer();
4707
+ const onRequest = (req, res) => {
4316
4708
  const requestId = `req_${randomBytes(8).toString("hex")}`;
4317
4709
  res.setHeader("x-request-id", requestId);
4318
4710
  if (log && !quiet) {
@@ -4360,7 +4752,7 @@ async function startHolding(options, data, checked, stops) {
4360
4752
  if (options.apiOnly && !servedApiOnly(ROUTES, req.method, raw))
4361
4753
  return fail(new ApiError("not_found", apiOnlyRefusal(raw)));
4362
4754
  // Before the page: its cookie must not stand in for the token on the owner's own routes, nor on the MCP endpoint.
4363
- if (owner && (raw === "/v2/setup" || raw === "/v2/setup/import" || raw.startsWith("/v2/auth/")))
4755
+ if (owner && (raw === "/v2/setup" || raw === "/v2/setup/import" || raw === "/v2/setup/code" || raw.startsWith("/v2/auth/")))
4364
4756
  return void ownerRoute(req, res, raw.slice(3), owner).catch(fail);
4365
4757
  if (raw === MCP_PATH)
4366
4758
  return void mcp(req, res).catch(fail);
@@ -4380,13 +4772,13 @@ async function startHolding(options, data, checked, stops) {
4380
4772
  if (viewing)
4381
4773
  return ID.test(viewing[1]) ? void liveRoute(req, res, viewing[1], viewing[2], viewing[3]).catch(fail) : fail(new ApiError("not_found", "no run's live view at that address"));
4382
4774
  route(req, res, url, raw.slice(3)).catch(fail);
4383
- });
4775
+ };
4384
4776
  // A request's headers come within 10 s, whatever its route: nothing sends more than a few kilobytes of them. Its body
4385
4777
  // keeps Node's 5-minute request timeout, which an upload of a large file needs; the token-less hook route has its own
4386
4778
  // 30 s for its body (push-handler.ts HOOK_BODY_MS), so dribbling senders hold no socket for long.
4387
4779
  server.headersTimeout = 10_000;
4388
4780
  // The one upgrade this server takes: a run's live computer viewer's WebSocket (browser-live.ts). Every other is refused.
4389
- server.on("upgrade", (req, socket, head) => {
4781
+ const onUpgrade = (req, socket, head) => {
4390
4782
  socket.on("error", () => socket.destroy());
4391
4783
  const raw = (req.url ?? "/").split("?")[0];
4392
4784
  const viewing = LIVE_PATH.exec(raw);
@@ -4442,28 +4834,14 @@ async function startHolding(options, data, checked, stops) {
4442
4834
  viewers.watch(socket, admitted);
4443
4835
  proxyLiveUpgrade(req, socket, head, handover, viewing[3], () => { piping = true; }, reach);
4444
4836
  })().catch(() => (piping ? void socket.destroy() : deny("500 Internal Server Error")));
4445
- });
4446
- const first = options.port ?? DEFAULT_PORT;
4447
- const last = options.nextFreePort && first !== 0 ? Math.min(first + 99, 65_535) : first;
4448
- for (let port = first;; port++) {
4449
- try {
4450
- // Each attempt takes off both its handlers when it ends, so a taken port leaves no listener behind.
4451
- await new Promise((done, reject) => {
4452
- const onError = (error) => (server.off("listening", onListening), reject(error));
4453
- const onListening = () => (server.off("error", onError), done());
4454
- server.once("error", onError);
4455
- server.once("listening", onListening);
4456
- server.listen(port, host);
4457
- });
4458
- break;
4459
- }
4460
- catch (error) {
4461
- if (error.code !== "EADDRINUSE")
4462
- throw error;
4463
- if (port < last)
4464
- continue;
4465
- throw last > first ? Object.assign(new Error(`every port from ${first} to ${last} on ${host} is taken`), { code: "EADDRINUSE" }) : error;
4466
- }
4837
+ };
4838
+ // The CLI's early listener answers with this server's routes from here on, where a new one would start to listen.
4839
+ if (options.listener)
4840
+ takeOver(server, onRequest, onUpgrade);
4841
+ else {
4842
+ server.on("request", onRequest);
4843
+ server.on("upgrade", onUpgrade);
4844
+ await listenOn(server, host, options.port ?? DEFAULT_PORT, options.nextFreePort === true);
4467
4845
  }
4468
4846
  // The tool keys the server is started with, each checked once against its provider, in the background, once it
4469
4847
  // listens: a start that fails sends no check, and the start never waits on one. Capabilities are made again as each
@@ -4475,12 +4853,10 @@ async function startHolding(options, data, checked, stops) {
4475
4853
  void importAtSetup();
4476
4854
  else if (offersImport && options.countSessions && owner && !owner.hasPassword())
4477
4855
  countSessions();
4478
- const address = server.address();
4479
4856
  if (isLoopback(host))
4480
4857
  names = loopbackNames(host, options.allowHosts, options.publicUrl);
4481
4858
  // An address of every interface is reached on this machine at its loopback one.
4482
- const shown = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
4483
- const url = `http://${shown.includes(":") ? `[${shown}]` : shown}:${address.port}`;
4859
+ const url = urlOf(server, host);
4484
4860
  owner?.attach(options.publicUrl ?? url);
4485
4861
  webhooks.attach(options.publicUrl ?? url);
4486
4862
  // A local install is the one server an MCP server's URL may be on loopback for (anywhere else, loopback is this machine's
@@ -4540,7 +4916,8 @@ async function startHolding(options, data, checked, stops) {
4540
4916
  * is not done (a read that failed, or its notice not saved): it is read again. */
4541
4917
  const tellWait = async (row) => {
4542
4918
  const seen = `${row.state}\n${row.epoch}\n${row.runner ?? ""}\n${row.summary ?? ""}`;
4543
- if (readWaits.get(row.id) === seen)
4919
+ // An audit's shadow run waits on no one (runner/audit.ts AUDIT_PARKED): the park it ends at once is no one's to answer.
4920
+ if (readWaits.get(row.id) === seen || isShadowRun(row.id))
4544
4921
  return true;
4545
4922
  const view = await viewOverStore(store, row.id, viewDepsFor(ownOriginOf()));
4546
4923
  if (view?.status !== "input_required")
@@ -4605,6 +4982,10 @@ async function startHolding(options, data, checked, stops) {
4605
4982
  };
4606
4983
  /** A run's end, told once the run reads final. False when it is not done (a read that failed, or its notice not saved). */
4607
4984
  const tellEnd = async (id) => {
4985
+ // An audit's shadow run is no host's run (learn/audit.ts): it sends no notice of any kind; its cost reaches a host as
4986
+ // the audited run's cost.learning_usd alone.
4987
+ if (isShadowRun(id))
4988
+ return true;
4608
4989
  const now = await endNotice(id).catch((error) => (sayUnread(id, error.message), undefined));
4609
4990
  if (now === undefined)
4610
4991
  return false;
@@ -4739,7 +5120,7 @@ async function startHolding(options, data, checked, stops) {
4739
5120
  const rows = await store.runs.list({});
4740
5121
  // An end catchUp cannot read, or whose notice the store refused, is said there and left for each read to try
4741
5122
  // (endsLeft): it is before the feed's head, so no change of the feed brings it back.
4742
- const unsaved = await webhooks.catchUp(rows.filter((row) => !row.importedFrom).map(endOf), (id) => endNotice(id).catch((error) => (endsLeft.add(id), Promise.reject(error))));
5123
+ const unsaved = await webhooks.catchUp(rows.filter((row) => !row.importedFrom && !isShadowRun(row.id)).map(endOf), (id) => endNotice(id).catch((error) => (endsLeft.add(id), Promise.reject(error))));
4743
5124
  for (const id of unsaved)
4744
5125
  endsLeft.add(id);
4745
5126
  // A run that stands at a person's stop waits too (tellWait reads its view: one its stop ended reads no wait).
@@ -4777,6 +5158,7 @@ async function startHolding(options, data, checked, stops) {
4777
5158
  }
4778
5159
  await Promise.all([...workers.values()].map((w) => w.exit));
4779
5160
  await importing;
5161
+ await schemaSealed;
4780
5162
  await installStopped;
4781
5163
  await observationStopped;
4782
5164
  // The ends' follower stops before the webhooks it feeds and the store it reads.
@@ -4801,7 +5183,7 @@ async function startHolding(options, data, checked, stops) {
4801
5183
  return {
4802
5184
  url,
4803
5185
  baseUrl: `${url}/v2`,
4804
- port: address.port,
5186
+ port: server.address().port,
4805
5187
  token,
4806
5188
  tokenIds: tokens.map((entry) => entry.id),
4807
5189
  tokenFile,