@parcha/agentrun-serve 0.1.0-beta.43 → 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 (141) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/README.md +213 -24
  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/errors.d.ts +1 -0
  18. package/dist/errors.js +3 -0
  19. package/dist/harness-table.d.ts +51 -3
  20. package/dist/harness-table.js +101 -13
  21. package/dist/harness.d.ts +18 -1
  22. package/dist/harness.js +21 -9
  23. package/dist/host.d.ts +12 -10
  24. package/dist/host.js +18 -16
  25. package/dist/import-worker.d.ts +3 -0
  26. package/dist/import-worker.js +7 -5
  27. package/dist/import.d.ts +22 -1
  28. package/dist/import.js +141 -28
  29. package/dist/learn/check.d.ts +3 -0
  30. package/dist/learn/check.js +1 -1
  31. package/dist/learn/compile.js +1 -1
  32. package/dist/learn/delete.d.ts +17 -0
  33. package/dist/learn/delete.js +44 -0
  34. package/dist/learn/promote.d.ts +7 -1
  35. package/dist/learn/promote.js +8 -4
  36. package/dist/learn/skills.d.ts +4 -0
  37. package/dist/learn/skills.js +17 -1
  38. package/dist/learn/workflow-nodes.d.ts +22 -1
  39. package/dist/learn/workflow-nodes.js +28 -9
  40. package/dist/learning-cost.d.ts +100 -0
  41. package/dist/learning-cost.js +116 -1
  42. package/dist/learning-evals.d.ts +2 -0
  43. package/dist/learning-evals.js +4 -3
  44. package/dist/learning-routes.d.ts +8 -0
  45. package/dist/learning-routes.js +17 -0
  46. package/dist/learning.d.ts +1 -1
  47. package/dist/listen-first.d.ts +30 -0
  48. package/dist/listen-first.js +115 -0
  49. package/dist/llms.txt +2 -1
  50. package/dist/mcp-servers-store.d.ts +12 -12
  51. package/dist/model.d.ts +8 -4
  52. package/dist/model.js +16 -8
  53. package/dist/openapi.js +115 -39
  54. package/dist/owner.d.ts +8 -0
  55. package/dist/owner.js +11 -0
  56. package/dist/paid-calls.d.ts +6 -0
  57. package/dist/paid-calls.js +11 -1
  58. package/dist/place.d.ts +8 -3
  59. package/dist/place.js +13 -9
  60. package/dist/provider.js +15 -1
  61. package/dist/run-learning-served.d.ts +1 -1
  62. package/dist/run-model-key.d.ts +64 -0
  63. package/dist/run-model-key.js +147 -0
  64. package/dist/runner/adapter-loop.d.ts +6 -0
  65. package/dist/runner/adapter-loop.js +9 -2
  66. package/dist/runner/adapter-run-spec.d.ts +6 -3
  67. package/dist/runner/adapter-run-spec.js +70 -23
  68. package/dist/runner/adapters/index.d.ts +4 -2
  69. package/dist/runner/adapters/index.js +13 -4
  70. package/dist/runner/audit.d.ts +4 -0
  71. package/dist/runner/audit.js +15 -4
  72. package/dist/runner/beside.d.ts +2 -1
  73. package/dist/runner/beside.js +5 -2
  74. package/dist/runner/claim-secrets.d.ts +49 -0
  75. package/dist/runner/claim-secrets.js +110 -1
  76. package/dist/runner/cli-run-spec.d.ts +2 -1
  77. package/dist/runner/cli-run-spec.js +32 -13
  78. package/dist/runner/commands.d.ts +3 -6
  79. package/dist/runner/feedback-round.d.ts +3 -2
  80. package/dist/runner/feedback-round.js +7 -3
  81. package/dist/runner/harness-loops.js +30 -8
  82. package/dist/runner/journal-kinds.d.ts +5 -0
  83. package/dist/runner/learning-end.d.ts +3 -0
  84. package/dist/runner/learning-end.js +4 -0
  85. package/dist/runner/loop-contract.d.ts +6 -0
  86. package/dist/runner/loop-contract.js +4 -0
  87. package/dist/runner/loop.js +6 -2
  88. package/dist/runner/main.d.ts +1 -0
  89. package/dist/runner/main.js +24 -7
  90. package/dist/runner/memory-claim.d.ts +9 -6
  91. package/dist/runner/memory-claim.js +12 -9
  92. package/dist/runner/promotion.d.ts +5 -0
  93. package/dist/runner/promotion.js +46 -7
  94. package/dist/runner/reflect-hook.d.ts +4 -0
  95. package/dist/runner/reflect-hook.js +22 -3
  96. package/dist/runner/runner.js +57 -4
  97. package/dist/runner/store-secrets.js +9 -5
  98. package/dist/runner/workflow-spec.js +10 -2
  99. package/dist/runs-over-store.d.ts +5 -4
  100. package/dist/runs-over-store.js +13 -3
  101. package/dist/sdk/workflows.d.ts +1 -1
  102. package/dist/server.d.ts +64 -50
  103. package/dist/server.js +457 -120
  104. package/dist/store/index.d.ts +2 -2
  105. package/dist/store/index.js +1 -1
  106. package/dist/store/seal.d.ts +20 -2
  107. package/dist/store/seal.js +24 -8
  108. package/dist/store/sqlite/run-launch.d.ts +4 -1
  109. package/dist/store/sqlite/run-launch.js +12 -0
  110. package/dist/store/sqlite/store.d.ts +3 -2
  111. package/dist/store/sqlite/store.js +118 -16
  112. package/dist/store/store.d.ts +38 -3
  113. package/dist/store-reads/analytics.js +11 -1
  114. package/dist/store-reads/learning.d.ts +41 -2
  115. package/dist/store-reads/learning.js +158 -5
  116. package/dist/store-reads/stats.js +13 -3
  117. package/dist/store-view.d.ts +5 -1
  118. package/dist/store-view.js +12 -11
  119. package/dist/telemetry.d.ts +59 -0
  120. package/dist/telemetry.js +153 -0
  121. package/dist/tool-keys-store.d.ts +1 -1
  122. package/dist/tool-keys.d.ts +2 -2
  123. package/dist/tool-plane.d.ts +12 -12
  124. package/dist/tools.d.ts +11 -11
  125. package/dist/tools.js +18 -5
  126. package/dist/trigger-adapter.d.ts +3 -0
  127. package/dist/trigger-adapters.d.ts +4 -0
  128. package/dist/trigger-adapters.js +13 -0
  129. package/dist/trigger-composio.d.ts +58 -1
  130. package/dist/trigger-composio.js +160 -6
  131. package/dist/triggers.d.ts +4 -0
  132. package/dist/triggers.js +22 -3
  133. package/dist/validate.d.ts +11 -7
  134. package/dist/validate.js +8 -7
  135. package/dist/workspace/computer-for-claim.d.ts +15 -5
  136. package/dist/workspace/computer-for-claim.js +228 -32
  137. package/dist/workspace/resolve-computer.d.ts +8 -2
  138. package/dist/workspace/resolve-computer.js +1 -1
  139. package/package.json +10 -9
  140. package/dist/console/assets/index-BrcDSBD8.css +0 -1
  141. package/dist/console/assets/index-Bz6IWncl.js +0 -711
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,14 +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";
87
89
  import { gradeRow, notAuditableOf } from "./runner/audit.js";
