@hearsay-tools/squawk 0.18.0-dev.8054 → 0.18.0-dev.8063

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 (112) hide show
  1. package/dist/automations/agent-tools.d.ts +2 -0
  2. package/dist/automations/agent-tools.js +24 -0
  3. package/dist/automations/agent-tools.js.map +1 -0
  4. package/dist/automations/tool-catalog.d.ts +119 -0
  5. package/dist/automations/tool-catalog.js +48 -0
  6. package/dist/automations/tool-catalog.js.map +1 -0
  7. package/dist/automations/tool-client.d.ts +9 -0
  8. package/dist/automations/tool-client.js +19 -0
  9. package/dist/automations/tool-client.js.map +1 -0
  10. package/dist/automations/tool-env.d.ts +1 -0
  11. package/dist/automations/tool-env.js +3 -0
  12. package/dist/automations/tool-env.js.map +1 -0
  13. package/dist/automations/tool-errors.d.ts +9 -0
  14. package/dist/automations/tool-errors.js +34 -0
  15. package/dist/automations/tool-errors.js.map +1 -0
  16. package/dist/automations/tool-session.d.ts +5 -0
  17. package/dist/automations/tool-session.js +19 -0
  18. package/dist/automations/tool-session.js.map +1 -0
  19. package/dist/automations/tools.d.ts +325 -0
  20. package/dist/automations/tools.js +30 -0
  21. package/dist/automations/tools.js.map +1 -0
  22. package/dist/built-in-tool-definitions.d.ts +0 -2
  23. package/dist/built-in-tool-definitions.js +3 -35
  24. package/dist/built-in-tool-definitions.js.map +1 -1
  25. package/dist/built-in-tools.js +4 -2
  26. package/dist/built-in-tools.js.map +1 -1
  27. package/dist/built-in-wait-kinds.d.ts +2 -1
  28. package/dist/built-in-wait-kinds.js +9 -5
  29. package/dist/built-in-wait-kinds.js.map +1 -1
  30. package/dist/ci-wait/client.d.ts +0 -17
  31. package/dist/ci-wait/client.js +0 -31
  32. package/dist/ci-wait/client.js.map +1 -1
  33. package/dist/ci-wait/controller.js +1 -2
  34. package/dist/ci-wait/controller.js.map +1 -1
  35. package/dist/ci-wait/errors.d.ts +1 -14
  36. package/dist/ci-wait/errors.js +0 -68
  37. package/dist/ci-wait/errors.js.map +1 -1
  38. package/dist/ci-wait/pr-wait-kind.d.ts +65 -0
  39. package/dist/ci-wait/pr-wait-kind.js +120 -0
  40. package/dist/ci-wait/pr-wait-kind.js.map +1 -0
  41. package/dist/ci-wait/tool-catalog.d.ts +0 -263
  42. package/dist/ci-wait/tool-catalog.js +0 -58
  43. package/dist/ci-wait/tool-catalog.js.map +1 -1
  44. package/dist/ci-wait/tool-definition.d.ts +21 -0
  45. package/dist/ci-wait/tool-definition.js +9 -0
  46. package/dist/ci-wait/tool-definition.js.map +1 -0
  47. package/dist/ci-wait/tool-registry.d.ts +2 -0
  48. package/dist/ci-wait/tool-registry.js.map +1 -1
  49. package/dist/ci-wait/tools.d.ts +2 -381
  50. package/dist/ci-wait/tools.js +3 -46
  51. package/dist/ci-wait/tools.js.map +1 -1
  52. package/dist/delegation/wait-kinds.d.ts +8 -0
  53. package/dist/delegation/wait-kinds.js +317 -0
  54. package/dist/delegation/wait-kinds.js.map +1 -0
  55. package/dist/preview/agent-address.js +1 -1
  56. package/dist/preview/agent-address.js.map +1 -1
  57. package/dist/preview/agent-tools.d.ts +2 -0
  58. package/dist/preview/agent-tools.js +18 -0
  59. package/dist/preview/agent-tools.js.map +1 -0
  60. package/dist/preview/registration.js +1 -1
  61. package/dist/preview/registration.js.map +1 -1
  62. package/dist/preview/run-tools.d.ts +1 -0
  63. package/dist/preview/run-tools.js +2 -1
  64. package/dist/preview/run-tools.js.map +1 -1
  65. package/dist/preview/tool-catalog.d.ts +146 -0
  66. package/dist/preview/tool-catalog.js +14 -0
  67. package/dist/preview/tool-catalog.js.map +1 -0
  68. package/dist/preview/tool-client.d.ts +8 -0
  69. package/dist/preview/tool-client.js +16 -0
  70. package/dist/preview/tool-client.js.map +1 -0
  71. package/dist/preview/tool-env.d.ts +2 -0
  72. package/dist/preview/tool-env.js +4 -0
  73. package/dist/preview/tool-env.js.map +1 -0
  74. package/dist/preview/tool-errors.d.ts +7 -0
  75. package/dist/preview/tool-errors.js +36 -0
  76. package/dist/preview/tool-errors.js.map +1 -0
  77. package/dist/preview/tool-session.d.ts +6 -0
  78. package/dist/preview/tool-session.js +9 -0
  79. package/dist/preview/tool-session.js.map +1 -0
  80. package/dist/preview/tools.d.ts +57 -0
  81. package/dist/preview/tools.js +18 -0
  82. package/dist/preview/tools.js.map +1 -0
  83. package/dist/serve-command.d.ts +1 -1
  84. package/dist/serve-command.js +1 -1
  85. package/dist/server/preview-cdp-socket.js +1 -1
  86. package/dist/server/preview-socket.js +1 -1
  87. package/dist/workflows/run/compose.js +2 -2
  88. package/dist/workflows/run/compose.js.map +1 -1
  89. package/dist/workflows/run/squawk-tools.d.ts +6 -9
  90. package/dist/workflows/run/squawk-tools.js +8 -18
  91. package/dist/workflows/run/squawk-tools.js.map +1 -1
  92. package/dist/workflows/run/wait-engine.d.ts +23 -37
  93. package/dist/workflows/run/wait-engine.js +100 -212
  94. package/dist/workflows/run/wait-engine.js.map +1 -1
  95. package/dist/workflows/run/wait-kind-registry.d.ts +78 -2
  96. package/dist/workflows/run/wait-kind-registry.js.map +1 -1
  97. package/dist/workflows/run/wait-kinds.d.ts +390 -1011
  98. package/dist/workflows/run/wait-kinds.js +71 -188
  99. package/dist/workflows/run/wait-kinds.js.map +1 -1
  100. package/dist/workflows/run/wait-registration.d.ts +7 -0
  101. package/dist/workflows/run/wait-registration.js +2 -0
  102. package/dist/workflows/run/wait-registration.js.map +1 -1
  103. package/dist/workflows/run/wait-registry.d.ts +26 -36
  104. package/dist/workflows/run/wait-registry.js +71 -160
  105. package/dist/workflows/run/wait-registry.js.map +1 -1
  106. package/dist/workflows/waits.d.ts +2 -2
  107. package/dist/workflows/waits.js +2 -2
  108. package/dist/workflows/waits.js.map +1 -1
  109. package/package.json +4 -4
  110. package/dist/ci-wait/tool-env.d.ts +0 -4
  111. package/dist/ci-wait/tool-env.js +0 -11
  112. package/dist/ci-wait/tool-env.js.map +0 -1
