pi-better-background-tasks 0.17.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/package.json +4 -2
- package/runtime-client/artifacts/darwin-arm64.gz +0 -0
- package/runtime-client/artifacts/darwin-arm64.json +1 -1
- package/runtime-client/artifacts/darwin-x64.gz +0 -0
- package/runtime-client/artifacts/darwin-x64.json +1 -1
- package/runtime-client/artifacts/linux-arm64.gz +0 -0
- package/runtime-client/artifacts/linux-arm64.json +1 -1
- package/runtime-client/artifacts/linux-x64.gz +0 -0
- package/runtime-client/artifacts/linux-x64.json +1 -1
- package/runtime-client/src/runtime/client.mjs +30 -3
- package/runtime-client/src/runtime/work-client.mjs +150 -7
- package/src/adapter-contract.ts +1 -1
- package/src/failures.ts +4 -2
- package/src/goal-provider.ts +31 -16
- package/src/index.ts +9 -37
- package/src/managed-authority.ts +30 -0
- package/src/managed-client.ts +73 -0
- package/src/managed-frontend.ts +176 -0
- package/src/navigator-provider.ts +28 -10
- package/src/observed-wait-client.ts +10 -0
- package/src/observed-waits.ts +268 -62
- package/src/output.ts +12 -0
- package/src/process-identity.ts +18 -2
- package/src/process.ts +3 -3
- package/src/registry.ts +71 -6
- package/src/runtime.ts +26 -10
- package/src/sandbox.ts +21 -11
- package/src/shared-callback-batcher.ts +15 -3
- package/src/shared-failure-observations.ts +3 -0
- package/src/shared-navigator-panels.ts +26 -4
- package/src/shared-navigator.ts +220 -19
- package/src/shared-operation-coordinator/assignment-observation.mjs +71 -33
- package/src/shared-operation-coordinator/index.ts +2 -0
- package/src/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/src/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/src/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
- package/src/shared-operation-coordinator/src/background-requests.ts +90 -0
- package/src/shared-operation-coordinator/src/discovery.ts +5 -3
- package/src/shared-operation-coordinator/src/operations.ts +50 -2
- package/src/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/src/shared-operation-coordinator/src/rows.ts +2 -0
- package/src/shared-operation-coordinator/src/schema.ts +71 -24
- package/src/shared-operation-coordinator/src/store.ts +50 -6
- package/src/shared-operation-coordinator/src/subagent-launch.ts +142 -0
- package/src/shared-operation-coordinator/src/types.ts +5 -1
- package/src/shared-operation-coordinator/src/upgrade.ts +22 -0
- package/src/shared-sandbox-core.ts +1 -1
- package/src/shared-work-client.mjs +150 -7
- package/src/supervisor/generated/process-identity.mjs +20 -2
- package/src/supervisor/generated/process.mjs +3 -3
- package/src/task-diagnostics.ts +1 -1
- package/src/tools.ts +60 -41
- package/src/types.ts +3 -1
- package/src/work-observation.ts +46 -19
package/src/observed-waits.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { getObservedWaitHost, registerObservedWaitClient } from "./observed-wait-client.js";
|
|
2
|
+
export { getObservedWaitHost, registerObservedWaitClient } from "./observed-wait-client.js";
|
|
1
3
|
/**
|
|
2
4
|
* Parent-side observed waits: the integration between background tasks, the
|
|
3
5
|
* detached local supervisor and the durable operation coordinator.
|
|
@@ -21,7 +23,7 @@
|
|
|
21
23
|
*/
|
|
22
24
|
|
|
23
25
|
import { createHash, randomUUID } from "node:crypto";
|
|
24
|
-
import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, statSync, writeFileSync } from "node:fs";
|
|
26
|
+
import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, watch, type FSWatcher } from "node:fs";
|
|
25
27
|
import { homedir } from "node:os";
|
|
26
28
|
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
27
29
|
|
|
@@ -71,6 +73,8 @@ import {
|
|
|
71
73
|
type SupervisorStartOptions,
|
|
72
74
|
type SupervisorTaskStatus,
|
|
73
75
|
} from "./supervisor/index.js";
|
|
76
|
+
import { processGroupAlive } from "./supervisor/identity.js";
|
|
77
|
+
import { readStopRequest } from "./supervisor/store.js";
|
|
74
78
|
import type { BackgroundTaskCallbackOrigin, CommandSpec, Condition, TaskSandboxProvenance } from "./types.js";
|
|
75
79
|
import type { SpawnTaskParams, WatchTaskParams } from "./runtime.js";
|
|
76
80
|
|
|
@@ -148,6 +152,7 @@ export interface DurableProjectionMetrics {
|
|
|
148
152
|
export interface DurableTaskChange {
|
|
149
153
|
readonly sessionId: string;
|
|
150
154
|
readonly workspace: string;
|
|
155
|
+
readonly branchId?: string | null;
|
|
151
156
|
}
|
|
152
157
|
|
|
153
158
|
/** A parent launch is always local; remote launches stay on the legacy task route. */
|
|
@@ -215,6 +220,7 @@ export interface WaitEvidenceView {
|
|
|
215
220
|
export interface WaitDispatchEvent {
|
|
216
221
|
readonly waitId: string;
|
|
217
222
|
readonly generation: number;
|
|
223
|
+
readonly parkedAttemptId?: string;
|
|
218
224
|
readonly owner: OwnerIdentity;
|
|
219
225
|
/** Parent session origin captured when the supervised task launched. */
|
|
220
226
|
readonly parentOrigin?: BackgroundTaskCallbackOrigin;
|
|
@@ -256,6 +262,7 @@ export interface ParentNotification {
|
|
|
256
262
|
* `notifyParent` is not delivery.
|
|
257
263
|
*/
|
|
258
264
|
export interface ParentDelivery {
|
|
265
|
+
readonly receiptId?: string;
|
|
259
266
|
delivered(): void;
|
|
260
267
|
defer(reason: string): void;
|
|
261
268
|
}
|
|
@@ -264,6 +271,7 @@ export type ParentNotifier = (notification: ParentNotification, delivery: Parent
|
|
|
264
271
|
|
|
265
272
|
export interface WorkerRunScope {
|
|
266
273
|
readonly runId: string;
|
|
274
|
+
readonly assignmentAttemptId?: string;
|
|
267
275
|
readonly conversationId: string;
|
|
268
276
|
readonly workspace: string;
|
|
269
277
|
readonly authorityReference: string;
|
|
@@ -273,6 +281,7 @@ export interface WorkerRunScope {
|
|
|
273
281
|
|
|
274
282
|
interface RpcRunBinding {
|
|
275
283
|
readonly runId: string;
|
|
284
|
+
readonly assignmentTaskOwnership: boolean;
|
|
276
285
|
readonly conversationId: string;
|
|
277
286
|
readonly attemptId: string;
|
|
278
287
|
readonly workspace: string;
|
|
@@ -413,6 +422,9 @@ export interface StatusView {
|
|
|
413
422
|
|
|
414
423
|
/** Read-only projection of one supervised durable task for list/navigator/Goal. */
|
|
415
424
|
export interface DurableTaskProjection {
|
|
425
|
+
readonly parentAgentId?: string;
|
|
426
|
+
readonly parentRecipient?: { sessionId: string; workspace: string; branchId?: string | null };
|
|
427
|
+
readonly readOnly?: boolean;
|
|
416
428
|
readonly id: string;
|
|
417
429
|
readonly operationId: string;
|
|
418
430
|
readonly kind: DurableTaskKind;
|
|
@@ -442,7 +454,7 @@ export interface DurableTaskProjection {
|
|
|
442
454
|
readonly logPaths: { stdout: string; stderr: string; events: string };
|
|
443
455
|
readonly waits: readonly WaitView[];
|
|
444
456
|
readonly sandbox?: TaskSandboxProvenance;
|
|
445
|
-
readonly owner: { sessionId: string; workspace: string };
|
|
457
|
+
readonly owner: { sessionId: string; workspace: string; branchId?: string | null };
|
|
446
458
|
}
|
|
447
459
|
|
|
448
460
|
export interface DurableTaskLogView {
|
|
@@ -557,6 +569,16 @@ function rpcCode(error: unknown): string {
|
|
|
557
569
|
}
|
|
558
570
|
|
|
559
571
|
export interface ObservedWaitHostOptions {
|
|
572
|
+
/** Fixed server admission guard, checked immediately before external dispatch. */
|
|
573
|
+
assertAdmission?: () => void;
|
|
574
|
+
/** Fixed native adapter alone may authorize an explicit cross-owner stop. */
|
|
575
|
+
authorizeParentCancellation?: (input: { requester: OwnerIdentity; operation: OperationRecord; requestId: string }) => { requestId: string; reason: string };
|
|
576
|
+
prepareWorkerPolicy?: (run: WorkerRunScope) => (() => void);
|
|
577
|
+
beforeParentOperation?: (operation: { operationId: string; taskId: string; token: string }) => void;
|
|
578
|
+
/** Runtime-owned coordinator handle. The caller retains its lifetime lease. */
|
|
579
|
+
sharedStore?: Store;
|
|
580
|
+
enterControl?: () => (() => void) | undefined;
|
|
581
|
+
verificationMs?: number;
|
|
560
582
|
/** Production adapters leave global discovery and terminal import to the server. */
|
|
561
583
|
serverOwnedResults?: boolean;
|
|
562
584
|
/** SQLite path. Defaults under the Pi agent directory. */
|
|
@@ -636,21 +658,16 @@ export function observedWaitServiceUnavailableReason(pi: unknown): string | unde
|
|
|
636
658
|
return events ? serviceErrors.get(events) : undefined;
|
|
637
659
|
}
|
|
638
660
|
|
|
639
|
-
const hosts = new WeakMap<object, ObservedWaitHost>();
|
|
640
|
-
|
|
641
661
|
export function createObservedWaitHost(pi: ExtensionAPI, options: ObservedWaitHostOptions = {}): ObservedWaitHost {
|
|
642
|
-
const existing =
|
|
662
|
+
const existing = getObservedWaitHost(pi);
|
|
643
663
|
if (existing && existing !== undefined) existing.close();
|
|
644
664
|
const host = new ObservedWaitHost(pi, options);
|
|
645
|
-
|
|
665
|
+
registerObservedWaitClient(pi, host);
|
|
646
666
|
return host;
|
|
647
667
|
}
|
|
648
668
|
|
|
649
|
-
export function getObservedWaitHost(pi: unknown): ObservedWaitHost | undefined {
|
|
650
|
-
return pi && typeof pi === "object" ? hosts.get(pi as object) : undefined;
|
|
651
|
-
}
|
|
652
|
-
|
|
653
669
|
interface LaunchContext {
|
|
670
|
+
readonly workerAttemptId?: string;
|
|
654
671
|
readonly kind: DurableTaskKind;
|
|
655
672
|
readonly parentOrigin?: BackgroundTaskCallbackOrigin;
|
|
656
673
|
readonly gated: boolean;
|
|
@@ -864,6 +881,43 @@ export class ObservedWaitHost {
|
|
|
864
881
|
private readonly pollMs: number;
|
|
865
882
|
private readonly options: ObservedWaitHostOptions;
|
|
866
883
|
private timer?: NodeJS.Timeout;
|
|
884
|
+
private changeWatcher?: FSWatcher;
|
|
885
|
+
private changeRepair?: NodeJS.Timeout;
|
|
886
|
+
private changePosition?: { generation: string; seq: number };
|
|
887
|
+
private changeScheduled = false;
|
|
888
|
+
private managedDirty = false;
|
|
889
|
+
private managedAfter = 0;
|
|
890
|
+
private observeManagedChanges() {
|
|
891
|
+
const schedule = () => {
|
|
892
|
+
if (this.closed || this.changeScheduled) return;
|
|
893
|
+
this.changeScheduled = true;
|
|
894
|
+
setImmediate(() => {
|
|
895
|
+
this.changeScheduled = false;
|
|
896
|
+
if (this.closed || !this.store) return;
|
|
897
|
+
try {
|
|
898
|
+
const page = this.store.resultSupervisionChanges(this.changePosition);
|
|
899
|
+
const changed = page.reset || page.seq !== this.changePosition?.seq;
|
|
900
|
+
this.changePosition = { generation: page.generation, seq: page.seq };
|
|
901
|
+
this.managedDirty ||= changed;
|
|
902
|
+
if (this.managedDirty && Date.now() >= this.managedAfter) {
|
|
903
|
+
this.managedDirty = false; this.managedAfter = Date.now() + 1000;
|
|
904
|
+
void this.reconcileNow();
|
|
905
|
+
}
|
|
906
|
+
if (page.more) schedule();
|
|
907
|
+
} catch { /* Existing authority remains unchanged; the bounded feed repair retries. */ }
|
|
908
|
+
});
|
|
909
|
+
};
|
|
910
|
+
this.changeWatcher = watch(dirname(this.storePath), (_event, file) => {
|
|
911
|
+
if (!file || String(file).startsWith("operation-coordinator.sqlite")) schedule();
|
|
912
|
+
});
|
|
913
|
+
this.changeWatcher.on("error", () => { this.changeWatcher?.close(); this.changeWatcher = undefined; });
|
|
914
|
+
const repair = () => {
|
|
915
|
+
if (this.closed) return;
|
|
916
|
+
schedule();
|
|
917
|
+
this.changeRepair = setTimeout(repair, 1000); this.changeRepair.unref();
|
|
918
|
+
};
|
|
919
|
+
repair();
|
|
920
|
+
}
|
|
867
921
|
private closed = false;
|
|
868
922
|
private activationAttempted = false;
|
|
869
923
|
private unavailableReason?: string;
|
|
@@ -901,6 +955,7 @@ export class ObservedWaitHost {
|
|
|
901
955
|
private continuationError?: string;
|
|
902
956
|
private readonly launches = new Map<string, LaunchContext>();
|
|
903
957
|
private readonly localCancels = new Set<string>();
|
|
958
|
+
private assignmentCleanupCursor?: string;
|
|
904
959
|
private readonly resultHandoffs = new Set<string>();
|
|
905
960
|
private readonly rpcRuns = new Map<string, RpcRunBinding>();
|
|
906
961
|
private readonly waitOwners = new Map<string, OwnerIdentity>();
|
|
@@ -915,10 +970,31 @@ export class ObservedWaitHost {
|
|
|
915
970
|
private discoveryToken?: string;
|
|
916
971
|
private discoveryRole?: "holder" | "follower";
|
|
917
972
|
private reconcileInFlight?: Promise<void>;
|
|
973
|
+
private reconcileScope?: object;
|
|
918
974
|
private authorityPassCache?: Map<string, "live" | "dead" | "unknown">;
|
|
919
975
|
/** Running operations this follower is currently assigned to supervise. */
|
|
920
976
|
private readonly followerRunningTasks = new Set<string>();
|
|
921
|
-
private
|
|
977
|
+
private readonly unscopedCallbackRecovery = { revision: -1, branch: "", delivery: undefined as string | undefined, claims: undefined as string | undefined };
|
|
978
|
+
private readonly callbackRecoveryScopes = new Map<string, { revision: number; delivery?: string; claims?: string; branch: string }>();
|
|
979
|
+
private recoveryScopeState() {
|
|
980
|
+
if (!this.activeOrigin) return this.unscopedCallbackRecovery;
|
|
981
|
+
// Concurrent foregrounds can retain different branch snapshots of one session.
|
|
982
|
+
const key = JSON.stringify([this.activeOrigin.cwd, this.activeOrigin.sessionId, branchIdsOf(this.activeContext!)]);
|
|
983
|
+
let state = this.callbackRecoveryScopes.get(key);
|
|
984
|
+
if (!state) {
|
|
985
|
+
if (this.callbackRecoveryScopes.size >= 128) this.callbackRecoveryScopes.delete(this.callbackRecoveryScopes.keys().next().value!);
|
|
986
|
+
state = { revision: -1, branch: "" }; this.callbackRecoveryScopes.set(key, state);
|
|
987
|
+
}
|
|
988
|
+
return state;
|
|
989
|
+
}
|
|
990
|
+
private get lastChangeRevision() { return this.recoveryScopeState().revision; }
|
|
991
|
+
private set lastChangeRevision(value: number) { this.recoveryScopeState().revision = value; }
|
|
992
|
+
private get pendingCallbackCursor() { return this.recoveryScopeState().delivery; }
|
|
993
|
+
private set pendingCallbackCursor(value: string | undefined) { this.recoveryScopeState().delivery = value; }
|
|
994
|
+
private get pendingClaimCursor() { return this.recoveryScopeState().claims; }
|
|
995
|
+
private set pendingClaimCursor(value: string | undefined) { this.recoveryScopeState().claims = value; }
|
|
996
|
+
private get activeBranchSignature() { return this.recoveryScopeState().branch; }
|
|
997
|
+
private set activeBranchSignature(value: string) { this.recoveryScopeState().branch = value; }
|
|
922
998
|
private lastOwnedTerminalAt = 0;
|
|
923
999
|
|
|
924
1000
|
constructor(private readonly pi: ExtensionAPI, options: ObservedWaitHostOptions = {}) {
|
|
@@ -981,6 +1057,16 @@ export class ObservedWaitHost {
|
|
|
981
1057
|
get usesServerResults(): boolean { return this.options.serverOwnedResults === true; }
|
|
982
1058
|
get hasActivated(): boolean { return this.activationAttempted; }
|
|
983
1059
|
|
|
1060
|
+
/** Ready worker continuations can advance; held decisions and unread results cannot. */
|
|
1061
|
+
advancingWaits() {
|
|
1062
|
+
if (!this.store || !this.continuation) return [];
|
|
1063
|
+
return this.store.listWaits({ phase: ["ready", "resuming"], pendingOnly: true })
|
|
1064
|
+
.filter(wait => wait.owner.kind === "worker-conversation")
|
|
1065
|
+
.map(wait => ({ kind: "advancing-wait", id: wait.waitId, generation: wait.generation, owner: wait.owner,
|
|
1066
|
+
lastProgressAt: wait.updatedAt, nextDeadline: wait.updatedAt + (this.options.verificationMs ?? 30000), recovery: "captured-worker-continuation" }))
|
|
1067
|
+
.filter(wait => wait.nextDeadline > Date.now());
|
|
1068
|
+
}
|
|
1069
|
+
|
|
984
1070
|
get reason(): string | undefined {
|
|
985
1071
|
return this.unavailableReason;
|
|
986
1072
|
}
|
|
@@ -1003,7 +1089,7 @@ export class ObservedWaitHost {
|
|
|
1003
1089
|
this.closed = false;
|
|
1004
1090
|
this.unavailableReason = undefined;
|
|
1005
1091
|
try {
|
|
1006
|
-
this.store = openStore({
|
|
1092
|
+
this.store = this.options.sharedStore ?? openStore({
|
|
1007
1093
|
path: this.storePath,
|
|
1008
1094
|
...(this.options.now ? { now: this.options.now } : {}),
|
|
1009
1095
|
});
|
|
@@ -1023,7 +1109,9 @@ export class ObservedWaitHost {
|
|
|
1023
1109
|
void this.reconcileNow();
|
|
1024
1110
|
this.recoverTerminalNotifications();
|
|
1025
1111
|
this.terminalRecoveryNeeded = false;
|
|
1026
|
-
if (this.
|
|
1112
|
+
if (this.options.serverOwnedResults && this.options.sharedStore) {
|
|
1113
|
+
this.observeManagedChanges();
|
|
1114
|
+
} else if (this.pollMs > 0) {
|
|
1027
1115
|
this.timer = setInterval(() => { void this.reconcileNow(); }, this.pollMs);
|
|
1028
1116
|
this.timer.unref?.();
|
|
1029
1117
|
}
|
|
@@ -1034,10 +1122,13 @@ export class ObservedWaitHost {
|
|
|
1034
1122
|
this.closed = true;
|
|
1035
1123
|
HOST_INSTANCE_STATE.closed.add(this.hostId);
|
|
1036
1124
|
if (this.timer) clearInterval(this.timer);
|
|
1125
|
+
this.changeWatcher?.close(); this.changeWatcher = undefined;
|
|
1126
|
+
if (this.changeRepair) clearTimeout(this.changeRepair);
|
|
1127
|
+
this.changeRepair = undefined; this.changePosition = undefined;
|
|
1037
1128
|
this.timer = undefined;
|
|
1038
1129
|
this.releaseDiscoveryAuthority();
|
|
1039
1130
|
this.releaseSupervisionAuthority();
|
|
1040
|
-
try { this.store?.close(); } catch { /* already closed */ }
|
|
1131
|
+
try { if (!this.options.sharedStore) this.store?.close(); } catch { /* already closed */ }
|
|
1041
1132
|
this.store = undefined;
|
|
1042
1133
|
this.launches.clear();
|
|
1043
1134
|
this.rpcRuns.clear();
|
|
@@ -1048,6 +1139,7 @@ export class ObservedWaitHost {
|
|
|
1048
1139
|
this.activeContext = undefined;
|
|
1049
1140
|
this.terminalRecoveryNeeded = false;
|
|
1050
1141
|
this.pendingTerminalCallbacks.clear();
|
|
1142
|
+
this.callbackRecoveryScopes.clear();
|
|
1051
1143
|
this.watchedRunningTasks.clear();
|
|
1052
1144
|
this.discoveredTaskSidecars.clear();
|
|
1053
1145
|
this.durableProjectionCache = undefined;
|
|
@@ -1069,13 +1161,14 @@ export class ObservedWaitHost {
|
|
|
1069
1161
|
}
|
|
1070
1162
|
}
|
|
1071
1163
|
|
|
1072
|
-
private activeParentTerminalOperations(): OperationRecord[] {
|
|
1164
|
+
private activeParentTerminalOperations(claims = false): OperationRecord[] {
|
|
1073
1165
|
const origin = this.activeOrigin;
|
|
1074
1166
|
if (!this.store || !origin?.sessionId) return [];
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1167
|
+
const page = this.store.listPendingParentCallbacks({ sessionId: origin.sessionId, workspace: origin.cwd },
|
|
1168
|
+
{ after: claims ? this.pendingClaimCursor : this.pendingCallbackCursor, limit: 256 });
|
|
1169
|
+
const next = page.length === 256 ? page.at(-1)!.operationId : undefined;
|
|
1170
|
+
if (claims) this.pendingClaimCursor = next; else this.pendingCallbackCursor = next;
|
|
1171
|
+
return page;
|
|
1079
1172
|
}
|
|
1080
1173
|
|
|
1081
1174
|
/**
|
|
@@ -1122,9 +1215,18 @@ export class ObservedWaitHost {
|
|
|
1122
1215
|
* pending set is seeded once at activation and by each terminal attempt; it is
|
|
1123
1216
|
* not a scan of the historical terminal table on every 250 ms tick.
|
|
1124
1217
|
*/
|
|
1218
|
+
hasPendingParentCallbackRecovery(): boolean { return this.lastChangeRevision < 0 || this.pendingCallbackCursor !== undefined || this.pendingClaimCursor !== undefined; }
|
|
1219
|
+
|
|
1220
|
+
private rememberPendingCallback(taskId: string): void {
|
|
1221
|
+
if (!this.pendingTerminalCallbacks.has(taskId) && this.pendingTerminalCallbacks.size >= 256)
|
|
1222
|
+
this.pendingTerminalCallbacks.delete(this.pendingTerminalCallbacks.values().next().value!);
|
|
1223
|
+
this.pendingTerminalCallbacks.add(taskId);
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1125
1226
|
private retryPendingTerminalCallbacks(): void {
|
|
1126
1227
|
if (!this.store || this.pendingTerminalCallbacks.size === 0) return;
|
|
1127
|
-
for (const taskId of [...this.pendingTerminalCallbacks]) {
|
|
1228
|
+
for (const taskId of [...this.pendingTerminalCallbacks].slice(0, 64)) {
|
|
1229
|
+
this.pendingTerminalCallbacks.delete(taskId); this.rememberPendingCallback(taskId);
|
|
1128
1230
|
const operation = this.operationForTask(taskId);
|
|
1129
1231
|
if (!operation || operation.terminalRevision === 0) {
|
|
1130
1232
|
this.pendingTerminalCallbacks.delete(taskId);
|
|
@@ -1159,13 +1261,26 @@ export class ObservedWaitHost {
|
|
|
1159
1261
|
|
|
1160
1262
|
/** A deterministic, awaitable reconciliation pass for tests and session activation. */
|
|
1161
1263
|
async reconcileNow(): Promise<void> {
|
|
1162
|
-
|
|
1163
|
-
|
|
1264
|
+
const scope = this.recoveryScopeState();
|
|
1265
|
+
if (this.reconcileInFlight) {
|
|
1266
|
+
const sameScope = this.reconcileScope === scope;
|
|
1267
|
+
await this.reconcileInFlight;
|
|
1268
|
+
// Startup or another foreground's pass cannot verify this scope's recovery.
|
|
1269
|
+
if (!sameScope) return this.reconcileNow();
|
|
1270
|
+
return;
|
|
1271
|
+
}
|
|
1272
|
+
const release = this.options.enterControl?.();
|
|
1273
|
+
if (this.options.enterControl && !release) { this.managedDirty = true; return; }
|
|
1274
|
+
this.reconcileScope = scope;
|
|
1275
|
+
const pass = this.reconcilePass().finally(() => release?.());
|
|
1164
1276
|
this.reconcileInFlight = pass;
|
|
1165
1277
|
try {
|
|
1166
1278
|
await pass;
|
|
1167
1279
|
} finally {
|
|
1168
|
-
if (this.reconcileInFlight === pass)
|
|
1280
|
+
if (this.reconcileInFlight === pass) {
|
|
1281
|
+
this.reconcileInFlight = undefined;
|
|
1282
|
+
this.reconcileScope = undefined;
|
|
1283
|
+
}
|
|
1169
1284
|
}
|
|
1170
1285
|
}
|
|
1171
1286
|
|
|
@@ -1187,6 +1302,7 @@ export class ObservedWaitHost {
|
|
|
1187
1302
|
if (role === "holder") {
|
|
1188
1303
|
this.discoverObservedTasks();
|
|
1189
1304
|
this.reconcileGlobalRunning();
|
|
1305
|
+
if (discovery!.hasAssignmentTasks) await this.reconcileAssignmentCleanup();
|
|
1190
1306
|
} else {
|
|
1191
1307
|
this.reconcileFollowerRunning();
|
|
1192
1308
|
this.reconcileOwnerChanges();
|
|
@@ -1198,6 +1314,35 @@ export class ObservedWaitHost {
|
|
|
1198
1314
|
}
|
|
1199
1315
|
}
|
|
1200
1316
|
|
|
1317
|
+
private async reconcileAssignmentCleanup(): Promise<void> {
|
|
1318
|
+
const store = this.requireStore();
|
|
1319
|
+
const [candidate] = store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor);
|
|
1320
|
+
this.assignmentCleanupCursor = candidate?.operationId;
|
|
1321
|
+
if (!candidate || candidate.resultManaged || this.supervisionAuthority(candidate) !== "self") return;
|
|
1322
|
+
const { taskId, launchToken } = candidate;
|
|
1323
|
+
try {
|
|
1324
|
+
const inspection = this.supervisor.snapshot(taskId);
|
|
1325
|
+
const stop = readStopRequest(this.directory, taskId);
|
|
1326
|
+
if (inspection?.token !== launchToken || (stop && stop.token !== launchToken)) return;
|
|
1327
|
+
if (inspection.terminal) {
|
|
1328
|
+
if (inspection.status !== "lost" && inspection.result?.groupCleanup !== "unproven") return;
|
|
1329
|
+
const pgid = inspection.command?.pgid ?? inspection.command?.pid;
|
|
1330
|
+
if (inspection.cleanup?.groupEmpty === true || (pgid && !processGroupAlive(pgid))) {
|
|
1331
|
+
store.verifyAssignmentCleanup(candidate.operationId, launchToken, candidate.terminalRevision);
|
|
1332
|
+
return;
|
|
1333
|
+
}
|
|
1334
|
+
if (!pgid) return;
|
|
1335
|
+
}
|
|
1336
|
+
if (!this.localCancels.has(taskId)) {
|
|
1337
|
+
this.localCancels.add(taskId);
|
|
1338
|
+
try { await this.supervisor.stop(taskId, { token: launchToken, reason: "owning assignment ended" }); }
|
|
1339
|
+
finally { this.localCancels.delete(taskId); }
|
|
1340
|
+
}
|
|
1341
|
+
} catch (error) {
|
|
1342
|
+
this.options.logger?.(`Assignment cleanup for ${taskId}: ${String(error)}`);
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1201
1346
|
private reconcileGlobalRunning(): void {
|
|
1202
1347
|
const store = this.store;
|
|
1203
1348
|
if (!store) return;
|
|
@@ -1260,14 +1405,11 @@ export class ObservedWaitHost {
|
|
|
1260
1405
|
} catch {
|
|
1261
1406
|
return;
|
|
1262
1407
|
}
|
|
1263
|
-
if (revision === this.lastChangeRevision) return;
|
|
1408
|
+
if (revision === this.lastChangeRevision && !this.pendingCallbackCursor) return;
|
|
1264
1409
|
this.lastChangeRevision = revision;
|
|
1265
1410
|
let operations: OperationRecord[];
|
|
1266
1411
|
try {
|
|
1267
|
-
operations =
|
|
1268
|
-
ownerScope: { kind: "parent-session", sessionId, workspace: ctx.cwd },
|
|
1269
|
-
phase: "terminal",
|
|
1270
|
-
});
|
|
1412
|
+
operations = this.activeParentTerminalOperations();
|
|
1271
1413
|
} catch {
|
|
1272
1414
|
return;
|
|
1273
1415
|
}
|
|
@@ -1365,13 +1507,15 @@ export class ObservedWaitHost {
|
|
|
1365
1507
|
const owner = this.ownerFor(input.ctx);
|
|
1366
1508
|
const prepared = this.prepareLaunch(input.kind, input.params, "bg_task_spawn", owner, undefined);
|
|
1367
1509
|
if (this.options.serverOwnedResults) {
|
|
1368
|
-
this.
|
|
1510
|
+
this.assertManagedResultAdmission(prepared.provenance);
|
|
1369
1511
|
const client = await this.resultSupervisionClient();
|
|
1370
1512
|
client.close();
|
|
1371
1513
|
}
|
|
1372
1514
|
const operationId = `op_${randomUUID()}`;
|
|
1373
1515
|
const token = `launch_${randomUUID()}`;
|
|
1374
1516
|
const taskId = supervisorTaskIdForToken(token);
|
|
1517
|
+
this.options.assertAdmission?.();
|
|
1518
|
+
this.options.beforeParentOperation?.({ operationId, taskId, token });
|
|
1375
1519
|
store.registerOperation({
|
|
1376
1520
|
operationId,
|
|
1377
1521
|
taskId,
|
|
@@ -1400,7 +1544,7 @@ export class ObservedWaitHost {
|
|
|
1400
1544
|
// worker-owned operation to the parent's callback.
|
|
1401
1545
|
this.writeLaunchContext(taskId, launchContext);
|
|
1402
1546
|
this.launches.set(taskId, launchContext);
|
|
1403
|
-
if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!]);
|
|
1547
|
+
if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!], true);
|
|
1404
1548
|
const started = await this.startSupervisor({
|
|
1405
1549
|
token, taskId, kind: input.kind, params: input.params, prepared, operationId,
|
|
1406
1550
|
});
|
|
@@ -1522,7 +1666,11 @@ export class ObservedWaitHost {
|
|
|
1522
1666
|
/** Called from an actual admitted parent tool context, not a wire owner claim. */
|
|
1523
1667
|
authorizeCancellationForParent(ctx: ExtensionContext, taskId: string, requestId: string): string {
|
|
1524
1668
|
if (this.localCancels.has(taskId)) throw new Error("not_accepted: old cancellation admission is still draining");
|
|
1525
|
-
const
|
|
1669
|
+
const requester = this.ownerFor(ctx), operation = this.operationForTask(taskId);
|
|
1670
|
+
if (!operation) throw new Error(`Unknown task ${taskId}`);
|
|
1671
|
+
const admission = this.options.authorizeParentCancellation?.({ requester, operation, requestId });
|
|
1672
|
+
if (!ownerMatchesOperation(operation, requester) && !admission) throw new Error(`Task ${taskId} belongs to another execution owner.`);
|
|
1673
|
+
requestId = admission?.requestId ?? requestId;
|
|
1526
1674
|
const managed = this.requireStore().resultSupervision(operation.operationId);
|
|
1527
1675
|
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");
|
|
1528
1676
|
const proof = cancellationCredential();
|
|
@@ -1531,13 +1679,12 @@ export class ObservedWaitHost {
|
|
|
1531
1679
|
this.requireStore().admitTaskCancellation({ credentialHash: proof.hash, directory: this.directory, request: previous ?? {
|
|
1532
1680
|
owner: operation.owner, idempotencyKey: requestId, operationId: operation.operationId,
|
|
1533
1681
|
expectedLaunchToken: operation.launchToken, expectedTerminalRevision: operation.terminalRevision,
|
|
1534
|
-
expectedHostId: operation.supervision?.hostId ?? "unavailable", reason: "explicit stop",
|
|
1682
|
+
expectedHostId: operation.supervision?.hostId ?? "unavailable", reason: admission?.reason ?? "explicit stop",
|
|
1535
1683
|
} });
|
|
1536
1684
|
return proof.credential;
|
|
1537
1685
|
}
|
|
1538
1686
|
|
|
1539
1687
|
private async stopThroughRuntime(ctx: ExtensionContext, taskId: string, requestId: string): Promise<StatusView> {
|
|
1540
|
-
this.ownedOperation(taskId, this.ownerFor(ctx));
|
|
1541
1688
|
const root = realpathSync(dirname(this.storePath));
|
|
1542
1689
|
const registrationPath = join(root, "server-registration-v1.json");
|
|
1543
1690
|
if (!existsSync(registrationPath)) {
|
|
@@ -1561,7 +1708,12 @@ export class ObservedWaitHost {
|
|
|
1561
1708
|
receipt = await client.request("runtime_cancel_task", { credential });
|
|
1562
1709
|
}
|
|
1563
1710
|
if (receipt.state === "outcome_unknown" || !receipt.result) throw new Error(`${receipt.state}: cancellation ${requestId}; query the same request before retrying`);
|
|
1564
|
-
|
|
1711
|
+
// The credential above authorizes this exact recorded owner/token. Keep
|
|
1712
|
+
// the requester context intact even when its explicit all:true grant won.
|
|
1713
|
+
const operation = this.requireStore().getOperation(receipt.operationId);
|
|
1714
|
+
if (!operation || operation.taskId !== taskId || operation.launchToken !== receipt.expectedLaunchToken
|
|
1715
|
+
|| !sameOwner(operation.owner, receipt.owner)) throw new Error('outcome_unknown: cancellation target identity changed');
|
|
1716
|
+
return this.statusForOperation(operation, this.ownerFor(ctx));
|
|
1565
1717
|
} catch (error) {
|
|
1566
1718
|
const message = String(error);
|
|
1567
1719
|
if (/not_accepted|accepted:|outcome_unknown/.test(message)) throw error;
|
|
@@ -1733,7 +1885,7 @@ export class ObservedWaitHost {
|
|
|
1733
1885
|
// request a repaint.
|
|
1734
1886
|
if (owner.kind !== "parent-session" || this.activeOwnerRelation(owner) !== "match") return;
|
|
1735
1887
|
this.invalidateDurableProjection(owner);
|
|
1736
|
-
const change = { sessionId: owner.sessionId, workspace: owner.workspace };
|
|
1888
|
+
const change = { sessionId: owner.sessionId, workspace: owner.workspace, branchId: owner.branchId ?? null };
|
|
1737
1889
|
for (const listener of [...this.durableChangeListeners]) {
|
|
1738
1890
|
try { listener(change); } catch { /* a projection listener cannot break supervision */ }
|
|
1739
1891
|
}
|
|
@@ -1804,13 +1956,16 @@ export class ObservedWaitHost {
|
|
|
1804
1956
|
logPaths: { stdout: pathSet.stdout, stderr: pathSet.stderr, events: pathSet.events },
|
|
1805
1957
|
waits,
|
|
1806
1958
|
...(context?.sandbox ? { sandbox: context.sandbox } : {}),
|
|
1807
|
-
owner: { sessionId: operation.owner.sessionId, workspace: operation.owner.workspace },
|
|
1959
|
+
owner: { sessionId: operation.owner.sessionId, workspace: operation.owner.workspace, branchId: operation.owner.branchId ?? null },
|
|
1808
1960
|
};
|
|
1809
1961
|
}
|
|
1810
1962
|
|
|
1811
1963
|
private status(taskId: string, owner: OwnerIdentity): StatusView {
|
|
1812
|
-
|
|
1813
|
-
|
|
1964
|
+
return this.statusForOperation(this.ownedOperation(taskId, owner), owner);
|
|
1965
|
+
}
|
|
1966
|
+
|
|
1967
|
+
private statusForOperation(operation: OperationRecord, owner: OwnerIdentity): StatusView {
|
|
1968
|
+
const store = this.requireStore(), taskId = operation.taskId;
|
|
1814
1969
|
const inspection = this.inspect(taskId);
|
|
1815
1970
|
this.reconcileInspection(operation, inspection);
|
|
1816
1971
|
const current = store.getOperation(operation.operationId) ?? operation;
|
|
@@ -2002,6 +2157,12 @@ export class ObservedWaitHost {
|
|
|
2002
2157
|
return imported;
|
|
2003
2158
|
}
|
|
2004
2159
|
|
|
2160
|
+
private assertManagedResultAdmission(captured: TaskSandboxProvenance): void {
|
|
2161
|
+
if (captured.policySource !== "no-publisher" && !currentForegroundSandboxPolicy(this.pi)) {
|
|
2162
|
+
throw new Error("permission-unavailable: expected current Background permission source is unavailable");
|
|
2163
|
+
}
|
|
2164
|
+
}
|
|
2165
|
+
|
|
2005
2166
|
private assertResultAdmission(captured: TaskSandboxProvenance, transferring: ReadonlySet<string> = new Set()): void {
|
|
2006
2167
|
const discovery = this.requireStore().readDiscoveryClaim(this.discoveryScope);
|
|
2007
2168
|
if (discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
|
|
@@ -2026,12 +2187,15 @@ export class ObservedWaitHost {
|
|
|
2026
2187
|
}
|
|
2027
2188
|
}
|
|
2028
2189
|
|
|
2029
|
-
private async handoffResults(operations: readonly OperationRecord[]): Promise<void> {
|
|
2190
|
+
private async handoffResults(operations: readonly OperationRecord[], newManaged = false): Promise<void> {
|
|
2030
2191
|
const client = await this.resultSupervisionClient();
|
|
2031
2192
|
try {
|
|
2032
2193
|
const manager = await client.request("runtime_result_supervision");
|
|
2194
|
+
// Already granted dependencies need no discovery scope transfer. Legacy
|
|
2195
|
+
// holders may keep supervising unrelated work beside server-owned tasks.
|
|
2196
|
+
if (operations.every(operation => this.requireStore().resultSupervision(operation.operationId))) return;
|
|
2033
2197
|
const discovery = this.requireStore().readDiscoveryClaim(this.discoveryScope);
|
|
2034
|
-
if (discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
|
|
2198
|
+
if (!newManaged && discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
|
|
2035
2199
|
throw new Error("permission-unavailable: live or unknown original discovery holder prevents scope handoff");
|
|
2036
2200
|
}
|
|
2037
2201
|
const transfers = [];
|
|
@@ -2043,7 +2207,8 @@ export class ObservedWaitHost {
|
|
|
2043
2207
|
}
|
|
2044
2208
|
const context = this.launchContext(operation.taskId);
|
|
2045
2209
|
if (!context?.sandbox || !context.supervisionPolicy || !operation.authorityRef) throw new Error("permission-unavailable: captured Background authority is unavailable");
|
|
2046
|
-
this.
|
|
2210
|
+
if (newManaged) this.assertManagedResultAdmission(context.sandbox);
|
|
2211
|
+
else this.assertResultAdmission(context.sandbox, transferring);
|
|
2047
2212
|
const current = currentForegroundSandboxPolicy(this.pi);
|
|
2048
2213
|
if (context.sandbox.policySource !== "no-publisher" && !current) throw new Error("permission-unavailable: expected current Background permission source is unavailable");
|
|
2049
2214
|
transfers.push({ operationId: operation.operationId,
|
|
@@ -2053,10 +2218,15 @@ export class ObservedWaitHost {
|
|
|
2053
2218
|
// Validate the whole batch, then stop admission before the durable CAS.
|
|
2054
2219
|
for (const transfer of transfers) this.resultHandoffs.add(transfer.operationId);
|
|
2055
2220
|
try {
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2221
|
+
if (newManaged) {
|
|
2222
|
+
// New work grants only its own results; legacy discovery remains live.
|
|
2223
|
+
this.requireStore().handoffResultSupervisions(transfers);
|
|
2224
|
+
} else {
|
|
2225
|
+
this.requireStore().handoffResultScope({ scope: this.discoveryScope,
|
|
2226
|
+
expectedDiscovery: discovery ? { hostId: discovery.hostId, token: discovery.token } : null, grants: transfers });
|
|
2227
|
+
this.discoveryToken = undefined;
|
|
2228
|
+
this.discoveryRole = "follower";
|
|
2229
|
+
}
|
|
2060
2230
|
} catch (error) {
|
|
2061
2231
|
// The transaction rolled back; only these uncommitted local fences may reopen.
|
|
2062
2232
|
for (const transfer of transfers) this.resultHandoffs.delete(transfer.operationId);
|
|
@@ -2117,6 +2287,7 @@ export class ObservedWaitHost {
|
|
|
2117
2287
|
const client = await this.resultSupervisionClient();
|
|
2118
2288
|
client.close();
|
|
2119
2289
|
}
|
|
2290
|
+
const assertWorkerPolicy = this.options.prepareWorkerPolicy?.(run);
|
|
2120
2291
|
const prepared = this.prepareLaunch(
|
|
2121
2292
|
input.kind,
|
|
2122
2293
|
input.params,
|
|
@@ -2125,7 +2296,7 @@ export class ObservedWaitHost {
|
|
|
2125
2296
|
input.policy,
|
|
2126
2297
|
run.workspace,
|
|
2127
2298
|
);
|
|
2128
|
-
if (this.options.serverOwnedResults) this.
|
|
2299
|
+
if (this.options.serverOwnedResults) this.assertManagedResultAdmission(prepared.provenance);
|
|
2129
2300
|
const operationId = `op_${randomUUID()}`;
|
|
2130
2301
|
const token = `launch_${randomUUID()}`;
|
|
2131
2302
|
const taskId = supervisorTaskIdForToken(token);
|
|
@@ -2138,8 +2309,10 @@ export class ObservedWaitHost {
|
|
|
2138
2309
|
supervision: this.supervision(),
|
|
2139
2310
|
authorityRef: authorityReference(`worker:${run.authorityReference}`),
|
|
2140
2311
|
intentRef: typeof input.params.operation_id === "string" ? input.params.operation_id : null,
|
|
2312
|
+
...(run.assignmentAttemptId ? { assignmentAttemptId: run.assignmentAttemptId } : {}),
|
|
2141
2313
|
});
|
|
2142
2314
|
const launchContext: LaunchContext = {
|
|
2315
|
+
workerAttemptId: run.runId,
|
|
2143
2316
|
kind: input.kind,
|
|
2144
2317
|
parentOrigin: this.parentOrigin,
|
|
2145
2318
|
gated: prepared.gated,
|
|
@@ -2154,9 +2327,9 @@ export class ObservedWaitHost {
|
|
|
2154
2327
|
};
|
|
2155
2328
|
this.writeLaunchContext(taskId, launchContext);
|
|
2156
2329
|
this.launches.set(taskId, launchContext);
|
|
2157
|
-
if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!]);
|
|
2330
|
+
if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!], true);
|
|
2158
2331
|
const started = await this.startSupervisor({
|
|
2159
|
-
token, taskId, kind: input.kind, params: input.params, prepared, operationId,
|
|
2332
|
+
token, taskId, kind: input.kind, params: input.params, prepared, operationId, assertDispatch: assertWorkerPolicy,
|
|
2160
2333
|
});
|
|
2161
2334
|
this.launches.set(taskId, launchContext);
|
|
2162
2335
|
this.emitDurableTaskChange(owner);
|
|
@@ -2510,6 +2683,7 @@ export class ObservedWaitHost {
|
|
|
2510
2683
|
: {};
|
|
2511
2684
|
this.rpcRuns.set(runId, Object.freeze({
|
|
2512
2685
|
runId,
|
|
2686
|
+
assignmentTaskOwnership: params.assignmentTaskOwnership === true,
|
|
2513
2687
|
conversationId,
|
|
2514
2688
|
attemptId,
|
|
2515
2689
|
workspace,
|
|
@@ -2866,6 +3040,7 @@ export class ObservedWaitHost {
|
|
|
2866
3040
|
private rpcScope(binding: RpcRunBinding): WorkerRunScope {
|
|
2867
3041
|
return {
|
|
2868
3042
|
runId: binding.runId,
|
|
3043
|
+
...(binding.assignmentTaskOwnership ? { assignmentAttemptId: binding.attemptId } : {}),
|
|
2869
3044
|
conversationId: binding.conversationId,
|
|
2870
3045
|
workspace: binding.workspace,
|
|
2871
3046
|
authorityReference: binding.authorityReference,
|
|
@@ -2987,6 +3162,7 @@ export class ObservedWaitHost {
|
|
|
2987
3162
|
params: Record<string, unknown>;
|
|
2988
3163
|
prepared: ReturnType<ObservedWaitHost["prepareLaunch"]>;
|
|
2989
3164
|
operationId: string;
|
|
3165
|
+
assertDispatch?: () => void;
|
|
2990
3166
|
}): Promise<{ started: boolean; claimed: boolean }> {
|
|
2991
3167
|
const { token, taskId, kind, params, prepared, operationId } = input;
|
|
2992
3168
|
const profilePath = join(supervisorPaths(this.directory, taskId).dir, "sandbox.sb");
|
|
@@ -3014,6 +3190,15 @@ export class ObservedWaitHost {
|
|
|
3014
3190
|
...(typeof params.max_log_bytes === "number" ? { maxLogBytes: params.max_log_bytes } : {}),
|
|
3015
3191
|
...(kind === "watch" ? this.watchOptions(params) : this.processTimeout(params)),
|
|
3016
3192
|
};
|
|
3193
|
+
try { this.options.assertAdmission?.(); input.assertDispatch?.(); }
|
|
3194
|
+
catch (error) {
|
|
3195
|
+
const operation = this.requireStore().getOperation(operationId);
|
|
3196
|
+
if (operation && operation.terminalRevision === 0) this.requireStore().recordTerminalOutcome({
|
|
3197
|
+
operationId, eventId: `admission_refused_${randomUUID()}`, owner: operation.owner,
|
|
3198
|
+
outcome: "failed", evidence: [], reason: `External dispatch refused before spawn: ${String(error)}`,
|
|
3199
|
+
});
|
|
3200
|
+
throw error;
|
|
3201
|
+
}
|
|
3017
3202
|
const started = await this.supervisor.start(options);
|
|
3018
3203
|
return { started: started.started, claimed: started.claimed };
|
|
3019
3204
|
}
|
|
@@ -3307,13 +3492,14 @@ export class ObservedWaitHost {
|
|
|
3307
3492
|
if (!this.options.notifyParent) return;
|
|
3308
3493
|
if (operation.owner.kind !== "parent-session") return;
|
|
3309
3494
|
if (!context) return;
|
|
3310
|
-
if (context.callback === false) return;
|
|
3495
|
+
if (context.callback === false) { this.store?.setParentCallbackPending(operation.taskId, false); return; }
|
|
3311
3496
|
// Never write any journal field while a newer or unprovable other host owns
|
|
3312
3497
|
// the claim. In particular, a stale host's reconcile must not rewrite its
|
|
3313
3498
|
// cached claim token over the current shared one.
|
|
3314
3499
|
const claim = this.claimState(context.callbackClaimedBy);
|
|
3315
3500
|
if (claim === "live" || claim === "unknown") return;
|
|
3316
3501
|
if (context.callbackDeliveredAt !== undefined) {
|
|
3502
|
+
this.store?.setParentCallbackPending(operation.taskId, false);
|
|
3317
3503
|
this.pendingTerminalCallbacks.delete(operation.taskId);
|
|
3318
3504
|
skip("already delivered");
|
|
3319
3505
|
return;
|
|
@@ -3353,7 +3539,7 @@ export class ObservedWaitHost {
|
|
|
3353
3539
|
// A terminal result can become eligible later: the live session may have
|
|
3354
3540
|
// been settling when the record was produced, or the owner may navigate
|
|
3355
3541
|
// back to an eligible descendant branch. Keep retrying only this id.
|
|
3356
|
-
this.
|
|
3542
|
+
this.rememberPendingCallback(operation.taskId);
|
|
3357
3543
|
const origin = context.parentOrigin ?? { cwd: operation.owner.workspace, sessionId: operation.owner.sessionId };
|
|
3358
3544
|
const branchId = context.branchId ?? operation.owner.branchId;
|
|
3359
3545
|
if (!this.isParentOriginActive(origin, branchId)) {
|
|
@@ -3373,6 +3559,7 @@ export class ObservedWaitHost {
|
|
|
3373
3559
|
const claimToken = context.callbackClaimToken;
|
|
3374
3560
|
let settled = false;
|
|
3375
3561
|
const delivery: ParentDelivery = {
|
|
3562
|
+
receiptId: `background-terminal:${operation.operationId}`,
|
|
3376
3563
|
delivered: () => {
|
|
3377
3564
|
if (settled) return;
|
|
3378
3565
|
settled = true;
|
|
@@ -3429,13 +3616,13 @@ export class ObservedWaitHost {
|
|
|
3429
3616
|
if (!context || context.callbackDeliveredAt !== undefined) return;
|
|
3430
3617
|
const claim = this.claimState(context.callbackClaimedBy);
|
|
3431
3618
|
if (claim === "live" || claim === "unknown") {
|
|
3432
|
-
this.
|
|
3619
|
+
this.rememberPendingCallback(taskId);
|
|
3433
3620
|
return; // preserve the current owner's claim without any write
|
|
3434
3621
|
}
|
|
3435
3622
|
context.callbackPendingAt ??= Date.now();
|
|
3436
3623
|
this.launches.set(taskId, context);
|
|
3437
3624
|
this.writeLaunchContext(taskId, context);
|
|
3438
|
-
this.
|
|
3625
|
+
this.rememberPendingCallback(taskId);
|
|
3439
3626
|
}
|
|
3440
3627
|
|
|
3441
3628
|
private completeTerminalCallback(taskId: string, claimToken?: string): void {
|
|
@@ -3465,7 +3652,7 @@ export class ObservedWaitHost {
|
|
|
3465
3652
|
if (!context || context.callbackDeliveredAt !== undefined) return;
|
|
3466
3653
|
// A stale suppression must not clear the claim of a newer attempt.
|
|
3467
3654
|
if (claimToken !== undefined && context.callbackClaimToken !== claimToken) return;
|
|
3468
|
-
this.
|
|
3655
|
+
this.rememberPendingCallback(taskId);
|
|
3469
3656
|
context.callbackDeferredReason = oneLine(reason, 200);
|
|
3470
3657
|
context.callbackAttemptedAt = Date.now();
|
|
3471
3658
|
context.callbackSkipReason = `deferred: ${oneLine(reason, 160)}`;
|
|
@@ -3568,7 +3755,7 @@ export class ObservedWaitHost {
|
|
|
3568
3755
|
});
|
|
3569
3756
|
} catch { /* another host already recovered it */ }
|
|
3570
3757
|
}
|
|
3571
|
-
for (const operation of this.activeParentTerminalOperations()) {
|
|
3758
|
+
for (const operation of this.activeParentTerminalOperations(true)) {
|
|
3572
3759
|
const context = this.currentLaunchContext(operation.taskId);
|
|
3573
3760
|
if (!context?.callbackClaimedBy || context.callbackClaimedBy === this.hostId) continue;
|
|
3574
3761
|
if (this.claimState(context.callbackClaimedBy) !== "dead") continue;
|
|
@@ -3640,6 +3827,7 @@ export class ObservedWaitHost {
|
|
|
3640
3827
|
const outcome = await adapter.onWaitReady({
|
|
3641
3828
|
waitId: event.waitId,
|
|
3642
3829
|
generation: event.generation,
|
|
3830
|
+
...(wait?.park?.attemptId ? { parkedAttemptId: wait.park.attemptId } : {}),
|
|
3643
3831
|
owner,
|
|
3644
3832
|
...(taskId && this.launches.get(taskId)?.parentOrigin
|
|
3645
3833
|
? { parentOrigin: this.launches.get(taskId)!.parentOrigin }
|
|
@@ -3691,6 +3879,7 @@ export class ObservedWaitHost {
|
|
|
3691
3879
|
}
|
|
3692
3880
|
let settled = false;
|
|
3693
3881
|
const delivery: ParentDelivery = {
|
|
3882
|
+
receiptId: event.eventId,
|
|
3694
3883
|
delivered: () => {
|
|
3695
3884
|
if (settled) return;
|
|
3696
3885
|
settled = true;
|
|
@@ -3998,8 +4187,9 @@ export class ObservedWaitHost {
|
|
|
3998
4187
|
* on every session_tree/branch navigation. Branch changes must be visible to
|
|
3999
4188
|
* a queued callback *before* the batcher decides whether to deliver it.
|
|
4000
4189
|
*/
|
|
4001
|
-
noteParentContext(ctx: ExtensionContext): void {
|
|
4002
|
-
this.setActiveOrigin(ctx);
|
|
4190
|
+
noteParentContext(ctx: ExtensionContext, options: {recover?: boolean} = {}): void {
|
|
4191
|
+
this.setActiveOrigin(ctx, options.recover !== false);
|
|
4192
|
+
if(options.recover === false)return;
|
|
4003
4193
|
if (!this.store) return;
|
|
4004
4194
|
this.recoverAbandonedDeliveries();
|
|
4005
4195
|
if (this.terminalRecoveryNeeded) {
|
|
@@ -4011,7 +4201,7 @@ export class ObservedWaitHost {
|
|
|
4011
4201
|
this.writeHostDebug();
|
|
4012
4202
|
}
|
|
4013
4203
|
|
|
4014
|
-
private setActiveOrigin(ctx: ExtensionContext): void {
|
|
4204
|
+
private setActiveOrigin(ctx: ExtensionContext, debug = true): void {
|
|
4015
4205
|
const previous = this.activeContext;
|
|
4016
4206
|
const previousKey = previous ? this.contextKey(previous) : undefined;
|
|
4017
4207
|
const nextSessionId = this.sessionIdIfAvailable(ctx);
|
|
@@ -4027,11 +4217,16 @@ export class ObservedWaitHost {
|
|
|
4027
4217
|
// A tool call or activation for a different session/workspace must seed the
|
|
4028
4218
|
// terminal callback journal once. Same-session calls keep the live context
|
|
4029
4219
|
// current without rescanning historical terminal records.
|
|
4030
|
-
|
|
4031
|
-
|
|
4220
|
+
const branchSignature = JSON.stringify(branchIdsOf(ctx));
|
|
4221
|
+
const branchChanged = branchSignature !== this.activeBranchSignature;
|
|
4222
|
+
if (!previous || previousKey !== nextKey || branchChanged) this.terminalRecoveryNeeded = true;
|
|
4223
|
+
if (branchChanged) {
|
|
4032
4224
|
this.lastChangeRevision = -1;
|
|
4225
|
+
this.pendingCallbackCursor = undefined;
|
|
4226
|
+
this.pendingClaimCursor = undefined;
|
|
4033
4227
|
}
|
|
4034
|
-
this.
|
|
4228
|
+
this.activeBranchSignature = branchSignature;
|
|
4229
|
+
if(debug)this.writeHostDebug();
|
|
4035
4230
|
}
|
|
4036
4231
|
|
|
4037
4232
|
private contextKey(ctx: ExtensionContext): string | undefined {
|
|
@@ -4104,10 +4299,21 @@ export class ObservedWaitHost {
|
|
|
4104
4299
|
|
|
4105
4300
|
private writeLaunchContext(taskId: string, context: LaunchContext): void {
|
|
4106
4301
|
try {
|
|
4302
|
+
const operation = this.operationForTask(taskId);
|
|
4303
|
+
const parent = operation?.owner.kind === "parent-session";
|
|
4304
|
+
const outboxDelivered = operation && Object.values(context.outboxDelivered ?? {}).some(proof => proof.terminalRevision === operation.terminalRevision);
|
|
4305
|
+
const pending = context.callback !== false && context.callbackDeliveredAt === undefined && !outboxDelivered;
|
|
4306
|
+
// Publish the obligation before the sidecar: a crash may leave a pending
|
|
4307
|
+
// candidate, but cannot hide an accepted callback. Retire only after the
|
|
4308
|
+
// delivered/disabled sidecar is durable, so replay can prove suppression.
|
|
4309
|
+
if (parent && pending) this.store?.setParentCallbackPending(taskId, true);
|
|
4107
4310
|
const path = this.sidecarPath(taskId);
|
|
4108
4311
|
mkdirSync(dirname(path), { recursive: true });
|
|
4109
|
-
|
|
4110
|
-
|
|
4312
|
+
const staged = `${path}.${randomUUID()}.tmp`;
|
|
4313
|
+
try { writeFileSync(staged, JSON.stringify(context), { mode: 0o600, flag: "wx" }); renameSync(staged, path); }
|
|
4314
|
+
finally { rmSync(staged, { force: true }); }
|
|
4315
|
+
if (parent && !pending) this.store?.setParentCallbackPending(taskId, false);
|
|
4316
|
+
} catch { /* retain an obligation if the exact sidecar cannot be persisted */ }
|
|
4111
4317
|
}
|
|
4112
4318
|
|
|
4113
4319
|
private readLaunchContext(taskId: string): LaunchContext | undefined {
|