podster 0.0.1-test.5 → 0.0.1-test.8

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.
@@ -1,12 +1,12 @@
1
1
  import { GatewayError, meaningOf } from "./errors.js";
2
- import { consumeRunDecision, evaluate, factsKey, issueRunDecision, outputsOf, parsePolicyConfig, pinRunBase, repositoryOf } from "./policy.js";
2
+ import { consumeRunDecision, evaluate, factsKey, issueRunDecision, outputsOf, parsePolicyConfig, pinRunBase, policyProblem, repositoryOf } from "./policy.js";
3
3
  import { pullRequestUrl, RepoPathError } from "./repository.js";
4
4
  import { readTaskDetail, sha256Hex } from "./prompt.js";
5
- import { cleanResult, composeNote } from "./results.js";
5
+ import { cleanResult, composeBlockedNote, composeNote } from "./results.js";
6
6
  import { parseRunResult } from "./tool-policy.js";
7
7
  import { AuthorityEnded, waitForNext } from "./poller.js";
8
8
  import { MAX_PROMPT_BYTES } from "./run-interface.js";
9
- import { budgetOf, clockWentBack, dayOf, newEntry, owedSubmission, reserve, settle } from "./runs.js";
9
+ import { budgetOf, clockWentBack, dayOf, newEntry, owedReport, owedSubmission, reserve, settle } from "./runs.js";
10
10
  /** The check-in's fixed maximum interval during a run (S-33, S-43). **Proposed** figure. */
11
11
  export const CHECK_IN_MS = 60_000;
12
12
  export const MIN_CHECK_IN_MS = 5_000;
