pi-better-server 0.6.0 → 0.7.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 (120) hide show
  1. package/package.json +4 -3
  2. package/scripts/measure-full-runtime/frontend.ts +10 -2
  3. package/scripts/measure-full-runtime.mjs +2 -0
  4. package/src/runtime/background-tools.ts +54 -8
  5. package/src/runtime/background.ts +16 -4
  6. package/src/runtime/domain/background/process.mjs +49 -11
  7. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  8. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  9. package/src/runtime/domain/background-service/index.domain.mjs +19 -0
  10. package/src/runtime/domain/background-service/index.ts +19 -0
  11. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +87 -5
  12. package/src/runtime/domain/background-service/managed-frontend.ts +76 -5
  13. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +5 -0
  14. package/src/runtime/domain/background-service/navigator-provider.ts +4 -0
  15. package/src/runtime/domain/background-service/observed-waits.domain.mjs +203 -31
  16. package/src/runtime/domain/background-service/observed-waits.ts +168 -24
  17. package/src/runtime/domain/background-service/process.domain.mjs +49 -11
  18. package/src/runtime/domain/background-service/process.ts +45 -11
  19. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  20. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  21. package/src/runtime/domain/background-service/runtime.domain.mjs +8 -70
  22. package/src/runtime/domain/background-service/runtime.ts +8 -73
  23. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +55 -28
  24. package/src/runtime/domain/background-service/shared-navigator.ts +47 -26
  25. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  26. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  27. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +5 -1
  28. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +6 -0
  29. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  30. package/src/runtime/domain/background-service/stall.ts +7 -4
  31. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  32. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  33. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  34. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  35. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +49 -11
  36. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  37. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  38. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  39. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  40. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  41. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  42. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  43. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  44. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  45. package/src/runtime/domain/background-service/tools.domain.mjs +22 -16
  46. package/src/runtime/domain/background-service/tools.ts +26 -16
  47. package/src/runtime/domain/background-service/types.ts +4 -2
  48. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  49. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  50. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  51. package/src/runtime/domain/coordinator/src/store.mjs +5 -1
  52. package/src/runtime/domain/log-paths.mjs +8 -1
  53. package/src/runtime/domain/parse.mjs +9 -5
  54. package/src/runtime/domain/sandbox-policy/README.md +3 -3
  55. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  56. package/src/runtime/domain/session-store.mjs +7 -0
  57. package/src/runtime/domain/subagents/README.md +12 -10
  58. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +2 -5
  59. package/src/runtime/domain/subagents/assignment-outcomes.ts +2 -5
  60. package/src/runtime/domain/subagents/assignment-report.domain.mjs +22 -0
  61. package/src/runtime/domain/subagents/assignment-report.ts +20 -0
  62. package/src/runtime/domain/subagents/batch.mjs +13 -5
  63. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  64. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  65. package/src/runtime/domain/subagents/config.domain.mjs +5 -0
  66. package/src/runtime/domain/subagents/config.ts +7 -1
  67. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  68. package/src/runtime/domain/subagents/continuation.ts +4 -2
  69. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  70. package/src/runtime/domain/subagents/failures.ts +10 -2
  71. package/src/runtime/domain/subagents/finalization.domain.mjs +5 -2
  72. package/src/runtime/domain/subagents/finalization.ts +7 -2
  73. package/src/runtime/domain/subagents/index.domain.mjs +163 -61
  74. package/src/runtime/domain/subagents/index.ts +163 -60
  75. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +515 -0
  76. package/src/runtime/domain/subagents/isolated-workspace.ts +557 -0
  77. package/src/runtime/domain/subagents/list.mjs +2 -2
  78. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +22 -5
  79. package/src/runtime/domain/subagents/managed-launch-client.ts +23 -6
  80. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  81. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  82. package/src/runtime/domain/subagents/package.json +4 -2
  83. package/src/runtime/domain/subagents/parse.domain.mjs +9 -5
  84. package/src/runtime/domain/subagents/parse.ts +10 -5
  85. package/src/runtime/domain/subagents/registry.domain.mjs +24 -18
  86. package/src/runtime/domain/subagents/registry.ts +23 -5
  87. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  88. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  89. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  90. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  91. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  92. package/src/runtime/domain/subagents/session-store.ts +9 -0
  93. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  94. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  95. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +23 -7
  96. package/src/runtime/domain/subagents/shared-catalog.ts +23 -7
  97. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +55 -28
  98. package/src/runtime/domain/subagents/shared-navigator.ts +47 -26
  99. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  100. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  101. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +5 -1
  102. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +6 -0
  103. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  104. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  105. package/src/runtime/domain/subagents/task-policy.domain.mjs +2 -1
  106. package/src/runtime/domain/subagents/task-policy.ts +5 -1
  107. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  108. package/src/runtime/domain/subagents/tools.ts +4 -7
  109. package/src/runtime/domain/subagents/work-observation.domain.mjs +25 -1
  110. package/src/runtime/domain/subagents/work-observation.ts +20 -1
  111. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  112. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  113. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  114. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  115. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  116. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  117. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  118. package/src/runtime/read-model.ts +4 -2
  119. package/src/runtime/root.ts +5 -2
  120. package/src/version.ts +1 -1
@@ -11,6 +11,7 @@ import { observeNavigatorLaunch } from './shared-navigator.ts';
11
11
  export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
12
12
  let ctx: ExtensionContext | undefined, generation = 0, refresh: Promise<void> | undefined, dirty=false;
