@parcha/agentrun-serve 0.1.0-beta.29 → 0.1.0-beta.31

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 (172) hide show
  1. package/CHANGELOG.md +238 -0
  2. package/README.md +739 -116
  3. package/dist/adapters.d.ts +35 -6
  4. package/dist/adapters.js +152 -26
  5. package/dist/agents.d.ts +18 -7
  6. package/dist/agents.js +19 -10
  7. package/dist/app.js +101 -26
  8. package/dist/background.d.ts +29 -0
  9. package/dist/background.js +397 -0
  10. package/dist/box-egress-vm.d.ts +125 -0
  11. package/dist/box-egress-vm.js +350 -0
  12. package/dist/box-egress.d.ts +99 -0
  13. package/dist/box-egress.js +259 -0
  14. package/dist/box-image.d.ts +1 -1
  15. package/dist/box-image.js +9 -7
  16. package/dist/box-relay-vm.d.ts +84 -0
  17. package/dist/box-relay-vm.js +410 -0
  18. package/dist/box-relay.d.ts +8 -5
  19. package/dist/box-relay.js +14 -9
  20. package/dist/boxes.d.ts +28 -5
  21. package/dist/boxes.js +44 -18
  22. package/dist/browser-cost.d.ts +41 -0
  23. package/dist/browser-cost.js +158 -0
  24. package/dist/cap.d.ts +130 -21
  25. package/dist/cap.js +339 -67
  26. package/dist/cli.js +30 -4
  27. package/dist/coding-tools.d.ts +7 -3
  28. package/dist/coding-tools.js +16 -10
  29. package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
  30. package/dist/console/assets/index-CnJBf7Lc.js +486 -0
  31. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  32. package/dist/console/index.html +2 -2
  33. package/dist/content-filter.d.ts +7 -0
  34. package/dist/content-filter.js +23 -0
  35. package/dist/decision-rows.d.ts +11 -3
  36. package/dist/decision-rows.js +18 -11
  37. package/dist/decisions.d.ts +3 -3
  38. package/dist/decisions.js +4 -3
  39. package/dist/errors.d.ts +2 -0
  40. package/dist/errors.js +5 -2
  41. package/dist/files.d.ts +9 -1
  42. package/dist/files.js +10 -2
  43. package/dist/grade.d.ts +11 -11
  44. package/dist/grade.js +43 -55
  45. package/dist/graph-served.d.ts +23 -0
  46. package/dist/graph-served.js +75 -0
  47. package/dist/graph-view.d.ts +7 -5
  48. package/dist/graph-view.js +10 -3
  49. package/dist/harness-app.d.ts +4 -2
  50. package/dist/harness-app.js +110 -19
  51. package/dist/harness-opencode/adapter.d.ts +45 -0
  52. package/dist/harness-opencode/adapter.js +272 -0
  53. package/dist/harness-opencode/binary.d.ts +18 -0
  54. package/dist/harness-opencode/binary.js +87 -0
  55. package/dist/harness-opencode/config.d.ts +24 -0
  56. package/dist/harness-opencode/config.js +61 -0
  57. package/dist/harness-opencode/harness.d.ts +77 -0
  58. package/dist/harness-opencode/harness.js +620 -0
  59. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  60. package/dist/harness-opencode/host/mcp.js +208 -0
  61. package/dist/harness-opencode/host/policy.d.ts +71 -0
  62. package/dist/harness-opencode/host/policy.js +419 -0
  63. package/dist/harness-opencode/host/server.d.ts +55 -0
  64. package/dist/harness-opencode/host/server.js +165 -0
  65. package/dist/harness-opencode/index.d.ts +9 -0
  66. package/dist/harness-opencode/index.js +6 -0
  67. package/dist/harness-opencode/verify.d.ts +32 -0
  68. package/dist/harness-opencode/verify.js +75 -0
  69. package/dist/harness-opencode/versions.d.ts +33 -0
  70. package/dist/harness-opencode/versions.js +64 -0
  71. package/dist/harness.d.ts +4 -1
  72. package/dist/harness.js +5 -2
  73. package/dist/host-check.d.ts +12 -0
  74. package/dist/host-check.js +34 -0
  75. package/dist/host-tools.d.ts +12 -2
  76. package/dist/host-tools.js +26 -12
  77. package/dist/host.js +6 -2
  78. package/dist/hosted-search.js +5 -1
  79. package/dist/import.d.ts +2 -2
  80. package/dist/import.js +4 -3
  81. package/dist/key-check.d.ts +3 -2
  82. package/dist/key-check.js +7 -3
  83. package/dist/key-refusal.js +8 -4
  84. package/dist/key-words.d.ts +37 -0
  85. package/dist/key-words.js +40 -0
  86. package/dist/learn/check.d.ts +10 -1
  87. package/dist/learn/check.js +19 -1
  88. package/dist/learn/grade.d.ts +6 -2
  89. package/dist/learn/grade.js +28 -14
  90. package/dist/learn/index.d.ts +3 -3
  91. package/dist/learn/index.js +3 -3
  92. package/dist/learn/notes.js +2 -1
  93. package/dist/learn/reflect.d.ts +2 -2
  94. package/dist/learn/reflect.js +53 -5
  95. package/dist/learn/secrets.js +28 -8
  96. package/dist/learn/skills.d.ts +19 -4
  97. package/dist/learn/skills.js +95 -6
  98. package/dist/learned-workflow.d.ts +59 -0
  99. package/dist/learned-workflow.js +191 -0
  100. package/dist/learning-routes.d.ts +30 -1
  101. package/dist/learning-routes.js +173 -19
  102. package/dist/learning-run.d.ts +8 -6
  103. package/dist/learning-run.js +70 -27
  104. package/dist/learning-words.d.ts +12 -5
  105. package/dist/learning-words.js +34 -13
  106. package/dist/learning.d.ts +52 -3
  107. package/dist/learning.js +204 -4
  108. package/dist/mcp-gateway.d.ts +96 -0
  109. package/dist/mcp-gateway.js +408 -0
  110. package/dist/mcp-meta.d.ts +17 -0
  111. package/dist/mcp-meta.js +38 -0
  112. package/dist/mcp-servers.d.ts +33 -9
  113. package/dist/mcp-servers.js +58 -10
  114. package/dist/mcp.js +5 -5
  115. package/dist/model.d.ts +13 -11
  116. package/dist/model.js +11 -10
  117. package/dist/openapi/agentrun-v2.openapi.json +1 -0
  118. package/dist/openapi.js +407 -54
  119. package/dist/page.d.ts +2 -0
  120. package/dist/page.js +3 -0
  121. package/dist/paid-calls.d.ts +5 -1
  122. package/dist/paid-calls.js +1 -1
  123. package/dist/pause.d.ts +2 -0
  124. package/dist/place.d.ts +29 -5
  125. package/dist/place.js +51 -11
  126. package/dist/print.d.ts +7 -0
  127. package/dist/print.js +13 -0
  128. package/dist/propose.d.ts +2 -0
  129. package/dist/propose.js +38 -8
  130. package/dist/request-start.d.ts +12 -4
  131. package/dist/request-start.js +139 -15
  132. package/dist/run-box.d.ts +56 -4
  133. package/dist/run-box.js +183 -23
  134. package/dist/runnable.d.ts +13 -3
  135. package/dist/runnable.js +63 -6
  136. package/dist/runs.d.ts +266 -37
  137. package/dist/runs.js +884 -90
  138. package/dist/secrets.d.ts +27 -0
  139. package/dist/secrets.js +38 -2
  140. package/dist/server.d.ts +141 -36
  141. package/dist/server.js +562 -118
  142. package/dist/sign-ins.d.ts +99 -0
  143. package/dist/sign-ins.js +288 -0
  144. package/dist/skills.d.ts +16 -4
  145. package/dist/skills.js +35 -7
  146. package/dist/stats.d.ts +7 -2
  147. package/dist/stats.js +28 -7
  148. package/dist/tool-gate.d.ts +281 -0
  149. package/dist/tool-gate.js +585 -0
  150. package/dist/tool-keys.d.ts +48 -11
  151. package/dist/tool-keys.js +46 -8
  152. package/dist/tool-plane.d.ts +116 -27
  153. package/dist/tool-plane.js +232 -50
  154. package/dist/tools.d.ts +69 -14
  155. package/dist/tools.js +148 -26
  156. package/dist/trigger-secrets.d.ts +32 -0
  157. package/dist/trigger-secrets.js +143 -0
  158. package/dist/triggers.d.ts +439 -0
  159. package/dist/triggers.js +863 -0
  160. package/dist/turn-end.d.ts +3 -2
  161. package/dist/turn-end.js +3 -2
  162. package/dist/usage-lines.d.ts +26 -0
  163. package/dist/usage-lines.js +28 -0
  164. package/dist/validate.d.ts +2 -0
  165. package/dist/validate.js +11 -2
  166. package/dist/web-fetch.js +3 -3
  167. package/dist/webhooks.d.ts +11 -4
  168. package/dist/webhooks.js +17 -1
  169. package/launcher/agentrun-serve +1 -1
  170. package/package.json +16 -14
  171. package/dist/console/assets/index-BN7oVcO4.js +0 -445
  172. package/dist/console/assets/index-By-jkqki.css +0 -1
package/dist/server.js CHANGED
@@ -8,7 +8,7 @@ import { pipeline } from "node:stream/promises";
8
8
  import { pathToFileURL } from "node:url";
9
9
  import { Worker } from "node:worker_threads";
10
10
  import { once } from "node:events";
11
- import { existsSync } from "node:fs";
11
+ import { existsSync, readFileSync } from "node:fs";
12
12
  import { rm } from "node:fs/promises";
13
13
  import { homedir } from "node:os";
14
14
  import { agentView, Agents, etagOf, homeBusy, revisionView, storeBusy } from "./agents.js";
@@ -17,39 +17,50 @@ import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_
17
17
  import { FAUX_WEB_ENV } from "./fetch-page.js";
18
18
  import { FAUX_MONID_ENV } from "./monid.js";
19
19
  import { FAUX_EXA_ENV } from "./exa-keyless.js";
20
- import { FAUX_BROWSER_ENV, NODE_TOOLS, toolingOf, toolsView } from "./tools.js";
20
+ import { FAUX_BROWSER_ENV, NODE_TOOLS, toolingOf, toolOf, toolsView } from "./tools.js";
21
21
  import { ApiError, invalid, unsupported } from "./errors.js";
22
- import { DATA_ENV, DOOR_TOKEN_FILE, HOME_HOST_OWNED, HOMES_DIR, homeOf, readJson, RUN_META, syncDir, TOKEN_FILE, writeDurable } from "./files.js";
22
+ import { DATA_ENV, DOOR_TOKEN_FILE, HOME_HOST_OWNED, HOMES_DIR, homeOf, readJson, RUN_META, SETUP_LOST, syncDir, TOKEN_FILE, writeDurable } from "./files.js";
23
23
  import { checkedPath, decodedPath, homePath, hostOwnedOf, hostOwnedRefusal, ownedByIdentity } from "./home-path.js";
24
24
  import { chooseModel, EFFORTS, FAUX_ENV, FAUX_UPSTREAM_ENV, MODEL_NODES, modelSource, THINKING_LEVELS, withoutFaux } from "./model.js";
25
25
  import { DEFAULT_HARNESS, FAUX_HARNESS_ENV, harnessOffers } from "./harness.js";
26
26
  import { healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
27
27
  import { IMPORT_ASKED } from "./import.js";
28
28
  import { gradeModelOf, learningBudgetOf, learningOf } from "./learning.js";
29
- import { agentLearning, learningLog, learningNotes, noteBody, readNote, runDiff, runLearning, secretsShown, sendNote, writeNote } from "./learning-routes.js";
29
+ import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, readNote, runDiff, runLearning, secretsShown, sendNote, writeNote } from "./learning-routes.js";
30
30
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
31
31
  import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
32
- import { boxesLine, noBoxReason, placesOf, resolvePlace } from "./place.js";
33
- import { boxLimitsOf, FAUX_BOX_ENV, fauxBoxes } from "./run-box.js";
32
+ import { boxesLine, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf, resolvePlace } from "./place.js";
33
+ import { BOX_ALLOW_ENV, boxAllowOf, boxLimitsOf, boxNetworkOf, FAUX_BOX_ENV, fauxBoxes } from "./run-box.js";
34
34
  import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
