@xzzpig/pi-subagents 0.7.0 → 0.9.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 +456 -4
- package/README.md +3 -3
- 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 +13 -3
- package/agents/scout.md +1 -1
- package/docs/agents.md +154 -42
- package/docs/configuration.md +85 -26
- package/docs/extension-api.md +81 -16
- package/docs/missions.md +2 -0
- package/docs/models.md +75 -11
- package/docs/observability.md +34 -21
- package/docs/tool-reference.md +142 -18
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +148 -4
- package/index.ts +10 -1
- package/install.mjs +1 -1
- package/package.json +7 -6
- package/prompts/council.md +19 -7
- package/prompts/parallel-review.md +5 -1
- package/prompts/review-loop.md +11 -7
- package/skills/council-mode/SKILL.md +44 -215
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +90 -32
- package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
- package/skills/pi-subagents/references/execution-controls.md +104 -19
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
- package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +471 -114
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +16 -4
- package/src/agents/agents.ts +1076 -351
- package/src/agents/builtin-names.ts +6 -0
- package/src/agents/runtime-agent-events.ts +70 -0
- package/src/agents/runtime-agent-registry.ts +31 -20
- 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-job-provider.ts +10 -1
- package/src/api/external-runs.ts +67 -4
- package/src/api/preflight.ts +97 -34
- package/src/api/project-panes.ts +2 -0
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +15 -13
- package/src/extension/fanout-child.ts +17 -16
- package/src/extension/index.ts +139 -41
- package/src/extension/public-execution.ts +113 -22
- package/src/extension/rpc.ts +182 -13
- package/src/extension/schemas.ts +63 -21
- package/src/extension/tool-description.ts +48 -23
- package/src/extension/tool-result.ts +19 -0
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/client.ts +3 -3
- package/src/inspectors/herdr/focus.ts +55 -0
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/project-panes.ts +228 -44
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +75 -5
- package/src/intercom/native-supervisor-channel.ts +138 -60
- package/src/intercom/result-intercom.ts +2 -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 +492 -125
- package/src/runs/background/async-job-tracker.ts +127 -28
- package/src/runs/background/async-resume.ts +67 -29
- package/src/runs/background/async-retention.ts +21 -4
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +199 -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 +79 -8
- package/src/runs/background/control-channel.ts +101 -214
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +295 -8
- 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 +43 -19
- 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 +99 -18
- 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 +13 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +959 -1159
- 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 +45 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +27 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/async-stop-action.ts +23 -2
- package/src/runs/foreground/execution.ts +585 -481
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +26 -3
- package/src/runs/foreground/subagent-executor.ts +1549 -410
- package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
- 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 +147 -39
- package/src/runs/shared/agent-contract.ts +1 -1
- 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 +62 -0
- package/src/runs/shared/child-launch-plan.ts +151 -0
- package/src/runs/shared/child-launch.ts +314 -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 +342 -0
- package/src/runs/shared/child-tool-plan.ts +540 -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 +57 -6
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +4 -4
- package/src/runs/shared/extension-bindings.ts +78 -0
- 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 +349 -54
- package/src/runs/shared/external-job-bridge.ts +53 -37
- package/src/runs/shared/external-job-runner.ts +126 -23
- package/src/runs/shared/fast-mode-extension.ts +10 -0
- 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 +141 -10
- package/src/runs/shared/model-fallback.ts +187 -33
- package/src/runs/shared/model-scope.ts +106 -39
- package/src/runs/shared/mutation-evidence.ts +199 -0
- package/src/runs/shared/nested-events.ts +38 -48
- 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 +83 -16
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +28 -5
- 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/single-output.ts +89 -22
- package/src/runs/shared/structured-output.ts +61 -7
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -64
- 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 +20 -6
- package/src/shared/pruned-fork.ts +450 -0
- package/src/shared/session-file-trust.ts +19 -0
- package/src/shared/session-tokens.ts +14 -3
- package/src/shared/settings.ts +21 -102
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +46 -0
- package/src/shared/types.ts +644 -75
- 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 +278 -90
- 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 +1433 -166
- 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/permission-arbiter.ts +59 -52
- 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 +1142 -69
- 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 -858
- 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
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
|
-
import
|
|
3
|
-
import
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { resultFilePath, resultPayloadPathForSessionRun } from "./result-files.ts";
|
|
4
|
+
import type { AcceptanceLedger, ArtifactPaths, AsyncStatus, CostSummary, EffectsProjection, ExecutionProjection, ModelAttempt, Usage } from "../../shared/types.ts";
|
|
4
5
|
import { readStatus } from "../../shared/utils.ts";
|
|
5
6
|
|
|
6
7
|
export interface ImportedAsyncRoot {
|
|
@@ -12,6 +13,8 @@ export interface ImportedAsyncRoot {
|
|
|
12
13
|
|
|
13
14
|
export interface ImportedAsyncRootResult {
|
|
14
15
|
agent: string;
|
|
16
|
+
/** Human-readable display name for the child session, when derived at launch. */
|
|
17
|
+
sessionName?: string;
|
|
15
18
|
output: string;
|
|
16
19
|
success: boolean;
|
|
17
20
|
exitCode: number;
|
|
@@ -21,13 +24,21 @@ export interface ImportedAsyncRootResult {
|
|
|
21
24
|
model?: string;
|
|
22
25
|
attemptedModels?: string[];
|
|
23
26
|
modelAttempts?: ModelAttempt[];
|
|
27
|
+
contextOverflow?: boolean;
|
|
24
28
|
totalCost?: CostSummary;
|
|
29
|
+
usage?: Usage;
|
|
25
30
|
structuredOutput?: unknown;
|
|
26
31
|
structuredOutputPath?: string;
|
|
27
32
|
structuredOutputSchemaPath?: string;
|
|
28
33
|
acceptance?: AcceptanceLedger;
|
|
34
|
+
artifactPaths?: ArtifactPaths;
|
|
35
|
+
outputSaveError?: string;
|
|
36
|
+
transcriptPath?: string;
|
|
37
|
+
transcriptError?: string;
|
|
29
38
|
timedOut?: boolean;
|
|
30
39
|
stopped?: boolean;
|
|
40
|
+
execution?: ExecutionProjection;
|
|
41
|
+
effects?: EffectsProjection;
|
|
31
42
|
}
|
|
32
43
|
|
|
33
44
|
interface AsyncResultFile {
|
|
@@ -39,26 +50,52 @@ interface AsyncResultFile {
|
|
|
39
50
|
stopped?: boolean;
|
|
40
51
|
results?: Array<{
|
|
41
52
|
agent?: string;
|
|
53
|
+
sessionName?: string;
|
|
42
54
|
output?: string;
|
|
43
55
|
error?: string;
|
|
44
56
|
success?: boolean;
|
|
45
57
|
timedOut?: boolean;
|
|
46
58
|
stopped?: boolean;
|
|
59
|
+
execution?: ExecutionProjection;
|
|
60
|
+
effects?: EffectsProjection;
|
|
47
61
|
sessionFile?: string;
|
|
48
62
|
intercomTarget?: string;
|
|
49
63
|
model?: string;
|
|
50
64
|
attemptedModels?: string[];
|
|
51
65
|
modelAttempts?: ModelAttempt[];
|
|
66
|
+
contextOverflow?: boolean;
|
|
52
67
|
totalCost?: CostSummary;
|
|
68
|
+
usage?: Usage;
|
|
53
69
|
structuredOutput?: unknown;
|
|
54
70
|
structuredOutputPath?: string;
|
|
55
71
|
structuredOutputSchemaPath?: string;
|
|
56
72
|
acceptance?: AcceptanceLedger;
|
|
73
|
+
artifactPaths?: ArtifactPaths;
|
|
74
|
+
outputSaveError?: string;
|
|
75
|
+
transcriptPath?: string;
|
|
76
|
+
transcriptError?: string;
|
|
57
77
|
}>;
|
|
58
78
|
}
|
|
59
79
|
|
|
60
|
-
const TERMINAL_STATES = new Set(["complete", "failed", "paused", "stopped"]);
|
|
61
|
-
const TERMINAL_STEP_STATUSES = new Set(["complete", "completed", "failed", "paused", "stopped"]);
|
|
80
|
+
const TERMINAL_STATES = new Set(["complete", "failed", "partial", "paused", "stopped"]);
|
|
81
|
+
const TERMINAL_STEP_STATUSES = new Set(["complete", "completed", "failed", "partial", "paused", "stopped"]);
|
|
82
|
+
|
|
83
|
+
function usageFromAttempts(attempts: ModelAttempt[] | undefined): Usage | undefined {
|
|
84
|
+
if (!attempts?.length) return undefined;
|
|
85
|
+
const usage: Usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
|
|
86
|
+
for (const attempt of attempts) {
|
|
87
|
+
if (!attempt.usage) continue;
|
|
88
|
+
usage.input += attempt.usage.input;
|
|
89
|
+
usage.output += attempt.usage.output;
|
|
90
|
+
usage.cacheRead += attempt.usage.cacheRead;
|
|
91
|
+
usage.cacheWrite += attempt.usage.cacheWrite;
|
|
92
|
+
usage.cost += attempt.usage.cost;
|
|
93
|
+
usage.turns += attempt.usage.turns;
|
|
94
|
+
}
|
|
95
|
+
return usage.input !== 0 || usage.output !== 0 || usage.cacheRead !== 0 || usage.cacheWrite !== 0 || usage.cost !== 0 || usage.turns !== 0
|
|
96
|
+
? usage
|
|
97
|
+
: undefined;
|
|
98
|
+
}
|
|
62
99
|
|
|
63
100
|
function readResultFile(resultPath: string): AsyncResultFile | undefined {
|
|
64
101
|
try {
|
|
@@ -71,6 +108,13 @@ function readResultFile(resultPath: string): AsyncResultFile | undefined {
|
|
|
71
108
|
}
|
|
72
109
|
}
|
|
73
110
|
|
|
111
|
+
function readImportedResultFile(root: ImportedAsyncRoot, status: AsyncStatus | null): AsyncResultFile | undefined {
|
|
112
|
+
const direct = readResultFile(root.resultPath);
|
|
113
|
+
if (direct || !status?.sessionId) return direct;
|
|
114
|
+
const indexedPath = resultPayloadPathForSessionRun(path.dirname(root.resultPath), status.sessionId, root.runId);
|
|
115
|
+
return indexedPath ? readResultFile(indexedPath) : undefined;
|
|
116
|
+
}
|
|
117
|
+
|
|
74
118
|
function selectedStatusStep(status: AsyncStatus | null, index: number): NonNullable<AsyncStatus["steps"]>[number] | undefined {
|
|
75
119
|
return status?.steps?.[index];
|
|
76
120
|
}
|
|
@@ -82,12 +126,12 @@ function isTerminalStatus(status: AsyncStatus | null, index: number): boolean {
|
|
|
82
126
|
return TERMINAL_STATES.has(status.state);
|
|
83
127
|
}
|
|
84
128
|
|
|
85
|
-
function resultState(result: AsyncResultFile | undefined, child: NonNullable<AsyncResultFile["results"]>[number] | undefined): "complete" | "failed" | "paused" | "stopped" | undefined {
|
|
129
|
+
function resultState(result: AsyncResultFile | undefined, child: NonNullable<AsyncResultFile["results"]>[number] | undefined): "complete" | "failed" | "partial" | "paused" | "stopped" | undefined {
|
|
86
130
|
if (!result) return undefined;
|
|
87
131
|
if (child?.stopped === true) return "stopped";
|
|
88
132
|
if (child?.success === true) return "complete";
|
|
89
|
-
if (child?.success === false) return result.state === "stopped" ? "stopped" : result.state === "paused" ? "paused" : "failed";
|
|
90
|
-
if (result.state === "complete" || result.state === "failed" || result.state === "paused" || result.state === "stopped") return result.state;
|
|
133
|
+
if (child?.success === false) return result.state === "stopped" ? "stopped" : result.state === "paused" ? "paused" : result.state === "partial" ? "partial" : "failed";
|
|
134
|
+
if (result.state === "complete" || result.state === "failed" || result.state === "partial" || result.state === "paused" || result.state === "stopped") return result.state;
|
|
91
135
|
if (result.success === true) return "complete";
|
|
92
136
|
if (result.success === false) return "failed";
|
|
93
137
|
return undefined;
|
|
@@ -98,6 +142,11 @@ function outputFromTerminalStatus(root: ImportedAsyncRoot, status: AsyncStatus,
|
|
|
98
142
|
const timedOut = step?.timedOut === true || status.timedOut === true;
|
|
99
143
|
const stopped = step?.stopped === true || status.stopped === true || status.state === "stopped";
|
|
100
144
|
const message = step?.error ?? status.error ?? (stopped ? "Subagent stopped by user." : `Attached async root ${root.runId} ended without a result file at ${root.resultPath}.`);
|
|
145
|
+
const partialStatus = status.state === "partial" || step?.status === "partial";
|
|
146
|
+
const execution = step?.execution ?? (partialStatus
|
|
147
|
+
? { status: "partial" as const, success: false, exitCode: 1, error: message }
|
|
148
|
+
: undefined);
|
|
149
|
+
const usage = usageFromAttempts(step?.modelAttempts);
|
|
101
150
|
return {
|
|
102
151
|
agent,
|
|
103
152
|
output: message,
|
|
@@ -106,20 +155,27 @@ function outputFromTerminalStatus(root: ImportedAsyncRoot, status: AsyncStatus,
|
|
|
106
155
|
error: message,
|
|
107
156
|
...(timedOut ? { timedOut: true } : {}),
|
|
108
157
|
...(stopped ? { stopped: true } : {}),
|
|
158
|
+
...(step?.sessionName ? { sessionName: step.sessionName } : {}),
|
|
109
159
|
...(step?.sessionFile ?? status.sessionFile ? { sessionFile: step?.sessionFile ?? status.sessionFile } : {}),
|
|
110
160
|
...(step?.model ? { model: step.model } : {}),
|
|
111
161
|
...(step?.attemptedModels ? { attemptedModels: step.attemptedModels } : {}),
|
|
112
162
|
...(step?.modelAttempts ? { modelAttempts: step.modelAttempts } : {}),
|
|
163
|
+
...(step?.contextOverflow ? { contextOverflow: true } : {}),
|
|
113
164
|
...(step?.totalCost ? { totalCost: step.totalCost } : {}),
|
|
165
|
+
...(usage ? { usage } : {}),
|
|
114
166
|
...(step?.structuredOutput !== undefined ? { structuredOutput: step.structuredOutput } : {}),
|
|
115
167
|
...(step?.structuredOutputPath ? { structuredOutputPath: step.structuredOutputPath } : {}),
|
|
116
168
|
...(step?.structuredOutputSchemaPath ? { structuredOutputSchemaPath: step.structuredOutputSchemaPath } : {}),
|
|
117
169
|
...(step?.acceptance ? { acceptance: step.acceptance } : {}),
|
|
170
|
+
...(execution ? { execution } : {}),
|
|
171
|
+
...(step?.effects ? { effects: step.effects } : {}),
|
|
172
|
+
...(step?.transcriptPath ? { transcriptPath: step.transcriptPath } : {}),
|
|
118
173
|
};
|
|
119
174
|
}
|
|
120
175
|
|
|
121
176
|
function outputFromTimeout(root: ImportedAsyncRoot, status: AsyncStatus | null, message: string): ImportedAsyncRootResult {
|
|
122
177
|
const step = selectedStatusStep(status, root.index);
|
|
178
|
+
const usage = usageFromAttempts(step?.modelAttempts);
|
|
123
179
|
return {
|
|
124
180
|
agent: step?.agent ?? status?.steps?.[root.index]?.agent ?? "subagent",
|
|
125
181
|
output: message,
|
|
@@ -127,11 +183,15 @@ function outputFromTimeout(root: ImportedAsyncRoot, status: AsyncStatus | null,
|
|
|
127
183
|
exitCode: 1,
|
|
128
184
|
error: message,
|
|
129
185
|
timedOut: true,
|
|
186
|
+
...(step?.sessionName ? { sessionName: step.sessionName } : {}),
|
|
130
187
|
...(step?.sessionFile ?? status?.sessionFile ? { sessionFile: step?.sessionFile ?? status?.sessionFile } : {}),
|
|
131
188
|
...(step?.model ? { model: step.model } : {}),
|
|
132
189
|
...(step?.attemptedModels ? { attemptedModels: step.attemptedModels } : {}),
|
|
133
190
|
...(step?.modelAttempts ? { modelAttempts: step.modelAttempts } : {}),
|
|
191
|
+
...(step?.contextOverflow ? { contextOverflow: true } : {}),
|
|
134
192
|
...(step?.totalCost ? { totalCost: step.totalCost } : {}),
|
|
193
|
+
...(usage ? { usage } : {}),
|
|
194
|
+
...(step?.transcriptPath ? { transcriptPath: step.transcriptPath } : {}),
|
|
135
195
|
};
|
|
136
196
|
}
|
|
137
197
|
|
|
@@ -145,6 +205,8 @@ function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null
|
|
|
145
205
|
const stopped = child?.stopped === true || step?.stopped === true || result.stopped === true || status?.stopped === true || state === "stopped";
|
|
146
206
|
const success = state === "complete" && !timedOut && !stopped;
|
|
147
207
|
const error = child?.error ?? (success ? undefined : stopped ? "Subagent stopped by user." : result.error ?? result.summary ?? status?.error ?? `Attached async root ${root.runId} did not complete successfully.`);
|
|
208
|
+
const execution = state ? { status: state === "complete" ? "completed" as const : state, success, exitCode: success ? 0 : 1, ...(error ? { error } : {}) } : undefined;
|
|
209
|
+
const usage = child?.usage ?? usageFromAttempts(step?.modelAttempts);
|
|
148
210
|
return {
|
|
149
211
|
agent,
|
|
150
212
|
output: success ? output : (output || error || ""),
|
|
@@ -153,16 +215,25 @@ function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null
|
|
|
153
215
|
...(error ? { error } : {}),
|
|
154
216
|
...(timedOut ? { timedOut: true } : {}),
|
|
155
217
|
...(stopped ? { stopped: true } : {}),
|
|
218
|
+
...(child?.sessionName ?? step?.sessionName ? { sessionName: child?.sessionName ?? step?.sessionName } : {}),
|
|
156
219
|
...(child?.sessionFile ?? step?.sessionFile ?? status?.sessionFile ? { sessionFile: child?.sessionFile ?? step?.sessionFile ?? status?.sessionFile } : {}),
|
|
157
220
|
...(child?.intercomTarget ? { intercomTarget: child.intercomTarget } : {}),
|
|
158
221
|
...(child?.model ?? step?.model ? { model: child?.model ?? step?.model } : {}),
|
|
159
222
|
...(child?.attemptedModels ?? step?.attemptedModels ? { attemptedModels: child?.attemptedModels ?? step?.attemptedModels } : {}),
|
|
160
223
|
...(child?.modelAttempts ?? step?.modelAttempts ? { modelAttempts: child?.modelAttempts ?? step?.modelAttempts } : {}),
|
|
224
|
+
...(child?.contextOverflow || step?.contextOverflow ? { contextOverflow: true } : {}),
|
|
161
225
|
...(child?.totalCost ?? step?.totalCost ? { totalCost: child?.totalCost ?? step?.totalCost } : {}),
|
|
226
|
+
...(usage ? { usage } : {}),
|
|
162
227
|
...(child?.structuredOutput !== undefined ? { structuredOutput: child.structuredOutput } : step?.structuredOutput !== undefined ? { structuredOutput: step.structuredOutput } : {}),
|
|
163
228
|
...(child?.structuredOutputPath ?? step?.structuredOutputPath ? { structuredOutputPath: child?.structuredOutputPath ?? step?.structuredOutputPath } : {}),
|
|
164
229
|
...(child?.structuredOutputSchemaPath ?? step?.structuredOutputSchemaPath ? { structuredOutputSchemaPath: child?.structuredOutputSchemaPath ?? step?.structuredOutputSchemaPath } : {}),
|
|
165
230
|
...(child?.acceptance ?? step?.acceptance ? { acceptance: child?.acceptance ?? step?.acceptance } : {}),
|
|
231
|
+
...(child?.artifactPaths ? { artifactPaths: child.artifactPaths } : {}),
|
|
232
|
+
...(child?.outputSaveError ? { outputSaveError: child.outputSaveError } : {}),
|
|
233
|
+
...(child?.transcriptPath ?? step?.transcriptPath ? { transcriptPath: child?.transcriptPath ?? step?.transcriptPath } : {}),
|
|
234
|
+
...(child?.transcriptError ? { transcriptError: child.transcriptError } : {}),
|
|
235
|
+
...(execution ? { execution } : {}),
|
|
236
|
+
...(child?.effects ?? step?.effects ? { effects: child?.effects ?? step?.effects } : {}),
|
|
166
237
|
};
|
|
167
238
|
}
|
|
168
239
|
|
|
@@ -177,7 +248,7 @@ export async function waitForImportedAsyncRoot(
|
|
|
177
248
|
for (;;) {
|
|
178
249
|
const status = readStatus(root.asyncDir);
|
|
179
250
|
if (options.shouldAbort?.()) return outputFromTimeout(root, status, options.timeoutMessage ?? "Subagent timed out.");
|
|
180
|
-
const result =
|
|
251
|
+
const result = readImportedResultFile(root, status);
|
|
181
252
|
if (result) return buildImportedResult(root, status, result);
|
|
182
253
|
if (isTerminalStatus(status, root.index)) {
|
|
183
254
|
terminalSince ??= now();
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Cross-OS control channel for async subagent runs.
|
|
3
3
|
*
|
|
4
|
-
* Background runs
|
|
5
|
-
*
|
|
4
|
+
* Background runs use a detached runner process. Unix detaches it from the parent process.
|
|
5
|
+
* The original control path delivered an interrupt with
|
|
6
|
+
* `process.kill(pid, SIGUSR2|SIGBREAK)`, but Windows cannot
|
|
6
7
|
* deliver those signals cross-process via `process.kill` and throws `ENOSYS`,
|
|
7
8
|
* which left async runs uninterruptible (no stop, no live steer) on Windows.
|
|
8
9
|
*
|
|
@@ -55,6 +56,8 @@ export interface StopRequest {
|
|
|
55
56
|
ts?: number;
|
|
56
57
|
source?: string;
|
|
57
58
|
reason?: string;
|
|
59
|
+
targetIndex?: number;
|
|
60
|
+
childId?: string;
|
|
58
61
|
}
|
|
59
62
|
|
|
60
63
|
export type SteerDeliveryMode = "steer" | "follow_up" | "auto";
|
|
@@ -71,32 +74,10 @@ export interface SteerRequest {
|
|
|
71
74
|
source?: string;
|
|
72
75
|
}
|
|
73
76
|
|
|
74
|
-
export interface SteerCapability {
|
|
75
|
-
type: "steer-capability";
|
|
76
|
-
protocolVersion: 1;
|
|
77
|
-
index: number;
|
|
78
|
-
pid: number;
|
|
79
|
-
readyAt: number;
|
|
80
|
-
supported: boolean;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export interface SteerAck {
|
|
84
|
-
type: "steer-ack";
|
|
85
|
-
protocolVersion: 1;
|
|
86
|
-
requestId: string;
|
|
87
|
-
index: number;
|
|
88
|
-
ts: number;
|
|
89
|
-
state: "delivered" | "queued" | "failed";
|
|
90
|
-
deliveryStatus?: SteerDeliveryStatus;
|
|
91
|
-
message: string;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
77
|
const STEER_REQUESTS_DIR = "steer-requests";
|
|
78
|
+
const STOP_REQUESTS_DIR = "stop-requests";
|
|
95
79
|
const REVIVAL_BRIEFS_DIR = "revival-briefs";
|
|
96
80
|
export const MAX_STEER_QUEUE_SIZE = 20;
|
|
97
|
-
const STEER_TARGETS_DIR = "steer-targets";
|
|
98
|
-
const STEER_CAPABILITIES_DIR = "steer-capabilities";
|
|
99
|
-
const STEER_ACKS_DIR = "steer-acks";
|
|
100
81
|
const STEER_INBOX_CLOSED_FILE = "steer-inbox-closed.json";
|
|
101
82
|
const MAX_STEER_MESSAGE_BYTES = 128 * 1024;
|
|
102
83
|
const MAX_STEER_REQUEST_ID_LENGTH = 256;
|
|
@@ -121,6 +102,11 @@ export function stopRequestPath(asyncDir: string): string {
|
|
|
121
102
|
return path.join(controlInboxDir(asyncDir), "stop.json");
|
|
122
103
|
}
|
|
123
104
|
|
|
105
|
+
/** Directory of parent-to-runner stop requests. */
|
|
106
|
+
export function stopRequestsDir(asyncDir: string): string {
|
|
107
|
+
return path.join(controlInboxDir(asyncDir), STOP_REQUESTS_DIR);
|
|
108
|
+
}
|
|
109
|
+
|
|
124
110
|
/** Directory of parent-to-runner steering requests. */
|
|
125
111
|
export function steerRequestsDir(asyncDir: string): string {
|
|
126
112
|
return path.join(controlInboxDir(asyncDir), STEER_REQUESTS_DIR);
|
|
@@ -134,43 +120,25 @@ export function closeSteerInbox(asyncDir: string, state: string, write: (filePat
|
|
|
134
120
|
write(steerInboxClosedPath(asyncDir), { version: 1, closedAt: Date.now(), state });
|
|
135
121
|
}
|
|
136
122
|
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
assertChildIndex(index);
|
|
140
|
-
return path.join(controlInboxDir(asyncDir), STEER_TARGETS_DIR, String(index));
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
export function steerCapabilitiesDir(asyncDir: string): string {
|
|
144
|
-
return path.join(controlInboxDir(asyncDir), STEER_CAPABILITIES_DIR);
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
export function steerCapabilityPath(asyncDir: string, index: number): string {
|
|
148
|
-
assertChildIndex(index);
|
|
149
|
-
return path.join(steerCapabilitiesDir(asyncDir), `${index}.json`);
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
export function steerAcksDir(asyncDir: string, index: number): string {
|
|
153
|
-
assertChildIndex(index);
|
|
154
|
-
return path.join(controlInboxDir(asyncDir), STEER_ACKS_DIR, String(index));
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
function steerAckFileName(requestId: string): string {
|
|
158
|
-
return `${Buffer.from(requestId).toString("base64url")}.json`;
|
|
123
|
+
function assertChildIndex(index: number): void {
|
|
124
|
+
if (!Number.isInteger(index) || index < 0 || index > 1_000_000) throw new Error("child index must be a non-negative integer.");
|
|
159
125
|
}
|
|
160
126
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
function assertChildIndex(index: number): void {
|
|
167
|
-
if (!Number.isInteger(index) || index < 0 || index > 1_000_000) throw new Error("steer child index must be a non-negative integer.");
|
|
127
|
+
function validStopChildId(childId: unknown): childId is string {
|
|
128
|
+
return typeof childId === "string"
|
|
129
|
+
&& Boolean(childId.trim())
|
|
130
|
+
&& childId.length <= 256
|
|
131
|
+
&& !/[\r\n]/.test(childId);
|
|
168
132
|
}
|
|
169
133
|
|
|
170
134
|
function steerRequestFileName(request: SteerRequest): string {
|
|
171
135
|
return `${String(request.ts).padStart(13, "0")}-${Buffer.from(request.id).toString("base64url")}.json`;
|
|
172
136
|
}
|
|
173
137
|
|
|
138
|
+
function stopRequestFileName(request: StopRequest): string {
|
|
139
|
+
return `${String(request.ts ?? 0).padStart(13, "0")}-${randomUUID()}.json`;
|
|
140
|
+
}
|
|
141
|
+
|
|
174
142
|
function validSteerRequest(request: Partial<SteerRequest>): request is SteerRequest {
|
|
175
143
|
return request.type === "steer"
|
|
176
144
|
&& typeof request.id === "string"
|
|
@@ -209,45 +177,6 @@ export function writeSteerRequestToExistingDir(dir: string, request: SteerReques
|
|
|
209
177
|
return requestPath;
|
|
210
178
|
}
|
|
211
179
|
|
|
212
|
-
export function writeSteerCapabilityAt(filePath: string, capability: Omit<SteerCapability, "type" | "protocolVersion">): string {
|
|
213
|
-
assertChildIndex(capability.index);
|
|
214
|
-
if (!Number.isInteger(capability.pid) || capability.pid <= 0) throw new Error("steer capability pid must be a positive integer.");
|
|
215
|
-
if (!Number.isFinite(capability.readyAt) || capability.readyAt <= 0) throw new Error("steer capability readyAt must be a finite timestamp.");
|
|
216
|
-
const record: SteerCapability = { type: "steer-capability", protocolVersion: 1, ...capability };
|
|
217
|
-
writeAtomicJson(filePath, record);
|
|
218
|
-
return filePath;
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
export function writeSteerCapability(asyncDir: string, capability: Omit<SteerCapability, "type" | "protocolVersion">): string {
|
|
222
|
-
return writeSteerCapabilityAt(steerCapabilityPath(asyncDir, capability.index), capability);
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
function steerAckWritePath(filePath: string, ack: Omit<SteerAck, "type" | "protocolVersion">): string {
|
|
226
|
-
const parsed = path.parse(filePath);
|
|
227
|
-
const stateOrder = ack.state === "queued" ? "0" : ack.state === "delivered" ? "1" : "2";
|
|
228
|
-
const timestamp = String(Math.trunc(ack.ts)).padStart(13, "0");
|
|
229
|
-
for (let suffix = 0; suffix < 1_000; suffix += 1) {
|
|
230
|
-
const candidate = path.join(parsed.dir, `${parsed.name}-${timestamp}-${stateOrder}-${ack.state}${suffix === 0 ? "" : `-${suffix}`}${parsed.ext}`);
|
|
231
|
-
if (!fs.existsSync(candidate)) return candidate;
|
|
232
|
-
}
|
|
233
|
-
throw new Error("steer acknowledgment queue is full.");
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
export function writeSteerAckAt(filePath: string, ack: Omit<SteerAck, "type" | "protocolVersion">): string {
|
|
237
|
-
assertChildIndex(ack.index);
|
|
238
|
-
if (!/^[^\s]+$/.test(ack.requestId) || ack.requestId.length > 256) throw new Error("steer acknowledgment requestId is invalid.");
|
|
239
|
-
if (!Number.isFinite(ack.ts) || ack.ts <= 0) throw new Error("steer acknowledgment ts must be a finite timestamp.");
|
|
240
|
-
if (!ack.message.trim() || ack.message.length > 1000) throw new Error("steer acknowledgment message is invalid.");
|
|
241
|
-
const record: SteerAck = { type: "steer-ack", protocolVersion: 1, ...ack, message: ack.message.trim() };
|
|
242
|
-
const ackPath = steerAckWritePath(filePath, ack);
|
|
243
|
-
writeAtomicJson(ackPath, record);
|
|
244
|
-
return ackPath;
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
export function writeSteerAck(asyncDir: string, ack: Omit<SteerAck, "type" | "protocolVersion">): string {
|
|
248
|
-
return writeSteerAckAt(path.join(steerAcksDir(asyncDir, ack.index), steerAckFileName(ack.requestId)), ack);
|
|
249
|
-
}
|
|
250
|
-
|
|
251
180
|
/**
|
|
252
181
|
* Parent side: drop a portable interrupt request the runner's inbox watcher will
|
|
253
182
|
* pick up regardless of OS. Written atomically (temp + rename), dir auto-created.
|
|
@@ -279,8 +208,12 @@ export function requestAsyncStop(
|
|
|
279
208
|
payload: Omit<StopRequest, "type"> = {},
|
|
280
209
|
deps: { now?: () => number } = {},
|
|
281
210
|
): string {
|
|
282
|
-
|
|
211
|
+
if (payload.targetIndex !== undefined) assertChildIndex(payload.targetIndex);
|
|
212
|
+
if (payload.childId !== undefined && !validStopChildId(payload.childId)) {
|
|
213
|
+
throw new Error("stop childId must be a non-empty string without newlines and at most 256 characters.");
|
|
214
|
+
}
|
|
283
215
|
const request: StopRequest = { ...payload, ts: payload.ts ?? deps.now?.() ?? Date.now(), type: "stop" };
|
|
216
|
+
const requestPath = path.join(stopRequestsDir(asyncDir), stopRequestFileName(request));
|
|
284
217
|
writeAtomicJson(requestPath, request);
|
|
285
218
|
return requestPath;
|
|
286
219
|
}
|
|
@@ -326,97 +259,6 @@ export function requestAsyncSteer(
|
|
|
326
259
|
return requestPath;
|
|
327
260
|
}
|
|
328
261
|
|
|
329
|
-
export function enqueueStepSteer(asyncDir: string, index: number, request: SteerRequest): string {
|
|
330
|
-
assertChildIndex(index);
|
|
331
|
-
const { targetIndexes: _targetIndexes, ...singleTargetRequest } = request;
|
|
332
|
-
return writeSteerRequestToDir(stepSteerInboxDir(asyncDir, index), { ...singleTargetRequest, targetIndex: index, type: "steer" });
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
function parseSteerCapability(raw: unknown): SteerCapability | undefined {
|
|
336
|
-
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
|
|
337
|
-
const input = raw as Partial<SteerCapability>;
|
|
338
|
-
if (input.type !== "steer-capability" || input.protocolVersion !== 1) return undefined;
|
|
339
|
-
const { index, pid, readyAt, supported } = input;
|
|
340
|
-
if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index > 1_000_000) return undefined;
|
|
341
|
-
if (typeof pid !== "number" || typeof readyAt !== "number" || !Number.isInteger(pid) || pid <= 0 || !Number.isFinite(readyAt) || readyAt <= 0 || typeof supported !== "boolean") return undefined;
|
|
342
|
-
return { type: "steer-capability", protocolVersion: 1, index, pid, readyAt, supported };
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
function parseSteerAck(raw: unknown): SteerAck | undefined {
|
|
346
|
-
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
|
|
347
|
-
const input = raw as Partial<SteerAck>;
|
|
348
|
-
if (input.type !== "steer-ack" || input.protocolVersion !== 1 || typeof input.requestId !== "string" || !/^[^\s]+$/.test(input.requestId) || input.requestId.length > 256) return undefined;
|
|
349
|
-
const { index, ts, state, message } = input;
|
|
350
|
-
if (typeof index !== "number" || typeof ts !== "number" || !Number.isInteger(index) || index < 0 || index > 1_000_000 || !Number.isFinite(ts) || ts <= 0) return undefined;
|
|
351
|
-
if (state !== "delivered" && state !== "queued" && state !== "failed") return undefined;
|
|
352
|
-
if (input.deliveryStatus !== undefined && input.deliveryStatus !== "delivered" && input.deliveryStatus !== "queued") return undefined;
|
|
353
|
-
if (typeof message !== "string" || !message.trim() || message.length > 1000) return undefined;
|
|
354
|
-
return { type: "steer-ack", protocolVersion: 1, requestId: input.requestId, index, ts, state, ...(input.deliveryStatus ? { deliveryStatus: input.deliveryStatus } : {}), message: message.trim() };
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
export function readSteerCapability(asyncDir: string, index: number): SteerCapability | undefined {
|
|
358
|
-
try {
|
|
359
|
-
return parseSteerCapability(JSON.parse(fs.readFileSync(steerCapabilityPath(asyncDir, index), "utf-8")));
|
|
360
|
-
} catch {
|
|
361
|
-
return undefined;
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
export function consumeSteerCapabilities(asyncDir: string, fsImpl: Pick<typeof fs, "existsSync" | "readdirSync" | "readFileSync"> = fs): SteerCapability[] {
|
|
366
|
-
const dir = steerCapabilitiesDir(asyncDir);
|
|
367
|
-
if (!fsImpl.existsSync(dir)) return [];
|
|
368
|
-
const capabilities: SteerCapability[] = [];
|
|
369
|
-
for (const entry of fsImpl.readdirSync(dir).filter((name) => /^\d+\.json$/.test(name)).sort()) {
|
|
370
|
-
try {
|
|
371
|
-
const capability = parseSteerCapability(JSON.parse(fsImpl.readFileSync(path.join(dir, entry), "utf-8")));
|
|
372
|
-
if (capability) capabilities.push(capability);
|
|
373
|
-
} catch {
|
|
374
|
-
// A partially written or malformed capability is ignored until a valid one arrives.
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
return capabilities;
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
export function consumeSteerAckFromDir(
|
|
381
|
-
dir: string,
|
|
382
|
-
requestId: string,
|
|
383
|
-
fsImpl: Pick<typeof fs, "existsSync" | "readdirSync" | "readFileSync" | "rmSync"> = fs,
|
|
384
|
-
): SteerAck | undefined {
|
|
385
|
-
if (!fsImpl.existsSync(dir)) return undefined;
|
|
386
|
-
let entries: string[];
|
|
387
|
-
try { entries = fsImpl.readdirSync(dir).filter((name) => name.endsWith(".json")).sort(); } catch { return undefined; }
|
|
388
|
-
for (const entry of entries) {
|
|
389
|
-
const target = path.join(dir, entry);
|
|
390
|
-
let ack: SteerAck | undefined;
|
|
391
|
-
try { ack = parseSteerAck(JSON.parse(fsImpl.readFileSync(target, "utf-8"))); } catch { ack = undefined; }
|
|
392
|
-
if (ack?.requestId !== requestId) continue;
|
|
393
|
-
try { fsImpl.rmSync(target, { force: true }); } catch { return undefined; }
|
|
394
|
-
return ack;
|
|
395
|
-
}
|
|
396
|
-
return undefined;
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
export function consumeSteerAcks(asyncDir: string, fsImpl: Pick<typeof fs, "existsSync" | "readdirSync" | "readFileSync" | "rmSync"> = fs): SteerAck[] {
|
|
400
|
-
const root = path.join(controlInboxDir(asyncDir), STEER_ACKS_DIR);
|
|
401
|
-
if (!fsImpl.existsSync(root)) return [];
|
|
402
|
-
const acks: SteerAck[] = [];
|
|
403
|
-
let indexNames: string[];
|
|
404
|
-
try { indexNames = fsImpl.readdirSync(root).filter((name) => /^\d+$/.test(name)); } catch { return []; }
|
|
405
|
-
for (const indexName of indexNames) {
|
|
406
|
-
const dir = path.join(root, indexName);
|
|
407
|
-
let entries: string[];
|
|
408
|
-
try { entries = fsImpl.readdirSync(dir).filter((name) => name.endsWith(".json")).sort(); } catch { continue; }
|
|
409
|
-
for (const entry of entries) {
|
|
410
|
-
const target = path.join(dir, entry);
|
|
411
|
-
let ack: SteerAck | undefined;
|
|
412
|
-
try { ack = parseSteerAck(JSON.parse(fsImpl.readFileSync(target, "utf-8"))); } catch { ack = undefined; }
|
|
413
|
-
try { fsImpl.rmSync(target, { force: true }); } catch { continue; }
|
|
414
|
-
if (ack) acks.push(ack);
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
return acks;
|
|
418
|
-
}
|
|
419
|
-
|
|
420
262
|
function parseSteerRequest(raw: unknown): SteerRequest | undefined {
|
|
421
263
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
|
|
422
264
|
const input = raw as Partial<SteerRequest>;
|
|
@@ -521,16 +363,78 @@ export function consumeTimeoutRequest(
|
|
|
521
363
|
|
|
522
364
|
export function consumeStopRequest(
|
|
523
365
|
asyncDir: string,
|
|
524
|
-
fsImpl: Pick<typeof fs, "existsSync" | "rmSync"> = fs,
|
|
366
|
+
fsImpl: Pick<typeof fs, "existsSync" | "rmSync" | "readdirSync" | "readFileSync"> = fs,
|
|
525
367
|
): boolean {
|
|
526
|
-
|
|
527
|
-
|
|
368
|
+
return consumeStopRequestPayload(asyncDir, fsImpl) !== undefined;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function parseStopRequest(raw: unknown): StopRequest | undefined {
|
|
372
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
|
|
373
|
+
const parsed = raw as Partial<StopRequest>;
|
|
374
|
+
if (parsed.type !== "stop") return undefined;
|
|
375
|
+
if (Object.hasOwn(parsed, "targetIndex") && !(Number.isInteger(parsed.targetIndex) && parsed.targetIndex! >= 0 && parsed.targetIndex! <= 1_000_000)) return undefined;
|
|
376
|
+
if (Object.hasOwn(parsed, "childId") && !validStopChildId(parsed.childId)) return undefined;
|
|
377
|
+
return {
|
|
378
|
+
type: "stop",
|
|
379
|
+
...(typeof parsed.ts === "number" ? { ts: parsed.ts } : {}),
|
|
380
|
+
...(typeof parsed.source === "string" ? { source: parsed.source } : {}),
|
|
381
|
+
...(typeof parsed.reason === "string" ? { reason: parsed.reason } : {}),
|
|
382
|
+
...(parsed.targetIndex !== undefined ? { targetIndex: parsed.targetIndex } : {}),
|
|
383
|
+
...(validStopChildId(parsed.childId) ? { childId: parsed.childId } : {}),
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function consumeStopRequestFile(
|
|
388
|
+
requestPath: string,
|
|
389
|
+
fsImpl: Pick<typeof fs, "rmSync" | "readFileSync">,
|
|
390
|
+
): StopRequest | undefined {
|
|
391
|
+
let request: StopRequest | undefined;
|
|
392
|
+
try {
|
|
393
|
+
request = parseStopRequest(JSON.parse(fsImpl.readFileSync(requestPath, "utf-8")));
|
|
394
|
+
} catch {
|
|
395
|
+
request = undefined;
|
|
396
|
+
}
|
|
528
397
|
try {
|
|
529
398
|
fsImpl.rmSync(requestPath, { force: true, recursive: true });
|
|
530
399
|
} catch {
|
|
531
|
-
// Already removed by a concurrent check —
|
|
400
|
+
// Already removed by a concurrent check — do not execute it twice.
|
|
401
|
+
return undefined;
|
|
532
402
|
}
|
|
533
|
-
return
|
|
403
|
+
return request;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
export function consumeStopRequestPayloads(
|
|
407
|
+
asyncDir: string,
|
|
408
|
+
fsImpl: Pick<typeof fs, "existsSync" | "rmSync" | "readdirSync" | "readFileSync"> = fs,
|
|
409
|
+
): StopRequest[] {
|
|
410
|
+
const dir = stopRequestsDir(asyncDir);
|
|
411
|
+
const requests: StopRequest[] = [];
|
|
412
|
+
if (fsImpl.existsSync(dir)) {
|
|
413
|
+
let entries: string[];
|
|
414
|
+
try {
|
|
415
|
+
entries = fsImpl.readdirSync(dir).filter((name) => name.endsWith(".json")).sort();
|
|
416
|
+
} catch {
|
|
417
|
+
entries = [];
|
|
418
|
+
}
|
|
419
|
+
for (const entry of entries) {
|
|
420
|
+
const request = consumeStopRequestFile(path.join(dir, entry), fsImpl);
|
|
421
|
+
if (request) requests.push(request);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const legacyPath = stopRequestPath(asyncDir);
|
|
426
|
+
if (fsImpl.existsSync(legacyPath)) {
|
|
427
|
+
const request = consumeStopRequestFile(legacyPath, fsImpl);
|
|
428
|
+
if (request) requests.push(request);
|
|
429
|
+
}
|
|
430
|
+
return requests.sort((left, right) => (left.ts ?? 0) - (right.ts ?? 0));
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
export function consumeStopRequestPayload(
|
|
434
|
+
asyncDir: string,
|
|
435
|
+
fsImpl: Pick<typeof fs, "existsSync" | "rmSync" | "readdirSync" | "readFileSync"> = fs,
|
|
436
|
+
): StopRequest | undefined {
|
|
437
|
+
return consumeStopRequestPayloads(asyncDir, fsImpl)[0];
|
|
534
438
|
}
|
|
535
439
|
|
|
536
440
|
/** Parent side: write the authoritative portable interrupt request. */
|
|
@@ -560,8 +464,10 @@ export function deliverStopRequest(input: {
|
|
|
560
464
|
signal?: NodeJS.Signals;
|
|
561
465
|
now?: () => number;
|
|
562
466
|
source?: string;
|
|
467
|
+
targetIndex?: number;
|
|
468
|
+
childId?: string;
|
|
563
469
|
}): void {
|
|
564
|
-
requestAsyncStop(input.asyncDir, input.source ? { source: input.source } : {}, { now: input.now });
|
|
470
|
+
requestAsyncStop(input.asyncDir, { ...(input.source ? { source: input.source } : {}), ...(input.targetIndex !== undefined ? { targetIndex: input.targetIndex } : {}), ...(input.childId ? { childId: input.childId } : {}) }, { now: input.now });
|
|
565
471
|
}
|
|
566
472
|
|
|
567
473
|
/**
|
|
@@ -575,10 +481,8 @@ export function watchAsyncControlInbox(
|
|
|
575
481
|
opts: {
|
|
576
482
|
onInterrupt: () => void;
|
|
577
483
|
onTimeout?: () => void;
|
|
578
|
-
onStop?: () => void;
|
|
484
|
+
onStop?: (request: StopRequest) => void;
|
|
579
485
|
onSteer?: (request: SteerRequest) => void;
|
|
580
|
-
onSteerCapability?: (capability: SteerCapability) => void;
|
|
581
|
-
onSteerAck?: (ack: SteerAck) => void;
|
|
582
486
|
pollIntervalMs?: number;
|
|
583
487
|
safetyPollIntervalMs?: number;
|
|
584
488
|
platform?: NodeJS.Platform;
|
|
@@ -599,12 +503,10 @@ export function watchAsyncControlInbox(
|
|
|
599
503
|
const check = (): void => {
|
|
600
504
|
if (disposed) return;
|
|
601
505
|
try {
|
|
602
|
-
|
|
506
|
+
for (const stopRequest of consumeStopRequestPayloads(asyncDir, fsImpl)) opts.onStop?.(stopRequest);
|
|
603
507
|
if (consumeTimeoutRequest(asyncDir, fsImpl)) opts.onTimeout?.();
|
|
604
508
|
if (consumeInterruptRequest(asyncDir, fsImpl)) opts.onInterrupt();
|
|
605
509
|
for (const request of consumeSteerRequests(asyncDir, fsImpl)) opts.onSteer?.(request);
|
|
606
|
-
for (const capability of consumeSteerCapabilities(asyncDir, fsImpl)) opts.onSteerCapability?.(capability);
|
|
607
|
-
for (const ack of consumeSteerAcks(asyncDir, fsImpl)) opts.onSteerAck?.(ack);
|
|
608
510
|
} catch {
|
|
609
511
|
// Never let inbox errors crash the runner.
|
|
610
512
|
}
|
|
@@ -630,31 +532,16 @@ export function watchAsyncControlInbox(
|
|
|
630
532
|
const watchDir = (target: string, create = false): void => {
|
|
631
533
|
if (disposed || watchedDirs.has(target)) return;
|
|
632
534
|
if (create) fsImpl.mkdirSync(target, { recursive: true });
|
|
633
|
-
const watcher = fsImpl.watch(resolveWatchPath(target, fsImpl.realpathSync.native), () =>
|
|
634
|
-
watchExistingSteerAckDirs();
|
|
635
|
-
check();
|
|
636
|
-
});
|
|
535
|
+
const watcher = fsImpl.watch(resolveWatchPath(target, fsImpl.realpathSync.native), () => check());
|
|
637
536
|
watcher.on?.("error", startPolling);
|
|
638
537
|
watchers.push(watcher);
|
|
639
538
|
watchedDirs.add(target);
|
|
640
539
|
};
|
|
641
|
-
const watchExistingSteerAckDirs = (): void => {
|
|
642
|
-
const ackRoot = path.join(dir, STEER_ACKS_DIR);
|
|
643
|
-
let entries: string[];
|
|
644
|
-
try {
|
|
645
|
-
entries = fsImpl.readdirSync(ackRoot).filter((name) => /^\d+$/.test(name));
|
|
646
|
-
} catch {
|
|
647
|
-
return;
|
|
648
|
-
}
|
|
649
|
-
for (const entry of entries) watchDir(path.join(ackRoot, entry));
|
|
650
|
-
};
|
|
651
540
|
try {
|
|
652
541
|
if (shouldUseNativeFsWatch("runner-control-inbox", opts.platform)) {
|
|
653
542
|
watchDir(dir);
|
|
543
|
+
watchDir(stopRequestsDir(asyncDir), true);
|
|
654
544
|
watchDir(steerRequestsDir(asyncDir), true);
|
|
655
|
-
watchDir(steerCapabilitiesDir(asyncDir), true);
|
|
656
|
-
watchDir(path.join(dir, STEER_ACKS_DIR), true);
|
|
657
|
-
watchExistingSteerAckDirs();
|
|
658
545
|
startSafetyPolling();
|
|
659
546
|
} else {
|
|
660
547
|
startPolling();
|