@@ -1,19 +1,19 @@
1
+ import { type WaitFeatureServices } from './wait-kind-registry.ts';
1
2
  import type { Wait, WaitErrorCode, AskErrorCode, WorkerWaitEntry } from '../../contract/index.js';
2
3
  import type { ActiveRun } from '../active-run.ts';
3
4
  import type { RunModuleContext } from './types.ts';
4
5
  import type { RunRecord } from '../../runs/store.ts';
5
- import type { CiWatcherSupervisor } from '../../ci-wait/supervisor.ts';
6
6
  import { ProcessWaitSupervisor } from '../../process-wait/supervisor.ts';
7
7
  import type { ExitFileRoots } from '../../process-wait/exit-file.ts';
8
8
  import { type WaitResult } from '../waits.ts';
9
9
  import { type RegistrationIdentity } from './wait-registration.ts';
10
10
  export declare function warnRegistrationRefused(code: WaitErrorCode | AskErrorCode): void;
11
11
  /** What the engine asks the rest of the run manager (ADR 0053): wake admission, the run line,
12
- * the family reconcile, human waits and the subagent session. */
13
- export interface WaitEngineHost {
12
+ * the family reconcile, human waits and the subagent session. Feature wait kinds add their own
13
+ * services through `WaitFeatureServices`. */
14
+ export interface WaitEngineHost extends WaitFeatureServices {
14
15
  active(id: string): ActiveRun | undefined;
15
16
  canProceedWithRun(id: string, run: RunRecord | undefined): run is RunRecord;
16
- ciSupervisor(): Pick<CiWatcherSupervisor, 'resolve' | 'watch' | 'close'>;
17
17
  reconcileWorkerWaits(family?: string): void;
18
18
  noticeParkedWorkers(id: string): void;
19
19
  withdrawSquawkHumanWaits(id: string): void;
@@ -69,24 +69,21 @@ export declare class WaitEngine {
69
69
  private readonly host;
70
70
  private readonly maxAutoContinues;
71
71
  private readonly processSupervisor;
72
- /** One CI watch per open CI wait, keyed by wait id. */
73
- private readonly ciWatches;
74
72
  /** A resolution whose checkpoint failed, retried by wait id. */
75
- private readonly ciRetries;
76
- /** Process waits' watches (hearsay-tools/cezarion#1446), by wait id. */
77
- private readonly processWatches;
78
- private readonly customWatches;
73
+ private readonly settleRetries;
74
+ /** Each armed wait's watch, by wait id: the context its row's lifecycle reads, and the signal
75
+ * the engine aborts when it disarms the wait. */
76
+ private readonly armedWatches;
79
77
  private readonly workerResolveRetries;
80
- /** One timer per open timer wait, keyed by wait id. */
78
+ /** One timer per wait with an armed deadline, keyed by wait id. */
81
79
  private readonly waitTimers;
82
- /** The watch adapter each row names. */
83
- private readonly watches;
84
80
  constructor(context: RunModuleContext, host: WaitEngineHost, maxAutoContinues: number, processSupervisor?: Pick<ProcessWaitSupervisor, 'watch' | 'close'>);
85
81
  /** Whether the run's open-wait list has room. Each caller keeps its own refusal shape. */
86
82
  hasRoom(run: Pick<RunRecord, 'waits'>): boolean;
87
83
  /** Commit, arm and (at a boundary) park on a newly registered wait. A wait opened with the
88
84
  * result its caller already holds arms nothing and resolves with it after the park. */
89
85
  open<W extends Wait>(runId: string, state: ActiveRun | undefined, wait: W, options: OpenOptions): OpenResult<W>;
86
+ /** A row's open hook replaces the arm a newly opened wait takes. */
90
87
  private armOpened;
91
88
  /**
92
89
  * Commit a changed open wait, then arm it. A moved deadline disarms the old one first; an
@@ -97,10 +94,10 @@ export declare class WaitEngine {
97
94
  log: string;
98
95
  }): boolean;
99
96
  private commitOpened;
100
- /** A worker wait the family reconcile already resolved is no longer listed, and parks nothing. */
97
+ /** A wait its open hook already settled is no longer listed, and parks nothing. */
101
98
  private park;
102
99
  /** The entry as recorded now: the store keeps the entry it was given, and only its phase can
103
- * have moved since. A worker wait with a deadline may already be settled by the reconcile. */
100
+ * have moved since. A row's lookup can read a wait its open hook already settled. */
104
101
  private openedEntry;
105
102
  /** Where a process wait's exit file may sit: the run's worktree (the checkout for a run without
106
103
  * one) and, unless turned off, the Squawk temp directory its agent gets as `TMPDIR`. */
@@ -1254,30 +1251,20 @@ export declare class WaitEngine {
1254
1251
  }[];
1255
1252
  } | undefined;
1256
1253
  } | undefined): ExitFileRoots;
