pi-better-server 0.6.0 → 0.7.1

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 (142) 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/codex/return.ts +3 -2
  5. package/src/detach/extension.ts +20 -3
  6. package/src/event-log.ts +40 -12
  7. package/src/hosted-session.ts +11 -5
  8. package/src/remote-client/packages.ts +1 -4
  9. package/src/runtime/background-tools.ts +54 -8
  10. package/src/runtime/background.ts +16 -4
  11. package/src/runtime/domain/background/process.mjs +49 -11
  12. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  13. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  14. package/src/runtime/domain/background-service/index.domain.mjs +19 -0
  15. package/src/runtime/domain/background-service/index.ts +19 -0
  16. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +87 -5
  17. package/src/runtime/domain/background-service/managed-frontend.ts +76 -5
  18. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +5 -0
  19. package/src/runtime/domain/background-service/navigator-provider.ts +4 -0
  20. package/src/runtime/domain/background-service/observed-waits.domain.mjs +203 -31
  21. package/src/runtime/domain/background-service/observed-waits.ts +168 -24
  22. package/src/runtime/domain/background-service/process.domain.mjs +49 -11
  23. package/src/runtime/domain/background-service/process.ts +45 -11
  24. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  25. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  26. package/src/runtime/domain/background-service/runtime.domain.mjs +8 -70
  27. package/src/runtime/domain/background-service/runtime.ts +8 -73
  28. package/src/runtime/domain/background-service/shared-harness-settings.domain.mjs +2 -3
  29. package/src/runtime/domain/background-service/shared-harness-settings.ts +2 -5
  30. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +55 -28
  31. package/src/runtime/domain/background-service/shared-navigator.ts +47 -26
  32. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  33. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  34. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +5 -1
  35. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +6 -0
  36. package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +1 -1
  37. package/src/runtime/domain/background-service/shared-ssh-core/index.ts +1 -1
  38. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  39. package/src/runtime/domain/background-service/stall.ts +7 -4
  40. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  41. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  42. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  43. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  44. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +49 -11
  45. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  46. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  47. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  48. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  49. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  50. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  51. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  52. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  53. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  54. package/src/runtime/domain/background-service/tools.domain.mjs +22 -16
  55. package/src/runtime/domain/background-service/tools.ts +26 -16
  56. package/src/runtime/domain/background-service/types.ts +4 -2
  57. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  58. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  59. package/src/runtime/domain/catalog/catalog-preferences.mjs +1 -3
  60. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  61. package/src/runtime/domain/coordinator/src/store.mjs +5 -1
  62. package/src/runtime/domain/log-paths.mjs +8 -1
  63. package/src/runtime/domain/parse.mjs +9 -5
  64. package/src/runtime/domain/sandbox-policy/README.md +3 -3
  65. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  66. package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +2 -3
  67. package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +2 -5
  68. package/src/runtime/domain/session-store.mjs +7 -0
  69. package/src/runtime/domain/shared-harness-settings.mjs +2 -3
  70. package/src/runtime/domain/subagents/README.md +12 -10
  71. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +2 -5
  72. package/src/runtime/domain/subagents/assignment-outcomes.ts +2 -5
  73. package/src/runtime/domain/subagents/assignment-report.domain.mjs +22 -0
  74. package/src/runtime/domain/subagents/assignment-report.ts +20 -0
  75. package/src/runtime/domain/subagents/batch.mjs +13 -5
  76. package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +1 -3
  77. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -5
  78. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  79. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  80. package/src/runtime/domain/subagents/config.domain.mjs +5 -0
  81. package/src/runtime/domain/subagents/config.ts +8 -2
  82. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  83. package/src/runtime/domain/subagents/continuation.ts +4 -2
  84. package/src/runtime/domain/subagents/extensions.mjs +1 -0
  85. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  86. package/src/runtime/domain/subagents/failures.ts +10 -2
  87. package/src/runtime/domain/subagents/finalization.domain.mjs +39 -32
  88. package/src/runtime/domain/subagents/finalization.ts +37 -30
  89. package/src/runtime/domain/subagents/git-workspace.domain.mjs +51 -6
  90. package/src/runtime/domain/subagents/git-workspace.ts +48 -6
  91. package/src/runtime/domain/subagents/index.domain.mjs +208 -75
  92. package/src/runtime/domain/subagents/index.ts +213 -75
  93. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +508 -0
  94. package/src/runtime/domain/subagents/isolated-workspace.ts +551 -0
  95. package/src/runtime/domain/subagents/list.mjs +2 -2
  96. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +22 -5
  97. package/src/runtime/domain/subagents/managed-launch-client.ts +23 -6
  98. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  99. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  100. package/src/runtime/domain/subagents/package.json +4 -2
  101. package/src/runtime/domain/subagents/parse.domain.mjs +9 -5
  102. package/src/runtime/domain/subagents/parse.ts +10 -5
  103. package/src/runtime/domain/subagents/registry.domain.mjs +31 -25
  104. package/src/runtime/domain/subagents/registry.ts +31 -13
  105. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  106. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  107. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  108. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  109. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  110. package/src/runtime/domain/subagents/session-store.ts +9 -0
  111. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  112. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  113. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +23 -7
  114. package/src/runtime/domain/subagents/shared-catalog.ts +23 -7
  115. package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +2 -3
  116. package/src/runtime/domain/subagents/shared-harness-settings.ts +2 -5
  117. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +55 -28
  118. package/src/runtime/domain/subagents/shared-navigator.ts +47 -26
  119. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  120. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  121. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +5 -1
  122. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +6 -0
  123. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  124. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  125. package/src/runtime/domain/subagents/task-policy.domain.mjs +2 -1
  126. package/src/runtime/domain/subagents/task-policy.ts +5 -1
  127. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  128. package/src/runtime/domain/subagents/tools.ts +4 -7
  129. package/src/runtime/domain/subagents/work-observation.domain.mjs +25 -1
  130. package/src/runtime/domain/subagents/work-observation.ts +20 -1
  131. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  132. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  133. package/src/runtime/domain/subagents/workspace-prepare-worker.mjs +12 -0
  134. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  135. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  136. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  137. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  138. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  139. package/src/runtime/read-model.ts +4 -2
  140. package/src/runtime/root.ts +5 -2
  141. package/src/shared-ssh-core/index.ts +1 -1
  142. package/src/version.ts +1 -1
