@parcha/agentrun-serve 0.1.0-beta.40 → 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 (126) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +78 -15
  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-B8Zn1Iqn.css → index-C3gNPz58.css} +1 -1
  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/eval-feed.d.ts +26 -0
  25. package/dist/eval-feed.js +68 -0
  26. package/dist/eval-mailbox.d.ts +4 -1
  27. package/dist/eval-mailbox.js +11 -3
  28. package/dist/exa-keyless.d.ts +1 -1
  29. package/dist/exa-keyless.js +1 -1
  30. package/dist/feed/feed-faux.d.ts +62 -0
  31. package/dist/feed/feed-faux.js +123 -0
  32. package/dist/feed/fetch.d.ts +41 -0
  33. package/dist/feed/fetch.js +128 -0
  34. package/dist/feed/parse.d.ts +41 -0
  35. package/dist/feed/parse.js +300 -0
  36. package/dist/learn/check.d.ts +3 -1
  37. package/dist/learn/check.js +57 -2
  38. package/dist/learn/compile.js +1 -1
  39. package/dist/learned-nodes.d.ts +21 -4
  40. package/dist/learned-nodes.js +21 -8
  41. package/dist/learned-workflow.d.ts +3 -3
  42. package/dist/learned-workflow.js +14 -5
  43. package/dist/mcp-oauth.d.ts +15 -1
  44. package/dist/mcp-oauth.js +39 -5
  45. package/dist/mcp-pin-first.d.ts +4 -2
  46. package/dist/mcp-pin-first.js +4 -3
  47. package/dist/mcp-servers-store.d.ts +58 -5
  48. package/dist/mcp-servers-store.js +136 -17
  49. package/dist/mcp.d.ts +2 -2
  50. package/dist/mcp.js +2 -2
  51. package/dist/observation/http.d.ts +4 -1
  52. package/dist/observation/http.js +5 -4
  53. package/dist/openapi.js +46 -12
  54. package/dist/print.d.ts +6 -3
  55. package/dist/print.js +4 -2
  56. package/dist/run-labels.d.ts +23 -0
  57. package/dist/run-labels.js +79 -0
  58. package/dist/run-secrets.js +12 -4
  59. package/dist/runner/adapter-loop.js +91 -10
  60. package/dist/runner/adapter-run-spec.d.ts +4 -0
  61. package/dist/runner/adapter-run-spec.js +38 -31
  62. package/dist/runner/beside.d.ts +6 -3
  63. package/dist/runner/beside.js +9 -7
  64. package/dist/runner/cli-run-spec.js +32 -26
  65. package/dist/runner/conformance/harness.js +69 -14
  66. package/dist/runner/conformance/subject.d.ts +4 -1
  67. package/dist/runner/main.d.ts +1 -1
  68. package/dist/runner/main.js +2 -2
  69. package/dist/runner/mcp-claim.d.ts +3 -0
  70. package/dist/runner/mcp-claim.js +1 -1
  71. package/dist/runner/mcp-run.d.ts +4 -0
  72. package/dist/runner/mcp-run.js +5 -3
  73. package/dist/runner/model-route.d.ts +4 -2
  74. package/dist/runner/model-route.js +8 -8
  75. package/dist/runner/promotion.d.ts +8 -0
  76. package/dist/runner/promotion.js +43 -1
  77. package/dist/runner/workflow-first.d.ts +6 -5
  78. package/dist/runner/workflow-first.js +9 -7
  79. package/dist/runs-over-store.js +5 -2
  80. package/dist/sdk/runs.d.ts +7 -1
  81. package/dist/sdk/runs.js +19 -6
  82. package/dist/secret-cut.js +3 -1
  83. package/dist/secrets.js +3 -1
  84. package/dist/server.d.ts +27 -2
  85. package/dist/server.js +168 -50
  86. package/dist/store/dialect.d.ts +3 -0
  87. package/dist/store/dialect.js +1 -0
  88. package/dist/store/index.d.ts +1 -1
  89. package/dist/store/postgres/dialect.js +1 -0
  90. package/dist/store/postgres/migrations/0015_run_labels.sql +5 -0
  91. package/dist/store/postgres/migrations/0016_minted_tokens.sql +21 -0
  92. package/dist/store/schema.d.ts +9 -0
  93. package/dist/store/schema.js +26 -2
  94. package/dist/store/sqlite/connection.js +11 -3
  95. package/dist/store/sqlite/run-patch.d.ts +2 -1
  96. package/dist/store/sqlite/run-patch.js +3 -2
  97. package/dist/store/sqlite/store.js +64 -10
  98. package/dist/store/store.d.ts +38 -1
  99. package/dist/store-reads/journal.js +2 -1
  100. package/dist/store-reads/learning.js +6 -1
  101. package/dist/store-reads/runs.d.ts +4 -3
  102. package/dist/store-reads/runs.js +3 -2
  103. package/dist/store-view.js +4 -2
  104. package/dist/template-eval.d.ts +4 -0
  105. package/dist/template-eval.js +127 -50
  106. package/dist/templates.d.ts +10 -0
  107. package/dist/templates.js +75 -17
  108. package/dist/timeline/origin.d.ts +1 -1
  109. package/dist/timeline/origin.js +2 -2
  110. package/dist/trigger-adapter.d.ts +9 -4
  111. package/dist/trigger-adapters.js +2 -1
  112. package/dist/trigger-feed.d.ts +12 -0
  113. package/dist/trigger-feed.js +371 -0
  114. package/dist/triggers.d.ts +2 -1
  115. package/dist/triggers.js +23 -5
  116. package/dist/webhooks.js +9 -5
  117. package/dist/workspace/computer-deps.d.ts +5 -1
  118. package/dist/workspace/computer-deps.js +2 -2
  119. package/dist/workspace/index.d.ts +1 -0
  120. package/dist/workspace/index.js +2 -0
  121. package/dist/workspace/resolve-computer.d.ts +32 -3
  122. package/dist/workspace/resolve-computer.js +47 -9
  123. package/launcher/agentrun-serve +6 -1
  124. package/package.json +10 -9
  125. package/templates/README.md +27 -2
  126. package/dist/console/assets/index-Jbxjcmdp.js +0 -705