13
13
  let rows: any[] = [], legacyRows: any[] = [], details = new Map<string, any>(), logs = new Map<string, any>();
14
+ let pendingAttention = new Set<string>();
14
15
  const retainedTasks = new Map<string, any>();
15
16
  const cachedTask = (id: string) => rows.find(row => row.id === id) ?? retainedTasks.get(id);
16
17
  let adoptedScope: string | undefined;
@@ -20,6 +21,7 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
20
21
  const adoptContext = (context: ExtensionContext) => {
21
22
  if (adoptedScope !== undefined && adoptedScope !== scopeOf(context)) {
22
23
  ownership.clear(); rows = []; legacyRows = []; details.clear(); logs.clear(); retainedTasks.clear(); generation++;
24
+ pendingAttention.clear();
23
25
  }
24
26
  ctx = context; adoptedScope = scopeOf(context);
25
27
  };
@@ -50,6 +52,30 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
50
52
  };
51
53
  const notify = () => { for (const listener of listeners)
52
54
  listener({ workspace: ctx?.cwd, sessionId: ctx?.sessionManager.getSessionId() }); };
55
+ let handoffRetry: ReturnType<typeof setTimeout> | undefined;
56
+ let attentionRetry: ReturnType<typeof setTimeout> | undefined;
57
+ let retryAt = Infinity;
58
+ const scheduleHandoffPoll = (delayMs: number) => {
59
+ if (!ctx || retryAt <= Date.now() + delayMs) return;
60
+ clearTimeout(handoffRetry);
61
+ retryAt = Date.now() + delayMs;
62
+ // Poll again before attempting delivery: the task or its recipient may have changed.
63
+ handoffRetry = setTimeout(() => {
64
+ handoffRetry = undefined; retryAt = Infinity;
65
+ if (ctx) void reconcile().catch(() => undefined);
66
+ }, delayMs);
67
+ handoffRetry.unref();
68
+ };
69
+ const waitForAttentionIdle = () => {
70
+ if (attentionRetry) return;
71
+ attentionRetry = setTimeout(() => {
72
+ attentionRetry = undefined;
73
+ if (!ctx || !pendingAttention.size) return;
74
+ if (!ctx.isIdle()) { waitForAttentionIdle(); return; }
75
+ void reconcile().catch(() => undefined);
76
+ }, 1000);
77
+ attentionRetry.unref();
78
+ };
53
79
  const reconcile = () => {
54
80
  if (!ctx)
55
81
  return Promise.resolve();
@@ -57,15 +83,18 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
57
83
  dirty=false;
58
84
  const captured = ctx, version = generation;
59
85
  refresh = (async () => {
86
+ const rechecking = pendingAttention.size && captured.isIdle() ? pendingAttention : undefined;
60
87
  trace('poll-start');
61
88
  const snapshot = await request('__background_poll', { knownActiveIds: rows.filter(row => row.active).map(row => row.id).slice(0, 200) });
62
89
  trace('poll-received', { stale: version !== generation, total: snapshot.deliveries?.length ?? 0, deliveries: (snapshot.deliveries ?? []).slice(0, 8).map((item: any) => ({ taskId: item.notification.taskId, receiptId: item.receiptId })) });
63
90
  if (version !== generation)
64
91
  return;
92
+ if (Number.isFinite(snapshot.retryAfterMs)) scheduleHandoffPoll(snapshot.retryAfterMs);
65
93
  if (snapshot.recoveryPending === true) dirty = true;
66
94
  // A rebuilding snapshot is not evidence that visible tasks vanished.
67
95
  if (snapshot.status !== 'rebuilding' && snapshot.status !== 'degraded') {
68
- rows = snapshot.tasks ?? [];
96
+ // Older servers include compact callback pointers in the task list.
97
+ rows = (snapshot.tasks ?? []).filter((task: any) => !task.callbackPending);
69
98
  // Detail remains inspectable while Navigator retains a terminal row.
70
99
  for (const task of rows) {
71
100
  retainedTasks.delete(task.id); retainedTasks.set(task.id, task);
@@ -74,9 +103,19 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
74
103
  legacyRows = snapshot.legacyRows ?? [];
75
104
  }
76
105
  notify();
106
+ const deferredAttention = new Set<string>();
77
107
  for (const item of snapshot.deliveries ?? []) {
78
108
  if (queued.has(item.token))
79
109
  continue;
110
+ const n = item.notification;
111
+ const type = n.event?.customType;
112
+ if ((type === 'background-task-stall' || type === 'background-wait-review')
113
+ && (!rechecking?.has(item.receiptId) || !captured.isIdle())) {
114
+ // Keep the candidate here while busy. Pi's followUp queue cannot
115
+ // revalidate it when the current turn eventually ends.
116
+ deferredAttention.add(item.receiptId);
117
+ continue;
118
+ }
80
119
  queued.add(item.token);
81
120
  const facts = { taskId: item.notification.taskId, receiptId: item.receiptId };
82
121
  const receipt = (delivered: boolean, reason?: string) => {
@@ -93,15 +132,30 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
93
132
  receipt(true);
94
133
  continue;
95
134
  }
96
- const n = item.notification;
97
135
  trace('queue', { ...facts, urgent: n.urgent === true, recipientActive: active(n.origin, n.branchId) });
98
- if(n.urgent){void getCallbackBatcher(pi).deliverUrgent({...n.event,receiptId:item.receiptId,getSuppressionReason:()=>active(n.origin,n.branchId)?undefined:'The originating session or branch is no longer active',onDelivered:()=>receipt(true),onSuppressed:(reason)=>receipt(false,reason)});continue;}
136
+ if (n.urgent) {
137
+ const handoff = getCallbackBatcher(pi).deliverUrgent({ ...n.event, receiptId: item.receiptId,
138
+ getSuppressionReason: () => active(n.origin, n.branchId) ? undefined : 'The originating session or branch is no longer active',
139
+ onDelivered: () => receipt(true), onSuppressed: reason => receipt(false, reason) });
140
+ const retry = () => { queued.delete(item.token); if (version === generation) scheduleHandoffPoll(1000); };
141
+ void Promise.resolve(handoff).then(ok => { if (!ok) retry(); }, retry);
142
+ continue;
143
+ }
99
144
  getCallbackBatcher(pi).enqueue({ ...n.event, source: 'background-task', id: n.taskId, label: n.taskId, status: n.waitId ? `${n.status}; wait ${n.waitId} ready` : n.status,
100
145
  detailTool: 'bg_task_status', outcome: n.outcome, callback: true, receiptId: item.receiptId,
101
146
  getSuppressionReason: () => active(n.origin, n.branchId) ? undefined : 'The originating session or branch is no longer active',
102
147
  onDelivered: () => receipt(true), onSuppressed: (reason) => receipt(false, reason) });
103
148
  }
104
- })().catch(error => { trace('poll-error', { error: String(error).slice(0, 256) }); throw error; })
149
+ pendingAttention = deferredAttention;
150
+ if (pendingAttention.size) {
151
+ if (captured.isIdle()) dirty = true;
152
+ else waitForAttentionIdle();
153
+ }
154
+ })().catch(error => {
155
+ trace('poll-error', { error: String(error).slice(0, 256) });
156
+ if (version === generation && pendingAttention.size) waitForAttentionIdle();
157
+ throw error;
158
+ })
105
159
  .finally(() => { refresh = undefined;if(dirty&&ctx)void reconcile().catch(()=>undefined); });
