@parcha/agentrun-serve 0.1.0-beta.39 → 0.1.0-beta.41

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 (173) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/README.md +129 -16
  3. package/dist/api-only.d.ts +3 -1
  4. package/dist/api-only.js +4 -2
  5. package/dist/api-token.d.ts +30 -0
  6. package/dist/api-token.js +89 -0
  7. package/dist/cli.js +19 -5
  8. package/dist/composio-made.d.ts +54 -0
  9. package/dist/composio-made.js +83 -0
  10. package/dist/composio-preset.d.ts +16 -8
  11. package/dist/composio-preset.js +106 -43
  12. package/dist/composio-triggers.d.ts +7 -2
  13. package/dist/composio-triggers.js +13 -7
  14. package/dist/computer-attach.d.ts +29 -11
  15. package/dist/computer-attach.js +141 -47
  16. package/dist/computer-keys.d.ts +4 -0
  17. package/dist/computer-keys.js +5 -0
  18. package/dist/computers.d.ts +11 -1
  19. package/dist/computers.js +21 -12
  20. package/dist/console/assets/index-C3gNPz58.css +1 -0
  21. package/dist/console/assets/index-COGhx_2Z.js +711 -0
  22. package/dist/console/index.html +2 -2
  23. package/dist/decisions.js +9 -2
  24. package/dist/email/account.d.ts +0 -1
  25. package/dist/email/account.js +3 -3
  26. package/dist/email/answer.d.ts +5 -0
  27. package/dist/email/answer.js +35 -0
  28. package/dist/email/mail.js +19 -26
  29. package/dist/email/names.d.ts +30 -0
  30. package/dist/email/names.js +34 -0
  31. package/dist/email/routes.d.ts +1 -0
  32. package/dist/email/routes.js +1 -1
  33. package/dist/email/tools.d.ts +11 -4
  34. package/dist/email/tools.js +91 -46
  35. package/dist/eval-feed.d.ts +26 -0
  36. package/dist/eval-feed.js +68 -0
  37. package/dist/eval-mailbox.d.ts +5 -2
  38. package/dist/eval-mailbox.js +14 -6
  39. package/dist/exa-keyless.d.ts +1 -1
  40. package/dist/exa-keyless.js +1 -1
  41. package/dist/feed/feed-faux.d.ts +62 -0
  42. package/dist/feed/feed-faux.js +123 -0
  43. package/dist/feed/fetch.d.ts +41 -0
  44. package/dist/feed/fetch.js +128 -0
  45. package/dist/feed/parse.d.ts +41 -0
  46. package/dist/feed/parse.js +300 -0
  47. package/dist/learn/check.d.ts +3 -1
  48. package/dist/learn/check.js +57 -2
  49. package/dist/learn/compile.d.ts +3 -2
  50. package/dist/learn/compile.js +7 -6
  51. package/dist/learn/promote.d.ts +25 -14
  52. package/dist/learn/promote.js +32 -14
  53. package/dist/learned-nodes.d.ts +21 -4
  54. package/dist/learned-nodes.js +21 -8
  55. package/dist/learned-workflow.d.ts +3 -3
  56. package/dist/learned-workflow.js +14 -5
  57. package/dist/learning-cost.d.ts +17 -8
  58. package/dist/learning-cost.js +12 -4
  59. package/dist/local-models.d.ts +7 -1
  60. package/dist/local-models.js +11 -5
  61. package/dist/mcp-oauth.d.ts +15 -1
  62. package/dist/mcp-oauth.js +39 -5
  63. package/dist/mcp-pin-first.d.ts +4 -2
  64. package/dist/mcp-pin-first.js +4 -3
  65. package/dist/mcp-servers-store.d.ts +58 -5
  66. package/dist/mcp-servers-store.js +136 -17
  67. package/dist/mcp.d.ts +2 -2
  68. package/dist/mcp.js +2 -2
  69. package/dist/observation/http.d.ts +4 -1
  70. package/dist/observation/http.js +5 -4
  71. package/dist/openapi.d.ts +1 -1
  72. package/dist/openapi.js +63 -27
  73. package/dist/port-models.d.ts +4 -1
  74. package/dist/port-models.js +1 -0
  75. package/dist/print.d.ts +6 -3
  76. package/dist/print.js +4 -2
  77. package/dist/refusal-words.d.ts +3 -0
  78. package/dist/refusal-words.js +3 -0
  79. package/dist/run-labels.d.ts +23 -0
  80. package/dist/run-labels.js +79 -0
  81. package/dist/run-launch.d.ts +2 -0
  82. package/dist/run-launch.js +2 -0
  83. package/dist/run-secrets.js +12 -4
  84. package/dist/run-view.d.ts +3 -4
  85. package/dist/run-view.js +26 -24
  86. package/dist/runner/adapter-loop.d.ts +6 -2
  87. package/dist/runner/adapter-loop.js +136 -22
  88. package/dist/runner/adapter-run-spec.d.ts +5 -0
  89. package/dist/runner/adapter-run-spec.js +75 -32
  90. package/dist/runner/beside.d.ts +6 -3
  91. package/dist/runner/beside.js +9 -7
  92. package/dist/runner/cli-run-spec.js +33 -26
  93. package/dist/runner/conformance/harness.js +69 -14
  94. package/dist/runner/conformance/subject.d.ts +4 -1
  95. package/dist/runner/journal-kinds.d.ts +22 -0
  96. package/dist/runner/journal-kinds.js +39 -0
  97. package/dist/runner/main.d.ts +1 -1
  98. package/dist/runner/main.js +2 -2
  99. package/dist/runner/mcp-claim.d.ts +3 -0
  100. package/dist/runner/mcp-claim.js +1 -1
  101. package/dist/runner/mcp-run.d.ts +4 -0
  102. package/dist/runner/mcp-run.js +5 -3
  103. package/dist/runner/model-route.d.ts +7 -3
  104. package/dist/runner/model-route.js +24 -9
  105. package/dist/runner/promotion.d.ts +16 -8
  106. package/dist/runner/promotion.js +178 -55
  107. package/dist/runner/workflow-first.d.ts +6 -5
  108. package/dist/runner/workflow-first.js +9 -7
  109. package/dist/runs-over-store.js +5 -2
  110. package/dist/sdk/runs.d.ts +7 -1
  111. package/dist/sdk/runs.js +19 -6
  112. package/dist/secret-cut.js +3 -1
  113. package/dist/secrets.js +3 -1
  114. package/dist/server.d.ts +27 -2
  115. package/dist/server.js +181 -56
  116. package/dist/store/dialect.d.ts +6 -0
  117. package/dist/store/dialect.js +2 -0
  118. package/dist/store/index.d.ts +1 -1
  119. package/dist/store/postgres/connection.d.ts +11 -5
  120. package/dist/store/postgres/connection.js +44 -17
  121. package/dist/store/postgres/dialect.js +6 -0
  122. package/dist/store/postgres/migrations/0015_run_labels.sql +5 -0
  123. package/dist/store/postgres/migrations/0016_minted_tokens.sql +21 -0
  124. package/dist/store/postgres/store.d.ts +7 -3
  125. package/dist/store/postgres/store.js +1 -0
  126. package/dist/store/schema.d.ts +9 -0
  127. package/dist/store/schema.js +26 -2
  128. package/dist/store/sqlite/connection.js +80 -8
  129. package/dist/store/sqlite/run-launch.d.ts +11 -0
  130. package/dist/store/sqlite/run-launch.js +8 -0
  131. package/dist/store/sqlite/run-patch.d.ts +2 -1
  132. package/dist/store/sqlite/run-patch.js +3 -2
  133. package/dist/store/sqlite/store.js +101 -26
  134. package/dist/store/sqlite/worker.d.ts +2 -0
  135. package/dist/store/sqlite/worker.js +13 -10
  136. package/dist/store/store.d.ts +53 -1
  137. package/dist/store-reads/journal.js +2 -1
  138. package/dist/store-reads/learning.d.ts +30 -13
  139. package/dist/store-reads/learning.js +130 -51
  140. package/dist/store-reads/runs.d.ts +4 -3
  141. package/dist/store-reads/runs.js +3 -2
  142. package/dist/store-view.js +4 -2
  143. package/dist/template-eval.d.ts +4 -0
  144. package/dist/template-eval.js +127 -50
  145. package/dist/templates.d.ts +24 -1
  146. package/dist/templates.js +129 -21
  147. package/dist/timeline/origin.d.ts +1 -1
  148. package/dist/timeline/origin.js +2 -2
  149. package/dist/tool-gate.d.ts +5 -3
  150. package/dist/tool-gate.js +5 -2
  151. package/dist/tools.d.ts +13 -0
  152. package/dist/tools.js +15 -10
  153. package/dist/trigger-adapter.d.ts +12 -36
  154. package/dist/trigger-adapters.js +2 -1
  155. package/dist/trigger-email.js +30 -77
  156. package/dist/trigger-feed.d.ts +12 -0
  157. package/dist/trigger-feed.js +371 -0
  158. package/dist/triggers.d.ts +27 -14
  159. package/dist/triggers.js +121 -80
  160. package/dist/webhooks.js +9 -5
  161. package/dist/workflow/decision-recovery.js +5 -2
  162. package/dist/workflow/decisions.d.ts +7 -0
  163. package/dist/workspace/computer-deps.d.ts +5 -1
  164. package/dist/workspace/computer-deps.js +2 -2
  165. package/dist/workspace/index.d.ts +1 -0
  166. package/dist/workspace/index.js +2 -0
  167. package/dist/workspace/resolve-computer.d.ts +32 -3
  168. package/dist/workspace/resolve-computer.js +47 -9
  169. package/launcher/agentrun-serve +6 -1
  170. package/package.json +10 -9
  171. package/templates/README.md +27 -2
  172. package/dist/console/assets/index-BNhZs-jp.css +0 -1
  173. package/dist/console/assets/index-BQv5aOGB.js +0 -700
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";
@@ -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";
@@ -136,8 +138,9 @@ import { webhook } from "./trigger-webhook.js";
136
138
  import { SCHEME_NAMES } from "./trigger-signatures.js";
