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

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 (199) hide show
  1. package/CHANGELOG.md +130 -0
  2. package/NOTICE +2 -0
  3. package/README.md +149 -21
  4. package/dist/agent-rows.d.ts +1 -1
  5. package/dist/agents-store.js +3 -1
  6. package/dist/api-only.d.ts +3 -1
  7. package/dist/api-only.js +4 -2
  8. package/dist/api-token.d.ts +30 -0
  9. package/dist/api-token.js +89 -0
  10. package/dist/calendar/address.d.ts +49 -0
  11. package/dist/calendar/address.js +153 -0
  12. package/dist/calendar/fetch.d.ts +24 -0
  13. package/dist/calendar/fetch.js +146 -0
  14. package/dist/calendar/ics-faux.d.ts +39 -0
  15. package/dist/calendar/ics-faux.js +236 -0
  16. package/dist/calendar/labels.d.ts +3 -0
  17. package/dist/calendar/labels.js +61 -0
  18. package/dist/calendar/names.d.ts +52 -0
  19. package/dist/calendar/names.js +54 -0
  20. package/dist/calendar/parse.d.ts +108 -0
  21. package/dist/calendar/parse.js +625 -0
  22. package/dist/calendar/routes.d.ts +17 -0
  23. package/dist/calendar/routes.js +81 -0
  24. package/dist/calendar/tools.d.ts +23 -0
  25. package/dist/calendar/tools.js +124 -0
  26. package/dist/cli.js +22 -6
  27. package/dist/composio-made.d.ts +54 -0
  28. package/dist/composio-made.js +83 -0
  29. package/dist/composio-preset.d.ts +16 -8
  30. package/dist/composio-preset.js +106 -43
  31. package/dist/composio-triggers.d.ts +7 -2
  32. package/dist/composio-triggers.js +13 -7
  33. package/dist/computer-attach.d.ts +29 -11
  34. package/dist/computer-attach.js +141 -47
  35. package/dist/computer-keys.d.ts +4 -0
  36. package/dist/computer-keys.js +5 -0
  37. package/dist/computer-record.d.ts +55 -0
  38. package/dist/computer-record.js +315 -0
  39. package/dist/computer-setting.d.ts +1 -0
  40. package/dist/computer-setting.js +15 -2
  41. package/dist/computers.d.ts +11 -1
  42. package/dist/computers.js +23 -26
  43. package/dist/console/assets/{index-B8Zn1Iqn.css → index-C3gNPz58.css} +1 -1
  44. package/dist/console/assets/index-DYJ_wj27.js +711 -0
  45. package/dist/console/index.html +2 -2
  46. package/dist/decisions.js +9 -2
  47. package/dist/eval-feed.d.ts +26 -0
  48. package/dist/eval-feed.js +72 -0
  49. package/dist/eval-mailbox.d.ts +4 -1
  50. package/dist/eval-mailbox.js +11 -3
  51. package/dist/exa-keyless.d.ts +1 -1
  52. package/dist/exa-keyless.js +1 -1
  53. package/dist/feed/feed-faux.d.ts +62 -0
  54. package/dist/feed/feed-faux.js +123 -0
  55. package/dist/feed/fetch.d.ts +41 -0
  56. package/dist/feed/fetch.js +128 -0
  57. package/dist/feed/parse.d.ts +42 -0
  58. package/dist/feed/parse.js +291 -0
  59. package/dist/feed/pointer.d.ts +2 -0
  60. package/dist/feed/pointer.js +17 -0
  61. package/dist/file-types.js +1 -0
  62. package/dist/host-command.d.ts +3 -0
  63. package/dist/host-command.js +18 -0
  64. package/dist/host.d.ts +3 -0
  65. package/dist/host.js +3 -0
  66. package/dist/learn/check.d.ts +17 -1
  67. package/dist/learn/check.js +240 -5
  68. package/dist/learn/compile.d.ts +48 -27
  69. package/dist/learn/compile.js +134 -101
  70. package/dist/learn/promote.d.ts +61 -5
  71. package/dist/learn/promote.js +12 -2
  72. package/dist/learned-nodes.d.ts +21 -4
  73. package/dist/learned-nodes.js +21 -8
  74. package/dist/learned-workflow.d.ts +3 -3
  75. package/dist/learned-workflow.js +14 -5
  76. package/dist/learning-setting.d.ts +23 -0
  77. package/dist/learning-setting.js +51 -0
  78. package/dist/learning-words.d.ts +3 -0
  79. package/dist/learning-words.js +3 -0
  80. package/dist/learning.d.ts +3 -2
  81. package/dist/learning.js +5 -3
  82. package/dist/mcp-oauth.d.ts +23 -1
  83. package/dist/mcp-oauth.js +46 -5
  84. package/dist/mcp-pin-first.d.ts +4 -2
  85. package/dist/mcp-pin-first.js +4 -3
  86. package/dist/mcp-private-hosts.d.ts +13 -0
  87. package/dist/mcp-private-hosts.js +16 -0
  88. package/dist/mcp-servers-store.d.ts +58 -5
  89. package/dist/mcp-servers-store.js +136 -17
  90. package/dist/mcp.d.ts +2 -2
  91. package/dist/mcp.js +2 -2
  92. package/dist/observation/http.d.ts +4 -1
  93. package/dist/observation/http.js +5 -4
  94. package/dist/openapi.d.ts +1 -0
  95. package/dist/openapi.js +151 -21
  96. package/dist/print.d.ts +6 -3
  97. package/dist/print.js +4 -2
  98. package/dist/run-files.d.ts +6 -2
  99. package/dist/run-files.js +29 -7
  100. package/dist/run-labels.d.ts +23 -0
  101. package/dist/run-labels.js +79 -0
  102. package/dist/run-learning-served.d.ts +1 -1
  103. package/dist/run-reads-over-store.d.ts +5 -1
  104. package/dist/run-reads-over-store.js +8 -4
  105. package/dist/run-recordings.d.ts +20 -0
  106. package/dist/run-recordings.js +133 -0
  107. package/dist/run-secrets.js +12 -4
  108. package/dist/runner/adapter-loop.d.ts +1 -1
  109. package/dist/runner/adapter-loop.js +94 -16
  110. package/dist/runner/adapter-run-spec.d.ts +19 -0
  111. package/dist/runner/adapter-run-spec.js +57 -36
  112. package/dist/runner/beside.d.ts +6 -3
  113. package/dist/runner/beside.js +9 -7
  114. package/dist/runner/cli-run-spec.js +41 -32
  115. package/dist/runner/conformance/harness.js +69 -14
  116. package/dist/runner/conformance/subject.d.ts +4 -1
  117. package/dist/runner/feedback-round.d.ts +9 -25
  118. package/dist/runner/feedback-round.js +22 -40
  119. package/dist/runner/learning-end.d.ts +17 -7
  120. package/dist/runner/learning-end.js +79 -53
  121. package/dist/runner/main.d.ts +12 -1
  122. package/dist/runner/main.js +31 -4
  123. package/dist/runner/mcp-claim.d.ts +3 -0
  124. package/dist/runner/mcp-claim.js +1 -1
  125. package/dist/runner/mcp-run.d.ts +6 -2
  126. package/dist/runner/mcp-run.js +5 -3
  127. package/dist/runner/model-route.d.ts +4 -2
  128. package/dist/runner/model-route.js +8 -8
  129. package/dist/runner/promotion.d.ts +44 -4
  130. package/dist/runner/promotion.js +323 -21
  131. package/dist/runner/reflect-hook.d.ts +5 -0
  132. package/dist/runner/reflect-hook.js +22 -14
  133. package/dist/runner/store-secrets.js +3 -1
  134. package/dist/runner/workflow-first.d.ts +6 -11
  135. package/dist/runner/workflow-first.js +16 -20
  136. package/dist/runs-over-store.d.ts +1 -1
  137. package/dist/runs-over-store.js +5 -2
  138. package/dist/sdk/runs.d.ts +7 -1
  139. package/dist/sdk/runs.js +21 -7
  140. package/dist/secret-cut.js +3 -1
  141. package/dist/secrets.js +5 -3
  142. package/dist/server.d.ts +31 -5
  143. package/dist/server.js +240 -61
  144. package/dist/store/agent-body.d.ts +5 -3
  145. package/dist/store/agent-body.js +14 -10
  146. package/dist/store/dialect.d.ts +3 -0
  147. package/dist/store/dialect.js +1 -0
  148. package/dist/store/index.d.ts +1 -1
  149. package/dist/store/postgres/dialect.js +1 -0
  150. package/dist/store/postgres/migrations/0015_run_labels.sql +5 -0
  151. package/dist/store/postgres/migrations/0016_minted_tokens.sql +21 -0
  152. package/dist/store/schema.d.ts +9 -0
  153. package/dist/store/schema.js +26 -2
  154. package/dist/store/sqlite/connection.js +11 -3
  155. package/dist/store/sqlite/run-patch.d.ts +2 -1
  156. package/dist/store/sqlite/run-patch.js +3 -2
  157. package/dist/store/sqlite/store.js +64 -10
  158. package/dist/store/store.d.ts +38 -1
  159. package/dist/store-reads/journal.js +2 -1
  160. package/dist/store-reads/learning.d.ts +1 -1
  161. package/dist/store-reads/learning.js +6 -1
  162. package/dist/store-reads/loop.d.ts +1 -0
  163. package/dist/store-reads/loop.js +14 -4
  164. package/dist/store-reads/runs.d.ts +4 -3
  165. package/dist/store-reads/runs.js +3 -2
  166. package/dist/store-view.d.ts +5 -0
  167. package/dist/store-view.js +8 -2
  168. package/dist/template-eval.d.ts +11 -0
  169. package/dist/template-eval.js +177 -52
  170. package/dist/templates.d.ts +13 -1
  171. package/dist/templates.js +89 -18
  172. package/dist/timeline/computer.js +2 -1
  173. package/dist/timeline/origin.d.ts +1 -1
  174. package/dist/timeline/origin.js +2 -2
  175. package/dist/tool-list.js +1 -0
  176. package/dist/tools.d.ts +7 -0
  177. package/dist/tools.js +11 -0
  178. package/dist/trigger-adapter.d.ts +9 -4
  179. package/dist/trigger-adapters.js +2 -1
  180. package/dist/trigger-feed.d.ts +12 -0
  181. package/dist/trigger-feed.js +420 -0
  182. package/dist/triggers.d.ts +2 -1
  183. package/dist/triggers.js +23 -5
  184. package/dist/validate.js +7 -2
  185. package/dist/webhooks.js +9 -5
  186. package/dist/workspace/computer-deps.d.ts +5 -1
  187. package/dist/workspace/computer-deps.js +2 -2
  188. package/dist/workspace/computer-for-claim.d.ts +7 -0
  189. package/dist/workspace/computer-for-claim.js +12 -2
  190. package/dist/workspace/index.d.ts +1 -0
  191. package/dist/workspace/index.js +2 -0
  192. package/dist/workspace/paths.d.ts +4 -0
  193. package/dist/workspace/paths.js +9 -0
  194. package/dist/workspace/resolve-computer.d.ts +35 -4
  195. package/dist/workspace/resolve-computer.js +47 -9
  196. package/launcher/agentrun-serve +34 -22
  197. package/package.json +11 -9
  198. package/templates/README.md +38 -4
  199. package/dist/console/assets/index-Jbxjcmdp.js +0 -705