@@ -79,7 +79,9 @@ class Gate {
79
79
  const keyOf = (workspace, task) => `${workspace}/${task}`;
80
80
  /** What marks an offer as new: its latest event, sequence, status and version, never the time it was last listed. */
81
81
  export const markerOf = (offer) => `${offer.last}|${offer.seq ?? "-"}|${offer.version ?? "-"}`;
82
- const ACTIVE = new Set(["accepting", "ready", "running", "giving_up", "held"]);
82
+ const ACTIVE = new Set(["accepting", "ready", "running", "giving_up", "held", "reporting"]);
83
+ /** The SHA-256 of a decision's facts, as a blocked run's record keeps it. */
84
+ const factsHash = (key) => sha256Hex(new TextEncoder().encode(key));
83
85
  /** Resolves with `promise`, or with `aborted` at once when the signal fires, whichever is first. */
84
86
  function orAbort(promise, signal) {
85
87
  if (signal.aborted) {
@@ -113,6 +115,8 @@ export class Lifecycle {
113
115
  approvals = new Map();
114
116
  /** Each finished run's structured result, by task, until it's submitted: in memory only, never stored or logged. */
115
117
  results = new Map();
118
+ /** Each repository run's task title, as its inputs had it, by task, for its pull request: in memory only, never stored or logged. */
119
+ titles = new Map();
116
120
  /** The agent's own organization, checked at open: a policy reread later must still name it. */
117
121
  ownerOrg = "";
118
122
  constructor(deps, state) {
@@ -130,7 +134,7 @@ export class Lifecycle {
130
134
  static async open(deps) {
131
135
  const parsed = parsePolicyConfig(await readConfig(deps.config), homeOf(deps));
132
136
  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.`);
137
+ throw new Error(`Runner's run policy can't be used: ${policyProblem(parsed.at)}. Nothing was started.`);
134
138
  const identity = (await deps.poller.request("get_identity"));
135
139
  if (identity?.id !== deps.poller.agentId)
136
140
  throw new AuthorityEnded();
@@ -160,6 +164,10 @@ export class Lifecycle {
160
164
  log(at, outcome, entry, extra = {}) {
161
165
  this.deps.log(at, outcome, { agent: this.deps.poller.agentId, workspace: entry.workspace_id, task: entry.task_id, ...extra });
162
166
  }
167
+ /** A failure, for the local diagnostics file only: its code, the task's IDs and the raw error, if there is one. */
168
+ diagnose(at, entry, code, error) {
169
+ this.deps.diagnostics?.record({ at, code, workspace: entry.workspace_id, task: entry.task_id, ...(entry.run_ref ? { run_ref: entry.run_ref } : {}), ...(error === undefined ? {} : { error }) });
170
+ }
163
171
  /**
164
172
  * Ends every attempt that has no process: its reservation settles at zero, and nothing more is sent for it. A run that
165
173
  * may still be going stays held.
@@ -217,6 +225,7 @@ export class Lifecycle {
217
225
  return "stopped";
218
226
  const failure = error instanceof GatewayError ? error : new GatewayError(0, "unknown");
219
227
  this.deps.log("lifecycle.tick", "unreachable", { agent: this.deps.poller.agentId, status: failure.status, code: failure.code });
228
+ this.deps.diagnostics?.record({ at: "lifecycle.tick", code: failure.code, error });
220
229
  return "idle";
221
230
  }
222
231
  finally {
@@ -261,6 +270,13 @@ export class Lifecycle {
261
270
  if (entry.submission?.state === "owed" && (entry.retry_at === null || this.now() >= entry.retry_at))
262
271
  await this.submit(entry, signal);
263
272
  }
273
+ for (const entry of this.entries("reporting")) {
274
+ // A blocked run's reason, owed to the room, once any wait for the owner's review is over.
275
+ if (signal.aborted)
276
+ return "stopped";
277
+ if (entry.retry_at === null || this.now() >= entry.retry_at)
278
+ await this.report(entry, signal);
279
+ }
264
280
  for (const entry of this.entries("giving_up")) {
265
281
  if (signal.aborted)
266
282
  return "stopped";
@@ -302,6 +318,11 @@ export class Lifecycle {
302
318
  counted = false;
303
319
  else if (entry.marker !== marker && TRIGGERS.has(offer.last))
304
320
  counted = true;
321
+ else if (entry.marker !== marker && offer.last === "task.message" && entry.blocked) {
322
+ // A message on a task whose last run answered blocked: a person acted, so the same inputs may run again.
323
+ await this.put({ ...entry, blocked: null });
324
+ counted = true;
325
+ }
305
326
  else if (entry.marker !== marker && RECHECKS.has(offer.last))
306
327
  onlyIfOffered = offer.last === "task.updated";
307
328
  else {
@@ -386,7 +407,7 @@ export class Lifecycle {
386
407
  const detail = await this.read(offer.workspace_id, offer.task_id);
387
408
  const task = detail?.task;
388
409
  if (!detail || !task || task.assignee !== this.deps.poller.agentId || (task.status !== "offered" && task.status !== "accepted")) {
389
- this.results.delete(key);
410
+ this.forgetWords(key);
390
411
  await this.put({ ...entry, phase: "done", outcome: task ? `task_${task.status}` : "not_readable" });
391
412
  return;
392
413
  }
@@ -462,6 +483,20 @@ export class Lifecycle {
462
483
  await this.giveUp(entry, task.status, decision.reason, task.version);
463
484
  return null;
464
485
  }
486
+ const blocked = entry.blocked;
487
+ if (decision.outcome === "run" && blocked && blocked.input_hash === detail.prompt.hash && blocked.facts_hash === (await factsHash(factsKey(decision) ?? ""))) {
488
+ // The last run on these exact inputs and facts answered blocked, and its reason went to the room: nothing new to
489
+ // run on, so no spend. An ask still asks the owner, who may run it.
490
+ this.log("lifecycle.decision", "refuse", entry, { code: "blocked_same_inputs" });
491
+ if (task.status === "offered")
492
+ await this.giveUp(entry, task.status, "blocked_same_inputs", task.version);
493
+ // A first run's task is never left accepted: its release, refused or lost before, is sent again.
494
+ else if (detail.prompt.shape.change_request_event_id === null)
495
+ await this.giveUp(entry, task.status, "run_blocked", task.version);
496
+ else
497
+ await this.put({ ...entry, phase: "done", outcome: "blocked_same_inputs" });
498
+ return null;
499
+ }
465
500
  let approved = false;
466
501
  if (decision.outcome === "ask") {
467
502
  const held = this.approvals.get(key);
@@ -535,6 +570,7 @@ export class Lifecycle {
535
570
  // The task changed under it: it's read and evaluated afresh at its next turn.
536
571
  await this.put({ ...entry, phase: "done", give_up: null, marker: "", outcome: `give_up_${error.code}` });
537
572
  this.log("lifecycle.give_up", "refused", entry, { status: error.status, code: error.code });
573
+ this.diagnose("lifecycle.give_up", entry, error.code, error);
538
574
  return;
539
575
  }
540
576
  if (attempt + 1 < COMMAND_TRIES)
@@ -652,6 +688,9 @@ export class Lifecycle {
652
688
  // Stored as returned, with the run's ID, before the adapter starts anything.
653
689
  const running = { ...entry, phase: "running", outcome: "started", consumed: consumed.record, run_ref };
654
690
  await this.put(running);
691
+ const title = prompt?.inputs.find((i) => i.input === "title")?.text;
692
+ if (consumed.record.repository_id !== null && title !== undefined)
693
+ this.titles.set(keyOf(entry.workspace_id, entry.task_id), { run_ref, title });
655
694
  return { running, facts: fresh.facts };
656
695
  });
657
696
  if (started === "aborted")
@@ -675,9 +714,12 @@ export class Lifecycle {
675
714
  }
676
715
  handle = answered;
677
716
  }
678
- catch {
717
+ catch (error) {
718
+ // A run that never started: its cause, a code only, is logged and reported to the room before the release.
719
+ const cause = startCause(error);
720
+ this.log("lifecycle.run", "start_failed", running, { code: cause });
679
721
  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" });
722
+ await this.stopped(running, stopped ? "stopped" : "unknown", null, "run_failed", { kind: "start_failed", code: cause });
681
723
  return "idle";
682
724
  }
683
725
  // A local stop that came while the adapter started ends the run now, with no wait for a check-in (M1 on #458).
@@ -729,6 +771,7 @@ export class Lifecycle {
729
771
  if (!(error instanceof RepoPathError))
730
772
  throw error;
731
773
  this.log("lifecycle.repository", error.transient ? "unavailable" : "refused", entry, { code: error.code });
774
+ this.diagnose("lifecycle.repository", entry, error.code, error);
732
775
  if (error.transient) {
733
776
  // Passing: the decision is dropped and the task evaluated afresh at its next turn, with a new checkout.
734
777
  path.forget(entry.workspace_id, entry.task_id);
@@ -776,7 +819,13 @@ export class Lifecycle {
776
819
  return null;
777
820
  }
778
821
  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);
822
+ const key = keyOf(entry.workspace_id, entry.task_id);
823
+ const held = this.titles.get(key);
824
+ const kept = this.results.get(key);
825
+ const words = { title: held && held.run_ref === entry.run_ref ? held.title : null, change_type: kept && kept.run_ref === entry.run_ref ? (kept.result.change_type ?? null) : null };
826
+ 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, ...words }, signal ?? new AbortController().signal);
827
+ // Published or not, the title has done its work; the result stays held for the submission.
828
+ this.titles.delete(key);
780
829
  if (publication.kind === "no_changes") {
781
830
  this.log("lifecycle.publish", "no_changes", entry);
782
831
  return { published: entry.published ?? null, outcome: "no_changes" };
@@ -792,9 +841,12 @@ export class Lifecycle {
792
841
  if (error.transient) {
793
842
  // Passing: the finished work is kept and published again at a later pass, never released (ruling 5 on #462).
794
843
  this.log("lifecycle.publish", "unavailable", entry, { code: error.code });
844
+ this.diagnose("lifecycle.publish", entry, error.code, error);
795
845
  return { wait: `repo_${error.code}` };
796
846
  }
847
+ this.titles.delete(keyOf(entry.workspace_id, entry.task_id));
797
848
  this.log("lifecycle.publish", "refused", entry, { code: error.code });
849
+ this.diagnose("lifecycle.publish", entry, error.code, error);
798
850
  await this.giveUp(entry, "accepted", `repo_${error.code}`);
799
851
  return null;
800
852
  }
@@ -923,28 +975,38 @@ export class Lifecycle {
923
975
  const result = await this.safeStop(handle);
924
976
  const spent = typeof report.spent_micro_usd === "number" ? report.spent_micro_usd : null;
925
977
  if (report.status !== "succeeded") {
926
- await this.stopped(entry, result, spent, `run_${report.status}`, { kind: "release", reason: `run_${report.status}` });
978
+ // The most specific cause the adapter gave: the driver's own code, else Runner's stop reason.
979
+ const cause = codeOf(report.stop_detail) ?? codeOf(report.stop_reason) ?? `run_${report.status}`;
980
+ this.diagnose("lifecycle.run", entry, cause);
981
+ await this.stopped(entry, result, spent, `run_${report.status}`, { kind: "release", reason: `run_${report.status}` }, true, cause);
927
982
  return "idle";
928
983
  }
929
984
  // 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.
985
+ // trusted. Only `completed` is work to submit; `blocked` is an answer whose reason the room is told; none or a
986
+ // malformed one is released.
931
987
  const parsed = report.result ? parseRunResult(report.result) : null;
932
988
  if (parsed?.ok && parsed.value.status === "completed") {
933
989
  this.results.set(keyOf(entry.workspace_id, entry.task_id), { run_ref: entry.run_ref, result: parsed.value });
934
990
  await this.stopped(entry, result, spent, "succeeded", { kind: "finish" });
935
991
  }
992
+ else if (parsed?.ok && parsed.value.status === "blocked") {
993
+ this.results.set(keyOf(entry.workspace_id, entry.task_id), { run_ref: entry.run_ref, result: parsed.value });
994
+ await this.stopped(entry, result, spent, "run_blocked", { kind: "blocked" });
995
+ }
936
996
  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 });
997
+ const reason = !report.result ? "result_missing" : "result_invalid";
998
+ const cause = parsed && !parsed.ok ? parsed.rule : reason;
999
+ this.diagnose("lifecycle.run", entry, cause);
1000
+ await this.stopped(entry, result, spent, reason, { kind: "release", reason }, true, cause);
939
1001
  }
940
1002
  return "idle";
941
1003
  }
942
1004
  /** 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) {
1005
+ async stopped(entry, result, spent, outcome, after, act = true, code) {
944
1006
  const ledger = settle(this.state.ledger, entry.reservation, spent, this.now());
945
1007
  this.state = { ...this.state, ledger };
946
1008
  const settled = { ...entry, reservation: null, outcome };
947
- this.log("lifecycle.run", outcome, entry, { count: spent ?? undefined });
1009
+ this.log("lifecycle.run", outcome, entry, { count: spent ?? undefined, ...(code ? { code } : {}) });
948
1010
  if (result !== "stopped") {
949
1011
  await this.put({ ...settled, phase: "held", after_stop: after });
950
1012
  this.log("lifecycle.run", "held", entry, { code: outcome });
@@ -987,7 +1049,7 @@ export class Lifecycle {
987
1049
  // Step 11: in a room with a repository, only a commit Runner itself pushed for these inputs can be submitted: this
988
1050
  // run's own, or, when it changed nothing, the one it started from. Otherwise there is no work to submit.
989
1051
  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));
1052
+ this.forgetWords(keyOf(entry.workspace_id, entry.task_id));
991
1053
  this.log("lifecycle.submit", "nothing_to_submit", entry, { code: "run_no_changes" });
992
1054
  await this.giveUp({ ...base, publish_since: null, retry_at: null, published: pub }, "accepted", "run_no_changes");
993
1055
  return;
@@ -995,16 +1057,47 @@ export class Lifecycle {
995
1057
  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
1058
  }
997
1059
  else if (after.kind === "release") {
998
- this.results.delete(keyOf(entry.workspace_id, entry.task_id));
1060
+ this.forgetWords(keyOf(entry.workspace_id, entry.task_id));
999
1061
  if (entry.consumed?.repository_id)
1000
1062
  this.deps.repository?.forget(entry.workspace_id, entry.task_id);
1001
1063
  await this.giveUp(base, "accepted", after.reason);
1002
1064
  }
1065
+ else if (after.kind === "start_failed") {
1066
+ // Nothing ran: the room is told why in Runner's fixed words, then the task is released as before.
1067
+ const key = keyOf(entry.workspace_id, entry.task_id);
1068
+ this.forgetWords(key);
1069
+ if (entry.consumed?.repository_id)
1070
+ this.deps.repository?.forget(entry.workspace_id, entry.task_id);
1071
+ if (!entry.consumed) {
1072
+ await this.giveUp(base, "accepted", "run_failed");
1073
+ return;
1074
+ }
1075
+ await this.put({ ...base, phase: "reporting", retry_at: null, report: { ...owedReport(), sharing: "withheld", start_failed: after.code } });
1076
+ }
1077
+ else if (after.kind === "blocked") {
1078
+ // Nothing is published for a blocked run; its reason is owed to the room, and its inputs recorded.
1079
+ const key = keyOf(entry.workspace_id, entry.task_id);
1080
+ this.titles.delete(key);
1081
+ if (entry.consumed?.repository_id)
1082
+ this.deps.repository?.forget(entry.workspace_id, entry.task_id);
1083
+ const consumed = entry.consumed;
1084
+ if (!consumed) {
1085
+ this.forgetWords(key);
1086
+ await this.giveUp(base, "accepted", "run_blocked");
1087
+ return;
1088
+ }
1089
+ await this.put({ ...base, phase: "reporting", retry_at: null, report: owedReport(), blocked: { input_hash: consumed.input_hash, facts_hash: await factsHash(consumed.facts_key) } });
1090
+ }
1003
1091
  else if (after.kind === "reconsider")
1004
1092
  await this.put({ ...base, phase: "done", marker: "" });
1005
1093
  else
1006
1094
  await this.put({ ...base, phase: "done" });
1007
1095
  }
1096
+ /** Drops what is held in memory for a task's run: its result and its title. */
1097
+ forgetWords(key) {
1098
+ this.results.delete(key);
1099
+ this.titles.delete(key);
1100
+ }
1008
1101
  /** The entry as it stands in the record, which a step of the submission may have just saved. */
1009
1102
  current(entry) {
1010
1103
  return this.state.entries[keyOf(entry.workspace_id, entry.task_id)] ?? entry;
@@ -1021,12 +1114,12 @@ export class Lifecycle {
1021
1114
  const agent = this.deps.poller.agentId;
1022
1115
  const consumed = entry.consumed;
1023
1116
  const release = async (reason) => {
1024
- this.results.delete(key);
1117
+ this.forgetWords(key);
1025
1118
  this.log("lifecycle.submit", "refused", entry, { code: reason });
1026
1119
  await this.giveUp({ ...this.current(entry), submission: null, retry_at: null }, "accepted", reason);
1027
1120
  };
1028
1121
  const notSubmitted = async (why) => {
1029
- this.results.delete(key);
1122
+ this.forgetWords(key);
1030
1123
  this.log("lifecycle.submit", "not_submitted", entry, { code: `submit_${why}` });
1031
1124
  // Read and evaluated afresh at its next turn.
1032
1125
  await this.put({ ...this.current(entry), phase: "done", marker: "", outcome: `submit_${why}`, submission: null, retry_at: null });
@@ -1110,6 +1203,7 @@ export class Lifecycle {
1110
1203
  throw error;
1111
1204
  if (meaningOf(error) === "refused" && !SUBMIT_AGAIN.has(error.code)) {
1112
1205
  this.log("lifecycle.submit", "refused", entry, { status: error.status, code: error.code });
1206
+ this.diagnose("lifecycle.submit", entry, error.code, error);
1113
1207
  // The task changed under it: read afresh. Anything else the server refused can't be submitted as it is.
1114
1208
  if (error.code === "version_conflict")
1115
1209
  return notSubmitted("version_conflict");
@@ -1124,8 +1218,166 @@ export class Lifecycle {
1124
1218
  // Unknown: it may have gone through. Only the same key is sent for this note, at a later pass.
1125
1219
  this.log("lifecycle.submit", "unknown", entry);
1126
1220
  }
1221
+ /**
1222
+ * A blocked run's report: a fresh read must show the task as the run left it, or nothing is sent; the agent's reason goes
1223
+ * only where sharing is allowed or the owner approved it; then `send_message`, with a key stored first and bound to the
1224
+ * note. Once it's posted, or the server refused it, a change request's task is kept and a first run's released.
1225
+ */
1226
+ async report(entry, signal) {
1227
+ if (signal.aborted)
1228
+ return;
1229
+ const key = keyOf(entry.workspace_id, entry.task_id);
1230
+ const agent = this.deps.poller.agentId;
1231
+ const consumed = entry.consumed;
1232
+ const code = entry.report?.start_failed ? "run_failed" : "run_blocked";
1233
+ const logged = (posted, status) => this.log("lifecycle.blocked", posted ? "reason_posted" : "reason_not_posted", entry, { code, ...(status === undefined ? {} : { status }) });
1234
+ const detail = await this.read(entry.workspace_id, entry.task_id);
1235
+ if (signal.aborted)
1236
+ return;
1237
+ const task = detail?.task;
1238
+ if (!detail || !task || task.assignee !== agent || task.status !== "accepted" || task.version !== entry.expected_version || detail.prompt?.hash !== consumed.input_hash) {
1239
+ // The task moved on since the run: a reason about other inputs isn't sent, and the task is read afresh.
1240
+ this.forgetWords(key);
1241
+ logged(false);
1242
+ await this.put({ ...this.current(entry), phase: "done", marker: "", outcome: task ? `blocked_task_${task.status}` : "blocked_not_readable", report: null, retry_at: null });
1243
+ return;
1244
+ }
1245
+ let rep = this.current(entry).report;
1246
+ const save = async (next) => {
1247
+ rep = next;
1248
+ await this.put({ ...this.current(entry), report: next });
1249
+ };
1250
+ // From the task as it stands: a run that answered a change request keeps the task (ruling 2). A run that never
1251
+ // started answered nothing, so its task is released as before.
1252
+ if (rep.keep === null)
1253
+ await save({ ...rep, keep: !rep.start_failed && detail.prompt.shape.change_request_event_id !== null });
1254
+ if (rep.sharing === "pending") {
1255
+ const share = await this.sharingAllowed(entry.workspace_id, consumed);
1256
+ await save({ ...rep, sharing: share ? "share" : "review", held_since: share ? null : this.now() });
1257
+ }
1258
+ const kept = this.results.get(key);
1259
+ const result = kept && kept.run_ref === entry.run_ref ? kept.result : null;
1260
+ const cleaned = result ? cleanResult(result) : null;
1261
+ if (rep.sharing === "review" && cleaned?.ok && this.now() - (rep.held_since ?? this.now()) >= REVIEW_HOLD_MS) {
1262
+ await save({ ...rep, sharing: "withheld" });
1263
+ this.log("lifecycle.review", "withheld", entry, { code: "review_hold_expired" });
1264
+ }
1265
+ if (rep.sharing === "review" && cleaned?.ok) {
1266
+ const review = this.deps.prompter.review;
1267
+ const answer = review ? await review.call(this.deps.prompter, { workspace_id: entry.workspace_id, task_id: entry.task_id, pull_request: null, summary: cleaned.summary, files: cleaned.files, redactions: cleaned.redactions, blocked: true }, signal) : "later";
1268
+ if (signal.aborted)
1269
+ return;
1270
+ this.log("lifecycle.review", answer, entry, { code: "run_blocked" });
1271
+ if (answer === "later") {
1272
+ await this.put({ ...this.current(entry), retry_at: this.now() + ASK_AGAIN_MS });
1273
+ return;
1274
+ }
1275
+ await save({ ...rep, sharing: answer === "approve" ? "approved" : "withheld" });
1276
+ }
1277
+ const words = rep.start_failed ? { kind: "withheld" } : !result || !cleaned ? { kind: "lost" } : !cleaned.ok ? { kind: "secret_hidden" } : rep.sharing === "share" || rep.sharing === "approved" ? { kind: "shared", ...cleaned } : { kind: "withheld" };
1278
+ const compose = async (k) => composeBlockedNote({ task_id: entry.task_id, keep: rep.keep === true, words, start_failed: !!rep.start_failed, reference: await referenceOf(k) });
1279
+ let note = rep.key === null ? "" : await compose(rep.key);
1280
+ if (rep.key !== null && rep.note_hash !== (await sha256Hex(new TextEncoder().encode(note)))) {
1281
+ // A note was stored and may have been sent, but its body can't be made again (the words went with a restart). It
1282
+ // is never followed by a second, contradicting one: the thread is read for its reference first.
1283
+ const scans = (rep.scans ?? 0) + 1;
1284
+ const landed = scans > MAX_NOTE_SCANS ? false : await this.noteLanded(entry, await referenceOf(rep.key));
1285
+ if (landed === "unknown") {
1286
+ // The thread couldn't be read: tried again after a wait that doubles, from 5 minutes up to an hour.
1287
+ await save({ ...rep, scans });
1288
+ await this.put({ ...this.current(entry), retry_at: this.now() + Math.min(SCAN_FIRST_WAIT_MS * 2 ** (scans - 1), SCAN_LONGEST_WAIT_MS) });
1289
+ this.log("lifecycle.blocked", "unknown", entry, { code: "note_scan_unknown", count: scans });
1290
+ return;
1291
+ }
1292
+ if (scans > MAX_NOTE_SCANS) {
1293
+ // Past its scans, a small chance of a second note is taken over a task left stuck: the fixed note goes once.
1294
+ this.log("lifecycle.blocked", "scan_given_up", entry, { code: "note_scan_exhausted", count: MAX_NOTE_SCANS });
1295
+ }
1296
+ if (landed) {
1297
+ this.forgetWords(key);
1298
+ logged(true);
1299
+ await this.finishReport(entry, rep, code, task.version);
1300
+ return;
1301
+ }
1302
+ await save({ ...rep, key: null, note_hash: null, scans: 0 });
1303
+ }
1304
+ if (rep.key === null) {
1305
+ const fresh = this.newId();
1306
+ note = await compose(fresh);
1307
+ await save({ ...rep, key: fresh, note_hash: await sha256Hex(new TextEncoder().encode(note)) });
1308
+ }
1309
+ let posted = false;
1310
+ let refused;
1311
+ for (let attempt = 0; attempt < COMMAND_TRIES; attempt++) {
1312
+ try {
1313
+ await this.deps.poller.request("send_message", { workspace_id: entry.workspace_id, task_id: entry.task_id, body: note, idempotency_key: rep.key });
1314
+ posted = true;
1315
+ break;
1316
+ }
1317
+ catch (error) {
1318
+ if (!(error instanceof GatewayError))
1319
+ throw error;
1320
+ if (meaningOf(error) === "refused") {
1321
+ // The server won't take it as it is: the task goes on without it, and the log says so.
1322
+ refused = error.status;
1323
+ break;
1324
+ }
1325
+ if (attempt + 1 < COMMAND_TRIES)
1326
+ await this.backoff(attempt, signal, error);
1327
+ if (signal.aborted)
1328
+ return;
1329
+ }
1330
+ }
1331
+ if (!posted && refused === undefined) {
1332
+ // Unknown: it may have gone through. Only the same key is sent for this note, at a later pass.
1333
+ this.log("lifecycle.blocked", "unknown", entry, { code });
1334
+ return;
1335
+ }
1336
+ this.forgetWords(key);
1337
+ logged(posted, refused);
1338
+ await this.finishReport(entry, rep, code, task.version);
1339
+ }
1340
+ /** After the report: a change request's task is kept; any other is released. */
1341
+ async finishReport(entry, rep, code, version) {
1342
+ const done = { ...this.current(entry), report: null, retry_at: null };
1343
+ if (rep.keep)
1344
+ await this.put({ ...done, phase: "done", outcome: code });
1345
+ else
1346
+ await this.giveUp(done, "accepted", code, version);
1347
+ }
1348
+ /**
1349
+ * Whether a note with this reference is on the task's thread, sent by this agent: true, false, or `unknown` when the
1350
+ * thread can't be read now. Pages are read to the end, at most `NOTE_PAGES` of them; bodies are only searched for the
1351
+ * fixed-shape reference, never read for meaning.
1352
+ */
1353
+ async noteLanded(entry, reference) {
1354
+ const agent = this.deps.poller.agentId;
1355
+ let after = null;
1356
+ for (let page = 0; page < NOTE_PAGES; page++) {
1357
+ let answer;
1358
+ try {
1359
+ answer = (await this.deps.poller.request("list_messages", { workspace_id: entry.workspace_id, task_id: entry.task_id, ...(after ? { after } : {}) }));
1360
+ }
1361
+ catch (error) {
1362
+ if (!(error instanceof GatewayError))
1363
+ throw error;
1364
+ return "unknown";
1365
+ }
1366
+ const messages = Array.isArray(answer?.messages) ? answer.messages : [];
1367
+ for (const m of messages) {
1368
+ const from = m && typeof m === "object" ? m.from : null;
1369
+ if (from?.id === agent && typeof m.body === "string" && m.body.includes(reference))
1370
+ return true;
1371
+ }
1372
+ const last = messages.at(-1)?.id;
1373
+ if (messages.length < 50 || typeof last !== "string")
1374
+ return false;
1375
+ after = last;
1376
+ }
1377
+ return "unknown";
1378
+ }
1127
1379
  async submitted(entry) {
1128
- this.results.delete(keyOf(entry.workspace_id, entry.task_id));
1380
+ this.forgetWords(keyOf(entry.workspace_id, entry.task_id));
1129
1381
  const current = this.current(entry);
1130
1382
  await this.put({ ...current, outcome: "submitted", retry_at: null, submission: { ...current.submission, state: "submitted" } });
1131
1383
  this.log("lifecycle.submit", "submitted", entry);
@@ -1195,6 +1447,24 @@ export async function runWithLifecycle(poller, lifecycle, clock, signal, bell) {
1195
1447
  }
1196
1448
  return "stopped";
1197
1449
  }
1450
+ /** Scans of a thread that couldn't be read before the fixed note is posted anyway, and the waits between them. */
1451
+ export const MAX_NOTE_SCANS = 6;
1452
+ export const SCAN_FIRST_WAIT_MS = 5 * 60 * 1000;
1453
+ export const SCAN_LONGEST_WAIT_MS = 60 * 60 * 1000;
1454
+ /** The most pages of a task's thread read to find whether a note landed. */
1455
+ const NOTE_PAGES = 40;
1456
+ /** A note's reference: a fixed-shape tag from its key, which says nothing of the key. */
1457
+ async function referenceOf(key) {
1458
+ return `rr_${(await sha256Hex(new TextEncoder().encode(`runner-report:${key}`))).slice(0, 16)}`;
1459
+ }
1460
+ /** A value that is a fixed code, or undefined. */
1461
+ const codeOf = (v) => (typeof v === "string" && /^[a-z][a-z0-9_]{0,63}$/.test(v) ? v : undefined);
1462
+ /** A failed start's cause as a code: the adapter's `start_failed:<code>`, or its own bare code; `unknown` otherwise. */
1463
+ function startCause(error) {
1464
+ const message = error instanceof Error ? error.message : "";
1465
+ const code = message.startsWith("start_failed:") ? message.slice("start_failed:".length) : message;
1466
+ return /^[a-z][a-z0-9_]{0,63}$/.test(code) ? code : "unknown";
1467
+ }
1198
1468
  const homeOf = (deps) => (deps.home === undefined ? {} : { runner_home: deps.home });
1199
1469
  /** The run policy as it stands: a function's answer read now, or the value given. A read that throws is no policy. */
1200
1470
  async function readConfig(config) {
@@ -28,7 +28,8 @@
28
28
  * request, are required, each a positive integer under a fixed ceiling, with no "none" (condition 3; spike B rulings 3
29
29
  * and 5). A configuration lacking any of them is refused whole, as is anything else malformed.
30
30
  * - **Tools and network** are facts for step 9's adapter, which enforces them: no shell and no network unless listed by
31
- * name (condition 2). The adapter's result tool is always named.
31
+ * name (condition 2). The adapter's result tool is always named. A room listing hosts is refused at load with
32
+ * `network_allowlist_unsupported` until Runner's egress proxy exists: only `"network": []` works today.
32
33
  * - **Run decisions** are bound to every run fact, by a canonical form of the whole `RunFacts` (M1 on #455's review), and
33
34
  * to the task's version, input hash, repository and base. They are single-use and expire.
34
35
  * - **The repository** (M7 step 10; L4 on #455's review): a room has one only when the owner named it here, by full name
@@ -95,6 +96,15 @@ const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
95
96
  const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
96
97
  const TLD = /^[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
97
98
  const INPUTS = ["title", "instructions", "acceptance_criteria", "change_request"];
99
+ /** A room's `network` listing hosts: refused until Runner's egress proxy exists; only `[]` works. */
100
+ export const NETWORK_UNSUPPORTED = "network_allowlist_unsupported";
101
+ /** What's wrong with a policy that failed to parse, for the owner, by where it failed. */
102
+ export function policyProblem(at) {
103
+ const network = at.match(new RegExp(`^rooms\\[\\]\\.network:${NETWORK_UNSUPPORTED}:([A-Za-z0-9_-]{1,128})$`));
104
+ if (network)
105
+ return `the room ${network[1]} lists hosts in rooms[].network, which Runner can't allow yet (${NETWORK_UNSUPPORTED}): a task's container has no egress proxy, so only "network": [] works`;
106
+ return `${at} is missing or out of range`;
107
+ }
98
108
  const fail = (at) => ({ ok: false, at });
99
109
  /**
100
110
  * A plain-data copy: null-prototype objects of own enumerable keys, arrays, strings, numbers, booleans, null. Each
@@ -237,6 +247,9 @@ function parseRoom(v, ownerOrg) {
237
247
  const network = Object.hasOwn(v, "network") ? uniqueList(v.network, MAX_HOSTS, isHost) : [];
238
248
  if (!network)
239
249
  return fail("rooms[].network");
250
+ // No sandbox can hold an allowlist until Runner's egress proxy exists: refused here, at load, not at every run's start.
251
+ if (network.length > 0)
252
+ return fail(`rooms[].network:${NETWORK_UNSUPPORTED}:${roomId}`);
240
253
  const outputs = Object.hasOwn(v, "outputs") ? v.outputs : "hold";
241
254
  if (outputs !== "hold" && outputs !== "share")
242
255
  return fail("rooms[].outputs");
@@ -112,6 +112,10 @@ export class Poller {
112
112
  throw failure;
113
113
  }
114
114
  }
115
+ /** The gateway's origin this Runner is paired with, as checked at open. */
116
+ get origin() {
117
+ return this.deps.origin;
118
+ }
115
119
  /** The Podster agent this Runner acts as. */
116
120
  get agentId() {
117
121
  return this.state.agent_id;