pi-better-background-tasks 0.18.0 → 0.20.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 +25 -13
- 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/root.mjs +5 -2
- 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 +25 -9
- package/src/managed-authority.ts +5 -3
- package/src/managed-client.ts +20 -7
- package/src/managed-frontend.ts +135 -19
- package/src/navigator-provider.ts +19 -5
- package/src/observed-wait-client.ts +10 -0
- package/src/observed-waits.ts +321 -53
- package/src/process-identity.ts +18 -2
- package/src/process.ts +48 -14
- package/src/registry.ts +53 -5
- package/src/review-settings.ts +18 -0
- package/src/runtime.ts +27 -82
- 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 +244 -40
- 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/outbox.ts +9 -0
- 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 +40 -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/stall.ts +7 -4
- package/src/supervised-progress.ts +43 -0
- package/src/supervisor/README.md +1 -4
- package/src/supervisor/emit-runner.mjs +1 -0
- package/src/supervisor/generated/process-identity.mjs +20 -2
- package/src/supervisor/generated/process.mjs +52 -14
- package/src/supervisor/generated/runner.mjs +47 -4
- package/src/supervisor/generated/store.mjs +3 -3
- package/src/supervisor/generated/watch-fingerprint.mjs +69 -0
- package/src/supervisor/runner.ts +38 -3
- package/src/supervisor/store.ts +3 -3
- package/src/supervisor/supervisor.ts +6 -3
- package/src/task-diagnostics.ts +1 -1
- package/src/tools.ts +67 -54
- package/src/types.ts +7 -3
- package/src/watch-fingerprint.ts +70 -0
- package/src/work-observation.ts +46 -19
package/src/managed-client.ts
CHANGED
|
@@ -3,25 +3,36 @@ import { lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, w
|
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { getAgentDir, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
5
5
|
import { backgroundDigest } from './managed-authority.js';
|
|
6
|
-
import { readProcessStartTokenFresh } from './process-identity.js';
|
|
6
|
+
import { readAdmissionStartToken, readProcessStartTokenFresh } from './process-identity.js';
|
|
7
7
|
import { currentForegroundSandboxPolicy, FOREGROUND_SANDBOX_POLICY_CHANNEL } from './sandbox.js';
|
|
8
|
-
import { backgroundObservation } from './work-observation.js';
|
|
8
|
+
import { backgroundListNeedsHistory, backgroundObservation } from './work-observation.js';
|
|
9
9
|
/** Native host proof carries scope and captured policy, never a transcript or module path. */
|
|
10
10
|
export async function requestBackgroundTool(pi: ExtensionAPI, ctx: ExtensionContext, key: string, tool: string, params: unknown, parameters?: unknown, signal?: AbortSignal): Promise<any> {
|
|
11
11
|
if (signal?.aborted)
|
|
12
12
|
throw new Error('Background request cancelled before admission');
|
|
13
|
-
|
|
13
|
+
const input = params && typeof params === 'object' ? params as Record<string, unknown> : {};
|
|
14
|
+
const list = tool === 'bg_task_list' || (tool === 'bg_task' && input.action === 'list');
|
|
15
|
+
if (list && backgroundListNeedsHistory(input)) {
|
|
16
|
+
// The root history index is shared. Wait on its read plane before acquiring
|
|
17
|
+
// a grant or entering the serialized tool queue, even for an all-session list.
|
|
18
|
+
const snapshot = await backgroundObservation(pi, ctx, true, false, { limit: 1 }, { timeoutMs: 60000, signal });
|
|
19
|
+
if (snapshot.status !== 'ready')
|
|
20
|
+
throw new Error(snapshot.reason ?? `Background history is ${snapshot.status}`);
|
|
21
|
+
} else {
|
|
22
|
+
await backgroundObservation(pi, ctx);
|
|
23
|
+
}
|
|
24
|
+
signal?.throwIfAborted();
|
|
14
25
|
const root = realpathSync(getAgentDir()), registration = JSON.parse(readFileSync(join(root, 'server-registration-v1.json'), 'utf8'));
|
|
15
26
|
if (registration.version !== 1 || registration.agentDir !== root)
|
|
16
27
|
throw new Error('Invalid runtime registration');
|
|
17
28
|
const module = new URL('./shared-work-client.mjs', import.meta.url).href;
|
|
18
|
-
const {
|
|
29
|
+
const { connectWorkClient } = await import(module);
|
|
19
30
|
const directory = join(root, 'background-tool-admission');
|
|
20
31
|
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
21
32
|
const stat = lstatSync(directory);
|
|
22
33
|
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077))
|
|
23
34
|
throw new Error('Unsafe Background admission directory');
|
|
24
|
-
const client =
|
|
35
|
+
const client = await connectWorkClient(join(registration.serverDir, 'pi-server.sock'), root, ['runtime-background-execution-v1'], { signal });
|
|
25
36
|
const id = randomUUID(), secret = randomBytes(32).toString('hex'), path = join(directory, `${id}.json`);
|
|
26
37
|
let off: unknown;
|
|
27
38
|
const abort = () => client.close();
|
|
@@ -33,9 +44,11 @@ export async function requestBackgroundTool(pi: ExtensionAPI, ctx: ExtensionCont
|
|
|
33
44
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
34
45
|
if (!sessionId)
|
|
35
46
|
throw new Error('Background tools require a native session identity');
|
|
36
|
-
const
|
|
47
|
+
const version = hello.capabilities?.includes("runtime-background-admission-v2") ? 2 : 1;
|
|
48
|
+
const start = version === 2 ? readAdmissionStartToken(process.pid) : readProcessStartTokenFresh(process.pid);
|
|
49
|
+
const record = { version, id, secretHash: createHash('sha256').update(secret).digest('hex'), instanceId: hello.instanceId,
|
|
37
50
|
owner: { kind: 'parent-session', sessionId, workspace: realpathSync(ctx.cwd) }, branchIds, projectTrusted: ctx.isProjectTrusted(),
|
|
38
|
-
pid: process.pid, start
|
|
51
|
+
pid: process.pid, start, key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundDigest(parameters), policy };
|
|
39
52
|
const staged = `${path}.tmp`;
|
|
40
53
|
writeFileSync(staged, JSON.stringify(record), { flag: 'wx', mode: 0o600 });
|
|
41
54
|
renameSync(staged, path);
|
package/src/managed-frontend.ts
CHANGED
|
@@ -4,17 +4,24 @@ 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
|
+
let pendingAttention = new Set<string>();
|
|
15
|
+
const retainedTasks = new Map<string, any>();
|
|
16
|
+
const cachedTask = (id: string) => rows.find(row => row.id === id) ?? retainedTasks.get(id);
|
|
12
17
|
let adoptedScope: string | undefined;
|
|
18
|
+
let observing = false;
|
|
13
19
|
const scopeOf = (context: ExtensionContext) => JSON.stringify([context.cwd, context.sessionManager.getSessionId()]);
|
|
14
20
|
const ownership = new Map<string, { operationId: string; owner: { kind: string; sessionId: string; workspace: string } }>();
|
|
15
21
|
const adoptContext = (context: ExtensionContext) => {
|
|
16
22
|
if (adoptedScope !== undefined && adoptedScope !== scopeOf(context)) {
|
|
17
|
-
ownership.clear(); rows = []; legacyRows = []; details.clear(); logs.clear(); generation++;
|
|
23
|
+
ownership.clear(); rows = []; legacyRows = []; details.clear(); logs.clear(); retainedTasks.clear(); generation++;
|
|
24
|
+
pendingAttention.clear();
|
|
18
25
|
}
|
|
19
26
|
ctx = context; adoptedScope = scopeOf(context);
|
|
20
27
|
};
|
|
@@ -26,6 +33,16 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
26
33
|
if (ownership.size > 256) ownership.delete(ownership.keys().next().value!);
|
|
27
34
|
};
|
|
28
35
|
const queued = new Set<string>(), listeners = new Set<(change: any) => void>();
|
|
36
|
+
const traceSeen = new Set<string>();
|
|
37
|
+
const trace = (stage: string, facts: Record<string, unknown> = {}) => {
|
|
38
|
+
if (process.env.PI_BG_OBSERVED_WAITS_DEBUG !== '1') return;
|
|
39
|
+
const full = JSON.stringify({ stage, sessionId: ctx?.sessionManager.getSessionId(), ...facts });
|
|
40
|
+
const line = full.length <= 4096 ? full : JSON.stringify({ stage, truncated: true });
|
|
41
|
+
if (traceSeen.has(line) || traceSeen.size >= 128) return;
|
|
42
|
+
const output = traceSeen.size === 127 ? JSON.stringify({ stage: 'capture-limit', limit: 128 }) : line;
|
|
43
|
+
traceSeen.add(line);
|
|
44
|
+
try { console.error('[background-handoff-frontend]', output); } catch { /* diagnostics never own delivery */ }
|
|
45
|
+
};
|
|
29
46
|
const active = (origin: any, branch?: string | null) => Boolean(ctx && origin.cwd === ctx.cwd && origin.sessionId === ctx.sessionManager.getSessionId()
|
|
30
47
|
&& (!branch || ctx.sessionManager.getBranch().some(entry => entry.id === branch)));
|
|
31
48
|
const request = (tool: string, params: any) => {
|
|
@@ -35,6 +52,30 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
35
52
|
};
|
|
36
53
|
const notify = () => { for (const listener of listeners)
|
|
37
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
|
+
};
|
|
38
79
|
const reconcile = () => {
|
|
39
80
|
if (!ctx)
|
|
40
81
|
return Promise.resolve();
|
|
@@ -42,19 +83,47 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
42
83
|
dirty=false;
|
|
43
84
|
const captured = ctx, version = generation;
|
|
44
85
|
refresh = (async () => {
|
|
45
|
-
const
|
|
86
|
+
const rechecking = pendingAttention.size && captured.isIdle() ? pendingAttention : undefined;
|
|
87
|
+
trace('poll-start');
|
|
88
|
+
const snapshot = await request('__background_poll', { knownActiveIds: rows.filter(row => row.active).map(row => row.id).slice(0, 200) });
|
|
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 })) });
|
|
46
90
|
if (version !== generation)
|
|
47
91
|
return;
|
|
92
|
+
if (Number.isFinite(snapshot.retryAfterMs)) scheduleHandoffPoll(snapshot.retryAfterMs);
|
|
48
93
|
if (snapshot.recoveryPending === true) dirty = true;
|
|
49
|
-
|
|
50
|
-
|
|
94
|
+
// A rebuilding snapshot is not evidence that visible tasks vanished.
|
|
95
|
+
if (snapshot.status !== 'rebuilding' && snapshot.status !== 'degraded') {
|
|
96
|
+
// Older servers include compact callback pointers in the task list.
|
|
97
|
+
rows = (snapshot.tasks ?? []).filter((task: any) => !task.callbackPending);
|
|
98
|
+
// Detail remains inspectable while Navigator retains a terminal row.
|
|
99
|
+
for (const task of rows) {
|
|
100
|
+
retainedTasks.delete(task.id); retainedTasks.set(task.id, task);
|
|
101
|
+
if (retainedTasks.size > 256) retainedTasks.delete(retainedTasks.keys().next().value!);
|
|
102
|
+
}
|
|
103
|
+
legacyRows = snapshot.legacyRows ?? [];
|
|
104
|
+
}
|
|
51
105
|
notify();
|
|
106
|
+
const deferredAttention = new Set<string>();
|
|
52
107
|
for (const item of snapshot.deliveries ?? []) {
|
|
53
108
|
if (queued.has(item.token))
|
|
54
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
|
+
}
|
|
55
119
|
queued.add(item.token);
|
|
56
|
-
const
|
|
57
|
-
|
|
120
|
+
const facts = { taskId: item.notification.taskId, receiptId: item.receiptId };
|
|
121
|
+
const receipt = (delivered: boolean, reason?: string) => {
|
|
122
|
+
trace('handoff', { ...facts, delivered, reason: reason?.slice(0, 256) });
|
|
123
|
+
void requestBackgroundTool(pi, captured, randomUUID(), '__background_receipt', { token: item.token, delivered, reason })
|
|
124
|
+
.then(() => trace('receipt-return', facts), error => trace('receipt-error', { ...facts, error: String(error).slice(0, 256) }))
|
|
125
|
+
.finally(() => {queued.delete(item.token);if(ctx===captured)void reconcile().catch(()=>undefined);});
|
|
126
|
+
};
|
|
58
127
|
const proof = captured.sessionManager.getBranch().some((entry: any) => {
|
|
59
128
|
const message = entry.type === 'custom_message' ? entry : entry.message;
|
|
60
129
|
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);
|
|
@@ -63,26 +132,69 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
63
132
|
receipt(true);
|
|
64
133
|
continue;
|
|
65
134
|
}
|
|
66
|
-
|
|
67
|
-
if(n.urgent)
|
|
135
|
+
trace('queue', { ...facts, urgent: n.urgent === true, recipientActive: active(n.origin, n.branchId) });
|
|
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
|
+
}
|
|
68
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,
|
|
69
145
|
detailTool: 'bg_task_status', outcome: n.outcome, callback: true, receiptId: item.receiptId,
|
|
70
146
|
getSuppressionReason: () => active(n.origin, n.branchId) ? undefined : 'The originating session or branch is no longer active',
|
|
71
147
|
onDelivered: () => receipt(true), onSuppressed: (reason) => receipt(false, reason) });
|
|
72
148
|
}
|
|
73
|
-
|
|
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
|
+
})
|
|
159
|
+
.finally(() => { refresh = undefined;if(dirty&&ctx)void reconcile().catch(()=>undefined); });
|
|
74
160
|
return refresh;
|
|
75
161
|
};
|
|
162
|
+
const activate = () => {
|
|
163
|
+
if (observing || !ctx) return;
|
|
164
|
+
observing = true;
|
|
165
|
+
const version = generation;
|
|
166
|
+
void reconcile().catch(() => { if (generation === version) observing = false; });
|
|
167
|
+
};
|
|
76
168
|
const host = {
|
|
77
169
|
async reconcileNow() { await reconcile(); while (refresh) await refresh; },
|
|
78
|
-
start(context: ExtensionContext
|
|
170
|
+
start(context: ExtensionContext, restore = true) {
|
|
171
|
+
adoptContext(context); generation++; observing = false;
|
|
172
|
+
if (restore) activate();
|
|
173
|
+
},
|
|
79
174
|
noteParentContext(context: ExtensionContext) { adoptContext(context); generation++; void reconcile().catch(() => undefined); },
|
|
80
|
-
close() {
|
|
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
|
+
},
|
|
81
193
|
isParentOriginActive: active,
|
|
82
194
|
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); },
|
|
195
|
+
listDurableTasks(origin: any, _options: any = {}) { return active(origin) ? rows : []; },
|
|
196
|
+
readDurableTask(origin: any, id: string) { const task = cachedTask(id); return active(origin, task?.parentRecipient?.branchId) ? task : undefined; },
|
|
197
|
+
ownsDurableTask(id: string) { if (!ctx || adoptedScope !== scopeOf(ctx)) return false; return ownership.has(id) || rows.some(row => row.id === id && !row.readOnly); },
|
|
86
198
|
readDurableTaskLog(origin: any, id: string, lines = 40) {
|
|
87
199
|
if (!active(origin))
|
|
88
200
|
return;
|
|
@@ -104,7 +216,10 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
104
216
|
throw new Error('Native Background context unavailable');
|
|
105
217
|
adoptContext(context);
|
|
106
218
|
const capturedGeneration = generation, capturedScope = adoptedScope;
|
|
107
|
-
const
|
|
219
|
+
const launch = () => requestBackgroundTool(pi, context, id, definition.name, params, definition.parameters, signal);
|
|
220
|
+
const spawning = ['bg_task_spawn', 'bg_task_spawn_batch', 'bg_task_watch'].includes(definition.name)
|
|
221
|
+
|| definition.name === 'bg_task' && ['spawn', 'watch'].includes(params?.action);
|
|
222
|
+
const result = spawning ? await observeNavigatorLaunch(context, 'background-tasks', id, params?.name || 'Background task launch', launch) : await launch();
|
|
108
223
|
if (ctx === context && generation === capturedGeneration && adoptedScope === capturedScope) rememberOwnership(result.details?.backgroundOwnership, context);
|
|
109
224
|
await host.reconcileNow().catch(() => undefined);
|
|
110
225
|
return result;
|
|
@@ -114,10 +229,11 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
114
229
|
} });
|
|
115
230
|
registerObservedWaitClient(proxy, host as unknown as ObservedWaitHost);
|
|
116
231
|
const ui: ManagedBackgroundNavigator = {
|
|
117
|
-
|
|
232
|
+
onOpen: activate,
|
|
233
|
+
rows: () => legacyRows,
|
|
118
234
|
prepareDetail(id, options) {
|
|
119
235
|
const lines = options?.logTailLines ?? 40, key = `${id}:${lines}`;
|
|
120
|
-
const durable =
|
|
236
|
+
const durable = Boolean(cachedTask(id)), cache = durable ? logs : details;
|
|
121
237
|
const version=generation;
|
|
122
238
|
if (cache.has(key))
|
|
123
239
|
return;
|
|
@@ -125,7 +241,7 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
125
241
|
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
242
|
},
|
|
127
243
|
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 }; }
|
|
244
|
+
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
245
|
};
|
|
130
246
|
return { host, proxy, ui };
|
|
131
247
|
}
|
|
@@ -16,8 +16,10 @@ 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 { describeSupervisedProgress } from "./supervised-progress.js";
|
|
21
|
+
import type { DurableTaskProjection } from "./observed-waits.js";
|
|
22
|
+
import type { BackgroundTaskRuntime } from "./runtime.js";
|
|
21
23
|
import { formatBackgroundTaskStall, observeBackgroundTaskStall } from "./stall.js";
|
|
22
24
|
import type { BackgroundTaskCallbackOrigin, BackgroundTaskMeta, BackgroundTaskStatus } from "./types.js";
|
|
23
25
|
|
|
@@ -30,12 +32,13 @@ let durableRowCache: {
|
|
|
30
32
|
} | undefined;
|
|
31
33
|
|
|
32
34
|
export interface ManagedBackgroundNavigator {
|
|
35
|
+
onOpen?(): void;
|
|
33
36
|
rows(): BackgroundWorkRow[];
|
|
34
37
|
prepareDetail(id:string,options?:{logTailLines?:number}): void;
|
|
35
38
|
detail(id: string, now: number, options?: {logTailLines?: number}): BackgroundWorkDetail | null;
|
|
36
39
|
close(id: string): {action:string;providerId:string;id:string;status?:string};
|
|
37
40
|
}
|
|
38
|
-
export function createBackgroundTasksNavigator(runtime
|
|
41
|
+
export function createBackgroundTasksNavigator(runtime?: Pick<BackgroundTaskRuntime, "stopTask">, managed?: ManagedBackgroundNavigator) {
|
|
39
42
|
const owner = Symbol("background-tasks navigator factory");
|
|
40
43
|
let unregister: (() => void) | undefined;
|
|
41
44
|
let navigatorContext: ExtensionContext | undefined;
|
|
@@ -93,6 +96,7 @@ const provider: BackgroundWorkProvider = {
|
|
|
93
96
|
id: "background-tasks",
|
|
94
97
|
label: "Background Tasks",
|
|
95
98
|
priority: 20,
|
|
99
|
+
onOpen: managed?.onOpen,
|
|
96
100
|
visibleCount: () => {
|
|
97
101
|
const now = Date.now();
|
|
98
102
|
return (managed ? managed.rows().filter(row => row.status === "running").length : visibleMetas(now).filter((meta) => meta.status === "running").length)
|
|
@@ -110,8 +114,10 @@ const provider: BackgroundWorkProvider = {
|
|
|
110
114
|
},
|
|
111
115
|
armCloseLabel: (row) => row.status === "running" || row.status === "starting" ? "x again to stop" : "x again to dismiss",
|
|
112
116
|
close: (id) => {
|
|
117
|
+
if (durableTask(id)?.readOnly) return {action: "not-closable", providerId: "background-tasks", id};
|
|
113
118
|
if(managed)return managed.close(id);
|
|
114
119
|
const durable = durableTask(id);
|
|
120
|
+
if (durable?.readOnly) return {action: "not-closable", providerId: "background-tasks", id};
|
|
115
121
|
if (durable) {
|
|
116
122
|
const host = navigatorHost();
|
|
117
123
|
const origin = activeNavigatorOrigin;
|
|
@@ -128,7 +134,9 @@ const provider: BackgroundWorkProvider = {
|
|
|
128
134
|
const meta = readMeta(id);
|
|
129
135
|
if (!meta) return { action: "missing", providerId: "background-tasks", id };
|
|
130
136
|
if (meta.status === "running") {
|
|
131
|
-
|
|
137
|
+
const pi = piRef as ExtensionAPI;
|
|
138
|
+
if (runtime) void runtime.stopTask(pi, id);
|
|
139
|
+
else void import("./runtime.js").then(({ stopTask }) => stopTask(pi, id));
|
|
132
140
|
return { action: "stopped", providerId: "background-tasks", id, status: "stopping" };
|
|
133
141
|
}
|
|
134
142
|
meta.dismissedAt = Date.now();
|
|
@@ -184,6 +192,8 @@ function rowFromDurable(task: DurableTaskProjection, now: number): BackgroundWor
|
|
|
184
192
|
const command = durableCommandLabel(task);
|
|
185
193
|
const elapsed = formatDuration((task.endedAt ?? now) - task.startedAt);
|
|
186
194
|
const facts: string[] = [];
|
|
195
|
+
const progress = task.progress && describeSupervisedProgress(task.progress, now);
|
|
196
|
+
if (progress) facts.push(progress);
|
|
187
197
|
if (task.attention && task.reason) facts.push(task.reason);
|
|
188
198
|
else if (task.attention) facts.push(task.status);
|
|
189
199
|
if (task.kind === "watch" && task.intervalSeconds) facts.push(`every ${formatDuration(task.intervalSeconds * 1000)}`);
|
|
@@ -192,6 +202,8 @@ function rowFromDurable(task: DurableTaskProjection, now: number): BackgroundWor
|
|
|
192
202
|
return {
|
|
193
203
|
providerId: "background-tasks",
|
|
194
204
|
id: task.id,
|
|
205
|
+
parentAgentId: task.parentAgentId,
|
|
206
|
+
readOnly: task.readOnly,
|
|
195
207
|
name: task.name,
|
|
196
208
|
status: task.status,
|
|
197
209
|
statusTone: toneForDurableStatus(task.status),
|
|
@@ -217,7 +229,9 @@ function detailFromDurable(task: DurableTaskProjection, options?: { logTailLines
|
|
|
217
229
|
const metadata = [
|
|
218
230
|
{ label: "provider", value: "Background Tasks (durable)" },
|
|
219
231
|
{ label: "kind", value: task.kind },
|
|
232
|
+
...(task.parentAgentId ? [{label: "agent", value: task.parentAgentId}] : []),
|
|
220
233
|
{ label: "operation", value: task.operationId },
|
|
234
|
+
...(task.progress ? [{ label: "last progress", value: new Date(task.progress.observedAt).toISOString() }] : []),
|
|
221
235
|
{ label: "status", value: `${task.status}${task.terminalOutcome ? ` (${task.terminalOutcome})` : ""}` },
|
|
222
236
|
{ label: "started", value: new Date(task.startedAt).toISOString() },
|
|
223
237
|
...(task.endedAt !== undefined ? [{ label: "ended", value: new Date(task.endedAt).toISOString() }] : []),
|
|
@@ -255,7 +269,7 @@ function detailFromDurable(task: DurableTaskProjection, options?: { logTailLines
|
|
|
255
269
|
label: log?.truncated ? "log tail" : "log",
|
|
256
270
|
text: evidenceText,
|
|
257
271
|
},
|
|
258
|
-
footerActions: [task.active ? "x stop" : "x dismiss"],
|
|
272
|
+
footerActions: task.readOnly ? ["Managed by owning agent"] : [task.active ? "x stop" : "x dismiss"],
|
|
259
273
|
};
|
|
260
274
|
}
|
|
261
275
|
|
|
@@ -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
|
+
}
|