podster 0.0.1-test.13 → 0.0.1-test.15

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.
@@ -0,0 +1,347 @@
1
+ /**
2
+ * Role invites (issue 522): Runner answers an invite to a role opening as its own agent, through its ordinary inbox, under
3
+ * the owner's local policy. No other client and no other credential is involved.
4
+ *
5
+ * - **Found through the inbox.** `role.invited` names only the room. The reducer records that room (`record.ts`) in the
6
+ * same save as the cursor, and a reconciliation records every room it lists, so an invite is never acknowledged
7
+ * unrecorded and one made while Runner was off is still found. Each room is then read with `list_role_openings`, whose
8
+ * `mine: "invited"` is Podster's own answer about this agent; Runner takes only the opening's ID from it to act on.
9
+ * - **The owner's policy decides.** A room the owner set to `roles: "accept"` in Runner's local policy has its invites
10
+ * claimed with no question. Anywhere else, the default, Runner asks the owner on this machine, as it does for a task in
11
+ * ask mode. Silence is never an answer: no prompter, no terminal or no reply leaves the invite waiting, asked again
12
+ * later. Runner never declines by itself; only the owner's answer does.
13
+ * - **Podster decides authority.** `claim_role` and `decline_role` are the agent's own calls, and the room checks each:
14
+ * only the invite naming this agent can be claimed or declined, and a claim copies only the opening's preset. A claim
15
+ * accepts no task and a decline declines none; neither grants a person anything.
16
+ * - **Agent content is data.** An opening's title and responsibilities are someone else's text. They go only to the
17
+ * owner's screen, marked as untrusted, never to a model, a log or Runner's record.
18
+ * - **A question never holds up task work** (issue 528). The owner's answer is waited for off the poll loop: a pass starts
19
+ * the question and returns, and the answer is used on a later pass, after the room is read again. One question is on
20
+ * the terminal at a time; other invites wait, unanswered, for their turn. The invite stays pending until it's answered.
21
+ * A question a task needs the terminal for interrupts it (`QuestionInterrupted`), and it's asked again after.
22
+ * - **A stored answer belongs to one invite.** The room's list doesn't name an invite apart from its opening, so Runner
23
+ * ties each answer to the room's newest `role.invited` notice when the answer was made. A newer notice may be the same
24
+ * opening withdrawn and invited again, so a refusal, a `later` or an answer not yet sent is dropped then, and the invite
25
+ * is read and asked about afresh. An owner's answer that arrives after a newer notice is set aside the same way.
26
+ * - **An older pairing.** A pairing registered before these capabilities were Runner's doesn't hold them, and calling one
27
+ * would read as an authority error. Runner checks its stored grants first and, missing any, leaves invites alone and
28
+ * says once that pairing again enables this.
29
+ */
30
+ import { GatewayError, meaningOf } from "./errors.js";
31
+ import { parsePolicyConfig } from "./policy.js";
32
+ import { AuthorityEnded } from "./poller.js";
33
+ import { isId } from "./state.js";
34
+ /** The capabilities answering an invite needs, all of them. */
35
+ export const ROLE_CAPABILITIES = ["list_role_openings", "claim_role", "decline_role"];
36
+ /** How long an invite the owner left waits before it's asked again. */
37
+ export const ROLE_ASK_AGAIN_MS = 10 * 60 * 1000;
38
+ /** Rooms read in one pass. The rest wait for the next. */
39
+ export const ROOMS_PER_PASS = 10;
40
+ /** A role question set aside because something else needed the terminal: not an answer, and asked again soon. */
41
+ export class QuestionInterrupted extends Error {
42
+ constructor() {
43
+ super("question_interrupted");
44
+ }
45
+ }
46
+ const PRESET = /^[a-z_]{1,32}$/;
47
+ const answerKey = (workspace, role) => `${workspace}/${role}`;
48
+ /** The invites to this agent a `list_role_openings` answer shows, read for their shape. Null for an answer that isn't one. */
49
+ export function readInvites(workspaceId, answer) {
50
+ if (!answer || typeof answer !== "object")
51
+ return null;
52
+ const { roles, external } = answer;
53
+ if (!Array.isArray(roles))
54
+ return null;
55
+ const invited = [];
56
+ const listed = new Set();
57
+ for (const row of roles) {
58
+ if (!row || typeof row !== "object")
59
+ continue;
60
+ const { id, mine, title, responsibilities, preset, is_lead } = row;
61
+ if (!isId(id))
62
+ continue;
63
+ listed.add(id);
64
+ if (mine !== "invited")
65
+ continue;
66
+ invited.push({
67
+ workspace_id: workspaceId,
68
+ role_id: id,
69
+ title: typeof title === "string" ? title : "",
70
+ responsibilities: typeof responsibilities === "string" ? responsibilities : "",
71
+ preset: typeof preset === "string" && PRESET.test(preset) ? preset : "unknown",
72
+ is_lead: is_lead === true,
73
+ external: external === true,
74
+ });
75
+ }
76
+ return { invited, listed };
77
+ }
78
+ /** The owner's choice for invites in a room: `accept` only where the local policy says so for that room. */
79
+ export function roleMode(config, workspaceId, home) {
80
+ const parsed = parsePolicyConfig(config, home === undefined ? {} : { runner_home: home });
81
+ if (!parsed.ok)
82
+ return "ask";
83
+ return parsed.value.rooms.find((room) => room.room_id === workspaceId)?.roles ?? "ask";
84
+ }
85
+ export class RoleInvites {
86
+ deps;
87
+ newId;
88
+ toldMissing = false;
89
+ /** The one question waiting for the owner, if any. */
90
+ asking = null;
91
+ /** Owner answers not yet used, by answer key, with the notice they were asked under. Used only after a fresh read. */
92
+ heard = new Map();
93
+ constructor(deps) {
94
+ this.deps = deps;
95
+ this.newId = deps.newId ?? (() => crypto.randomUUID());
96
+ }
97
+ now() {
98
+ return this.deps.clock.now();
99
+ }
100
+ log(outcome, workspace, code) {
101
+ this.deps.log("roles.invite", outcome, { agent: this.deps.poller.agentId, workspace, ...(code ? { code } : {}) });
102
+ }
103
+ async readConfig() {
104
+ try {
105
+ const config = this.deps.config;
106
+ return typeof config === "function" ? await config() : config;
107
+ }
108
+ catch {
109
+ return null;
110
+ }
111
+ }
112
+ async setAnswer(key, answer) {
113
+ await this.deps.poller.updateRecord((state) => {
114
+ const answers = { ...(state.role_answers ?? {}) };
115
+ if (answer)
116
+ answers[key] = { ...answer, updated_at: this.now() };
117
+ else
118
+ delete answers[key];
119
+ return { ...state, role_answers: answers };
120
+ });
121
+ }
122
+ async settleCheck(workspace) {
123
+ await this.deps.poller.updateRecord((state) => {
124
+ const known = state.role_checks?.[workspace];
125
+ if (!known)
126
+ return state;
127
+ return { ...state, role_checks: { ...state.role_checks, [workspace]: { ...known, due: false, updated_at: this.now() } } };
128
+ });
129
+ }
130
+ /** The room's newest invite notice: what a stored answer's `invite_seq` is checked against. */
131
+ noticeSeq(workspace) {
132
+ return this.deps.poller.record.role_checks?.[workspace]?.seq ?? null;
133
+ }
134
+ /** Whether a stored answer was made under an older notice than the room's newest, so may be for another invite. */
135
+ stale(answer) {
136
+ return (answer.invite_seq ?? null) !== this.noticeSeq(answer.workspace_id);
137
+ }
138
+ /**
139
+ * Rooms with something to do now: a check due, a command owed, an owner's answer to use, or an invite whose turn to be
140
+ * asked has come. An invite waiting for the question on the terminal to end waits without reading its room.
141
+ */
142
+ work() {
143
+ const record = this.deps.poller.record;
144
+ const answers = Object.entries(record.role_answers ?? {});
145
+ const owed = answers.map(([, a]) => a).filter((a) => a.state === "claiming" || a.state === "declining");
146
+ const rooms = new Set(Object.values(record.role_checks ?? {}).filter((c) => c.due).sort((a, b) => a.updated_at - b.updated_at).map((c) => c.workspace_id));
147
+ for (const [key, a] of answers) {
148
+ if (a.state !== "later")
149
+ continue;
150
+ if (this.heard.has(key))
151
+ rooms.add(a.workspace_id);
152
+ else if (a.asked_at === null ? this.asking === null : this.now() - a.asked_at >= ROLE_ASK_AGAIN_MS)
153
+ rooms.add(a.workspace_id);
154
+ }
155
+ return { rooms: [...rooms].slice(0, ROOMS_PER_PASS), owed };
156
+ }
157
+ /**
158
+ * One pass: owed claims and declines first, with their stored keys, then each room due a read. An authority error
159
+ * throws `AuthorityEnded` for the lifecycle to handle. A network failure leaves everything as it is, for the next pass.
160
+ */
161
+ async pass(signal) {
162
+ const { rooms, owed } = this.work();
163
+ if (rooms.length === 0 && owed.length === 0)
164
+ return;
165
+ if (!this.deps.poller.authorityFresh())
166
+ return;
167
+ const granted = await this.deps.poller.granted();
168
+ if (!ROLE_CAPABILITIES.every((c) => granted.has(c))) {
169
+ if (!this.toldMissing)
170
+ this.deps.log("roles.invite", "unavailable", { agent: this.deps.poller.agentId, code: "pair_again_for_roles" });
171
+ this.toldMissing = true;
172
+ return;
173
+ }
174
+ try {
175
+ for (const answer of owed) {
176
+ if (signal.aborted)
177
+ return;
178
+ if (this.stale(answer)) {
179
+ // A newer invite notice in the room: this answer may be for an invite that's gone. The room is read again.
180
+ await this.setAnswer(answerKey(answer.workspace_id, answer.role_id), null);
181
+ this.log("answer_set_aside", answer.workspace_id);
182
+ continue;
183
+ }
184
+ await this.send(answer);
185
+ }
186
+ for (const room of rooms) {
187
+ if (signal.aborted)
188
+ return;
189
+ await this.room(room, signal);
190
+ }
191
+ }
192
+ catch (error) {
193
+ if (error instanceof AuthorityEnded)
194
+ throw error;
195
+ if (signal.aborted)
196
+ return;
197
+ const failure = error instanceof GatewayError ? error : new GatewayError(0, "unknown");
198
+ this.deps.log("roles.invite", "unreachable", { agent: this.deps.poller.agentId, status: failure.status, code: failure.code });
199
+ }
200
+ }
201
+ /** Reads one room's openings and answers each invite to this agent. */
202
+ async room(workspace, signal) {
203
+ let answer;
204
+ try {
205
+ answer = await this.deps.poller.request("list_role_openings", { workspace_id: workspace });
206
+ }
207
+ catch (error) {
208
+ if (error instanceof GatewayError && meaningOf(error) === "refused") {
209
+ // A room this agent can no longer read: nothing to answer there.
210
+ this.log("room_unreadable", workspace, error.code);
211
+ await this.forgetRoom(workspace, new Set());
212
+ await this.settleCheck(workspace);
213
+ return;
214
+ }
215
+ throw error;
216
+ }
217
+ const read = readInvites(workspace, answer);
218
+ if (!read)
219
+ throw new GatewayError(0, "bad_answer");
220
+ // An answer whose invite the room no longer lists is done with: claimed, declined, withdrawn or closed.
221
+ await this.forgetRoom(workspace, new Set(read.invited.map((i) => i.role_id)));
222
+ const config = await this.readConfig();
223
+ const seq = this.noticeSeq(workspace);
224
+ for (const invite of read.invited) {
225
+ if (signal.aborted)
226
+ return;
227
+ const key = answerKey(workspace, invite.role_id);
228
+ const known = this.deps.poller.record.role_answers?.[key];
229
+ const fresh = !!known && !this.stale(known);
230
+ if (fresh && known.state === "refused")
231
+ continue;
232
+ if (known?.state === "claiming" || known?.state === "declining")
233
+ continue;
234
+ const mode = roleMode(config, workspace, this.deps.home);
235
+ const heard = this.heard.get(key);
236
+ this.heard.delete(key);
237
+ let choice;
238
+ if (mode === "accept") {
239
+ // The owner set this room to claim by itself: a question still open about it isn't needed.
240
+ if (this.asking?.key === key)
241
+ this.asking.controller.abort();
242
+ this.log("found", workspace);
243
+ choice = "approve";
244
+ }
245
+ else if (heard && heard.seq === seq) {
246
+ choice = heard.choice;
247
+ }
248
+ else {
249
+ // An answer asked under an older notice may be about an invite that's gone: asked again, never reused.
250
+ if (heard)
251
+ this.log("answer_set_aside", workspace);
252
+ if (this.asking?.key === key) {
253
+ // Asked under an older notice: its answer couldn't be used, so the question ends now and is asked again after.
254
+ if (this.asking.seq !== seq)
255
+ this.asking.controller.abort();
256
+ continue;
257
+ }
258
+ if (fresh && known.state === "later" && known.asked_at !== null && this.now() - known.asked_at < ROLE_ASK_AGAIN_MS)
259
+ continue;
260
+ if (this.asking || !this.deps.prompter.role) {
261
+ // Another question is on the terminal, or there's no way to ask: it waits, never answered by silence.
262
+ if (!this.asking)
263
+ choice = "later";
264
+ else {
265
+ if (known?.state !== "later" || known.asked_at !== null || known.invite_seq !== seq)
266
+ await this.setAnswer(key, this.later(invite, seq, null));
267
+ continue;
268
+ }
269
+ }
270
+ else {
271
+ this.log("found", workspace);
272
+ await this.setAnswer(key, this.later(invite, seq, null));
273
+ this.ask(key, seq, invite, signal);
274
+ this.log("asking_owner", workspace);
275
+ continue;
276
+ }
277
+ }
278
+ if (choice === "later") {
279
+ await this.setAnswer(key, this.later(invite, seq, this.now()));
280
+ this.log("waiting_for_owner", workspace);
281
+ continue;
282
+ }
283
+ const pending = { workspace_id: workspace, role_id: invite.role_id, state: choice === "approve" ? "claiming" : "declining", key: this.newId(), code: null, asked_at: this.now(), invite_seq: seq, updated_at: this.now() };
284
+ // Stored before it's sent, so a lost answer is asked again with the same key.
285
+ await this.setAnswer(key, pending);
286
+ this.log(mode === "accept" ? "accepting_by_policy" : choice === "approve" ? "accepting_by_owner" : "declining_by_owner", workspace);
287
+ await this.send(pending);
288
+ }
289
+ await this.settleCheck(workspace);
290
+ }
291
+ /** An invite left unanswered, asked at `asked_at`, or null while it waits for the terminal. */
292
+ later(invite, seq, askedAt) {
293
+ return { workspace_id: invite.workspace_id, role_id: invite.role_id, state: "later", key: null, code: null, asked_at: askedAt, invite_seq: seq, updated_at: this.now() };
294
+ }
295
+ /**
296
+ * Puts the question to the owner without waiting for the answer. The answer is kept in memory only, and used on a later
297
+ * pass once the room is read again. A local stop, a withdrawn invite or a policy that claims by itself ends it unanswered.
298
+ */
299
+ ask(key, seq, invite, signal) {
300
+ const controller = new AbortController();
301
+ const stop = () => controller.abort();
302
+ signal.addEventListener("abort", stop, { once: true });
303
+ const asking = { key, seq, controller };
304
+ this.asking = asking;
305
+ const question = (async () => this.deps.prompter.role.call(this.deps.prompter, invite, controller.signal))();
306
+ void question
307
+ .then((choice) => choice, (error) => (error instanceof QuestionInterrupted ? null : "later"))
308
+ .then((choice) => {
309
+ signal.removeEventListener("abort", stop);
310
+ if (this.asking === asking)
311
+ this.asking = null;
312
+ // Set aside for something else on the terminal: no answer, so it's asked again on a coming pass.
313
+ if (choice !== null && !controller.signal.aborted)
314
+ this.heard.set(key, { choice, seq });
315
+ this.deps.wake?.();
316
+ });
317
+ }
318
+ /** Drops this room's settled answers whose invite isn't listed now. One under way is kept until it's sent. */
319
+ async forgetRoom(workspace, stillInvited) {
320
+ const stale = Object.entries(this.deps.poller.record.role_answers ?? {}).filter(([, a]) => a.workspace_id === workspace && !stillInvited.has(a.role_id) && a.state !== "claiming" && a.state !== "declining");
321
+ for (const [key] of stale) {
322
+ this.heard.delete(key);
323
+ // A question about an invite that's gone ends unanswered.
324
+ if (this.asking?.key === key)
325
+ this.asking.controller.abort();
326
+ await this.setAnswer(key, null);
327
+ }
328
+ }
329
+ /** Sends a claim or a decline with its stored key. A refusal is recorded and not tried again for this invite. */
330
+ async send(answer) {
331
+ const key = answerKey(answer.workspace_id, answer.role_id);
332
+ const capability = answer.state === "claiming" ? "claim_role" : "decline_role";
333
+ try {
334
+ await this.deps.poller.request(capability, { workspace_id: answer.workspace_id, role_id: answer.role_id, idempotency_key: answer.key });
335
+ }
336
+ catch (error) {
337
+ if (error instanceof GatewayError && meaningOf(error) === "refused") {
338
+ await this.setAnswer(key, { ...answer, state: "refused", key: null, code: error.code });
339
+ this.log(capability === "claim_role" ? "claim_refused" : "decline_refused", answer.workspace_id, error.code);
340
+ return;
341
+ }
342
+ throw error;
343
+ }
344
+ await this.setAnswer(key, null);
345
+ this.log(capability === "claim_role" ? "claimed" : "declined", answer.workspace_id);
346
+ }
347
+ }
@@ -82,8 +82,18 @@ export function markUntrusted(bytes) {
82
82
  */
83
83
  export const TASK_HOME_IN_FOLDER = [".cache", "home"];
84
84
  export const TASK_HOME = `${TASK_FOLDER_IN_CONTAINER}/${TASK_HOME_IN_FOLDER.join("/")}`;
85
- /** The container's whole environment: fixed, nothing inherited, nothing shaped like a secret. */
86
- export const CONTAINER_ENV = Object.freeze({ HOME: TASK_HOME, PATH: "/usr/local/bin:/usr/bin:/bin", LANG: "C.UTF-8" });
85
+ /**
86
+ * npm's cache, under the task's `HOME` and so under a folder Runner excludes from a repository room's commit. The task
87
+ * image's npmrc puts it in /tmp, a 64 MB tmpfs an install can fill; on 2026-11-21 an agent moved it to
88
+ * `/work/.npm-cache` instead, and Runner committed it. Pinned here, in code, it lands where nothing is committed.
89
+ */
90
+ export const TASK_NPM_CACHE = `${TASK_HOME}/.npm`;
91
+ /**
92
+ * The container's whole environment: fixed, nothing inherited, nothing shaped like a secret. `WRANGLER_SEND_METRICS`
93
+ * keeps wrangler from calling its metrics host (sparrow.cloudflare.com), and `npm_config_cache` pins npm's cache
94
+ * (`TASK_NPM_CACHE`); both are set here in code, never from the task.
95
+ */
96
+ export const CONTAINER_ENV = Object.freeze({ HOME: TASK_HOME, PATH: "/usr/local/bin:/usr/bin:/bin", LANG: "C.UTF-8", WRANGLER_SEND_METRICS: "false", npm_config_cache: TASK_NPM_CACHE });
87
97
  export const CONTAINER_WORKDIR = TASK_FOLDER_IN_CONTAINER;
88
98
  /** The egress proxy's name on a run's internal network, and its port (`egress-proxy.ts`). */
89
99
  export const EGRESS_ALIAS = "egress";
@@ -149,6 +149,8 @@ export function checkRuns(v) {
149
149
  (rep.scans !== undefined && !isCount(rep.scans)) ||
150
150
  (rep.start_failed !== undefined && !orNull(rep.start_failed, isCode))))