package/dist/server.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { maintainObservations, Observations } from './observation/observer.js';
2
2
  import { isObservationRoute, observationHttp } from './observation/http.js';
3
- import { SdkRuns, sdkOf } from "./sdk/runs.js";
3
+ import { SdkRuns, sdkOf, sdkRunSecret } from "./sdk/runs.js";
4
4
  import { gradeRouteFor } from "./runner/harness-loops.js";
5
5
  import { routeOf as sdkModelRoute } from "./runner/model-route.js";
6
6
  import { answerSkill } from './skill-route.js';
@@ -12,7 +12,7 @@ import { isNativeRuntime } from "./native/runtimes.js";
12
12
  import { connectNative, launchNative, updateNative, verifyConnection } from "./native/connection.js";
13
13
  // The /v2 API over the agent store in a data directory: the contract agentrun.v2/0, served on loopback with a bearer
14
14
  // token.
15
- import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
15
+ import { createHash, randomBytes } from "node:crypto";
16
16
  import { chmod, lstat, mkdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises";
17
17
  import { createServer } from "node:http";
18
18
  import proxyaddr from "proxy-addr";
@@ -41,7 +41,7 @@ import { chooseModel, EFFORTS, FAUX_ENV, FAUX_UPSTREAM_ENV, MODEL_NODES, modelSo
41
41
  import { DEFAULT_HARNESS, HARNESSES, harnessOfBody, harnessOffers } from "./harness.js";
42
42
  import { HARNESS_TABLE_ENV, harnessOf } from "./harness-table.js";
43
43
  import { HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./harness-install.js";
44
- import { healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
44
+ import { DEFAULT_PORT, healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
45
45
  import { IMPORT_ASKED } from "./import.js";
46
46
  import { answerStoreCall } from "./import-proxy.js";
47
47
  import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningFolderOf, learningOf, learnsOf, RUN_LEARNING_USE, seedOf } from "./learning.js";
@@ -53,7 +53,8 @@ import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPl
53
53
  import { boxAllowOf, boxAllowSetIn } from "./box-settings.js";
54
54
  import { dockerLimitsOf } from "./workspace/computer-deps.js";
55
55
  import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
56
- import { answerPage, byOwnerSession, ConsoleSessions, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
56
+ import { acceptedTokens, bearerCheck, tokenProblem } from "./api-token.js";
57
+ import { answerPage, byConsoleSession, byOwnerSession, ConsoleSessions, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
57
58
  import { hostFix, hostName, loopbackNames } from "./host-check.js";
58
59
  import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile, viewerAnswers } from "./browser-live.js";
59
60
  import { browserHandBack, handBackTarget } from "./browser-commands.js";
@@ -72,6 +73,7 @@ import { runCutValues } from "./run-cut.js";
72
73
  import { readLaunchBody } from "./run-launch.js";
73
74
  import { listRunFiles as listRunFilesOverStore, readRunFile as readRunFileOverStore, runGraphView, runTimelines } from "./run-reads-over-store.js";
74
75
  import { triggerTargets } from "./trigger-targets.js";
76
+ import { labelFilter, labelsIssues } from "./run-labels.js";
75
77
  import { listRuns as listRunsOverStore, readRun as readRunOverStore, runOfOrigin as runOfOriginOverStore } from "./store-reads/runs.js";
76
78
  import { runEntries } from "./store-reads/journal.js";
77
79
  import { metersOverStore } from "./store-reads/cap.js";
@@ -115,12 +117,12 @@ import { signInsOverStore } from "./sign-ins-store.js";
115
117
  import { boundTool, MCP_AUTH_TYPES, marked, mcpAuthOf, nameOf as mcpNameOf } from "./mcp-probe.js";
116
118
  import { composioForget, composioNote, composioSave, composioTools } from "./composio-preset.js";
117
119
  import { ComposioTriggers } from "./composio-triggers.js";
118
- import { mcpServersOverStore } from "./mcp-servers-store.js";
120
+ import { loopbackWords, mcpServersOverStore } from "./mcp-servers-store.js";
119
121
  import { getMcpServer, listMcpServers } from "./mcp-store.js";
120
- import { privateHostsRoute } from "./mcp-private-hosts.js";
122
+ import { privateHostsRoute, saveServerOwn } from "./mcp-private-hosts.js";
121
123
  import { metaToolOf } from "./mcp-meta.js";
122
124
  import { mcpPinOf } from "./mcp-gateway.js";
123
- import { MCP_SETTINGS_PAGE, signInCookie, startedHere } from "./mcp-oauth.js";
125
+ import { LOOPBACK, MCP_SETTINGS_PAGE, signInCookie, startedHere } from "./mcp-oauth.js";
124
126
  import { WEBHOOK_EVENTS, WEBHOOK_FILE, waitMarkerOf, Webhooks } from "./webhooks.js";
125
127
  import { appPermissionWarnings } from "./template-github-permissions.js";
126
128
  import { templateApplied, templateTriggerSecret, templateWebhookSecrets, triggerMade, triggerRotated, webhookSaved, withTriggerSecret } from "./trigger-secrets-shown.js";
@@ -138,7 +140,7 @@ import { permissionFrom, pinnedEffect, toolEffect } from "./tool-gate.js";
138
140
  import { mcpNameOf as mcpToolOf, mcpToolName } from "./tool-names.js";
139
141
  import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
140
142
  import { PAYLOAD_KEPT_BYTES } from "./trigger-adapter.js";
141
- import { applyBodyOf, choiceUnrunnable, COMPOSIO_TRIGGER_FIX, composioTriggerSkipped, COMPUTER_FIX, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, mcpSetUp, onServerName, onServers, packageDetail, packageModel, packageTiers, packageView, pickComputer, readPackages, notSetUpYet, serversFor, TemplateRegistry } from "./templates.js";
143
+ import { applyBodyOf, choiceUnrunnable, COMPOSIO_TRIGGER_FIX, composioTriggerSkipped, COMPUTER_FIX, compiled, feedLeftEmpty, feedTriggerEmpty, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, mcpSetUp, onServerName, onServers, packageDetail, packageModel, packageTiers, packageView, pickComputer, readPackages, notSetUpYet, serversFor, TemplateRegistry } from "./templates.js";
142
144
  import { deleteTemplate, importTemplate, loadImported } from "./template-import.js";
143
145
  import { templateInstallLink, templateLink } from "./console-links.js";
144
146
  import { GITHUB_HOSTS } from "./template-source.js";
@@ -149,6 +151,8 @@ import { toolSettingsOverStore } from "./tool-settings-store.js";
149
151
  import { readApprovers, writeApprovers } from "./server-approvers.js";
150
152
  import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
151
153
  import { entryAt, listFiles, sendFile as sendWorkspaceFile, viewOf } from "./run-files.js";
154
+ import { recordingsOf, recordingsWorkspace } from "./run-recordings.js";
155
+ import { recordingsFolder } from "./workspace/paths.js";
152
156
  import { heldRoute, holdIssues, runComputerRead } from "./computer-held-routes.js";
153
157
  import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runComputerKind } from "./computer-routes.js";
154
158
  import { ATTACH_PATH, AttachHub, PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
@@ -159,17 +163,19 @@ import { freeModelRequestsOf } from "@parcha/agentrun-kernel/kernel/cap";
159
163
  import { archilRoute, createArchilRoutes, liveRunsOnDisk } from "./archil-routes.js";
160
164
  import { noAccount, openAccount } from "./email/account.js";
161
165
  import { emailRoute } from "./email/routes.js";
166
+ import { addressForms, openCalendar } from "./calendar/address.js";
167
+ import { calendarRoute } from "./calendar/routes.js";
162
168
  import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode } from "./archil-settings.js";
163
169
  import { computerOfPlace } from "./computer-setting.js";
164
170
  import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
165
171
  import { fauxComputers } from "./faux-computers.js";
166
172
  import { writesHeld } from "./workspace.js";
167
- import { agentComputerOf, agentComputerView, agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, reconcileAgentComputer, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
173
+ import { agentComputerOf, agentComputerView, agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, reconcileAgentComputer, registryHere, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
168
174
  import { keyReader } from "./key-meta.js";
169
175
  export const CONTRACT = "agentrun.v2/0";
170
176
  /** A process's flags for a worker of it: without --input-type and the code string given with -e, --eval, -p or --print. */
171
177
  const workerArgs = (args) => args.filter((arg, i) => !arg.startsWith("--input-type") && !/^(?:-e|--eval|-p|--print)(?:=|$)/.test(arg) && !/^(?:-e|--eval|-p|--print)$/.test(args[i - 1] ?? ""));
172
- export const DEFAULT_PORT = 7340;
178
+ export { DEFAULT_PORT };
173
179
  const VERSION = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8")).version;
174
180
  const IDEMPOTENCY_FILE = ".idempotency.json";
175
181
  /** A run's live viewer, under the run's path (browser-live.ts): its run id, the family's address (`computer`, one for every
@@ -221,7 +227,6 @@ async function tokenIn(file) {
221
227
  await writeDurable(file, `${token}\n`, 0o600, undefined, true);
222
228
  return { token, made: true };
223
229
  }
224
- const digest = (text) => createHash("sha256").update(text).digest();
225
230
  const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
226
231
  const SESSION_S = SESSION_MS / 1000;
227
232
  export const ROUTES = [
@@ -309,6 +314,8 @@ export const ROUTES = [
309
314
  { method: "POST", pattern: /^\/computers\/pairings$/, name: "createPairing" },
310
315
  { method: "POST", pattern: /^\/computers\/pair$/, name: "pairComputer" },
311
316
  { method: "GET", pattern: /^\/computers\/attach$/, name: "attachComputer" },
317
+ // A hosted machine's computerd build, fetched at its boot with the token its create minted (computer-attach.ts daemon).
318
+ { method: "GET", pattern: /^\/computers\/daemon$/, name: "getComputerDaemon" },
312
319
  { method: "DELETE", pattern: /^\/computers\/([^/]+)$/, name: "deleteComputer" },
313
320
  { method: "GET", pattern: /^\/workspace\/archil$/, name: "getWorkspaceArchil" },
314
321
  { method: "PUT", pattern: /^\/workspace\/archil$/, name: "putWorkspaceArchil" },
@@ -331,6 +338,11 @@ export const ROUTES = [
331
338
  { method: "PUT", pattern: /^\/settings\/email$/, name: "saveEmailAccount" },
332
339
  { method: "DELETE", pattern: /^\/settings\/email$/, name: "deleteEmailAccount" },
333
340
  { method: "POST", pattern: /^\/settings\/email\/test$/, name: "testEmailAccount" },
341
+ // The server's calendar (calendar/routes.ts): the owner's session's alone, its address in no answer.
342
+ { method: "GET", pattern: /^\/settings\/calendar$/, name: "getCalendar" },
343
+ { method: "PUT", pattern: /^\/settings\/calendar$/, name: "saveCalendar" },
344
+ { method: "DELETE", pattern: /^\/settings\/calendar$/, name: "deleteCalendar" },
345
+ { method: "POST", pattern: /^\/settings\/calendar\/test$/, name: "testCalendar" },
334
346
  { method: "GET", pattern: /^\/settings\/chatgpt$/, name: "getChatGPTSignIn" },
335
347
  { method: "DELETE", pattern: /^\/settings\/chatgpt$/, name: "signOutChatGPT" },
336
348
  { method: "POST", pattern: /^\/settings\/chatgpt\/sign-in$/, name: "startChatGPTSignIn" },
@@ -580,7 +592,7 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
580
592
  runs: { stop: true, cancel: true, kill: false, list: true, kinds: ["agentic", "workflow"], pause_workflow_runs: true, graph: true },
581
593
  messages: { steer: true, answer: true, follow_up: true, steer_workflow_runs: false },
582
594
  timeline: { long_poll: true, sse: true, live_rows: true, live_workflow_rows: false },
583
- files: { upload: true, read: true, range: false, during_run: true },
595
+ files: { upload: true, read: true, range: true, during_run: true },
584
596
  quotes: false,
585
597
  usage: { basis: "estimate", meters: ["tokens", "tools", "browser_time", "learning"] },
586
598
  efforts: [...EFFORTS],
@@ -672,8 +684,17 @@ export async function startServe(options) {
672
684
  await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
673
685
  // Canonical once, here: a computer's mount source below it must then be its own canonical path, through no link.
674
686
  const data = await realpath(resolve(options.data));
675
- if (options.token !== undefined && (options.token.length < 32 || /\s/.test(options.token)))
676
- throw new Error("the token must be 32 characters or more, with no whitespace");
687
+ const tokenRefused = options.token === undefined ? undefined : tokenProblem(options.token);
688
+ if (tokenRefused)
689
+ throw new Error(tokenRefused);
690
+ for (const entry of options.tokens ?? []) {
691
+ const refused = tokenProblem(entry.token, `the API token ${entry.id}`);
692
+ if (refused)
693
+ throw new Error(refused);
694
+ }
695
+ // Ids each once, secrets each once (api-token.ts), checked before any lock is taken.
696
+ if (options.token !== undefined || (options.tokens?.length ?? 0) > 0)
697
+ acceptedTokens(options.token, options.tokens);
677
698
  if (options.drainTimeout !== undefined && durationMs(options.drainTimeout) === undefined)
678
699
  throw new Error(`the drain timeout ${options.drainTimeout} is not a duration such as 8s`);
679
700
  enabledBoxes(process.env);
@@ -796,7 +817,7 @@ async function startHolding(options, data, checked, stops) {
796
817
  // which the runner beside the server shares (Serve.attachHub), so one process holds them. A second server on this
797
818
  // store is refused above (its owner lock).
798
819
  const attachHub = new AttachHub();
799
- const attach = createAttachRoutes({ store, hub: attachHub, log: (event, fields) => (log ? log(logLine(event, fields)) : void process.stderr.write(`agentrun-serve: ${logLine(event, fields)}\n`)) });
820
+ const attach = createAttachRoutes({ store, hub: attachHub, machinesOnly: options.apiOnly === true, log: (event, fields) => (log ? log(logLine(event, fields)) : void process.stderr.write(`agentrun-serve: ${logLine(event, fields)}\n`)) });
800
821
  // The data root's own lock, once the store is held (so a deploy on Postgres waits at the store's owner lock first): the
801
822
  // store's lock holds one store, but the data root also holds what the server writes beside it (its token, its seal key,
802
823
  // uploads, harness installs, learning folders), which two servers on two stores (two Postgres schemas, or SQLite and
@@ -806,13 +827,17 @@ async function startHolding(options, data, checked, stops) {
806
827
  const dataLock = await whileReplaced(() => takeServerLock(data), (error) => error instanceof ServerLockHeldError, Math.max(replacedUntil, Date.now() + START_WAIT_MARGIN_MS), waitingForReplaced);
807
828
  stops.push(async () => dataLock.release());
808
829
  // The token, once both locks are held: a start the locks refuse reads, makes and removes nothing in the data root.
809
- const tokenFile = options.token === undefined ? join(data, TOKEN_FILE) : null;
810
- const stored = options.token === undefined ? await tokenIn(tokenFile) : undefined;
811
- const token = options.token ?? stored.token;
812
- // Given a token (AGENTRUN_TOKEN), a .token an earlier start made holds one this server refuses: it goes, so nothing
830
+ // Given a token list (AGENTRUN_TOKENS), DIR/.token is no token of this server's, as with AGENTRUN_TOKEN.
831
+ const given = options.token !== undefined || (options.tokens?.length ?? 0) > 0;
832
+ const tokenFile = given ? null : join(data, TOKEN_FILE);
833
+ const stored = given ? undefined : await tokenIn(tokenFile);
834
+ // Every token this server takes, by id (api-token.ts): AGENTRUN_TOKEN's (or DIR/.token's) as `default`, then the list's.
835
+ const tokens = acceptedTokens(options.token ?? stored?.token, options.tokens);
836
+ const token = tokens[0].token;
837
+ // Given a token (AGENTRUN_TOKEN or AGENTRUN_TOKENS), a .token an earlier start made holds one this server refuses: it goes, so nothing
813
838
  // (a person told the token is there, a CLI that reads it) takes a dead token from it. A later start without one makes a
814
839
  // new file and token.
815
- if (options.token !== undefined)
840
+ if (given)
816
841
  await rm(join(data, TOKEN_FILE), { force: true });
817
842
  // No start without a seal key (seal-key.ts), checked against the store before anything reads it: the one handed over,
818
843
  // else the one in the data directory beside the store, made at the first start with only its path printed. A store whose
@@ -967,6 +992,8 @@ async function startHolding(options, data, checked, stops) {
967
992
  const adapters = options.triggerAdapters ?? TRIGGER_ADAPTERS;
968
993
  const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability, adapters);
969
994
  const sealKey = seal.key;
995
+ // SDK runs' credentials are signed with a key from the seal key, never an API token: a rotation leaves them working.
996
+ const sdkSecret = sdkRunSecret(sealKey);
970
997
  // Its runners on other hosts (AGENTRUN_RUNNER_HOSTS): a viewer's row naming one of their hosts is dialled there, with
971
998
  // the proxy's proof under the seal key (live-reach.ts); any other host is never dialled.
972
999
  const reach = liveReachOf(env, sealKey);
@@ -1009,7 +1036,9 @@ async function startHolding(options, data, checked, stops) {
1009
1036
  // probe Docker: a provider whose program is missing is not ready, and its words say what to install.
1010
1037
  const hostWhy = hostCommandRefusals(COMPUTER_PROVIDERS, process.env.PATH);
1011
1038
  const computersOf = () => (computerRoutes ??= createComputerRoutes({
1012
- store, sealKey, tools: kindTools, mode: folderModeOf(store, process.env), env: process.env,
1039
+ // A provider's key set where the server starts is one of its secrets, held off process.env (secrets.ts): read by name
1040
+ // from what the server was started with, as computerReady below reads it.
1041
+ store, sealKey, tools: kindTools, mode: folderModeOf(store, process.env), env: withSecrets(process.env, "own"),
1013
1042
  paired: { rows: () => store.pairedComputers.list(), viewOf: (row, serves) => pairedView(row, attachHub, serves) },
1014
1043
  ...(options.faux
1015
1044
  // --faux's providers stand in for every vendor's, a local one's daemon included.
@@ -1033,6 +1062,8 @@ async function startHolding(options, data, checked, stops) {
1033
1062
  const modeNow = async () => ((await folderModeOf(store, process.env)()) === "disk" ? 2 : 1);
1034
1063
  /** The registry a run's claim resolves against (claimKinds), as its runner composes it. */
1035
1064
  const claimRegistry = () => claimKinds(options.faux ? { faux: fauxOf() } : {});
1065
+ /** A key as the runner reads it: the secrets this process was started with (withSecrets "own"), else the saved one. */
1066
+ const runnerKeys = () => keyReader(store, sealKey, own(withSecrets(process.env, "own")));
1036
1067
  // A paired computer is one more provider of the registry (workspace/attached-computers.ts), ready while its driver is
1037
1068
  // attached to this process's hub.
1038
1069
  const computerReady = async (setting) => {
@@ -1041,12 +1072,12 @@ async function startHolding(options, data, checked, stops) {
1041
1072
  const offline = row ? pairedRefusal(row, attachHub) : undefined;
1042
1073
  if (offline)
1043
1074
  return { refused: offline };
1044
- return computerReadiness(setting, await modeNow(), withPaired(claimRegistry(), paired), keyReader(store, sealKey, own(withSecrets(process.env, "own"))), dockerAnswers, boxAllow, (provider) => (Object.hasOwn(hostWhy, provider) ? hostWhy[provider] : undefined));
1075
+ return computerReadiness(setting, await modeNow(), withPaired(claimRegistry(), paired), runnerKeys(), dockerAnswers, boxAllow, (provider) => (Object.hasOwn(hostWhy, provider) ? hostWhy[provider] : undefined));
1045
1076
  };
1046
1077
  /** Where a run of an agent with computer `setting` has its shell here now (resolve-computer.ts runShellOf, in the
1047
1078
  * folder mode of now, over the registry the claim reads): what runnable.ts lets a sandbox-only tool on the runner by,
1048
1079
  * and capabilities show bash by. In Mode 2 a run with no computer has bash on Archil's serverless exec. */
1049
- const shellOf = async (setting) => runShellOf(setting, await modeNow(), setting.provider === undefined ? claimRegistry() : withPaired(claimRegistry(), await store.pairedComputers.list()));
1080
+ const shellOf = async (setting) => runShellOf(setting, await modeNow(), await registryHere(setting.provider === undefined ? claimRegistry() : withPaired(claimRegistry(), await store.pairedComputers.list()), runnerKeys()));
1050
1081
  /** The shell this server can give a template's agent now (templates.ts pickComputer's `shell`), by the rules a run
1051
1082
  * has it by (shellOf): Archil's serverless exec on the runner in Mode 2 (bash alone); else the box a new agent is saved
1052
1083
  * with (Docker), where it answers now (computerReady asks the daemon, not the start's offers: a Docker stopped since
@@ -1079,7 +1110,8 @@ async function startHolding(options, data, checked, stops) {
1079
1110
  return { entry: pick.entry, computer: pick.computer, shell: pick.shell, dropped: pick.dropped, note: pick.note };
1080
1111
  };
1081
1112
  };
1082
- const archil = createArchilRoutes({ store, sealKey, env: process.env, ...(options.archilControl ? { control: options.archilControl } : {}) });
1113
+ // ARCHIL_API_KEY set where the server starts is one of its secrets, held off process.env (secrets.ts): read by name.
1114
+ const archil = createArchilRoutes({ store, sealKey, env: withSecrets(process.env, "own"), ...(options.archilControl ? { control: options.archilControl } : {}) });
1083
1115
  /** Where a run of `revision` has its shell (shellOf): its computer setting as the claim reads it (computer-for-claim.ts
1084
1116
  * settingOf), else its place's computer, else the place its run would resolve to (fallbackPlace). The agent's tool
1085
1117
  * list reads it, so a tool of bash's family the run would not have shows unavailable (tool-plane.ts shellUnavailable). */
@@ -1113,7 +1145,7 @@ async function startHolding(options, data, checked, stops) {
1113
1145
  close: () => store.close(),
1114
1146
  };
1115
1147
  ({ secrets: secretStores, settings: triggerSettings } = await openServerSecretsOverStore(store, data, env, adapters, (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`))));
1116
- secretStores.add("server", () => [token]);
1148
+ secretStores.add("server", () => tokens.map((entry) => entry.token));
1117
1149
  // The email account's password (email/account.ts), and each one saved since this server started: cut from everything
1118
1150
  // it shows, so a tool's error or a model's text that ever echoed it shows it nowhere.
1119
1151
  const emailPasswords = new Set();
@@ -1124,12 +1156,24 @@ async function startHolding(options, data, checked, stops) {
1124
1156
  };
1125
1157
  await heldEmailPassword();
1126
1158
  secretStores.add("email", () => [...emailPasswords]);
1159
+ // The calendar's iCal address (calendar/address.ts), in each of its forms, and each one saved since this server started:
1160
+ // the address reads the calendar, so it is cut from everything the server shows, as a password is.
1161
+ const calendarAddresses = new Set();
1162
+ const heldCalendar = async () => {
1163
+ const url = (await openCalendar(store, sealKey).catch(() => undefined))?.url;
1164
+ if (url)
1165
+ for (const form of addressForms(url))
1166
+ calendarAddresses.add(form);
1167
+ };
1168
+ await heldCalendar();
1169
+ secretStores.add("calendar", () => [...calendarAddresses]);
1127
1170
  // Each agent's saved sign-ins, over the one store (module A, sign-ins-store): the vendor's calls on the server's keys
1128
1171
  // (under faux, the vendor's fake alone), under this server's seal key. The store holds whether a sign-in is still held
1129
1172
  // (a live run's sign_in_handed) and who was handed it, so this takes no `holds`/`handedTo` callback — one store, one lock.
1130
1173
  const signIns = signInsOverStore(store, sealKey, vendorsOver(() => env, checkFetch));
1131
1174
  const webhooks = new Webhooks(store, sealKey, (fields) => (log ? log(logLine("webhook", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("webhook", fields)}\n`)), {
1132
1175
  ...(options.webhookRetryMs ? { retryMs: options.webhookRetryMs } : {}),
1176
+ ...(options.webhookLookup ? { lookup: options.webhookLookup } : {}),
1133
1177
  privateTargets: options.webhookPrivateTargets ?? process.env.AGENTRUN_WEBHOOK_PRIVATE_TARGETS === "1",
1134
1178
  });
1135
1179
  // The outbound webhook's secret, as it stands (set by a PUT, gone with a DELETE), and each it held before.
@@ -1330,6 +1374,10 @@ async function startHolding(options, data, checked, stops) {
1330
1374
  // What a run held for its owner's OK reads as it stands on its agent's learning folder's main (statusesOf).
1331
1375
  const statuses = (agentId) => statusesOf(data, agentId);
1332
1376
  const viewDepsFor = (origin) => ({ origin, serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)), statuses });
1377
+ // A run read as a whole (its own read, its archive) lists its recordings too, from its recordings folder on this machine
1378
+ // (run-recordings.ts), where the runner beside it wrote them; every other read of the view opens no file.
1379
+ const recordings = (agentId, runId, endedAt) => recordingsOf(recordingsFolder(data, agentId, runId), endedAt);
1380
+ const runReadDepsFor = (origin) => ({ ...viewDepsFor(origin), recordings });
1333
1381
  const ownOriginOf = () => options.publicUrl ?? url;
1334
1382
  // The run read routes (a run's files, its browser state, its workflow graph) over the one store (run-reads-over-store):
1335
1383
  // a run's files through the server's read-only Workspace of its folder (serverRunWorkspace, no runner claim), its view
@@ -1337,7 +1385,11 @@ async function startHolding(options, data, checked, stops) {
1337
1385
  // (liveViewerLink, the one the runner's browser tool wrote under its claim), opened with the server's seal key. The
1338
1386
  // timeline route keeps its own stub (store-reads journal + SSE) until E2c's timeline lands.
1339
1387
  const runReadsDeps = {
1340
- runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey, env: process.env }),
1388
+ runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey, env: withSecrets(process.env, "own") }),
1389
+ recordings: async (_store, runId) => {
1390
+ const run = await store.runs.get(runId);
1391
+ return run ? recordingsWorkspace(recordingsFolder(data, run.agentId, runId)) : null;
1392
+ },
1341
1393
  env,
1342
1394
  runFacts: (_store, runId) => factsOverStore(store, runId, viewDepsFor(ownOriginOf())),
1343
1395
  withheld: (_store, runId) => withheldOverStore(store, runId, viewDepsFor(ownOriginOf())),
@@ -1373,7 +1425,16 @@ async function startHolding(options, data, checked, stops) {
1373
1425
  },
1374
1426
  };
1375
1427
  const targets = triggerTargets(store, triggerDeps);
1376
- const expected = digest(`Bearer ${token}`);
1428
+ // Every presented token is checked here, against every token the server takes, in constant time (api-token.ts). The id
1429
+ // of the one that opened a request is kept with it for its log line (tokenUsed), never the secret.
1430
+ const bearerOf = bearerCheck(tokens);
1431
+ const tokenUsed = new WeakMap();
1432
+ const bearer = (header, req) => {
1433
+ const id = bearerOf(header);
1434
+ if (id !== undefined && req)
1435
+ tokenUsed.set(req, id);
1436
+ return id !== undefined;
1437
+ };
1377
1438
  const keptFile = join(data, IDEMPOTENCY_FILE);
1378
1439
  const kept = JSON.parse(await readFile(keptFile, "utf8").catch(() => "null"));
1379
1440
  const idempotency = new Map((kept?.entries ?? []).filter(([, v]) => v?.answer && Date.now() - v.at <= IDEMPOTENCY_TTL_S * 1000));
@@ -1494,7 +1555,9 @@ async function startHolding(options, data, checked, stops) {
1494
1555
  adapters,
1495
1556
  unavailable: async (kind) => (kind === "github" && !githubConnection() ? new ApiError("github_not_connected", "This server has no GitHub App: Connect GitHub in Settings, then make the trigger (or turn it on).") : kind === "email" && !(await openAccount(store, sealKey)) ? noAccount() : undefined),
1496
1557
  // The email trigger's account, its password opened as it polls (email/account.ts): never kept in the engine.
1497
- credentials: async (kind) => (kind === "email" ? openAccount(store, sealKey) : undefined),
1558
+ // A feed trigger's reach: where its reads may go, as an MCP server's requests may (mcp-oauth.ts feedAt), and a test's
1559
+ // or an eval's route to its fake feeds (feedsAt).
1560
+ credentials: async (kind) => (kind === "email" ? openAccount(store, sealKey) : kind === "feed" ? { ...(await mcpServers.outboundReach()), ...(options.feedsAt ? { route: options.feedsAt } : {}) } : undefined),
1498
1561
  say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
1499
1562
  // The trigger target policy (what a trigger may start or message, and in what words it is refused) is the one store's
1500
1563
  // (trigger-targets.ts, over the run write half and the run view): targetIssues, start, message, statusOf, runOf. The
@@ -1514,6 +1577,21 @@ async function startHolding(options, data, checked, stops) {
1514
1577
  signal: stopping.signal,
1515
1578
  say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
1516
1579
  });
1580
+ /** What a save refused while Composio triggers use the server says to do once they are gone (composio-triggers.ts inUse). */
1581
+ const SAVE_AFTER_TRIGGERS = "then save the server again";
1582
+ /** What a save over a preset server left at Composio (ComposioDropped), removed there with the key it was made with, in
1583
+ * words; when that key doesn't open here, all of it said to remove by hand. */
1584
+ const composioLeft = async (name, dropped) => "unusable" in dropped && (dropped.mcp || dropped.cleanup.remove.length) ? composioNote(name, dropped.cleanup, dropped.mcp ?? false, true)
1585
+ : await composioForget(options.composioControl ?? {}, "key" in dropped ? dropped.key : "", dropped.mcp, name, stopping.signal, dropped.cleanup);
1586
+ // The Composio preset's saves, the saves of the servers it made, and the MCP servers' deletes, one at a time, Composio's
1587
+ // calls included: a delete never removes there an auth config or account that a save still at Composio reuses (it would
1588
+ // find no record of it yet), and a save never reuses one a delete is removing. A failure of one never stops the next.
1589
+ let composioLast = Promise.resolve();
1590
+ const inComposioTurn = (work) => {
1591
+ const turn = composioLast.then(work, work);
1592
+ composioLast = turn.catch(() => undefined);
1593
+ return turn;
1594
+ };
1517
1595
  // A repair of the GitHub installations (below) stops before the triggers close, in a start that fails as in close.
1518
1596
  stops.push(() => githubConnect.close());
1519
1597
  stops.push(async () => triggers.close());
@@ -1821,7 +1899,14 @@ async function startHolding(options, data, checked, stops) {
1821
1899
  if (!named || !mcpMeta.has(named.server))
1822
1900
  return [];
1823
1901
  const pinned = Object.hasOwn(pin, named.server) && pin[named.server].tools.some((one) => one.name === named.tool);
1824
- return pinned ? [] : [{ field: `definition.tools[${index}]`, reason: "not_an_option", message: `The MCP tool ${tool} was not pinned when this revision was saved: save the agent again to pin it.`, tool }];
1902
+ if (pinned)
1903
+ return [];
1904
+ // Its first run could not pin it (mcp-pin-first.ts) because this server refuses its server's address: a loopback
1905
+ // one on a server whose operator never said it is a local install. Saving again is refused the same way, so the
1906
+ // words say the cause, as the save's refusal does (mcp-servers-store.ts reached).
1907
+ const at = URL.parse(mcpMeta.get(named.server).url)?.hostname ?? "";
1908
+ const why = options.mcpLoopback !== true && LOOPBACK.test(at) ? `its server ${named.server} can't be listed here to pin it: ${loopbackWords(at)}` : "save the agent again to pin it.";
1909
+ return [{ field: `definition.tools[${index}]`, reason: "not_an_option", message: `The MCP tool ${tool} was not pinned when this revision was saved: ${why}`, tool }];
1825
1910
  });
1826
1911
  if (unpinned.length)
1827
1912
  throw new ApiError("agent_not_runnable", unpinned.map((one) => one.message).join(" "), { fields: unpinned.map(({ tool: _tool, ...issue }) => issue), details: { unbound: unpinned.map((one) => one.tool), missing: {} } });
@@ -2145,7 +2230,9 @@ async function startHolding(options, data, checked, stops) {
2145
2230
  // Every trigger is checked as POST /triggers checks it, its parameters filled, before anything is made: a schedule
2146
2231
  // from a parameter that does not read, or a date that has passed, refuses the apply (422 under triggers.<i>). "Passed"
2147
2232
  // by the triggers' own clock, the one POST /triggers checks by and they fire by (a template eval case's `now`).
2148
- const refusedTriggers = madeTriggerIssues(made.triggers, options.triggerClock?.now() ?? Date.now(), pkg.inputSchema);
2233
+ // A feed trigger whose urls are one array parameter given empty reads no feed: skipped, never the apply (feedLeftEmpty).
2234
+ const emptyFeeds = new Set(made.triggers.flatMap((trigger, i) => (feedLeftEmpty(trigger) ? [i] : [])));
2235
+ const refusedTriggers = madeTriggerIssues(made.triggers, options.triggerClock?.now() ?? Date.now(), pkg.inputSchema).filter((issue) => !emptyFeeds.has(Number(/^triggers\.(\d+)\./.exec(issue.field)?.[1])));
2149
2236
  if (refusedTriggers.length)
2150
2237
  throw invalid(refusedTriggers);
2151
2238
  // POST /agents' and POST /triggers' own body limit: parameters filled in more than once can grow a package past it.
@@ -2164,6 +2251,8 @@ async function startHolding(options, data, checked, stops) {
2164
2251
  const unconnected = new Map();
2165
2252
  try {
2166
2253
  for (const [i, trigger] of made.triggers.entries()) {
2254
+ if (emptyFeeds.has(i))
2255
+ continue;
2167
2256
  try {
2168
2257
  const { id: madeId, secret } = await triggers.create({ ...trigger, target: { ...trigger.target, agent_id: entry.agent.id } });
2169
2258
  ids.push(madeId);
@@ -2214,12 +2303,14 @@ async function startHolding(options, data, checked, stops) {
2214
2303
  const refused = unconnected.get(i);
2215
2304
  return refused && isObject(trigger.source) && trigger.source.kind === "composio" ? [{ field: `triggers.${i}`, reason: NOT_SET_UP, message: composioTriggerSkipped(pkg.name, trigger, refused.message), fix: COMPOSIO_TRIGGER_FIX }] : [];
2216
2305
  });
2306
+ // Each feed trigger it skipped for want of a feed: which, and the parameter to set.
2307
+ const feedsSkipped = [...emptyFeeds].map((i) => ({ field: `triggers.${i}`, reason: NOT_SET_UP, message: feedTriggerEmpty(pkg.name, made.triggers[i], isObject(pkg.triggers[i]?.source) ? pkg.triggers[i].source.urls : undefined) }));
2217
2308
  // Each trigger it made, a webhook trigger's with its secret's metadata; the values go back beside the answer, never in it
2218
2309
  // (the route adds them to the first answer to the owner's session, after the Idempotency-Key's record is written).
2219
2310
  const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
2220
2311
  // Which saved server each MCP need runs on (null: none here, said under mcp.<toolkit>).
2221
2312
  const used = Object.fromEntries(mapped.map(({ need, server }) => [need.toolkit, server]));
2222
- const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, servers: used, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...composioSkipped, ...appShort] };
2313
+ const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, servers: used, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...composioSkipped, ...feedsSkipped, ...appShort] };
2223
2314
  return { applied, minted };
2224
2315
  }
2225
2316
  /** A run create's issues told from the input this server checks (explain.ts): an agentic run's input schema in force
@@ -2420,7 +2511,7 @@ async function startHolding(options, data, checked, stops) {
2420
2511
  }
2421
2512
  /** A run create's body as POST /agents/{id}/runs checks it before it reads the agent: each field issue. */
2422
2513
  function runBodyIssues(body) {
2423
- const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "quote_id", "learning", "archil_disk", "repo", "workflow_first", "hold", "hold_minutes"]);
2514
+ const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "quote_id", "learning", "archil_disk", "repo", "workflow_first", "hold", "hold_minutes", "labels"]);
2424
2515
  issues.push(...holdIssues(body));
