pi-better-background-tasks 0.16.0 → 0.17.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 +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/daemon-owner.mjs +2 -1
- package/runtime-client/src/runtime/work-client.mjs +16 -2
- package/src/index.ts +1 -0
- package/src/observed-waits.ts +168 -12
- package/src/shared-operation-coordinator/assignment-observation.mjs +18 -1
- 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 +19 -1
- package/src/shared-operation-coordinator/src/store.ts +20 -0
- package/src/shared-operation-coordinator/src/types.ts +6 -0
- package/src/shared-work-client.mjs +16 -2
- package/src/tools.ts +59 -36
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
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"build":{"format":1,"sourceDigest":"
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"f1a415e52552342511151e078257a3d81660989f30a684a263fb8f6252ac9e63","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.4.0","contentId":"d8babdaa88ccdf11463b69738823e4175a88cb25e1f6b51bd1cde1dc5ebbd6b3"},"sha256":"40cbb55c9f6bcba62ac2fde5d00521d44c627177baede403fdfa9ee53ccec6ce"}
|
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"build":{"format":1,"sourceDigest":"
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"f1a415e52552342511151e078257a3d81660989f30a684a263fb8f6252ac9e63","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.4.0","contentId":"0c892582dfd3e78b9f5fc25821dfd6b7c233f7f8b6d31677196dc3aaeda0a909"},"sha256":"61e469f213ae5ef7e379897f03f069b4a8c668a3a338f7fee7cafffeb7c648f3"}
|
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"build":{"format":1,"sourceDigest":"
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"f1a415e52552342511151e078257a3d81660989f30a684a263fb8f6252ac9e63","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.4.0","contentId":"d71fc0b69c23b6808726d5a971c3ddd1da00985dfb655c79190b83c3997fcb1f"},"sha256":"057130e7109c592068e375f31a5f39297163326bb88f6461d59ae4e7742d7a80"}
|
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"build":{"format":1,"sourceDigest":"
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"f1a415e52552342511151e078257a3d81660989f30a684a263fb8f6252ac9e63","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.4.0","contentId":"5e132e98f011fb0eee44a2184ef8d17787a7ac0f1b792b676b08582d248ba19f"},"sha256":"a007cde2962d0b0eb4fe378a3e9d08fd2f20ada6fce2c96b76f849cb6dd62c96"}
|
|
@@ -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/index.ts
CHANGED
|
@@ -18,6 +18,7 @@ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
|
|
|
18
18
|
// Created before registerTools so the tools can resolve it lazily; the durable
|
|
19
19
|
// store opens on session activation and closes on switch/unload.
|
|
20
20
|
const observedWaits = createObservedWaitHost(pi, {
|
|
21
|
+
serverOwnedResults: true,
|
|
21
22
|
notifyParent: (notification, delivery) => {
|
|
22
23
|
getCallbackBatcher(pi).enqueue({
|
|
23
24
|
source: "background-task",
|
package/src/observed-waits.ts
CHANGED
|
@@ -42,6 +42,7 @@ import {
|
|
|
42
42
|
backgroundExecutionLimits,
|
|
43
43
|
confineCommandSpec,
|
|
44
44
|
resolveForegroundSandboxPlan,
|
|
45
|
+
currentForegroundSandboxPolicy,
|
|
45
46
|
resolveWorkerSandboxPlan,
|
|
46
47
|
sandboxProvenance,
|
|
47
48
|
type ForegroundSandboxPlan,
|
|
@@ -556,6 +557,8 @@ function rpcCode(error: unknown): string {
|
|
|
556
557
|
}
|
|
557
558
|
|
|
558
559
|
export interface ObservedWaitHostOptions {
|
|
560
|
+
/** Production adapters leave global discovery and terminal import to the server. */
|
|
561
|
+
serverOwnedResults?: boolean;
|
|
559
562
|
/** SQLite path. Defaults under the Pi agent directory. */
|
|
560
563
|
storePath?: string;
|
|
561
564
|
/** Durable supervisor record directory. Defaults beside the task registry. */
|
|
@@ -658,6 +661,7 @@ interface LaunchContext {
|
|
|
658
661
|
readonly cwd?: string;
|
|
659
662
|
/** Launch-time sandbox provenance; never recomputed from the current profile. */
|
|
660
663
|
readonly sandbox?: TaskSandboxProvenance;
|
|
664
|
+
readonly supervisionPolicy?: ForegroundSandboxPlan;
|
|
661
665
|
/** Owner branch anchor captured at launch (undefined when unavailable). */
|
|
662
666
|
readonly branchId?: string | null;
|
|
663
667
|
callbackPendingAt?: number;
|
|
@@ -861,6 +865,7 @@ export class ObservedWaitHost {
|
|
|
861
865
|
private readonly options: ObservedWaitHostOptions;
|
|
862
866
|
private timer?: NodeJS.Timeout;
|
|
863
867
|
private closed = false;
|
|
868
|
+
private activationAttempted = false;
|
|
864
869
|
private unavailableReason?: string;
|
|
865
870
|
private parentOrigin?: BackgroundTaskCallbackOrigin;
|
|
866
871
|
private activeOrigin?: BackgroundTaskCallbackOrigin;
|
|
@@ -896,6 +901,7 @@ export class ObservedWaitHost {
|
|
|
896
901
|
private continuationError?: string;
|
|
897
902
|
private readonly launches = new Map<string, LaunchContext>();
|
|
898
903
|
private readonly localCancels = new Set<string>();
|
|
904
|
+
private readonly resultHandoffs = new Set<string>();
|
|
899
905
|
private readonly rpcRuns = new Map<string, RpcRunBinding>();
|
|
900
906
|
private readonly waitOwners = new Map<string, OwnerIdentity>();
|
|
901
907
|
private readonly stagedCheckpoints = new Map<string, { evidence: JsonRecord; toolCallId: string; checkpointRecorded: boolean }>();
|
|
@@ -972,12 +978,16 @@ export class ObservedWaitHost {
|
|
|
972
978
|
return this.store !== undefined && !this.closed;
|
|
973
979
|
}
|
|
974
980
|
|
|
981
|
+
get usesServerResults(): boolean { return this.options.serverOwnedResults === true; }
|
|
982
|
+
get hasActivated(): boolean { return this.activationAttempted; }
|
|
983
|
+
|
|
975
984
|
get reason(): string | undefined {
|
|
976
985
|
return this.unavailableReason;
|
|
977
986
|
}
|
|
978
987
|
|
|
979
988
|
/** Open the durable store and begin bounded reconciliation. */
|
|
980
989
|
start(ctx?: ExtensionContext): void {
|
|
990
|
+
this.activationAttempted = true;
|
|
981
991
|
if (ctx) this.setActiveOrigin(ctx);
|
|
982
992
|
if (this.store) {
|
|
983
993
|
// The same host instance can be activated for another session without a
|
|
@@ -1163,7 +1173,16 @@ export class ObservedWaitHost {
|
|
|
1163
1173
|
if (!this.store || this.closed) return;
|
|
1164
1174
|
this.authorityPassCache = new Map();
|
|
1165
1175
|
try {
|
|
1166
|
-
const
|
|
1176
|
+
const discovery = this.options.serverOwnedResults ? undefined : this.store.readDiscoveryState(this.discoveryScope);
|
|
1177
|
+
if (this.options.serverOwnedResults || discovery?.managed) {
|
|
1178
|
+
this.releaseDiscoveryAuthority();
|
|
1179
|
+
if (!this.options.serverOwnedResults) this.reconcileFollowerRunning();
|
|
1180
|
+
this.reconcileOwnerChanges();
|
|
1181
|
+
this.retryPendingTerminalCallbacks();
|
|
1182
|
+
await this.dispatchOutbox();
|
|
1183
|
+
return;
|
|
1184
|
+
}
|
|
1185
|
+
const role = this.refreshDiscoveryAuthority(discovery!.claim);
|
|
1167
1186
|
this.noteDiscoveryRole(role);
|
|
1168
1187
|
if (role === "holder") {
|
|
1169
1188
|
this.discoverObservedTasks();
|
|
@@ -1286,15 +1305,9 @@ export class ObservedWaitHost {
|
|
|
1286
1305
|
* Acquire or confirm the one shared discovery claim. Process identity and
|
|
1287
1306
|
* explicit close evidence decide replacement; elapsed time is not a lease.
|
|
1288
1307
|
*/
|
|
1289
|
-
private refreshDiscoveryAuthority(): "holder" | "follower" {
|
|
1308
|
+
private refreshDiscoveryAuthority(claim: ReturnType<Store["readDiscoveryClaim"]>): "holder" | "follower" {
|
|
1290
1309
|
const store = this.store;
|
|
1291
1310
|
if (!store) return "follower";
|
|
1292
|
-
let claim;
|
|
1293
|
-
try {
|
|
1294
|
-
claim = store.readDiscoveryClaim(this.discoveryScope);
|
|
1295
|
-
} catch {
|
|
1296
|
-
return "follower";
|
|
1297
|
-
}
|
|
1298
1311
|
if (claim?.hostId === this.hostId) {
|
|
1299
1312
|
this.discoveryToken = claim.token;
|
|
1300
1313
|
return "holder";
|
|
@@ -1351,6 +1364,11 @@ export class ObservedWaitHost {
|
|
|
1351
1364
|
}
|
|
1352
1365
|
const owner = this.ownerFor(input.ctx);
|
|
1353
1366
|
const prepared = this.prepareLaunch(input.kind, input.params, "bg_task_spawn", owner, undefined);
|
|
1367
|
+
if (this.options.serverOwnedResults) {
|
|
1368
|
+
this.assertResultAdmission(prepared.provenance);
|
|
1369
|
+
const client = await this.resultSupervisionClient();
|
|
1370
|
+
client.close();
|
|
1371
|
+
}
|
|
1354
1372
|
const operationId = `op_${randomUUID()}`;
|
|
1355
1373
|
const token = `launch_${randomUUID()}`;
|
|
1356
1374
|
const taskId = supervisorTaskIdForToken(token);
|
|
@@ -1374,12 +1392,15 @@ export class ObservedWaitHost {
|
|
|
1374
1392
|
...(prepared.spec.argv ? { argv: [...prepared.spec.argv] } : {}),
|
|
1375
1393
|
cwd: prepared.cwd,
|
|
1376
1394
|
sandbox: prepared.provenance,
|
|
1395
|
+
supervisionPolicy: prepared.plan,
|
|
1377
1396
|
branchId: owner.branchId ?? null,
|
|
1378
1397
|
};
|
|
1379
1398
|
// Persist supervision metadata outside the task execution record so a
|
|
1380
1399
|
// replacement host can still notify the right parent and never re-route a
|
|
1381
1400
|
// worker-owned operation to the parent's callback.
|
|
1382
1401
|
this.writeLaunchContext(taskId, launchContext);
|
|
1402
|
+
this.launches.set(taskId, launchContext);
|
|
1403
|
+
if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!]);
|
|
1383
1404
|
const started = await this.startSupervisor({
|
|
1384
1405
|
token, taskId, kind: input.kind, params: input.params, prepared, operationId,
|
|
1385
1406
|
});
|
|
@@ -1502,7 +1523,8 @@ export class ObservedWaitHost {
|
|
|
1502
1523
|
authorizeCancellationForParent(ctx: ExtensionContext, taskId: string, requestId: string): string {
|
|
1503
1524
|
if (this.localCancels.has(taskId)) throw new Error("not_accepted: old cancellation admission is still draining");
|
|
1504
1525
|
const operation = this.ownedOperation(taskId, this.ownerFor(ctx));
|
|
1505
|
-
|
|
1526
|
+
const managed = this.requireStore().resultSupervision(operation.operationId);
|
|
1527
|
+
if (this.supervisionAuthority(operation) === "foreign" && !(managed?.launchToken === operation.launchToken && managed.hostId === operation.supervision?.hostId)) throw new Error("permission-unavailable: live legacy or unknown supervisor prevents cancellation handoff");
|
|
1506
1528
|
const proof = cancellationCredential();
|
|
1507
1529
|
const previous = this.requireStore().getTaskCancellation({ owner: operation.owner, idempotencyKey: requestId });
|
|
1508
1530
|
if (previous && previous.operationId !== operation.operationId) throw new Error("not_accepted: request-conflict: cancellation key belongs to another task");
|
|
@@ -1557,7 +1579,7 @@ export class ObservedWaitHost {
|
|
|
1557
1579
|
*/
|
|
1558
1580
|
listDurableTasks(
|
|
1559
1581
|
origin: BackgroundTaskCallbackOrigin,
|
|
1560
|
-
options: { retentionMs?: number; includeDismissed?: boolean } = {},
|
|
1582
|
+
options: { retentionMs?: number; includeDismissed?: boolean; fresh?: boolean } = {},
|
|
1561
1583
|
): DurableTaskProjection[] {
|
|
1562
1584
|
const store = this.store;
|
|
1563
1585
|
if (!store || this.closed) return [];
|
|
@@ -1567,7 +1589,7 @@ export class ObservedWaitHost {
|
|
|
1567
1589
|
const originKey = `${origin.cwd}\0${origin.sessionId}`;
|
|
1568
1590
|
const cacheKey = `${originKey}\0${options.retentionMs ?? ""}\0${options.includeDismissed === true ? 1 : 0}`;
|
|
1569
1591
|
const cached = this.durableProjectionCache;
|
|
1570
|
-
if (cached && cached.key === cacheKey && now >= cached.at && now - cached.at < DURABLE_PROJECTION_CACHE_MS) {
|
|
1592
|
+
if (!options.fresh && cached && cached.key === cacheKey && now >= cached.at && now - cached.at < DURABLE_PROJECTION_CACHE_MS) {
|
|
1571
1593
|
this.projectionMetrics.cacheHits += 1;
|
|
1572
1594
|
if (options.retentionMs === undefined) return cached.list;
|
|
1573
1595
|
const live = cached.list.filter((projection) => !this.expiredProjection(projection, options, now));
|
|
@@ -1933,6 +1955,124 @@ export class ObservedWaitHost {
|
|
|
1933
1955
|
return this.waitView(store.getWait({ waitId: result.wait.waitId }) ?? result.wait);
|
|
1934
1956
|
}
|
|
1935
1957
|
|
|
1958
|
+
private async resultSupervisionClient(): Promise<any> {
|
|
1959
|
+
const root = realpathSync(dirname(this.storePath));
|
|
1960
|
+
const ports = (globalThis as any)[Symbol.for("pi-better-server:result-supervision-ports-v1")];
|
|
1961
|
+
const port = ports?.get(root);
|
|
1962
|
+
if (port) return { request: async (type: string) => {
|
|
1963
|
+
if (type !== "runtime_result_supervision") throw new Error("not_accepted: unsupported in-process supervision operation");
|
|
1964
|
+
return port.status();
|
|
1965
|
+
}, close() {} };
|
|
1966
|
+
// @ts-expect-error Generated standalone lightweight socket client.
|
|
1967
|
+
const { WorkClient } = await import("./shared-work-client.mjs");
|
|
1968
|
+
const connect = async () => {
|
|
1969
|
+
const registration = JSON.parse(readFileSync(join(root, "server-registration-v1.json"), "utf8"));
|
|
1970
|
+
if (registration.version !== 1 || registration.agentDir !== root) throw new Error("Invalid canonical runtime registration");
|
|
1971
|
+
const connection = new WorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-result-supervision-v1"]);
|
|
1972
|
+
try { await connection.ready; return connection; }
|
|
1973
|
+
catch (error) { connection.close(); throw error; }
|
|
1974
|
+
};
|
|
1975
|
+
let client;
|
|
1976
|
+
try { client = await connect(); }
|
|
1977
|
+
catch (error) {
|
|
1978
|
+
if (!["ENOENT", "ECONNREFUSED"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error;
|
|
1979
|
+
// The packaged canonical client owns artifact verification, owner checks and startup.
|
|
1980
|
+
// @ts-expect-error Generated by sync-runtime-client during package preparation.
|
|
1981
|
+
const { ensureRuntime } = await import("../runtime-client/src/runtime/client.mjs");
|
|
1982
|
+
await ensureRuntime({ agentDir: root, serverDir: process.env.PI_SERVER_DIR });
|
|
1983
|
+
client = await connect();
|
|
1984
|
+
}
|
|
1985
|
+
return client;
|
|
1986
|
+
}
|
|
1987
|
+
|
|
1988
|
+
async refreshManagedResults(): Promise<void> {
|
|
1989
|
+
if (!this.options.serverOwnedResults || !this.store || this.closed) return;
|
|
1990
|
+
const client = await this.resultSupervisionClient();
|
|
1991
|
+
try { await client.request("runtime_result_supervision"); }
|
|
1992
|
+
finally { client.close(); }
|
|
1993
|
+
}
|
|
1994
|
+
|
|
1995
|
+
/** A runner may finish between the server pass and this session's inspection. */
|
|
1996
|
+
async settledStatusForParent(ctx: ExtensionContext, taskId: string): Promise<StatusView> {
|
|
1997
|
+
const observed = this.statusForParent(ctx, taskId);
|
|
1998
|
+
if (!this.options.serverOwnedResults || observed.terminalRevision > 0 || ["running", "starting"].includes(observed.status)) return observed;
|
|
1999
|
+
await this.refreshManagedResults();
|
|
2000
|
+
const imported = this.statusForParent(ctx, taskId);
|
|
2001
|
+
if (imported.terminalRevision === 0) throw new Error("Terminal runner evidence is awaiting authoritative server import; supervision is unavailable.");
|
|
2002
|
+
return imported;
|
|
2003
|
+
}
|
|
2004
|
+
|
|
2005
|
+
private assertResultAdmission(captured: TaskSandboxProvenance, transferring: ReadonlySet<string> = new Set()): void {
|
|
2006
|
+
const discovery = this.requireStore().readDiscoveryClaim(this.discoveryScope);
|
|
2007
|
+
if (discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
|
|
2008
|
+
throw new Error("permission-unavailable: live or unknown original discovery holder prevents scope handoff");
|
|
2009
|
+
}
|
|
2010
|
+
if (captured.policySource !== "no-publisher" && !currentForegroundSandboxPolicy(this.pi)) {
|
|
2011
|
+
throw new Error("permission-unavailable: expected current Background permission source is unavailable");
|
|
2012
|
+
}
|
|
2013
|
+
for (const operation of this.requireStore().listOperations({ phase: "running" })) {
|
|
2014
|
+
if (!existsSync(this.sidecarPath(operation.taskId)) || this.requireStore().resultSupervision(operation.operationId)) continue;
|
|
2015
|
+
// A compatible peer may be between registration and its grant transaction.
|
|
2016
|
+
// It cannot start a runner until that grant commits and never discovers globally.
|
|
2017
|
+
if (operation.supervision?.resultAdapter === 1) continue;
|
|
2018
|
+
if (this.supervisionAuthority(operation) === "foreign") {
|
|
2019
|
+
throw new Error("permission-unavailable: a live or unknown legacy operation holder prevents scope handoff");
|
|
2020
|
+
}
|
|
2021
|
+
// A dead holder is not itself a grant. Fencing discovery for a different
|
|
2022
|
+
// task would strand this runner: the server only imports explicit grants.
|
|
2023
|
+
if (!transferring.has(operation.operationId)) {
|
|
2024
|
+
throw new Error("permission-unavailable: an untransferred legacy operation prevents scope handoff; explicitly supervise its wait first");
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
|
|
2029
|
+
private async handoffResults(operations: readonly OperationRecord[]): Promise<void> {
|
|
2030
|
+
const client = await this.resultSupervisionClient();
|
|
2031
|
+
try {
|
|
2032
|
+
const manager = await client.request("runtime_result_supervision");
|
|
2033
|
+
const discovery = this.requireStore().readDiscoveryClaim(this.discoveryScope);
|
|
2034
|
+
if (discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
|
|
2035
|
+
throw new Error("permission-unavailable: live or unknown original discovery holder prevents scope handoff");
|
|
2036
|
+
}
|
|
2037
|
+
const transfers = [];
|
|
2038
|
+
const transferring = new Set(operations.map(operation => operation.operationId));
|
|
2039
|
+
for (const operation of operations) {
|
|
2040
|
+
if (this.requireStore().resultSupervision(operation.operationId)) continue;
|
|
2041
|
+
if (this.supervisionAuthority(operation) === "foreign" || this.localCancels.has(operation.taskId)) {
|
|
2042
|
+
throw new Error("permission-unavailable: original supervision owner is live, unknown or draining");
|
|
2043
|
+
}
|
|
2044
|
+
const context = this.launchContext(operation.taskId);
|
|
2045
|
+
if (!context?.sandbox || !context.supervisionPolicy || !operation.authorityRef) throw new Error("permission-unavailable: captured Background authority is unavailable");
|
|
2046
|
+
this.assertResultAdmission(context.sandbox, transferring);
|
|
2047
|
+
const current = currentForegroundSandboxPolicy(this.pi);
|
|
2048
|
+
if (context.sandbox.policySource !== "no-publisher" && !current) throw new Error("permission-unavailable: expected current Background permission source is unavailable");
|
|
2049
|
+
transfers.push({ operationId: operation.operationId,
|
|
2050
|
+
expectedHostId: operation.supervision?.hostId ?? "unavailable", directory: this.directory, hostId: manager.hostId, epoch: manager.epoch,
|
|
2051
|
+
capability: { adapter: "background-results-v1", captured: { provenance: context.sandbox, policy: context.supervisionPolicy }, current: current ?? { state: "legacy-unconfined", policySource: "no-publisher" } } });
|
|
2052
|
+
}
|
|
2053
|
+
// Validate the whole batch, then stop admission before the durable CAS.
|
|
2054
|
+
for (const transfer of transfers) this.resultHandoffs.add(transfer.operationId);
|
|
2055
|
+
try {
|
|
2056
|
+
this.requireStore().handoffResultScope({ scope: this.discoveryScope,
|
|
2057
|
+
expectedDiscovery: discovery ? { hostId: discovery.hostId, token: discovery.token } : null, grants: transfers });
|
|
2058
|
+
this.discoveryToken = undefined;
|
|
2059
|
+
this.discoveryRole = "follower";
|
|
2060
|
+
} catch (error) {
|
|
2061
|
+
// The transaction rolled back; only these uncommitted local fences may reopen.
|
|
2062
|
+
for (const transfer of transfers) this.resultHandoffs.delete(transfer.operationId);
|
|
2063
|
+
throw error;
|
|
2064
|
+
}
|
|
2065
|
+
await client.request("runtime_result_supervision");
|
|
2066
|
+
} finally { client.close(); }
|
|
2067
|
+
}
|
|
2068
|
+
|
|
2069
|
+
async superviseParentWait(ctx: ExtensionContext, taskIds: readonly string[], note: string): Promise<WaitView> {
|
|
2070
|
+
this.noteParentContext(ctx);
|
|
2071
|
+
const operations = this.operationsForTaskIds(this.ownerFor(ctx), taskIds);
|
|
2072
|
+
await this.handoffResults(operations);
|
|
2073
|
+
return this.waitForParent(ctx, taskIds, note);
|
|
2074
|
+
}
|
|
2075
|
+
|
|
1936
2076
|
waitViewForParent(ctx: ExtensionContext, waitId: string, generation?: number): WaitView | undefined {
|
|
1937
2077
|
const store = this.requireStore();
|
|
1938
2078
|
const wait = store.getWait({ waitId, ...(generation ? { generation } : {}) });
|
|
@@ -1973,6 +2113,10 @@ export class ObservedWaitHost {
|
|
|
1973
2113
|
const store = this.requireStore();
|
|
1974
2114
|
if (input.params.ssh) throw new Error("Worker background launches are local-only; structured SSH is unavailable through this service.");
|
|
1975
2115
|
const owner = this.workerOwner(run);
|
|
2116
|
+
if (this.options.serverOwnedResults) {
|
|
2117
|
+
const client = await this.resultSupervisionClient();
|
|
2118
|
+
client.close();
|
|
2119
|
+
}
|
|
1976
2120
|
const prepared = this.prepareLaunch(
|
|
1977
2121
|
input.kind,
|
|
1978
2122
|
input.params,
|
|
@@ -1981,6 +2125,7 @@ export class ObservedWaitHost {
|
|
|
1981
2125
|
input.policy,
|
|
1982
2126
|
run.workspace,
|
|
1983
2127
|
);
|
|
2128
|
+
if (this.options.serverOwnedResults) this.assertResultAdmission(prepared.provenance);
|
|
1984
2129
|
const operationId = `op_${randomUUID()}`;
|
|
1985
2130
|
const token = `launch_${randomUUID()}`;
|
|
1986
2131
|
const taskId = supervisorTaskIdForToken(token);
|
|
@@ -2004,9 +2149,12 @@ export class ObservedWaitHost {
|
|
|
2004
2149
|
...(prepared.spec.argv ? { argv: [...prepared.spec.argv] } : {}),
|
|
2005
2150
|
cwd: prepared.cwd,
|
|
2006
2151
|
sandbox: prepared.provenance,
|
|
2152
|
+
supervisionPolicy: prepared.plan,
|
|
2007
2153
|
branchId: owner.branchId ?? null,
|
|
2008
2154
|
};
|
|
2009
2155
|
this.writeLaunchContext(taskId, launchContext);
|
|
2156
|
+
this.launches.set(taskId, launchContext);
|
|
2157
|
+
if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!]);
|
|
2010
2158
|
const started = await this.startSupervisor({
|
|
2011
2159
|
token, taskId, kind: input.kind, params: input.params, prepared, operationId,
|
|
2012
2160
|
});
|
|
@@ -2913,6 +3061,8 @@ export class ObservedWaitHost {
|
|
|
2913
3061
|
|
|
2914
3062
|
private reconcileOperation(operation: OperationRecord): void {
|
|
2915
3063
|
if (operation.terminalRevision > 0) return;
|
|
3064
|
+
if (this.resultHandoffs.has(operation.operationId) || (operation.resultManaged ?? !!this.store?.resultSupervision(operation.operationId))) return;
|
|
3065
|
+
if (this.options.serverOwnedResults) return;
|
|
2916
3066
|
const authority = this.supervisionAuthority(operation);
|
|
2917
3067
|
if (authority === "foreign") return;
|
|
2918
3068
|
let claimed = false;
|
|
@@ -3078,6 +3228,8 @@ export class ObservedWaitHost {
|
|
|
3078
3228
|
}
|
|
3079
3229
|
|
|
3080
3230
|
private recordTerminal(operation: OperationRecord, inspection: SupervisorInspection): void {
|
|
3231
|
+
if (this.options.serverOwnedResults) return;
|
|
3232
|
+
if (this.resultHandoffs.has(operation.operationId) || this.store?.resultSupervision(operation.operationId)) return;
|
|
3081
3233
|
const store = this.requireStore();
|
|
3082
3234
|
const status = inspection.status;
|
|
3083
3235
|
const outcome = terminalOutcome(status);
|
|
@@ -3925,6 +4077,7 @@ export class ObservedWaitHost {
|
|
|
3925
4077
|
hostId: this.hostId,
|
|
3926
4078
|
storeOpen: !!this.store,
|
|
3927
4079
|
closed: this.closed,
|
|
4080
|
+
managementMode: this.options.serverOwnedResults ? "server-client" : "legacy",
|
|
3928
4081
|
activeContext: !!ctx,
|
|
3929
4082
|
activeSessionId: ctx ? this.sessionIdIfAvailable(ctx) ?? this.sessionId(ctx) : undefined,
|
|
3930
4083
|
activeCwd: ctx ? ctx.cwd : undefined,
|
|
@@ -3974,6 +4127,8 @@ export class ObservedWaitHost {
|
|
|
3974
4127
|
...(typeof value.cwd === "string" ? { cwd: value.cwd } : {}),
|
|
3975
4128
|
...(value.sandbox && typeof value.sandbox === "object" && !Array.isArray(value.sandbox)
|
|
3976
4129
|
? { sandbox: value.sandbox as TaskSandboxProvenance } : {}),
|
|
4130
|
+
...(value.supervisionPolicy && typeof value.supervisionPolicy === "object"
|
|
4131
|
+
? { supervisionPolicy: value.supervisionPolicy } : {}),
|
|
3977
4132
|
...(typeof value.branchId === "string" || value.branchId === null ? { branchId: value.branchId } : {}),
|
|
3978
4133
|
...(typeof value.callbackPendingAt === "number" ? { callbackPendingAt: value.callbackPendingAt } : {}),
|
|
3979
4134
|
...(typeof value.callbackDeliveredAt === "number" ? { callbackDeliveredAt: value.callbackDeliveredAt }
|
|
@@ -4065,7 +4220,8 @@ export class ObservedWaitHost {
|
|
|
4065
4220
|
}
|
|
4066
4221
|
|
|
4067
4222
|
private supervision(): SupervisionIdentity {
|
|
4068
|
-
return { hostId: this.hostId, runnerId: null, processStartToken: null
|
|
4223
|
+
return { hostId: this.hostId, runnerId: null, processStartToken: null, resultScope: this.discoveryScope,
|
|
4224
|
+
...(this.options.serverOwnedResults ? { resultAdapter: 1 as const } : {}) };
|
|
4069
4225
|
}
|
|
4070
4226
|
|
|
4071
4227
|
private parentAuthority(owner: OwnerIdentity, plan: ForegroundSandboxPlan): string {
|
|
@@ -47,6 +47,7 @@ export function readAssignmentWaits(path, owner, connection) {
|
|
|
47
47
|
export function createAssignmentReader(path) {
|
|
48
48
|
let db;
|
|
49
49
|
let identity;
|
|
50
|
+
let snapshot = false;
|
|
50
51
|
const statements = new Map();
|
|
51
52
|
return {
|
|
52
53
|
revision() {
|
|
@@ -54,6 +55,7 @@ export function createAssignmentReader(path) {
|
|
|
54
55
|
const stat = statSync(path, { bigint: true });
|
|
55
56
|
const next = `${stat.dev}:${stat.ino}`;
|
|
56
57
|
if (identity !== next) {
|
|
58
|
+
if (snapshot) throw new Error("Coordinator identity changed during observation");
|
|
57
59
|
db?.close();
|
|
58
60
|
db = undefined;
|
|
59
61
|
statements.clear();
|
|
@@ -63,6 +65,21 @@ export function createAssignmentReader(path) {
|
|
|
63
65
|
db ??= new DatabaseSync(path, { readOnly: true });
|
|
64
66
|
return `${identity}:${db.prepare("PRAGMA data_version").get().data_version}`;
|
|
65
67
|
},
|
|
68
|
+
beginSnapshot() {
|
|
69
|
+
this.revision();
|
|
70
|
+
if (snapshot) throw new Error("Coordinator snapshot already open");
|
|
71
|
+
db.exec("BEGIN");
|
|
72
|
+
snapshot = true;
|
|
73
|
+
const release = () => {
|
|
74
|
+
if (!snapshot) return;
|
|
75
|
+
try { db.exec("ROLLBACK"); } finally { snapshot = false; }
|
|
76
|
+
};
|
|
77
|
+
try {
|
|
78
|
+
// Pin the WAL read view before recording its revision; other writers keep advancing.
|
|
79
|
+
db.prepare("SELECT count(*) FROM sqlite_schema").get();
|
|
80
|
+
return { revision: this.revision(), release };
|
|
81
|
+
} catch (error) { release(); throw error; }
|
|
82
|
+
},
|
|
66
83
|
read(owner) {
|
|
67
84
|
try {
|
|
68
85
|
this.revision();
|
|
@@ -98,6 +115,6 @@ export function createAssignmentReader(path) {
|
|
|
98
115
|
return new Map([...hashes].map(([key, hash]) => [key, hash.digest("hex")]));
|
|
99
116
|
} catch { return undefined; }
|
|
100
117
|
},
|
|
101
|
-
close() { db?.close(); db = undefined; statements.clear(); identity = undefined; },
|
|
118
|
+
close() { if (snapshot) { db.exec("ROLLBACK"); snapshot = false; } db?.close(); db = undefined; statements.clear(); identity = undefined; },
|
|
102
119
|
};
|
|
103
120
|
}
|
|
@@ -48,6 +48,14 @@ export function readDiscoveryClaim(ctx: StoreContext, scope: unknown): Discovery
|
|
|
48
48
|
return readClaim(ctx, requireId("scope", scope));
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
+
/** Read scope transfer and its discovery claim from one SQLite snapshot. */
|
|
52
|
+
export function readDiscoveryState(ctx: StoreContext, scope: string): { managed: boolean; claim: DiscoveryClaimRecord | null } {
|
|
53
|
+
scope = requireId("scope", scope);
|
|
54
|
+
const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed
|
|
55
|
+
FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, scope)!;
|
|
56
|
+
return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row) };
|
|
57
|
+
}
|
|
58
|
+
|
|
51
59
|
export function tryClaimDiscovery(
|
|
52
60
|
ctx: StoreContext,
|
|
53
61
|
input: TryClaimDiscoveryInput,
|
|
@@ -62,6 +70,7 @@ export function tryClaimDiscovery(
|
|
|
62
70
|
const expectedToken = input.expected === null ? null : requireId("expected.token", input.expected.token);
|
|
63
71
|
|
|
64
72
|
return ctx.transaction(() => {
|
|
73
|
+
if (getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", "result-scope-v1:" + scope)) return null;
|
|
65
74
|
const current = readClaim(ctx, scope);
|
|
66
75
|
if (input.expected === null) {
|
|
67
76
|
if (current) return null;
|
|
@@ -63,6 +63,8 @@ function normalizeSupervision(value: unknown): SupervisionIdentity | null {
|
|
|
63
63
|
const supervision = value as Partial<SupervisionIdentity>;
|
|
64
64
|
return {
|
|
65
65
|
hostId: requireId("supervision.hostId", supervision.hostId),
|
|
66
|
+
...(supervision.resultScope === undefined ? {} : { resultScope: requireId("supervision.resultScope", supervision.resultScope) }),
|
|
67
|
+
...(supervision.resultAdapter === 1 ? { resultAdapter: 1 as const } : {}),
|
|
66
68
|
runnerId: supervision.runnerId === undefined || supervision.runnerId === null
|
|
67
69
|
? null
|
|
68
70
|
: requireId("supervision.runnerId", supervision.runnerId),
|
|
@@ -433,8 +435,8 @@ export function listOperations(
|
|
|
433
435
|
params.push(requireId("taskId", filter.taskId));
|
|
434
436
|
}
|
|
435
437
|
const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
|
|
436
|
-
return getRows(ctx, `SELECT
|
|
437
|
-
.map(mapOperation);
|
|
438
|
+
return getRows(ctx, `SELECT *, EXISTS(SELECT 1 FROM coordinator_state s WHERE s.key = 'result-supervision-v1:' || operations.operation_id) AS result_managed FROM operations ${where} ORDER BY created_at, operation_id`, ...params)
|
|
439
|
+
.map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
|
|
438
440
|
}
|
|
439
441
|
|
|
440
442
|
/** Running operations assigned to one supervising host, using the phase/host index. */
|
|
@@ -444,9 +446,9 @@ export function listRunningSupervisedBy(
|
|
|
444
446
|
): OperationRecord[] {
|
|
445
447
|
return getRows(
|
|
446
448
|
ctx,
|
|
447
|
-
"SELECT
|
|
449
|
+
"SELECT *, EXISTS(SELECT 1 FROM coordinator_state s WHERE s.key = 'result-supervision-v1:' || operations.operation_id) AS result_managed FROM operations WHERE phase = 'running' AND supervision_host_id = ? ORDER BY created_at, operation_id",
|
|
448
450
|
requireId("hostId", hostId),
|
|
449
|
-
).map(mapOperation);
|
|
451
|
+
).map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
|
|
450
452
|
}
|
|
451
453
|
|
|
452
454
|
function listOutboxForRevision(
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// Generated from packages/operation-coordinator/src/result-supervision.ts. Do not edit directly.
|
|
2
|
+
import { isDeepStrictEqual } from "node:util";
|
|
3
|
+
import { getRow, run, type StoreContext } from "./sqlite.ts";
|
|
4
|
+
import { getOperation, recordSupervision, recordTerminalOutcome } from "./operations.ts";
|
|
5
|
+
import { requireId, requirePath } from "./validate.ts";
|
|
6
|
+
import type { RecordTerminalOutcomeInput } from "./types.ts";
|
|
7
|
+
import type { OwnerIdentity } from "./types.ts";
|
|
8
|
+
|
|
9
|
+
const PREFIX = "result-supervision-v1:";
|
|
10
|
+
export interface ResultSupervision {
|
|
11
|
+
operationId: string;
|
|
12
|
+
directory: string;
|
|
13
|
+
launchToken: string;
|
|
14
|
+
authorityRef: string | null;
|
|
15
|
+
hostId: string;
|
|
16
|
+
epoch: string;
|
|
17
|
+
owner: OwnerIdentity;
|
|
18
|
+
capability?: { adapter: string; captured: unknown; current: unknown };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function resultSupervisions(ctx: StoreContext, activeOnly = false): ResultSupervision[] {
|
|
22
|
+
const rows = activeOnly
|
|
23
|
+
? ctx.db.prepare("SELECT s.value FROM operations o JOIN coordinator_state s ON s.key = ? || o.operation_id WHERE o.phase = 'running'").all(PREFIX)
|
|
24
|
+
: ctx.db.prepare("SELECT value FROM coordinator_state WHERE key LIKE ?").all(`${PREFIX}%`);
|
|
25
|
+
return rows
|
|
26
|
+
.map(row => JSON.parse(String(row.value)));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function resultSupervision(ctx: StoreContext, operationId: string): ResultSupervision | null {
|
|
30
|
+
const row = getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", PREFIX + requireId("operationId", operationId));
|
|
31
|
+
return row ? JSON.parse(String(row.value)) : null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The admitting host has stopped its local route before this exact-owner CAS. */
|
|
35
|
+
export function handoffResultSupervision(ctx: StoreContext, input: {
|
|
36
|
+
operationId: string; expectedHostId: string; directory: string; hostId: string; epoch: string;
|
|
37
|
+
capability?: ResultSupervision["capability"];
|
|
38
|
+
}): ResultSupervision {
|
|
39
|
+
const operationId = requireId("operationId", input.operationId);
|
|
40
|
+
const hostId = requireId("hostId", input.hostId);
|
|
41
|
+
const epoch = requireId("epoch", input.epoch);
|
|
42
|
+
const directory = requirePath("directory", input.directory);
|
|
43
|
+
return ctx.transaction(() => {
|
|
44
|
+
const previous = resultSupervision(ctx, operationId);
|
|
45
|
+
if (previous) {
|
|
46
|
+
if (previous.directory !== directory || previous.hostId !== hostId || previous.epoch !== epoch
|
|
47
|
+
|| !isDeepStrictEqual(previous.capability, input.capability)) {
|
|
48
|
+
throw new Error("supervision-conflict: repeated handoff changed destination or captured authority");
|
|
49
|
+
}
|
|
50
|
+
return previous;
|
|
51
|
+
}
|
|
52
|
+
const operation = getOperation(ctx, operationId);
|
|
53
|
+
if (!operation || operation.supervision?.hostId !== input.expectedHostId) throw new Error("permission-unavailable: exact supervision owner changed");
|
|
54
|
+
const grant = { operationId, directory, hostId, epoch, launchToken: operation.launchToken,
|
|
55
|
+
authorityRef: operation.authorityRef, owner: operation.owner, ...(input.capability ? { capability: input.capability } : {}) };
|
|
56
|
+
recordSupervision(ctx, { operationId, owner: operation.owner, expectedHostId: input.expectedHostId,
|
|
57
|
+
supervision: { hostId }, health: "active" });
|
|
58
|
+
run(ctx, "INSERT INTO coordinator_state (key, value) VALUES (?, ?)", PREFIX + operationId, JSON.stringify(grant));
|
|
59
|
+
return grant;
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** A wait's dependency set transfers together, or none of it does. */
|
|
64
|
+
export function handoffResultSupervisions(ctx: StoreContext, inputs: Parameters<typeof handoffResultSupervision>[1][]): ResultSupervision[] {
|
|
65
|
+
return ctx.transaction(() => inputs.map(input => handoffResultSupervision(ctx, input)));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function resultScopeManaged(ctx: StoreContext, scope: string): boolean {
|
|
69
|
+
return !!getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", "result-scope-v1:" + requireId("scope", scope));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function handoffResultScope(ctx: StoreContext, input: {
|
|
73
|
+
scope: string;
|
|
74
|
+
expectedDiscovery: { hostId: string; token: string } | null;
|
|
75
|
+
grants: Parameters<typeof handoffResultSupervision>[1][];
|
|
76
|
+
}): ResultSupervision[] {
|
|
77
|
+
return ctx.transaction(() => {
|
|
78
|
+
const claim = getRow(ctx, "SELECT host_id, token FROM discovery_claims WHERE scope = ?", requireId("scope", input.scope));
|
|
79
|
+
if (claim ? !input.expectedDiscovery || claim.host_id !== input.expectedDiscovery.hostId || claim.token !== input.expectedDiscovery.token : input.expectedDiscovery !== null) {
|
|
80
|
+
throw new Error("supervision-conflict: discovery owner changed during handoff");
|
|
81
|
+
}
|
|
82
|
+
const grants = handoffResultSupervisions(ctx, input.grants);
|
|
83
|
+
// Registration precedes sidecar creation. Check durable records inside
|
|
84
|
+
// this transaction, including old records whose scope is unknown.
|
|
85
|
+
const stranded = getRow(ctx, `SELECT operation_id FROM operations o
|
|
86
|
+
WHERE phase = 'running' AND observer_kind = 'local-supervisor'
|
|
87
|
+
AND COALESCE(json_extract(supervision_json, '$.resultAdapter'), 0) != 1
|
|
88
|
+
AND (json_extract(supervision_json, '$.resultScope') IS NULL
|
|
89
|
+
OR json_extract(supervision_json, '$.resultScope') = ?)
|
|
90
|
+
AND NOT EXISTS (SELECT 1 FROM coordinator_state s WHERE s.key = ? || o.operation_id)
|
|
91
|
+
LIMIT 1`, input.scope, PREFIX);
|
|
92
|
+
if (stranded) throw new Error("permission-unavailable: untransferred legacy operation prevents scope handoff");
|
|
93
|
+
run(ctx, "DELETE FROM discovery_claims WHERE scope = ?", input.scope);
|
|
94
|
+
run(ctx, "INSERT OR IGNORE INTO coordinator_state (key, value) VALUES (?, 'managed')", "result-scope-v1:" + input.scope);
|
|
95
|
+
return grants;
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Called by the singleton server after proving the preceding server has exited. */
|
|
100
|
+
export function recoverResultSupervision(ctx: StoreContext, input: ResultSupervision): void {
|
|
101
|
+
ctx.transaction(() => {
|
|
102
|
+
const previous = resultSupervision(ctx, input.operationId);
|
|
103
|
+
if (!previous || previous.launchToken !== input.launchToken || previous.directory !== input.directory
|
|
104
|
+
|| previous.authorityRef !== input.authorityRef || JSON.stringify(previous.owner) !== JSON.stringify(input.owner)
|
|
105
|
+
|| JSON.stringify(previous.capability) !== JSON.stringify(input.capability)) {
|
|
106
|
+
throw new Error("supervision-conflict: execution or captured authority changed");
|
|
107
|
+
}
|
|
108
|
+
const operation = getOperation(ctx, input.operationId)!;
|
|
109
|
+
if (operation.terminalRevision > 0) return;
|
|
110
|
+
recordSupervision(ctx, { operationId: input.operationId, owner: operation.owner,
|
|
111
|
+
expectedHostId: previous.hostId, supervision: { hostId: input.hostId }, health: "active" });
|
|
112
|
+
run(ctx, "UPDATE coordinator_state SET value = ? WHERE key = ?", JSON.stringify(input), PREFIX + input.operationId);
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function publishSupervisedResult(ctx: StoreContext, input: {
|
|
117
|
+
operationId: string; epoch: string; publication: RecordTerminalOutcomeInput;
|
|
118
|
+
}) {
|
|
119
|
+
return ctx.transaction(() => {
|
|
120
|
+
const grant = resultSupervision(ctx, input.operationId);
|
|
121
|
+
const operation = getOperation(ctx, input.operationId);
|
|
122
|
+
if (!grant || grant.epoch !== input.epoch || operation?.supervision?.hostId !== grant.hostId
|
|
123
|
+
|| operation.launchToken !== grant.launchToken || input.publication.operationId !== input.operationId) {
|
|
124
|
+
throw new Error("stale-runtime-epoch: result supervision changed");
|
|
125
|
+
}
|
|
126
|
+
return recordTerminalOutcome(ctx, input.publication);
|
|
127
|
+
});
|
|
128
|
+
}
|
|
@@ -18,6 +18,18 @@ import { SCHEMA_VERSION } from "./types.ts";
|
|
|
18
18
|
import { StoreError } from "./errors.ts";
|
|
19
19
|
import { columnText, getRow, getRows, run, type StoreContext } from "./sqlite.ts";
|
|
20
20
|
|
|
21
|
+
// Enforce the handoff even for an older process still using its bundled store.
|
|
22
|
+
// Unknown legacy scopes conservatively conflict with any managed root scope.
|
|
23
|
+
const RESULT_ADMISSION_FENCE = `CREATE TRIGGER IF NOT EXISTS result_scope_admission_v1
|
|
24
|
+
BEFORE INSERT ON operations
|
|
25
|
+
WHEN NEW.observer_kind = 'local-supervisor'
|
|
26
|
+
AND COALESCE(json_extract(NEW.supervision_json, '$.resultAdapter'), 0) != 1
|
|
27
|
+
AND EXISTS (SELECT 1 FROM coordinator_state
|
|
28
|
+
WHERE key LIKE 'result-scope-v1:%'
|
|
29
|
+
AND (json_extract(NEW.supervision_json, '$.resultScope') IS NULL
|
|
30
|
+
OR key = 'result-scope-v1:' || json_extract(NEW.supervision_json, '$.resultScope')))
|
|
31
|
+
BEGIN SELECT RAISE(ABORT, 'permission-unavailable: legacy launch into managed result scope'); END`;
|
|
32
|
+
|
|
21
33
|
const DDL: readonly string[] = [
|
|
22
34
|
`CREATE TABLE task_cancellation_authorities (
|
|
23
35
|
credential_hash TEXT PRIMARY KEY,
|
|
@@ -238,6 +250,7 @@ const DDL: readonly string[] = [
|
|
|
238
250
|
generation INTEGER NOT NULL,
|
|
239
251
|
PRIMARY KEY (wait_id, generation)
|
|
240
252
|
)`,
|
|
253
|
+
RESULT_ADMISSION_FENCE,
|
|
241
254
|
];
|
|
242
255
|
|
|
243
256
|
const SCHEMA_VERSION_KEY = "schema_version";
|
|
@@ -294,6 +307,7 @@ export function ensureSchema(ctx: StoreContext): void {
|
|
|
294
307
|
if (recorded < SCHEMA_VERSION) {
|
|
295
308
|
if (recorded === 3) {
|
|
296
309
|
ctx.transaction(() => {
|
|
310
|
+
ensureAdditiveSchema(ctx);
|
|
297
311
|
ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE assignment_repairs"))!);
|
|
298
312
|
run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
|
|
299
313
|
});
|
|
@@ -340,7 +354,10 @@ function ensureAdditiveSchema(ctx: StoreContext): void {
|
|
|
340
354
|
&& hasTable("task_cancellation_requests")
|
|
341
355
|
&& hasTable("task_cancellation_authorities")
|
|
342
356
|
&& getRows(ctx, "PRAGMA table_info(task_cancellation_requests)").some(row => row.name === "result_json")
|
|
343
|
-
)
|
|
357
|
+
) {
|
|
358
|
+
ctx.db.exec(RESULT_ADMISSION_FENCE);
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
344
361
|
|
|
345
362
|
ctx.transaction(() => {
|
|
346
363
|
ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE task_cancellation_requests"))!.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS"));
|
|
@@ -366,6 +383,7 @@ function ensureAdditiveSchema(ctx: StoreContext): void {
|
|
|
366
383
|
key TEXT PRIMARY KEY,
|
|
367
384
|
value TEXT NOT NULL
|
|
368
385
|
)`);
|
|
386
|
+
ctx.db.exec(RESULT_ADMISSION_FENCE);
|
|
369
387
|
});
|
|
370
388
|
}
|
|
371
389
|
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* and leaves no partial record.
|
|
9
9
|
*/
|
|
10
10
|
import { StoreError } from "./errors.ts";
|
|
11
|
+
import { resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
|
|
11
12
|
import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.ts";
|
|
12
13
|
import type { TaskCancellationIntent, TaskCancellationRequest } from "./task-cancellation.ts";
|
|
13
14
|
import { repairFailedResume, type RepairResumeInput } from "./recovery.ts";
|
|
@@ -34,6 +35,7 @@ import {
|
|
|
34
35
|
import {
|
|
35
36
|
getChangeRevision as readChangeRevision,
|
|
36
37
|
readDiscoveryClaim as readClaim,
|
|
38
|
+
readDiscoveryState,
|
|
37
39
|
releaseDiscoveryClaim as deleteDiscoveryClaim,
|
|
38
40
|
tryClaimDiscovery as writeDiscoveryClaim,
|
|
39
41
|
} from "./discovery.ts";
|
|
@@ -118,6 +120,14 @@ import {
|
|
|
118
120
|
} from "./types.ts";
|
|
119
121
|
|
|
120
122
|
export interface Store {
|
|
123
|
+
resultScopeManaged(scope: string): boolean;
|
|
124
|
+
handoffResultScope(input: Parameters<typeof handoffResultScope>[1]): ReturnType<typeof handoffResultScope>;
|
|
125
|
+
resultSupervision(operationId: string): ReturnType<typeof resultSupervision>;
|
|
126
|
+
resultSupervisions(activeOnly?: boolean): ReturnType<typeof resultSupervisions>;
|
|
127
|
+
handoffResultSupervision(input: Parameters<typeof handoffResultSupervision>[1]): ReturnType<typeof handoffResultSupervision>;
|
|
128
|
+
handoffResultSupervisions(input: Parameters<typeof handoffResultSupervisions>[1]): ReturnType<typeof handoffResultSupervisions>;
|
|
129
|
+
recoverResultSupervision(input: Parameters<typeof recoverResultSupervision>[1]): void;
|
|
130
|
+
publishSupervisedResult(input: Parameters<typeof publishSupervisedResult>[1]): ReturnType<typeof publishSupervisedResult>;
|
|
121
131
|
unknownTaskCancellation(input: TaskCancellationRequest): TaskCancellationIntent;
|
|
122
132
|
taskCancellationManaged(operationId: string): boolean;
|
|
123
133
|
pendingTaskCancellations(): ReturnType<typeof pendingTaskCancellations>;
|
|
@@ -183,6 +193,7 @@ export interface Store {
|
|
|
183
193
|
|
|
184
194
|
/** The shared discovery leader for this store/supervisor scope, if recorded. */
|
|
185
195
|
readDiscoveryClaim(scope: string): DiscoveryClaimRecord | null;
|
|
196
|
+
readDiscoveryState(scope: string): ReturnType<typeof readDiscoveryState>;
|
|
186
197
|
/**
|
|
187
198
|
* Compare-and-swap a discovery claim. The caller must name the exact claim it
|
|
188
199
|
* observed, or null for none; a stale contender receives null and must not
|
|
@@ -325,6 +336,14 @@ export function openStore(options: StoreOptions): Store {
|
|
|
325
336
|
};
|
|
326
337
|
|
|
327
338
|
const store: Store = {
|
|
339
|
+
resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
|
|
340
|
+
handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
|
|
341
|
+
resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
|
|
342
|
+
resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
|
|
343
|
+
handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
|
|
344
|
+
handoffResultSupervisions(input) { alive(); return handoffResultSupervisions(ctx, input); },
|
|
345
|
+
recoverResultSupervision(input) { alive(); recoverResultSupervision(ctx, input); },
|
|
346
|
+
publishSupervisedResult(input) { alive(); return publishSupervisedResult(ctx, input); },
|
|
328
347
|
unknownTaskCancellation(input) { alive(); return unknownTaskCancellation(ctx, input); },
|
|
329
348
|
taskCancellationManaged(operationId) { alive(); return taskCancellationManaged(ctx, operationId); },
|
|
330
349
|
pendingTaskCancellations() { alive(); return pendingTaskCancellations(ctx); },
|
|
@@ -383,6 +402,7 @@ export function openStore(options: StoreOptions): Store {
|
|
|
383
402
|
terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision),
|
|
384
403
|
);
|
|
385
404
|
},
|
|
405
|
+
readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
|
|
386
406
|
readDiscoveryClaim(scope) {
|
|
387
407
|
alive();
|
|
388
408
|
return readClaim(ctx, scope);
|
|
@@ -83,6 +83,10 @@ export interface ObserverIdentity {
|
|
|
83
83
|
* (a replacement host takes over on reload) while launch identity is not.
|
|
84
84
|
*/
|
|
85
85
|
export interface SupervisionIdentity {
|
|
86
|
+
/** Durable discovery scope, recorded before sidecar creation or runner start. */
|
|
87
|
+
resultScope?: string;
|
|
88
|
+
/** The host uses grant-before-runner result admission and performs no global discovery. */
|
|
89
|
+
resultAdapter?: 1;
|
|
86
90
|
/** Host that owns supervision, e.g. the Pi process id plus a start token. */
|
|
87
91
|
hostId: string;
|
|
88
92
|
/** Runner process identity, when a separate runner owns the operation. */
|
|
@@ -112,6 +116,8 @@ export interface RegisterOperationInput {
|
|
|
112
116
|
}
|
|
113
117
|
|
|
114
118
|
export interface OperationRecord {
|
|
119
|
+
/** Grant presence in the same snapshot as a bulk operation read. */
|
|
120
|
+
resultManaged?: boolean;
|
|
115
121
|
operationId: string;
|
|
116
122
|
taskId: string;
|
|
117
123
|
launchToken: string;
|
|
@@ -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/tools.ts
CHANGED
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
getObservedWaitHost,
|
|
23
23
|
observedWaitServiceUnavailableReason,
|
|
24
24
|
type DurableTaskKind,
|
|
25
|
+
type DurableLaunch,
|
|
25
26
|
type WaitView,
|
|
26
27
|
} from "./observed-waits.js";
|
|
27
28
|
import { backgroundObservation } from "./work-observation.js";
|
|
@@ -348,13 +349,15 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
|
|
|
348
349
|
promptGuidelines: BACKGROUND_ORCHESTRATION_GUIDELINES,
|
|
349
350
|
parameters: SpawnParams,
|
|
350
351
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
351
|
-
|
|
352
|
-
|
|
352
|
+
const origin = getCallbackOrigin(ctx);
|
|
353
|
+
activeSession = origin;
|
|
354
|
+
let receipt: DurableLaunch | undefined;
|
|
355
|
+
const durable = await durableLaunchText(pi, "process", params, ctx, launch => { receipt = launch; });
|
|
353
356
|
if (durable !== undefined) {
|
|
354
357
|
refreshNavigator(ctx);
|
|
355
|
-
return text(durable);
|
|
358
|
+
return text(durable, launchReceipt(receipt));
|
|
356
359
|
}
|
|
357
|
-
const launched = reportLaunch(() => spawnTask(pi, params, ctx.cwd,
|
|
360
|
+
const launched = reportLaunch(() => spawnTask(pi, params, ctx.cwd, origin, getActiveSession));
|
|
358
361
|
refreshNavigator(ctx);
|
|
359
362
|
return text(launched);
|
|
360
363
|
},
|
|
@@ -381,13 +384,15 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
|
|
|
381
384
|
promptGuidelines: BACKGROUND_ORCHESTRATION_GUIDELINES,
|
|
382
385
|
parameters: WatchParams,
|
|
383
386
|
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
384
|
-
|
|
385
|
-
|
|
387
|
+
const origin = getCallbackOrigin(ctx);
|
|
388
|
+
activeSession = origin;
|
|
389
|
+
let receipt: DurableLaunch | undefined;
|
|
390
|
+
const durable = await durableLaunchText(pi, "watch", params, ctx, launch => { receipt = launch; });
|
|
386
391
|
if (durable !== undefined) {
|
|
387
392
|
refreshNavigator(ctx);
|
|
388
|
-
return text(durable);
|
|
393
|
+
return text(durable, launchReceipt(receipt));
|
|
389
394
|
}
|
|
390
|
-
const launched = await launchWatch(pi, params, ctx.cwd,
|
|
395
|
+
const launched = await launchWatch(pi, params, ctx.cwd, origin, getActiveSession, FIRST_WATCH_CHECK_WAIT_MS, signal, runtime);
|
|
391
396
|
refreshNavigator(ctx);
|
|
392
397
|
return text(launched);
|
|
393
398
|
},
|
|
@@ -410,10 +415,11 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
|
|
|
410
415
|
description: "Inspect one background task. Default output is a compact model-facing summary (1 KiB UTF-8) with matched condition, exit/signal, stop error, and failure counts before progress. Current-session only unless all:true; unknown ownership is a gap, not missing or healthy. Pass verbose:true only when full raw metadata is explicitly needed. Environment values are omitted. A raw log nextCursor passed as cursor continues the raw log page; an incidentCursor pages incidents that need action; history:true lists failure history too. After a terminal callback, call this first and call bg_task_log only if the summary is insufficient.",
|
|
411
416
|
parameters: StatusParams,
|
|
412
417
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
413
|
-
|
|
414
|
-
|
|
418
|
+
const origin = getCallbackOrigin(ctx);
|
|
419
|
+
activeSession = origin;
|
|
420
|
+
const durable = await durableStatusText(pi, params.id, ctx);
|
|
415
421
|
if (durable !== undefined) return text(durable);
|
|
416
|
-
return text(taskStatus(pi, params.id, params, statusOptions(params,
|
|
422
|
+
return text(taskStatus(pi, params.id, params, statusOptions(params, origin)));
|
|
417
423
|
},
|
|
418
424
|
});
|
|
419
425
|
|
|
@@ -426,10 +432,11 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
|
|
|
426
432
|
return renderBackgroundTaskLogDisplay(result, options, theme);
|
|
427
433
|
},
|
|
428
434
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
429
|
-
|
|
430
|
-
|
|
435
|
+
const origin = getCallbackOrigin(ctx);
|
|
436
|
+
activeSession = origin;
|
|
437
|
+
const durable = await durableLogText(pi, params.id, params, ctx);
|
|
431
438
|
if (durable !== undefined) return text(durable);
|
|
432
|
-
return logText(params.id, logOptions(params,
|
|
439
|
+
return logText(params.id, logOptions(params, origin));
|
|
433
440
|
},
|
|
434
441
|
});
|
|
435
442
|
|
|
@@ -439,13 +446,14 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
|
|
|
439
446
|
description: "Cancel a watcher or terminate a background task. Only a task owned by the current session stops; a foreign-session or unverifiable task is refused unless all:true. For a tmux-backed SSH task, stop kills its remote tmux session before marking it cancelled. Direct SSH stop only tears down the local client and may leave the remote process running.",
|
|
440
447
|
parameters: Type.Object({ ...IdParams.properties, request_id: Type.Optional(Type.String({ description: "Stable cancellation request identity. Reuse this value after a disconnect." })) }),
|
|
441
448
|
async execute(toolCallId, params, _signal, _onUpdate, ctx) {
|
|
442
|
-
|
|
449
|
+
const origin = getCallbackOrigin(ctx);
|
|
450
|
+
activeSession = origin;
|
|
443
451
|
const durable = await durableStopText(pi, params.id, ctx, params.request_id ?? toolCallId);
|
|
444
452
|
if (durable !== undefined) {
|
|
445
453
|
refreshNavigator(ctx);
|
|
446
454
|
return text(durable);
|
|
447
455
|
}
|
|
448
|
-
const result = await formatStop(pi, params.id, ctx, getActiveSession, statusOptions(params,
|
|
456
|
+
const result = await formatStop(pi, params.id, ctx, getActiveSession, statusOptions(params, origin), runtime);
|
|
449
457
|
refreshNavigator(ctx);
|
|
450
458
|
return text(result);
|
|
451
459
|
},
|
|
@@ -496,7 +504,9 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
|
|
|
496
504
|
?? "Observed waits are unavailable in this session; inspect tasks directly and continue without a durable wait.");
|
|
497
505
|
}
|
|
498
506
|
try {
|
|
499
|
-
const wait = host.
|
|
507
|
+
const wait = host.usesServerResults
|
|
508
|
+
? await host.superviseParentWait(ctx, params.task_ids, params.continuation_note)
|
|
509
|
+
: host.waitForParent(ctx, params.task_ids, params.continuation_note);
|
|
500
510
|
return text(formatWaitView(wait), wait);
|
|
501
511
|
} catch (error) {
|
|
502
512
|
return text(`Wait was not registered: ${readableError(error)}`);
|
|
@@ -592,6 +602,11 @@ export function text(textValue: string, details?: unknown) {
|
|
|
592
602
|
return { content: [{ type: "text" as const, text: textValue }], details };
|
|
593
603
|
}
|
|
594
604
|
|
|
605
|
+
function launchReceipt(launch?: DurableLaunch) {
|
|
606
|
+
return launch ? { id: launch.id, operationId: launch.operationId, kind: launch.kind,
|
|
607
|
+
owner: launch.owner, started: launch.started, claimed: launch.claimed } : undefined;
|
|
608
|
+
}
|
|
609
|
+
|
|
595
610
|
/** Requested byte budget: canonical `max_bytes`, else the deprecated `maxBytes` alias (#321). */
|
|
596
611
|
function requestedMaxBytes(params: Record<string, unknown>): number | undefined {
|
|
597
612
|
const value = readOutputControls(params).maxBytes;
|
|
@@ -657,11 +672,13 @@ async function actionText(
|
|
|
657
672
|
refreshNavigator: typeof refreshBackgroundTasksNavigator,
|
|
658
673
|
) {
|
|
659
674
|
if (params.action === "log" && params.id) {
|
|
660
|
-
const durable = durableLogText(pi, String(params.id), params, ctx);
|
|
675
|
+
const durable = await durableLogText(pi, String(params.id), params, ctx);
|
|
661
676
|
if (durable !== undefined) return text(durable);
|
|
662
677
|
return logText(String(params.id), logOptions(params, callbackOrigin));
|
|
663
678
|
}
|
|
664
|
-
|
|
679
|
+
let receipt: DurableLaunch | undefined;
|
|
680
|
+
return text(await runAction(pi, params, ctx, callbackOrigin, getActiveSession, signal, runtime, refreshNavigator,
|
|
681
|
+
launch => { receipt = launch; }), launchReceipt(receipt));
|
|
665
682
|
}
|
|
666
683
|
|
|
667
684
|
async function runAction(
|
|
@@ -673,18 +690,19 @@ async function runAction(
|
|
|
673
690
|
signal: AbortSignal | undefined,
|
|
674
691
|
runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime>,
|
|
675
692
|
refreshNavigator: typeof refreshBackgroundTasksNavigator,
|
|
693
|
+
onLaunch?: (launch: DurableLaunch) => void,
|
|
676
694
|
): Promise<string> {
|
|
677
695
|
const { spawnTask } = runtime;
|
|
678
696
|
const withNavigatorRefresh = (ctx: ExtensionContext, result: string) => { refreshNavigator(ctx); return result; };
|
|
679
697
|
switch (params.action) {
|
|
680
698
|
case "spawn": {
|
|
681
|
-
const durable = await durableLaunchText(pi, "process", params, ctx);
|
|
699
|
+
const durable = await durableLaunchText(pi, "process", params, ctx, onLaunch);
|
|
682
700
|
if (durable !== undefined) return withNavigatorRefresh(ctx, durable);
|
|
683
701
|
return withNavigatorRefresh(ctx, reportLaunch(() => spawnTask(pi, params, ctx.cwd, callbackOrigin, getActiveSession)));
|
|
684
702
|
}
|
|
685
703
|
case "watch": {
|
|
686
704
|
if (!params.success_when) return "Invalid parameters: watch requires success_when.";
|
|
687
|
-
const durable = await durableLaunchText(pi, "watch", params, ctx);
|
|
705
|
+
const durable = await durableLaunchText(pi, "watch", params, ctx, onLaunch);
|
|
688
706
|
if (durable !== undefined) return withNavigatorRefresh(ctx, durable);
|
|
689
707
|
return withNavigatorRefresh(ctx, await launchWatch(pi, params as unknown as WatchTaskParams, ctx.cwd, callbackOrigin, getActiveSession, FIRST_WATCH_CHECK_WAIT_MS, signal, runtime));
|
|
690
708
|
}
|
|
@@ -692,13 +710,13 @@ async function runAction(
|
|
|
692
710
|
return durableAwareList(pi, params, callbackOrigin, ctx);
|
|
693
711
|
case "status": {
|
|
694
712
|
if (!params.id) return "Invalid parameters: status requires id.";
|
|
695
|
-
const durable = durableStatusText(pi, String(params.id), ctx);
|
|
713
|
+
const durable = await durableStatusText(pi, String(params.id), ctx);
|
|
696
714
|
if (durable !== undefined) return durable;
|
|
697
715
|
return taskStatus(pi, String(params.id), params, statusOptions(params, callbackOrigin));
|
|
698
716
|
}
|
|
699
717
|
case "log": {
|
|
700
718
|
if (!params.id) return "Invalid parameters: log requires id.";
|
|
701
|
-
const durable = durableLogText(pi, String(params.id), params, ctx);
|
|
719
|
+
const durable = await durableLogText(pi, String(params.id), params, ctx);
|
|
702
720
|
if (durable !== undefined) return durable;
|
|
703
721
|
return formatLog(String(params.id), logOptions(params, callbackOrigin));
|
|
704
722
|
}
|
|
@@ -710,6 +728,7 @@ async function runAction(
|
|
|
710
728
|
}
|
|
711
729
|
case "clear": {
|
|
712
730
|
const host = getObservedWaitHost(pi);
|
|
731
|
+
await host?.refreshManagedResults();
|
|
713
732
|
const durableId = typeof params.id === "string" && params.id && host?.isDurableTask(params.id) === true;
|
|
714
733
|
if (durableId) {
|
|
715
734
|
return withNavigatorRefresh(ctx, dismissDurableForClear(pi, params, callbackOrigin)
|
|
@@ -776,13 +795,13 @@ function dismissDurableForClear(
|
|
|
776
795
|
if (!host.isDurableTask(id)) return undefined;
|
|
777
796
|
const task = host.readDurableTask(origin, id);
|
|
778
797
|
if (!task) return `Durable operation ${id} belongs to another session; it was not dismissed.`;
|
|
779
|
-
if (!task.terminal) return `Durable operation ${id} is ${task.status}; stop it before dismissing it.`;
|
|
780
798
|
const dismissed = host.dismissDurableTask(origin, id);
|
|
799
|
+
if (!dismissed && !task.terminal) return `Durable operation ${id} is ${task.status}; stop it before dismissing it.`;
|
|
781
800
|
return dismissed
|
|
782
801
|
? `Dismissed durable operation ${id}. Its terminal evidence remains available through bg_task_status and bg_task_log.`
|
|
783
802
|
: `Durable operation ${id} was not dismissed.`;
|
|
784
803
|
}
|
|
785
|
-
const terminal = host.listDurableTasks(origin).filter((task) => task.terminal);
|
|
804
|
+
const terminal = host.listDurableTasks(origin, { fresh: true }).filter((task) => task.terminal);
|
|
786
805
|
let dismissed = 0;
|
|
787
806
|
for (const task of terminal) if (host.dismissDurableTask(origin, task.id)) dismissed += 1;
|
|
788
807
|
return dismissed > 0
|
|
@@ -796,9 +815,10 @@ function readableError(error: unknown): string {
|
|
|
796
815
|
|
|
797
816
|
/**
|
|
798
817
|
* Route a local launch through the durable supervisor when the observed-waits
|
|
799
|
-
* host is
|
|
800
|
-
* an extension
|
|
801
|
-
*
|
|
818
|
+
* host is installed. `undefined` means "use the legacy task route": remote/SSH
|
|
819
|
+
* work, an extension without the durable host, or a session not yet activated.
|
|
820
|
+
* A failed activation is never permission to start a second legacy command.
|
|
821
|
+
* Admission and sandboxing happen inside the host, through the
|
|
802
822
|
* same `resolve*SandboxPlan` helpers the legacy route uses.
|
|
803
823
|
*/
|
|
804
824
|
async function durableLaunchText(
|
|
@@ -806,11 +826,13 @@ async function durableLaunchText(
|
|
|
806
826
|
kind: DurableTaskKind,
|
|
807
827
|
params: Record<string, unknown>,
|
|
808
828
|
ctx: ExtensionContext,
|
|
829
|
+
onLaunch?: (launch: DurableLaunch) => void,
|
|
809
830
|
): Promise<string | undefined> {
|
|
810
831
|
const host = getObservedWaitHost(pi);
|
|
811
|
-
if (!host
|
|
832
|
+
if (!host || params.ssh || !host.available && !host.hasActivated) return undefined;
|
|
812
833
|
try {
|
|
813
834
|
const launched = await host.launchParent({ kind, params, ctx });
|
|
835
|
+
onLaunch?.(launched);
|
|
814
836
|
return host.formatLaunch(launched);
|
|
815
837
|
} catch (error) {
|
|
816
838
|
if (error instanceof ForegroundSandboxBlockedError) return error.message;
|
|
@@ -818,25 +840,26 @@ async function durableLaunchText(
|
|
|
818
840
|
}
|
|
819
841
|
}
|
|
820
842
|
|
|
821
|
-
function durableStatusText(pi: ExtensionAPI, id: string, ctx: ExtensionContext): string | undefined {
|
|
843
|
+
async function durableStatusText(pi: ExtensionAPI, id: string, ctx: ExtensionContext): Promise<string | undefined> {
|
|
822
844
|
const host = getObservedWaitHost(pi);
|
|
823
|
-
if (!host
|
|
845
|
+
if (!host || !host.isDurableTask(id)) return undefined;
|
|
824
846
|
try {
|
|
825
|
-
return host.formatStatus(host.
|
|
847
|
+
return host.formatStatus(await host.settledStatusForParent(ctx, id));
|
|
826
848
|
} catch (error) {
|
|
827
849
|
return readableError(error);
|
|
828
850
|
}
|
|
829
851
|
}
|
|
830
852
|
|
|
831
|
-
function durableLogText(
|
|
853
|
+
async function durableLogText(
|
|
832
854
|
pi: ExtensionAPI,
|
|
833
855
|
id: string,
|
|
834
856
|
params: Record<string, unknown>,
|
|
835
857
|
ctx: ExtensionContext,
|
|
836
|
-
): string | undefined {
|
|
858
|
+
): Promise<string | undefined> {
|
|
837
859
|
const host = getObservedWaitHost(pi);
|
|
838
|
-
if (!host
|
|
860
|
+
if (!host || !host.isDurableTask(id)) return undefined;
|
|
839
861
|
try {
|
|
862
|
+
await host.settledStatusForParent(ctx, id);
|
|
840
863
|
const requested = typeof params.lines === "number" ? params.lines
|
|
841
864
|
: typeof params.tail_lines === "number" ? params.tail_lines : 40;
|
|
842
865
|
// `lines: 0` means the retained raw log on the legacy route; the durable
|
|
@@ -850,7 +873,7 @@ function durableLogText(
|
|
|
850
873
|
|
|
851
874
|
async function durableStopText(pi: ExtensionAPI, id: string, ctx: ExtensionContext, requestId?: string): Promise<string | undefined> {
|
|
852
875
|
const host = getObservedWaitHost(pi);
|
|
853
|
-
if (!host
|
|
876
|
+
if (!host || !host.isDurableTask(id)) return undefined;
|
|
854
877
|
try {
|
|
855
878
|
const status = host.formatStatus(await host.stopForParent(ctx, id, requestId));
|
|
856
879
|
return requestId ? `Cancellation request: ${requestId}\n${status}` : status;
|