35
- import { answerPage, byOwnerSession, isJson, ownerCookie, ownOrigin, signedIn } from "./page.js";
35
+ import { answerPage, byOwnerSession, isJson, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
36
+ import { HOST_FIX, hostName, loopbackNames } from "./host-check.js";
36
37
  import { durationMs, logLine } from "./print.js";
37
- import { Runs, STATUSES, statusOf, toolCostOf } from "./runs.js";
38
+ import { knownToolCostOf, Runs, STATUSES, statusOf, toolCostOf, WAITS_ON_A_PERSON } from "./runs.js";
39
+ import { runLines } from "./usage-lines.js";
38
40
  import { BOX_QUARANTINE, Quarantine } from "./box/sweep.js";
39
- import { boxesLog, boxRegistry, daytonaApi, enabledBoxes } from "./boxes.js";
41
+ import { boxesByDefault, boxesLog, boxRegistry, daytonaApi, enabledBoxes, VM_NO_LIST, VM_PROVIDER } from "./boxes.js";
42
+ import { FAUX_EGRESS_ENV, sweepEgressDirs } from "./box-egress.js";
43
+ import { startEgressContainer } from "./box-egress-vm.js";
40
44
  import { boxImageOf, clearImage, dockerImage, withImage } from "./box-image.js";
41
45
  import { startBoxRelay } from "./box-relay.js";
46
+ import { vmRelay } from "./box-relay-vm.js";
47
+ import { memoryMbOf } from "./run-box.js";
42
48
  import { DOCUMENTS_ENV } from "./pdf-pages.js";
43
- import { metersIn } from "./cap.js";
44
- import { blockersOf, CODE_NODES_ENV, issueOf } from "./runnable.js";
49
+ import { meterFiguresIn } from "./cap.js";
50
+ import { blockersOf, CODE_NODES_ENV, issueOf, MCP_HARNESSES } from "./runnable.js";
45
51
  import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
46
- import { analyticsFilter, analyticsView, statsView } from "./stats.js";
52
+ import { redactedOutput } from "./key-refusal.js";
53
+ import { analyticsFilter, analyticsView, pendingOf, statsView } from "./stats.js";
47
54
  import { outcomes } from "./usage.js";
48
55
  import { keyOf, SEAL_KEY_ENV, sealKeyOf, TOOL_FIELDS, ToolKeys } from "./tool-keys.js";
56
+ import { SIGN_INS_DIR, SignIns, vendorsOver } from "./sign-ins.js";
49
57
  import { MCP_AUTH_TYPES, McpServers } from "./mcp-servers.js";
58
+ import { metaToolOf } from "./mcp-meta.js";
50
59
  import { WEBHOOK_EVENTS, Webhooks } from "./webhooks.js";
51
- import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, ID, inputIssues, isObject, stable, unknownFields } from "./validate.js";
52
- import { agentTools, settingsIssues, ToolSettings, withDefaults } from "./tool-plane.js";
60
+ import { HOOK_TOLERANCE_S, hookHeadersRefusal, hookRefusal, TriggerSecrets } from "./trigger-secrets.js";
61
+ import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, OVERLAP, PAYLOAD_KEPT_BYTES, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
62
+ import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, ID, IDEMPOTENCY_TTL_S, inputIssues, isObject, stable, unknownFields } from "./validate.js";
63
+ import { agentTools, browserKeyRow, settingsIssues, ToolSettings, withDefaults } from "./tool-plane.js";
53
64
  import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
54
65
  import { INLINE_TYPES, openWorkFile, removeWorkFile, typeOf, WALK_DEPTH, walkWork, WorkRefused, writesHeld, writeWorkFile } from "./workspace.js";
55
66
  import { markRunning, markStopping, takeServerLockAfterStop } from "./server-lock.js";
@@ -60,10 +71,11 @@ export const DEFAULT_PORT = 7340;
60
71
  const VERSION = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8")).version;
61
72
  const IDEMPOTENCY_FILE = ".idempotency.json";
62
73
  const MAX_BODY = 1 << 20;
74
+ /** The largest body a webhook trigger takes (POST /v2/hooks/{id}). */
75
+ const HOOK_MAX_BODY = 256 << 10;
63
76
  const MAX_MESSAGE = 20_000;
64
77
  const MAX_WAIT_MS = 25_000;
65
78
  const PAGE_ROWS = 500;
66
- const IDEMPOTENCY_TTL_S = 86_400;
67
79
  const FILE_LIST_CAP = 2_000;
68
80
  /** What a stopping server's record allows past its runs' kill bound, the cap a start waits under: the runs' carry backs,
69
81
  * retried while the agent store is held (about 15.5 s), their boxes' cleanup (up to a minute), and the deliveries', the
@@ -85,7 +97,7 @@ const HOME_WRITES_OFF = "This server can't write a home's files safely here: a w
85
97
  const FILE_CSP = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox; form-action 'none'";
86
98
  /** Each test switch a run's process reads, by the variable it reads it from: set only under `faux`, but the faux
87
99
  * harness's, which scripts the harnesses with or without it. */
88
- 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]];
100
+ 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]];
89
101
  /** The test switches a run's process gets, each module path resolved: empty outside tests. */
90
102
  function fauxEnvOf(options) {
91
103
  const env = options.fauxHarness ? { [FAUX_HARNESS_ENV]: resolve(options.fauxHarness) } : {};
@@ -111,6 +123,11 @@ async function tokenIn(file) {
111
123
  return { token, made: true };
112
124
  }
113
125
  const digest = (text) => createHash("sha256").update(text).digest();
126
+ /** Why a trigger never messages a run: it has no spend cap, and every turn a trigger drives is capped. */
127
+ const NO_CAP = "The run has no spend cap: a trigger only messages a run with one, as every turn it drives is capped.";
128
+ /** What an unknown trigger's request is checked against, so it is refused in a known trigger's time. */
129
+ const NO_TRIGGER_SECRET = `whsec_${randomBytes(32).toString("base64")}`;
130
+ const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
114
131
  const SESSION_S = SESSION_MS / 1000;
115
132
  export const ROUTES = [
116
133
  { method: "GET", pattern: /^\/capabilities$/, name: "getCapabilities" },
@@ -124,6 +141,7 @@ export const ROUTES = [
124
141
  { method: "POST", pattern: /^\/agents\/([^/]+)\/current$/, name: "setCurrent" },
125
142
  { method: "POST", pattern: /^\/agents\/([^/]+)\/archive$/, name: "archiveAgent" },
126
143
  { method: "POST", pattern: /^\/agents\/([^/]+)\/unarchive$/, name: "unarchiveAgent" },
144
+ { method: "DELETE", pattern: /^\/agents\/([^/]+)\/sign-ins\/([^/]+)$/, name: "forgetSignIn" },
127
145
  { method: "POST", pattern: /^\/agents\/([^/]+)\/runs$/, name: "createRun" },
128
146
  { method: "GET", pattern: /^\/agents\/([^/]+)\/runs$/, name: "listRuns" },
129
147
  { method: "GET", pattern: /^\/agents\/([^/]+)\/home$/, name: "exportHome", capability: "home.export" },
@@ -134,10 +152,12 @@ export const ROUTES = [
134
152
  { method: "DELETE", pattern: /^\/agents\/([^/]+)\/home\/files\/(.+)$/, name: "deleteHomeFile" },
135
153
  { method: "GET", pattern: /^\/runs$/, name: "listAllRuns" },
136
154
  { method: "GET", pattern: /^\/runs\/([^/]+)$/, name: "getRun" },
155
+ { method: "PATCH", pattern: /^\/runs\/([^/]+)$/, name: "raiseRunCap" },
137
156
  { method: "GET", pattern: /^\/runs\/([^/]+)\/timeline$/, name: "getTimeline" },
138
157
  { method: "POST", pattern: /^\/runs\/([^/]+)\/messages$/, name: "sendMessage" },
139
158
  { method: "POST", pattern: /^\/runs\/([^/]+)\/stop$/, name: "stopRun" },
140
159
  { method: "POST", pattern: /^\/runs\/([^/]+)\/cancel$/, name: "cancelRun" },
160
+ { method: "POST", pattern: /^\/runs\/([^/]+)\/approvals\/([^/]+)$/, name: "answerApproval" },
141
161
  { method: "POST", pattern: /^\/runs\/([^/]+)\/archive$/, name: "archiveRun" },
142
162
  { method: "POST", pattern: /^\/runs\/([^/]+)\/unarchive$/, name: "unarchiveRun" },
143
163
  { method: "POST", pattern: /^\/runs\/([^/]+)\/kill$/, name: "killRun", capability: "runs.kill" },
@@ -172,6 +192,16 @@ export const ROUTES = [
172
192
  { method: "POST", pattern: /^\/settings\/webhook\/test$/, name: "testWebhook" },
173
193
  { method: "GET", pattern: /^\/settings\/webhook\/deliveries$/, name: "listWebhookDeliveries" },
174
194
  { method: "POST", pattern: /^\/settings\/webhook\/deliveries\/([^/]+)\/redeliver$/, name: "redeliverWebhook" },
195
+ { method: "GET", pattern: /^\/triggers$/, name: "listTriggers" },
196
+ { method: "POST", pattern: /^\/triggers$/, name: "createTrigger" },
197
+ { method: "GET", pattern: /^\/triggers\/([^/]+)$/, name: "getTrigger" },
198
+ { method: "PATCH", pattern: /^\/triggers\/([^/]+)$/, name: "updateTrigger" },
199
+ { method: "DELETE", pattern: /^\/triggers\/([^/]+)$/, name: "deleteTrigger" },
200
+ { method: "POST", pattern: /^\/triggers\/([^/]+)\/fire$/, name: "fireTrigger" },
201
+ { method: "GET", pattern: /^\/triggers\/([^/]+)\/firings$/, name: "listTriggerFirings" },
202
+ { method: "POST", pattern: /^\/triggers\/([^/]+)\/secret$/, name: "rotateTriggerSecret" },
203
+ // Answered before the bearer check: the request's signature is its credential.
204
+ { method: "POST", pattern: /^\/hooks\/([^/]+)$/, name: "receiveHook" },
175
205
  // Answered before routing (mcp.ts), with the token only: listed here for the document.
176
206
  { method: "POST", pattern: /^\/mcp$/, name: "callMcp" },
177
207
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
@@ -181,12 +211,13 @@ export const ROUTES = [
181
211
  { method: "PUT", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)$/, name: "writeLearningFile" },
182
212
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/retire$/, name: "retireLearningFile" },
183
213
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/approve$/, name: "approveLearningFile" },
214
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/restore$/, name: "restoreLearningFile" },
184
215
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning$/, name: "getRunLearning" },
185
216
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning\/diff$/, name: "getRunLearningDiff" },
186
217
  ];
187
218
  /** Where agent `agentId`'s host-owned path is read on this server: its route, when ROUTES has one (the learning API, for
188
- * learning/). */
189
- const ownedReadAt = (agentId) => (owned) => (ROUTES.some((r) => r.method === "GET" && r.pattern.test(`/agents/${agentId}/${owned}`)) ? `/v2/agents/${agentId}/${owned}` : undefined);
219
+ * learning/); sign-ins/ only as the agent's `sign_ins`, never a pointer. */
220
+ const ownedReadAt = (agentId) => (owned) => (owned === SIGN_INS_DIR ? `/v2/agents/${agentId}` : ROUTES.some((r) => r.method === "GET" && r.pattern.test(`/agents/${agentId}/${owned}`)) ? `/v2/agents/${agentId}/${owned}` : undefined);
190
221
  /** Whether the request to `path` (under /v2) is a PUT of a route marked `raw`. */
191
222
  export const takesBytes = (method, path) => (method === "PUT" || method === "POST") && ROUTES.some((r) => r.raw === true && r.method === method && r.pattern.test(path));
192
223
  /** What this server offers. Every flag is present; an off one answers 501 naming it. */
