podster 0.0.0-stage → 0.0.1-test.2

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 (53) hide show
  1. package/README.md +116 -2
  2. package/build/core/adapter.js +1 -0
  3. package/build/core/broker.js +461 -0
  4. package/build/core/capabilities.js +49 -0
  5. package/build/core/claude-profile.js +35 -0
  6. package/build/core/connection.js +106 -0
  7. package/build/core/errors.js +115 -0
  8. package/build/core/gateway.js +93 -0
  9. package/build/core/lifecycle.js +1207 -0
  10. package/build/core/nudge.js +340 -0
  11. package/build/core/pairing.js +285 -0
  12. package/build/core/policy.js +741 -0
  13. package/build/core/poller.js +261 -0
  14. package/build/core/prompt.js +93 -0
  15. package/build/core/record.js +106 -0
  16. package/build/core/repository.js +272 -0
  17. package/build/core/results.js +149 -0
  18. package/build/core/run-interface.js +464 -0
  19. package/build/core/runs.js +172 -0
  20. package/build/core/runtime.js +38 -0
  21. package/build/core/state.js +41 -0
  22. package/build/core/storage.js +125 -0
  23. package/build/core/thumbprint.js +15 -0
  24. package/build/core/tool-policy.js +130 -0
  25. package/build/node/broker-listener.js +183 -0
  26. package/build/node/child-env.js +26 -0
  27. package/build/node/claude-driver.js +741 -0
  28. package/build/node/claude-engine.js +196 -0
  29. package/build/node/cli.js +273 -0
  30. package/build/node/docker-sandbox.js +465 -0
  31. package/build/node/file-runs.js +63 -0
  32. package/build/node/file-state.js +73 -0
  33. package/build/node/git.js +124 -0
  34. package/build/node/github-api.js +79 -0
  35. package/build/node/hidden-input.js +47 -0
  36. package/build/node/key-store.js +150 -0
  37. package/build/node/keychain.js +160 -0
  38. package/build/node/local-stop.js +67 -0
  39. package/build/node/lock.js +155 -0
  40. package/build/node/nudge-command.js +132 -0
  41. package/build/node/nudge-listener.js +137 -0
  42. package/build/node/platform.js +127 -0
  43. package/build/node/policy-file.js +13 -0
  44. package/build/node/prompter.js +166 -0
  45. package/build/node/provider-transport.js +181 -0
  46. package/build/node/repo-path.js +370 -0
  47. package/build/node/run-command.js +59 -0
  48. package/build/node/safe-fs.js +244 -0
  49. package/claude-image/Dockerfile +29 -0
  50. package/git/credential-helper +23 -0
  51. package/npm-shrinkwrap.json +3173 -0
  52. package/package.json +47 -4
  53. package/sandbox/Dockerfile +17 -0