88
90
  import { auditsOffWords, auditWriterOf, isShadowRun, readAudits, servingLinesOf } from "./learn/audit.js";
89
91
  import { auditLoopOf, COMPILE_AFTER_MAX } from "./learning-setting.js";
90
92
  import { FINAL_STATES, RUN_CHANGES_PAGE } from "./store/store.js";
91
- import { GRADE_SOURCES, gradeView, LABEL_MAX, promotionsOf, promotionsShown, servingOf } 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";
92
95
  import { runModelRef } from "./model.js";
93
96
  import { REDACTED } from "./secret-cut.js";
94
97
  // The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
@@ -109,7 +112,7 @@ import { DRAIN_TIMEOUT } from "./runner/beside.js";
109
112
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
110
113
  import { agentLoopOverStore } from "./store-reads/loop.js";
111
114
  import { printable } from "./learn/index.js";
112
- import { agentCostOverStore, agentLearningOverStore, allInOf, costRunOf, learningCountsOverStore, learningSpendOverStore, runLearningEnd, shadowSpendOf } from "./store-reads/learning.js";
115
+ import { agentCostOverStore, agentLearningOverStore, allInOf, costRunOf, learningCountsOverStore, learningSpendOverStore, runAllInOverStore, runLearningEnd, shadowSpendOf } from "./store-reads/learning.js";
113
116
  import { figuresOf, LearningBatches } from "./learning-batch.js";
114
117
  import { costCsv, learningCostQuery, RUN_PATHS } from "./learning-cost.js";
115
118
  import { evalOf, evalsOf, recordEval } from "./learning-evals.js";
@@ -136,7 +139,8 @@ import { FAUX_GITHUB, FAUX_GITHUB_FILE, startFauxGitHub } from "./github-faux.js
136
139
  import { GITHUB_API } from "./github.js";
137
140
  import { bindingOf, REPO_NAME } from "./run-repo.js";
138
141
  import { HookCut, receivePush } from "./push-handler.js";
139
- 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";
140
144
  import { webhook } from "./trigger-webhook.js";
141
145
  import { SCHEME_NAMES } from "./trigger-signatures.js";
142
146
  import { permissionFrom, pinnedEffect, toolEffect } from "./tool-gate.js";
@@ -185,6 +189,12 @@ const IDEMPOTENCY_FILE = ".idempotency.json";
185
189
  * computer kind; `browser`, the browser's own), then its page, files or WebSocket. Both are served by the same code. */
186
190
  const LIVE_PATH = /^\/v2\/runs\/([^/]+)\/(computer|browser)\/live(\/.*)$/;
187
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;
188
198
  const MAX_MESSAGE = 20_000;
189
199
  const MAX_WAIT_MS = 25_000;
190
200
  const PAGE_ROWS = 500;
@@ -205,10 +215,12 @@ const LINK_REFUSED = "A link is on the way to this path, or is the file: this se
205
215
  /** Each test switch a run's process reads, by the variable it reads it from: set only under `faux`, but the faux
206
216
  * harness's, which scripts the harnesses with or without it. */
207
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]];
208
- /** The test switches a run's process gets, each module path resolved: empty outside tests. A test's in-process runner
209
- * 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). */
210
221
  export function fauxEnvOf(options) {
211
- 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) } : {}) };
212
224
  if (!options.faux)
213
225
  return env;
214
226
  env[FAUX_ENV] = resolve(options.faux);
@@ -560,7 +572,7 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
560
572
  runtimes: ["runner"],
561
573
  /** The harnesses a revision may name (`definition.harness`), whether this server runs each, and how many at once. */
562
574
  // `keys`, what a model key would unlock, is the key rows' (listToolKeys), never served here.
563
- 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)) })),
564
576
  /** The places a revision may name (`definition.place`), this host's default, and whether this server has each box. */
565
577
  places: placesOf(boxes, boxAllowOf(env)),
566
578
  models,
@@ -620,8 +632,9 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
620
632
  * (tool-keys-store.ts), never in the clear. */
621
633
  tool_keys: { routes: true, at_rest: "sealed" },
622
634
  /** /settings/mcp-servers: remote MCP servers previewed and saved, each credential sealed under the server's seal key,
623
- * which always exists (seal-key.ts), so MCP credentials are always kept sealed. */
624
- 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)] },
625
638
  /** This server's learning switch (`--learning`): on, a run learns when its agent says `learning: true`; off, none does. */
626
639
  learning,
