pi-better-background-tasks 0.13.0 → 0.14.0

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 (47) hide show
  1. package/README.md +131 -4
  2. package/package.json +3 -1
  3. package/src/adapter-contract.ts +16 -2
  4. package/src/batch.ts +108 -0
  5. package/src/delivery-observer.ts +42 -0
  6. package/src/goal-provider.ts +72 -5
  7. package/src/index.ts +39 -0
  8. package/src/navigator-provider.ts +175 -6
  9. package/src/observed-waits.ts +3677 -0
  10. package/src/output.ts +22 -2
  11. package/src/process.ts +100 -1
  12. package/src/runtime.ts +189 -10
  13. package/src/sandbox.ts +276 -2
  14. package/src/shared-callback-batcher.ts +18 -1
  15. package/src/shared-execution-policy.ts +2 -0
  16. package/src/shared-failure-observations.ts +78 -24
  17. package/src/shared-log-utils.ts +277 -31
  18. package/src/shared-operation-coordinator/index.ts +113 -0
  19. package/src/shared-operation-coordinator/src/errors.ts +75 -0
  20. package/src/shared-operation-coordinator/src/operations.ts +376 -0
  21. package/src/shared-operation-coordinator/src/outbox.ts +431 -0
  22. package/src/shared-operation-coordinator/src/rows.ts +439 -0
  23. package/src/shared-operation-coordinator/src/schema.ts +244 -0
  24. package/src/shared-operation-coordinator/src/sqlite.ts +239 -0
  25. package/src/shared-operation-coordinator/src/store.ts +397 -0
  26. package/src/shared-operation-coordinator/src/types.ts +648 -0
  27. package/src/shared-operation-coordinator/src/validate.ts +239 -0
  28. package/src/shared-operation-coordinator/src/waits.ts +1378 -0
  29. package/src/stall.ts +4 -1
  30. package/src/supervisor/README.md +111 -0
  31. package/src/supervisor/emit-runner.mjs +101 -0
  32. package/src/supervisor/generated/conditions.mjs +96 -0
  33. package/src/supervisor/generated/identity.mjs +95 -0
  34. package/src/supervisor/generated/process-identity.mjs +43 -0
  35. package/src/supervisor/generated/process.mjs +514 -0
  36. package/src/supervisor/generated/runner.mjs +872 -0
  37. package/src/supervisor/generated/store.mjs +605 -0
  38. package/src/supervisor/generated/types.mjs +50 -0
  39. package/src/supervisor/identity.ts +99 -0
  40. package/src/supervisor/index.ts +37 -0
  41. package/src/supervisor/invocation.ts +44 -0
  42. package/src/supervisor/runner.ts +982 -0
  43. package/src/supervisor/store.ts +649 -0
  44. package/src/supervisor/supervisor.ts +730 -0
  45. package/src/supervisor/types.ts +384 -0
  46. package/src/tools.ts +410 -12
  47. package/src/types.ts +41 -1