@@ -9,11 +9,16 @@
9
9
  // each, never the value. A wrong, used or expired code is one answer, 404 with no word about which, and each source
10
10
  // address gets PAIR_TRIES_PER_MINUTE tries a minute.
11
11
  //
12
+ // A hosted machine that dials this server (a dial provider's, spec/computer/attach.md) is let in by the token its create
13
+ // minted (machineTokens), kept as its SHA-256 until the machine's backstop or its delete: its socket goes to the hub under
14
+ // the machine's name, and it fetches this server's computerd build with the same token (GET /v2/computers/daemon,
15
+ // DAEMON_FETCHES_PER_MINUTE a minute per machine).
16
+ //
12
17
  // One process: the hub is this process's memory, so a run takes a paired computer only from a runner in the process
13
18
  // that holds its socket (the CLI's start, with its runner beside the server). A runner of its own process refuses one in
14
19
  // words (workspace/attached-computers.ts ONE_PROCESS_WORDS); a second server on the same store is refused at its start.
15
20
  import { createHash, randomBytes, randomInt } from "node:crypto";
16
- import { ATTACH_CLOSE, ATTACH_HEARTBEAT_MS, ATTACH_IDLE_MS, ATTACH_SUBPROTOCOL, MAX_LINE_BYTES, PAIRING_CODE_PATTERN, PAIRING_CODE_TTL_MS, PROTOCOL_VERSION, RUN_LABEL } from "@parcha/agentrun-computer";
21
+ import { ATTACH_CLOSE, ATTACH_HEARTBEAT_MS, ATTACH_IDLE_MS, ATTACH_SUBPROTOCOL, hostedDaemonPath, MAX_LINE_BYTES, mintedComputer, PAIRING_CODE_PATTERN, PAIRING_CODE_TTL_MS, PROTOCOL_VERSION, RUN_LABEL } from "@parcha/agentrun-computer";
17
22
  import { WebSocketServer } from "ws";
18
23
  import { ApiError, invalid } from "./errors.js";
19
24
  import { peerKey } from "./owner.js";
@@ -30,11 +35,13 @@ export const PAIRING_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
30
35
  export const ATTACH_TOKEN_PREFIX = "art_";
31
36
  /** Pair tries a source address makes in a minute; the next waits. */
32
37
  export const PAIR_TRIES_PER_MINUTE = 10;
33
- const PAIR_WINDOW_MS = 60_000;
34
- /** The most source addresses the pair limit keeps at once; past it, those with no try in the window go first. */
35
- const PAIR_PEERS = 10_000;
36
- /** The one key the addresses the full table has no room for are counted under (no address's key has a space). */
37
- const OVERFLOW_PEER = "every address past the table";
38
+ /** Daemon fetches a minted machine's token makes in a minute (GET /v2/computers/daemon); the next is 429. */
39
+ export const DAEMON_FETCHES_PER_MINUTE = 10;
40
+ const MINUTE_MS = 60_000;
41
+ /** The most keys a minute limit keeps at once; past it, those with no try in the window go first. */
42
+ const LIMIT_KEYS = 10_000;
43
+ /** The one key the keys the full table has no room for are counted under (no address's or machine's has a space). */
44
+ const OVERFLOW_KEY = "every key past the table";
38
45
  /** The longest name a person gives a computer, in characters. */
39
46
  export const PAIRED_NAME_MAX = 100;
40
47
  /** A WebSocket close frame's reason holds at most this many bytes of UTF-8. */