627
640
  /** /settings/webhook: one URL POSTed, signed by the Standard Webhooks spec, when a run needs its person and when it
@@ -685,6 +698,9 @@ export async function startServe(options) {
685
698
  // A harness table module is the server's to name, from `harnessTable` alone, for itself and its runs: one in its own
686
699
  // environment (an operator's export, a leftover) never loads, wherever the server reads its environment.
687
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];
688
704
  await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
689
705
  // Canonical once, here: a computer's mount source below it must then be its own canonical path, through no link.
690
706
  const data = await realpath(resolve(options.data));
@@ -716,8 +732,8 @@ export async function startServe(options) {
716
732
  const learningBudget = learningBudgetOf(process.env, options.learningBudget);
717
733
  // A limit on a run's requests on free models that is no whole number above 0 stops the start, naming its variable.
718
734
  freeModelRequestsOf(process.env);
719
- const minFreeMib = process.env.AGENTRUN_MIN_FREE_MB ? Number(process.env.AGENTRUN_MIN_FREE_MB) : MIN_FREE_MIB;
720
- if (!(Number.isFinite(minFreeMib) && minFreeMib >= 0))
735
+ const minFreeMib = minFreeMibOf(process.env);
736
+ if (minFreeMib === undefined)
721
737
  throw new Error("AGENTRUN_MIN_FREE_MB is a number of MiB, 0 or more");
722
738
  const minFreeBytes = options.minFreeBytes ?? minFreeMib * 2 ** 20;
723
739
  // The template packages, each checked whole (templates.ts readPackage): a broken one stops the start.
@@ -781,7 +797,11 @@ async function startHolding(options, data, checked, stops) {
781
797
  // shown nowhere.
782
798
  let secretStores;
783
799
  let triggerSettings = new Map();
784
- 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);
785
805
  // The one store (module A), opened here as this data root's single owner, before the settings layers that read it: its
786
806
  // owner lock holds the store to this server (the data root's own lock follows), and it refuses a data directory an
787
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
@@ -867,6 +887,8 @@ async function startHolding(options, data, checked, stops) {
867
887
  };
868
888
  // Aborted as close() begins: a key's check still waiting on its provider stops waiting, and its save stores nothing.
869
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();
870
892
  // This server's saved keys, read by name: handed to its own reading and its own runs, never shared with another server.
871
893
  const storedKeys = (name) => toolKeys.value(name);
872
894
  // A stored key that does not open is said once at the start, never a refusal to start.
@@ -1125,6 +1147,19 @@ async function startHolding(options, data, checked, stops) {
1125
1147
  };
1126
1148
  /** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
1127
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
+ };
1128
1163
  // The agents accessor the routes call, over the one store (module A): the agents-store functions, with the run-row reads
1129
1164
  // the server makes (store-reads) under `.store`. `.request` is a thin pass-through — the store runs its own transactions,
1130
1165
  // so a call needs no outer serialization. The old Agents class and its per-agent home store are gone.
@@ -1326,6 +1361,10 @@ async function startHolding(options, data, checked, stops) {
1326
1361
  return { learns: false, why: "it is archived." };
1327
1362
  if (learning === "off")
1328
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 };
1329
1368
  if (entry.revision?.kind !== "agentic" || !learnsOf(entry.revision.body.learning))
1330
1369
  return { learns: false, why: "its current revision does not say learning: true. Turn learning on first." };
1331
1370
  return { learns: true };
@@ -1450,9 +1489,25 @@ async function startHolding(options, data, checked, stops) {
1450
1489
  tokenUsed.set(req, id);
1451
1490
  return id !== undefined;
1452
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);
1453
1505
  const keptFile = join(data, IDEMPOTENCY_FILE);
1454
1506
  const kept = JSON.parse(await readFile(keptFile, "utf8").catch(() => "null"));
1455
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;
1456
1511
  // A failed save rejects only its own caller: the next save starts from a settled chain and writes every kept key.
1457
1512
  let saving = Promise.resolve();
1458
1513
  const keep = () => (saving = saving
@@ -1462,7 +1517,7 @@ async function startHolding(options, data, checked, stops) {
1462
1517
  await writeFile(`${keptFile}.partial`, JSON.stringify({ version: 1, entries }), { mode: 0o600 });
1463
1518
  await rename(`${keptFile}.partial`, keptFile);
1464
1519
  }));
1465
- const host = options.host ?? "127.0.0.1";
1520
+ const host = options.host ?? DEFAULT_HOST;
1466
1521
  // Open setup (no code) only where no one else reaches the port: a loopback listener. Bound to any other address
1467
1522
  // (0.0.0.0 in the image, a LAN address), the first visit takes the printed code even with no public address.
1468
1523
  const openSetup = options.openSetup === true && isLoopback(host);
@@ -1592,6 +1647,137 @@ async function startHolding(options, data, checked, stops) {
1592
1647
  signal: stopping.signal,
1593
1648
  say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
1594
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
+ }
1595
1781
  /** What a save refused while Composio triggers use the server says to do once they are gone (composio-triggers.ts inUse). */
1596
1782
  const SAVE_AFTER_TRIGGERS = "then save the server again";