@@ -241,6 +272,8 @@ export async function readingOf(base, maxRuns, stored, learning, toolSettings =
241
272
  * `learning` is the server's learning switch (`--learning`), AGENTRUN_SERVE_LEARNING's when not given; with this
242
273
  * server's tool settings, what each web tool resolves to (tool-plane.ts); `boxes`, the box offers its places show;
243
274
  * `gradeModel`, its `--grade-model`. */
275
+ /** Why a Daytona box has no network although AGENTRUN_BOX_ALLOW names hosts: Daytona refused its domain list (`code`). */
276
+ const noListReason = (code) => `Daytona did not keep a sandbox's domain list (${code}), so this server's Daytona boxes have no network until it starts again: Daytona takes a domain list on its tier 3 and 4 only. To keep them closed without trying, set ${BOX_ALLOW_ENV}=none`;
244
277
  export async function capabilities(env = withSecrets(process.env), maxRuns = maxRunsOf(env), learning = learningOf(env), toolSettings = {}, boxes = [], gradeModel) {
245
278
  return capabilitiesWith(env, maxRuns, await harnessOffers(env), learning, await needsOf(env), toolSettings, boxes, gradeModel);
246
279
  }
@@ -252,10 +285,14 @@ export function forCaller(caps, ownerSession) {
252
285
  /** The capabilities document from offers already resolved, under the server's learning switch, tool settings and box
253
286
  * offers: cheap, made again after each key or tool-settings write with the offers the server holds; and `needs` as
254
287
  * needsOf says it for a revision that names no model (null when it runs). */
255
- function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings, boxes, gradeModel) {
288
+ function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings, boxes, gradeModel, refused = {}) {
256
289
  const models = { ...modelSource(env), ready: needs === null, needs };
257
290
  // Both limits apply: the cap on the count, and the memory each run reserves (host.ts).
258
291
  const memory = hostMemory();
292
+ // The browser's key is its vendor's row: Kernel's where Kernel is picked or resolved (tool-plane.ts browserKeyRow).
293
+ const keyFor = (tool) => (tool.name === "browser" ? browserKeyRow(tool.provider, tool.resolves?.[DEFAULT_HARNESS]) : keyOf(tool.name));
294
+ const tools = toolsView(env, toolSettings, noBoxReason(boxes), refused).map((tool) => (keyFor(tool) ? { ...tool, key: keyFor(tool) } : tool));
295
+ const browser = tools.find((tool) => tool.name === "browser");
259
296
  return {
260
297
  backend: "local",
261
298
  contract: CONTRACT,
@@ -265,7 +302,7 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings
265
302
  // `keys`, what a model key would unlock, is the key rows' (listToolKeys), never served here.
266
303
  harnesses: harnesses.map(({ keys: _keys, ...offer }) => ({ ...offer, max_concurrent_runs: Math.min(maxRuns, runsThatFit(offer.id, memory)) })),
267
304
  /** The places a revision may name (`definition.place`), this host's default, and whether this server has each box. */
268
- places: placesOf(boxes),
305
+ places: placesOf(boxes, boxAllowOf(env)),
269
306
  models,
270
307
  /** What grades a run's proposed notes: the model this server names for it (learning.ts gradeModelOf), or null when
271
308
  * each run is graded on its agent's own model; and `pending`: a risky rule, the user's or the run's own, is kept to
@@ -275,7 +312,7 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings
275
312
  /** Every tool a revision may name (the closed table in tools.ts): available here, or the variables it is missing; a
276
313
  * web tool, what it resolves to on each harness under this server's tool settings; `key`, the tool key that unlocks
277
314
  * it (tool-keys.ts), when one does. */
278
- tools: toolsView(env, toolSettings, noBoxReason(boxes)).map((tool) => (keyOf(tool.name) ? { ...tool, key: keyOf(tool.name) } : tool)),
315
+ tools,
279
316
  /** How this server holds its secrets (secrets.ts, the launcher), and what that does not cover. */
280
317
  secrets: {
281
318
  names: [...SECRET_NAMES],
@@ -301,14 +338,18 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings
301
338
  timeline: { long_poll: true, sse: true, live_rows: true, live_workflow_rows: false },
302
339
  files: { upload: true, read: true, range: false, during_run: true },
303
340
  quotes: false,
304
- usage: { basis: "estimate", meters: ["tokens", "tools", "learning"] },
341
+ usage: { basis: "estimate", meters: ["tokens", "tools", "browser_time", "learning"] },
305
342
  efforts: [...EFFORTS],
306
343
  thinking: [...THINKING_LEVELS],
307
- browser: "none",
308
- /** A tool setting's `permission` (definition.tool_settings, /v2/settings/tools): false until the tool gate lands,
309
- * and a save that names one is refused. */
310
- tool_permissions: false,
311
- sign_ins: false,
344
+ /** The browser a run's `browser` tool drives: the vendor it resolves to under the server's settings when the tool is
345
+ * available here (tools[]), Browserbase's or Kernel's, else none. */
346
+ browser: browser?.available ? (browser.resolves?.[DEFAULT_HARNESS] === "kernel" ? "kernel" : "browserbase") : "none",
347
+ /** A tool setting's `permission` (definition.tool_settings, /v2/settings/tools): allow, ask or deny, which the tool
348
+ * gate holds every tool call to (tool-gate.ts); an ask is answered at POST /runs/{id}/approvals/{approval_id}. */
349
+ tool_permissions: true,
350
+ /** An agent's browser stays signed in between its runs (sign-ins.ts): with a seal key to keep each pointer under, and a
351
+ * browser vendor here (Browserbase's or Kernel's; local Chrome keeps none). */
352
+ sign_ins: sealKeyOf(env[SEAL_KEY_ENV]) !== undefined && tools.some((tool) => tool.name === "browser" && tool.available),
312
353
  vault: false,
313
354
  query: false,
314
355
  /** GET, PUT and DELETE /settings/tool-keys: a tool's key saved by name, kept sealed under the launcher's seal key
@@ -316,12 +357,14 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings
316
357
  tool_keys: { routes: true, at_rest: sealKeyOf(env[SEAL_KEY_ENV]) ? "sealed" : "unavailable" },
317
358
  /** /settings/mcp-servers: remote MCP servers previewed and saved, each credential sealed under the same seal key
318
359
  * (mcp-servers.ts); with none, only servers that take no credential are kept. */
319
- mcp_client: { routes: true, transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: sealKeyOf(env[SEAL_KEY_ENV]) ? "sealed" : "unavailable" },
360
+ mcp_client: { routes: true, transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: sealKeyOf(env[SEAL_KEY_ENV]) ? "sealed" : "unavailable", harnesses: [...MCP_HARNESSES] },
320
361
  /** This server's learning switch (`--learning`): on, a run learns when its agent says `learning: true`; off, none does. */
321
362
  learning,
322
363
  /** /settings/webhook: one URL POSTed, signed by the Standard Webhooks spec, when a run needs its person and when it
323
364
  * ends (webhooks.ts); its secret kept sealed under the same seal key, so with none no webhook is set. */
324
365
  webhooks: { routes: true, events: [...WEBHOOK_EVENTS], signing: "standard-webhooks/v1", at_rest: sealKeyOf(env[SEAL_KEY_ENV]) ? "sealed" : "unavailable" },
366
+ /** /triggers: what starts an agent's capped runs with no caller (triggers.ts). */
367
+ triggers: { routes: true, sources: [...SOURCE_KINDS], targets: [...TARGET_KINDS], overlap: [...OVERLAP], 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", tolerance_s: HOOK_TOLERANCE_S, max_body_bytes: HOOK_MAX_BODY, payload_kept_bytes: PAYLOAD_KEPT_BYTES, at_rest: sealKeyOf(env[SEAL_KEY_ENV]) ? "sealed" : "unavailable" } },
325
368
  },
326
369
  regions: [{ id: "local", jurisdiction: null, state: "live" }],
327
370
  /** This server's own: where its OpenAPI document is, beside this one. */
@@ -393,6 +436,7 @@ export async function startServe(options) {
393
436
  throw new Error(`the drain timeout ${options.drainTimeout} is not a duration such as 8s`);
394
437
  enabledBoxes(process.env);
395
438
  boxLimitsOf(process.env);
439
+ const boxAllow = boxAllowOf(process.env);
396
440
  const maxRuns = maxRunsOf(process.env, options.maxRuns);
397
441
  const learning = learningOf(process.env, options.learning);
398
442
  const learningBudget = learningBudgetOf(process.env, options.learningBudget);
@@ -413,7 +457,7 @@ export async function startServe(options) {
413
457
  try {
414
458
  // The server's record, which its stop rewrites in place (server-lock.ts): made now, so the stop makes nothing.
415
459
  markRunning(data);
416
- return await startHolding(options, data, lock, { maxRuns, minFreeBytes, learning, learningBudget }, stops);
460
+ return await startHolding(options, data, lock, { maxRuns, minFreeBytes, learning, learningBudget, boxAllow }, stops);
417
461
  }
418
462
  catch (error) {
419
463
  for (const stop of stops)
@@ -423,7 +467,16 @@ export async function startServe(options) {
423
467
  }
424
468
  }
425
469
  async function startHolding(options, data, lock, checked, stops) {
426
- const { maxRuns, minFreeBytes, learning, learningBudget } = checked;
470
+ const { maxRuns, minFreeBytes, learning, learningBudget, boxAllow } = checked;
471
+ /** What an agent's view says of its learning: how many learned items wait for its owner's OK, for an agent that learns
472
+ * on this server (learning on, its current revision `learning: true`); none for another, or when the count cannot be
473
+ * read (the view never fails for it). */
474
+ const learningOfAgent = async (entry) => {
475
+ if (learning === "off" || entry.revision?.kind !== "agentic" || entry.revision.body.learning !== true)
476
+ return undefined;
477
+ const pending = await pendingCount(data, entry.agent.id);
478
+ return pending === undefined ? undefined : { pending };
479
+ };
427
480
  const tokenFile = options.token === undefined ? join(data, TOKEN_FILE) : null;
428
481
  const stored = options.token === undefined ? await tokenIn(tokenFile) : undefined;
429
482
  const token = options.token ?? stored.token;
@@ -434,14 +487,16 @@ async function startHolding(options, data, lock, checked, stops) {
434
487
  const authFailed = (route, reason) => log?.(logLine("auth_failed", { route, reason }));
435
488
  /** The host's secrets as a run's notes are checked against (learning-run.ts), and the keys a person saved on this
436
489
  * server (storedKeys, below), read at each call: a person's note, and every learning text read. */
437
- const learningSecrets = () => [...hostSecrets(process.env, storedKeys), token, doorToken];
490
+ const learningSecrets = () => [...hostSecrets(process.env, storedKeys), token, doorToken, ...(triggerSecrets?.values() ?? [])];
491
+ // Each webhook trigger's secret, made below once the environment is read; shown nowhere, as the server's own are not.
492
+ let triggerSecrets;
438
493
  const base = { ...withoutFaux(process.env), [DATA_ENV]: data, ...(options.allowCodeNodes ? { [CODE_NODES_ENV]: "1" } : {}), ...(options.faux ? { [FAUX_ENV]: resolve(options.faux) } : {}), ...(options.fauxHarness ? { [FAUX_HARNESS_ENV]: resolve(options.fauxHarness) } : {}) };
439
494
  // Which fields are the server's is read from what it is started with alone: handed the saved keys too, ToolKeys would
440
495
  // call each the server's, and none could be deleted.
441
496
  const toolKeys = new ToolKeys(data, withSecrets(base, "own"), (fields) => (log ? log(logLine("tool_keys", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("tool_keys", fields)}\n`)));
442
497
  // 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,
443
498
  // the one its runs are given (monid, Parallel, TypeSafe's Jev), never to the network: one with no fake is not checked.
444
- const fakes = { monid: options.fauxMonid, parallel: options.fauxParallel, typesafe: options.fauxJev };
499
+ const fakes = { monid: options.fauxMonid, parallel: options.fauxParallel, typesafe: options.fauxJev, browserbase: options.fauxBrowserbase, kernel: options.fauxKernel };
445
500
  const checkFetch = async (id) => {
446
501
  if (!options.faux)
447
502
  return fetch;
@@ -455,6 +510,27 @@ async function startHolding(options, data, lock, checked, stops) {
455
510
  // A stored key that does not open is said once at the start, never a refusal to start.
456
511
  toolKeys.view();
457
512
  const mcpServers = new McpServers(data, withSecrets(base, "own"), VERSION);
513
+ // What a run's grants are checked against, its pin made from and its credentials read from (runs.ts, runnable.ts).
514
+ const mcpSource = {
515
+ server: (name) => {
516
+ try {
517
+ const saved = mcpServers.get(name);
518
+ return { url: saved.url, tools: saved.tools.map(({ name: tool, title, description, input_schema, annotations }) => ({ name: tool, ...(title ? { title } : {}), ...(description ? { description } : {}), inputSchema: input_schema, ...(annotations ? { annotations: annotations } : {}) })), ...(saved.prices ? { prices: saved.prices } : {}) };
519
+ }
520
+ catch {
521
+ return undefined;
522
+ }
523
+ },
524
+ headers: (name) => mcpServers.headers(name),
525
+ };
526
+ // Each with whether it can be granted: a known meta tool can't (mcp-meta.ts).
527
+ const mcpTools = (server) => {
528
+ const saved = mcpSource.server(server);
529
+ return saved?.tools.map((tool) => {
530
+ const meta = metaToolOf(saved.url, tool.name);
531
+ return meta ? { ...tool, grantable: false, reason: meta.reason } : tool;
532
+ });
533
+ };
458
534
  // The server's tool settings, beside the agent store: capabilities say what they resolve to, again after a PUT.
459
535
  const settings = new ToolSettings(data);
460
536
  // The server's reading, in parts: `env`, its environment with its secrets, saved keys among them (storedKeys);
@@ -470,7 +546,10 @@ async function startHolding(options, data, lock, checked, stops) {
470
546
  // Whether a revision that names no model runs (needsOf): made from env alone, so remade with it, before the caps.
471
547
  let needs = await needsOf(env);
472
548
  // The box offers are probed once, below, before the first reading is made.
473
- const recompose = () => void (caps = capabilitiesWith(env, maxRuns, offers, learning, needs, settings.get(), boxOffers, options.gradeModel));
549
+ // With accounts off no one can answer an ask (the answer route takes the owner's session alone): each tool ask is
550
+ // offered for says it needs the password sign-in, as learning's approve does.
551
+ const askNeeds = (made) => (options.accounts ? made : { ...made, tools: made.tools.map((tool) => (tool.permissions.includes("ask") ? { ...tool, ask_needs: "password" } : tool)) });
552
+ const recompose = () => void (caps = askNeeds(capabilitiesWith(env, maxRuns, offers, learning, needs, settings.get(), boxOffers, options.gradeModel, toolKeys.refused())));
474
553
  // What the offers held now were made from (offersInputs), and the latest probe: one a later probe overtook is dropped.
475
554
  let offersFrom;
476
555
  let probes = 0;
@@ -503,15 +582,40 @@ async function startHolding(options, data, lock, checked, stops) {
503
582
  else
504
583
  await probe("key");
505
584
  };
506
- // The boxes AGENTRUN_BOXES lists, each probed once (boxes.ts); runs execute in Docker's (place.ts). Under --faux, a faux
585
+ // The boxes AGENTRUN_BOXES lists, docker when it is not set, each probed once (boxes.ts); runs execute in Docker's (place.ts). Under --faux, a faux
507
586
  // box stands in for Docker, and nothing asks Docker.
508
- const boxes = await boxRegistry(env);
587
+ // Under --faux, the tests' fake stands in for the VM provider's SDK (startServe's `fauxVm`), never the provider.
588
+ const boxes = await boxRegistry(env, options.faux && options.fauxVm ? { vmSdk: () => import(pathToFileURL(resolve(options.fauxVm)).href) } : {});
509
589
  const fauxBox = options.faux && options.fauxBox ? await fauxBoxes(resolve(options.fauxBox), data) : undefined;
510
590
  // The Docker box's image, asked of Docker now and pulled in the background when Docker has none (box-image.ts): docker
511
591
  // is preparing until it is in, and unavailable if the pull fails. Its record tells the run's processes; with no Docker
512
592
  // box here there is none, so no run waits on one an earlier start left.
513
593
  let image;
514
- const offersNow = () => boxes.offers().map((offer) => (fauxBox && offer.id === "docker" ? { id: "docker", available: true, reason: "a faux box (tests)" } : offer.id === "docker" && image ? withImage(offer, image.state()) : offer));
594
+ // What a Docker box's programs reach, resolved once here (run-box.ts boxNetworkOf): the setting's list, on a Docker
595
+ // daemon of this Linux machine's own; else none, and why. A run's process gets the list or none (RUN_BOX_ALLOW_ENV).
596
+ const boxNetwork = fauxBox ? { allow: "none", reason: "a faux box (tests)" } : boxes.provider("docker") ? await boxNetworkOf(env, options.faux && options.fauxPlatform ? { platform: options.fauxPlatform } : {}) : { allow: "none", reason: "no Docker box on this server" };
597
+ // The proxy directories runs that are gone left in /tmp (box-egress.ts): a live run's, any server's, stays.
598
+ if (!fauxBox && boxes.provider("docker"))
599
+ await sweepEgressDirs().catch(() => 0);
600
+ // On a Mac whose Docker runs in a VM this server knows, the list is served by one proxy container inside that VM
601
+ // (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.
602
+ let egress;
603
+ const dockerNetwork = (offer) => {
604
+ if (!offer.available)
605
+ return offer;
606
+ if (boxNetwork.allow === "none")
607
+ return { ...offer, network: "none", network_reason: boxNetwork.reason };
608
+ const proxy = egress?.state();
609
+ return proxy && proxy.state !== "ready" ? { ...offer, network: "none", network_reason: proxy.reason } : { ...offer, network: "allowlist" };
610
+ };
611
+ // A Daytona box reaches the hosts AGENTRUN_BOX_ALLOW names, through Daytona's domain list, until Daytona cannot keep
612
+ // one here (an organization whose tier takes none): from then on each is made with no network, and capabilities say why.
613
+ let daytonaNoList;
614
+ const daytonaNetwork = (offer) => !offer.available ? offer : boxAllow === "none" ? { ...offer, network: "none" } : daytonaNoList ? { ...offer, network: "none", network_reason: noListReason(daytonaNoList) } : { ...offer, network: "allowlist" };
615
+ // The VM box has no network whatever AGENTRUN_BOX_ALLOW names: its provider takes a host list, but has no read of a
616
+ // box's list back, so the server cannot check one held (run-box.ts ensureRemoteBox makes it blocked). Said, with why.
617
+ const vmNetwork = (offer) => (!offer.available ? offer : boxAllow === "none" ? { ...offer, network: "none" } : { ...offer, network: "none", network_reason: VM_NO_LIST });
618
+ const offersNow = () => boxes.offers().map((offer) => (fauxBox && offer.id === "docker" ? dockerNetwork({ id: "docker", available: true, reason: "a faux box (tests)" }) : offer.id === "docker" ? dockerNetwork(image ? withImage(offer, image.state()) : offer) : offer.id === "daytona" ? daytonaNetwork(offer) : offer.id === VM_PROVIDER.id ? vmNetwork(offer) : offer));
515
619
  const imageLog = (state, more = {}) => log?.(logLine("box_image", { image: image.image, state: state.state, ...more, ...("reason" in state ? { reason: state.reason } : {}) }));
516
620
  let boxOffers = offersNow();
517
621
  const boxImage = !fauxBox && boxes.provider("docker") ? boxImageOf(env) : undefined;
@@ -521,6 +625,7 @@ async function startHolding(options, data, lock, checked, stops) {
521
625
  onChange: (state, ms) => {
522
626
  boxOffers = offersNow();
523
627
  imageLog(state, { ms });
628
+ options.onBoxImage?.(state);
524
629
  // The box's state is in caps alone, not in the offers: recomposed now, or, while the start's probe of the offers
525
630
  // has not ended, by that probe, which reads the box offers when it does.
526
631
  if (offers)
@@ -528,6 +633,7 @@ async function startHolding(options, data, lock, checked, stops) {
528
633
  },
529
634
  });
530
635
  stops.push(async () => void (await image?.close()));
636
+ options.onBoxImage?.(image.state());
531
637
  }
532
638
  else
533
639
  await clearImage(data);
@@ -536,11 +642,51 @@ async function startHolding(options, data, lock, checked, stops) {
536
642
  // Daytona's boxes are made, seeded, pulled and destroyed here, with the key this server holds; a run's process reaches
537
643
  // its own through the relay below, which holds the key for it (box-relay.ts).
538
644
  const remoteBoxes = boxes.provider("daytona");
645
+ // And the VM box's, the same way, with this server's SDK client: the relay's VM half makes a run's calls with it.
646
+ const vmBoxes = boxes.provider(VM_PROVIDER.id);
647
+ const vmClient = boxes.vmClient();
648
+ // What the provider says in an error is cut of every value this server holds (the VM token among them) before a run's
649
+ // process sees it.
650
+ const vmSecrets = () => [...learningSecrets(), ...VM_PROVIDER.keys.map((name) => env[name] ?? "").filter(Boolean)];
651
+ const vmRelayHalf = vmBoxes && vmClient ? vmRelay(vmClient, vmSecrets) : undefined;
652
+ const vmLimits = (() => {
653
+ const limits = boxLimitsOf(env);
654
+ return { cpus: limits.cpus, memoryMb: memoryMbOf(limits.memory) };
655
+ })();
656
+ // Daytona could not keep a run's box's domain list: said in the log and in capabilities, which recompose now.
657
+ // Daytona's own words go to the log, so a refusal for another cause is not taken silently for a tier that takes no list.
658
+ const onNoBoxList = (code, message) => {
659
+ daytonaNoList = code;
660
+ log?.(logLine("box_network", { box: "daytona", network: "none", refused: code, message }));
661
+ boxOffers = offersNow();
662
+ if (offers)
663
+ recompose();
664
+ };
665
+ if (boxNetwork.allow !== "none" && boxNetwork.vm) {
666
+ const allow = boxNetwork.allow;
667
+ const egressLog = (state) => log?.(logLine("box_egress", { runtime: boxNetwork.vm, state: state.state, ...("reason" in state ? { reason: state.reason } : {}) }));
668
+ egress = await startEgressContainer({
669
+ env, data, allow, uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0,
670
+ onChange: (state) => {
671
+ egressLog(state);
672
+ boxOffers = offersNow();
673
+ if (offers)
674
+ recompose();
675
+ },
676
+ });
677
+ stops.push(() => egress.close());
678
+ egressLog(egress.state());
679
+ boxOffers = offersNow();
680
+ }
539
681
  log?.(logLine("boxes", boxesLog(boxOffers, enabledBoxes(env))));
540
682
  if (image)
541
683
  imageLog(image.state());
542
684
  const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability);
543
685
  const agents = new Agents(data);
686
+ triggerSecrets = new TriggerSecrets(data, env, (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)));
687
+ // Each agent's saved sign-ins (sign-ins.ts), under the seal key the tool keys are kept under: its vendor's calls on the
688
+ // server's keys (under faux, the vendor's fake alone), and a lease held while the run it names has not ended.
689
+ const signIns = new SignIns(data, sealKeyOf(withSecrets(base, "own")[SEAL_KEY_ENV]), vendorsOver(() => env, checkFetch), async (runId) => (await agents.request(() => agents.store.readRun(runId)))?.state === "running");
544
690
  const webhooks = new Webhooks(data, env, (fields) => (log ? log(logLine("webhook", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("webhook", fields)}\n`)), options.webhookRetryMs);
545
691
  stops.push(() => webhooks.close());
546
692
  const uploads = new Uploads(join(data, UPLOADS_DIR));
@@ -552,9 +698,9 @@ async function startHolding(options, data, lock, checked, stops) {
552
698
  const documents = options.documents ?? process.env[DOCUMENTS_ENV];
553
699
  if (documents !== undefined && !(await stat(documents).then((info) => info.isDirectory(), () => false)))
554
700
  throw new Error(`the documents directory ${documents} is not a directory`);
555
- const runs = new Runs({ agents, token, storedKeys, doorTokenFile, doorToken, learning, learningBudget, ...(documents ? { documents: resolve(documents) } : {}), fauxEnv: fauxEnvOf(options), toolSettings: () => settings.get(), ...(runBoxes ? { runBoxes } : {}), ...(remoteBoxes ? { remoteBoxes } : {}), ...(remoteBoxes && daytonaApi(env) ? { remoteApi: daytonaApi(env) } : {}), ...(options.drainTimeout ? { drainTimeout: options.drainTimeout } : {}), ...(options.carryBackRetry ? { carryBackRetry: options.carryBackRetry } : {}), maxRuns, ...(options.box ? { box: { host: options.box, quarantine: await Quarantine.open(join(data, BOX_QUARANTINE)) } } : {}), ...(options.settleRetryMs ? { settleRetryMs: options.settleRetryMs } : {}), ...(options.readyTimeoutMs ? { readyTimeoutMs: options.readyTimeoutMs } : {}), ...(options.reflectTimeoutMs ? { reflectTimeoutMs: options.reflectTimeoutMs } : {}), ...(options.gradeTimeoutMs ? { gradeTimeoutMs: options.gradeTimeoutMs } : {}), ...(options.gradeModel ? { gradeModel: options.gradeModel } : {}), ...(log ? { log: (event, fields) => log(logLine(event, fields)) } : {}), notify: (event, run, marker) => webhooks.emit(event, run, marker) });
701
+ const runs = new Runs({ dockerAllow: boxNetwork.allow, ...(egress?.volume ? { dockerVolume: egress.volume } : {}), agents, token, storedKeys, mcpServers: mcpSource, doorTokenFile, doorToken, learning, learningBudget, ...(documents ? { documents: resolve(documents) } : {}), fauxEnv: fauxEnvOf(options), toolSettings: () => settings.get(), ...(runBoxes ? { runBoxes } : {}), ...(remoteBoxes ? { remoteBoxes } : {}), ...(vmBoxes && vmRelayHalf ? { vmBoxes, vmLimits, vmRelay: vmRelayHalf } : {}), ...(remoteBoxes && daytonaApi(env) ? { remoteApi: daytonaApi(env) } : {}), ...(remoteBoxes ? { boxAllow, onNoBoxList } : {}), ...(options.drainTimeout ? { drainTimeout: options.drainTimeout } : {}), ...(options.carryBackRetry ? { carryBackRetry: options.carryBackRetry } : {}), maxRuns, ...(options.box ? { box: { host: options.box, quarantine: await Quarantine.open(join(data, BOX_QUARANTINE)) } } : {}), ...(options.settleRetryMs ? { settleRetryMs: options.settleRetryMs } : {}), ...(options.readyTimeoutMs ? { readyTimeoutMs: options.readyTimeoutMs } : {}), ...(options.reflectTimeoutMs ? { reflectTimeoutMs: options.reflectTimeoutMs } : {}), ...(options.gradeTimeoutMs ? { gradeTimeoutMs: options.gradeTimeoutMs } : {}), ...(options.gradeModel ? { gradeModel: options.gradeModel } : {}), ...(log ? { log: (event, fields) => log(logLine(event, fields)) } : {}), notify: (event, run, marker) => webhooks.emit(event, run, marker), ownSecrets: () => triggerSecrets?.values() ?? [], signIns, approvers: options.accounts === true });
556
702
  const daytona = daytonaApi(env);
557
- const relay = remoteBoxes && daytona ? await startBoxRelay({ root: data, tokenOf: (id) => runs.relayToken(id), ...daytona, serves: (id) => runs.servesBox(id), ensure: (id) => runs.ensureBox(id) }) : undefined;
703
+ const relay = (remoteBoxes && daytona) || vmRelayHalf ? await startBoxRelay({ root: data, tokenOf: (id) => runs.relayToken(id), ...(remoteBoxes && daytona ? daytona : {}), ...(vmRelayHalf ? { vm: vmRelayHalf } : {}), serves: (id) => runs.servesBox(id), ensure: (id) => runs.ensureBox(id) }) : undefined;
558
704
  if (relay)
559
705
  stops.push(() => relay.close());
560
706
  const expected = digest(`Bearer ${token}`);
@@ -564,6 +710,12 @@ async function startHolding(options, data, lock, checked, stops) {
564
710
  runs.beforeReopenLaunch = options.beforeReopenLaunch;
565
711
  if (options.beforeSubmit)
566
712
  runs.beforeSubmit = options.beforeSubmit;
713
+ if (options.beforeMetaSave)
714
+ runs.beforeMetaSave = options.beforeMetaSave;
715
+ if (options.onRunLoad)
716
+ runs.onRunLoad = options.onRunLoad;
717
+ if (options.messageOrigin)
718
+ runs.messageOrigin = options.messageOrigin;
567
719
  const keptFile = join(data, IDEMPOTENCY_FILE);
568
720
  const kept = JSON.parse(await readFile(keptFile, "utf8").catch(() => "null"));
569
721
  const idempotency = new Map((kept?.entries ?? []).filter(([, v]) => v?.answer && Date.now() - v.at <= IDEMPOTENCY_TTL_S * 1000));
@@ -581,6 +733,16 @@ async function startHolding(options, data, lock, checked, stops) {
581
733
  // A saved key is read by name from here, past the checks that refuse a start and before any run (a recovered one too)
582
734
  // is launched: each launch hands over what is saved then. One server in a process reads them: the last started.
583
735
  await probe("start");
736
+ // Under faux, a key the server starts with is checked only against a check's own fake (fauxBrowserbase,
737
+ // fauxMonidCheck, fauxKernel): the fakes the runs use (monid, Parallel, Jev) see the runs' calls alone, and a key with no check fake
738
+ // is not checked.
739
+ const checkFakes = { browserbase: options.fauxBrowserbase, monid: options.fauxMonidCheck, kernel: options.fauxKernel };
740
+ const startFetch = async (id) => {
741
+ if (!options.faux)
742
+ return fetch;
743
+ const fake = checkFakes[id];
744
+ return fake ? (await import(pathToFileURL(resolve(fake)).href)).default : null;
745
+ };
584
746
  // Decided once, by the probe the confinement walks by: capabilities.home.writes says what PUT and DELETE do.
585
747
  const homeWrites = caps.home.writes;
586
748
  // Runs an earlier server left: supervised again, carried back when they already ended, or opened again. Then, however
@@ -604,6 +766,77 @@ async function startHolding(options, data, lock, checked, stops) {
604
766
  });
605
767
  })
606
768
  .catch((error) => void process.stderr.write(`agentrun-serve: the webhook's catch-up: ${error.message}\n`));
769
+ // Schedules: each firing starts its run as POST /agents/{id}/runs does, capped, under the firing's key (triggers.ts).
770
+ // Firings an earlier server left due are driven again now, beside the recovery above.
771
+ const triggers = new Triggers(data, {
772
+ clock: options.triggerClock,
773
+ say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
774
+ async targetIssues(target) {
775
+ if (target.kind === "message_run") {
776
+ const run = await runs.get(target.run_id);
777
+ if (!run)
778
+ return [{ field: "target.run_id", reason: "not_found", message: `no run ${target.run_id}` }];
779
+ if (run.kind === "workflow")
780
+ return [{ field: "target.run_id", reason: "not_allowed", message: "A workflow run takes no messages here." }];
781
+ return run.meta.max_cost_usd === undefined ? [{ field: "target.run_id", reason: "not_allowed", message: NO_CAP }] : [];
782
+ }
783
+ const entry = await agents.get(target.agent_id);
784
+ if (!entry)
785
+ return [{ field: "target.agent_id", reason: "not_found", message: `no agent ${target.agent_id}` }];
786
+ if (!entry.revision)
787
+ return [{ field: "target.agent_id", reason: "invalid", message: `the agent ${target.agent_id} has no current revision` }];
788
+ if (entry.revision.kind === "workflow")
789
+ return [{ field: "target.agent_id", reason: "not_allowed", message: "A trigger's runs are capped, and a workflow run's spend is not capped here: name an agent that is not a workflow." }];
790
+ const uncapped = target.max_cost_usd === undefined && entry.revision.body.maxCostUsd === undefined ? [{ field: "target.max_cost_usd", reason: "missing", message: `Every run a trigger starts is capped: give the target a max_cost_usd or set the agent's (the agent ${target.agent_id} has none).` }] : [];
791
+ return [...uncapped, ...(await inputIssuesOf(entry.revision, target.input)).map((issue) => ({ ...issue, field: `target.${issue.field}` }))];
792
+ },
793
+ async start(target, input, trigger) {
794
+ const entry = await needAgent(target.agent_id);
795
+ // The target's cap, else the agent's default as it stands now: a run a trigger starts is never uncapped.
796
+ const run = await startRunOf(entry, { input, ...(target.max_cost_usd !== undefined ? { max_cost_usd: target.max_cost_usd } : {}), ...(target.effort ? { effort: target.effort } : {}) }, { trigger, origin: { key: trigger.firing_key }, capped: true });
797
+ return { run_id: run.id };
798
+ },
799
+ async message(target, input, key) {
800
+ const run = await needRun(target.run_id);
801
+ if (run.kind === "workflow")
802
+ throw unsupported("messages.steer_workflow_runs", "A workflow run takes no messages here.");
803
+ // A store held past its retries is a busy store: the firing stays due and is tried again, never failed.
804
+ if (await runs.tookMessage(run, key).catch((error) => { throw storeBusy(error) ? homeBusy() : error; }))
805
+ return;
806
+ // Never an uncapped turn, nor an answer to a person's question, an approval or a budget pause: a run that waits on
807
+ // its person is told nothing by a trigger.
808
+ if (run.meta.max_cost_usd === undefined)
809
+ throw new ApiError("not_continuable", NO_CAP);
810
+ const { status, state } = statusOf(run);
811
+ if (status === "input_required" && state === "waiting")
812
+ return { skipped: WAITS_ON_A_PERSON };
813
+ try {
814
+ await runs.message(run, String(input.content), key, { answers: false });
815
+ }
816
+ catch (error) {
817
+ if (error instanceof ApiError && error.message === WAITS_ON_A_PERSON)
818
+ return { skipped: WAITS_ON_A_PERSON };
819
+ throw error;
820
+ }
821
+ },
822
+ secrets: { mint: (id) => triggerSecrets.mint(id), remove: (id) => triggerSecrets.remove(id) },
823
+ notify: (failed, key) => webhooks.emitTrigger(failed, key),
824
+ async runOf(key) {
825
+ const started = await agents.request(() => agents.store.runOfOrigin(key));
826
+ if (!started)
827
+ return null;
828
+ // Never set up as runs.ts load reads it (notSetUp: the store has it running and its serve.json holds no input), which
829
+ // this start's recovery fails as server_lost_at_setup; or failed so already.
830
+ const run = await runs.get(started.runId);
831
+ return { run_id: started.runId, setup_lost: run?.notSetUp === true || run?.error?.details?.reason === SETUP_LOST };
832
+ },
833
+ async statusOf(runId) {
834
+ const row = await agents.request(() => agents.store.readRun(runId));
835
+ return row ? runs.statusOfRow(row) : null;
836
+ },
837
+ });
838
+ stops.push(async () => triggers.close());
839
+ triggers.start();
607
840
  // Setup's import of this machine's sessions: offered by a server on this machine only (no public address, listening
608
841
  // on loopback), counted once (a listing, no transcript kept), run once, each on a worker thread (import-worker.ts) so
609
842
  // a busy store's wait and the sessions' parsing never hold up a request.
@@ -688,20 +921,46 @@ async function startHolding(options, data, lock, checked, stops) {
688
921
  }
689
922
  })());
690
923
  // ---- helpers --------------------------------------------------------------------------------------------------------
691
- /** The body's bytes, at most MAX_BODY of them. */
692
- async function bytesOf(req) {
924
+ /** The body's bytes, at most `max` of them. */
925
+ async function bytesOf(req, max = MAX_BODY) {
693
926
  const chunks = [];
694
927
  let size = 0;
695
928
  // An oversized body is read to its end before the refusal, so the client gets the answer and not a reset.
696
929
  for await (const chunk of req) {
697
930
  size += chunk.length;
698
- if (size <= MAX_BODY)
931
+ if (size <= max)
699
932
  chunks.push(chunk);
700
933
  }
701
- if (size > MAX_BODY)
702
- throw new ApiError("payload_too_large", `the body is over ${MAX_BODY} bytes`, { details: { limit: "max_body_bytes" } });
934
+ if (size > max)
935
+ throw new ApiError("payload_too_large", `the body is over ${max} bytes`, { details: { limit: "max_body_bytes" } });
703
936
  return Buffer.concat(chunks);
704
937
  }
938
+ /** POST /v2/hooks/{trigger_id}: a webhook trigger's firing, signed by the Standard Webhooks spec under its secret
939
+ * (trigger-secrets.ts), checked on the raw body before anything else. An unknown trigger, one that is off or not a
940
+ * webhook's, and a check that fails are one answer, so no trigger id can be found by asking; an unknown one is
941
+ * checked against a secret of no trigger's, so it takes the same time. A webhook-id already fired answers its firing. */
942
+ async function hook(req, res, path) {
943
+ const refuse = (reason) => {
944
+ authFailed(`/v2${path}`, reason);
945
+ return new ApiError("unauthenticated", "this route needs a request signed by the webhook trigger's secret");
946
+ };
947
+ // Headers that can never pass are refused before a byte of the body is read; they say nothing of the trigger.
948
+ const early = hookHeadersRefusal(req.headers, Date.now());
949
+ if (early)
950
+ throw refuse(early);
951
+ const body = await bytesOf(req, HOOK_MAX_BODY);
952
+ let id = "";
953
+ try {
954
+ id = decodeURIComponent(/^\/hooks\/([^/]+)$/.exec(path)[1]);
955
+ }
956
+ catch { }
957
+ const secret = ID.test(id) && triggers.hookable(id) ? triggerSecrets.value(id) : undefined;
958
+ const refusal = hookRefusal(secret ?? NO_TRIGGER_SECRET, req.headers, body, Date.now());
959
+ if (!secret || refusal)
960
+ throw refuse(secret ? refusal : "no_webhook_trigger");
961
+ const { created, firing } = triggers.receive(id, String(req.headers["webhook-id"]), body.toString("utf8"));
962
+ return send(res, created ? 202 : 200, firing, created ? {} : { "idempotent-replayed": "true" });
963
+ }
705
964
  async function bodyOf(req) {
706
965
  const type = String(req.headers["content-type"] ?? "");
707
966
  if (!type.startsWith("application/json"))
@@ -730,7 +989,9 @@ async function startHolding(options, data, lock, checked, stops) {
730
989
  throw new ApiError("not_found", `no run ${id}`);
731
990
  return run;
732
991
  }
733
- /** Replays the first answer to a create with the same key and body; another body is a mismatch. */
992
+ const mismatch = () => new ApiError("idempotency_mismatch", "this Idempotency-Key was used with another body");
993
+ /** Replays the first answer to a create with the same key and body; another body is a mismatch. `work` gets the key's
994
+ * origin (its slot and the body, hashed) for a create the agent store records with the run it starts. */
734
995
  async function idempotent(req, path, body, work) {
735
996
  const key = req.headers["idempotency-key"];
736
997
  if (key === undefined)
@@ -746,7 +1007,7 @@ async function startHolding(options, data, lock, checked, stops) {
746
1007
  const known = idempotency.get(slot);
747
1008
  if (known) {
748
1009
  if (known.fingerprint !== fingerprint)
749
- throw new ApiError("idempotency_mismatch", "this Idempotency-Key was used with another body");
1010
+ throw mismatch();
750
1011
  if (!known.answer)
751
1012
  throw new ApiError("idempotency_in_progress", "the first request with this Idempotency-Key is still in flight", { retry_after_ms: 500 });
752
1013
  return { ...known.answer, headers: { ...known.answer.headers, "idempotent-replayed": "true" } };
@@ -754,14 +1015,15 @@ async function startHolding(options, data, lock, checked, stops) {
754
1015
  idempotency.set(slot, { fingerprint, at: now });
755
1016
  let answer;
756
1017
  try {
757
- answer = await work();
1018
+ answer = await work({ key: `idk_${sha256Hex(slot).slice(0, 32)}`, fingerprint: sha256Hex(fingerprint) });
758
1019
  }
759
1020
  catch (error) {
760
1021
  idempotency.delete(slot);
761
1022
  throw error;
762
1023
  }
763
1024
  // The work happened, so the key keeps its answer in memory even when the file write fails: a retry replays it
764
- // instead of doing the work twice. Only a restart before the next good save loses it.
1025
+ // instead of doing the work twice. Only a restart before the next good save loses it, and a run's create not even
1026
+ // then: the store keeps its run under the key's origin.
765
1027
  idempotency.set(slot, { fingerprint, at: now, answer: { status: answer.status, body: answer.body, headers: answer.headers ?? {} } });
766
1028
  await keep().catch((error) => void process.stderr.write(`agentrun-serve: idempotency save: ${error.message}\n`));
767
1029
  return answer;
@@ -775,7 +1037,7 @@ async function startHolding(options, data, lock, checked, stops) {
775
1037
  * does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). */
776
1038
  async function runnable(revision, place, { capped = false } = {}) {
777
1039
  const shape = { ...shapeOf(revision), place };
778
- const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, offers });
1040
+ const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, offers, mcp: mcpTools });
779
1041
  if (!blockers.length)
780
1042
  return;
781
1043
  const message = blockers.map((b) => b.message).join(" ");
@@ -788,11 +1050,23 @@ async function startHolding(options, data, lock, checked, stops) {
788
1050
  throw new ApiError("agent_not_runnable", message, { details: { unbound, missing, ...named } });
789
1051
  const tier = blockers.find((b) => b.tier)?.tier;
790
1052
  const decisions = Object.fromEntries(blockers.flatMap((b) => (b.decision ? [[b.decision.provider, { reason: b.reason, needs: b.decision.needs }]] : [])));
791
- throw new ApiError("agent_not_runnable", message, { 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 } : {}), ...named } });
1053
+ const denied = blockers.flatMap((b) => (b.denied ? [b.denied] : []));
1054
+ const asks = blockers.flatMap((b) => (b.asks ? [b.asks] : []));
1055
+ throw new ApiError("agent_not_runnable", message, { 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 } });
792
1056
  }
793
1057
  /** A definition being saved: refused (422 by field) when it can never run here; else what this host still lacks. */
794
1058
  async function saveable(revision) {
795
- const blockers = await blockersOf(env, revision.kind === "agentic" ? revision : workflowShape(revision), settings.get(), { boxes: boxOffers, offers });
1059
+ const shape = revision.kind === "agentic" ? revision : workflowShape(revision);
1060
+ const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, offers, mcp: mcpTools });
1061
+ // An agent's default cap caps each run started without one of its own, and a web tool resolves by the cap: what a cap
1062
+ // alone keeps from running under the definition's own picks, whatever this host's settings, would keep every such run
1063
+ // from running, so the save is refused, not each run (claude-agent's or codex's own search, picked, under a cap).
1064
+ if (revision.kind === "agentic" && (revision.maxCostUsd ?? 0) > 0) {
1065
+ const key = (b) => `${b.field}\n${b.message}`;
1066
+ const plain = new Set((await blockersOf(env, shape, {}, { boxes: boxOffers, offers, mcp: mcpTools })).map(key));
1067
+ const capped = await blockersOf(env, shape, {}, { capped: true, boxes: boxOffers, offers, mcp: mcpTools });
1068
+ blockers.push(...capped.filter((b) => !plain.has(key(b))).map((b) => ({ ...b, reason: "not_an_option", fix: "Pick another provider for this tool in definition.tool_settings, or clear the agent's default cap (max_cost_usd: 0).", host: false })));
1069
+ }
796
1070
  const never = blockers.filter((b) => !b.host);
797
1071
  if (never.length)
798
1072
  throw invalid(never.map(issueOf));
@@ -811,43 +1085,65 @@ async function startHolding(options, data, lock, checked, stops) {
811
1085
  if (entry.agent.archivedAt)
812
1086
  throw new ApiError("agent_not_runnable", `The agent ${agentId} is archived: unarchive it to run it.`, { details: { archived_at: entry.agent.archivedAt } });
813
1087
  const body = await bodyOf(req);
814
- return idempotent(req, `/agents/${agentId}/runs`, body, async () => {
815
- const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "quote_id"]);
816
- if (!isObject(body.input))
817
- issues.push({ field: "input", reason: body.input === undefined ? "missing" : "wrong_type", message: "input is an object" });
818
- if (body.revision !== undefined && (typeof body.revision !== "string" || !ID.test(body.revision)))
819
- issues.push({ field: "revision", reason: "wrong_type", message: "revision is a revision id of this agent" });
820
- if (body.effort !== undefined && !EFFORTS.includes(body.effort))
821
- issues.push({ field: "effort", reason: "not_an_option", message: `effort is one of ${EFFORTS.join(", ")}` });
822
- if (body.max_cost_usd !== undefined && !(typeof body.max_cost_usd === "number" && body.max_cost_usd > 0))
823
- issues.push({ field: "max_cost_usd", reason: "wrong_type", message: "max_cost_usd is a number above 0" });
824
- if (body.file_ids !== undefined && !Array.isArray(body.file_ids))
825
- issues.push({ field: "file_ids", reason: "wrong_type", message: "file_ids is a list of file ids" });
826
- if (issues.length)
827
- throw invalid(issues);
828
- if (body.quote_id !== undefined)
829
- throw unsupported("quotes", "This server has no billing, so it takes no quotes.");
830
- // Each a ready file, before anything starts: copied into the run's work/inputs/ once its directory is made.
831
- const files = Array.isArray(body.file_ids) ? await uploads.readyFiles(body.file_ids) : [];
832
- const pinned = typeof body.revision === "string" ? await agents.revision(entry.agent.id, body.revision) : entry.revision && { revision: entry.revision, version: entry.version };
833
- if (!pinned)
834
- throw invalid([{ field: "revision", reason: "not_an_option", message: typeof body.revision === "string" ? `${body.revision} is not a revision of the agent ${entry.agent.id}` : `the agent ${entry.agent.id} has no current revision` }]);
835
- const { revision, version } = pinned;
836
- if (revision.kind === "workflow" && body.max_cost_usd !== undefined)
837
- throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "A workflow run's spend is not capped here: its cost shows once it ends." }]);
838
- const input = body.input;
839
- const wrong = await inputIssuesOf(revision, input);
840
- if (wrong.length)
841
- throw invalid(wrong);
842
- const place = resolvePlace(revision.body.place);
843
- await runnable(revision, place, { capped: body.max_cost_usd !== undefined });
844
- const title = revision.kind === "workflow" ? workflowTitle(entry.agent.name || entry.agent.id, input) : typeof input.content === "string" ? input.content : (Object.values(input).find((v) => typeof v === "string") ?? JSON.stringify(input));
845
- const run = await runs.create(entry, revision, version, { input, title, place, ...(typeof body.effort === "string" ? { effort: body.effort } : {}), ...(typeof body.max_cost_usd === "number" ? { maxCostUsd: body.max_cost_usd } : {}), ...(files.length ? { inputs: (work) => uploads.copyInto(work, files) } : {}) });
1088
+ return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
1089
+ // A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
1090
+ const first = origin && (await agents.request(() => agents.store.runOfOrigin(origin.key)));
1091
+ if (first) {
1092
+ if (first.existing?.fingerprint !== origin.fingerprint)
1093
+ throw mismatch();
1094
+ const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
1095
+ return { status: 202, body: await runs.view(await needRun(first.runId)), headers };
1096
+ }
1097
+ const run = await startRunOf(entry, body, { ...(origin ? { origin } : {}) });
846
1098
  // Its view from the run itself: it is written, with its first message, so an answer read from the store, which a
847
1099
  // busy store would turn into home_busy, would refuse a run that runs, and a retry would start a second one.
848
1100
  return { status: 202, body: await runs.view(run, { stored: null }), headers: { location: `/v2/runs/${run.id}` } };
849
1101
  });
