@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.
- package/CHANGELOG.md +114 -0
- package/README.md +129 -16
- package/dist/api-only.d.ts +3 -1
- package/dist/api-only.js +4 -2
- package/dist/api-token.d.ts +30 -0
- package/dist/api-token.js +89 -0
- package/dist/cli.js +19 -5
- package/dist/composio-made.d.ts +54 -0
- package/dist/composio-made.js +83 -0
- package/dist/composio-preset.d.ts +16 -8
- package/dist/composio-preset.js +106 -43
- package/dist/composio-triggers.d.ts +7 -2
- package/dist/composio-triggers.js +13 -7
- package/dist/computer-attach.d.ts +29 -11
- package/dist/computer-attach.js +141 -47
- package/dist/computer-keys.d.ts +4 -0
- package/dist/computer-keys.js +5 -0
- package/dist/computers.d.ts +11 -1
- package/dist/computers.js +21 -12
- package/dist/console/assets/index-C3gNPz58.css +1 -0
- package/dist/console/assets/index-COGhx_2Z.js +711 -0
- package/dist/console/index.html +2 -2
- package/dist/decisions.js +9 -2
- package/dist/email/account.d.ts +0 -1
- package/dist/email/account.js +3 -3
- package/dist/email/answer.d.ts +5 -0
- package/dist/email/answer.js +35 -0
- package/dist/email/mail.js +19 -26
- package/dist/email/names.d.ts +30 -0
- package/dist/email/names.js +34 -0
- package/dist/email/routes.d.ts +1 -0
- package/dist/email/routes.js +1 -1
- package/dist/email/tools.d.ts +11 -4
- package/dist/email/tools.js +91 -46
- package/dist/eval-feed.d.ts +26 -0
- package/dist/eval-feed.js +68 -0
- package/dist/eval-mailbox.d.ts +5 -2
- package/dist/eval-mailbox.js +14 -6
- package/dist/exa-keyless.d.ts +1 -1
- package/dist/exa-keyless.js +1 -1
- package/dist/feed/feed-faux.d.ts +62 -0
- package/dist/feed/feed-faux.js +123 -0
- package/dist/feed/fetch.d.ts +41 -0
- package/dist/feed/fetch.js +128 -0
- package/dist/feed/parse.d.ts +41 -0
- package/dist/feed/parse.js +300 -0
- package/dist/learn/check.d.ts +3 -1
- package/dist/learn/check.js +57 -2
- package/dist/learn/compile.d.ts +3 -2
- package/dist/learn/compile.js +7 -6
- package/dist/learn/promote.d.ts +25 -14
- package/dist/learn/promote.js +32 -14
- package/dist/learned-nodes.d.ts +21 -4
- package/dist/learned-nodes.js +21 -8
- package/dist/learned-workflow.d.ts +3 -3
- package/dist/learned-workflow.js +14 -5
- package/dist/learning-cost.d.ts +17 -8
- package/dist/learning-cost.js +12 -4
- package/dist/local-models.d.ts +7 -1
- package/dist/local-models.js +11 -5
- package/dist/mcp-oauth.d.ts +15 -1
- package/dist/mcp-oauth.js +39 -5
- package/dist/mcp-pin-first.d.ts +4 -2
- package/dist/mcp-pin-first.js +4 -3
- package/dist/mcp-servers-store.d.ts +58 -5
- package/dist/mcp-servers-store.js +136 -17
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +2 -2
- package/dist/observation/http.d.ts +4 -1
- package/dist/observation/http.js +5 -4
- package/dist/openapi.d.ts +1 -1
- package/dist/openapi.js +63 -27
- package/dist/port-models.d.ts +4 -1
- package/dist/port-models.js +1 -0
- package/dist/print.d.ts +6 -3
- package/dist/print.js +4 -2
- package/dist/refusal-words.d.ts +3 -0
- package/dist/refusal-words.js +3 -0
- package/dist/run-labels.d.ts +23 -0
- package/dist/run-labels.js +79 -0
- package/dist/run-launch.d.ts +2 -0
- package/dist/run-launch.js +2 -0
- package/dist/run-secrets.js +12 -4
- package/dist/run-view.d.ts +3 -4
- package/dist/run-view.js +26 -24
- package/dist/runner/adapter-loop.d.ts +6 -2
- package/dist/runner/adapter-loop.js +136 -22
- package/dist/runner/adapter-run-spec.d.ts +5 -0
- package/dist/runner/adapter-run-spec.js +75 -32
- package/dist/runner/beside.d.ts +6 -3
- package/dist/runner/beside.js +9 -7
- package/dist/runner/cli-run-spec.js +33 -26
- package/dist/runner/conformance/harness.js +69 -14
- package/dist/runner/conformance/subject.d.ts +4 -1
- package/dist/runner/journal-kinds.d.ts +22 -0
- package/dist/runner/journal-kinds.js +39 -0
- package/dist/runner/main.d.ts +1 -1
- package/dist/runner/main.js +2 -2
- package/dist/runner/mcp-claim.d.ts +3 -0
- package/dist/runner/mcp-claim.js +1 -1
- package/dist/runner/mcp-run.d.ts +4 -0
- package/dist/runner/mcp-run.js +5 -3
- package/dist/runner/model-route.d.ts +7 -3
- package/dist/runner/model-route.js +24 -9
- package/dist/runner/promotion.d.ts +16 -8
- package/dist/runner/promotion.js +178 -55
- package/dist/runner/workflow-first.d.ts +6 -5
- package/dist/runner/workflow-first.js +9 -7
- package/dist/runs-over-store.js +5 -2
- package/dist/sdk/runs.d.ts +7 -1
- package/dist/sdk/runs.js +19 -6
- package/dist/secret-cut.js +3 -1
- package/dist/secrets.js +3 -1
- package/dist/server.d.ts +27 -2
- package/dist/server.js +181 -56
- package/dist/store/dialect.d.ts +6 -0
- package/dist/store/dialect.js +2 -0
- package/dist/store/index.d.ts +1 -1
- package/dist/store/postgres/connection.d.ts +11 -5
- package/dist/store/postgres/connection.js +44 -17
- package/dist/store/postgres/dialect.js +6 -0
- package/dist/store/postgres/migrations/0015_run_labels.sql +5 -0
- package/dist/store/postgres/migrations/0016_minted_tokens.sql +21 -0
- package/dist/store/postgres/store.d.ts +7 -3
- package/dist/store/postgres/store.js +1 -0
- package/dist/store/schema.d.ts +9 -0
- package/dist/store/schema.js +26 -2
- package/dist/store/sqlite/connection.js +80 -8
- package/dist/store/sqlite/run-launch.d.ts +11 -0
- package/dist/store/sqlite/run-launch.js +8 -0
- package/dist/store/sqlite/run-patch.d.ts +2 -1
- package/dist/store/sqlite/run-patch.js +3 -2
- package/dist/store/sqlite/store.js +101 -26
- package/dist/store/sqlite/worker.d.ts +2 -0
- package/dist/store/sqlite/worker.js +13 -10
- package/dist/store/store.d.ts +53 -1
- package/dist/store-reads/journal.js +2 -1
- package/dist/store-reads/learning.d.ts +30 -13
- package/dist/store-reads/learning.js +130 -51
- package/dist/store-reads/runs.d.ts +4 -3
- package/dist/store-reads/runs.js +3 -2
- package/dist/store-view.js +4 -2
- package/dist/template-eval.d.ts +4 -0
- package/dist/template-eval.js +127 -50
- package/dist/templates.d.ts +24 -1
- package/dist/templates.js +129 -21
- package/dist/timeline/origin.d.ts +1 -1
- package/dist/timeline/origin.js +2 -2
- package/dist/tool-gate.d.ts +5 -3
- package/dist/tool-gate.js +5 -2
- package/dist/tools.d.ts +13 -0
- package/dist/tools.js +15 -10
- package/dist/trigger-adapter.d.ts +12 -36
- package/dist/trigger-adapters.js +2 -1
- package/dist/trigger-email.js +30 -77
- package/dist/trigger-feed.d.ts +12 -0
- package/dist/trigger-feed.js +371 -0
- package/dist/triggers.d.ts +27 -14
- package/dist/triggers.js +121 -80
- package/dist/webhooks.js +9 -5
- package/dist/workflow/decision-recovery.js +5 -2
- package/dist/workflow/decisions.d.ts +7 -0
- package/dist/workspace/computer-deps.d.ts +5 -1
- package/dist/workspace/computer-deps.js +2 -2
- package/dist/workspace/index.d.ts +1 -0
- package/dist/workspace/index.js +2 -0
- package/dist/workspace/resolve-computer.d.ts +32 -3
- package/dist/workspace/resolve-computer.js +47 -9
- package/launcher/agentrun-serve +6 -1
- package/package.json +10 -9
- package/templates/README.md +27 -2
- package/dist/console/assets/index-BNhZs-jp.css +0 -1
- package/dist/console/assets/index-BQv5aOGB.js +0 -700
package/dist/computer-attach.js
CHANGED
|
@@ -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
|
-
|
|
34
|
-
|
|
35
|
-
const
|
|
36
|
-
/** The
|
|
37
|
-
const
|
|
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
|
-
/**
|
|
74
|
-
|
|
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
|
-
|
|
92
|
+
keys;
|
|
77
93
|
#tries = new Map();
|
|
78
|
-
constructor(now = Date.now,
|
|
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.
|
|
98
|
+
this.keys = keys;
|
|
81
99
|
}
|
|
82
|
-
/** Counts a try
|
|
83
|
-
allow(
|
|
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 =
|
|
86
|
-
if (!this.#tries.has(key) && this.#tries.size >= this.
|
|
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 <
|
|
106
|
+
if (!at.some((one) => now - one < MINUTE_MS))
|
|
89
107
|
this.#tries.delete(known);
|
|
90
|
-
// A table still full of
|
|
91
|
-
//
|
|
92
|
-
if (this.#tries.size >= this.
|
|
93
|
-
key =
|
|
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 <
|
|
96
|
-
if (recent.length >=
|
|
97
|
-
return { ok: false, retryAfterMs: recent[0] +
|
|
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:
|
|
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
|
-
/**
|
|
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
|
|
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
|
-
|
|
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
|
-
/**
|
|
277
|
-
*
|
|
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 =
|
|
283
|
-
const row = bearer?.startsWith(ATTACH_TOKEN_PREFIX) ? await paired.byToken(sha256Hex(bearer)) : undefined;
|
|
284
|
-
|
|
285
|
-
|
|
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
|
-
|
|
297
|
-
|
|
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(
|
|
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
|
-
|
|
304
|
-
|
|
305
|
-
|
|
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
|
|
309
|
-
log(
|
|
402
|
+
await dialer.seen(said.value);
|
|
403
|
+
log(`${event}_attached`, { [field]: computer.id, driver: said.value.version });
|
|
310
404
|
}).catch((error) => {
|
|
311
|
-
log(
|
|
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
|
}
|
package/dist/computer-keys.d.ts
CHANGED
|
@@ -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
|
package/dist/computer-keys.js
CHANGED
|
@@ -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 } });
|
package/dist/computers.d.ts
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
168
|
-
const paired = rows.map((row) => options.paired.viewOf(row,
|
|
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 =
|
|
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
|
-
|
|
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
|
|
295
|
-
if (!
|
|
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,
|
|
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
|