pi-better-subagents 0.34.0 → 0.35.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/assignment-outcomes.ts +44 -6
- package/capacity.mjs +13 -0
- package/continuation-authority.ts +29 -0
- package/continuation.ts +21 -0
- package/failures.ts +7 -1
- package/health.ts +0 -1
- package/index.ts +273 -109
- package/managed-background-capability.ts +9 -0
- package/managed-failure-worker.mjs +27 -0
- package/managed-launch-bootstrap.mjs +35 -0
- package/managed-launch-client.ts +56 -0
- package/managed-launch-host.ts +351 -0
- package/managed-launch-journal.mjs +18 -0
- package/managed-launch-ownership.ts +22 -0
- package/managed-launch-port.ts +21 -0
- package/managed-launch-recovery.ts +45 -0
- package/managed-worker-bridge.ts +48 -0
- package/managed-worker.mjs +11 -0
- package/package.json +1 -1
- package/permission-policy.ts +12 -0
- package/registry.ts +2 -0
- 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/shared-callback-batcher.ts +4 -1
- package/shared-failure-observations.ts +3 -0
- package/shared-navigator.ts +23 -5
- package/shared-operation-coordinator/assignment-observation.mjs +30 -0
- package/shared-operation-coordinator/index.ts +2 -0
- package/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
- package/shared-operation-coordinator/src/background-requests.ts +79 -0
- package/shared-operation-coordinator/src/schema.ts +31 -0
- package/shared-operation-coordinator/src/store.ts +18 -0
- package/shared-operation-coordinator/src/subagent-launch.ts +119 -0
- package/shared-operation-coordinator/src/upgrade.ts +22 -0
- package/task-runtime.mjs +1 -0
- package/timing-notifications.ts +37 -0
- package/timing.ts +1 -0
- package/tools.ts +10 -3
- package/work-observation.ts +18 -2
- package/worker-waits.ts +46 -14
package/index.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { appendTimingWake, removeTimingReceipt, receiptTimingWake, timingWakeReceipt } from "./timing-notifications.ts";
|
|
1
2
|
/**
|
|
2
3
|
* pi-better-subagents — Claude Code-style async subagents for pi.
|
|
3
4
|
*
|
|
@@ -28,7 +29,7 @@ import { workObservation, workObservationFailure, startWorkObservation, stopWork
|
|
|
28
29
|
import { withAssignmentObservations } from "./assignment-projection.mjs";
|
|
29
30
|
import { formatNavigatorHealthFacts } from "./health-surface.mjs";
|
|
30
31
|
import { matchesKey, Key, truncateToWidth, type AutocompleteItem } from "@earendil-works/pi-tui";
|
|
31
|
-
import { Type } from "
|
|
32
|
+
import { Type } from "typebox";
|
|
32
33
|
import {
|
|
33
34
|
disposeBackgroundWorkNavigator,
|
|
34
35
|
ensureBackgroundWorkNavigator,
|
|
@@ -106,7 +107,7 @@ import {
|
|
|
106
107
|
listMetasForParent,
|
|
107
108
|
onMetaChanged,
|
|
108
109
|
effectiveStatus,
|
|
109
|
-
ownedByThisParent,
|
|
110
|
+
ownedByThisParent as ownedByFrontend,
|
|
110
111
|
navigatorVisibleRuns,
|
|
111
112
|
isDismissed,
|
|
112
113
|
dismissRun,
|
|
@@ -143,6 +144,9 @@ import {
|
|
|
143
144
|
} from "./capacity.mjs";
|
|
144
145
|
import { buildHealthCallbackDelivery } from "./completion.ts";
|
|
145
146
|
import { cancelCallbackBatch, getCallbackBatcher, setCallbackBatchContext } from "./shared-callback-batcher.ts";
|
|
147
|
+
let managementPort: import("./managed-launch-port.ts").ManagedLaunchPort | undefined;
|
|
148
|
+
const ownedByThisParent = (meta: Partial<RunMeta>) => managementPort ? managementPort.owns(meta) : ownedByFrontend(meta as RunMeta);
|
|
149
|
+
const supervisedMetas = () => managementPort ? managementPort.supervised() : listMetasForParent(process.pid);
|
|
146
150
|
import { completionCallbackFields, failureAttentionFields, healthCallbackFields } from "./callback-fields.ts";
|
|
147
151
|
import { collectRunFailures, failurePath, markFailureAttentionDelivered, pendingFailureAttention } from "./failures.ts";
|
|
148
152
|
import { failureAttentionHandled, observeFailures } from "./shared-failure-observations.ts";
|
|
@@ -379,6 +383,13 @@ function callbackSuppressionReason(meta: RunMeta, active: RunCallbackOrigin | un
|
|
|
379
383
|
if (origin.sessionId && origin.sessionId !== active.sessionId) {
|
|
380
384
|
return `origin session ${origin.sessionId} does not match active session ${active.sessionId ?? "unknown"}`;
|
|
381
385
|
}
|
|
386
|
+
const recipient = meta.assignment?.recipient;
|
|
387
|
+
if (recipient && (recipient.sessionId !== active.sessionId || recipient.workspace !== active.cwd)) {
|
|
388
|
+
return `origin session ${recipient.sessionId} does not match the active recipient scope`;
|
|
389
|
+
}
|
|
390
|
+
if (recipient?.branchId && (!uiCtx || !branchContains(uiCtx, recipient.branchId))) {
|
|
391
|
+
return `origin branch ${recipient.branchId} is not active`;
|
|
392
|
+
}
|
|
382
393
|
if (meta.operations?.resumeLaunchToken && meta.operations.branchId
|
|
383
394
|
&& (!uiCtx || !branchContains(uiCtx, meta.operations.branchId))) {
|
|
384
395
|
return `origin branch ${meta.operations.branchId} is not active`;
|
|
@@ -439,6 +450,7 @@ function interruptCurrentSessionSubagents(reason: string, ctx: ExtensionContext)
|
|
|
439
450
|
const now = Date.now();
|
|
440
451
|
const interrupted: RunMeta[] = [];
|
|
441
452
|
for (const summary of listMetasForParent(process.pid)) {
|
|
453
|
+
if (summary.management) continue;
|
|
442
454
|
if (!ownedByThisParent(summary)) continue;
|
|
443
455
|
if (summary.status !== "running" && summary.status !== "orphaned") continue;
|
|
444
456
|
if (!belongsToOrigin(summary, origin)) continue;
|
|
@@ -488,6 +500,18 @@ let outcomeHost = createOutcomeHost();
|
|
|
488
500
|
const outcomeAdmission = new Map<string, () => boolean>();
|
|
489
501
|
const outcomeEnqueuing = new Set<string>();
|
|
490
502
|
let outcomeTicker: ReturnType<typeof setInterval> | undefined;
|
|
503
|
+
const pendingRecipientRecovery = new Map<string, Set<"timing" | "health" | "failure" | "completion" | "assignment">>();
|
|
504
|
+
const observedRecipientRows = new Map<string, string>();
|
|
505
|
+
function trackRecipientRecovery(id: string, kind: "timing" | "health" | "failure" | "completion" | "assignment"): void {
|
|
506
|
+
let pending = pendingRecipientRecovery.get(id);
|
|
507
|
+
if (!pending) pendingRecipientRecovery.set(id, pending = new Set());
|
|
508
|
+
pending.add(kind);
|
|
509
|
+
}
|
|
510
|
+
function finishRecipientRecovery(id: string, kind: "timing" | "health" | "failure" | "completion" | "assignment"): void {
|
|
511
|
+
const pending = pendingRecipientRecovery.get(id);
|
|
512
|
+
pending?.delete(kind);
|
|
513
|
+
if (!pending?.size) pendingRecipientRecovery.delete(id);
|
|
514
|
+
}
|
|
491
515
|
|
|
492
516
|
/**
|
|
493
517
|
* "The rightful conversation is not the active one", not "this notification is
|
|
@@ -535,6 +559,9 @@ function enqueueCompletionCallback(pi: ExtensionAPI, id: string): void {
|
|
|
535
559
|
if (meta?.assignment) {
|
|
536
560
|
try {
|
|
537
561
|
const outcome = commitAssignmentTerminal(meta);
|
|
562
|
+
// Persist mechanically even when the recipient is absent. Only its
|
|
563
|
+
// attached foreground may write or activate the parent transcript.
|
|
564
|
+
if (managementPort) return;
|
|
538
565
|
if (outcome) { void enqueueAssignmentOutcome(pi, meta); return; }
|
|
539
566
|
// An unresolved assignment exit belongs to repair, not legacy delivery.
|
|
540
567
|
return;
|
|
@@ -543,6 +570,7 @@ function enqueueCompletionCallback(pi: ExtensionAPI, id: string): void {
|
|
|
543
570
|
return;
|
|
544
571
|
}
|
|
545
572
|
}
|
|
573
|
+
if (managementPort) return;
|
|
546
574
|
if (!meta
|
|
547
575
|
|| meta.callback === false
|
|
548
576
|
|| meta.completionCallbackPendingAt === undefined
|
|
@@ -660,32 +688,58 @@ async function tryEnqueueAssignmentOutcome(pi: ExtensionAPI, meta: RunMeta): Pro
|
|
|
660
688
|
* path never takes a live pi's terminal callback (#625, DEV-226 criterion 5).
|
|
661
689
|
*/
|
|
662
690
|
function recoverAssignmentOutcomes(pi: ExtensionAPI): void {
|
|
663
|
-
for (const
|
|
664
|
-
|
|
691
|
+
for (const [id, pending] of pendingRecipientRecovery) {
|
|
692
|
+
const meta = readMeta(id);
|
|
693
|
+
if (!meta) { pendingRecipientRecovery.delete(id); continue; }
|
|
694
|
+
if (pending.has("timing")) {
|
|
695
|
+
replayTimingWakes(pi, meta);
|
|
696
|
+
if (!meta.timing?.pendingWakes?.some(wake => !timingWakeReceipt(id, wake.key))) finishRecipientRecovery(id, "timing");
|
|
697
|
+
}
|
|
698
|
+
if (pending.has("health")) {
|
|
699
|
+
if ((meta.status !== "orphaned" && meta.status !== "lost") || isHealthCallbackHandled(meta, meta.status)) finishRecipientRecovery(id, "health");
|
|
700
|
+
else deliverHealthCallback(pi, meta, meta.status, Date.now());
|
|
701
|
+
}
|
|
702
|
+
if (pending.has("failure")) deliverFailureAttention(pi, meta, Date.now());
|
|
703
|
+
if (pending.has("completion")) {
|
|
704
|
+
if (meta.completionCallbackSentAt !== undefined || meta.completionCallbackSuppressedAt !== undefined) finishRecipientRecovery(id, "completion");
|
|
705
|
+
else enqueueCompletionCallback(pi, id);
|
|
706
|
+
}
|
|
707
|
+
if (pending.has("assignment")) {
|
|
708
|
+
try {
|
|
709
|
+
const outcome = readOutcome(meta);
|
|
710
|
+
if (outcome?.deliveryReceipt || outcome?.disposition) finishRecipientRecovery(id, "assignment");
|
|
711
|
+
else if (outcome) void enqueueAssignmentOutcome(pi, meta);
|
|
712
|
+
} catch { /* retry only the recorded pending handoff */ }
|
|
713
|
+
}
|
|
665
714
|
}
|
|
666
715
|
}
|
|
716
|
+
function observeRecipientNotifications(pi: ExtensionAPI): void {
|
|
717
|
+
const observation = workObservation();
|
|
718
|
+
if (sessionTornDown || observation?.status !== "ready") return;
|
|
719
|
+
const ids = new Set<string>();
|
|
720
|
+
for (const row of observation.rows) {
|
|
721
|
+
const meta = row.meta as RunMeta;
|
|
722
|
+
ids.add(meta.id);
|
|
723
|
+
const revision = JSON.stringify(row);
|
|
724
|
+
if (observedRecipientRows.get(meta.id) === revision) continue;
|
|
725
|
+
observedRecipientRows.set(meta.id, revision);
|
|
726
|
+
if (meta.timing?.pendingWakes?.length) trackRecipientRecovery(meta.id, "timing");
|
|
727
|
+
if (!meta.assignment && meta.completionCallbackPendingAt !== undefined && meta.completionCallbackSentAt === undefined && meta.completionCallbackSuppressedAt === undefined
|
|
728
|
+
&& (meta.management || ownedByThisParent(meta) || (meta.supervisionInterruptedAt !== undefined && isAbandonedByParent(meta, realProcessProbe)))) trackRecipientRecovery(meta.id, "completion");
|
|
729
|
+
if ((meta.status === "orphaned" || meta.status === "lost") && !isHealthCallbackHandled(meta, meta.status)) trackRecipientRecovery(meta.id, "health");
|
|
730
|
+
if (meta.assignment && ["completed", "failed", "killed", "lost"].includes(meta.status)) trackRecipientRecovery(meta.id, "assignment");
|
|
731
|
+
if (row.failurePending || ["running", "orphaned", "lost"].includes(meta.status)) deliverFailureAttention(pi, meta, Date.now());
|
|
732
|
+
}
|
|
733
|
+
for (const id of observedRecipientRows.keys()) if (!ids.has(id)) observedRecipientRows.delete(id);
|
|
734
|
+
recoverAssignmentOutcomes(pi);
|
|
735
|
+
}
|
|
667
736
|
|
|
668
737
|
function recoverCompletionCallbacks(pi: ExtensionAPI): void {
|
|
669
|
-
|
|
670
|
-
for (const meta of listMetasForParent(process.pid)) {
|
|
671
|
-
if (!ownedByThisParent(meta)) continue;
|
|
672
|
-
enqueueCompletionCallback(pi, meta.id);
|
|
673
|
-
}
|
|
674
|
-
const activeSessionId = activeCallbackOrigin?.sessionId;
|
|
675
|
-
if (!activeSessionId) return;
|
|
676
|
-
for (const summary of listMetas()) {
|
|
677
|
-
if (ownedByThisParent(summary) || summary.supervisionInterruptedAt === undefined) continue;
|
|
678
|
-
if (summary.status === "running" || summary.status === "orphaned") continue;
|
|
679
|
-
// A live foreign parent still owns its run's callback: never deliver for it.
|
|
680
|
-
if (!isAbandonedByParent(summary, realProcessProbe)) continue;
|
|
681
|
-
const meta = readMeta(summary.id);
|
|
682
|
-
if (!meta || meta.status === "running" || meta.status === "orphaned") continue;
|
|
683
|
-
if (meta.callbackOrigin?.sessionId !== activeSessionId) continue;
|
|
684
|
-
enqueueCompletionCallback(pi, meta.id);
|
|
685
|
-
}
|
|
738
|
+
observeRecipientNotifications(pi);
|
|
686
739
|
}
|
|
687
740
|
|
|
688
741
|
function deliverFailureAttention(pi: ExtensionAPI | undefined, meta: RunMeta, now: number): void {
|
|
742
|
+
if (managementPort) return;
|
|
689
743
|
if (!pi || meta.callback === false || callbackSuppressionReason(meta)) return;
|
|
690
744
|
if ((meta.status === "orphaned" || meta.status === "lost") && !isHealthCallbackHandled(meta, meta.status)) return;
|
|
691
745
|
const state = collectRunFailures(meta.id, meta.cwd, meta.status !== "running" && meta.status !== "orphaned");
|
|
@@ -694,7 +748,10 @@ function deliverFailureAttention(pi: ExtensionAPI | undefined, meta: RunMeta, no
|
|
|
694
748
|
// orphaned run's health callback is handled there is no later callback that is sure to come
|
|
695
749
|
// (the run may stay orphaned), so gaps found after it are delivered now (#325).
|
|
696
750
|
const pending = pendingFailureAttention(state, now, { deferObservationGaps: meta.status === "running" });
|
|
697
|
-
if (!pending
|
|
751
|
+
if (!pending) { finishRecipientRecovery(meta.id, "failure"); return; }
|
|
752
|
+
if ((meta.status !== "running" && meta.status !== "orphaned" && meta.completionCallbackPendingAt !== undefined
|
|
753
|
+
&& meta.completionCallbackSentAt === undefined && meta.completionCallbackSuppressedAt === undefined)) return;
|
|
754
|
+
trackRecipientRecovery(meta.id, "failure");
|
|
698
755
|
// Only the pending incidents are rendered; earlier deliveries are counted, not repeated (#315).
|
|
699
756
|
void getCallbackBatcher(pi).deliverUrgent({
|
|
700
757
|
...failureAttentionFields(meta, state, pending),
|
|
@@ -704,11 +761,12 @@ function deliverFailureAttention(pi: ExtensionAPI | undefined, meta: RunMeta, no
|
|
|
704
761
|
if (!current) throw new Error("Subagent metadata is unavailable; defer failure notification");
|
|
705
762
|
return callbackSuppressionReason(current);
|
|
706
763
|
},
|
|
707
|
-
onDelivered: (at) => { markFailureAttentionDelivered(failurePath(meta.id), pending, at); },
|
|
764
|
+
onDelivered: (at) => { markFailureAttentionDelivered(failurePath(meta.id), pending, at); finishRecipientRecovery(meta.id, "failure"); },
|
|
708
765
|
});
|
|
709
766
|
}
|
|
710
767
|
|
|
711
768
|
function markHealthCallbackSuppressed(meta: RunMeta, status: "orphaned" | "lost", reason: string, now: number): void {
|
|
769
|
+
if (isConversationIdentityReason(reason)) return;
|
|
712
770
|
if (status === "orphaned") {
|
|
713
771
|
if (meta.orphanedCallbackSuppressedAt !== undefined) return;
|
|
714
772
|
meta.orphanedCallbackSuppressedAt = now;
|
|
@@ -872,15 +930,17 @@ let healthPi: ExtensionAPI | undefined;
|
|
|
872
930
|
*
|
|
873
931
|
* Markers live on RunMeta so reloads and repeated health ticks never re-fire.
|
|
874
932
|
* A marker means successful handoff only: written after sendMessage returns, or
|
|
875
|
-
* after
|
|
876
|
-
*
|
|
877
|
-
* `callback:false` suppresses the model message only
|
|
878
|
-
*
|
|
933
|
+
* after a UI warning under callback:false. An unavailable UI, failed or crashed
|
|
934
|
+
* delivery leaves the marker unset so reload/recovery can retry.
|
|
935
|
+
* `callback:false` suppresses the model message only; the scoped frontend UI
|
|
936
|
+
* is notified before recording quiet delivery. Uses the same followUp mechanics as
|
|
879
937
|
* completion, with distinct ATTENTION wording from buildHealthCallbackDelivery.
|
|
880
938
|
*/
|
|
881
939
|
function deliverHealthCallback(pi: ExtensionAPI | undefined, meta: RunMeta, status: "orphaned" | "lost", now: number): void {
|
|
940
|
+
if (managementPort) return;
|
|
882
941
|
if (!pi) return;
|
|
883
942
|
if (isHealthCallbackHandled(meta, status)) return;
|
|
943
|
+
if (callbackSuppressionReason(meta)) return;
|
|
884
944
|
|
|
885
945
|
const callback = meta.callback !== false;
|
|
886
946
|
const label = meta.name ? `${meta.name} (${meta.id})` : meta.id;
|
|
@@ -888,8 +948,16 @@ function deliverHealthCallback(pi: ExtensionAPI | undefined, meta: RunMeta, stat
|
|
|
888
948
|
const attention = pendingFailureAttention(failureState, now, { terminal: status === "lost" });
|
|
889
949
|
const delivery = buildHealthCallbackDelivery({ id: meta.id, label, status, callback });
|
|
890
950
|
if (!delivery) {
|
|
891
|
-
|
|
892
|
-
|
|
951
|
+
const current = readMeta(meta.id);
|
|
952
|
+
if (!current || current.status !== status || isHealthCallbackHandled(current, status) || callbackSuppressionReason(current)) return;
|
|
953
|
+
meta = current;
|
|
954
|
+
if (!uiCtx?.hasUI) return;
|
|
955
|
+
const notice = status === "orphaned"
|
|
956
|
+
? `Subagent ${label} lost supervision - related processes may still be alive (orphaned).`
|
|
957
|
+
: `Subagent ${label} is lost - no related process remains and no terminal result was observed.`;
|
|
958
|
+
try { uiCtx.ui.notify(notice, "warning"); }
|
|
959
|
+
catch { return; }
|
|
960
|
+
// The marker acknowledges quiet delivery, never a model turn.
|
|
893
961
|
if (status === "orphaned") meta.orphanedCallbackSentAt = now;
|
|
894
962
|
else meta.lostCallbackSentAt = now;
|
|
895
963
|
writeMeta(meta);
|
|
@@ -1007,12 +1075,24 @@ function sameOpenCalls(a: readonly OpenCallRecord[] | undefined, b: readonly Ope
|
|
|
1007
1075
|
*/
|
|
1008
1076
|
function deliverTimingWake(pi: ExtensionAPI | undefined, meta: RunMeta, kind: "deadline" | "stuck" | "tool-wait", key: string,
|
|
1009
1077
|
content: string, isHandled: (current: RunMeta) => boolean, markHandled: (at: number) => void): void {
|
|
1010
|
-
if (
|
|
1011
|
-
|
|
1078
|
+
if (managementPort) {
|
|
1079
|
+
foldTimingWakeReceipts(readMeta(meta.id) ?? meta);
|
|
1080
|
+
if (isHandled(readMeta(meta.id) ?? meta)) return;
|
|
1081
|
+
const receipt = timingWakeReceipt(meta.id, key);
|
|
1082
|
+
if (receipt !== undefined) { markHandled(receipt); return; }
|
|
1083
|
+
const current = readMeta(meta.id);
|
|
1084
|
+
const pending = (current?.timing?.pendingWakes ?? []).filter(wake => timingWakeReceipt(meta.id, wake.key) === undefined);
|
|
1085
|
+
const next = appendTimingWake(pending, { kind, key, content });
|
|
1086
|
+
if (next !== pending) patchTiming(meta.id, { pendingWakes: next });
|
|
1087
|
+
return;
|
|
1012
1088
|
}
|
|
1089
|
+
// Foreign/inactive foregrounds must leave the durable notification pending.
|
|
1090
|
+
if (callbackSuppressionReason(meta)) return;
|
|
1091
|
+
try { uiCtx?.ui.notify(content, "warning"); } catch { /* ignore */ }
|
|
1013
1092
|
if (!pi || meta.callback === false) { markHandled(Date.now()); return; }
|
|
1014
1093
|
void getCallbackBatcher(pi).deliverUrgent({
|
|
1015
1094
|
source: "subagent",
|
|
1095
|
+
receiptId: `timing:${meta.id}:${key}`,
|
|
1016
1096
|
id: meta.id,
|
|
1017
1097
|
label: timingLabel(meta),
|
|
1018
1098
|
status: key,
|
|
@@ -1030,10 +1110,51 @@ function deliverTimingWake(pi: ExtensionAPI | undefined, meta: RunMeta, kind: "d
|
|
|
1030
1110
|
return callbackSuppressionReason(current);
|
|
1031
1111
|
},
|
|
1032
1112
|
onDelivered: (at) => markHandled(at),
|
|
1033
|
-
onSuppressed: (
|
|
1113
|
+
onSuppressed: () => {},
|
|
1034
1114
|
});
|
|
1035
1115
|
}
|
|
1036
1116
|
|
|
1117
|
+
function replayTimingWakes(pi: ExtensionAPI, meta: RunMeta): void {
|
|
1118
|
+
if (managementPort || callbackSuppressionReason(meta)) return;
|
|
1119
|
+
meta = readMeta(meta.id) ?? meta;
|
|
1120
|
+
for (const wake of meta.timing?.pendingWakes ?? []) {
|
|
1121
|
+
if (timingWakeHandled(meta, wake.key)) continue;
|
|
1122
|
+
const eventId = `timing:${meta.id}:${wake.key}`;
|
|
1123
|
+
const entries = uiCtx?.sessionManager?.getBranch?.() ?? [];
|
|
1124
|
+
const receipt = entries.some((entry: any) => {
|
|
1125
|
+
const message = entry.type === "custom_message" ? entry : entry.type === "message" && entry.message?.role === "custom" ? entry.message : undefined;
|
|
1126
|
+
return message?.customType === `subagent-${wake.kind}` && message.details?.urgentEventId === eventId;
|
|
1127
|
+
});
|
|
1128
|
+
if (receipt) { receiptTimingWake(meta.id, wake.key, Date.now()); continue; }
|
|
1129
|
+
deliverTimingWake(pi, meta, wake.kind, wake.key, wake.content,
|
|
1130
|
+
() => timingWakeHandled(readMeta(meta.id) ?? meta, wake.key),
|
|
1131
|
+
at => receiptTimingWake(meta.id, wake.key, at));
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
function timingWakeHandled(meta: RunMeta, key: string): boolean {
|
|
1136
|
+
if (timingWakeReceipt(meta.id, key) !== undefined) return true;
|
|
1137
|
+
if (key === "deadline") return meta.timing?.deadlineWakeSentAt !== undefined;
|
|
1138
|
+
if (key.startsWith("tool-wait:")) return (meta.timing?.toolWaitAlerted ?? []).includes(key.slice(10));
|
|
1139
|
+
if (key.startsWith("stuck:")) return meta.timing?.stuckWakeSentAt !== undefined && (meta.timing.stuckAnchorAt ?? 0) >= Number(key.slice(6));
|
|
1140
|
+
return false;
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
function foldTimingWakeReceipts(meta: RunMeta): void {
|
|
1144
|
+
const pending = meta.timing?.pendingWakes ?? [];
|
|
1145
|
+
const acknowledged = pending.filter(wake => wake.key !== "timing-overflow" && timingWakeReceipt(meta.id, wake.key) !== undefined);
|
|
1146
|
+
if (!acknowledged.length || !meta.timing) return;
|
|
1147
|
+
const patch = { ...meta.timing, pendingWakes: pending.filter(wake => !acknowledged.includes(wake)) };
|
|
1148
|
+
for (const wake of acknowledged) {
|
|
1149
|
+
const at = timingWakeReceipt(meta.id, wake.key)!;
|
|
1150
|
+
if (wake.kind === "deadline") patch.deadlineWakeSentAt = at;
|
|
1151
|
+
if (wake.kind === "stuck") { patch.stuckWakeSentAt = at; patch.stuckAnchorAt = Math.max(patch.stuckAnchorAt ?? 0, Number(wake.key.slice(6))); }
|
|
1152
|
+
if (wake.kind === "tool-wait") patch.toolWaitAlerted = [...new Set([...(patch.toolWaitAlerted ?? []), wake.key.slice(10)])];
|
|
1153
|
+
}
|
|
1154
|
+
patchTiming(meta.id, patch);
|
|
1155
|
+
for (const wake of acknowledged) removeTimingReceipt(meta.id, wake.key);
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1037
1158
|
/** Stop a run for a timing reason and report it through the ordinary completion callback. */
|
|
1038
1159
|
function stopForTiming(pi: ExtensionAPI | undefined, id: string, reason: TimingStopReason, now: number): boolean {
|
|
1039
1160
|
if (!patchTiming(id, { stopReason: reason, stoppedAt: now })) return false;
|
|
@@ -1177,9 +1298,11 @@ function enforceTiming(pi: ExtensionAPI | undefined, meta: RunMeta, now: number)
|
|
|
1177
1298
|
|
|
1178
1299
|
/** One reconciliation + durable health-callback recovery pass. */
|
|
1179
1300
|
function reconcileHealth(): void {
|
|
1301
|
+
if (!managementPort) return;
|
|
1302
|
+
try { managementPort.assertCurrent(); } catch { stopHealthTicker(); return; }
|
|
1180
1303
|
const ctx = uiCtx;
|
|
1181
1304
|
const pi = healthPi;
|
|
1182
|
-
for (const summary of
|
|
1305
|
+
for (const summary of supervisedMetas()) {
|
|
1183
1306
|
if (!ownedByThisParent(summary)) continue;
|
|
1184
1307
|
// running/orphaned: process reconcile. lost: durable callback recovery only.
|
|
1185
1308
|
if (summary.status !== "running" && summary.status !== "orphaned" && summary.status !== "lost") continue;
|
|
@@ -1232,6 +1355,11 @@ function reconcileHealth(): void {
|
|
|
1232
1355
|
}
|
|
1233
1356
|
}
|
|
1234
1357
|
|
|
1358
|
+
// Canonical loss is an assignment terminal fact even when no recipient
|
|
1359
|
+
// is attached. This manager already proved current epoch, ownership and
|
|
1360
|
+
// process identity above; native foregrounds never enter this pass.
|
|
1361
|
+
if (meta.status === "lost" && meta.assignment && pi) enqueueCompletionCallback(pi, meta.id);
|
|
1362
|
+
|
|
1235
1363
|
// Durable recovery independent of a fresh transition: any current
|
|
1236
1364
|
// orphaned/lost without a successful handoff marker must eventually
|
|
1237
1365
|
// deliver exactly one coordinator follow-up (or mark callback:false).
|
|
@@ -1253,7 +1381,7 @@ function reconcileHealth(): void {
|
|
|
1253
1381
|
try { finalizeInterruptedRunFromLog(pi, meta, Date.now()); } catch { /* the next tick retries */ }
|
|
1254
1382
|
}
|
|
1255
1383
|
// Completed runs can still have failed completion handoffs to retry.
|
|
1256
|
-
for (const summary of
|
|
1384
|
+
for (const summary of supervisedMetas()) {
|
|
1257
1385
|
if (!pi || !ownedByThisParent(summary) || summary.status === "running" || summary.status === "orphaned" || summary.status === "lost") continue;
|
|
1258
1386
|
const meta = readMeta(summary.id);
|
|
1259
1387
|
if (meta && meta.completionCallbackPendingAt !== undefined && meta.completionCallbackSentAt === undefined && meta.completionCallbackSuppressedAt === undefined) enqueueCompletionCallback(pi!, meta.id);
|
|
@@ -1315,6 +1443,7 @@ function reconcileAbandonedRuns(now: number = Date.now()): number {
|
|
|
1315
1443
|
let adopted = 0;
|
|
1316
1444
|
try {
|
|
1317
1445
|
for (const summary of listMetas()) {
|
|
1446
|
+
if (summary.management && !ownedByThisParent(summary)) continue;
|
|
1318
1447
|
if (ownedByThisParent(summary)) continue;
|
|
1319
1448
|
if (summary.status !== "running" && summary.status !== "orphaned") continue;
|
|
1320
1449
|
if (!isAbandonedByParent(summary, realProcessProbe)) continue;
|
|
@@ -1335,6 +1464,7 @@ function reconcileAbandonedRuns(now: number = Date.now()): number {
|
|
|
1335
1464
|
|
|
1336
1465
|
/** Completion batches own their retry timer; only supervision keeps this one alive. */
|
|
1337
1466
|
function syncHealthTicker(): void {
|
|
1467
|
+
if (!managementPort) { stopHealthTicker(); return; }
|
|
1338
1468
|
// A replaced instance never restarts supervision loops for a session it no
|
|
1339
1469
|
// longer owns; the live instance runs its own. It must still STOP one that is
|
|
1340
1470
|
// already armed: a run this instance launched before teardown can finish
|
|
@@ -1344,12 +1474,13 @@ function syncHealthTicker(): void {
|
|
|
1344
1474
|
stopHealthTicker();
|
|
1345
1475
|
return;
|
|
1346
1476
|
}
|
|
1347
|
-
if (needsMonitoring(
|
|
1477
|
+
if (needsMonitoring(supervisedMetas()) || needsInterruptedSupervision()) ensureHealthTicker();
|
|
1348
1478
|
else stopHealthTicker();
|
|
1349
1479
|
}
|
|
1350
1480
|
|
|
1351
1481
|
/** Start the reconciliation loop if it isn't already running. */
|
|
1352
1482
|
function ensureHealthTicker(): void {
|
|
1483
|
+
if (!managementPort) return;
|
|
1353
1484
|
// Not gated on `sessionTornDown`: a spawn always means the current session is
|
|
1354
1485
|
// doing new work. Only `syncHealthTicker` — the path a late child finalizer
|
|
1355
1486
|
// takes — stays closed in a replaced instance.
|
|
@@ -1751,7 +1882,7 @@ function ensureSubagentProvider(): void {
|
|
|
1751
1882
|
saveDelegationDefault(readDelegation().mode);
|
|
1752
1883
|
return true;
|
|
1753
1884
|
},
|
|
1754
|
-
armCloseLabel: (row) => pendingNavigatorPark(
|
|
1885
|
+
armCloseLabel: (row) => pendingNavigatorPark(workObservation()?.rows.find((observed: any) => observed.meta.id === row.id)?.meta) ? "x again to cancel resume" : row.status === "running" || row.status === "orphaned" ? "x again to stop" : "x again to dismiss",
|
|
1755
1886
|
close: (id) => {
|
|
1756
1887
|
const outcome = navigatorCloseRun(id) as { action: string; id: string; status?: string };
|
|
1757
1888
|
return { ...outcome, providerId: "subagents" };
|
|
@@ -1918,7 +2049,8 @@ function finalizeInterruptedRunFromLog(
|
|
|
1918
2049
|
* so its recorded interruption is the only thing that can recover it. Anything
|
|
1919
2050
|
* else belongs to a live pi and is never adjudicated here.
|
|
1920
2051
|
*/
|
|
1921
|
-
function ownsInterruptedSupervision(summary: Pick<RunMeta, "spawnPid" | "spawnPidStartTime" | "supervisionInterruptedAt">): boolean {
|
|
2052
|
+
function ownsInterruptedSupervision(summary: Pick<RunMeta, "spawnPid" | "spawnPidStartTime" | "supervisionInterruptedAt" | "management">): boolean {
|
|
2053
|
+
if (summary.management) return Boolean(managementPort?.owns(summary));
|
|
1922
2054
|
if (summary.supervisionInterruptedAt === undefined) return false;
|
|
1923
2055
|
return ownedByThisParent(summary) || isAbandonedByParent(summary, realProcessProbe);
|
|
1924
2056
|
}
|
|
@@ -2147,7 +2279,11 @@ function continuationPlanFor(sessionId: string, origin: RunCallbackOrigin | unde
|
|
|
2147
2279
|
`Check the session id reported by the launching attempt, or omit session_id to start a new conversation.`,
|
|
2148
2280
|
);
|
|
2149
2281
|
}
|
|
2150
|
-
|
|
2282
|
+
// The activity index chooses the attempt, not its frozen execution recipe.
|
|
2283
|
+
// Another process may have republished the authoritative record since indexing.
|
|
2284
|
+
const current = readMeta(latest.id);
|
|
2285
|
+
if (!current) throw new ContinuationError(`Cannot continue ${latest.id}: its saved run record is unavailable.`);
|
|
2286
|
+
return planContinuation({ id: latest.id, prior: current, origin, others });
|
|
2151
2287
|
}
|
|
2152
2288
|
|
|
2153
2289
|
function timingSchemaFields() {
|
|
@@ -2190,7 +2326,8 @@ function discoveredSkillsFromContext(ctx: { getSystemPromptOptions?: () => { ski
|
|
|
2190
2326
|
}
|
|
2191
2327
|
}
|
|
2192
2328
|
|
|
2193
|
-
export default function (pi: ExtensionAPI) {
|
|
2329
|
+
export default function (pi: ExtensionAPI, managed?: import("./managed-launch-port.ts").ManagedLaunchPort) {
|
|
2330
|
+
managementPort = managed;
|
|
2194
2331
|
// A standalone Subagents install has no Harness extension, so the parent
|
|
2195
2332
|
// session applies the same linked-worktree project boundary as its children.
|
|
2196
2333
|
pi.on("before_agent_start", (event) => {
|
|
@@ -2338,13 +2475,16 @@ export default function (pi: ExtensionAPI) {
|
|
|
2338
2475
|
};
|
|
2339
2476
|
const activeDelegationMode = (): DelegationMode => delegationOverride ?? normalizeDelegationMode(loadConfig().delegationMode);
|
|
2340
2477
|
const countRunning = () =>
|
|
2341
|
-
listActiveMetasForParent(process.pid).filter((meta) =>
|
|
2478
|
+
listActiveMetasForParent(managed?.owner.pid ?? process.pid).filter((meta) =>
|
|
2479
|
+
(!managed || meta.spawnPidStartTime === managed.owner.start) && effectiveStatus(meta) === "running").length;
|
|
2480
|
+
const capacityGate = () => managed ? managed.capacity(countRunning) : getSharedCapacityGate(countRunning);
|
|
2342
2481
|
// Supervised worker operations: the Background observed-waits service owns
|
|
2343
2482
|
// durable records, this extension owns the trusted transport its children
|
|
2344
2483
|
// talk to. Both are absent in a standalone Subagents install, which is why
|
|
2345
2484
|
// the bridge is optional and parking refuses instead of pretending.
|
|
2346
2485
|
const workerOperations: WorkerOperationsHost = createWorkerOperationsHost({
|
|
2347
2486
|
pi,
|
|
2487
|
+
managedRoot: managed?.identity.root,
|
|
2348
2488
|
childExtensionPath: childBridgeExtensionPath(selfDir()),
|
|
2349
2489
|
});
|
|
2350
2490
|
let resumeOrchestration: ResumeOrchestration | undefined;
|
|
@@ -2376,7 +2516,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2376
2516
|
sources: { toolWaitMinutes: timing.toolWaitSource, stuckMinutes: timing.stuckSource },
|
|
2377
2517
|
...(timing.timingError ? { error: timing.timingError } : {}),
|
|
2378
2518
|
},
|
|
2379
|
-
}, countRunning(),
|
|
2519
|
+
}, countRunning(), capacityGate().pending);
|
|
2380
2520
|
};
|
|
2381
2521
|
const saveSettings = (): { ok: boolean; message: string } => {
|
|
2382
2522
|
try {
|
|
@@ -2527,7 +2667,15 @@ export default function (pi: ExtensionAPI) {
|
|
|
2527
2667
|
const registeredSpawnSchemas = new Map<string, object>();
|
|
2528
2668
|
const registerSpawnTool: ExtensionAPI["registerTool"] = (definition) => {
|
|
2529
2669
|
registeredSpawnSchemas.set(definition.name, definition.parameters);
|
|
2530
|
-
pi.registerTool(definition)
|
|
2670
|
+
pi.registerTool(managed ? { ...definition, async execute(key, params, signal, onUpdate, ctx) {
|
|
2671
|
+
restoreDelegationMode(ctx);
|
|
2672
|
+
await workerOperations.start();
|
|
2673
|
+
return definition.execute(key, params, signal, onUpdate, ctx);
|
|
2674
|
+
} } : { ...definition, async execute(key, params, _signal, _onUpdate, ctx) {
|
|
2675
|
+
catalogHostFrom(ctx);
|
|
2676
|
+
const { submitManagedLaunch } = await import("./managed-launch-client.ts");
|
|
2677
|
+
return await submitManagedLaunch(pi, ctx, key, definition.name, params) as never;
|
|
2678
|
+
} });
|
|
2531
2679
|
};
|
|
2532
2680
|
announceExecutionAdapter(pi, {
|
|
2533
2681
|
parametersFor: (name) => registeredSpawnSchemas.get(name),
|
|
@@ -2547,7 +2695,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2547
2695
|
}
|
|
2548
2696
|
|
|
2549
2697
|
function catalogHostFrom(ctx: ExtensionContext): CatalogHost {
|
|
2550
|
-
noteCatalogHostContext(ctx, () => agentSessionSettings.snapshot());
|
|
2698
|
+
if (!managed) noteCatalogHostContext(ctx, () => agentSessionSettings.snapshot());
|
|
2551
2699
|
if (typeof ctx.sessionManager?.getBranch === "function") agentSessionSettings.restore(ctx);
|
|
2552
2700
|
catalogModelRegistry = ctx.modelRegistry;
|
|
2553
2701
|
const cfg = loadConfig();
|
|
@@ -2590,7 +2738,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2590
2738
|
if (!jobs.some((job) => hasCatalogSelector(job))) {
|
|
2591
2739
|
return { status: "ready", jobs: jobs as SpawnParams[] };
|
|
2592
2740
|
}
|
|
2593
|
-
const snapshot = await loadSharedLaunchSnapshot(host);
|
|
2741
|
+
const snapshot = managed ? await managed.snapshot(host) : await loadSharedLaunchSnapshot(host);
|
|
2594
2742
|
const clarified = await clarifyCatalogRequest(jobs, { hasUI: host.hasUI === true, select: host.select });
|
|
2595
2743
|
if (clarified.status === "clarification-needed") return clarified;
|
|
2596
2744
|
const prepared: SpawnParams[] = [];
|
|
@@ -2759,7 +2907,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2759
2907
|
|
|
2760
2908
|
// An auto-resume carries the attempt id the coordinator already published;
|
|
2761
2909
|
// a fresh or manual launch allocates a new one.
|
|
2762
|
-
const id = internal?.assignedRunId ?? nextRunId();
|
|
2910
|
+
const id = internal?.assignedRunId ?? managed?.attempt() ?? nextRunId();
|
|
2763
2911
|
// Attempt identity (`id`) and conversation identity (`sessionId`) are
|
|
2764
2912
|
// separate. A continuation keeps the native session; only the attempt is new.
|
|
2765
2913
|
const sessionId = resume ? resume.conversation.sessionId : id;
|
|
@@ -2872,6 +3020,15 @@ export default function (pi: ExtensionAPI) {
|
|
|
2872
3020
|
explicitTools: requestedTools !== undefined,
|
|
2873
3021
|
productionSchemas: new Set(productionBridgeSchemas.schemas.keys()),
|
|
2874
3022
|
});
|
|
3023
|
+
if (managed) {
|
|
3024
|
+
const captured = new Set(managed.backgroundTools());
|
|
3025
|
+
bridgePlan.tools = bridgePlan.tools.filter(name => captured.has(name));
|
|
3026
|
+
if (requestedTools && requestedTools.split(",").some(name => DEFAULT_WORKER_BRIDGE_TOOLS.includes(name.trim() as any) && !captured.has(name.trim()))) {
|
|
3027
|
+
throw new Error("The original Pi host did not authorize the requested Background capability");
|
|
3028
|
+
}
|
|
3029
|
+
const has = (name: string) => bridgePlan.tools.includes(name as any);
|
|
3030
|
+
bridgePlan.capabilities = { background: { spawn: has("bg_task_spawn"), watch: has("bg_task_watch"), status: has("bg_task_status"), log: has("bg_task_log") }, wait: has("wait_for_operations"), acknowledge: has("acknowledge_operation_result"), parking: has("wait_for_operations") };
|
|
3031
|
+
}
|
|
2875
3032
|
const parent = ownerBindingFromContext(ctx);
|
|
2876
3033
|
const assignment: AssignmentBinding | undefined = internal?.resumeWait && resume?.prior.assignment
|
|
2877
3034
|
? resume.prior.assignment
|
|
@@ -3083,7 +3240,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
3083
3240
|
try { ctx.ui?.notify?.(`Subagent ${id}: recovery snapshot failed (run continues): ${outcome.detail}`, "warning"); } catch { /* ignore */ }
|
|
3084
3241
|
});
|
|
3085
3242
|
}
|
|
3086
|
-
const cmd = taskRuntime ? { file: taskRuntime.file, fileArgs: [...taskRuntime.fileArgs, ...args] }
|
|
3243
|
+
const cmd = taskRuntime ? { file: taskRuntime.file, fileArgs: [...taskRuntime.fileArgs, ...args] }
|
|
3244
|
+
: managed ? managed.workerCommand(args)
|
|
3245
|
+
: { file: process.execPath, fileArgs: [join(selfDir(), "child-runtime.mjs"), resolvePiBinary(), ...args] };
|
|
3087
3246
|
const sandboxDir = taskRuntime ? requestedSandboxDir : undefined;
|
|
3088
3247
|
|
|
3089
3248
|
// Reservations prevent competing admissions, but do not grandfather
|
|
@@ -3098,7 +3257,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
3098
3257
|
// letting two processes rewrite one session file. A fresh launch has a
|
|
3099
3258
|
// brand-new native session id, so it cannot contend with anyone and
|
|
3100
3259
|
// needs no lease; every continuation does.
|
|
3101
|
-
if (resume) {
|
|
3260
|
+
if (resume || managed) {
|
|
3102
3261
|
lease = acquireConversationLease({ sessionId, attemptId: id });
|
|
3103
3262
|
}
|
|
3104
3263
|
// The lease is the first moment no other process can retire this
|
|
@@ -3184,67 +3343,33 @@ export default function (pi: ExtensionAPI) {
|
|
|
3184
3343
|
...(taskRuntime.policy.permissions ? { permissions: taskRuntime.policy.permissions } : {}),
|
|
3185
3344
|
...(taskRuntime.policy.denyWrite ? { denyWrite: [...taskRuntime.policy.denyWrite] } : {}),
|
|
3186
3345
|
} : null;
|
|
3187
|
-
assertAssignmentPermissionScope(captured, { sandbox: currentSandbox, mandatoryPermissions: permissionPlan.enforced });
|
|
3346
|
+
assertAssignmentPermissionScope(captured, { sandbox: currentSandbox, mandatoryPermissions: permissionPlan.enforced }, Boolean(managed));
|
|
3188
3347
|
}
|
|
3189
|
-
|
|
3190
|
-
spawned = releaseChild(dispatchGuard, () => spawnDetached({ file: cmd.file, fileArgs: cmd.fileArgs, cwd, logPath: logPathFor(id),
|
|
3191
|
-
env: {
|
|
3192
|
-
[STEER_FILE_ENV]: steerPathFor(id),
|
|
3193
|
-
[PREFLIGHT_ENV]: preflightPath,
|
|
3194
|
-
...(workerBridge?.env ?? {}),
|
|
3195
|
-
} }));
|
|
3196
|
-
internal?.onSpawned?.();
|
|
3197
|
-
// Record process identity (pgid, start-time token) so health
|
|
3198
|
-
// reconciliation can tell a supervised child from a recycled pid
|
|
3199
|
-
// or an orphaned process group (#63). Best-effort: when the OS
|
|
3200
|
-
// probes are unavailable the fields stay absent and the run is
|
|
3201
|
-
// reconciled via the conservative old-metadata path.
|
|
3202
|
-
const identity = captureProcessIdentity(spawned.pid, spawnIdentityProbe);
|
|
3203
|
-
const startedAt = Date.now();
|
|
3204
|
-
// The effective launch recipe is frozen on the attempt so a later
|
|
3205
|
-
// continuation can reproduce its runtime intent without re-resolving the
|
|
3206
|
-
// catalog or guessing from current configuration.
|
|
3348
|
+
// Freeze the ordinary recipe before the durable external-launch intent.
|
|
3207
3349
|
const recipe = buildLaunchRecipe({
|
|
3208
|
-
attemptId: id,
|
|
3209
|
-
|
|
3210
|
-
|
|
3211
|
-
|
|
3212
|
-
|
|
3213
|
-
|
|
3214
|
-
tools: callerLaunchTools(allow),
|
|
3215
|
-
excludeTools: requestedExcludes.size ? [...requestedExcludes].join(",") : undefined,
|
|
3216
|
-
skills: skills.mode === "inherit" ? undefined : [...skills.paths],
|
|
3217
|
-
clean,
|
|
3218
|
-
allowNested,
|
|
3219
|
-
approve,
|
|
3220
|
-
sandbox: sandboxEnabled,
|
|
3221
|
-
sandboxDir: requestedSandboxDir,
|
|
3222
|
-
gitCloneWorkspace,
|
|
3223
|
-
callback: callbackEnabled,
|
|
3224
|
-
name: launchName,
|
|
3225
|
-
agent: resume ? resume.recipe.agent : p.agent,
|
|
3226
|
-
role: resume ? resume.recipe.role : p.role,
|
|
3227
|
-
alias: resume ? resume.recipe.alias : p.alias,
|
|
3228
|
-
catalog: launchCatalog,
|
|
3229
|
-
extensionArgs: extArgs,
|
|
3230
|
-
baseExtensionArgs,
|
|
3350
|
+
attemptId: id, sessionId, sessionDir: childSessionDir, cwd, model, effort: thinking,
|
|
3351
|
+
tools: callerLaunchTools(allow), excludeTools: requestedExcludes.size ? [...requestedExcludes].join(",") : undefined,
|
|
3352
|
+
skills: skills.mode === "inherit" ? undefined : [...skills.paths], clean, allowNested, approve,
|
|
3353
|
+
sandbox: sandboxEnabled, sandboxDir: requestedSandboxDir, gitCloneWorkspace, callback: callbackEnabled, name: launchName,
|
|
3354
|
+
agent: resume ? resume.recipe.agent : p.agent, role: resume ? resume.recipe.role : p.role,
|
|
3355
|
+
alias: resume ? resume.recipe.alias : p.alias, catalog: launchCatalog, extensionArgs: extArgs, baseExtensionArgs,
|
|
3231
3356
|
trustedExtensions: resume?.recipe.trustedExtensions ?? taskTools?.trusted.map(({ name, package: owner, loadPath }) => ({ name, package: owner, loadPath })),
|
|
3232
3357
|
});
|
|
3233
|
-
|
|
3358
|
+
const startedAt = Date.now();
|
|
3234
3359
|
const meta: RunMeta = {
|
|
3235
3360
|
assignment,
|
|
3236
3361
|
outcomeSupport: { version: 1, available: Boolean(assignment), ...(!assignment ? { reason: "Legacy host has no verified parent session/transcript; durable assignment delivery is unavailable." } : {}) },
|
|
3237
3362
|
id, name: launchName, status: "running",
|
|
3238
|
-
pid:
|
|
3363
|
+
pid: 0, spawnPid: managed?.owner.pid ?? process.pid, spawnPidStartTime: managed?.owner.start ?? parentStartToken(), model,
|
|
3239
3364
|
effort: thinking, cwd,
|
|
3240
3365
|
...(skills.mode === "inherit" ? {} : { skills: [...skills.paths] }),
|
|
3241
3366
|
skillsSource: skills.source,
|
|
3242
|
-
...identity,
|
|
3243
3367
|
promptPreview: p.prompt.slice(0, 200),
|
|
3244
3368
|
startedAt, logPath: logPathFor(id), sessionId,
|
|
3245
3369
|
rootRunId,
|
|
3246
3370
|
...(resume ? { resumedFrom: resume.prior.id } : {}),
|
|
3247
3371
|
recipe,
|
|
3372
|
+
...(managed ? { management: managed.identity } : {}),
|
|
3248
3373
|
callbackOrigin,
|
|
3249
3374
|
sandbox: sandboxDir, taskRuntime: Boolean(taskRuntime), taskScratch: taskRuntime?.policy.scratch, callback: callbackEnabled,
|
|
3250
3375
|
...batchInfo,
|
|
@@ -3282,6 +3407,25 @@ export default function (pi: ExtensionAPI) {
|
|
|
3282
3407
|
} : {}),
|
|
3283
3408
|
timing: resolveRunTiming({ params: launchTimingParams(p), settings: timingSettingsFor(cfg), env: process.env, startedAt }),
|
|
3284
3409
|
};
|
|
3410
|
+
const dispatchGuard = await internal?.beforeSpawn?.({ runId: id, permissionPlan });
|
|
3411
|
+
const managedEnv = managed?.beforeSpawn({ id, sessionId, lease: lease!.token, leasePath: lease!.path,
|
|
3412
|
+
preflightPath, policyPath: taskRuntime?.policyPath, permissions: permissionPlan, recipe, recoveryMeta: meta });
|
|
3413
|
+
spawned = releaseChild(dispatchGuard, () => spawnDetached({ file: cmd.file, fileArgs: cmd.fileArgs, cwd, logPath: logPathFor(id),
|
|
3414
|
+
env: {
|
|
3415
|
+
[STEER_FILE_ENV]: steerPathFor(id),
|
|
3416
|
+
[PREFLIGHT_ENV]: preflightPath,
|
|
3417
|
+
...(workerBridge?.env ?? {}),
|
|
3418
|
+
...(managedEnv ?? {}),
|
|
3419
|
+
} }));
|
|
3420
|
+
managed?.spawned(id, spawned.pid);
|
|
3421
|
+
internal?.onSpawned?.();
|
|
3422
|
+
// Record process identity (pgid, start-time token) so health
|
|
3423
|
+
// reconciliation can tell a supervised child from a recycled pid
|
|
3424
|
+
// or an orphaned process group (#63). Best-effort: when the OS
|
|
3425
|
+
// probes are unavailable the fields stay absent and the run is
|
|
3426
|
+
// reconciled via the conservative old-metadata path.
|
|
3427
|
+
const identity = captureProcessIdentity(spawned.pid, spawnIdentityProbe);
|
|
3428
|
+
Object.assign(meta, { pid: spawned.pid, ...identity });
|
|
3285
3429
|
// This instance holds the exit observer for a run it actually
|
|
3286
3430
|
// started; only it can finalize on the exit event (#625).
|
|
3287
3431
|
directlySupervisedRunIds.add(id);
|
|
@@ -3406,7 +3550,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
3406
3550
|
* (must be held).
|
|
3407
3551
|
*/
|
|
3408
3552
|
async function launchParkedResume(input: ResumeLaunchInput): Promise<void> {
|
|
3409
|
-
const ctx = uiCtx;
|
|
3553
|
+
const ctx = managed?.continuationContext?.() ?? uiCtx;
|
|
3410
3554
|
if (!ctx || sessionTornDown) {
|
|
3411
3555
|
throw new PreSpawnResumeError("No active foreground session can resume the parked assignment.");
|
|
3412
3556
|
}
|
|
@@ -3468,7 +3612,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
3468
3612
|
// Getter, not a captured value: the foreground context can be
|
|
3469
3613
|
// replaced during the asynchronous preparation.
|
|
3470
3614
|
service: () => workerOperations.service,
|
|
3471
|
-
context: () => uiCtx,
|
|
3615
|
+
context: () => managed?.continuationContext?.() ?? uiCtx,
|
|
3472
3616
|
park: input.park,
|
|
3473
3617
|
claim: input.claim,
|
|
3474
3618
|
owner,
|
|
@@ -3529,7 +3673,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
3529
3673
|
* unresumable claim; the recheck covers a cap reduced in the meantime.
|
|
3530
3674
|
*/
|
|
3531
3675
|
function resumeCapacity(): ResumeCapacity {
|
|
3532
|
-
const gate =
|
|
3676
|
+
const gate = capacityGate;
|
|
3533
3677
|
return {
|
|
3534
3678
|
tryReserve: () => gate().tryReserve(1, activeConcurrencyCap()),
|
|
3535
3679
|
recheck: () => countRunning() + gate().pending <= activeConcurrencyCap(),
|
|
@@ -3542,9 +3686,11 @@ export default function (pi: ExtensionAPI) {
|
|
|
3542
3686
|
function ensureResumeOrchestration(): ResumeOrchestration {
|
|
3543
3687
|
resumeOrchestration ??= createResumeOrchestration({
|
|
3544
3688
|
pi,
|
|
3689
|
+
leaseOwnerId: managed ? `managed-subagents:${managed.identity.instance}` : undefined,
|
|
3545
3690
|
service: () => workerOperations.service,
|
|
3546
3691
|
rpc: workerOperations.rpc,
|
|
3547
|
-
context: () => uiCtx,
|
|
3692
|
+
context: () => managed?.continuationContext?.() ?? uiCtx,
|
|
3693
|
+
...(managed?.dispatchContinuation ? { dispatch: managed.dispatchContinuation } : {}),
|
|
3548
3694
|
capacity: resumeCapacity(),
|
|
3549
3695
|
launch: launchParkedResume,
|
|
3550
3696
|
stopAttempt: stopPublishedAttempt,
|
|
@@ -3572,11 +3718,16 @@ export default function (pi: ExtensionAPI) {
|
|
|
3572
3718
|
service.registerContinuationAdapter(orchestration.adapter);
|
|
3573
3719
|
} catch { /* a host that refuses the adapter leaves parking unavailable */ }
|
|
3574
3720
|
try {
|
|
3575
|
-
|
|
3721
|
+
const reconciliation = reconcileParkedWaits(service, {
|
|
3576
3722
|
resume: (park) => orchestration.resume(park),
|
|
3577
3723
|
notifyWhen: (meta) => Boolean(activeCallbackOrigin && belongsToOrigin(meta, activeCallbackOrigin)),
|
|
3578
3724
|
notify: notifyOwnedWait,
|
|
3579
3725
|
});
|
|
3726
|
+
if (managed) {
|
|
3727
|
+
void reconciliation.catch(() => undefined);
|
|
3728
|
+
return;
|
|
3729
|
+
}
|
|
3730
|
+
await reconciliation;
|
|
3580
3731
|
const historical = historicalWaits(activeCallbackOrigin);
|
|
3581
3732
|
if (historical.length && activeCallbackOrigin && !attentionDismissed(activeCallbackOrigin.cwd, attentionRevision(historical))) {
|
|
3582
3733
|
uiCtx?.ui?.notify?.(`${historical.length} historical subagent waits remain. Inspect or cancel with /subagents history; dismiss this notice with /subagents history dismiss.`, "warning");
|
|
@@ -3658,7 +3809,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
3658
3809
|
const maxConcurrent = activeConcurrencyCap();
|
|
3659
3810
|
// Shared with batch-spawn: reserve before any async work so an interleaved
|
|
3660
3811
|
// batch cannot oversubscribe after this check and before writeMeta.
|
|
3661
|
-
const gate =
|
|
3812
|
+
const gate = capacityGate();
|
|
3662
3813
|
if (!gate.tryReserve(1, maxConcurrent)) {
|
|
3663
3814
|
throw new Error(`Max concurrent subagents (${maxConcurrent}) reached. Stop or let some finish first.`);
|
|
3664
3815
|
}
|
|
@@ -3850,7 +4001,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
3850
4001
|
const launchAvailable = p.onCapacity === "launch-available";
|
|
3851
4002
|
// Shared with single-spawn. Reservations count against maxConcurrent so a
|
|
3852
4003
|
// concurrent single spawn cannot take a slot the batch already admitted.
|
|
3853
|
-
const gate =
|
|
4004
|
+
const gate = capacityGate();
|
|
3854
4005
|
|
|
3855
4006
|
// session_id selects one saved conversation, so it is per job: a shared
|
|
3856
4007
|
// value would point every job at the same conversation writer.
|
|
@@ -3874,7 +4025,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
3874
4025
|
if (needsCatalog) {
|
|
3875
4026
|
catalogHost = catalogHostFrom(ctx);
|
|
3876
4027
|
noteCatalogHost(catalogHost);
|
|
3877
|
-
catalogSnapshot = await loadSharedLaunchSnapshot(catalogHost);
|
|
4028
|
+
catalogSnapshot = managed ? await managed.snapshot(catalogHost) : await loadSharedLaunchSnapshot(catalogHost);
|
|
3878
4029
|
const clarified = await clarifyCatalogRequest(
|
|
3879
4030
|
p.jobs.map((job) => mergeJobOptions(p.shared, job) as CatalogJobFields),
|
|
3880
4031
|
{ hasUI: catalogHost.hasUI === true, select: catalogHost.select },
|
|
@@ -4340,13 +4491,23 @@ export default function (pi: ExtensionAPI) {
|
|
|
4340
4491
|
catch { mainAgentStartedAt = undefined; }
|
|
4341
4492
|
mainAgentTools.clear();
|
|
4342
4493
|
activeCallbackOrigin = callbackOriginFromContext(ctx);
|
|
4343
|
-
|
|
4344
|
-
|
|
4494
|
+
pendingRecipientRecovery.clear();
|
|
4495
|
+
observedRecipientRows.clear();
|
|
4496
|
+
if (!managed && activeCallbackOrigin) await startWorkObservation(PiCodingAgent.getAgentDir(), activeCallbackOrigin, () => {
|
|
4497
|
+
refreshBackgroundWorkNavigator(ctx);
|
|
4498
|
+
observeRecipientNotifications(pi);
|
|
4499
|
+
});
|
|
4500
|
+
if (!managed) {
|
|
4501
|
+
recoverCompletionCallbacks(pi);
|
|
4502
|
+
observeRecipientNotifications(pi);
|
|
4503
|
+
}
|
|
4345
4504
|
// Admission can defer before batcher enqueue, even after the last child
|
|
4346
4505
|
// exits. Keep reconciliation independent of the live-run health ticker.
|
|
4347
4506
|
if (outcomeTicker) clearInterval(outcomeTicker);
|
|
4348
|
-
|
|
4349
|
-
|
|
4507
|
+
if (!managed) {
|
|
4508
|
+
outcomeTicker = setInterval(() => recoverAssignmentOutcomes(pi), 1000);
|
|
4509
|
+
outcomeTicker.unref?.();
|
|
4510
|
+
}
|
|
4350
4511
|
// Reload / session switch hardening (#48):
|
|
4351
4512
|
// - Drop any leftover overlay timers/confirm state from a prior session
|
|
4352
4513
|
// (defensive if the host skipped session_shutdown before re-start).
|
|
@@ -4360,10 +4521,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
4360
4521
|
// supervises them until they exit. This runs BEFORE abandonment
|
|
4361
4522
|
// adoption: a finished child's coherent log is terminal evidence, and
|
|
4362
4523
|
// `lost` would otherwise win the race and hide the result.
|
|
4363
|
-
recoverInterruptedSubagents(pi);
|
|
4524
|
+
if (managed) recoverInterruptedSubagents(pi);
|
|
4525
|
+
if (managed) for (const meta of managed.supervised()) {
|
|
4526
|
+
if (meta.assignment) commitAssignmentTerminal(meta);
|
|
4527
|
+
}
|
|
4364
4528
|
// Adopt records left non-terminal by a pi that died without a clean
|
|
4365
4529
|
// shutdown, so the age sweep can eventually retire them.
|
|
4366
|
-
reconcileAbandonedRuns();
|
|
4530
|
+
if (managed) reconcileAbandonedRuns();
|
|
4367
4531
|
disposeBackgroundWorkNavigator(ctx, navigatorOwner);
|
|
4368
4532
|
widgetNavActive = false;
|
|
4369
4533
|
widgetNavSelectedId = undefined;
|
|
@@ -4378,7 +4542,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
4378
4542
|
// Supervised worker operations (ADR 0020): the bridge host is bound to this
|
|
4379
4543
|
// process, and parked generations from a previous session are reconciled
|
|
4380
4544
|
// against the durable coordinator before anything resumes.
|
|
4381
|
-
|
|
4545
|
+
if (managed) await startWorkerOperations();
|
|
4382
4546
|
});
|
|
4383
4547
|
|
|
4384
4548
|
pi.on("session_before_switch", () => {
|
|
@@ -4413,7 +4577,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
4413
4577
|
// from the child's own log.
|
|
4414
4578
|
const reason = typeof event?.reason === "string" ? event.reason : "shutdown";
|
|
4415
4579
|
try {
|
|
4416
|
-
const interrupted = interruptCurrentSessionSubagents(reason, ctx);
|
|
4580
|
+
const interrupted = managed ? [] : interruptCurrentSessionSubagents(reason, ctx);
|
|
4417
4581
|
warnInterruptedSubagents(ctx, interrupted, reason);
|
|
4418
4582
|
} catch { /* shutdown cleanup must never block the session teardown */ }
|
|
4419
4583
|
// Late finalizers of surviving children must not restart supervision
|
|
@@ -4424,7 +4588,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
4424
4588
|
// to a replaced session's handlers. Durable wait records are untouched.
|
|
4425
4589
|
try { resumeOrchestration?.stop(); } catch { /* best effort */ }
|
|
4426
4590
|
resumeOrchestration = undefined;
|
|
4427
|
-
|
|
4591
|
+
await workerOperations.close().catch(() => {});
|
|
4428
4592
|
// Children keep running; their finalizers (if this instance still holds
|
|
4429
4593
|
// one) must not reach for a ctx that Pi invalidates once the session is
|
|
4430
4594
|
// replaced.
|