@@ -58,6 +65,12 @@ export function pairingCodeOf(typed) {
58
65
  export const newPairedId = (pick = randomInt) => `${PAIRED_ID_PREFIX}${Array.from({ length: 16 }, () => "abcdefghijkmnpqrstuvwxyz23456789"[pick(32)]).join("")}`;
59
66
  /** A new computer token: ATTACH_TOKEN_PREFIX and 32 random bytes. */
60
67
  export const newAttachToken = () => `${ATTACH_TOKEN_PREFIX}${randomBytes(32).toString("base64url")}`;
68
+ /** A new hosted machine's token: ATTACH_TOKEN_PREFIX and 32 random bytes in hex, which goes in the machine's env. */
69
+ export const newMintedToken = () => `${ATTACH_TOKEN_PREFIX}${randomBytes(32).toString("hex")}`;
70
+ /** The computerd builds a minted machine fetches (GET /v2/computers/daemon?arch=), each at hostedDaemonPath: the file a
71
+ * hosted provider uploads by default, so the route serves the bytes whose SHA-256 the provider puts in the machine's env. */
72
+ const DAEMON_ARCHES = ["amd64", "arm64"];
73
+ const isDaemonArch = (arch) => DAEMON_ARCHES.includes(arch);
61
74
  /** `reason` cut to what a close frame holds (123 bytes of UTF-8), never inside a character. */
62
75
  export function closeReason(reason) {
63
76
  if (Buffer.byteLength(reason) <= CLOSE_REASON_BYTES)
@@ -70,35 +83,47 @@ export function closeReason(reason) {
70
83
  }
71
84
  return `${cut}...`;
72
85
  }
73
- /** The pair route's limit: PAIR_TRIES_PER_MINUTE tries a minute by source address (peerKey: an IPv6 one by its /64). */
74
- export class PairTries {
86
+ /** A limit of `perMinute` tries a minute by key: the pair route's by source address (`keyOf` peerKey: an IPv6 one by its
87
+ * /64), the daemon route's by the minted token's machine. */
88
+ export class MinuteLimit {
89
+ perMinute;
90
+ keyOf;
75
91
  now;
76
- peers;
92
+ keys;
77
93
  #tries = new Map();
78
- constructor(now = Date.now, peers = PAIR_PEERS) {
94
+ constructor(perMinute, keyOf = (key) => key, now = Date.now, keys = LIMIT_KEYS) {
95
+ this.perMinute = perMinute;
96
+ this.keyOf = keyOf;
79
97
  this.now = now;
80
- this.peers = peers;
98
+ this.keys = keys;
81
99
  }
82
- /** Counts a try from `address`: ok, or how long until the next is let in. */
83
- allow(address) {
100
+ /** Counts a try by `key`: ok, or how long until the next is let in. */
101
+ allow(given) {
84
102
  const now = this.now();
85
- let key = peerKey(address);
86
- if (!this.#tries.has(key) && this.#tries.size >= this.peers) {
103
+ let key = this.keyOf(given);
104
+ if (!this.#tries.has(key) && this.#tries.size >= this.keys) {
87
105
  for (const [known, at] of this.#tries)
88
- if (!at.some((one) => now - one < PAIR_WINDOW_MS))
106
+ if (!at.some((one) => now - one < MINUTE_MS))
89
107
  this.#tries.delete(known);
90
- // A table still full of addresses trying now counts every address it has no room for as one: the table never grows
91
- // past its bound, and no address goes uncounted.
92
- if (this.#tries.size >= this.peers)
93
- key = OVERFLOW_PEER;
108
+ // A table still full of keys trying now counts every key it has no room for as one: the table never grows past its
109
+ // bound, and no key goes uncounted.
110
+ if (this.#tries.size >= this.keys)
111
+ key = OVERFLOW_KEY;
94
112
  }
95
- const recent = (this.#tries.get(key) ?? []).filter((at) => now - at < PAIR_WINDOW_MS);
96
- if (recent.length >= PAIR_TRIES_PER_MINUTE)
97
- return { ok: false, retryAfterMs: recent[0] + PAIR_WINDOW_MS - now };
113
+ const recent = (this.#tries.get(key) ?? []).filter((at) => now - at < MINUTE_MS);
114
+ if (recent.length >= this.perMinute)
115
+ return { ok: false, retryAfterMs: recent[0] + MINUTE_MS - now };
98
116
  this.#tries.set(key, [...recent, now]);
99
117
  return { ok: true };
100
118
  }
101
119
  }
120
+ /** The pair route's limit: PAIR_TRIES_PER_MINUTE tries a minute by source address. */
121
+ export const pairTries = (now = Date.now, keys = LIMIT_KEYS) => new MinuteLimit(PAIR_TRIES_PER_MINUTE, peerKey, now, keys);
122
+ /** A 429 for a limit's refusal, saying how long to wait. */
123
+ const limited = (what, retryAfterMs) => {
124
+ const seconds = Math.max(1, Math.ceil(retryAfterMs / 1000));
125
+ return new ApiError("rate_limited", `${what}; try again in ${seconds} s`, { retry_after_ms: retryAfterMs }, { "retry-after": String(seconds) });
126
+ };
102
127
  const KINDS = new Set(["linux", "desktop", "android", "ios", "browser"]);
103
128
  const OSES = new Set(["linux", "windows", "macos", "android", "ios"]);
104
129
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -157,6 +182,9 @@ export function pairedView(row, hub, serves) {
157
182
  const hello = hub.hello(row.id) ?? paired;
158
183
  const holder = hub.claimed(row.id)?.[RUN_LABEL] ?? null;
159
184
  const until = holder === null ? undefined : hub.deadline(row.id);
185
+ // The hub has the socket live before the store keeps its hello (attach's accept, then seen), so a list between the
186
+ // two reads the hub's time: an online computer is never listed as never seen.
187
+ const seen = hub.since(row.id)?.getTime() ?? row.seenAt;
160
188
  return {
161
189
  id: row.id,
162
190
  name: row.name,
@@ -176,7 +204,7 @@ export function pairedView(row, hub, serves) {
176
204
  held_until: until === undefined ? null : until.toISOString(),
177
205
  pairing: row.pairingId,
178
206
  created_at: new Date(row.createdAt).toISOString(),
179
- seen_at: row.seenAt === null ? null : new Date(row.seenAt).toISOString(),
207
+ seen_at: seen === null ? null : new Date(seen).toISOString(),
180
208
  };
181
209
  }
182
210
  /** One WebSocket as the hub takes it (attach.ts AttachSocket): text frames in and out; a ping each heartbeat; closed
@@ -226,11 +254,22 @@ export function attachSocketOf(ws, timing = { heartbeatMs: ATTACH_HEARTBEAT_MS,
226
254
  onClose: (listener) => (ended ? listener(ended.code, ended.reason) : void closes.push(listener)),
227
255
  };
228
256
  }
229
- /** The pairing routes and the attach socket over one store and one hub. */
257
+ /** A request's Bearer token, or undefined. */
258
+ const bearerOf = (authorization) => /^Bearer (\S+)$/.exec(String(authorization ?? ""))?.[1];
259
+ /** The attach socket's 401: a token no paired computer or hosted machine has good. */
260
+ const TOKEN_REFUSED = "no paired computer or hosted machine has this token: pair the computer again from the console's Computers page (a hosted machine's token ends at its delete or its backstop)";
261
+ /** The daemon route's 401: a token no hosted machine has good. */
262
+ const MACHINE_TOKEN_REFUSED = "no hosted machine has this token: a machine's token ends at its delete or its backstop";
263
+ /** Why a minted machine's socket closed at its token's revoke. */
264
+ const machineGone = (machine) => `${machine} was deleted: its token ends`;
265
+ /** The pairing routes, the attach socket and the daemon route over one store and one hub, and the tokens a dial
266
+ * provider mints. */
230
267
  export function createAttachRoutes(options) {
231
268
  const { store, hub, log = () => { }, now = Date.now } = options;
232
269
  const paired = store.pairedComputers;
233
- const tries = new PairTries(now);
270
+ const minted = store.mintedTokens;
271
+ const tries = pairTries(now);
272
+ const fetches = new MinuteLimit(DAEMON_FETCHES_PER_MINUTE, undefined, now);
234
273
  const sockets = new Set();
235
274
  let closing = false;
236
275
  const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_LINE_BYTES, clientTracking: false, handleProtocols: () => ATTACH_SUBPROTOCOL });
@@ -245,10 +284,8 @@ export function createAttachRoutes(options) {
245
284
  /** POST /v2/computers/pair: the code traded for the computer's id and token, once; `address` the try's source. */
246
285
  async function pair(body, address) {
247
286
  const allowed = tries.allow(address);
248
- if (!allowed.ok) {
249
- const seconds = Math.max(1, Math.ceil(allowed.retryAfterMs / 1000));
250
- throw new ApiError("rate_limited", `too many pairing tries from this address; try again in ${seconds} s`, { retry_after_ms: allowed.retryAfterMs }, { "retry-after": String(seconds) });
251
- }
287
+ if (!allowed.ok)
288
+ throw limited("too many pairing tries from this address", allowed.retryAfterMs);
252
289
  const { code, name, hello } = pairBodyOf(body);
253
290
  const refused = pairRefusal(name, hello);
254
291
  if (refused)
@@ -273,16 +310,73 @@ export function createAttachRoutes(options) {
273
310
  hub.revoke(id, `${row.name} was removed from this server's console: pair it again to use it`);
274
311
  log("computer_removed", { computer: id });
275
312
  }
276
- /** GET /v2/computers/attach's upgrade: the token's computer, then the protocol, then the hub's hello. A refusal is an
277
- * HTTP answer before the upgrade (401 for a token no paired computer has, 426 for another protocol version). */
313
+ /** A dial provider's tokens (computer package MachineTokens): a new one per create, kept as its SHA-256 by the machine
314
+ * (its name, from its create's request id) until `expiresAt` (its backstop); a revoke (its delete) ends it and closes
315
+ * its socket with 4401. */
316
+ const machineTokens = {
317
+ async mint(machine, { kind, os, arch, expiresAt }) {
318
+ const until = expiresAt.getTime();
319
+ if (!Number.isFinite(until))
320
+ throw new TypeError(`a machine token's expiresAt is a time, not ${JSON.stringify(expiresAt)}`);
321
+ const token = newMintedToken();
322
+ await minted.mint({ machine, tokenSha256: sha256Hex(token), kind, os, arch, expiresAt: until });
323
+ log("machine_token_minted", { machine, kind, os, arch, expires_at: new Date(until).toISOString() });
324
+ return token;
325
+ },
326
+ async revoke(machine) {
327
+ await minted.revoke(machine);
328
+ hub.revoke(machine, machineGone(machine));
329
+ log("machine_token_revoked", { machine });
330
+ },
331
+ };
332
+ const pairedDialer = (row) => ({
333
+ computer: pairedOf(row),
334
+ field: "computer",
335
+ event: "computer",
336
+ gone: `${row.name} was removed from this server's console: pair it again to use it`,
337
+ good: async () => (await paired.get(row.id))?.revokedAt === null,
338
+ seen: (hello) => paired.seen(row.id, hello),
339
+ });
340
+ const machineDialer = (row) => ({
341
+ computer: mintedComputer(row.machine, { kind: row.kind, os: row.os, arch: row.arch }),
342
+ field: "machine",
343
+ event: "machine",
344
+ gone: machineGone(row.machine),
345
+ good: async () => (await minted.get(row.machine))?.revokedAt === null,
346
+ seen: async () => undefined,
347
+ });
348
+ /** The minted machine whose good token `authorization` bears (Bearer), or undefined. */
349
+ async function machineBy(authorization) {
350
+ const bearer = bearerOf(authorization);
351
+ return bearer?.startsWith(ATTACH_TOKEN_PREFIX) ? minted.byToken(sha256Hex(bearer)) : undefined;
352
+ }
353
+ /** GET /v2/computers/daemon?arch=: the path of this server's computerd build for `arch`, for the minted machine whose
354
+ * token `authorization` bears. 401 for a token no machine has good (unknown, revoked or past its end); 429 past
355
+ * DAEMON_FETCHES_PER_MINUTE a minute by one machine; 422 for an arch with no build. */
356
+ async function daemon(authorization, arch) {
357
+ const machine = await machineBy(authorization);
358
+ if (machine === undefined)
359
+ throw new ApiError("unauthenticated", MACHINE_TOKEN_REFUSED, {}, { "www-authenticate": "Bearer" });
360
+ const allowed = fetches.allow(machine.machine);
361
+ if (!allowed.ok)
362
+ throw limited("too many daemon fetches with this machine's token", allowed.retryAfterMs);
363
+ if (!isDaemonArch(arch))
364
+ throw invalid([{ field: "arch", reason: "invalid", message: `arch is the machine's, ${DAEMON_ARCHES.join(" or ")}` }]);
365
+ return hostedDaemonPath(arch);
366
+ }
367
+ /** GET /v2/computers/attach's upgrade: the token's paired computer or minted machine, then the protocol, then the hub's
368
+ * hello. A refusal is an HTTP answer before the upgrade (401 for a token neither has good, 426 for another protocol
369
+ * version). A minted machine's socket goes to the hub under its name. */
278
370
  function upgrade(req, socket, head, deny) {
279
371
  void (async () => {
280
372
  if (closing)
281
373
  return deny("503 Service Unavailable", "this server is stopping");
282
- const bearer = /^Bearer (\S+)$/.exec(String(req.headers.authorization ?? ""))?.[1];
283
- const row = bearer?.startsWith(ATTACH_TOKEN_PREFIX) ? await paired.byToken(sha256Hex(bearer)) : undefined;
284
- if (row === undefined)
285
- return deny("401 Unauthorized", "no paired computer has this token: pair the computer again from the console's Computers page", { "www-authenticate": "Bearer" });
374
+ const bearer = bearerOf(req.headers.authorization);
375
+ const row = !options.machinesOnly && bearer?.startsWith(ATTACH_TOKEN_PREFIX) ? await paired.byToken(sha256Hex(bearer)) : undefined;
376
+ const machine = row === undefined ? await machineBy(req.headers.authorization) : undefined;
377
+ const dialer = row !== undefined ? pairedDialer(row) : machine !== undefined ? machineDialer(machine) : undefined;
378
+ if (dialer === undefined)
379
+ return deny("401 Unauthorized", options.machinesOnly ? MACHINE_TOKEN_REFUSED : TOKEN_REFUSED, { "www-authenticate": "Bearer" });
286
380
  const asked = String(req.headers["sec-websocket-protocol"] ?? "").split(",").map((one) => one.trim()).filter(Boolean);
287
381
  if (!asked.includes(ATTACH_SUBPROTOCOL)) {
288
382
  return deny("426 Upgrade Required", `this server speaks ${ATTACH_SUBPROTOCOL}, and the driver asked for ${asked.join(", ") || "no subprotocol"}: update whichever is older`, { "sec-websocket-protocol": ATTACH_SUBPROTOCOL });
@@ -293,22 +387,22 @@ export function createAttachRoutes(options) {
293
387
  sockets.add(ws);
294
388
  ws.once("close", () => sockets.delete(ws));
295
389
  const attach = attachSocketOf(ws, options.timing);
296
- options.onSocket?.(row.id, ws);
297
- void hub.accept(pairedOf(row), attach).then(async (said) => {
390
+ const { computer, field, event } = dialer;
391
+ options.onSocket?.(computer.id, ws);
392
+ void hub.accept(computer, attach).then(async (said) => {
298
393
  if (!said.ok)
299
- return log("computer_refused", { computer: row.id, code: said.error.code, why: said.error.message });
394
+ return log(`${event}_refused`, { [field]: computer.id, code: said.error.code, why: said.error.message });
300
395
  // The row read for the token may be older than a removal that committed, and its hub.revoke, while this socket
301
396
  // was still being accepted (a Postgres read and write are separate connections): read the row again, now that the
302
397
  // socket is the hub's. A removal committing after this read revokes the hub's socket after this accept, closing it.
303
- const now = await paired.get(row.id);
304
- if (now === undefined || now.revokedAt !== null) {
305
- hub.revoke(row.id, `${row.name} was removed from this server's console: pair it again to use it`);
306
- return log("computer_refused", { computer: row.id, why: "removed while it attached" });
398
+ if (!(await dialer.good())) {
399
+ hub.revoke(computer.id, dialer.gone);
400
+ return log(`${event}_refused`, { [field]: computer.id, why: "removed while it attached" });
307
401
  }
308
- await paired.seen(row.id, said.value);
309
- log("computer_attached", { computer: row.id, driver: said.value.version });
402
+ await dialer.seen(said.value);
403
+ log(`${event}_attached`, { [field]: computer.id, driver: said.value.version });
310
404
  }).catch((error) => {
311
- log("computer_refused", { computer: row.id, why: error instanceof Error ? error.message : String(error) });
405
+ log(`${event}_refused`, { [field]: computer.id, why: error instanceof Error ? error.message : String(error) });
312
406
  attach.close(ATTACH_CLOSE.going, "the server could not take this socket");
313
407
  });
314
408
  });
@@ -326,5 +420,5 @@ export function createAttachRoutes(options) {
326
420
  await Promise.all(ended);
327
421
  clearTimeout(cut);
328
422
  }
329
- return { createPairing, pair, remove, upgrade, close };
423
+ return { createPairing, pair, remove, upgrade, close, machineTokens, daemon };
330
424
  }
@@ -70,6 +70,10 @@ export interface KeyTable {
70
70
  export declare function keyTableOf(entries: readonly Pick<ProviderEntry, "id" | "label" | "keys" | "settings">[]): KeyTable;
71
71
  /** Serve's table: every provider the computer package declares. */
72
72
  export declare const KEY_TABLE: KeyTable;
73
+ /** The computer providers' keys that are secrets: each name a descriptor declares that is named like a key (keyShaped:
74
+ * DAYTONA_API_KEY, MODAL_TOKEN_ID, AGENT37_SSH_KEY; not DAYTONA_API_URL or ORGO_WORKSPACE_ID). Each is on the launcher's
75
+ * list, so a key set where the server starts is held in memory (secrets.ts), never left in its environment. */
76
+ export declare const COMPUTER_KEY_NAMES: readonly string[];
73
77
  /**
74
78
  * Provider `providerId`'s create() options from its saved keys (by its descriptor's names) and the server's settings
75
79
  * (each of its descriptor's settings, by name, else its default). An id the table does not list is refused, naming the
@@ -11,6 +11,7 @@
11
11
  // here answers that its test is not available. No key is ever in an answer: each value is scrubbed from the provider's
12
12
  // words, and the words this module adds name keys only by their names.
13
13
  import { PROVIDERS } from "@parcha/agentrun-computer";
14
+ import { keyShaped } from "./secret-name.js";
14
15
  /** The key table of `entries` (the kind registry's PROVIDERS, each from its descriptor). */
15
16
  export function keyTableOf(entries) {
16
17
  return {
@@ -21,6 +22,10 @@ export function keyTableOf(entries) {
21
22
  }
22
23
  /** Serve's table: every provider the computer package declares. */
23
24
  export const KEY_TABLE = keyTableOf(PROVIDERS);
25
+ /** The computer providers' keys that are secrets: each name a descriptor declares that is named like a key (keyShaped:
26
+ * DAYTONA_API_KEY, MODAL_TOKEN_ID, AGENT37_SSH_KEY; not DAYTONA_API_URL or ORGO_WORKSPACE_ID). Each is on the launcher's
27
+ * list, so a key set where the server starts is held in memory (secrets.ts), never left in its environment. */
28
+ export const COMPUTER_KEY_NAMES = [...new Set(PROVIDERS.flatMap((entry) => entry.keys.map((key) => key.name)).filter(keyShaped))];
24
29
  const has = (record, key) => Object.prototype.hasOwnProperty.call(record, key);
25
30
  const labelOf = (providerId, table) => (has(table.labels, providerId) ? table.labels[providerId] : providerId);
26
31
  const refused = (code, message) => ({ ok: false, error: { code, message } });
@@ -37,6 +37,14 @@ export interface ProviderEntry {
37
37
  readonly mounts: readonly string[];
38
38
  /** Why its computers take none of these mounts, each in one sentence (Daytona's archil), as its descriptor says. */
39
39
  readonly unmounted?: Readonly<Partial<Record<string, string>>>;
40
+ /** Mounts its computers take only where the operator sets the key named, by mount (Daytona's archil, with
41
+ * DAYTONA_ARCHIL_EGRESS), as its descriptor says: resolve-computer.ts entryHere reads it with the keys set here. */
42
+ readonly mountsWith?: Readonly<Partial<Record<string, string>>>;
43
+ /** The server's environment variable that names the image every computer of it starts from (Daytona's
44
+ * AGENTRUN_DAYTONA_SNAPSHOT), as its descriptor says: set, the operator names its image here (entryHere). */
45
+ readonly imageEnv?: string;
46
+ /** Set by entryHere alone: its imageEnv has a value here. */
47
+ readonly imageNamed?: true;
40
48
  /** The network forms its computers make ("none", "open", "allow"), as its descriptor declares them. Absent (a
41
49
  * test's fixture): nothing is said of its network. */
42
50
  readonly network?: readonly string[];
@@ -202,7 +210,9 @@ export declare const COMPUTER_UNAVAILABLE = "computer_unavailable";
202
210
  * local Docker bind). A desktop, phone or browser holds no folder unless its provider mounts it, so either mode takes
203
211
  * it. A sandbox that mounts the disk can't start yet either, nor can a desktop that would mount it (resolve-computer.ts
204
212
  * mode2ArchilWhy), unless its provider prepares its image (prepareImage: Agent37 registers the box image, which has
205
- * Archil's client, in the owner's workspace; Modal pulls it; E2B starts its public template). */
213
+ * Archil's client, in the owner's workspace; Modal pulls it; E2B starts its public template) or the operator names it
214
+ * here (Daytona's AGENTRUN_DAYTONA_SNAPSHOT). `provider` is as this server has it (resolve-computer.ts entryHere): a
215
+ * Daytona sandbox mounts the disk only where DAYTONA_ARCHIL_EGRESS names a self-hosted target's Archil egress relay. */
206
216
  export declare function modeRefusal(kind: ComputerKind, provider: ProviderEntry, mode: FolderMode): string | undefined;
207
217
  /** The routes' work over the server's store: GET /v2/computers (view), PUT /v2/computers/{provider}/keys (saveKeys), POST
208
218
  * /v2/computers/{provider}/test (test), and the claim's refusal (claimRefusal). */
package/dist/computers.js CHANGED
@@ -22,7 +22,7 @@ import { keyMetaOf, envValue } from "./key-meta.js";
22
22
  import { registerNotSecretWrite, registerSecretWrite, secretName } from "./secret-writes.js";
23
23
  import { getSealedKey, putSealedKey, removeSealedKey, sealedKeyNames } from "./server-keys.js";
24
24
  import { withPaired } from "./workspace/attached-computers.js";
25
- import { aLabel, mode2ArchilWhy, needsNetwork, shellChoiceOf } from "./workspace/resolve-computer.js";
25
+ import { aLabel, archilImageHere, entryHere, mode2ArchilWhy, needsNetwork, shellChoiceOf } from "./workspace/resolve-computer.js";
26
26
  // Every request to a computer's keys is a secret write (secret-writes.ts), whatever its body (a value, a null, an empty
27
27
  // body or none), as saveToolKey's is: the server's one dispatch check keeps it to the owner's session before any provider
28
28
  // is looked up, so a token learns nothing of which providers exist. The view and the connection test write none.
@@ -101,11 +101,13 @@ export const COMPUTER_UNAVAILABLE = "computer_unavailable";
101
101
  * local Docker bind). A desktop, phone or browser holds no folder unless its provider mounts it, so either mode takes
102
102
  * it. A sandbox that mounts the disk can't start yet either, nor can a desktop that would mount it (resolve-computer.ts
103
103
  * mode2ArchilWhy), unless its provider prepares its image (prepareImage: Agent37 registers the box image, which has
104
- * Archil's client, in the owner's workspace; Modal pulls it; E2B starts its public template). */
104
+ * Archil's client, in the owner's workspace; Modal pulls it; E2B starts its public template) or the operator names it
105
+ * here (Daytona's AGENTRUN_DAYTONA_SNAPSHOT). `provider` is as this server has it (resolve-computer.ts entryHere): a
106
+ * Daytona sandbox mounts the disk only where DAYTONA_ARCHIL_EGRESS names a self-hosted target's Archil egress relay. */
105
107
  export function modeRefusal(kind, provider, mode) {
106
108
  // A desktop with files and exec on a provider that mounts the disk would mount it in Mode 2, so it needs the image too.
107
109
  if (kind === "desktop")
108
- return mode === "disk" && provider.mounts.includes("archil") && !provider.prepareImage && provider.capabilities.some((one) => one.kind === "desktop" && one.groups.includes("files") && one.groups.includes("exec")) ? mode2ArchilWhy(provider.label, "desktop") : undefined;
110
+ return mode === "disk" && provider.mounts.includes("archil") && !archilImageHere(provider) && provider.capabilities.some((one) => one.kind === "desktop" && one.groups.includes("files") && one.groups.includes("exec")) ? mode2ArchilWhy(provider.label, "desktop", provider.imageEnv) : undefined;
109
111
  if (kind !== "sandbox")
110
112
  return undefined;
111
113
  if (mode === "local" && !provider.mounts.includes("bind"))
@@ -114,7 +116,7 @@ export function modeRefusal(kind, provider, mode) {
114
116
  const why = provider.unmounted?.archil;
115
117
  return `${provider.label} can't mount the owner's disk this server keeps run folders on${why ? ` (${why})` : ""}: set this agent's computer to a sandbox that mounts it, or none (Settings → Computers)`;
116
118
  }
117
- return mode === "disk" && !provider.prepareImage ? mode2ArchilWhy(provider.label, "sandbox") : undefined;
119
+ return mode === "disk" && !archilImageHere(provider) ? mode2ArchilWhy(provider.label, "sandbox", provider.imageEnv) : undefined;
118
120
  }
119
121
  /** The GPUs a sandbox of `provider` gives, as its configuration that serves a sandbox declares them, or undefined. */
120
122
  const sandboxGpu = (kinds, provider) => provider.capabilities.find((one) => one.gpu !== undefined && kinds.servingRefusals(one, "sandbox").length === 0)?.gpu;
@@ -164,15 +166,17 @@ export function createComputerRoutes(options) {
164
166
  const mode = await modeNow();
165
167
  // The paired computers, each one more provider of its kind; one not attached now is not ready, saying so.
166
168
  const rows = options.paired ? await options.paired.rows() : [];
167
- const kinds = withPaired(options.kinds, rows);
168
- const paired = rows.map((row) => options.paired.viewOf(row, kinds.PROVIDERS.find((provider) => provider.id === row.id)?.kinds ?? []));
169
+ const listed = withPaired(options.kinds, rows);
170
+ const paired = rows.map((row) => options.paired.viewOf(row, listed.PROVIDERS.find((provider) => provider.id === row.id)?.kinds ?? []));
169
171
  const offline = new Map(rows.flatMap((row, at) => (paired[at].online ? [] : [[row.id, `${row.name} is not attached now: open its driver on that computer, which dials this server`]])));
170
- const choice = (setting) => shellChoiceOf(setting, mode === "disk" ? 2 : 1, kinds);
171
172
  // Every provider's keys in one read: each a SecretMeta named for its provider, set by the environment or the store row
172
173
  // of its key's name.
173
- const slots = kinds.PROVIDERS.flatMap((provider) => provider.keys.map((key) => ({ secret: secretName("computer", provider.id, key.name), env: key.name, row: key.name })));
174
+ const slots = listed.PROVIDERS.flatMap((provider) => provider.keys.map((key) => ({ secret: secretName("computer", provider.id, key.name), env: key.name, row: key.name })));
174
175
  const metas = new Map((await keyMetaOf(store, slots, env)).map((meta) => [meta.name, meta]));
175
176
  const saved = new Set(slots.filter((slot) => metas.get(slot.secret).set).map((slot) => slot.env));
177
+ // Each provider as this server has it: the mounts its saved keys turn on, and whether this server names its image.
178
+ const kinds = { ...listed, PROVIDERS: listed.PROVIDERS.map((provider) => entryHere(provider, (name) => saved.has(name) || envValue(env, name) !== undefined)) };
179
+ const choice = (setting) => shellChoiceOf(setting, mode === "disk" ? 2 : 1, kinds);
176
180
  // Under this server's AGENTRUN_BOX_ALLOW none, a computer that needs a network is refused at a
177
181
  // run's start and its claim (resolve-computer.ts noNetworkRefusal), so it is never ready here, whatever its keys.
178
182
  const refusedOpen = (provider) => boxAllowOf(env) === "none" && needsNetwork(provider.network);
@@ -218,7 +222,9 @@ export function createComputerRoutes(options) {
218
222
  return undefined;
219
223
  const declared = new Set(provider.keys.map((key) => key.name));
220
224
  const refused = Object.entries(body).flatMap(([name, value]) => !declared.has(name) ? [{ field: name, reason: "not_allowed", message: `${provider.label} takes ${[...declared].join(", ") || "no keys"}, not ${name}` }]
221
- : value !== null && (typeof value !== "string" || value === "") ? [{ field: name, reason: "wrong_type", message: `${name} is a non-empty string, or null to remove it` }] : []);
225
+ // Whitespace alone is no value, as in the environment (key-meta.ts envValue): saved, it would read as set here and
226
+ // as none where a value is read (resolve-computer.ts registryHere), so Settings would show ready what a run refuses.
227
+ : value !== null && (typeof value !== "string" || value.trim() === "") ? [{ field: name, reason: "wrong_type", message: `${name} is a non-empty string, or null to remove it` }] : []);
222
228
  if (refused.length)
223
229
  throw new KeysRefused(refused);
224
230
  for (const [name, value] of Object.entries(body)) {
@@ -291,9 +297,12 @@ export function createComputerRoutes(options) {
291
297
  async function claimRefusal(computer) {
292
298
  if (computer.kind === "none")
293
299
  return undefined;
294
- const provider = providerOf(computer.provider);
295
- if (!provider)
300
+ const listed = providerOf(computer.provider);
301
+ if (!listed)
296
302
  return `this agent's computer names the provider ${computer.provider}, which this server does not have: set its computer in Settings → Computers`;
303
+ // The keys set here, saved or the environment's: what the provider is made with, and what turns its mounts on.
304
+ const set = new Set([...(await sealedKeyNames(store)), ...listed.keys.filter((key) => envValue(env, key.name) !== undefined).map((key) => key.name)]);
305
+ const provider = entryHere(listed, (name) => set.has(name) || envValue(env, name) !== undefined);
297
306
  if (!provider.kinds.includes(computer.kind)) {
298
307
  const words = [...new Set(provider.capabilities.flatMap((capabilities) => kinds.servingRefusals(capabilities, computer.kind)))];
299
308
  return `${provider.label} does not serve a ${computer.kind} computer${words.length ? ` (${words.join("; ")})` : ""}: set this agent's computer to one it serves (Settings → Computers)`;
@@ -302,7 +311,7 @@ export function createComputerRoutes(options) {
302
311
  const refused = modeRefusal(computer.kind, provider, mode) ?? gpuRefusal(kinds, computer, provider, mode) ?? (local(provider) ? daemonWhy(computer.kind, await answers(provider.id), mode) : undefined) ?? hostOf(provider);
303
312
  if (refused)
304
313
  return refused;
305
- const missing = missingKeys(provider, new Set([...(await sealedKeyNames(store)), ...provider.keys.filter((key) => envValue(env, key.name) !== undefined).map((key) => key.name)]));
314
+ const missing = missingKeys(provider, set);
306
315
  return missing.length ? keysWhy(provider, missing, true) : undefined;
307
316
  }
308
317
  /** What the claim makes a run's computer with: the options its provider's create() takes, from its saved keys and the