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,1207 @@
1
+ import { GatewayError, meaningOf } from "./errors.js";
2
+ import { consumeRunDecision, evaluate, factsKey, issueRunDecision, outputsOf, parsePolicyConfig, pinRunBase, repositoryOf } from "./policy.js";
3
+ import { pullRequestUrl, RepoPathError } from "./repository.js";
4
+ import { readTaskDetail, sha256Hex } from "./prompt.js";
5
+ import { cleanResult, composeNote } from "./results.js";
6
+ import { parseRunResult } from "./tool-policy.js";
7
+ import { AuthorityEnded, waitForNext } from "./poller.js";
8
+ import { MAX_PROMPT_BYTES } from "./run-interface.js";
9
+ import { budgetOf, clockWentBack, dayOf, newEntry, owedSubmission, reserve, settle } from "./runs.js";
10
+ /** The check-in's fixed maximum interval during a run (S-33, S-43). **Proposed** figure. */
11
+ export const CHECK_IN_MS = 60_000;
12
+ export const MIN_CHECK_IN_MS = 5_000;
13
+ /** Tries of one command within a tick before it waits for the next, always with the same key. */
14
+ const COMMAND_TRIES = 4;
15
+ const FIRST_BACKOFF_MS = 2_000;
16
+ /** Evaluations of one task in one UTC day, past which it waits for the next (S-09: re-offers are rate-limited). */
17
+ export const MAX_ATTEMPTS_PER_DAY = 20;
18
+ /** How long an ask the owner put off waits before it's asked again. */
19
+ export const ASK_AGAIN_MS = 10 * 60 * 1000;
20
+ /** How long a task waits on a local condition before it's evaluated again; also the wait between publication tries. */
21
+ export const WAIT_MS = 60_000;
22
+ /**
23
+ * How long a finished run's publication is retried after its first passing failure before the task is released as
24
+ * `repo_publish_failed` (the ruling on #462's held publications). **Proposed** figure.
25
+ */
26
+ export const PUBLISH_RETRY_MS = 60 * 60 * 1000;
27
+ /** A finished run whose stop is confirmed and whose publication is held for a retry: it runs nothing. */
28
+ const publicationHeld = (e) => e.phase === "held" && e.after_stop?.kind === "finish" && typeof e.publish_since === "number";
29
+ /**
30
+ * The one progress message Podster gets while a result waits for the owner's review: Runner's fixed status, with no word
31
+ * of the agent's (RUNNER.md: "fixed status generated by Runner, with no model text").
32
+ */
33
+ export const HELD_STATUS = "Podster Runner finished its run for this task. The result waits for review by the owner of the machine it ran on before any of it is shared.";
34
+ /**
35
+ * How long a result's words wait for the owner's review before the result is submitted without them, with Runner's fixed
36
+ * note only: the ruling on #465's review, for a held review with no terminal to answer it. **Proposed** figure.
37
+ */
38
+ export const REVIEW_HOLD_MS = 24 * 60 * 60 * 1000;
39
+ /** Refusals of a submission that are safe to send again as they were. */
40
+ const SUBMIT_AGAIN = new Set(["pull_request_unread"]);
41
+ /** Refusals about Runner's own state, not the task: they leave the task waiting rather than give it up. */
42
+ const LOCAL = new Set(["authority_stale", "config_invalid", "budget_invalid", "clock_invalid"]);
43
+ /**
44
+ * Refusals that come from the owner's own budget or configuration. Podster is told only `runner_unavailable`, so a
45
+ * decline doesn't disclose the owner's caps or allowlists; the reason itself stays in Runner's record and log (Info on
46
+ * #458's review).
47
+ */
48
+ const PRIVATE = new Set([
49
+ "day_budget_exhausted",
50
+ "room_not_configured",
51
+ "requester_out_of_scope",
52
+ "author_out_of_scope",
53
+ // The owner's repository scope and Runner's own setup (M7 step 10): Podster hears only that Runner can't do it.
54
+ "repository_unavailable",
55
+ "repo_repository_out_of_scope",
56
+ "repo_clone_url_unexpected",
57
+ "repo_repository_id_mismatch",
58
+ "repo_repository_renamed",
59
+ "repo_path_unsafe",
60
+ "repo_helper_unavailable",
61
+ ]);
62
+ export const GENERIC_REASON = "runner_unavailable";
63
+ /** Events that count as a new attempt at a task: an offer or re-offer, and a change request (L6 on #458). */
64
+ const TRIGGERS = new Set(["task.offered", "task.changes_requested", "offered"]);
65
+ /**
66
+ * Events read afresh without counting as an attempt, so no task is left unconsidered (L6 liveness, re-review of #458):
67
+ * reconciliation finding a task accepted by this agent, and an edit to a task that's still offered.
68
+ */
69
+ const RECHECKS = new Set(["accepted", "task.updated"]);
70
+ /** One at a time: each call waits for the one before it. */
71
+ class Gate {
72
+ tail = Promise.resolve();
73
+ run(fn) {
74
+ const result = this.tail.then(fn);
75
+ this.tail = result.then(() => undefined, () => undefined);
76
+ return result;
77
+ }
78
+ }
79
+ const keyOf = (workspace, task) => `${workspace}/${task}`;
80
+ /** What marks an offer as new: its latest event, sequence, status and version, never the time it was last listed. */
81
+ export const markerOf = (offer) => `${offer.last}|${offer.seq ?? "-"}|${offer.version ?? "-"}`;
82
+ const ACTIVE = new Set(["accepting", "ready", "running", "giving_up", "held"]);
83
+ /** Resolves with `promise`, or with `aborted` at once when the signal fires, whichever is first. */
84
+ function orAbort(promise, signal) {
85
+ if (signal.aborted) {
86
+ promise.catch(() => undefined);
87
+ return Promise.resolve(ABORTED);
88
+ }
89
+ return new Promise((resolve, reject) => {
90
+ const onAbort = () => {
91
+ promise.catch(() => undefined);
92
+ resolve(ABORTED);
93
+ };
94
+ signal.addEventListener("abort", onAbort, { once: true });
95
+ promise.then((value) => {
96
+ signal.removeEventListener("abort", onAbort);
97
+ resolve(value);
98
+ }, (error) => {
99
+ signal.removeEventListener("abort", onAbort);
100
+ reject(error);
101
+ });
102
+ });
103
+ }
104
+ const ABORTED = Symbol("aborted");
105
+ export class Lifecycle {
106
+ deps;
107
+ policy;
108
+ gate = new Gate();
109
+ newId;
110
+ checkInMs;
111
+ state;
112
+ /** What the owner approved on an ask, by task, until it's issued: it holds only while a fresh read still matches. */
113
+ approvals = new Map();
114
+ /** Each finished run's structured result, by task, until it's submitted: in memory only, never stored or logged. */
115
+ results = new Map();
116
+ /** The agent's own organization, checked at open: a policy reread later must still name it. */
117
+ ownerOrg = "";
118
+ constructor(deps, state) {
119
+ this.deps = deps;
120
+ this.state = state;
121
+ this.policy = { evaluate, issueRunDecision, consumeRunDecision, pinRunBase, ...deps.policy };
122
+ this.newId = deps.newId ?? (() => crypto.randomUUID());
123
+ this.checkInMs = Math.min(Math.max(Math.round(deps.checkInMs ?? CHECK_IN_MS), MIN_CHECK_IN_MS), CHECK_IN_MS);
124
+ }
125
+ /**
126
+ * The lifecycle for a connected Runner. Refuses a run policy it can't read, or one whose `owner_org` isn't the agent's
127
+ * own organization, which would make every author of that organization read as the owner's. A run that was going when
128
+ * Runner last stopped is held until the adapter confirms it stopped, then released: a run is never resumed.
129
+ */
130
+ static async open(deps) {
131
+ const parsed = parsePolicyConfig(await readConfig(deps.config), homeOf(deps));
132
+ if (!parsed.ok)
133
+ throw new Error(`Runner's run policy can't be used: ${parsed.at} is missing or out of range. Nothing was started.`);
134
+ const identity = (await deps.poller.request("get_identity"));
135
+ if (identity?.id !== deps.poller.agentId)
136
+ throw new AuthorityEnded();
137
+ if (identity?.org_id !== parsed.value.owner_org)
138
+ throw new Error("The run policy's owner_org isn't this agent's organization. Nothing was started.");
139
+ const lifecycle = new Lifecycle(deps, await deps.runs.load());
140
+ lifecycle.ownerOrg = parsed.value.owner_org;
141
+ await lifecycle.recover();
142
+ return lifecycle;
143
+ }
144
+ /** A copy of the record as it stands. */
145
+ get record() {
146
+ return structuredClone(this.state);
147
+ }
148
+ now() {
149
+ return this.deps.clock.now();
150
+ }
151
+ async save(next) {
152
+ await this.deps.runs.save(next);
153
+ this.state = next;
154
+ }
155
+ /** Saves the record with this entry, and the ledger, as given. */
156
+ async put(entry, ledger = this.state.ledger, nextReservation = this.state.next_reservation) {
157
+ const key = keyOf(entry.workspace_id, entry.task_id);
158
+ await this.save({ ...this.state, ledger, next_reservation: nextReservation, entries: { ...this.state.entries, [key]: { ...entry, updated_at: this.now() } } });
159
+ }
160
+ log(at, outcome, entry, extra = {}) {
161
+ this.deps.log(at, outcome, { agent: this.deps.poller.agentId, workspace: entry.workspace_id, task: entry.task_id, ...extra });
162
+ }
163
+ /**
164
+ * Ends every attempt that has no process: its reservation settles at zero, and nothing more is sent for it. A run that
165
+ * may still be going stays held.
166
+ */
167
+ async abandon(outcome) {
168
+ let ledger = this.state.ledger;
169
+ const entries = { ...this.state.entries };
170
+ for (const [key, entry] of Object.entries(entries)) {
171
+ if (entry.phase !== "accepting" && entry.phase !== "ready" && entry.phase !== "giving_up" && entry.phase !== "waiting")
172
+ continue;
173
+ ledger = settle(ledger, entry.reservation, 0, this.now());
174
+ entries[key] = { ...entry, phase: "done", outcome, decision: null, reservation: null, accept_key: null, give_up: null, expected_version: null, retry_at: null, updated_at: this.now() };
175
+ }
176
+ await this.save({ ...this.state, ledger, entries });
177
+ }
178
+ async recover() {
179
+ const agent = this.deps.poller.agentId;
180
+ if (this.state.agent_id !== agent) {
181
+ // A record left by an earlier pairing on this home: its tasks aren't this agent's. Spend so far still counts.
182
+ if (this.state.agent_id !== null)
183
+ await this.abandon("other_agent");
184
+ await this.save({ ...this.state, agent_id: agent });
185
+ }
186
+ for (const entry of Object.values(this.state.entries)) {
187
+ if (entry.phase !== "running")
188
+ continue;
189
+ // Runner stopped mid-run: whatever the run spent is unknown, so the whole reservation counts.
190
+ const ledger = settle(this.state.ledger, entry.reservation, null, this.now());
191
+ await this.put({ ...entry, phase: "held", outcome: "runner_restarted", reservation: null, after_stop: { kind: "release", reason: "runner_restarted" } }, ledger);
192
+ this.log("lifecycle.run", "held", entry, { code: "runner_restarted" });
193
+ }
194
+ }
195
+ /**
196
+ * One pass: held runs, owed commands, a ready run, then new events, one task at a time. A run started here is supervised
197
+ * to its end before this returns. `signal` is the local stop.
198
+ */
199
+ async tick(signal) {
200
+ if (signal.aborted)
201
+ return "stopped";
202
+ // One pass at a time: a second call while one runs does nothing.
203
+ if (this.busy)
204
+ return "idle";
205
+ this.busy = true;
206
+ this.tickSignal = signal;
207
+ try {
208
+ return await this.work(signal);
209
+ }
210
+ catch (error) {
211
+ if (error instanceof AuthorityEnded) {
212
+ await this.abandon("revoked");
213
+ await this.deps.poller.endAuthority();
214
+ return "revoked";
215
+ }
216
+ if (signal.aborted)
217
+ return "stopped";
218
+ const failure = error instanceof GatewayError ? error : new GatewayError(0, "unknown");
219
+ this.deps.log("lifecycle.tick", "unreachable", { agent: this.deps.poller.agentId, status: failure.status, code: failure.code });
220
+ return "idle";
221
+ }
222
+ finally {
223
+ this.busy = false;
224
+ }
225
+ }
226
+ busy = false;
227
+ /** The local stop of the pass under way, so a publication after a confirmed stop never runs past it. */
228
+ tickSignal;
229
+ entries(phase) {
230
+ return Object.values(this.state.entries).filter((e) => e.phase === phase);
231
+ }
232
+ async work(signal) {
233
+ // No run is supervised between passes, so any entry still recorded as running is an orphan: held (M2 on #458).
234
+ for (const entry of this.entries("running"))
235
+ await this.holdOrphan(entry, "run_interrupted");
236
+ for (const entry of this.entries("held")) {
237
+ if (publicationHeld(entry)) {
238
+ // Its stop was confirmed before the publication was first tried: tried again once its wait is over.
239
+ if (signal.aborted)
240
+ return "stopped";
241
+ if (entry.retry_at === null || this.now() >= entry.retry_at)
242
+ await this.afterStop(entry, { kind: "finish" });
243
+ continue;
244
+ }
245
+ const stopped = entry.run_ref !== null && (await this.deps.adapter.confirmStopped(entry.run_ref).catch(() => false));
246
+ if (!stopped)
247
+ continue;
248
+ this.log("lifecycle.run", "confirmed_stopped", entry);
249
+ await this.afterStop(entry, entry.after_stop ?? { kind: "none" });
250
+ }
251
+ const unconfirmed = this.entries("held").filter((e) => !publicationHeld(e));
252
+ if (unconfirmed.length > 0) {
253
+ // A run that may still be going: nothing is released and nothing new starts until it's confirmed stopped.
254
+ this.deps.log("lifecycle.held", "waiting_for_owner", { agent: this.deps.poller.agentId, count: unconfirmed.length });
255
+ return "idle";
256
+ }
257
+ for (const entry of this.entries("finished")) {
258
+ // Step 11: an owed submission, once any wait for the owner's review is over.
259
+ if (signal.aborted)
260
+ return "stopped";
261
+ if (entry.submission?.state === "owed" && (entry.retry_at === null || this.now() >= entry.retry_at))
262
+ await this.submit(entry, signal);
263
+ }
264
+ for (const entry of this.entries("giving_up")) {
265
+ if (signal.aborted)
266
+ return "stopped";
267
+ await this.sendGiveUp(entry, signal);
268
+ }
269
+ for (const entry of this.entries("accepting")) {
270
+ if (signal.aborted)
271
+ return "stopped";
272
+ await this.accept(entry, signal);
273
+ }
274
+ // The owner's limit on tasks held at once counts every held publication, and the run that would start now.
275
+ const waiting = Object.values(this.state.entries).filter(publicationHeld).length;
276
+ if (waiting > 0 && waiting + 1 > (await this.maxActive())) {
277
+ this.deps.log("lifecycle.held", "publication_waiting", { agent: this.deps.poller.agentId, count: waiting });
278
+ return "idle";
279
+ }
280
+ for (const entry of this.entries("ready")) {
281
+ if (signal.aborted)
282
+ return "stopped";
283
+ return this.start(entry, signal);
284
+ }
285
+ const offers = Object.values(this.deps.poller.record.offers).sort((a, b) => a.updated_at - b.updated_at);
286
+ for (const offer of offers) {
287
+ if (signal.aborted)
288
+ return "stopped";
289
+ const key = keyOf(offer.workspace_id, offer.task_id);
290
+ const entry = this.state.entries[key];
291
+ if (entry && ACTIVE.has(entry.phase))
292
+ continue;
293
+ const marker = markerOf(offer);
294
+ // Only an offer, a re-offer or a change request is a new attempt; a retry after a refused consume or give-up
295
+ // (marker cleared) and a wait that's over aren't, and any other event only moves the marker (L6 on #458).
296
+ const waitOver = !!entry && entry.phase === "waiting" && entry.retry_at !== null && this.now() >= entry.retry_at;
297
+ let counted = false;
298
+ let onlyIfOffered = false;
299
+ if (!entry)
300
+ counted = true;
301
+ else if (entry.marker === "")
302
+ counted = false;
303
+ else if (entry.marker !== marker && TRIGGERS.has(offer.last))
304
+ counted = true;
305
+ else if (entry.marker !== marker && RECHECKS.has(offer.last))
306
+ onlyIfOffered = offer.last === "task.updated";
307
+ else {
308
+ if (entry.marker !== marker)
309
+ await this.put({ ...entry, marker });
310
+ if (!waitOver)
311
+ continue;
312
+ }
313
+ await this.consider(offer, marker, counted, signal, false, onlyIfOffered);
314
+ if (signal.aborted)
315
+ return "stopped";
316
+ const now = this.state.entries[key];
317
+ if (now?.phase === "giving_up")
318
+ await this.sendGiveUp(now, signal);
319
+ const after = this.state.entries[key];
320
+ if (after?.phase === "accepting")
321
+ await this.accept(after, signal);
322
+ if (signal.aborted)
323
+ return "stopped";
324
+ const ready = this.state.entries[key];
325
+ if (ready?.phase === "ready")
326
+ return this.start(ready, signal);
327
+ }
328
+ return "idle";
329
+ }
330
+ /** The owner's `max_active_tasks`, read afresh; one when the policy can't be read. */
331
+ async maxActive() {
332
+ const parsed = parsePolicyConfig(await readConfig(this.deps.config), homeOf(this.deps));
333
+ return parsed.ok ? parsed.value.max_active_tasks : 1;
334
+ }
335
+ /** A fresh `get_task`. Null when the gateway refuses the read (the task isn't this agent's to read) or it's malformed. */
336
+ async read(workspace, task) {
337
+ let answer;
338
+ try {
339
+ answer = await this.deps.poller.request("get_task", { workspace_id: workspace, task_id: task });
340
+ }
341
+ catch (error) {
342
+ if (error instanceof GatewayError && meaningOf(error) === "refused")
343
+ return null;
344
+ throw error;
345
+ }
346
+ const detail = await readTaskDetail(answer);
347
+ // An answer about another task is never read as this one (step 12's harness).
348
+ return detail && detail.task.id === task ? detail : null;
349
+ }
350
+ budget(ownReservation) {
351
+ const budget = budgetOf(this.state.ledger, this.now());
352
+ return ownReservation === undefined ? budget : { ...budget, own_reservation_micro_usd: ownReservation };
353
+ }
354
+ async evaluateFresh(detail, entry, authorityFresh, ownReservation) {
355
+ const ids = { task_id: entry.task_id, workspace_id: entry.workspace_id };
356
+ // A clock gone back before the ledger's day can't be trusted with the day's budget (L4 on #458).
357
+ if (clockWentBack(this.state.ledger, this.now()))
358
+ return { outcome: "refuse", reason: "clock_invalid", ...ids };
359
+ const config = await readConfig(this.deps.config);
360
+ const parsed = parsePolicyConfig(config, homeOf(this.deps));
361
+ if (parsed.ok && parsed.value.owner_org !== this.ownerOrg)
362
+ return { outcome: "refuse", reason: "config_invalid", ...ids };
363
+ return this.policy.evaluate({
364
+ config,
365
+ provenance: detail.provenance,
366
+ prompt: detail.prompt?.shape ?? null,
367
+ task: { id: entry.task_id, workspace_id: entry.workspace_id },
368
+ authority_fresh: authorityFresh,
369
+ budget: this.budget(ownReservation),
370
+ ...homeOf(this.deps),
371
+ now: this.now(),
372
+ });
373
+ }
374
+ /** A new event for a task, or a wait that's over: a fresh read and a fresh evaluation. */
375
+ async consider(offer, marker, counted, signal, approvedRound = false, onlyIfOffered = false) {
376
+ const key = keyOf(offer.workspace_id, offer.task_id);
377
+ const today = dayOf(this.now());
378
+ const known = this.state.entries[key] ?? newEntry(offer.workspace_id, offer.task_id, this.now());
379
+ const attempts = known.attempts.day === today ? known.attempts : { day: today, count: 0 };
380
+ if (counted && attempts.count >= MAX_ATTEMPTS_PER_DAY) {
381
+ await this.put({ ...known, marker, phase: "waiting", outcome: "attempts_exhausted", retry_at: (today + 1) * 24 * 60 * 60 * 1000 });
382
+ this.log("lifecycle.decision", "waiting", known, { code: "attempts_exhausted" });
383
+ return;
384
+ }
385
+ const entry = { ...known, marker, attempts: { day: today, count: attempts.count + (counted ? 1 : 0) }, retry_at: null, decision: null, consumed: null, reservation: null, accept_key: null, expected_version: null, run_ref: null, give_up: null, after_stop: null, submission: null };
386
+ const detail = await this.read(offer.workspace_id, offer.task_id);
387
+ const task = detail?.task;
388
+ if (!detail || !task || task.assignee !== this.deps.poller.agentId || (task.status !== "offered" && task.status !== "accepted")) {
389
+ this.results.delete(key);
390
+ await this.put({ ...entry, phase: "done", outcome: task ? `task_${task.status}` : "not_readable" });
391
+ return;
392
+ }
393
+ if (onlyIfOffered && task.status !== "offered") {
394
+ // An edit to a task that isn't an offer any more: nothing to evaluate. A running run's check-in sees edits itself.
395
+ await this.put({ ...known, marker, attempts: entry.attempts });
396
+ return;
397
+ }
398
+ if (task.status === "accepted" && detail.prompt && entry.ran_hash === detail.prompt.hash) {
399
+ // A run with these exact inputs finished already; nothing new to run.
400
+ // A finished run's record is kept whole for step 11.
401
+ if (known.phase === "finished")
402
+ await this.put({ ...known, marker, attempts: entry.attempts });
403
+ else
404
+ await this.put({ ...entry, phase: "done", outcome: "already_ran" });
405
+ return;
406
+ }
407
+ const asked = await this.gate.run(() => this.decide(entry, detail));
408
+ if (!asked)
409
+ return;
410
+ // Stored before the owner is asked, so this attempt counts once whatever the answer (L6 on #458).
411
+ const asking = { ...entry, phase: "waiting", outcome: "asking", retry_at: this.now() + ASK_AGAIN_MS };
412
+ await this.put(asking);
413
+ const answer = await this.deps.prompter.ask(asked.view, signal);
414
+ if (signal.aborted)
415
+ return;
416
+ this.log("lifecycle.ask", answer, entry, { code: asked.decision.reason });
417
+ if (answer === "approve" && detail.prompt && !approvedRound) {
418
+ const facts = factsKey(asked.decision);
419
+ if (facts)
420
+ this.approvals.set(key, { hash: detail.prompt.hash, version: task.version, facts });
421
+ // Issued only on a fresh read and evaluation that still match what the owner saw.
422
+ await this.consider(offer, marker, false, signal, true);
423
+ return;
424
+ }
425
+ if (answer === "decline") {
426
+ await this.gate.run(() => this.giveUp(entry, task.status, "owner_declined", task.version));
427
+ return;
428
+ }
429
+ await this.put({ ...entry, phase: "waiting", outcome: answer === "approve" ? "approval_stale" : "owner_later", retry_at: this.now() + ASK_AGAIN_MS });
430
+ }
431
+ /**
432
+ * Evaluate, then issue, as one step behind the gate. Answers what to ask the owner when the policy asks and no matching
433
+ * approval is held; otherwise it has stored what follows: an issued decision, a decline or release owed, or a wait.
434
+ */
435
+ async decide(entry, detail) {
436
+ const key = keyOf(entry.workspace_id, entry.task_id);
437
+ const task = detail.task;
438
+ const current = this.state.entries[key];
439
+ // Never a second decision for a task that already has one in hand.
440
+ if (current && ACTIVE.has(current.phase))
441
+ return null;
442
+ if (!detail.prompt) {
443
+ // An input provenance lists isn't in the answer: no prompt can be built from exactly those inputs.
444
+ this.log("lifecycle.decision", "refuse", entry, { code: "prompt_unavailable" });
445
+ await this.giveUp(entry, task.status, "prompt_unavailable", task.version);
446
+ return null;
447
+ }
448
+ if (detail.prompt.bytes.byteLength > MAX_PROMPT_BYTES) {
449
+ // Words past the most a driver is handed could never start: declined before anything is reserved or accepted
450
+ // (step 12's harness: they were accepted, then failed at the start and were released).
451
+ this.log("lifecycle.decision", "refuse", entry, { code: "prompt_too_large" });
452
+ await this.giveUp(entry, task.status, "prompt_too_large", task.version);
453
+ return null;
454
+ }
455
+ // Never `own_reservation_micro_usd` here: no reservation of this decision's exists before it's issued.
456
+ const decision = await this.evaluateFresh(detail, entry, this.deps.poller.authorityFresh());
457
+ this.log("lifecycle.decision", decision.outcome, entry, { code: decision.reason });
458
+ if (decision.outcome === "refuse") {
459
+ if (LOCAL.has(decision.reason))
460
+ await this.put({ ...entry, phase: "waiting", outcome: decision.reason, retry_at: this.now() + WAIT_MS });
461
+ else
462
+ await this.giveUp(entry, task.status, decision.reason, task.version);
463
+ return null;
464
+ }
465
+ let approved = false;
466
+ if (decision.outcome === "ask") {
467
+ const held = this.approvals.get(key);
468
+ approved = !!held && held.hash === detail.prompt.hash && held.version === task.version && held.facts === factsKey(decision);
469
+ this.approvals.delete(key);
470
+ if (!approved)
471
+ return { view: askView(entry, decision, detail), decision };
472
+ }
473
+ // The owner's repository for the room, if any; its base is pinned after the accept, against a fresh checkout.
474
+ const repository = decision.facts.repository;
475
+ const binding = { task_id: entry.task_id, workspace_id: entry.workspace_id, task_version: task.version, input_hash: detail.prompt.hash, repository_id: repository === null ? null : String(repository.provider_repo_id), base_commit: null };
476
+ const issued = this.policy.issueRunDecision(decision, binding, this.now(), approved ? { approved_by_owner: true } : {});
477
+ if (!issued.ok) {
478
+ await this.put({ ...entry, phase: "waiting", outcome: `issue_${issued.reason}`, retry_at: this.now() + WAIT_MS });
479
+ this.log("lifecycle.issue", "refused", entry, { code: issued.reason });
480
+ return null;
481
+ }
482
+ const reservation = `r${this.state.next_reservation}`;
483
+ const ledger = reserve(this.state.ledger, reservation, issued.record.reserved_micro_usd, this.now());
484
+ const offered = task.status === "offered";
485
+ // Stored as returned, with its reservation and, for an offer, the accept's key, before anything is sent.
486
+ await this.put({ ...entry, phase: offered ? "accepting" : "ready", outcome: decision.reason, decision: issued.record, reservation, accept_key: offered ? this.newId() : null, expected_version: offered ? null : task.version }, ledger, this.state.next_reservation + 1);
487
+ this.log("lifecycle.issue", issued.record.mode, entry);
488
+ return null;
489
+ }
490
+ /** Records that a decline (an offer) or a release (an accepted task) is owed, with its key. Sent by `sendGiveUp`. */
491
+ async giveUp(entry, status, reason, version = null) {
492
+ if (status !== "offered" && status !== "accepted") {
493
+ await this.put({ ...entry, phase: "done", outcome: reason });
494
+ return;
495
+ }
496
+ const capability = status === "offered" ? "decline_task" : "release_task";
497
+ // What Podster is told; the record keeps the reason itself.
498
+ const told = PRIVATE.has(reason) ? GENERIC_REASON : reason;
499
+ await this.put({ ...entry, phase: "giving_up", outcome: reason, give_up: { capability, reason: told, version, key: this.newId() } });
500
+ }
501
+ async backoff(attempt, signal, failure) {
502
+ const wait = Math.max(FIRST_BACKOFF_MS * 2 ** attempt, (failure.retryAfter ?? 0) * 1000);
503
+ await this.deps.clock.idle(Math.min(wait, 60_000), signal);
504
+ }
505
+ /** Sends an owed decline or release, retried with its stored key. */
506
+ async sendGiveUp(entry, signal) {
507
+ // After a local stop nothing calls Podster (L1 on #458).
508
+ if (signal.aborted)
509
+ return;
510
+ let give = entry.give_up;
511
+ if (give.version === null) {
512
+ // A release after a stop: the task's version as it stands, read before the key is first used.
513
+ const detail = await this.read(entry.workspace_id, entry.task_id);
514
+ const task = detail?.task;
515
+ if (!task || task.assignee !== this.deps.poller.agentId || task.status !== (give.capability === "decline_task" ? "offered" : "accepted")) {
516
+ await this.put({ ...entry, phase: "done", give_up: null, outcome: task ? `task_${task.status}` : "not_readable" });
517
+ return;
518
+ }
519
+ give = { ...give, version: task.version };
520
+ entry = { ...entry, give_up: give };
521
+ await this.put(entry);
522
+ }
523
+ for (let attempt = 0; attempt < COMMAND_TRIES; attempt++) {
524
+ try {
525
+ await this.deps.poller.request(give.capability, { workspace_id: entry.workspace_id, task_id: entry.task_id, version: give.version, reason: give.reason, idempotency_key: give.key });
526
+ await this.put({ ...entry, phase: "done", give_up: null });
527
+ this.log("lifecycle.give_up", give.capability === "decline_task" ? "declined" : "released", entry, { code: give.reason });
528
+ return;
529
+ }
530
+ catch (error) {
531
+ if (!(error instanceof GatewayError))
532
+ throw error;
533
+ const meaning = meaningOf(error);
534
+ if (meaning === "refused") {
535
+ // The task changed under it: it's read and evaluated afresh at its next turn.
536
+ await this.put({ ...entry, phase: "done", give_up: null, marker: "", outcome: `give_up_${error.code}` });
537
+ this.log("lifecycle.give_up", "refused", entry, { status: error.status, code: error.code });
538
+ return;
539
+ }
540
+ if (attempt + 1 < COMMAND_TRIES)
541
+ await this.backoff(attempt, signal, error);
542
+ if (signal.aborted)
543
+ return;
544
+ }
545
+ }
546
+ this.log("lifecycle.give_up", "unknown", entry);
547
+ }
548
+ /** Sends the accept, with the evaluated version and the stored key, retried with that key until it's answered. */
549
+ async accept(entry, signal) {
550
+ const decision = entry.decision;
551
+ if (!decision || !entry.accept_key)
552
+ throw new Error("accept_without_decision");
553
+ if (signal.aborted)
554
+ return;
555
+ for (let attempt = 0; attempt < COMMAND_TRIES; attempt++) {
556
+ try {
557
+ const answer = (await this.deps.poller.request("accept_task", { workspace_id: entry.workspace_id, task_id: entry.task_id, version: decision.task_version, idempotency_key: entry.accept_key }));
558
+ const version = answer?.version;
559
+ if (answer?.status === "accepted" && answer.assignee === this.deps.poller.agentId && typeof version === "number" && Number.isSafeInteger(version)) {
560
+ await this.put({ ...entry, phase: "ready", expected_version: version });
561
+ this.log("lifecycle.accept", "accepted", entry);
562
+ }
563
+ else {
564
+ await this.drop(entry, "accept_unexpected");
565
+ }
566
+ return;
567
+ }
568
+ catch (error) {
569
+ if (!(error instanceof GatewayError))
570
+ throw error;
571
+ if (meaningOf(error) === "refused") {
572
+ // `version_conflict`: the task changed after it was evaluated. Evaluated afresh, with a new key.
573
+ await this.drop(entry, `accept_${error.code}`, error.code === "version_conflict" ? "" : entry.marker);
574
+ this.log("lifecycle.accept", "refused", entry, { status: error.status, code: error.code });
575
+ return;
576
+ }
577
+ // Unknown: the accept may have happened. Only the same key is ever sent for it.
578
+ if (attempt + 1 < COMMAND_TRIES)
579
+ await this.backoff(attempt, signal, error);
580
+ if (signal.aborted)
581
+ return;
582
+ }
583
+ }
584
+ this.log("lifecycle.accept", "unknown", entry);
585
+ }
586
+ /** Ends an attempt that never ran: its reservation settles at zero. */
587
+ async drop(entry, outcome, marker = entry.marker) {
588
+ const ledger = settle(this.state.ledger, entry.reservation, 0, this.now());
589
+ await this.put({ ...entry, phase: "done", outcome, marker, decision: null, reservation: null, accept_key: null, expected_version: null }, ledger);
590
+ }
591
+ /** The fresh read, the fresh evaluation and the consume, then the run, supervised to its end. */
592
+ async start(entry, signal) {
593
+ const decision = entry.decision;
594
+ if (!decision)
595
+ throw new Error("start_without_decision");
596
+ const detail = await this.read(entry.workspace_id, entry.task_id);
597
+ if (signal.aborted)
598
+ return "stopped";
599
+ const task = detail?.task;
600
+ if (!detail || !task || task.status !== "accepted" || task.assignee !== this.deps.poller.agentId) {
601
+ // Canceled, re-offered or taken back after the accept: a retried accept may have answered a stored success.
602
+ await this.drop(entry, task ? `task_${task.status}` : "not_readable", task?.status === "offered" ? "" : entry.marker);
603
+ this.log("lifecycle.start", "not_accepted", entry, { code: task?.status });
604
+ return "idle";
605
+ }
606
+ const prompt = detail.prompt;
607
+ const started = await this.gate.run(async () => {
608
+ if (signal.aborted)
609
+ return "aborted";
610
+ let fresh = await this.evaluateFresh(detail, entry, this.deps.poller.authorityFresh(), decision.reserved_micro_usd);
611
+ if (signal.aborted)
612
+ return "aborted";
613
+ // The accept moved the version by exactly itself; any other change since shows as a different version and refuses.
614
+ const version = task.version === entry.expected_version ? decision.task_version : task.version;
615
+ // A room with a repository: a fresh checkout, verified, and its commit pinned into the stored decision (step 10).
616
+ let pinned = decision;
617
+ if (decision.repository_id !== null && prompt && fresh.outcome !== "refuse") {
618
+ const checkout = await this.checkout(entry, decision, fresh.facts, signal);
619
+ if (checkout === "aborted")
620
+ return "aborted";
621
+ if (checkout === null)
622
+ return null;
623
+ pinned = checkout;
624
+ // The checkout took time: the policy is read and evaluated again, so anything the owner changed meanwhile
625
+ // refuses the consume with `facts_changed` (ruling 7 on #462).
626
+ fresh = await this.evaluateFresh(detail, entry, this.deps.poller.authorityFresh(), decision.reserved_micro_usd);
627
+ if (signal.aborted)
628
+ return "aborted";
629
+ }
630
+ const binding = { task_id: entry.task_id, workspace_id: entry.workspace_id, task_version: version, input_hash: prompt?.hash ?? "", repository_id: pinned.repository_id, base_commit: pinned.base_commit };
631
+ const consumed = prompt ? this.policy.consumeRunDecision(pinned, fresh, binding, this.now()) : { ok: false, reason: "binding_changed" };
632
+ if (!consumed.ok) {
633
+ if (entry.decision?.repository_id)
634
+ this.deps.repository?.forget(entry.workspace_id, entry.task_id);
635
+ const ledger = settle(this.state.ledger, entry.reservation, 0, this.now());
636
+ const cleared = { ...entry, decision: null, reservation: null, expected_version: null };
637
+ this.state = { ...this.state, ledger };
638
+ this.log("lifecycle.consume", "refused", entry, { code: consumed.reason });
639
+ if (!prompt)
640
+ await this.giveUp(cleared, task.status, "prompt_unavailable", task.version);
641
+ else if (fresh.outcome === "refuse" && !LOCAL.has(fresh.reason))
642
+ await this.giveUp(cleared, task.status, fresh.reason, task.version);
643
+ // Expired, or anything else that changed: evaluated afresh at its next turn, asking again if the policy asks.
644
+ else
645
+ await this.put({ ...cleared, phase: "done", marker: "", outcome: `consume_${consumed.reason}` });
646
+ return null;
647
+ }
648
+ // A local stop while the policy decided: nothing is consumed, and the decision waits as it was (M1 on #458).
649
+ if (signal.aborted)
650
+ return "aborted";
651
+ const run_ref = this.newId();
652
+ // Stored as returned, with the run's ID, before the adapter starts anything.
653
+ const running = { ...entry, phase: "running", outcome: "started", consumed: consumed.record, run_ref };
654
+ await this.put(running);
655
+ return { running, facts: fresh.facts };
656
+ });
657
+ if (started === "aborted")
658
+ return "stopped";
659
+ if (!started || !prompt)
660
+ return "idle";
661
+ const { running, facts } = started;
662
+ this.log("lifecycle.run", "started", running);
663
+ try {
664
+ let handle;
665
+ const starting = this.deps.adapter.start({ run_ref: running.run_ref, workspace_id: running.workspace_id, task_id: running.task_id, prompt: prompt.bytes, facts });
666
+ try {
667
+ const answered = await orAbort(starting, signal);
668
+ if (answered === ABORTED) {
669
+ // Stopped while the adapter was starting: whatever it starts is stopped as soon as it's there, and the run is
670
+ // held until the adapter confirms nothing is left of it.
671
+ starting.then((late) => this.safeStop(late), () => undefined);
672
+ this.log("lifecycle.stop", "local_stop_unknown", running);
673
+ await this.stopped(running, "unknown", null, "stopped_locally", { kind: "release", reason: "stopped_locally" }, false);
674
+ return "stopped";
675
+ }
676
+ handle = answered;
677
+ }
678
+ catch {
679
+ const stopped = await this.deps.adapter.confirmStopped(running.run_ref).catch(() => false);
680
+ await this.stopped(running, stopped ? "stopped" : "unknown", null, "run_failed", { kind: "release", reason: "run_failed" });
681
+ return "idle";
682
+ }
683
+ // A local stop that came while the adapter started ends the run now, with no wait for a check-in (M1 on #458).
684
+ if (signal.aborted)
685
+ return await this.localStop(running, handle);
686
+ return await this.supervise(running, handle, signal);
687
+ }
688
+ catch (error) {
689
+ // Whatever went wrong, a run that may still be going is never left looking like nothing is (M2 on #458).
690
+ await this.holdOrphan(running, "run_interrupted");
691
+ throw error;
692
+ }
693
+ }
694
+ /**
695
+ * Step 10's checkout, inside the gate between the fresh evaluation and the consume: a fresh, verified checkout of the
696
+ * decision's own repository, and its commit pinned into the stored decision. Answers the pinned decision, or null when
697
+ * the task was given up, left to be evaluated afresh, or held.
698
+ */
699
+ async checkout(entry, decision, facts, signal) {
700
+ const repository = facts.repository;
701
+ const path = this.deps.repository;
702
+ const release = async (reason) => {
703
+ path?.forget(entry.workspace_id, entry.task_id);
704
+ const ledger = settle(this.state.ledger, entry.reservation, 0, this.now());
705
+ this.state = { ...this.state, ledger };
706
+ await this.giveUp({ ...entry, decision: null, reservation: null, expected_version: null }, "accepted", reason);
707
+ };
708
+ // The fresh facts name the decision's repository, or the consume refuses them anyway; no path is never a quiet run.
709
+ if (repository === null || String(repository.provider_repo_id) !== decision.repository_id)
710
+ return decision;
711
+ if (!path) {
712
+ this.log("lifecycle.repository", "refused", entry, { code: "repository_unavailable" });
713
+ await release("repository_unavailable");
714
+ return null;
715
+ }
716
+ const published = entry.published && entry.published.repository_id === decision.repository_id ? entry.published : null;
717
+ let base;
718
+ try {
719
+ const checkout = await path.prepare({ workspace_id: entry.workspace_id, task_id: entry.task_id, task_folder: facts.task_folder, repository, continue_from: published?.commit ?? null }, signal);
720
+ if (signal.aborted)
721
+ return "aborted";
722
+ if (checkout.repository_id !== decision.repository_id)
723
+ throw new RepoPathError("repository_id_mismatch");
724
+ base = checkout.base_commit;
725
+ }
726
+ catch (error) {
727
+ if (signal.aborted)
728
+ return "aborted";
729
+ if (!(error instanceof RepoPathError))
730
+ throw error;
731
+ this.log("lifecycle.repository", error.transient ? "unavailable" : "refused", entry, { code: error.code });
732
+ if (error.transient) {
733
+ // Passing: the decision is dropped and the task evaluated afresh at its next turn, with a new checkout.
734
+ path.forget(entry.workspace_id, entry.task_id);
735
+ const ledger = settle(this.state.ledger, entry.reservation, 0, this.now());
736
+ this.state = { ...this.state, ledger };
737
+ await this.put({ ...entry, phase: "waiting", outcome: `repo_${error.code}`, decision: null, reservation: null, expected_version: null, retry_at: this.now() + WAIT_MS });
738
+ }
739
+ else
740
+ await release(`repo_${error.code}`);
741
+ return null;
742
+ }
743
+ const pin = (this.policy.pinRunBase ?? pinRunBase)(decision, base, this.now());
744
+ if (!pin.ok) {
745
+ this.log("lifecycle.repository", "pin_refused", entry, { code: pin.reason });
746
+ path.forget(entry.workspace_id, entry.task_id);
747
+ const ledger = settle(this.state.ledger, entry.reservation, 0, this.now());
748
+ this.state = { ...this.state, ledger };
749
+ await this.put({ ...entry, phase: "done", marker: "", outcome: `pin_${pin.reason}`, decision: null, reservation: null, expected_version: null });
750
+ return null;
751
+ }
752
+ // Stored as returned, before the consume reads it.
753
+ await this.put({ ...entry, decision: pin.record });
754
+ this.log("lifecycle.repository", "checked_out", entry);
755
+ return pin.record;
756
+ }
757
+ /**
758
+ * Step 10's publication, after the run's container is confirmed stopped: committed, pushed and opened as a pull request
759
+ * through the broker. Answers what to store, or null when the task was given up instead. After a local stop nothing
760
+ * reaches Podster or GitHub: the finish waits, held, for a restart.
761
+ */
762
+ async publish(entry, signal) {
763
+ const consumed = entry.consumed;
764
+ const facts = consumed && consumed.repository_id !== null ? repositoryOf(consumed) : null;
765
+ if (!consumed || consumed.repository_id === null)
766
+ return { published: entry.published ?? null, outcome: entry.outcome ?? "succeeded" };
767
+ if (!facts || consumed.base_commit === null) {
768
+ await this.giveUp(entry, "accepted", "repo_record_invalid");
769
+ return null;
770
+ }
771
+ if (signal?.aborted)
772
+ return "wait";
773
+ const path = this.deps.repository;
774
+ if (!path) {
775
+ await this.giveUp(entry, "accepted", "repository_unavailable");
776
+ return null;
777
+ }
778
+ try {
779
+ const publication = await path.publish({ workspace_id: entry.workspace_id, task_id: entry.task_id, task_folder: facts.task_folder, repository: facts.repository, base_commit: consumed.base_commit }, signal ?? new AbortController().signal);
780
+ if (publication.kind === "no_changes") {
781
+ this.log("lifecycle.publish", "no_changes", entry);
782
+ return { published: entry.published ?? null, outcome: "no_changes" };
783
+ }
784
+ this.log("lifecycle.publish", "published", entry, { count: publication.pr_number });
785
+ return { published: { repository_id: consumed.repository_id, branch: publication.branch, commit: publication.commit, pr_number: publication.pr_number }, outcome: "published" };
786
+ }
787
+ catch (error) {
788
+ if (signal?.aborted)
789
+ return "wait";
790
+ if (!(error instanceof RepoPathError))
791
+ throw error;
792
+ if (error.transient) {
793
+ // Passing: the finished work is kept and published again at a later pass, never released (ruling 5 on #462).
794
+ this.log("lifecycle.publish", "unavailable", entry, { code: error.code });
795
+ return { wait: `repo_${error.code}` };
796
+ }
797
+ this.log("lifecycle.publish", "refused", entry, { code: error.code });
798
+ await this.giveUp(entry, "accepted", `repo_${error.code}`);
799
+ return null;
800
+ }
801
+ finally {
802
+ path.forget(entry.workspace_id, entry.task_id);
803
+ }
804
+ }
805
+ /** A stop that throws counts as unconfirmed (M2 on #458). */
806
+ async safeStop(handle) {
807
+ try {
808
+ return (await handle.stop()) === "stopped" ? "stopped" : "unknown";
809
+ }
810
+ catch {
811
+ return "unknown";
812
+ }
813
+ }
814
+ /**
815
+ * Holds an entry still recorded as running: its spend counts as the whole reservation, and it's released only once the
816
+ * adapter confirms it stopped. Kept in memory if the record can't be saved, so this process starts nothing new.
817
+ */
818
+ async holdOrphan(entry, outcome) {
819
+ const key = keyOf(entry.workspace_id, entry.task_id);
820
+ const current = this.state.entries[key];
821
+ if (!current || current.phase !== "running")
822
+ return;
823
+ const ledger = settle(this.state.ledger, current.reservation, null, this.now());
824
+ const next = { ...this.state, ledger, entries: { ...this.state.entries, [key]: { ...current, phase: "held", outcome, reservation: null, after_stop: { kind: "release", reason: outcome }, updated_at: this.now() } } };
825
+ try {
826
+ await this.save(next);
827
+ }
828
+ catch {
829
+ this.state = next;
830
+ }
831
+ this.log("lifecycle.run", "held", entry, { code: outcome });
832
+ }
833
+ /** Waits on the run, checking in at the fixed interval, and stops it on a local stop or anything a check-in finds. */
834
+ async supervise(entry, handle, signal) {
835
+ const done = handle.done.then((report) => ({ kind: "done", report }), () => ({ kind: "done", report: { status: "failed", spent_micro_usd: null } }));
836
+ let lastContact = this.now();
837
+ for (;;) {
838
+ // Before every wait, and never a listener on a signal that already fired (M1 on #458).
839
+ if (signal.aborted)
840
+ return this.localStop(entry, handle);
841
+ const wake = new AbortController();
842
+ const onAbort = () => wake.abort();
843
+ signal.addEventListener("abort", onAbort, { once: true });
844
+ const checkIn = this.deps.clock.idle(this.checkInMs, wake.signal).then(() => ({ kind: "check_in" }));
845
+ const next = await Promise.race([done, checkIn]);
846
+ wake.abort();
847
+ signal.removeEventListener("abort", onAbort);
848
+ if (signal.aborted)
849
+ return this.localStop(entry, handle);
850
+ if (next.kind === "done")
851
+ return this.ended(entry, handle, next.report);
852
+ let detail;
853
+ try {
854
+ detail = await orAbort(this.read(entry.workspace_id, entry.task_id), signal);
855
+ }
856
+ catch (error) {
857
+ if (error instanceof AuthorityEnded) {
858
+ // Revoked in Podster: the run stops at this check-in, then the agent's key is retired.
859
+ await this.stopFor(entry, handle, "revoked", { kind: "none" });
860
+ throw error;
861
+ }
862
+ if (signal.aborted)
863
+ return this.localStop(entry, handle);
864
+ if (this.now() - lastContact > this.deps.poller.graceMs) {
865
+ await this.stopFor(entry, handle, "offline_grace", { kind: "release", reason: "offline_grace" });
866
+ return "idle";
867
+ }
868
+ this.log("lifecycle.check_in", "unreachable", entry);
869
+ continue;
870
+ }
871
+ if (detail === ABORTED || signal.aborted)
872
+ return this.localStop(entry, handle);
873
+ lastContact = this.now();
874
+ const verdict = await this.gate.run(() => this.checkIn(entry, detail));
875
+ if (verdict) {
876
+ await this.stopFor(entry, handle, verdict.outcome, verdict.after);
877
+ return "idle";
878
+ }
879
+ this.log("lifecycle.check_in", "ok", entry);
880
+ }
881
+ }
882
+ /**
883
+ * What a check-in finds: null to go on, or why to stop and what follows. The task must still be accepted by this agent
884
+ * with the inputs the run was decided on, and a fresh evaluation must give the same facts, and `run` for an unattended
885
+ * decision.
886
+ */
887
+ async checkIn(entry, detail) {
888
+ const consumed = entry.consumed;
889
+ const task = detail?.task;
890
+ if (!detail || !task)
891
+ return { outcome: "not_readable", after: { kind: "none" } };
892
+ if (task.status === "canceled")
893
+ return { outcome: "canceled", after: { kind: "none" } };
894
+ if (task.status !== "accepted" || task.assignee !== this.deps.poller.agentId)
895
+ return { outcome: `task_${task.status}`, after: { kind: "reconsider" } };
896
+ if (!detail.prompt || detail.prompt.hash !== consumed.input_hash)
897
+ return { outcome: "inputs_changed", after: { kind: "reconsider" } };
898
+ // The read just made was answered as this agent, so its authority is fresh for this evaluation.
899
+ const fresh = await this.evaluateFresh(detail, entry, true, consumed.reserved_micro_usd);
900
+ if (fresh.outcome === "refuse")
901
+ return { outcome: `policy_${fresh.reason}`, after: { kind: "reconsider" } };
902
+ if (consumed.mode === "unattended" && fresh.outcome !== "run")
903
+ return { outcome: "policy_changed", after: { kind: "reconsider" } };
904
+ if (factsKey(fresh) !== consumed.facts_key)
905
+ return { outcome: "policy_changed", after: { kind: "reconsider" } };
906
+ return null;
907
+ }
908
+ /** The owner's local stop: the run's process tree first, with no call to Podster, then the record on this machine. */
909
+ async localStop(entry, handle) {
910
+ const result = await this.safeStop(handle);
911
+ this.log("lifecycle.stop", result === "stopped" ? "local_stop" : "local_stop_unknown", entry);
912
+ // The release is owed to Podster and sent after a restart, once the stop is confirmed.
913
+ await this.stopped(entry, result, null, "stopped_locally", { kind: "release", reason: "stopped_locally" }, false);
914
+ return "stopped";
915
+ }
916
+ async stopFor(entry, handle, outcome, after) {
917
+ const result = await this.safeStop(handle);
918
+ await this.stopped(entry, result, null, outcome, after);
919
+ }
920
+ /** A run that ended by itself. A failure, a budget stop or a time-out is never a submission: it's released. */
921
+ async ended(entry, handle, report) {
922
+ // Confirmed, not assumed: the tree is stopped before anything is released (R-24).
923
+ const result = await this.safeStop(handle);
924
+ const spent = typeof report.spent_micro_usd === "number" ? report.spent_micro_usd : null;
925
+ if (report.status !== "succeeded") {
926
+ await this.stopped(entry, result, spent, `run_${report.status}`, { kind: "release", reason: `run_${report.status}` });
927
+ return "idle";
928
+ }
929
+ // Step 11: the result is evidence, checked again here, so an adapter that hands over a malformed one is caught, not
930
+ // trusted. Only `completed` is work to submit; `blocked`, none or a malformed one is released.
931
+ const parsed = report.result ? parseRunResult(report.result) : null;
932
+ if (parsed?.ok && parsed.value.status === "completed") {
933
+ this.results.set(keyOf(entry.workspace_id, entry.task_id), { run_ref: entry.run_ref, result: parsed.value });
934
+ await this.stopped(entry, result, spent, "succeeded", { kind: "finish" });
935
+ }
936
+ else {
937
+ const reason = !report.result ? "result_missing" : !parsed?.ok ? "result_invalid" : "run_blocked";
938
+ await this.stopped(entry, result, spent, reason, { kind: "release", reason });
939
+ }
940
+ return "idle";
941
+ }
942
+ /** Settles the run's reservation and records what follows: at once if the stop is confirmed, held if it isn't. */
943
+ async stopped(entry, result, spent, outcome, after, act = true) {
944
+ const ledger = settle(this.state.ledger, entry.reservation, spent, this.now());
945
+ this.state = { ...this.state, ledger };
946
+ const settled = { ...entry, reservation: null, outcome };
947
+ this.log("lifecycle.run", outcome, entry, { count: spent ?? undefined });
948
+ if (result !== "stopped") {
949
+ await this.put({ ...settled, phase: "held", after_stop: after });
950
+ this.log("lifecycle.run", "held", entry, { code: outcome });
951
+ return;
952
+ }
953
+ if (!act) {
954
+ // Nothing more now: what follows waits for a restart, as a held run whose stop is already confirmed.
955
+ await this.put({ ...settled, phase: "held", after_stop: after });
956
+ return;
957
+ }
958
+ await this.afterStop(settled, after);
959
+ }
960
+ async afterStop(entry, after) {
961
+ const base = { ...entry, after_stop: null, run_ref: entry.run_ref };
962
+ if (after.kind === "finish") {
963
+ // Step 10: a run in a room with a repository is published before it counts as finished.
964
+ const published = await this.publish(base, this.tickSignal);
965
+ if (published === "wait") {
966
+ // A local stop: held as it was, for a restart.
967
+ await this.put({ ...entry, phase: "held", after_stop: after });
968
+ return;
969
+ }
970
+ if (published !== null && "wait" in published) {
971
+ // Held, its stop already confirmed and its folder and commit kept, and tried again after a wait, for at most
972
+ // an hour from its first failure; then released (the ruling on #462's held publications).
973
+ const since = typeof entry.publish_since === "number" ? entry.publish_since : this.now();
974
+ if (this.now() - since >= PUBLISH_RETRY_MS) {
975
+ this.log("lifecycle.publish", "given_up", entry, { code: "repo_publish_failed" });
976
+ this.deps.repository?.forget(entry.workspace_id, entry.task_id);
977
+ await this.giveUp({ ...base, publish_since: null, retry_at: null }, "accepted", "repo_publish_failed");
978
+ return;
979
+ }
980
+ await this.put({ ...entry, phase: "held", after_stop: after, outcome: published.wait, publish_since: since, retry_at: this.now() + WAIT_MS });
981
+ return;
982
+ }
983
+ if (published === null)
984
+ return;
985
+ const consumed = entry.consumed;
986
+ const pub = published.published;
987
+ // Step 11: in a room with a repository, only a commit Runner itself pushed for these inputs can be submitted: this
988
+ // run's own, or, when it changed nothing, the one it started from. Otherwise there is no work to submit.
989
+ if (consumed?.repository_id && !(pub && pub.repository_id === consumed.repository_id && (published.outcome === "published" || pub.commit === consumed.base_commit))) {
990
+ this.results.delete(keyOf(entry.workspace_id, entry.task_id));
991
+ this.log("lifecycle.submit", "nothing_to_submit", entry, { code: "run_no_changes" });
992
+ await this.giveUp({ ...base, publish_since: null, retry_at: null, published: pub }, "accepted", "run_no_changes");
993
+ return;
994
+ }
995
+ await this.put({ ...base, phase: "finished", publish_since: null, retry_at: null, ran_hash: consumed?.input_hash ?? null, published: pub, outcome: published.outcome === "succeeded" ? entry.outcome : published.outcome, submission: owedSubmission() });
996
+ }
997
+ else if (after.kind === "release") {
998
+ this.results.delete(keyOf(entry.workspace_id, entry.task_id));
999
+ if (entry.consumed?.repository_id)
1000
+ this.deps.repository?.forget(entry.workspace_id, entry.task_id);
1001
+ await this.giveUp(base, "accepted", after.reason);
1002
+ }
1003
+ else if (after.kind === "reconsider")
1004
+ await this.put({ ...base, phase: "done", marker: "" });
1005
+ else
1006
+ await this.put({ ...base, phase: "done" });
1007
+ }
1008
+ /** The entry as it stands in the record, which a step of the submission may have just saved. */
1009
+ current(entry) {
1010
+ return this.state.entries[keyOf(entry.workspace_id, entry.task_id)] ?? entry;
1011
+ }
1012
+ /**
1013
+ * Step 11: an owed submission. What it says of the work comes from Runner's records, bound to the run's decision; a
1014
+ * fresh read must show the task as the run left it; the agent's words go only where sharing is allowed or the owner
1015
+ * approved them; then `submit_task`, with a key stored first.
1016
+ */
1017
+ async submit(entry, signal) {
1018
+ if (signal.aborted)
1019
+ return;
1020
+ const key = keyOf(entry.workspace_id, entry.task_id);
1021
+ const agent = this.deps.poller.agentId;
1022
+ const consumed = entry.consumed;
1023
+ const release = async (reason) => {
1024
+ this.results.delete(key);
1025
+ this.log("lifecycle.submit", "refused", entry, { code: reason });
1026
+ await this.giveUp({ ...this.current(entry), submission: null, retry_at: null }, "accepted", reason);
1027
+ };
1028
+ const notSubmitted = async (why) => {
1029
+ this.results.delete(key);
1030
+ this.log("lifecycle.submit", "not_submitted", entry, { code: `submit_${why}` });
1031
+ // Read and evaluated afresh at its next turn.
1032
+ await this.put({ ...this.current(entry), phase: "done", marker: "", outcome: `submit_${why}`, submission: null, retry_at: null });
1033
+ };
1034
+ if (!consumed)
1035
+ return release("result_record_invalid");
1036
+ // The pull request and commit are what Runner pushed and checked for this run's repository and branch (step 10).
1037
+ let pr = null;
1038
+ if (consumed.repository_id !== null) {
1039
+ const scope = repositoryOf(consumed);
1040
+ const pub = entry.published;
1041
+ if (!scope || !pub || pub.repository_id !== consumed.repository_id || pub.branch !== scope.repository.branch)
1042
+ return release("result_record_invalid");
1043
+ pr = { full_name: scope.repository.full_name, number: pub.pr_number, branch: pub.branch, commit: pub.commit };
1044
+ }
1045
+ const detail = await this.read(entry.workspace_id, entry.task_id);
1046
+ if (signal.aborted)
1047
+ return;
1048
+ const task = detail?.task;
1049
+ if (task && entry.submission?.key && task.status === "submitted" && task.assignee === agent && entry.expected_version !== null && task.version > entry.expected_version) {
1050
+ // An earlier send went through and its answer was lost: only this agent can have submitted it.
1051
+ return this.submitted(entry);
1052
+ }
1053
+ if (!detail || !task)
1054
+ return notSubmitted("not_readable");
1055
+ if (task.assignee !== agent || task.status !== "accepted")
1056
+ return notSubmitted(`task_${task.status}`);
1057
+ if (task.version !== entry.expected_version)
1058
+ return notSubmitted("version_changed");
1059
+ if (detail.prompt?.hash !== consumed.input_hash)
1060
+ return notSubmitted("inputs_changed");
1061
+ let sub = this.current(entry).submission;
1062
+ if (sub.sharing === "pending") {
1063
+ const share = await this.sharingAllowed(entry.workspace_id, consumed);
1064
+ sub = { ...sub, sharing: share ? "share" : "review", held_since: share ? null : this.now() };
1065
+ await this.put({ ...this.current(entry), submission: sub });
1066
+ }
1067
+ const kept = this.results.get(key);
1068
+ const result = kept && kept.run_ref === entry.run_ref ? kept.result : null;
1069
+ const cleaned = result ? cleanResult(result) : null;
1070
+ if (sub.sharing === "review" && cleaned?.ok && this.now() - (sub.held_since ?? this.now()) >= REVIEW_HOLD_MS) {
1071
+ // Held past its limit with no answer: submitted with Runner's fixed note only, never the agent's words.
1072
+ sub = { ...sub, sharing: "withheld" };
1073
+ await this.put({ ...this.current(entry), submission: sub });
1074
+ this.log("lifecycle.review", "withheld", entry, { code: "review_hold_expired" });
1075
+ }
1076
+ if (sub.sharing === "review" && cleaned?.ok) {
1077
+ await this.tellHeld(entry);
1078
+ const review = this.deps.prompter.review;
1079
+ const answer = review ? await review.call(this.deps.prompter, { workspace_id: entry.workspace_id, task_id: entry.task_id, pull_request: pr, summary: cleaned.summary, files: cleaned.files, redactions: cleaned.redactions }, signal) : "later";
1080
+ if (signal.aborted)
1081
+ return;
1082
+ this.log("lifecycle.review", answer, entry);
1083
+ if (answer === "later") {
1084
+ await this.put({ ...this.current(entry), retry_at: this.now() + ASK_AGAIN_MS });
1085
+ return;
1086
+ }
1087
+ sub = { ...this.current(entry).submission, sharing: answer === "approve" ? "approved" : "withheld" };
1088
+ await this.put({ ...this.current(entry), submission: sub });
1089
+ }
1090
+ const words = !result || !cleaned ? { kind: "lost" } : !cleaned.ok ? { kind: "secret_hidden" } : sub.sharing === "share" || sub.sharing === "approved" ? { kind: "shared", ...cleaned } : { kind: "withheld" };
1091
+ const note = composeNote({ task_id: entry.task_id, pull_request: pr, words });
1092
+ const noteHash = await sha256Hex(new TextEncoder().encode(note));
1093
+ if (sub.key === null || sub.note_hash !== noteHash) {
1094
+ // Stored before it's first sent. A different note gets a new key, so a replay never carries another body.
1095
+ sub = { ...sub, key: this.newId(), note_hash: noteHash };
1096
+ await this.put({ ...this.current(entry), submission: sub });
1097
+ }
1098
+ const args = { workspace_id: entry.workspace_id, task_id: entry.task_id, version: task.version, note, idempotency_key: sub.key };
1099
+ if (pr)
1100
+ Object.assign(args, { commit_sha: pr.commit, pr_number: pr.number, artifacts: [{ uri: pullRequestUrl(pr.full_name, pr.number), label: "Pull request" }] });
1101
+ for (let attempt = 0; attempt < COMMAND_TRIES; attempt++) {
1102
+ try {
1103
+ const answer = (await this.deps.poller.request("submit_task", args));
1104
+ if (answer?.status === "submitted")
1105
+ return this.submitted(entry);
1106
+ return notSubmitted("unexpected");
1107
+ }
1108
+ catch (error) {
1109
+ if (!(error instanceof GatewayError))
1110
+ throw error;
1111
+ if (meaningOf(error) === "refused" && !SUBMIT_AGAIN.has(error.code)) {
1112
+ this.log("lifecycle.submit", "refused", entry, { status: error.status, code: error.code });
1113
+ // The task changed under it: read afresh. Anything else the server refused can't be submitted as it is.
1114
+ if (error.code === "version_conflict")
1115
+ return notSubmitted("version_conflict");
1116
+ return release(`submit_${error.code}`);
1117
+ }
1118
+ if (attempt + 1 < COMMAND_TRIES)
1119
+ await this.backoff(attempt, signal, error);
1120
+ if (signal.aborted)
1121
+ return;
1122
+ }
1123
+ }
1124
+ // Unknown: it may have gone through. Only the same key is sent for this note, at a later pass.
1125
+ this.log("lifecycle.submit", "unknown", entry);
1126
+ }
1127
+ async submitted(entry) {
1128
+ this.results.delete(keyOf(entry.workspace_id, entry.task_id));
1129
+ const current = this.current(entry);
1130
+ await this.put({ ...current, outcome: "submitted", retry_at: null, submission: { ...current.submission, state: "submitted" } });
1131
+ this.log("lifecycle.submit", "submitted", entry);
1132
+ }
1133
+ /** Whether the agent's words may go without the owner's review: the run's facts and the room's policy now both say so. */
1134
+ async sharingAllowed(workspace_id, consumed) {
1135
+ if (outputsOf(consumed) !== "share")
1136
+ return false;
1137
+ const parsed = parsePolicyConfig(await readConfig(this.deps.config), homeOf(this.deps));
1138
+ return parsed.ok && parsed.value.owner_org === this.ownerOrg && parsed.value.rooms.some((r) => r.room_id === workspace_id && r.outputs === "share");
1139
+ }
1140
+ /** The fixed progress message for a held result, sent once, with a key stored first; a failure is tried at a later review. */
1141
+ async tellHeld(entry) {
1142
+ let sub = this.current(entry).submission;
1143
+ if (sub.told)
1144
+ return;
1145
+ if (sub.told_key === null) {
1146
+ sub = { ...sub, told_key: this.newId() };
1147
+ await this.put({ ...this.current(entry), submission: sub });
1148
+ }
1149
+ try {
1150
+ await this.deps.poller.request("send_message", { workspace_id: entry.workspace_id, task_id: entry.task_id, body: HELD_STATUS, idempotency_key: sub.told_key });
1151
+ await this.put({ ...this.current(entry), submission: { ...this.current(entry).submission, told: true } });
1152
+ this.log("lifecycle.progress", "result_held", entry);
1153
+ }
1154
+ catch (error) {
1155
+ if (!(error instanceof GatewayError))
1156
+ throw error;
1157
+ this.log("lifecycle.progress", "unsent", entry, { status: error.status, code: error.code });
1158
+ }
1159
+ }
1160
+ }
1161
+ function askView(entry, decision, detail) {
1162
+ const facts = decision.facts;
1163
+ return {
1164
+ workspace_id: entry.workspace_id,
1165
+ task_id: entry.task_id,
1166
+ reason: decision.reason,
1167
+ room_visibility: facts.room_visibility,
1168
+ requester: facts.requester,
1169
+ authors: facts.authors,
1170
+ tools: facts.tools,
1171
+ network: facts.network,
1172
+ caps: facts.caps,
1173
+ repository: facts.repository,
1174
+ inputs: detail.prompt?.inputs.map(({ input, text }) => ({ input, text })) ?? [],
1175
+ };
1176
+ }
1177
+ /**
1178
+ * Runner's loop with the lifecycle: a poll, then a lifecycle pass, then the wait. A local stop (`signal`) ends it at once,
1179
+ * a run included, and nothing is called after it; a revoked agent ends it too.
1180
+ */
1181
+ export async function runWithLifecycle(poller, lifecycle, clock, signal, bell) {
1182
+ while (!signal.aborted) {
1183
+ const polled = await poller.pollOnce();
1184
+ if (polled === "revoked")
1185
+ return "revoked";
1186
+ if (signal.aborted)
1187
+ break;
1188
+ if (polled === "ok") {
1189
+ const outcome = await lifecycle.tick(signal);
1190
+ if (outcome !== "idle")
1191
+ return outcome;
1192
+ }
1193
+ // A nudge (M7 step 14) only ends this wait early: the next poll and tick are the ordinary ones.
1194
+ await waitForNext(clock, poller.nextWaitMs(polled), polled, signal, bell);
1195
+ }
1196
+ return "stopped";
1197
+ }
1198
+ const homeOf = (deps) => (deps.home === undefined ? {} : { runner_home: deps.home });
1199
+ /** The run policy as it stands: a function's answer read now, or the value given. A read that throws is no policy. */
1200
+ async function readConfig(config) {
1201
+ try {
1202
+ return typeof config === "function" ? await config() : config;
1203
+ }
1204
+ catch {
1205
+ return null;
1206
+ }
1207
+ }