pi-better-background-tasks 0.16.0 → 0.18.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 +9 -0
- 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/daemon-owner.mjs +2 -1
- package/runtime-client/src/runtime/work-client.mjs +16 -2
- package/src/failures.ts +4 -2
- package/src/index.ts +6 -30
- package/src/managed-authority.ts +28 -0
- package/src/managed-client.ts +60 -0
- package/src/managed-frontend.ts +131 -0
- package/src/navigator-provider.ts +14 -6
- package/src/observed-waits.ts +286 -48
- package/src/output.ts +12 -0
- package/src/registry.ts +18 -1
- package/src/runtime.ts +8 -2
- package/src/sandbox.ts +7 -0
- package/src/shared-callback-batcher.ts +4 -1
- package/src/shared-failure-observations.ts +3 -0
- package/src/shared-navigator.ts +23 -5
- package/src/shared-operation-coordinator/assignment-observation.mjs +48 -1
- package/src/shared-operation-coordinator/index.ts +2 -0
- package/src/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
- package/src/shared-operation-coordinator/src/background-requests.ts +79 -0
- package/src/shared-operation-coordinator/src/discovery.ts +9 -0
- package/src/shared-operation-coordinator/src/operations.ts +6 -4
- package/src/shared-operation-coordinator/src/result-supervision.ts +128 -0
- package/src/shared-operation-coordinator/src/schema.ts +50 -1
- package/src/shared-operation-coordinator/src/store.ts +38 -0
- package/src/shared-operation-coordinator/src/subagent-launch.ts +119 -0
- package/src/shared-operation-coordinator/src/types.ts +6 -0
- package/src/shared-operation-coordinator/src/upgrade.ts +22 -0
- package/src/shared-work-client.mjs +16 -2
- package/src/tools.ts +76 -37
package/README.md
CHANGED
|
@@ -320,6 +320,15 @@ keeps observing after the worker or Pi process exits. Status and logs recover
|
|
|
320
320
|
from durable evidence; an ambiguous launch becomes `lost` and is not relaunched.
|
|
321
321
|
SSH tasks and older `bg_` identifiers use the existing runtime.
|
|
322
322
|
|
|
323
|
+
The canonical local server owns result supervision for newly admitted local
|
|
324
|
+
tasks. Closing every frontend leaves the independent runner running. The server
|
|
325
|
+
imports matching terminal evidence, advances already-authorized waits, and keeps
|
|
326
|
+
notifications for their recorded recipients. Hosted sessions use the same root
|
|
327
|
+
supervisor rather than starting another discovery loop. A live or unverified
|
|
328
|
+
legacy owner blocks handoff; missing permission authority or execution evidence
|
|
329
|
+
is reported without starting a replacement command. This transfer does not
|
|
330
|
+
authorize a continuation, consume evidence, or start a parent model turn.
|
|
331
|
+
|
|
323
332
|
Stop and timeout evidence can contain `groupCleanup=unproven` when the command's
|
|
324
333
|
leader exits before cleanup can be verified. Descendants may remain running;
|
|
325
334
|
inspect that evidence before interpreting the result.
|
package/package.json
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-better-background-tasks",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.0",
|
|
4
4
|
"description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
|
-
"bin": {
|
|
7
|
+
"bin": {
|
|
8
|
+
"pi-background-runtime-status": "./runtime-client/src/runtime/status-cli.mjs"
|
|
9
|
+
},
|
|
8
10
|
"keywords": [
|
|
9
11
|
"pi-package",
|
|
10
12
|
"pi-extension",
|
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"build":{"format":1,"sourceDigest":"
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"e89627fd959da4e828f709c00fa6b2178ffac42197f95bd118ba7d4625f97a25","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"a104a72371ffce16cf6acd48e6ccbbf36023e4eb0fbe571677bdaeaa4fb84c27","protocolVersion":1,"serverVersion":"0.5.0","contentId":"ff6f0431d44ca8784bb3075ecd23f3f819435df221fa8635def2c05d826a23af"},"sha256":"74642cefa6adb1f02c54e759bd3f9f81ab21c18c27ca05ba09302f5ef12a61f1"}
|
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"build":{"format":1,"sourceDigest":"
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"e89627fd959da4e828f709c00fa6b2178ffac42197f95bd118ba7d4625f97a25","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"a104a72371ffce16cf6acd48e6ccbbf36023e4eb0fbe571677bdaeaa4fb84c27","protocolVersion":1,"serverVersion":"0.5.0","contentId":"9e4de6d9e748e598ebed703c087df5b5bc76f01cd02ecf482c75b7f95ac881d7"},"sha256":"1e9387e6da69c4ba18cdbbc0f70fe01e4700c73e69ea507e4a30db761478b0be"}
|
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"build":{"format":1,"sourceDigest":"
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"e89627fd959da4e828f709c00fa6b2178ffac42197f95bd118ba7d4625f97a25","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"a104a72371ffce16cf6acd48e6ccbbf36023e4eb0fbe571677bdaeaa4fb84c27","protocolVersion":1,"serverVersion":"0.5.0","contentId":"f440118e90639f06127f3f2082a117e8d4aaa137ecde155870192539fc200eaa"},"sha256":"e740abc2b40d3069701ce3540f2881fd836406eb6a66e856c834c967ee8e9e90"}
|
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"build":{"format":1,"sourceDigest":"
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"e89627fd959da4e828f709c00fa6b2178ffac42197f95bd118ba7d4625f97a25","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"a104a72371ffce16cf6acd48e6ccbbf36023e4eb0fbe571677bdaeaa4fb84c27","protocolVersion":1,"serverVersion":"0.5.0","contentId":"d750352fca4145db9e04031a9a8c384ec19c9bd3277dd5139e881d8f0f79fe04"},"sha256":"923e3a45528bd8cb1354ccffe53ca7c8a613d458b2b1914f8e94698146499cc8"}
|
|
@@ -29,8 +29,9 @@ export function processMatchesStart(pid, start) {
|
|
|
29
29
|
try {
|
|
30
30
|
const observed = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
|
|
31
31
|
encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2000,
|
|
32
|
+
env: { ...process.env, LC_ALL: "C" },
|
|
32
33
|
}).trim();
|
|
33
|
-
return observed.length > 0 && observed === start.trim();
|
|
34
|
+
return observed.length > 0 && observed.replace(/\s+/g, " ") === start.trim().replace(/\s+/g, " ");
|
|
34
35
|
}
|
|
35
36
|
catch {
|
|
36
37
|
return false;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { connect } from "node:net";
|
|
2
|
+
import { performance } from "node:perf_hooks";
|
|
2
3
|
|
|
3
4
|
/** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
|
|
4
5
|
export class WorkClient {
|
|
@@ -6,6 +7,7 @@ export class WorkClient {
|
|
|
6
7
|
snapshot;
|
|
7
8
|
pending = new Map();
|
|
8
9
|
listeners = new Set();
|
|
10
|
+
catalogListeners = new Set();
|
|
9
11
|
sequence = 0;
|
|
10
12
|
scope;
|
|
11
13
|
buffer = "";
|
|
@@ -23,6 +25,7 @@ export class WorkClient {
|
|
|
23
25
|
try {
|
|
24
26
|
const message = JSON.parse(line);
|
|
25
27
|
if (message.type === "event") {
|
|
28
|
+
if (message.event.type === "runtime_catalog_snapshot") { for (const listener of this.catalogListeners) listener(message.event.snapshot); continue; }
|
|
26
29
|
if (message.event.type === "resync_required") { this.degrade(message.event.reason); void this.resync().catch(error => this.degrade(String(error))); }
|
|
27
30
|
else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot);
|
|
28
31
|
} else {
|
|
@@ -50,6 +53,7 @@ export class WorkClient {
|
|
|
50
53
|
});
|
|
51
54
|
}
|
|
52
55
|
onChange(listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
|
|
56
|
+
onCatalog(listener) { this.catalogListeners.add(listener); return () => this.catalogListeners.delete(listener); }
|
|
53
57
|
notify() { for (const listener of this.listeners) listener(this.snapshot); }
|
|
54
58
|
degrade(reason) {
|
|
55
59
|
this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
|
|
@@ -77,12 +81,22 @@ export class WorkClient {
|
|
|
77
81
|
const snapshot = await this.request("runtime_subscribe", { scope: this.scope, sinceSeq: this.snapshot?.seq, instanceId: this.snapshot?.instanceId });
|
|
78
82
|
this.accept(snapshot); return snapshot;
|
|
79
83
|
}
|
|
80
|
-
async get(scope) {
|
|
84
|
+
async get(scope) {
|
|
85
|
+
await this.ready;
|
|
86
|
+
const until = performance.now() + 3500;
|
|
87
|
+
for (let attempt = 0; ; attempt++) {
|
|
88
|
+
const value = await this.request("runtime_get_snapshot", { scope });
|
|
89
|
+
if (!scope?.id || value.status !== "rebuilding" || value.rows.length || performance.now() >= until) return value;
|
|
90
|
+
// A newly written ID may join an inventory without holding the shared RPC queue.
|
|
91
|
+
await new Promise(resolve => setTimeout(resolve, Math.min(250, 50 * 2 ** attempt, until - performance.now())));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
81
94
|
fail(error) {
|
|
82
95
|
if (this.closed) return;
|
|
83
96
|
this.closed = true;
|
|
84
97
|
for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
|
|
85
98
|
this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
|
|
99
|
+
for (const listener of this.catalogListeners) listener({ status: "revoked" });
|
|
86
100
|
}
|
|
87
|
-
close() { this.fail(new Error("runtime-unavailable: client closed")); this.listeners.clear(); }
|
|
101
|
+
close() { this.fail(new Error("runtime-unavailable: client closed")); this.listeners.clear(); this.catalogListeners.clear(); }
|
|
88
102
|
}
|
package/src/failures.ts
CHANGED
|
@@ -103,7 +103,7 @@ export function recoverDeclaredOperation(meta: BackgroundTaskMeta, at = Date.now
|
|
|
103
103
|
}
|
|
104
104
|
}
|
|
105
105
|
|
|
106
|
-
export function createFailureAttention() {
|
|
106
|
+
export function createFailureAttention(deliverUrgent?: (origin: BackgroundTaskMeta["callbackOrigin"], event: Parameters<ReturnType<typeof getCallbackBatcher>["deliverUrgent"]>[0]) => boolean | Promise<boolean>) {
|
|
107
107
|
const attentionTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
108
108
|
let attentionSuspended = false;
|
|
109
109
|
/** Session shutdown: stop this instance's attention timers; the next session_start reschedules (#324). */
|
|
@@ -159,7 +159,9 @@ function scheduleFailureAttention(pi: ExtensionAPI, id: string, getActiveSession
|
|
|
159
159
|
const state = readFailureState(failurePath(id));
|
|
160
160
|
const pending = pendingFailureAttention(state, Date.now());
|
|
161
161
|
if (pending) {
|
|
162
|
-
const
|
|
162
|
+
const deliver = (event: Parameters<ReturnType<typeof getCallbackBatcher>["deliverUrgent"]>[0]) => deliverUrgent ? deliverUrgent(meta.callbackOrigin,event) : getCallbackBatcher(pi).deliverUrgent(event);
|
|
163
|
+
const delivery = deliver({
|
|
164
|
+
receiptId: `background-failure:${meta.id}:${pending.key}`,
|
|
163
165
|
...failureAttentionFields(meta, state, pending),
|
|
164
166
|
isDelivered: () => {
|
|
165
167
|
const current = readMeta(id);
|
package/src/index.ts
CHANGED
|
@@ -3,42 +3,18 @@ import { initializeNavigatorPanels } from "./shared-navigator-panels.ts";
|
|
|
3
3
|
import { registerBackgroundTasksGoalProvider } from "./goal-provider.js";
|
|
4
4
|
import { createBackgroundTasksNavigator } from "./navigator-provider.js";
|
|
5
5
|
import { createBackgroundTaskRuntime } from "./runtime.js";
|
|
6
|
-
import {
|
|
7
|
-
import { getCallbackBatcher } from "./shared-callback-batcher.js";
|
|
6
|
+
import { createManagedBackgroundFrontend } from "./managed-frontend.js";
|
|
8
7
|
import { observeForegroundSandboxPolicy } from "./sandbox.js";
|
|
9
8
|
import { registerTools } from "./tools.js";
|
|
10
9
|
import { deliverBackgroundTasksPrompt } from "./prompt.js";
|
|
11
10
|
import { closeBackgroundObservation } from "./work-observation.js";
|
|
12
11
|
|
|
13
12
|
export default function backgroundTasksExtension(pi: ExtensionAPI): void {
|
|
14
|
-
//
|
|
15
|
-
//
|
|
13
|
+
// The frontend owns native UI/delivery only. Mechanical tools run in the
|
|
14
|
+
// fixed server service; this runtime supplies registration metadata only.
|
|
16
15
|
const runtime = createBackgroundTaskRuntime();
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
// store opens on session activation and closes on switch/unload.
|
|
20
|
-
const observedWaits = createObservedWaitHost(pi, {
|
|
21
|
-
notifyParent: (notification, delivery) => {
|
|
22
|
-
getCallbackBatcher(pi).enqueue({
|
|
23
|
-
source: "background-task",
|
|
24
|
-
id: notification.taskId,
|
|
25
|
-
label: notification.taskId,
|
|
26
|
-
status: notification.waitId
|
|
27
|
-
? `${notification.status}; wait ${notification.waitId} ready`
|
|
28
|
-
: notification.status,
|
|
29
|
-
detailTool: "bg_task_status",
|
|
30
|
-
outcome: notification.outcome,
|
|
31
|
-
callback: true,
|
|
32
|
-
// The batcher can hold the event across a busy turn or a session switch.
|
|
33
|
-
// Receipt is the durable outbox/sidecar acknowledgement, not enqueue.
|
|
34
|
-
getSuppressionReason: () => observedWaits.isParentOriginActive(notification.origin, notification.branchId)
|
|
35
|
-
? undefined
|
|
36
|
-
: "the originating session or branch is no longer active",
|
|
37
|
-
onDelivered: () => delivery.delivered(),
|
|
38
|
-
onSuppressed: (reason) => delivery.defer(reason ?? "callback delivery was suppressed"),
|
|
39
|
-
});
|
|
40
|
-
},
|
|
41
|
-
});
|
|
16
|
+
const {host: observedWaits, proxy, ui} = createManagedBackgroundFrontend(pi);
|
|
17
|
+
const navigator = createBackgroundTasksNavigator(runtime, ui);
|
|
42
18
|
initializeNavigatorPanels(pi);
|
|
43
19
|
// Sections on a host that renders them; text only where it renders none.
|
|
44
20
|
// Returning a prompt on modern pi would set forceSystemPrompt, and the request
|
|
@@ -67,7 +43,7 @@ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
|
|
|
67
43
|
runtime.suspendScheduledWork();
|
|
68
44
|
navigator.clearBackgroundTasksNavigatorSession();
|
|
69
45
|
});
|
|
70
|
-
registerTools(
|
|
46
|
+
registerTools(proxy, runtime, navigator.refreshBackgroundTasksNavigator, {resumeLocal:false});
|
|
71
47
|
// Registered after registerTools so the callback batcher has its session
|
|
72
48
|
// context before a reconciled delivery can enqueue a parent notification.
|
|
73
49
|
pi.on("session_start", async (_event, ctx) => {
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { lstatSync, readFileSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { readProcessStartTokenFresh } from './process-identity.js';
|
|
5
|
+
const ordered = (value: any): any => value === null || typeof value !== 'object' ? value : Array.isArray(value) ? value.map(ordered) : Object.fromEntries(Object.keys(value).sort().map(key => [key, ordered(value[key])]));
|
|
6
|
+
export const backgroundDigest = (value: unknown) => createHash('sha256').update(JSON.stringify(ordered(value))).digest('hex');
|
|
7
|
+
export function readBackgroundAuthority(root: string, instance: string, authority: any, requireLive = true): any {
|
|
8
|
+
if (!authority || !/^[a-f0-9-]{36}$/.test(authority.id) || !/^[a-f0-9]{64}$/.test(authority.secret))
|
|
9
|
+
throw new Error('background-authority-refused');
|
|
10
|
+
const directory = join(root, 'background-tool-admission'), path = join(directory, `${authority.id}.json`);
|
|
11
|
+
const dir = lstatSync(directory), stat = lstatSync(path);
|
|
12
|
+
if (!dir.isDirectory() || dir.isSymbolicLink() || dir.uid !== process.getuid?.() || (dir.mode & 0o077)
|
|
13
|
+
|| !stat.isFile() || stat.isSymbolicLink() || stat.uid !== dir.uid || (stat.mode & 0o077) || stat.size > 1024 * 1024)
|
|
14
|
+
throw new Error('background-authority-refused');
|
|
15
|
+
const record = JSON.parse(readFileSync(path, 'utf8')), digest = createHash('sha256').update(authority.secret).digest('hex');
|
|
16
|
+
if (record.version !== 1 || record.instanceId !== instance || record.id !== authority.id || typeof record.secretHash !== 'string'
|
|
17
|
+
|| record.secretHash.length !== digest.length || !timingSafeEqual(Buffer.from(record.secretHash), Buffer.from(digest))
|
|
18
|
+
|| typeof record.key !== 'string' || !record.key || typeof record.tool !== 'string' || !record.owner?.sessionId
|
|
19
|
+
|| record.owner.workspace !== realpathSync(record.owner.workspace) || !Number.isSafeInteger(record.pid) || !record.start
|
|
20
|
+
|| !Array.isArray(record.branchIds) || record.branchIds.some((id: unknown) => typeof id !== 'string'))
|
|
21
|
+
throw new Error('background-authority-refused');
|
|
22
|
+
if (requireLive) {
|
|
23
|
+
if (readProcessStartTokenFresh(record.pid) !== record.start)
|
|
24
|
+
throw new Error('background-authority-refused: host identity changed');
|
|
25
|
+
process.kill(record.pid, 0);
|
|
26
|
+
}
|
|
27
|
+
return record;
|
|
28
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
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 { readProcessStartTokenFresh } from './process-identity.js';
|
|
7
|
+
import { currentForegroundSandboxPolicy, FOREGROUND_SANDBOX_POLICY_CHANNEL } from './sandbox.js';
|
|
8
|
+
import { 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
|
+
await backgroundObservation(pi, ctx);
|
|
14
|
+
const root = realpathSync(getAgentDir()), registration = JSON.parse(readFileSync(join(root, 'server-registration-v1.json'), 'utf8'));
|
|
15
|
+
if (registration.version !== 1 || registration.agentDir !== root)
|
|
16
|
+
throw new Error('Invalid runtime registration');
|
|
17
|
+
const module = new URL('./shared-work-client.mjs', import.meta.url).href;
|
|
18
|
+
const { WorkClient } = await import(module);
|
|
19
|
+
const directory = join(root, 'background-tool-admission');
|
|
20
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
21
|
+
const stat = lstatSync(directory);
|
|
22
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077))
|
|
23
|
+
throw new Error('Unsafe Background admission directory');
|
|
24
|
+
const client = new WorkClient(join(registration.serverDir, 'pi-server.sock'), root, ['runtime-background-execution-v1']);
|
|
25
|
+
const id = randomUUID(), secret = randomBytes(32).toString('hex'), path = join(directory, `${id}.json`);
|
|
26
|
+
let off: unknown;
|
|
27
|
+
const abort = () => client.close();
|
|
28
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
29
|
+
try {
|
|
30
|
+
const hello = await client.ready;
|
|
31
|
+
const policy = currentForegroundSandboxPolicy(pi);
|
|
32
|
+
const branchIds = ctx.sessionManager.getBranch().map(entry => entry.id).filter((value): value is string => typeof value === 'string');
|
|
33
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
34
|
+
if (!sessionId)
|
|
35
|
+
throw new Error('Background tools require a native session identity');
|
|
36
|
+
const record = { version: 1, id, secretHash: createHash('sha256').update(secret).digest('hex'), instanceId: hello.instanceId,
|
|
37
|
+
owner: { kind: 'parent-session', sessionId, workspace: realpathSync(ctx.cwd) }, branchIds, projectTrusted: ctx.isProjectTrusted(),
|
|
38
|
+
pid: process.pid, start: readProcessStartTokenFresh(process.pid), key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundDigest(parameters), policy };
|
|
39
|
+
const staged = `${path}.tmp`;
|
|
40
|
+
writeFileSync(staged, JSON.stringify(record), { flag: 'wx', mode: 0o600 });
|
|
41
|
+
renameSync(staged, path);
|
|
42
|
+
let checking = false;
|
|
43
|
+
off = pi.events.on(FOREGROUND_SANDBOX_POLICY_CHANNEL, () => { if (checking)
|
|
44
|
+
return; checking = true; try {
|
|
45
|
+
if (backgroundDigest(currentForegroundSandboxPolicy(pi) ?? null) !== backgroundDigest(policy ?? null))
|
|
46
|
+
rmSync(path, { force: true });
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
checking = false;
|
|
50
|
+
} });
|
|
51
|
+
return await client.request('runtime_background_tool', { authority: { id, secret } });
|
|
52
|
+
}
|
|
53
|
+
finally {
|
|
54
|
+
if (typeof off === 'function')
|
|
55
|
+
off();
|
|
56
|
+
signal?.removeEventListener('abort', abort);
|
|
57
|
+
client.close();
|
|
58
|
+
rmSync(path, { force: true });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
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, type ObservedWaitHost } from './observed-waits.js';
|
|
8
|
+
/** Native transcript delivery and cached UI projections; no coordinator or supervisor. */
|
|
9
|
+
export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
10
|
+
let ctx: ExtensionContext | undefined, generation = 0, refresh: Promise<void> | undefined, dirty=false;
|
|
11
|
+
let rows: any[] = [], legacyRows: any[] = [], details = new Map<string, any>(), logs = new Map<string, any>();
|
|
12
|
+
let adoptedScope: string | undefined;
|
|
13
|
+
const scopeOf = (context: ExtensionContext) => JSON.stringify([context.cwd, context.sessionManager.getSessionId()]);
|
|
14
|
+
const ownership = new Map<string, { operationId: string; owner: { kind: string; sessionId: string; workspace: string } }>();
|
|
15
|
+
const adoptContext = (context: ExtensionContext) => {
|
|
16
|
+
if (adoptedScope !== undefined && adoptedScope !== scopeOf(context)) {
|
|
17
|
+
ownership.clear(); rows = []; legacyRows = []; details.clear(); logs.clear(); generation++;
|
|
18
|
+
}
|
|
19
|
+
ctx = context; adoptedScope = scopeOf(context);
|
|
20
|
+
};
|
|
21
|
+
const rememberOwnership = (proof: any, context: ExtensionContext) => {
|
|
22
|
+
if (!proof || typeof proof.id !== 'string' || typeof proof.operationId !== 'string'
|
|
23
|
+
|| proof.owner?.kind !== 'parent-session' || proof.owner.workspace !== context.cwd
|
|
24
|
+
|| proof.owner.sessionId !== context.sessionManager.getSessionId()) return;
|
|
25
|
+
ownership.delete(proof.id); ownership.set(proof.id, proof);
|
|
26
|
+
if (ownership.size > 256) ownership.delete(ownership.keys().next().value!);
|
|
27
|
+
};
|
|
28
|
+
const queued = new Set<string>(), listeners = new Set<(change: any) => void>();
|
|
29
|
+
const active = (origin: any, branch?: string | null) => Boolean(ctx && origin.cwd === ctx.cwd && origin.sessionId === ctx.sessionManager.getSessionId()
|
|
30
|
+
&& (!branch || ctx.sessionManager.getBranch().some(entry => entry.id === branch)));
|
|
31
|
+
const request = (tool: string, params: any) => {
|
|
32
|
+
if (!ctx)
|
|
33
|
+
throw new Error('Native Background session unavailable');
|
|
34
|
+
return requestBackgroundTool(pi, ctx, randomUUID(), tool, params);
|
|
35
|
+
};
|
|
36
|
+
const notify = () => { for (const listener of listeners)
|
|
37
|
+
listener({ workspace: ctx?.cwd, sessionId: ctx?.sessionManager.getSessionId() }); };
|
|
38
|
+
const reconcile = () => {
|
|
39
|
+
if (!ctx)
|
|
40
|
+
return Promise.resolve();
|
|
41
|
+
if (refresh) {dirty=true;return refresh;}
|
|
42
|
+
dirty=false;
|
|
43
|
+
const captured = ctx, version = generation;
|
|
44
|
+
refresh = (async () => {
|
|
45
|
+
const snapshot = await request('__background_poll', {});
|
|
46
|
+
if (version !== generation)
|
|
47
|
+
return;
|
|
48
|
+
if (snapshot.recoveryPending === true) dirty = true;
|
|
49
|
+
rows = snapshot.tasks ?? [];
|
|
50
|
+
legacyRows = snapshot.legacyRows ?? [];
|
|
51
|
+
notify();
|
|
52
|
+
for (const item of snapshot.deliveries ?? []) {
|
|
53
|
+
if (queued.has(item.token))
|
|
54
|
+
continue;
|
|
55
|
+
queued.add(item.token);
|
|
56
|
+
const receipt = (delivered: boolean, reason?: string) => void requestBackgroundTool(pi, captured, randomUUID(), '__background_receipt', { token: item.token, delivered, reason })
|
|
57
|
+
.catch(() => undefined).finally(() => {queued.delete(item.token);if(ctx===captured)void reconcile().catch(()=>undefined);});
|
|
58
|
+
const proof = captured.sessionManager.getBranch().some((entry: any) => {
|
|
59
|
+
const message = entry.type === 'custom_message' ? entry : entry.message;
|
|
60
|
+
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);
|
|
61
|
+
});
|
|
62
|
+
if (proof) {
|
|
63
|
+
receipt(true);
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const n = item.notification;
|
|
67
|
+
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
|
+
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
|
+
detailTool: 'bg_task_status', outcome: n.outcome, callback: true, receiptId: item.receiptId,
|
|
70
|
+
getSuppressionReason: () => active(n.origin, n.branchId) ? undefined : 'The originating session or branch is no longer active',
|
|
71
|
+
onDelivered: () => receipt(true), onSuppressed: (reason) => receipt(false, reason) });
|
|
72
|
+
}
|
|
73
|
+
})().finally(() => { refresh = undefined;if(dirty&&ctx)void reconcile().catch(()=>undefined); });
|
|
74
|
+
return refresh;
|
|
75
|
+
};
|
|
76
|
+
const host = {
|
|
77
|
+
async reconcileNow() { await reconcile(); while (refresh) await refresh; },
|
|
78
|
+
start(context: ExtensionContext) { adoptContext(context); generation++; void reconcile().catch(() => undefined); },
|
|
79
|
+
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(); },
|
|
81
|
+
isParentOriginActive: active,
|
|
82
|
+
onDurableTaskChange(listener: (change: any) => void) { listeners.add(listener); return () => listeners.delete(listener); },
|
|
83
|
+
listDurableTasks(origin: any, options: any = {}) { return active(origin) ? rows.filter(row => !options.retentionMs || !row.terminal || Date.now() - (row.endedAt ?? Date.now()) < options.retentionMs) : []; },
|
|
84
|
+
readDurableTask(origin: any, id: string) { return active(origin) ? rows.find(row => row.id === id) : undefined; },
|
|
85
|
+
ownsDurableTask(id: string) { if (!ctx || adoptedScope !== scopeOf(ctx)) return false; return ownership.has(id) || rows.some(row => row.id === id); },
|
|
86
|
+
readDurableTaskLog(origin: any, id: string, lines = 40) {
|
|
87
|
+
if (!active(origin))
|
|
88
|
+
return;
|
|
89
|
+
const key = `${id}:${lines}`;
|
|
90
|
+
return logs.get(key);
|
|
91
|
+
},
|
|
92
|
+
async stopDurableTask(origin: any, id: string) { if (!active(origin))
|
|
93
|
+
return; const result = await request('__background_stop', { id }); await host.reconcileNow(); return result; },
|
|
94
|
+
dismissDurableTask(origin: any, id: string) { if (!active(origin))
|
|
95
|
+
return false; void request('__background_dismiss', { id }).then(() => reconcile()).catch(() => undefined); return false; },
|
|
96
|
+
};
|
|
97
|
+
registerObservedWaitClient(pi, host as unknown as ObservedWaitHost);
|
|
98
|
+
pi.events?.on?.('pi-better-background-tasks:managed-capability',(request:any)=>{if(ctx&&typeof request?.accept==='function')request.accept({version:1,assignmentContinuation:1});});
|
|
99
|
+
onBackgroundObservation(pi, () => { details.clear(); logs.clear(); void reconcile().catch(() => undefined); });
|
|
100
|
+
const proxy = new Proxy(pi, { get(target, key) {
|
|
101
|
+
if (key === 'registerTool')
|
|
102
|
+
return (definition: any) => target.registerTool({ ...definition, execute: async (id: string, params: any, signal?: AbortSignal, _update?: unknown, context?: ExtensionContext) => {
|
|
103
|
+
if (!context)
|
|
104
|
+
throw new Error('Native Background context unavailable');
|
|
105
|
+
adoptContext(context);
|
|
106
|
+
const capturedGeneration = generation, capturedScope = adoptedScope;
|
|
107
|
+
const result = await requestBackgroundTool(pi, context, id, definition.name, params, definition.parameters, signal);
|
|
108
|
+
if (ctx === context && generation === capturedGeneration && adoptedScope === capturedScope) rememberOwnership(result.details?.backgroundOwnership, context);
|
|
109
|
+
await host.reconcileNow().catch(() => undefined);
|
|
110
|
+
return result;
|
|
111
|
+
} });
|
|
112
|
+
const value = Reflect.get(target, key);
|
|
113
|
+
return typeof value === 'function' ? value.bind(target) : value;
|
|
114
|
+
} });
|
|
115
|
+
registerObservedWaitClient(proxy, host as unknown as ObservedWaitHost);
|
|
116
|
+
const ui: ManagedBackgroundNavigator = {
|
|
117
|
+
rows: () => legacyRows.filter(row => !row.expiresAt || row.expiresAt > Date.now()),
|
|
118
|
+
prepareDetail(id, options) {
|
|
119
|
+
const lines = options?.logTailLines ?? 40, key = `${id}:${lines}`;
|
|
120
|
+
const durable = rows.some(row => row.id === id), cache = durable ? logs : details;
|
|
121
|
+
const version=generation;
|
|
122
|
+
if (cache.has(key))
|
|
123
|
+
return;
|
|
124
|
+
cache.set(key, null);
|
|
125
|
+
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
|
+
},
|
|
127
|
+
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 }; }
|
|
129
|
+
};
|
|
130
|
+
return { host, proxy, ui };
|
|
131
|
+
}
|
|
@@ -29,7 +29,13 @@ let durableRowCache: {
|
|
|
29
29
|
rows: BackgroundWorkRow[];
|
|
30
30
|
} | undefined;
|
|
31
31
|
|
|
32
|
-
export
|
|
32
|
+
export interface ManagedBackgroundNavigator {
|
|
33
|
+
rows(): BackgroundWorkRow[];
|
|
34
|
+
prepareDetail(id:string,options?:{logTailLines?:number}): void;
|
|
35
|
+
detail(id: string, now: number, options?: {logTailLines?: number}): BackgroundWorkDetail | null;
|
|
36
|
+
close(id: string): {action:string;providerId:string;id:string;status?:string};
|
|
37
|
+
}
|
|
38
|
+
export function createBackgroundTasksNavigator(runtime: Pick<BackgroundTaskRuntime, "stopTask"> = { stopTask }, managed?: ManagedBackgroundNavigator) {
|
|
33
39
|
const owner = Symbol("background-tasks navigator factory");
|
|
34
40
|
let unregister: (() => void) | undefined;
|
|
35
41
|
let navigatorContext: ExtensionContext | undefined;
|
|
@@ -89,20 +95,22 @@ const provider: BackgroundWorkProvider = {
|
|
|
89
95
|
priority: 20,
|
|
90
96
|
visibleCount: () => {
|
|
91
97
|
const now = Date.now();
|
|
92
|
-
return visibleMetas(now).filter((meta) => meta.status === "running").length
|
|
98
|
+
return (managed ? managed.rows().filter(row => row.status === "running").length : visibleMetas(now).filter((meta) => meta.status === "running").length)
|
|
93
99
|
+ visibleDurableTasks(now).filter((task) => task.active).length;
|
|
94
100
|
},
|
|
95
101
|
listRows: (now) => [
|
|
96
|
-
...visibleMetas(now).map((meta) => rowFromMeta(meta, now)),
|
|
102
|
+
...(managed ? managed.rows() : visibleMetas(now).map((meta) => rowFromMeta(meta, now))),
|
|
97
103
|
...durableRows(visibleDurableTasks(now), now),
|
|
98
104
|
],
|
|
105
|
+
prepareDetail: (id,options) => managed?.prepareDetail(id,options),
|
|
99
106
|
detail: (id, now, options) => {
|
|
100
107
|
const durable = durableTask(id);
|
|
101
108
|
if (durable) return detailFromDurable(durable, options);
|
|
102
|
-
return detailFromMeta(readMeta(id), now, options);
|
|
109
|
+
return managed ? managed.detail(id,now,options) : detailFromMeta(readMeta(id), now, options);
|
|
103
110
|
},
|
|
104
111
|
armCloseLabel: (row) => row.status === "running" || row.status === "starting" ? "x again to stop" : "x again to dismiss",
|
|
105
112
|
close: (id) => {
|
|
113
|
+
if(managed)return managed.close(id);
|
|
106
114
|
const durable = durableTask(id);
|
|
107
115
|
if (durable) {
|
|
108
116
|
const host = navigatorHost();
|
|
@@ -316,7 +324,7 @@ function isExpiredTerminalNavigatorRow(meta: BackgroundTaskMeta, now: number): b
|
|
|
316
324
|
return typeof endedAt === "number" && now - endedAt >= TERMINAL_NAVIGATOR_RETENTION_MS;
|
|
317
325
|
}
|
|
318
326
|
|
|
319
|
-
function rowFromMeta(meta: BackgroundTaskMeta, now: number): BackgroundWorkRow {
|
|
327
|
+
export function rowFromMeta(meta: BackgroundTaskMeta, now: number): BackgroundWorkRow {
|
|
320
328
|
// Only a failure that needs action replaces the row's command; history stays in the detail view (#332).
|
|
321
329
|
const view = failureView(meta.id);
|
|
322
330
|
const failure = view.actionable ? view.text : "";
|
|
@@ -341,7 +349,7 @@ function rowFromMeta(meta: BackgroundTaskMeta, now: number): BackgroundWorkRow {
|
|
|
341
349
|
};
|
|
342
350
|
}
|
|
343
351
|
|
|
344
|
-
function detailFromMeta(meta: BackgroundTaskMeta | undefined, now: number, options?: { logTailLines?: number }): BackgroundWorkDetail | null {
|
|
352
|
+
export function detailFromMeta(meta: BackgroundTaskMeta | undefined, now: number, options?: { logTailLines?: number }): BackgroundWorkDetail | null {
|
|
345
353
|
if (!meta) return null;
|
|
346
354
|
const view = failureView(meta.id);
|
|
347
355
|
const failure = view.text;
|