137
139
  import { permissionFrom, pinnedEffect, toolEffect } from "./tool-gate.js";
138
140
  import { mcpNameOf as mcpToolOf, mcpToolName } from "./tool-names.js";
139
- import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, PAYLOAD_KEPT_BYTES, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
140
- import { applyBodyOf, choiceUnrunnable, COMPUTER_FIX, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, mcpSetUp, onServerName, onServers, packageDetail, packageModel, packageTiers, packageView, pickComputer, readPackages, serversFor, TemplateRegistry } from "./templates.js";
141
+ import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
142
+ import { PAYLOAD_KEPT_BYTES } from "./trigger-adapter.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";
141
144
  import { deleteTemplate, importTemplate, loadImported } from "./template-import.js";
142
145
  import { templateInstallLink, templateLink } from "./console-links.js";
143
146
  import { GITHUB_HOSTS } from "./template-source.js";
@@ -163,7 +166,7 @@ import { computerOfPlace } from "./computer-setting.js";
163
166
  import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
164
167
  import { fauxComputers } from "./faux-computers.js";
165
168
  import { writesHeld } from "./workspace.js";
166
- import { agentComputerOf, agentComputerView, agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, reconcileAgentComputer, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
169
+ import { agentComputerOf, agentComputerView, agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, reconcileAgentComputer, registryHere, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
167
170
  import { keyReader } from "./key-meta.js";
168
171
  export const CONTRACT = "agentrun.v2/0";
169
172
  /** A process's flags for a worker of it: without --input-type and the code string given with -e, --eval, -p or --print. */
@@ -220,7 +223,6 @@ async function tokenIn(file) {
220
223
  await writeDurable(file, `${token}\n`, 0o600, undefined, true);
221
224
  return { token, made: true };
222
225
  }
223
- const digest = (text) => createHash("sha256").update(text).digest();
224
226
  const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
225
227
  const SESSION_S = SESSION_MS / 1000;
226
228
  export const ROUTES = [
@@ -308,6 +310,8 @@ export const ROUTES = [
308
310
  { method: "POST", pattern: /^\/computers\/pairings$/, name: "createPairing" },
309
311
  { method: "POST", pattern: /^\/computers\/pair$/, name: "pairComputer" },
310
312
  { method: "GET", pattern: /^\/computers\/attach$/, name: "attachComputer" },
313
+ // A hosted machine's computerd build, fetched at its boot with the token its create minted (computer-attach.ts daemon).
314
+ { method: "GET", pattern: /^\/computers\/daemon$/, name: "getComputerDaemon" },
311
315
  { method: "DELETE", pattern: /^\/computers\/([^/]+)$/, name: "deleteComputer" },
312
316
  { method: "GET", pattern: /^\/workspace\/archil$/, name: "getWorkspaceArchil" },
313
317
  { method: "PUT", pattern: /^\/workspace\/archil$/, name: "putWorkspaceArchil" },
@@ -671,8 +675,17 @@ export async function startServe(options) {
671
675
  await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
672
676
  // Canonical once, here: a computer's mount source below it must then be its own canonical path, through no link.
673
677
  const data = await realpath(resolve(options.data));
674
- if (options.token !== undefined && (options.token.length < 32 || /\s/.test(options.token)))
675
- throw new Error("the token must be 32 characters or more, with no whitespace");
678
+ const tokenRefused = options.token === undefined ? undefined : tokenProblem(options.token);
679
+ if (tokenRefused)
680
+ throw new Error(tokenRefused);
681
+ for (const entry of options.tokens ?? []) {
682
+ const refused = tokenProblem(entry.token, `the API token ${entry.id}`);
683
+ if (refused)
684
+ throw new Error(refused);
685
+ }
686
+ // Ids each once, secrets each once (api-token.ts), checked before any lock is taken.
687
+ if (options.token !== undefined || (options.tokens?.length ?? 0) > 0)
688
+ acceptedTokens(options.token, options.tokens);
676
689
  if (options.drainTimeout !== undefined && durationMs(options.drainTimeout) === undefined)
677
690
  throw new Error(`the drain timeout ${options.drainTimeout} is not a duration such as 8s`);
678
691
  enabledBoxes(process.env);
@@ -795,7 +808,7 @@ async function startHolding(options, data, checked, stops) {
795
808
  // which the runner beside the server shares (Serve.attachHub), so one process holds them. A second server on this
796
809
  // store is refused above (its owner lock).
797
810
  const attachHub = new AttachHub();
798
- const attach = createAttachRoutes({ store, hub: attachHub, log: (event, fields) => (log ? log(logLine(event, fields)) : void process.stderr.write(`agentrun-serve: ${logLine(event, fields)}\n`)) });
811
+ 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`)) });
799
812
  // 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
800
813
  // store's lock holds one store, but the data root also holds what the server writes beside it (its token, its seal key,
801
814
  // uploads, harness installs, learning folders), which two servers on two stores (two Postgres schemas, or SQLite and
@@ -805,13 +818,17 @@ async function startHolding(options, data, checked, stops) {
805
818
  const dataLock = await whileReplaced(() => takeServerLock(data), (error) => error instanceof ServerLockHeldError, Math.max(replacedUntil, Date.now() + START_WAIT_MARGIN_MS), waitingForReplaced);
806
819
  stops.push(async () => dataLock.release());
807
820
  // The token, once both locks are held: a start the locks refuse reads, makes and removes nothing in the data root.
808
- const tokenFile = options.token === undefined ? join(data, TOKEN_FILE) : null;
809
- const stored = options.token === undefined ? await tokenIn(tokenFile) : undefined;
810
- const token = options.token ?? stored.token;
811
- // Given a token (AGENTRUN_TOKEN), a .token an earlier start made holds one this server refuses: it goes, so nothing
821
+ // Given a token list (AGENTRUN_TOKENS), DIR/.token is no token of this server's, as with AGENTRUN_TOKEN.
822
+ const given = options.token !== undefined || (options.tokens?.length ?? 0) > 0;
823
+ const tokenFile = given ? null : join(data, TOKEN_FILE);
824
+ const stored = given ? undefined : await tokenIn(tokenFile);
825
+ // Every token this server takes, by id (api-token.ts): AGENTRUN_TOKEN's (or DIR/.token's) as `default`, then the list's.
826
+ const tokens = acceptedTokens(options.token ?? stored?.token, options.tokens);
827
+ const token = tokens[0].token;
828
+ // Given a token (AGENTRUN_TOKEN or AGENTRUN_TOKENS), a .token an earlier start made holds one this server refuses: it goes, so nothing
812
829
  // (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
813
830
  // new file and token.
814
- if (options.token !== undefined)
831
+ if (given)
815
832
  await rm(join(data, TOKEN_FILE), { force: true });
816
833
  // No start without a seal key (seal-key.ts), checked against the store before anything reads it: the one handed over,
817
834
  // else the one in the data directory beside the store, made at the first start with only its path printed. A store whose
@@ -966,6 +983,8 @@ async function startHolding(options, data, checked, stops) {
966
983
  const adapters = options.triggerAdapters ?? TRIGGER_ADAPTERS;
967
984
  const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability, adapters);
968
985
  const sealKey = seal.key;
986
+ // SDK runs' credentials are signed with a key from the seal key, never an API token: a rotation leaves them working.
987
+ const sdkSecret = sdkRunSecret(sealKey);
969
988
  // Its runners on other hosts (AGENTRUN_RUNNER_HOSTS): a viewer's row naming one of their hosts is dialled there, with
970
989
  // the proxy's proof under the seal key (live-reach.ts); any other host is never dialled.
971
990
  const reach = liveReachOf(env, sealKey);
@@ -1008,7 +1027,9 @@ async function startHolding(options, data, checked, stops) {
1008
1027
  // probe Docker: a provider whose program is missing is not ready, and its words say what to install.
1009
1028
  const hostWhy = hostCommandRefusals(COMPUTER_PROVIDERS, process.env.PATH);
1010
1029
  const computersOf = () => (computerRoutes ??= createComputerRoutes({
1011
- store, sealKey, tools: kindTools, mode: folderModeOf(store, process.env), env: process.env,
1030
+ // A provider's key set where the server starts is one of its secrets, held off process.env (secrets.ts): read by name
1031
+ // from what the server was started with, as computerReady below reads it.
1032
+ store, sealKey, tools: kindTools, mode: folderModeOf(store, process.env), env: withSecrets(process.env, "own"),
1012
1033
  paired: { rows: () => store.pairedComputers.list(), viewOf: (row, serves) => pairedView(row, attachHub, serves) },
1013
1034
  ...(options.faux
1014
1035
  // --faux's providers stand in for every vendor's, a local one's daemon included.
@@ -1032,6 +1053,8 @@ async function startHolding(options, data, checked, stops) {
1032
1053
  const modeNow = async () => ((await folderModeOf(store, process.env)()) === "disk" ? 2 : 1);
1033
1054
  /** The registry a run's claim resolves against (claimKinds), as its runner composes it. */
1034
1055
  const claimRegistry = () => claimKinds(options.faux ? { faux: fauxOf() } : {});
1056
+ /** A key as the runner reads it: the secrets this process was started with (withSecrets "own"), else the saved one. */
1057
+ const runnerKeys = () => keyReader(store, sealKey, own(withSecrets(process.env, "own")));
1035
1058
  // A paired computer is one more provider of the registry (workspace/attached-computers.ts), ready while its driver is
1036
1059
  // attached to this process's hub.
1037
1060
  const computerReady = async (setting) => {
@@ -1040,12 +1063,12 @@ async function startHolding(options, data, checked, stops) {
1040
1063
  const offline = row ? pairedRefusal(row, attachHub) : undefined;
1041
1064
  if (offline)
1042
1065
  return { refused: offline };
1043
- 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));
1066
+ return computerReadiness(setting, await modeNow(), withPaired(claimRegistry(), paired), runnerKeys(), dockerAnswers, boxAllow, (provider) => (Object.hasOwn(hostWhy, provider) ? hostWhy[provider] : undefined));
1044
1067
  };
1045
1068
  /** Where a run of an agent with computer `setting` has its shell here now (resolve-computer.ts runShellOf, in the
1046
1069
  * folder mode of now, over the registry the claim reads): what runnable.ts lets a sandbox-only tool on the runner by,
1047
1070
  * and capabilities show bash by. In Mode 2 a run with no computer has bash on Archil's serverless exec. */
1048
- const shellOf = async (setting) => runShellOf(setting, await modeNow(), setting.provider === undefined ? claimRegistry() : withPaired(claimRegistry(), await store.pairedComputers.list()));
1071
+ const shellOf = async (setting) => runShellOf(setting, await modeNow(), await registryHere(setting.provider === undefined ? claimRegistry() : withPaired(claimRegistry(), await store.pairedComputers.list()), runnerKeys()));
1049
1072
  /** The shell this server can give a template's agent now (templates.ts pickComputer's `shell`), by the rules a run
1050
1073
  * has it by (shellOf): Archil's serverless exec on the runner in Mode 2 (bash alone); else the box a new agent is saved
1051
1074
  * with (Docker), where it answers now (computerReady asks the daemon, not the start's offers: a Docker stopped since
@@ -1078,7 +1101,8 @@ async function startHolding(options, data, checked, stops) {
1078
1101
  return { entry: pick.entry, computer: pick.computer, shell: pick.shell, dropped: pick.dropped, note: pick.note };
1079
1102
  };
1080
1103
  };
1081
- const archil = createArchilRoutes({ store, sealKey, env: process.env, ...(options.archilControl ? { control: options.archilControl } : {}) });
1104
+ // ARCHIL_API_KEY set where the server starts is one of its secrets, held off process.env (secrets.ts): read by name.
1105
+ const archil = createArchilRoutes({ store, sealKey, env: withSecrets(process.env, "own"), ...(options.archilControl ? { control: options.archilControl } : {}) });
1082
1106
  /** Where a run of `revision` has its shell (shellOf): its computer setting as the claim reads it (computer-for-claim.ts
1083
1107
  * settingOf), else its place's computer, else the place its run would resolve to (fallbackPlace). The agent's tool
1084
1108
  * list reads it, so a tool of bash's family the run would not have shows unavailable (tool-plane.ts shellUnavailable). */
@@ -1112,7 +1136,7 @@ async function startHolding(options, data, checked, stops) {
1112
1136
  close: () => store.close(),
1113
1137
  };
1114
1138
  ({ 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`))));
1115
- secretStores.add("server", () => [token]);
1139
+ secretStores.add("server", () => tokens.map((entry) => entry.token));
1116
1140
  // The email account's password (email/account.ts), and each one saved since this server started: cut from everything
1117
1141
  // it shows, so a tool's error or a model's text that ever echoed it shows it nowhere.
1118
1142
  const emailPasswords = new Set();
@@ -1129,6 +1153,7 @@ async function startHolding(options, data, checked, stops) {
1129
1153
  const signIns = signInsOverStore(store, sealKey, vendorsOver(() => env, checkFetch));
1130
1154
  const webhooks = new Webhooks(store, sealKey, (fields) => (log ? log(logLine("webhook", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("webhook", fields)}\n`)), {
1131
1155
  ...(options.webhookRetryMs ? { retryMs: options.webhookRetryMs } : {}),
1156
+ ...(options.webhookLookup ? { lookup: options.webhookLookup } : {}),
1132
1157
  privateTargets: options.webhookPrivateTargets ?? process.env.AGENTRUN_WEBHOOK_PRIVATE_TARGETS === "1",
1133
1158
  });
1134
1159
  // The outbound webhook's secret, as it stands (set by a PUT, gone with a DELETE), and each it held before.
@@ -1336,7 +1361,7 @@ async function startHolding(options, data, checked, stops) {
1336
1361
  // (liveViewerLink, the one the runner's browser tool wrote under its claim), opened with the server's seal key. The
1337
1362
  // timeline route keeps its own stub (store-reads journal + SSE) until E2c's timeline lands.
1338
1363
  const runReadsDeps = {
1339
- runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey, env: process.env }),
1364
+ runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey, env: withSecrets(process.env, "own") }),
1340
1365
  env,
1341
1366
  runFacts: (_store, runId) => factsOverStore(store, runId, viewDepsFor(ownOriginOf())),
1342
1367
  withheld: (_store, runId) => withheldOverStore(store, runId, viewDepsFor(ownOriginOf())),
@@ -1372,7 +1397,16 @@ async function startHolding(options, data, checked, stops) {
1372
1397
  },
1373
1398
  };
1374
1399
  const targets = triggerTargets(store, triggerDeps);
1375
- const expected = digest(`Bearer ${token}`);
1400
+ // Every presented token is checked here, against every token the server takes, in constant time (api-token.ts). The id
1401
+ // of the one that opened a request is kept with it for its log line (tokenUsed), never the secret.
1402
+ const bearerOf = bearerCheck(tokens);
1403
+ const tokenUsed = new WeakMap();
1404
+ const bearer = (header, req) => {
1405
+ const id = bearerOf(header);
1406
+ if (id !== undefined && req)
1407
+ tokenUsed.set(req, id);
1408
+ return id !== undefined;
1409
+ };
1376
1410
  const keptFile = join(data, IDEMPOTENCY_FILE);
1377
1411
  const kept = JSON.parse(await readFile(keptFile, "utf8").catch(() => "null"));
1378
1412
  const idempotency = new Map((kept?.entries ?? []).filter(([, v]) => v?.answer && Date.now() - v.at <= IDEMPOTENCY_TTL_S * 1000));
@@ -1493,7 +1527,9 @@ async function startHolding(options, data, checked, stops) {
1493
1527
  adapters,
1494
1528
  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),
1495
1529
  // The email trigger's account, its password opened as it polls (email/account.ts): never kept in the engine.
1496
- credentials: async (kind) => (kind === "email" ? openAccount(store, sealKey) : undefined),
1530
+ // 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
1531
+ // or an eval's route to its fake feeds (feedsAt).
1532
+ credentials: async (kind) => (kind === "email" ? openAccount(store, sealKey) : kind === "feed" ? { ...(await mcpServers.outboundReach()), ...(options.feedsAt ? { route: options.feedsAt } : {}) } : undefined),
1497
1533
  say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
1498
1534
  // The trigger target policy (what a trigger may start or message, and in what words it is refused) is the one store's
1499
1535
  // (trigger-targets.ts, over the run write half and the run view): targetIssues, start, message, statusOf, runOf. The
@@ -1513,6 +1549,21 @@ async function startHolding(options, data, checked, stops) {
1513
1549
  signal: stopping.signal,
1514
1550
  say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
1515
1551
  });
1552
+ /** What a save refused while Composio triggers use the server says to do once they are gone (composio-triggers.ts inUse). */
1553
+ const SAVE_AFTER_TRIGGERS = "then save the server again";
1554
+ /** What a save over a preset server left at Composio (ComposioDropped), removed there with the key it was made with, in
1555
+ * words; when that key doesn't open here, all of it said to remove by hand. */
1556
+ const composioLeft = async (name, dropped) => "unusable" in dropped && (dropped.mcp || dropped.cleanup.remove.length) ? composioNote(name, dropped.cleanup, dropped.mcp ?? false, true)
1557
+ : await composioForget(options.composioControl ?? {}, "key" in dropped ? dropped.key : "", dropped.mcp, name, stopping.signal, dropped.cleanup);
1558
+ // The Composio preset's saves, the saves of the servers it made, and the MCP servers' deletes, one at a time, Composio's
1559
+ // calls included: a delete never removes there an auth config or account that a save still at Composio reuses (it would
1560
+ // find no record of it yet), and a save never reuses one a delete is removing. A failure of one never stops the next.
1561
+ let composioLast = Promise.resolve();
1562
+ const inComposioTurn = (work) => {
1563
+ const turn = composioLast.then(work, work);
1564
+ composioLast = turn.catch(() => undefined);
1565
+ return turn;
1566
+ };
1516
1567
  // A repair of the GitHub installations (below) stops before the triggers close, in a start that fails as in close.
1517
1568
  stops.push(() => githubConnect.close());
1518
1569
  stops.push(async () => triggers.close());
@@ -2144,7 +2195,9 @@ async function startHolding(options, data, checked, stops) {
2144
2195
  // Every trigger is checked as POST /triggers checks it, its parameters filled, before anything is made: a schedule
2145
2196
  // from a parameter that does not read, or a date that has passed, refuses the apply (422 under triggers.<i>). "Passed"
2146
2197
  // by the triggers' own clock, the one POST /triggers checks by and they fire by (a template eval case's `now`).
2147
- const refusedTriggers = madeTriggerIssues(made.triggers, options.triggerClock?.now() ?? Date.now(), pkg.inputSchema);
2198
+ // A feed trigger whose urls are one array parameter given empty reads no feed: skipped, never the apply (feedLeftEmpty).
2199
+ const emptyFeeds = new Set(made.triggers.flatMap((trigger, i) => (feedLeftEmpty(trigger) ? [i] : [])));
2200
+ const refusedTriggers = madeTriggerIssues(made.triggers, options.triggerClock?.now() ?? Date.now(), pkg.inputSchema).filter((issue) => !emptyFeeds.has(Number(/^triggers\.(\d+)\./.exec(issue.field)?.[1])));
2148
2201
  if (refusedTriggers.length)
2149
2202
  throw invalid(refusedTriggers);
2150
2203
  // POST /agents' and POST /triggers' own body limit: parameters filled in more than once can grow a package past it.
@@ -2157,11 +2210,14 @@ async function startHolding(options, data, checked, stops) {
2157
2210
  // Each webhook trigger's signing secret, minted as it is made: handed back in the apply's first answer alone, as POST
2158
2211
  // /triggers hands back its own, so the owner can give it to the sender.
2159
2212
  const secrets = [];
2160
- // A github trigger on a server GitHub is not connected to is skipped, never the apply: the agent stands, and the
2161
- // answer says to connect GitHub and apply again (a warning under triggers.<i>).
2162
- const unconnected = new Set();
2213
+ // A trigger this server can't set up yet (templates.ts TRIGGER_NOT_SET_UP_YET: a github one with GitHub not connected,
2214
+ // a composio one Composio can't reach or run as here) is skipped, never the apply: the agent stands, and the answer
2215
+ // says what to do (a warning under triggers.<i>). Kept with its refusal, whose words the warning carries.
2216
+ const unconnected = new Map();
2163
2217
  try {
2164
2218
  for (const [i, trigger] of made.triggers.entries()) {
2219
+ if (emptyFeeds.has(i))
2220
+ continue;
2165
2221
  try {
2166
2222
  const { id: madeId, secret } = await triggers.create({ ...trigger, target: { ...trigger.target, agent_id: entry.agent.id } });
2167
2223
  ids.push(madeId);
@@ -2169,8 +2225,8 @@ async function startHolding(options, data, checked, stops) {
2169
2225
  secrets.push({ trigger_id: madeId, secret });
2170
2226
  }
2171
2227
  catch (error) {
2172
- if (error instanceof ApiError && error.code === "github_not_connected" && isObject(trigger.source) && trigger.source.kind === "github") {
2173
- unconnected.add(i);
2228
+ if (error instanceof ApiError && isObject(trigger.source) && notSetUpYet(trigger.source.kind, error.code)) {
2229
+ unconnected.set(i, error);
2174
2230
  continue;
2175
2231
  }
2176
2232
  if (error instanceof ApiError && error.code === "input_invalid" && error.extra.fields)
@@ -2207,12 +2263,19 @@ async function startHolding(options, data, checked, stops) {
2207
2263
  const githubTriggers = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "github"
2208
2264
  ? [unconnected.has(i) ? { field: `triggers.${i}`, reason: NOT_SET_UP, message: githubTriggerUnconnected(pkg.name, trigger.source) } : { field: `triggers.${i}`, reason: "not_an_option", message: githubTriggerWords(pkg.name, trigger.source) }]
2209
2265
  : []));
2266
+ // Each composio trigger it skipped: which, the refusal's words, and where to make it once that's fixed.
2267
+ const composioSkipped = made.triggers.flatMap((trigger, i) => {
2268
+ const refused = unconnected.get(i);
2269
+ 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 }] : [];
2270
+ });
2271
+ // Each feed trigger it skipped for want of a feed: which, and the parameter to set.
2272
+ 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) }));
2210
2273
  // Each trigger it made, a webhook trigger's with its secret's metadata; the values go back beside the answer, never in it
2211
2274
  // (the route adds them to the first answer to the owner's session, after the Idempotency-Key's record is written).
2212
2275
  const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
2213
2276
  // Which saved server each MCP need runs on (null: none here, said under mcp.<toolkit>).
2214
2277
  const used = Object.fromEntries(mapped.map(({ need, server }) => [need.toolkit, server]));
2215
- 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, ...appShort] };
2278
+ 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] };
2216
2279
  return { applied, minted };
2217
2280
  }
2218
2281
  /** A run create's issues told from the input this server checks (explain.ts): an agentic run's input schema in force
@@ -2413,7 +2476,7 @@ async function startHolding(options, data, checked, stops) {
2413
2476
  }
2414
2477
  /** A run create's body as POST /agents/{id}/runs checks it before it reads the agent: each field issue. */
2415
2478
  function runBodyIssues(body) {
2416
- const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "quote_id", "learning", "archil_disk", "repo", "workflow_first", "hold", "hold_minutes"]);
2479
+ const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "quote_id", "learning", "archil_disk", "repo", "workflow_first", "hold", "hold_minutes", "labels"]);
2417
2480
  issues.push(...holdIssues(body));
2418
2481
  if (body.repo !== undefined && !(typeof body.repo === "string" && REPO_NAME.test(body.repo)))
2419
2482
  issues.push({ field: "repo", reason: "wrong_type", message: "repo is a GitHub repository as owner/name, one the agent is bound to" });
@@ -2439,6 +2502,7 @@ async function startHolding(options, data, checked, stops) {
2439
2502
  issues.push({ field: "workflow_first", reason: "wrong_type", message: "workflow_first is true or false" });
2440
2503
  if (body.learning !== undefined && body.learning !== RUN_LEARNING_USE)
2441
2504
  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)` });
2505
+ issues.push(...labelsIssues(body.labels));
2442
2506
  return issues;
2443
2507
  }
2444
2508
  /** A page of runs from the store, newest first: `agent`, `revision` and `status` narrow it. */
@@ -2459,8 +2523,10 @@ async function startHolding(options, data, checked, stops) {
2459
2523
  if (value !== undefined && !ID.test(value))
2460
2524
  throw new ApiError("bad_request", `${key} is an id`);
2461
2525
  const archived = archivedParam(url);
2526
+ // `label=<key>:<value>`, once: only the runs holding it (run-labels.ts), filtered in the store.
2527
+ const labels = labelFilter(url.searchParams.getAll("label"));
2462
2528
  const vd = viewDepsFor(origin);
2463
- let rows = (await listRunsOverStore(store, filter, ctx)).filter((row) => Boolean(row.archivedAt) === archived);
2529
+ let rows = (await listRunsOverStore(store, { ...filter, ...(labels ? { labels } : {}) }, ctx)).filter((row) => Boolean(row.archivedAt) === archived);
2464
2530
  if (status !== null) {
2465
2531
  // The v2 status is the run view's (store-view over the journal), per row.
2466
2532
  const statuses = await Promise.all(rows.map((row) => viewOverStore(store, row.id, vd).then((v) => v?.status)));
@@ -2704,7 +2770,7 @@ async function startHolding(options, data, checked, stops) {
2704
2770
  switch (path) {
2705
2771
  case "/setup": {
2706
2772
  const byToken = req.headers.authorization !== undefined;
2707
- if (byToken && !timingSafeEqual(digest(String(req.headers.authorization)), expected))
2773
+ if (byToken && !bearer(req.headers.authorization, req))
2708
2774
  throw new ApiError("unauthenticated", "the Bearer here is the server's token, or none", {}, { "www-authenticate": "Bearer" });
2709
2775
  if (!byToken)
2710
2776
  fromPage(req);
@@ -2718,7 +2784,7 @@ async function startHolding(options, data, checked, stops) {
2718
2784
  const along = body.import === true ? { keep: () => writeDurable(importAsked, ""), drop: () => rm(importAsked, { force: true }) } : undefined;
2719
2785
  // The server's API token stands in for the code in the code field too (on Render it is in the Environment tab, the
2720
2786
  // code only in the log), compared as the header is, in constant time; a wrong one counts as a wrong code.
2721
- const tokenAsCode = typeof body.code === "string" && body.code !== "" && timingSafeEqual(digest(`Bearer ${body.code}`), expected);
2787
+ const tokenAsCode = typeof body.code === "string" && body.code !== "" && bearer(`Bearer ${body.code}`, req);
2722
2788
  const made = await me.setFirst(password, body.code, byToken || tokenAsCode, along);
2723
2789
  if (made === "exists")
2724
2790
  throw new ApiError("forbidden", "this server has its owner, or is being set up: sign in");
@@ -2911,6 +2977,20 @@ async function startHolding(options, data, checked, stops) {
2911
2977
  // limited by source address before anything in the body is checked.
2912
2978
  if (found.name === "pairComputer")
2913
2979
  return send(res, 201, await attach.pair(await bodyOf(req), clientOf(req)), { "cache-control": "no-store" });
2980
+ // A hosted machine fetching this server's computerd build: the token its create minted is its credential, never the
2981
+ // owner's (computer-attach.ts daemon).
2982
+ if (found.name === "getComputerDaemon") {
2983
+ const file = await attach.daemon(req.headers.authorization, url.searchParams.get("arch")).catch((error) => {
2984
+ if (error instanceof ApiError && error.status === 401)
2985
+ authFailed(`/v2${path}`, "machine_token");
2986
+ throw error;
2987
+ });
2988
+ const bytes = await readFile(file).catch(() => {
2989
+ throw new ApiError("unavailable", `this server has no computerd build at ${file}: run npm run build:daemon -w @parcha/agentrun-computer where it runs`);
2990
+ });
2991
+ res.writeHead(200, { "content-type": "application/octet-stream", "content-length": String(bytes.length), "cache-control": "no-store", "x-content-type-options": "nosniff" });
2992
+ return void res.end(req.method === "HEAD" ? undefined : bytes);
2993
+ }
2914
2994
  // An MCP server's OAuth sign-in: the browser coming back from its authorization server carries no token (the state
2915
2995
  // it brings is the check, mcp-oauth.ts), and the client metadata document is for that server to fetch.
2916
2996
  if (found.name === "mcpOAuthCallback") {
@@ -3043,7 +3123,7 @@ async function startHolding(options, data, checked, stops) {
3043
3123
  if (found.name === "importRemoteTarget")
3044
3124
  return send(res, 200, await broker.importTarget(connectorId, body));
3045
3125
  if (found.name === "importRemoteHistory")
3046
- return send(res, 200, await broker.importHistory(connectorId, decodeURIComponent(parts[2]), body, [token, String(req.headers.authorization ?? "").replace(/^Bearer /, "")]));
3126
+ return send(res, 200, await broker.importHistory(connectorId, decodeURIComponent(parts[2]), body, [...tokens.map((entry) => entry.token), String(req.headers.authorization ?? "").replace(/^Bearer /, "")]));
3047
3127
  if (found.name === "pollRemoteConnector")
3048
3128
  return send(res, 200, await broker.poll(connectorId, body));
3049
3129
  const commandId = decodeURIComponent(parts[2]);
@@ -3051,7 +3131,7 @@ async function startHolding(options, data, checked, stops) {
3051
3131
  }
3052
3132
  if (["getSdkRun", "sdkRunEvents", "completeSdkRun"].includes(found.name)) {
3053
3133
  const runId = decodeURIComponent(found.pattern.exec(path)[1]);
3054
- const sdk = new SdkRuns(store, data, token, serverSecrets);
3134
+ const sdk = new SdkRuns(store, data, sdkSecret, serverSecrets, tokens.map((entry) => entry.token));
3055
3135
  await sdk.authenticate(runId, String(req.headers.authorization ?? "").replace(/^Bearer /, ""));
3056
3136
  if (found.name === "sdkRunEvents")
3057
3137
  return send(res, 200, await sdk.events(runId, await bodyOf(req)));
@@ -3059,7 +3139,7 @@ async function startHolding(options, data, checked, stops) {
3059
3139
  return send(res, 200, await sdk.complete(runId, await bodyOf(req)));
3060
3140
  return send(res, 200, { ...await sdk.status(runId), learning: await servedRunLearning({ serverSecrets, signIns, statuses }, store, runId) });
3061
3141
  }
3062
- if (!timingSafeEqual(digest(String(req.headers.authorization ?? "")), expected)) {
3142
+ if (!bearer(req.headers.authorization, req)) {
3063
3143
  authFailed(`/v2${path}`, req.headers.authorization === undefined ? "no_credential" : "wrong_token");
3064
3144
  throw new ApiError("unauthenticated", "this route needs Authorization: Bearer <the token in the data directory>", {}, { "www-authenticate": "Bearer" });
3065
3145
  }
@@ -3083,7 +3163,7 @@ async function startHolding(options, data, checked, stops) {
3083
3163
  }
3084
3164
  catch { }
3085
3165
  }
3086
- const sdk = new SdkRuns(store, data, token, serverSecrets);
3166
+ const sdk = new SdkRuns(store, data, sdkSecret, serverSecrets, tokens.map((entry) => entry.token));
3087
3167
  const answer = await idempotent(req, path, body, async (origin) => ({ status: 201, body: await sdk.start(entry, body, { ...startDeps, ...(gradeModel ? { gradeModel } : {}) }, origin, async (model) => {
3088
3168
  try {
3089
3169
  const route = await gradeRouteFor({ model, agentId: id }, env, sdkModelRoute);
@@ -3743,9 +3823,30 @@ async function startHolding(options, data, checked, stops) {
3743
3823
  case "previewMcpServer":
3744
3824
  return send(res, 200, await mcpServers.preview(await bodyOf(req), stopping.signal));
3745
3825
  case "saveMcpServer": {
3746
- const saved = await mcpServers.save(id, await bodyOf(req), stopping.signal, secretSeen);
3826
+ const body = await bodyOf(req);
3827
+ // A server that isn't a Composio preset's is saved at once, as ever: no save waits on another's listing.
3828
+ if (!(await mcpServers.composioPreset(id))) {
3829
+ const saved = await mcpServers.save(id, body, stopping.signal, secretSeen);
3830
+ await refreshMcpMeta();
3831
+ return send(res, 200, saved);
3832
+ }
3833
+ // A preset server's: listed as any save is, at once; then its write and cleanup in the Composio turn and its
3834
+ // project's. A save that moves it off Composio is refused while Composio triggers use it, in the delete's words;
3835
+ // else it removes there what its save made (the MCP server, then what no other saved server uses), as a delete
3836
+ // does, with the key it was saved with, and says so.
3837
+ const over = {};
3838
+ const guard = {
3839
+ turn: (work) => inComposioTurn(async () => {
3840
+ const done = await composioTriggers.inTurnOf(id, work);
3841
+ if (over.dropped)
3842
+ over.note = await composioLeft(id, over.dropped);
3843
+ return done;
3844
+ }),
3845
+ inUse: () => composioTriggers.inUse(id, SAVE_AFTER_TRIGGERS),
3846
+ };
3847
+ const saved = await mcpServers.save(id, body, stopping.signal, secretSeen, undefined, undefined, (left) => (over.dropped = left), guard);
3747
3848
  await refreshMcpMeta();
3748
- return send(res, 200, saved);
3849
+ return send(res, 200, over.note ? { ...saved, composio: over.note } : saved);
3749
3850
  }
3750
3851
  // Composio makes the managed MCP server; what is kept is the ordinary MCP save, so the key is a sealed header.
3751
3852
  case "listComposioTools":
@@ -3754,8 +3855,18 @@ async function startHolding(options, data, checked, stops) {
3754
3855
  // The name is checked before Composio is called: a refused name leaves nothing made there.
3755
3856
  mcpNameOf(id);
3756
3857
  const body = await bodyOf(req);
3757
- 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);
3758
- await refreshMcpMeta();
3858
+ // In the Composio turn. A save over a preset server removes there, once it is saved, the MCP server the save before
3859
+ // made and what that save made that this one no longer stands on (an account of another user, an auth config of
3860
+ // another toolkit), with the key it was made with, and says so as a delete does; what another saved server uses is
3861
+ // that one's now, and said too. A save as another user or auth config is refused while Composio triggers use the
3862
+ // server, in the delete's words, checked in its project's turn before the row is written.
3863
+ const answer = await inComposioTurn(async () => {
3864
+ const over = {};
3865
+ const guard = { turn: (work) => composioTriggers.inTurnOf(id, work), inUse: () => composioTriggers.inUse(id, SAVE_AFTER_TRIGGERS) };
3866
+ 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);
3867
+ await refreshMcpMeta();
3868
+ return over.dropped ? { ...saved, composio: await composioLeft(id, over.dropped) } : saved;
3869
+ });
3759
3870
  return send(res, 200, answer, { "cache-control": "no-store" });
3760
3871
  }
3761
3872
  case "listComposioEvents":
@@ -3812,14 +3923,18 @@ async function startHolding(options, data, checked, stops) {
3812
3923
  return send(res, 200, await privateHostsRoute(mcpServers, { method: "PUT", body: () => bodyOf(req) }), { "cache-control": "no-store" });
3813
3924
  case "deleteMcpServer": {
3814
3925
  // Our row goes first, by the checked removal (a 412 sends Composio nothing), and answers what it removed: a Composio
3815
- // preset server's MCP server on Composio is deleted next, as the row removed named it and with its saved key.
3816
- // Composio refusing or not answering, or a key that does not open, never keeps our row: the answer says what to
3817
- // remove there by hand. One that Composio triggers still use is kept: refused, naming them, checked and deleted in
3818
- // its Composio project's turn, so a trigger still being made on it is counted (composio-triggers.ts deleting).
3819
- const { composio: made } = await composioTriggers.deleting(id, () => mcpServers.remove(id, secretSeen));
3820
- await refreshMcpMeta();
3821
- const forgotten = !made ? undefined : "unusable" in made ? composioNote(id) : await composioForget(options.composioControl ?? {}, made.key, made.id, id, stopping.signal);
3822
- if (forgotten && !forgotten.removed)
3926
+ // preset server's MCP server on Composio is deleted next, as the row removed named it and with its saved key, then
3927
+ // what its save made for it there that no other saved server uses (its connect link's account, its auth config).
3928
+ // Composio refusing or not answering, or a key that does not open, never keeps our row. A preset's answer says in
3929
+ // 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
3930
+ // its Composio project's turn, so a trigger still being made on it is counted (composio-triggers.ts deleting). All of
3931
+ // it in the Composio turn, so a Composio save still at work finishes first and its record is counted.
3932
+ const forgotten = await inComposioTurn(async () => {
3933
+ const { composio: made } = await composioTriggers.deleting(id, () => mcpServers.remove(id, secretSeen));
3934
+ await refreshMcpMeta();
3935
+ return !made ? undefined : "unusable" in made ? composioNote(id, made.cleanup) : await composioForget(options.composioControl ?? {}, made.key, made.id, id, stopping.signal, made.cleanup);
3936
+ });
3937
+ if (forgotten)
3823
3938
  return send(res, 200, { deleted: true, composio: forgotten }, { "cache-control": "no-store" });
3824
3939
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
3825
3940
  }
@@ -4108,7 +4223,7 @@ async function startHolding(options, data, checked, stops) {
4108
4223
  throw new ApiError("not_found", `no route ${path}`);
4109
4224
  }
4110
4225
  // The MCP endpoint's tools are the routes above, called in process with the caller's token (mcp.ts).
4111
- const mcp = mcpEndpoint({ route, authorized: (header) => timingSafeEqual(digest(header), expected), authFailed, version: VERSION });
4226
+ const mcp = mcpEndpoint({ route, authorized: (header, req) => bearer(header, req), authFailed, version: VERSION });
4112
4227
  function send(res, status, body, headers = {}) {
4113
4228
  const text = JSON.stringify(body);
4114
4229
  res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", "x-content-type-options": "nosniff", ...headers });
@@ -4151,7 +4266,12 @@ async function startHolding(options, data, checked, stops) {
4151
4266
  const started = performance.now();
4152
4267
  const method = req.method ?? "GET";
4153
4268
  const path = (req.url ?? "/").split("?")[0];
4154
- res.once("finish", () => log(logLine("request", { method, path, status: res.statusCode, ms: Math.round(performance.now() - started) })));
4269
+ // Who the request was answered for: the owner's or the console's session, or the id of the API token it carried
4270
+ // (api-token.ts), never a secret. A request opened by neither has no such field.
4271
+ res.once("finish", () => {
4272
+ const by = byOwnerSession(req) ? { session: "owner" } : byConsoleSession(req) ? { session: "console" } : tokenUsed.has(req) ? { token: tokenUsed.get(req) } : {};
4273
+ log(logLine("request", { method, path, status: res.statusCode, ms: Math.round(performance.now() - started), ...by }));
4274
+ });
4155
4275
  }
4156
4276
  const fail = (error) => {
4157
4277
  if (res.headersSent)
@@ -4198,7 +4318,7 @@ async function startHolding(options, data, checked, stops) {
4198
4318
  if (answerPage(req, res, raw, { token, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(consoleSessions ? { sessions: consoleSessions } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
4199
4319
  return;
4200
4320
  if (isObservationRoute(raw))
4201
- return void observationHttp(req, res, url, new Observations(store), token).catch(fail);
4321
+ return void observationHttp(req, res, url, new Observations(store), (header) => bearer(header, req)).catch(fail);
4202
4322
  if (!raw.startsWith("/v2/"))
4203
4323
  return fail(new ApiError("not_found", `no route ${raw}; the API is under /v2`));
4204
4324
  // 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
@@ -4223,10 +4343,12 @@ async function startHolding(options, data, checked, stops) {
4223
4343
  // away. Its name alone, on any port, as the HTTP routes check it.
4224
4344
  if (names && !names.has(hostName(req.headers.host) ?? ""))
4225
4345
  return deny("403 Forbidden");
4226
- // API-only: a run's live view is the console's, and refused with it; so are paired computers (Settings).
4227
- if (options.apiOnly)
4346
+ // API-only: a run's live view is the console's, and refused with it; so are paired computers (Settings), whose tokens
4347
+ // the attach socket takes as unknown there (machinesOnly). A run's hosted machine that dials still reaches it.
4348
+ if (options.apiOnly && raw !== ATTACH_PATH)
4228
4349
  return deny("404 Not Found");
4229
- // A paired computer's driver dialing its attach socket (computer-attach.ts): its token, not the owner's, lets it in.
4350
+ // A paired computer's driver or a hosted machine dialing the attach socket (computer-attach.ts): its token, not the
4351
+ // owner's, lets it in.
4230
4352
  if (raw === ATTACH_PATH) {
4231
4353
  return attach.upgrade(req, socket, head, (status, words = "", headers = {}) => {
4232
4354
  if (status.startsWith("401"))
@@ -4620,13 +4742,16 @@ async function startHolding(options, data, checked, stops) {
4620
4742
  baseUrl: `${url}/v2`,
4621
4743
  port: address.port,
4622
4744
  token,
4745
+ tokenIds: tokens.map((entry) => entry.id),
4623
4746
  tokenFile,
4624
4747
  tokenMade: stored?.made ?? false,
4625
4748
  ...(setupUrl ? { setupUrl, setupOpen: openSetup } : {}),
4626
4749
  ...(consoleSessions ? { launchCode: consoleSessions.code } : {}),
4627
4750
  boxesLine: boxesLine(boxOffers, enabledBoxes(env), boxAllow, boxesByDefault(env)),
4628
4751
  attachHub,
4752
+ dial: { ...(options.publicUrl ? { url: options.publicUrl.replace(/\/+$/, "") } : {}), tokens: attach.machineTokens, hub: attachHub },
4629
4753
  localInstall,
4754
+ own: mcpServers.own,
4630
4755
  // Once: a second call, at any time, is the first one's promise, so a close repeated after the next server started
4631
4756
  // never writes this data root's record again (the next server's, by then).
4632
4757
  close: () => (stopped ??= stop()),
@@ -10,6 +10,9 @@ export interface Dialect {
10
10
  jsonNotFalse(column: string, path: readonly string[]): string;
11
11
  /** True when the JSON array in TEXT column `column` holds the string parameter that follows (one `?`). */
12
12
  jsonArrayHas(column: string): string;
13
+ /** True when the JSON object of strings in TEXT column `column` holds the key and the value of the two string parameters
14
+ * that follow (two `?`): bound, never spliced, so any key reads safely. False when the column is NULL. */
15
+ jsonObjectHas(column: string): string;
13
16
  /** The length of the JSON array in TEXT column `column`. */
14
17
  jsonArrayLength(column: string): string;
15
18
  /** The JSON object in TEXT column `column` without its top-level `key`. */
@@ -50,6 +53,9 @@ export interface Dialect {
50
53
  * trigger's firings, an agent's current revision) is not interleaved with another. `"update"`: the run row of a write
51
54
  * that moves its epoch (a release, a run's end), held against every write under the claim (`shareLock`) as well. */
52
55
  lockRow(tx: LockExecutor, table: string, column: string, value: string, mode?: "update"): Promise<void>;
56
+ /** lockRow (its first form) of every row whose `column` is one of `values`, in one statement and in `column`'s order, so
57
+ * two transactions holding overlapping sets never wait on each other in a cycle. */
58
+ lockRows(tx: LockExecutor, table: string, column: string, values: readonly string[]): Promise<void>;
53
59
  /** Holds the named lock until the transaction ends: two transactions that each check, then write what the other checks. */
54
60
  lockKey(tx: LockExecutor, key: string): Promise<void>;
55
61
  }
@@ -15,6 +15,7 @@ export const SQLITE = {
15
15
  jsonText: (column, path) => `json_extract(${column}, ${jsonPath(path)})`,
16
16
  jsonNotFalse: (column, path) => `json_extract(${column}, ${jsonPath(path)}) IS NOT 0`,
17
17
  jsonArrayHas: (column) => `EXISTS (SELECT 1 FROM json_each(${column}) WHERE value = ?)`,
18
+ jsonObjectHas: (column) => `EXISTS (SELECT 1 FROM json_each(${column}) AS entry WHERE entry.key = ? AND entry.value = ?)`,
18
19
  jsonArrayLength: (column) => `json_array_length(${column})`,
19
20
  jsonWithout: (column, key) => `json_remove(${column}, ${jsonPath([key])})`,
20
21
  firingOrder: "rowid",
@@ -29,6 +30,7 @@ export const SQLITE = {
29
30
  claimOneLock: "",
30
31
  shareLock: "",
31
32
  lockRow: async () => undefined,
33
+ lockRows: async () => undefined,
32
34
  lockKey: async () => undefined,
33
35
  };
34
36
  /** The SET fragment every statement that settles command rows (taken or refused) carries: a computer call's params go