850
1102
  }
1103
+ /** A run of `entry`'s agent from a create's body, checked as POST /agents/{id}/runs checks it: that route's, and a
1104
+ * trigger's firing's, which names itself as the run's `trigger`. Under `origin`, a key that already started a run
1105
+ * gets that run (the agent store's run_origins). */
1106
+ /** `capped`: the run must have a cap (a trigger's), its own or else its agent's default. */
1107
+ async function startRunOf(entry, body, { trigger, origin, capped = false } = {}) {
1108
+ const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "quote_id"]);
1109
+ if (!isObject(body.input))
1110
+ issues.push({ field: "input", reason: body.input === undefined ? "missing" : "wrong_type", message: "input is an object" });
1111
+ if (body.revision !== undefined && (typeof body.revision !== "string" || !ID.test(body.revision)))
1112
+ issues.push({ field: "revision", reason: "wrong_type", message: "revision is a revision id of this agent" });
1113
+ if (body.effort !== undefined && !EFFORTS.includes(body.effort))
1114
+ issues.push({ field: "effort", reason: "not_an_option", message: `effort is one of ${EFFORTS.join(", ")}` });
1115
+ if (body.max_cost_usd !== undefined && !(typeof body.max_cost_usd === "number" && body.max_cost_usd > 0 && Number.isFinite(body.max_cost_usd)))
1116
+ issues.push({ field: "max_cost_usd", reason: "wrong_type", message: "max_cost_usd is a number above 0" });
1117
+ if (body.file_ids !== undefined && !Array.isArray(body.file_ids))
1118
+ issues.push({ field: "file_ids", reason: "wrong_type", message: "file_ids is a list of file ids" });
1119
+ if (issues.length)
1120
+ throw invalid(issues);
1121
+ if (body.quote_id !== undefined)
1122
+ throw unsupported("quotes", "This server has no billing, so it takes no quotes.");
1123
+ // Each a ready file, before anything starts: copied into the run's work/inputs/ once its directory is made.
1124
+ const files = Array.isArray(body.file_ids) ? await uploads.readyFiles(body.file_ids) : [];
1125
+ const pinned = typeof body.revision === "string" ? await agents.revision(entry.agent.id, body.revision) : entry.revision && { revision: entry.revision, version: entry.version };
1126
+ if (!pinned)
1127
+ throw invalid([{ field: "revision", reason: "not_an_option", message: typeof body.revision === "string" ? `${body.revision} is not a revision of the agent ${entry.agent.id}` : `the agent ${entry.agent.id} has no current revision` }]);
1128
+ const { revision, version } = pinned;
1129
+ if (revision.kind === "workflow" && body.max_cost_usd !== undefined)
1130
+ throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "A workflow run's spend is not capped here: its cost shows once it ends." }]);
1131
+ const input = body.input;
1132
+ const wrong = await inputIssuesOf(revision, input);
1133
+ if (wrong.length)
1134
+ throw invalid(wrong);
1135
+ // The run's own cap, else the agent's default (an agentic revision's): the caller chose its own.
1136
+ const cap = typeof body.max_cost_usd === "number" ? body.max_cost_usd : revision.kind === "agentic" ? revision.body.maxCostUsd : undefined;
1137
+ if (capped && cap === undefined)
1138
+ throw invalid([{ field: "max_cost_usd", reason: "missing", message: "Every run a trigger starts is capped: give the trigger's target a max_cost_usd or set the agent's." }]);
1139
+ const place = resolvePlace(revision.body.place);
1140
+ await runnable(revision, place, { capped: cap !== undefined });
1141
+ // The title shows on the run's page, the runs list and Mission Control: built from its input as shown, each held
1142
+ // value redacted before a long one is cut (a cut key could no longer be found), and the run gets its input as given.
1143
+ const shown = redactedOutput(input, learningSecrets());
1144
+ const title = revision.kind === "workflow" ? workflowTitle(entry.agent.name || entry.agent.id, isObject(shown) ? shown : {}) : typeof input.content === "string" ? input.content : (Object.values(input).find((v) => typeof v === "string") ?? JSON.stringify(input));
1145
+ return runs.create(entry, revision, version, { input, title, place, ...(typeof body.effort === "string" ? { effort: body.effort } : {}), ...(cap !== undefined ? { maxCostUsd: cap } : {}), ...(trigger ? { trigger } : {}), ...(origin ? { origin } : {}), ...(files.length ? { inputs: (work) => uploads.copyInto(work, files) } : {}) });
1146
+ }
851
1147
  /** A page of runs from the store, newest first: `agent`, `revision` and `status` narrow it. */
