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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/CHANGELOG.md +130 -0
  2. package/NOTICE +2 -0
  3. package/README.md +149 -21
  4. package/dist/agent-rows.d.ts +1 -1
  5. package/dist/agents-store.js +3 -1
  6. package/dist/api-only.d.ts +3 -1
  7. package/dist/api-only.js +4 -2
  8. package/dist/api-token.d.ts +30 -0
  9. package/dist/api-token.js +89 -0
  10. package/dist/calendar/address.d.ts +49 -0
  11. package/dist/calendar/address.js +153 -0
  12. package/dist/calendar/fetch.d.ts +24 -0
  13. package/dist/calendar/fetch.js +146 -0
  14. package/dist/calendar/ics-faux.d.ts +39 -0
  15. package/dist/calendar/ics-faux.js +236 -0
  16. package/dist/calendar/labels.d.ts +3 -0
  17. package/dist/calendar/labels.js +61 -0
  18. package/dist/calendar/names.d.ts +52 -0
  19. package/dist/calendar/names.js +54 -0
  20. package/dist/calendar/parse.d.ts +108 -0
  21. package/dist/calendar/parse.js +625 -0
  22. package/dist/calendar/routes.d.ts +17 -0
  23. package/dist/calendar/routes.js +81 -0
  24. package/dist/calendar/tools.d.ts +23 -0
  25. package/dist/calendar/tools.js +124 -0
  26. package/dist/cli.js +22 -6
  27. package/dist/composio-made.d.ts +54 -0
  28. package/dist/composio-made.js +83 -0
  29. package/dist/composio-preset.d.ts +16 -8
  30. package/dist/composio-preset.js +106 -43
  31. package/dist/composio-triggers.d.ts +7 -2
  32. package/dist/composio-triggers.js +13 -7
  33. package/dist/computer-attach.d.ts +29 -11
  34. package/dist/computer-attach.js +141 -47
  35. package/dist/computer-keys.d.ts +4 -0
  36. package/dist/computer-keys.js +5 -0
  37. package/dist/computer-record.d.ts +55 -0
  38. package/dist/computer-record.js +315 -0
  39. package/dist/computer-setting.d.ts +1 -0
  40. package/dist/computer-setting.js +15 -2
  41. package/dist/computers.d.ts +11 -1
  42. package/dist/computers.js +23 -26
  43. package/dist/console/assets/{index-B8Zn1Iqn.css → index-C3gNPz58.css} +1 -1
  44. package/dist/console/assets/index-DYJ_wj27.js +711 -0
  45. package/dist/console/index.html +2 -2
  46. package/dist/decisions.js +9 -2
  47. package/dist/eval-feed.d.ts +26 -0
  48. package/dist/eval-feed.js +72 -0
  49. package/dist/eval-mailbox.d.ts +4 -1
  50. package/dist/eval-mailbox.js +11 -3
  51. package/dist/exa-keyless.d.ts +1 -1
  52. package/dist/exa-keyless.js +1 -1
  53. package/dist/feed/feed-faux.d.ts +62 -0
  54. package/dist/feed/feed-faux.js +123 -0
  55. package/dist/feed/fetch.d.ts +41 -0
  56. package/dist/feed/fetch.js +128 -0
  57. package/dist/feed/parse.d.ts +42 -0
  58. package/dist/feed/parse.js +291 -0
  59. package/dist/feed/pointer.d.ts +2 -0
  60. package/dist/feed/pointer.js +17 -0
  61. package/dist/file-types.js +1 -0
  62. package/dist/host-command.d.ts +3 -0
  63. package/dist/host-command.js +18 -0
  64. package/dist/host.d.ts +3 -0
  65. package/dist/host.js +3 -0
  66. package/dist/learn/check.d.ts +17 -1
  67. package/dist/learn/check.js +240 -5
  68. package/dist/learn/compile.d.ts +48 -27
  69. package/dist/learn/compile.js +134 -101
  70. package/dist/learn/promote.d.ts +61 -5
  71. package/dist/learn/promote.js +12 -2
  72. package/dist/learned-nodes.d.ts +21 -4
  73. package/dist/learned-nodes.js +21 -8
  74. package/dist/learned-workflow.d.ts +3 -3
  75. package/dist/learned-workflow.js +14 -5
  76. package/dist/learning-setting.d.ts +23 -0
  77. package/dist/learning-setting.js +51 -0
  78. package/dist/learning-words.d.ts +3 -0
  79. package/dist/learning-words.js +3 -0
  80. package/dist/learning.d.ts +3 -2
  81. package/dist/learning.js +5 -3
  82. package/dist/mcp-oauth.d.ts +23 -1
  83. package/dist/mcp-oauth.js +46 -5
  84. package/dist/mcp-pin-first.d.ts +4 -2
  85. package/dist/mcp-pin-first.js +4 -3
  86. package/dist/mcp-private-hosts.d.ts +13 -0
  87. package/dist/mcp-private-hosts.js +16 -0
  88. package/dist/mcp-servers-store.d.ts +58 -5
  89. package/dist/mcp-servers-store.js +136 -17
  90. package/dist/mcp.d.ts +2 -2
  91. package/dist/mcp.js +2 -2
  92. package/dist/observation/http.d.ts +4 -1
  93. package/dist/observation/http.js +5 -4
  94. package/dist/openapi.d.ts +1 -0
  95. package/dist/openapi.js +151 -21
  96. package/dist/print.d.ts +6 -3
  97. package/dist/print.js +4 -2
  98. package/dist/run-files.d.ts +6 -2
  99. package/dist/run-files.js +29 -7
  100. package/dist/run-labels.d.ts +23 -0
  101. package/dist/run-labels.js +79 -0
  102. package/dist/run-learning-served.d.ts +1 -1
  103. package/dist/run-reads-over-store.d.ts +5 -1
  104. package/dist/run-reads-over-store.js +8 -4
  105. package/dist/run-recordings.d.ts +20 -0
  106. package/dist/run-recordings.js +133 -0
  107. package/dist/run-secrets.js +12 -4
  108. package/dist/runner/adapter-loop.d.ts +1 -1
  109. package/dist/runner/adapter-loop.js +94 -16
  110. package/dist/runner/adapter-run-spec.d.ts +19 -0
  111. package/dist/runner/adapter-run-spec.js +57 -36
  112. package/dist/runner/beside.d.ts +6 -3
  113. package/dist/runner/beside.js +9 -7
  114. package/dist/runner/cli-run-spec.js +41 -32
  115. package/dist/runner/conformance/harness.js +69 -14
  116. package/dist/runner/conformance/subject.d.ts +4 -1
  117. package/dist/runner/feedback-round.d.ts +9 -25
  118. package/dist/runner/feedback-round.js +22 -40
  119. package/dist/runner/learning-end.d.ts +17 -7
  120. package/dist/runner/learning-end.js +79 -53
  121. package/dist/runner/main.d.ts +12 -1
  122. package/dist/runner/main.js +31 -4
  123. package/dist/runner/mcp-claim.d.ts +3 -0
  124. package/dist/runner/mcp-claim.js +1 -1
  125. package/dist/runner/mcp-run.d.ts +6 -2
  126. package/dist/runner/mcp-run.js +5 -3
  127. package/dist/runner/model-route.d.ts +4 -2
  128. package/dist/runner/model-route.js +8 -8
  129. package/dist/runner/promotion.d.ts +44 -4
  130. package/dist/runner/promotion.js +323 -21
  131. package/dist/runner/reflect-hook.d.ts +5 -0
  132. package/dist/runner/reflect-hook.js +22 -14
  133. package/dist/runner/store-secrets.js +3 -1
  134. package/dist/runner/workflow-first.d.ts +6 -11
  135. package/dist/runner/workflow-first.js +16 -20
  136. package/dist/runs-over-store.d.ts +1 -1
  137. package/dist/runs-over-store.js +5 -2
  138. package/dist/sdk/runs.d.ts +7 -1
  139. package/dist/sdk/runs.js +21 -7
  140. package/dist/secret-cut.js +3 -1
  141. package/dist/secrets.js +5 -3
  142. package/dist/server.d.ts +31 -5
  143. package/dist/server.js +240 -61
  144. package/dist/store/agent-body.d.ts +5 -3
  145. package/dist/store/agent-body.js +14 -10
  146. package/dist/store/dialect.d.ts +3 -0
  147. package/dist/store/dialect.js +1 -0
  148. package/dist/store/index.d.ts +1 -1
  149. package/dist/store/postgres/dialect.js +1 -0
  150. package/dist/store/postgres/migrations/0015_run_labels.sql +5 -0
  151. package/dist/store/postgres/migrations/0016_minted_tokens.sql +21 -0
  152. package/dist/store/schema.d.ts +9 -0
  153. package/dist/store/schema.js +26 -2
  154. package/dist/store/sqlite/connection.js +11 -3
  155. package/dist/store/sqlite/run-patch.d.ts +2 -1
  156. package/dist/store/sqlite/run-patch.js +3 -2
  157. package/dist/store/sqlite/store.js +64 -10
  158. package/dist/store/store.d.ts +38 -1
  159. package/dist/store-reads/journal.js +2 -1
  160. package/dist/store-reads/learning.d.ts +1 -1
  161. package/dist/store-reads/learning.js +6 -1
  162. package/dist/store-reads/loop.d.ts +1 -0
  163. package/dist/store-reads/loop.js +14 -4
  164. package/dist/store-reads/runs.d.ts +4 -3
  165. package/dist/store-reads/runs.js +3 -2
  166. package/dist/store-view.d.ts +5 -0
  167. package/dist/store-view.js +8 -2
  168. package/dist/template-eval.d.ts +11 -0
  169. package/dist/template-eval.js +177 -52
  170. package/dist/templates.d.ts +13 -1
  171. package/dist/templates.js +89 -18
  172. package/dist/timeline/computer.js +2 -1
  173. package/dist/timeline/origin.d.ts +1 -1
  174. package/dist/timeline/origin.js +2 -2
  175. package/dist/tool-list.js +1 -0
  176. package/dist/tools.d.ts +7 -0
  177. package/dist/tools.js +11 -0
  178. package/dist/trigger-adapter.d.ts +9 -4
  179. package/dist/trigger-adapters.js +2 -1
  180. package/dist/trigger-feed.d.ts +12 -0
  181. package/dist/trigger-feed.js +420 -0
  182. package/dist/triggers.d.ts +2 -1
  183. package/dist/triggers.js +23 -5
  184. package/dist/validate.js +7 -2
  185. package/dist/webhooks.js +9 -5
  186. package/dist/workspace/computer-deps.d.ts +5 -1
  187. package/dist/workspace/computer-deps.js +2 -2
  188. package/dist/workspace/computer-for-claim.d.ts +7 -0
  189. package/dist/workspace/computer-for-claim.js +12 -2
  190. package/dist/workspace/index.d.ts +1 -0
  191. package/dist/workspace/index.js +2 -0
  192. package/dist/workspace/paths.d.ts +4 -0
  193. package/dist/workspace/paths.js +9 -0
  194. package/dist/workspace/resolve-computer.d.ts +35 -4
  195. package/dist/workspace/resolve-computer.js +47 -9
  196. package/launcher/agentrun-serve +34 -22
  197. package/package.json +11 -9
  198. package/templates/README.md +38 -4
  199. package/dist/console/assets/index-Jbxjcmdp.js +0 -705
