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.
- package/package.json +4 -3
- package/scripts/measure-full-runtime/frontend.ts +10 -2
- package/scripts/measure-full-runtime.mjs +2 -0
- package/src/runtime/background-tools.ts +54 -8
- package/src/runtime/background.ts +16 -4
- package/src/runtime/domain/background/process.mjs +49 -11
- package/src/runtime/domain/background/supervisor/store.mjs +3 -3
- package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
- package/src/runtime/domain/background-service/index.domain.mjs +19 -0
- package/src/runtime/domain/background-service/index.ts +19 -0
- package/src/runtime/domain/background-service/managed-frontend.domain.mjs +87 -5
- package/src/runtime/domain/background-service/managed-frontend.ts +76 -5
- package/src/runtime/domain/background-service/navigator-provider.domain.mjs +5 -0
- package/src/runtime/domain/background-service/navigator-provider.ts +4 -0
- package/src/runtime/domain/background-service/observed-waits.domain.mjs +203 -31
- package/src/runtime/domain/background-service/observed-waits.ts +168 -24
- package/src/runtime/domain/background-service/process.domain.mjs +49 -11
- package/src/runtime/domain/background-service/process.ts +45 -11
- package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
- package/src/runtime/domain/background-service/review-settings.ts +18 -0
- package/src/runtime/domain/background-service/runtime.domain.mjs +8 -70
- package/src/runtime/domain/background-service/runtime.ts +8 -73
- package/src/runtime/domain/background-service/shared-navigator.domain.mjs +55 -28
- package/src/runtime/domain/background-service/shared-navigator.ts +47 -26
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +5 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +6 -0
- package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
- package/src/runtime/domain/background-service/stall.ts +7 -4
- package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
- package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
- package/src/runtime/domain/background-service/supervisor/README.md +1 -4
- package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
- package/src/runtime/domain/background-service/supervisor/generated/process.mjs +49 -11
- package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
- package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
- package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
- package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
- package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
- package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
- package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
- package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
- package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
- package/src/runtime/domain/background-service/tools.domain.mjs +22 -16
- package/src/runtime/domain/background-service/tools.ts +26 -16
- package/src/runtime/domain/background-service/types.ts +4 -2
- package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
- package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
- package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
- package/src/runtime/domain/coordinator/src/store.mjs +5 -1
- package/src/runtime/domain/log-paths.mjs +8 -1
- package/src/runtime/domain/parse.mjs +9 -5
- package/src/runtime/domain/sandbox-policy/README.md +3 -3
- package/src/runtime/domain/sandbox-policy/package.json +1 -1
- package/src/runtime/domain/session-store.mjs +7 -0
- package/src/runtime/domain/subagents/README.md +12 -10
- package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +2 -5
- package/src/runtime/domain/subagents/assignment-outcomes.ts +2 -5
- package/src/runtime/domain/subagents/assignment-report.domain.mjs +22 -0
- package/src/runtime/domain/subagents/assignment-report.ts +20 -0
- package/src/runtime/domain/subagents/batch.mjs +13 -5
- package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
- package/src/runtime/domain/subagents/cleanup.ts +10 -2
- package/src/runtime/domain/subagents/config.domain.mjs +5 -0
- package/src/runtime/domain/subagents/config.ts +7 -1
- package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
- package/src/runtime/domain/subagents/continuation.ts +4 -2
- package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
- package/src/runtime/domain/subagents/failures.ts +10 -2
- package/src/runtime/domain/subagents/finalization.domain.mjs +5 -2
- package/src/runtime/domain/subagents/finalization.ts +7 -2
- package/src/runtime/domain/subagents/index.domain.mjs +163 -61
- package/src/runtime/domain/subagents/index.ts +163 -60
- package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +515 -0
- package/src/runtime/domain/subagents/isolated-workspace.ts +557 -0
- package/src/runtime/domain/subagents/list.mjs +2 -2
- package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +22 -5
- package/src/runtime/domain/subagents/managed-launch-client.ts +23 -6
- package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
- package/src/runtime/domain/subagents/output-payload.ts +26 -12
- package/src/runtime/domain/subagents/package.json +4 -2
- package/src/runtime/domain/subagents/parse.domain.mjs +9 -5
- package/src/runtime/domain/subagents/parse.ts +10 -5
- package/src/runtime/domain/subagents/registry.domain.mjs +24 -18
- package/src/runtime/domain/subagents/registry.ts +23 -5
- package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
- package/src/runtime/domain/subagents/retained-result.ts +65 -0
- package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
- package/src/runtime/domain/subagents/session-selection.ts +2 -1
- package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
- package/src/runtime/domain/subagents/session-store.ts +9 -0
- package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
- package/src/runtime/domain/subagents/settings-page.ts +147 -108
- package/src/runtime/domain/subagents/shared-catalog.domain.mjs +23 -7
- package/src/runtime/domain/subagents/shared-catalog.ts +23 -7
- package/src/runtime/domain/subagents/shared-navigator.domain.mjs +55 -28
- package/src/runtime/domain/subagents/shared-navigator.ts +47 -26
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +5 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +6 -0
- package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
- package/src/runtime/domain/subagents/task-guard.ts +13 -1
- package/src/runtime/domain/subagents/task-policy.domain.mjs +2 -1
- package/src/runtime/domain/subagents/task-policy.ts +5 -1
- package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
- package/src/runtime/domain/subagents/tools.ts +4 -7
- package/src/runtime/domain/subagents/work-observation.domain.mjs +25 -1
- package/src/runtime/domain/subagents/work-observation.ts +20 -1
- package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
- package/src/runtime/domain/subagents/workspace-files.ts +114 -0
- package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
- package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
- package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
- package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
- package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
- package/src/runtime/read-model.ts +4 -2
- package/src/runtime/root.ts +5 -2
- package/src/version.ts +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-better-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Daemon that hosts Pi agent sessions behind a local Unix socket with session-addressed Pi RPC.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -47,13 +47,15 @@
|
|
|
47
47
|
"verify": "npm run typecheck && npm test"
|
|
48
48
|
},
|
|
49
49
|
"peerDependencies": {
|
|
50
|
-
"@earendil-works/pi-coding-agent": ">=0.82.0"
|
|
50
|
+
"@earendil-works/pi-coding-agent": ">=0.82.0",
|
|
51
|
+
"typebox": "*"
|
|
51
52
|
},
|
|
52
53
|
"devDependencies": {
|
|
53
54
|
"@earendil-works/pi-ai": "^0.82.0",
|
|
54
55
|
"@earendil-works/pi-coding-agent": "^0.82.0",
|
|
55
56
|
"@types/node": "^25.0.0",
|
|
56
57
|
"tsx": "^4.22.3",
|
|
58
|
+
"typebox": "1.3.27",
|
|
57
59
|
"typescript": "^6.0.0"
|
|
58
60
|
},
|
|
59
61
|
"engines": {
|
|
@@ -66,7 +68,6 @@
|
|
|
66
68
|
"proper-lockfile": "^4.1.2",
|
|
67
69
|
"shell-quote": "1.12.0",
|
|
68
70
|
"smol-toml": "1.9.0",
|
|
69
|
-
"typebox": "1.3.27",
|
|
70
71
|
"yaml": "^2.9.1"
|
|
71
72
|
}
|
|
72
73
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createAgentSession, DefaultResourceLoader, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
|
|
1
|
+
import { createAgentSession, initTheme, DefaultResourceLoader, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
|
|
2
2
|
import subagents from '../../../pi-better-subagents/index.ts';
|
|
3
3
|
import background from '../../../pi-better-background-tasks/src/index.ts';
|
|
4
4
|
import { getObservedWaitHost } from '../../../pi-better-background-tasks/src/observed-waits.ts';
|
|
@@ -9,12 +9,20 @@ const settingsManager = SettingsManager.inMemory({});
|
|
|
9
9
|
const resourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager, noExtensions: true, noSkills: true, noContextFiles: true, noThemes: true, noPromptTemplates: true, extensionFactories: process.env.BACKGROUND_ONLY ? [capturedBackground] : [subagents, capturedBackground] });
|
|
10
10
|
await resourceLoader.reload();
|
|
11
11
|
const { session } = await createAgentSession({ cwd, agentDir, settingsManager, resourceLoader, sessionManager: process.env.BACKGROUND_SESSION_FILE ? SessionManager.open(process.env.BACKGROUND_SESSION_FILE) : SessionManager.inMemory(cwd), noTools: 'all' });
|
|
12
|
-
|
|
12
|
+
const testNavigator = process.env.BACKGROUND_TEST_NAVIGATOR === "1";
|
|
13
|
+
if (testNavigator) initTheme("dark", false);
|
|
14
|
+
await session.bindExtensions({ mode: testNavigator ? 'tui' : 'print',
|
|
15
|
+
...(testNavigator ? { uiContext: { ...session.extensionRunner.createContext().ui, setEditorComponent() {}, setWidget() {}, setStatus() {} } } : {}), onError: error => { throw new Error(String(error)); } });
|
|
13
16
|
process.send?.({ ready: true, pid: process.pid, sessionId: session.sessionId });
|
|
14
17
|
process.on('message', async (request: any) => {
|
|
15
18
|
try {
|
|
16
19
|
if (request.stop) { await session.extensionRunner.emit({ type: 'session_shutdown', reason: 'quit' }); session.dispose(); process.disconnect(); return; }
|
|
17
20
|
if(request.barrier){await getObservedWaitHost(backgroundApi)!.reconcileNow();process.send?.({id:request.id,result:{ready:true}});return;}
|
|
21
|
+
if (request.navigatorRows) {
|
|
22
|
+
const state = (globalThis as any)[Symbol.for("pi-better-harness.navigator.state")];
|
|
23
|
+
process.send?.({ id: request.id, result: state.providers.get("background-tasks").listRows(Date.now()) });
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
18
26
|
if(request.entries){process.send?.({id:request.id,result:session.sessionManager.getBranch()});return;}
|
|
19
27
|
const tool = session.extensionRunner.getToolDefinition(request.tool);
|
|
20
28
|
if (!tool) throw new Error(`Missing real tool ${request.tool}`);
|
|
@@ -21,6 +21,8 @@ const probe = new URL('./measure-full-runtime/probe.mjs', import.meta.url).href;
|
|
|
21
21
|
const execPath = process.env.PI_TEST_PRIVATE_RUNTIME_NODE ?? process.execPath;
|
|
22
22
|
process.env.PI_RESOURCE_REPORT_DIR=samples;await import(probe);
|
|
23
23
|
const env = { ...process.env, PI_CODING_AGENT_DIR: agent, PI_SERVER_DIR: transport, TMPDIR: root, TMP: root, TEMP: root, PI_RESOURCE_REPORT_DIR: samples,
|
|
24
|
+
// The steady-state measurement needs silent commands to stay healthy for the entire run.
|
|
25
|
+
PI_BETTER_STALL_QUIET_MS: String(60 * 60_000), PI_BETTER_STALL_MS: String(2 * 60 * 60_000),
|
|
24
26
|
BACKGROUND_SESSION_FILE:sessionFile,NODE_OPTIONS: `--import ${probe}`, LAUNCH_WORKSPACE: cwd, LAUNCH_ENTERED: join(cwd, 'entered'), LAUNCH_RELEASE: join(cwd, 'release'), PI_OFFLINE: '1' };
|
|
25
27
|
mkdirSync(join(agent,'extensions'),{recursive:true});
|
|
26
28
|
writeFileSync(join(agent,'extensions','resource-hosted.ts'),`export { default } from ${JSON.stringify(fileURLToPath(new URL('./measure-full-runtime/hosted-extension.ts',import.meta.url)))};\n`);
|
|
@@ -10,9 +10,9 @@ import { acquireMutationStore } from './mutation-store.ts';
|
|
|
10
10
|
export async function createBackgroundTools(root: string, instance: string, draining: () => boolean = () => false, observe?: (scope: Record<string, unknown>) => Promise<any>, verificationMs = 30000,
|
|
11
11
|
trace?: (slot: number, phase: 'queued' | 'executing' | 'recovery' | 'read-pending' | 'read-returned' | 'tool-pending' | 'tool-returned' | 'settled') => void) {
|
|
12
12
|
const load = (file: string) => import(`./domain/background-service/${file}.domain.mjs`);
|
|
13
|
-
const [{ createObservedWaitHost }, { registerTools }, { createBackgroundTaskRuntime }, sandbox, authority, permissions, registry, navigator, failures] = await Promise.all([
|
|
13
|
+
const [{ createObservedWaitHost }, { registerTools }, { createBackgroundTaskRuntime }, sandbox, authority, permissions, registry, navigator, failures, reviewSettings] = await Promise.all([
|
|
14
14
|
load('observed-waits'), load('tools'), load('runtime'), load('sandbox'), load('managed-authority'),
|
|
15
|
-
import(String('./domain/sandbox-policy/permission-settings.domain.mjs')), load('registry'), load('navigator-provider'), load('failures'),
|
|
15
|
+
import(String('./domain/sandbox-policy/permission-settings.domain.mjs')), load('registry'), load('navigator-provider'), load('failures'), load('review-settings'),
|
|
16
16
|
]);
|
|
17
17
|
const identity = await load('process-identity');
|
|
18
18
|
const lease = acquireMutationStore(root);
|
|
@@ -34,6 +34,12 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
34
34
|
traceSeen.add(line);
|
|
35
35
|
try { console.error('[background-handoff-server]', output); } catch { /* diagnostics never own delivery */ }
|
|
36
36
|
};
|
|
37
|
+
const isAttentionDelivery = (item: any) => {
|
|
38
|
+
const type = item.notification.event?.customType;
|
|
39
|
+
return type === 'background-task-stall' || type === 'background-wait-review';
|
|
40
|
+
};
|
|
41
|
+
const sameNativeHost = (item: any, record: any) => item.scope.pid === record.pid && item.scope.start === record.start;
|
|
42
|
+
const deliveryLeaseMs = 30000;
|
|
37
43
|
const ownerKey = (owner: any) => JSON.stringify([owner.workspace, owner.sessionId]);
|
|
38
44
|
const forgetView = (view: string) => { projections.delete(view); recoveryVersions.delete(view); };
|
|
39
45
|
const forgetOwner = (key: string) => {
|
|
@@ -193,7 +199,7 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
193
199
|
sessionManager: { getSessionId: () => record.owner.sessionId, getBranch: () => branch, getEntries: () => branch, getLeafId: () => record.branchIds.at(-1), getSessionFile: () => undefined } };
|
|
194
200
|
service.noteParentContext(ctx, { recover: false });
|
|
195
201
|
for (const [token, item] of deliveries)
|
|
196
|
-
if (Date.now() - item.createdAt
|
|
202
|
+
if (Date.now() - item.createdAt >= deliveryLeaseMs) {
|
|
197
203
|
item.delivery.defer('Native delivery lease expired');
|
|
198
204
|
forgetOwner(ownerKey(item.scope.owner));
|
|
199
205
|
deliveries.delete(token);
|
|
@@ -202,7 +208,7 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
202
208
|
const item = deliveries.get(record.params.token);
|
|
203
209
|
traceHandoff('receipt', { sessionId: record.owner.sessionId, taskId: item?.notification.taskId,
|
|
204
210
|
receiptId: item?.receiptId, found: Boolean(item), delivered: record.params.delivered === true });
|
|
205
|
-
if (!item || ownerKey(item.scope.owner) !== key)
|
|
211
|
+
if (!item || ownerKey(item.scope.owner) !== key || isAttentionDelivery(item) && !sameNativeHost(item, record))
|
|
206
212
|
throw new Error('delivery-receipt-refused');
|
|
207
213
|
if (record.params.delivered === true && !service.isParentOriginActive(item.notification.origin, item.notification.branchId))
|
|
208
214
|
throw new Error('delivery-recipient-inactive');
|
|
@@ -234,7 +240,9 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
234
240
|
trace?.(slot, 'read-returned');
|
|
235
241
|
if (snapshot.status !== 'ready')
|
|
236
242
|
throw new Error(snapshot.reason ?? 'Shared Background observation unverified');
|
|
237
|
-
|
|
243
|
+
// Callback pointers carry a delivery obligation but no navigator detail.
|
|
244
|
+
const visibleRows = snapshot.rows.filter(({ meta }: any) => !meta.callbackPending
|
|
245
|
+
&& (!meta.parentRecipient?.branchId || record.branchIds.includes(meta.parentRecipient.branchId)));
|
|
238
246
|
const revision = authority.backgroundDigest([snapshot.scopeRevision, record.branchIds]);
|
|
239
247
|
let projection = projections.get(viewKey);
|
|
240
248
|
if (projection?.revision !== revision) {
|
|
@@ -260,14 +268,52 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
260
268
|
let task = service.readDurableTask({cwd: record.owner.workspace, sessionId: record.owner.sessionId}, id);
|
|
261
269
|
if (!task) {
|
|
262
270
|
const exact = await observe({background: true, cwd: record.owner.workspace, sessionId: record.owner.sessionId, id});
|
|
263
|
-
task = exact.rows.find((row: any) => row.meta.id === id)?.meta;
|
|
271
|
+
task = exact.rows.find((row: any) => row.meta.id === id && !row.meta.callbackPending)?.meta;
|
|
264
272
|
}
|
|
265
273
|
if (task && task.dismissedAt === undefined && (!task.parentRecipient?.branchId || record.branchIds.includes(task.parentRecipient.branchId))) { tasks.push(task); present.add(id); }
|
|
266
274
|
}
|
|
267
275
|
}
|
|
268
|
-
const
|
|
276
|
+
const origin = { cwd: record.owner.workspace, sessionId: record.owner.sessionId };
|
|
277
|
+
const liveAlerts = new Map<string, any>();
|
|
278
|
+
const reviewTasks = tasks.filter(task => task.active && task.progress && task.callback && task.owner.kind === 'parent-session');
|
|
279
|
+
let intervalMinutes = reviewSettings.DEFAULT_BACKGROUND_REVIEW_INTERVAL_MINUTES;
|
|
280
|
+
if (reviewTasks.some(task => task.waits.length)) {
|
|
281
|
+
try { intervalMinutes = reviewSettings.readBackgroundReviewInterval({ agentDir: () => root }); }
|
|
282
|
+
catch { /* An unreadable settings file must not interrupt Background delivery. */ }
|
|
283
|
+
}
|
|
284
|
+
let nextReviewAt = Infinity;
|
|
285
|
+
for (const task of reviewTasks) {
|
|
286
|
+
const stall = task.progress.alertDue ? service.pendingStallAlert(origin, task.id, task.waits) : undefined;
|
|
287
|
+
const review = task.waits.length ? service.backgroundWaitReview(origin, task.id, task.waits, intervalMinutes * 60_000) : undefined;
|
|
288
|
+
for (const alert of [stall, review?.alert]) {
|
|
289
|
+
if (!alert) continue;
|
|
290
|
+
liveAlerts.set(alert.delivery.receiptId, alert.notification);
|
|
291
|
+
notifyParent(alert.notification, alert.delivery);
|
|
292
|
+
}
|
|
293
|
+
if (review && !review.alert) nextReviewAt = Math.min(nextReviewAt, review.dueAt);
|
|
294
|
+
}
|
|
295
|
+
const outgoing = [];
|
|
296
|
+
let retryAfterMs = Number.isFinite(nextReviewAt) ? Math.max(1, nextReviewAt - Date.now()) : undefined;
|
|
297
|
+
if (liveAlerts.size && deliveries.size >= 256) retryAfterMs = Math.min(retryAfterMs ?? 1000, 1000);
|
|
298
|
+
for (const [token, item] of deliveries) {
|
|
299
|
+
if (ownerKey(item.scope.owner) !== key) continue;
|
|
300
|
+
let notification = item.notification;
|
|
301
|
+
if (isAttentionDelivery(item)) {
|
|
302
|
+
if (item.notification.branchId && !record.branchIds.includes(item.notification.branchId)) continue;
|
|
303
|
+
notification = liveAlerts.get(item.receiptId);
|
|
304
|
+
if (!notification) { deliveries.delete(token); continue; }
|
|
305
|
+
// Two frontends can share a session and branch. Only the holder may hand off
|
|
306
|
+
// each alert. A survivor polls again at lease expiry if no receipt arrives.
|
|
307
|
+
if (!sameNativeHost(item, record)) {
|
|
308
|
+
const remaining = Math.max(1, item.createdAt + deliveryLeaseMs - Date.now());
|
|
309
|
+
retryAfterMs = Math.min(retryAfterMs ?? remaining, remaining);
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
outgoing.push({ token, notification, receiptId: item.receiptId });
|
|
314
|
+
}
|
|
269
315
|
traceHandoff('poll-return', { sessionId: record.owner.sessionId, total: outgoing.length, deliveries: outgoing.slice(0, 8).map(item => ({ taskId: item.notification.taskId, receiptId: item.receiptId })) });
|
|
270
|
-
return { ...projection, tasks, recoveryPending: service.hasPendingParentCallbackRecovery(), deliveries: outgoing };
|
|
316
|
+
return { ...projection, tasks, retryAfterMs, recoveryPending: service.hasPendingParentCallbackRecovery(), deliveries: outgoing };
|
|
271
317
|
}
|
|
272
318
|
const origin = { cwd: record.owner.workspace, sessionId: record.owner.sessionId };
|
|
273
319
|
if (record.tool === '__background_detail' || record.tool === '__background_action') {
|
|
@@ -7,6 +7,8 @@ import { tmpdir } from "node:os";
|
|
|
7
7
|
import { snapshot } from "./domain/background/snapshot.mjs";
|
|
8
8
|
// @ts-expect-error Generated canonical registry queries.
|
|
9
9
|
import { observeMetasForOrigin, observeRecentMetasForOrigin, recentMetaDeadline, observationRevisionForOrigin, belongsToOrigin, readMeta, getRegistryIoMetrics } from "./domain/background/registry.mjs";
|
|
10
|
+
// @ts-expect-error Generated canonical progress policy.
|
|
11
|
+
import { supervisedProgress } from "./domain/background-service/supervised-progress.domain.mjs";
|
|
10
12
|
import { BackgroundHistory } from "./background-history.ts";
|
|
11
13
|
import type { WorkScope } from "./read-model.ts";
|
|
12
14
|
import { ENTITY_BUDGET } from "./work-budget.ts";
|
|
@@ -141,6 +143,8 @@ export class BackgroundObservation {
|
|
|
141
143
|
try {
|
|
142
144
|
const watcher = watch(directory, { recursive: true }, (_event, file) => {
|
|
143
145
|
if (this.closed) return;
|
|
146
|
+
// Progress changes only the active overlay. Historical rows and wait inputs stay cached.
|
|
147
|
+
if (file && /^tasks[/\\][^/\\]+[/\\]progress\.json$/.test(String(file))) { this.schedule(); return; }
|
|
144
148
|
const match = file && /^(?:observed[/\\]([^/\\]+)\.json|tasks[/\\]([^/\\]+)[/\\](?:launch|claim|command|result|lost|stop|cleanup)\.json)$/.exec(String(file));
|
|
145
149
|
if (match) {
|
|
146
150
|
const op = this.db?.prepare("SELECT operation_id FROM operations WHERE task_id=? AND observer_kind='local-supervisor'").get(match[1] ?? match[2]);
|
|
@@ -310,10 +314,14 @@ export class BackgroundObservation {
|
|
|
310
314
|
this.dirtyOperations.clear();
|
|
311
315
|
if (this.inbox.metrics.more || this.inbox.metrics.pending) this.schedule();
|
|
312
316
|
if (this.expiry) clearTimeout(this.expiry);
|
|
313
|
-
const deadlines = [...this.recent.map(op => op.terminal_at + 30000), ...[...this.legacy.values()].flatMap(entry => [
|
|
317
|
+
const deadlines = [...rows.flatMap(row => row.progress?.nextDeadline ?? []), ...this.recent.map(op => op.terminal_at + 30000), ...[...this.legacy.values()].flatMap(entry => [
|
|
314
318
|
...entry.recent.map(row => row.endedAt + 30000), ...recentMetaDeadline(entry.origin),
|
|
315
319
|
...(entry.origin.sessionId ? recentMetaDeadline({ cwd: entry.origin.cwd }) : [])])].filter(Number.isFinite);
|
|
316
|
-
if (deadlines.length) {
|
|
320
|
+
if (deadlines.length) {
|
|
321
|
+
const delay = Math.max(1, Math.min(2_147_483_647, Math.min(...deadlines) - Date.now()));
|
|
322
|
+
this.expiry = setTimeout(() => this.schedule(), delay);
|
|
323
|
+
this.expiry.unref();
|
|
324
|
+
}
|
|
317
325
|
observation?.commit();
|
|
318
326
|
return changed;
|
|
319
327
|
} catch (error) {
|
|
@@ -404,7 +412,7 @@ export class BackgroundObservation {
|
|
|
404
412
|
const terminal = inspection?.terminal === true || op.terminal_revision > 0;
|
|
405
413
|
const status = inspection?.terminal ? inspection.status : op.terminal_revision > 0 ? op.terminal_outcome : inspection?.status ?? "running";
|
|
406
414
|
const row = { ...parent, durable: true, id: op.task_id, operationId: op.operation_id, kind: context.kind ?? inspection?.kind ?? "process",
|
|
407
|
-
status, active: !terminal, terminal, attention: terminal && status !== "succeeded", waits,
|
|
415
|
+
callback: Boolean(context.kind && context.callback !== false), status, active: !terminal, terminal, attention: terminal && status !== "succeeded", waits,
|
|
408
416
|
terminalRevision: op.terminal_revision, terminalOutcome: op.terminal_outcome,
|
|
409
417
|
owner: { kind: op.owner_kind, sessionId: op.owner_session_id, workspace: op.owner_workspace, branchId: op.owner_branch_id ?? null },
|
|
410
418
|
startedAt: inspection?.result?.startedAt ?? inspection?.launch.createdAt ?? op.created_at,
|
|
@@ -417,7 +425,11 @@ export class BackgroundObservation {
|
|
|
417
425
|
if (this.terminalProjections.size > 4096) this.terminalProjections.delete(this.terminalProjections.keys().next().value!);
|
|
418
426
|
return row;
|
|
419
427
|
} catch (error) { this.dirtyOperations.add(op.operation_id); throw error; }
|
|
420
|
-
}).filter(Boolean)
|
|
428
|
+
}).filter(Boolean).map(row => {
|
|
429
|
+
if (!row.active) return row;
|
|
430
|
+
const inspection = this.terminalProjections.get(row.operationId)?.inspection;
|
|
431
|
+
return { ...row, progress: supervisedProgress(inspection) };
|
|
432
|
+
});
|
|
421
433
|
}
|
|
422
434
|
private pendingRows(entry: BackgroundScope): any[] { return entry.pending; }
|
|
423
435
|
private refreshPending(entry: BackgroundScope, revision: number): void {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
-
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, writeSync } from "node:fs";
|
|
3
|
-
import {
|
|
2
|
+
import { accessSync, appendFileSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join, win32 } from "node:path";
|
|
4
5
|
/** Known Git for Windows locations; `bash -lc` needs a real bash, not the WSL shim. */
|
|
5
6
|
const WINDOWS_BASH_CANDIDATES = [
|
|
6
7
|
"C:\\Program Files\\Git\\bin\\bash.exe",
|
|
@@ -13,7 +14,8 @@ const WINDOWS_BASH_CANDIDATES = [
|
|
|
13
14
|
* POSIX keeps `/bin/bash`. Windows has no `/bin/bash`, and the `bash.exe` found
|
|
14
15
|
* on PATH is usually the WSL launcher in System32 or the WindowsApps alias,
|
|
15
16
|
* either of which would run the command inside WSL instead of Windows. Prefer
|
|
16
|
-
* an explicit override, then Git for Windows,
|
|
17
|
+
* an explicit override, then Pi's shellPath, Git for Windows, and a non-WSL
|
|
18
|
+
* `bash.exe` on PATH.
|
|
17
19
|
*
|
|
18
20
|
* Resolved lazily at spawn time, not module load: env-injection extensions
|
|
19
21
|
* (e.g. pi-env) may apply settings.json `env` values after this module is
|
|
@@ -21,27 +23,62 @@ const WINDOWS_BASH_CANDIDATES = [
|
|
|
21
23
|
*
|
|
22
24
|
* Exposed for tests and reuse.
|
|
23
25
|
*/
|
|
24
|
-
export function resolveDefaultShell() {
|
|
26
|
+
export function resolveDefaultShell(shellPath) {
|
|
25
27
|
const fromEnv = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
|
|
26
28
|
if (fromEnv)
|
|
27
29
|
return fromEnv;
|
|
28
30
|
if (process.platform !== "win32")
|
|
29
31
|
return "/bin/bash";
|
|
30
|
-
|
|
32
|
+
const configured = shellPath ?? readWindowsShellSetting();
|
|
33
|
+
const tried = [];
|
|
34
|
+
if (configured?.trim()) {
|
|
35
|
+
const candidate = /^~[\\/]/.test(configured) ? win32.join(homedir(), configured.slice(2)) : configured;
|
|
36
|
+
tried.push(candidate);
|
|
37
|
+
try {
|
|
38
|
+
accessSync(candidate, constants.F_OK);
|
|
39
|
+
return candidate;
|
|
40
|
+
}
|
|
41
|
+
catch { /* An unavailable setting leaves standard Windows discovery enabled. */ }
|
|
42
|
+
}
|
|
43
|
+
const gitCandidates = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]]
|
|
44
|
+
.filter((directory) => Boolean(directory))
|
|
45
|
+
.map(directory => win32.join(directory, "Git", "bin", "bash.exe"));
|
|
46
|
+
for (const candidate of new Set([...gitCandidates, ...WINDOWS_BASH_CANDIDATES])) {
|
|
47
|
+
tried.push(candidate);
|
|
31
48
|
if (existsSync(candidate))
|
|
32
49
|
return candidate;
|
|
33
50
|
}
|
|
34
|
-
for (const dir of (process.env.PATH ?? "").split(";")) {
|
|
51
|
+
for (const dir of (process.env.PATH ?? process.env.Path ?? "").split(";")) {
|
|
35
52
|
const trimmed = dir.trim();
|
|
36
53
|
if (!trimmed || /(^|[\\/])(system32|windowsapps)([\\/]|$)/i.test(trimmed))
|
|
37
54
|
continue;
|
|
38
|
-
const candidate = join(trimmed, "bash.exe");
|
|
55
|
+
const candidate = win32.join(trimmed, "bash.exe");
|
|
56
|
+
tried.push(candidate);
|
|
39
57
|
if (existsSync(candidate))
|
|
40
58
|
return candidate;
|
|
41
59
|
}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
60
|
+
throw new Error("No Bash executable found for Windows Background tasks. Set Pi's shellPath in settings.json or "
|
|
61
|
+
+ "PI_BETTER_BACKGROUND_TASKS_SHELL to a working bash.exe. Searched:\n " + [...new Set(tried)].join("\n "));
|
|
62
|
+
}
|
|
63
|
+
function readWindowsShellSetting() {
|
|
64
|
+
const agentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
|
|
65
|
+
try {
|
|
66
|
+
const settings = JSON.parse(readFileSync(join(agentDir, "settings.json"), "utf8"));
|
|
67
|
+
return typeof settings?.shellPath === "string" ? settings.shellPath : undefined;
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/** Capture effective session settings before dispatching a Windows launch. */
|
|
74
|
+
export function resolveWindowsLaunchShell(pi) {
|
|
75
|
+
if (process.platform !== "win32")
|
|
76
|
+
return undefined;
|
|
77
|
+
const override = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
|
|
78
|
+
if (override)
|
|
79
|
+
return override;
|
|
80
|
+
const settings = pi.getSettings?.();
|
|
81
|
+
return resolveDefaultShell(typeof settings?.shellPath === "string" ? settings.shellPath : undefined);
|
|
45
82
|
}
|
|
46
83
|
/** How long a timed-out process group has to exit on SIGTERM before SIGKILL. */
|
|
47
84
|
const TERMINATION_GRACE_MS = 2_000;
|
|
@@ -494,7 +531,8 @@ export function commandExecution(spec) {
|
|
|
494
531
|
const [command, ...args] = spec.argv;
|
|
495
532
|
return { execPath: command, execArgs: args };
|
|
496
533
|
}
|
|
497
|
-
|
|
534
|
+
const resolved = process.platform === "win32" ? spec.resolvedWindowsShell : undefined;
|
|
535
|
+
return { execPath: resolved ?? resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command] };
|
|
498
536
|
}
|
|
499
537
|
function spawnArgs(spec, detached, stdio) {
|
|
500
538
|
const env = { ...process.env, ...spec.env };
|
|
@@ -325,13 +325,13 @@ function readText(path) {
|
|
|
325
325
|
catch (error) {
|
|
326
326
|
if (error.code === "ENOENT")
|
|
327
327
|
return { missing: true };
|
|
328
|
-
return { missing:
|
|
328
|
+
return { missing: false, error: error instanceof Error ? error.message : String(error) };
|
|
329
329
|
}
|
|
330
330
|
}
|
|
331
331
|
function readJsonRecord(path, problem) {
|
|
332
332
|
const read = readText(path);
|
|
333
|
-
if (read.
|
|
334
|
-
return { missing:
|
|
333
|
+
if (read.value === undefined)
|
|
334
|
+
return { missing: read.missing, error: read.error };
|
|
335
335
|
let parsed;
|
|
336
336
|
try {
|
|
337
337
|
parsed = JSON.parse(read.value);
|
|
@@ -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)
|
|
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)
|
|
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)
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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() {
|
|
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 : []; },
|