852
1148
  /** A list's `archived`: true lists only what is archived, false (the default) only what is not. */
853
1149
  function archivedParam(url) {
@@ -1023,18 +1319,37 @@ async function startHolding(options, data, lock, checked, stops) {
1023
1319
  throw new ApiError("not_found", "no such file");
1024
1320
  }
1025
1321
  // ---- usage ----------------------------------------------------------------------------------------------------------
1026
- // Each ended run's meters, from its store (metersIn): kept, as its store no longer changes, keyed by its end, so a run
1322
+ // Each ended run's meters, from its store (meterFiguresIn): kept, as its store no longer changes, keyed by its end, so a run
1027
1323
  // opened again and ended again is read again. A store that cannot be read leaves it all tokens.
1028
1324
  const endedMeters = new Map();
1325
+ // Each ended run's spend so far as it saved it at its end (serve.json's cost_so_far: every conversation's charges and
1326
+ // its decisions' receipts, which its root store alone does not hold), kept as its meters are; undefined when it saved
1327
+ // none (a run whose cost is known, or one ended before the figure was kept).
1328
+ const endedSoFar = new Map();
1329
+ const savedSoFarOf = (row) => {
1330
+ const key = `${row.id} ${row.endedAt}`;
1331
+ if (!endedSoFar.has(key)) {
1332
+ let usd;
1333
+ try {
1334
+ const kept = JSON.parse(readFileSync(join(dirname(dirname(agents.store.runStorePath(row.id))), RUN_META), "utf8")).cost_so_far?.so_far_usd;
1335
+ usd = typeof kept === "number" && Number.isFinite(kept) ? kept : undefined;
1336
+ }
1337
+ catch {
1338
+ usd = undefined;
1339
+ }
1340
+ endedSoFar.set(key, usd);
1341
+ }
1342
+ return endedSoFar.get(key);
1343
+ };
1029
1344
  const metersOf = (row) => {
1030
1345
  const key = `${row.id} ${row.endedAt}`;
1031
1346
  let meters = endedMeters.get(key);
1032
1347
  if (!meters) {
1033
1348
  try {
1034
- meters = metersIn(agents.store.runStorePath(row.id));
1349
+ meters = meterFiguresIn(agents.store.runStorePath(row.id));
1035
1350
  }
1036
1351
  catch {
1037
- meters = { tools: 0, tokens: null };
1352
+ meters = { tools: 0, tokens: null, browser: { usd: 0, seconds: 0 }, others: 0, known: { tokens: 0, browser: 0, others: 0 } };
1038
1353
  }
1039
1354
  endedMeters.set(key, meters);
1040
1355
  }
@@ -1052,7 +1367,11 @@ async function startHolding(options, data, lock, checked, stops) {
1052
1367
  if (!["meter", "agent", "key", "day", "region"].includes(group))
1053
1368
  throw new ApiError("bad_request", "group_by is meter, agent, key, day or region");
1054
1369
  const lines = new Map();
1370
+ // Tool calls run with no price (an MCP tool its owner set none for): outside every cost, counted on `tools`.
1371
+ let notMetered = 0;
1055
1372
  const total = { usd: 0, unpriced: 0 };
1373
+ // The browser_time line's seconds: its ended runs' (their stores keep each charge's), none once a live run is in it.
1374
+ let browserSeconds = 0;
1056
1375
  // A cost that is unknown adds no dollars, so no sum turns unknown; it is counted as unpriced instead, so it never
1057
1376
  // passes as $0.
1058
1377
  const add = (key, usd) => {
@@ -1073,25 +1392,35 @@ async function startHolding(options, data, lock, checked, stops) {
1073
1392
  const live = row.state === "running" ? await runs.get(row.id) : null;
1074
1393
  const usd = live ? runs.cost(live).usd : (row.costUsd ?? null);
1075
1394
  const key = group === "agent" ? row.agent : group === "day" ? row.startedAt.slice(0, 10) : group === "meter" ? "tokens" : "local";
1076
- // By meter, what a run's paid tools charged (monid's) is `tools`, the rest `tokens`, both from the same records: a
1077
- // live run's rows (a call still marked is no charge), else its store as it ended (a call a crash cut makes `tools`
1078
- // unknown, never `tokens`). An unknown meter counts the run as unpriced on it.
1079
- const meters = group !== "meter" || usd === 0 ? undefined : live ? { tools: toolCostOf(live.rows), tokens: null } : metersOf(row);
1080
- const tokens = meters && (usd !== null && meters.tools !== null ? usd - meters.tools : usd === null && meters.tools === null ? meters.tokens : null);
1081
- const parts = !meters ? [[key, usd]] : [[key, tokens ?? null], ...(meters.tools !== 0 ? [["tools", meters.tools]] : [])];
1082
- // A run whose cost is unknown adds no dollars, so no sum turns unknown; it is counted as unpriced instead, so it
1083
- // never passes as $0.
1084
- for (const [name, part] of parts) {
1085
- const line = lines.get(name) ?? lines.set(name, { usd: 0, unpriced: 0 }).get(name);
1086
- if (part === null)
1395
+ // By meter, what a run's paid tools charged (monid's) is `tools`, its browser session time `browser_time`, the rest
1396
+ // `tokens`, all from the same records: a live run's rows (a call still marked is no charge), else its store as it
1397
+ // ended (a call a crash cut makes `tools` unknown, never `tokens`). An unknown meter counts the run as unpriced on it.
1398
+ // An ended run's are its store's figures (metersOf keeps them, never its timeline), read for its lines by meter and,
1399
+ // by any group, for what a run of unknown cost is known to have spent.
1400
+ const read = (group === "meter" && usd !== 0) || usd === null ? (live ? { tools: toolCostOf(live.rows), tokens: null, browser: { usd: toolCostOf(live.rows, "browser"), seconds: null }, others: toolCostOf(live.rows, "browser", true), known: { tokens: 0, browser: knownToolCostOf(live.rows, "browser"), others: knownToolCostOf(live.rows, "browser", true) } } : metersOf(row)) : undefined;
1401
+ // A run whose cost is unknown still spent what is known of it (so_far: each meter's known dollars): that is in the
1402
+ // total and its lines, and the run is counted unpriced, so a total is never below a line of its own and reads as
1403
+ // the lower bound unpriced_runs says it is.
1404
+ const soFar = usd !== null || !read ? 0 : live ? (runs.cost(live).so_far_usd ?? 0) : (savedSoFarOf(row) ?? read.known.tokens + read.known.browser + read.known.others);
1405
+ const meters = group === "meter" && usd !== 0 ? read : undefined;
1406
+ if (meters && meters.browser.usd !== 0)
1407
+ browserSeconds = browserSeconds === null || meters.browser.seconds === null ? null : browserSeconds + meters.browser.seconds;
1408
+ // Its parts of the lines (usage-lines.ts): an unknown one counts the run unpriced there and adds what is known of it.
1409
+ // An unpriced MCP call is in none of them: counted apart as not metered on the tools line, which a $0 run shows only
1410
+ // when it made one.
1411
+ const unmetered = group !== "meter" ? 0 : ((live ? live.rows.find((one) => one.kind === "usage")?.usage?.not_metered : metersOf(row).notMetered) ?? 0);
1412
+ notMetered += unmetered;
1413
+ if (unmetered && !lines.has("tools"))
1414
+ lines.set("tools", { usd: 0, unpriced: 0 });
1415
+ for (const part of runLines({ usd, soFar, key, meters })) {
1416
+ const line = lines.get(part.name) ?? lines.set(part.name, { usd: 0, unpriced: 0 }).get(part.name);
1417
+ line.usd += part.usd;
1418
+ if (part.unpriced)
1087
1419
  line.unpriced++;
1088
- else
1089
- line.usd += part;
1090
1420
  }
1091
1421
  if (usd === null)
1092
1422
  total.unpriced++;
1093
- else
1094
- total.usd += usd;
1423
+ total.usd += usd ?? soFar;
1095
1424
  }
1096
1425
  // What learning spent on this server, outside any run (usage.ts): each run's grade, on the day its learning ended.
1097
1426
  for (const entry of (await outcomes(data)).values()) {
@@ -1102,7 +1431,7 @@ async function startHolding(options, data, lock, checked, stops) {
1102
1431
  const round = (v) => Math.round(v * 1e6) / 1e6;
1103
1432
  return {
1104
1433
  from: new Date(from).toISOString(), to: new Date(to).toISOString(), currency: "USD", basis: "estimate", group_by: group, total_usd: round(total.usd), unpriced_runs: total.unpriced,
1105
- lines: [...lines].map(([key, line]) => ({ group: key, ...(group === "meter" ? { meter: key } : {}), usd: round(line.usd), unpriced_runs: line.unpriced })),
1434
+ lines: [...lines].map(([key, line]) => ({ group: key, ...(group === "meter" ? { meter: key } : {}), ...(key === "browser_time" && group === "meter" && browserSeconds !== null ? { quantity: round(browserSeconds), unit: "second" } : {}), usd: round(line.usd), unpriced_runs: line.unpriced, ...(group === "meter" && key === "tools" && notMetered ? { not_metered_calls: notMetered } : {}) })),
1106
1435
  account: null,
1107
1436
  };
1108
1437
  }
@@ -1227,6 +1556,9 @@ async function startHolding(options, data, lock, checked, stops) {
1227
1556
  return send(res, 200, forCaller(caps, byOwnerSession(req)));
1228
1557
  if (found.name === "getOpenapi")
1229
1558
  return send(res, 200, servedOpenapi(openapi, req.socket.localPort));
1559
+ // The one route with no token: a webhook trigger's request, checked by its signature before anything else is read.
1560
+ if (found.name === "receiveHook")
1561
+ return hook(req, res, path);
1230
1562
  if (found.name === "getHealth") {
1231
1563
  const health = await healthOf(data, minFreeBytes);
1232
1564
  return send(res, health.status === "ok" ? 200 : 503, health);
@@ -1236,10 +1568,21 @@ async function startHolding(options, data, lock, checked, stops) {
1236
1568
  // page cookie a token can mint (accounts off). The page's cookie stands in for the token only on its own origin
1237
1569
  // with a JSON body (page.ts), so this is CSRF-checked as every page write is. With no credential at all it is 401,
1238
1570
  // as every route is.
1571
+ // Restoring a retired one puts it back in every later run, as an approval does: the same owner's session alone.
1572
+ if (found.name === "restoreLearningFile" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
1573
+ authFailed(`/v2${path}`, "restore_without_session");
1574
+ throw new ApiError("forbidden", owner ? "Restoring a retired note takes the owner's password sign-in in the console, never a token." : "Restoring a retired note takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
1575
+ }
1239
1576
  if (found.name === "approveLearningFile" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
1240
1577
  authFailed(`/v2${path}`, "approve_without_session");
1241
1578
  throw new ApiError("forbidden", owner ? "Approving a note takes the owner's password sign-in in the console, never a token." : "Approving a note takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
1242
1579
  }
1580
+ // Answering a tool call that waits for approval (tool-gate.ts) is the same: the owner's signed-in page alone, never a
1581
+ // token, which the run's own process, an agent's MCP client or a script may hold.
1582
+ if (found.name === "answerApproval" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
1583
+ authFailed(`/v2${path}`, "approve_without_session");
1584
+ throw new ApiError("forbidden", owner ? "Answering a tool call's approval takes the owner's password sign-in in the console, never a token." : "Answering a tool call's approval takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
1585
+ }
1243
1586
  if (!timingSafeEqual(digest(String(req.headers.authorization ?? "")), expected)) {
1244
1587
  authFailed(`/v2${path}`, req.headers.authorization === undefined ? "no_credential" : "wrong_token");
1245
1588
  throw new ApiError("unauthenticated", "this route needs Authorization: Bearer <the token in the data directory>", {}, { "www-authenticate": "Bearer" });
@@ -1253,8 +1596,13 @@ async function startHolding(options, data, lock, checked, stops) {
1253
1596
  const body = await bodyOf(req);
1254
1597
  const answer = await idempotent(req, "/agents", body, async () => {
1255
1598
  let warnings = [];
1256
- const entry = await agents.create(checkDefinitionBody(body), async (revision) => void (warnings = await saveable(revision)));
1257
- return { status: 201, body: { ...agentView(entry), warnings }, headers: { location: `/v2/agents/${entry.agent.id}`, etag: etagOf(entry) } };
1599
+ // A new agent that names no place is given this server's box (place.ts newAgentPlace), stamped on its revision;
1600
+ // one that names a tool the box refuses (browser) keeps the runner, as before.
1601
+ const definition = checkDefinitionBody(body);
1602
+ const named = Array.isArray(definition.definition.tools) ? definition.definition.tools : [];
1603
+ const fresh = named.some((tool) => typeof tool === "string" && toolOf(tool)?.runnerOnly) ? { reason: "" } : newAgentPlace(boxOffers);
1604
+ const entry = await agents.create(definition, async (revision) => void (warnings = await saveable(revision)), "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined);
1605
+ return { status: 201, body: { ...agentView(entry, await signIns.view(entry.agent.id), await learningOfAgent(entry)), warnings }, headers: { location: `/v2/agents/${entry.agent.id}`, etag: etagOf(entry) } };
1258
1606
  });
1259
1607
  return send(res, answer.status, answer.body, answer.headers);
1260
1608
  }
@@ -1263,13 +1611,13 @@ async function startHolding(options, data, lock, checked, stops) {
1263
1611
  const offset = cursorOf(url.searchParams.get("cursor"));
1264
1612
  const archived = archivedParam(url);
1265
1613
  const all = (await agents.list()).filter((entry) => Boolean(entry.agent.archivedAt) === archived);
1266
- return send(res, 200, { agents: all.slice(offset, offset + limit).map((entry) => agentView(entry)), next_cursor: nextCursor(offset + limit, all.length) });
1614
+ return send(res, 200, { agents: await Promise.all(all.slice(offset, offset + limit).map(async (entry) => agentView(entry, await signIns.view(entry.agent.id), await learningOfAgent(entry)))), next_cursor: nextCursor(offset + limit, all.length) });
1267
1615
  }
1268
1616
  case "getAgent": {
1269
1617
  const entry = await needAgent(id);
1270
1618
  // The tools its current revision grants, as capabilities list them, each with its provider for this agent.
1271
1619
  const tools = entry.revision ? agentTools(env, settings.get(), await toolingOf(entry.revision), caps.tools.map((tool) => tool.name)) : [];
1272
- return send(res, 200, { ...agentView(entry), tools }, { etag: etagOf(entry) });
1620
+ return send(res, 200, { ...agentView(entry, await signIns.view(entry.agent.id), await learningOfAgent(entry)), tools }, { etag: etagOf(entry) });
1273
1621
  }
1274
1622
  case "updateDefinition": {
1275
1623
  const entry = await needAgent(id);
@@ -1292,7 +1640,7 @@ async function startHolding(options, data, lock, checked, stops) {
1292
1640
  let warnings = [];
1293
1641
  const check = async (revision) => void (warnings = await saveable(revision));
1294
1642
  const edited = await agents.commit(entry, checkDefinitionBody(contract ? { definition: body } : body, { creating: false }), { check, contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
1295
- return send(res, 200, { ...agentView(edited), warnings }, { etag: etagOf(edited) });
1643
+ return send(res, 200, { ...agentView(edited, await signIns.view(edited.agent.id), await learningOfAgent(edited)), warnings }, { etag: etagOf(edited) });
1296
1644
  }
1297
1645
  case "listRevisions": {
1298
1646
  const entry = await needAgent(id);
@@ -1314,7 +1662,7 @@ async function startHolding(options, data, lock, checked, stops) {
1314
1662
  if (!(await agents.revision(id, revision)))
1315
1663
  throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
1316
1664
  const moved = await agents.setCurrent(entry, revision);
1317
- return send(res, 200, agentView(moved), { etag: etagOf(moved) });
1665
+ return send(res, 200, agentView(moved, await signIns.view(moved.agent.id), await learningOfAgent(moved)), { etag: etagOf(moved) });
1318
1666
  }
1319
1667
  case "archiveAgent":
1320
1668
  case "unarchiveAgent": {
@@ -1323,7 +1671,18 @@ async function startHolding(options, data, lock, checked, stops) {
1323
1671
  if (found.name === "archiveAgent")
1324
1672
  await runs.archived();
1325
1673
  const entry = await needAgent(id);
1326
- return send(res, 200, agentView(entry), { etag: etagOf(entry) });
1674
+ return send(res, 200, agentView(entry, await signIns.view(entry.agent.id), await learningOfAgent(entry)), { etag: etagOf(entry) });
1675
+ }
1676
+ case "forgetSignIn": {
1677
+ await needAgent(id);
1678
+ let key;
1679
+ try {
1680
+ key = decodeURIComponent(second);
1681
+ }
1682
+ catch {
1683
+ throw new ApiError("bad_request", "the sign-in's key is not a valid path segment");
1684
+ }
1685
+ return send(res, 200, await signIns.forget(id, key));
1327
1686
  }
1328
1687
  case "createRun": {
1329
1688
  const answer = await createRun(req, id);
@@ -1363,6 +1722,24 @@ async function startHolding(options, data, lock, checked, stops) {
1363
1722
  });
1364
1723
  return send(res, answer.status, answer.body, answer.headers);
1365
1724
  }
1725
+ case "raiseRunCap": {
1726
+ const run = await needRun(id);
1727
+ const body = await bodyOf(req);
1728
+ const extra = unknownFields(body, ["max_cost_usd"]);
1729
+ if (extra.length)
1730
+ throw invalid(extra);
1731
+ const cap = body.max_cost_usd;
1732
+ if (!(typeof cap === "number" && Number.isFinite(cap) && cap > 0))
1733
+ throw invalid([{ field: "max_cost_usd", reason: cap === undefined ? "missing" : "wrong_type", message: "max_cost_usd is a number above 0" }]);
1734
+ if (run.kind === "workflow")
1735
+ throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "A workflow run's spend is not capped here, so it has no cap to raise." }]);
1736
+ const now = run.meta.max_cost_usd;
1737
+ if (now === undefined)
1738
+ throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "This run has no cap to raise: a cap is named when a run starts." }]);
1739
+ const { resumed, messageId, note } = await runs.raiseCap(run, cap);
1740
+ const { status, state } = statusOf(run);
1741
+ return send(res, 200, { run_id: run.id, max_cost_usd: cap, resumed, ...(messageId ? { message_id: messageId } : {}), ...(note ? { note } : {}), status, state });
1742
+ }
1366
1743
  case "stopRun": {
1367
1744
  const run = await needRun(id);
1368
1745
  const stopped = await runs.stop(run);
@@ -1375,6 +1752,21 @@ async function startHolding(options, data, lock, checked, stops) {
1375
1752
  const requested = await runs.cancel(run);
1376
1753
  return send(res, 202, { run_id: run.id, cancel_requested: requested, already_terminal: !requested, status: statusOf(run).status });
1377
1754
  }
1755
+ case "answerApproval": {
1756
+ // The owner's answer to a tool call that waits for approval (tool-gate.ts): the first answer wins.
1757
+ const run = await needRun(id);
1758
+ const body = await bodyOf(req);
1759
+ const issues = Object.keys(body).filter((k) => k !== "decision" && k !== "note").map((k) => ({ field: k, reason: "not_allowed", message: `The body keeps no field ${k}.` }));
1760
+ if (body.decision !== "allow" && body.decision !== "deny")
1761
+ issues.push({ field: "decision", reason: body.decision === undefined ? "missing" : "not_an_option", message: "decision is allow or deny" });
1762
+ if (body.note !== undefined && (typeof body.note !== "string" || body.note.length > 2000))
1763
+ issues.push({ field: "note", reason: "wrong_type", message: "note is a string of at most 2000 characters" });
1764
+ if (issues.length)
1765
+ throw invalid(issues);
1766
+ await runs.approve(run, decodeURIComponent(second), body.decision, typeof body.note === "string" && body.note.trim() ? body.note.trim() : undefined);
1767
+ res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
1768
+ return void res.end();
1769
+ }
1378
1770
  case "archiveRun":
1379
1771
  case "unarchiveRun": {
1380
1772
  const run = await needRun(id);
@@ -1450,7 +1842,7 @@ async function startHolding(options, data, lock, checked, stops) {
1450
1842
  const { issues, warnings } = await workflowIssues(body.workflow, body.tools);
1451
1843
  // What a save refuses on this host (a model node's tool, a code node where none runs), and what it lacks yet.
1452
1844
  if (!issues.length) {
1453
- for (const blocker of await blockersOf(env, { kind: "workflow", workflow: body.workflow, ...(body.tools ? { tools: body.tools } : {}) }, settings.get(), { offers }).catch(() => [])) {
1845
+ for (const blocker of await blockersOf(env, { kind: "workflow", workflow: body.workflow, ...(body.tools ? { tools: body.tools } : {}) }, settings.get(), { offers, mcp: mcpTools }).catch(() => [])) {
1454
1846
  if (blocker.host)
1455
1847
  warnings.push(blocker.message);
1456
1848
  else
@@ -1509,9 +1901,15 @@ async function startHolding(options, data, lock, checked, stops) {
1509
1901
  return send(res, 200, await usage(url));
1510
1902
  case "getStats": {
1511
1903
  const filter = analyticsFilter(url);
1512
- const [stats, analytics, rows] = await agents.request(() => [agents.store.stats(), agents.store.analytics(filter), agents.store.listRuns()]);
1904
+ // A run this server holds as ended whose end the store does not have yet is pending: counted as it ended, its
1905
+ // metrics left out until the store has them (stats.ts pendingOf).
1906
+ const [stats, analytics, rows, pending] = await agents.request(() => {
1907
+ const stats = agents.store.stats();
1908
+ const pending = pendingOf(stats.running, runs);
1909
+ return [stats, agents.store.analytics({ ...filter, pending }), agents.store.listRuns(), pending];
1910
+ });
1513
1911
  // How the runs that tried to learn fared: a held run's learning from memory, any other's end from the ledger.
1514
- return send(res, 200, { ...statsView(stats, runs), analytics: analyticsView(analytics, filter), learning: await runs.learning.counts(rows, filter) });
1912
+ return send(res, 200, { ...statsView(stats, runs, pending), analytics: analyticsView(analytics, filter), learning: await runs.learning.counts(rows, filter) });
1515
1913
  }
1516
1914
  case "listToolKeys":
1517
1915
  // The offers the server holds, not capabilities': a model key's row names the harnesses its key would run too.
@@ -1580,11 +1978,12 @@ async function startHolding(options, data, lock, checked, stops) {
1580
1978
  return sendNote(res, 200, await readNote(data, id, second, secretsShown(learningSecrets())));
1581
1979
  case "writeLearningFile":
1582
1980
  case "retireLearningFile":
1583
- case "approveLearningFile": {
1981
+ case "approveLearningFile":
1982
+ case "restoreLearningFile": {
1584
1983
  await needAgent(id);
1585
1984
  const header = (name) => (typeof req.headers[name] === "string" ? req.headers[name] : undefined);
1586
1985
  const body = found.name === "writeLearningFile" ? await noteBody(req, MAX_BODY) : undefined;
1587
- const written = await writeNote(data, id, second, { ifMatch: header("if-match"), ifNoneMatch: header("if-none-match"), body, refuse: learningSecrets(), approve: found.name === "approveLearningFile" });
1986
+ const written = await writeNote(data, id, second, { ifMatch: header("if-match"), ifNoneMatch: header("if-none-match"), body, refuse: learningSecrets(), approve: found.name === "approveLearningFile", restore: found.name === "restoreLearningFile" });
1588
1987
  // A name holding a secret (one the checks let by) is never echoed, not even as where the note is.
1589
1988
  const shown = secretsShown(learningSecrets());
1590
1989
  const located = written.status === 201 && shown.name(written.file) === written.file;
@@ -1610,6 +2009,40 @@ async function startHolding(options, data, lock, checked, stops) {
1610
2009
  return send(res, 200, webhooks.attemptsView());
1611
2010
  case "redeliverWebhook":
1612
2011
  return send(res, 200, await webhooks.redeliver(id));
2012
+ case "listTriggers":
2013
+ return send(res, 200, triggers.list());
2014
+ case "createTrigger": {
2015
+ const body = await bodyOf(req);
2016
+ // A webhook trigger's secret is in its first answer alone: the Idempotency-Key's record keeps the trigger and a
2017
+ // note, so a retry under the key gets the same trigger, never a second one, and never the secret.
2018
+ let secret;
2019
+ const answer = await idempotent(req, "/triggers", body, async () => {
2020
+ const { secret: shown, ...made } = await triggers.create(body);
2021
+ secret = shown;
2022
+ return { status: 201, body: shown ? { ...made, note: `Its secret was shown once, in the first answer; POST /v2/triggers/${made.id}/secret makes a new one.` } : made, headers: { location: `/v2/triggers/${made.id}` } };
2023
+ });
2024
+ const replayed = answer.headers?.["idempotent-replayed"] === "true";
2025
+ const { note: _, ...first } = answer.body;
2026
+ return send(res, answer.status, secret && !replayed ? { ...first, secret } : answer.body, answer.headers);
2027
+ }
2028
+ case "rotateTriggerSecret":
2029
+ return send(res, 200, triggers.rotate(id));
2030
+ case "getTrigger":
2031
+ return send(res, 200, triggers.get(id));
2032
+ case "updateTrigger":
2033
+ return send(res, 200, await triggers.update(id, await bodyOf(req)));
2034
+ case "deleteTrigger":
2035
+ triggers.remove(id);
2036
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
2037
+ case "fireTrigger": {
2038
+ const key = req.headers["idempotency-key"];
2039
+ if (typeof key !== "string" || key.length < 1 || key.length > 255)
2040
+ throw new ApiError("bad_request", "Running a trigger now takes an Idempotency-Key of 1 to 255 characters: a retry with the same key fires it once.");
2041
+ const fired = await triggers.fire(id, key);
2042
+ return send(res, fired.created ? 202 : 200, fired.firing, fired.created ? {} : { "idempotent-replayed": "true" });
2043
+ }
2044
+ case "listTriggerFirings":
2045
+ return send(res, 200, triggers.firings(id));
1613
2046
  }
1614
2047
  throw new ApiError("not_found", `no route ${path}`);
1615
2048
  }
@@ -1646,9 +2079,13 @@ async function startHolding(options, data, lock, checked, stops) {
1646
2079
  catch {
1647
2080
  return fail(new ApiError("bad_request", "the request target is not a URL"));
1648
2081
  }
1649
- // On loopback, a Host that is not a loopback name is a page that rebound a name of its own to this address.
1650
- if (names && !names.has(String(req.headers.host ?? "").toLowerCase()))
1651
- return fail(new ApiError("forbidden", "unexpected Host header"));
2082
+ // On loopback, a Host that is not one of its names (host-check.ts) is a page that rebound a name of its own to this
2083
+ // address. A browser is shown a page that says which names work; a script, the same in the error.
2084
+ if (names && !names.has(hostName(req.headers.host) ?? "")) {
2085
+ if (/\btext\/html\b/i.test(String(req.headers.accept ?? "")))
2086
+ return sendHostRefused(req, res);
2087
+ return fail(new ApiError("forbidden", `unexpected Host header: ${HOST_FIX}`));
2088
+ }
1652
2089
  // Routed on the path as sent: a parsed URL folds `..` and `%2E%2E` segments away, and a file path must see them.
1653
2090
  const raw = (req.url ?? "/").split("?")[0];
1654
2091
  // Before the page: its cookie must not stand in for the token on the owner's own routes, nor on the MCP endpoint.
@@ -1686,6 +2123,10 @@ async function startHolding(options, data, lock, checked, stops) {
1686
2123
  throw last > first ? Object.assign(new Error(`every port from ${first} to ${last} on ${host} is taken`), { code: "EADDRINUSE" }) : error;
1687
2124
  }
1688
2125
  }
2126
+ // The tool keys the server is started with, each checked once against its provider, in the background, once it
2127
+ // listens: a start that fails sends no check, and the start never waits on one. Capabilities are made again as each
2128
+ // answers (a refused one leaves its tools unavailable); close() aborts one still waiting. It never rejects.
2129
+ void toolKeys.checkServer(startFetch, stopping.signal, () => recompose()).catch(() => undefined);
1689
2130
  // Only a server that started takes up the import its owner asked for, or counts for setup's offer: one that failed to
1690
2131
  // listen hands back no close to stop them.
1691
2132
  if (offersImport && existsSync(importAsked))
@@ -1694,7 +2135,7 @@ async function startHolding(options, data, lock, checked, stops) {
1694
2135
  countSessions();
1695
2136
  const address = server.address();
1696
2137
  if (isLoopback(host))
1697
- names = new Set(["localhost", "127.0.0.1", "[::1]", host, ...(options.allowHosts ?? [])].map((h) => `${h.toLowerCase()}:${address.port}`));
2138
+ names = loopbackNames(host, options.allowHosts, options.publicUrl);
1698
2139
  // An address of every interface is reached on this machine at its loopback one.
1699
2140
  const shown = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
1700
2141
  const url = `http://${shown.includes(":") ? `[${shown}]` : shown}:${address.port}`;
@@ -1721,6 +2162,7 @@ async function startHolding(options, data, lock, checked, stops) {
1721
2162
  // count writes nothing (it lists and reads), so it is ended at once: its listing of a big home checks for no stop.
1722
2163
  closing = true;
1723
2164
  stopping.abort();
2165
+ triggers.close();
1724
2166
  for (const [worker, { task }] of workers) {
1725
2167
  if (task === "plan")
1726
2168
  void worker.terminate();
@@ -1734,6 +2176,8 @@ async function startHolding(options, data, lock, checked, stops) {
1734
2176
  await relay?.close();
1735
2177
  // Before the lock goes: the image's last record lands first (box-image.ts), never after the next server's start.
1736
2178
  await image?.close();
2179
+ // The box network proxy goes with the server that owns it (box-egress-vm.ts); its volume stays for the next start.
2180
+ await egress?.close();
1737
2181
  await webhooks.close();
1738
2182
  await new Promise((done) => (server.close(done), server.closeAllConnections()));
1739
2183
  agents.close();
@@ -1748,7 +2192,7 @@ async function startHolding(options, data, lock, checked, stops) {
1748
2192
  tokenFile,
1749
2193
  tokenMade: stored?.made ?? false,
1750
2194
  ...(setupUrl ? { setupUrl } : {}),
1751
- boxesLine: boxesLine(boxOffers, enabledBoxes(env)),
2195
+ boxesLine: boxesLine(boxOffers, enabledBoxes(env), boxAllow, boxesByDefault(env)),
1752
2196
  // Once: a second call, at any time, is the first one's promise, so a close repeated after the next server started
1753
2197
  // never writes this data root's record again (the next server's, by then).
1754
2198
  close: () => (stopped ??= stop()),