151
151
  return `${at}.report`;
152
+ if (e.unlinked !== undefined && e.unlinked !== null && typeof e.unlinked !== "boolean")
153
+ return `${at}.unlinked`;
152
154
  const blocked = e.blocked;
153
155
  if (blocked !== undefined && blocked !== null && (!isObj(blocked) || !isHash(blocked.input_hash) || !isHash(blocked.facts_hash)))
154
156
  return `${at}.blocked`;
@@ -22,6 +22,7 @@ const NAMES_VALUE = /^[a-z_?]{1,40}(,[a-z_?]{1,40}){0,9}$/;
22
22
  const PREFIX_VALUE = /^(yes|no)$/;
23
23
  /** A lower-case DNS name of two or more labels whose last starts with a letter, so never an IP address. */
24
24
  const HOST_VALUE = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
25
+ const STAGE_VALUE = /^[a-z]{1,16}$/;
25
26
  const TYPE_VALUE = /^(null|array|object|string|number|boolean|undefined|bigint|symbol|function)$/;
26
27
  const NUMBER_FIELDS = new Set(["seq", "count", "status", "length"]);
27
28
  const ID_FIELDS = new Set(["agent", "plugin_agent", "workspace", "task", "attempt_id", "run"]);
@@ -43,6 +44,8 @@ export function logLine(at, outcome, fields = {}) {
43
44
  line[name] = value;
44
45
  else if (name === "code" && typeof value === "string" && CODE_VALUE.test(value))
45
46
  line[name] = value;
47
+ else if (name === "stage" && typeof value === "string" && STAGE_VALUE.test(value))
48
+ line[name] = value;
46
49
  }