1597
1783
  /** What a save over a preset server left at Composio (ComposioDropped), removed there with the key it was made with, in
@@ -1624,18 +1810,21 @@ async function startHolding(options, data, checked, stops) {
1624
1810
  let closing = false;
1625
1811
  const workers = new Map();
1626
1812
  // Once the server closes, no worker starts: a setup still being answered then leaves its yes for the next start.
1627
- 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) => {
1628
1814
  const worker = new Worker(new URL("./import-worker.js", import.meta.url), {
1629
1815
  // The secrets this process holds (secrets.ts keeps them out of every environment, so the worker's has none), in the
1630
1816
  // worker's memory alone: what the import cuts out of everything it writes. The keys saved on the Tool keys page are
1631
1817
  // not passed; the worker reads them from the store over the port (sealed rows it opens with the seal key among these
1632
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.
1633
- 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]]; })) },
1634
1820
  // Started from a string (node --input-type=module -e, as a test or a `--` command may), the server's flags are given again
1635
1821
  // without that string and its type: a worker started from a file with them is refused. Otherwise the worker
1636
1822
  // inherits them as Node passes them on, which leaves out the flags a worker may not take (on Node 24 a test
1637
1823
  // runner's child holds many).
1638
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 },
1639
1828
  });
1640
1829
  workers.set(worker, { task, exit: once(worker, "exit").catch(() => undefined) });
1641
1830
  let answer;
@@ -1666,7 +1855,7 @@ async function startHolding(options, data, checked, stops) {
1666
1855
  if (count)
1667
1856
  return;
1668
1857
  count = { state: "counting" };
1669
- 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) => {
1670
1859
  count = { state: "failed" };
1671
1860
  process.stderr.write(`agentrun-serve: the count of this machine's sessions failed: ${error.message}\n`);
1672
1861
  });
@@ -1675,25 +1864,69 @@ async function startHolding(options, data, checked, stops) {
1675
1864
  if (task === "plan")
1676
1865
  worker.postMessage("stop"); };
1677
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`).
1678
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
+ };
1679
1895
  let importing;
1680
- /** The import at setup as the owner's console reads it: running, done with what it took, or stopped (the next start
1681
- * 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). */
1682
1898
  let importState;
1683
1899
  /** Never rejects: whatever stops it (the store held past its wait, a file) is said on stderr, and the server goes on. */
1684
1900
  const importAtSetup = () => (importing ??= (async () => {
1685
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;
1686
1910
  try {
1687
- const answer = await onWorker("import");
1688
- 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));
1689
1923
  return void (importState = { state: "stopped" });
1924
+ }
1690
1925
  // The whole import, every start's part of it: what earlier starts took is kept with the owner's yes.
1691
- // The yes as setup wrote it is empty: no earlier start took anything.
1692
- const before = (await readJson(importAsked));
1693
- const agents = [...new Set([...(Array.isArray(before?.agents) ? before.agents.filter((id) => typeof id === "string") : []), ...answer.took.agents])];
1694
- 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;
1695
1928
  if (answer.stopped) {
1696
- await writeDurable(importAsked, JSON.stringify({ agents, runs }));
1929
+ await writeDurable(importAsked, JSON.stringify({ ...asked, agents, runs }));
1697
1930
  return void (importState = { state: "stopped" });
1698
1931
  }
1699
1932
  await rm(importAsked, { force: true });
@@ -1702,9 +1935,18 @@ async function startHolding(options, data, checked, stops) {
1702
1935
  process.stdout.write(`${logLine("import", took)}\n`);
1703
1936
  }
1704
1937
  catch (error) {
1705
- importState = { state: "stopped" };
1706
- 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" };
1707
1948
  process.stderr.write(`agentrun-serve: the import at setup stopped (the next start goes on with it): ${error.message}\n`);
1949
+ }
1708
1950
  }
1709
1951
  })());
1710
1952
  // ---- helpers --------------------------------------------------------------------------------------------------------
@@ -1845,7 +2087,8 @@ async function startHolding(options, data, checked, stops) {
1845
2087
  if (typeof key !== "string" || key.length < 1 || key.length > 255)
1846
2088
  throw new ApiError("bad_request", "Idempotency-Key is 1 to 255 characters");
1847
2089
  const slot = `${path}\n${key}`;
1848
- const fingerprint = stable(body);
2090
+ const text = stable(body);
2091
+ const fingerprint = fingerprintOf(text);
1849
2092
  const now = Date.now();
1850
2093
  for (const [k, v] of idempotency)
1851
2094
  if (now - v.at > IDEMPOTENCY_TTL_S * 1000)
@@ -1861,7 +2104,8 @@ async function startHolding(options, data, checked, stops) {
1861
2104
  idempotency.set(slot, { fingerprint, at: now });
1862
2105
  let answer;
1863
2106
  try {
1864
- 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) });
1865
2109
  }
1866
2110
  catch (error) {
1867
2111
  idempotency.delete(slot);
@@ -1870,7 +2114,7 @@ async function startHolding(options, data, checked, stops) {
1870
2114
  // The work happened, so the key keeps its answer in memory even when the file write fails: a retry replays it
1871
2115
  // instead of doing the work twice. Only a restart before the next good save loses it, and a run's create not even
1872
2116
  // then: the store keeps its run under the key's origin.
1873
- 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 ?? {} } });
1874
2118
  await keep().catch((error) => void process.stderr.write(`agentrun-serve: idempotency save: ${error.message}\n`));
1875
2119
  return answer;
1876
2120
  }
@@ -1959,7 +2203,7 @@ async function startHolding(options, data, checked, stops) {
1959
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 } });
1960
2204
  }
1961
2205
  /** Where a revision of `kind` naming `tools` and no place runs here: the place a new agent would be saved with. */
