pi-better-background-tasks 0.18.0 → 0.19.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/README.md +4 -3
- package/package.json +1 -1
- package/runtime-client/artifacts/darwin-arm64.gz +0 -0
- package/runtime-client/artifacts/darwin-arm64.json +1 -1
- package/runtime-client/artifacts/darwin-x64.gz +0 -0
- package/runtime-client/artifacts/darwin-x64.json +1 -1
- package/runtime-client/artifacts/linux-arm64.gz +0 -0
- package/runtime-client/artifacts/linux-arm64.json +1 -1
- package/runtime-client/artifacts/linux-x64.gz +0 -0
- package/runtime-client/artifacts/linux-x64.json +1 -1
- package/runtime-client/src/runtime/client.mjs +30 -3
- package/runtime-client/src/runtime/work-client.mjs +150 -7
- package/src/adapter-contract.ts +1 -1
- package/src/goal-provider.ts +31 -16
- package/src/index.ts +6 -9
- package/src/managed-authority.ts +5 -3
- package/src/managed-client.ts +20 -7
- package/src/managed-frontend.ts +62 -17
- package/src/navigator-provider.ts +15 -5
- package/src/observed-wait-client.ts +10 -0
- package/src/observed-waits.ts +154 -30
- package/src/process-identity.ts +18 -2
- package/src/process.ts +3 -3
- package/src/registry.ts +53 -5
- package/src/runtime.ts +19 -9
- package/src/sandbox.ts +14 -11
- package/src/shared-callback-batcher.ts +11 -2
- package/src/shared-navigator-panels.ts +26 -4
- package/src/shared-navigator.ts +197 -14
- package/src/shared-operation-coordinator/assignment-observation.mjs +43 -35
- package/src/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/src/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/src/shared-operation-coordinator/src/background-requests.ts +14 -3
- package/src/shared-operation-coordinator/src/discovery.ts +5 -3
- package/src/shared-operation-coordinator/src/operations.ts +50 -2
- package/src/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/src/shared-operation-coordinator/src/rows.ts +2 -0
- package/src/shared-operation-coordinator/src/schema.ts +40 -24
- package/src/shared-operation-coordinator/src/store.ts +34 -8
- package/src/shared-operation-coordinator/src/subagent-launch.ts +24 -1
- package/src/shared-operation-coordinator/src/types.ts +5 -1
- package/src/shared-sandbox-core.ts +1 -1
- package/src/shared-work-client.mjs +150 -7
- package/src/supervisor/generated/process-identity.mjs +20 -2
- package/src/supervisor/generated/process.mjs +3 -3
- package/src/task-diagnostics.ts +1 -1
- package/src/tools.ts +41 -38
- package/src/types.ts +3 -1
- package/src/work-observation.ts +46 -19
package/src/managed-frontend.ts
CHANGED
|
@@ -4,17 +4,22 @@ import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-a
|
|
|
4
4
|
import { requestBackgroundTool } from './managed-client.js';
|
|
5
5
|
import { onBackgroundObservation } from './work-observation.js';
|
|
6
6
|
import { getCallbackBatcher } from './shared-callback-batcher.js';
|
|
7
|
-
import { registerObservedWaitClient
|
|
7
|
+
import { registerObservedWaitClient } from "./observed-wait-client.js";
|
|
8
|
+
import type { ObservedWaitHost } from "./observed-waits.js";
|
|
9
|
+
import { observeNavigatorLaunch } from './shared-navigator.ts';
|
|
8
10
|
/** Native transcript delivery and cached UI projections; no coordinator or supervisor. */
|
|
9
11
|
export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
10
12
|
let ctx: ExtensionContext | undefined, generation = 0, refresh: Promise<void> | undefined, dirty=false;
|
|
11
13
|
let rows: any[] = [], legacyRows: any[] = [], details = new Map<string, any>(), logs = new Map<string, any>();
|
|
14
|
+
const retainedTasks = new Map<string, any>();
|
|
15
|
+
const cachedTask = (id: string) => rows.find(row => row.id === id) ?? retainedTasks.get(id);
|
|
12
16
|
let adoptedScope: string | undefined;
|
|
17
|
+
let observing = false;
|
|
13
18
|
const scopeOf = (context: ExtensionContext) => JSON.stringify([context.cwd, context.sessionManager.getSessionId()]);
|
|
14
19
|
const ownership = new Map<string, { operationId: string; owner: { kind: string; sessionId: string; workspace: string } }>();
|
|
15
20
|
const adoptContext = (context: ExtensionContext) => {
|
|
16
21
|
if (adoptedScope !== undefined && adoptedScope !== scopeOf(context)) {
|
|
17
|
-
ownership.clear(); rows = []; legacyRows = []; details.clear(); logs.clear(); generation++;
|
|
22
|
+
ownership.clear(); rows = []; legacyRows = []; details.clear(); logs.clear(); retainedTasks.clear(); generation++;
|
|
18
23
|
}
|
|
19
24
|
ctx = context; adoptedScope = scopeOf(context);
|
|
20
25
|
};
|
|
@@ -26,6 +31,16 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
26
31
|
if (ownership.size > 256) ownership.delete(ownership.keys().next().value!);
|
|
27
32
|
};
|
|
28
33
|
const queued = new Set<string>(), listeners = new Set<(change: any) => void>();
|
|
34
|
+
const traceSeen = new Set<string>();
|
|
35
|
+
const trace = (stage: string, facts: Record<string, unknown> = {}) => {
|
|
36
|
+
if (process.env.PI_BG_OBSERVED_WAITS_DEBUG !== '1') return;
|
|
37
|
+
const full = JSON.stringify({ stage, sessionId: ctx?.sessionManager.getSessionId(), ...facts });
|
|
38
|
+
const line = full.length <= 4096 ? full : JSON.stringify({ stage, truncated: true });
|
|
39
|
+
if (traceSeen.has(line) || traceSeen.size >= 128) return;
|
|
40
|
+
const output = traceSeen.size === 127 ? JSON.stringify({ stage: 'capture-limit', limit: 128 }) : line;
|
|
41
|
+
traceSeen.add(line);
|
|
42
|
+
try { console.error('[background-handoff-frontend]', output); } catch { /* diagnostics never own delivery */ }
|
|
43
|
+
};
|
|
29
44
|
const active = (origin: any, branch?: string | null) => Boolean(ctx && origin.cwd === ctx.cwd && origin.sessionId === ctx.sessionManager.getSessionId()
|
|
30
45
|
&& (!branch || ctx.sessionManager.getBranch().some(entry => entry.id === branch)));
|
|
31
46
|
const request = (tool: string, params: any) => {
|
|
@@ -42,19 +57,34 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
42
57
|
dirty=false;
|
|
43
58
|
const captured = ctx, version = generation;
|
|
44
59
|
refresh = (async () => {
|
|
45
|
-
|
|
60
|
+
trace('poll-start');
|
|
61
|
+
const snapshot = await request('__background_poll', { knownActiveIds: rows.filter(row => row.active).map(row => row.id).slice(0, 200) });
|
|
62
|
+
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 })) });
|
|
46
63
|
if (version !== generation)
|
|
47
64
|
return;
|
|
48
65
|
if (snapshot.recoveryPending === true) dirty = true;
|
|
49
|
-
|
|
50
|
-
|
|
66
|
+
// A rebuilding snapshot is not evidence that visible tasks vanished.
|
|
67
|
+
if (snapshot.status !== 'rebuilding' && snapshot.status !== 'degraded') {
|
|
68
|
+
rows = snapshot.tasks ?? [];
|
|
69
|
+
// Detail remains inspectable while Navigator retains a terminal row.
|
|
70
|
+
for (const task of rows) {
|
|
71
|
+
retainedTasks.delete(task.id); retainedTasks.set(task.id, task);
|
|
72
|
+
if (retainedTasks.size > 256) retainedTasks.delete(retainedTasks.keys().next().value!);
|
|
73
|
+
}
|
|
74
|
+
legacyRows = snapshot.legacyRows ?? [];
|
|
75
|
+
}
|
|
51
76
|
notify();
|
|
52
77
|
for (const item of snapshot.deliveries ?? []) {
|
|
53
78
|
if (queued.has(item.token))
|
|
54
79
|
continue;
|
|
55
80
|
queued.add(item.token);
|
|
56
|
-
const
|
|
57
|
-
|
|
81
|
+
const facts = { taskId: item.notification.taskId, receiptId: item.receiptId };
|
|
82
|
+
const receipt = (delivered: boolean, reason?: string) => {
|
|
83
|
+
trace('handoff', { ...facts, delivered, reason: reason?.slice(0, 256) });
|
|
84
|
+
void requestBackgroundTool(pi, captured, randomUUID(), '__background_receipt', { token: item.token, delivered, reason })
|
|
85
|
+
.then(() => trace('receipt-return', facts), error => trace('receipt-error', { ...facts, error: String(error).slice(0, 256) }))
|
|
86
|
+
.finally(() => {queued.delete(item.token);if(ctx===captured)void reconcile().catch(()=>undefined);});
|
|
87
|
+
};
|
|
58
88
|
const proof = captured.sessionManager.getBranch().some((entry: any) => {
|
|
59
89
|
const message = entry.type === 'custom_message' ? entry : entry.message;
|
|
60
90
|
return item.notification.urgent ? message?.customType===item.notification.event.customType&&message.details?.urgentEventId===item.receiptId : message?.customType === 'background-completion-batch' && message.details?.completionEventIds?.includes(item.receiptId);
|
|
@@ -64,25 +94,36 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
64
94
|
continue;
|
|
65
95
|
}
|
|
66
96
|
const n = item.notification;
|
|
97
|
+
trace('queue', { ...facts, urgent: n.urgent === true, recipientActive: active(n.origin, n.branchId) });
|
|
67
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;}
|
|
68
99
|
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,
|
|
69
100
|
detailTool: 'bg_task_status', outcome: n.outcome, callback: true, receiptId: item.receiptId,
|
|
70
101
|
getSuppressionReason: () => active(n.origin, n.branchId) ? undefined : 'The originating session or branch is no longer active',
|
|
71
102
|
onDelivered: () => receipt(true), onSuppressed: (reason) => receipt(false, reason) });
|
|
72
103
|
}
|
|
73
|
-
})().
|
|
104
|
+
})().catch(error => { trace('poll-error', { error: String(error).slice(0, 256) }); throw error; })
|
|
105
|
+
.finally(() => { refresh = undefined;if(dirty&&ctx)void reconcile().catch(()=>undefined); });
|
|
74
106
|
return refresh;
|
|
75
107
|
};
|
|
108
|
+
const activate = () => {
|
|
109
|
+
if (observing || !ctx) return;
|
|
110
|
+
observing = true;
|
|
111
|
+
const version = generation;
|
|
112
|
+
void reconcile().catch(() => { if (generation === version) observing = false; });
|
|
113
|
+
};
|
|
76
114
|
const host = {
|
|
77
115
|
async reconcileNow() { await reconcile(); while (refresh) await refresh; },
|
|
78
|
-
start(context: ExtensionContext
|
|
116
|
+
start(context: ExtensionContext, restore = true) {
|
|
117
|
+
adoptContext(context); generation++; observing = false;
|
|
118
|
+
if (restore) activate();
|
|
119
|
+
},
|
|
79
120
|
noteParentContext(context: ExtensionContext) { adoptContext(context); generation++; void reconcile().catch(() => undefined); },
|
|
80
|
-
close() { ctx = undefined; adoptedScope = undefined; generation++; rows = []; legacyRows = []; details.clear(); logs.clear(); queued.clear(); ownership.clear(); },
|
|
121
|
+
close() { observing = false; ctx = undefined; adoptedScope = undefined; generation++; rows = []; legacyRows = []; details.clear(); logs.clear(); retainedTasks.clear(); queued.clear(); ownership.clear(); },
|
|
81
122
|
isParentOriginActive: active,
|
|
82
123
|
onDurableTaskChange(listener: (change: any) => void) { listeners.add(listener); return () => listeners.delete(listener); },
|
|
83
|
-
listDurableTasks(origin: any,
|
|
84
|
-
readDurableTask(origin: any, id: string) { return active(origin) ?
|
|
85
|
-
ownsDurableTask(id: string) { if (!ctx || adoptedScope !== scopeOf(ctx)) return false; return ownership.has(id) || rows.some(row => row.id === id); },
|
|
124
|
+
listDurableTasks(origin: any, _options: any = {}) { return active(origin) ? rows : []; },
|
|
125
|
+
readDurableTask(origin: any, id: string) { const task = cachedTask(id); return active(origin, task?.parentRecipient?.branchId) ? task : undefined; },
|
|
126
|
+
ownsDurableTask(id: string) { if (!ctx || adoptedScope !== scopeOf(ctx)) return false; return ownership.has(id) || rows.some(row => row.id === id && !row.readOnly); },
|
|
86
127
|
readDurableTaskLog(origin: any, id: string, lines = 40) {
|
|
87
128
|
if (!active(origin))
|
|
88
129
|
return;
|
|
@@ -104,7 +145,10 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
104
145
|
throw new Error('Native Background context unavailable');
|
|
105
146
|
adoptContext(context);
|
|
106
147
|
const capturedGeneration = generation, capturedScope = adoptedScope;
|
|
107
|
-
const
|
|
148
|
+
const launch = () => requestBackgroundTool(pi, context, id, definition.name, params, definition.parameters, signal);
|
|
149
|
+
const spawning = ['bg_task_spawn', 'bg_task_spawn_batch', 'bg_task_watch'].includes(definition.name)
|
|
150
|
+
|| definition.name === 'bg_task' && ['spawn', 'watch'].includes(params?.action);
|
|
151
|
+
const result = spawning ? await observeNavigatorLaunch(context, 'background-tasks', id, params?.name || 'Background task launch', launch) : await launch();
|
|
108
152
|
if (ctx === context && generation === capturedGeneration && adoptedScope === capturedScope) rememberOwnership(result.details?.backgroundOwnership, context);
|
|
109
153
|
await host.reconcileNow().catch(() => undefined);
|
|
110
154
|
return result;
|
|
@@ -114,10 +158,11 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
114
158
|
} });
|
|
115
159
|
registerObservedWaitClient(proxy, host as unknown as ObservedWaitHost);
|
|
116
160
|
const ui: ManagedBackgroundNavigator = {
|
|
117
|
-
|
|
161
|
+
onOpen: activate,
|
|
162
|
+
rows: () => legacyRows,
|
|
118
163
|
prepareDetail(id, options) {
|
|
119
164
|
const lines = options?.logTailLines ?? 40, key = `${id}:${lines}`;
|
|
120
|
-
const durable =
|
|
165
|
+
const durable = Boolean(cachedTask(id)), cache = durable ? logs : details;
|
|
121
166
|
const version=generation;
|
|
122
167
|
if (cache.has(key))
|
|
123
168
|
return;
|
|
@@ -125,7 +170,7 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
125
170
|
void request(durable ? '__background_log' : '__background_detail', { id, lines }).then(value => { if(version===generation){cache.set(key, value); notify();} }, () => {if(version===generation)cache.delete(key);});
|
|
126
171
|
},
|
|
127
172
|
detail(id, now, options) { return details.get(`${id}:${options?.logTailLines ?? 40}`) ?? null; },
|
|
128
|
-
close(id) { void request('__background_action', { id, action: rows.find(row => row.id === id)?.active || legacyRows.find(row => row.id === id)?.status === 'running' ? 'stop' : 'dismiss' }).then(() => reconcile()).catch(() => undefined); return { action: 'requested', providerId: 'background-tasks', id }; }
|
|
173
|
+
close(id) { if (cachedTask(id)?.readOnly) return {action: 'not-closable', providerId: 'background-tasks', id}; void request('__background_action', { id, action: rows.find(row => row.id === id)?.active || legacyRows.find(row => row.id === id)?.status === 'running' ? 'stop' : 'dismiss' }).then(() => reconcile()).catch(() => undefined); return { action: 'requested', providerId: 'background-tasks', id }; }
|
|
129
174
|
};
|
|
130
175
|
return { host, proxy, ui };
|
|
131
176
|
}
|
|
@@ -16,8 +16,9 @@ import { actionableFailures, failureLabel, readFailureState } from "./shared-fai
|
|
|
16
16
|
import { failurePath, failureView } from "./failures.js";
|
|
17
17
|
import { readLog } from "./logs.js";
|
|
18
18
|
import { listMetasForOrigin, onMetaChanged, readMeta, writeMeta } from "./registry.js";
|
|
19
|
-
import { getObservedWaitHost
|
|
20
|
-
import {
|
|
19
|
+
import { getObservedWaitHost } from "./observed-wait-client.js";
|
|
20
|
+
import type { DurableTaskProjection } from "./observed-waits.js";
|
|
21
|
+
import type { BackgroundTaskRuntime } from "./runtime.js";
|
|
21
22
|
import { formatBackgroundTaskStall, observeBackgroundTaskStall } from "./stall.js";
|
|
22
23
|
import type { BackgroundTaskCallbackOrigin, BackgroundTaskMeta, BackgroundTaskStatus } from "./types.js";
|
|
23
24
|
|
|
@@ -30,12 +31,13 @@ let durableRowCache: {
|
|
|
30
31
|
} | undefined;
|
|
31
32
|
|
|
32
33
|
export interface ManagedBackgroundNavigator {
|
|
34
|
+
onOpen?(): void;
|
|
33
35
|
rows(): BackgroundWorkRow[];
|
|
34
36
|
prepareDetail(id:string,options?:{logTailLines?:number}): void;
|
|
35
37
|
detail(id: string, now: number, options?: {logTailLines?: number}): BackgroundWorkDetail | null;
|
|
36
38
|
close(id: string): {action:string;providerId:string;id:string;status?:string};
|
|
37
39
|
}
|
|
38
|
-
export function createBackgroundTasksNavigator(runtime
|
|
40
|
+
export function createBackgroundTasksNavigator(runtime?: Pick<BackgroundTaskRuntime, "stopTask">, managed?: ManagedBackgroundNavigator) {
|
|
39
41
|
const owner = Symbol("background-tasks navigator factory");
|
|
40
42
|
let unregister: (() => void) | undefined;
|
|
41
43
|
let navigatorContext: ExtensionContext | undefined;
|
|
@@ -93,6 +95,7 @@ const provider: BackgroundWorkProvider = {
|
|
|
93
95
|
id: "background-tasks",
|
|
94
96
|
label: "Background Tasks",
|
|
95
97
|
priority: 20,
|
|
98
|
+
onOpen: managed?.onOpen,
|
|
96
99
|
visibleCount: () => {
|
|
97
100
|
const now = Date.now();
|
|
98
101
|
return (managed ? managed.rows().filter(row => row.status === "running").length : visibleMetas(now).filter((meta) => meta.status === "running").length)
|
|
@@ -110,8 +113,10 @@ const provider: BackgroundWorkProvider = {
|
|
|
110
113
|
},
|
|
111
114
|
armCloseLabel: (row) => row.status === "running" || row.status === "starting" ? "x again to stop" : "x again to dismiss",
|
|
112
115
|
close: (id) => {
|
|
116
|
+
if (durableTask(id)?.readOnly) return {action: "not-closable", providerId: "background-tasks", id};
|
|
113
117
|
if(managed)return managed.close(id);
|
|
114
118
|
const durable = durableTask(id);
|
|
119
|
+
if (durable?.readOnly) return {action: "not-closable", providerId: "background-tasks", id};
|
|
115
120
|
if (durable) {
|
|
116
121
|
const host = navigatorHost();
|
|
117
122
|
const origin = activeNavigatorOrigin;
|
|
@@ -128,7 +133,9 @@ const provider: BackgroundWorkProvider = {
|
|
|
128
133
|
const meta = readMeta(id);
|
|
129
134
|
if (!meta) return { action: "missing", providerId: "background-tasks", id };
|
|
130
135
|
if (meta.status === "running") {
|
|
131
|
-
|
|
136
|
+
const pi = piRef as ExtensionAPI;
|
|
137
|
+
if (runtime) void runtime.stopTask(pi, id);
|
|
138
|
+
else void import("./runtime.js").then(({ stopTask }) => stopTask(pi, id));
|
|
132
139
|
return { action: "stopped", providerId: "background-tasks", id, status: "stopping" };
|
|
133
140
|
}
|
|
134
141
|
meta.dismissedAt = Date.now();
|
|
@@ -192,6 +199,8 @@ function rowFromDurable(task: DurableTaskProjection, now: number): BackgroundWor
|
|
|
192
199
|
return {
|
|
193
200
|
providerId: "background-tasks",
|
|
194
201
|
id: task.id,
|
|
202
|
+
parentAgentId: task.parentAgentId,
|
|
203
|
+
readOnly: task.readOnly,
|
|
195
204
|
name: task.name,
|
|
196
205
|
status: task.status,
|
|
197
206
|
statusTone: toneForDurableStatus(task.status),
|
|
@@ -217,6 +226,7 @@ function detailFromDurable(task: DurableTaskProjection, options?: { logTailLines
|
|
|
217
226
|
const metadata = [
|
|
218
227
|
{ label: "provider", value: "Background Tasks (durable)" },
|
|
219
228
|
{ label: "kind", value: task.kind },
|
|
229
|
+
...(task.parentAgentId ? [{label: "agent", value: task.parentAgentId}] : []),
|
|
220
230
|
{ label: "operation", value: task.operationId },
|
|
221
231
|
{ label: "status", value: `${task.status}${task.terminalOutcome ? ` (${task.terminalOutcome})` : ""}` },
|
|
222
232
|
{ label: "started", value: new Date(task.startedAt).toISOString() },
|
|
@@ -255,7 +265,7 @@ function detailFromDurable(task: DurableTaskProjection, options?: { logTailLines
|
|
|
255
265
|
label: log?.truncated ? "log tail" : "log",
|
|
256
266
|
text: evidenceText,
|
|
257
267
|
},
|
|
258
|
-
footerActions: [task.active ? "x stop" : "x dismiss"],
|
|
268
|
+
footerActions: task.readOnly ? ["Managed by owning agent"] : [task.active ? "x stop" : "x dismiss"],
|
|
259
269
|
};
|
|
260
270
|
}
|
|
261
271
|
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { ObservedWaitHost } from "./observed-waits.js";
|
|
3
|
+
|
|
4
|
+
const hosts = new WeakMap<object, ObservedWaitHost>();
|
|
5
|
+
|
|
6
|
+
export function registerObservedWaitClient(pi: ExtensionAPI, host: ObservedWaitHost): void { hosts.set(pi as object, host); }
|
|
7
|
+
|
|
8
|
+
export function getObservedWaitHost(pi: unknown): ObservedWaitHost | undefined {
|
|
9
|
+
return pi && typeof pi === "object" ? hosts.get(pi as object) : undefined;
|
|
10
|
+
}
|