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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +78 -46
  3. package/dist/adapters.d.ts +0 -3
  4. package/dist/adapters.js +0 -7
  5. package/dist/agents.d.ts +1 -1
  6. package/dist/api-only.d.ts +14 -0
  7. package/dist/api-only.js +33 -0
  8. package/dist/archil-routes.d.ts +1 -1
  9. package/dist/box-egress-vm.d.ts +0 -8
  10. package/dist/box-egress-vm.js +0 -10
  11. package/dist/box-egress.d.ts +0 -4
  12. package/dist/box-egress.js +1 -16
  13. package/dist/box-paths.d.ts +25 -2
  14. package/dist/box-paths.js +79 -11
  15. package/dist/box-relay.d.ts +0 -11
  16. package/dist/box-relay.js +0 -20
  17. package/dist/box-settings.d.ts +46 -0
  18. package/dist/box-settings.js +107 -0
  19. package/dist/boxes.d.ts +4 -1
  20. package/dist/browser-cost.js +2 -1
  21. package/dist/browser-person.d.ts +0 -2
  22. package/dist/browser-person.js +0 -2
  23. package/dist/budget.d.ts +0 -4
  24. package/dist/budget.js +0 -7
  25. package/dist/cap.d.ts +0 -7
  26. package/dist/cap.js +0 -22
  27. package/dist/cli.js +23 -8
  28. package/dist/computers.d.ts +1 -1
  29. package/dist/console/assets/index-Dn0ngwG9.js +535 -0
  30. package/dist/console/assets/index-DvW6Aled.css +1 -0
  31. package/dist/console/index.html +2 -2
  32. package/dist/daytona-api.d.ts +0 -11
  33. package/dist/daytona-api.js +1 -82
  34. package/dist/docker-host-addresses.d.ts +37 -0
  35. package/dist/docker-host-addresses.js +110 -0
  36. package/dist/files.d.ts +0 -8
  37. package/dist/files.js +0 -17
  38. package/dist/github-connection.d.ts +1 -1
  39. package/dist/github-connection.js +1 -1
  40. package/dist/harness-install.d.ts +23 -0
  41. package/dist/harness-install.js +99 -4
  42. package/dist/harness.d.ts +4 -3
  43. package/dist/harness.js +16 -1
  44. package/dist/import.js +52 -13
  45. package/dist/learn/secrets.d.ts +2 -1
  46. package/dist/learn/secrets.js +19 -6
  47. package/dist/learned-workflow.d.ts +5 -4
  48. package/dist/learned-workflow.js +6 -3
  49. package/dist/learning-routes.d.ts +9 -46
  50. package/dist/learning-routes.js +25 -29
  51. package/dist/learning-run.d.ts +4 -231
  52. package/dist/learning-run.js +7 -651
  53. package/dist/live/translate.js +1 -1
  54. package/dist/mcp-gateway.d.ts +0 -3
  55. package/dist/mcp-gateway.js +0 -13
  56. package/dist/mcp-probe.d.ts +2 -2
  57. package/dist/mcp-probe.js +2 -2
  58. package/dist/mcp-servers-store.js +1 -1
  59. package/dist/openapi.js +3 -3
  60. package/dist/page.js +3 -1
  61. package/dist/paid-calls.js +3 -2
  62. package/dist/pause.d.ts +0 -2
  63. package/dist/pause.js +1 -8
  64. package/dist/place.d.ts +0 -5
  65. package/dist/place.js +0 -10
  66. package/dist/print.d.ts +2 -1
  67. package/dist/print.js +4 -2
  68. package/dist/run-db.d.ts +0 -2
  69. package/dist/run-db.js +0 -4
  70. package/dist/run-learning-served.d.ts +38 -0
  71. package/dist/run-learning-served.js +9 -0
  72. package/dist/run-secrets.d.ts +33 -0
  73. package/dist/run-secrets.js +53 -0
  74. package/dist/run-timeline-served.js +5 -2
  75. package/dist/run-view.d.ts +5 -9
  76. package/dist/run-view.js +4 -22
  77. package/dist/runner/adapter-loop.d.ts +8 -2
  78. package/dist/runner/adapter-loop.js +44 -12
  79. package/dist/runner/adapter-run-spec.d.ts +8 -0
  80. package/dist/runner/adapter-run-spec.js +6 -5
  81. package/dist/runner/adapters/pi.d.ts +4 -0
  82. package/dist/runner/adapters/pi.js +4 -1
  83. package/dist/runner/beside.js +19 -8
  84. package/dist/runner/claim-secrets.js +1 -1
  85. package/dist/runner/cli-run-spec.js +15 -1
  86. package/dist/runner/journal-kinds.d.ts +6 -0
  87. package/dist/runner/live-ticker.d.ts +1 -1
  88. package/dist/runner/live-ticker.js +28 -4
  89. package/dist/runner/loop-contract.d.ts +3 -2
  90. package/dist/runner/main.d.ts +11 -4
  91. package/dist/runner/main.js +39 -10
  92. package/dist/runner/mcp-claim.d.ts +1 -1
  93. package/dist/runner/mcp-claim.js +1 -1
  94. package/dist/runner/model-route.js +21 -2
  95. package/dist/runner/redact.d.ts +8 -2
  96. package/dist/runner/redact.js +11 -2
  97. package/dist/runner/workflow-spec.js +5 -9
  98. package/dist/runs-over-store.d.ts +1 -1
  99. package/dist/runs-over-store.js +16 -5
  100. package/dist/seal-key.d.ts +54 -15
  101. package/dist/seal-key.js +272 -84
  102. package/dist/sealed-settings.d.ts +2 -2
  103. package/dist/sealed-settings.js +3 -10
  104. package/dist/secrets.d.ts +2 -10
  105. package/dist/secrets.js +21 -17
  106. package/dist/server-secrets-store.js +1 -1
  107. package/dist/server-secrets.js +3 -0
  108. package/dist/server.d.ts +10 -6
  109. package/dist/server.js +89 -41
  110. package/dist/store/index.d.ts +1 -1
  111. package/dist/store/index.js +1 -1
  112. package/dist/store/open.d.ts +12 -2
  113. package/dist/store/open.js +23 -3
  114. package/dist/store/postgres/migrate.js +18 -1
  115. package/dist/store/sqlite/store.js +23 -8
  116. package/dist/store/store.d.ts +3 -0
  117. package/dist/store-reads/journal.d.ts +16 -0
  118. package/dist/store-reads/journal.js +82 -6
  119. package/dist/store-view.js +38 -5
  120. package/dist/tool-keys.d.ts +4 -3
  121. package/dist/tool-keys.js +7 -4
  122. package/dist/tools.d.ts +1 -1
  123. package/dist/tools.js +4 -1
  124. package/dist/trigger-schedule.js +2 -1
  125. package/dist/trigger-secrets-shown.js +5 -1
  126. package/dist/workspace/computer-deps.d.ts +29 -0
  127. package/dist/workspace/computer-deps.js +48 -1
  128. package/dist/workspace/computer-for-claim.d.ts +7 -3
  129. package/dist/workspace/computer-for-claim.js +1 -1
  130. package/dist/workspace/computer-providers.d.ts +6 -2
  131. package/dist/workspace/computer-providers.js +1 -1
  132. package/dist/workspace/index.d.ts +1 -1
  133. package/dist/workspace/index.js +1 -1
  134. package/dist/workspace.d.ts +0 -3
  135. package/dist/workspace.js +0 -3
  136. package/launcher/agentrun-serve +6 -33
  137. package/package.json +14 -14
  138. package/templates/inbound-lead/agent.md +1 -1
  139. package/templates/kyb/agent.md +1 -1
  140. package/dist/app.d.ts +0 -5
  141. package/dist/app.js +0 -514
  142. package/dist/bounds.d.ts +0 -26
  143. package/dist/bounds.js +0 -137
  144. package/dist/console/assets/index-35-7aeIZ.js +0 -519
  145. package/dist/console/assets/index-Cejbov-Y.css +0 -1
  146. package/dist/content-filter.d.ts +0 -7
  147. package/dist/content-filter.js +0 -23
  148. package/dist/disk.d.ts +0 -33
  149. package/dist/disk.js +0 -85
  150. package/dist/door-line.d.ts +0 -23
  151. package/dist/door-line.js +0 -83
  152. package/dist/harness-app.d.ts +0 -69
  153. package/dist/harness-app.js +0 -1162
  154. package/dist/request-start.d.ts +0 -27
  155. package/dist/request-start.js +0 -381
  156. package/dist/run-box.d.ts +0 -205
  157. package/dist/run-box.js +0 -661
  158. package/dist/run-holder.d.ts +0 -52
  159. package/dist/run-holder.js +0 -139
  160. package/dist/runs.d.ts +0 -1200
  161. package/dist/runs.js +0 -4103
  162. package/dist/served-only.d.ts +0 -5
  163. package/dist/served-only.js +0 -12