1962
- const fallbackPlace = (kind, tools) => defaultPlaceOf(kind, tools, boxOffers, (tool) => toolOf(tool)?.runnerOnly === true);
2206
+ const fallbackPlace = (kind, tools) => defaultPlaceOf(kind, tools, boxOffers, toolOf);
1963
2207
  /** What a save of `revision` pins of the MCP tools it grants (an agentic revision's: a workflow's nodes bind none): each
1964
2208
  * granted server listed once, now, with its saved credential (McpServersOverStore.pinListing), as `tools` each server's
1965
2209
  * listing in the harnesses' shape for the save's checks (blockersOf's `mcp`), and `pin` making the pin from them. A server
@@ -2049,7 +2293,8 @@ async function startHolding(options, data, checked, stops) {
2049
2293
  if (sdkOf(body))
2050
2294
  return { warnings: [], stamp: {} };
2051
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.
2052
- 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;
2053
2298
  if (install) {
2054
2299
  void install.ensure().catch((error) => log?.(logLine("harness_install_failed", { harness: install.entry.id, message: error.message })));
2055
2300
  }
@@ -2095,18 +2340,19 @@ async function startHolding(options, data, checked, stops) {
2095
2340
  return pinned && { monid: pinned.pin, warnings: pinned.warnings.map(({ tool, message }) => ({ field: `definition.tools[${tools.indexOf(tool)}]`, reason: PRICED_BY_USAGE, message })) };
2096
2341
  }
2097
2342
  /** POST /agents' body made into its agent, as that route makes one, with what this host still lacks for it. A new agent
2098
- * that names no place is given this server's box (place.ts newAgentPlace), stamped on its revision; one that names a
2099
- * 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. */
2100
2346
  async function createAgentOf(body, template) {
2101
2347
  let warnings = [];
2102
- const definition = checkDefinitionBody(body);
2348
+ const definition = checkDefinitionBody(body, { harnesses });
2103
2349
  const named = Array.isArray(definition.definition.tools) ? definition.definition.tools : [];
2104
- 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);
2105
2351
  const entry = await agents.create(definition, async (revision) => {
2106
2352
  const saved = await saveable(revision);
2107
2353
  warnings = saved.warnings;
2108
2354
  return saved.stamp;
2109
- }, "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined, template);
2355
+ }, place.mode === "sandbox" ? { place, tools: NEW_AGENT_TOOLS } : undefined, template);
2110
2356
  return { entry, warnings };
2111
2357
  }
2112
2358
  /** A replay's ports for agent `entry` (runner/promotion.ts askReplay, replayView): its learning folder where this server
@@ -2376,37 +2622,89 @@ async function startHolding(options, data, checked, stops) {
2376
2622
  * tunnel's own port, say); else, with no Host, its own. Links made outside a request (the owner's, the webhooks') are
2377
2623
  * at the public URL or the server's own address. */
2378
2624
  const linkOrigin = (req) => (options.publicUrl ?? (req.headers.host ? ownOrigin(req) : url)).replace(/\/+$/, "");
2379
- /** A run body's `mcp_auth` taken out of it, before anything else reads the body: the credentials a run's caller hands
2380
- * its per_run MCP servers for this run alone (mcp-probe.ts mcpAuthOf). They never reach the run's saved body, its
2381
- * timeline, an idempotency fingerprint (a retry with a fresh credential replays its first answer) or a log: only the
2382
- * seal `sealer` makes, which seals them for the run's id into its launch row (store/seal.ts sealRunMcpAuth), bound to
2383
- * each server's origin then. The request calls `sealer` only for new work, inside its idempotent work: there each
2384
- * entry must name a saved per_run server, else 422, nothing written. A retry its key already answered replays that
2385
- * answer even when the server has since changed or gone, since it does no new work. */
2386
- function handedMcpAuth(body) {
2387
- if (body.mcp_auth === undefined)
2388
- return { body, sealer: async () => undefined };
2389
- const { mcp_auth, ...rest } = body;
2390
- 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 () => {
2391
2639
  const issues = [];
2392
- const handed = mcpAuthOf(mcp_auth, issues);
2640
+ const mcp = mcp_auth === undefined ? undefined : mcpAuthOf(mcp_auth, issues);
2393
2641
  const auth = {};
2394
- for (const [server, headers] of Object.entries(handed ?? {})) {
2642
+ for (const [server, headers] of Object.entries(mcp ?? {})) {
2395
2643
  const row = await getMcpServer(store, server);
2396
2644
  if (row?.auth !== "per_run")
2397
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.` });
2398
2646
  else
2399
2647
  auth[server] = { headers, origin: new URL(row.url).origin };
2400
2648
  }
2649
+ const model = model_key === undefined ? undefined : modelKeyOf(model_key, issues);
2401
2650
  if (issues.length)
2402
2651
  throw invalid(issues);
2403
- 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 } : {}) });
2404
2703
  };
2405
- return { body: rest, sealer };
2406
2704
  }
2407
2705
  async function createRun(req, agentId) {
2408
2706
  const entry = await needRunnableAgent(agentId);
2409
- const { body, sealer } = handedMcpAuth(await bodyOf(req));
2707
+ const { body, handed } = handedLaunchSecrets(await bodyOf(req));
2410
2708
  return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
2411
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.
2412
2710
  const first = origin && (await agents.request(() => agents.store.runOfOrigin(origin.key)));
@@ -2416,7 +2714,7 @@ async function startHolding(options, data, checked, stops) {
2416
2714
  const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
2417
2715
  return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
2418
2716
  }
2419
- const seal = await sealer();
2717
+ const seal = startSeal(await handed());
2420
2718
  const run = await startRunOf(entry, body, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}) });
2421
2719
  // Its view from the store: the run and its launch were inserted in one transaction, so the view reads it whole.
2422
2720
  return { status: 202, body: await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${run.id}` } };
@@ -2428,7 +2726,7 @@ async function startHolding(options, data, checked, stops) {
2428
2726
  * Its first run makes the agent, a version's first run its revision; a later run of the version reuses both
2429
2727
  * (runs-over-store startInline). The answer is POST /agents/{agent_id}/runs' own: 202 and the run. */
2430
2728
  async function createInlineRun(req) {
2431
- const { body, sealer } = handedMcpAuth(await bodyOf(req));
2729
+ const { body, handed } = handedLaunchSecrets(await bodyOf(req));
2432
2730
  if (isObject(body.definition) && body.definition.native !== undefined)
2433
2731
  throw new ApiError("input_invalid", "Native references are registered only through /native/connect on the source machine; an inline definition cannot create one.");
2434
2732
  const { external, definition, skills, note, revision: pinned, ...run } = body;
@@ -2437,13 +2735,13 @@ async function startHolding(options, data, checked, stops) {
2437
2735
  ...externalIssues(external),
2438
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." }] : []),
2439
2737
  ...runBodyIssues(run),
2440
- ...definitionBodyIssues(given),
2738
+ ...definitionBodyIssues(given, { harnesses }),
2441
2739
  // The agent's id is this server's, one per external reference, and its version is the reference's.
2442
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}.` }] : [])),
2443
2741
  ];
2444
2742
  if (issues.length)
2445
2743
  throw invalid(issues);
2446
- const checked = checkDefinitionBody(given);
2744
+ const checked = checkDefinitionBody(given, { harnesses });
2447
2745
  const made = makeRevision(checked.definition, checked.skills ?? {}, checked.note);
2448
2746
  // A version's first run is its save: refused where POST /agents refuses the definition (one this host can never run),
2449
2747
  // its MCP tools pinned as a save pins them (a server down keeps the agent's current pin when this version grants nothing
@@ -2471,7 +2769,7 @@ async function startHolding(options, data, checked, stops) {
2471
2769
  const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
2472
2770
  return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
2473
2771
  }
2474
- const seal = await sealer();
2772
+ const seal = startSeal(await handed());
2475
2773
  const started = await startInline(store, startDeps, inline, run, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}) });
2476
2774
  return { status: 202, body: await viewOverStore(store, started.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${started.id}` } };
2477
2775
  });