1257
- /** Start what resolves an open wait: the watch adapter its row names. An overdue deadline
1258
- * (restart) resolves at once. */
1254
+ /** Start what resolves an open wait: the lifecycle its row registers. An overdue deadline
1255
+ * (restart) resolves at once. A plugin kind's arm runs once per watch; a built-in kind's
1256
+ * own guard keeps it idempotent across refreshes and recovery. */
1259
1257
  private armWait;
1260
- private customWatchContext;
1261
- /** A timer, peer or subagent deadline. Native subagents live only in their session: with none,
1262
- * as at a restart, they stopped (hearsay-tools/cezarion#2431). At its deadline a lost session
1263
- * reads the same. */
1258
+ /** The wait's watch context: the armed one, now reading this entry, or a new one. */
1259
+ private watchContext;
1260
+ /** The wait's one timer. A newer timer clears the previous one, and disarm clears the current one. */
1261
+ private armTimer;
1262
+ /** A timer, peer or subagent deadline. A stopping, stopped or finishing run takes no
1263
+ * self-generated wake: the wait stays open for that transition to cancel, as the monitoring
1264
+ * timer did before it was a wait. */
1264
1265
  private armDeadline;
1265
- /**
1266
- * A worker wait's deadline re-observes its family (hearsay-tools/cezarion#1235): the reconcile
1267
- * resolves it with `timeout`, keeping any outcome observed by then. A failed checkpoint is
1268
- * retried every second while the wait is still open, never dropped as an uncaught error. An
1269
- * outcome whose resolution failed to commit arms the same retry with `firstDelay` 1 second.
1270
- */
1271
- private armWorkerDeadline;
1272
1266
  /** Stop everything that could still resolve this wait. */
1273
1267
  private disarmWait;
1274
- /**
1275
- * Watch a process wait's command (hearsay-tools/cezarion#1446). Like a timer, its wake is the
1276
- * agent's own arrangement: a stopping, stopped or finishing run takes none, and the wait stays
1277
- * open for that transition to cancel.
1278
- */
1279
- private startProcessWatch;
1280
- private startCiWatch;
1281
1268
  /** `resolveWait`, retried while its durable checkpoint is unavailable: a failed write may not
1282
1269
  * drop the accepted intent or publish a false result. */
1283
1270
  settleWait(runId: string, waitId: string, result?: WaitResult): void;