@@ -0,0 +1,3677 @@
1
+ /**
2
+ * Parent-side observed waits: the integration between background tasks, the
3
+ * detached local supervisor and the durable operation coordinator.
4
+ *
5
+ * Scope of this module:
6
+ *
7
+ * - launch local processes and command watches through the supervisor after the
8
+ * normal Background / worker sandbox admission has already admitted them;
9
+ * - register the durable operation *before* the runner starts, using the
10
+ * token-derived `bgs_…` task id;
11
+ * - reconcile terminal supervisor evidence into the coordinator store without
12
+ * re-running an ambiguous launch;
13
+ * - register all-settled waits, dispatch ready deliveries to the owner, and
14
+ * require an exact evidence read before an acknowledgement consumes a wait;
15
+ * - expose a versioned, in-process service for the Subagents bridge. The bridge
16
+ * owns its transport; this module owns authorization and the durable records.
17
+ *
18
+ * What it deliberately does not own: SSH/remote launches, a bridge socket, model
19
+ * continuation, goal/workflow completion, or any permission decision beyond
20
+ * calling the existing `resolve*SandboxPlan` helpers.
21
+ */
22
+
23
+ import { createHash, randomUUID } from "node:crypto";
24
+ import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, statSync, writeFileSync } from "node:fs";
25
+ import { homedir } from "node:os";
26
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
27
+
28
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
29
+
30
+ import { validateCondition } from "./conditions.js";
31
+ import {
32
+ STEP_GATE_COMMAND_ENV,
33
+ commandExecution,
34
+ parseStepGateFailure,
35
+ processExists,
36
+ stepGateScript,
37
+ validateCommandSpec,
38
+ } from "./process.js";
39
+ import { currentProcessStartToken, readProcessStartToken } from "./process-identity.js";
40
+ import {
41
+ assertBackgroundExecutionAllowed,
42
+ backgroundExecutionLimits,
43
+ confineCommandSpec,
44
+ resolveForegroundSandboxPlan,
45
+ resolveWorkerSandboxPlan,
46
+ sandboxProvenance,
47
+ type ForegroundSandboxPlan,
48
+ type WorkerSandboxPolicy,
49
+ } from "./sandbox.js";
50
+ import {
51
+ openStore,
52
+ type AcknowledgeDisposition,
53
+ type EvidenceKind,
54
+ type OperationEvidenceRecord,
55
+ type OperationRecord,
56
+ type OutboxEventRecord,
57
+ type OwnerIdentity,
58
+ type Store,
59
+ type SupervisionIdentity,
60
+ type WaitRecord,
61
+ } from "./shared-operation-coordinator/index.js";
62
+ import {
63
+ createLocalSupervisor,
64
+ defaultSupervisorDirectory,
65
+ supervisorPaths,
66
+ supervisorTaskIdForToken,
67
+ type LocalSupervisor,
68
+ type SupervisorInspection,
69
+ type SupervisorStartOptions,
70
+ type SupervisorTaskStatus,
71
+ } from "./supervisor/index.js";
72
+ import type { BackgroundTaskCallbackOrigin, CommandSpec, Condition, TaskSandboxProvenance } from "./types.js";
73
+ import type { SpawnTaskParams, WatchTaskParams } from "./runtime.js";
74
+
75
+ export const OBSERVED_WAITS_SERVICE_VERSION = 1 as const;
76
+ export const OBSERVED_WAITS_SERVICE_CHANNEL = "pi-better-background-tasks:observed-waits-service";
77
+ export const OBSERVED_WAITS_SERVICE_REQUEST_CHANNEL = "pi-better-background-tasks:observed-waits-service-request";
78
+
79
+ /**
80
+ * Request/reply compatibility surface used by the Subagents coordinator. The
81
+ * object service above is the richer in-process API; this channel is the
82
+ * versioned wire contract that lets a standalone Subagents build register runs,
83
+ * execute worker tools, admit parks, and drive resume claims without importing
84
+ * this package.
85
+ */
86
+ export const OBSERVED_WAITS_RPC_CHANNEL = "pi-better-background-tasks:observed-waits";
87
+ export const OBSERVED_WAITS_READY_CHANNEL = "pi-better-background-tasks:observed-waits-ready";
88
+ export const OBSERVED_WAITS_RPC_VERSION = 1 as const;
89
+
90
+ export type JsonRecord = Record<string, unknown>;
91
+
92
+ export type ObservedWaitsRpcReply =
93
+ | { ok: true; value: JsonRecord }
94
+ | { ok: false; code: string; reason: string };
95
+
96
+ export interface ObservedWaitsRpcRequest {
97
+ version: typeof OBSERVED_WAITS_RPC_VERSION;
98
+ id: string;
99
+ method: string;
100
+ params: JsonRecord;
101
+ reply(reply: ObservedWaitsRpcReply): void;
102
+ }
103
+
104
+ /** Structural mirror of Subagents' captured `WorkerRunPolicy`. */
105
+ export interface WorkerRunPolicyInput {
106
+ readonly version: 1;
107
+ readonly sandbox: WorkerSandboxPolicy | null;
108
+ readonly tools: readonly string[];
109
+ readonly clean: boolean;
110
+ readonly deadlineAt: number | null;
111
+ readonly authorityReference: string;
112
+ readonly workspace: string;
113
+ }
114
+
115
+ const OBSERVER = Object.freeze({ kind: "local-supervisor", version: "1" });
116
+
117
+ /**
118
+ * Process-wide host-instance ordering shared across module copies. A stale host
119
+ * must never take over a newer same-process host's callback claim, while the
120
+ * newer host may still recover an older instance's claim after a reload.
121
+ */
122
+ const HOST_INSTANCE_STATE = (() => {
123
+ const key = Symbol.for("pi-better-background-tasks:observed-waits-host-instances");
124
+ const global = globalThis as typeof globalThis & { [key]?: { next: number; generations: Map<string, number>; closed: Set<string> } };
125
+ return global[key] ??= { next: 0, generations: new Map<string, number>(), closed: new Set<string>() };
126
+ })();
127
+ const LOCAL_DURABLE_ID = /^bgs_[0-9a-f]{20}$/;
128
+ const DEFAULT_POLL_MS = 250;
129
+
130
+ /** A parent launch is always local; remote launches stay on the legacy task route. */
131
+ export type DurableTaskKind = "process" | "watch";
132
+
133
+ export interface DurableLaunch {
134
+ readonly id: string;
135
+ readonly operationId: string;
136
+ readonly kind: DurableTaskKind;
137
+ readonly status: "running";
138
+ readonly name?: string;
139
+ readonly cwd: string;
140
+ readonly command?: string;
141
+ readonly argv?: readonly string[];
142
+ readonly shell: boolean;
143
+ readonly owner: OwnerIdentity;
144
+ readonly started: boolean;
145
+ readonly claimed: boolean;
146
+ readonly notices: readonly string[];
147
+ readonly firstCheck?: DurableFirstCheck;
148
+ }
149
+
150
+ export interface DurableFirstCheck {
151
+ readonly attempt: number;
152
+ readonly exitCode: number | null;
153
+ readonly signal: string | null;
154
+ readonly stdout: string;
155
+ readonly stderr: string;
156
+ }
157
+
158
+ /** Compact, model-facing view of one wait generation. */
159
+ export interface WaitView {
160
+ readonly waitId: string;
161
+ readonly generation: number;
162
+ readonly phase: string;
163
+ readonly settled: boolean;
164
+ readonly park: boolean;
165
+ /** Cancellation epoch the caller must echo when claiming or cancelling. */
166
+ readonly cancelEpoch: number;
167
+ readonly ownerKind: OwnerIdentity["kind"];
168
+ readonly continuationNote: string;
169
+ readonly taskIds: readonly string[];
170
+ readonly dependencies: readonly WaitDependencyView[];
171
+ readonly evidence: readonly WaitEvidenceView[];
172
+ }
173
+
174
+ export interface WaitDependencyView {
175
+ readonly taskId?: string;
176
+ readonly operationId: string;
177
+ readonly terminalRevision: number;
178
+ readonly terminalOutcome: string | null;
179
+ }
180
+
181
+ export interface WaitEvidenceView {
182
+ readonly operationId: string;
183
+ readonly taskId?: string;
184
+ readonly terminalRevision: number;
185
+ readonly kind: EvidenceKind;
186
+ readonly ref: string;
187
+ readonly summary?: string;
188
+ readonly detailLost: boolean;
189
+ }
190
+
191
+ export interface WaitDispatchEvent {
192
+ readonly waitId: string;
193
+ readonly generation: number;
194
+ readonly owner: OwnerIdentity;
195
+ /** Parent session origin captured when the supervised task launched. */
196
+ readonly parentOrigin?: BackgroundTaskCallbackOrigin;
197
+ readonly taskIds: readonly string[];
198
+ readonly continuationNote: string;
199
+ readonly evidence: readonly WaitEvidenceView[];
200
+ }
201
+
202
+ /**
203
+ * Continuation admission is owned by Subagents. The host emits a ready wait to
204
+ * this adapter and never launches a model itself. Returning `"deferred"` (or
205
+ * throwing) leaves the durable delivery pending, so nothing is silently lost.
206
+ */
207
+ export interface ContinuationAdapter {
208
+ readonly version: 1;
209
+ readonly id: string;
210
+ onWaitReady(event: WaitDispatchEvent): void | Promise<void | "delivered" | "deferred">;
211
+ onWaitCancelled?(event: { waitId: string; generation: number; reason: string }): void | Promise<void>;
212
+ }
213
+
214
+ export interface ParentNotification {
215
+ readonly taskId: string;
216
+ /** Launching parent origin captured when the supervised task started. */
217
+ readonly origin?: BackgroundTaskCallbackOrigin;
218
+ /** Branch anchor captured at launch; a descendant branch is eligible. */
219
+ readonly branchId?: string | null;
220
+ readonly operationId: string;
221
+ readonly waitId?: string;
222
+ readonly generation?: number;
223
+ readonly status: SupervisorTaskStatus;
224
+ readonly outcome: string;
225
+ readonly summary: string;
226
+ readonly evidence: readonly WaitEvidenceView[];
227
+ }
228
+
229
+ /**
230
+ * Delivery acknowledgement. A callback is not durable receipt until the host
231
+ * calls `delivered()` from the batcher's real handoff; returning from
232
+ * `notifyParent` is not delivery.
233
+ */
234
+ export interface ParentDelivery {
235
+ delivered(): void;
236
+ defer(reason: string): void;
237
+ }
238
+
239
+ export type ParentNotifier = (notification: ParentNotification, delivery: ParentDelivery) => void;
240
+
241
+ export interface WorkerRunScope {
242
+ readonly runId: string;
243
+ readonly conversationId: string;
244
+ readonly workspace: string;
245
+ readonly authorityReference: string;
246
+ readonly branchId?: string | null;
247
+ readonly goalId?: string | null;
248
+ }
249
+
250
+ interface RpcRunBinding {
251
+ readonly runId: string;
252
+ readonly conversationId: string;
253
+ readonly attemptId: string;
254
+ readonly workspace: string;
255
+ readonly authorityReference: string;
256
+ readonly policy: WorkerRunPolicyInput;
257
+ readonly owner: OwnerIdentity;
258
+ readonly tools: ReadonlySet<string>;
259
+ readonly capabilities: JsonRecord;
260
+ readonly writerPid?: number;
261
+ readonly writerLeaseId?: string | null;
262
+ }
263
+
264
+ export interface WorkerLaunchInput {
265
+ readonly kind: DurableTaskKind;
266
+ readonly params: Record<string, unknown>;
267
+ /** Parent-captured task authority; absent means an unconfined worker. */
268
+ readonly policy?: WorkerSandboxPolicy | null;
269
+ }
270
+
271
+ export interface WorkerWaitInput {
272
+ readonly taskIds: readonly string[];
273
+ readonly continuationNote: string;
274
+ readonly attemptId: string;
275
+ readonly checkpointId: string;
276
+ readonly writerLeaseId?: string | null;
277
+ }
278
+
279
+ export interface WorkerCheckpointInput {
280
+ readonly waitId: string;
281
+ readonly generation: number;
282
+ /**
283
+ * The Subagents bridge verifies the native checkpoint and the original
284
+ * writer's exit; this records that proof. All three facts are required before
285
+ * a parked generation may leave parking.
286
+ */
287
+ readonly proof: { checkpointRecorded: boolean; writerLeaseReleased: boolean; writerPidGone: boolean };
288
+ }
289
+
290
+ export interface WorkerEvidenceInput {
291
+ readonly waitId: string;
292
+ readonly generation: number;
293
+ readonly taskId?: string;
294
+ }
295
+
296
+ export interface WorkerAcknowledgeInput {
297
+ readonly waitId: string;
298
+ readonly generation: number;
299
+ readonly terminalRevisions: unknown;
300
+ readonly disposition: AcknowledgeDisposition;
301
+ readonly note: string;
302
+ }
303
+
304
+ export interface ResumeClaimViewInput {
305
+ readonly waitId: string;
306
+ readonly generation: number;
307
+ readonly expectedCancelEpoch: number;
308
+ readonly lease: { ownerId: string; pid?: number; processStartToken?: string | null };
309
+ readonly reservedCheckpointId: string;
310
+ }
311
+
312
+ export interface PublishResumeViewInput {
313
+ readonly waitId: string;
314
+ readonly generation: number;
315
+ readonly claimId: string;
316
+ readonly claimToken: string;
317
+ readonly attemptId: string;
318
+ readonly launchToken: string;
319
+ }
320
+
321
+ export interface ReleaseResumeViewInput {
322
+ readonly waitId: string;
323
+ readonly generation: number;
324
+ readonly claimId: string;
325
+ readonly claimToken: string;
326
+ readonly outcome: "ready" | "held";
327
+ readonly reason: string;
328
+ }
329
+
330
+ export interface ResumeClaimView {
331
+ readonly claimId: string;
332
+ readonly claimToken: string;
333
+ readonly state: string;
334
+ readonly attemptId: string | null;
335
+ readonly phase: string;
336
+ readonly cancelEpoch: number;
337
+ }
338
+
339
+ /** Exact identity and proof for holding a failed published resume. */
340
+ export interface HoldResumedAttemptInput {
341
+ readonly waitId: string;
342
+ readonly generation: number;
343
+ readonly claimId: string;
344
+ readonly claimToken: string;
345
+ readonly attemptId: string;
346
+ readonly launchToken: string;
347
+ /** Proven exit: writer gone and its conversation lease free. */
348
+ readonly proof: { readonly writerPidGone: boolean; readonly writerLeaseReleased: boolean };
349
+ readonly reason: string;
350
+ }
351
+
352
+ export interface HoldResumedAttemptView {
353
+ readonly waitId: string;
354
+ readonly generation: number;
355
+ readonly phase: string;
356
+ readonly applied: boolean;
357
+ readonly claim: { readonly claimId: string; readonly state: string; readonly attemptId: string | null; readonly reason?: string };
358
+ }
359
+
360
+ export interface AcknowledgeView {
361
+ readonly waitId: string;
362
+ readonly generation: number;
363
+ readonly disposition: AcknowledgeDisposition;
364
+ readonly acknowledgedOutboxIds: readonly string[];
365
+ readonly releasedPinIds: readonly string[];
366
+ readonly phase: string;
367
+ }
368
+
369
+ export interface StatusView {
370
+ readonly taskId: string;
371
+ readonly operationId: string;
372
+ readonly kind: DurableTaskKind;
373
+ readonly status: SupervisorTaskStatus;
374
+ readonly phase: string;
375
+ readonly exitCode: number | null;
376
+ readonly signal: string | null;
377
+ readonly reason?: string;
378
+ readonly terminalRevision: number;
379
+ readonly terminalOutcome: string | null;
380
+ readonly startedAt?: number;
381
+ readonly endedAt?: number;
382
+ readonly checks?: number;
383
+ readonly matchedCondition?: Condition;
384
+ readonly lastOutput?: { stdout: string; stderr: string };
385
+ readonly stepGateFailure?: { stepExitCode: number; shellExitCode: number | null; command: string };
386
+ readonly waits: readonly WaitView[];
387
+ readonly sandbox?: TaskSandboxProvenance;
388
+ }
389
+
390
+ /** Read-only projection of one supervised durable task for list/navigator/Goal. */
391
+ export interface DurableTaskProjection {
392
+ readonly id: string;
393
+ readonly operationId: string;
394
+ readonly kind: DurableTaskKind;
395
+ readonly status: SupervisorTaskStatus;
396
+ readonly active: boolean;
397
+ readonly terminal: boolean;
398
+ readonly attention: boolean;
399
+ readonly name?: string;
400
+ readonly cwd: string;
401
+ readonly command?: string;
402
+ readonly argv?: readonly string[];
403
+ readonly startedAt: number;
404
+ readonly endedAt?: number;
405
+ readonly exitCode: number | null;
406
+ readonly signal: string | null;
407
+ readonly reason?: string;
408
+ readonly matchedCondition?: Condition;
409
+ readonly lastOutput?: { stdout: string; stderr: string };
410
+ readonly stepGateFailure?: { stepExitCode: number; shellExitCode: number | null; command: string };
411
+ readonly terminalRevision: number;
412
+ readonly terminalOutcome: string | null;
413
+ readonly detailLost: boolean;
414
+ readonly dismissedAt?: number;
415
+ readonly logDiscardedBytes?: number;
416
+ readonly intervalSeconds?: number;
417
+ readonly deadlineAt?: number;
418
+ readonly logPaths: { stdout: string; stderr: string; events: string };
419
+ readonly waits: readonly WaitView[];
420
+ readonly sandbox?: TaskSandboxProvenance;
421
+ readonly owner: { sessionId: string; workspace: string };
422
+ }
423
+
424
+ export interface DurableTaskLogView {
425
+ readonly taskId: string;
426
+ readonly status: SupervisorTaskStatus;
427
+ readonly stdout: string;
428
+ readonly stderr: string;
429
+ readonly events: string;
430
+ readonly truncated: boolean;
431
+ }
432
+
433
+ export interface LogView {
434
+ readonly taskId: string;
435
+ readonly status: SupervisorTaskStatus;
436
+ readonly stdout: string;
437
+ readonly stderr: string;
438
+ readonly events: string;
439
+ readonly truncated: boolean;
440
+ }
441
+
442
+ /**
443
+ * The versioned capability published for the Subagents coordinator. Every method
444
+ * rechecks ownership in the durable store; a caller's run id is never a grant.
445
+ * The transport is Subagents' responsibility.
446
+ */
447
+ export interface BackgroundOperationService {
448
+ readonly version: typeof OBSERVED_WAITS_SERVICE_VERSION;
449
+ readonly serviceId: string;
450
+ readonly available: true;
451
+ /** True when a verified continuation adapter is registered. */
452
+ readonly continuationReady: boolean;
453
+ ownsTask(run: WorkerRunScope, taskId: string): boolean;
454
+ launchForWorker(run: WorkerRunScope, input: WorkerLaunchInput): Promise<DurableLaunch>;
455
+ statusForWorker(run: WorkerRunScope, taskId: string): StatusView;
456
+ logForWorker(run: WorkerRunScope, taskId: string, options?: { lines?: number }): LogView;
457
+ stopForWorker(run: WorkerRunScope, taskId: string): Promise<StatusView>;
458
+ registerWorkerWait(run: WorkerRunScope, input: WorkerWaitInput): WaitView;
459
+ checkpointWorkerWait(run: WorkerRunScope, input: WorkerCheckpointInput): Promise<WaitView>;
460
+ failWorkerPark(run: WorkerRunScope, input: { waitId: string; generation: number; reason: string }): WaitView;
461
+ readEvidence(run: WorkerRunScope, input: WorkerEvidenceInput): readonly WaitEvidenceView[];
462
+ acknowledgeForWorker(run: WorkerRunScope, input: WorkerAcknowledgeInput): AcknowledgeView;
463
+ claimResumeForWorker(run: WorkerRunScope, input: ResumeClaimViewInput): ResumeClaimView;
464
+ publishResumeForWorker(run: WorkerRunScope, input: PublishResumeViewInput): ResumeClaimView;
465
+ releaseResumeForWorker(run: WorkerRunScope, input: ReleaseResumeViewInput): ResumeClaimView;
466
+ /**
467
+ * Hold a published generation whose attempt exited without interpreting it.
468
+ * Requires exact claim identity and proven writer exit; keeps the cancellation
469
+ * epoch and evidence pins and invalidates the claim so nothing resumes again.
470
+ */
471
+ holdFailedResumeForWorker(run: WorkerRunScope, input: HoldResumedAttemptInput): HoldResumedAttemptView;
472
+ listWorkerWaits(run: WorkerRunScope, options?: { pendingOnly?: boolean }): readonly WaitView[];
473
+ cancelWorkerWait(run: WorkerRunScope, input: { waitId: string; generation: number; reason: string }): WaitView;
474
+ registerContinuationAdapter(adapter: ContinuationAdapter): void;
475
+ unregisterContinuationAdapter(id: string): void;
476
+ }
477
+
478
+ export interface BackgroundOperationCapability {
479
+ readonly version: typeof OBSERVED_WAITS_SERVICE_VERSION;
480
+ readonly available: false;
481
+ readonly reason: string;
482
+ }
483
+
484
+ export type PublishedBackgroundOperationCapability = BackgroundOperationService | BackgroundOperationCapability;
485
+
486
+ function normalizeRunPolicy(value: unknown): WorkerRunPolicyInput {
487
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("register-run requires a policy object.");
488
+ const policy = value as Record<string, unknown>;
489
+ if (policy.version !== 1) throw new Error("register-run requires policy version 1.");
490
+ if (typeof policy.workspace !== "string" || !policy.workspace) throw new Error("register-run policy.workspace is required.");
491
+ if (typeof policy.authorityReference !== "string" || !policy.authorityReference) {
492
+ throw new Error("register-run policy.authorityReference is required.");
493
+ }
494
+ const sandbox = policy.sandbox === null || policy.sandbox === undefined
495
+ ? null
496
+ : policy.sandbox as WorkerSandboxPolicy;
497
+ if (sandbox !== null && (typeof sandbox !== "object" || typeof (sandbox as { root?: unknown }).root !== "string")) {
498
+ throw new Error("register-run policy.sandbox must be null or a worker sandbox authority.");
499
+ }
500
+ const tools = Array.isArray(policy.tools)
501
+ ? policy.tools.filter((tool): tool is string => typeof tool === "string")
502
+ : [];
503
+ return Object.freeze({
504
+ version: 1 as const,
505
+ sandbox,
506
+ tools: Object.freeze(tools),
507
+ clean: policy.clean === true,
508
+ deadlineAt: typeof policy.deadlineAt === "number" && Number.isFinite(policy.deadlineAt) ? policy.deadlineAt : null,
509
+ authorityReference: policy.authorityReference,
510
+ workspace: policy.workspace,
511
+ });
512
+ }
513
+
514
+ function normalizeRpcOwner(value: unknown, fallback: OwnerIdentity): OwnerIdentity {
515
+ if (!value || typeof value !== "object" || Array.isArray(value)) return fallback;
516
+ const owner = value as Record<string, unknown>;
517
+ if (typeof owner.sessionId !== "string" || typeof owner.workspace !== "string") return fallback;
518
+ return {
519
+ kind: "worker-conversation",
520
+ sessionId: owner.sessionId,
521
+ workspace: owner.workspace,
522
+ branchId: typeof owner.branchId === "string" ? owner.branchId : null,
523
+ goalId: typeof owner.goalId === "string" ? owner.goalId : null,
524
+ };
525
+ }
526
+
527
+ function rpcCode(error: unknown): string {
528
+ const code = (error as { code?: unknown } | undefined)?.code;
529
+ return typeof code === "string" && code.length > 0 ? code : "refused";
530
+ }
531
+
532
+ export interface ObservedWaitHostOptions {
533
+ /** SQLite path. Defaults under the Pi agent directory. */
534
+ storePath?: string;
535
+ /** Durable supervisor record directory. Defaults beside the task registry. */
536
+ supervisorDirectory?: string;
537
+ /** Test seam: a pre-built local supervisor. */
538
+ supervisor?: LocalSupervisor;
539
+ /** Reconcile cadence; `0` disables the timer (tests call `reconcileNow`). */
540
+ pollMs?: number;
541
+ /** Parent callback delivery. Production wires the existing callback batcher. */
542
+ notifyParent?: ParentNotifier;
543
+ logger?: (line: string) => void;
544
+ now?: () => number;
545
+ }
546
+
547
+ /** Minimal event bus surface, mirrored from the sandbox policy contract. */
548
+ interface ServiceEventBus {
549
+ on(channel: string, handler: (data: unknown) => void): unknown;
550
+ off?(channel: string, handler: (data: unknown) => void): unknown;
551
+ emit(channel: string, data: unknown): void;
552
+ }
553
+
554
+ function eventBusOf(pi: unknown): ServiceEventBus | undefined {
555
+ const events = (pi as { events?: unknown } | undefined)?.events;
556
+ if (!events || typeof events !== "object") return undefined;
557
+ const candidate = events as Partial<ServiceEventBus>;
558
+ if (typeof candidate.on !== "function" || typeof candidate.emit !== "function") return undefined;
559
+ return candidate as ServiceEventBus;
560
+ }
561
+
562
+ function isService(value: unknown): value is BackgroundOperationService {
563
+ return !!value && typeof value === "object"
564
+ && (value as { version?: unknown }).version === OBSERVED_WAITS_SERVICE_VERSION
565
+ && (value as { available?: unknown }).available === true
566
+ && typeof (value as { launchForWorker?: unknown }).launchForWorker === "function";
567
+ }
568
+
569
+ const serviceMirrors = new WeakMap<ServiceEventBus, BackgroundOperationService | undefined>();
570
+ const serviceErrors = new WeakMap<ServiceEventBus, string | undefined>();
571
+
572
+ function observeServiceChannel(pi: unknown): ServiceEventBus | undefined {
573
+ const events = eventBusOf(pi);
574
+ if (!events || serviceMirrors.has(events)) return events;
575
+ serviceMirrors.set(events, undefined);
576
+ events.on(OBSERVED_WAITS_SERVICE_CHANNEL, (data) => {
577
+ if (isService(data)) {
578
+ serviceMirrors.set(events, data);
579
+ serviceErrors.delete(events);
580
+ } else if (data && typeof data === "object"
581
+ && (data as { version?: unknown }).version === OBSERVED_WAITS_SERVICE_VERSION
582
+ && (data as { available?: unknown }).available === false) {
583
+ serviceMirrors.set(events, undefined);
584
+ const reason = (data as { reason?: unknown }).reason;
585
+ serviceErrors.set(events, typeof reason === "string" ? reason : "observed waits are unavailable");
586
+ }
587
+ });
588
+ return events;
589
+ }
590
+
591
+ /**
592
+ * Ask for the Background operation service. Pi's bus dispatches synchronously,
593
+ * so a host that is already running answers before this returns. Returns
594
+ * `undefined` when this package is installed alone or the host is closed.
595
+ */
596
+ export function getObservedWaitService(pi: unknown): BackgroundOperationService | undefined {
597
+ const events = observeServiceChannel(pi);
598
+ if (!events) return undefined;
599
+ events.emit(OBSERVED_WAITS_SERVICE_REQUEST_CHANNEL, { version: OBSERVED_WAITS_SERVICE_VERSION });
600
+ return serviceMirrors.get(events);
601
+ }
602
+
603
+ /** Why a service request returned nothing, when a host refused to open. */
604
+ export function observedWaitServiceUnavailableReason(pi: unknown): string | undefined {
605
+ observeServiceChannel(pi);
606
+ const events = eventBusOf(pi);
607
+ return events ? serviceErrors.get(events) : undefined;
608
+ }
609
+
610
+ const hosts = new WeakMap<object, ObservedWaitHost>();
611
+
612
+ export function createObservedWaitHost(pi: ExtensionAPI, options: ObservedWaitHostOptions = {}): ObservedWaitHost {
613
+ const existing = hosts.get(pi as unknown as object);
614
+ if (existing && existing !== undefined) existing.close();
615
+ const host = new ObservedWaitHost(pi, options);
616
+ hosts.set(pi as unknown as object, host);
617
+ return host;
618
+ }
619
+
620
+ export function getObservedWaitHost(pi: unknown): ObservedWaitHost | undefined {
621
+ return pi && typeof pi === "object" ? hosts.get(pi as object) : undefined;
622
+ }
623
+
624
+ interface LaunchContext {
625
+ readonly kind: DurableTaskKind;
626
+ readonly parentOrigin?: BackgroundTaskCallbackOrigin;
627
+ readonly gated: boolean;
628
+ readonly callback: boolean;
629
+ readonly name?: string;
630
+ readonly command?: string;
631
+ readonly argv?: readonly string[];
632
+ readonly cwd?: string;
633
+ /** Launch-time sandbox provenance; never recomputed from the current profile. */
634
+ readonly sandbox?: TaskSandboxProvenance;
635
+ /** Owner branch anchor captured at launch (undefined when unavailable). */
636
+ readonly branchId?: string | null;
637
+ callbackPendingAt?: number;
638
+ callbackDeliveredAt?: number;
639
+ callbackDeferredReason?: string;
640
+ callbackClaimedBy?: string;
641
+ callbackClaimedAt?: number;
642
+ /** Identifies the exact callback attempt, so stale delivery callbacks are ignored. */
643
+ callbackClaimToken?: string;
644
+ callbackAttemptedAt?: number;
645
+ callbackSkipReason?: string;
646
+ terminalRecordedBy?: string;
647
+ terminalRecordedAt?: number;
648
+ terminalRecordedWithContext?: boolean;
649
+ terminalActiveSessionId?: string;
650
+ terminalActiveBranchIds?: readonly string[];
651
+ terminalReplayObservedBy?: string;
652
+ /** Exact outbox event handoffs whose store receipt was lost to a reload. */
653
+ outboxDelivered?: Record<string, { waitId: string; generation: number; terminalRevision: number; deliveredAt: number }>;
654
+ dismissedAt?: number;
655
+ }
656
+
657
+ function branchIdsOf(ctx: ExtensionContext): string[] {
658
+ try {
659
+ const branch = ctx.sessionManager?.getBranch?.() as readonly { id?: unknown }[] | undefined;
660
+ if (!branch) return [];
661
+ return branch.map((entry) => entry?.id).filter((id): id is string => typeof id === "string");
662
+ } catch {
663
+ return [];
664
+ }
665
+ }
666
+
667
+ function startTokenDigest(token: string | undefined): string {
668
+ return token ? createHash("sha256").update(token, "utf8").digest("hex").slice(0, 16) : "unknown";
669
+ }
670
+
671
+ function parseHostIdentity(hostId: string): { pid?: number; startTokenDigest?: string } {
672
+ const parts = hostId.split(":");
673
+ const pid = Number(parts[0]);
674
+ if (!Number.isSafeInteger(pid) || pid <= 0) return {};
675
+ // New format: pid:startTokenDigest:instance. A legacy pid:instance claim has
676
+ // no process-instance identity and is therefore treated as unknown, not dead.
677
+ if (parts.length < 3) return { pid };
678
+ let digest = parts[1] || undefined;
679
+ if (digest === "unknown") return { pid };
680
+ if (digest && !/^[0-9a-f]{16}$/.test(digest)) {
681
+ // Tolerate an older/raw URL-encoded token form without putting its spaces or
682
+ // percent escapes into a durable ID field.
683
+ try { digest = startTokenDigest(decodeURIComponent(digest)); } catch { digest = undefined; }
684
+ }
685
+ return { pid, ...(digest ? { startTokenDigest: digest } : {}) };
686
+ }
687
+
688
+ function oneLine(value: string, max = 300): string {
689
+ const text = String(value).replace(/\s+/g, " ").trim();
690
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
691
+ }
692
+
693
+ function ownerKey(owner: OwnerIdentity): string {
694
+ return [owner.kind, owner.sessionId, owner.workspace, owner.branchId ?? "", owner.goalId ?? ""].join("\u0000");
695
+ }
696
+
697
+ function sameOwner(a: OwnerIdentity, b: OwnerIdentity): boolean {
698
+ return ownerKey(a) === ownerKey(b);
699
+ }
700
+
701
+ function ownerMatchesOperation(operation: OperationRecord, owner: OwnerIdentity): boolean {
702
+ // The execution identity is the session (or conversation) plus workspace. The
703
+ // branch anchor decides which continuation may resume; it must not hide a
704
+ // task from its own session after the branch advances.
705
+ return operation.owner.kind === owner.kind
706
+ && operation.owner.sessionId === owner.sessionId
707
+ && operation.owner.workspace === owner.workspace;
708
+ }
709
+
710
+ function authorityReference(seed: string): string {
711
+ return `authority:local:${createHash("sha256").update(seed, "utf8").digest("hex").slice(0, 32)}`;
712
+ }
713
+
714
+ function defaultStorePath(): string {
715
+ const agentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
716
+ return join(agentDir, "operation-coordinator.sqlite");
717
+ }
718
+
719
+ function tail(path: string, maxBytes = 64 * 1024): { text: string; truncated: boolean } {
720
+ let fd: number | undefined;
721
+ try {
722
+ if (!existsSync(path)) return { text: "", truncated: false };
723
+ fd = openSync(path, "r");
724
+ const size = fstatSync(fd).size;
725
+ const start = Math.max(0, size - maxBytes);
726
+ const length = Math.min(maxBytes, size - start);
727
+ const buffer = Buffer.alloc(length);
728
+ if (length > 0) readSync(fd, buffer, 0, length, start);
729
+ return { text: buffer.toString("utf8"), truncated: start > 0 };
730
+ } catch {
731
+ return { text: "", truncated: false };
732
+ } finally {
733
+ if (fd !== undefined) { try { closeSync(fd); } catch { /* already closed */ } }
734
+ }
735
+ }
736
+
737
+ function lastLines(text: string, lines: number): string {
738
+ if (lines <= 0) return "";
739
+ const split = text.split(/\r?\n/);
740
+ if (split.length > 0 && split[split.length - 1] === "") split.pop();
741
+ return split.slice(-lines).join("\n");
742
+ }
743
+
744
+ function terminalOutcome(status: SupervisorTaskStatus): "succeeded" | "failed" | "cancelled" | "lost" {
745
+ switch (status) {
746
+ case "succeeded": return "succeeded";
747
+ case "cancelled": return "cancelled";
748
+ case "lost": return "lost";
749
+ default: return "failed";
750
+ }
751
+ }
752
+
753
+ function supervisionReasonFields(inspection: SupervisorInspection | undefined): { reason?: string } {
754
+ const reason = inspection?.result?.reason ?? inspection?.lost?.reason;
755
+ const cleanup = inspection?.result?.groupCleanup === "unproven"
756
+ ? "Process-group cleanup is unproven; descendants may remain running."
757
+ : undefined;
758
+ const text = [reason, cleanup].filter(Boolean).join("; ");
759
+ return text ? { reason: oneLine(text) } : {};
760
+ }
761
+
762
+ function evidenceFor(inspection: SupervisorInspection): WaitEvidenceView[] {
763
+ const paths = inspection.logs;
764
+ const evidence: WaitEvidenceView[] = [];
765
+ const result = inspection.result;
766
+ const lost = inspection.lost;
767
+ const terminalRef = result ? "result.json" : "lost.json";
768
+ const summary = result
769
+ ? `status=${result.status} exit=${result.exitCode ?? "null"} timedOut=${result.timedOut ? "true" : "false"}${result.groupCleanup ? ` groupCleanup=${result.groupCleanup}` : ""}`
770
+ : `status=lost detailLost=true`;
771
+ evidence.push({
772
+ operationId: "",
773
+ terminalRevision: 0,
774
+ kind: "terminal-record",
775
+ ref: terminalRef,
776
+ summary,
777
+ detailLost: !result,
778
+ });
779
+ for (const [label, path] of [["stdout", paths.stdout], ["stderr", paths.stderr]] as const) {
780
+ try {
781
+ const size = existsSync(path) ? statSync(path).size : 0;
782
+ if (size <= 0) continue;
783
+ evidence.push({
784
+ operationId: "",
785
+ terminalRevision: 0,
786
+ kind: "log",
787
+ ref: `${label}.log`,
788
+ summary: `${label} retained (${size} bytes)`,
789
+ detailLost: false,
790
+ });
791
+ } catch { /* a reclaimed log costs detail, never the outcome */ }
792
+ }
793
+ return evidence;
794
+ }
795
+
796
+ function mapEvidence(
797
+ operationId: string,
798
+ taskId: string | undefined,
799
+ records: readonly (OperationEvidenceRecord | WaitEvidenceView)[],
800
+ revision: number,
801
+ ): WaitEvidenceView[] {
802
+ return records.map((entry) => ({
803
+ operationId: "operationId" in entry ? entry.operationId || operationId : operationId,
804
+ ...(taskId ? { taskId } : {}),
805
+ terminalRevision: "terminalRevision" in entry ? entry.terminalRevision || revision : revision,
806
+ kind: entry.kind,
807
+ ref: entry.ref,
808
+ ...(entry.summary ? { summary: entry.summary } : {}),
809
+ detailLost: entry.detailLost,
810
+ }));
811
+ }
812
+
813
+ export class ObservedWaitHost {
814
+ readonly service: BackgroundOperationService;
815
+ private store?: Store;
816
+ private readonly supervisor: LocalSupervisor;
817
+ private readonly directory: string;
818
+ private readonly pollMs: number;
819
+ private readonly options: ObservedWaitHostOptions;
820
+ private timer?: NodeJS.Timeout;
821
+ private closed = false;
822
+ private unavailableReason?: string;
823
+ private parentOrigin?: BackgroundTaskCallbackOrigin;
824
+ private activeOrigin?: BackgroundTaskCallbackOrigin;
825
+ /**
826
+ * The live extension context for the active session. Branch eligibility is
827
+ * read from this context on every check; the SDK can settle/reload session
828
+ * history after session_start, so a start-time branch snapshot is stale.
829
+ */
830
+ private activeContext?: ExtensionContext;
831
+ /** A new session/workspace context needs one seed scan of terminal callbacks. */
832
+ private terminalRecoveryNeeded = false;
833
+ /** Terminal callbacks awaiting their exact batcher handoff. */
834
+ private readonly pendingTerminalCallbacks = new Set<string>();
835
+ /** Running operations this host observed; a transition out of running can need recovery. */
836
+ private readonly watchedRunningTasks = new Set<string>();
837
+ /** Durable sidecars discovered in this supervisor directory. */
838
+ private readonly discoveredTaskSidecars = new Set<string>();
839
+ private continuation?: ContinuationAdapter;
840
+ private continuationError?: string;
841
+ private readonly launches = new Map<string, LaunchContext>();
842
+ private readonly rpcRuns = new Map<string, RpcRunBinding>();
843
+ private readonly waitOwners = new Map<string, OwnerIdentity>();
844
+ private readonly stagedCheckpoints = new Map<string, { evidence: JsonRecord; toolCallId: string; checkpointRecorded: boolean }>();
845
+ private readonly branchAnchors = new Map<string, string | null>();
846
+ private readonly durableChangeListeners = new Set<() => void>();
847
+ private readonly serviceId = `bg-observed-${randomUUID()}`;
848
+ /** Opaque, validation-safe process-instance identity: pid + hashed start token. */
849
+ private readonly hostStartDigest = startTokenDigest(currentProcessStartToken());
850
+ private readonly hostId = `${process.pid}:${this.hostStartDigest}:${randomUUID()}`;
851
+ private hostGeneration = ++HOST_INSTANCE_STATE.next;
852
+
853
+ constructor(private readonly pi: ExtensionAPI, options: ObservedWaitHostOptions = {}) {
854
+ this.options = options;
855
+ this.directory = options.supervisorDirectory ?? defaultSupervisorDirectory();
856
+ this.supervisor = options.supervisor ?? createLocalSupervisor({ directory: this.directory });
857
+ this.pollMs = options.pollMs ?? DEFAULT_POLL_MS;
858
+ const base = {
859
+ version: OBSERVED_WAITS_SERVICE_VERSION,
860
+ serviceId: this.serviceId,
861
+ available: true as const,
862
+ ownsTask: (run: WorkerRunScope, taskId: string) => this.ownsTask(run, taskId),
863
+ launchForWorker: (run: WorkerRunScope, input: WorkerLaunchInput) => this.launchForWorker(run, input),
864
+ statusForWorker: (run: WorkerRunScope, taskId: string) => this.statusForWorker(run, taskId),
865
+ logForWorker: (run: WorkerRunScope, taskId: string, logOptions?: { lines?: number }) => this.logForWorker(run, taskId, logOptions),
866
+ stopForWorker: (run: WorkerRunScope, taskId: string) => this.stopForWorker(run, taskId),
867
+ registerWorkerWait: (run: WorkerRunScope, input: WorkerWaitInput) => this.registerWorkerWait(run, input),
868
+ checkpointWorkerWait: (run: WorkerRunScope, input: WorkerCheckpointInput) => this.checkpointWorkerWait(run, input),
869
+ failWorkerPark: (run: WorkerRunScope, input: { waitId: string; generation: number; reason: string }) => this.failWorkerPark(run, input),
870
+ readEvidence: (run: WorkerRunScope, input: WorkerEvidenceInput) => this.readEvidence(run, input),
871
+ acknowledgeForWorker: (run: WorkerRunScope, input: WorkerAcknowledgeInput) => this.acknowledgeForWorker(run, input),
872
+ claimResumeForWorker: (run: WorkerRunScope, input: ResumeClaimViewInput) => this.claimResumeForWorker(run, input),
873
+ publishResumeForWorker: (run: WorkerRunScope, input: PublishResumeViewInput) => this.publishResumeForWorker(run, input),
874
+ releaseResumeForWorker: (run: WorkerRunScope, input: ReleaseResumeViewInput) => this.releaseResumeForWorker(run, input),
875
+ holdFailedResumeForWorker: (run: WorkerRunScope, input: HoldResumedAttemptInput) => this.holdFailedResumeForWorker(run, input),
876
+ listWorkerWaits: (run: WorkerRunScope, listOptions?: { pendingOnly?: boolean }) => this.listWorkerWaits(run, listOptions),
877
+ cancelWorkerWait: (run: WorkerRunScope, input: { waitId: string; generation: number; reason: string }) => this.cancelWorkerWait(run, input),
878
+ registerContinuationAdapter: (adapter: ContinuationAdapter) => this.registerContinuationAdapter(adapter),
879
+ unregisterContinuationAdapter: (id: string) => this.unregisterContinuationAdapter(id),
880
+ } satisfies Omit<BackgroundOperationService, "continuationReady">;
881
+ Object.defineProperty(base, "continuationReady", {
882
+ enumerable: true,
883
+ get: () => this.continuation !== undefined || this.rpcRuns.size > 0,
884
+ });
885
+ HOST_INSTANCE_STATE.generations.set(this.hostId, this.hostGeneration);
886
+ this.service = Object.freeze(base) as unknown as BackgroundOperationService;
887
+ this.listenForServiceRequests();
888
+ this.listenForWorkerRequests();
889
+ // Announce the capability object at extension load so a Subagents probe does
890
+ // not depend on handler order. The store opens on session activation or on
891
+ // the first operation, and a failure replaces this with an unavailable
892
+ // capability instead of pretending to be durable.
893
+ this.announce();
894
+ }
895
+
896
+ get available(): boolean {
897
+ return this.store !== undefined && !this.closed;
898
+ }
899
+
900
+ get reason(): string | undefined {
901
+ return this.unavailableReason;
902
+ }
903
+
904
+ /** Open the durable store and begin bounded reconciliation. */
905
+ start(ctx?: ExtensionContext): void {
906
+ if (ctx) this.setActiveOrigin(ctx);
907
+ if (this.store) {
908
+ // The same host instance can be activated for another session without a
909
+ // reload. Re-evaluate pending deliveries against the new active origin.
910
+ this.recoverAbandonedDeliveries();
911
+ this.discoverObservedTasks();
912
+ void this.reconcileNow();
913
+ this.recoverTerminalNotifications();
914
+ this.terminalRecoveryNeeded = false;
915
+ return;
916
+ }
917
+ // session_before_switch closes the store, and the same extension instance
918
+ // handles the next session_start. A real unload is followed by no start.
919
+ this.closed = false;
920
+ this.unavailableReason = undefined;
921
+ try {
922
+ this.store = openStore({
923
+ path: this.options.storePath ?? defaultStorePath(),
924
+ ...(this.options.now ? { now: this.options.now } : {}),
925
+ });
926
+ } catch (error) {
927
+ this.unavailableReason = oneLine(error instanceof Error ? error.message : String(error), 300);
928
+ this.announceUnavailable(this.unavailableReason);
929
+ return;
930
+ }
931
+ if (HOST_INSTANCE_STATE.closed.delete(this.hostId)) {
932
+ // Reactivation is newer than instances created while this host was closed.
933
+ this.hostGeneration = ++HOST_INSTANCE_STATE.next;
934
+ HOST_INSTANCE_STATE.generations.set(this.hostId, this.hostGeneration);
935
+ }
936
+ this.announce();
937
+ this.writeHostDebug();
938
+ this.recoverAbandonedDeliveries();
939
+ this.discoverObservedTasks();
940
+ void this.reconcileNow();
941
+ this.recoverTerminalNotifications();
942
+ this.terminalRecoveryNeeded = false;
943
+ if (this.pollMs > 0) {
944
+ this.timer = setInterval(() => { void this.reconcileNow(); }, this.pollMs);
945
+ this.timer.unref?.();
946
+ }
947
+ }
948
+
949
+ close(): void {
950
+ if (this.closed) return;
951
+ this.closed = true;
952
+ HOST_INSTANCE_STATE.closed.add(this.hostId);
953
+ if (this.timer) clearInterval(this.timer);
954
+ this.timer = undefined;
955
+ try { this.store?.close(); } catch { /* already closed */ }
956
+ this.store = undefined;
957
+ this.launches.clear();
958
+ this.rpcRuns.clear();
959
+ this.waitOwners.clear();
960
+ this.stagedCheckpoints.clear();
961
+ this.branchAnchors.clear();
962
+ this.activeOrigin = undefined;
963
+ this.activeContext = undefined;
964
+ this.terminalRecoveryNeeded = false;
965
+ this.pendingTerminalCallbacks.clear();
966
+ this.watchedRunningTasks.clear();
967
+ this.discoveredTaskSidecars.clear();
968
+ this.writeHostDebug();
969
+ this.announceUnavailable("the Background operation host closed");
970
+ }
971
+
972
+ /** Recover a callback a previous host recorded terminal but never delivered. */
973
+ private recoverTerminalNotifications(): void {
974
+ if (!this.store) return;
975
+ for (const operation of this.store.listOperations({ phase: "terminal" })) {
976
+ if (operation.terminalOutcome === null) continue;
977
+ this.attemptTerminalCallback(
978
+ operation,
979
+ this.statusOf(operation.operationId),
980
+ operation.terminalOutcome,
981
+ [],
982
+ );
983
+ }
984
+ }
985
+
986
+ /**
987
+ * Discover durable tasks launched by any host sharing this supervisor
988
+ * directory. A host that started before a task was registered never saw it in
989
+ * the running set; terminal discovery must not depend on that observation.
990
+ * This is a bounded directory listing plus new-sidecar lookup, not a scan of
991
+ * historical terminal rows on every tick.
992
+ */
993
+ private discoverObservedTasks(): void {
994
+ const store = this.store;
995
+ if (!store) return;
996
+ let names: string[];
997
+ try { names = readdirSync(join(this.directory, "observed")); } catch { return; }
998
+ for (const name of names) {
999
+ if (!name.endsWith(".json") || name === "host.json") continue;
1000
+ const taskId = name.slice(0, -5);
1001
+ if (!LOCAL_DURABLE_ID.test(taskId) || this.discoveredTaskSidecars.has(taskId)) continue;
1002
+ const operation = this.operationForTask(taskId);
1003
+ if (!operation) continue; // registration may land on the next tick
1004
+ this.discoveredTaskSidecars.add(taskId);
1005
+ if (operation.terminalRevision > 0) {
1006
+ this.attemptTerminalCallback(
1007
+ operation,
1008
+ this.statusOf(operation.operationId),
1009
+ operation.terminalOutcome ?? "failed",
1010
+ [],
1011
+ { pendingWithoutContext: true },
1012
+ );
1013
+ } else {
1014
+ this.watchedRunningTasks.add(taskId);
1015
+ }
1016
+ }
1017
+ }
1018
+
1019
+ /**
1020
+ * Retry only terminal callbacks that are still awaiting an exact handoff. The
1021
+ * pending set is seeded once at activation and by each terminal attempt; it is
1022
+ * not a scan of the historical terminal table on every 250 ms tick.
1023
+ */
1024
+ private retryPendingTerminalCallbacks(): void {
1025
+ if (!this.store || this.pendingTerminalCallbacks.size === 0) return;
1026
+ for (const taskId of [...this.pendingTerminalCallbacks]) {
1027
+ const operation = this.operationForTask(taskId);
1028
+ if (!operation || operation.terminalRevision === 0) {
1029
+ this.pendingTerminalCallbacks.delete(taskId);
1030
+ continue;
1031
+ }
1032
+ const context = this.launchContext(taskId);
1033
+ if (!context || context.callback === false || context.callbackDeliveredAt !== undefined || !this.options.notifyParent) {
1034
+ this.pendingTerminalCallbacks.delete(taskId);
1035
+ continue;
1036
+ }
1037
+ if (!this.activeContext) continue; // wait for an exact active owner
1038
+ const relation = this.activeOwnerRelation(operation.owner);
1039
+ if (relation === "unknown") continue; // keep pending; never guess
1040
+ if (relation === "foreign") {
1041
+ this.pendingTerminalCallbacks.delete(taskId);
1042
+ continue;
1043
+ }
1044
+ const waitPending = this.store.listWaits({ owner: operation.owner, pendingOnly: true })
1045
+ .some((wait) => wait.dependencies.some((dep) => dep.operationId === operation.operationId));
1046
+ if (waitPending) {
1047
+ this.pendingTerminalCallbacks.delete(taskId);
1048
+ continue;
1049
+ }
1050
+ this.attemptTerminalCallback(
1051
+ operation,
1052
+ this.statusOf(operation.operationId),
1053
+ operation.terminalOutcome ?? "failed",
1054
+ [],
1055
+ );
1056
+ }
1057
+ }
1058
+
1059
+ /** A deterministic, awaitable reconciliation pass for tests and session activation. */
1060
+ async reconcileNow(): Promise<void> {
1061
+ if (!this.store || this.closed) return;
1062
+ this.discoverObservedTasks();
1063
+ const running = this.store.listOperations({ phase: "running" });
1064
+ const runningIds = new Set(running.map((operation) => operation.taskId));
1065
+ for (const taskId of [...this.watchedRunningTasks]) {
1066
+ if (runningIds.has(taskId)) continue;
1067
+ this.watchedRunningTasks.delete(taskId);
1068
+ const operation = this.operationForTask(taskId);
1069
+ if (operation && operation.terminalRevision > 0) {
1070
+ // Another host may have recorded the terminal result without a live
1071
+ // owner context. This host watched the operation, so recover its callback
1072
+ // now that the active branch/identity can authorize the handoff.
1073
+ this.attemptTerminalCallback(
1074
+ operation,
1075
+ this.statusOf(operation.operationId),
1076
+ operation.terminalOutcome ?? "failed",
1077
+ [],
1078
+ { pendingWithoutContext: true },
1079
+ );
1080
+ }
1081
+ }
1082
+ for (const operation of running) {
1083
+ this.watchedRunningTasks.add(operation.taskId);
1084
+ this.reconcileOperation(operation);
1085
+ }
1086
+ this.retryPendingTerminalCallbacks();
1087
+ await this.dispatchOutbox();
1088
+ }
1089
+
1090
+ isDurableTask(taskId: string): boolean {
1091
+ if (!LOCAL_DURABLE_ID.test(taskId)) return false;
1092
+ if (this.store) return this.operationForTask(taskId) !== undefined;
1093
+ return existsSync(supervisorPaths(this.directory, taskId).dir);
1094
+ }
1095
+
1096
+ // ---- parent launches -------------------------------------------------
1097
+
1098
+ async launchParent(input: {
1099
+ kind: DurableTaskKind;
1100
+ params: Record<string, unknown>;
1101
+ ctx: ExtensionContext;
1102
+ waitForFirstCheck?: boolean;
1103
+ }): Promise<DurableLaunch> {
1104
+ const store = this.requireStore();
1105
+ this.requireStarted(input.ctx);
1106
+ if (input.params.ssh) {
1107
+ throw new Error("Structured SSH is not supervised by the durable local host; use the legacy remote task route.");
1108
+ }
1109
+ const owner = this.ownerFor(input.ctx);
1110
+ const prepared = this.prepareLaunch(input.kind, input.params, "bg_task_spawn", owner, undefined);
1111
+ const operationId = `op_${randomUUID()}`;
1112
+ const token = `launch_${randomUUID()}`;
1113
+ const taskId = supervisorTaskIdForToken(token);
1114
+ store.registerOperation({
1115
+ operationId,
1116
+ taskId,
1117
+ launchToken: token,
1118
+ owner,
1119
+ observer: OBSERVER,
1120
+ supervision: this.supervision(),
1121
+ authorityRef: this.parentAuthority(owner, prepared.plan),
1122
+ intentRef: typeof input.params.operation_id === "string" ? input.params.operation_id : null,
1123
+ });
1124
+ const launchContext: LaunchContext = {
1125
+ kind: input.kind,
1126
+ parentOrigin: this.parentOrigin,
1127
+ gated: prepared.gated,
1128
+ callback: input.params.callback !== false,
1129
+ ...(typeof input.params.name === "string" ? { name: input.params.name } : {}),
1130
+ ...(typeof input.params.command === "string" ? { command: input.params.command } : {}),
1131
+ ...(prepared.spec.argv ? { argv: [...prepared.spec.argv] } : {}),
1132
+ cwd: prepared.cwd,
1133
+ sandbox: prepared.provenance,
1134
+ branchId: owner.branchId ?? null,
1135
+ };
1136
+ // Persist supervision metadata outside the task execution record so a
1137
+ // replacement host can still notify the right parent and never re-route a
1138
+ // worker-owned operation to the parent's callback.
1139
+ this.writeLaunchContext(taskId, launchContext);
1140
+ const started = await this.startSupervisor({
1141
+ token, taskId, kind: input.kind, params: input.params, prepared, operationId,
1142
+ });
1143
+ this.launches.set(taskId, launchContext);
1144
+ this.emitDurableTaskChange();
1145
+ const launch: DurableLaunch = {
1146
+ id: taskId,
1147
+ operationId,
1148
+ kind: input.kind,
1149
+ status: "running",
1150
+ ...(typeof input.params.name === "string" ? { name: input.params.name } : {}),
1151
+ cwd: prepared.cwd,
1152
+ ...(typeof input.params.command === "string" ? { command: input.params.command } : {}),
1153
+ ...(prepared.spec.argv ? { argv: prepared.spec.argv } : {}),
1154
+ shell: prepared.spec.shell !== false,
1155
+ owner,
1156
+ started: started.started,
1157
+ claimed: started.claimed,
1158
+ notices: prepared.notices,
1159
+ };
1160
+ if (input.kind === "watch" && input.waitForFirstCheck !== false) {
1161
+ const check = await this.firstCheck(taskId);
1162
+ return { ...launch, ...(check ? { firstCheck: check } : {}) };
1163
+ }
1164
+ return launch;
1165
+ }
1166
+
1167
+ formatLaunch(launch: DurableLaunch): string {
1168
+ const lines = [
1169
+ `Started durable background ${launch.kind === "watch" ? "watch" : "process"} ${launch.id} (operation ${launch.operationId}).`,
1170
+ `Owner: ${launch.owner.kind} ${launch.owner.sessionId}.${launch.owner.branchId ? ` branch ${launch.owner.branchId}` : ""}`.trim(),
1171
+ `Status: ${launch.status}; supervisor ${launch.started ? "started" : "reported the existing execution"}${launch.claimed ? ", runner claimed" : ", runner claim pending"}.`,
1172
+ `Inspect with bg_task_status ${launch.id}; read output with bg_task_log ${launch.id}; stop with bg_task_stop ${launch.id}.`,
1173
+ "Never poll in the foreground. Register wait_for_operations when no independent work remains.",
1174
+ ];
1175
+ if (launch.firstCheck) {
1176
+ lines.push(`First check: exit=${launch.firstCheck.exitCode ?? "null"}${launch.firstCheck.signal ? ` signal=${launch.firstCheck.signal}` : ""}.`);
1177
+ if (launch.firstCheck.stdout.trim()) lines.push(`stdout: ${tailText(launch.firstCheck.stdout, 10)}`);
1178
+ if (launch.firstCheck.stderr.trim()) lines.push(`stderr: ${tailText(launch.firstCheck.stderr, 10)}`);
1179
+ }
1180
+ for (const notice of launch.notices) lines.push(`Notice: ${notice}`);
1181
+ return lines.join("\n");
1182
+ }
1183
+
1184
+ /**
1185
+ * Bounded first-check observation, mirroring the legacy watch launch. A watch
1186
+ * whose first check is still running returns the retained tails and says so;
1187
+ * it never invents an exit code. A check that ends without a terminal record
1188
+ * is given a short grace for the runner to publish the next attempt.
1189
+ */
1190
+ private async firstCheck(taskId: string): Promise<DurableFirstCheck | undefined> {
1191
+ const deadline = Date.now() + 15_000;
1192
+ const tails = (attempt: number): DurableFirstCheck | undefined => {
1193
+ const inspection = this.supervisor.inspect(taskId);
1194
+ if (!inspection) return undefined;
1195
+ const paths = inspection.logs;
1196
+ return {
1197
+ attempt,
1198
+ exitCode: null,
1199
+ signal: null,
1200
+ stdout: lastLines(tail(paths.stdout).text, 10),
1201
+ stderr: lastLines(tail(paths.stderr).text, 10),
1202
+ };
1203
+ };
1204
+ let endedAt: number | undefined;
1205
+ while (Date.now() < deadline) {
1206
+ const inspection = this.supervisor.inspect(taskId);
1207
+ if (inspection?.result) {
1208
+ const last = inspection.result.lastCheck;
1209
+ return {
1210
+ attempt: inspection.result.checks ?? 1,
1211
+ exitCode: last?.exitCode ?? inspection.result.exitCode,
1212
+ signal: last?.signal ?? inspection.result.signal,
1213
+ stdout: last?.stdout ?? inspection.result.lastOutput?.stdout ?? "",
1214
+ stderr: last?.stderr ?? inspection.result.lastOutput?.stderr ?? "",
1215
+ };
1216
+ }
1217
+ const command = inspection?.command;
1218
+ if (command) {
1219
+ if (command.alive) {
1220
+ endedAt = undefined;
1221
+ } else if (endedAt === undefined) {
1222
+ endedAt = Date.now();
1223
+ } else if (Date.now() - endedAt >= 250) {
1224
+ return tails(command.attempt);
1225
+ }
1226
+ }
1227
+ await new Promise((resolve) => setTimeout(resolve, 100));
1228
+ }
1229
+ // Still running after the legacy first-check window: report what the logs hold.
1230
+ const inspection = this.supervisor.inspect(taskId);
1231
+ return inspection?.command ? tails(inspection.command.attempt) : undefined;
1232
+ }
1233
+
1234
+ // ---- status / log / stop --------------------------------------------
1235
+
1236
+ statusForParent(ctx: ExtensionContext, taskId: string): StatusView {
1237
+ this.noteParentContext(ctx);
1238
+ return this.status(taskId, this.ownerFor(ctx));
1239
+ }
1240
+
1241
+ logForParent(ctx: ExtensionContext, taskId: string, options?: { lines?: number }): LogView {
1242
+ this.noteParentContext(ctx);
1243
+ return this.log(taskId, this.ownerFor(ctx), options);
1244
+ }
1245
+
1246
+ async stopForParent(ctx: ExtensionContext, taskId: string): Promise<StatusView> {
1247
+ this.noteParentContext(ctx);
1248
+ return this.stop(taskId, this.ownerFor(ctx));
1249
+ }
1250
+
1251
+ // ---- read-only projections for list, navigator and Goal -----------------
1252
+
1253
+ /**
1254
+ * Durable operations owned by exactly this parent origin, newest first. This
1255
+ * never writes a legacy registry meta and never reconciles; it projects the
1256
+ * canonical operation store plus the supervisor's durable records.
1257
+ */
1258
+ listDurableTasks(
1259
+ origin: BackgroundTaskCallbackOrigin,
1260
+ options: { retentionMs?: number; includeDismissed?: boolean } = {},
1261
+ ): DurableTaskProjection[] {
1262
+ const store = this.store;
1263
+ if (!store || this.closed) return [];
1264
+ const now = this.options.now?.() ?? Date.now();
1265
+ const projections: DurableTaskProjection[] = [];
1266
+ for (const operation of store.listOperations()) {
1267
+ if (!this.belongsToParentOrigin(operation, origin)) continue;
1268
+ const projection = this.projectDurable(operation, now);
1269
+ if (!projection) continue;
1270
+ if (projection.dismissedAt !== undefined && options.includeDismissed !== true) continue;
1271
+ if (projection.terminal && options.retentionMs !== undefined) {
1272
+ const endedAt = projection.endedAt ?? now;
1273
+ if (now - endedAt >= options.retentionMs) continue;
1274
+ }
1275
+ projections.push(projection);
1276
+ }
1277
+ return projections.sort((a, b) => b.startedAt - a.startedAt);
1278
+ }
1279
+
1280
+ readDurableTask(origin: BackgroundTaskCallbackOrigin, taskId: string): DurableTaskProjection | undefined {
1281
+ const operation = this.operationForTask(taskId);
1282
+ if (!operation || !this.belongsToParentOrigin(operation, origin)) return undefined;
1283
+ return this.projectDurable(operation, this.options.now?.() ?? Date.now());
1284
+ }
1285
+
1286
+ /**
1287
+ * True only when this host's **currently active** parent session/workspace
1288
+ * owns the durable operation. The adapter contract uses this to admit a local
1289
+ * stop/clear as a registry operation; it is not a regex and cannot authorize a
1290
+ * foreign session or a worker-owned operation.
1291
+ */
1292
+ ownsDurableTask(taskId: string): boolean {
1293
+ const origin = this.activeOrigin;
1294
+ if (!origin) return false;
1295
+ return this.readDurableTask(origin, taskId) !== undefined;
1296
+ }
1297
+
1298
+ /** Read-only log tails. Unlike status/log tools, this records no evidence read. */
1299
+ readDurableTaskLog(
1300
+ origin: BackgroundTaskCallbackOrigin,
1301
+ taskId: string,
1302
+ lines = 40,
1303
+ ): DurableTaskLogView | undefined {
1304
+ const projection = this.readDurableTask(origin, taskId);
1305
+ if (!projection) return undefined;
1306
+ const count = Math.max(1, Math.floor(lines));
1307
+ const stdout = tail(projection.logPaths.stdout);
1308
+ const stderr = tail(projection.logPaths.stderr);
1309
+ return {
1310
+ taskId,
1311
+ status: projection.status,
1312
+ stdout: lastLines(stdout.text, count),
1313
+ stderr: lastLines(stderr.text, count),
1314
+ events: lastLines(tail(projection.logPaths.events).text, Math.min(count, 20)),
1315
+ truncated: stdout.truncated || stderr.truncated,
1316
+ };
1317
+ }
1318
+
1319
+ /** Stop a durable task through the supervisor. Foreign ids are refused. */
1320
+ async stopDurableTask(origin: BackgroundTaskCallbackOrigin, taskId: string): Promise<DurableTaskProjection | undefined> {
1321
+ const operation = this.operationForTask(taskId);
1322
+ if (!operation || !this.belongsToParentOrigin(operation, origin)) return undefined;
1323
+ await this.stop(taskId, operation.owner);
1324
+ return this.projectDurable(operation, this.options.now?.() ?? Date.now());
1325
+ }
1326
+
1327
+ /** Dismiss one terminal durable task from list/navigator/Goal. Evidence stays readable. */
1328
+ dismissDurableTask(origin: BackgroundTaskCallbackOrigin, taskId: string): boolean {
1329
+ const operation = this.operationForTask(taskId);
1330
+ if (!operation || !this.belongsToParentOrigin(operation, origin)) return false;
1331
+ const projection = this.projectDurable(operation, this.options.now?.() ?? Date.now());
1332
+ if (!projection || !projection.terminal) return false;
1333
+ const context = this.currentLaunchContext(taskId) ?? {
1334
+ kind: projection.kind,
1335
+ gated: projection.stepGateFailure !== undefined,
1336
+ callback: false,
1337
+ ...(projection.name ? { name: projection.name } : {}),
1338
+ ...(projection.command ? { command: projection.command } : {}),
1339
+ ...(projection.argv ? { argv: [...projection.argv] } : {}),
1340
+ cwd: projection.cwd,
1341
+ };
1342
+ context.dismissedAt = Date.now();
1343
+ this.launches.set(taskId, context);
1344
+ this.writeLaunchContext(taskId, context);
1345
+ this.emitDurableTaskChange();
1346
+ return true;
1347
+ }
1348
+
1349
+ onDurableTaskChange(listener: () => void): () => void {
1350
+ this.durableChangeListeners.add(listener);
1351
+ return () => { this.durableChangeListeners.delete(listener); };
1352
+ }
1353
+
1354
+ private emitDurableTaskChange(): void {
1355
+ for (const listener of [...this.durableChangeListeners]) {
1356
+ try { listener(); } catch { /* a projection listener cannot break supervision */ }
1357
+ }
1358
+ }
1359
+
1360
+ private belongsToParentOrigin(operation: OperationRecord, origin: BackgroundTaskCallbackOrigin): boolean {
1361
+ if (operation.owner.kind !== "parent-session") return false;
1362
+ if (operation.owner.workspace !== origin.cwd) return false;
1363
+ if (origin.sessionId || operation.owner.sessionId) return operation.owner.sessionId === origin.sessionId;
1364
+ return true;
1365
+ }
1366
+
1367
+ private projectDurable(operation: OperationRecord, now: number): DurableTaskProjection | undefined {
1368
+ const context = this.launchContext(operation.taskId);
1369
+ const inspection = LOCAL_DURABLE_ID.test(operation.taskId)
1370
+ ? (() => { try { return this.supervisor.inspect(operation.taskId, { recordLost: false }); } catch { return undefined; } })()
1371
+ : undefined;
1372
+ const storeStatus = operation.terminalRevision > 0 ? this.statusOf(operation.operationId) : undefined;
1373
+ const status: SupervisorTaskStatus = inspection?.terminal ? inspection.status : storeStatus ?? inspection?.status ?? "running";
1374
+ const terminal = inspection?.terminal === true || operation.terminalRevision > 0;
1375
+ const active = !terminal && (status === "running" || status === "starting");
1376
+ const startedAt = inspection?.result?.startedAt ?? inspection?.launch?.createdAt ?? operation.createdAt;
1377
+ const endedAt = inspection?.result?.endedAt ?? inspection?.lost?.recordedAt ?? operation.terminalAt ?? undefined;
1378
+ const pathSet = inspection?.logs ?? supervisorPaths(this.directory, operation.taskId);
1379
+ const result = inspection?.result;
1380
+ const lost = inspection?.lost;
1381
+ const waits = (this.store?.listWaits({ owner: operation.owner, pendingOnly: true }) ?? [])
1382
+ .filter((wait) => wait.dependencies.some((dep) => dep.operationId === operation.operationId))
1383
+ .map((wait) => this.waitView(wait));
1384
+ const stepGate = result && context?.gated
1385
+ ? parseStepGateFailure(tail(pathSet.stderr).text, operation.taskId)
1386
+ : undefined;
1387
+ const timeoutSeconds = inspection?.launch.timeoutSeconds;
1388
+ return {
1389
+ id: operation.taskId,
1390
+ operationId: operation.operationId,
1391
+ kind: (context?.kind ?? inspection?.launch.kind) === "watch" ? "watch" : "process",
1392
+ status,
1393
+ active,
1394
+ terminal,
1395
+ attention: terminal && status !== "succeeded",
1396
+ ...(context?.name ?? inspection?.launch.name ? { name: context?.name ?? inspection?.launch.name } : {}),
1397
+ cwd: inspection?.launch.cwd ?? context?.cwd ?? operation.owner.workspace,
1398
+ ...(context?.command ? { command: context.command } : {}),
1399
+ ...(context?.argv ? { argv: context.argv } : {}),
1400
+ startedAt,
1401
+ ...(endedAt !== undefined ? { endedAt } : {}),
1402
+ exitCode: result?.exitCode ?? null,
1403
+ signal: result?.signal ?? null,
1404
+ ...supervisionReasonFields(inspection),
1405
+ ...(result?.matchedCondition ? { matchedCondition: result.matchedCondition } : {}),
1406
+ ...(result?.lastOutput ? { lastOutput: result.lastOutput } : {}),
1407
+ ...(stepGate ? { stepGateFailure: stepGate } : {}),
1408
+ terminalRevision: operation.terminalRevision,
1409
+ terminalOutcome: operation.terminalOutcome,
1410
+ detailLost: lost !== undefined || operation.terminalDetailLost,
1411
+ ...(context?.dismissedAt !== undefined ? { dismissedAt: context.dismissedAt } : {}),
1412
+ ...(result ? { logDiscardedBytes: result.stdoutDiscardedBytes + result.stderrDiscardedBytes } : {}),
1413
+ ...(inspection?.launch.intervalSeconds !== undefined ? { intervalSeconds: inspection.launch.intervalSeconds } : {}),
1414
+ ...(timeoutSeconds !== undefined && timeoutSeconds > 0 ? { deadlineAt: startedAt + timeoutSeconds * 1000 } : {}),
1415
+ logPaths: { stdout: pathSet.stdout, stderr: pathSet.stderr, events: pathSet.events },
1416
+ waits,
1417
+ ...(context?.sandbox ? { sandbox: context.sandbox } : {}),
1418
+ owner: { sessionId: operation.owner.sessionId, workspace: operation.owner.workspace },
1419
+ };
1420
+ }
1421
+
1422
+ private status(taskId: string, owner: OwnerIdentity): StatusView {
1423
+ const store = this.requireStore();
1424
+ const operation = this.ownedOperation(taskId, owner);
1425
+ const inspection = this.inspect(taskId);
1426
+ this.reconcileInspection(operation, inspection);
1427
+ const current = store.getOperation(operation.operationId) ?? operation;
1428
+ if (this.watchedRunningTasks.delete(taskId) && current.terminalRevision > 0) {
1429
+ this.attemptTerminalCallback(
1430
+ current,
1431
+ this.statusOf(current.operationId),
1432
+ current.terminalOutcome ?? "failed",
1433
+ [],
1434
+ { pendingWithoutContext: true },
1435
+ );
1436
+ }
1437
+ if (current.terminalRevision > 0) {
1438
+ // Status is an explicit owner read of this exact terminal operation. It is
1439
+ // the natural recovery point when another host recorded terminal first.
1440
+ this.attemptTerminalCallback(
1441
+ current,
1442
+ this.statusOf(current.operationId),
1443
+ current.terminalOutcome ?? "failed",
1444
+ [],
1445
+ { pendingWithoutContext: true },
1446
+ );
1447
+ }
1448
+ this.recordReadsForTask(owner, current);
1449
+ const paths = supervisorPaths(this.directory, taskId);
1450
+ const gateText = inspection ? `${tail(paths.stderr).text}` : "";
1451
+ const waits = store.listWaits({ pendingOnly: true })
1452
+ .filter((wait) => sameOwner(wait.owner, owner))
1453
+ .filter((wait) => wait.dependencies.some((dep) => dep.operationId === current.operationId))
1454
+ .map((wait) => this.waitView(wait));
1455
+ const result = inspection?.result;
1456
+ const launched = this.launchContext(taskId);
1457
+ const stepGate = result && launched?.gated ? parseStepGateFailure(gateText, taskId) : undefined;
1458
+ const kind = inspection?.kind ?? launched?.kind ?? "process";
1459
+ return {
1460
+ taskId,
1461
+ operationId: current.operationId,
1462
+ kind: kind === "watch" ? "watch" : "process",
1463
+ status: inspection?.status ?? this.statusOf(current.operationId),
1464
+ phase: current.phase,
1465
+ exitCode: result?.exitCode ?? null,
1466
+ signal: result?.signal ?? null,
1467
+ ...supervisionReasonFields(inspection),
1468
+ terminalRevision: current.terminalRevision,
1469
+ terminalOutcome: current.terminalOutcome,
1470
+ ...(result ? { startedAt: result.startedAt, endedAt: result.endedAt } : {}),
1471
+ ...(result?.checks !== undefined ? { checks: result.checks } : {}),
1472
+ ...(result?.matchedCondition ? { matchedCondition: result.matchedCondition } : {}),
1473
+ ...(result?.lastOutput ? { lastOutput: result.lastOutput } : {}),
1474
+ ...(stepGate ? { stepGateFailure: stepGate } : {}),
1475
+ waits,
1476
+ ...(launched?.sandbox ? { sandbox: launched.sandbox } : {}),
1477
+ };
1478
+ }
1479
+
1480
+ private log(taskId: string, owner: OwnerIdentity, options: { lines?: number } = {}): LogView {
1481
+ const store = this.requireStore();
1482
+ const operation = this.ownedOperation(taskId, owner);
1483
+ const inspection = this.inspect(taskId);
1484
+ this.reconcileInspection(operation, inspection);
1485
+ this.recordReadsForTask(owner, store.getOperation(operation.operationId) ?? operation);
1486
+ const paths = supervisorPaths(this.directory, taskId);
1487
+ const lines = Math.max(1, Math.floor(options.lines ?? 40));
1488
+ const stdout = tail(paths.stdout);
1489
+ const stderr = tail(paths.stderr);
1490
+ return {
1491
+ taskId,
1492
+ status: inspection?.status ?? "running",
1493
+ stdout: lastLines(stdout.text, lines),
1494
+ stderr: lastLines(stderr.text, lines),
1495
+ events: lastLines(tail(paths.events).text, Math.min(lines, 20)),
1496
+ truncated: stdout.truncated || stderr.truncated,
1497
+ };
1498
+ }
1499
+
1500
+ private async stop(taskId: string, owner: OwnerIdentity): Promise<StatusView> {
1501
+ const store = this.requireStore();
1502
+ const operation = this.ownedOperation(taskId, owner);
1503
+ const result = await this.supervisor.stop(taskId);
1504
+ const inspection = result?.inspection ?? this.supervisor.inspect(taskId);
1505
+ this.reconcileInspection(operation, inspection);
1506
+ const current = store.getOperation(operation.operationId) ?? operation;
1507
+ if (current.terminalRevision === 0 && inspection?.terminal) {
1508
+ this.recordTerminal(current, inspection);
1509
+ }
1510
+ return this.status(taskId, owner);
1511
+ }
1512
+
1513
+ formatStatus(view: StatusView): string {
1514
+ const lines = [
1515
+ `${view.taskId} ${view.kind}: ${view.status} (${view.phase})`,
1516
+ `operation: ${view.operationId}; terminal revision: ${view.terminalRevision}${view.terminalOutcome ? ` (${view.terminalOutcome})` : ""}`,
1517
+ ];
1518
+ if (view.sandbox) {
1519
+ lines.push(`sandbox: ${view.sandbox.confinement}${view.sandbox.backend ? `; ${oneLine(view.sandbox.backend, 40)}` : ""}; source: ${oneLine(view.sandbox.policySource, 80)}; later changes do not affect this task.`);
1520
+ }
1521
+ if (view.exitCode !== null || view.signal) lines.push(`exit=${view.exitCode ?? "null"}${view.signal ? ` signal=${view.signal}` : ""}${view.stepGateFailure ? " (step gate)" : ""}`);
1522
+ if (view.startedAt) lines.push(`started: ${new Date(view.startedAt).toISOString()}${view.endedAt ? `; ended: ${new Date(view.endedAt).toISOString()}` : ""}`);
1523
+ if (view.checks !== undefined) lines.push(`checks: ${view.checks}`);
1524
+ if (view.matchedCondition) lines.push(`matched: ${oneLine(JSON.stringify(view.matchedCondition))}`);
1525
+ if (view.reason) lines.push(`reason: ${view.reason}`);
1526
+ if (view.stepGateFailure) lines.push(`failing step: ${view.stepGateFailure.command}`);
1527
+ if (view.waits.length) {
1528
+ for (const wait of view.waits) {
1529
+ lines.push(`wait: ${wait.waitId} generation ${wait.generation} ${wait.phase}${wait.settled ? " (settled)" : ""}`);
1530
+ }
1531
+ } else {
1532
+ lines.push("wait: none pending for this owner");
1533
+ }
1534
+ lines.push("Read the terminal evidence with bg_task_log before acknowledging a wait.");
1535
+ return lines.join("\n");
1536
+ }
1537
+
1538
+ formatLog(view: LogView): string {
1539
+ const parts = [`${view.taskId} ${view.status}`, "stdout:", view.stdout || "(empty)"];
1540
+ if (view.stderr.trim()) parts.push("stderr:", view.stderr);
1541
+ parts.push("events:", view.events || "(empty)");
1542
+ if (view.truncated) parts.push("Retention removed older output; the terminal outcome is preserved.");
1543
+ return parts.join("\n");
1544
+ }
1545
+
1546
+ // ---- parent waits ----------------------------------------------------
1547
+
1548
+ waitForParent(ctx: ExtensionContext, taskIds: readonly string[], continuationNote: string): WaitView {
1549
+ this.noteParentContext(ctx);
1550
+ const store = this.requireStore();
1551
+ const owner = this.ownerFor(ctx);
1552
+ const operations = this.operationsForTaskIds(owner, taskIds);
1553
+ for (const operation of operations) this.reconcileOperation(operation);
1554
+ const result = store.registerWait({
1555
+ owner,
1556
+ dependencies: operations.map((operation) => ({ operationId: operation.operationId })),
1557
+ continuationNote,
1558
+ origin: { taskIds: [...taskIds] },
1559
+ });
1560
+ void this.dispatchOutbox();
1561
+ return this.waitView(store.getWait({ waitId: result.wait.waitId }) ?? result.wait);
1562
+ }
1563
+
1564
+ waitViewForParent(ctx: ExtensionContext, waitId: string, generation?: number): WaitView | undefined {
1565
+ const store = this.requireStore();
1566
+ const wait = store.getWait({ waitId, ...(generation ? { generation } : {}) });
1567
+ return wait && sameOwner(wait.owner, this.ownerFor(ctx)) ? this.waitView(wait) : undefined;
1568
+ }
1569
+
1570
+ listWaitsForParent(ctx: ExtensionContext, options: { pendingOnly?: boolean } = {}): WaitView[] {
1571
+ this.noteParentContext(ctx);
1572
+ const store = this.requireStore();
1573
+ const owner = this.ownerFor(ctx);
1574
+ return store.listWaits({ owner, ...(options.pendingOnly ? { pendingOnly: true } : {}) }).map((wait) => this.waitView(wait));
1575
+ }
1576
+
1577
+ cancelWaitForParent(ctx: ExtensionContext, waitId: string, generation: number, reason: string): WaitView {
1578
+ this.noteParentContext(ctx);
1579
+ return this.cancelWait(this.ownerFor(ctx), waitId, generation, reason);
1580
+ }
1581
+
1582
+ acknowledgeForParent(ctx: ExtensionContext, input: {
1583
+ waitId: string;
1584
+ generation: number;
1585
+ terminalRevisions: unknown;
1586
+ disposition: AcknowledgeDisposition;
1587
+ note: string;
1588
+ }): AcknowledgeView {
1589
+ this.noteParentContext(ctx);
1590
+ return this.acknowledge(this.ownerFor(ctx), input);
1591
+ }
1592
+
1593
+ // ---- worker service --------------------------------------------------
1594
+
1595
+ ownsTask(run: WorkerRunScope, taskId: string): boolean {
1596
+ const operation = this.operationForTask(taskId);
1597
+ return !!operation && ownerMatchesOperation(operation, this.workerOwner(run));
1598
+ }
1599
+
1600
+ async launchForWorker(run: WorkerRunScope, input: WorkerLaunchInput): Promise<DurableLaunch> {
1601
+ const store = this.requireStore();
1602
+ if (input.params.ssh) throw new Error("Worker background launches are local-only; structured SSH is unavailable through this service.");
1603
+ const owner = this.workerOwner(run);
1604
+ const prepared = this.prepareLaunch(
1605
+ input.kind,
1606
+ input.params,
1607
+ input.kind === "watch" ? "bg_task_watch" : "bg_task_spawn",
1608
+ owner,
1609
+ input.policy,
1610
+ run.workspace,
1611
+ );
1612
+ const operationId = `op_${randomUUID()}`;
1613
+ const token = `launch_${randomUUID()}`;
1614
+ const taskId = supervisorTaskIdForToken(token);
1615
+ store.registerOperation({
1616
+ operationId,
1617
+ taskId,
1618
+ launchToken: token,
1619
+ owner,
1620
+ observer: OBSERVER,
1621
+ supervision: this.supervision(),
1622
+ authorityRef: authorityReference(`worker:${run.authorityReference}`),
1623
+ intentRef: typeof input.params.operation_id === "string" ? input.params.operation_id : null,
1624
+ });
1625
+ const launchContext: LaunchContext = {
1626
+ kind: input.kind,
1627
+ parentOrigin: this.parentOrigin,
1628
+ gated: prepared.gated,
1629
+ callback: false,
1630
+ ...(typeof input.params.name === "string" ? { name: input.params.name } : {}),
1631
+ ...(typeof input.params.command === "string" ? { command: input.params.command } : {}),
1632
+ ...(prepared.spec.argv ? { argv: [...prepared.spec.argv] } : {}),
1633
+ cwd: prepared.cwd,
1634
+ sandbox: prepared.provenance,
1635
+ branchId: owner.branchId ?? null,
1636
+ };
1637
+ this.writeLaunchContext(taskId, launchContext);
1638
+ const started = await this.startSupervisor({
1639
+ token, taskId, kind: input.kind, params: input.params, prepared, operationId,
1640
+ });
1641
+ this.launches.set(taskId, launchContext);
1642
+ this.emitDurableTaskChange();
1643
+ return {
1644
+ id: taskId,
1645
+ operationId,
1646
+ kind: input.kind,
1647
+ status: "running",
1648
+ ...(typeof input.params.name === "string" ? { name: input.params.name } : {}),
1649
+ cwd: prepared.cwd,
1650
+ ...(typeof input.params.command === "string" ? { command: input.params.command } : {}),
1651
+ ...(prepared.spec.argv ? { argv: prepared.spec.argv } : {}),
1652
+ shell: prepared.spec.shell !== false,
1653
+ owner,
1654
+ started: started.started,
1655
+ claimed: started.claimed,
1656
+ notices: prepared.notices,
1657
+ };
1658
+ }
1659
+
1660
+ statusForWorker(run: WorkerRunScope, taskId: string): StatusView {
1661
+ return this.status(taskId, this.workerOwner(run));
1662
+ }
1663
+
1664
+ logForWorker(run: WorkerRunScope, taskId: string, options?: { lines?: number }): LogView {
1665
+ return this.log(taskId, this.workerOwner(run), options);
1666
+ }
1667
+
1668
+ async stopForWorker(run: WorkerRunScope, taskId: string): Promise<StatusView> {
1669
+ return this.stop(taskId, this.workerOwner(run));
1670
+ }
1671
+
1672
+ registerWorkerWait(run: WorkerRunScope, input: WorkerWaitInput): WaitView {
1673
+ const store = this.requireStore();
1674
+ if (!this.continuation && this.rpcRuns.size === 0) {
1675
+ throw new Error("Worker parking requires a verified continuation adapter; start Subagents' coordinator before registering a park wait. The operation was not parked.");
1676
+ }
1677
+ const owner = this.workerOwner(run);
1678
+ const operations = this.operationsForTaskIds(owner, input.taskIds);
1679
+ const registered = store.registerWait({
1680
+ owner,
1681
+ dependencies: operations.map((operation) => ({ operationId: operation.operationId })),
1682
+ continuationNote: input.continuationNote,
1683
+ park: {
1684
+ attemptId: input.attemptId,
1685
+ checkpointId: input.checkpointId,
1686
+ ...(input.writerLeaseId ? { writerLeaseId: input.writerLeaseId } : {}),
1687
+ },
1688
+ origin: { taskIds: [...input.taskIds], attemptId: input.attemptId },
1689
+ });
1690
+ const parking = store.transitionWaitPhase({
1691
+ waitId: registered.wait.waitId,
1692
+ generation: registered.wait.generation,
1693
+ from: "registering",
1694
+ to: "parking",
1695
+ reason: "waiting for the parked worker checkpoint",
1696
+ });
1697
+ return this.waitView(parking.wait);
1698
+ }
1699
+
1700
+ async checkpointWorkerWait(run: WorkerRunScope, input: WorkerCheckpointInput): Promise<WaitView> {
1701
+ const store = this.requireStore();
1702
+ const owner = this.workerOwner(run);
1703
+ const wait = this.ownedWait(owner, input.waitId, input.generation);
1704
+ // A replacement host may replay the post-exit finalization. Once the
1705
+ // generation has left parking, the checkpoint is already proven.
1706
+ if (wait.phase === "waiting" || wait.phase === "ready" || wait.phase === "resuming" || wait.phase === "consumed") {
1707
+ return this.waitView(wait);
1708
+ }
1709
+ if (wait.phase !== "parking") throw new Error(`Wait ${wait.waitId} generation ${wait.generation} is ${wait.phase}, not parking.`);
1710
+ const proof = input.proof;
1711
+ if (!proof?.checkpointRecorded || !proof.writerLeaseReleased || !proof.writerPidGone) {
1712
+ throw new Error("A parked worker wait needs proven checkpoint commit, writer-lease release and original writer process exit before it can leave parking.");
1713
+ }
1714
+ const transitioned = store.transitionWaitPhase({
1715
+ waitId: wait.waitId,
1716
+ generation: wait.generation,
1717
+ from: "parking",
1718
+ to: "waiting",
1719
+ proof,
1720
+ reason: "checkpoint committed and the original writer exited",
1721
+ });
1722
+ await this.dispatchOutbox();
1723
+ return this.waitView(transitioned.wait);
1724
+ }
1725
+
1726
+ /**
1727
+ * Record that the attempt could not become safely parked. A checkpoint that
1728
+ * was never committed must never look parked; if this store version cannot
1729
+ * hold an unproven generation, the generation is cancelled with the failure
1730
+ * reason instead of being left to block every future wait.
1731
+ */
1732
+ failWorkerPark(run: WorkerRunScope, input: { waitId: string; generation: number; reason: string }): WaitView {
1733
+ const store = this.requireStore();
1734
+ const owner = this.workerOwner(run);
1735
+ const wait = this.ownedWait(owner, input.waitId, input.generation);
1736
+ try {
1737
+ const transitioned = store.transitionWaitPhase({
1738
+ waitId: input.waitId,
1739
+ generation: input.generation,
1740
+ from: wait.phase as "registering" | "parking",
1741
+ to: "held",
1742
+ reason: input.reason,
1743
+ });
1744
+ return this.waitView(transitioned.wait);
1745
+ } catch (error) {
1746
+ const code = (error as { code?: unknown }).code;
1747
+ if (code !== "checkpoint-proof" && code !== "wait-phase") throw error;
1748
+ return this.cancelWait(owner, input.waitId, input.generation, `park failed: ${input.reason}`);
1749
+ }
1750
+ }
1751
+
1752
+ readEvidence(run: WorkerRunScope, input: WorkerEvidenceInput): WaitEvidenceView[] {
1753
+ return this.readEvidenceForOwner(this.workerOwner(run), input.waitId, input.generation, input.taskId);
1754
+ }
1755
+
1756
+ acknowledgeForWorker(run: WorkerRunScope, input: WorkerAcknowledgeInput): AcknowledgeView {
1757
+ return this.acknowledge(this.workerOwner(run), input);
1758
+ }
1759
+
1760
+ claimResumeForWorker(run: WorkerRunScope, input: ResumeClaimViewInput): ResumeClaimView {
1761
+ const owner = this.workerOwner(run);
1762
+ this.ownedWait(owner, input.waitId, input.generation);
1763
+ const result = this.requireStore().claimResume({
1764
+ waitId: input.waitId,
1765
+ generation: input.generation,
1766
+ expectedCancelEpoch: input.expectedCancelEpoch,
1767
+ lease: {
1768
+ ownerId: input.lease.ownerId,
1769
+ ...(input.lease.pid !== undefined ? { pid: input.lease.pid } : {}),
1770
+ ...(input.lease.processStartToken !== undefined ? { processStartToken: input.lease.processStartToken } : {}),
1771
+ },
1772
+ reservedCheckpointId: input.reservedCheckpointId,
1773
+ });
1774
+ return {
1775
+ claimId: result.claim.claimId,
1776
+ claimToken: result.claim.claimToken,
1777
+ state: result.claim.state,
1778
+ attemptId: result.claim.attemptId,
1779
+ phase: result.wait.phase,
1780
+ cancelEpoch: result.wait.cancelEpoch,
1781
+ };
1782
+ }
1783
+
1784
+ publishResumeForWorker(run: WorkerRunScope, input: PublishResumeViewInput): ResumeClaimView {
1785
+ this.ownedWait(this.workerOwner(run), input.waitId, input.generation);
1786
+ const result = this.requireStore().publishResumeAttempt({
1787
+ waitId: input.waitId,
1788
+ generation: input.generation,
1789
+ claimId: input.claimId,
1790
+ claimToken: input.claimToken,
1791
+ attemptId: input.attemptId,
1792
+ launchToken: input.launchToken,
1793
+ });
1794
+ return {
1795
+ claimId: result.claim.claimId,
1796
+ claimToken: result.claim.claimToken,
1797
+ state: result.claim.state,
1798
+ attemptId: result.claim.attemptId,
1799
+ phase: result.wait.phase,
1800
+ cancelEpoch: result.wait.cancelEpoch,
1801
+ };
1802
+ }
1803
+
1804
+ releaseResumeForWorker(run: WorkerRunScope, input: ReleaseResumeViewInput): ResumeClaimView {
1805
+ this.ownedWait(this.workerOwner(run), input.waitId, input.generation);
1806
+ const result = this.requireStore().releaseResumeClaim({
1807
+ waitId: input.waitId,
1808
+ generation: input.generation,
1809
+ claimId: input.claimId,
1810
+ claimToken: input.claimToken,
1811
+ outcome: input.outcome,
1812
+ reason: input.reason,
1813
+ });
1814
+ return {
1815
+ claimId: result.claim.claimId,
1816
+ claimToken: result.claim.claimToken,
1817
+ state: result.claim.state,
1818
+ attemptId: result.claim.attemptId,
1819
+ phase: result.wait.phase,
1820
+ cancelEpoch: result.wait.cancelEpoch,
1821
+ };
1822
+ }
1823
+
1824
+ listWorkerWaits(run: WorkerRunScope, options: { pendingOnly?: boolean } = {}): WaitView[] {
1825
+ const store = this.requireStore();
1826
+ return store.listWaits({ owner: this.workerOwner(run), ...(options.pendingOnly ? { pendingOnly: true } : {}) })
1827
+ .map((wait) => this.waitView(wait));
1828
+ }
1829
+
1830
+ cancelWorkerWait(run: WorkerRunScope, input: { waitId: string; generation: number; reason: string }): WaitView {
1831
+ return this.cancelWait(this.workerOwner(run), input.waitId, input.generation, input.reason);
1832
+ }
1833
+
1834
+ /**
1835
+ * A published continuation exited without interpreting its wait.
1836
+ *
1837
+ * This is not a cancellation: the epoch and evidence pins survive and the
1838
+ * generation becomes `held` with the failure reason. The claim is invalidated so
1839
+ * a second automatic attempt can never be published. Only a proven exit is
1840
+ * accepted; an ambiguous identity is refused and stays with its live writer.
1841
+ */
1842
+ holdFailedResumeForWorker(run: WorkerRunScope, input: HoldResumedAttemptInput): HoldResumedAttemptView {
1843
+ const owner = this.workerOwner(run);
1844
+ this.ownedWait(owner, input.waitId, input.generation);
1845
+ const result = this.requireStore().holdFailedResume({
1846
+ waitId: input.waitId,
1847
+ generation: input.generation,
1848
+ claimId: input.claimId,
1849
+ claimToken: input.claimToken,
1850
+ attemptId: input.attemptId,
1851
+ launchToken: input.launchToken,
1852
+ proof: { writerPidGone: input.proof?.writerPidGone === true, writerLeaseReleased: input.proof?.writerLeaseReleased === true },
1853
+ reason: input.reason,
1854
+ });
1855
+ return {
1856
+ waitId: input.waitId,
1857
+ generation: input.generation,
1858
+ phase: result.wait.phase,
1859
+ applied: result.applied,
1860
+ claim: {
1861
+ claimId: result.claim.claimId,
1862
+ state: result.claim.state,
1863
+ attemptId: result.claim.attemptId,
1864
+ ...(result.claim.reason ? { reason: result.claim.reason } : {}),
1865
+ },
1866
+ };
1867
+ }
1868
+
1869
+ registerContinuationAdapter(adapter: ContinuationAdapter): void {
1870
+ if (!adapter || adapter.version !== 1 || typeof adapter.onWaitReady !== "function" || !adapter.id) {
1871
+ throw new Error("A version-1 continuation adapter is required.");
1872
+ }
1873
+ this.continuation = adapter;
1874
+ this.continuationError = undefined;
1875
+ this.announce();
1876
+ void this.dispatchOutbox();
1877
+ }
1878
+
1879
+ unregisterContinuationAdapter(id: string): void {
1880
+ if (this.continuation?.id === id) this.continuation = undefined;
1881
+ this.announce();
1882
+ }
1883
+
1884
+ // ---- Subagents request/reply compatibility surface -------------------
1885
+
1886
+ /** Answer the versioned request/reply channel the Subagents coordinator uses. */
1887
+ listenForWorkerRequests(): void {
1888
+ const events = eventBusOf(this.pi);
1889
+ if (!events) return;
1890
+ events.on(OBSERVED_WAITS_RPC_CHANNEL, (data) => {
1891
+ void this.handleWorkerRequest(data);
1892
+ });
1893
+ }
1894
+
1895
+ private async handleWorkerRequest(data: unknown): Promise<void> {
1896
+ if (!data || typeof data !== "object") return;
1897
+ const request = data as Partial<ObservedWaitsRpcRequest>;
1898
+ if (request.version !== OBSERVED_WAITS_RPC_VERSION || typeof request.method !== "string" ||
1899
+ typeof request.reply !== "function") return;
1900
+ const reply = request.reply;
1901
+ let answered = false;
1902
+ const answer = (value: ObservedWaitsRpcReply): void => {
1903
+ if (answered) return;
1904
+ answered = true;
1905
+ try { reply(value); } catch { /* the requester timed out */ }
1906
+ };
1907
+ const params = request.params && typeof request.params === "object" && !Array.isArray(request.params)
1908
+ ? request.params as JsonRecord
1909
+ : {};
1910
+ if (!this.available && !this.closed) {
1911
+ // A capability probe may arrive before the session_start handler that
1912
+ // normally opens the store. Worker operations are parent-owned, so the
1913
+ // store can open now; the next parent context supplies its origin.
1914
+ this.start();
1915
+ }
1916
+ if (!this.available) {
1917
+ answer({ ok: false, code: "unavailable", reason: this.unavailableReason ?? "Observed waits are unavailable." });
1918
+ return;
1919
+ }
1920
+ try {
1921
+ answer({ ok: true, value: await this.dispatchWorkerRequest(request.method, params) });
1922
+ } catch (error) {
1923
+ answer({
1924
+ ok: false,
1925
+ code: rpcCode(error),
1926
+ reason: oneLine(error instanceof Error ? error.message : String(error), 500),
1927
+ });
1928
+ }
1929
+ }
1930
+
1931
+ private async dispatchWorkerRequest(method: string, params: JsonRecord): Promise<JsonRecord> {
1932
+ switch (method) {
1933
+ case "status":
1934
+ return { version: OBSERVED_WAITS_RPC_VERSION, workerOperations: true, runs: this.rpcRuns.size };
1935
+ case "register-run":
1936
+ return this.rpcRegisterRun(params);
1937
+ case "release-run":
1938
+ return this.rpcReleaseRun(params);
1939
+ case "execute-tool":
1940
+ return this.rpcExecuteTool(params);
1941
+ case "wait-admission":
1942
+ return this.rpcWaitAdmission(params);
1943
+ case "checkpoint":
1944
+ return this.rpcCheckpoint(params);
1945
+ case "park-failed":
1946
+ return this.rpcParkFailed(params);
1947
+ case "acknowledge":
1948
+ return this.rpcAcknowledge(params);
1949
+ case "wait-snapshot":
1950
+ return this.rpcWaitSnapshot(params);
1951
+ case "claim-resume":
1952
+ return this.rpcClaimResume(params);
1953
+ case "publish-resume":
1954
+ return this.rpcPublishResume(params);
1955
+ case "release-resume":
1956
+ return this.rpcReleaseResume(params);
1957
+ case "hold-resume":
1958
+ return this.rpcHoldResume(params);
1959
+ case "cancel-wait":
1960
+ return this.rpcCancelWait(params);
1961
+ default:
1962
+ throw new Error(`Unsupported observed-waits method ${JSON.stringify(method)}.`);
1963
+ }
1964
+ }
1965
+
1966
+ private rpcRegisterRun(params: JsonRecord): JsonRecord {
1967
+ const runId = requireRpcString(params, "runId");
1968
+ const conversationId = requireRpcString(params, "conversationId");
1969
+ const workspace = requireRpcString(params, "workspace");
1970
+ const authorityReference = requireRpcString(params, "authorityReference");
1971
+ const policy = normalizeRunPolicy(params.policy);
1972
+ if (policy.workspace !== workspace) throw new Error("register-run policy.workspace does not match the registered workspace.");
1973
+ const attemptId = typeof params.attemptId === "string" && params.attemptId ? params.attemptId : runId;
1974
+ const owner = normalizeRpcOwner(params.owner, {
1975
+ kind: "worker-conversation",
1976
+ sessionId: conversationId,
1977
+ workspace,
1978
+ branchId: null,
1979
+ goalId: null,
1980
+ });
1981
+ if (owner.sessionId !== conversationId || owner.workspace !== workspace) {
1982
+ throw new Error("register-run owner does not match the conversation and workspace.");
1983
+ }
1984
+ const tools = new Set<string>(Array.isArray(params.tools)
1985
+ ? params.tools.filter((tool): tool is string => typeof tool === "string")
1986
+ : policy.tools);
1987
+ const capabilities = params.capabilities && typeof params.capabilities === "object" && !Array.isArray(params.capabilities)
1988
+ ? params.capabilities as JsonRecord
1989
+ : {};
1990
+ this.rpcRuns.set(runId, Object.freeze({
1991
+ runId,
1992
+ conversationId,
1993
+ attemptId,
1994
+ workspace,
1995
+ authorityReference,
1996
+ policy,
1997
+ owner,
1998
+ tools,
1999
+ capabilities,
2000
+ ...(typeof params.writerPid === "number" && params.writerPid > 0 ? { writerPid: params.writerPid } : {}),
2001
+ ...(typeof params.writerLeaseId === "string" ? { writerLeaseId: params.writerLeaseId } : {}),
2002
+ }));
2003
+ return { runId, conversationId, workspace, attemptId, workerOperations: true };
2004
+ }
2005
+
2006
+ private rpcReleaseRun(params: JsonRecord): JsonRecord {
2007
+ const runId = requireRpcString(params, "runId");
2008
+ this.rpcRuns.delete(runId);
2009
+ if (this.rpcRuns.size === 0) this.waitOwners.clear();
2010
+ return { runId, released: true };
2011
+ }
2012
+
2013
+ private async rpcExecuteTool(params: JsonRecord): Promise<JsonRecord> {
2014
+ const binding = this.requireRpcRun(params);
2015
+ const tool = requireRpcString(params, "tool");
2016
+ const toolParams = params.params && typeof params.params === "object" && !Array.isArray(params.params)
2017
+ ? params.params as JsonRecord
2018
+ : {};
2019
+ if (!binding.tools.has(tool)) {
2020
+ throw new Error(`Tool ${tool} is not in this run's captured tool allowlist.`);
2021
+ }
2022
+ const run = this.rpcScope(binding);
2023
+ const deadlineParams = this.withAssignmentDeadline(binding, toolParams);
2024
+ switch (tool) {
2025
+ case "bg_task_spawn":
2026
+ case "bg_task_watch": {
2027
+ const launch = await this.launchForWorker(run, {
2028
+ kind: tool === "bg_task_watch" ? "watch" : "process",
2029
+ params: deadlineParams,
2030
+ policy: binding.policy.sandbox,
2031
+ });
2032
+ return {
2033
+ id: launch.id,
2034
+ taskId: launch.id,
2035
+ operationId: launch.operationId,
2036
+ kind: launch.kind,
2037
+ status: launch.status,
2038
+ name: launch.name,
2039
+ cwd: launch.cwd,
2040
+ owner: launch.owner as unknown as JsonRecord,
2041
+ durable: true,
2042
+ started: launch.started,
2043
+ claimed: launch.claimed,
2044
+ notices: launch.notices,
2045
+ ...(launch.firstCheck ? { firstCheck: launch.firstCheck as unknown as JsonRecord } : {}),
2046
+ };
2047
+ }
2048
+ case "bg_task_status": {
2049
+ const taskId = this.requireOwnedRpcTask(binding, toolParams);
2050
+ return this.statusForWorker(run, taskId) as unknown as JsonRecord;
2051
+ }
2052
+ case "bg_task_log": {
2053
+ const taskId = this.requireOwnedRpcTask(binding, toolParams);
2054
+ return this.logForWorker(run, taskId, {
2055
+ ...(typeof toolParams.lines === "number" ? { lines: toolParams.lines } : {}),
2056
+ }) as unknown as JsonRecord;
2057
+ }
2058
+ case "bg_task_stop": {
2059
+ const taskId = this.requireOwnedRpcTask(binding, toolParams);
2060
+ return await this.stopForWorker(run, taskId) as unknown as JsonRecord;
2061
+ }
2062
+ default:
2063
+ throw new Error(`Tool ${tool} is not supported by the observed-waits execute-tool surface.`);
2064
+ }
2065
+ }
2066
+
2067
+ private rpcWaitAdmission(params: JsonRecord): JsonRecord {
2068
+ const binding = this.requireRpcRun(params);
2069
+ const taskIds = Array.isArray(params.taskIds)
2070
+ ? params.taskIds.filter((taskId): taskId is string => typeof taskId === "string")
2071
+ : Array.isArray(params.task_ids)
2072
+ ? params.task_ids.filter((taskId): taskId is string => typeof taskId === "string")
2073
+ : [];
2074
+ if (taskIds.length === 0) throw new Error("wait-admission needs at least one task id.");
2075
+ for (const taskId of taskIds) this.requireOwnedRpcTask(binding, { id: taskId });
2076
+ const note = typeof params.continuationNote === "string" ? params.continuationNote
2077
+ : typeof params.continuation_note === "string" ? params.continuation_note : "";
2078
+ if (!note.trim()) throw new Error("wait-admission needs a continuation note.");
2079
+ const owner = normalizeRpcOwner(params.owner, binding.owner);
2080
+ if (owner.sessionId !== binding.conversationId || owner.workspace !== binding.workspace) {
2081
+ throw new Error("wait-admission owner does not match the registered conversation and workspace.");
2082
+ }
2083
+ const attemptId = typeof params.attemptId === "string" && params.attemptId ? params.attemptId : binding.attemptId;
2084
+ const run: WorkerRunScope = {
2085
+ runId: binding.runId,
2086
+ conversationId: binding.conversationId,
2087
+ workspace: binding.workspace,
2088
+ authorityReference: binding.authorityReference,
2089
+ branchId: owner.branchId ?? null,
2090
+ goalId: owner.goalId ?? null,
2091
+ };
2092
+ const wait = this.registerWorkerWait(run, {
2093
+ taskIds,
2094
+ continuationNote: note,
2095
+ attemptId,
2096
+ checkpointId: `park:${attemptId}`,
2097
+ ...(binding.writerLeaseId ? { writerLeaseId: binding.writerLeaseId } : {}),
2098
+ });
2099
+ this.waitOwners.set(waitKey(wait.waitId, wait.generation), this.workerOwner(run));
2100
+ return { ...wait as unknown as JsonRecord, park: true };
2101
+ }
2102
+
2103
+ private rpcCheckpoint(params: JsonRecord): JsonRecord {
2104
+ const binding = this.requireRpcRun(params);
2105
+ const waitId = requireRpcString(params, "waitId");
2106
+ const generation = requireRpcCounter(params, "generation");
2107
+ const { wait, owner } = this.ownedRpcWait(binding, waitId, generation);
2108
+ if (wait.phase === "waiting" || wait.phase === "ready" || wait.phase === "resuming") {
2109
+ return { checkpointed: true, phase: wait.phase, staged: false };
2110
+ }
2111
+ if (wait.phase !== "parking") {
2112
+ throw new Error(`Wait ${waitId} generation ${generation} is ${wait.phase}; a checkpoint can only be recorded while parking.`);
2113
+ }
2114
+ const key = waitKey(waitId, generation);
2115
+ const evidence = params.evidence && typeof params.evidence === "object" && !Array.isArray(params.evidence)
2116
+ ? params.evidence as JsonRecord
2117
+ : undefined;
2118
+ const staged = this.stagedCheckpoints.get(key);
2119
+ if (!evidence && !staged) throw new Error("A park checkpoint needs the verified native checkpoint evidence.");
2120
+ if (evidence) {
2121
+ this.stagedCheckpoints.set(key, {
2122
+ evidence,
2123
+ toolCallId: typeof params.toolCallId === "string" ? params.toolCallId
2124
+ : typeof params.tool_call_id === "string" ? params.tool_call_id : "",
2125
+ checkpointRecorded: true,
2126
+ });
2127
+ }
2128
+ const proofParam = params.proof && typeof params.proof === "object" && !Array.isArray(params.proof)
2129
+ ? params.proof as JsonRecord
2130
+ : undefined;
2131
+ const writerLeaseReleased = params.writerLeaseReleased === true || proofParam?.writerLeaseReleased === true;
2132
+ const writerPidGone = params.writerPidGone === true || proofParam?.writerPidGone === true
2133
+ || (binding.writerPid !== undefined && !processExists(binding.writerPid));
2134
+ if (!writerLeaseReleased || !writerPidGone) {
2135
+ // Staged while the child is alive. The trusted writer-exit observation
2136
+ // must make a second call; the wait never looks parked before that.
2137
+ return { checkpointed: true, phase: "parking", staged: true };
2138
+ }
2139
+ const transitioned = this.requireStore().transitionWaitPhase({
2140
+ waitId,
2141
+ generation,
2142
+ from: "parking",
2143
+ to: "waiting",
2144
+ proof: { checkpointRecorded: true, writerLeaseReleased: true, writerPidGone: true },
2145
+ reason: "trusted park checkpoint and writer process exit",
2146
+ });
2147
+ this.stagedCheckpoints.delete(key);
2148
+ void this.dispatchOutbox();
2149
+ return { checkpointed: true, phase: transitioned.wait.phase, staged: false };
2150
+ }
2151
+
2152
+ private rpcParkFailed(params: JsonRecord): JsonRecord {
2153
+ const binding = this.requireRpcRun(params);
2154
+ const waitId = requireRpcString(params, "waitId");
2155
+ const generation = requireRpcCounter(params, "generation");
2156
+ const reason = requireRpcString(params, "reason");
2157
+ const { wait, owner } = this.ownedRpcWait(binding, waitId, generation);
2158
+ const run: WorkerRunScope = {
2159
+ runId: binding.runId,
2160
+ conversationId: binding.conversationId,
2161
+ workspace: binding.workspace,
2162
+ authorityReference: binding.authorityReference,
2163
+ branchId: owner.branchId ?? null,
2164
+ goalId: owner.goalId ?? null,
2165
+ };
2166
+ const failed = this.failWorkerPark(run, { waitId, generation, reason });
2167
+ this.stagedCheckpoints.delete(waitKey(waitId, generation));
2168
+ return { waitId, generation, phase: failed.phase, held: failed.phase === "held" };
2169
+ }
2170
+
2171
+ private rpcAcknowledge(params: JsonRecord): JsonRecord {
2172
+ const binding = this.requireRpcRun(params);
2173
+ const waitId = requireRpcString(params, "waitId" in params ? "waitId" : "wait_id");
2174
+ const generation = requireRpcCounter(params, "generation");
2175
+ const { owner } = this.ownedRpcWait(binding, waitId, generation);
2176
+ const disposition = params.disposition;
2177
+ if (disposition !== "continue" && disposition !== "blocked" && disposition !== "assignment-complete") {
2178
+ throw new Error("acknowledge disposition must be continue, blocked or assignment-complete.");
2179
+ }
2180
+ const note = typeof params.note === "string" ? params.note : "";
2181
+ const ack = this.acknowledge(owner, {
2182
+ waitId,
2183
+ generation,
2184
+ terminalRevisions: params.terminal_revisions ?? params.terminalRevisions,
2185
+ disposition,
2186
+ note,
2187
+ });
2188
+ return ack as unknown as JsonRecord;
2189
+ }
2190
+
2191
+ private rpcWaitSnapshot(params: JsonRecord): JsonRecord {
2192
+ const waitId = requireRpcString(params, "waitId");
2193
+ const generation = requireRpcCounter(params, "generation");
2194
+ const wait = this.requireStore().getWait({ waitId, generation });
2195
+ if (!wait) throw new Error(`Unknown wait ${waitId} generation ${generation}.`);
2196
+ if (wait.owner.kind !== "worker-conversation") throw new Error(`Wait ${waitId} does not belong to a worker conversation.`);
2197
+ const registered = [...this.rpcRuns.values()].some((run) =>
2198
+ run.conversationId === wait.owner.sessionId && run.workspace === wait.owner.workspace);
2199
+ if (!registered) throw new Error(`Wait ${waitId} belongs to a conversation with no registered worker run.`);
2200
+ const claims = this.requireStore().listResumeClaims({ waitId, generation });
2201
+ const active = claims.find((claim) => claim.state === "claimed" || claim.state === "published");
2202
+ const view = this.waitView(wait);
2203
+ return {
2204
+ ...view as unknown as JsonRecord,
2205
+ cancelEpoch: wait.cancelEpoch,
2206
+ claim: active ? {
2207
+ claimId: active.claimId,
2208
+ state: active.state,
2209
+ attemptId: active.attemptId,
2210
+ reservedCheckpointId: active.reservedCheckpointId,
2211
+ } : null,
2212
+ };
2213
+ }
2214
+
2215
+ private rpcClaimResume(params: JsonRecord): JsonRecord {
2216
+ const binding = this.requireRpcRun(params);
2217
+ const waitId = requireRpcString(params, "waitId");
2218
+ const generation = requireRpcCounter(params, "generation");
2219
+ const { owner } = this.ownedRpcWait(binding, waitId, generation);
2220
+ const lease = params.lease && typeof params.lease === "object" && !Array.isArray(params.lease)
2221
+ ? params.lease as JsonRecord
2222
+ : undefined;
2223
+ if (!lease || typeof lease.ownerId !== "string" || !lease.ownerId) throw new Error("claim-resume requires a lease ownerId.");
2224
+ const result = this.requireStore().claimResume({
2225
+ waitId,
2226
+ generation,
2227
+ expectedCancelEpoch: requireRpcCounter(params, "expectedCancelEpoch"),
2228
+ lease: {
2229
+ ownerId: lease.ownerId,
2230
+ ...(typeof lease.pid === "number" ? { pid: lease.pid } : {}),
2231
+ ...(typeof lease.processStartToken === "string" ? { processStartToken: lease.processStartToken } : {}),
2232
+ },
2233
+ reservedCheckpointId: requireRpcString(params, "reservedCheckpointId"),
2234
+ });
2235
+ void owner;
2236
+ return {
2237
+ claimId: result.claim.claimId,
2238
+ claimToken: result.claim.claimToken,
2239
+ waitId,
2240
+ generation,
2241
+ phase: result.wait.phase,
2242
+ cancelEpoch: result.wait.cancelEpoch,
2243
+ };
2244
+ }
2245
+
2246
+ private rpcPublishResume(params: JsonRecord): JsonRecord {
2247
+ const binding = this.requireRpcRun(params);
2248
+ const waitId = requireRpcString(params, "waitId");
2249
+ const generation = requireRpcCounter(params, "generation");
2250
+ this.ownedRpcWait(binding, waitId, generation);
2251
+ const result = this.requireStore().publishResumeAttempt({
2252
+ waitId,
2253
+ generation,
2254
+ claimId: requireRpcString(params, "claimId"),
2255
+ claimToken: requireRpcString(params, "claimToken"),
2256
+ attemptId: requireRpcString(params, "attemptId"),
2257
+ launchToken: requireRpcString(params, "launchToken"),
2258
+ });
2259
+ return {
2260
+ claimId: result.claim.claimId,
2261
+ state: result.claim.state,
2262
+ attemptId: result.claim.attemptId,
2263
+ published: result.published,
2264
+ phase: result.wait.phase,
2265
+ };
2266
+ }
2267
+
2268
+ private rpcReleaseResume(params: JsonRecord): JsonRecord {
2269
+ const binding = this.requireRpcRun(params);
2270
+ const waitId = requireRpcString(params, "waitId");
2271
+ const generation = requireRpcCounter(params, "generation");
2272
+ this.ownedRpcWait(binding, waitId, generation);
2273
+ const outcome = params.outcome;
2274
+ if (outcome !== "ready" && outcome !== "held") throw new Error("release-resume outcome must be ready or held.");
2275
+ const result = this.requireStore().releaseResumeClaim({
2276
+ waitId,
2277
+ generation,
2278
+ claimId: requireRpcString(params, "claimId"),
2279
+ claimToken: requireRpcString(params, "claimToken"),
2280
+ outcome,
2281
+ reason: requireRpcString(params, "reason"),
2282
+ });
2283
+ return { claimId: result.claim.claimId, state: result.claim.state, phase: result.wait.phase };
2284
+ }
2285
+
2286
+ private rpcHoldResume(params: JsonRecord): JsonRecord {
2287
+ const binding = this.requireRpcRun(params);
2288
+ const waitId = requireRpcString(params, "waitId");
2289
+ const generation = requireRpcCounter(params, "generation");
2290
+ this.ownedRpcWait(binding, waitId, generation);
2291
+ const owner = this.workerOwner(this.rpcScope(binding));
2292
+ const proof = params.proof && typeof params.proof === "object" && !Array.isArray(params.proof)
2293
+ ? params.proof as JsonRecord
2294
+ : {};
2295
+ const result = this.holdFailedResumeForWorker(this.rpcScope(binding), {
2296
+ waitId,
2297
+ generation,
2298
+ claimId: requireRpcString(params, "claimId"),
2299
+ claimToken: requireRpcString(params, "claimToken"),
2300
+ attemptId: requireRpcString(params, "attemptId"),
2301
+ launchToken: requireRpcString(params, "launchToken"),
2302
+ proof: {
2303
+ writerPidGone: proof.writerPidGone === true,
2304
+ writerLeaseReleased: proof.writerLeaseReleased === true,
2305
+ },
2306
+ reason: requireRpcString(params, "reason"),
2307
+ });
2308
+ void owner;
2309
+ return result as unknown as JsonRecord;
2310
+ }
2311
+
2312
+ private rpcCancelWait(params: JsonRecord): JsonRecord {
2313
+ const binding = this.requireRpcRun(params);
2314
+ const waitId = requireRpcString(params, "waitId");
2315
+ const generation = requireRpcCounter(params, "generation");
2316
+ const { wait } = this.ownedRpcWait(binding, waitId, generation);
2317
+ const reason = requireRpcString(params, "reason");
2318
+ const expected = typeof params.expectedCancelEpoch === "number"
2319
+ ? params.expectedCancelEpoch
2320
+ : wait.cancelEpoch;
2321
+ const result = this.requireStore().cancelWait({
2322
+ waitId,
2323
+ generation,
2324
+ expectedCancelEpoch: expected,
2325
+ owner: wait.owner,
2326
+ reason,
2327
+ });
2328
+ this.stagedCheckpoints.delete(waitKey(waitId, generation));
2329
+ try {
2330
+ void Promise.resolve(this.continuation?.onWaitCancelled?.({ waitId, generation, reason })).catch(() => {});
2331
+ } catch { /* persisted cancellation stands */ }
2332
+ return { waitId, generation, phase: result.wait.phase, cancelEpoch: result.wait.cancelEpoch };
2333
+ }
2334
+
2335
+ private requireRpcRun(params: JsonRecord): RpcRunBinding {
2336
+ const runId = requireRpcString(params, "runId");
2337
+ const binding = this.rpcRuns.get(runId);
2338
+ if (!binding) throw new Error(`Run ${runId} is not registered with the Background observed-waits service.`);
2339
+ if (typeof params.conversationId === "string" && params.conversationId !== binding.conversationId) {
2340
+ throw new Error(`Run ${runId} belongs to a different conversation.`);
2341
+ }
2342
+ return binding;
2343
+ }
2344
+
2345
+ private rpcScope(binding: RpcRunBinding): WorkerRunScope {
2346
+ return {
2347
+ runId: binding.runId,
2348
+ conversationId: binding.conversationId,
2349
+ workspace: binding.workspace,
2350
+ authorityReference: binding.authorityReference,
2351
+ branchId: binding.owner.branchId ?? null,
2352
+ goalId: binding.owner.goalId ?? null,
2353
+ };
2354
+ }
2355
+
2356
+ private requireOwnedRpcTask(binding: RpcRunBinding, params: JsonRecord): string {
2357
+ const taskId = requireRpcString(params, "id");
2358
+ if (!LOCAL_DURABLE_ID.test(taskId)) throw new Error(`Task ${taskId} is not a durable local operation.`);
2359
+ const operation = this.operationForTask(taskId);
2360
+ if (!operation) throw new Error(`Unknown durable task ${taskId}.`);
2361
+ if (operation.owner.kind !== "worker-conversation" ||
2362
+ operation.owner.sessionId !== binding.conversationId ||
2363
+ operation.owner.workspace !== binding.workspace) {
2364
+ throw new Error(`Task ${taskId} is not owned by this worker conversation.`);
2365
+ }
2366
+ return taskId;
2367
+ }
2368
+
2369
+ private ownedRpcWait(binding: RpcRunBinding, waitId: string, generation: number): { wait: WaitRecord; owner: OwnerIdentity } {
2370
+ const wait = this.requireStore().getWait({ waitId, generation });
2371
+ if (!wait) throw new Error(`Unknown wait ${waitId} generation ${generation}.`);
2372
+ if (wait.owner.kind !== "worker-conversation" ||
2373
+ wait.owner.sessionId !== binding.conversationId ||
2374
+ wait.owner.workspace !== binding.workspace) {
2375
+ throw new Error(`Wait ${waitId} is not owned by this worker conversation.`);
2376
+ }
2377
+ return { wait, owner: wait.owner };
2378
+ }
2379
+
2380
+ private withAssignmentDeadline(binding: RpcRunBinding, params: JsonRecord): JsonRecord {
2381
+ const deadlineAt = binding.policy.deadlineAt;
2382
+ if (deadlineAt === null) return params;
2383
+ const remaining = (deadlineAt - (this.options.now?.() ?? Date.now())) / 1000;
2384
+ if (!(remaining > 0)) throw new Error("The assignment deadline has expired; no background task was launched.");
2385
+ const requested = typeof params.timeout_seconds === "number" ? params.timeout_seconds : undefined;
2386
+ const timeout = requested === undefined || requested === 0
2387
+ ? remaining
2388
+ : Math.min(requested, remaining);
2389
+ return { ...params, timeout_seconds: timeout };
2390
+ }
2391
+
2392
+ // ---- launch preparation and admission --------------------------------
2393
+
2394
+ private prepareLaunch(
2395
+ kind: DurableTaskKind,
2396
+ params: Record<string, unknown>,
2397
+ tool: string,
2398
+ owner: OwnerIdentity,
2399
+ workerPolicy: WorkerSandboxPolicy | null | undefined,
2400
+ workerWorkspace?: string,
2401
+ ): {
2402
+ plan: ForegroundSandboxPlan;
2403
+ spec: CommandSpec;
2404
+ cwd: string;
2405
+ env?: Record<string, string>;
2406
+ notices: string[];
2407
+ gated: boolean;
2408
+ provenance: TaskSandboxProvenance;
2409
+ commandTimeoutSeconds?: number;
2410
+ } {
2411
+ const cwd = workerWorkspace !== undefined
2412
+ ? this.resolveWorkerCwd(workerWorkspace, params.cwd)
2413
+ : typeof params.cwd === "string" && params.cwd.length > 0
2414
+ ? params.cwd
2415
+ : this.parentOrigin?.cwd ?? owner.workspace;
2416
+ const spec: CommandSpec = {
2417
+ ...(typeof params.command === "string" ? { command: params.command } : {}),
2418
+ ...(Array.isArray(params.argv) && params.argv.every((entry) => typeof entry === "string") ? { argv: params.argv as string[] } : {}),
2419
+ shell: params.shell !== false,
2420
+ ...(typeof params.loginShell === "boolean" ? { loginShell: params.loginShell } : {}),
2421
+ cwd,
2422
+ ...(params.env && typeof params.env === "object" && !Array.isArray(params.env)
2423
+ ? { env: params.env as Record<string, string> } : {}),
2424
+ };
2425
+ validateCommandSpec(spec);
2426
+ if (kind === "watch") {
2427
+ if (!params.success_when) throw new Error("Invalid parameters: watch requires success_when.");
2428
+ for (const [name, condition] of [["success_when", params.success_when], ["failure_when", params.failure_when]] as const) {
2429
+ const error = condition && validateCondition(condition as Condition);
2430
+ if (error) throw new Error(`${name}: ${error}`);
2431
+ }
2432
+ if (params.require_successful_steps === true) {
2433
+ throw new Error("Invalid step gate: require_successful_steps is for a spawned shell command; a watch poll reports its own exit code as the outcome. The task was not started.");
2434
+ }
2435
+ }
2436
+ const plan = workerPolicy !== undefined || owner.kind === "worker-conversation"
2437
+ ? resolveWorkerSandboxPlan(this.pi, workerPolicy, params, tool)
2438
+ : resolveForegroundSandboxPlan(this.pi, false, params, tool);
2439
+ assertBackgroundExecutionAllowed(spec, plan, { remote: false, cwd });
2440
+ const limits = backgroundExecutionLimits(plan);
2441
+ const gated = kind === "process" && params.require_successful_steps === true;
2442
+ if (gated) {
2443
+ if (spec.shell === false) {
2444
+ throw new Error("Invalid step gate: require_successful_steps needs a shell command; argv with shell:false already reports the real exit code. The task was not started.");
2445
+ }
2446
+ if (!spec.command || spec.command.trim().length === 0) {
2447
+ throw new Error("Invalid step gate: require_successful_steps needs a non-empty shell command. The task was not started.");
2448
+ }
2449
+ }
2450
+ return {
2451
+ plan,
2452
+ spec,
2453
+ cwd,
2454
+ ...(spec.env ? { env: spec.env } : {}),
2455
+ notices: [],
2456
+ gated,
2457
+ provenance: sandboxProvenance(plan, false),
2458
+ ...(limits.commandTimeoutSeconds !== undefined ? { commandTimeoutSeconds: limits.commandTimeoutSeconds } : {}),
2459
+ };
2460
+ }
2461
+
2462
+ private async startSupervisor(input: {
2463
+ token: string;
2464
+ taskId: string;
2465
+ kind: DurableTaskKind;
2466
+ params: Record<string, unknown>;
2467
+ prepared: ReturnType<ObservedWaitHost["prepareLaunch"]>;
2468
+ operationId: string;
2469
+ }): Promise<{ started: boolean; claimed: boolean }> {
2470
+ const { token, taskId, kind, params, prepared, operationId } = input;
2471
+ const profilePath = join(supervisorPaths(this.directory, taskId).dir, "sandbox.sb");
2472
+ let spec = prepared.spec;
2473
+ if (prepared.gated) {
2474
+ spec = {
2475
+ ...spec,
2476
+ command: stepGateScript(taskId),
2477
+ env: { ...spec.env, [STEP_GATE_COMMAND_ENV]: prepared.spec.command! },
2478
+ };
2479
+ }
2480
+ const notices: string[] = [];
2481
+ const confined = confineCommandSpec(spec, prepared.plan, profilePath, {}, (line) => notices.push(line));
2482
+ prepared.notices.push(...notices);
2483
+ const { execPath, execArgs } = commandExecution(confined);
2484
+ const options: SupervisorStartOptions = {
2485
+ token,
2486
+ argv: [execPath, ...execArgs],
2487
+ cwd: confined.cwd ?? prepared.cwd,
2488
+ kind: kind === "watch" ? "watch" : "process",
2489
+ ...(typeof params.name === "string" ? { name: params.name } : {}),
2490
+ operationId,
2491
+ ...(prepared.commandTimeoutSeconds !== undefined ? { commandTimeoutSeconds: prepared.commandTimeoutSeconds } : {}),
2492
+ ...(confined.env ? { env: confined.env } : prepared.env ? { env: prepared.env } : {}),
2493
+ ...(typeof params.max_log_bytes === "number" ? { maxLogBytes: params.max_log_bytes } : {}),
2494
+ ...(kind === "watch" ? this.watchOptions(params) : this.processTimeout(params)),
2495
+ };
2496
+ const started = await this.supervisor.start(options);
2497
+ return { started: started.started, claimed: started.claimed };
2498
+ }
2499
+
2500
+ private processTimeout(params: Record<string, unknown>): { timeoutSeconds?: number } {
2501
+ return typeof params.timeout_seconds === "number" ? { timeoutSeconds: params.timeout_seconds } : {};
2502
+ }
2503
+
2504
+ private watchOptions(params: Record<string, unknown>): {
2505
+ intervalSeconds: number;
2506
+ timeoutSeconds: number;
2507
+ successWhen: Condition;
2508
+ failureWhen?: Condition;
2509
+ } {
2510
+ return {
2511
+ intervalSeconds: Math.max(0.001, typeof params.interval_seconds === "number" ? params.interval_seconds : 30),
2512
+ timeoutSeconds: typeof params.timeout_seconds === "number" ? params.timeout_seconds : 900,
2513
+ successWhen: params.success_when as Condition,
2514
+ ...(params.failure_when ? { failureWhen: params.failure_when as Condition } : {}),
2515
+ };
2516
+ }
2517
+
2518
+ /**
2519
+ * Resolve a worker launch directory against the **registered worker
2520
+ * workspace**, never the parent's current directory. Omitted cwd means the
2521
+ * workspace itself; a relative path and symlinks are resolved before the
2522
+ * containment check so the policy and the executed command see one absolute
2523
+ * path.
2524
+ */
2525
+ private resolveWorkerCwd(workspace: string, requested: unknown): string {
2526
+ const base = resolve(workspace);
2527
+ let workspaceReal = base;
2528
+ try { workspaceReal = realpathSync.native(base); } catch { /* the bridge already validated existence */ }
2529
+ const raw = typeof requested === "string" && requested.trim().length > 0 ? requested : ".";
2530
+ let candidate = resolve(base, raw);
2531
+ try { candidate = realpathSync.native(candidate); } catch { /* a missing cwd fails at supervisor start */ }
2532
+ const inside = relative(workspaceReal, candidate);
2533
+ if (inside.startsWith("..") || isAbsolute(inside)) {
2534
+ throw new Error("Worker launch cwd is outside the registered workspace.");
2535
+ }
2536
+ return candidate;
2537
+ }
2538
+
2539
+ // ---- reconciliation --------------------------------------------------
2540
+
2541
+ private reconcileOperation(operation: OperationRecord): void {
2542
+ if (operation.terminalRevision > 0) return;
2543
+ const inspection = this.inspect(operation.taskId);
2544
+ if (!inspection) {
2545
+ const now = this.options.now?.() ?? Date.now();
2546
+ if (now - operation.createdAt >= 30_000) {
2547
+ // The supervisor writes its launch record before spawning. No record
2548
+ // after the claim grace means no execution can be witnessed; this is
2549
+ // `lost`, never a success and never a silent retry.
2550
+ try {
2551
+ this.requireStore().recordTerminalOutcome({
2552
+ operationId: operation.operationId,
2553
+ eventId: `${operation.taskId}:missing:lost`,
2554
+ outcome: "lost",
2555
+ owner: operation.owner,
2556
+ evidence: [{
2557
+ kind: "summary",
2558
+ ref: "lost.json",
2559
+ summary: "status=lost detailLost=true",
2560
+ detailLost: true,
2561
+ }],
2562
+ detailLost: true,
2563
+ reason: "launch produced no durable supervisor record",
2564
+ });
2565
+ } catch { /* a concurrent terminal record wins */ }
2566
+ void this.dispatchOutbox();
2567
+ return;
2568
+ }
2569
+ try {
2570
+ this.store?.recordSupervision({
2571
+ operationId: operation.operationId,
2572
+ owner: operation.owner,
2573
+ health: "unmonitored",
2574
+ reason: "no durable supervisor record exists for this operation",
2575
+ });
2576
+ } catch { /* the owner may have been superseded; health is observational */ }
2577
+ return;
2578
+ }
2579
+ if (inspection.terminal) {
2580
+ this.recordTerminal(operation, inspection);
2581
+ return;
2582
+ }
2583
+ if (operation.health !== "active" || operation.supervision?.hostId !== this.hostId) {
2584
+ // Health is observational; write it only when the supervising host or the
2585
+ // reported health actually changed. A 250 ms tick must not churn SQLite.
2586
+ this.store?.recordSupervision({
2587
+ operationId: operation.operationId,
2588
+ owner: operation.owner,
2589
+ supervision: this.supervision(),
2590
+ health: "active",
2591
+ });
2592
+ }
2593
+ }
2594
+
2595
+ private reconcileInspection(operation: OperationRecord, inspection: SupervisorInspection | undefined): void {
2596
+ if (inspection?.terminal && operation.terminalRevision === 0) this.recordTerminal(operation, inspection);
2597
+ }
2598
+
2599
+ private recordTerminal(operation: OperationRecord, inspection: SupervisorInspection): void {
2600
+ const store = this.requireStore();
2601
+ const status = inspection.status;
2602
+ const outcome = terminalOutcome(status);
2603
+ const eventId = `${operation.taskId}:${inspection.result?.endedAt ?? inspection.lost?.recordedAt ?? inspection.observedAt}:${status}`;
2604
+ const refs = evidenceFor(inspection);
2605
+ let recorded;
2606
+ try {
2607
+ recorded = store.recordTerminalOutcome({
2608
+ operationId: operation.operationId,
2609
+ eventId,
2610
+ outcome,
2611
+ owner: operation.owner,
2612
+ evidence: refs.map((ref) => ({
2613
+ kind: ref.kind,
2614
+ ref: ref.ref,
2615
+ ...(ref.summary ? { summary: ref.summary } : {}),
2616
+ detailLost: ref.detailLost,
2617
+ })),
2618
+ ...(outcome === "lost" ? { detailLost: true } : {}),
2619
+ reason: inspection.result
2620
+ ? `supervisor ${status} exit=${inspection.result.exitCode ?? "null"}`
2621
+ : "supervisor lost: no terminal evidence",
2622
+ });
2623
+ } catch (error) {
2624
+ // A timer and a tool call can observe the same terminal record. The store
2625
+ // keeps the first revision; a replay is never a second execution.
2626
+ this.options.logger?.(`observed waits: terminal replay for ${operation.taskId}: ${oneLine(String(error), 160)}`);
2627
+ return;
2628
+ }
2629
+ const recordContext = this.currentLaunchContext(operation.taskId);
2630
+ if (recordContext) {
2631
+ if (recorded.recorded) {
2632
+ recordContext.terminalRecordedBy = this.hostId;
2633
+ recordContext.terminalRecordedAt = Date.now();
2634
+ recordContext.terminalRecordedWithContext = !!this.activeContext;
2635
+ recordContext.terminalActiveSessionId = this.activeContext ? this.sessionId(this.activeContext) : undefined;
2636
+ recordContext.terminalActiveBranchIds = this.activeContext ? branchIdsOf(this.activeContext) : [];
2637
+ } else {
2638
+ recordContext.terminalReplayObservedBy = this.hostId;
2639
+ }
2640
+ this.launches.set(operation.taskId, recordContext);
2641
+ this.writeLaunchContext(operation.taskId, recordContext);
2642
+ }
2643
+ if (!recorded.recorded) {
2644
+ // A concurrent host recorded this terminal revision. This host may still be
2645
+ // the one with the live owner context; evaluate the callback against it.
2646
+ this.attemptTerminalCallback(
2647
+ recorded.operation,
2648
+ status,
2649
+ outcome,
2650
+ refs,
2651
+ { pendingWithoutContext: true },
2652
+ );
2653
+ return;
2654
+ }
2655
+ this.options.logger?.(`observed waits: ${operation.taskId} ${status} (revision ${recorded.operation.terminalRevision})`);
2656
+ this.attemptTerminalCallback(operation, status, outcome, refs, { pendingWithoutContext: true });
2657
+ this.emitDurableTaskChange();
2658
+ // The parent callback is independent from the worker's wait: a worker may be
2659
+ // parked, while the parent session still learns that the supervised task ended.
2660
+ void this.dispatchOutbox();
2661
+ }
2662
+
2663
+ /**
2664
+ * A parent-owned launch with callbacks on is notified once at its terminal
2665
+ * revision. A registered wait carries the same information and is delivered by
2666
+ * the outbox, so the two paths do not double-notify. A callback is only
2667
+ * receipted after the batcher's real handoff; returning from `notifyParent`
2668
+ * leaves it pending, and a replacement host recovers it.
2669
+ */
2670
+ private attemptTerminalCallback(
2671
+ operation: OperationRecord,
2672
+ status: SupervisorTaskStatus,
2673
+ outcome: string,
2674
+ refs: readonly WaitEvidenceView[],
2675
+ options: { pendingWithoutContext?: boolean } = {},
2676
+ ): void {
2677
+ const context = this.currentLaunchContext(operation.taskId);
2678
+ const skip = (reason: string): void => {
2679
+ if (!context) return;
2680
+ if (context.callbackSkipReason === reason && context.callbackAttemptedAt !== undefined) return;
2681
+ context.callbackAttemptedAt = Date.now();
2682
+ context.callbackSkipReason = oneLine(reason, 200);
2683
+ this.launches.set(operation.taskId, context);
2684
+ this.writeLaunchContext(operation.taskId, context);
2685
+ };
2686
+ if (!this.options.notifyParent) return;
2687
+ if (operation.owner.kind !== "parent-session") return;
2688
+ if (!context) return;
2689
+ if (context.callback === false) return;
2690
+ // Never write any journal field while a newer or unprovable other host owns
2691
+ // the claim. In particular, a stale host's reconcile must not rewrite its
2692
+ // cached claim token over the current shared one.
2693
+ const claim = this.claimState(context.callbackClaimedBy);
2694
+ if (claim === "live" || claim === "unknown") return;
2695
+ if (context.callbackDeliveredAt !== undefined) {
2696
+ this.pendingTerminalCallbacks.delete(operation.taskId);
2697
+ skip("already delivered");
2698
+ return;
2699
+ }
2700
+ const waitPending = this.store?.listWaits({ owner: operation.owner, pendingOnly: true })
2701
+ .some((wait) => wait.dependencies.some((dep) => dep.operationId === operation.operationId)) ?? false;
2702
+ if (waitPending) {
2703
+ this.pendingTerminalCallbacks.delete(operation.taskId);
2704
+ skip("a registered wait owns delivery");
2705
+ return;
2706
+ }
2707
+ if (claim === "self") return; // this host's event is already in flight
2708
+ if (!this.activeContext) {
2709
+ // This host recorded terminal before a session context was restored. Keep
2710
+ // the callback pending so the next activation/tool call can hand it off;
2711
+ // never notify without an exact active owner.
2712
+ skip("no active context; pending");
2713
+ if (options.pendingWithoutContext) this.markCallbackPending(operation.taskId, context);
2714
+ return;
2715
+ }
2716
+ // A shared coordinator store can contain other sessions' operations. They are
2717
+ // never this host's callback work, even when they are terminal. An active
2718
+ // context without a readable session identity is unknown, so keep pending.
2719
+ const relation = this.activeOwnerRelation(operation.owner);
2720
+ if (relation === "unknown") {
2721
+ skip("active session identity is unavailable; pending");
2722
+ if (options.pendingWithoutContext) this.markCallbackPending(operation.taskId, context);
2723
+ return;
2724
+ }
2725
+ if (relation === "foreign") {
2726
+ // Another session owns this operation. This host may have recorded the
2727
+ // terminal revision while reconciling the shared store, but it must not
2728
+ // write callback journal state or clear the owner's pending work.
2729
+ this.pendingTerminalCallbacks.delete(operation.taskId);
2730
+ return;
2731
+ }
2732
+ // A terminal result can become eligible later: the live session may have
2733
+ // been settling when the record was produced, or the owner may navigate
2734
+ // back to an eligible descendant branch. Keep retrying only this id.
2735
+ this.pendingTerminalCallbacks.add(operation.taskId);
2736
+ const origin = context.parentOrigin ?? { cwd: operation.owner.workspace, sessionId: operation.owner.sessionId };
2737
+ const branchId = context.branchId ?? operation.owner.branchId;
2738
+ if (!this.isParentOriginActive(origin, branchId)) {
2739
+ skip("recorded branch anchor is not on the active branch; pending");
2740
+ this.markCallbackPending(operation.taskId, context);
2741
+ return;
2742
+ }
2743
+ context.callbackAttemptedAt = Date.now();
2744
+ context.callbackSkipReason = undefined;
2745
+ context.callbackPendingAt ??= Date.now();
2746
+ context.callbackClaimedBy = this.hostId;
2747
+ context.callbackClaimedAt = Date.now();
2748
+ context.callbackClaimToken = randomUUID();
2749
+ context.callbackDeferredReason = undefined;
2750
+ this.launches.set(operation.taskId, context);
2751
+ this.writeLaunchContext(operation.taskId, context);
2752
+ const claimToken = context.callbackClaimToken;
2753
+ let settled = false;
2754
+ const delivery: ParentDelivery = {
2755
+ delivered: () => {
2756
+ if (settled) return;
2757
+ settled = true;
2758
+ this.completeTerminalCallback(operation.taskId, claimToken);
2759
+ },
2760
+ defer: (reason: string) => {
2761
+ if (settled) return;
2762
+ settled = true;
2763
+ this.deferTerminalCallback(operation.taskId, reason, true, claimToken);
2764
+ },
2765
+ };
2766
+ try {
2767
+ this.options.notifyParent({
2768
+ taskId: operation.taskId,
2769
+ origin,
2770
+ branchId,
2771
+ operationId: operation.operationId,
2772
+ status,
2773
+ outcome,
2774
+ summary: refs[0]?.summary ?? `terminal revision ${operation.terminalRevision}`,
2775
+ evidence: refs.map((ref) => ({
2776
+ ...ref,
2777
+ operationId: operation.operationId,
2778
+ taskId: operation.taskId,
2779
+ terminalRevision: operation.terminalRevision,
2780
+ })),
2781
+ }, delivery);
2782
+ } catch (error) {
2783
+ // A notifier that threw synchronously must not spin the microtask retry.
2784
+ this.deferTerminalCallback(operation.taskId, error instanceof Error ? error.message : String(error), false, claimToken);
2785
+ }
2786
+ }
2787
+
2788
+ /**
2789
+ * Exact owner relation for the live context. An active context without a
2790
+ * readable session identity is `unknown`, never `foreign`: a terminal result
2791
+ * stays pending until the real session identity is restored.
2792
+ */
2793
+ private activeOwnerRelation(owner: OwnerIdentity): "match" | "foreign" | "unknown" {
2794
+ const ctx = this.activeContext;
2795
+ if (!ctx) return "unknown";
2796
+ let cwd: string;
2797
+ try { cwd = ctx.cwd; } catch { return "unknown"; }
2798
+ if (cwd !== owner.workspace) return "foreign";
2799
+ const known = this.sessionIdIfAvailable(ctx);
2800
+ if (known) return owner.sessionId === known ? "match" : "foreign";
2801
+ const fallback = this.sessionId(ctx);
2802
+ if (owner.sessionId === fallback) return "match";
2803
+ // A real owner and an anonymous active context cannot prove each other.
2804
+ return owner.sessionId.startsWith("anonymous:") ? "foreign" : "unknown";
2805
+ }
2806
+
2807
+ private markCallbackPending(taskId: string, context = this.currentLaunchContext(taskId)): void {
2808
+ if (!context || context.callbackDeliveredAt !== undefined) return;
2809
+ const claim = this.claimState(context.callbackClaimedBy);
2810
+ if (claim === "live" || claim === "unknown") {
2811
+ this.pendingTerminalCallbacks.add(taskId);
2812
+ return; // preserve the current owner's claim without any write
2813
+ }
2814
+ context.callbackPendingAt ??= Date.now();
2815
+ this.launches.set(taskId, context);
2816
+ this.writeLaunchContext(taskId, context);
2817
+ this.pendingTerminalCallbacks.add(taskId);
2818
+ }
2819
+
2820
+ private completeTerminalCallback(taskId: string, claimToken?: string): void {
2821
+ // The sidecar is shared across hosts and is authoritative for the claim.
2822
+ // Never validate a stale delivery against this host's cached launch object.
2823
+ const context = this.currentLaunchContext(taskId);
2824
+ if (!context) return;
2825
+ // A stale handoff from an older attempt must not receipt a newer attempt.
2826
+ if (claimToken !== undefined && context.callbackClaimToken !== claimToken) return;
2827
+ this.pendingTerminalCallbacks.delete(taskId);
2828
+ context.callbackDeliveredAt ??= Date.now();
2829
+ context.callbackAttemptedAt = Date.now();
2830
+ delete context.callbackSkipReason;
2831
+ delete context.callbackPendingAt;
2832
+ delete context.callbackClaimedBy;
2833
+ delete context.callbackClaimedAt;
2834
+ delete context.callbackClaimToken;
2835
+ delete context.callbackDeferredReason;
2836
+ this.launches.set(taskId, context);
2837
+ this.writeLaunchContext(taskId, context);
2838
+ this.emitDurableTaskChange();
2839
+ }
2840
+
2841
+ private deferTerminalCallback(taskId: string, reason: string, retry = true, claimToken?: string): void {
2842
+ const context = this.currentLaunchContext(taskId);
2843
+ if (!context || context.callbackDeliveredAt !== undefined) return;
2844
+ // A stale suppression must not clear the claim of a newer attempt.
2845
+ if (claimToken !== undefined && context.callbackClaimToken !== claimToken) return;
2846
+ this.pendingTerminalCallbacks.add(taskId);
2847
+ context.callbackDeferredReason = oneLine(reason, 200);
2848
+ context.callbackAttemptedAt = Date.now();
2849
+ context.callbackSkipReason = `deferred: ${oneLine(reason, 160)}`;
2850
+ delete context.callbackClaimedBy;
2851
+ delete context.callbackClaimedAt;
2852
+ delete context.callbackClaimToken;
2853
+ this.launches.set(taskId, context);
2854
+ this.writeLaunchContext(taskId, context);
2855
+ if (retry) {
2856
+ // A batcher suppression can land after a session_tree retry already saw
2857
+ // the old claim. Re-evaluate the live branch after the claim is cleared.
2858
+ queueMicrotask(() => {
2859
+ if (!this.closed) this.retryPendingTerminalCallbacks();
2860
+ });
2861
+ }
2862
+ }
2863
+
2864
+ private outboxHandoffProof(
2865
+ taskId: string,
2866
+ event: OutboxEventRecord,
2867
+ ): boolean {
2868
+ const proof = this.currentLaunchContext(taskId)?.outboxDelivered?.[event.eventId];
2869
+ return !!proof && proof.waitId === event.waitId && proof.generation === event.generation
2870
+ && proof.terminalRevision === event.terminalRevision;
2871
+ }
2872
+
2873
+ private recordOutboxHandoffProof(taskId: string, event: OutboxEventRecord): void {
2874
+ const context = this.currentLaunchContext(taskId);
2875
+ if (!context) return;
2876
+ const map = { ...(context.outboxDelivered ?? {}) };
2877
+ const at = this.options.now?.() ?? Date.now();
2878
+ map[event.eventId] = {
2879
+ waitId: event.waitId,
2880
+ generation: event.generation,
2881
+ terminalRevision: event.terminalRevision,
2882
+ deliveredAt: at,
2883
+ };
2884
+ const kept = Object.entries(map)
2885
+ .sort((a, b) => b[1].deliveredAt - a[1].deliveredAt)
2886
+ .slice(0, 20);
2887
+ context.outboxDelivered = Object.fromEntries(kept);
2888
+ this.launches.set(taskId, context);
2889
+ this.writeLaunchContext(taskId, context);
2890
+ }
2891
+
2892
+ private clearOutboxHandoffProof(taskId: string, eventId: string): void {
2893
+ const context = this.currentLaunchContext(taskId);
2894
+ if (!context?.outboxDelivered || !(eventId in context.outboxDelivered)) return;
2895
+ const map = { ...context.outboxDelivered };
2896
+ delete map[eventId];
2897
+ context.outboxDelivered = map;
2898
+ this.launches.set(taskId, context);
2899
+ this.writeLaunchContext(taskId, context);
2900
+ }
2901
+
2902
+ /**
2903
+ * Identity of a claiming host. Liveness uses the process start token, not
2904
+ * elapsed time. `unknown` is held: an unprovable owner is never stolen from.
2905
+ */
2906
+ private claimState(hostId: string | undefined): "none" | "self" | "live" | "dead" | "unknown" {
2907
+ if (!hostId) return "none";
2908
+ if (hostId === this.hostId) return "self";
2909
+ const { pid, startTokenDigest: claimedDigest } = parseHostIdentity(hostId);
2910
+ if (!pid) return "unknown";
2911
+ if (HOST_INSTANCE_STATE.closed.has(hostId)) return "dead";
2912
+ const generation = HOST_INSTANCE_STATE.generations.get(hostId);
2913
+ if (generation !== undefined) {
2914
+ if (pid === process.pid) {
2915
+ // A newer live instance owns the claim; an older one is a reload
2916
+ // predecessor whose claim this host may recover.
2917
+ return generation > this.hostGeneration ? "live" : "dead";
2918
+ }
2919
+ }
2920
+ // A different instance with this process's pid is a previous instance in the
2921
+ // same process (a reload) or a host this process cannot prove is current.
2922
+ if (pid === process.pid) return "dead";
2923
+ if (!processExists(pid)) return "dead";
2924
+ if (!claimedDigest) return "unknown";
2925
+ const current = readProcessStartToken(pid);
2926
+ if (!current) return "unknown";
2927
+ return startTokenDigest(current) === claimedDigest ? "live" : "dead";
2928
+ }
2929
+
2930
+ /**
2931
+ * Recover deliveries whose claiming host disappeared (reload, crash, or a
2932
+ * session switch). A claim owned by a live or unprovable host is left alone.
2933
+ */
2934
+ private recoverAbandonedDeliveries(): void {
2935
+ const store = this.store;
2936
+ if (!store) return;
2937
+ for (const event of store.listOutbox({ state: "claimed" })) {
2938
+ const claim = event.dispatchClaim;
2939
+ if (!claim || claim.claimedBy === this.hostId) continue;
2940
+ if (this.claimState(claim.claimedBy) !== "dead") continue;
2941
+ try {
2942
+ store.releaseOutbox({
2943
+ eventId: event.eventId,
2944
+ claimToken: claim.token,
2945
+ reason: "abandoned callback delivery claim recovered",
2946
+ });
2947
+ } catch { /* another host already recovered it */ }
2948
+ }
2949
+ for (const operation of store.listOperations({ phase: "terminal" })) {
2950
+ const context = this.currentLaunchContext(operation.taskId);
2951
+ if (!context?.callbackClaimedBy || context.callbackClaimedBy === this.hostId) continue;
2952
+ if (this.claimState(context.callbackClaimedBy) !== "dead") continue;
2953
+ delete context.callbackClaimedBy;
2954
+ delete context.callbackClaimedAt;
2955
+ delete context.callbackClaimToken;
2956
+ this.launches.set(operation.taskId, context);
2957
+ this.writeLaunchContext(operation.taskId, context);
2958
+ }
2959
+ }
2960
+
2961
+ private inspect(taskId: string): SupervisorInspection | undefined {
2962
+ if (!LOCAL_DURABLE_ID.test(taskId)) return undefined;
2963
+ try {
2964
+ return this.supervisor.inspect(taskId, { recordLost: true });
2965
+ } catch {
2966
+ return undefined;
2967
+ }
2968
+ }
2969
+
2970
+ private async dispatchOutbox(): Promise<void> {
2971
+ const store = this.store;
2972
+ if (!store || this.closed) return;
2973
+ const pending = store.listOutbox({ state: "pending" });
2974
+ if (pending.length === 0) return;
2975
+ const byRecipient = new Map<string, { owner: OwnerIdentity; events: OutboxEventRecord[] }>();
2976
+ for (const event of pending) {
2977
+ const key = ownerKey(event.recipient);
2978
+ const entry = byRecipient.get(key) ?? { owner: event.recipient, events: [] };
2979
+ entry.events.push(event);
2980
+ byRecipient.set(key, entry);
2981
+ }
2982
+ for (const { owner, events } of byRecipient.values()) {
2983
+ if (owner.kind === "worker-conversation" && !this.continuation && this.rpcRuns.size === 0) continue;
2984
+ const claimToken = `dispatch_${randomUUID()}`;
2985
+ let claimed: OutboxEventRecord[];
2986
+ try {
2987
+ claimed = store.claimOutbox({
2988
+ recipient: owner,
2989
+ claimToken,
2990
+ claimedBy: this.hostId,
2991
+ limit: Math.min(events.length, 20),
2992
+ });
2993
+ } catch (error) {
2994
+ this.options.logger?.(`observed waits: outbox claim failed: ${oneLine(String(error), 160)}`);
2995
+ continue;
2996
+ }
2997
+ for (const event of claimed) {
2998
+ const operation = store.getOperation(event.operationId);
2999
+ const taskId = operation?.taskId;
3000
+ const evidence = mapEvidence(
3001
+ event.operationId,
3002
+ taskId,
3003
+ event.evidence.map((pin) => ({
3004
+ operationId: pin.operationId,
3005
+ ...(taskId ? { taskId } : {}),
3006
+ terminalRevision: pin.terminalRevision,
3007
+ kind: pin.kind,
3008
+ ref: pin.ref,
3009
+ ...(pin.summary ? { summary: pin.summary } : {}),
3010
+ detailLost: pin.detailLost,
3011
+ })),
3012
+ event.terminalRevision,
3013
+ );
3014
+ try {
3015
+ if (owner.kind === "worker-conversation" && this.continuation) {
3016
+ const adapter = this.continuation;
3017
+ const wait = store.getWait({ waitId: event.waitId, generation: event.generation });
3018
+ const outcome = await adapter.onWaitReady({
3019
+ waitId: event.waitId,
3020
+ generation: event.generation,
3021
+ owner,
3022
+ ...(taskId && this.launches.get(taskId)?.parentOrigin
3023
+ ? { parentOrigin: this.launches.get(taskId)!.parentOrigin }
3024
+ : {}),
3025
+ taskIds: wait ? this.waitTaskIds(wait) : [],
3026
+ continuationNote: wait?.continuationNote ?? "",
3027
+ evidence,
3028
+ });
3029
+ if (outcome === "deferred") {
3030
+ store.releaseOutbox({ eventId: event.eventId, claimToken, reason: "continuation owner is inactive; delivery deferred" });
3031
+ continue;
3032
+ }
3033
+ } else if (owner.kind === "worker-conversation") {
3034
+ const wait = store.getWait({ waitId: event.waitId, generation: event.generation });
3035
+ eventBusOf(this.pi)?.emit(OBSERVED_WAITS_READY_CHANNEL, {
3036
+ version: OBSERVED_WAITS_RPC_VERSION,
3037
+ waitId: event.waitId,
3038
+ generation: event.generation,
3039
+ owner,
3040
+ taskIds: wait ? this.waitTaskIds(wait) : [],
3041
+ continuationNote: wait?.continuationNote ?? "",
3042
+ });
3043
+ } else {
3044
+ if (!this.options.notifyParent) {
3045
+ store.releaseOutbox({ eventId: event.eventId, claimToken, reason: "no parent notification channel is available" });
3046
+ continue;
3047
+ }
3048
+ const context = taskId ? this.launchContext(taskId) : undefined;
3049
+ // A handoff that landed just as the store closed is recorded against
3050
+ // this exact event, wait generation and terminal revision. A task-wide
3051
+ // standalone callback receipt is never proof for a later wait.
3052
+ if (taskId && this.outboxHandoffProof(taskId, event)) {
3053
+ try { store.markOutboxDelivered({ eventId: event.eventId, claimToken }); } catch { /* already receipted */ }
3054
+ this.clearOutboxHandoffProof(taskId, event.eventId);
3055
+ continue;
3056
+ }
3057
+ const origin = context?.parentOrigin ?? { cwd: owner.workspace, sessionId: owner.sessionId };
3058
+ const branchId = context?.branchId ?? owner.branchId ?? null;
3059
+ if (!this.isParentOriginActive(origin, branchId)) {
3060
+ // Keep the durable delivery pending: the owning session may activate
3061
+ // (or regain the eligible branch) later. Never route it to whoever is
3062
+ // currently in front of the UI.
3063
+ store.releaseOutbox({
3064
+ eventId: event.eventId,
3065
+ claimToken,
3066
+ reason: "owning session or branch is not active",
3067
+ });
3068
+ continue;
3069
+ }
3070
+ let settled = false;
3071
+ const delivery: ParentDelivery = {
3072
+ delivered: () => {
3073
+ if (settled) return;
3074
+ settled = true;
3075
+ let receipted = false;
3076
+ try {
3077
+ store.markOutboxDelivered({ eventId: event.eventId, claimToken });
3078
+ receipted = true;
3079
+ } catch { /* the store closed between handoff and receipt */ }
3080
+ // Key the recovered receipt to this exact event. Never use the
3081
+ // standalone task callback's receipt as proof for a wait.
3082
+ if (!receipted && taskId) this.recordOutboxHandoffProof(taskId, event);
3083
+ },
3084
+ defer: (reason: string) => {
3085
+ if (settled) return;
3086
+ settled = true;
3087
+ try {
3088
+ store.releaseOutbox({
3089
+ eventId: event.eventId,
3090
+ claimToken,
3091
+ reason: oneLine(reason, 200) || "callback delivery deferred",
3092
+ });
3093
+ } catch { /* another host recovered it */ }
3094
+ if (taskId) this.markCallbackPending(taskId);
3095
+ },
3096
+ };
3097
+ try {
3098
+ this.options.notifyParent({
3099
+ taskId: taskId ?? event.operationId,
3100
+ origin,
3101
+ branchId,
3102
+ operationId: event.operationId,
3103
+ waitId: event.waitId,
3104
+ generation: event.generation,
3105
+ status: this.statusOf(event.operationId),
3106
+ outcome: operation?.terminalOutcome ?? "failed",
3107
+ summary: evidence[0]?.summary ?? "terminal evidence is available",
3108
+ evidence,
3109
+ }, delivery);
3110
+ } catch (error) {
3111
+ delivery.defer(error instanceof Error ? error.message : String(error));
3112
+ }
3113
+ // The callback remains claimed until the batcher's actual handoff
3114
+ // calls `delivered()`; a reload recovers the abandoned claim.
3115
+ continue;
3116
+ }
3117
+ store.markOutboxDelivered({ eventId: event.eventId, claimToken });
3118
+ } catch (error) {
3119
+ if (this.closed) return;
3120
+ try {
3121
+ store.releaseOutbox({
3122
+ eventId: event.eventId,
3123
+ claimToken,
3124
+ reason: oneLine(error instanceof Error ? error.message : String(error), 200) || "delivery failed",
3125
+ });
3126
+ } catch { /* the store closed while the delivery was in flight */ }
3127
+ }
3128
+ }
3129
+ }
3130
+ }
3131
+
3132
+ private statusOf(operationId: string): SupervisorTaskStatus {
3133
+ const operation = this.store?.getOperation(operationId);
3134
+ if (!operation) return "lost";
3135
+ if (operation.terminalRevision === 0) return "running";
3136
+ switch (operation.terminalOutcome) {
3137
+ case "succeeded": return "succeeded";
3138
+ case "cancelled": return "cancelled";
3139
+ case "lost": return "lost";
3140
+ default: return "failed";
3141
+ }
3142
+ }
3143
+
3144
+ // ---- wait helpers ----------------------------------------------------
3145
+
3146
+ private waitView(wait: WaitRecord): WaitView {
3147
+ const store = this.requireStore();
3148
+ const dependencies = wait.dependencies.map((dep): WaitDependencyView => {
3149
+ const operation = store.getOperation(dep.operationId);
3150
+ return {
3151
+ ...(operation?.taskId ? { taskId: operation.taskId } : {}),
3152
+ operationId: dep.operationId,
3153
+ terminalRevision: dep.terminalRevision,
3154
+ terminalOutcome: dep.terminalOutcome,
3155
+ };
3156
+ });
3157
+ const evidence: WaitEvidenceView[] = [];
3158
+ for (const dep of wait.dependencies) {
3159
+ if (dep.terminalRevision <= 0) continue;
3160
+ const operation = store.getOperation(dep.operationId);
3161
+ evidence.push(...mapEvidence(
3162
+ dep.operationId,
3163
+ operation?.taskId,
3164
+ store.listOperationEvidence(dep.operationId, dep.terminalRevision),
3165
+ dep.terminalRevision,
3166
+ ));
3167
+ }
3168
+ return {
3169
+ waitId: wait.waitId,
3170
+ generation: wait.generation,
3171
+ phase: wait.phase,
3172
+ settled: wait.settled,
3173
+ park: wait.park !== null,
3174
+ cancelEpoch: wait.cancelEpoch,
3175
+ ownerKind: wait.owner.kind,
3176
+ continuationNote: wait.continuationNote,
3177
+ taskIds: dependencies
3178
+ .map((dep) => dep.taskId)
3179
+ .filter((taskId): taskId is string => typeof taskId === "string"),
3180
+ dependencies,
3181
+ evidence,
3182
+ };
3183
+ }
3184
+
3185
+ private waitTaskIds(wait: WaitRecord): string[] {
3186
+ return wait.dependencies
3187
+ .map((dep) => this.store?.getOperation(dep.operationId)?.taskId)
3188
+ .filter((taskId): taskId is string => typeof taskId === "string");
3189
+ }
3190
+
3191
+ private readEvidenceForOwner(owner: OwnerIdentity, waitId: string, generation: number, taskId?: string): WaitEvidenceView[] {
3192
+ const store = this.requireStore();
3193
+ const wait = this.ownedWait(owner, waitId, generation);
3194
+ const reads: WaitEvidenceView[] = [];
3195
+ for (const dep of wait.dependencies) {
3196
+ if (dep.terminalRevision <= 0) continue;
3197
+ const operation = store.getOperation(dep.operationId);
3198
+ if (!operation) continue;
3199
+ if (taskId && operation.taskId !== taskId) continue;
3200
+ store.recordEvidenceRead({
3201
+ waitId,
3202
+ generation,
3203
+ owner,
3204
+ operationId: dep.operationId,
3205
+ terminalRevision: dep.terminalRevision,
3206
+ });
3207
+ reads.push(...mapEvidence(
3208
+ dep.operationId,
3209
+ operation.taskId,
3210
+ store.listOperationEvidence(dep.operationId, dep.terminalRevision),
3211
+ dep.terminalRevision,
3212
+ ));
3213
+ }
3214
+ return reads;
3215
+ }
3216
+
3217
+ /** A status/log read is the evidence read the acknowledgement requires. */
3218
+ private recordReadsForTask(owner: OwnerIdentity, operation: OperationRecord): void {
3219
+ const store = this.store;
3220
+ if (!store || operation.terminalRevision <= 0) return;
3221
+ for (const wait of store.listWaits({ owner, pendingOnly: true })) {
3222
+ const dep = wait.dependencies.find((entry) => entry.operationId === operation.operationId);
3223
+ if (!dep || dep.terminalRevision <= 0) continue;
3224
+ try {
3225
+ store.recordEvidenceRead({
3226
+ waitId: wait.waitId,
3227
+ generation: wait.generation,
3228
+ owner,
3229
+ operationId: operation.operationId,
3230
+ terminalRevision: dep.terminalRevision,
3231
+ });
3232
+ } catch { /* a consumed or foreign generation is not this read's business */ }
3233
+ }
3234
+ }
3235
+
3236
+ private cancelWait(owner: OwnerIdentity, waitId: string, generation: number, reason: string): WaitView {
3237
+ const store = this.requireStore();
3238
+ const wait = this.ownedWait(owner, waitId, generation);
3239
+ const cancelled = store.cancelWait({
3240
+ waitId,
3241
+ generation,
3242
+ expectedCancelEpoch: wait.cancelEpoch,
3243
+ owner,
3244
+ reason,
3245
+ });
3246
+ try {
3247
+ void Promise.resolve(this.continuation?.onWaitCancelled?.({ waitId, generation, reason })).catch(() => {});
3248
+ } catch { /* a continuation adapter failure cannot undo a persisted cancellation */ }
3249
+ return this.waitView(cancelled.wait);
3250
+ }
3251
+
3252
+ private acknowledge(owner: OwnerIdentity, input: WorkerAcknowledgeInput): AcknowledgeView {
3253
+ const store = this.requireStore();
3254
+ const wait = this.ownedWait(owner, input.waitId, input.generation);
3255
+ const revisions = this.normalizeRevisions(wait, input.terminalRevisions);
3256
+ const result = store.acknowledgeResult({
3257
+ waitId: wait.waitId,
3258
+ generation: wait.generation,
3259
+ owner,
3260
+ disposition: input.disposition,
3261
+ note: input.note,
3262
+ terminalRevisions: revisions,
3263
+ });
3264
+ return {
3265
+ waitId: result.wait.waitId,
3266
+ generation: result.wait.generation,
3267
+ disposition: input.disposition,
3268
+ acknowledgedOutboxIds: result.acknowledgedOutboxIds,
3269
+ releasedPinIds: result.releasedPinIds,
3270
+ phase: result.wait.phase,
3271
+ };
3272
+ }
3273
+
3274
+ private normalizeRevisions(wait: WaitRecord, input: unknown): Array<{ operationId: string; revision: number }> {
3275
+ const store = this.requireStore();
3276
+ const resolved: Array<{ operationId: string; revision: number }> = [];
3277
+ const add = (operationId: unknown, taskId: unknown, revision: unknown) => {
3278
+ if (typeof revision !== "number" || !Number.isSafeInteger(revision) || revision < 1) {
3279
+ throw new Error("terminal_revisions must carry positive integer revisions.");
3280
+ }
3281
+ let operationIdValue = typeof operationId === "string" ? operationId : undefined;
3282
+ if (!operationIdValue && typeof taskId === "string") {
3283
+ operationIdValue = this.operationForTask(taskId)?.operationId;
3284
+ }
3285
+ if (!operationIdValue) throw new Error("terminal_revisions must name an operation_id (or a known task_id).");
3286
+ const dependency = wait.dependencies.find((dep) => dep.operationId === operationIdValue);
3287
+ if (!dependency) throw new Error(`Operation ${operationIdValue} is not a dependency of wait ${wait.waitId}.`);
3288
+ if (dependency.terminalRevision !== revision) {
3289
+ throw new Error(`Operation ${operationIdValue} is at terminal revision ${dependency.terminalRevision}, not ${revision}.`);
3290
+ }
3291
+ resolved.push({ operationId: operationIdValue, revision });
3292
+ };
3293
+ if (Array.isArray(input)) {
3294
+ for (const entry of input) {
3295
+ if (!entry || typeof entry !== "object") throw new Error("terminal_revisions entries must be objects.");
3296
+ const record = entry as Record<string, unknown>;
3297
+ add(record.operation_id ?? record.operationId, record.task_id ?? record.taskId, record.revision);
3298
+ }
3299
+ } else if (input && typeof input === "object") {
3300
+ for (const [key, revision] of Object.entries(input)) {
3301
+ const operation = store.getOperation(key) ? key : this.operationForTask(key)?.operationId;
3302
+ add(operation, key, revision);
3303
+ }
3304
+ } else {
3305
+ throw new Error("terminal_revisions is required.");
3306
+ }
3307
+ const unique = new Map(resolved.map((entry) => [entry.operationId, entry.revision]));
3308
+ if (unique.size === 0) throw new Error("terminal_revisions is empty.");
3309
+ return [...unique].map(([operationId, revision]) => ({ operationId, revision }));
3310
+ }
3311
+
3312
+ // ---- identity and ownership -----------------------------------------
3313
+
3314
+ private sessionId(ctx: ExtensionContext): string {
3315
+ try {
3316
+ const id = ctx.sessionManager?.getSessionId();
3317
+ if (typeof id === "string" && id.length > 0) return id;
3318
+ } catch { /* unavailable */ }
3319
+ return this.fallbackSessionId();
3320
+ }
3321
+
3322
+ private fallbackSessionId(): string {
3323
+ // A synthetic id keeps one host's launches owned by that host; it is stable
3324
+ // only for this process, which matches the missing-session contract.
3325
+ return `anonymous:${this.hostId}`;
3326
+ }
3327
+
3328
+ private ownerFor(ctx: ExtensionContext): OwnerIdentity {
3329
+ const sessionId = this.sessionId(ctx);
3330
+ const workspace = ctx.cwd;
3331
+ const key = `${sessionId}\u0000${workspace}`;
3332
+ let branchId = this.branchAnchors.get(key);
3333
+ if (branchId === undefined) {
3334
+ branchId = this.latestBranchId(ctx);
3335
+ // Reuse a pending wait's anchor after a reload so the store owner matches
3336
+ // the anchor recorded in the previous process.
3337
+ const existing = this.store?.listWaits({ pendingOnly: true })
3338
+ .find((wait) => wait.owner.kind === "parent-session"
3339
+ && wait.owner.sessionId === sessionId && wait.owner.workspace === workspace);
3340
+ if (existing) branchId = existing.owner.branchId ?? null;
3341
+ this.branchAnchors.set(key, branchId);
3342
+ }
3343
+ return {
3344
+ kind: "parent-session",
3345
+ sessionId,
3346
+ workspace,
3347
+ branchId,
3348
+ goalId: null,
3349
+ };
3350
+ }
3351
+
3352
+ private latestBranchId(ctx: ExtensionContext): string | null {
3353
+ try {
3354
+ const branch = ctx.sessionManager?.getBranch?.() as readonly { id?: unknown }[] | undefined;
3355
+ if (!branch || branch.length === 0) return null;
3356
+ const id = branch[branch.length - 1]?.id;
3357
+ return typeof id === "string" && id.length > 0 ? id : null;
3358
+ } catch {
3359
+ return null;
3360
+ }
3361
+ }
3362
+
3363
+ private workerOwner(run: WorkerRunScope): OwnerIdentity {
3364
+ return {
3365
+ kind: "worker-conversation",
3366
+ sessionId: run.conversationId,
3367
+ workspace: run.workspace,
3368
+ branchId: run.branchId ?? null,
3369
+ goalId: run.goalId ?? null,
3370
+ };
3371
+ }
3372
+
3373
+ /**
3374
+ * Refresh the active session/branch snapshot. Called at start, at launch and
3375
+ * on every session_tree/branch navigation. Branch changes must be visible to
3376
+ * a queued callback *before* the batcher decides whether to deliver it.
3377
+ */
3378
+ noteParentContext(ctx: ExtensionContext): void {
3379
+ this.setActiveOrigin(ctx);
3380
+ if (!this.store) return;
3381
+ this.recoverAbandonedDeliveries();
3382
+ if (this.terminalRecoveryNeeded) {
3383
+ this.terminalRecoveryNeeded = false;
3384
+ this.recoverTerminalNotifications();
3385
+ }
3386
+ void this.dispatchOutbox();
3387
+ this.retryPendingTerminalCallbacks();
3388
+ this.writeHostDebug();
3389
+ }
3390
+
3391
+ private setActiveOrigin(ctx: ExtensionContext): void {
3392
+ const previous = this.activeContext;
3393
+ const previousKey = previous ? this.contextKey(previous) : undefined;
3394
+ const nextSessionId = this.sessionIdIfAvailable(ctx);
3395
+ const previousSessionId = previous ? this.sessionIdIfAvailable(previous) : undefined;
3396
+ // A partial tool/event context (no readable session identity) must not
3397
+ // replace a context that still proves the real session.
3398
+ if (!nextSessionId && previousSessionId) return;
3399
+ const origin = { cwd: ctx.cwd, sessionId: nextSessionId ?? this.sessionId(ctx) };
3400
+ const nextKey = this.contextKey(ctx);
3401
+ this.parentOrigin = origin;
3402
+ this.activeOrigin = origin;
3403
+ this.activeContext = ctx;
3404
+ // A tool call or activation for a different session/workspace must seed the
3405
+ // terminal callback journal once. Same-session calls keep the live context
3406
+ // current without rescanning historical terminal records.
3407
+ if (!previous || previousKey !== nextKey) this.terminalRecoveryNeeded = true;
3408
+ this.writeHostDebug();
3409
+ }
3410
+
3411
+ private contextKey(ctx: ExtensionContext): string | undefined {
3412
+ try { return `${this.sessionId(ctx)}\u0000${ctx.cwd}`; } catch { return undefined; }
3413
+ }
3414
+
3415
+ /**
3416
+ * Exact session/workspace match plus an eligible branch anchor. A descendant
3417
+ * branch contains the recorded anchor; an abandoned fork does not.
3418
+ */
3419
+ isParentOriginActive(origin: BackgroundTaskCallbackOrigin | undefined, branchId?: string | null): boolean {
3420
+ const ctx = this.activeContext;
3421
+ if (!ctx || !origin) return false;
3422
+ let cwd: string;
3423
+ try { cwd = ctx.cwd; } catch { return false; }
3424
+ if (cwd !== origin.cwd) return false;
3425
+ const sessionId = this.sessionId(ctx);
3426
+ if (origin.sessionId || sessionId) {
3427
+ if (origin.sessionId !== sessionId) return false;
3428
+ }
3429
+ if (!branchId) return true;
3430
+ // Read the branch live: the SDK may settle reload history after session_start.
3431
+ return branchIdsOf(ctx).includes(branchId);
3432
+ }
3433
+
3434
+ get parentSessionOrigin(): BackgroundTaskCallbackOrigin | undefined {
3435
+ return this.parentOrigin;
3436
+ }
3437
+
3438
+ private requireStarted(ctx?: ExtensionContext): void {
3439
+ if (!ctx) return;
3440
+ this.noteParentContext(ctx);
3441
+ }
3442
+
3443
+ /** Bounded host-level diagnostics for root reload investigations. */
3444
+ private writeHostDebug(): void {
3445
+ if (process.env.PI_BG_OBSERVED_WAITS_DEBUG !== "1") return;
3446
+ try {
3447
+ const dir = join(this.directory, "observed");
3448
+ mkdirSync(dir, { recursive: true });
3449
+ const ctx = this.activeContext;
3450
+ writeFileSync(join(dir, "host.json"), JSON.stringify({
3451
+ hostId: this.hostId,
3452
+ storeOpen: !!this.store,
3453
+ closed: this.closed,
3454
+ activeContext: !!ctx,
3455
+ activeSessionId: ctx ? this.sessionIdIfAvailable(ctx) ?? this.sessionId(ctx) : undefined,
3456
+ activeCwd: ctx ? ctx.cwd : undefined,
3457
+ activeBranchIds: ctx ? branchIdsOf(ctx) : [],
3458
+ terminalRecoveryNeeded: this.terminalRecoveryNeeded,
3459
+ pendingTerminalCallbacks: [...this.pendingTerminalCallbacks],
3460
+ writtenAt: Date.now(),
3461
+ }), { mode: 0o600 });
3462
+ } catch { /* diagnostics only */ }
3463
+ }
3464
+
3465
+ private sessionIdIfAvailable(ctx: ExtensionContext): string | undefined {
3466
+ try {
3467
+ const id = ctx.sessionManager?.getSessionId();
3468
+ return typeof id === "string" && id.length > 0 ? id : undefined;
3469
+ } catch {
3470
+ return undefined;
3471
+ }
3472
+ }
3473
+
3474
+ private sidecarPath(taskId: string): string {
3475
+ return join(this.directory, "observed", `${taskId}.json`);
3476
+ }
3477
+
3478
+ private writeLaunchContext(taskId: string, context: LaunchContext): void {
3479
+ try {
3480
+ const path = this.sidecarPath(taskId);
3481
+ mkdirSync(dirname(path), { recursive: true });
3482
+ writeFileSync(path, JSON.stringify(context), { mode: 0o600 });
3483
+ } catch { /* notification metadata is best-effort; durable state is in SQLite */ }
3484
+ }
3485
+
3486
+ private readLaunchContext(taskId: string): LaunchContext | undefined {
3487
+ try {
3488
+ const value = JSON.parse(readFileSync(this.sidecarPath(taskId), "utf8")) as Partial<LaunchContext>;
3489
+ if (value.kind !== "process" && value.kind !== "watch") return undefined;
3490
+ return {
3491
+ kind: value.kind,
3492
+ ...(value.parentOrigin && typeof value.parentOrigin === "object"
3493
+ ? { parentOrigin: value.parentOrigin as BackgroundTaskCallbackOrigin } : {}),
3494
+ gated: value.gated === true,
3495
+ callback: value.callback !== false,
3496
+ ...(typeof value.name === "string" ? { name: value.name } : {}),
3497
+ ...(typeof value.command === "string" ? { command: value.command } : {}),
3498
+ ...(Array.isArray(value.argv) && value.argv.every((entry) => typeof entry === "string")
3499
+ ? { argv: value.argv as string[] } : {}),
3500
+ ...(typeof value.cwd === "string" ? { cwd: value.cwd } : {}),
3501
+ ...(value.sandbox && typeof value.sandbox === "object" && !Array.isArray(value.sandbox)
3502
+ ? { sandbox: value.sandbox as TaskSandboxProvenance } : {}),
3503
+ ...(typeof value.branchId === "string" || value.branchId === null ? { branchId: value.branchId } : {}),
3504
+ ...(typeof value.callbackPendingAt === "number" ? { callbackPendingAt: value.callbackPendingAt } : {}),
3505
+ ...(typeof value.callbackDeliveredAt === "number" ? { callbackDeliveredAt: value.callbackDeliveredAt }
3506
+ : typeof (value as { callbackNotifiedAt?: unknown }).callbackNotifiedAt === "number"
3507
+ ? { callbackDeliveredAt: (value as { callbackNotifiedAt: number }).callbackNotifiedAt }
3508
+ : {}),
3509
+ ...(typeof value.callbackDeferredReason === "string" ? { callbackDeferredReason: value.callbackDeferredReason } : {}),
3510
+ ...(typeof value.callbackClaimedBy === "string" ? { callbackClaimedBy: value.callbackClaimedBy } : {}),
3511
+ ...(typeof value.callbackClaimedAt === "number" ? { callbackClaimedAt: value.callbackClaimedAt } : {}),
3512
+ ...(typeof value.callbackClaimToken === "string" ? { callbackClaimToken: value.callbackClaimToken } : {}),
3513
+ ...(typeof value.callbackAttemptedAt === "number" ? { callbackAttemptedAt: value.callbackAttemptedAt } : {}),
3514
+ ...(typeof value.callbackSkipReason === "string" ? { callbackSkipReason: value.callbackSkipReason } : {}),
3515
+ ...(typeof value.terminalRecordedBy === "string" ? { terminalRecordedBy: value.terminalRecordedBy } : {}),
3516
+ ...(typeof value.terminalRecordedAt === "number" ? { terminalRecordedAt: value.terminalRecordedAt } : {}),
3517
+ ...(typeof value.terminalRecordedWithContext === "boolean" ? { terminalRecordedWithContext: value.terminalRecordedWithContext } : {}),
3518
+ ...(typeof value.terminalActiveSessionId === "string" ? { terminalActiveSessionId: value.terminalActiveSessionId } : {}),
3519
+ ...(Array.isArray(value.terminalActiveBranchIds) ? { terminalActiveBranchIds: value.terminalActiveBranchIds } : {}),
3520
+ ...(typeof value.terminalReplayObservedBy === "string" ? { terminalReplayObservedBy: value.terminalReplayObservedBy } : {}),
3521
+ ...(value.outboxDelivered && typeof value.outboxDelivered === "object" && !Array.isArray(value.outboxDelivered)
3522
+ ? { outboxDelivered: value.outboxDelivered as LaunchContext["outboxDelivered"] } : {}),
3523
+ ...(typeof value.dismissedAt === "number" ? { dismissedAt: value.dismissedAt } : {}),
3524
+ };
3525
+ } catch {
3526
+ return undefined;
3527
+ }
3528
+ }
3529
+
3530
+ private launchContext(taskId: string): LaunchContext | undefined {
3531
+ return this.launches.get(taskId) ?? this.readLaunchContext(taskId);
3532
+ }
3533
+
3534
+ /**
3535
+ * The shared sidecar is authoritative for callback claims. Every callback
3536
+ * mutation and diagnostic write uses this fresh copy, never a cached object
3537
+ * that another host may have already superseded.
3538
+ */
3539
+ private currentLaunchContext(taskId: string): LaunchContext | undefined {
3540
+ const persisted = this.readLaunchContext(taskId);
3541
+ if (persisted) { this.launches.set(taskId, persisted); return persisted; }
3542
+ // An unreadable journal cannot establish ownership of a delivery claim.
3543
+ this.launches.delete(taskId);
3544
+ return undefined;
3545
+ }
3546
+
3547
+ private requireStore(): Store {
3548
+ if (!this.store && !this.closed) this.start();
3549
+ if (!this.store || this.closed) {
3550
+ throw new Error(this.unavailableReason ?? "Observed waits are unavailable; the durable store is not open.");
3551
+ }
3552
+ return this.store;
3553
+ }
3554
+
3555
+ private operationsForTaskIds(owner: OwnerIdentity, taskIds: readonly string[]): OperationRecord[] {
3556
+ if (!Array.isArray(taskIds) || taskIds.length === 0) throw new Error("At least one task id is required.");
3557
+ const operations: OperationRecord[] = [];
3558
+ for (const taskId of taskIds) {
3559
+ if (typeof taskId !== "string" || !LOCAL_DURABLE_ID.test(taskId)) {
3560
+ throw new Error(`Task ${String(taskId)} is not a durable local operation; results are observed only for supervised local tasks.`);
3561
+ }
3562
+ const operation = this.operationForTask(taskId);
3563
+ if (!operation) throw new Error(`Unknown durable task ${taskId}.`);
3564
+ if (!ownerMatchesOperation(operation, owner)) {
3565
+ throw new Error(`Task ${taskId} belongs to another execution owner; a wait may only depend on an owned operation.`);
3566
+ }
3567
+ if (operations.some((entry) => entry.operationId === operation.operationId)) continue;
3568
+ operations.push(operation);
3569
+ }
3570
+ return operations;
3571
+ }
3572
+
3573
+ private operationForTask(taskId: string): OperationRecord | undefined {
3574
+ return this.store?.listOperations({ taskId })[0];
3575
+ }
3576
+
3577
+ private ownedOperation(taskId: string, owner: OwnerIdentity): OperationRecord {
3578
+ const operation = this.operationForTask(taskId);
3579
+ if (!operation) throw new Error(`Unknown durable task ${taskId}.`);
3580
+ if (!ownerMatchesOperation(operation, owner)) {
3581
+ throw new Error(`Task ${taskId} belongs to another execution owner (${operation.owner.kind} ${operation.owner.sessionId}).`);
3582
+ }
3583
+ return operation;
3584
+ }
3585
+
3586
+ private ownedWait(owner: OwnerIdentity, waitId: string, generation: number): WaitRecord {
3587
+ const wait = this.requireStore().getWait({ waitId, generation });
3588
+ if (!wait) throw new Error(`Unknown wait ${waitId} generation ${generation}.`);
3589
+ if (!sameOwner(wait.owner, owner)) throw new Error(`Wait ${waitId} belongs to another execution owner.`);
3590
+ return wait;
3591
+ }
3592
+
3593
+ private supervision(): SupervisionIdentity {
3594
+ return { hostId: this.hostId, runnerId: null, processStartToken: null };
3595
+ }
3596
+
3597
+ private parentAuthority(owner: OwnerIdentity, plan: ForegroundSandboxPlan): string {
3598
+ const levels = plan.confined && plan.permissions
3599
+ ? `${plan.permissions.projectFiles}/${plan.permissions.outsideProject}/${plan.permissions.storedCredentials}/${plan.permissions.commands ? "commands" : "no-commands"}/${plan.permissions.network ? "network" : "no-network"}`
3600
+ : plan.confined ? "write-confinement" : "unconfined";
3601
+ return authorityReference(`parent:${owner.sessionId}:${levels}`);
3602
+ }
3603
+
3604
+ private announce(): void {
3605
+ const events = eventBusOf(this.pi);
3606
+ if (!events) return;
3607
+ events.emit(OBSERVED_WAITS_SERVICE_CHANNEL, this.service);
3608
+ }
3609
+
3610
+ private announceUnavailable(reason: string): void {
3611
+ const events = eventBusOf(this.pi);
3612
+ if (!events) return;
3613
+ events.emit(OBSERVED_WAITS_SERVICE_CHANNEL, {
3614
+ version: OBSERVED_WAITS_SERVICE_VERSION,
3615
+ available: false,
3616
+ reason: oneLine(reason, 300),
3617
+ } satisfies BackgroundOperationCapability);
3618
+ }
3619
+
3620
+ /** Answer a late service request without requiring the requester to know the host. */
3621
+ listenForServiceRequests(): void {
3622
+ const events = eventBusOf(this.pi);
3623
+ if (!events) return;
3624
+ events.on(OBSERVED_WAITS_SERVICE_REQUEST_CHANNEL, () => {
3625
+ if (this.closed) {
3626
+ this.announceUnavailable(this.unavailableReason ?? "the Background operation host closed");
3627
+ } else if (this.store || this.unavailableReason === undefined) {
3628
+ // A load-order probe may arrive before session_start. The capability
3629
+ // object exists; its methods open the store on first use.
3630
+ this.announce();
3631
+ } else {
3632
+ this.announceUnavailable(this.unavailableReason);
3633
+ }
3634
+ });
3635
+ }
3636
+ }
3637
+
3638
+ function tailText(text: string, lines: number): string {
3639
+ return lastLines(text, lines).replace(/\n+/g, " ⏎ ").slice(0, 400);
3640
+ }
3641
+
3642
+ function requireRpcString(params: JsonRecord, key: string): string {
3643
+ const value = params[key];
3644
+ if (typeof value !== "string" || value.length === 0) throw new Error(`${key} is required.`);
3645
+ return value;
3646
+ }
3647
+
3648
+ function requireRpcCounter(params: JsonRecord, key: string): number {
3649
+ const value = params[key];
3650
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error(`${key} must be a non-negative integer.`);
3651
+ return value;
3652
+ }
3653
+
3654
+ function waitKey(waitId: string, generation: number): string {
3655
+ return `${waitId}:${generation}`;
3656
+ }
3657
+
3658
+ /** Model-facing summary of one wait generation. */
3659
+ export function formatWaitView(view: WaitView): string {
3660
+ const lines = [
3661
+ `${view.waitId} generation ${view.generation}: ${view.phase}${view.settled ? " (all dependencies settled)" : " (waiting)"}`,
3662
+ `owner: ${view.ownerKind}`,
3663
+ ];
3664
+ for (const dep of view.dependencies) {
3665
+ lines.push(`- ${dep.taskId ?? dep.operationId}: revision ${dep.terminalRevision}${dep.terminalOutcome ? ` ${dep.terminalOutcome}` : " unsettled"}`);
3666
+ }
3667
+ if (view.evidence.length) {
3668
+ lines.push(`evidence: ${view.evidence.map((entry) => `${entry.kind}:${entry.ref}`).join(", ")}`);
3669
+ }
3670
+ lines.push(view.park
3671
+ ? "Parked worker wait: resumption belongs to the registered continuation adapter."
3672
+ : "The parent stays responsive; this registration never blocks the model.");
3673
+ if (view.settled) {
3674
+ lines.push("Read the terminal evidence with bg_task_status and bg_task_log, then call acknowledge_operation_result with the exact revisions.");
3675
+ }
3676
+ return lines.join("\n");
3677
+ }