@@ -2579,8 +2877,9 @@ async function startHolding(options, data, checked, stops) {
2579
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.
2580
2878
  let rows = (await listRunsOverStore(store, { ...filter, ...(labels ? { labels } : {}) }, ctx)).filter((row) => Boolean(row.archivedAt) === archived && !isShadowRun(row.id));
2581
2879
  if (status !== null) {
2582
- // The v2 status is the run view's (store-view over the journal), per row.
2583
- 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)));
2584
2883
  rows = rows.filter((_, i) => statuses[i] === status);
2585
2884
  }
2586
2885
  // summaryOverStore reads each run's view (its version, status, cost and learning among them); no versions map is needed.
@@ -2811,7 +3110,7 @@ async function startHolding(options, data, checked, stops) {
2811
3110
  throw invalid(issues);
2812
3111
  return { password: body.password, body };
2813
3112
  }
2814
- /** 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
2815
3114
  * /v2/auth/session, answered before any credential: their own checks are the setup code (or the token), the password,
2816
3115
  * and the session. */
2817
3116
  async function ownerRoute(req, res, path, me) {
@@ -2826,13 +3125,18 @@ async function startHolding(options, data, checked, stops) {
2826
3125
  if (!byToken)
2827
3126
  fromPage(req);
2828
3127
  const { password, body } = await passwordIn(req, ["password", "code", "import"]);
2829
- if (body.import !== undefined && typeof body.import !== "boolean")
2830
- throw invalid([{ field: "import", reason: "wrong_type", message: "import is true or false" }]);
2831
- 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)
2832
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." }]);
2833
3137
  // The owner's yes, on the box ticked, is kept with the owner: written durably before the password, so a setup that
2834
3138
  // cannot keep it sets no owner and can be tried again, and taken back if the password is not written.
2835
- 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;
2836
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
2837
3141
  // code only in the log), compared as the header is, in constant time; a wrong one counts as a wrong code.
2838
3142
  const tokenAsCode = typeof body.code === "string" && body.code !== "" && bearer(`Bearer ${body.code}`, req);
@@ -2849,23 +3153,38 @@ async function startHolding(options, data, checked, stops) {
2849
3153
  viewers.recheck();
2850
3154
  // The count is for the offer, now answered: it stops.
2851
3155
  stopCount();
2852
- // Only on the box ticked: the owner, now set, asked for it. It runs after the answer; agents arrive as it goes.
2853
- 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)
2854
3158
  void importAtSetup();
2855
- 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() });
2856
3174
  }
2857
3175
  case "/setup/import": {
2858
3176
  // No offer is an answer, `{ offer: false }`, never a 404: the console reads this on its first page, and a browser
2859
3177
  // logs every 404 as an error.
2860
3178
  // Before the owner is set, to the setup page: none on a server that cannot import, else that it can (202 while it
2861
- // 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.
2862
3181
  if (!me.hasPassword()) {
2863
3182
  pageRead(req);
2864
3183
  if (!offersImport)
2865
3184
  return send(res, 200, { offer: false });
2866
3185
  countSessions();
2867
3186
  if (count?.state === "counted")
2868
- return send(res, 200, { projects: count.projects, sessions: count.sessions });
3187
+ return send(res, 200, { projects: count.projects, sessions: count.sessions, candidates: count.candidates });
2869
3188
  if (count?.state === "failed")
2870
3189
  return send(res, 200, { projects: null, sessions: null });
2871
3190
  return send(res, 202, { counting: true });
@@ -2961,14 +3280,14 @@ async function startHolding(options, data, checked, stops) {
2961
3280
  const bodies = new WeakMap();
2962
3281
  /** The check of a whole body a route makes before anything else, by operation, for the body sent: what a suggested
2963
3282
  * value must pass. PUT .../definition's contract body (the definition itself) has none here. */
2964
- const definitionCheck = (creating) => (body) => definitionBodyIssues(isObject(body) ? body : {}, { creating });
3283
+ const definitionCheck = (creating) => (body) => definitionBodyIssues(isObject(body) ? body : {}, { creating, harnesses });
2965
3284
  const BODY_CHECKS = {
2966
3285
  createAgent: () => definitionCheck(true),
2967
3286
  updateDefinition: (sent) => ("definition" in sent ? definitionCheck(false) : undefined),
2968
3287
  // POST /runs' agent, given inline, is POST /agents' body inside its own: checked as that one is.
2969
3288
  createInlineRun: () => (body) => {
2970
3289
  const { definition, skills, note } = isObject(body) ? body : {};
2971
- return definitionBodyIssues({ definition, ...(skills !== undefined ? { skills } : {}), ...(note !== undefined ? { note } : {}) });
3290
+ return definitionBodyIssues({ definition, ...(skills !== undefined ? { skills } : {}), ...(note !== undefined ? { note } : {}) }, { harnesses });
2972
3291
  },
2973
3292
  };
2974
3293
  /** An operation's documented request bodies (its JSON media type's examples), each its value. */
@@ -3343,7 +3662,7 @@ async function startHolding(options, data, checked, stops) {
3343
3662
  warnings = saved.warnings;
3344
3663
  return saved.stamp;
3345
3664
  };
3346
- 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 }) });
3347
3666
  reconcileComputer(id);