@@ -1290,8 +1277,7 @@ export declare class WaitEngine {
1290
1277
  dispose(): void;
1291
1278
  /** The open peer waits of these runs whose named peer already wrote, settled or was deleted resolve now. */
1292
1279
  resolvePeerWaits(runIds: readonly string[]): void;
1293
- /** Like a timer, the wake is the agent's own arrangement: a stopping or finishing run takes none,
1294
- * and the wait stays for that transition to cancel. True when the wait is no longer open. */
1280
+ /** The wait's row re-observes its target now. True when the wait is no longer open. */
1295
1281
  private resolvePeerWait;
1296
1282
  /** Commit an open wait as resolved together with its lifecycle input (id = wait id, or an
1297
1283
  * upgraded worker wait's `wakeInputId`), then queue the run's wake. A worker wait passes the
@@ -1,14 +1,11 @@
1
1
  import { waitKindForWait, registeredWaitKinds } from './wait-kind-registry.js';
2
- import { ciWaitResultSchema } from '../../contract/index.js';
3
2
  import { recordedDirectory } from '../../runs/shared-hosts.js';
4
3
  import { assertWaitCapacity, WaitCapacityError } from '../../runs/wait-capacity.js';
5
4
  import { waitErrorMessage } from '../../ci-wait/errors.js';
6
5
  import { ProcessWaitSupervisor } from '../../process-wait/supervisor.js';
7
6
  import { agentTmpDirEnabled, resolveAgentTmpDir } from '../../runs/agent-tmpdir.js';
8
- import { peerWaitResult } from '../wait-scope.js';
9
- import { chargesBudget, openWaits, waitInputId, waitResultText, settledWaitEntry, ciWatchRequest } from '../waits.js';
10
- import { familyOf } from './run-guards.js';
11
- import { WAIT_KINDS, waitPolicyForWait } from './wait-kinds.js';
7
+ import { chargesBudget, openWaits, waitInputId, waitResultText, settledWaitEntry } from '../waits.js';
8
+ import { WAIT_KINDS } from './wait-kinds.js';
12
9
  import { registrationReceipt } from './wait-registration.js';
13
10
  import { watchDeadline } from './wait-watches.js';
14
11
  export function warnRegistrationRefused(code) {
@@ -22,30 +19,14 @@ export class WaitEngine {
22
19
  host;
23
20
  maxAutoContinues;
24
21
  processSupervisor;
25
- /** One CI watch per open CI wait, keyed by wait id. */
26
- ciWatches = new Map();
27
22
  /** A resolution whose checkpoint failed, retried by wait id. */
28
- ciRetries = new Map();
29
- /** Process waits' watches (hearsay-tools/cezarion#1446), by wait id. */
30
- processWatches = new Map();
31
- customWatches = new Map();
23
+ settleRetries = new Map();
24
+ /** Each armed wait's watch, by wait id: the context its row's lifecycle reads, and the signal
25
+ * the engine aborts when it disarms the wait. */
26
+ armedWatches = new Map();
32
27
  workerResolveRetries = new Set();
33
- /** One timer per open timer wait, keyed by wait id. */
28
+ /** One timer per wait with an armed deadline, keyed by wait id. */
34
29
  waitTimers = new Map();
35
- /** The watch adapter each row names. */
36
- watches = {
37
- ci: (runId, wait) => this.startCiWatch(runId, wait),
38
- process: (runId, wait) => this.startProcessWatch(runId, wait),
39
- // Only the user's answer, or a cancel, ends a human wait: nothing to arm.
40
- none: () => { },
41
- worker: (runId, wait) => { if (!this.waitTimers.has(wait.id))
42
- this.armWorkerDeadline(runId, wait); },
43
- timer: (runId, wait) => this.armDeadline(runId, wait, false),
44
- // A peer that already wrote or settled resolves it first, at registration and recovery alike.
45
- peer: (runId, wait) => { if (!this.waitTimers.has(wait.id) && !this.resolvePeerWait(runId, wait))
46
- this.armDeadline(runId, wait, false); },
47
- subagent: (runId, wait) => this.armDeadline(runId, wait, true),
48
- };
49
30
  constructor(context, host, maxAutoContinues, processSupervisor = new ProcessWaitSupervisor()) {
50
31
  this.context = context;
51
32
  this.host = host;
@@ -72,31 +53,26 @@ export class WaitEngine {
72
53
  if (!this.commitOpened(runId, wait, options.onCommitFailure, options.receipt))
73
54
  return { status: 'refused' };
74
55
  const settled = 'result' in options;
75
- if (!settled)
76
- this.armOpened(runId, wait);
77
56
  const hooks = waitKindForWait(wait)?.lifecycle;
57
+ if (!settled)
58
+ this.armOpened(runId, wait, hooks);
78
59
  if (hooks?.postOpen && this.context.store.getRun(runId)?.waits?.some(entry => entry.id === wait.id && entry.phase === 'open')) {
79
- hooks.postOpen(this.customWatchContext(runId, wait));
60
+ hooks.postOpen(this.watchContext(runId, wait));
80
61
  }
81
62
  if (options.park)
82
- this.park(runId, state, wait);
63
+ this.park(runId, state, wait, hooks);
83
64
  // The answer is the wait as opened, even when the result resolves it at once.
84
65
  const opened = this.openedEntry(runId, wait);
85
66
  if (settled)
86
67
  this.settleWait(runId, wait.id, options.result);
87
68
  return { status: 'opened', wait: opened };
88
69
  }
89
- armOpened(runId, wait) {
90
- if (waitPolicyForWait(wait).watch !== 'worker') {
70
+ /** A row's open hook replaces the arm a newly opened wait takes. */
71
+ armOpened(runId, wait, hooks) {
72
+ if (hooks?.open)
73
+ hooks.open(this.watchContext(runId, wait));
74
+ else
91
75
  this.armWait(runId, wait);
92
- return;
93
- }
94
- const run = this.context.store.getRun(runId);
95
- // Outcomes already in resolve it now (or, with every worker destroyed, cancel it); the rest arm it.
96
- this.host.reconcileWorkerWaits(familyOf(run));
97
- // A worker that parked before this wait opened tells the parent now (hearsay-tools/cezarion#1327).
98
- // Squawk's completion wait tells its own workers; an agent's wait tells its family.
99
- this.host.noticeParkedWorkers(wait.source === 'cezar' ? runId : familyOf(run));
100
76
  }
101
77
  /**
102
78
  * Commit a changed open wait, then arm it. A moved deadline disarms the old one first; an
@@ -136,26 +112,22 @@ export class WaitEngine {
136
112
  throw Object.assign(new Error(waitErrorMessage('persistence')), { code: 'persistence' });
137
113
  }
138
114
  }
139
- /** A worker wait the family reconcile already resolved is no longer listed, and parks nothing. */
140
- park(runId, state, wait) {
115
+ /** A wait its open hook already settled is no longer listed, and parks nothing. */
116
+ park(runId, state, wait, hooks) {
141
117
  if (!state)
142
118
  return;
143
- if (waitPolicyForWait(wait).watch === 'worker' && !this.context.store.getRun(runId)?.waits?.some(entry => entry.id === wait.id))
119
+ if (hooks?.parkOnlyWhileListed && !this.context.store.getRun(runId)?.waits?.some(entry => entry.id === wait.id))
144
120
  return;
145
121
  if (state.boundary.atTurnBoundary === state.liveSession.session || this.host.isParked(runId))
146
122
  this.host.parkOnWaits(runId, state);
147
123
  }
148
124
  /** The entry as recorded now: the store keeps the entry it was given, and only its phase can
149
- * have moved since. A worker wait with a deadline may already be settled by the reconcile. */
125
+ * have moved since. A row's lookup can read a wait its open hook already settled. */
150
126
  openedEntry(runId, wait) {
151
127
  const latest = this.context.store.getRun(runId);
152
128
  const lookup = waitKindForWait(wait)?.lifecycle?.openedEntry;
153
129
  if (lookup)
154
130
  return lookup(wait, [...latest?.waits ?? [], ...latest?.lastWaits ?? []]);
155
- if (waitPolicyForWait(wait).watch === 'worker') {
156
- return WAIT_KINDS.worker.select([...latest?.waits ?? [], ...latest?.lastWaits ?? []])
157
- .find(entry => entry.id === wait.id && WAIT_KINDS.worker.hasDeadline(entry)) ?? wait;
158
- }
159
131
  return latest?.waits?.find(entry => entry.id === wait.id) ?? wait;
160
132
  }
161
133
  /** Where a process wait's exit file may sit: the run's worktree (the checkout for a run without
@@ -163,8 +135,9 @@ export class WaitEngine {
163
135
  exitFileRoots(runId, run = this.context.store.getRun(runId)) {
164
136
  return { worktree: recordedDirectory(run, this.context.repoRoot), ...(agentTmpDirEnabled() ? { tmpDir: resolveAgentTmpDir(this.context.dataDir, runId) } : {}) };
165
137
  }
166
- /** Start what resolves an open wait: the watch adapter its row names. An overdue deadline
167
- * (restart) resolves at once. */
138
+ /** Start what resolves an open wait: the lifecycle its row registers. An overdue deadline
139
+ * (restart) resolves at once. A plugin kind's arm runs once per watch; a built-in kind's
140
+ * own guard keeps it idempotent across refreshes and recovery. */
168
141
  armWait(runId, wait) {
169
142
  if (this.context.disposed() || wait.phase !== 'open')
170
143
  return;
@@ -173,199 +146,122 @@ export class WaitEngine {
173
146
  console.warn(`[hsq] no wait adapter registered for plugin kind ${wait.pluginKind}; retaining wait ${wait.id}`);
174
147
  return;
175
148
  }
176
- if (row?.lifecycle?.arm) {
177
- if (this.customWatches.has(wait.id))
178
- return;
179
- row.lifecycle.arm(this.customWatchContext(runId, wait));
149
+ // Only the user's answer, or a cancel, ends a wait without an arm hook: nothing to arm.
150
+ if (!row?.lifecycle?.arm || (row.isPlugin && this.armedWatches.get(wait.id)?.armed))
180
151
  return;
181
- }
182
- this.watches[waitPolicyForWait(wait).watch](runId, wait);
152
+ const context = this.watchContext(runId, wait);
153
+ this.armedWatches.get(wait.id).armed = true;
154
+ row.lifecycle.arm(context);
183
155
  }
184
- customWatchContext(runId, wait) {
185
- const current = this.customWatches.get(wait.id);
186
- if (current)
156
+ /** The wait's watch context: the armed one, now reading this entry, or a new one. */
157
+ watchContext(runId, wait) {
158
+ const current = this.armedWatches.get(wait.id);
159
+ if (current) {
160
+ current.context.wait = wait;
187
161
  return current.context;
162
+ }
188
163
  const abort = new AbortController();
189
- const context = { runId, store: this.context.store, host: this.host, wait, signal: abort.signal, resolve: result => {
190
- if (abort.signal.aborted || this.context.disposed() || this.customWatches.get(wait.id)?.context !== context)
191
- return;
192
- this.settleWait(runId, wait.id, result);
193
- } };
194
- this.customWatches.set(wait.id, { context, abort });
164
+ const isCurrent = () => !abort.signal.aborted && !this.context.disposed() && this.armedWatches.get(wait.id)?.context === context;
165
+ const context = {
166
+ runId, store: this.context.store, host: this.host, wait, signal: abort.signal,
167
+ resolve: result => { if (isCurrent())
168
+ this.settleWait(runId, wait.id, result); },
169
+ disposed: () => this.context.disposed(),
170
+ deadlineArmed: () => this.waitTimers.has(wait.id),
171
+ armTimer: (delay, due) => { if (isCurrent())
172
+ this.armTimer(runId, context.wait, delay, () => { if (isCurrent())
173
+ due(); }); },
174
+ armDeadline: (due = () => context.resolve()) => { if (isCurrent())
175
+ this.armDeadline(runId, context.wait, () => { if (isCurrent())
176
+ due(); }); },
177
+ processes: this.processSupervisor,
178
+ exitFileRoots: () => this.exitFileRoots(runId),
179
+ };
180
+ this.armedWatches.set(wait.id, { context, abort, armed: false });
195
181
  return context;
196
182
  }
197
- /** A timer, peer or subagent deadline. Native subagents live only in their session: with none,
198
- * as at a restart, they stopped (hearsay-tools/cezarion#2431). At its deadline a lost session
199
- * reads the same. */
200
- armDeadline(runId, wait, subagent) {
201
- if (this.waitTimers.has(wait.id))
202
- return;
203
- const interrupted = () => subagent && !this.host.subagentSessionLive(runId);
204
- if (interrupted()) {
205
- this.host.interruptSubagentWait(runId, wait.id);
183
+ /** The wait's one timer. A newer timer clears the previous one, and disarm clears the current one. */
184
+ armTimer(runId, wait, delay, due) {
185
+ const previous = this.waitTimers.get(wait.id);
186
+ if (previous)
187
+ clearTimeout(previous.timer);
188
+ const timer = watchDeadline({ deadline: 'deadline' in wait ? wait.deadline : undefined, delay }, deadlineSignal, () => {
189
+ if (this.waitTimers.get(wait.id)?.timer !== timer)
190
+ return;
191
+ this.waitTimers.delete(wait.id);
192
+ due();
193
+ });
194
+ this.waitTimers.set(wait.id, { runId, timer });
195
+ }
196
+ /** A timer, peer or subagent deadline. A stopping, stopped or finishing run takes no
197
+ * self-generated wake: the wait stays open for that transition to cancel, as the monitoring
198
+ * timer did before it was a wait. */
199
+ armDeadline(runId, wait, due) {
200
+ if (this.waitTimers.has(wait.id) || !('deadline' in wait) || wait.deadline === undefined)
206
201
  return;
207
- }
208
- // A stopping, stopped or finishing run takes no self-generated wake: the timer stays open
209
- // for that transition to cancel, as the monitoring timer did before it was a wait.
210
202
  const fire = () => {
211
203
  const run = this.context.store.getRun(runId);
212
204
  if (!this.host.canProceedWithRun(runId, run))
213
205
  return;
214
- if (interrupted())
215
- this.host.interruptSubagentWait(runId, wait.id);
216
- else
217
- this.settleWait(runId, wait.id);
206
+ due();
218
207
  };
219
- const deadline = wait.deadline;
220
- const due = Date.parse(deadline) - Date.now();
221
- if (due <= 0) {
208
+ const delay = Date.parse(wait.deadline) - Date.now();
209
+ if (delay <= 0) {
222
210
  fire();
223
211
  return;
224
212
  }
225
- const timer = watchDeadline({ deadline, delay: due }, deadlineSignal, () => {
226
- if (this.waitTimers.get(wait.id)?.timer !== timer)
227
- return;
228
- this.waitTimers.delete(wait.id);
229
- fire();
230
- });
231
- this.waitTimers.set(wait.id, { runId, timer });
232
- }
233
- /**
234
- * A worker wait's deadline re-observes its family (hearsay-tools/cezarion#1235): the reconcile
235
- * resolves it with `timeout`, keeping any outcome observed by then. A failed checkpoint is
236
- * retried every second while the wait is still open, never dropped as an uncaught error. An
237
- * outcome whose resolution failed to commit arms the same retry with `firstDelay` 1 second.
238
- */
239
- armWorkerDeadline(runId, wait, firstDelay) {
240
- // A deadline-less (Squawk completion) wait ends only when its workers settle (hearsay-tools/cezarion#1301).
241
- if (firstDelay === undefined && wait.deadline === undefined)
242
- return;
243
- const run = this.context.store.getRun(runId);
244
- if (!run)
245
- return;
246
- const family = familyOf(run);
247
- let warned = false;
248
- const arm = (delay) => {
249
- const timer = watchDeadline({ deadline: wait.deadline, delay }, deadlineSignal, () => {
250
- if (this.waitTimers.get(wait.id)?.timer !== timer)
251
- return;
252
- this.waitTimers.delete(wait.id);
253
- try {
254
- this.host.reconcileWorkerWaits(family);
255
- }
256
- catch {
257
- if (!warned)
258
- console.warn(`[hsq] worker wait checkpoint failed; retrying in 1 second`);
259
- warned = true;
260
- if (!this.context.disposed() && this.context.store.getRun(runId)?.waits?.some(entry => entry.id === wait.id && entry.phase === 'open'))
261
- arm(1_000);
262
- }
263
- });
264
- this.waitTimers.set(wait.id, { runId, timer });
265
- };
266
- arm(Math.max(0, firstDelay ?? Date.parse(wait.deadline) - Date.now()));
213
+ this.armTimer(runId, wait, delay, fire);
267
214
  }
268
215
  /** Stop everything that could still resolve this wait. */
269
216
  disarmWait(waitId) {
270
- const custom = this.customWatches.get(waitId);
271
- if (custom) {
272
- custom.abort.abort();
273
- this.customWatches.delete(waitId);
274
- waitKindForWait(custom.context.wait)?.lifecycle?.disarm?.(custom.context);
217
+ const watch = this.armedWatches.get(waitId);
218
+ if (watch) {
219
+ watch.abort.abort();
220
+ this.armedWatches.delete(waitId);
275
221
  }
276
- this.ciWatches.get(waitId)?.abort.abort();
277
- this.ciWatches.delete(waitId);
278
222
  const timer = this.waitTimers.get(waitId);
279
223
  if (timer)
280
224
  clearTimeout(timer.timer);
281
225
  this.waitTimers.delete(waitId);
282
- const retry = this.ciRetries.get(waitId);
226
+ const retry = this.settleRetries.get(waitId);
283
227
  if (retry)
284
228
  clearTimeout(retry.timer);
285
- this.ciRetries.delete(waitId);
229
+ this.settleRetries.delete(waitId);
286
230
  this.workerResolveRetries.delete(waitId);
287
- this.processWatches.get(waitId)?.abort.abort();
288
- this.processWatches.delete(waitId);
289
- }
290
- /**
291
- * Watch a process wait's command (hearsay-tools/cezarion#1446). Like a timer, its wake is the
292
- * agent's own arrangement: a stopping, stopped or finishing run takes none, and the wait stays
293
- * open for that transition to cancel.
294
- */
295
- startProcessWatch(runId, wait) {
296
- if (this.processWatches.has(wait.id))
297
- return;
298
- const abort = new AbortController();
299
- const watch = { runId, abort };
300
- this.processWatches.set(wait.id, watch);
301
- const settle = (result) => {
302
- if (this.context.disposed() || abort.signal.aborted || this.processWatches.get(wait.id) !== watch)
303
- return;
304
- this.processWatches.delete(wait.id);
305
- const run = this.context.store.getRun(runId);
306
- if (!this.host.canProceedWithRun(runId, run))
307
- return;
308
- this.settleWait(runId, wait.id, result);
309
- };
310
- const request = { pid: wait.pid, deadline: wait.deadline, roots: this.exitFileRoots(runId),
311
- ...(wait.startToken === undefined ? {} : { startToken: wait.startToken }), ...(wait.exitFile === undefined ? {} : { exitFile: wait.exitFile }) };
312
- void this.processSupervisor.watch(request, abort.signal).then(settle, (error) => settle({ outcome: 'error', observedAt: new Date().toISOString(),
313
- diagnostic: (error instanceof Error ? error.message : String(error)).slice(0, 512) }));
314
- }
315
- startCiWatch(runId, wait) {
316
- if (this.ciWatches.has(wait.id))
317
- return;
318
- const abort = new AbortController();
319
- const watch = { runId, abort };
320
- this.ciWatches.set(wait.id, watch);
321
- const current = () => !this.context.disposed() && !abort.signal.aborted && this.ciWatches.get(wait.id) === watch;
322
- const settle = (result) => {
323
- if (!current())
324
- return;
325
- const parsed = ciWaitResultSchema.safeParse(result);
326
- const validated = parsed.success ? parsed.data : { outcome: 'error', headSha: wait.headSha,
327
- observedAt: new Date().toISOString(), checks: [], totalChecks: 0, truncated: false,
328
- diagnostic: 'CI watcher returned an invalid observation; inspect the PR and register a new wait.' };
329
- this.ciWatches.delete(wait.id);
330
- this.settleWait(runId, wait.id, validated);
331
- };
332
- void this.host.ciSupervisor().watch(ciWatchRequest(wait), abort.signal).then(settle, () => settle({ outcome: 'error', headSha: wait.headSha,
333
- observedAt: new Date().toISOString(), checks: [], totalChecks: 0, truncated: false,
334
- diagnostic: 'CI watcher unavailable; inspect the pull request and retry the wait.' }));
231
+ if (watch) {
232
+ try {
233
+ waitKindForWait(watch.context.wait)?.lifecycle?.disarm?.(watch.context);
234
+ }
235
+ catch (error) {
236
+ console.warn(`[hsq] wait disarm hook failed: ${error instanceof Error ? error.message : String(error)}`);
237
+ }
238
+ }
335
239
  }
336
240
  /** `resolveWait`, retried while its durable checkpoint is unavailable: a failed write may not
337
241
  * drop the accepted intent or publish a false result. */
338
242
  settleWait(runId, waitId, result) {
339
- if (this.context.disposed())
243
+ if (this.context.disposed() || this.settleRetries.has(waitId))
340
244
  return;
341
245
  try {
342
246
  this.resolveWait(runId, waitId, result);
343
247
  }
344
248
  catch {
345
- if (this.ciRetries.has(waitId))
346
- return;
347
249
  console.warn(`[hsq] wait checkpoint unavailable; retaining result for retry.`);
348
- const timer = setTimeout(() => { this.ciRetries.delete(waitId); this.settleWait(runId, waitId, result); }, 1000);
250
+ const timer = setTimeout(() => { this.settleRetries.delete(waitId); this.settleWait(runId, waitId, result); }, 1000);
349
251
  timer.unref();
350
- this.ciRetries.set(waitId, { runId, timer });
252
+ this.settleRetries.set(waitId, { runId, timer });
351
253
  }
352
254
  }
353
255
  disarmRun(runId) {
354
- for (const [id, watch] of this.customWatches)
256
+ for (const [id, watch] of this.armedWatches)
355
257
  if (watch.context.runId === runId)
356
258
  this.disarmWait(id);
357
- for (const [id, watch] of this.ciWatches)
358
- if (watch.runId === runId)
359
- this.disarmWait(id);
360
259
  for (const [id, entry] of this.waitTimers)
361
260
  if (entry.runId === runId)
362
261
  this.disarmWait(id);
363
- for (const [id, retry] of this.ciRetries)
262
+ for (const [id, retry] of this.settleRetries)
364
263
  if (retry.runId === runId)
365
264
  this.disarmWait(id);
366
- for (const [id, watch] of this.processWatches)
367
- if (watch.runId === runId)
368
- this.disarmWait(id);
369
265
  }
370
266
  /** Re-arm the caller's recovery snapshot. Do not re-read between waits: an overdue
371
267
  * deadline can resolve synchronously, but the remaining snapshot entries still arm. */
@@ -374,19 +270,16 @@ export class WaitEngine {
374
270
  this.armWait(run.id, wait);
375
271
  }
376
272
  disposeWatches() {
377
- for (const id of this.customWatches.keys())
273
+ for (const id of this.armedWatches.keys())
378
274
  this.disarmWait(id);
379
275
  for (const row of registeredWaitKinds())
380
276
  row.lifecycle?.dispose?.();
381
- for (const task of this.ciWatches.values())
382
- task.abort.abort();
383
277
  this.processSupervisor.close();
384
- this.ciWatches.clear();
385
278
  }
386
279
  disposeRetries() {
387
- for (const retry of this.ciRetries.values())
280
+ for (const retry of this.settleRetries.values())
388
281
  clearTimeout(retry.timer);
389
- this.ciRetries.clear();
282
+ this.settleRetries.clear();
390
283
  }
391
284
  dispose() {
392
285
  for (const entry of this.waitTimers.values())
@@ -399,16 +292,11 @@ export class WaitEngine {
399
292
  for (const wait of WAIT_KINDS.peer.select(openWaits(this.context.store.getRun(id) ?? {})))
400
293
  this.resolvePeerWait(id, wait);
401
294
  }
402
- /** Like a timer, the wake is the agent's own arrangement: a stopping or finishing run takes none,
403
- * and the wait stays for that transition to cancel. True when the wait is no longer open. */
295
+ /** The wait's row re-observes its target now. True when the wait is no longer open. */
404
296
  resolvePeerWait(runId, wait) {
405
- const run = this.context.store.getRun(runId);
406
- if (this.context.disposed() || !this.host.canProceedWithRun(runId, run))
297
+ if (this.context.disposed())
407
298
  return false;
408
- const result = peerWaitResult(run, wait, this.context.store);
409
- if (result)
410
- this.settleWait(runId, wait.id, result);
411
- return !!result && this.context.store.getRun(runId)?.waits?.find(entry => entry.id === wait.id)?.phase !== 'open';
299
+ return waitKindForWait(wait)?.lifecycle?.reconcile?.(this.watchContext(runId, wait)) ?? false;
412
300
  }
413
301
  /** Commit an open wait as resolved together with its lifecycle input (id = wait id, or an
414
302
  * upgraded worker wait's `wakeInputId`), then queue the run's wake. A worker wait passes the
@@ -430,7 +318,7 @@ export class WaitEngine {
430
318
  const input = { id: waitInputId(settled), parentRunId: runId, source: 'lifecycle', createdAt: resolvedAt,
431
319
  text: waitResultText(settled, { workerStatus: this.workerStatus }) };
432
320
  this.context.store.commitWait(runId, settled, input);
433
- if (this.customWatches.has(waitId))
321
+ if (this.armedWatches.has(waitId))
434
322
  this.disarmWait(waitId);
435
323
  try {
436
324
  this.host.queueWaitWake(runId);
@@ -452,7 +340,7 @@ export class WaitEngine {
452
340
  console.warn(`[hsq] worker wait checkpoint failed; retrying in 1 second`);
453
341
  this.disarmWait(entry.id);
454
342
  this.workerResolveRetries.add(entry.id);
455
- this.armWorkerDeadline(runId, entry, 1_000);
343
+ waitKindForWait(entry)?.lifecycle?.rearm?.(this.watchContext(runId, entry), 1_000);
456
344
  return false;
457
345
  }
458
346
  this.disarmWait(entry.id);