106
160
  return refresh;
107
161
  };
@@ -118,7 +172,24 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
118
172
  if (restore) activate();
119
173
  },
120
174
  noteParentContext(context: ExtensionContext) { adoptContext(context); generation++; void reconcile().catch(() => undefined); },
121
- close() { observing = false; ctx = undefined; adoptedScope = undefined; generation++; rows = []; legacyRows = []; details.clear(); logs.clear(); retainedTasks.clear(); queued.clear(); ownership.clear(); },
175
+ close() {
176
+ clearTimeout(handoffRetry);
177
+ clearTimeout(attentionRetry);
178
+ handoffRetry = attentionRetry = undefined;
179
+ retryAt = Infinity;
180
+ observing = false;
181
+ ctx = undefined;
182
+ adoptedScope = undefined;
183
+ generation++;
184
+ rows = [];
185
+ legacyRows = [];
186
+ details.clear();
187
+ logs.clear();
188
+ retainedTasks.clear();
189
+ queued.clear();
190
+ ownership.clear();
191
+ pendingAttention.clear();
192
+ },
122
193
  isParentOriginActive: active,
123
194
  onDurableTaskChange(listener: (change: any) => void) { listeners.add(listener); return () => listeners.delete(listener); },
124
195
  listDurableTasks(origin: any, _options: any = {}) { return active(origin) ? rows : []; },
@@ -7,6 +7,7 @@ import { failurePath, failureView } from "./failures.domain.mjs";
7
7
  import { readLog } from "./logs.domain.mjs";
8
8
  import { listMetasForOrigin, onMetaChanged, readMeta, writeMeta } from "./registry.domain.mjs";
9
9
  import { getObservedWaitHost } from "./observed-wait-client.domain.mjs";
10
+ import { describeSupervisedProgress } from "./supervised-progress.domain.mjs";
10
11
  import { formatBackgroundTaskStall, observeBackgroundTaskStall } from "./stall.domain.mjs";
11
12
  const TERMINAL_NAVIGATOR_RETENTION_MS = 30_000;
12
13
  const DURABLE_ROW_CACHE_MS = 1_000;