3348
3667
  return send(res, 200, { ...agentView(edited, linkOrigin(req), await agentExtra(edited)), warnings }, { etag: etagOf(edited) });
3349
3668
  }
@@ -3439,7 +3758,7 @@ async function startHolding(options, data, checked, stops) {
3439
3758
  const view = await viewOverStore(store, id, runReadDepsFor(linkOrigin(req)));
3440
3759
  if (!view)
3441
3760
  throw new ApiError("not_found", `no run ${id}`);
3442
- return send(res, 200, { ...view, ...(await runComputerOf(id, view)) });
3761
+ return send(res, 200, { ...view, ...(await runComputerOf(id, view)), ...(await allInViewOf(id, view)) });
3443
3762
  }
3444
3763
  case "getTimeline":
3445
3764
  await needRun(id);
@@ -3450,9 +3769,9 @@ async function startHolding(options, data, checked, stops) {
3450
3769
  const run = await needRun(id);
3451
3770
  if (run.kind === "workflow")
3452
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.");
3453
- const { body, sealer } = handedMcpAuth(await bodyOf(req));
3772
+ const { body, handed } = handedLaunchSecrets(await bodyOf(req));
3454
3773
  const answer = await idempotent(req, `/runs/${id}/messages`, body, async () => {
3455
- const seal = await sealer();
3774
+ const seal = await messageSeal(run, await handed());
3456
3775
  const extra = unknownFields(body, ["content"]);
3457
3776
  if (extra.length)
3458
3777
  throw invalid(extra);
@@ -3461,8 +3780,8 @@ async function startHolding(options, data, checked, stops) {
3461
3780
  throw invalid([{ field: "content", reason: content === undefined ? "missing" : "wrong_type", message: "content is a non-empty string" }]);
3462
3781
  if (content.length > MAX_MESSAGE)
3463
3782
  throw invalid([{ field: "content", reason: "too_long", message: `content is at most ${MAX_MESSAGE} characters` }]);
3464
- // Its mcp_auth replaces the run's handed credentials in the steer's own write, so the turn it starts uses them.
3465
- 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 } : {}) });
3466
3785
  // The run's state after the command row is written (the run view): the runner applies the steer; the client polls.
3467
3786
  const { status, state } = await runStatusState(run.id);
3468
3787
  return { status: 202, body: { run_id: run.id, message_id: messageId, mode, status, state, poll_after_ms: 1000 } };
@@ -3548,7 +3867,8 @@ async function startHolding(options, data, checked, stops) {
3548
3867
  ...(typeof m.workflow_promotion === "number" ? { promotion: m.workflow_promotion } : {}),
3549
3868
  };
3550
3869
  // Kept with what it asks of the run's learning (runner/feedback-round.ts): nothing, or a look-back.
3551
- 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) })));
3552
3872
  // A grade of a run its learned workflow answered alone is an audit row too (runner/audit.ts gradeRow): the hold rule
3553
3873
  // reads it with the shadows'. A row not written now is logged, never the grade refused.
3554
3874
  const said = (line) => log?.(logLine("audit", { run: row.id, said: line }));
@@ -4051,7 +4371,7 @@ async function startHolding(options, data, checked, stops) {
4051
4371
  const read = await agentCostOverStore(store, id, limit);
4052
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.
4053
4373
  const shown = await learningShown(id);
4054
- 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) })) } };
4055
4375
  if (csv) {
4056
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"` });
4057
4377
  return void res.end(costCsv(cost.runs));
@@ -4074,9 +4394,27 @@ async function startHolding(options, data, checked, stops) {
4074
4394
  // rule startAudit reads); and how many of the serving revision's runs a trigger started (never audited).
4075
4395
  const writer = auditWriterOf(entry.revision ?? undefined);
4076
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
+ };
4077
4414
  const serving = await Promise.all(servingOf(records).map(async (one, i) => ({
4078
4415
  ...shownRead.serving[i], ...lines[i], audits_off: auditsOff,
4079
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),
4080
4418
  })));
4081
4419
  return send(res, 200, { agent: id, promotions: shownRead.promotions, serving });
4082
4420
  }