47
50
  return JSON.stringify(line);
48
51
  }
@@ -17,6 +17,8 @@ export const emptyState = () => ({
17
17
  retired: [],
18
18
  inbox_cursor: 0,
19
19
  offers: {},
20
+ role_checks: {},
21
+ role_answers: {},
20
22
  last_contact_at: null,
21
23
  reconciled_at: null,
22
24
  });
@@ -1,3 +1,4 @@
1
+ import { STORED_CAPABILITY_BITS } from "./capabilities.js";
1
2
  import { isRegistration } from "./nudge.js";
2
3
  import { thumbprintOf } from "./thumbprint.js";
3
4
  /** For tests only: secrets in memory. */
@@ -17,6 +18,80 @@ const HOST = "host";
17
18
  const NUDGE = "nudge";
18
19
  const AGENTS = "agents";
19
20
  const agentName = (id) => `agent:${id}`;
21
+ const isString = (value) => typeof value === "string";
22
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
23
+ const isJwk = (value) => isObject(value) && isString(value.kty);
24
+ const isKeypair = (value) => isObject(value) && isJwk(value.publicKey) && isJwk(value.privateKey);
25
+ /** The public half of a private JWK: the same members without `d`. */
26
+ function publicOf(privateKey) {
27
+ const { d: _d, ...rest } = privateKey;
28
+ return rest;
29
+ }
30
+ function sameJwk(a, b) {
31
+ const keys = Object.keys(a);
32
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && a[key] === b[key]);
33
+ }
34
+ function compact(connection) {
35
+ const active = [...new Set(connection.capabilityGrants.filter((grant) => grant.status === "active").map((grant) => grant.capability))];
36
+ let bits = 0n;
37
+ const named = [];
38
+ for (const capability of active) {
39
+ const bit = STORED_CAPABILITY_BITS.indexOf(capability);
40
+ if (bit >= 0)
41
+ bits |= 1n << BigInt(bit);
42
+ else
43
+ named.push(capability);
44
+ }
45
+ const { publicKey, privateKey } = connection.agentKeypair;
46
+ const derivable = isString(privateKey.d) && sameJwk(publicKey, publicOf(privateKey));
47
+ return {
48
+ v: 2,
49
+ a: connection.agentId,
50
+ h: connection.hostId,
51
+ p: connection.providerName,
52
+ i: connection.issuer,
53
+ m: connection.mode,
54
+ ...(derivable ? { k: privateKey } : { kp: connection.agentKeypair }),
55
+ g: bits.toString(16),
56
+ ...(named.length > 0 ? { n: named } : {}),
57
+ t: connection.createdAt,
58
+ };
59
+ }
60
+ function isCompact(value) {
61
+ if (!isObject(value) || value.v !== 2)
62
+ return false;
63
+ if (![value.a, value.h, value.p, value.i, value.m].every(isString))
64
+ return false;
65
+ if (typeof value.t !== "number" || !isString(value.g) || !/^[0-9a-f]{1,64}$/.test(value.g))
66
+ return false;
67
+ if (value.n !== undefined && !(Array.isArray(value.n) && value.n.every(isString)))
68
+ return false;
69
+ return value.k !== undefined ? isJwk(value.k) && isString(value.k.d) && value.kp === undefined : isKeypair(value.kp);
70
+ }
71
+ /** A record in the slim form Runner stored before issue 527: an `AgentConnection` with only active grant names. */
72
+ function isSlim(value) {
73
+ if (!isObject(value) || value.v !== undefined)
74
+ return false;
75
+ if (![value.agentId, value.hostId, value.providerName, value.issuer, value.mode].every(isString))
76
+ return false;
77
+ return typeof value.createdAt === "number" && isKeypair(value.agentKeypair) && Array.isArray(value.capabilityGrants) && value.capabilityGrants.every((grant) => isObject(grant) && isString(grant.capability) && isString(grant.status));
78
+ }
79
+ function expand(record) {
80
+ const bits = BigInt(`0x${record.g}`);
81
+ // A bit past the table's end came from a later Runner's table: a capability this one doesn't know, so not one it uses.
82
+ const fromBits = STORED_CAPABILITY_BITS.filter((_, bit) => (bits >> BigInt(bit)) & 1n);
83
+ const agentKeypair = record.k !== undefined ? { publicKey: publicOf(record.k), privateKey: record.k } : record.kp;
84
+ return {
85
+ agentId: record.a,
86
+ hostId: record.h,
87
+ providerName: record.p,
88
+ issuer: record.i,
89
+ mode: record.m,
90
+ agentKeypair,
91
+ capabilityGrants: [...fromBits, ...(record.n ?? [])].map((capability) => ({ capability, status: "active" })),
92
+ createdAt: record.t,
93
+ };
94
+ }
20
95
  export class RunnerStorage {
21
96
  secrets;
22
97
  providers = new Map();
@@ -52,30 +127,33 @@ export class RunnerStorage {
52
127
  async deleteHostIdentity() {
53
128
  await this.secrets.delete(HOST);
54
129
  }
130
+ /**
131
+ * The agent's connection. A record in the compact form (`v: 2`, issue 527) is expanded; one in the slim form Runner
132
+ * stored before it (H1 on #454) is read as it is, and is rewritten compactly at the next write. Anything else reads as
133
+ * an error, never as no connection.
134
+ */
55
135
  async getAgentConnection(agentId) {
56
- return this.read(agentName(agentId));
136
+ const value = await this.read(agentName(agentId));
137
+ if (value === null)
138
+ return null;
139
+ const connection = isCompact(value) ? expand(value) : isSlim(value) ? value : null;
140
+ if (!connection)
141
+ throw new Error("Runner's key store holds something it can't read. Run `forget`, then pair again.");
142
+ return connection;
57
143
  }
58
144
  /**
59
- * Stores the agent's connection, slimmed to what Runner uses (H1 on #454): its IDs, issuer, mode, keypair and the names
60
- * of its active grants. The plugin's answer also carries each grant's description and schemas, about 14 KB in all,
61
- * which is more than macOS's keychain tool takes on one line; Runner reads those from the gateway when it needs them.
145
+ * Stores the agent's connection in the compact form (issue 527): its IDs, issuer, mode, private key and the names of
146
+ * its active grants as a bitset over `STORED_CAPABILITY_BITS`, with any name not in that table listed by name. The
147
+ * plugin's answer also carries each grant's description and schemas, about 14 KB in all, which is more than macOS's
148
+ * keychain tool takes on one line (H1 on #454); Runner reads those from the gateway when it needs them. The public key
149
+ * is the private key without `d`, so only the private key is kept; a keypair that isn't shaped so is kept whole.
62
150
  * The agent is named in the index first, so a write that fails part way is still found and deleted by `deleteAll`.
63
151
  */
64
152
  async setAgentConnection(agentId, connection) {
65
153
  const ids = (await this.read(AGENTS)) ?? [];
66
154
  if (!ids.includes(agentId))
67
155
  await this.secrets.set(AGENTS, JSON.stringify([...ids, agentId]));
68
- const slim = {
69
- agentId: connection.agentId,
70
- hostId: connection.hostId,
71
- providerName: connection.providerName,
72
- issuer: connection.issuer,
73
- mode: connection.mode,
74
- agentKeypair: connection.agentKeypair,
75
- capabilityGrants: connection.capabilityGrants.filter((grant) => grant.status === "active").map((grant) => ({ capability: grant.capability, status: "active" })),
76
- createdAt: connection.createdAt,
77
- };
78
- await this.secrets.set(agentName(agentId), JSON.stringify(slim));
156
+ await this.secrets.set(agentName(agentId), JSON.stringify(compact(connection)));
79
157
  }
80
158
  async deleteAgentConnection(agentId) {
81
159
  await this.secrets.delete(agentName(agentId));
@@ -66,8 +66,14 @@ export function diagnosticLine(failure, now) {
66
66
  if (typeof error.detail.errno === "string")
67
67
  line.errno = scrub(error.detail.errno, 64);
68
68
  }
69
- if (error instanceof RepoPathError)
69
+ if (error instanceof RepoPathError) {
70
70
  line.transient = error.transient ? 1 : 0;
71
+ // Where on the repository path, and Git's exit code (#520): fixed words and a number, never Git's own output.
72
+ if (error.detail.stage !== undefined && /^[a-z]{1,16}$/.test(error.detail.stage))
73
+ line.stage = error.detail.stage;
74
+ if (typeof error.detail.exit_code === "number" && Number.isSafeInteger(error.detail.exit_code))
75
+ line.exit_code = error.detail.exit_code;
76
+ }
71
77
  }
72
78
  else if (error !== undefined) {
73
79
  line.message = scrub(String(error));
@@ -170,6 +176,7 @@ export class FileDiagnostics {
170
176
  const TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
171
177
  const AT = /^[a-z][a-z0-9_.]{0,63}$/;
172
178
  const FAILURE_CODE = /^[a-z][a-z0-9_]{0,63}$/;
179
+ const STAGE = /^[a-z]{1,16}$/;
173
180
  /** A field read back from the file, shown only when it has its fixed shape. */
174
181
  const shaped = (v, re) => (typeof v === "string" && re.test(v) ? v : "invalid");
175
182
  /**
@@ -183,7 +190,7 @@ export function whyLines(task, entry, file) {
183
190
  const code = shaped(entry.code, FAILURE_CODE);
184
191
  const e = explain(code);
185
192
  return [
186
- `${shaped(entry.time, TIME)} at ${shaped(entry.at, AT)}: ${e.what} ${e.todo} (code ${code})`,
193
+ `${shaped(entry.time, TIME)} at ${shaped(entry.at, AT)}${typeof entry.stage === "string" && STAGE.test(entry.stage) ? ` (stage ${entry.stage})` : ""}: ${e.what} ${e.todo} (code ${code})`,
187
194
  `From ${file}, local to this machine and redacted:`,
188
195
  markHidden(JSON.stringify(entry, null, 2)),
189
196
  ];
package/build/node/git.js CHANGED
@@ -95,7 +95,7 @@ export function gitCli(program, home, from = process.env) {
95
95
  throw new RepoPathError("git_unavailable");
96
96
  }
97
97
  return (args, opts) => new Promise((resolve, reject) => {
98
- const child = spawn(resolved, args, { cwd: home, env, stdio: ["ignore", "pipe", "pipe", opts.secret === undefined ? "ignore" : "pipe"], signal: opts.signal, timeout: opts.timeout_ms ?? GIT_TIMEOUT_MS, killSignal: "SIGKILL" });
98
+ const child = spawn(resolved, args, { cwd: home, env, stdio: [opts.input === undefined ? "ignore" : "pipe", "pipe", "pipe", opts.secret === undefined ? "ignore" : "pipe"], signal: opts.signal, timeout: opts.timeout_ms ?? GIT_TIMEOUT_MS, killSignal: "SIGKILL" });
99
99
  const out = [];
100
100
  const err = [];
101
101
  let size = 0;
@@ -117,6 +117,11 @@ export function gitCli(program, home, from = process.env) {
117
117
  pipe.on("error", () => undefined);
118
118
  pipe.end(`${opts.secret}\n`);
119
119
  }
120
+ if (opts.input !== undefined && child.stdin) {
121
+ // Only Runner's own fixed-shape input (object IDs); a command that ends early leaves the rest unread.
122
+ child.stdin.on("error", () => undefined);
123
+ child.stdin.end(opts.input);
124
+ }
120
125
  child.on("error", () => reject(new RepoPathError("git_unavailable", true)));
121
126
  child.on("close", (code, signal) => {
122
127
  if (cut)
@@ -33,7 +33,7 @@ export const KEY_STORE_LINES = Object.freeze({
33
33
  });
34
34
  export const SECRET_TOOL = "/usr/bin/secret-tool";
35
35
  const MARKER = "key-store";
36
- /** The most one item may hold. Runner's largest, an agent connection, is about 2 KB. **Proposed** figure. */
36
+ /** The most one item may hold. Runner's largest, the nudge registration, is under 2 KB. **Proposed** figure. */
37
37
  export const MAX_ITEM_BYTES = 256 * 1024;
38
38
  const ownUid = () => (typeof process.getuid === "function" ? process.getuid() : -1);
39
39
  export class FileSecretStore {