@@ -0,0 +1,340 @@
1
+ import { isId } from "./state.js";
2
+ export const NUDGE_KIND = "podster.dev/nudge";
3
+ export const VERIFY_METHOD = "podster.dev/verifyEndpoint";
4
+ /** What the proof is an HMAC of, before the agent, version and challenge (`podster_egress::nudge::PROOF_LABEL`). */
5
+ export const PROOF_LABEL = "podster-endpoint-proof/1";
6
+ /** **Proposed:** the largest body read. A nudge is about 600 bytes and a challenge about 250. */
7
+ export const MAX_NUDGE_BODY_BYTES = 8 * 1024;
8
+ /** **Proposed:** how far a signature's time may be from Runner's clock, either way. */
9
+ export const SIGNATURE_WINDOW_S = 300;
10
+ /** **Proposed:** requests taken at once, and refilled per minute, for the whole endpoint. */
11
+ export const RATE_BURST = 30;
12
+ export const RATE_PER_MINUTE = 60;
13
+ /** **Proposed:** signatures, attempts and challenges remembered, each for twice the window. */
14
+ export const SEEN_LIMIT = 512;
15
+ /**
16
+ * **Proposed:** the longest public URL taken, under Podster's 2,048. The key-store item holding it with the secret must fit
17
+ * one line of macOS's keychain tool, which a test measures.
18
+ */
19
+ export const MAX_NUDGE_URL_BYTES = 1024;
20
+ /** The shortest wait after a poll, nudged or not: Runner's shortest poll interval, so nudges never poll faster. */
21
+ export const NUDGE_GAP_MS = 5_000;
22
+ const SIGNATURE = /^t=(\d{1,12}),v1=([0-9a-f]{64})$/;
23
+ const CHALLENGE = /^[0-9a-f]{64}$/;
24
+ const ATTEMPT_KINDS = new Set(["offer", "change_request"]);
25
+ const encoder = new TextEncoder();
26
+ export function isRegistration(value) {
27
+ const v = value;
28
+ return !!v && typeof v === "object" && typeof v.url === "string" && isId(v.agent_id) && Number.isSafeInteger(v.version) && v.version > 0 && typeof v.secret === "string" && v.secret.length > 0;
29
+ }
30
+ const hex = (bytes) => [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
31
+ const hmacKey = (secret, usage) => crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [usage]);
32
+ /** Lowercase hex HMAC-SHA256 of `text` under `secret`. */
33
+ export async function hmacHex(secret, text) {
34
+ return hex(await crypto.subtle.sign("HMAC", await hmacKey(secret, "sign"), encoder.encode(text)));
35
+ }
36
+ /** The answer to Podster's challenge: `podster_egress::nudge::proof`. */
37
+ export function proofFor(secret, agent, version, challenge) {
38
+ return hmacHex(secret, `${PROOF_LABEL}.${agent}.${version}.${challenge}`);
39
+ }
40
+ /**
41
+ * Whether `header` signs `body` under `secret` at a time within the window of `nowMs`. The HMAC is checked first, by
42
+ * Web Crypto's own constant-time verify, so the time is only read from a signature that's genuine.
43
+ */
44
+ export async function checkSignature(secret, header, body, nowMs) {
45
+ if (header === null || header === "")
46
+ return { ok: false, code: "unsigned" };
47
+ const match = SIGNATURE.exec(header);
48
+ if (!match)
49
+ return { ok: false, code: "forged" };
50
+ const [, t, digest] = match;
51
+ const given = new Uint8Array(digest.match(/../g).map((pair) => parseInt(pair, 16)));
52
+ const genuine = await crypto.subtle.verify("HMAC", await hmacKey(secret, "verify"), given, encoder.encode(`${t}.${body}`));
53
+ if (!genuine)
54
+ return { ok: false, code: "forged" };
55
+ if (Math.abs(Number(t) - Math.floor(nowMs / 1000)) > SIGNATURE_WINDOW_S)
56
+ return { ok: false, code: "stale" };
57
+ return { ok: true, digest };
58
+ }
59
+ /**
60
+ * The public URL the owner registers: HTTPS, a DNS name with a dot, the default port, no credentials, query or fragment.
61
+ * Podster checks it again under its own egress rules. Answers the URL as written out, or null.
62
+ */
63
+ export function checkNudgeUrl(value) {
64
+ if (encoder.encode(value).byteLength > MAX_NUDGE_URL_BYTES)
65
+ return null;
66
+ let url;
67
+ try {
68
+ url = new URL(value);
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ const host = url.hostname;
74
+ if (url.protocol !== "https:" || url.username || url.password || url.port || url.search || url.hash)
75
+ return null;
76
+ // The URL parser writes every IPv4 form (hex, octal, short) as dotted digits, and IPv6 in brackets.
77
+ if (!host.includes(".") || host.startsWith("[") || /^[0-9.]+$/.test(host))
78
+ return null;
79
+ return encoder.encode(url.href).byteLength > MAX_NUDGE_URL_BYTES ? null : url.href;
80
+ }
81
+ /**
82
+ * The poll loop's wait, cut short by a nudge. Each wait after a good poll first waits `NUDGE_GAP_MS`, so nudges never make
83
+ * Runner poll faster than its shortest interval; a ring before or during that ends the wait there, and a ring later ends
84
+ * it at once. A ring is used once. Only a good poll's wait is ever shortened, so a nudge never cuts a backoff.
85
+ */
86
+ export class NudgeBell {
87
+ pending = false;
88
+ wake = null;
89
+ gapMs;
90
+ constructor(gapMs = NUDGE_GAP_MS) {
91
+ this.gapMs = gapMs;
92
+ }
93
+ ring() {
94
+ this.pending = true;
95
+ this.wake?.();
96
+ }
97
+ take() {
98
+ const was = this.pending;
99
+ this.pending = false;
100
+ return was;
101
+ }
102
+ async idle(clock, ms, signal) {
103
+ const gap = Math.min(ms, this.gapMs);
104
+ await clock.idle(gap, signal);
105
+ if (signal.aborted || gap >= ms || this.take())
106
+ return;
107
+ const woken = new AbortController();
108
+ const stop = () => woken.abort();
109
+ signal.addEventListener("abort", stop, { once: true });
110
+ this.wake = stop;
111
+ try {
112
+ await clock.idle(ms - gap, woken.signal);
113
+ }
114
+ finally {
115
+ this.wake = null;
116
+ signal.removeEventListener("abort", stop);
117
+ this.take();
118
+ }
119
+ }
120
+ }
121
+ const refused = (status) => new Response(null, { status, headers: { connection: "close" } });
122
+ const rpc = (id, answer) => new Response(JSON.stringify({ jsonrpc: "2.0", id: typeof id === "string" || typeof id === "number" ? id : null, ...answer }), { status: 200, headers: { "content-type": "application/json", connection: "close" } });
123
+ const isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
124
+ /** Reads at most `max` bytes of a request's body as UTF-8. Null if it's longer, unreadable or not UTF-8. */
125
+ async function readUpTo(request, max) {
126
+ const body = request.body;
127
+ if (body === null)
128
+ return "";
129
+ const reader = body.getReader();
130
+ const chunks = [];
131
+ let size = 0;
132
+ try {
133
+ for (;;) {
134
+ const { done, value } = await reader.read();
135
+ if (done)
136
+ break;
137
+ size += value.byteLength;
138
+ if (size > max) {
139
+ void reader.cancel().catch(() => undefined);
140
+ return null;
141
+ }
142
+ chunks.push(value);
143
+ }
144
+ }
145
+ catch {
146
+ void reader.cancel().catch(() => undefined);
147
+ return null;
148
+ }
149
+ const bytes = new Uint8Array(size);
150
+ let at = 0;
151
+ for (const chunk of chunks) {
152
+ bytes.set(chunk, at);
153
+ at += chunk.byteLength;
154
+ }
155
+ try {
156
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
157
+ }
158
+ catch {
159
+ return null;
160
+ }
161
+ }
162
+ export class NudgeEndpoint {
163
+ deps;
164
+ /** Each key seen, with when it may be forgotten. Insertion order is age order. */
165
+ seen = new Map();
166
+ tokens = RATE_BURST;
167
+ refilledAt;
168
+ constructor(deps) {
169
+ this.deps = deps;
170
+ this.refilledAt = deps.clock.now();
171
+ }
172
+ /** How many keys the replay memory holds now, for tests. */
173
+ get remembered() {
174
+ return this.seen.size;
175
+ }
176
+ log(outcome, code, ids = {}) {
177
+ this.deps.log("nudge.request", outcome, { ...ids, ...(code ? { code } : {}) });
178
+ }
179
+ refuse(status, code) {
180
+ this.log("refused", code);
181
+ return refused(status);
182
+ }
183
+ admit() {
184
+ const now = this.deps.clock.now();
185
+ this.tokens = Math.min(RATE_BURST, this.tokens + ((now - this.refilledAt) * RATE_PER_MINUTE) / 60_000);
186
+ this.refilledAt = now;
187
+ if (this.tokens < 1)
188
+ return false;
189
+ this.tokens -= 1;
190
+ return true;
191
+ }
192
+ /** Forgets what's past its time. Answers whether there's room for `count` more. */
193
+ room(count) {
194
+ const now = this.deps.clock.now();
195
+ for (const [key, until] of this.seen) {
196
+ if (until > now)
197
+ break;
198
+ this.seen.delete(key);
199
+ }
200
+ return this.seen.size + count <= SEEN_LIMIT;
201
+ }
202
+ remember(...keys) {
203
+ const until = this.deps.clock.now() + 2 * SIGNATURE_WINDOW_S * 1000;
204
+ for (const key of keys) {
205
+ this.seen.delete(key);
206
+ this.seen.set(key, until);
207
+ }
208
+ }
209
+ async handle(request) {
210
+ if (!this.admit())
211
+ return this.refuse(429, "rate_limited");
212
+ if (request.headers.get("origin") !== null)
213
+ return this.refuse(403, "origin_refused");
214
+ if (request.method !== "POST")
215
+ return this.refuse(405, "wrong_method");
216
+ if (new URL(request.url).pathname !== this.deps.path)
217
+ return this.refuse(404, "wrong_path");
218
+ const registration = this.deps.registration();
219
+ if (registration === null)
220
+ return this.refuse(503, "no_registration");
221
+ const declared = request.headers.get("content-length");
222
+ if (declared !== null && !(Number(declared) <= MAX_NUDGE_BODY_BYTES))
223
+ return this.refuse(413, "too_large");
224
+ const body = await readUpTo(request, MAX_NUDGE_BODY_BYTES);
225
+ if (body === null)
226
+ return this.refuse(413, "too_large");
227
+ // Nothing in the body is looked at until its signature and time pass.
228
+ const signature = await checkSignature(registration.secret, request.headers.get("x-podster-signature"), body, this.deps.clock.now());
229
+ if (!signature.ok)
230
+ return this.refuse(401, signature.code);
231
+ if (!this.room(0))
232
+ return this.refuse(503, "memory_full");
233
+ if (this.seen.has(`sig:${signature.digest}`))
234
+ return this.refuse(409, "replayed");
235
+ let parsed;
236
+ try {
237
+ parsed = JSON.parse(body);
238
+ }
239
+ catch {
240
+ return this.refuse(400, "bad_request");
241
+ }
242
+ if (!isObject(parsed) || parsed.jsonrpc !== "2.0" || !isObject(parsed.params))
243
+ return this.refuse(400, "bad_request");
244
+ const { id, method, params } = parsed;
245
+ if (method === VERIFY_METHOD)
246
+ return this.verify(registration, id, params, signature.digest);
247
+ if (method === "SendMessage")
248
+ return this.nudge(id, params, signature.digest);
249
+ this.log("refused", "wrong_kind");
250
+ return rpc(id, { error: { code: -32601, message: "Only a Podster nudge is taken here." } });
251
+ }
252
+ async verify(registration, id, params, digest) {
253
+ const { agent_id: agent, version, challenge } = params;
254
+ if (agent !== registration.agent_id || version !== registration.version || typeof challenge !== "string" || !CHALLENGE.test(challenge) || id !== challenge) {
255
+ this.log("refused", "wrong_registration");
256
+ return rpc(id, { error: { code: -32602, message: "Not this endpoint's registration." } });
257
+ }
258
+ if (this.seen.has(`challenge:${challenge}`)) {
259
+ // Refused, and not remembered: a repeat is harmless, and remembering it could fill the memory.
260
+ this.log("refused", "replayed");
261
+ return rpc(id, { error: { code: -32602, message: "This challenge was answered already." } });
262
+ }
263
+ if (!this.room(2))
264
+ return this.refuse(503, "memory_full");
265
+ this.remember(`sig:${digest}`, `challenge:${challenge}`);
266
+ this.log("verified");
267
+ return rpc(id, { result: { proof: await proofFor(registration.secret, registration.agent_id, registration.version, challenge) } });
268
+ }
269
+ nudge(id, params, digest) {
270
+ const message = params.message;
271
+ const parts = isObject(message) ? message.parts : undefined;
272
+ const part = Array.isArray(parts) && parts.length === 1 && isObject(parts[0]) ? parts[0] : null;
273
+ const data = part && isObject(part.data) ? part.data : null;
274
+ const keys = data ? Object.keys(data).sort().join(",") : "";
275
+ if (!isObject(message) ||
276
+ !data ||
277
+ data.kind !== NUDGE_KIND ||
278
+ keys !== "attempt_id,attempt_kind,kind,task_id,workspace_id" ||
279
+ !isId(data.workspace_id) ||
280
+ !isId(data.task_id) ||
281
+ !isId(data.attempt_id) ||
282
+ !ATTEMPT_KINDS.has(data.attempt_kind) ||
283
+ message.messageId !== data.attempt_id) {
284
+ this.log("refused", "wrong_kind");
285
+ return rpc(id, { error: { code: -32602, message: "Only a Podster nudge is taken here." } });
286
+ }
287
+ // The attempt's ID ties this line to Podster's own audit of the nudge (R-18).
288
+ const ids = { workspace: data.workspace_id, task: data.task_id, attempt_id: data.attempt_id };
289
+ const taken = { result: { message: { messageId: crypto.randomUUID(), role: "ROLE_AGENT", parts: [{ text: "Nudged. Runner checks its inbox." }] } } };
290
+ if (this.seen.has(`attempt:${data.attempt_id}`)) {
291
+ // Podster's retry of an attempt already taken: answered, so it stops retrying, and nothing more is rung. Not
292
+ // remembered: answering it again is harmless, and remembering it could fill the memory.
293
+ this.log("duplicate", undefined, ids);
294
+ return rpc(id, taken);
295
+ }
296
+ if (!this.room(2))
297
+ return this.refuse(503, "memory_full");
298
+ this.remember(`sig:${digest}`, `attempt:${data.attempt_id}`);
299
+ this.log("nudged", undefined, ids);
300
+ this.deps.bell.ring();
301
+ return rpc(id, taken);
302
+ }
303
+ }
304
+ /**
305
+ * Registers `url` as this agent's nudge endpoint, keeping any registration Podster and Runner already share. The same URL
306
+ * set again keeps its version and secret in Podster, and its proof and the owner's opt-in with them. Only if Runner holds
307
+ * no secret for the version Podster answers does it ask for a new one (`rotate_secret`), which needs proof and the
308
+ * owner's opt-in again. A new secret goes to the key store before anything else uses it.
309
+ */
310
+ export async function registerNudge(calls, storage, url, log) {
311
+ const held = await storage.getNudge();
312
+ const read = async (args) => {
313
+ const answer = await calls.request("set_a2a_endpoint", args);
314
+ if (!isObject(answer) || answer.url !== url || answer.delivery !== "nudge" || !Number.isSafeInteger(answer.version))
315
+ throw new Error("bad_answer");
316
+ return answer;
317
+ };
318
+ let answer = await read({ url, delivery: "nudge" });
319
+ let secret = typeof answer.signing_secret === "string" && answer.signing_secret.length > 0 ? answer.signing_secret : null;
320
+ const same = held !== null && held.url === url && held.agent_id === calls.agentId && held.version === answer.version;
321
+ if (secret === null && !same) {
322
+ answer = await read({ url, delivery: "nudge", rotate_secret: true });
323
+ secret = typeof answer.signing_secret === "string" && answer.signing_secret.length > 0 ? answer.signing_secret : null;
324
+ if (secret === null)
325
+ throw new Error("bad_answer");
326
+ }
327
+ const registration = secret === null ? held : { url, agent_id: calls.agentId, version: answer.version, secret };
328
+ if (secret !== null)
329
+ await storage.setNudge(registration);
330
+ log("nudge.register", secret === null ? "kept" : "new_secret", { agent: calls.agentId, count: registration.version });
331
+ return { registration, control: answer.control === "verified" ? "verified" : "unverified", nudge_on: answer.nudge_on === true };
332
+ }
333
+ /** Asks Podster to challenge the endpoint, which must already be listening. Answers whether it proved control. */
334
+ export async function verifyNudge(calls, log) {
335
+ const answer = await calls.request("verify_a2a_endpoint");
336
+ const verified = isObject(answer) && answer.verified === true;
337
+ const reason = isObject(answer) && typeof answer.reason === "string" ? answer.reason : undefined;
338
+ log("nudge.verify", verified ? "verified" : "not_verified", { agent: calls.agentId, ...(reason ? { code: reason } : {}) });
339
+ return { verified, nudge_on: isObject(answer) && answer.nudge_on === true };
340
+ }
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Pairing from the machine (M7 step 6; decision 222; RUNNER.md, "Pair once"). A person starts a pairing in Podster and
3
+ * gets a code; here Runner, with the owner's consent, makes a key on this machine, shows its whole thumbprint, redeems
4
+ * the code with a proof signed by that key, registers its one agent on the paired host, and waits for the person to
5
+ * confirm the same thumbprint in Podster.
6
+ *
7
+ * - **A fresh proof each time.** Every redeem, a retry included, sends a new host JWT signed by the key, with the
8
+ * session's agent as its issuer and subject, the gateway's origin as its audience, and no agent key in it.
9
+ * - **One agent, reused.** Runner registers exactly one agent on the host, naming only `RUNNER_CAPABILITIES`, and keeps
10
+ * using it. If registration's answer is lost, Runner can't know whether an agent exists, so it never registers again:
11
+ * it stops and asks the owner to cancel and pair again.
12
+ * - **Waiting.** `agent_unclaimed` means the person hasn't confirmed yet: Runner asks again with a backoff.
13
+ * - **Ended.** A pairing that's canceled, refused or ended (a refused redeem, a refused registration, `agent_revoked`
14
+ * while waiting) retires its key: its thumbprint is recorded so it's never used again, the keys are deleted, and the
15
+ * owner is told to start a new pairing in Podster. A new pairing always makes a new key.
16
+ * - **Lost answers.** A redeem that can't reach the gateway keeps the key, so running `pair` again with the same agent
17
+ * and code tries again with the same key and a fresh proof, and the gateway answers as before.
18
+ *
19
+ * Runner never calls the SDK's `disconnectAgent`, `rotateAgentKey` or `rotateHostKey` (M7 plan, the architect's ruling
20
+ * 3 on spike A). Nothing here logs a code, a key or a proof.
21
+ */
22
+ import { AgentAuthClient, generateKeypair, signHostJWT } from "@auth/agent";
23
+ import { RUNNER_CAPABILITIES, SWITCHED } from "./capabilities.js";
24
+ import { Connection } from "./connection.js";
25
+ import { errorFrom, GatewayError, meaningOf, readBounded } from "./errors.js";
26
+ import { boundedBodies, gatewayFetch } from "./gateway.js";
27
+ import { emptyState, isId } from "./state.js";
28
+ import { RunnerStorage } from "./storage.js";
29
+ import { grouped, thumbprintOf } from "./thumbprint.js";
30
+ /** A pairing code as Podster gives it: the plugin's one-time enrollment token. */
31
+ const CODE = /^[A-Za-z0-9_-]{32,128}$/;
32
+ /** Redeem tries before Runner leaves it for the owner to run again. */
33
+ const REDEEM_TRIES = 5;
34
+ /** How long Runner waits for the person's confirmation in one run of `pair`. The session itself expires sooner. */
35
+ export const CONFIRM_WITHIN_MS = 15 * 60 * 1000;
36
+ const FIRST_WAIT_MS = 2_000;
37
+ /** No wait is shorter than this, whatever a retry-after says, so a refusal can never make Runner spin. */
38
+ const MIN_WAIT_MS = 1_000;
39
+ const LONGEST_WAIT_MS = 30_000;
40
+ /** Retired thumbprints kept, newest last. */
41
+ const RETIRED_KEPT = 200;
42
+ const RUNNER_NAME = "Podster Runner";
43
+ /** Pairs this Runner, or carries an interrupted pairing on from where its record says it got to. */
44
+ export async function pair(deps, input) {
45
+ const { agentId } = input;
46
+ if (!isId(agentId) || !agentId.startsWith("agt_"))
47
+ throw new Error("The agent ID is the agt_… shown in Podster's pairing address");
48
+ const storage = new RunnerStorage(deps.secrets);
49
+ let state = await deps.state.load();
50
+ // The thumbprint of the key this run used, kept for the answer even once the key is retired.
51
+ let used = state.thumbprint;
52
+ const done = (outcome) => ({ outcome, agentId, thumbprint: state.thumbprint ?? used });
53
+ // A connected Runner stays as it is until the owner runs `forget`: one Runner, one agent.
54
+ if (state.phase === "connected" && state.stopped === null)
55
+ return done("already_paired");
56
+ // The same pairing, interrupted, carries on with its own key. Anything else is a new pairing, which retires whatever key
57
+ // came before: a key is never carried from one pairing to another.
58
+ const resuming = state.agent_id === agentId && state.gateway === deps.origin && state.stopped === null && state.phase !== null;
59
+ if (resuming && state.phase === "registering") {
60
+ state = { ...state, stopped: "registration_unknown" };
61
+ await deps.state.save(state);
62
+ deps.log("pairing.register", "answer_lost", { agent: agentId });
63
+ return done("registration_unknown");
64
+ }
65
+ if (!resuming) {
66
+ if (typeof input.code !== "string" || !CODE.test(input.code))
67
+ throw new Error("The code is the one Podster showed when the pairing started");
68
+ if (!(await deps.consent({ origin: deps.origin, agentId })))
69
+ return done("declined");
70
+ state = await retire(deps, storage, state, null);
71
+ const keypair = await freshKey(state.retired);
72
+ const thumbprint = await thumbprintOf(keypair.publicKey);
73
+ // The record names the key before the key is stored, so a crash between leaves a thumbprint with no key, never a key the record doesn't know.
74
+ used = thumbprint;
75
+ state = { ...emptyState(), retired: state.retired, gateway: deps.origin, agent_id: agentId, thumbprint, phase: "key_made" };
76
+ await deps.state.save(state);
77
+ await storage.installHostKey(keypair);
78
+ deps.log("pairing.key", "made", { agent: agentId });
79
+ }
80
+ const host = await storage.getHostIdentity();
81
+ if (!host || !state.thumbprint || (await thumbprintOf(host.keypair.publicKey)) !== state.thumbprint || state.retired.includes(state.thumbprint)) {
82
+ state = await retire(deps, storage, state, "pairing_ended");
83
+ return done("pairing_ended");
84
+ }
85
+ deps.notify({ kind: "thumbprint", thumbprint: state.thumbprint, grouped: grouped(state.thumbprint) });
86
+ if (state.phase === "key_made") {
87
+ if (typeof input.code !== "string" || !CODE.test(input.code))
88
+ throw new Error("The code is the one Podster showed when the pairing started");
89
+ const redeemed = await redeem(deps, host.keypair, agentId, input.code, state.thumbprint);
90
+ if (redeemed.kind === "unreachable")
91
+ return done("unreachable");
92
+ if (redeemed.kind === "ended") {
93
+ state = await retire(deps, storage, state, "pairing_ended");
94
+ return done("pairing_ended");
95
+ }
96
+ state = { ...state, phase: "redeemed", plugin_host_id: redeemed.hostId };
97
+ await deps.state.save(state);
98
+ }
99
+ if (state.phase === "redeemed") {
100
+ state = { ...state, phase: "registering" };
101
+ await deps.state.save(state);
102
+ const registered = await register(deps, storage);
103
+ if (registered.kind === "retry") {
104
+ state = { ...state, phase: "redeemed" };
105
+ await deps.state.save(state);
106
+ return done("unreachable");
107
+ }
108
+ if (registered.kind === "unknown") {
109
+ state = { ...state, stopped: "registration_unknown" };
110
+ await deps.state.save(state);
111
+ deps.log("pairing.register", "answer_lost", { agent: agentId });
112
+ return done("registration_unknown");
113
+ }
114
+ if (registered.kind === "ended") {
115
+ state = await retire(deps, storage, state, "pairing_ended");
116
+ return done("pairing_ended");
117
+ }
118
+ state = { ...state, phase: "registered", plugin_agent_id: registered.pluginAgentId };
119
+ await deps.state.save(state);
120
+ deps.log("pairing.register", "registered", { agent: agentId, plugin_agent: registered.pluginAgentId });
121
+ }
122
+ if (state.phase === "registered" && state.plugin_agent_id) {
123
+ deps.notify({ kind: "waiting_for_confirmation", agentId });
124
+ const confirmed = await waitForConfirmation(deps, storage, state.plugin_agent_id, agentId);
125
+ if (confirmed === "waiting")
126
+ return done("waiting");
127
+ if (confirmed === "ended") {
128
+ state = await retire(deps, storage, state, "pairing_ended");
129
+ return done("pairing_ended");
130
+ }
131
+ state = { ...state, phase: "connected", last_contact_at: deps.clock.now() };
132
+ await deps.state.save(state);
133
+ deps.log("pairing.confirm", "connected", { agent: agentId });
134
+ return done("connected");
135
+ }
136
+ return done(state.phase === "connected" ? "connected" : "pairing_ended");
137
+ }
138
+ /** A new key whose thumbprint was never retired. */
139
+ async function freshKey(retired) {
140
+ for (;;) {
141
+ const keypair = await generateKeypair();
142
+ if (!retired.includes(await thumbprintOf(keypair.publicKey)))
143
+ return keypair;
144
+ }
145
+ }
146
+ /**
147
+ * Retires the current pairing's key, if there is one: its thumbprint goes on the retired list before the keys are
148
+ * deleted, so a crash between still never uses it again. With `stop`, the record says why Runner stopped.
149
+ */
150
+ export async function retire(deps, storage, state, stop) {
151
+ const retired = state.thumbprint && !state.retired.includes(state.thumbprint) ? [...state.retired, state.thumbprint].slice(-RETIRED_KEPT) : state.retired;
152
+ const next = { ...state, retired, phase: null, plugin_host_id: null, plugin_agent_id: null, thumbprint: null, stopped: stop };
153
+ await deps.state.save(next);
154
+ await storage.deleteAll();
155
+ if (state.thumbprint)
156
+ deps.log("pairing.key", "retired", { agent: state.agent_id ?? undefined });
157
+ return next;
158
+ }
159
+ /** The most of a redeem answer Runner reads, and of any answer the SDK reads while registering. */
160
+ const MAX_REDEEM_BYTES = 16_384;
161
+ const MAX_SDK_ANSWER_BYTES = 64 * 1024;
162
+ async function redeem(deps, keypair, agentId, code, thumbprint) {
163
+ const reach = gatewayFetch(deps.origin, deps.fetch);
164
+ let wait = FIRST_WAIT_MS;
165
+ for (let attempt = 1; attempt <= REDEEM_TRIES; attempt++) {
166
+ // A fresh proof every time: its own `jti`, the session's agent as issuer and subject, and no agent key.
167
+ const proof = await signHostJWT({ hostKeypair: keypair, audience: deps.origin, issuer: agentId });
168
+ let failure;
169
+ try {
170
+ const response = await reach(`${deps.origin}/pairing/${agentId}/redeem`, {
171
+ method: "POST",
172
+ headers: { "content-type": "application/json", authorization: `Bearer ${proof}` },
173
+ body: JSON.stringify({ code }),
174
+ signal: AbortSignal.timeout(30_000),
175
+ });
176
+ if (response.ok) {
177
+ // Read only up to the bound: an answer past it, or one that never ends, is cut there and read as no answer.
178
+ const text = await readBounded(response, MAX_REDEEM_BYTES);
179
+ let answer = null;
180
+ try {
181
+ answer = text === null ? null : JSON.parse(text);
182
+ }
183
+ catch {
184
+ answer = null;
185
+ }
186
+ if (answer?.agent_id === agentId && answer.key_thumbprint === thumbprint && isId(answer.plugin_host_id)) {
187
+ deps.log("pairing.redeem", "redeemed", { agent: agentId });
188
+ return { kind: "redeemed", hostId: answer.plugin_host_id };
189
+ }
190
+ deps.log("pairing.redeem", "answer_mismatch", { agent: agentId });
191
+ return { kind: "ended" };
192
+ }
193
+ failure = await errorFrom(response);
194
+ }
195
+ catch (error) {
196
+ failure = error instanceof GatewayError ? error : new GatewayError(0, "network");
197
+ }
198
+ const meaning = meaningOf(failure);
199
+ deps.log("pairing.redeem", meaning === "transient" || meaning === "rate_limited" ? "retry" : "refused", { agent: agentId, status: failure.status, code: failure.code });
200
+ if (meaning !== "transient" && meaning !== "rate_limited")
201
+ return { kind: "ended" };
202
+ if (attempt < REDEEM_TRIES)
203
+ await deps.clock.idle(failure.retryAfter !== null ? Math.max(failure.retryAfter * 1000, MIN_WAIT_MS) : wait);
204
+ wait = Math.min(wait * 2, LONGEST_WAIT_MS);
205
+ }
206
+ return { kind: "unreachable" };
207
+ }
208
+ /**
209
+ * Registers the one agent on the paired host, with the stored host key and Runner's allowlist. The paired host makes it
210
+ * active at once; anything asking for an approval would ask for more than the pairing gives, so it ends the pairing.
211
+ */
212
+ async function register(deps, storage) {
213
+ const stop = new AbortController();
214
+ const client = new AgentAuthClient({
215
+ storage,
216
+ urls: [deps.origin],
217
+ // Every answer the SDK reads is bounded first: it reads them whole (review L3 on #461).
218
+ fetch: boundedBodies(gatewayFetch(deps.origin, deps.fetch), MAX_SDK_ANSWER_BYTES),
219
+ hostName: RUNNER_NAME,
220
+ approvalTimeoutMs: 1,
221
+ // An approval is never Runner's to wait for: the paired host's defaults are all it asks for.
222
+ onApprovalRequired: () => stop.abort(),
223
+ });
224
+ try {
225
+ await client.init();
226
+ const connect = (capabilities) => client.connectAgent({ provider: deps.origin, capabilities, mode: "delegated", preferredMethod: "device_authorization", name: RUNNER_NAME, signal: stop.signal });
227
+ let connected;
228
+ try {
229
+ connected = await connect([...RUNNER_CAPABILITIES]);
230
+ }
231
+ catch (error) {
232
+ // A deployment with managed repositories off doesn't list `get_repo_access` (M7 step 10): the same list without it.
233
+ if (error?.code !== "invalid_capabilities" || stop.signal.aborted)
234
+ throw error;
235
+ deps.log("pairing.register", "without_switched", { code: "invalid_capabilities" });
236
+ connected = await connect(RUNNER_CAPABILITIES.filter((c) => !SWITCHED.includes(c)));
237
+ }
238
+ if (connected.status !== "active" || !isId(connected.agentId))
239
+ return { kind: "ended" };
240
+ return { kind: "registered", pluginAgentId: connected.agentId };
241
+ }
242
+ catch (error) {
243
+ const status = typeof error?.status === "number" ? (error.status) : 0;
244
+ deps.log("pairing.register", "failed", { status });
245
+ if (stop.signal.aborted)
246
+ return { kind: "ended" };
247
+ if (status === 429)
248
+ return { kind: "retry" };
249
+ if (status >= 400 && status < 500)
250
+ return { kind: "ended" };
251
+ return { kind: "unknown" };
252
+ }
253
+ finally {
254
+ client.destroy();
255
+ }
256
+ }
257
+ /** Asks Podster who Runner is until the person confirms, with a backoff. */
258
+ async function waitForConfirmation(deps, storage, pluginAgentId, agentId) {
259
+ const connection = new Connection({ origin: deps.origin, pluginAgentId, storage, fetch: deps.fetch });
260
+ const until = deps.clock.now() + (deps.confirmWithinMs ?? CONFIRM_WITHIN_MS);
261
+ let wait = FIRST_WAIT_MS;
262
+ for (;;) {
263
+ try {
264
+ const identity = (await connection.call("get_identity"));
265
+ if (identity?.id === agentId)
266
+ return "connected";
267
+ deps.log("pairing.confirm", "wrong_agent", { agent: agentId });
268
+ return "ended";
269
+ }
270
+ catch (error) {
271
+ const failure = error instanceof GatewayError ? error : new GatewayError(0, "network");
272
+ const meaning = meaningOf(failure);
273
+ if (meaning === "authority") {
274
+ deps.log("pairing.confirm", "ended", { agent: agentId, status: failure.status, code: failure.code });
275
+ return "ended";
276
+ }
277
+ if (meaning !== "unclaimed")
278
+ deps.log("pairing.confirm", "retry", { agent: agentId, status: failure.status, code: failure.code });
279
+ if (deps.clock.now() >= until)
280
+ return "waiting";
281
+ await deps.clock.idle(failure.retryAfter !== null ? Math.max(failure.retryAfter * 1000, MIN_WAIT_MS) : wait);
282
+ wait = Math.min(Math.round(wait * 1.5), LONGEST_WAIT_MS);
283
+ }
284
+ }
285
+ }