package/dist/server.d.ts CHANGED
@@ -59,6 +59,10 @@ export type ServeOptions = {
59
59
  allowCodeNodes?: boolean;
60
60
  /** A faux model module (no key, no network): see the README. */
61
61
  faux?: string;
62
+ /** The API-only profile (AGENTRUN_API_ONLY=1, api-only.ts): serve the run routes alone and refuse every other address
63
+ * (the console, sign-in, setup, settings, MCP, triggers, hooks, ...) with a 404 before anything reads the request.
64
+ * It has no owner: accounts and open setup are off, there being no page to sign in to. */
65
+ apiOnly?: boolean;
62
66
  /** With `faux` only: a module whose default export gives the `browser` tool's `{ provider, driver }` (the tests' fake
63
67
  * backend), in place of Browserbase's or Kernel's. */
64
68
  fauxBrowser?: string;
@@ -321,7 +325,7 @@ export declare function readingOf(base: NodeJS.ProcessEnv, maxRuns: number, stor
321
325
  * web tool, what it resolves to on each harness under this server's tool settings; `key`, the tool key that unlocks
322
326
  * it (tool-keys.ts), when one does. */
323
327
  tools: ({
324
- providers?: ("auto" | "native" | "off" | "parallel" | "browserbase" | "kernel" | "exa-keyless" | "chrome")[] | undefined;
328
+ providers?: ("auto" | "native" | "parallel" | "browserbase" | "kernel" | "off" | "exa-keyless" | "chrome")[] | undefined;
325
329
  provider?: string | undefined;
326
330
  default_provider?: "auto" | "kernel" | undefined;
327
331
  resolves?: Record<"opencode" | "codex" | "pi" | "claude-agent", import("./tool-plane.js").Resolution> | undefined;
@@ -342,7 +346,7 @@ export declare function readingOf(base: NodeJS.ProcessEnv, maxRuns: number, stor
342
346
  summary: string;
343
347
  } | {
344
348
  key: string | undefined;
345
- providers?: ("auto" | "native" | "off" | "parallel" | "browserbase" | "kernel" | "exa-keyless" | "chrome")[] | undefined;
349
+ providers?: ("auto" | "native" | "parallel" | "browserbase" | "kernel" | "off" | "exa-keyless" | "chrome")[] | undefined;
346
350
  provider?: string | undefined;
347
351
  default_provider?: "auto" | "kernel" | undefined;
348
352
  resolves?: Record<"opencode" | "codex" | "pi" | "claude-agent", import("./tool-plane.js").Resolution> | undefined;
@@ -476,7 +480,7 @@ export declare function readingOf(base: NodeJS.ProcessEnv, maxRuns: number, stor
476
480
  harnesses: string[];
477
481
  };
478
482
  /** This server's learning switch (`--learning`): on, a run learns when its agent says `learning: true`; off, none does. */
479
- learning: "off" | "on";
483
+ learning: "on" | "off";
480
484
  /** /settings/webhook: one URL POSTed, signed by the Standard Webhooks spec, when a run needs its person and when it
481
485
  * ends (webhooks.ts); its secret kept sealed under the same seal key, so with none no webhook is set. */
482
486
  webhooks: {
@@ -579,7 +583,7 @@ export declare function capabilities(env?: NodeJS.ProcessEnv, maxRuns?: number,
579
583
  * web tool, what it resolves to on each harness under this server's tool settings; `key`, the tool key that unlocks
580
584
  * it (tool-keys.ts), when one does. */
581
585
  tools: ({
582
- providers?: ("auto" | "native" | "off" | "parallel" | "browserbase" | "kernel" | "exa-keyless" | "chrome")[] | undefined;
586
+ providers?: ("auto" | "native" | "parallel" | "browserbase" | "kernel" | "off" | "exa-keyless" | "chrome")[] | undefined;
583
587
  provider?: string | undefined;
584
588
  default_provider?: "auto" | "kernel" | undefined;
585
589
  resolves?: Record<"opencode" | "codex" | "pi" | "claude-agent", import("./tool-plane.js").Resolution> | undefined;
@@ -600,7 +604,7 @@ export declare function capabilities(env?: NodeJS.ProcessEnv, maxRuns?: number,
600
604
  summary: string;
601
605
  } | {
602
606
  key: string | undefined;
603
- providers?: ("auto" | "native" | "off" | "parallel" | "browserbase" | "kernel" | "exa-keyless" | "chrome")[] | undefined;
607
+ providers?: ("auto" | "native" | "parallel" | "browserbase" | "kernel" | "off" | "exa-keyless" | "chrome")[] | undefined;
604
608
  provider?: string | undefined;
605
609
  default_provider?: "auto" | "kernel" | undefined;
606
610
  resolves?: Record<"opencode" | "codex" | "pi" | "claude-agent", import("./tool-plane.js").Resolution> | undefined;
@@ -734,7 +738,7 @@ export declare function capabilities(env?: NodeJS.ProcessEnv, maxRuns?: number,
734
738
  harnesses: string[];
735
739
  };
736
740
  /** This server's learning switch (`--learning`): on, a run learns when its agent says `learning: true`; off, none does. */
737
- learning: "off" | "on";
741
+ learning: "on" | "off";
738
742
  /** /settings/webhook: one URL POSTed, signed by the Standard Webhooks spec, when a run needs its person and when it
739
743
  * ends (webhooks.ts); its secret kept sealed under the same seal key, so with none no webhook is set. */
740
744
  webhooks: {
package/dist/server.js CHANGED
@@ -4,6 +4,7 @@ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
4
4
  import { chmod, lstat, mkdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises";
5
5
  import { createServer } from "node:http";
6
6
  import proxyaddr from "proxy-addr";
7
+ import { apiOnlyRefusal, servedApiOnly } from "./api-only.js";
7
8
  import { dirname, join, relative, resolve, sep } from "node:path";
8
9
  import { pathToFileURL } from "node:url";
9
10
  import { Worker } from "node:worker_threads";
@@ -12,7 +13,7 @@ import { existsSync } from "node:fs";
12
13
  import { rm } from "node:fs/promises";
13
14
  import { homedir } from "node:os";
14
15
  import { agentRevision, agentRevisions, agentView, commitAgent, createAgent, etagOf, getAgent, listAgents, makeRevision, refuseExternal, revisionView, setAgentArchived, setCurrentRevision } from "./agents-store.js";
15
- import { WORKFLOW_ADAPTERS } from "./app.js";
16
+ import { WORKFLOW_ADAPTERS } from "./runner/workflow-adapters.js";
16
17
  import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_PARALLEL_ENV, fauxFetch } from "./decisions.js";
17
18
  import { FAUX_WEB_ENV } from "./web-fetch-direct.js";
18
19
  import { FAUX_MONID_ENV } from "./monid.js";
@@ -35,7 +36,7 @@ import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, read
35
36
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
36
37
  import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
37
38
  import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf } from "./place.js";
38
- import { BOX_ALLOW_ENV, boxAllowOf, boxLimitsOf, boxNetworkOf, FAUX_BOX_ENV, fauxBoxes } from "./run-box.js";
39
+ import { BOX_ALLOW_ENV, boxAllowOf, boxLimitsOf, boxNetworkOf, FAUX_BOX_ENV, fauxBoxes, memoryMbOf } from "./box-settings.js";
39
40
  import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
40
41
  import { answerPage, byOwnerSession, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
41
42
  import { hostFix, hostName, loopbackNames } from "./host-check.js";
@@ -47,7 +48,7 @@ import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, raise
47
48
  import { momentOverStore, summaryOverStore, timelineOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
48
49
  import { HELD_WAITS } from "./runner/journal-kinds.js";
49
50
  import { servedTimelineRows } from "./run-timeline-served.js";
50
- import { servedRunLearning } from "./run-learning-served.js";
51
+ import { servedRunDiff, servedRunLearning } from "./run-learning-served.js";
51
52
  import { runCutValues } from "./run-cut.js";
52
53
  import { readLaunchBody } from "./run-launch.js";
53
54
  import { listRunFiles as listRunFilesOverStore, readRunFile as readRunFileOverStore, runGraphView, runTimelines } from "./run-reads-over-store.js";
@@ -72,16 +73,16 @@ import { runLines } from "./usage-lines.js";
72
73
  import { boxesByDefault, boxesLog, boxRegistry, enabledBoxes, VM_NO_LIST, VM_PROVIDER } from "./boxes.js";
73
74
  import { egressParentTooLong, FAUX_EGRESS_ENV, MAX_EGRESS_PARENT, sweepEgressDirs } from "./box-egress.js";
74
75
  import { startEgressContainer } from "./box-egress-vm.js";
75
- import { dockerPathsOf, egressParentOf, FAUX_MOUNTINFO_ENV } from "./box-paths.js";
76
+ import { dockerComputerRefusal, dockerPathsOf, egressParentOf, FAUX_MOUNTINFO_ENV, remoteDockerOnce } from "./box-paths.js";
77
+ import { hostAddressesOnce, noHostAddresses, unionOf } from "./docker-host-addresses.js";
76
78
  import { boxImageOf, clearImage, dockerImage, withImage } from "./box-image.js";
77
79
  import { vmRelay } from "./box-relay-vm.js";
78
- import { memoryMbOf } from "./run-box.js";
79
80
  import { DOCUMENTS_ENV } from "./pdf-pages.js";
80
81
  import { CAP_MODES } from "./cap.js";
81
82
  import { blockersOf, CODE_NODES_ENV, issueOf, MCP_HARNESSES, NOT_SET_UP } from "./runnable.js";
82
83
  import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
83
84
  import { isSecretWriteOperation, SECRET_WRITE_REFUSAL, secretsWritableFields, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
84
- import { bootSealKey } from "./seal-key.js";
85
+ import { bootSealKey, withSealKey } from "./seal-key.js";
85
86
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
86
87
  import { agentLearningOverStore, learningCountsOverStore } from "./store-reads/learning.js";
87
88
  import { outcomes } from "./usage.js";
@@ -126,7 +127,7 @@ import { computerCapabilities, createComputerRoutes, folderModeOf, settingsCompu
126
127
  import { FAUX_VIEW_PATH, fauxComputers } from "./faux-computers.js";
127
128
  import { runComputerField } from "./run-computer.js";
128
129
  import { writesHeld } from "./workspace.js";
129
- import { agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, isWorkspaceError, localWorkspace, serverRunWorkspace, storeLedger } from "./workspace/index.js";
130
+ import { agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, serverRunWorkspace, storeLedger } from "./workspace/index.js";
130
131
  import { keyReader } from "./key-meta.js";
131
132
  // server-lock.ts is gone: the store's EXCLUSIVE connection is the one-server lock (StoreOwned refuses a second server).
132
133
  export const CONTRACT = "agentrun.v2/0";
@@ -164,7 +165,7 @@ const HOME_WRITES_OFF = "This server can't write a home's files safely here: a w
164
165
  const LINK_REFUSED = "A link is on the way to this path, or is the file: this server follows none.";
165
166
  /** Each test switch a run's process reads, by the variable it reads it from: set only under `faux`, but the faux
166
167
  * harness's, which scripts the harnesses with or without it. */
167
- 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], ["fauxBox", FAUX_BOX_ENV], ["fauxEgress", FAUX_EGRESS_ENV]];
168
+ 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], ["fauxBox", FAUX_BOX_ENV], ["fauxEgress", FAUX_EGRESS_ENV], ["fauxMountinfo", FAUX_MOUNTINFO_ENV]];
168
169
  /** The test switches a run's process gets, each module path resolved: empty outside tests. A test's in-process runner
169
170
  * takes the same (test/support.mjs startInProcessRunner). */
170
171
  export function fauxEnvOf(options) {
@@ -490,7 +491,7 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
490
491
  learning,
491
492
  /** /settings/webhook: one URL POSTed, signed by the Standard Webhooks spec, when a run needs its person and when it
492
493
  * ends (webhooks.ts); its secret kept sealed under the same seal key, so with none no webhook is set. */
493
- // Always sealed: the server starts with its seal key (seal-key.ts ensureSealKey), so nothing is kept in the clear.
494
+ // Always sealed: the server starts with its seal key (seal-key.ts bootSealKey), so nothing is kept in the clear.
494
495
  webhooks: { routes: true, events: [...WEBHOOK_EVENTS], signing: "standard-webhooks/v1", at_rest: "sealed" },
495
496
  /** /triggers: what starts an agent's capped runs with no caller (triggers.ts). */
496
497
  triggers: { routes: true, sources: [...SOURCE_KINDS], targets: [...TARGET_KINDS], min_every_s: MIN_EVERY_S, history_kept: HISTORY_KEPT, catchup_window_s: CATCHUP_WINDOW_S, failures_to_pause: FAILURES_TO_PAUSE, webhook: { signing: "standard-webhooks/v1", signatures: [...SCHEME_NAMES], tolerance_s: HOOK_TOLERANCE_S, max_body_bytes: webhook.push.maxBodyBytes, payload_kept_bytes: PAYLOAD_KEPT_BYTES, at_rest: "sealed" } },
@@ -540,12 +541,12 @@ function integerParam(value, name, max) {
540
541
  // A data directory an earlier version wrote (old agent homes, an old runs/ layout, or an earlier store version) is refused
541
542
  // by the store itself when it opens (StoreFromEarlierVersion), in words, to start fresh: no pre-open scan, no migration.
542
543
  export async function startServe(options) {
544
+ // API-only: no console, so no owner to sign in to it (and no setup code printed for a page that is refused).
545
+ if (options.apiOnly)
546
+ options = { ...options, accounts: false, openSetup: false };
543
547
  // A harness table module is the server's to name, from `harnessTable` alone, for itself and its runs: one in its own
544
548
  // environment (an operator's export, a leftover) never loads, wherever the server reads its environment.
545
549
  delete process.env[HARNESS_TABLE_ENV];
546
- // No start without a seal key (seal-key.ts): the one handed over, else the one kept under the config home, made at the
547
- // first start with only its path printed. Every secret here is kept under it; there is no keeping one in the clear.
548
- const seal = bootSealKey();
549
550
  await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
550
551
  // Canonical once, here: a box's mount source below it must then be its own canonical path, through no link (run-box.ts).
551
552
  const data = await realpath(resolve(options.data));
@@ -555,6 +556,8 @@ export async function startServe(options) {
555
556
  throw new Error(`the drain timeout ${options.drainTimeout} is not a duration such as 8s`);
556
557
  enabledBoxes(process.env);
557
558
  boxLimitsOf(process.env);
559
+ // The Docker host's addresses an operator names (workspace/computer-deps.ts): a bad entry stops the start, in words.
560
+ dockerHostAddressesOf(process.env);
558
561
  const boxAllow = boxAllowOf(process.env);
559
562
  const maxRuns = maxRunsOf(process.env, options.maxRuns);
560
563
  const learning = learningOf(process.env, options.learning);
@@ -572,7 +575,7 @@ export async function startServe(options) {
572
575
  // store handle it opened.
573
576
  const stops = [];
574
577
  try {
575
- return await startHolding(options, data, { maxRuns, minFreeBytes, learning, learningBudget, boxAllow, templates, sealKey: seal.key }, stops);
578
+ return await startHolding(options, data, { maxRuns, minFreeBytes, learning, learningBudget, boxAllow, templates }, stops);
576
579
  }
577
580
  catch (error) {
578
581
  for (const stop of stops)
@@ -619,9 +622,18 @@ async function startHolding(options, data, checked, stops) {
619
622
  // On Postgres when this process's AGENTRUN_STORE_URL secret names one (store/open.ts), its owner lock the one-server lock.
620
623
  const store = await openStore({ dataDir: data, role: "server" });
621
624
  stops.push(() => store.close());
625
+ // No start without a seal key (seal-key.ts), checked against the store before anything reads it: the one handed over,
626
+ // else the one in the data directory beside the store, made at the first start with only its path printed. A store whose
627
+ // secrets another key sealed is refused, in words, and no key is made over them. Every secret here is kept under it;
628
+ // there is no keeping one in the clear.
629
+ const seal = await bootSealKey(store, data);
630
+ stops.push(async () => seal.release());
631
+ // This server's own key on every environment it reads its secrets from, so a reader opens what this store holds with the
632
+ // key checked against it, never another data directory's that this process booted too (secrets.ts holds one made key).
633
+ const own = (env) => withSealKey(env, seal.text);
622
634
  // Which fields are the server's is read from what it is started with alone: handed the saved keys too, ToolKeys would
623
635
  // call each the server's, and none could be deleted. The keys are sealed rows in the store; load() reads them once here.
624
- const toolKeys = toolKeysOverStore(store, withSecrets(base, "own"), (fields) => (log ? log(logLine("tool_keys", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("tool_keys", fields)}\n`)));
636
+ const toolKeys = toolKeysOverStore(store, own(withSecrets(base, "own")), (fields) => (log ? log(logLine("tool_keys", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("tool_keys", fields)}\n`)));
625
637
  await toolKeys.load();
626
638
  // A key's check as it is saved (key-check.ts) goes to its provider; under faux only to the tests' fake for that provider,
627
639
  // the one its runs are given (monid, Parallel, TypeSafe's Jev), never to the network: one with no fake is not checked.
@@ -638,7 +650,7 @@ async function startHolding(options, data, checked, stops) {
638
650
  const storedKeys = (name) => toolKeys.value(name);
639
651
  // A stored key that does not open is said once at the start, never a refusal to start.
640
652
  toolKeys.view();
641
- const mcpServers = mcpServersOverStore(store, withSecrets(base, "own"), VERSION);
653
+ const mcpServers = mcpServersOverStore(store, own(withSecrets(base, "own")), VERSION);
642
654
  if (options.githubMcpOrigin)
643
655
  mcpServers.appOrigin = options.githubMcpOrigin;
644
656
  // The saved MCP servers' metadata (their addresses and the tools they list), a snapshot the run-grant checks read in
@@ -675,7 +687,7 @@ async function startHolding(options, data, checked, stops) {
675
687
  // settings, caps; a save or delete of a key, env and caps, and the offers only when what they are made from changed,
676
688
  // which no tool key is. So a write answers at once, and capabilities, save checks and run checks after it see it, with
677
689
  // no restart and no request opening the file. The offers are probed once saved keys are read (below), at the start.
678
- let env = withSecrets(base, "all", storedKeys);
690
+ let env = own(withSecrets(base, "all", storedKeys));
679
691
  let offers;
680
692
  let caps;
681
693
  // Whether a revision that names no model runs (needsOf): made from env alone, so remade with it, before the caps.
@@ -706,7 +718,7 @@ async function startHolding(options, data, checked, stops) {
706
718
  const keysChanged = async () => {
707
719
  // A run's learning, view, list and timeline row are cut of the keys saved now by the run view at read time (it reads
708
720
  // serverSecrets live, store-view), so a key change needs no cache invalidation here.
709
- env = withSecrets(base, "all", storedKeys);
721
+ env = own(withSecrets(base, "all", storedKeys));
710
722
  const mine = ++needsAsked;
711
723
  const next = await needsOf(env);
712
724
  if (mine === needsAsked)
@@ -726,7 +738,7 @@ async function startHolding(options, data, checked, stops) {
726
738
  // is preparing until it is in, and unavailable if the pull fails. Its record tells the run's processes; with no Docker
727
739
  // box here there is none, so no run waits on one an earlier start left.
728
740
  let image;
729
- // What a Docker box's programs reach, resolved once here (run-box.ts boxNetworkOf): the setting's list, on a Docker
741
+ // What a Docker box's programs reach, resolved once here (box-settings.ts boxNetworkOf): the setting's list, on a Docker
730
742
  // daemon of this Linux machine's own; else none, and why. A run's process gets the list or none (RUN_BOX_ALLOW_ENV).
731
743
  // Under --faux, the mountinfo a test gives (fauxMountinfo, or FAUX_MOUNTINFO_ENV in the process's own environment, which
732
744
  // `env` leaves out: a server under test in a container names its own /proc/self/mountinfo there); with none, a faux
@@ -751,15 +763,30 @@ async function startHolding(options, data, checked, stops) {
751
763
  // On a Mac whose Docker runs in a VM this server knows, the list is served by one proxy container inside that VM
752
764
  // (box-egress-vm.ts): a box's network is the list once it is ready, and none, saying why, until then or when it can't start.
753
765
  let egress;
766
+ // A run's Docker computer mounts the run's folder, and the computer's daemon, by this server's paths: as they are on
767
+ // its Docker's own host, or as its named data volume's subpaths from a container of that Docker's (compose.yaml).
768
+ // Any other layout, or a daemon of another machine (DOCKER_HOST, or the current context's endpoint: box-paths.ts
769
+ // remoteDockerOnce), can't run one, and says so here (dockerComputerRefusal), where capabilities, the run's start
770
+ // (dockerAnswers) and a place's box check all read it: no run starts only to fail at its create.
771
+ const dockerElsewhere = fauxBox || !boxes.provider("docker") ? undefined : dockerComputerRefusal(dockerPaths, await remoteDockerOnce(env));
772
+ // From a container, a Docker computer keeps this server's allow-list only knowing the Docker host's own addresses: the
773
+ // union of the read through the socket and AGENTRUN_DOCKER_HOST_ADDRESSES (docker-host-addresses.ts), the same read the
774
+ // runner beside this server takes. Said at the start with what was found; with none, Docker isn't offered, in words.
775
+ const hostAddresses = dockerElsewhere === undefined && boxPaths && boxAllow !== "none" ? unionOf(await hostAddressesOnce(env), dockerHostAddressesOf(env)) : undefined;
776
+ if (hostAddresses)
777
+ log?.(logLine("docker_host_addresses", { addresses: hostAddresses.addresses.join(",") || "none", ...(hostAddresses.why ? { read: hostAddresses.why } : {}) }));
778
+ const dockerRefused = dockerElsewhere ?? (hostAddresses && hostAddresses.addresses.length === 0 ? noHostAddresses(hostAddresses.why ?? "the read through Docker's socket found none") : undefined);
779
+ // The addresses found, where an operator looks: capabilities' Docker entry.
780
+ const hostShown = hostAddresses && hostAddresses.addresses.length > 0 ? { host_addresses: hostAddresses.addresses } : {};
754
781
  const dockerNetwork = (offer) => {
755
782
  if (!offer.available)
756
783
  return offer;
757
- if ("reason" in dockerPaths)
758
- return { id: offer.id, available: false, state: "unavailable", reason: dockerPaths.reason };
784
+ if (dockerRefused !== undefined)
785
+ return { id: offer.id, available: false, state: "unavailable", reason: dockerRefused };
759
786
  if (boxNetwork.allow === "none")
760
787
  return { ...offer, network: "none", network_reason: boxNetwork.reason };
761
788
  const proxy = egress?.state();
762
- return proxy && proxy.state !== "ready" ? { ...offer, network: "none", network_reason: proxy.reason } : { ...offer, network: "allowlist" };
789
+ return proxy && proxy.state !== "ready" ? { ...offer, network: "none", network_reason: proxy.reason } : { ...offer, network: "allowlist", ...hostShown };
763
790
  };
764
791
  // A Daytona box reaches the hosts AGENTRUN_BOX_ALLOW names, through Daytona's domain list, until Daytona cannot keep
765
792
  // one here (an organization whose tier takes none): from then on each is made with no network, and capabilities say why.
@@ -837,7 +864,7 @@ async function startHolding(options, data, checked, stops) {
837
864
  imageLog(image.state());
838
865
  const adapters = options.triggerAdapters ?? TRIGGER_ADAPTERS;
839
866
  const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability, adapters);
840
- const sealKey = sealKeyOf(withSecrets(base, "own")[SEAL_KEY_ENV]);
867
+ const sealKey = seal.key;
841
868
  // Settings → Computers and the owner's Archil settings, over the one store (computers.ts, archil-routes.ts), built once
842
869
  // at the first request, when the server's own address is known (--faux's desktop view is a page on it). The real kind
843
870
  // registry and each provider's create() are the computer package's (kinds.ts, providers.ts providerFor); under --faux,
@@ -851,7 +878,7 @@ async function startHolding(options, data, checked, stops) {
851
878
  const fauxOf = () => (faux ??= fauxComputers({ viewerBase: ownOriginOf() }));
852
879
  let computerRoutes;
853
880
  const computersOf = () => (computerRoutes ??= createComputerRoutes({
854
- store, sealKey: checked.sealKey, tools: kindTools, mode: folderModeOf(store), env: process.env,
881
+ store, sealKey, tools: kindTools, mode: folderModeOf(store), env: process.env,
855
882
  ...(options.faux
856
883
  ? { kinds: fauxOf().kinds, factories: fauxOf().factories, keyTable: fauxOf().keyTable }
857
884
  : {
@@ -871,8 +898,8 @@ async function startHolding(options, data, checked, stops) {
871
898
  const box = boxAvailability(boxOffers).find((one) => one.id === provider);
872
899
  return box?.available ? true : box?.reason ?? `${provider} is not a box this server has`;
873
900
  };
874
- const computerReady = async (setting) => computerReadiness(setting, (await folderModeOf(store)()) === "disk" ? 2 : 1, claimKinds({}), keyReader(store, checked.sealKey, withSecrets(process.env, "own")), dockerAnswers);
875
- const archil = createArchilRoutes({ store, sealKey: checked.sealKey, env: process.env });
901
+ const computerReady = async (setting) => computerReadiness(setting, (await folderModeOf(store)()) === "disk" ? 2 : 1, claimKinds({}), keyReader(store, sealKey, own(withSecrets(process.env, "own"))), dockerAnswers);
902
+ const archil = createArchilRoutes({ store, sealKey, env: process.env });
876
903
  /** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
877
904
  const runComputerOf = async (runId, view) => {
878
905
  const run = await store.runs.get(runId);
@@ -1007,7 +1034,7 @@ async function startHolding(options, data, checked, stops) {
1007
1034
  // console, the secrets are cut live, and the sign-ins give the handed-pointer cut. Trigger and background reads (no
1008
1035
  // request) use the server's public address, else its own.
1009
1036
  // The run's key read from this server's environment with the keys a person saved, as its Timeline reads it (keyEnv below).
1010
- const viewDepsFor = (origin) => ({ origin, serverSecrets, signIns, keyEnv: () => withSecrets(process.env, "all", storedKeys) });
1037
+ const viewDepsFor = (origin) => ({ origin, serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)) });
1011
1038
  const ownOriginOf = () => options.publicUrl ?? url;
1012
1039
  // The run read routes (a run's files, its browser state, its workflow graph) over the one store (run-reads-over-store):
1013
1040
  // a run's files through the server's read-only Workspace of its folder (serverRunWorkspace, no runner claim), its view
@@ -1022,7 +1049,7 @@ async function startHolding(options, data, checked, stops) {
1022
1049
  withheld: (_store, runId) => withheldOverStore(store, runId, viewDepsFor(ownOriginOf())),
1023
1050
  cutValues: (_store, runId) => runCutValues({ serverSecrets, signIns }, store, runId),
1024
1051
  context: ctx,
1025
- ...(sealKey ? { liveViewer: (runId) => liveViewerLink(store, sealKey, runId) } : {}),
1052
+ liveViewer: (runId) => liveViewerLink(store, sealKey, runId),
1026
1053
  };
1027
1054
  // The run timeline reader over the store (run-reads-over-store runTimelines): one change-numbered RowLog per run, synced
1028
1055
  // from its journal (store-reads) on each read, its view (viewOverStore) for status/state/cost and whether it is final.
@@ -1034,7 +1061,7 @@ async function startHolding(options, data, checked, stops) {
1034
1061
  // shows and each browser sign-in pointer the run was handed; its decision rows among them, its error rows in the
1035
1062
  // error's words. A run whose hand can't be read back here is withheld: none of its rows. A run's Timeline is read
1036
1063
  // from its journal, which keeps what the run said whole.
1037
- timelineRows: (forStore, runId, context) => servedTimelineRows({ serverSecrets, signIns, keyEnv: () => withSecrets(process.env, "all", storedKeys) }, forStore, runId, context),
1064
+ timelineRows: (forStore, runId, context) => servedTimelineRows({ serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)) }, forStore, runId, context),
1038
1065
  runView: (forStore, runId) => viewOverStore(forStore, runId, viewDepsFor(ownOriginOf())),
1039
1066
  });
1040
1067
  const triggerDeps = {
@@ -1075,6 +1102,19 @@ async function startHolding(options, data, checked, stops) {
1075
1102
  }
1076
1103
  })();
1077
1104
  const clientOf = (req) => (trusted ? proxyaddr(req, trusted) : req.socket.remoteAddress) ?? "unknown";
1105
+ // The owner's own sign-in (the right password) that came with X-Forwarded-For from an address not trusted as a proxy is
1106
+ // said once a start, with that address (`event=forwarded_untrusted peer=<it>`): behind a proxy that publishes no
1107
+ // address (Render's), the proxy that carried the owner's request, the one to name in AGENTRUN_TRUSTED_PROXIES. Only a
1108
+ // right password says it, so a peer that can reach the server without the password can't put its own address there;
1109
+ // once, so the log says it one time.
1110
+ let forwardedSaid = false;
1111
+ const sayForwarded = (req) => {
1112
+ const peer = req.socket.remoteAddress ?? "unknown";
1113
+ if (forwardedSaid || req.headers["x-forwarded-for"] === undefined || (trusted?.(peer, 0) ?? false))
1114
+ return;
1115
+ forwardedSaid = true;
1116
+ log?.(logLine("forwarded_untrusted", { peer }));
1117
+ };
1078
1118
  /** Whether `req` may be shown a secret this server mints (trigger-secrets-shown.ts): the caller that may write one. */
1079
1119
  const mayHoldSecrets = (req) => writesSecretsAllowed(req, { accounts: owner !== undefined, loopbackBound: isLoopback(host) });
1080
1120
  /** A trigger's view with its minted secret's metadata, never the secret (trigger-secrets-shown.ts). */
@@ -1156,7 +1196,7 @@ async function startHolding(options, data, checked, stops) {
1156
1196
  // worker's memory alone: what the import cuts out of everything it writes. The keys saved on the Tool keys page are
1157
1197
  // not passed; the worker reads them from the store over the port (sealed rows it opens with the seal key among these
1158
1198
  // secrets), the same cut as the CLI's import, where a saved key and the server's own of the same name may differ.
1159
- workerData: { task, data, home: options.sessionsHome?.home ?? homedir(), ...(options.sessionsHome?.temp ? { temp: options.sessionsHome.temp } : {}), secrets: Object.fromEntries(SECRET_NAMES.flatMap((name) => { const value = secret(name); return value === undefined ? [] : [[name, value]]; })) },
1199
+ 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]]; })) },
1160
1200
  // Started from a string (its launcher runs node --input-type=module -e), the server's flags are given again
1161
1201
  // without that string and its type: a worker started from a file with them is refused. Otherwise the worker
1162
1202
  // inherits them as Node passes them on, which leaves out the flags a worker may not take (on Node 24 a test
@@ -2076,6 +2116,7 @@ async function startHolding(options, data, checked, stops) {
2076
2116
  authFailed("/v2/auth/sign-in", "wrong_password");
2077
2117
  throw new ApiError("unauthenticated", "that is not the password");
2078
2118
  }
2119
+ sayForwarded(req);
2079
2120
  return send(res, 200, { signed_in: true }, { "set-cookie": ownerCookie(req, me.session(), SESSION_S) });
2080
2121
  }
2081
2122
  // This browser: its session revoked on the server (a copy of its cookie is no session either) and its cookie
@@ -2497,8 +2538,6 @@ async function startHolding(options, data, checked, stops) {
2497
2538
  const kept = await keptBrowserOf(store, run.id);
2498
2539
  const view = await computerView({
2499
2540
  viewer: async () => {
2500
- if (sealKey === undefined)
2501
- return undefined;
2502
2541
  if (family === "browser") {
2503
2542
  const link = await liveViewerLink(store, sealKey, run.id);
2504
2543
  return link === undefined ? undefined : { kind: "browser", viewer: link.viewer };
@@ -2851,11 +2890,13 @@ async function startHolding(options, data, checked, stops) {
2851
2890
  // Cut by the run's one cut, and refused for a withheld run (run-learning-served.ts).
2852
2891
  return send(res, 200, await servedRunLearning({ serverSecrets, signIns }, store, run.id));
2853
2892
  }
2854
- case "getRunLearningDiff":
2855
- await needRun(id);
2856
- // TODO(learning-1): the run's learning diff over the store — learning-1's diff read on untangle/cutover-switch-learn, not the run's
2857
- // .learning/diffs files. Wire when its head lands.
2858
- return runReadsTodo();
2893
+ case "getRunLearningDiff": {
2894
+ const run = await needRun(id);
2895
+ // The run's learning diff over the store (learning-routes.ts runDiffOverStore): its merge from its agent's learning
2896
+ // folder, else its kept proposal's notes against its seed, else no file against the seed its launch names. Cut by the
2897
+ // run's one cut, and refused for a withheld run, as its learning is (run-learning-served.ts).
2898
+ return send(res, 200, await servedRunDiff({ serverSecrets, signIns }, store, data, run.id));
2899
+ }
2859
2900
  case "getWebhook":
2860
2901
  return send(res, 200, webhooks.view());
2861
2902
  case "saveWebhook": {
@@ -2952,10 +2993,9 @@ async function startHolding(options, data, checked, stops) {
2952
2993
  }
2953
2994
  await needRun(runId);
2954
2995
  // The run's live viewer from the store (the runner's browser/computer tool wrote it under its claim; liveViewerFor picks
2955
- // a named viewer's handover or the run's open one). None for a run no runner holds; with no seal key this server serves
2956
- // no live view. A /computer/live path reaches a viewer of every kind (the link GET /computer gives, a browser's among
2996
+ // a named viewer's handover or the run's open one). None for a run no runner holds. A /computer/live path reaches a viewer of every kind (the link GET /computer gives, a browser's among
2957
2997
  // them), a /browser/live path a browser's alone (familyReaches).
2958
- const handover = sealKey ? await liveViewerFor(store, sealKey, runId, rest) : undefined;
2998
+ const handover = await liveViewerFor(store, sealKey, runId, rest);
2959
2999
  if (handover === undefined || !familyReaches(family, handover))
2960
3000
  throw new ApiError("not_found", `this run's ${family} has no live view at that address`);
2961
3001
  await serveViewerFile(req, res, rest);
@@ -3007,6 +3047,10 @@ async function startHolding(options, data, checked, stops) {
3007
3047
  }
3008
3048
  // Routed on the path as sent: a parsed URL folds `..` and `%2E%2E` segments away, and a file path must see them.
3009
3049
  const raw = (req.url ?? "/").split("?")[0];
3050
+ // API-only (api-only.ts): any address but the run routes is refused here, before the page, the owner's routes, the
3051
+ // MCP endpoint, the token-less hooks or the token check read anything of the request.
3052
+ if (options.apiOnly && !servedApiOnly(ROUTES, req.method, raw))
3053
+ return fail(new ApiError("not_found", apiOnlyRefusal(raw)));
3010
3054
  // Before the page: its cookie must not stand in for the token on the owner's own routes, nor on the MCP endpoint.
3011
3055
  if (owner && (raw === "/v2/setup" || raw === "/v2/setup/import" || raw.startsWith("/v2/auth/")))
3012
3056
  return void ownerRoute(req, res, raw.slice(3), owner).catch(fail);
@@ -3049,6 +3093,9 @@ async function startHolding(options, data, checked, stops) {
3049
3093
  // away. Its name alone, on any port, as the HTTP routes check it.
3050
3094
  if (names && !names.has(hostName(req.headers.host) ?? ""))
3051
3095
  return deny("403 Forbidden");
3096
+ // API-only: a run's live view is the console's, and refused with it.
3097
+ if (options.apiOnly)
3098
+ return deny("404 Not Found");
3052
3099
  if (!viewing || !ID.test(viewing[1]) || !/^\/v\/[A-Za-z0-9_-]{22}\/ws$/.test(viewing[3]))
3053
3100
  return deny("404 Not Found");
3054
3101
  // A browser always sends its page's origin on a WebSocket, which no other page's script can forge: this server's own
@@ -3064,9 +3111,9 @@ async function startHolding(options, data, checked, stops) {
3064
3111
  void (async () => {
3065
3112
  const run = ID.test(viewing[1]) ? await momentOverStore(store, viewing[1], viewDepsFor(ownOriginOf())) : undefined;
3066
3113
  // The run's live viewer from the store (the runner's browser/computer tool wrote it under its claim): none for a run no
3067
- // runner holds; with no seal key no live view is served. A /computer/live socket reaches a viewer of every kind, a
3114
+ // runner holds. A /computer/live socket reaches a viewer of every kind, a
3068
3115
  // /browser/live socket a browser's alone (familyReaches), as the page does.
3069
- const viewerHandover = run && sealKey ? await liveViewerById(store, sealKey, run.id, viewing[3].slice(3, -3)) : undefined;
3116
+ const viewerHandover = run ? await liveViewerById(store, sealKey, run.id, viewing[3].slice(3, -3)) : undefined;
3070
3117
  const handover = viewerHandover !== undefined && familyReaches(viewing[2], viewerHandover) ? viewerHandover : undefined;
3071
3118
  if (!handover)
3072
3119
  return deny("404 Not Found");
@@ -3268,6 +3315,7 @@ async function startHolding(options, data, checked, stops) {
3268
3315
  await githubStopped;
3269
3316
  // The store's EXCLUSIVE lock is the one-server lock: closing it releases it for the next server.
3270
3317
  await store.close();
3318
+ seal.release();
3271
3319
  }
3272
3320
  return {
3273
3321
  url,
@@ -9,7 +9,7 @@ export { claimFence, type FenceVariant } from "./fence.js";
9
9
  export { DEFAULT_LEASE_MS, openSqliteStore, type SqliteStoreOptions, storeOver } from "./sqlite/store.js";
10
10
  export { Connection, DEFAULT_TRANSACTION_DEADLINE_MS, type SqliteDatabase, type SqliteExecutor, type SqliteValue, type StoreConnection, type TransactionOptions, type Tx } from "./sqlite/connection.js";
11
11
  export { cleanText, type Dialect, SQLITE } from "./dialect.js";
12
- export { openStore, type OpenStoreOptions, storePlace, storeTarget, type StoreTarget } from "./open.js";
12
+ export { DEFAULT_STORE_POOL_SIZE, MAX_STORE_POOL_SIZE, openStore, type OpenStoreOptions, storePlace, storePoolSize, storeTarget, type StoreTarget } from "./open.js";
13
13
  export { CLOCK_WARN_MS, DEFAULT_SCHEMA, openPostgresStore, type PostgresStoreOptions, postgresWhere } from "./postgres/store.js";
14
14
  export { LEASE_DEADLINE_MS, PgConnection, SCHEMA_NAME, STORE_CONNECT_TIMEOUT_MS, Unanswered } from "./postgres/connection.js";
15
15
  export { dropPostgresSchema, migrate, migrationsIn, versionOf as postgresVersionOf } from "./postgres/migrate.js";
@@ -9,7 +9,7 @@ export { claimFence } from "./fence.js";
9
9
  export { DEFAULT_LEASE_MS, openSqliteStore, storeOver } from "./sqlite/store.js";
10
10
  export { Connection, DEFAULT_TRANSACTION_DEADLINE_MS } from "./sqlite/connection.js";
11
11
  export { cleanText, SQLITE } from "./dialect.js";
12
- export { openStore, storePlace, storeTarget } from "./open.js";
12
+ export { DEFAULT_STORE_POOL_SIZE, MAX_STORE_POOL_SIZE, openStore, storePlace, storePoolSize, storeTarget } from "./open.js";
13
13
  export { CLOCK_WARN_MS, DEFAULT_SCHEMA, openPostgresStore, postgresWhere } from "./postgres/store.js";
14
14
  export { LEASE_DEADLINE_MS, PgConnection, SCHEMA_NAME, STORE_CONNECT_TIMEOUT_MS, Unanswered } from "./postgres/connection.js";
15
15
  export { dropPostgresSchema, migrate, migrationsIn, versionOf as postgresVersionOf } from "./postgres/migrate.js";
@@ -12,6 +12,15 @@ export type StoreTarget = {
12
12
  * Postgres for a postgres:// or postgresql:// URL, else SQLite in `dataDir`. Any other URL is refused (never read as
13
13
  * SQLite by mistake). */
14
14
  export declare function storeTarget(dataDir: string, env?: NodeJS.ProcessEnv, url?: string | undefined): StoreTarget;
15
+ /** A Postgres pool's size when AGENTRUN_STORE_POOL_SIZE is unset or empty. */
16
+ export declare const DEFAULT_STORE_POOL_SIZE = 10;
17
+ /** The largest AGENTRUN_STORE_POOL_SIZE taken: a value past it is a typo, not a pool (Postgres allows 100 connections by
18
+ * default, for every process on it). */
19
+ export declare const MAX_STORE_POOL_SIZE = 1000;
20
+ /** The most connections this process's Postgres pool holds at once, from `env`'s AGENTRUN_STORE_POOL_SIZE: a whole number
21
+ * from 1 to MAX_STORE_POOL_SIZE, DEFAULT_STORE_POOL_SIZE when unset or empty. Anything else is refused in words (a
22
+ * TypeError), so a server or a runner never starts on a pool it was not asked for. */
23
+ export declare function storePoolSize(env?: NodeJS.ProcessEnv): number;
15
24
  /** Where `target` is, in words for a person: the store's file, or the Postgres schema (never its URL, which may carry a
16
25
  * password). */
17
26
  export declare function storePlace(target: StoreTarget): string;
@@ -25,10 +34,11 @@ export interface OpenStoreOptions {
25
34
  /** The store's URL, for a caller that holds it itself (a test, the conformance harness). By default this process's
26
35
  * AGENTRUN_STORE_URL secret (secrets.ts secret: as the launcher handed it over), never an environment's. */
27
36
  readonly url?: string;
28
- /** The environment AGENTRUN_STORE_SCHEMA is read from (process.env). The schema's name is no secret. */
37
+ /** The environment AGENTRUN_STORE_SCHEMA and AGENTRUN_STORE_POOL_SIZE are read from (process.env). Neither is a secret. */
29
38
  readonly env?: NodeJS.ProcessEnv;
30
39
  /** Told what a person should know at the open (a runner's clock far from Postgres's). */
31
40
  readonly warn?: (message: string) => void;
32
41
  }
33
- /** Opens the store `options` names (storeTarget): the server's and the runner's one way in. */
42
+ /** Opens the store `options` names (storeTarget): the server's and the runner's one way in. On Postgres its pool holds at
43
+ * most storePoolSize(env) connections; a pool size that is no size is refused on either store. */
34
44
  export declare function openStore({ dataDir, role, now, url, env, warn }: OpenStoreOptions): Promise<Store>;
@@ -16,15 +16,35 @@ export function storeTarget(dataDir, env = process.env, url = storeUrl()) {
16
16
  throw new TypeError("AGENTRUN_STORE_URL is a postgres:// or postgresql:// URL, or unset for the SQLite store in the data directory");
17
17
  return { kind: "postgres", url: named, schema: env.AGENTRUN_STORE_SCHEMA?.trim() || DEFAULT_SCHEMA };
18
18
  }
19
+ /** A Postgres pool's size when AGENTRUN_STORE_POOL_SIZE is unset or empty. */
20
+ export const DEFAULT_STORE_POOL_SIZE = 10;
21
+ /** The largest AGENTRUN_STORE_POOL_SIZE taken: a value past it is a typo, not a pool (Postgres allows 100 connections by
22
+ * default, for every process on it). */
23
+ export const MAX_STORE_POOL_SIZE = 1_000;
24
+ /** The most connections this process's Postgres pool holds at once, from `env`'s AGENTRUN_STORE_POOL_SIZE: a whole number
25
+ * from 1 to MAX_STORE_POOL_SIZE, DEFAULT_STORE_POOL_SIZE when unset or empty. Anything else is refused in words (a
26
+ * TypeError), so a server or a runner never starts on a pool it was not asked for. */
27
+ export function storePoolSize(env = process.env) {
28
+ const given = env.AGENTRUN_STORE_POOL_SIZE?.trim();
29
+ if (!given)
30
+ return DEFAULT_STORE_POOL_SIZE;
31
+ const size = /^[0-9]+$/.test(given) ? Number(given) : Number.NaN;
32
+ if (!Number.isSafeInteger(size) || size < 1 || size > MAX_STORE_POOL_SIZE) {
33
+ throw new TypeError(`AGENTRUN_STORE_POOL_SIZE is a whole number from 1 to ${MAX_STORE_POOL_SIZE} (the most connections this process's Postgres store holds at once), or unset for ${DEFAULT_STORE_POOL_SIZE}, not ${JSON.stringify(given)}`);
34
+ }
35
+ return size;
36
+ }
19
37
  /** Where `target` is, in words for a person: the store's file, or the Postgres schema (never its URL, which may carry a
20
38
  * password). */
21
39
  export function storePlace(target) {
22
40
  return target.kind === "sqlite" ? join(target.dataDir, STORE_FILE) : `the Postgres schema ${target.schema}`;
23
41
  }
24
- /** Opens the store `options` names (storeTarget): the server's and the runner's one way in. */
25
- export function openStore({ dataDir, role = "server", now, url, env = process.env, warn }) {
42
+ /** Opens the store `options` names (storeTarget): the server's and the runner's one way in. On Postgres its pool holds at
43
+ * most storePoolSize(env) connections; a pool size that is no size is refused on either store. */
44
+ export async function openStore({ dataDir, role = "server", now, url, env = process.env, warn }) {
26
45
  const target = storeTarget(dataDir, env, url ?? storeUrl());
46
+ const poolSize = storePoolSize(env);
27
47
  if (target.kind === "sqlite")
28
48
  return openSqliteStore({ dataDir, role, ...(now ? { now } : {}) });
29
- return openPostgresStore({ url: target.url, schema: target.schema, role, ...(now ? { now } : {}), ...(warn ? { warn } : {}) });
49
+ return openPostgresStore({ url: target.url, schema: target.schema, role, poolSize, ...(now ? { now } : {}), ...(warn ? { warn } : {}) });
30
50
  }
@@ -70,6 +70,19 @@ export async function dropPostgresSchema(url, schema) {
70
70
  await client.end().catch(() => undefined);
71
71
  }
72
72
  }
73
+ /** Makes `schema` (absent, under the migration lock). A role with no CREATE on the database is refused in words that say
74
+ * what to do: the schema made ahead of time, owned by this role, or CREATE granted. */
75
+ async function createSchema(client, schema) {
76
+ try {
77
+ await client.query(`CREATE SCHEMA ${schema}`);
78
+ }
79
+ catch (error) {
80
+ // 42501: insufficient_privilege.
81
+ if (error?.code !== "42501")
82
+ throw error;
83
+ throw new Error(`${placeOf(schema)} does not exist, and this role may not create it (no CREATE on the database): create the schema ahead of time, owned by this role, or grant this role CREATE on the database`, { cause: error });
84
+ }
85
+ }
73
86
  /** Applies every pending migration to `schema`, in one transaction under the schema's migration lock, at `at` (ms). A
74
87
  * schema at a version this build does not know is refused (SchemaVersionUnknown), and so is an applied file whose text
75
88
  * changed since. Answers the version it leaves. */
@@ -79,7 +92,11 @@ export async function migrate(client, schema, at, migrations = migrationsIn()) {
79
92
  await client.query("BEGIN");
80
93
  try {
81
94
  await client.query("SELECT pg_advisory_xact_lock(hashtext($1), hashtext('migrate'))", [schema]);
82
- await client.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);
95
+ // Made only when absent: Postgres checks CREATE on the database before IF NOT EXISTS, so a role that owns a schema an
96
+ // administrator made ahead of time, with no CREATE on the database, could not start on it otherwise.
97
+ const exists = (await client.query("SELECT 1 FROM pg_namespace WHERE nspname = $1", [schema])).rowCount !== 0;
98
+ if (!exists)
99
+ await createSchema(client, schema);
83
100
  await client.query(`SET LOCAL search_path TO ${schema}`);
84
101
  await client.query("CREATE TABLE IF NOT EXISTS schema_migrations (version BIGINT PRIMARY KEY, name TEXT NOT NULL, sha256 TEXT NOT NULL, applied_at BIGINT NOT NULL)");
85
102
  const applied = (await client.query("SELECT version, name, sha256 FROM schema_migrations ORDER BY version")).rows;