@@ -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 } });
@@ -0,0 +1,55 @@
1
+ import type { Result, ScreenWatch, ScreenWatchHandlers, WatchOptions } from "@parcha/agentrun-computer";
2
+ /** The program that encodes the video. */
3
+ export declare const FFMPEG = "ffmpeg";
4
+ /** The recorder's bounds: frames a second at most; the long side in pixels at most; the caps, in bytes across the run's
5
+ * files and in ms of one recording; how often the caps are checked; how long ffmpeg is given to finish its file once its input ends;
6
+ * how many times in a row a watch that ended is opened again, and after how long. */
7
+ export declare const RECORDING_LIMITS: {
8
+ readonly fps: 10;
9
+ readonly edge: 1280;
10
+ readonly maxBytes: number;
11
+ readonly maxMs: number;
12
+ readonly checkMs: 1000;
13
+ readonly settleMs: 5000;
14
+ readonly rewatches: 3;
15
+ readonly rewatchMs: 1000;
16
+ };
17
+ /** Why this server cannot record a screen, in words, or undefined: ffmpeg is on `path` (the server's PATH, read now). */
18
+ export declare const recorderMissing: (path?: string | undefined) => string | undefined;
19
+ /** Why a recording stops: the computer was released, the run ended, or the run parked (it goes on in a new file when the
20
+ * run resumes, under the claim that resumes it). */
21
+ export type RecordingStop = "released" | "ended" | "parked";
22
+ /** What a recording did: its files (recordings/<name>), the frames written, the frames replaced while ffmpeg was busy
23
+ * (dropped) or within the frame rate's bound (thinned), and why it ended before it was stopped, in words. */
24
+ export type RecordingFacts = {
25
+ readonly files: readonly string[];
26
+ readonly written: number;
27
+ readonly dropped: number;
28
+ readonly thinned: number;
29
+ readonly ended?: string;
30
+ };
31
+ export interface Recording {
32
+ /** Ends the recording: the newest frame written once more (so the video lasts until now), ffmpeg's input closed and its
33
+ * file finished, the watch let go. Idempotent; never throws. */
34
+ stop(why: RecordingStop): Promise<void>;
35
+ facts(): RecordingFacts;
36
+ }
37
+ /** The computer's watch, bound to its ref (provider.watch): the recorder gives the handlers and the signal. */
38
+ export type RecordWatch = (handlers: ScreenWatchHandlers, options: WatchOptions) => Promise<Result<ScreenWatch>>;
39
+ export type RecordInput = {
40
+ readonly watch: RecordWatch;
41
+ /** The run's recordings folder on this machine (recordingsFolder): made when the first frame comes. */
42
+ readonly folder: string;
43
+ /** The computer's ref id: its file's name. */
44
+ readonly tag: string;
45
+ readonly kind: "desktop" | "phone";
46
+ /** A line on the run's timeline. */
47
+ readonly say: (words: string) => void;
48
+ /** For tests: the program run in ffmpeg's place, the bounds, and where a line for the operator goes (default stderr). */
49
+ readonly ffmpeg?: string;
50
+ readonly limits?: Partial<typeof RECORDING_LIMITS>;
51
+ readonly log?: (line: string) => void;
52
+ };
53
+ /** Starts recording the computer's screen (see the top of this file). It never throws: whatever goes wrong ends the
54
+ * recording with a line on the timeline. */
55
+ export declare function startRecording(input: RecordInput): Recording;