@@ -4189,6 +4527,10 @@ async function startHolding(options, data, checked, stops) {
4189
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.`);
4190
4528
  }
4191
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);
4192
4534
  const started = await replayAsked(() => askReplay(replayAskOf(entry), name, digest, inputs));
4193
4535
  return send(res, 202, started, { location: `/v2/agents/${encodeURIComponent(id)}/learning/workflows/${encodeURIComponent(name)}/revisions/${encodeURIComponent(digest)}/replays/${started.replay}` });
4194
4536
  }
@@ -4303,6 +4645,10 @@ async function startHolding(options, data, checked, stops) {
4303
4645
  case "deleteTrigger": {
4304
4646
  // Deleted here whatever its sender says; what could not be removed there is answered (Composio's instance).
4305
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" }));
4306
4652
  if (said)
4307
4653
  return send(res, 200, { deleted: true, ...said });
4308
4654
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
@@ -4356,7 +4702,9 @@ async function startHolding(options, data, checked, stops) {
4356
4702
  }
4357
4703
  })();
4358
4704
  let names;
4359
- 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) => {
4360
4708
  const requestId = `req_${randomBytes(8).toString("hex")}`;
4361
4709
  res.setHeader("x-request-id", requestId);
4362
4710
  if (log && !quiet) {
@@ -4404,7 +4752,7 @@ async function startHolding(options, data, checked, stops) {
4404
4752
  if (options.apiOnly && !servedApiOnly(ROUTES, req.method, raw))
4405
4753
  return fail(new ApiError("not_found", apiOnlyRefusal(raw)));
4406
4754
  // Before the page: its cookie must not stand in for the token on the owner's own routes, nor on the MCP endpoint.
4407
- 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/")))
4408
4756
  return void ownerRoute(req, res, raw.slice(3), owner).catch(fail);
4409
4757
  if (raw === MCP_PATH)
4410
4758
  return void mcp(req, res).catch(fail);
@@ -4424,13 +4772,13 @@ async function startHolding(options, data, checked, stops) {
4424
4772
  if (viewing)
4425
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"));
4426
4774
  route(req, res, url, raw.slice(3)).catch(fail);
4427
- });
4775
+ };
4428
4776
  // A request's headers come within 10 s, whatever its route: nothing sends more than a few kilobytes of them. Its body
4429
4777
  // keeps Node's 5-minute request timeout, which an upload of a large file needs; the token-less hook route has its own
4430
4778
  // 30 s for its body (push-handler.ts HOOK_BODY_MS), so dribbling senders hold no socket for long.
4431
4779
  server.headersTimeout = 10_000;
4432
4780
  // The one upgrade this server takes: a run's live computer viewer's WebSocket (browser-live.ts). Every other is refused.
4433
- server.on("upgrade", (req, socket, head) => {
4781
+ const onUpgrade = (req, socket, head) => {
4434
4782
  socket.on("error", () => socket.destroy());
4435
4783
  const raw = (req.url ?? "/").split("?")[0];
4436
4784
  const viewing = LIVE_PATH.exec(raw);
@@ -4486,28 +4834,14 @@ async function startHolding(options, data, checked, stops) {
4486
4834
  viewers.watch(socket, admitted);
4487
4835
  proxyLiveUpgrade(req, socket, head, handover, viewing[3], () => { piping = true; }, reach);
4488
4836
  })().catch(() => (piping ? void socket.destroy() : deny("500 Internal Server Error")));
4489
- });
4490
- const first = options.port ?? DEFAULT_PORT;
4491
- const last = options.nextFreePort && first !== 0 ? Math.min(first + 99, 65_535) : first;
4492
- for (let port = first;; port++) {
4493
- try {
4494
- // Each attempt takes off both its handlers when it ends, so a taken port leaves no listener behind.
4495
- await new Promise((done, reject) => {
4496
- const onError = (error) => (server.off("listening", onListening), reject(error));
4497
- const onListening = () => (server.off("error", onError), done());
4498
- server.once("error", onError);
4499
- server.once("listening", onListening);
4500
- server.listen(port, host);
4501
- });
4502
- break;
4503
- }
4504
- catch (error) {
4505
- if (error.code !== "EADDRINUSE")
4506
- throw error;
4507
- if (port < last)
4508
- continue;
4509
- throw last > first ? Object.assign(new Error(`every port from ${first} to ${last} on ${host} is taken`), { code: "EADDRINUSE" }) : error;
4510
- }
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);
4511
4845
  }
4512
4846
  // The tool keys the server is started with, each checked once against its provider, in the background, once it
4513
4847
  // listens: a start that fails sends no check, and the start never waits on one. Capabilities are made again as each
@@ -4519,12 +4853,10 @@ async function startHolding(options, data, checked, stops) {
4519
4853
  void importAtSetup();
4520
4854
  else if (offersImport && options.countSessions && owner && !owner.hasPassword())
4521
4855
  countSessions();
4522
- const address = server.address();
4523
4856
  if (isLoopback(host))
4524
4857
  names = loopbackNames(host, options.allowHosts, options.publicUrl);
4525
4858
  // An address of every interface is reached on this machine at its loopback one.
4526
- const shown = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
4527
- const url = `http://${shown.includes(":") ? `[${shown}]` : shown}:${address.port}`;
4859
+ const url = urlOf(server, host);
4528
4860
  owner?.attach(options.publicUrl ?? url);
4529
4861
  webhooks.attach(options.publicUrl ?? url);
4530
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
@@ -4650,6 +4982,10 @@ async function startHolding(options, data, checked, stops) {
4650
4982
  };
4651
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). */
4652
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;
4653
4989
  const now = await endNotice(id).catch((error) => (sayUnread(id, error.message), undefined));
4654
4990
  if (now === undefined)
4655
4991
  return false;
@@ -4784,7 +5120,7 @@ async function startHolding(options, data, checked, stops) {
4784
5120
  const rows = await store.runs.list({});
4785
5121
  // An end catchUp cannot read, or whose notice the store refused, is said there and left for each read to try
4786
5122
  // (endsLeft): it is before the feed's head, so no change of the feed brings it back.
4787
- 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))));
4788
5124
  for (const id of unsaved)
4789
5125
  endsLeft.add(id);
4790
5126
  // A run that stands at a person's stop waits too (tellWait reads its view: one its stop ended reads no wait).
@@ -4822,6 +5158,7 @@ async function startHolding(options, data, checked, stops) {
4822
5158
  }
4823
5159
  await Promise.all([...workers.values()].map((w) => w.exit));
4824
5160
  await importing;
5161
+ await schemaSealed;
4825
5162
  await installStopped;
4826
5163
  await observationStopped;
4827
5164
  // The ends' follower stops before the webhooks it feeds and the store it reads.
@@ -4846,7 +5183,7 @@ async function startHolding(options, data, checked, stops) {
4846
5183
  return {
4847
5184
  url,
4848
5185
  baseUrl: `${url}/v2`,
4849
- port: address.port,
5186
+ port: server.address().port,
4850
5187
  token,
4851
5188
  tokenIds: tokens.map((entry) => entry.id),
4852
5189
  tokenFile,