2425
2516
  if (body.repo !== undefined && !(typeof body.repo === "string" && REPO_NAME.test(body.repo)))
2426
2517
  issues.push({ field: "repo", reason: "wrong_type", message: "repo is a GitHub repository as owner/name, one the agent is bound to" });
@@ -2446,6 +2537,7 @@ async function startHolding(options, data, checked, stops) {
2446
2537
  issues.push({ field: "workflow_first", reason: "wrong_type", message: "workflow_first is true or false" });
2447
2538
  if (body.learning !== undefined && body.learning !== RUN_LEARNING_USE)
2448
2539
  issues.push({ field: "learning", reason: "not_an_option", message: `learning is "${RUN_LEARNING_USE}" (the run starts from what its agent learned and keeps nothing), or absent (its agent's own)` });
2540
+ issues.push(...labelsIssues(body.labels));
2449
2541
  return issues;
2450
2542
  }
2451
2543
  /** A page of runs from the store, newest first: `agent`, `revision` and `status` narrow it. */
@@ -2466,8 +2558,10 @@ async function startHolding(options, data, checked, stops) {
2466
2558
  if (value !== undefined && !ID.test(value))
2467
2559
  throw new ApiError("bad_request", `${key} is an id`);
2468
2560
  const archived = archivedParam(url);
2561
+ // `label=<key>:<value>`, once: only the runs holding it (run-labels.ts), filtered in the store.
2562
+ const labels = labelFilter(url.searchParams.getAll("label"));
2469
2563
  const vd = viewDepsFor(origin);
2470
- let rows = (await listRunsOverStore(store, filter, ctx)).filter((row) => Boolean(row.archivedAt) === archived);
2564
+ let rows = (await listRunsOverStore(store, { ...filter, ...(labels ? { labels } : {}) }, ctx)).filter((row) => Boolean(row.archivedAt) === archived);
2471
2565
  if (status !== null) {
2472
2566
  // The v2 status is the run view's (store-view over the journal), per row.
2473
2567
  const statuses = await Promise.all(rows.map((row) => viewOverStore(store, row.id, vd).then((v) => v?.status)));
@@ -2711,7 +2805,7 @@ async function startHolding(options, data, checked, stops) {
2711
2805
  switch (path) {
2712
2806
  case "/setup": {
2713
2807
  const byToken = req.headers.authorization !== undefined;
2714
- if (byToken && !timingSafeEqual(digest(String(req.headers.authorization)), expected))
2808
+ if (byToken && !bearer(req.headers.authorization, req))
2715
2809
  throw new ApiError("unauthenticated", "the Bearer here is the server's token, or none", {}, { "www-authenticate": "Bearer" });
2716
2810
  if (!byToken)
2717
2811
  fromPage(req);
@@ -2725,7 +2819,7 @@ async function startHolding(options, data, checked, stops) {
2725
2819
  const along = body.import === true ? { keep: () => writeDurable(importAsked, ""), drop: () => rm(importAsked, { force: true }) } : undefined;
2726
2820
  // The server's API token stands in for the code in the code field too (on Render it is in the Environment tab, the
2727
2821
  // code only in the log), compared as the header is, in constant time; a wrong one counts as a wrong code.
2728
- const tokenAsCode = typeof body.code === "string" && body.code !== "" && timingSafeEqual(digest(`Bearer ${body.code}`), expected);
2822
+ const tokenAsCode = typeof body.code === "string" && body.code !== "" && bearer(`Bearer ${body.code}`, req);
2729
2823
  const made = await me.setFirst(password, body.code, byToken || tokenAsCode, along);
2730
2824
  if (made === "exists")
2731
2825
  throw new ApiError("forbidden", "this server has its owner, or is being set up: sign in");
@@ -2918,6 +3012,20 @@ async function startHolding(options, data, checked, stops) {
2918
3012
  // limited by source address before anything in the body is checked.
2919
3013
  if (found.name === "pairComputer")
2920
3014
  return send(res, 201, await attach.pair(await bodyOf(req), clientOf(req)), { "cache-control": "no-store" });
3015
+ // A hosted machine fetching this server's computerd build: the token its create minted is its credential, never the
3016
+ // owner's (computer-attach.ts daemon).
3017
+ if (found.name === "getComputerDaemon") {
3018
+ const file = await attach.daemon(req.headers.authorization, url.searchParams.get("arch")).catch((error) => {
3019
+ if (error instanceof ApiError && error.status === 401)
3020
+ authFailed(`/v2${path}`, "machine_token");
3021
+ throw error;
3022
+ });
3023
+ const bytes = await readFile(file).catch(() => {
3024
+ throw new ApiError("unavailable", `this server has no computerd build at ${file}: run npm run build:daemon -w @parcha/agentrun-computer where it runs`);
3025
+ });
3026
+ res.writeHead(200, { "content-type": "application/octet-stream", "content-length": String(bytes.length), "cache-control": "no-store", "x-content-type-options": "nosniff" });
3027
+ return void res.end(req.method === "HEAD" ? undefined : bytes);
3028
+ }
2921
3029
  // An MCP server's OAuth sign-in: the browser coming back from its authorization server carries no token (the state
2922
3030
  // it brings is the check, mcp-oauth.ts), and the client metadata document is for that server to fetch.
2923
3031
  if (found.name === "mcpOAuthCallback") {
@@ -3050,7 +3158,7 @@ async function startHolding(options, data, checked, stops) {
3050
3158
  if (found.name === "importRemoteTarget")
3051
3159
  return send(res, 200, await broker.importTarget(connectorId, body));
3052
3160
  if (found.name === "importRemoteHistory")
3053
- return send(res, 200, await broker.importHistory(connectorId, decodeURIComponent(parts[2]), body, [token, String(req.headers.authorization ?? "").replace(/^Bearer /, "")]));
3161
+ return send(res, 200, await broker.importHistory(connectorId, decodeURIComponent(parts[2]), body, [...tokens.map((entry) => entry.token), String(req.headers.authorization ?? "").replace(/^Bearer /, "")]));
3054
3162
  if (found.name === "pollRemoteConnector")
3055
3163
  return send(res, 200, await broker.poll(connectorId, body));
3056
3164
  const commandId = decodeURIComponent(parts[2]);
@@ -3058,7 +3166,7 @@ async function startHolding(options, data, checked, stops) {
3058
3166
  }
3059
3167
  if (["getSdkRun", "sdkRunEvents", "completeSdkRun"].includes(found.name)) {
3060
3168
  const runId = decodeURIComponent(found.pattern.exec(path)[1]);
3061
- const sdk = new SdkRuns(store, data, token, serverSecrets);
3169
+ const sdk = new SdkRuns(store, data, sdkSecret, serverSecrets, tokens.map((entry) => entry.token));
3062
3170
  await sdk.authenticate(runId, String(req.headers.authorization ?? "").replace(/^Bearer /, ""));
3063
3171
  if (found.name === "sdkRunEvents")
3064
3172
  return send(res, 200, await sdk.events(runId, await bodyOf(req)));
@@ -3066,7 +3174,7 @@ async function startHolding(options, data, checked, stops) {
3066
3174
  return send(res, 200, await sdk.complete(runId, await bodyOf(req)));
3067
3175
  return send(res, 200, { ...await sdk.status(runId), learning: await servedRunLearning({ serverSecrets, signIns, statuses }, store, runId) });
3068
3176
  }
3069
- if (!timingSafeEqual(digest(String(req.headers.authorization ?? "")), expected)) {
3177
+ if (!bearer(req.headers.authorization, req)) {
3070
3178
  authFailed(`/v2${path}`, req.headers.authorization === undefined ? "no_credential" : "wrong_token");
3071
3179
  throw new ApiError("unauthenticated", "this route needs Authorization: Bearer <the token in the data directory>", {}, { "www-authenticate": "Bearer" });
3072
3180
  }
@@ -3090,7 +3198,7 @@ async function startHolding(options, data, checked, stops) {
3090
3198
  }
3091
3199
  catch { }
3092
3200
  }
3093
- const sdk = new SdkRuns(store, data, token, serverSecrets);
3201
+ const sdk = new SdkRuns(store, data, sdkSecret, serverSecrets, tokens.map((entry) => entry.token));
3094
3202
  const answer = await idempotent(req, path, body, async (origin) => ({ status: 201, body: await sdk.start(entry, body, { ...startDeps, ...(gradeModel ? { gradeModel } : {}) }, origin, async (model) => {
3095
3203
  try {
3096
3204
  const route = await gradeRouteFor({ model, agentId: id }, env, sdkModelRoute);
@@ -3312,7 +3420,7 @@ async function startHolding(options, data, checked, stops) {
3312
3420
  return send(res, 200, await runsPage(url, { ...(agent ? { agent } : {}), ...(revision ? { revision } : {}) }, linkOrigin(req)));
3313
3421
  }
3314
3422
  case "getRun": {
3315
- const view = await viewOverStore(store, id, viewDepsFor(linkOrigin(req)));
3423
+ const view = await viewOverStore(store, id, runReadDepsFor(linkOrigin(req)));
3316
3424
  if (!view)
3317
3425
  throw new ApiError("not_found", `no run ${id}`);
3318
3426
  return send(res, 200, { ...view, ...(await runComputerOf(id, view)) });
@@ -3421,7 +3529,7 @@ async function startHolding(options, data, checked, stops) {
3421
3529
  ...(typeof m.workflow === "string" ? { workflow: m.workflow } : {}), ...(typeof m.workflow_digest === "string" ? { digest: m.workflow_digest } : {}),
3422
3530
  ...(typeof m.workflow_promotion === "number" ? { promotion: m.workflow_promotion } : {}),
3423
3531
  };
3424
- // Kept with what it asks of the run's learning (runner/feedback-round.ts): nothing, a revision ask, or a look-back.
3532
+ // Kept with what it asks of the run's learning (runner/feedback-round.ts): nothing, or a look-back.
3425
3533
  const kept = gradeView(await keepGrade(store, row.agentId, grade, typeof body.label === "string" ? body.label : undefined));
3426
3534
  // Its workflow's name cut as GET /runs/{id}/learning cuts it (learningShown); withheld whole when that cut can't be
3427
3535
  // read (the grade is kept by then: never a shorter cut, never a refusal of a grade it kept).
@@ -3432,7 +3540,7 @@ async function startHolding(options, data, checked, stops) {
3432
3540
  case "unarchiveRun": {
3433
3541
  const run = await needRun(id);
3434
3542
  await archiveRun(store, run.id, found.name === "archiveRun");
3435
- return send(res, 200, await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))));
3543
+ return send(res, 200, await viewOverStore(store, run.id, runReadDepsFor(linkOrigin(req))));
3436
3544
  }
3437
3545
  case "getRunBrowser":
3438
3546
  case "getRunComputer": {
@@ -3728,6 +3836,24 @@ async function startHolding(options, data, checked, stops) {
3728
3836
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
3729
3837
  return send(res, 200, answer, { "cache-control": "no-store" });
3730
3838
  }
3839
+ // Never through `idempotent` either: its record keeps the body, and the body holds the calendar's address. A read
3840
+ // reaches loopback only on a local install (its fakes), and a private host only where the owner allows it.
3841
+ case "getCalendar":
3842
+ case "saveCalendar":
3843
+ case "deleteCalendar":
3844
+ case "testCalendar": {
3845
+ const body = found.name === "saveCalendar" || found.name === "testCalendar" ? await bodyOf(req) : undefined;
3846
+ if (found.name === "saveCalendar" && stopping.signal.aborted)
3847
+ throw new ApiError("unavailable", "The server is shutting down: the calendar was not saved.");
3848
+ // The MCP servers' network and reach (mcp-oauth.ts calendarAt is mcpServerAt's rule), and their stop with the server's.
3849
+ const outbound = await mcpServers.outboundReach();
3850
+ const answer = await calendarRoute({ store, sealKey, reach: async () => outbound.reach, network: outbound.network, signal: AbortSignal.any([outbound.signal, stopping.signal]) }, found.name, body);
3851
+ if (found.name === "saveCalendar")
3852
+ await heldCalendar();
3853
+ if (answer === undefined)
3854
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
3855
+ return send(res, 200, answer, { "cache-control": "no-store" });
3856
+ }
3731
3857
  // The ChatGPT sign-in (chatgpt-plan.ts): a step it refuses is 400 in its words; its token is in no answer.
3732
3858
  case "getChatGPTSignIn":
3733
3859
  await planNow();
@@ -3750,9 +3876,30 @@ async function startHolding(options, data, checked, stops) {
3750
3876
  case "previewMcpServer":
3751
3877
  return send(res, 200, await mcpServers.preview(await bodyOf(req), stopping.signal));
3752
3878
  case "saveMcpServer": {
3753
- const saved = await mcpServers.save(id, await bodyOf(req), stopping.signal, secretSeen);
3879
+ const body = await bodyOf(req);
3880
+ // A server that isn't a Composio preset's is saved at once, as ever: no save waits on another's listing.
3881
+ if (!(await mcpServers.composioPreset(id))) {
3882
+ const saved = await mcpServers.save(id, body, stopping.signal, secretSeen);
3883
+ await refreshMcpMeta();
3884
+ return send(res, 200, saved);
3885
+ }
3886
+ // A preset server's: listed as any save is, at once; then its write and cleanup in the Composio turn and its
3887
+ // project's. A save that moves it off Composio is refused while Composio triggers use it, in the delete's words;
3888
+ // else it removes there what its save made (the MCP server, then what no other saved server uses), as a delete
3889
+ // does, with the key it was saved with, and says so.
3890
+ const over = {};
3891
+ const guard = {
3892
+ turn: (work) => inComposioTurn(async () => {
3893
+ const done = await composioTriggers.inTurnOf(id, work);
3894
+ if (over.dropped)
3895
+ over.note = await composioLeft(id, over.dropped);
3896
+ return done;
3897
+ }),
3898
+ inUse: () => composioTriggers.inUse(id, SAVE_AFTER_TRIGGERS),
3899
+ };
3900
+ const saved = await mcpServers.save(id, body, stopping.signal, secretSeen, undefined, undefined, (left) => (over.dropped = left), guard);
3754
3901
  await refreshMcpMeta();
3755
- return send(res, 200, saved);
3902
+ return send(res, 200, over.note ? { ...saved, composio: over.note } : saved);
3756
3903
  }
3757
3904
  // Composio makes the managed MCP server; what is kept is the ordinary MCP save, so the key is a sealed header.
3758
3905
  case "listComposioTools":
@@ -3761,8 +3908,18 @@ async function startHolding(options, data, checked, stops) {
3761
3908
  // The name is checked before Composio is called: a refused name leaves nothing made there.
3762
3909
  mcpNameOf(id);
3763
3910
  const body = await bodyOf(req);
3764
- const answer = await composioSave(body, options.composioControl ?? {}, (mcp, made) => mcpServers.save(id, mcp, stopping.signal, undefined, made), id, stopping.signal, async () => (await mcpServers.get(id)).url);
3765
- await refreshMcpMeta();
3911
+ // In the Composio turn. A save over a preset server removes there, once it is saved, the MCP server the save before
3912
+ // made and what that save made that this one no longer stands on (an account of another user, an auth config of
3913
+ // another toolkit), with the key it was made with, and says so as a delete does; what another saved server uses is
3914
+ // that one's now, and said too. A save as another user or auth config is refused while Composio triggers use the
3915
+ // server, in the delete's words, checked in its project's turn before the row is written.
3916
+ const answer = await inComposioTurn(async () => {
3917
+ const over = {};
3918
+ const guard = { turn: (work) => composioTriggers.inTurnOf(id, work), inUse: () => composioTriggers.inUse(id, SAVE_AFTER_TRIGGERS) };
3919
+ const saved = await composioSave(body, options.composioControl ?? {}, (mcp, made, stands) => mcpServers.save(id, mcp, stopping.signal, undefined, made, stands, (left) => (over.dropped = left), guard), id, stopping.signal, async () => (await mcpServers.get(id)).url);
3920
+ await refreshMcpMeta();
3921
+ return over.dropped ? { ...saved, composio: await composioLeft(id, over.dropped) } : saved;
3922
+ });
3766
3923
  return send(res, 200, answer, { "cache-control": "no-store" });
3767
3924
  }
3768
3925
  case "listComposioEvents":
@@ -3819,14 +3976,18 @@ async function startHolding(options, data, checked, stops) {
3819
3976
  return send(res, 200, await privateHostsRoute(mcpServers, { method: "PUT", body: () => bodyOf(req) }), { "cache-control": "no-store" });
3820
3977
  case "deleteMcpServer": {
3821
3978
  // Our row goes first, by the checked removal (a 412 sends Composio nothing), and answers what it removed: a Composio
3822
- // preset server's MCP server on Composio is deleted next, as the row removed named it and with its saved key.
3823
- // Composio refusing or not answering, or a key that does not open, never keeps our row: the answer says what to
3824
- // remove there by hand. One that Composio triggers still use is kept: refused, naming them, checked and deleted in
3825
- // its Composio project's turn, so a trigger still being made on it is counted (composio-triggers.ts deleting).
3826
- const { composio: made } = await composioTriggers.deleting(id, () => mcpServers.remove(id, secretSeen));
3827
- await refreshMcpMeta();
3828
- const forgotten = !made ? undefined : "unusable" in made ? composioNote(id) : await composioForget(options.composioControl ?? {}, made.key, made.id, id, stopping.signal);
3829
- if (forgotten && !forgotten.removed)
3979
+ // preset server's MCP server on Composio is deleted next, as the row removed named it and with its saved key, then
3980
+ // what its save made for it there that no other saved server uses (its connect link's account, its auth config).
3981
+ // Composio refusing or not answering, or a key that does not open, never keeps our row. A preset's answer says in
3982
+ // words what went there, what stays and why, and what to remove by hand. One that Composio triggers still use is kept: refused, naming them, checked and deleted in
3983
+ // its Composio project's turn, so a trigger still being made on it is counted (composio-triggers.ts deleting). All of
3984
+ // it in the Composio turn, so a Composio save still at work finishes first and its record is counted.
3985
+ const forgotten = await inComposioTurn(async () => {
3986
+ const { composio: made } = await composioTriggers.deleting(id, () => mcpServers.remove(id, secretSeen));
3987
+ await refreshMcpMeta();
3988
+ return !made ? undefined : "unusable" in made ? composioNote(id, made.cleanup) : await composioForget(options.composioControl ?? {}, made.key, made.id, id, stopping.signal, made.cleanup);
3989
+ });
3990
+ if (forgotten)
3830
3991
  return send(res, 200, { deleted: true, composio: forgotten }, { "cache-control": "no-store" });
3831
3992
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
3832
3993
  }
@@ -3930,7 +4091,7 @@ async function startHolding(options, data, checked, stops) {
3930
4091
  return { ...one, workflow, from_notes: one.from_notes.map(shown.name), attempts: one.attempts.map(({ ok, errors }) => ({ ok, errors: errors.map(said) })), draft_errors: one.draft_errors.map(said), withheld: false };
3931
4092
  }));
3932
4093
  const guards = read.guards.map((one) => ({ ...one, workflow: shown.name(one.workflow), node: shown.text(one.node) }));
3933
- return send(res, 200, { agent: id, compiles, guards });
4094
+ return send(res, 200, { agent: id, completed_runs: read.completed_runs, compiles, guards });
3934
4095
  }
3935
4096
  case "listLearningNotes":
3936
4097
  case "listLearningLog":
@@ -4115,7 +4276,7 @@ async function startHolding(options, data, checked, stops) {
4115
4276
  throw new ApiError("not_found", `no route ${path}`);
4116
4277
  }
4117
4278
  // The MCP endpoint's tools are the routes above, called in process with the caller's token (mcp.ts).
4118
- const mcp = mcpEndpoint({ route, authorized: (header) => timingSafeEqual(digest(header), expected), authFailed, version: VERSION });
4279
+ const mcp = mcpEndpoint({ route, authorized: (header, req) => bearer(header, req), authFailed, version: VERSION });
4119
4280
  function send(res, status, body, headers = {}) {
4120
4281
  const text = JSON.stringify(body);
4121
4282
  res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", "x-content-type-options": "nosniff", ...headers });
@@ -4158,7 +4319,12 @@ async function startHolding(options, data, checked, stops) {
4158
4319
  const started = performance.now();
4159
4320
  const method = req.method ?? "GET";
4160
4321
  const path = (req.url ?? "/").split("?")[0];
4161
- res.once("finish", () => log(logLine("request", { method, path, status: res.statusCode, ms: Math.round(performance.now() - started) })));
4322
+ // Who the request was answered for: the owner's or the console's session, or the id of the API token it carried
4323
+ // (api-token.ts), never a secret. A request opened by neither has no such field.
4324
+ res.once("finish", () => {
4325
+ const by = byOwnerSession(req) ? { session: "owner" } : byConsoleSession(req) ? { session: "console" } : tokenUsed.has(req) ? { token: tokenUsed.get(req) } : {};
4326
+ log(logLine("request", { method, path, status: res.statusCode, ms: Math.round(performance.now() - started), ...by }));
4327
+ });
4162
4328
  }
4163
4329
  const fail = (error) => {
4164
4330
  if (res.headersSent)
@@ -4205,7 +4371,7 @@ async function startHolding(options, data, checked, stops) {
4205
4371
  if (answerPage(req, res, raw, { token, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(consoleSessions ? { sessions: consoleSessions } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
4206
4372
  return;
4207
4373
  if (isObservationRoute(raw))
4208
- return void observationHttp(req, res, url, new Observations(store), token).catch(fail);
4374
+ return void observationHttp(req, res, url, new Observations(store), (header) => bearer(header, req)).catch(fail);
4209
4375
  if (!raw.startsWith("/v2/"))
4210
4376
  return fail(new ApiError("not_found", `no route ${raw}; the API is under /v2`));
4211
4377
  // A run's id needs no decoding: one that is not an id as sent (a stray or malformed escape) is no run's, and is never
@@ -4230,10 +4396,12 @@ async function startHolding(options, data, checked, stops) {
4230
4396
  // away. Its name alone, on any port, as the HTTP routes check it.
4231
4397
  if (names && !names.has(hostName(req.headers.host) ?? ""))
4232
4398
  return deny("403 Forbidden");
4233
- // API-only: a run's live view is the console's, and refused with it; so are paired computers (Settings).
4234
- if (options.apiOnly)
4399
+ // API-only: a run's live view is the console's, and refused with it; so are paired computers (Settings), whose tokens
4400
+ // the attach socket takes as unknown there (machinesOnly). A run's hosted machine that dials still reaches it.
4401
+ if (options.apiOnly && raw !== ATTACH_PATH)
4235
4402
  return deny("404 Not Found");
4236
- // A paired computer's driver dialing its attach socket (computer-attach.ts): its token, not the owner's, lets it in.
4403
+ // A paired computer's driver or a hosted machine dialing the attach socket (computer-attach.ts): its token, not the
4404
+ // owner's, lets it in.
4237
4405
  if (raw === ATTACH_PATH) {
4238
4406
  return attach.upgrade(req, socket, head, (status, words = "", headers = {}) => {
4239
4407
  if (status.startsWith("401"))
@@ -4320,6 +4488,14 @@ async function startHolding(options, data, checked, stops) {
4320
4488
  // listens: a hosted container listens on loopback behind its proxy too.
4321
4489
  const localInstall = options.mcpLoopback === true;
4322
4490
  mcpServers.attach(options.publicUrl ?? url, url, localInstall);
4491
+ // Its own addresses, kept in the store for a runner in its own process whose own opt-in lets it reach loopback: its runs
4492
+ // never reach this server's ports there either (mcp-private-hosts.ts saveServerOwn). It listens already: a write that
4493
+ // fails stops the start and lets go of the port, as the start's other stops let go of the store and the locks.
4494
+ await saveServerOwn(store, mcpServers.own).catch(async (error) => {
4495
+ server.closeAllConnections();
4496
+ await new Promise((done) => server.close(() => done()));
4497
+ throw error;
4498
+ });
4323
4499
  // A run's end and its wait are the outbound webhook's run.ended and run.needs_input (webhooks.ts). The runners write them
4324
4500
  // to the store and this server runs no run, so it follows the store's run-change feed (Store.runs.changedSince): every
4325
4501
  // run reaching a final state, or let go by its runner (parked, or running with none), once, in order, under a cursor
@@ -4627,13 +4803,16 @@ async function startHolding(options, data, checked, stops) {
4627
4803
  baseUrl: `${url}/v2`,
4628
4804
  port: address.port,
4629
4805
  token,
4806
+ tokenIds: tokens.map((entry) => entry.id),
4630
4807
  tokenFile,
4631
4808
  tokenMade: stored?.made ?? false,
4632
4809
  ...(setupUrl ? { setupUrl, setupOpen: openSetup } : {}),
4633
4810
  ...(consoleSessions ? { launchCode: consoleSessions.code } : {}),
4634
4811
  boxesLine: boxesLine(boxOffers, enabledBoxes(env), boxAllow, boxesByDefault(env)),
4635
4812
  attachHub,
4813
+ dial: { ...(options.publicUrl ? { url: options.publicUrl.replace(/\/+$/, "") } : {}), tokens: attach.machineTokens, hub: attachHub },
4636
4814
  localInstall,
4815
+ own: mcpServers.own,
4637
4816
  // Once: a second call, at any time, is the first one's promise, so a close repeated after the next server started
4638
4817
  // never writes this data root's record again (the next server's, by then).
4639
4818
  close: () => (stopped ??= stop()),