pi-better-background-tasks 0.21.4 → 0.21.6

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.21.4",
3
+ "version": "0.21.6",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"65746505a072aa1596764b4458d968941ab105350369815050f6ab8f467d2884","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.4","contentId":"28b4109c57b16d1daedac9e127dc5dbab070230eb1285d179b82a6053a354f7c"},"sha256":"39eaec5eac80494b154758c9b879736e26f492e8c386edb6f5ca51ff67fa84a6"}
1
+ {"build":{"format":1,"sourceDigest":"c6db9b45efd44a01aa2aa18d5f458c0894ab2b824f473fab81d0176e64b3f1e9","piSdkVersion":"1.6.1","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"4b8b42f3d091ddf390547a02a1b71031543baab877d8cf5fd3241179b85e9554","protocolVersion":1,"serverVersion":"0.8.6","contentId":"2cef74a80c13ca63f6e604b9b486735a7fd0e6b060a9b6eb4b4bebd67a911945"},"sha256":"44063f32b7c7f08905f0081ef5033c1d964c4acd34968b25ea3f2a7a454a77ca"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"65746505a072aa1596764b4458d968941ab105350369815050f6ab8f467d2884","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.4","contentId":"aca525dbaba9b02dcec19e6c7875e0bdcfc3a9ce756571c463d8fba32b244a94"},"sha256":"d186a852343fa9c163703e4b65439b2a378c1d859a364172e3d6c52562027038"}
1
+ {"build":{"format":1,"sourceDigest":"c6db9b45efd44a01aa2aa18d5f458c0894ab2b824f473fab81d0176e64b3f1e9","piSdkVersion":"1.6.1","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"4b8b42f3d091ddf390547a02a1b71031543baab877d8cf5fd3241179b85e9554","protocolVersion":1,"serverVersion":"0.8.6","contentId":"f0182a8cd792b0831e30c3d849157f1151b38a54f9ae21e62aa89102ab8efc28"},"sha256":"921a176234cdbe2d6c7b0fe8ac44cd3799c2afe86a71307f8e76fcd9405c0f7c"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"65746505a072aa1596764b4458d968941ab105350369815050f6ab8f467d2884","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.4","contentId":"d920b273016e2621a49c305335e9842f3836d3814fee6005466624847c95a43b"},"sha256":"ee02a82127297bd0b645aad1b171cdefcd658056bf5a6e6da176acf02465ba77"}
1
+ {"build":{"format":1,"sourceDigest":"c6db9b45efd44a01aa2aa18d5f458c0894ab2b824f473fab81d0176e64b3f1e9","piSdkVersion":"1.6.1","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"4b8b42f3d091ddf390547a02a1b71031543baab877d8cf5fd3241179b85e9554","protocolVersion":1,"serverVersion":"0.8.6","contentId":"f9ec6aa84873f15c8c3065b099b9920139de61479e2ac83b3b61b23aab4bdd36"},"sha256":"e846045028030493af2c539cc2578701c10470c7f3205b77105660422f839026"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"65746505a072aa1596764b4458d968941ab105350369815050f6ab8f467d2884","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.4","contentId":"0b344d12f9ac9c186d2627d425f46f173ec5dd71949d4274fdf79e8188429a9e"},"sha256":"c1bf6b160a2a89f0e83dc602387b4dcfb6a2b79010da1a980932b7755358f577"}
1
+ {"build":{"format":1,"sourceDigest":"c6db9b45efd44a01aa2aa18d5f458c0894ab2b824f473fab81d0176e64b3f1e9","piSdkVersion":"1.6.1","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"4b8b42f3d091ddf390547a02a1b71031543baab877d8cf5fd3241179b85e9554","protocolVersion":1,"serverVersion":"0.8.6","contentId":"5f99633ed368186b5219a9f4061c666135d93ab10afa8c99b726648dd93abbbe"},"sha256":"9e45a229a24f76490840ddfb7f872f36c6f4f36a014ff0cba3cdcc0f4b274668"}
@@ -1,4 +1,5 @@
1
1
  import { existsSync } from "node:fs";
2
+ import { randomUUID } from "node:crypto";
2
3
  import { connect } from "node:net";
3
4
  import { performance } from "node:perf_hooks";
4
5
  import { setTimeout as delay } from "node:timers/promises";
@@ -13,8 +14,13 @@ export function shouldRestoreWorkObservation(event, session) {
13
14
  return file ? existsSync(file) : Boolean(session.getLeafId?.());
14
15
  }
15
16
 
17
+ function unknownLaunchReceipt(cause) {
18
+ return Object.assign(new Error(`Launch receipt unavailable: ${cause.message}`, { cause }), { code: "LAUNCH_OUTCOME_UNKNOWN" });
19
+ }
20
+
16
21
  /** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
17
22
  export class WorkClient {
23
+ lastSubscriptionTrace;
18
24
  socket;
19
25
  snapshot;
20
26
  pending = new Map();
@@ -29,6 +35,7 @@ export class WorkClient {
29
35
  recoveryAgain = false;
30
36
  recoveryDelay = 100;
31
37
  scopeGeneration = 0;
38
+ snapshotGeneration = 0;
32
39
 
33
40
  constructor(socketPath, agentDir, requiredCapabilities = []) {
34
41
  this.socket = typeof socketPath === "string" ? connect(socketPath) : socketPath;
@@ -44,7 +51,10 @@ export class WorkClient {
44
51
  if (message.type === "event") {
45
52
  if (message.event.type === "runtime_catalog_snapshot") { for (const listener of this.catalogListeners) listener(message.event.snapshot); continue; }
46
53
  if (message.event.type === "resync_required") { this.degrade(message.event.reason); this.scheduleRecovery(); }
47
- else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot, message.event.previousSeq);
54
+ else if (message.event.type === "runtime_snapshot") {
55
+ const generation = message.event.subscriptionGeneration ?? this.snapshotGeneration;
56
+ this.accept(message.event.snapshot, message.event.previousSeq, generation);
57
+ }
48
58
  } else {
49
59
  const request = this.pending.get(message.id);
50
60
  if (!request) continue;
@@ -64,10 +74,30 @@ export class WorkClient {
64
74
  request(type, params = {}) {
65
75
  if (this.closed) return Promise.reject(new Error("runtime-unavailable: disconnected; resync required"));
66
76
  if (this.pending.size >= 32) return Promise.reject(new Error("runtime-unhealthy: too many in-flight queries"));
67
- const id = `work-${++this.sequence}`;
77
+ const trace = type === "runtime_subscribe" ? { id: `sub-${randomUUID()}`, sentAt: Date.now() } : undefined;
78
+ if (trace) this.lastSubscriptionTrace = trace;
79
+ const id = trace?.id ?? `work-${++this.sequence}`;
68
80
  return new Promise((resolve, reject) => {
69
- const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`runtime-unhealthy: ${type} timed out`)); }, 5000);
70
- this.pending.set(id, { resolve, reject, timer });
81
+ // The host rechecks the caller's grant between workers and replies after batch admission.
82
+ const launch = type === "runtime_launch_subagent";
83
+ const rejectPending = launch ? error => reject(unknownLaunchReceipt(error)) : reject;
84
+ const timer = setTimeout(() => {
85
+ this.pending.delete(id);
86
+ if (trace) trace.timedOutAt = Date.now();
87
+ rejectPending(new Error(`runtime-unhealthy: ${type} timed out${trace ? ` (${trace.id})` : ""}`));
88
+ }, launch ? 120_000 : 5000);
89
+ this.pending.set(id, { resolve: value => {
90
+ if (trace) trace.receivedAt = Date.now();
91
+ // Apply subscription receipts in wire order, including events in the same socket chunk.
92
+ try {
93
+ if (type === "runtime_subscribe" && Number.isSafeInteger(params.subscriptionGeneration))
94
+ this.accept(value, undefined, params.subscriptionGeneration);
95
+ resolve(value);
96
+ } catch (error) { reject(error); }
97
+ }, reject: error => {
98
+ if (trace) trace.receivedAt = Date.now();
99
+ reject(error);
100
+ }, rejectPending, timer });
71
101
  this.socket.write(JSON.stringify({ id, type, ...params }) + "\n");
72
102
  });
73
103
  }
@@ -78,17 +108,20 @@ export class WorkClient {
78
108
  this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
79
109
  this.notify();
80
110
  }
81
- accept(snapshot, previousSeq) {
82
- if (this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
111
+ accept(snapshot, previousSeq, generation = this.scopeGeneration) {
112
+ if (this.closed || generation !== this.scopeGeneration) return;
113
+ const sameSubscription = this.snapshotGeneration === generation;
114
+ if (sameSubscription && this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
83
115
  if (this.snapshot?.instanceId && this.snapshot.instanceId !== snapshot.instanceId) {
84
116
  this.degrade("instance-changed: resync required");
85
117
  snapshot = { ...snapshot, resyncRequired: true, resyncReason: "instance-changed" };
86
- } else if (this.snapshot?.seq !== undefined && Number.isSafeInteger(previousSeq) && previousSeq > this.snapshot.seq) {
118
+ } else if (sameSubscription && this.snapshot?.seq !== undefined && Number.isSafeInteger(previousSeq) && previousSeq > this.snapshot.seq) {
87
119
  this.degrade("sequence-gap: replacing with a full authoritative snapshot");
88
120
  snapshot = { ...snapshot, resyncRequired: true, resyncReason: "sequence-gap" };
89
121
  }
90
122
  // Global seq may skip unrelated changes; only a missing subscription
91
123
  // predecessor indicates loss. The received snapshot is still complete.
124
+ this.snapshotGeneration = generation;
92
125
  this.snapshot = Object.freeze(snapshot); this.notify();
93
126
  }
94
127
  scheduleRecovery(delay = 0) {
@@ -123,18 +156,16 @@ export class WorkClient {
123
156
  }
124
157
  async subscribe(scope) {
125
158
  await this.ready;
126
- this.scopeGeneration++;
159
+ const generation = ++this.scopeGeneration;
127
160
  clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
128
161
  this.recoveryAgain = false; this.recoveryDelay = 100;
129
162
  this.scope = scope;
130
- const snapshot = await this.request("runtime_subscribe", { scope });
131
- this.accept(snapshot); return snapshot;
163
+ return this.request("runtime_subscribe", { scope, subscriptionGeneration: generation });
132
164
  }
133
165
  async resync() {
134
166
  const generation = this.scopeGeneration;
135
- const snapshot = await this.request("runtime_subscribe", { scope: this.scope, sinceSeq: this.snapshot?.seq, instanceId: this.snapshot?.instanceId });
136
- if (!this.closed && generation === this.scopeGeneration) this.accept(snapshot);
137
- return snapshot;
167
+ return this.request("runtime_subscribe", { scope: this.scope, subscriptionGeneration: generation,
168
+ sinceSeq: this.snapshotGeneration === generation ? this.snapshot?.seq : undefined, instanceId: this.snapshot?.instanceId });
138
169
  }
139
170
  async get(scope) {
140
171
  await this.ready;
@@ -151,7 +182,7 @@ export class WorkClient {
151
182
  this.closed = true;
152
183
  this.scopeGeneration++;
153
184
  clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
154
- for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
185
+ for (const request of this.pending.values()) { clearTimeout(request.timer); request.rejectPending(error); }
155
186
  this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
156
187
  for (const listener of this.catalogListeners) listener({ status: "revoked" });
157
188
  }
@@ -77,7 +77,7 @@ import {
77
77
  type SupervisorStartOptions,
78
78
  type SupervisorTaskStatus,
79
79
  } from "./supervisor/index.js";
80
- import { processGroupExitVerified } from "./supervisor/identity.js";
80
+ import { processGroupExitVerified, verifyProcessIdentity } from "./supervisor/identity.js";
81
81
  import { readStopRequest, writeTextAtomic } from "./supervisor/store.js";
82
82
  import { ciObserverArgv, ciRunFromArgv, validCiRun } from "./ci-observation.js";
83
83
  import type { BackgroundTaskCallbackOrigin, CommandSpec, Condition, TaskSandboxProvenance } from "./types.js";
@@ -1355,7 +1355,8 @@ export class ObservedWaitHost {
1355
1355
  store.verifyAssignmentCleanup(candidate.operationId, launchToken, candidate.terminalRevision);
1356
1356
  return;
1357
1357
  }
1358
- if (!pgid) return;
1358
+ if (!pgid || (process.platform === "win32" &&
1359
+ verifyProcessIdentity(inspection.command?.pid, inspection.command?.pidStartTime) !== "verified")) return;
1359
1360
  }
1360
1361
  if (!this.localCancels.has(taskId)) {
1361
1362
  this.localCancels.add(taskId);
package/src/registry.ts CHANGED
@@ -286,9 +286,68 @@ export function recentMetaDeadline(origin: BackgroundTaskCallbackOrigin): number
286
286
  return recentEntries(origin).map(entry => entry.observedAt + RECENT_MS);
287
287
  }
288
288
 
289
+ /** Read each task once, even when its active and recent pointers overlap. */
290
+ export function observeOriginActivity(origin: BackgroundTaskCallbackOrigin, retained: string[] = [], exactId?: string) {
291
+ let active: string[];
292
+ let recent: Array<{ id: string; observedAt: number }>;
293
+ if (exactId !== undefined) {
294
+ if (!/^[A-Za-z0-9_-]+$/.test(exactId)) throw new Error("Invalid Background task ID");
295
+ registryIo.indexRevisionChecks += 2;
296
+ const marker = statSync(join(recentPath(origin), exactId), { throwIfNoEntry: false });
297
+ recent = marker && marker.mtimeMs + RECENT_MS > Date.now() ? [{ id: exactId, observedAt: marker.mtimeMs }] : [];
298
+ active = statSync(join(originActiveIndexDir(origin), exactId), { throwIfNoEntry: false }) ? [exactId] : [];
299
+ } else {
300
+ registryIo.indexDirectoryReads++;
301
+ try { active = readdirSync(originActiveIndexDir(origin)).filter(id => id !== ".initialized"); }
302
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; active = []; }
303
+ recent = recentEntries(origin);
304
+ }
305
+ const deadlines = recent.map(entry => entry.observedAt + RECENT_MS);
306
+ const recentIds = new Set(recent.map(entry => entry.id));
307
+ const activeIds = new Set(active);
308
+ const retainedIds = new Set(retained);
309
+ const rows: BackgroundTaskMeta[] = [];
310
+ for (const id of new Set([...active, ...recentIds, ...retained])) {
311
+ const record = inspectMeta(id);
312
+ if (record.found && !record.meta) throw new Error(`Unverified background task ${id}: ${record.error}`);
313
+ const meta = record.meta;
314
+ if (!meta || !belongsToOrigin(meta, origin) || meta.dismissedAt !== undefined) continue;
315
+ const wasRetained = retainedIds.has(id) && meta.status !== "running" && (!meta.endedAt || meta.endedAt + RECENT_MS > Date.now());
316
+ if (wasRetained && meta.endedAt) deadlines.push(meta.endedAt + RECENT_MS);
317
+ if (wasRetained || recentIds.has(id) || (activeIds.has(id) && meta.callbackOrigin && meta.status === "running")) rows.push(meta);
318
+ }
319
+ return { rows, deadline: deadlines.length ? Math.min(...deadlines) : null };
320
+ }
321
+
289
322
  /** Exact cooperative source identity; no metadata or historical enumeration. */
290
323
  export function observationRevisionForOrigin(origin: BackgroundTaskCallbackOrigin): string {
291
- return [originActiveIndexDir(origin), recentPath(origin)].map(indexDirectorySignature).join(";");
324
+ return observedIndexRevision(originKey(origin));
325
+ }
326
+
327
+ const absentOrigin = "missing;missing";
328
+ function observedIndexRevision(key: string): string {
329
+ const root = baseDir();
330
+ return [join(root, "by-origin-active", key), join(root, "by-origin-recent", key)]
331
+ .map(path => indexDirectorySignature(path, true)).join(";");
332
+ }
333
+
334
+ /** A missing origin directory cannot appear without changing its parent. Existing directories
335
+ * still need exact checks because writes to their children do not change the parent's stamp. */
336
+ export function beginOriginIndexScan(previous?: { roots: string; missing: Set<string> }) {
337
+ const roots = observedIndexRevision("");
338
+ const missing = new Set<string>();
339
+ const revisions = new Map<string, string>();
340
+ function revision(origin: BackgroundTaskCallbackOrigin): string {
341
+ if (roots === absentOrigin) return absentOrigin;
342
+ const key = originKey(origin);
343
+ const cached = revisions.get(key);
344
+ if (cached !== undefined) return cached;
345
+ const stamp = previous?.roots === roots && previous.missing.has(key) ? absentOrigin : observedIndexRevision(key);
346
+ if (stamp === absentOrigin) missing.add(key);
347
+ revisions.set(key, stamp);
348
+ return stamp;
349
+ }
350
+ return { state: { roots, missing }, revision };
292
351
  }
293
352
 
294
353
  /** Bounded cooperative writes, including results written before the first reader. */
@@ -441,12 +500,13 @@ function removeIndexEntry(directory: string, id: string): void {
441
500
  }
442
501
  }
443
502
 
444
- function indexDirectorySignature(directory: string): string {
503
+ function indexDirectorySignature(directory: string, verifyAbsence = false): string {
445
504
  registryIo.indexRevisionChecks += 1;
446
505
  try {
447
- const stat = statSync(directory);
448
- return `${stat.dev}:${stat.ino}:${stat.mtimeMs}:${stat.ctimeMs}`;
449
- } catch {
506
+ const stat = statSync(directory, { bigint: true });
507
+ return [stat.dev, stat.ino, stat.mtimeNs, stat.ctimeNs].join(":");
508
+ } catch (error) {
509
+ if (verifyAbsence && (error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
450
510
  return "missing";
451
511
  }
452
512
  }
@@ -1539,7 +1539,7 @@ function neighbourCloseTarget(
1539
1539
 
1540
1540
  function buildTranscriptDetailLines(
1541
1541
  detail: BackgroundWorkDetail,
1542
- transcriptLines: string[],
1542
+ transcriptLines: readonly string[],
1543
1543
  width: number,
1544
1544
  truncate: (s: string, width: number) => string,
1545
1545
  fg: (color: string, value: string) => string,
@@ -1599,7 +1599,7 @@ function detailOverlayOptions() {
1599
1599
  };
1600
1600
  }
1601
1601
 
1602
- function renderEditorLines(width: number): string[] {
1602
+ function renderEditorLines(width: number): readonly string[] {
1603
1603
  try {
1604
1604
  const lines = state().editorComponent?.render(width);
1605
1605
  if (lines?.length) return lines;
@@ -1,4 +1,5 @@
1
1
  import { existsSync } from "node:fs";
2
+ import { randomUUID } from "node:crypto";
2
3
  import { connect } from "node:net";
3
4
  import { performance } from "node:perf_hooks";
4
5
  import { setTimeout as delay } from "node:timers/promises";
@@ -13,8 +14,13 @@ export function shouldRestoreWorkObservation(event, session) {
13
14
  return file ? existsSync(file) : Boolean(session.getLeafId?.());
14
15
  }
15
16
 
17
+ function unknownLaunchReceipt(cause) {
18
+ return Object.assign(new Error(`Launch receipt unavailable: ${cause.message}`, { cause }), { code: "LAUNCH_OUTCOME_UNKNOWN" });
19
+ }
20
+
16
21
  /** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
17
22
  export class WorkClient {
23
+ lastSubscriptionTrace;
18
24
  socket;
19
25
  snapshot;
20
26
  pending = new Map();
@@ -29,6 +35,7 @@ export class WorkClient {
29
35
  recoveryAgain = false;
30
36
  recoveryDelay = 100;
31
37
  scopeGeneration = 0;
38
+ snapshotGeneration = 0;
32
39
 
33
40
  constructor(socketPath, agentDir, requiredCapabilities = []) {
34
41
  this.socket = typeof socketPath === "string" ? connect(socketPath) : socketPath;
@@ -44,7 +51,10 @@ export class WorkClient {
44
51
  if (message.type === "event") {
45
52
  if (message.event.type === "runtime_catalog_snapshot") { for (const listener of this.catalogListeners) listener(message.event.snapshot); continue; }
46
53
  if (message.event.type === "resync_required") { this.degrade(message.event.reason); this.scheduleRecovery(); }
47
- else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot, message.event.previousSeq);
54
+ else if (message.event.type === "runtime_snapshot") {
55
+ const generation = message.event.subscriptionGeneration ?? this.snapshotGeneration;
56
+ this.accept(message.event.snapshot, message.event.previousSeq, generation);
57
+ }
48
58
  } else {
49
59
  const request = this.pending.get(message.id);
50
60
  if (!request) continue;
@@ -64,10 +74,30 @@ export class WorkClient {
64
74
  request(type, params = {}) {
65
75
  if (this.closed) return Promise.reject(new Error("runtime-unavailable: disconnected; resync required"));
66
76
  if (this.pending.size >= 32) return Promise.reject(new Error("runtime-unhealthy: too many in-flight queries"));
67
- const id = `work-${++this.sequence}`;
77
+ const trace = type === "runtime_subscribe" ? { id: `sub-${randomUUID()}`, sentAt: Date.now() } : undefined;
78
+ if (trace) this.lastSubscriptionTrace = trace;
79
+ const id = trace?.id ?? `work-${++this.sequence}`;
68
80
  return new Promise((resolve, reject) => {
69
- const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`runtime-unhealthy: ${type} timed out`)); }, 5000);
70
- this.pending.set(id, { resolve, reject, timer });
81
+ // The host rechecks the caller's grant between workers and replies after batch admission.
82
+ const launch = type === "runtime_launch_subagent";
83
+ const rejectPending = launch ? error => reject(unknownLaunchReceipt(error)) : reject;
84
+ const timer = setTimeout(() => {
85
+ this.pending.delete(id);
86
+ if (trace) trace.timedOutAt = Date.now();
87
+ rejectPending(new Error(`runtime-unhealthy: ${type} timed out${trace ? ` (${trace.id})` : ""}`));
88
+ }, launch ? 120_000 : 5000);
89
+ this.pending.set(id, { resolve: value => {
90
+ if (trace) trace.receivedAt = Date.now();
91
+ // Apply subscription receipts in wire order, including events in the same socket chunk.
92
+ try {
93
+ if (type === "runtime_subscribe" && Number.isSafeInteger(params.subscriptionGeneration))
94
+ this.accept(value, undefined, params.subscriptionGeneration);
95
+ resolve(value);
96
+ } catch (error) { reject(error); }
97
+ }, reject: error => {
98
+ if (trace) trace.receivedAt = Date.now();
99
+ reject(error);
100
+ }, rejectPending, timer });
71
101
  this.socket.write(JSON.stringify({ id, type, ...params }) + "\n");
72
102
  });
73
103
  }
@@ -78,17 +108,20 @@ export class WorkClient {
78
108
  this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
79
109
  this.notify();
80
110
  }
81
- accept(snapshot, previousSeq) {
82
- if (this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
111
+ accept(snapshot, previousSeq, generation = this.scopeGeneration) {
112
+ if (this.closed || generation !== this.scopeGeneration) return;
113
+ const sameSubscription = this.snapshotGeneration === generation;
114
+ if (sameSubscription && this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
83
115
  if (this.snapshot?.instanceId && this.snapshot.instanceId !== snapshot.instanceId) {
84
116
  this.degrade("instance-changed: resync required");
85
117
  snapshot = { ...snapshot, resyncRequired: true, resyncReason: "instance-changed" };
86
- } else if (this.snapshot?.seq !== undefined && Number.isSafeInteger(previousSeq) && previousSeq > this.snapshot.seq) {
118
+ } else if (sameSubscription && this.snapshot?.seq !== undefined && Number.isSafeInteger(previousSeq) && previousSeq > this.snapshot.seq) {
87
119
  this.degrade("sequence-gap: replacing with a full authoritative snapshot");
88
120
  snapshot = { ...snapshot, resyncRequired: true, resyncReason: "sequence-gap" };
89
121
  }
90
122
  // Global seq may skip unrelated changes; only a missing subscription
91
123
  // predecessor indicates loss. The received snapshot is still complete.
124
+ this.snapshotGeneration = generation;
92
125
  this.snapshot = Object.freeze(snapshot); this.notify();
93
126
  }
94
127
  scheduleRecovery(delay = 0) {
@@ -123,18 +156,16 @@ export class WorkClient {
123
156
  }
124
157
  async subscribe(scope) {
125
158
  await this.ready;
126
- this.scopeGeneration++;
159
+ const generation = ++this.scopeGeneration;
127
160
  clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
128
161
  this.recoveryAgain = false; this.recoveryDelay = 100;
129
162
  this.scope = scope;
130
- const snapshot = await this.request("runtime_subscribe", { scope });
131
- this.accept(snapshot); return snapshot;
163
+ return this.request("runtime_subscribe", { scope, subscriptionGeneration: generation });
132
164
  }
133
165
  async resync() {
134
166
  const generation = this.scopeGeneration;
135
- const snapshot = await this.request("runtime_subscribe", { scope: this.scope, sinceSeq: this.snapshot?.seq, instanceId: this.snapshot?.instanceId });
136
- if (!this.closed && generation === this.scopeGeneration) this.accept(snapshot);
137
- return snapshot;
167
+ return this.request("runtime_subscribe", { scope: this.scope, subscriptionGeneration: generation,
168
+ sinceSeq: this.snapshotGeneration === generation ? this.snapshot?.seq : undefined, instanceId: this.snapshot?.instanceId });
138
169
  }
139
170
  async get(scope) {
140
171
  await this.ready;
@@ -151,7 +182,7 @@ export class WorkClient {
151
182
  this.closed = true;
152
183
  this.scopeGeneration++;
153
184
  clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
154
- for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
185
+ for (const request of this.pending.values()) { clearTimeout(request.timer); request.rejectPending(error); }
155
186
  this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
156
187
  for (const listener of this.catalogListeners) listener({ status: "revoked" });
157
188
  }