@@ -175,6 +176,9 @@ export function createBackgroundTasksNavigator(runtime, managed) {
175
176
  const command = durableCommandLabel(task);
176
177
  const elapsed = formatDuration((task.endedAt ?? now) - task.startedAt);
177
178
  const facts = [];
179
+ const progress = task.progress && describeSupervisedProgress(task.progress, now);
180
+ if (progress)
181
+ facts.push(progress);
178
182
  if (task.attention && task.reason)
179
183
  facts.push(task.reason);
180
184
  else if (task.attention)
@@ -216,6 +220,7 @@ export function createBackgroundTasksNavigator(runtime, managed) {
216
220
  { label: "kind", value: task.kind },
217
221
  ...(task.parentAgentId ? [{ label: "agent", value: task.parentAgentId }] : []),
218
222
  { label: "operation", value: task.operationId },
223
+ ...(task.progress ? [{ label: "last progress", value: new Date(task.progress.observedAt).toISOString() }] : []),
219
224
  { label: "status", value: `${task.status}${task.terminalOutcome ? ` (${task.terminalOutcome})` : ""}` },
220
225
  { label: "started", value: new Date(task.startedAt).toISOString() },
221
226
  ...(task.endedAt !== undefined ? [{ label: "ended", value: new Date(task.endedAt).toISOString() }] : []),
@@ -17,6 +17,7 @@ import { failurePath, failureView } from "./failures.js";
17
17
  import { readLog } from "./logs.js";
18
18
  import { listMetasForOrigin, onMetaChanged, readMeta, writeMeta } from "./registry.js";
19
19
  import { getObservedWaitHost } from "./observed-wait-client.js";
20
+ import { describeSupervisedProgress } from "./supervised-progress.js";
20
21
  import type { DurableTaskProjection } from "./observed-waits.js";
21
22
  import type { BackgroundTaskRuntime } from "./runtime.js";
22
23
  import { formatBackgroundTaskStall, observeBackgroundTaskStall } from "./stall.js";
@@ -191,6 +192,8 @@ function rowFromDurable(task: DurableTaskProjection, now: number): BackgroundWor
191
192
  const command = durableCommandLabel(task);
192
193
  const elapsed = formatDuration((task.endedAt ?? now) - task.startedAt);
193
194
  const facts: string[] = [];
195
+ const progress = task.progress && describeSupervisedProgress(task.progress, now);
196
+ if (progress) facts.push(progress);
194
197
  if (task.attention && task.reason) facts.push(task.reason);
195
198
  else if (task.attention) facts.push(task.status);
196
199
  if (task.kind === "watch" && task.intervalSeconds) facts.push(`every ${formatDuration(task.intervalSeconds * 1000)}`);
@@ -228,6 +231,7 @@ function detailFromDurable(task: DurableTaskProjection, options?: { logTailLines
228
231
  { label: "kind", value: task.kind },
229
232
  ...(task.parentAgentId ? [{label: "agent", value: task.parentAgentId}] : []),
230
233
  { label: "operation", value: task.operationId },
234
+ ...(task.progress ? [{ label: "last progress", value: new Date(task.progress.observedAt).toISOString() }] : []),
231
235
  { label: "status", value: `${task.status}${task.terminalOutcome ? ` (${task.terminalOutcome})` : ""}` },
232
236
  { label: "started", value: new Date(task.startedAt).toISOString() },
233
237
  ...(task.endedAt !== undefined ? [{ label: "ended", value: new Date(task.endedAt).toISOString() }] : []),
@@ -26,14 +26,16 @@ import { createHash, randomUUID } from "node:crypto";
26
26
  import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, watch } from "node:fs";
27
27
  import { homedir } from "node:os";
28
28
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
29
+ import { describeSupervisedProgress, supervisedProgress } from "./supervised-progress.domain.mjs";
30
+ import { formatProgressDuration } from "./stall.domain.mjs";
29
31
  import { validateCondition } from "./conditions.domain.mjs";
30
- import { STEP_GATE_COMMAND_ENV, commandExecution, parseStepGateFailure, processExists, stepGateScript, validateCommandSpec, } from "./process.domain.mjs";
32
+ import { STEP_GATE_COMMAND_ENV, commandExecution, parseStepGateFailure, processExists, resolveWindowsLaunchShell, stepGateScript, validateCommandSpec, } from "./process.domain.mjs";
31
33
  import { currentProcessStartToken, readProcessStartToken } from "./process-identity.domain.mjs";
32
34
  import { assertBackgroundExecutionAllowed, backgroundExecutionLimits, confineCommandSpec, resolveForegroundSandboxPlan, currentForegroundSandboxPolicy, resolveWorkerSandboxPlan, sandboxProvenance, } from "./sandbox.domain.mjs";
33
35
  import { openStore, cancellationCredential, } from "./shared-operation-coordinator/index.domain.mjs";
34
36
  import { createLocalSupervisor, defaultSupervisorDirectory, supervisorPaths, supervisorTaskIdForToken, } from "./supervisor/index.domain.mjs";
35
37
  import { processGroupAlive } from "./supervisor/identity.domain.mjs";
36
- import { readStopRequest } from "./supervisor/store.domain.mjs";
38
+ import { readStopRequest, writeTextAtomic } from "./supervisor/store.domain.mjs";
37
39
  export const OBSERVED_WAITS_SERVICE_VERSION = 2;
38
40
  export const OBSERVED_WAITS_SERVICE_CHANNEL = "pi-better-background-tasks:observed-waits-service";
39
41
  export const OBSERVED_WAITS_SERVICE_REQUEST_CHANNEL = "pi-better-background-tasks:observed-waits-service-request";
@@ -1308,6 +1310,124 @@ export class ObservedWaitHost {
1308
1310
  this.projectionMetrics.projectionsBuilt += 1;
1309
1311
  return this.projectDurable(operation, now);
1310
1312
  }
1313
+ /** Rebuild a live incident from the runner checkpoint. Only the native handoff writes its receipt. */
1314
+ pendingStallAlert(origin, taskId, waits) {
1315
+ const operation = this.operationForTask(taskId);
1316
+ if (!operation || operation.terminalRevision || !this.belongsToParentOrigin(operation, origin))
1317
+ return;
1318
+ const branchId = operation.owner.branchId;
1319
+ if (!this.isParentOriginActive(origin, branchId))
1320
+ return;
1321
+ const directory = this.observationDirectory(operation);
1322
+ if (!directory)
1323
+ return;
1324
+ const context = this.readLaunchContext(taskId, directory);
1325
+ if (!context?.callback)
1326
+ return;
1327
+ const inspection = this.passiveSnapshot(taskId, directory);
1328
+ if (!inspection || inspection.token !== operation.launchToken || inspection.stopRequestedAt !== undefined)
1329
+ return;
1330
+ const now = this.options.now?.() ?? Date.now();
1331
+ const progress = supervisedProgress(inspection, now);
1332
+ if (!progress?.alertDue)
1333
+ return;
1334
+ const receiptId = `background-stall:${operation.operationId}:${progress.observedAt}`;
1335
+ const receiptPath = join(inspection.taskDir, "stall-receipt");
1336
+ try {
1337
+ if (readFileSync(receiptPath, "utf8") === receiptId)
1338
+ return;
1339
+ }
1340
+ catch (error) {
1341
+ if (error.code !== "ENOENT")
1342
+ throw error;
1343
+ }
1344
+ const lines = [describeSupervisedProgress(progress, now),
1345
+ `Task has run for ${formatProgressDuration(now - inspection.launch.createdAt)}.`];
1346
+ for (const ref of waits) {
1347
+ const wait = this.requireStore().getWait(ref);
1348
+ if (!wait || wait.phase === "cancelled" || wait.phase === "consumed" || !sameOwner(wait.owner, operation.owner))
1349
+ continue;
1350
+ if (!wait.dependencies.some(dep => dep.operationId === operation.operationId))
1351
+ continue;
1352
+ const others = wait.dependencies.filter(dep => dep.operationId !== operation.operationId);
1353
+ const siblings = others.slice(0, 8).map(dep => {
1354
+ const sibling = this.requireStore().getOperation(dep.operationId);
1355
+ return `${sibling?.taskId ?? dep.operationId} ${sibling?.terminalOutcome ?? sibling?.phase ?? "unknown"}`;
1356
+ });
1357
+ if (others.length > siblings.length)
1358
+ siblings.push(`+${others.length - siblings.length} more`);
1359
+ lines.push(`Wait ${ref.waitId} ${wait.phase}${siblings.length ? ". Other tasks: " + siblings.join(", ") : ""}`);
1360
+ }
1361
+ const output = [inspection.logs.stdout, inspection.logs.stderr].map(path => lastLines(tail(path).text, 1).slice(-300)).filter(Boolean);
1362
+ lines.push(...output, `Evidence: bg_task_log id=${taskId}`);
1363
+ const notification = { taskId, operationId: operation.operationId, origin, branchId, urgent: true,
1364
+ event: { source: "background-task", id: receiptId, inspectId: taskId, label: context.name ?? taskId,
1365
+ status: "suspected stall", customType: "background-task-stall", content: lines.join("\n"), detailTool: "bg_task_status" } };
1366
+ return { notification, delivery: { receiptId, delivered: () => writeTextAtomic(receiptPath, receiptId), defer: () => { } } };
1367
+ }
1368
+ /** Review an ongoing parent wait using durable launch, progress and handoff evidence. */
1369
+ backgroundWaitReview(origin, taskId, waits, intervalMs) {
1370
+ const operation = this.operationForTask(taskId);
1371
+ if (!operation || operation.terminalRevision || !this.belongsToParentOrigin(operation, origin))
1372
+ return;
1373
+ const branchId = operation.owner.branchId;
1374
+ if (!this.isParentOriginActive(origin, branchId))
1375
+ return;
1376
+ const wait = waits.map(ref => this.requireStore().getWait(ref)).find(record => record?.phase === "waiting"
1377
+ && sameOwner(record.owner, operation.owner)
1378
+ && record.dependencies.some(dep => dep.operationId === operation.operationId));
1379
+ if (!wait)
1380
+ return;
1381
+ const directory = this.observationDirectory(operation);
1382
+ if (!directory)
1383
+ return;
1384
+ const context = this.readLaunchContext(taskId, directory);
1385
+ if (!context?.callback)
1386
+ return;
1387
+ const inspection = this.passiveSnapshot(taskId, directory);
1388
+ if (!inspection || inspection.token !== operation.launchToken || inspection.stopRequestedAt !== undefined)
1389
+ return;
1390
+ const clock = this.options.now ?? Date.now;
1391
+ const now = clock();
1392
+ const progress = supervisedProgress(inspection, now);
1393
+ if (!progress)
1394
+ return;
1395
+ const receiptPath = join(inspection.taskDir, "wait-review-receipt.json");
1396
+ const incident = [wait.waitId, wait.generation, progress.observedAt].join(":");
1397
+ const firstReviewAnchor = Math.max(wait.createdAt, progress.observedAt);
1398
+ let anchor = firstReviewAnchor;
1399
+ try {
1400
+ const receipt = JSON.parse(readFileSync(receiptPath, "utf8"));
1401
+ if (receipt?.incident === incident && Number.isFinite(receipt.deliveredAt)) {
1402
+ anchor = Math.max(anchor, receipt.deliveredAt);
1403
+ }
1404
+ }
1405
+ catch (error) {
1406
+ if (!(error instanceof SyntaxError) && error.code !== "ENOENT")
1407
+ throw error;
1408
+ }
1409
+ const dueAt = anchor + intervalMs;
1410
+ if (now < dueAt)
1411
+ return { dueAt };
1412
+ const receiptId = `background-wait-review:${operation.operationId}:${incident}:${anchor}`;
1413
+ const lines = [
1414
+ `Task has run for ${formatProgressDuration(now - inspection.launch.createdAt)}. No observed progress for ${formatProgressDuration(now - progress.observedAt)}.`,
1415
+ `Wait ${wait.waitId} is still waiting. Reassess the blocker and report the next step.`,
1416
+ `Continuation note: ${oneLine(wait.continuationNote, 250)}`,
1417
+ ];
1418
+ if (inspection.kind === "watch") {
1419
+ const lastCheck = lastLines(tail(inspection.logs.events).text, 12).split("\n").reverse().find(line => / check #\d+ exit=/.test(line));
1420
+ if (lastCheck)
1421
+ lines.push(`Latest check: ${oneLine(lastCheck, 200)}`);
1422
+ }
1423
+ const output = [inspection.logs.stdout, inspection.logs.stderr].map(path => lastLines(tail(path).text, 1).slice(-300)).filter(Boolean);
1424
+ lines.push(...output, `Evidence: bg_task_log id=${taskId}`);
1425
+ const notification = { taskId, operationId: operation.operationId, origin, branchId, urgent: true,
1426
+ event: { source: "background-task", id: receiptId, inspectId: taskId, label: context.name ?? taskId,
1427
+ status: "wait review due", customType: "background-wait-review", content: lines.join("\n"), detailTool: "bg_task_status" } };
1428
+ return { dueAt, alert: { notification, delivery: { receiptId,
1429
+ delivered: () => writeTextAtomic(receiptPath, JSON.stringify({ incident, deliveredAt: clock() })), defer: () => { } } } };
1430
+ }
1311
1431
  /** Accumulated projection work, for performance regression proof. */
1312
1432
  getDurableProjectionMetrics() {
1313
1433
  return { ...this.projectionMetrics };
@@ -1415,18 +1535,30 @@ export class ObservedWaitHost {
1415
1535
  return operation.owner.sessionId === origin.sessionId;
1416
1536
  return true;
1417
1537
  }
1538
+ observationDirectory(operation) {
1539
+ if (!operation.supervision?.hostId?.startsWith("server:"))
1540
+ return this.directory;
1541
+ const grant = this.store?.resultSupervision(operation.operationId);
1542
+ if (!grant || grant.launchToken !== operation.launchToken || !sameOwner(grant.owner, operation.owner))
1543
+ return;
1544
+ return grant.directory;
1545
+ }
1546
+ passiveSnapshot(taskId, directory) {
1547
+ if (!directory || !LOCAL_DURABLE_ID.test(taskId))
1548
+ return;
1549
+ const supervisor = directory === this.directory ? this.supervisor : createLocalSupervisor({ directory });
1550
+ try {
1551
+ return supervisor.snapshot(taskId);
1552
+ }
1553
+ catch {
1554
+ return;
1555
+ }
1556
+ }
1418
1557
  projectDurable(operation, now) {
1419
- const context = this.launchContext(operation.taskId);
1420
- // Projection is the rendering path: a snapshot reads the durable records
1421
- // without taking the cross-process fence or spawning `ps`.
1422
- const inspection = LOCAL_DURABLE_ID.test(operation.taskId)
1423
- ? (() => { try {
1424
- return this.supervisor.snapshot(operation.taskId);
1425
- }
1426
- catch {
1427
- return undefined;
1428
- } })()
1429
- : undefined;
1558
+ const directory = this.observationDirectory(operation);
1559
+ const context = directory === this.directory ? this.launchContext(operation.taskId)
1560
+ : directory ? this.readLaunchContext(operation.taskId, directory) : undefined;
1561
+ const inspection = this.passiveSnapshot(operation.taskId, directory);
1430
1562
  const storeStatus = operation.terminalRevision > 0 ? this.statusOf(operation.operationId) : undefined;
1431
1563
  const status = inspection?.terminal ? inspection.status : storeStatus ?? inspection?.status ?? "running";
1432
1564
  const terminal = inspection?.terminal === true || operation.terminalRevision > 0;
@@ -1450,6 +1582,7 @@ export class ObservedWaitHost {
1450
1582
  status,
1451
1583
  active,
1452
1584
  terminal,
1585
+ progress: active ? supervisedProgress(inspection, now) : undefined,
1453
1586
  attention: terminal && status !== "succeeded",
1454
1587
  ...(context?.name ?? inspection?.launch.name ? { name: context?.name ?? inspection?.launch.name } : {}),
1455
1588
  cwd: inspection?.launch.cwd ?? context?.cwd ?? operation.owner.workspace,
@@ -1481,7 +1614,8 @@ export class ObservedWaitHost {
1481
1614
  }
1482
1615
  statusForOperation(operation, owner) {
1483
1616
  const store = this.requireStore(), taskId = operation.taskId;
1484
- const inspection = this.inspect(taskId);
1617
+ const directory = this.observationDirectory(operation);
1618
+ const inspection = directory === this.directory ? this.inspect(taskId) : this.passiveSnapshot(taskId, directory);
1485
1619
  this.reconcileInspection(operation, inspection);
1486
1620
  const current = store.getOperation(operation.operationId) ?? operation;
1487
1621
  if (this.watchedRunningTasks.delete(taskId) && current.terminalRevision > 0) {
@@ -1493,14 +1627,14 @@ export class ObservedWaitHost {
1493
1627
  this.attemptTerminalCallback(current, this.statusOf(current.operationId), current.terminalOutcome ?? "failed", [], { pendingWithoutContext: true });
1494
1628
  }
1495
1629
  this.recordReadsForTask(owner, current);
1496
- const paths = supervisorPaths(this.directory, taskId);
1630
+ const paths = inspection?.logs ?? supervisorPaths(this.directory, taskId);
1497
1631
  const gateText = inspection ? `${tail(paths.stderr).text}` : "";
1498
1632
  const waits = store.listWaits({ pendingOnly: true })
1499
1633
  .filter((wait) => sameOwner(wait.owner, owner))
1500
1634
  .filter((wait) => wait.dependencies.some((dep) => dep.operationId === current.operationId))
1501
1635
  .map((wait) => this.waitView(wait));
1502
1636
  const result = inspection?.result;
1503
- const launched = this.launchContext(taskId);
1637
+ const launched = directory === this.directory ? this.launchContext(taskId) : directory ? this.readLaunchContext(taskId, directory) : undefined;
1504
1638
  const stepGate = result && launched?.gated ? parseStepGateFailure(gateText, taskId) : undefined;
1505
1639
  const kind = inspection?.kind ?? launched?.kind ?? "process";
1506
1640
  return {
@@ -1509,6 +1643,7 @@ export class ObservedWaitHost {
1509
1643
  kind: kind === "watch" ? "watch" : "process",
1510
1644
  status: inspection?.status ?? this.statusOf(current.operationId),
1511
1645
  phase: current.phase,
1646
+ progress: current.terminalRevision === 0 ? supervisedProgress(inspection, this.options.now?.() ?? Date.now()) : undefined,
1512
1647
  exitCode: result?.exitCode ?? null,
1513
1648
  signal: result?.signal ?? null,
1514
1649
  ...supervisionReasonFields(inspection),
@@ -1526,10 +1661,13 @@ export class ObservedWaitHost {
1526
1661
  log(taskId, owner, options = {}) {
1527
1662
  const store = this.requireStore();
1528
1663
  const operation = this.ownedOperation(taskId, owner);
1529
- const inspection = this.inspect(taskId);
1664
+ const directory = this.observationDirectory(operation);
1665
+ const inspection = directory === this.directory ? this.inspect(taskId) : this.passiveSnapshot(taskId, directory);
1530
1666
  this.reconcileInspection(operation, inspection);
1531
1667
  this.recordReadsForTask(owner, store.getOperation(operation.operationId) ?? operation);
1532
- const paths = supervisorPaths(this.directory, taskId);
1668
+ if (!directory)
1669
+ throw new Error("Captured Background log directory unavailable");
1670
+ const paths = inspection?.logs ?? supervisorPaths(directory, taskId);
1533
1671
  const lines = Math.max(1, Math.floor(options.lines ?? 40));
1534
1672
  const stdout = tail(paths.stdout);
1535
1673
  const stderr = tail(paths.stderr);
@@ -1569,6 +1707,9 @@ export class ObservedWaitHost {
1569
1707
  `${view.taskId} ${view.kind}: ${view.status} (${view.phase})`,
1570
1708
  `operation: ${view.operationId}; terminal revision: ${view.terminalRevision}${view.terminalOutcome ? ` (${view.terminalOutcome})` : ""}`,
1571
1709
  ];
1710
+ const progress = view.progress && describeSupervisedProgress(view.progress, this.options.now?.() ?? Date.now());
1711
+ if (progress)
1712
+ lines.push(progress);
1572
1713
  if (view.sandbox) {
1573
1714
  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.`);
1574
1715
  }
@@ -2631,6 +2772,8 @@ export class ObservedWaitHost {
2631
2772
  ? resolveWorkerSandboxPlan(this.pi, workerPolicy, params, tool)
2632
2773
  : resolveForegroundSandboxPlan(this.pi, false, params, tool);
2633
2774
  assertBackgroundExecutionAllowed(spec, plan, { remote: false, cwd });
2775
+ if (spec.shell !== false)
2776
+ spec.resolvedWindowsShell = resolveWindowsLaunchShell(this.pi);
2634
2777
  const limits = backgroundExecutionLimits(plan);
2635
2778
  const gated = kind === "process" && params.require_successful_steps === true;
2636
2779
  if (gated) {
@@ -2764,10 +2907,18 @@ export class ObservedWaitHost {
2764
2907
  throw error;
2765
2908
  }
2766
2909
  }
2767
- const inspection = this.inspect(operation.taskId);
2910
+ let inspection;
2911
+ let unavailable = false;
2912
+ try {
2913
+ if (LOCAL_DURABLE_ID.test(operation.taskId))
2914
+ inspection = this.supervisor.inspect(operation.taskId, { recordLost: true });
2915
+ }
2916
+ catch {
2917
+ unavailable = true;
2918
+ }
2768
2919
  if (!inspection) {
2769
2920
  const now = this.options.now?.() ?? Date.now();
2770
- if (now - operation.createdAt >= 30_000) {
2921
+ if (!unavailable && now - operation.createdAt >= 30_000) {
2771
2922
  // The supervisor writes its launch record before spawning. No record
2772
2923
  // after the claim grace means no execution can be witnessed; this is
2773
2924
  // `lost`, never a success and never a silent retry.
@@ -2791,14 +2942,15 @@ export class ObservedWaitHost {
2791
2942
  void this.dispatchOutbox();
2792
2943
  return;
2793
2944
  }
2945
+ const reason = unavailable ? "durable supervisor records could not be read" : "no durable supervisor record exists for this operation";
2794
2946
  try {
2795
- if (claimed || operation.health !== "unmonitored" || operation.healthReason !== "no durable supervisor record exists for this operation") {
2947
+ if (claimed || operation.health !== "unmonitored" || operation.healthReason !== reason) {
2796
2948
  this.store?.recordSupervision({
2797
2949
  operationId: operation.operationId,
2798
2950
  owner: operation.owner,
2799
2951
  expectedHostId: this.hostId,
2800
2952
  health: "unmonitored",
2801
- reason: "no durable supervisor record exists for this operation",
2953
+ reason,
2802
2954
  });
2803
2955
  }
2804
2956
  }
@@ -2965,7 +3117,7 @@ export class ObservedWaitHost {
2965
3117
  return;
2966
3118
  }
2967
3119
  this.options.logger?.(`observed waits: ${operation.taskId} ${status} (revision ${recorded.operation.terminalRevision})`);
2968
- this.attemptTerminalCallback(operation, status, outcome, refs, { pendingWithoutContext: true });
3120
+ this.attemptTerminalCallback(recorded.operation, status, outcome, refs, { pendingWithoutContext: true });
2969
3121
  this.emitDurableTaskChange(operation.owner);
2970
3122
  // The parent callback is independent from the worker's wait: a worker may be
2971
3123
  // parked, while the parent session still learns that the supervised task ended.
@@ -3012,6 +3164,11 @@ export class ObservedWaitHost {
3012
3164
  skip("already delivered");
3013
3165
  return;
3014
3166
  }
3167
+ if (this.waitDeliveredTerminalRevision(operation, context)) {
3168
+ this.pendingTerminalCallbacks.delete(operation.taskId);
3169
+ this.store?.setParentCallbackPending(operation.taskId, false);
3170
+ return;
3171
+ }
3015
3172
  const waitPending = this.store?.listWaits({ owner: operation.owner, pendingOnly: true })
3016
3173
  .some((wait) => wait.dependencies.some((dep) => dep.operationId === operation.operationId)) ?? false;
3017
3174
  if (waitPending) {
@@ -3200,6 +3357,12 @@ export class ObservedWaitHost {
3200
3357
  return !!proof && proof.waitId === event.waitId && proof.generation === event.generation
3201
3358
  && proof.terminalRevision === event.terminalRevision;
3202
3359
  }
3360
+ waitDeliveredTerminalRevision(operation, context) {
3361
+ if (operation.terminalRevision === 0)
3362
+ return false;
3363
+ return Object.values(context.outboxDelivered ?? {}).some(proof => proof.terminalRevision === operation.terminalRevision)
3364
+ || (this.store?.hasDeliveredWaitDependency(operation.operationId, operation.terminalRevision, operation.owner) ?? false);
3365
+ }
3203
3366
  recordOutboxHandoffProof(taskId, event) {
3204
3367
  const context = this.currentLaunchContext(taskId);
3205
3368
  if (!context)
@@ -3431,8 +3594,17 @@ export class ObservedWaitHost {
3431
3594
  catch { /* the store closed between handoff and receipt */ }
3432
3595
  // Key the recovered receipt to this exact event. Never use the
3433
3596
  // standalone task callback's receipt as proof for a wait.
3434
- if (!receipted && taskId)
3435
- this.recordOutboxHandoffProof(taskId, event);
3597
+ if (taskId) {
3598
+ this.pendingTerminalCallbacks.delete(taskId);
3599
+ if (!receipted)
3600
+ this.recordOutboxHandoffProof(taskId, event);
3601
+ else {
3602
+ try {
3603
+ store.setParentCallbackPending(taskId, false);
3604
+ }
3605
+ catch { /* the wait receipt survives for recovery */ }
3606
+ }
3607
+ }
3436
3608
  },
3437
3609
  defer: (reason) => {
3438
3610
  if (settled)
@@ -3852,15 +4024,15 @@ export class ObservedWaitHost {
3852
4024
  return undefined;
3853
4025
  }
3854
4026
  }
3855
- sidecarPath(taskId) {
3856
- return join(this.directory, "observed", `${taskId}.json`);
4027
+ sidecarPath(taskId, directory = this.directory) {
4028
+ return join(directory, "observed", `${taskId}.json`);
3857
4029
  }
3858
4030
  writeLaunchContext(taskId, context) {
3859
4031
  try {
3860
4032
  const operation = this.operationForTask(taskId);
3861
4033
  const parent = operation?.owner.kind === "parent-session";
3862
- const outboxDelivered = operation && Object.values(context.outboxDelivered ?? {}).some(proof => proof.terminalRevision === operation.terminalRevision);
3863
- const pending = context.callback !== false && context.callbackDeliveredAt === undefined && !outboxDelivered;
4034
+ const pending = context.callback !== false && context.callbackDeliveredAt === undefined
4035
+ && (!parent || !this.waitDeliveredTerminalRevision(operation, context));
3864
4036
  // Publish the obligation before the sidecar: a crash may leave a pending
3865
4037
  // candidate, but cannot hide an accepted callback. Retire only after the
3866
4038
  // delivered/disabled sidecar is durable, so replay can prove suppression.
@@ -3881,9 +4053,9 @@ export class ObservedWaitHost {
3881
4053
  }
3882
4054
  catch { /* retain an obligation if the exact sidecar cannot be persisted */ }
3883
4055
  }
3884
- readLaunchContext(taskId) {
4056
+ readLaunchContext(taskId, directory = this.directory) {
3885
4057
  try {
3886
- const value = JSON.parse(readFileSync(this.sidecarPath(taskId), "utf8"));
4058
+ const value = JSON.parse(readFileSync(this.sidecarPath(taskId, directory), "utf8"));
3887
4059
  if (value.kind !== "process" && value.kind !== "watch")
3888
4060
  return undefined;
3889
4061
  return {