@xzzpig/pi-subagents 0.8.0 → 0.10.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/CHANGELOG.md +477 -0
- package/README.md +2 -2
- package/agents/claude-code-writer.md +15 -0
- package/agents/claude-code.md +15 -0
- package/agents/codex-exec-writer.md +15 -0
- package/agents/codex-exec.md +15 -0
- package/agents/cursor-agent-writer.md +14 -0
- package/agents/cursor-agent.md +14 -0
- package/agents/reviewer.md +1 -1
- package/agents/scout.md +1 -1
- package/docs/agents.md +195 -39
- package/docs/configuration.md +81 -22
- package/docs/extension-api.md +69 -14
- package/docs/missions.md +2 -0
- package/docs/models.md +32 -9
- package/docs/observability.md +22 -20
- package/docs/tool-reference.md +123 -14
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +142 -4
- package/install.mjs +1 -1
- package/package.json +7 -6
- package/prompts/review-loop.md +2 -2
- package/skills/council-mode/SKILL.md +48 -243
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +89 -35
- package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
- package/skills/pi-subagents/references/execution-controls.md +91 -15
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +384 -115
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +14 -2
- package/src/agents/agents.ts +935 -372
- package/src/agents/builtin-names.ts +6 -0
- package/src/agents/runtime-agent-events.ts +70 -0
- package/src/agents/runtime-agent-registry.ts +42 -21
- package/src/api/agents.ts +10 -5
- package/src/api/background-work.ts +12 -3
- package/src/api/capability-ceiling.ts +0 -1
- package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
- package/src/api/delegation.ts +0 -7
- package/src/api/external-runs.ts +67 -4
- package/src/api/preflight.ts +77 -21
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +5 -13
- package/src/extension/fanout-child.ts +14 -14
- package/src/extension/index.ts +115 -37
- package/src/extension/public-execution.ts +103 -15
- package/src/extension/rpc.ts +120 -25
- package/src/extension/schemas.ts +65 -29
- package/src/extension/tool-description.ts +48 -26
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +51 -3
- package/src/intercom/native-supervisor-channel.ts +138 -60
- package/src/intercom/result-intercom.ts +7 -0
- package/src/intercom/supervisor-ui.ts +243 -0
- package/src/profiles/profiles.ts +5 -6
- package/src/runs/background/active-async-capacity.ts +103 -18
- package/src/runs/background/async-execution.ts +417 -133
- package/src/runs/background/async-job-tracker.ts +95 -15
- package/src/runs/background/async-resume.ts +60 -28
- package/src/runs/background/async-retention.ts +20 -3
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +204 -14
- package/src/runs/background/auto-drain.ts +1 -1
- package/src/runs/background/chain-append.ts +8 -3
- package/src/runs/background/chain-root-attachment.ts +74 -8
- package/src/runs/background/control-channel.ts +4 -205
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +238 -12
- package/src/runs/background/process-terminal.ts +16 -0
- package/src/runs/background/result-delivery-ownership.ts +45 -0
- package/src/runs/background/result-files.ts +28 -14
- package/src/runs/background/result-watcher.ts +39 -16
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/retained-children.ts +1 -1
- package/src/runs/background/run-child-session.ts +613 -0
- package/src/runs/background/run-status.ts +84 -17
- package/src/runs/background/runner-aliases.ts +125 -0
- package/src/runs/background/runner-child-sessions.ts +31 -0
- package/src/runs/background/scheduled-runs.ts +174 -18
- package/src/runs/background/stale-run-reconciler.ts +10 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +718 -1161
- package/src/runs/background/subagent-wait.ts +86 -31
- package/src/runs/background/terminal-run-index.ts +1 -1
- package/src/runs/background/wait-completions.ts +43 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +26 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/execution.ts +489 -499
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +23 -1
- package/src/runs/foreground/subagent-executor.ts +1223 -402
- package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
- package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
- package/src/runs/shared/abort-recovery.ts +119 -0
- package/src/runs/shared/acceptance.ts +138 -36
- package/src/runs/shared/async-status-projection.ts +565 -0
- package/src/runs/shared/background-process-options.ts +9 -0
- package/src/runs/shared/capability-ceiling.ts +2 -2
- package/src/runs/shared/child-hooks.ts +25 -0
- package/src/runs/shared/child-identity.ts +32 -6
- package/src/runs/shared/child-launch-plan.ts +151 -0
- package/src/runs/shared/child-launch.ts +364 -0
- package/src/runs/shared/child-lifecycle.ts +25 -0
- package/src/runs/shared/child-runtime-config.ts +126 -0
- package/src/runs/shared/child-session.ts +366 -0
- package/src/runs/shared/child-tool-plan.ts +632 -0
- package/src/runs/shared/claude-code-adapter.ts +133 -0
- package/src/runs/shared/codex-exec-adapter.ts +129 -0
- package/src/runs/shared/completion-evidence.ts +89 -0
- package/src/runs/shared/completion-guard.ts +6 -5
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +3 -3
- package/src/runs/shared/external-cli-contract.ts +167 -0
- package/src/runs/shared/external-cli-preflight.ts +138 -0
- package/src/runs/shared/external-cli-runner.ts +348 -55
- package/src/runs/shared/fast-mode-extension.ts +5 -5
- package/src/runs/shared/host-step-status.ts +231 -0
- package/src/runs/shared/lane-metadata.ts +126 -0
- package/src/runs/shared/launch-cwd.ts +16 -0
- package/src/runs/shared/long-running-guard.ts +2 -1
- package/src/runs/shared/mcp-config-sources.ts +422 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
- package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
- package/src/runs/shared/model-exclusions.ts +139 -9
- package/src/runs/shared/model-fallback.ts +146 -14
- package/src/runs/shared/mutation-evidence.ts +57 -3
- package/src/runs/shared/nested-events.ts +99 -77
- package/src/runs/shared/nested-path.ts +0 -14
- package/src/runs/shared/nested-render.ts +9 -5
- package/src/runs/shared/orca-progress-tabs.ts +12 -7
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +20 -7
- package/src/runs/shared/permissions.ts +1 -14
- package/src/runs/shared/pi-spawn.ts +69 -35
- package/src/runs/shared/process-signal.ts +16 -0
- package/src/runs/shared/run-fanout-budget.ts +0 -13
- package/src/runs/shared/run-history.ts +21 -1
- package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
- package/src/runs/shared/sandbox-profile-guard.ts +85 -0
- package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
- package/src/runs/shared/single-output.ts +89 -22
- package/src/runs/shared/structured-output.ts +49 -9
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -62
- package/src/runs/shared/tool-budget.ts +0 -14
- package/src/runs/shared/tool-timeout.ts +1 -1
- package/src/runs/shared/workflow-graph.ts +16 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
- package/src/runs/shared/worktree.ts +571 -62
- package/src/shared/atomic-json.ts +3 -1
- package/src/shared/child-session-name.ts +46 -0
- package/src/shared/extension-context.ts +24 -0
- package/src/shared/fork-context.ts +21 -12
- package/src/shared/fork-session-cwd.ts +27 -0
- package/src/shared/formatters.ts +18 -3
- package/src/shared/jsonl-writer.ts +11 -0
- package/src/shared/launch-contract.ts +11 -1
- package/src/shared/pruned-fork.ts +450 -0
- package/src/shared/sandbox-profile.ts +23 -0
- package/src/shared/session-file-trust.ts +19 -0
- package/src/shared/session-tokens.ts +14 -3
- package/src/shared/settings.ts +19 -105
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +0 -6
- package/src/shared/types.ts +545 -70
- package/src/shared/utils.ts +60 -93
- package/src/shared/workflow-child-permit.ts +207 -0
- package/src/slash/delegation-adapters.ts +1 -9
- package/src/slash/delegation-request.ts +0 -4
- package/src/slash/prompt-template-bridge.ts +37 -1
- package/src/slash/slash-bridge.ts +1 -2
- package/src/slash/slash-commands.ts +383 -116
- package/src/slash/slash-live-state.ts +22 -11
- package/src/slash/subagents-admin.ts +29 -12
- package/src/tui/fleet-native-transcript.ts +4 -0
- package/src/tui/fleet-status.ts +217 -82
- package/src/tui/fleet-transcript.ts +11 -5
- package/src/tui/fleet.ts +54 -28
- package/src/tui/render-helpers.ts +31 -0
- package/src/tui/render.ts +1429 -163
- package/src/watchdog/change-signature.ts +40 -1
- package/src/watchdog/child-status.ts +54 -34
- package/src/watchdog/diff-tool.ts +77 -0
- package/src/watchdog/emission-guard.ts +5 -3
- package/src/watchdog/guidance.ts +20 -0
- package/src/watchdog/register-child.ts +28 -25
- package/src/watchdog/register-main.ts +10 -9
- package/src/watchdog/render.ts +4 -5
- package/src/watchdog/review.ts +15 -4
- package/src/watchdog/rules.ts +70 -0
- package/src/watchdog/runtime.ts +75 -92
- package/src/watchdog/scope.ts +0 -11
- package/src/watchdog/settings.ts +48 -104
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/watchdog/types.ts +18 -32
- package/src/watchdog/warning-format.ts +0 -1
- package/src/workflows/chat-progress.ts +7 -3
- package/src/workflows/host-command.ts +235 -0
- package/src/workflows/scripted-workflow.ts +988 -59
- package/src/workflows/workflow-checklist.ts +439 -0
- package/src/workflows/workflow-child-summary.ts +121 -0
- package/src/workflows/workflow-preflight.ts +297 -0
- package/src/workflows/workflow-receipt.ts +232 -6
- package/src/workflows/workflow-resources.ts +150 -0
- package/src/workflows/workflow-settlement.ts +246 -0
- package/src/runs/shared/child-protocol.ts +0 -401
- package/src/runs/shared/pi-args.ts +0 -935
- package/src/runs/shared/subagent-startup-retry.ts +0 -116
- package/src/runs/shared/turn-budget.ts +0 -98
- package/src/shared/post-exit-stdio-guard.ts +0 -85
|
@@ -24,6 +24,9 @@ import { findNestedRouteForRootId, hasLiveNestedDescendants, updateAsyncJobNeste
|
|
|
24
24
|
import { listAsyncRuns, type AsyncRunSummary } from "./async-status.ts";
|
|
25
25
|
import { EXTERNAL_JOB_BRIDGE_REQUEST_DIR, serviceExternalJobBridgeRequests } from "../shared/external-job-bridge.ts";
|
|
26
26
|
import { shouldUseNativeFsWatch } from "../../shared/watch-strategy.ts";
|
|
27
|
+
import { parseWorkflowChildSummary } from "../../workflows/workflow-child-summary.ts";
|
|
28
|
+
import { validHostStepNodes } from "../shared/host-step-status.ts";
|
|
29
|
+
import { withCachedUiContext } from "../../shared/extension-context.ts";
|
|
27
30
|
|
|
28
31
|
interface AsyncJobTrackerOptions {
|
|
29
32
|
completionRetentionMs?: number;
|
|
@@ -36,6 +39,8 @@ interface AsyncJobTrackerOptions {
|
|
|
36
39
|
watch?: typeof fs.watch;
|
|
37
40
|
kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
|
|
38
41
|
now?: () => number;
|
|
42
|
+
/** Resolve native supervisor requests without scanning supervisor mailboxes. */
|
|
43
|
+
supervisorRequestState?: (event: ControlEvent) => "pending" | "resolved" | "unknown";
|
|
39
44
|
}
|
|
40
45
|
|
|
41
46
|
const CONTROL_EVENT_READ_CHUNK_BYTES = 64 * 1024;
|
|
@@ -70,34 +75,58 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
70
75
|
const steeringNoticeSeen = new Map<string, number>();
|
|
71
76
|
const jobWatchers = new Map<string, { watchers: Map<string, fs.FSWatcher>; retryTimer?: ReturnType<typeof setTimeout> }>();
|
|
72
77
|
const refreshTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
78
|
+
let widgetRerenderTimer: ReturnType<typeof setTimeout> | undefined;
|
|
73
79
|
const runningJobIds = new Set<string>();
|
|
80
|
+
const externalJobBridgeRuns = new Set<string>();
|
|
81
|
+
const externalJobBridgeEligibility = (steps: AsyncJobState["steps"]): "required" | "not-required" | "unknown" => {
|
|
82
|
+
if (!Array.isArray(steps)) return "unknown";
|
|
83
|
+
for (const step of steps) {
|
|
84
|
+
const runner = (step as { runner?: unknown } | null)?.runner;
|
|
85
|
+
if (runner === undefined) continue;
|
|
86
|
+
if (!runner || typeof runner !== "object" || Array.isArray(runner)) return "unknown";
|
|
87
|
+
const runnerType = (runner as { type?: unknown }).type;
|
|
88
|
+
if (typeof runnerType !== "string") return "unknown";
|
|
89
|
+
if (runnerType === "external-job") return "required";
|
|
90
|
+
if (runnerType !== "pi" && runnerType !== "external-cli") return "unknown";
|
|
91
|
+
}
|
|
92
|
+
return "not-required";
|
|
93
|
+
};
|
|
74
94
|
let rootWatcher: fs.FSWatcher | undefined;
|
|
75
95
|
let nextLivenessAt = Date.now() + livenessIntervalMs;
|
|
76
96
|
let nextWidgetAnimationAt = Date.now() + WIDGET_ANIMATION_INTERVAL_MS;
|
|
77
97
|
const watch = options.watch ?? fs.watch;
|
|
78
98
|
const useNativeWatcher = () => shouldUseNativeFsWatch("async-job-tracker", options.platform);
|
|
79
99
|
const terminalStatus = (status: string) => status === "complete" || status === "failed" || status === "paused" || status === "stopped";
|
|
100
|
+
const withLastUiContext = <T>(run: (ctx: ExtensionContext) => T): T | undefined => {
|
|
101
|
+
const cached = state.lastUiContext;
|
|
102
|
+
return withCachedUiContext(cached, () => {
|
|
103
|
+
if (state.lastUiContext === cached) state.lastUiContext = null;
|
|
104
|
+
}, run);
|
|
105
|
+
};
|
|
80
106
|
const rerenderWidget = (ctx: ExtensionContext, jobs = Array.from(state.asyncJobs.values())) => {
|
|
81
107
|
if (state.widgetsSuspended) return;
|
|
82
108
|
renderWidget(ctx, options.widgetEnabled === false ? [] : jobs);
|
|
83
109
|
(ctx.ui as { requestRender?: () => void }).requestRender?.();
|
|
84
110
|
};
|
|
85
111
|
const rerenderLastWidget = (jobs = Array.from(state.asyncJobs.values())) => {
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
throw error;
|
|
96
|
-
}
|
|
112
|
+
withLastUiContext((ctx) => rerenderWidget(ctx, jobs));
|
|
113
|
+
};
|
|
114
|
+
const scheduleLastWidgetRerender = () => {
|
|
115
|
+
if (widgetRerenderTimer) return;
|
|
116
|
+
widgetRerenderTimer = setTimeout(() => {
|
|
117
|
+
widgetRerenderTimer = undefined;
|
|
118
|
+
rerenderLastWidget();
|
|
119
|
+
}, EVENT_REFRESH_DEBOUNCE_MS);
|
|
120
|
+
widgetRerenderTimer.unref?.();
|
|
97
121
|
};
|
|
98
122
|
const requestLastWidgetRender = () => {
|
|
99
123
|
if (options.widgetEnabled === false) return;
|
|
100
|
-
|
|
124
|
+
withLastUiContext((ctx) => {
|
|
125
|
+
if (state.widgetsSuspended) return;
|
|
126
|
+
const requestRender = (ctx.ui as { requestRender?: () => void }).requestRender;
|
|
127
|
+
if (requestRender) requestRender.call(ctx.ui);
|
|
128
|
+
else renderWidget(ctx, Array.from(state.asyncJobs.values()));
|
|
129
|
+
});
|
|
101
130
|
};
|
|
102
131
|
const refreshWidget = (ctx: ExtensionContext) => rerenderWidget(ctx);
|
|
103
132
|
const restoredControlEventCursor = (asyncDir: string) => {
|
|
@@ -146,6 +175,9 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
146
175
|
currentStep: run.currentStep,
|
|
147
176
|
chainStepCount: run.chainStepCount,
|
|
148
177
|
parallelGroups: groups,
|
|
178
|
+
hostSteps: run.hostSteps,
|
|
179
|
+
...(run.mode === "workflow" && run.workflowGraph ? { workflowGraph: run.workflowGraph } : {}),
|
|
180
|
+
preflight: run.preflight,
|
|
149
181
|
steps: visibleSteps,
|
|
150
182
|
stepsTotal: visibleSteps.length,
|
|
151
183
|
runningSteps: visibleSteps.filter((step) => step.status === "running").length,
|
|
@@ -171,6 +203,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
171
203
|
parentWorkflowRunId: run.parentWorkflowRunId,
|
|
172
204
|
workflowKey: run.workflowKey,
|
|
173
205
|
workflow: run.workflow,
|
|
206
|
+
workflowChildren: parseWorkflowChildSummary(run.workflowChildren),
|
|
174
207
|
};
|
|
175
208
|
};
|
|
176
209
|
const cancelCleanup = (asyncId: string) => {
|
|
@@ -262,6 +295,15 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
262
295
|
if ((parsed as { type?: unknown }).type !== "subagent.control") return;
|
|
263
296
|
const record = parsed as { event?: ControlEvent; channels?: string[]; childIntercomTarget?: string; noticeText?: string; intercom?: { to?: string; message?: string } };
|
|
264
297
|
if (!record.event || !Array.isArray(record.channels)) return;
|
|
298
|
+
if (record.event.type === "needs_attention" && record.event.reason === "supervisor_request" && options.supervisorRequestState) {
|
|
299
|
+
let requestState: "pending" | "resolved" | "unknown" = "unknown";
|
|
300
|
+
try {
|
|
301
|
+
requestState = options.supervisorRequestState(record.event);
|
|
302
|
+
} catch (error) {
|
|
303
|
+
console.error(`Failed to resolve supervisor request state for async control event in '${job.asyncDir}':`, error);
|
|
304
|
+
}
|
|
305
|
+
if (requestState === "resolved") return;
|
|
306
|
+
}
|
|
265
307
|
const payload = {
|
|
266
308
|
event: record.event,
|
|
267
309
|
source: "async" as const,
|
|
@@ -337,10 +379,11 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
337
379
|
if (timer) clearTimeout(timer);
|
|
338
380
|
refreshTimers.delete(asyncId);
|
|
339
381
|
runningJobIds.delete(asyncId);
|
|
382
|
+
externalJobBridgeRuns.delete(asyncId);
|
|
340
383
|
};
|
|
341
384
|
|
|
342
385
|
const refreshJob = (job: AsyncJobState): boolean => {
|
|
343
|
-
const widgetExpanded =
|
|
386
|
+
const widgetExpanded = withLastUiContext((ctx) => ctx.ui.getToolsExpanded?.() ?? false) ?? false;
|
|
344
387
|
const widgetStateBefore = widgetRenderKey(job, widgetExpanded);
|
|
345
388
|
let nestedRefreshFailed = false;
|
|
346
389
|
const refreshNestedProjection = () => {
|
|
@@ -351,9 +394,15 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
351
394
|
console.error(`Failed to refresh nested async descendants for '${job.asyncDir}':`, error);
|
|
352
395
|
}
|
|
353
396
|
};
|
|
397
|
+
let bridgeSweepAttempted = false;
|
|
354
398
|
try {
|
|
355
399
|
emitNewControlEvents(job);
|
|
356
|
-
|
|
400
|
+
const bridgeAlreadyRequired = externalJobBridgeRuns.has(job.asyncId) || externalJobBridgeEligibility(job.steps) === "required";
|
|
401
|
+
if (bridgeAlreadyRequired) {
|
|
402
|
+
externalJobBridgeRuns.add(job.asyncId);
|
|
403
|
+
bridgeSweepAttempted = true;
|
|
404
|
+
serviceExternalJobBridgeRequests(job.asyncDir);
|
|
405
|
+
}
|
|
357
406
|
try {
|
|
358
407
|
if (job.nestedRoute) reconcileNestedAsyncDescendants(job.nestedRoute, { resultsDir, kill: options.kill, now: options.now });
|
|
359
408
|
} catch (error) {
|
|
@@ -379,6 +428,15 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
379
428
|
},
|
|
380
429
|
});
|
|
381
430
|
const status = reconciliation.status ?? readStatus(job.asyncDir);
|
|
431
|
+
if (!bridgeAlreadyRequired) {
|
|
432
|
+
const bridgeEligibility = externalJobBridgeEligibility(status?.steps);
|
|
433
|
+
if (bridgeEligibility === "required") externalJobBridgeRuns.add(job.asyncId);
|
|
434
|
+
// Missing or ambiguous status retains the legacy sweep for recovery races.
|
|
435
|
+
if (bridgeEligibility !== "not-required") {
|
|
436
|
+
bridgeSweepAttempted = true;
|
|
437
|
+
serviceExternalJobBridgeRequests(job.asyncDir);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
382
440
|
if (status) {
|
|
383
441
|
const previousStatus = job.status;
|
|
384
442
|
job.status = status.state;
|
|
@@ -397,7 +455,13 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
397
455
|
job.mode = status.mode;
|
|
398
456
|
job.parentWorkflowRunId = status.parentWorkflowRunId ?? job.parentWorkflowRunId;
|
|
399
457
|
job.workflowKey = status.workflowKey ?? job.workflowKey;
|
|
458
|
+
job.lane = status.lane ?? job.lane;
|
|
400
459
|
job.workflow = status.workflow ?? job.workflow;
|
|
460
|
+
if (status.mode === "workflow") job.workflowGraph = status.workflowGraph ?? job.workflowGraph;
|
|
461
|
+
job.hostSteps = validHostStepNodes(status.workflowGraph);
|
|
462
|
+
const workflowChildren = parseWorkflowChildSummary(status.workflowChildren);
|
|
463
|
+
if (workflowChildren && workflowChildren.workflowRunId !== status.runId) throw new Error("workflowChildren.workflowRunId does not match async status runId.");
|
|
464
|
+
job.workflowChildren = workflowChildren ?? job.workflowChildren;
|
|
401
465
|
job.currentStep = status.currentStep ?? job.currentStep;
|
|
402
466
|
job.chainStepCount = status.chainStepCount ?? job.chainStepCount;
|
|
403
467
|
job.startedAt = status.startedAt ?? job.startedAt;
|
|
@@ -447,6 +511,14 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
447
511
|
runningJobIds.add(job.asyncId);
|
|
448
512
|
}
|
|
449
513
|
} catch (error) {
|
|
514
|
+
if (!bridgeSweepAttempted) {
|
|
515
|
+
try {
|
|
516
|
+
bridgeSweepAttempted = true;
|
|
517
|
+
serviceExternalJobBridgeRequests(job.asyncDir);
|
|
518
|
+
} catch (bridgeError) {
|
|
519
|
+
console.error(`Failed to service external job bridge for '${job.asyncDir}':`, bridgeError);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
450
522
|
if (job.status !== "failed") {
|
|
451
523
|
console.error(`Failed to read async status for '${job.asyncDir}':`, error);
|
|
452
524
|
job.status = "failed";
|
|
@@ -464,7 +536,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
464
536
|
const timer = setTimeout(() => {
|
|
465
537
|
refreshTimers.delete(asyncId);
|
|
466
538
|
const job = state.asyncJobs.get(asyncId);
|
|
467
|
-
if (job && refreshJob(job))
|
|
539
|
+
if (job && refreshJob(job)) scheduleLastWidgetRerender();
|
|
468
540
|
}, delayMs);
|
|
469
541
|
timer.unref?.();
|
|
470
542
|
refreshTimers.set(asyncId, timer);
|
|
@@ -595,6 +667,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
595
667
|
: rawAgents;
|
|
596
668
|
const sessionRoot = state.liveAsyncSessionRoots?.get(info.id);
|
|
597
669
|
state.liveAsyncSessionRoots?.delete(info.id);
|
|
670
|
+
externalJobBridgeRuns.delete(info.id);
|
|
598
671
|
state.asyncJobs.set(info.id, {
|
|
599
672
|
asyncId: info.id,
|
|
600
673
|
asyncDir,
|
|
@@ -620,6 +693,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
620
693
|
turnBudget: info.turnBudget,
|
|
621
694
|
parentWorkflowRunId: info.parentWorkflowRunId,
|
|
622
695
|
workflowKey: info.workflowKey,
|
|
696
|
+
...(info.mode === "workflow" && info.workflowGraph ? { workflowGraph: info.workflowGraph } : {}),
|
|
623
697
|
controlEventCursor: 0,
|
|
624
698
|
});
|
|
625
699
|
const job = state.asyncJobs.get(info.id)!;
|
|
@@ -667,11 +741,15 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
667
741
|
for (const asyncId of jobWatchers.keys()) closeJobWatcher(asyncId);
|
|
668
742
|
for (const timer of refreshTimers.values()) clearTimeout(timer);
|
|
669
743
|
refreshTimers.clear();
|
|
744
|
+
if (widgetRerenderTimer) clearTimeout(widgetRerenderTimer);
|
|
745
|
+
widgetRerenderTimer = undefined;
|
|
670
746
|
runningJobIds.clear();
|
|
747
|
+
externalJobBridgeRuns.clear();
|
|
671
748
|
};
|
|
672
749
|
|
|
673
750
|
const resetJobs = (ctx?: ExtensionContext) => {
|
|
674
751
|
dispose();
|
|
752
|
+
state.statusProjectionSessionId = null;
|
|
675
753
|
for (const timer of state.cleanupTimers.values()) clearTimeout(timer);
|
|
676
754
|
state.cleanupTimers.clear();
|
|
677
755
|
state.asyncJobs.clear();
|
|
@@ -688,6 +766,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
688
766
|
|
|
689
767
|
const restoreActiveJobs = (ctx?: ExtensionContext) => {
|
|
690
768
|
if (ctx?.hasUI) state.lastUiContext = ctx;
|
|
769
|
+
state.statusProjectionSessionId = null;
|
|
691
770
|
if (!state.currentSessionId) return;
|
|
692
771
|
let runs: AsyncRunSummary[];
|
|
693
772
|
try {
|
|
@@ -703,6 +782,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
|
|
|
703
782
|
rememberFleetJob(state, job);
|
|
704
783
|
watchJob(job);
|
|
705
784
|
}
|
|
785
|
+
state.statusProjectionSessionId = state.currentSessionId;
|
|
706
786
|
if (runs.length === 0) return;
|
|
707
787
|
ensurePoller();
|
|
708
788
|
rerenderLastWidget();
|
|
@@ -1,18 +1,21 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
2
|
import * as path from "node:path";
|
|
3
|
-
import { DIRS, type AcceptanceInput, type AsyncStatus, type
|
|
3
|
+
import { DIRS, type AcceptanceInput, type AsyncStatus, type SteeringRecoveryDescriptor, type SubagentRunMode } from "../../shared/types.ts";
|
|
4
4
|
import type { AgentConfig } from "../../agents/agents.ts";
|
|
5
5
|
import { normalizeExtensionBindings } from "../shared/extension-bindings.ts";
|
|
6
|
+
import { normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
|
|
6
7
|
import { validateAcceptanceInput } from "../shared/acceptance.ts";
|
|
7
8
|
import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
|
|
8
9
|
import { intersectSubagentCapabilityCeilings, parseSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
|
|
9
10
|
import { validateRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
|
|
10
|
-
import { resolveTurnBudgetConfig } from "../shared/turn-budget.ts";
|
|
11
11
|
import { reconcileAsyncRun } from "./stale-run-reconciler.ts";
|
|
12
12
|
import { resultFilePath, resultPayloadPathForIndexedRun } from "./result-files.ts";
|
|
13
13
|
import { canScanAsyncRunPrefix, MIN_SAFE_ASYNC_RUN_PREFIX_LENGTH } from "./run-id-query.ts";
|
|
14
14
|
import { parallelHandoffPath, resolveRetainedWorktreeCwd } from "../shared/parallel-handoff.ts";
|
|
15
|
+
import { normalizeWorktreeBaseRef } from "../shared/worktree.ts";
|
|
15
16
|
import { intersectThinkingCeilings, parseThinkingLevel, type ThinkingLevel } from "../../shared/thinking-ceiling.ts";
|
|
17
|
+
import { assertWorkflowGraphHostSteps } from "../shared/host-step-status.ts";
|
|
18
|
+
import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
|
|
16
19
|
|
|
17
20
|
export interface AsyncResumeParams {
|
|
18
21
|
id?: string;
|
|
@@ -40,8 +43,12 @@ export type AsyncResumeTarget = {
|
|
|
40
43
|
state: AsyncStatus["state"];
|
|
41
44
|
mode?: SubagentRunMode;
|
|
42
45
|
agent: string;
|
|
46
|
+
/** Human-readable display name for the child session, when derived at launch. */
|
|
47
|
+
sessionName?: string;
|
|
43
48
|
index: number;
|
|
44
49
|
cwd?: string;
|
|
50
|
+
/** True when cwd is the retained managed worktree recorded by the handoff. */
|
|
51
|
+
managedWorktree?: boolean;
|
|
45
52
|
sessionFile?: string;
|
|
46
53
|
model?: string;
|
|
47
54
|
thinking?: string;
|
|
@@ -49,6 +56,7 @@ export type AsyncResumeTarget = {
|
|
|
49
56
|
recoveryDescriptor?: SteeringRecoveryDescriptor;
|
|
50
57
|
capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
|
|
51
58
|
launchContractDigest?: string;
|
|
59
|
+
sandbox?: string;
|
|
52
60
|
runner?: NonNullable<AsyncStatus["steps"]>[number]["runner"];
|
|
53
61
|
externalJob?: NonNullable<AsyncStatus["steps"]>[number]["externalJob"];
|
|
54
62
|
};
|
|
@@ -63,11 +71,13 @@ interface AsyncResultFile {
|
|
|
63
71
|
cwd?: string;
|
|
64
72
|
sessionId?: string;
|
|
65
73
|
sessionFile?: string;
|
|
74
|
+
sessionName?: string;
|
|
66
75
|
model?: string;
|
|
67
76
|
thinking?: string;
|
|
68
77
|
launchContractDigest?: string;
|
|
78
|
+
sandbox?: string;
|
|
69
79
|
capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
|
|
70
|
-
results?: Array<{ agent?: string; success?: boolean; sessionFile?: string; intercomTarget?: string; model?: string; thinking?: string; launchContractDigest?: string; capabilityCeiling?: ResolvedSubagentCapabilityCeiling }>;
|
|
80
|
+
results?: Array<{ agent?: string; sessionName?: string; success?: boolean; sessionFile?: string; intercomTarget?: string; model?: string; thinking?: string; launchContractDigest?: string; sandbox?: string; capabilityCeiling?: ResolvedSubagentCapabilityCeiling }>;
|
|
71
81
|
}
|
|
72
82
|
|
|
73
83
|
export interface AsyncRunLocation {
|
|
@@ -104,14 +114,18 @@ function validateResultFile(value: unknown, resultPath: string): AsyncResultFile
|
|
|
104
114
|
const child = ensureObject(entry, `${resultPath} results[${index}]`);
|
|
105
115
|
const agent = validateOptionalString(child, "agent", resultPath, `results[${index}].agent`);
|
|
106
116
|
const sessionFile = validateOptionalString(child, "sessionFile", resultPath, `results[${index}].sessionFile`);
|
|
117
|
+
const sessionName = validateOptionalString(child, "sessionName", resultPath, `results[${index}].sessionName`);
|
|
107
118
|
const intercomTarget = validateOptionalString(child, "intercomTarget", resultPath, `results[${index}].intercomTarget`);
|
|
108
119
|
const model = validateOptionalString(child, "model", resultPath, `results[${index}].model`);
|
|
109
120
|
const thinking = validateOptionalString(child, "thinking", resultPath, `results[${index}].thinking`);
|
|
110
121
|
const launchContractDigest = validateOptionalString(child, "launchContractDigest", resultPath, `results[${index}].launchContractDigest`);
|
|
122
|
+
const sandbox = child.sandbox === undefined
|
|
123
|
+
? undefined
|
|
124
|
+
: validateSandboxProfileName(child.sandbox, `async result file '${resultPath}' results[${index}].sandbox`);
|
|
111
125
|
const capabilityCeiling = child.capabilityCeiling === undefined ? undefined : parseSubagentCapabilityCeiling(child.capabilityCeiling, `async result file '${resultPath}' results[${index}].capabilityCeiling`);
|
|
112
126
|
const success = child.success;
|
|
113
127
|
if (success !== undefined && typeof success !== "boolean") throw new Error(`Invalid async result file '${resultPath}': results[${index}].success must be a boolean.`);
|
|
114
|
-
return { agent, sessionFile, intercomTarget, model, thinking, launchContractDigest, ...(capabilityCeiling ? { capabilityCeiling } : {}), ...(typeof success === "boolean" ? { success } : {}) };
|
|
128
|
+
return { agent, sessionName, sessionFile, intercomTarget, model, thinking, launchContractDigest, ...(sandbox ? { sandbox } : {}), ...(capabilityCeiling ? { capabilityCeiling } : {}), ...(typeof success === "boolean" ? { success } : {}) };
|
|
115
129
|
});
|
|
116
130
|
}
|
|
117
131
|
const success = data.success;
|
|
@@ -128,6 +142,7 @@ function validateResultFile(value: unknown, resultPath: string): AsyncResultFile
|
|
|
128
142
|
model: validateOptionalString(data, "model", resultPath),
|
|
129
143
|
thinking: validateOptionalString(data, "thinking", resultPath),
|
|
130
144
|
launchContractDigest: validateOptionalString(data, "launchContractDigest", resultPath),
|
|
145
|
+
...(data.sandbox === undefined ? {} : { sandbox: validateSandboxProfileName(data.sandbox, `async result file '${resultPath}' sandbox`) }),
|
|
131
146
|
...(data.capabilityCeiling === undefined ? {} : { capabilityCeiling: parseSubagentCapabilityCeiling(data.capabilityCeiling, `async result file '${resultPath}' capabilityCeiling`) }),
|
|
132
147
|
...(typeof success === "boolean" ? { success } : {}),
|
|
133
148
|
...(results ? { results } : {}),
|
|
@@ -248,7 +263,7 @@ export function resolveAsyncRunLocation(params: AsyncResumeParams, asyncDirRoot:
|
|
|
248
263
|
}
|
|
249
264
|
|
|
250
265
|
function resultState(result: AsyncResultFile): AsyncStatus["state"] {
|
|
251
|
-
if (result.state === "complete" || result.state === "failed" || result.state === "paused" || result.state === "stopped" || result.state === "running" || result.state === "queued") {
|
|
266
|
+
if (result.state === "complete" || result.state === "failed" || result.state === "partial" || result.state === "paused" || result.state === "stopped" || result.state === "running" || result.state === "queued") {
|
|
252
267
|
return result.state;
|
|
253
268
|
}
|
|
254
269
|
return result.success ? "complete" : "failed";
|
|
@@ -257,6 +272,7 @@ function resultState(result: AsyncResultFile): AsyncStatus["state"] {
|
|
|
257
272
|
function validateStatusForResume(status: AsyncStatus | null, source: string): void {
|
|
258
273
|
if (!status) return;
|
|
259
274
|
if (typeof status.runId !== "string") throw new Error(`Invalid async status '${source}': runId must be a string.`);
|
|
275
|
+
assertWorkflowGraphHostSteps(status.workflowGraph, source, status.runId);
|
|
260
276
|
if (status.sessionId !== undefined && typeof status.sessionId !== "string") throw new Error(`Invalid async status '${source}': sessionId must be a string.`);
|
|
261
277
|
if (status.cwd !== undefined && typeof status.cwd !== "string") throw new Error(`Invalid async status '${source}': cwd must be a string.`);
|
|
262
278
|
if (status.sessionFile !== undefined && typeof status.sessionFile !== "string") throw new Error(`Invalid async status '${source}': sessionFile must be a string.`);
|
|
@@ -268,10 +284,12 @@ function validateStatusForResume(status: AsyncStatus | null, source: string): vo
|
|
|
268
284
|
const stepRecord = step as Record<string, unknown>;
|
|
269
285
|
if (typeof stepRecord.agent !== "string") throw new Error(`Invalid async status '${source}': steps[${index}].agent must be a string.`);
|
|
270
286
|
if (stepRecord.sessionFile !== undefined && typeof stepRecord.sessionFile !== "string") throw new Error(`Invalid async status '${source}': steps[${index}].sessionFile must be a string.`);
|
|
287
|
+
if (stepRecord.sessionName !== undefined && typeof stepRecord.sessionName !== "string") throw new Error(`Invalid async status '${source}': steps[${index}].sessionName must be a string.`);
|
|
271
288
|
if (stepRecord.model !== undefined && typeof stepRecord.model !== "string") throw new Error(`Invalid async status '${source}': steps[${index}].model must be a string.`);
|
|
272
289
|
if (stepRecord.thinking !== undefined && typeof stepRecord.thinking !== "string") throw new Error(`Invalid async status '${source}': steps[${index}].thinking must be a string.`);
|
|
273
290
|
if (stepRecord.thinkingCeiling !== undefined) stepRecord.thinkingCeiling = parseThinkingLevel(stepRecord.thinkingCeiling, `async status '${source}' steps[${index}].thinkingCeiling`);
|
|
274
291
|
if (stepRecord.launchContractDigest !== undefined && typeof stepRecord.launchContractDigest !== "string") throw new Error(`Invalid async status '${source}': steps[${index}].launchContractDigest must be a string.`);
|
|
292
|
+
if (stepRecord.sandbox !== undefined) stepRecord.sandbox = validateSandboxProfileName(stepRecord.sandbox, `async status '${source}' steps[${index}].sandbox`);
|
|
275
293
|
if (stepRecord.capabilityCeiling !== undefined) stepRecord.capabilityCeiling = parseSubagentCapabilityCeiling(stepRecord.capabilityCeiling, `async status '${source}' steps[${index}].capabilityCeiling`);
|
|
276
294
|
});
|
|
277
295
|
}
|
|
@@ -283,23 +301,6 @@ function normalizeRecoveryAcceptance(value: unknown, descriptorPath: string): Ac
|
|
|
283
301
|
return value as AcceptanceInput;
|
|
284
302
|
}
|
|
285
303
|
|
|
286
|
-
function normalizeRecoveryTurnBudget(value: unknown, descriptorPath: string): ResolvedTurnBudget {
|
|
287
|
-
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
288
|
-
const {
|
|
289
|
-
outcome: _outcome,
|
|
290
|
-
turnCount: _turnCount,
|
|
291
|
-
wrapUpRequestedAtTurn: _wrapUpRequestedAtTurn,
|
|
292
|
-
terminationDeferredAtTurn: _terminationDeferredAtTurn,
|
|
293
|
-
exceededAtTurn: _exceededAtTurn,
|
|
294
|
-
...publicTurnBudget
|
|
295
|
-
} = value as Record<string, unknown>;
|
|
296
|
-
value = publicTurnBudget;
|
|
297
|
-
}
|
|
298
|
-
const result = resolveTurnBudgetConfig(value, "recoveryDescriptor.initialTurnBudget");
|
|
299
|
-
if (result.error || !result.turnBudget) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': ${result.error ?? "recoveryDescriptor.initialTurnBudget is invalid."}`);
|
|
300
|
-
return result.turnBudget;
|
|
301
|
-
}
|
|
302
|
-
|
|
303
304
|
export function asyncReviveRequiresRecoveryDescriptor(target: Pick<AsyncResumeTarget, "recoveryDescriptor" | "mode" | "sessionFile">): boolean {
|
|
304
305
|
if (target.recoveryDescriptor) return false;
|
|
305
306
|
return !(target.mode === "workflow" && Boolean(target.sessionFile));
|
|
@@ -324,11 +325,11 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
|
|
|
324
325
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': expected an object.`);
|
|
325
326
|
const parsed = value as Record<string, unknown>;
|
|
326
327
|
const allowedFields = new Set([
|
|
327
|
-
"version", "launchContractDigest", "sourceRunId", "agentContract", "agent", "sessionFile", "cwd", "model", "modelProvider", "modelOverrideFromParent", "fallbackModels", "thinking", "thinkingCeiling", "tools", "extensions",
|
|
328
|
-
"subagentOnlyExtensions", "mcpDirectTools", "systemPrompt", "systemPromptMode", "inheritProjectContext", "inheritSkills", "skills",
|
|
328
|
+
"version", "launchContractDigest", "sourceRunId", "agentContract", "agent", "sandbox", "sessionFile", "cwd", "model", "modelProvider", "modelOverrideFromParent", "modelOrigin", "fallbackModels", "thinking", "thinkingCeiling", "tools", "allowNestedSubagents", "extensions",
|
|
329
|
+
"subagentOnlyExtensions", "mcpDirectTools", "excludeTools", "mutationTools", "systemPrompt", "systemPromptMode", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "skills",
|
|
329
330
|
"skillPath", "agentFilePath", "completionGuard", "memory", "outputPath", "outputMode", "structuredOutputSchema", "acceptance", "sessionDir", "artifactConfig",
|
|
330
331
|
"artifactsDir", "maxOutput", "controlConfig", "context", "intercomBridge", "absoluteDeadlineAt", "initialTurnBudget", "initialToolBudget", "maxSubagentDepth", "share", "capabilityCeiling",
|
|
331
|
-
"launchResolvedExtensions", "runFanoutBudget",
|
|
332
|
+
"launchResolvedExtensions", "runFanoutBudget", "lane", "baseRef",
|
|
332
333
|
"extensionBindings",
|
|
333
334
|
]);
|
|
334
335
|
for (const field of Object.keys(parsed)) {
|
|
@@ -347,6 +348,7 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
|
|
|
347
348
|
if (parsed.capabilityCeiling !== undefined) parsed.capabilityCeiling = parseSubagentCapabilityCeiling(parsed.capabilityCeiling, `async recovery descriptor '${descriptorPath}' capabilityCeiling`);
|
|
348
349
|
if (parsed.thinkingCeiling !== undefined) parsed.thinkingCeiling = parseThinkingLevel(parsed.thinkingCeiling, `async recovery descriptor '${descriptorPath}' thinkingCeiling`);
|
|
349
350
|
if (parsed.extensionBindings !== undefined) parsed.extensionBindings = normalizeExtensionBindings(parsed.extensionBindings)!.value;
|
|
351
|
+
if (parsed.lane !== undefined) parsed.lane = normalizeWorkflowLaneMetadata(parsed.lane, `Invalid async recovery descriptor '${descriptorPath}': lane`);
|
|
350
352
|
if (parsed.agentContract !== undefined) {
|
|
351
353
|
if (!parsed.agentContract || typeof parsed.agentContract !== "object" || Array.isArray(parsed.agentContract)) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': agentContract must be an object.`);
|
|
352
354
|
const contract = parsed.agentContract as Record<string, unknown>;
|
|
@@ -356,11 +358,16 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
|
|
|
356
358
|
if (parsed.outputMode !== "inline" && parsed.outputMode !== "file-only") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': outputMode is invalid.`);
|
|
357
359
|
if (parsed.context !== undefined && parsed.context !== "fresh" && parsed.context !== "fork") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': context is invalid.`);
|
|
358
360
|
if (parsed.modelOverrideFromParent !== undefined && typeof parsed.modelOverrideFromParent !== "boolean") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': modelOverrideFromParent must be a boolean.`);
|
|
361
|
+
if (parsed.modelOrigin !== undefined && parsed.modelOrigin !== "explicit" && parsed.modelOrigin !== "inherited" && parsed.modelOrigin !== "configured") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': modelOrigin must be 'explicit', 'inherited', or 'configured'.`);
|
|
362
|
+
if (parsed.modelOrigin === undefined && parsed.model !== undefined) parsed.modelOrigin = parsed.modelOverrideFromParent ? "inherited" : "configured";
|
|
359
363
|
for (const field of ["inheritProjectContext", "inheritSkills", "share"] as const) {
|
|
360
364
|
if (typeof parsed[field] !== "boolean") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': ${field} must be a boolean.`);
|
|
361
365
|
}
|
|
366
|
+
if (parsed.inheritGlobalContext === undefined) parsed.inheritGlobalContext = parsed.inheritProjectContext;
|
|
367
|
+
else if (typeof parsed.inheritGlobalContext !== "boolean") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': inheritGlobalContext must be a boolean.`);
|
|
368
|
+
if (parsed.allowNestedSubagents !== undefined && typeof parsed.allowNestedSubagents !== "boolean") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': allowNestedSubagents must be a boolean.`);
|
|
362
369
|
if (!Number.isInteger(parsed.maxSubagentDepth) || (parsed.maxSubagentDepth as number) < 0) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': maxSubagentDepth must be a non-negative integer.`);
|
|
363
|
-
for (const field of ["fallbackModels", "tools", "extensions", "subagentOnlyExtensions", "mcpDirectTools", "skills", "skillPath"] as const) {
|
|
370
|
+
for (const field of ["fallbackModels", "tools", "excludeTools", "extensions", "subagentOnlyExtensions", "mcpDirectTools", "mutationTools", "skills", "skillPath"] as const) {
|
|
364
371
|
const item = parsed[field];
|
|
365
372
|
if (item !== undefined && (!Array.isArray(item) || item.some((entry) => typeof entry !== "string" || !entry.trim()))) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': ${field} must contain non-empty strings.`);
|
|
366
373
|
}
|
|
@@ -368,6 +375,15 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
|
|
|
368
375
|
for (const field of ["launchContractDigest", "sessionFile", "model", "modelProvider", "thinking", "agentFilePath", "outputPath", "sessionDir", "artifactsDir"] as const) {
|
|
369
376
|
if (parsed[field] !== undefined && (typeof parsed[field] !== "string" || !(parsed[field] as string).trim())) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': ${field} must be a non-empty string.`);
|
|
370
377
|
}
|
|
378
|
+
if (parsed.baseRef !== undefined) {
|
|
379
|
+
if (typeof parsed.baseRef !== "string") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': baseRef must be a string.`);
|
|
380
|
+
try {
|
|
381
|
+
parsed.baseRef = normalizeWorktreeBaseRef(parsed.baseRef);
|
|
382
|
+
} catch (error) {
|
|
383
|
+
throw new Error(`Invalid async recovery descriptor '${descriptorPath}': ${error instanceof Error ? error.message : String(error)}`);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
if (parsed.sandbox !== undefined) parsed.sandbox = validateSandboxProfileName(parsed.sandbox, `async recovery descriptor '${descriptorPath}' sandbox`);
|
|
371
387
|
if (parsed.completionGuard !== undefined && typeof parsed.completionGuard !== "boolean") throw new Error(`Invalid async recovery descriptor '${descriptorPath}': completionGuard must be a boolean.`);
|
|
372
388
|
if (parsed.structuredOutputSchema !== undefined && (!parsed.structuredOutputSchema || typeof parsed.structuredOutputSchema !== "object" || Array.isArray(parsed.structuredOutputSchema))) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': structuredOutputSchema must be an object.`);
|
|
373
389
|
if (parsed.memory !== undefined) {
|
|
@@ -377,7 +393,9 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
|
|
|
377
393
|
}
|
|
378
394
|
if (parsed.absoluteDeadlineAt !== undefined && (!Number.isFinite(parsed.absoluteDeadlineAt) || (parsed.absoluteDeadlineAt as number) <= 0)) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': absoluteDeadlineAt must be a positive timestamp.`);
|
|
379
395
|
if (parsed.initialTurnBudget !== undefined) {
|
|
380
|
-
|
|
396
|
+
// Older descriptors may contain the removed turn-budget setting. Accept it
|
|
397
|
+
// for recovery compatibility, but do not restore or enforce it.
|
|
398
|
+
delete parsed.initialTurnBudget;
|
|
381
399
|
}
|
|
382
400
|
if (parsed.initialToolBudget !== undefined) {
|
|
383
401
|
const result = validateToolBudgetConfig(parsed.initialToolBudget, "recoveryDescriptor.initialToolBudget");
|
|
@@ -423,6 +441,8 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
|
|
|
423
441
|
if (!Array.isArray(control.notifyChannels) || control.notifyChannels.some((item) => item !== "event" && item !== "async" && item !== "intercom")) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': controlConfig.notifyChannels is invalid.`);
|
|
424
442
|
}
|
|
425
443
|
if (parsed.acceptance !== undefined) parsed.acceptance = normalizeRecoveryAcceptance(parsed.acceptance, descriptorPath);
|
|
444
|
+
// SAFETY: every supported field above is validated and normalized before this
|
|
445
|
+
// object crosses the persisted JSON boundary into the recovery descriptor type.
|
|
426
446
|
return parsed as unknown as SteeringRecoveryDescriptor;
|
|
427
447
|
}
|
|
428
448
|
|
|
@@ -490,11 +510,13 @@ export function resolveAsyncResumeTarget(params: AsyncResumeParams, deps: AsyncR
|
|
|
490
510
|
state,
|
|
491
511
|
...(mode ? { mode } : {}),
|
|
492
512
|
agent: selectedStep.agent,
|
|
513
|
+
...(selectedStep.sessionName ?? result?.results?.[requestedIndex]?.sessionName ? { sessionName: selectedStep.sessionName ?? result?.results?.[requestedIndex]?.sessionName } : {}),
|
|
493
514
|
index: requestedIndex,
|
|
494
515
|
cwd: status?.cwd ?? result?.cwd,
|
|
495
516
|
sessionFile: selectedStep.sessionFile ?? status?.sessionFile ?? result?.sessionFile,
|
|
496
517
|
model: selectedStep.model,
|
|
497
518
|
thinking: selectedStep.thinking,
|
|
519
|
+
sandbox: selectedStep.sandbox ?? result?.results?.[requestedIndex]?.sandbox ?? result?.sandbox ?? recoveryDescriptor?.sandbox,
|
|
498
520
|
launchContractDigest: selectedStep.launchContractDigest ?? result?.results?.[requestedIndex]?.launchContractDigest ?? result?.launchContractDigest ?? recoveryDescriptor?.launchContractDigest,
|
|
499
521
|
...(selectedStep.runner ? { runner: selectedStep.runner } : {}),
|
|
500
522
|
...(selectedStep.externalJob ? { externalJob: selectedStep.externalJob } : {}),
|
|
@@ -521,11 +543,13 @@ export function resolveAsyncResumeTarget(params: AsyncResumeParams, deps: AsyncR
|
|
|
521
543
|
state,
|
|
522
544
|
...(mode ? { mode } : {}),
|
|
523
545
|
agent: selected.step.agent,
|
|
546
|
+
...(selected.step.sessionName ?? result?.results?.[selected.index]?.sessionName ? { sessionName: selected.step.sessionName ?? result?.results?.[selected.index]?.sessionName } : {}),
|
|
524
547
|
index: selected.index,
|
|
525
548
|
cwd: status?.cwd ?? result?.cwd,
|
|
526
549
|
sessionFile: selected.step.sessionFile ?? status?.sessionFile ?? result?.sessionFile,
|
|
527
550
|
model: selected.step.model,
|
|
528
551
|
thinking: selected.step.thinking,
|
|
552
|
+
sandbox: selected.step.sandbox ?? result?.results?.[selected.index]?.sandbox ?? result?.sandbox ?? recoveryDescriptor?.sandbox,
|
|
529
553
|
launchContractDigest: selected.step.launchContractDigest ?? result?.results?.[selected.index]?.launchContractDigest ?? result?.launchContractDigest ?? recoveryDescriptor?.launchContractDigest,
|
|
530
554
|
...(selected.step.runner ? { runner: selected.step.runner } : {}),
|
|
531
555
|
...(selected.step.externalJob ? { externalJob: selected.step.externalJob } : {}),
|
|
@@ -566,11 +590,14 @@ export function resolveAsyncResumeTarget(params: AsyncResumeParams, deps: AsyncR
|
|
|
566
590
|
state,
|
|
567
591
|
...(mode ? { mode } : {}),
|
|
568
592
|
agent,
|
|
593
|
+
...(statusSteps[index]?.sessionName ?? resultSteps[index]?.sessionName ? { sessionName: statusSteps[index]?.sessionName ?? resultSteps[index]?.sessionName } : {}),
|
|
569
594
|
index,
|
|
570
595
|
...(resumeCwd ? { cwd: resumeCwd } : {}),
|
|
596
|
+
...(managedWorktreeCwd ? { managedWorktree: true } : {}),
|
|
571
597
|
...(resolvedSessionFile ? { sessionFile: resolvedSessionFile } : {}),
|
|
572
598
|
...(stepModel ? { model: stepModel } : {}),
|
|
573
599
|
...(stepThinking ? { thinking: stepThinking } : {}),
|
|
600
|
+
sandbox: statusSteps[index]?.sandbox ?? resultSteps[index]?.sandbox ?? result?.sandbox ?? recoveryDescriptor?.sandbox,
|
|
574
601
|
launchContractDigest: statusSteps[index]?.launchContractDigest ?? resultSteps[index]?.launchContractDigest ?? result?.launchContractDigest ?? recoveryDescriptor?.launchContractDigest,
|
|
575
602
|
...(statusSteps[index]?.runner ? { runner: statusSteps[index]!.runner } : {}),
|
|
576
603
|
...(statusSteps[index]?.externalJob ? { externalJob: statusSteps[index]!.externalJob } : {}),
|
|
@@ -589,12 +616,17 @@ export function applySteeringRecoveryAgentConfig(agentConfig: AgentConfig, descr
|
|
|
589
616
|
thinking: descriptor.thinking,
|
|
590
617
|
maxThinking: intersectThinkingCeilings(descriptor.thinkingCeiling, agentConfig.maxThinking),
|
|
591
618
|
tools: descriptor.tools ? [...descriptor.tools] : undefined,
|
|
619
|
+
excludeTools: descriptor.excludeTools ? [...descriptor.excludeTools] : undefined,
|
|
620
|
+
allowNestedSubagents: descriptor.allowNestedSubagents,
|
|
592
621
|
extensions: descriptor.extensions ? [...descriptor.extensions] : undefined,
|
|
593
622
|
subagentOnlyExtensions: descriptor.subagentOnlyExtensions ? [...descriptor.subagentOnlyExtensions] : undefined,
|
|
594
623
|
mcpDirectTools: descriptor.mcpDirectTools ? [...descriptor.mcpDirectTools] : undefined,
|
|
624
|
+
mutationTools: descriptor.mutationTools ? [...descriptor.mutationTools] : undefined,
|
|
625
|
+
sandbox: descriptor.sandbox ?? agentConfig.sandbox,
|
|
595
626
|
systemPrompt: descriptor.systemPrompt ?? agentConfig.systemPrompt,
|
|
596
627
|
systemPromptMode: descriptor.systemPromptMode,
|
|
597
628
|
inheritProjectContext: descriptor.inheritProjectContext,
|
|
629
|
+
inheritGlobalContext: descriptor.inheritGlobalContext,
|
|
598
630
|
inheritSkills: descriptor.inheritSkills,
|
|
599
631
|
skills: descriptor.skills ? [...descriptor.skills] : undefined,
|
|
600
632
|
skillPath: descriptor.skillPath ? [...descriptor.skillPath] : undefined,
|
|
@@ -615,7 +647,7 @@ export function buildRevivedAsyncTask(target: AsyncResumeTarget, message: string
|
|
|
615
647
|
`Original agent: ${target.agent}`,
|
|
616
648
|
target.sessionFile ? `Original session file: ${target.sessionFile}` : undefined,
|
|
617
649
|
"",
|
|
618
|
-
"Use the stored session context as background. Answer the orchestrator's follow-up below. Do not assume the original child
|
|
650
|
+
"Use the stored session context as background. Answer the orchestrator's follow-up below. Do not assume the original child session is still running.",
|
|
619
651
|
"",
|
|
620
652
|
"Follow-up:",
|
|
621
653
|
message,
|
|
@@ -9,6 +9,7 @@ import type { AsyncStatus } from "../../shared/types.ts";
|
|
|
9
9
|
import { MISSION_BINDING_FILE } from "../../missions/lifecycle.ts";
|
|
10
10
|
import { ACTIVE_RUN_INDEX_DIR } from "./active-run-index.ts";
|
|
11
11
|
import { encodeIndexSegment } from "./index-segment.ts";
|
|
12
|
+
import { reconcileAsyncRun } from "./stale-run-reconciler.ts";
|
|
12
13
|
|
|
13
14
|
export const ASYNC_RETENTION_DAYS = 30;
|
|
14
15
|
export const ASYNC_RETENTION_BATCH_SIZE = 100;
|
|
@@ -96,11 +97,13 @@ export interface AsyncRetentionOptions {
|
|
|
96
97
|
lstatSync?: typeof fs.lstatSync;
|
|
97
98
|
signal?: AbortSignal;
|
|
98
99
|
discoveryWorkerUrl?: URL;
|
|
100
|
+
reconcileKill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
|
|
99
101
|
}
|
|
100
102
|
|
|
101
103
|
export interface AsyncRetentionResult {
|
|
102
104
|
acquired: boolean;
|
|
103
105
|
scanned: number;
|
|
106
|
+
repairedRuns: number;
|
|
104
107
|
deletedRuns: number;
|
|
105
108
|
deletedResults: number;
|
|
106
109
|
reapedTombstones: number;
|
|
@@ -135,7 +138,7 @@ function listDir(dir: string): fs.Dirent[] {
|
|
|
135
138
|
|
|
136
139
|
function readJson(filePath: string): Record<string, unknown> | undefined {
|
|
137
140
|
try {
|
|
138
|
-
const parsed = JSON.parse(fs.readFileSync(filePath
|
|
141
|
+
const parsed = JSON.parse(fs.readFileSync(filePath).toString("utf8")) as unknown;
|
|
139
142
|
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as Record<string, unknown> : undefined;
|
|
140
143
|
} catch {
|
|
141
144
|
return undefined;
|
|
@@ -320,7 +323,7 @@ function readCursor(root: string): RetentionCursor {
|
|
|
320
323
|
function processStartIdentity(pid: number): string | undefined {
|
|
321
324
|
if (process.platform === "linux") {
|
|
322
325
|
try {
|
|
323
|
-
const stat = fs.readFileSync(`/proc/${pid}/stat
|
|
326
|
+
const stat = fs.readFileSync(`/proc/${pid}/stat`).toString("utf8");
|
|
324
327
|
const commandEnd = stat.lastIndexOf(")");
|
|
325
328
|
if (commandEnd === -1) return undefined;
|
|
326
329
|
const fields = stat.slice(commandEnd + 1).trim().split(/\s+/);
|
|
@@ -504,6 +507,7 @@ function appendMaintenanceLog(root: string, result: AsyncRetentionResult, now: n
|
|
|
504
507
|
at: new Date(now).toISOString(),
|
|
505
508
|
acquired: result.acquired,
|
|
506
509
|
scanned: result.scanned,
|
|
510
|
+
repairedRuns: result.repairedRuns,
|
|
507
511
|
deletedRuns: result.deletedRuns,
|
|
508
512
|
deletedResults: result.deletedResults,
|
|
509
513
|
reapedTombstones: result.reapedTombstones,
|
|
@@ -654,6 +658,7 @@ export async function cleanupAsyncRetention(options: AsyncRetentionOptions): Pro
|
|
|
654
658
|
const result: AsyncRetentionResult = {
|
|
655
659
|
acquired: false,
|
|
656
660
|
scanned: 0,
|
|
661
|
+
repairedRuns: 0,
|
|
657
662
|
deletedRuns: 0,
|
|
658
663
|
deletedResults: 0,
|
|
659
664
|
reapedTombstones: 0,
|
|
@@ -750,7 +755,19 @@ export async function cleanupAsyncRetention(options: AsyncRetentionOptions): Pro
|
|
|
750
755
|
increment(result.skipped, "unsafe-run-path");
|
|
751
756
|
continue;
|
|
752
757
|
}
|
|
753
|
-
|
|
758
|
+
let status = readStatus(runDir);
|
|
759
|
+
if (status?.state === "running"
|
|
760
|
+
&& validRunId(status.runId)
|
|
761
|
+
&& path.basename(runDir) === status.runId
|
|
762
|
+
&& !protectedRunIds.has(status.runId)) {
|
|
763
|
+
const reconciliation = reconcileAsyncRun(runDir, {
|
|
764
|
+
resultsDir: options.resultsDir,
|
|
765
|
+
kill: options.reconcileKill,
|
|
766
|
+
now,
|
|
767
|
+
});
|
|
768
|
+
status = reconciliation.status ?? undefined;
|
|
769
|
+
if (reconciliation.repaired) result.repairedRuns += 1;
|
|
770
|
+
}
|
|
754
771
|
const initialReason = runSkipReason({ runDir, status, asyncDirRoot: options.asyncDirRoot, resultsDir: options.resultsDir, cutoff, protectedRunIds, waitRunIds: waitReferences.runIds });
|
|
755
772
|
if (initialReason) {
|
|
756
773
|
increment(result.skipped, initialReason);
|