@xzzpig/pi-subagents 0.1.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 +1621 -0
- package/LICENSE +21 -0
- package/README.md +118 -0
- package/agents/delegate.md +14 -0
- package/agents/oracle.md +74 -0
- package/agents/researcher.md +52 -0
- package/agents/reviewer.md +79 -0
- package/agents/scout.md +50 -0
- package/agents/worker.md +58 -0
- package/index.ts +1 -0
- package/inspector-runner.mjs +11 -0
- package/install.mjs +93 -0
- package/package.json +105 -0
- package/prompts/gather-context-and-clarify.md +13 -0
- package/prompts/parallel-cleanup.md +59 -0
- package/prompts/parallel-research.md +50 -0
- package/prompts/parallel-review.md +54 -0
- package/prompts/review-loop.md +43 -0
- package/skills/pi-subagents/SKILL.md +41 -0
- package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
- package/skills/pi-subagents/references/execution-controls.md +428 -0
- package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
- package/src/agents/agent-management.ts +1256 -0
- package/src/agents/agent-memory.ts +254 -0
- package/src/agents/agent-refinements.ts +624 -0
- package/src/agents/agent-scope.ts +6 -0
- package/src/agents/agent-selection.ts +25 -0
- package/src/agents/agent-serializer.ts +163 -0
- package/src/agents/agents.ts +1889 -0
- package/src/agents/chain-serializer.ts +280 -0
- package/src/agents/frontmatter.ts +149 -0
- package/src/agents/identity.ts +30 -0
- package/src/agents/proactive-skills.ts +194 -0
- package/src/agents/skills.ts +761 -0
- package/src/api/background-work.ts +197 -0
- package/src/api/capability-ceiling.ts +17 -0
- package/src/api/control-channel.ts +4 -0
- package/src/api/delegation.ts +119 -0
- package/src/api/external-runs.ts +129 -0
- package/src/api/intercom-bridge.ts +3 -0
- package/src/api/pi-args.ts +5 -0
- package/src/api/preflight.ts +403 -0
- package/src/api/shared-types.ts +19 -0
- package/src/extension/config.ts +76 -0
- package/src/extension/control-notices.ts +58 -0
- package/src/extension/doctor.ts +230 -0
- package/src/extension/fanout-child.ts +201 -0
- package/src/extension/index.ts +805 -0
- package/src/extension/public-execution.ts +71 -0
- package/src/extension/rpc.ts +653 -0
- package/src/extension/schemas.ts +375 -0
- package/src/extension/steering-notices.ts +35 -0
- package/src/extension/tool-description.ts +164 -0
- package/src/inspectors/herdr/actions.ts +229 -0
- package/src/inspectors/herdr/client.ts +130 -0
- package/src/inspectors/herdr/inspector-runner.ts +141 -0
- package/src/inspectors/herdr/project-panes.ts +154 -0
- package/src/integrations/herdr-status.ts +330 -0
- package/src/intercom/intercom-bridge.ts +187 -0
- package/src/intercom/native-supervisor-channel.ts +715 -0
- package/src/intercom/result-intercom.ts +421 -0
- package/src/missions/actions.ts +410 -0
- package/src/missions/goal-driver.ts +162 -0
- package/src/missions/lifecycle.ts +346 -0
- package/src/missions/store.ts +507 -0
- package/src/missions/types.ts +157 -0
- package/src/missions/workflow-state.ts +250 -0
- package/src/policy/authority.ts +46 -0
- package/src/profiles/profiles.ts +661 -0
- package/src/runs/background/async-execution.ts +1574 -0
- package/src/runs/background/async-job-tracker.ts +511 -0
- package/src/runs/background/async-resume.ts +539 -0
- package/src/runs/background/async-status.ts +542 -0
- package/src/runs/background/auto-drain.ts +67 -0
- package/src/runs/background/chain-append.ts +328 -0
- package/src/runs/background/chain-root-attachment.ts +199 -0
- package/src/runs/background/completion-batcher.ts +168 -0
- package/src/runs/background/completion-dedupe.ts +54 -0
- package/src/runs/background/control-channel.ts +692 -0
- package/src/runs/background/fleet-view.ts +540 -0
- package/src/runs/background/notify.ts +332 -0
- package/src/runs/background/parallel-groups.ts +45 -0
- package/src/runs/background/process-terminal.ts +280 -0
- package/src/runs/background/result-watcher.ts +414 -0
- package/src/runs/background/retained-children.ts +68 -0
- package/src/runs/background/run-id-resolver.ts +167 -0
- package/src/runs/background/run-status.ts +504 -0
- package/src/runs/background/scheduled-runs.ts +753 -0
- package/src/runs/background/stale-run-reconciler.ts +396 -0
- package/src/runs/background/steering.ts +239 -0
- package/src/runs/background/subagent-runner.ts +4718 -0
- package/src/runs/background/subagent-wait.ts +661 -0
- package/src/runs/background/top-level-async.ts +14 -0
- package/src/runs/background/wait-completions.ts +112 -0
- package/src/runs/background/wait-config.ts +36 -0
- package/src/runs/background/wait-subscriptions.ts +253 -0
- package/src/runs/background/wait-tool.ts +34 -0
- package/src/runs/foreground/async-steering-action.ts +256 -0
- package/src/runs/foreground/async-stop-action.ts +65 -0
- package/src/runs/foreground/chain-clarify.ts +1354 -0
- package/src/runs/foreground/chain-execution.ts +1527 -0
- package/src/runs/foreground/execution.ts +1868 -0
- package/src/runs/foreground/foreground-control.ts +132 -0
- package/src/runs/foreground/subagent-executor.ts +5532 -0
- package/src/runs/shared/acceptance.ts +1365 -0
- package/src/runs/shared/agent-contract.ts +38 -0
- package/src/runs/shared/capability-ceiling.ts +209 -0
- package/src/runs/shared/chain-outputs.ts +118 -0
- package/src/runs/shared/child-protocol.ts +401 -0
- package/src/runs/shared/completion-guard.ts +95 -0
- package/src/runs/shared/context-mode.ts +44 -0
- package/src/runs/shared/dynamic-fanout.ts +297 -0
- package/src/runs/shared/external-cli-runner.ts +130 -0
- package/src/runs/shared/long-running-guard.ts +220 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
- package/src/runs/shared/model-fallback.ts +336 -0
- package/src/runs/shared/model-scope.ts +128 -0
- package/src/runs/shared/nested-events.ts +1076 -0
- package/src/runs/shared/nested-path.ts +52 -0
- package/src/runs/shared/nested-render.ts +123 -0
- package/src/runs/shared/parallel-handoff.ts +238 -0
- package/src/runs/shared/parallel-utils.ts +256 -0
- package/src/runs/shared/permissions.ts +95 -0
- package/src/runs/shared/pi-args.ts +808 -0
- package/src/runs/shared/pi-spawn.ts +163 -0
- package/src/runs/shared/process-signal.ts +19 -0
- package/src/runs/shared/run-history.ts +181 -0
- package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
- package/src/runs/shared/session-lease.ts +299 -0
- package/src/runs/shared/single-output.ts +235 -0
- package/src/runs/shared/spawn-budget.ts +128 -0
- package/src/runs/shared/structured-output.ts +182 -0
- package/src/runs/shared/subagent-control.ts +231 -0
- package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
- package/src/runs/shared/subagent-startup-retry.ts +104 -0
- package/src/runs/shared/task-intent.ts +181 -0
- package/src/runs/shared/tool-availability.ts +83 -0
- package/src/runs/shared/tool-budget.ts +80 -0
- package/src/runs/shared/turn-budget.ts +98 -0
- package/src/runs/shared/usage-budget.ts +65 -0
- package/src/runs/shared/workflow-graph.ts +231 -0
- package/src/runs/shared/worktree.ts +759 -0
- package/src/shared/accessible-dir.ts +47 -0
- package/src/shared/artifacts.ts +285 -0
- package/src/shared/atomic-json.ts +61 -0
- package/src/shared/child-transcript.ts +264 -0
- package/src/shared/file-coalescer.ts +40 -0
- package/src/shared/file-system-retry.ts +47 -0
- package/src/shared/fork-context.ts +213 -0
- package/src/shared/formatters.ts +133 -0
- package/src/shared/jsonl-writer.ts +81 -0
- package/src/shared/launch-contract.ts +124 -0
- package/src/shared/model-info.ts +81 -0
- package/src/shared/post-exit-stdio-guard.ts +85 -0
- package/src/shared/session-identity.ts +10 -0
- package/src/shared/session-tokens.ts +44 -0
- package/src/shared/settings.ts +501 -0
- package/src/shared/status-format.ts +55 -0
- package/src/shared/types.ts +2069 -0
- package/src/shared/utils.ts +613 -0
- package/src/slash/delegation-adapters.ts +434 -0
- package/src/slash/delegation-json.ts +108 -0
- package/src/slash/delegation-request.ts +166 -0
- package/src/slash/prompt-template-bridge.ts +383 -0
- package/src/slash/prompt-workflows.ts +300 -0
- package/src/slash/selector.ts +147 -0
- package/src/slash/slash-bridge.ts +192 -0
- package/src/slash/slash-commands.ts +994 -0
- package/src/slash/slash-live-state.ts +296 -0
- package/src/slash/subagents-admin.ts +432 -0
- package/src/tui/fleet-status.ts +564 -0
- package/src/tui/fleet-transcript.ts +577 -0
- package/src/tui/fleet.ts +879 -0
- package/src/tui/render-helpers.ts +80 -0
- package/src/tui/render.ts +2029 -0
- package/src/types/pi-runtime-compat.d.ts +8 -0
- package/src/watchdog/change-signature.ts +220 -0
- package/src/watchdog/child-status.ts +205 -0
- package/src/watchdog/emission-guard.ts +123 -0
- package/src/watchdog/lsp-diagnostics.ts +537 -0
- package/src/watchdog/model-selection.ts +167 -0
- package/src/watchdog/permission-arbiter.ts +145 -0
- package/src/watchdog/register-child.ts +117 -0
- package/src/watchdog/register-main.ts +440 -0
- package/src/watchdog/render.ts +54 -0
- package/src/watchdog/review.ts +302 -0
- package/src/watchdog/runtime.ts +868 -0
- package/src/watchdog/scope.ts +62 -0
- package/src/watchdog/settings.ts +568 -0
- package/src/watchdog/tool-actions.ts +155 -0
- package/src/watchdog/turn-delta.ts +161 -0
- package/src/watchdog/types.ts +198 -0
- package/src/watchdog/warning-format.ts +73 -0
- package/src/workflows/chat-progress.ts +140 -0
- package/src/workflows/scripted-workflow.ts +506 -0
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { buildCompletionKey, markSeenWithTtl } from "./completion-dedupe.ts";
|
|
4
|
+
import { createFileCoalescer } from "../../shared/file-coalescer.ts";
|
|
5
|
+
import {
|
|
6
|
+
SUBAGENT_ASYNC_COMPLETE_EVENT,
|
|
7
|
+
type IntercomEventBus,
|
|
8
|
+
type NestedRunSummary,
|
|
9
|
+
type ParallelHandoffReference,
|
|
10
|
+
type SubagentResultIntercomChild,
|
|
11
|
+
type SubagentOutputState,
|
|
12
|
+
type SubagentState,
|
|
13
|
+
} from "../../shared/types.ts";
|
|
14
|
+
import {
|
|
15
|
+
attachNestedChildrenToResultChildren,
|
|
16
|
+
buildSubagentResultIntercomPayload,
|
|
17
|
+
compactNestedResultChildren,
|
|
18
|
+
deliverSubagentResultIntercomEvent,
|
|
19
|
+
resolveSubagentResultStatus,
|
|
20
|
+
} from "../../intercom/result-intercom.ts";
|
|
21
|
+
import { projectNestedRegistryForRoot, sanitizeSummary } from "../shared/nested-events.ts";
|
|
22
|
+
import { resolveWatchPath } from "../../shared/utils.ts";
|
|
23
|
+
import { recordWaitCompletion } from "./wait-completions.ts";
|
|
24
|
+
import type { CompletionNotifier, CompletionNotification } from "./notify.ts";
|
|
25
|
+
|
|
26
|
+
const WATCHER_RESTART_DELAY_MS = 3000;
|
|
27
|
+
const POLL_INTERVAL_MS = 3000;
|
|
28
|
+
const RETRY_DELAY_MS = 100;
|
|
29
|
+
|
|
30
|
+
type ResultWatcherFs = Pick<typeof fs, "existsSync" | "readFileSync" | "unlinkSync" | "readdirSync" | "mkdirSync" | "realpathSync" | "watch">;
|
|
31
|
+
|
|
32
|
+
type ResultWatcherTimers = {
|
|
33
|
+
setTimeout: typeof setTimeout;
|
|
34
|
+
clearTimeout: typeof clearTimeout;
|
|
35
|
+
setInterval: typeof setInterval;
|
|
36
|
+
clearInterval: typeof clearInterval;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
type ResultWatcherDeps = {
|
|
40
|
+
fs?: ResultWatcherFs;
|
|
41
|
+
timers?: ResultWatcherTimers;
|
|
42
|
+
notifier?: Pick<CompletionNotifier, "deliver">;
|
|
43
|
+
/** Receives persisted completions before active-session delivery filtering. */
|
|
44
|
+
observeCompletion?: (result: CompletionNotification & { runId: string }) => void;
|
|
45
|
+
/** External grouped-result transport. Disable when native completion notifications own delivery. */
|
|
46
|
+
deliverIntercomResults?: boolean;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
type ResultFileChild = {
|
|
50
|
+
agent?: string;
|
|
51
|
+
output?: string;
|
|
52
|
+
structuredOutput?: unknown;
|
|
53
|
+
outputState?: SubagentOutputState;
|
|
54
|
+
error?: string;
|
|
55
|
+
success?: boolean;
|
|
56
|
+
state?: string;
|
|
57
|
+
interrupted?: boolean;
|
|
58
|
+
timedOut?: boolean;
|
|
59
|
+
stopped?: boolean;
|
|
60
|
+
turnBudgetExceeded?: boolean;
|
|
61
|
+
processSignal?: string | null;
|
|
62
|
+
sessionFile?: string;
|
|
63
|
+
artifactPaths?: { outputPath?: string };
|
|
64
|
+
intercomTarget?: string;
|
|
65
|
+
children?: unknown;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
type ResultFileData = CompletionNotification & {
|
|
69
|
+
runId?: string;
|
|
70
|
+
mode?: string;
|
|
71
|
+
results?: ResultFileChild[];
|
|
72
|
+
nestedChildren?: unknown;
|
|
73
|
+
asyncDir?: string;
|
|
74
|
+
intercomTarget?: string;
|
|
75
|
+
parallelHandoff?: ParallelHandoffReference;
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
function sanitizeNestedResultChildren(value: unknown, resultPath: string, label: string): NestedRunSummary[] | undefined {
|
|
79
|
+
if (value === undefined) return undefined;
|
|
80
|
+
if (!Array.isArray(value)) {
|
|
81
|
+
console.error(`Ignoring invalid nested children in subagent result file '${resultPath}' at ${label}: expected an array.`);
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
const children = value.map((child) => sanitizeSummary(child)).filter((child): child is NestedRunSummary => Boolean(child));
|
|
85
|
+
if (children.length !== value.length) {
|
|
86
|
+
console.error(`Ignoring ${value.length - children.length} invalid nested child record(s) in subagent result file '${resultPath}' at ${label}.`);
|
|
87
|
+
}
|
|
88
|
+
return children.length ? children : undefined;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function errorCode(error: unknown): string | undefined {
|
|
92
|
+
return typeof error === "object" && error !== null && "code" in error ? (error as NodeJS.ErrnoException).code : undefined;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function isNotFound(error: unknown): boolean {
|
|
96
|
+
return errorCode(error) === "ENOENT";
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function shouldPoll(error: unknown): boolean {
|
|
100
|
+
const code = errorCode(error);
|
|
101
|
+
return code === "EMFILE" || code === "ENOSPC";
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Watches persisted async results for the session currently owned by this
|
|
106
|
+
* runtime. `stopResultWatcher()` revokes ownership before closing resources,
|
|
107
|
+
* so old callbacks can never emit or delete after reload/session replacement.
|
|
108
|
+
*/
|
|
109
|
+
export function createResultWatcher(
|
|
110
|
+
pi: { events: IntercomEventBus },
|
|
111
|
+
state: SubagentState,
|
|
112
|
+
resultsDir: string,
|
|
113
|
+
completionTtlMs: number,
|
|
114
|
+
deps: ResultWatcherDeps = {},
|
|
115
|
+
): {
|
|
116
|
+
startResultWatcher: () => void;
|
|
117
|
+
primeExistingResults: (options?: { triggerTurn?: boolean }) => void;
|
|
118
|
+
stopResultWatcher: () => void;
|
|
119
|
+
} {
|
|
120
|
+
const fsApi = deps.fs ?? fs;
|
|
121
|
+
const timers = deps.timers ?? { setTimeout, clearTimeout, setInterval, clearInterval };
|
|
122
|
+
const notifier = deps.notifier ?? { deliver: async () => true };
|
|
123
|
+
const deliverIntercomResults = deps.deliverIntercomResults !== false;
|
|
124
|
+
const pendingTriggerTurn = new Map<string, boolean>();
|
|
125
|
+
const processing = new Set<string>();
|
|
126
|
+
let deliveryActive = true;
|
|
127
|
+
let deliveryEpoch = 0;
|
|
128
|
+
// The sole in-memory ownership lease. It is acquired for one active session
|
|
129
|
+
// and revoked before the watcher, queues, or callbacks are torn down.
|
|
130
|
+
let activeSessionId: string | null = null;
|
|
131
|
+
|
|
132
|
+
const ownsSession = (sessionId: string, epoch: number) => {
|
|
133
|
+
if (!deliveryActive || epoch !== deliveryEpoch) return false;
|
|
134
|
+
if (!activeSessionId && state.currentSessionId) activeSessionId = state.currentSessionId;
|
|
135
|
+
return activeSessionId === sessionId && state.currentSessionId === sessionId;
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const scheduleResult = (file: string, triggerTurn: boolean, delayMs = 0) => {
|
|
139
|
+
const pendingMode = pendingTriggerTurn.get(file);
|
|
140
|
+
pendingTriggerTurn.set(file, pendingMode === false || !triggerTurn ? false : true);
|
|
141
|
+
state.resultFileCoalescer.schedule(file, delayMs);
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const handleResult = async (file: string, triggerTurn: boolean) => {
|
|
145
|
+
const resultPath = path.join(resultsDir, file);
|
|
146
|
+
if (processing.has(file) || !fsApi.existsSync(resultPath)) return;
|
|
147
|
+
processing.add(file);
|
|
148
|
+
try {
|
|
149
|
+
const data = JSON.parse(fsApi.readFileSync(resultPath, "utf-8")) as ResultFileData;
|
|
150
|
+
if (typeof data.sessionId !== "string" || !data.sessionId) return;
|
|
151
|
+
const runId = data.runId ?? data.id ?? file.replace(/\.json$/i, "");
|
|
152
|
+
try {
|
|
153
|
+
deps.observeCompletion?.({ ...data, runId });
|
|
154
|
+
} catch (error) {
|
|
155
|
+
console.error(`Completion observer failed for '${resultPath}':`, error);
|
|
156
|
+
}
|
|
157
|
+
const epoch = deliveryEpoch;
|
|
158
|
+
if (!ownsSession(data.sessionId, epoch)) return;
|
|
159
|
+
// Recorded before dedupe and before the unlink below: the result file is
|
|
160
|
+
// the only durable carrier of the per-run payload, and subagent_wait
|
|
161
|
+
// surfaces this record in details once the file is gone.
|
|
162
|
+
recordWaitCompletion(state, runId, data, Date.now(), completionTtlMs);
|
|
163
|
+
const hasExplicitNestedChildren = data.nestedChildren !== undefined;
|
|
164
|
+
let nestedChildren = compactNestedResultChildren(sanitizeNestedResultChildren(data.nestedChildren, resultPath, "nestedChildren"));
|
|
165
|
+
if (!nestedChildren?.length && !hasExplicitNestedChildren) {
|
|
166
|
+
try {
|
|
167
|
+
nestedChildren = compactNestedResultChildren(projectNestedRegistryForRoot(runId)?.children);
|
|
168
|
+
} catch (error) {
|
|
169
|
+
console.error(`Failed to enrich subagent result file '${resultPath}' with nested registry children; will retry later:`, error);
|
|
170
|
+
scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const completionKey = buildCompletionKey(data, `result:${file}`);
|
|
176
|
+
const lastSeenAt = state.completionSeen.get(completionKey);
|
|
177
|
+
if (lastSeenAt !== undefined && Date.now() - lastSeenAt > completionTtlMs) {
|
|
178
|
+
state.completionSeen.delete(completionKey);
|
|
179
|
+
} else if (lastSeenAt !== undefined) {
|
|
180
|
+
if (!ownsSession(data.sessionId, epoch) || !fsApi.existsSync(resultPath)) return;
|
|
181
|
+
try {
|
|
182
|
+
fsApi.unlinkSync(resultPath);
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (!isNotFound(error)) {
|
|
185
|
+
console.error(`Failed to remove delivered subagent result '${resultPath}'; will retry:`, error);
|
|
186
|
+
scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const hasResultChildren = Array.isArray(data.results) && data.results.length > 0;
|
|
193
|
+
const resultChildren: ResultFileChild[] = hasResultChildren
|
|
194
|
+
? data.results!
|
|
195
|
+
: [{ agent: data.agent ?? undefined, output: data.summary, outputState: "unknown", success: data.success }];
|
|
196
|
+
const normalizedChildren = attachNestedChildrenToResultChildren(runId, resultChildren.map((result = {}, index): SubagentResultIntercomChild => {
|
|
197
|
+
const baseOutput = hasResultChildren ? result.output : result.output ?? data.summary;
|
|
198
|
+
const hasRealOutput = typeof baseOutput === "string" && baseOutput.trim().length > 0;
|
|
199
|
+
const structuredPreview = result.structuredOutput === undefined ? undefined : JSON.stringify(result.structuredOutput, null, 2).slice(0, 4_000);
|
|
200
|
+
const output = hasRealOutput ? baseOutput : structuredPreview ? `Structured output:\n${structuredPreview}` : "(no output)";
|
|
201
|
+
const summary = result.success === false && result.error
|
|
202
|
+
? `${result.error}${hasRealOutput ? `\n\nOutput:\n${baseOutput}` : ""}`
|
|
203
|
+
: output;
|
|
204
|
+
const sessionPath = result.sessionFile ?? (resultChildren.length === 1 ? data.sessionFile : undefined);
|
|
205
|
+
const childNestedChildren = sanitizeNestedResultChildren(result.children, resultPath, `results[${index}].children`);
|
|
206
|
+
const childState = result.state === "paused" || result.state === "stopped"
|
|
207
|
+
? result.state
|
|
208
|
+
: result.stopped === true
|
|
209
|
+
? "stopped"
|
|
210
|
+
: data.state === "paused" || (!hasResultChildren && (data.state === "stopped" || typeof result.success !== "boolean"))
|
|
211
|
+
? data.state
|
|
212
|
+
: undefined;
|
|
213
|
+
return {
|
|
214
|
+
agent: result.agent ?? data.agent ?? `step-${index + 1}`,
|
|
215
|
+
status: resolveSubagentResultStatus({
|
|
216
|
+
success: result.success,
|
|
217
|
+
state: childState,
|
|
218
|
+
interrupted: result.interrupted,
|
|
219
|
+
timedOut: result.timedOut,
|
|
220
|
+
stopped: result.stopped,
|
|
221
|
+
turnBudgetExceeded: result.turnBudgetExceeded,
|
|
222
|
+
processSignal: result.processSignal,
|
|
223
|
+
}),
|
|
224
|
+
outputState: result.outputState === "present" || result.outputState === "absent" || result.outputState === "unknown"
|
|
225
|
+
? result.outputState
|
|
226
|
+
: "unknown",
|
|
227
|
+
summary,
|
|
228
|
+
index,
|
|
229
|
+
artifactPath: result.artifactPaths?.outputPath,
|
|
230
|
+
...(typeof sessionPath === "string" && fsApi.existsSync(sessionPath) ? { sessionPath } : {}),
|
|
231
|
+
...(result.intercomTarget ? { intercomTarget: result.intercomTarget } : {}),
|
|
232
|
+
...(childNestedChildren ? { children: childNestedChildren } : {}),
|
|
233
|
+
};
|
|
234
|
+
}), nestedChildren);
|
|
235
|
+
|
|
236
|
+
const intercomTarget = data.intercomTarget?.trim();
|
|
237
|
+
let intercomDelivered = false;
|
|
238
|
+
if (deliverIntercomResults && intercomTarget && triggerTurn) {
|
|
239
|
+
const mode = data.mode === "single" || data.mode === "parallel" || data.mode === "chain" || data.mode === "workflow"
|
|
240
|
+
? data.mode
|
|
241
|
+
: resultChildren.length > 1 ? "chain" : "single";
|
|
242
|
+
intercomDelivered = await deliverSubagentResultIntercomEvent(pi.events, buildSubagentResultIntercomPayload({
|
|
243
|
+
to: intercomTarget,
|
|
244
|
+
runId,
|
|
245
|
+
mode,
|
|
246
|
+
source: "async",
|
|
247
|
+
children: normalizedChildren,
|
|
248
|
+
asyncId: data.id ?? undefined,
|
|
249
|
+
asyncDir: data.asyncDir,
|
|
250
|
+
...(data.parallelHandoff ? { parallelHandoff: data.parallelHandoff } : {}),
|
|
251
|
+
}));
|
|
252
|
+
if (!ownsSession(data.sessionId, epoch)) return;
|
|
253
|
+
if (!intercomDelivered) console.error(`Subagent async grouped result intercom delivery was not acknowledged for '${resultPath}'.`);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const accepted = await notifier.deliver({
|
|
257
|
+
...data,
|
|
258
|
+
id: data.id ?? runId,
|
|
259
|
+
runId,
|
|
260
|
+
triggerTurn,
|
|
261
|
+
intercomDelivered,
|
|
262
|
+
...(nestedChildren?.length ? { nestedChildren } : {}),
|
|
263
|
+
...(Array.isArray(data.results) ? {
|
|
264
|
+
results: hasResultChildren ? normalizedChildren.map((child, index) => ({
|
|
265
|
+
...data.results![index],
|
|
266
|
+
agent: child.agent,
|
|
267
|
+
status: child.status,
|
|
268
|
+
summary: child.summary,
|
|
269
|
+
index: child.index,
|
|
270
|
+
artifactPath: child.artifactPath,
|
|
271
|
+
sessionPath: child.sessionPath,
|
|
272
|
+
children: child.children,
|
|
273
|
+
})) : [],
|
|
274
|
+
} : {}),
|
|
275
|
+
});
|
|
276
|
+
if (!ownsSession(data.sessionId, epoch)) return;
|
|
277
|
+
if (!accepted) {
|
|
278
|
+
scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
markSeenWithTtl(state.completionSeen, completionKey, Date.now(), completionTtlMs);
|
|
282
|
+
try {
|
|
283
|
+
pi.events.emit(SUBAGENT_ASYNC_COMPLETE_EVENT, {
|
|
284
|
+
...data,
|
|
285
|
+
runId,
|
|
286
|
+
triggerTurn,
|
|
287
|
+
intercomDelivered,
|
|
288
|
+
...(nestedChildren?.length ? { nestedChildren } : {}),
|
|
289
|
+
...(Array.isArray(data.results) ? {
|
|
290
|
+
results: hasResultChildren ? normalizedChildren.map((child, index) => ({
|
|
291
|
+
...data.results![index],
|
|
292
|
+
agent: child.agent,
|
|
293
|
+
status: child.status,
|
|
294
|
+
summary: child.summary,
|
|
295
|
+
index: child.index,
|
|
296
|
+
artifactPath: child.artifactPath,
|
|
297
|
+
sessionPath: child.sessionPath,
|
|
298
|
+
children: child.children,
|
|
299
|
+
})) : [],
|
|
300
|
+
} : {}),
|
|
301
|
+
});
|
|
302
|
+
} catch (error) {
|
|
303
|
+
console.error(`Completion observer failed for '${resultPath}':`, error);
|
|
304
|
+
}
|
|
305
|
+
if (!ownsSession(data.sessionId, epoch) || !fsApi.existsSync(resultPath)) return;
|
|
306
|
+
try {
|
|
307
|
+
fsApi.unlinkSync(resultPath);
|
|
308
|
+
} catch (error) {
|
|
309
|
+
if (!isNotFound(error)) {
|
|
310
|
+
console.error(`Failed to remove delivered subagent result '${resultPath}'; will retry:`, error);
|
|
311
|
+
scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
} catch (error) {
|
|
315
|
+
if (!isNotFound(error)) console.error(`Failed to process subagent result file '${resultPath}':`, error);
|
|
316
|
+
} finally {
|
|
317
|
+
processing.delete(file);
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
state.resultFileCoalescer = createFileCoalescer((file) => {
|
|
322
|
+
const triggerTurn = pendingTriggerTurn.get(file) !== false;
|
|
323
|
+
pendingTriggerTurn.delete(file);
|
|
324
|
+
void handleResult(file, triggerTurn);
|
|
325
|
+
}, 50);
|
|
326
|
+
|
|
327
|
+
const primeExistingResults = (options: { triggerTurn?: boolean } = {}) => {
|
|
328
|
+
try {
|
|
329
|
+
const triggerTurn = options.triggerTurn !== false;
|
|
330
|
+
fsApi.readdirSync(resultsDir)
|
|
331
|
+
.filter((f) => f.endsWith(".json"))
|
|
332
|
+
.forEach((file) => scheduleResult(file, triggerTurn));
|
|
333
|
+
} catch (error) {
|
|
334
|
+
if (!isNotFound(error)) console.error(`Failed to scan subagent result directory '${resultsDir}':`, error);
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
const startPolling = (reason: unknown) => {
|
|
339
|
+
state.watcher?.close();
|
|
340
|
+
state.watcher = null;
|
|
341
|
+
if (state.watcherRestartTimer) return;
|
|
342
|
+
console.error(`Subagent result watcher for '${resultsDir}' fell back to polling because native fs.watch is unavailable (${errorCode(reason) ?? "unknown error"}).`);
|
|
343
|
+
primeExistingResults();
|
|
344
|
+
state.watcherRestartTimer = timers.setInterval(primeExistingResults, POLL_INTERVAL_MS);
|
|
345
|
+
state.watcherRestartTimer.unref?.();
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
const scheduleRestart = () => {
|
|
349
|
+
if (state.watcherRestartTimer) return;
|
|
350
|
+
state.watcherRestartTimer = timers.setTimeout(() => {
|
|
351
|
+
state.watcherRestartTimer = null;
|
|
352
|
+
try {
|
|
353
|
+
fsApi.mkdirSync(resultsDir, { recursive: true });
|
|
354
|
+
startResultWatcher();
|
|
355
|
+
} catch (error) {
|
|
356
|
+
if (shouldPoll(error)) return startPolling(error);
|
|
357
|
+
console.error(`Failed to restart subagent result watcher for '${resultsDir}':`, error);
|
|
358
|
+
scheduleRestart();
|
|
359
|
+
}
|
|
360
|
+
}, WATCHER_RESTART_DELAY_MS);
|
|
361
|
+
state.watcherRestartTimer.unref?.();
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
const startResultWatcher = () => {
|
|
365
|
+
if (state.watcher) return;
|
|
366
|
+
activeSessionId = state.currentSessionId;
|
|
367
|
+
deliveryActive = true;
|
|
368
|
+
deliveryEpoch += 1;
|
|
369
|
+
if (state.watcherRestartTimer) {
|
|
370
|
+
timers.clearTimeout(state.watcherRestartTimer);
|
|
371
|
+
timers.clearInterval(state.watcherRestartTimer);
|
|
372
|
+
state.watcherRestartTimer = null;
|
|
373
|
+
}
|
|
374
|
+
try {
|
|
375
|
+
const watchDir = resolveWatchPath(resultsDir, fsApi.realpathSync.native);
|
|
376
|
+
state.watcher = fsApi.watch(watchDir, (event, file) => {
|
|
377
|
+
if (event !== "rename" || !file) return;
|
|
378
|
+
const fileName = file.toString();
|
|
379
|
+
if (fileName.endsWith(".json")) scheduleResult(fileName, true);
|
|
380
|
+
});
|
|
381
|
+
state.watcher.on("error", (error) => {
|
|
382
|
+
if (shouldPoll(error)) return startPolling(error);
|
|
383
|
+
console.error(`Subagent result watcher failed for '${resultsDir}':`, error);
|
|
384
|
+
state.watcher?.close();
|
|
385
|
+
state.watcher = null;
|
|
386
|
+
scheduleRestart();
|
|
387
|
+
});
|
|
388
|
+
state.watcher.unref?.();
|
|
389
|
+
} catch (error) {
|
|
390
|
+
if (shouldPoll(error)) return startPolling(error);
|
|
391
|
+
console.error(`Failed to start subagent result watcher for '${resultsDir}':`, error);
|
|
392
|
+
state.watcher = null;
|
|
393
|
+
scheduleRestart();
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
const stopResultWatcher = () => {
|
|
398
|
+
deliveryActive = false;
|
|
399
|
+
activeSessionId = null;
|
|
400
|
+
deliveryEpoch += 1;
|
|
401
|
+
state.watcher?.close();
|
|
402
|
+
state.watcher = null;
|
|
403
|
+
if (state.watcherRestartTimer) {
|
|
404
|
+
timers.clearTimeout(state.watcherRestartTimer);
|
|
405
|
+
timers.clearInterval(state.watcherRestartTimer);
|
|
406
|
+
}
|
|
407
|
+
state.watcherRestartTimer = null;
|
|
408
|
+
state.resultFileCoalescer.clear();
|
|
409
|
+
pendingTriggerTurn.clear();
|
|
410
|
+
processing.clear();
|
|
411
|
+
};
|
|
412
|
+
|
|
413
|
+
return { startResultWatcher, primeExistingResults, stopResultWatcher };
|
|
414
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import { listAsyncRuns } from "./async-status.ts";
|
|
3
|
+
import type { TokenUsage } from "../../shared/types.ts";
|
|
4
|
+
|
|
5
|
+
const MAX_RETAINED_CHILDREN = 10;
|
|
6
|
+
const MAX_TASK_SUMMARY_LENGTH = 120;
|
|
7
|
+
|
|
8
|
+
export interface RetainedChild {
|
|
9
|
+
runId: string;
|
|
10
|
+
parentRunId?: string;
|
|
11
|
+
agent: string;
|
|
12
|
+
taskSummary: string;
|
|
13
|
+
completedAt: number;
|
|
14
|
+
sessionPath: string;
|
|
15
|
+
tokenTotals?: TokenUsage;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function retainedSessionFile(sessionFile: string | undefined): sessionFile is string {
|
|
19
|
+
if (!sessionFile?.endsWith(".jsonl")) return false;
|
|
20
|
+
try {
|
|
21
|
+
const stat = fs.lstatSync(sessionFile);
|
|
22
|
+
return stat.isFile() && !stat.isSymbolicLink();
|
|
23
|
+
} catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function boundedTaskSummary(value: string | undefined): string {
|
|
29
|
+
const normalized = value?.replace(/\s+/g, " ").trim() ?? "";
|
|
30
|
+
return normalized.length > MAX_TASK_SUMMARY_LENGTH
|
|
31
|
+
? `${normalized.slice(0, MAX_TASK_SUMMARY_LENGTH - 1)}…`
|
|
32
|
+
: normalized;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function listRetainedChildren(asyncDirRoot: string, sessionId: string): RetainedChild[] {
|
|
36
|
+
return listAsyncRuns(asyncDirRoot, { sessionId, states: ["complete"], reconcile: false })
|
|
37
|
+
.flatMap((run) => {
|
|
38
|
+
if (!run.parentWorkflowRunId || run.steps.length !== 1) return [];
|
|
39
|
+
const step = run.steps[0]!;
|
|
40
|
+
if ((step.status !== "complete" && step.status !== "completed") || !retainedSessionFile(step.sessionFile ?? run.sessionFile)) return [];
|
|
41
|
+
const completedAt = run.endedAt;
|
|
42
|
+
if (completedAt === undefined) return [];
|
|
43
|
+
return [{
|
|
44
|
+
runId: run.id,
|
|
45
|
+
...(run.parentWorkflowRunId ? { parentRunId: run.parentWorkflowRunId } : {}),
|
|
46
|
+
agent: step.agent,
|
|
47
|
+
taskSummary: boundedTaskSummary(step.description),
|
|
48
|
+
completedAt,
|
|
49
|
+
sessionPath: step.sessionFile ?? run.sessionFile!,
|
|
50
|
+
...(step.tokens ?? run.totalTokens ? { tokenTotals: step.tokens ?? run.totalTokens } : {}),
|
|
51
|
+
}];
|
|
52
|
+
})
|
|
53
|
+
.sort((left, right) => right.completedAt - left.completedAt)
|
|
54
|
+
.slice(0, MAX_RETAINED_CHILDREN);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function formatRetainedChildren(children: RetainedChild[]): string {
|
|
58
|
+
if (children.length === 0) return "No completed retained children in the active parent session.";
|
|
59
|
+
return [
|
|
60
|
+
`Completed retained children (newest first, last ${MAX_RETAINED_CHILDREN}):`,
|
|
61
|
+
...children.flatMap((child) => [
|
|
62
|
+
`- ${child.runId} | ${child.agent} | ${new Date(child.completedAt).toISOString()}`,
|
|
63
|
+
` task: ${child.taskSummary || "(no task summary)"}`,
|
|
64
|
+
` session: ${child.sessionPath}`,
|
|
65
|
+
...(child.tokenTotals ? [` tokens: input ${child.tokenTotals.input}, output ${child.tokenTotals.output}, total ${child.tokenTotals.total}`] : []),
|
|
66
|
+
]),
|
|
67
|
+
].join("\n");
|
|
68
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { DIRS, type SubagentState } from "../../shared/types.ts";
|
|
4
|
+
import { readStatus } from "../../shared/utils.ts";
|
|
5
|
+
import { findAsyncRunPrefixMatches, type AsyncRunLocation } from "./async-resume.ts";
|
|
6
|
+
import { assertSafeNestedId, findNestedRunMatchesById, type NestedRoute, type NestedRunMatch, type NestedRunResolutionScope } from "../shared/nested-events.ts";
|
|
7
|
+
|
|
8
|
+
export type ResolvedSubagentRunId =
|
|
9
|
+
| { kind: "foreground"; id: string }
|
|
10
|
+
| { kind: "async"; id: string; location: AsyncRunLocation }
|
|
11
|
+
| { kind: "nested"; id: string; match: NestedRunMatch };
|
|
12
|
+
|
|
13
|
+
export interface ResolveSubagentRunIdDeps {
|
|
14
|
+
state?: SubagentState;
|
|
15
|
+
asyncDirRoot?: string;
|
|
16
|
+
resultsDir?: string;
|
|
17
|
+
nested?: NestedRunResolutionScope;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function exactAsyncLocation(id: string, asyncDirRoot: string, resultsDir: string): AsyncRunLocation | undefined {
|
|
21
|
+
const asyncDir = path.join(asyncDirRoot, id);
|
|
22
|
+
const resultPath = path.join(resultsDir, `${id}.json`);
|
|
23
|
+
if (!fs.existsSync(asyncDir) && !fs.existsSync(resultPath)) return undefined;
|
|
24
|
+
return {
|
|
25
|
+
asyncDir: fs.existsSync(asyncDir) ? asyncDir : null,
|
|
26
|
+
resultPath: fs.existsSync(resultPath) ? resultPath : null,
|
|
27
|
+
resolvedId: id,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
type AsyncRunMatch = { id: string; location: AsyncRunLocation };
|
|
32
|
+
|
|
33
|
+
type WorkflowResultIdentity = {
|
|
34
|
+
id?: string;
|
|
35
|
+
runId?: string;
|
|
36
|
+
toolCallId?: string;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
function readWorkflowResultIdentity(resultPath: string): WorkflowResultIdentity | undefined {
|
|
40
|
+
let parsed: unknown;
|
|
41
|
+
try {
|
|
42
|
+
parsed = JSON.parse(fs.readFileSync(resultPath, "utf-8")) as unknown;
|
|
43
|
+
} catch {
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
|
|
47
|
+
const record = parsed as Record<string, unknown>;
|
|
48
|
+
return {
|
|
49
|
+
...(typeof record.id === "string" ? { id: record.id } : {}),
|
|
50
|
+
...(typeof record.runId === "string" ? { runId: record.runId } : {}),
|
|
51
|
+
...(typeof record.toolCallId === "string" ? { toolCallId: record.toolCallId } : {}),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function directoryEntries(root: string): string[] {
|
|
56
|
+
try {
|
|
57
|
+
return fs.readdirSync(root);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function resultPathFor(resultsDir: string, runId: string): string | null {
|
|
65
|
+
const resultPath = path.join(resultsDir, `${runId}.json`);
|
|
66
|
+
return fs.existsSync(resultPath) ? resultPath : null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function toolCallIdMatches(value: string | undefined, query: string, options: { prefix?: boolean }): boolean {
|
|
70
|
+
if (value === undefined) return false;
|
|
71
|
+
return options.prefix === true ? value.startsWith(query) : value === query;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function toolCallIdAsyncLocations(toolCallId: string, asyncDirRoot: string, resultsDir: string, options: { prefix?: boolean } = {}): AsyncRunMatch[] {
|
|
75
|
+
const byId = new Map<string, AsyncRunLocation>();
|
|
76
|
+
for (const entry of directoryEntries(asyncDirRoot)) {
|
|
77
|
+
const asyncDir = path.join(asyncDirRoot, entry);
|
|
78
|
+
const status = readStatus(asyncDir);
|
|
79
|
+
if (!status || !toolCallIdMatches(status.toolCallId, toolCallId, options)) continue;
|
|
80
|
+
const runId = status.runId || entry;
|
|
81
|
+
byId.set(runId, { asyncDir, resultPath: resultPathFor(resultsDir, runId), resolvedId: runId });
|
|
82
|
+
}
|
|
83
|
+
for (const entry of directoryEntries(resultsDir)) {
|
|
84
|
+
if (!entry.endsWith(".json")) continue;
|
|
85
|
+
const resultPath = path.join(resultsDir, entry);
|
|
86
|
+
const identity = readWorkflowResultIdentity(resultPath);
|
|
87
|
+
if (!identity || !toolCallIdMatches(identity.toolCallId, toolCallId, options)) continue;
|
|
88
|
+
const runId = identity.runId ?? identity.id ?? entry.slice(0, -".json".length);
|
|
89
|
+
const asyncDir = path.join(asyncDirRoot, runId);
|
|
90
|
+
byId.set(runId, { asyncDir: fs.existsSync(asyncDir) ? asyncDir : null, resultPath, resolvedId: runId });
|
|
91
|
+
}
|
|
92
|
+
return [...byId.entries()].map(([id, location]) => ({ id, location }));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function foregroundIds(state: SubagentState | undefined): string[] {
|
|
96
|
+
if (!state) return [];
|
|
97
|
+
const remembered = state.currentSessionId
|
|
98
|
+
? [...(state.foregroundRuns?.values() ?? [])]
|
|
99
|
+
.filter((run) => run.sessionId === state.currentSessionId)
|
|
100
|
+
.map((run) => run.runId)
|
|
101
|
+
: [];
|
|
102
|
+
return [...new Set([...state.foregroundControls.keys(), ...remembered])];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function hasExactForegroundId(state: SubagentState | undefined, id: string): boolean {
|
|
106
|
+
if (!state) return false;
|
|
107
|
+
if (state.foregroundControls.has(id)) return true;
|
|
108
|
+
const remembered = state.foregroundRuns?.get(id);
|
|
109
|
+
return Boolean(remembered && state.currentSessionId && remembered.sessionId === state.currentSessionId);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function nestedScopeFromState(state: SubagentState | undefined): NestedRunResolutionScope | undefined {
|
|
113
|
+
if (!state) return undefined;
|
|
114
|
+
const routes: NestedRoute[] = [];
|
|
115
|
+
const seen = new Set<string>();
|
|
116
|
+
const add = (route: NestedRoute | undefined) => {
|
|
117
|
+
if (!route) return;
|
|
118
|
+
const key = `${route.rootRunId}:${route.eventSink}:${route.controlInbox}`;
|
|
119
|
+
if (seen.has(key)) return;
|
|
120
|
+
seen.add(key);
|
|
121
|
+
routes.push(route);
|
|
122
|
+
};
|
|
123
|
+
for (const control of state.foregroundControls.values()) add(control.nestedRoute as NestedRoute | undefined);
|
|
124
|
+
for (const job of state.asyncJobs.values()) add(job.nestedRoute as NestedRoute | undefined);
|
|
125
|
+
return { routes };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function asyncPrefixMatches(prefix: string, asyncDirRoot: string, resultsDir: string): Array<{ id: string; location: AsyncRunLocation }> {
|
|
129
|
+
return findAsyncRunPrefixMatches(prefix, asyncDirRoot, resultsDir);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function resolveSubagentRunId(id: string, deps: ResolveSubagentRunIdDeps = {}): ResolvedSubagentRunId | undefined {
|
|
133
|
+
assertSafeNestedId("id", id);
|
|
134
|
+
const asyncDirRoot = deps.asyncDirRoot ?? DIRS.async;
|
|
135
|
+
const resultsDir = deps.resultsDir ?? DIRS.results;
|
|
136
|
+
|
|
137
|
+
const nestedScope = deps.nested ?? nestedScopeFromState(deps.state);
|
|
138
|
+
if (hasExactForegroundId(deps.state, id)) return { kind: "foreground", id };
|
|
139
|
+
const exactAsync = exactAsyncLocation(id, asyncDirRoot, resultsDir);
|
|
140
|
+
if (exactAsync) return { kind: "async", id, location: exactAsync };
|
|
141
|
+
const exactToolCallIdMatches = toolCallIdAsyncLocations(id, asyncDirRoot, resultsDir);
|
|
142
|
+
if (exactToolCallIdMatches.length > 1) throw new Error(`Subagent tool-call id '${id}' is ambiguous across async runs. Use the returned asyncId instead.`);
|
|
143
|
+
if (exactToolCallIdMatches[0]) return { kind: "async", id: exactToolCallIdMatches[0].id, location: exactToolCallIdMatches[0].location };
|
|
144
|
+
const exactNested = findNestedRunMatchesById(id, nestedScope ? { scope: nestedScope } : {});
|
|
145
|
+
if (exactNested.length > 1) throw new Error(`Nested run id '${id}' is ambiguous across authorized registries. Provide the full id after stale registries are cleaned up.`);
|
|
146
|
+
if (exactNested[0]) return { kind: "nested", id, match: exactNested[0] };
|
|
147
|
+
|
|
148
|
+
const matches: ResolvedSubagentRunId[] = [];
|
|
149
|
+
for (const foregroundId of foregroundIds(deps.state).filter((candidate) => candidate.startsWith(id))) {
|
|
150
|
+
matches.push({ kind: "foreground", id: foregroundId });
|
|
151
|
+
}
|
|
152
|
+
for (const match of asyncPrefixMatches(id, asyncDirRoot, resultsDir)) {
|
|
153
|
+
matches.push({ kind: "async", id: match.id, location: match.location });
|
|
154
|
+
}
|
|
155
|
+
for (const match of toolCallIdAsyncLocations(id, asyncDirRoot, resultsDir, { prefix: true })) {
|
|
156
|
+
matches.push({ kind: "async", id: match.id, location: match.location });
|
|
157
|
+
}
|
|
158
|
+
for (const match of findNestedRunMatchesById(id, nestedScope ? { prefix: true, scope: nestedScope } : { prefix: true })) {
|
|
159
|
+
matches.push({ kind: "nested", id: match.run.id, match });
|
|
160
|
+
}
|
|
161
|
+
const unique = new Map(matches.map((match) => [`${match.kind}:${match.id}`, match]));
|
|
162
|
+
const values = [...unique.values()];
|
|
163
|
+
if (values.length > 1) {
|
|
164
|
+
throw new Error(`Ambiguous subagent run id prefix '${id}' matched: ${values.map((match) => `${match.kind}:${match.id}`).join(", ")}. Provide a longer id.`);
|
|
165
|
+
}
|
|
166
|
+
return values[0];
|
|
167
|
+
}
|