@@ -463,13 +463,19 @@ class Supervisor {
463
463
  }
464
464
  applyReconciliation(launch, options) {
465
465
  return withStateFence(this.directory, launch.taskId, () => {
466
- const result = readTerminalRecord(this.directory, launch.taskId).value;
466
+ const { value: result, error: resultError } = readTerminalRecord(this.directory, launch.taskId);
467
+ if (resultError)
468
+ throw new Error(`Unreadable supervisor result record for ${launch.taskId}: ${resultError}`);
467
469
  if (result)
468
470
  return { status: result.status, terminal: true, result };
469
- const existingLost = readLostRecord(this.directory, launch.taskId).value;
471
+ const { value: existingLost, error: lostError } = readLostRecord(this.directory, launch.taskId);
472
+ if (lostError)
473
+ throw new Error(`Unreadable supervisor loss record for ${launch.taskId}: ${lostError}`);
470
474
  if (existingLost)
471
475
  return { status: "lost", terminal: true, lost: existingLost };
472
- const claim = readClaimRecord(this.directory, launch.taskId).value;
476
+ const { value: claim, error: claimError } = readClaimRecord(this.directory, launch.taskId);
477
+ if (claimError)
478
+ throw new Error(`Unreadable supervisor claim record for ${launch.taskId}: ${claimError}`);
473
479
  if (claim) {
474
480
  if (identityAlive(claim.pid, claim.pidStartTime, claim.claimedAt, this.readToken)) {
475
481
  return { status: "running", terminal: false };
@@ -8,12 +8,27 @@ import { observeForegroundSandboxPolicy } from "./sandbox.domain.mjs";
8
8
  import { registerTools } from "./tools.domain.mjs";
9
9
  import { deliverBackgroundTasksPrompt } from "./prompt.domain.mjs";
10
10
  import { closeBackgroundObservation } from "./work-observation.domain.mjs";
11
+ import { readBackgroundReviewInterval, saveBackgroundReviewInterval } from "./review-settings.domain.mjs";
11
12
  export default function backgroundTasksExtension(pi) {
12
13
  // The frontend owns native UI/delivery only. Mechanical tools run in the
13
14
  // fixed server service. Register their native definitions before the first turn.
14
15
  const { host: observedWaits, proxy, ui } = createManagedBackgroundFrontend(pi);
15
16
  const navigator = createBackgroundTasksNavigator(undefined, ui);
16
17
  initializeNavigatorPanels(pi);
18
+ const intervalLabel = (minutes) => `${minutes} minute${minutes === 1 ? "" : "s"}`;
19
+ const reviewSetting = {
20
+ id: "background-review-interval",
21
+ label: "Background wait review interval",
22
+ values: [1, 5, 10, 15, 30, 60].map(intervalLabel),
23
+ get: () => intervalLabel(readBackgroundReviewInterval()),
24
+ change(value) {
25
+ saveBackgroundReviewInterval(Number.parseInt(value, 10));
26
+ void observedWaits.reconcileNow().catch(() => undefined);
27
+ },
28
+ };
29
+ const registerReviewSetting = () => pi.events.emit("harness-settings:register", reviewSetting);
30
+ let stopReviewSettings = pi.events.on("harness-settings:request", registerReviewSetting);
31
+ registerReviewSetting();
17
32
  // Sections on a host that renders them; text only where it renders none.
18
33
  // Returning a prompt on modern pi would set forceSystemPrompt, and the request
19
34
  // would then carry a snapshot, so sections published after it never arrive.
@@ -25,6 +40,8 @@ export default function backgroundTasksExtension(pi) {
25
40
  observeForegroundSandboxPolicy(pi);
26
41
  // Registered before registerTools(pi), so this runs before running tasks are resumed.
27
42
  pi.on("session_start", async (_event, ctx) => {
43
+ stopReviewSettings ??= pi.events.on("harness-settings:request", registerReviewSetting);
44
+ registerReviewSetting();
28
45
  registerBackgroundTasksGoalProvider(pi);
29
46
  navigator.ensureBackgroundTasksNavigator(ctx);
30
47
  });
@@ -34,6 +51,8 @@ export default function backgroundTasksExtension(pi) {
34
51
  navigator.clearBackgroundTasksNavigatorSession();
35
52
  });
36
53
  pi.on("session_shutdown", async (_event, ctx) => {
54
+ stopReviewSettings?.();
55
+ stopReviewSettings = undefined;
37
56
  closeBackgroundObservation(pi);
38
57
  // /reload, session replacement, and quit load a fresh instance; stop this one's timers (#324).
39
58
  observedWaits.close();
@@ -8,6 +8,7 @@ import { observeForegroundSandboxPolicy } from "./sandbox.js";
8
8
  import { registerTools } from "./tools.js";
9
9
  import { deliverBackgroundTasksPrompt } from "./prompt.js";
10
10
  import { closeBackgroundObservation } from "./work-observation.js";
11
+ import { readBackgroundReviewInterval, saveBackgroundReviewInterval } from "./review-settings.js";
11
12
 
12
13
  export default function backgroundTasksExtension(pi: ExtensionAPI): void {
13
14
  // The frontend owns native UI/delivery only. Mechanical tools run in the
@@ -15,6 +16,20 @@ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
15
16
  const {host: observedWaits, proxy, ui} = createManagedBackgroundFrontend(pi);
16
17
  const navigator = createBackgroundTasksNavigator(undefined, ui);
17
18
  initializeNavigatorPanels(pi);
19
+ const intervalLabel = (minutes: number) => `${minutes} minute${minutes === 1 ? "" : "s"}`;
20
+ const reviewSetting = {
21
+ id: "background-review-interval",
22
+ label: "Background wait review interval",
23
+ values: [1, 5, 10, 15, 30, 60].map(intervalLabel),
24
+ get: () => intervalLabel(readBackgroundReviewInterval()),
25
+ change(value: string) {
26
+ saveBackgroundReviewInterval(Number.parseInt(value, 10));
27
+ void observedWaits.reconcileNow().catch(() => undefined);
28
+ },
29
+ };
30
+ const registerReviewSetting = () => pi.events.emit("harness-settings:register", reviewSetting);
31
+ let stopReviewSettings: (() => void) | undefined = pi.events.on("harness-settings:request", registerReviewSetting);
32
+ registerReviewSetting();
18
33
  // Sections on a host that renders them; text only where it renders none.
19
34
  // Returning a prompt on modern pi would set forceSystemPrompt, and the request
20
35
  // would then carry a snapshot, so sections published after it never arrive.
@@ -26,6 +41,8 @@ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
26
41
  observeForegroundSandboxPolicy(pi);
27
42
  // Registered before registerTools(pi), so this runs before running tasks are resumed.
28
43
  pi.on("session_start", async (_event, ctx) => {
44
+ stopReviewSettings ??= pi.events.on("harness-settings:request", registerReviewSetting);
45
+ registerReviewSetting();
29
46
  registerBackgroundTasksGoalProvider(pi);
30
47
  navigator.ensureBackgroundTasksNavigator(ctx);
31
48
  });
@@ -35,6 +52,8 @@ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
35
52
  navigator.clearBackgroundTasksNavigatorSession();
36
53
  });
37
54
  pi.on("session_shutdown", async (_event, ctx) => {
55
+ stopReviewSettings?.();
56
+ stopReviewSettings = undefined;
38
57
  closeBackgroundObservation(pi);
39
58
  // /reload, session replacement, and quit load a fresh instance; stop this one's timers (#324).
40
59
  observedWaits.close();
@@ -9,6 +9,7 @@ import { observeNavigatorLaunch } from "./shared-navigator.domain.mjs";
9
9
  export function createManagedBackgroundFrontend(pi) {
10
10
  let ctx, generation = 0, refresh, dirty = false;
11
11
  let rows = [], legacyRows = [], details = new Map(), logs = new Map();
12
+ let pendingAttention = new Set();
12
13
  const retainedTasks = new Map();
13
14
  const cachedTask = (id) => rows.find(row => row.id === id) ?? retainedTasks.get(id);
14
15
  let adoptedScope;
@@ -24,6 +25,7 @@ export function createManagedBackgroundFrontend(pi) {
24
25
  logs.clear();
25
26
  retainedTasks.clear();
26
27
  generation++;
28
+ pendingAttention.clear();
27
29
  }
28
30
  ctx = context;
29
31
  adoptedScope = scopeOf(context);
@@ -65,6 +67,38 @@ export function createManagedBackgroundFrontend(pi) {
65
67
  for (const listener of listeners)
66
68
  listener({ workspace: ctx?.cwd, sessionId: ctx?.sessionManager.getSessionId() });
67
69
  };
70
+ let handoffRetry;
71
+ let attentionRetry;
72
+ let retryAt = Infinity;
73
+ const scheduleHandoffPoll = (delayMs) => {
74
+ if (!ctx || retryAt <= Date.now() + delayMs)
75
+ return;
76
+ clearTimeout(handoffRetry);
77
+ retryAt = Date.now() + delayMs;
78
+ // Poll again before attempting delivery: the task or its recipient may have changed.
79
+ handoffRetry = setTimeout(() => {
80
+ handoffRetry = undefined;
81
+ retryAt = Infinity;
82
+ if (ctx)
83
+ void reconcile().catch(() => undefined);
84
+ }, delayMs);
85
+ handoffRetry.unref();
86
+ };
87
+ const waitForAttentionIdle = () => {
88
+ if (attentionRetry)
89
+ return;
90
+ attentionRetry = setTimeout(() => {
91
+ attentionRetry = undefined;
92
+ if (!ctx || !pendingAttention.size)
93
+ return;
94
+ if (!ctx.isIdle()) {
95
+ waitForAttentionIdle();
96
+ return;
97
+ }
98
+ void reconcile().catch(() => undefined);
99
+ }, 1000);
100
+ attentionRetry.unref();
101
+ };
68
102
  const reconcile = () => {
69
103
  if (!ctx)
70
104
  return Promise.resolve();
@@ -75,16 +109,20 @@ export function createManagedBackgroundFrontend(pi) {
75
109
  dirty = false;
76
110
  const captured = ctx, version = generation;
77
111
  refresh = (async () => {
112
+ const rechecking = pendingAttention.size && captured.isIdle() ? pendingAttention : undefined;
78
113
  trace('poll-start');
79
114
  const snapshot = await request('__background_poll', { knownActiveIds: rows.filter(row => row.active).map(row => row.id).slice(0, 200) });
80
115
  trace('poll-received', { stale: version !== generation, total: snapshot.deliveries?.length ?? 0, deliveries: (snapshot.deliveries ?? []).slice(0, 8).map((item) => ({ taskId: item.notification.taskId, receiptId: item.receiptId })) });
81
116
  if (version !== generation)
82
117
  return;
118
+ if (Number.isFinite(snapshot.retryAfterMs))
119
+ scheduleHandoffPoll(snapshot.retryAfterMs);
83
120
  if (snapshot.recoveryPending === true)
84
121
  dirty = true;
85
122
  // A rebuilding snapshot is not evidence that visible tasks vanished.
86
123
  if (snapshot.status !== 'rebuilding' && snapshot.status !== 'degraded') {
87
- rows = snapshot.tasks ?? [];
124
+ // Older servers include compact callback pointers in the task list.
125
+ rows = (snapshot.tasks ?? []).filter((task) => !task.callbackPending);
88
126
  // Detail remains inspectable while Navigator retains a terminal row.
89
127
  for (const task of rows) {
90
128
  retainedTasks.delete(task.id);
@@ -95,9 +133,19 @@ export function createManagedBackgroundFrontend(pi) {
95
133
  legacyRows = snapshot.legacyRows ?? [];
96
134
  }
97
135
  notify();
136
+ const deferredAttention = new Set();
98
137
  for (const item of snapshot.deliveries ?? []) {
99
138
  if (queued.has(item.token))
100
139
  continue;
140
+ const n = item.notification;
141
+ const type = n.event?.customType;
142
+ if ((type === 'background-task-stall' || type === 'background-wait-review')
143
+ && (!rechecking?.has(item.receiptId) || !captured.isIdle())) {
144
+ // Keep the candidate here while busy. Pi's followUp queue cannot
145
+ // revalidate it when the current turn eventually ends.
146
+ deferredAttention.add(item.receiptId);
147
+ continue;
148
+ }
101
149
  queued.add(item.token);
102
150
  const facts = { taskId: item.notification.taskId, receiptId: item.receiptId };
103
151
  const receipt = (delivered, reason) => {
@@ -115,10 +163,15 @@ export function createManagedBackgroundFrontend(pi) {
115
163
  receipt(true);
116
164
  continue;
117
165
  }
118
- const n = item.notification;
119
166
  trace('queue', { ...facts, urgent: n.urgent === true, recipientActive: active(n.origin, n.branchId) });
120
167
  if (n.urgent) {
121
- 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) });
168
+ const handoff = getCallbackBatcher(pi).deliverUrgent({ ...n.event, receiptId: item.receiptId,
169
+ getSuppressionReason: () => active(n.origin, n.branchId) ? undefined : 'The originating session or branch is no longer active',
170
+ onDelivered: () => receipt(true), onSuppressed: reason => receipt(false, reason) });
171
+ const retry = () => { queued.delete(item.token); if (version === generation)
172
+ scheduleHandoffPoll(1000); };
173
+ void Promise.resolve(handoff).then(ok => { if (!ok)
174
+ retry(); }, retry);
122
175
  continue;
123
176
  }
124
177
  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,
@@ -126,7 +179,19 @@ export function createManagedBackgroundFrontend(pi) {
126
179
  getSuppressionReason: () => active(n.origin, n.branchId) ? undefined : 'The originating session or branch is no longer active',
127
180
  onDelivered: () => receipt(true), onSuppressed: (reason) => receipt(false, reason) });
128
181
  }
129
- })().catch(error => { trace('poll-error', { error: String(error).slice(0, 256) }); throw error; })
182
+ pendingAttention = deferredAttention;
183
+ if (pendingAttention.size) {
184
+ if (captured.isIdle())
185
+ dirty = true;
186
+ else
187
+ waitForAttentionIdle();
188
+ }
189
+ })().catch(error => {
190
+ trace('poll-error', { error: String(error).slice(0, 256) });
191
+ if (version === generation && pendingAttention.size)
192
+ waitForAttentionIdle();
193
+ throw error;
194
+ })
130
195
  .finally(() => { refresh = undefined; if (dirty && ctx)
131
196
  void reconcile().catch(() => undefined); });
132
197
  return refresh;
@@ -150,7 +215,24 @@ export function createManagedBackgroundFrontend(pi) {
150
215
  activate();
151
216
  },
152
217
  noteParentContext(context) { adoptContext(context); generation++; void reconcile().catch(() => undefined); },
153
- close() { observing = false; ctx = undefined; adoptedScope = undefined; generation++; rows = []; legacyRows = []; details.clear(); logs.clear(); retainedTasks.clear(); queued.clear(); ownership.clear(); },
218
+ close() {
219
+ clearTimeout(handoffRetry);
220
+ clearTimeout(attentionRetry);
221
+ handoffRetry = attentionRetry = undefined;
222
+ retryAt = Infinity;
223
+ observing = false;
224
+ ctx = undefined;
225
+ adoptedScope = undefined;
226
+ generation++;
227
+ rows = [];
228
+ legacyRows = [];
229
+ details.clear();
230
+ logs.clear();
231
+ retainedTasks.clear();
232
+ queued.clear();
233
+ ownership.clear();
234
+ pendingAttention.clear();
235
+ },
154
236
  isParentOriginActive: active,
155
237
  onDurableTaskChange(listener) { listeners.add(listener); return () => listeners.delete(listener); },
156
238
  listDurableTasks(origin, _options = {}) { return active(origin) ? rows : []; },
@@ -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() }] : []),