pi-better-background-tasks 0.17.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 +4 -2
- 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/failures.ts +4 -2
- package/src/goal-provider.ts +31 -16
- package/src/index.ts +9 -37
- package/src/managed-authority.ts +30 -0
- package/src/managed-client.ts +73 -0
- package/src/managed-frontend.ts +176 -0
- package/src/navigator-provider.ts +28 -10
- package/src/observed-wait-client.ts +10 -0
- package/src/observed-waits.ts +268 -62
- package/src/output.ts +12 -0
- package/src/process-identity.ts +18 -2
- package/src/process.ts +3 -3
- package/src/registry.ts +71 -6
- package/src/runtime.ts +26 -10
- package/src/sandbox.ts +21 -11
- package/src/shared-callback-batcher.ts +15 -3
- package/src/shared-failure-observations.ts +3 -0
- package/src/shared-navigator-panels.ts +26 -4
- package/src/shared-navigator.ts +220 -19
- package/src/shared-operation-coordinator/assignment-observation.mjs +71 -33
- package/src/shared-operation-coordinator/index.ts +2 -0
- 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-parent-callbacks.ts +68 -0
- package/src/shared-operation-coordinator/src/background-requests.ts +90 -0
- 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 +71 -24
- package/src/shared-operation-coordinator/src/store.ts +50 -6
- package/src/shared-operation-coordinator/src/subagent-launch.ts +142 -0
- package/src/shared-operation-coordinator/src/types.ts +5 -1
- package/src/shared-operation-coordinator/src/upgrade.ts +22 -0
- 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 +60 -41
- package/src/types.ts +3 -1
- package/src/work-observation.ts +46 -19
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
2
|
+
import { lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { getAgentDir, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
5
|
+
import { backgroundDigest } from './managed-authority.js';
|
|
6
|
+
import { readAdmissionStartToken, readProcessStartTokenFresh } from './process-identity.js';
|
|
7
|
+
import { currentForegroundSandboxPolicy, FOREGROUND_SANDBOX_POLICY_CHANNEL } from './sandbox.js';
|
|
8
|
+
import { backgroundListNeedsHistory, backgroundObservation } from './work-observation.js';
|
|
9
|
+
/** Native host proof carries scope and captured policy, never a transcript or module path. */
|
|
10
|
+
export async function requestBackgroundTool(pi: ExtensionAPI, ctx: ExtensionContext, key: string, tool: string, params: unknown, parameters?: unknown, signal?: AbortSignal): Promise<any> {
|
|
11
|
+
if (signal?.aborted)
|
|
12
|
+
throw new Error('Background request cancelled before admission');
|
|
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();
|
|
25
|
+
const root = realpathSync(getAgentDir()), registration = JSON.parse(readFileSync(join(root, 'server-registration-v1.json'), 'utf8'));
|
|
26
|
+
if (registration.version !== 1 || registration.agentDir !== root)
|
|
27
|
+
throw new Error('Invalid runtime registration');
|
|
28
|
+
const module = new URL('./shared-work-client.mjs', import.meta.url).href;
|
|
29
|
+
const { connectWorkClient } = await import(module);
|
|
30
|
+
const directory = join(root, 'background-tool-admission');
|
|
31
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
32
|
+
const stat = lstatSync(directory);
|
|
33
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077))
|
|
34
|
+
throw new Error('Unsafe Background admission directory');
|
|
35
|
+
const client = await connectWorkClient(join(registration.serverDir, 'pi-server.sock'), root, ['runtime-background-execution-v1'], { signal });
|
|
36
|
+
const id = randomUUID(), secret = randomBytes(32).toString('hex'), path = join(directory, `${id}.json`);
|
|
37
|
+
let off: unknown;
|
|
38
|
+
const abort = () => client.close();
|
|
39
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
40
|
+
try {
|
|
41
|
+
const hello = await client.ready;
|
|
42
|
+
const policy = currentForegroundSandboxPolicy(pi);
|
|
43
|
+
const branchIds = ctx.sessionManager.getBranch().map(entry => entry.id).filter((value): value is string => typeof value === 'string');
|
|
44
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
45
|
+
if (!sessionId)
|
|
46
|
+
throw new Error('Background tools require a native session identity');
|
|
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,
|
|
50
|
+
owner: { kind: 'parent-session', sessionId, workspace: realpathSync(ctx.cwd) }, branchIds, projectTrusted: ctx.isProjectTrusted(),
|
|
51
|
+
pid: process.pid, start, key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundDigest(parameters), policy };
|
|
52
|
+
const staged = `${path}.tmp`;
|
|
53
|
+
writeFileSync(staged, JSON.stringify(record), { flag: 'wx', mode: 0o600 });
|
|
54
|
+
renameSync(staged, path);
|
|
55
|
+
let checking = false;
|
|
56
|
+
off = pi.events.on(FOREGROUND_SANDBOX_POLICY_CHANNEL, () => { if (checking)
|
|
57
|
+
return; checking = true; try {
|
|
58
|
+
if (backgroundDigest(currentForegroundSandboxPolicy(pi) ?? null) !== backgroundDigest(policy ?? null))
|
|
59
|
+
rmSync(path, { force: true });
|
|
60
|
+
}
|
|
61
|
+
finally {
|
|
62
|
+
checking = false;
|
|
63
|
+
} });
|
|
64
|
+
return await client.request('runtime_background_tool', { authority: { id, secret } });
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
if (typeof off === 'function')
|
|
68
|
+
off();
|
|
69
|
+
signal?.removeEventListener('abort', abort);
|
|
70
|
+
client.close();
|
|
71
|
+
rmSync(path, { force: true });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import type { ManagedBackgroundNavigator } from './navigator-provider.js';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
4
|
+
import { requestBackgroundTool } from './managed-client.js';
|
|
5
|
+
import { onBackgroundObservation } from './work-observation.js';
|
|
6
|
+
import { getCallbackBatcher } from './shared-callback-batcher.js';
|
|
7
|
+
import { registerObservedWaitClient } from "./observed-wait-client.js";
|
|
8
|
+
import type { ObservedWaitHost } from "./observed-waits.js";
|
|
9
|
+
import { observeNavigatorLaunch } from './shared-navigator.ts';
|
|
10
|
+
/** Native transcript delivery and cached UI projections; no coordinator or supervisor. */
|
|
11
|
+
export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
12
|
+
let ctx: ExtensionContext | undefined, generation = 0, refresh: Promise<void> | undefined, dirty=false;
|
|
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);
|
|
16
|
+
let adoptedScope: string | undefined;
|
|
17
|
+
let observing = false;
|
|
18
|
+
const scopeOf = (context: ExtensionContext) => JSON.stringify([context.cwd, context.sessionManager.getSessionId()]);
|
|
19
|
+
const ownership = new Map<string, { operationId: string; owner: { kind: string; sessionId: string; workspace: string } }>();
|
|
20
|
+
const adoptContext = (context: ExtensionContext) => {
|
|
21
|
+
if (adoptedScope !== undefined && adoptedScope !== scopeOf(context)) {
|
|
22
|
+
ownership.clear(); rows = []; legacyRows = []; details.clear(); logs.clear(); retainedTasks.clear(); generation++;
|
|
23
|
+
}
|
|
24
|
+
ctx = context; adoptedScope = scopeOf(context);
|
|
25
|
+
};
|
|
26
|
+
const rememberOwnership = (proof: any, context: ExtensionContext) => {
|
|
27
|
+
if (!proof || typeof proof.id !== 'string' || typeof proof.operationId !== 'string'
|
|
28
|
+
|| proof.owner?.kind !== 'parent-session' || proof.owner.workspace !== context.cwd
|
|
29
|
+
|| proof.owner.sessionId !== context.sessionManager.getSessionId()) return;
|
|
30
|
+
ownership.delete(proof.id); ownership.set(proof.id, proof);
|
|
31
|
+
if (ownership.size > 256) ownership.delete(ownership.keys().next().value!);
|
|
32
|
+
};
|
|
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
|
+
};
|
|
44
|
+
const active = (origin: any, branch?: string | null) => Boolean(ctx && origin.cwd === ctx.cwd && origin.sessionId === ctx.sessionManager.getSessionId()
|
|
45
|
+
&& (!branch || ctx.sessionManager.getBranch().some(entry => entry.id === branch)));
|
|
46
|
+
const request = (tool: string, params: any) => {
|
|
47
|
+
if (!ctx)
|
|
48
|
+
throw new Error('Native Background session unavailable');
|
|
49
|
+
return requestBackgroundTool(pi, ctx, randomUUID(), tool, params);
|
|
50
|
+
};
|
|
51
|
+
const notify = () => { for (const listener of listeners)
|
|
52
|
+
listener({ workspace: ctx?.cwd, sessionId: ctx?.sessionManager.getSessionId() }); };
|
|
53
|
+
const reconcile = () => {
|
|
54
|
+
if (!ctx)
|
|
55
|
+
return Promise.resolve();
|
|
56
|
+
if (refresh) {dirty=true;return refresh;}
|
|
57
|
+
dirty=false;
|
|
58
|
+
const captured = ctx, version = generation;
|
|
59
|
+
refresh = (async () => {
|
|
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 })) });
|
|
63
|
+
if (version !== generation)
|
|
64
|
+
return;
|
|
65
|
+
if (snapshot.recoveryPending === true) dirty = true;
|
|
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
|
+
}
|
|
76
|
+
notify();
|
|
77
|
+
for (const item of snapshot.deliveries ?? []) {
|
|
78
|
+
if (queued.has(item.token))
|
|
79
|
+
continue;
|
|
80
|
+
queued.add(item.token);
|
|
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
|
+
};
|
|
88
|
+
const proof = captured.sessionManager.getBranch().some((entry: any) => {
|
|
89
|
+
const message = entry.type === 'custom_message' ? entry : entry.message;
|
|
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);
|
|
91
|
+
});
|
|
92
|
+
if (proof) {
|
|
93
|
+
receipt(true);
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
const n = item.notification;
|
|
97
|
+
trace('queue', { ...facts, urgent: n.urgent === true, recipientActive: active(n.origin, n.branchId) });
|
|
98
|
+
if(n.urgent){void getCallbackBatcher(pi).deliverUrgent({...n.event,receiptId:item.receiptId,getSuppressionReason:()=>active(n.origin,n.branchId)?undefined:'The originating session or branch is no longer active',onDelivered:()=>receipt(true),onSuppressed:(reason)=>receipt(false,reason)});continue;}
|
|
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,
|
|
100
|
+
detailTool: 'bg_task_status', outcome: n.outcome, callback: true, receiptId: item.receiptId,
|
|
101
|
+
getSuppressionReason: () => active(n.origin, n.branchId) ? undefined : 'The originating session or branch is no longer active',
|
|
102
|
+
onDelivered: () => receipt(true), onSuppressed: (reason) => receipt(false, reason) });
|
|
103
|
+
}
|
|
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); });
|
|
106
|
+
return refresh;
|
|
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
|
+
};
|
|
114
|
+
const host = {
|
|
115
|
+
async reconcileNow() { await reconcile(); while (refresh) await refresh; },
|
|
116
|
+
start(context: ExtensionContext, restore = true) {
|
|
117
|
+
adoptContext(context); generation++; observing = false;
|
|
118
|
+
if (restore) activate();
|
|
119
|
+
},
|
|
120
|
+
noteParentContext(context: ExtensionContext) { adoptContext(context); generation++; void reconcile().catch(() => undefined); },
|
|
121
|
+
close() { observing = false; ctx = undefined; adoptedScope = undefined; generation++; rows = []; legacyRows = []; details.clear(); logs.clear(); retainedTasks.clear(); queued.clear(); ownership.clear(); },
|
|
122
|
+
isParentOriginActive: active,
|
|
123
|
+
onDurableTaskChange(listener: (change: any) => void) { listeners.add(listener); return () => listeners.delete(listener); },
|
|
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); },
|
|
127
|
+
readDurableTaskLog(origin: any, id: string, lines = 40) {
|
|
128
|
+
if (!active(origin))
|
|
129
|
+
return;
|
|
130
|
+
const key = `${id}:${lines}`;
|
|
131
|
+
return logs.get(key);
|
|
132
|
+
},
|
|
133
|
+
async stopDurableTask(origin: any, id: string) { if (!active(origin))
|
|
134
|
+
return; const result = await request('__background_stop', { id }); await host.reconcileNow(); return result; },
|
|
135
|
+
dismissDurableTask(origin: any, id: string) { if (!active(origin))
|
|
136
|
+
return false; void request('__background_dismiss', { id }).then(() => reconcile()).catch(() => undefined); return false; },
|
|
137
|
+
};
|
|
138
|
+
registerObservedWaitClient(pi, host as unknown as ObservedWaitHost);
|
|
139
|
+
pi.events?.on?.('pi-better-background-tasks:managed-capability',(request:any)=>{if(ctx&&typeof request?.accept==='function')request.accept({version:1,assignmentContinuation:1});});
|
|
140
|
+
onBackgroundObservation(pi, () => { details.clear(); logs.clear(); void reconcile().catch(() => undefined); });
|
|
141
|
+
const proxy = new Proxy(pi, { get(target, key) {
|
|
142
|
+
if (key === 'registerTool')
|
|
143
|
+
return (definition: any) => target.registerTool({ ...definition, execute: async (id: string, params: any, signal?: AbortSignal, _update?: unknown, context?: ExtensionContext) => {
|
|
144
|
+
if (!context)
|
|
145
|
+
throw new Error('Native Background context unavailable');
|
|
146
|
+
adoptContext(context);
|
|
147
|
+
const capturedGeneration = generation, capturedScope = adoptedScope;
|
|
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();
|
|
152
|
+
if (ctx === context && generation === capturedGeneration && adoptedScope === capturedScope) rememberOwnership(result.details?.backgroundOwnership, context);
|
|
153
|
+
await host.reconcileNow().catch(() => undefined);
|
|
154
|
+
return result;
|
|
155
|
+
} });
|
|
156
|
+
const value = Reflect.get(target, key);
|
|
157
|
+
return typeof value === 'function' ? value.bind(target) : value;
|
|
158
|
+
} });
|
|
159
|
+
registerObservedWaitClient(proxy, host as unknown as ObservedWaitHost);
|
|
160
|
+
const ui: ManagedBackgroundNavigator = {
|
|
161
|
+
onOpen: activate,
|
|
162
|
+
rows: () => legacyRows,
|
|
163
|
+
prepareDetail(id, options) {
|
|
164
|
+
const lines = options?.logTailLines ?? 40, key = `${id}:${lines}`;
|
|
165
|
+
const durable = Boolean(cachedTask(id)), cache = durable ? logs : details;
|
|
166
|
+
const version=generation;
|
|
167
|
+
if (cache.has(key))
|
|
168
|
+
return;
|
|
169
|
+
cache.set(key, null);
|
|
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);});
|
|
171
|
+
},
|
|
172
|
+
detail(id, now, options) { return details.get(`${id}:${options?.logTailLines ?? 40}`) ?? null; },
|
|
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 }; }
|
|
174
|
+
};
|
|
175
|
+
return { host, proxy, ui };
|
|
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
|
|
|
@@ -29,7 +30,14 @@ let durableRowCache: {
|
|
|
29
30
|
rows: BackgroundWorkRow[];
|
|
30
31
|
} | undefined;
|
|
31
32
|
|
|
32
|
-
export
|
|
33
|
+
export interface ManagedBackgroundNavigator {
|
|
34
|
+
onOpen?(): void;
|
|
35
|
+
rows(): BackgroundWorkRow[];
|
|
36
|
+
prepareDetail(id:string,options?:{logTailLines?:number}): void;
|
|
37
|
+
detail(id: string, now: number, options?: {logTailLines?: number}): BackgroundWorkDetail | null;
|
|
38
|
+
close(id: string): {action:string;providerId:string;id:string;status?:string};
|
|
39
|
+
}
|
|
40
|
+
export function createBackgroundTasksNavigator(runtime?: Pick<BackgroundTaskRuntime, "stopTask">, managed?: ManagedBackgroundNavigator) {
|
|
33
41
|
const owner = Symbol("background-tasks navigator factory");
|
|
34
42
|
let unregister: (() => void) | undefined;
|
|
35
43
|
let navigatorContext: ExtensionContext | undefined;
|
|
@@ -87,23 +95,28 @@ const provider: BackgroundWorkProvider = {
|
|
|
87
95
|
id: "background-tasks",
|
|
88
96
|
label: "Background Tasks",
|
|
89
97
|
priority: 20,
|
|
98
|
+
onOpen: managed?.onOpen,
|
|
90
99
|
visibleCount: () => {
|
|
91
100
|
const now = Date.now();
|
|
92
|
-
return visibleMetas(now).filter((meta) => meta.status === "running").length
|
|
101
|
+
return (managed ? managed.rows().filter(row => row.status === "running").length : visibleMetas(now).filter((meta) => meta.status === "running").length)
|
|
93
102
|
+ visibleDurableTasks(now).filter((task) => task.active).length;
|
|
94
103
|
},
|
|
95
104
|
listRows: (now) => [
|
|
96
|
-
...visibleMetas(now).map((meta) => rowFromMeta(meta, now)),
|
|
105
|
+
...(managed ? managed.rows() : visibleMetas(now).map((meta) => rowFromMeta(meta, now))),
|
|
97
106
|
...durableRows(visibleDurableTasks(now), now),
|
|
98
107
|
],
|
|
108
|
+
prepareDetail: (id,options) => managed?.prepareDetail(id,options),
|
|
99
109
|
detail: (id, now, options) => {
|
|
100
110
|
const durable = durableTask(id);
|
|
101
111
|
if (durable) return detailFromDurable(durable, options);
|
|
102
|
-
return detailFromMeta(readMeta(id), now, options);
|
|
112
|
+
return managed ? managed.detail(id,now,options) : detailFromMeta(readMeta(id), now, options);
|
|
103
113
|
},
|
|
104
114
|
armCloseLabel: (row) => row.status === "running" || row.status === "starting" ? "x again to stop" : "x again to dismiss",
|
|
105
115
|
close: (id) => {
|
|
116
|
+
if (durableTask(id)?.readOnly) return {action: "not-closable", providerId: "background-tasks", id};
|
|
117
|
+
if(managed)return managed.close(id);
|
|
106
118
|
const durable = durableTask(id);
|
|
119
|
+
if (durable?.readOnly) return {action: "not-closable", providerId: "background-tasks", id};
|
|
107
120
|
if (durable) {
|
|
108
121
|
const host = navigatorHost();
|
|
109
122
|
const origin = activeNavigatorOrigin;
|
|
@@ -120,7 +133,9 @@ const provider: BackgroundWorkProvider = {
|
|
|
120
133
|
const meta = readMeta(id);
|
|
121
134
|
if (!meta) return { action: "missing", providerId: "background-tasks", id };
|
|
122
135
|
if (meta.status === "running") {
|
|
123
|
-
|
|
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));
|
|
124
139
|
return { action: "stopped", providerId: "background-tasks", id, status: "stopping" };
|
|
125
140
|
}
|
|
126
141
|
meta.dismissedAt = Date.now();
|
|
@@ -184,6 +199,8 @@ function rowFromDurable(task: DurableTaskProjection, now: number): BackgroundWor
|
|
|
184
199
|
return {
|
|
185
200
|
providerId: "background-tasks",
|
|
186
201
|
id: task.id,
|
|
202
|
+
parentAgentId: task.parentAgentId,
|
|
203
|
+
readOnly: task.readOnly,
|
|
187
204
|
name: task.name,
|
|
188
205
|
status: task.status,
|
|
189
206
|
statusTone: toneForDurableStatus(task.status),
|
|
@@ -209,6 +226,7 @@ function detailFromDurable(task: DurableTaskProjection, options?: { logTailLines
|
|
|
209
226
|
const metadata = [
|
|
210
227
|
{ label: "provider", value: "Background Tasks (durable)" },
|
|
211
228
|
{ label: "kind", value: task.kind },
|
|
229
|
+
...(task.parentAgentId ? [{label: "agent", value: task.parentAgentId}] : []),
|
|
212
230
|
{ label: "operation", value: task.operationId },
|
|
213
231
|
{ label: "status", value: `${task.status}${task.terminalOutcome ? ` (${task.terminalOutcome})` : ""}` },
|
|
214
232
|
{ label: "started", value: new Date(task.startedAt).toISOString() },
|
|
@@ -247,7 +265,7 @@ function detailFromDurable(task: DurableTaskProjection, options?: { logTailLines
|
|
|
247
265
|
label: log?.truncated ? "log tail" : "log",
|
|
248
266
|
text: evidenceText,
|
|
249
267
|
},
|
|
250
|
-
footerActions: [task.active ? "x stop" : "x dismiss"],
|
|
268
|
+
footerActions: task.readOnly ? ["Managed by owning agent"] : [task.active ? "x stop" : "x dismiss"],
|
|
251
269
|
};
|
|
252
270
|
}
|
|
253
271
|
|
|
@@ -316,7 +334,7 @@ function isExpiredTerminalNavigatorRow(meta: BackgroundTaskMeta, now: number): b
|
|
|
316
334
|
return typeof endedAt === "number" && now - endedAt >= TERMINAL_NAVIGATOR_RETENTION_MS;
|
|
317
335
|
}
|
|
318
336
|
|
|
319
|
-
function rowFromMeta(meta: BackgroundTaskMeta, now: number): BackgroundWorkRow {
|
|
337
|
+
export function rowFromMeta(meta: BackgroundTaskMeta, now: number): BackgroundWorkRow {
|
|
320
338
|
// Only a failure that needs action replaces the row's command; history stays in the detail view (#332).
|
|
321
339
|
const view = failureView(meta.id);
|
|
322
340
|
const failure = view.actionable ? view.text : "";
|
|
@@ -341,7 +359,7 @@ function rowFromMeta(meta: BackgroundTaskMeta, now: number): BackgroundWorkRow {
|
|
|
341
359
|
};
|
|
342
360
|
}
|
|
343
361
|
|
|
344
|
-
function detailFromMeta(meta: BackgroundTaskMeta | undefined, now: number, options?: { logTailLines?: number }): BackgroundWorkDetail | null {
|
|
362
|
+
export function detailFromMeta(meta: BackgroundTaskMeta | undefined, now: number, options?: { logTailLines?: number }): BackgroundWorkDetail | null {
|
|
345
363
|
if (!meta) return null;
|
|
346
364
|
const view = failureView(meta.id);
|
|
347
365
|
const failure = view.text;
|
|
@@ -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
|
+
}
|