@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,504 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
4
|
+
import { formatAsyncRunList, formatAsyncRunOutputPath, formatAsyncRunProgressLabel, listAsyncRuns } from "./async-status.ts";
|
|
5
|
+
import { formatAsyncResultTranscript, formatAsyncRunTranscript, formatNestedRunTranscript, inspectSubagentFleet } from "./fleet-view.ts";
|
|
6
|
+
import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
|
|
7
|
+
import { formatModelThinking } from "../../shared/formatters.ts";
|
|
8
|
+
import { formatActivityLabel } from "../../shared/status-format.ts";
|
|
9
|
+
import { DIRS, type AsyncStatus, type Details, type ForegroundResumeRun, type NestedRunSummary, type SteeringStatus, type SubagentState } from "../../shared/types.ts";
|
|
10
|
+
import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.ts";
|
|
11
|
+
import { resolveSubagentResultStatus } from "../../intercom/result-intercom.ts";
|
|
12
|
+
import { readProcessTerminal, sanitizeProcessTerminal } from "./process-terminal.ts";
|
|
13
|
+
import { formatWaitSubscriptions } from "./wait-subscriptions.ts";
|
|
14
|
+
import { resolveAsyncRunLocation } from "./async-resume.ts";
|
|
15
|
+
import { resolveSubagentRunId } from "./run-id-resolver.ts";
|
|
16
|
+
import { flatToLogicalStepIndex, normalizeParallelGroups } from "./parallel-groups.ts";
|
|
17
|
+
import { reconcileAsyncRun, reconcileNestedAsyncDescendants } from "./stale-run-reconciler.ts";
|
|
18
|
+
import { attachRootChildrenToSteps, findNestedRouteForRootId, projectNestedRegistryForRoot, type NestedRunResolutionScope } from "../shared/nested-events.ts";
|
|
19
|
+
import { readMissionBinding } from "../../missions/lifecycle.ts";
|
|
20
|
+
import { formatWorkflowJsonPreview } from "../../workflows/scripted-workflow.ts";
|
|
21
|
+
|
|
22
|
+
interface RunStatusParams {
|
|
23
|
+
action?: string;
|
|
24
|
+
id?: string;
|
|
25
|
+
runId?: string;
|
|
26
|
+
dir?: string;
|
|
27
|
+
index?: number;
|
|
28
|
+
view?: "fleet" | "transcript";
|
|
29
|
+
lines?: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface RunStatusDeps {
|
|
33
|
+
asyncDirRoot?: string;
|
|
34
|
+
resultsDir?: string;
|
|
35
|
+
kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
|
|
36
|
+
now?: () => number;
|
|
37
|
+
state?: SubagentState;
|
|
38
|
+
nested?: NestedRunResolutionScope;
|
|
39
|
+
sessionRoots?: string[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function hasExistingSessionFile(value: unknown): value is string {
|
|
43
|
+
return typeof value === "string" && fs.existsSync(value);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function formatCheckpointGuidance(runId: string | undefined, checkpoint: AsyncStatus["checkpoint"] | undefined): string | undefined {
|
|
47
|
+
if (!runId || !checkpoint || checkpoint.status !== "pending") return undefined;
|
|
48
|
+
return `Checkpoint: ${checkpoint.name}${checkpoint.message ? ` — ${checkpoint.message}` : ""}\nApprove: subagent({ action: "approve-checkpoint", id: "${runId}" })\nReject: subagent({ action: "reject-checkpoint", id: "${runId}" })`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function formatResumeGuidance(runId: string | undefined, children: Array<{ agent?: unknown; sessionFile?: unknown }>, fallbackSessionFile?: unknown, options: { stopped?: boolean } = {}): string {
|
|
52
|
+
if (options.stopped) return "Resume: unavailable; stopped runs are not resumable. Start a new run instead.";
|
|
53
|
+
const knownChildren = children
|
|
54
|
+
.map((child, index) => ({ child, index }))
|
|
55
|
+
.filter(({ child }) => typeof child.agent === "string");
|
|
56
|
+
if (!runId || knownChildren.length === 0) return "Resume: unavailable; no child session file was persisted.";
|
|
57
|
+
const singleSessionFile = knownChildren[0]?.child.sessionFile ?? fallbackSessionFile;
|
|
58
|
+
if (children.length === 1 && knownChildren.length === 1 && hasExistingSessionFile(singleSessionFile)) {
|
|
59
|
+
return `Revive: subagent({ action: "resume", id: "${runId}", message: "..." })`;
|
|
60
|
+
}
|
|
61
|
+
const childWithSession = knownChildren.find(({ child }) => hasExistingSessionFile(child.sessionFile));
|
|
62
|
+
if (childWithSession) {
|
|
63
|
+
return `Revive child: subagent({ action: "resume", id: "${runId}", index: ${childWithSession.index}, message: "..." })`;
|
|
64
|
+
}
|
|
65
|
+
return "Resume: unavailable; no child session file was persisted.";
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function stepLineLabel(status: AsyncStatus, index: number): string {
|
|
69
|
+
const steps = status.steps ?? [];
|
|
70
|
+
if (status.mode === "parallel") return `Agent ${index + 1}/${steps.length || 1}`;
|
|
71
|
+
if (status.mode === "workflow") return `Workflow child ${steps[index]?.workflowKey ?? index + 1}`;
|
|
72
|
+
if (status.mode === "chain") {
|
|
73
|
+
const chainStepCount = status.chainStepCount ?? (steps.length || 1);
|
|
74
|
+
const groups = normalizeParallelGroups(status.parallelGroups, steps.length, chainStepCount);
|
|
75
|
+
const group = groups.find((candidate) => index >= candidate.start && index < candidate.start + candidate.count);
|
|
76
|
+
if (group) return `Step ${group.stepIndex + 1}/${chainStepCount} Agent ${index - group.start + 1}/${group.count}`;
|
|
77
|
+
return `Step ${flatToLogicalStepIndex(index, chainStepCount, groups) + 1}/${chainStepCount}`;
|
|
78
|
+
}
|
|
79
|
+
return `Step ${index + 1}`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function nestedRunDisplayName(run: NestedRunSummary): string {
|
|
83
|
+
if (run.agent) return run.agent;
|
|
84
|
+
if (run.agents?.length) return run.agents.join(", ");
|
|
85
|
+
return run.id;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function formatSteeringSummary(input: { steering?: SteeringStatus }): string | undefined {
|
|
89
|
+
const steering = input.steering;
|
|
90
|
+
if (!steering || steering.requested === 0) return undefined;
|
|
91
|
+
const lateAcknowledgments = steering.recent.reduce((count, request) => count + request.targets.filter((target) => target.lateDeliveredAt !== undefined).length, 0);
|
|
92
|
+
return `${steering.requested} requested, ${steering.scheduled} scheduled, ${steering.pending} pending, ${steering.delivered} delivered, ${steering.failed} failed, ${steering.recovered} recovered${lateAcknowledgments ? `, ${lateAcknowledgments} late acknowledged` : ""}`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function rememberedForegroundChildOutput(child: ForegroundResumeRun["children"][number]): string {
|
|
96
|
+
const outputPath = child.artifactPaths?.outputPath ?? child.savedOutputPath;
|
|
97
|
+
if (outputPath && fs.existsSync(outputPath)) {
|
|
98
|
+
try {
|
|
99
|
+
const artifactOutput = fs.readFileSync(outputPath, "utf-8").trim();
|
|
100
|
+
if (artifactOutput) return artifactOutput;
|
|
101
|
+
} catch {
|
|
102
|
+
// Fall back to the remembered snapshot below.
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return child.finalOutput ?? "";
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function formatRememberedForegroundStatus(run: ForegroundResumeRun): string {
|
|
109
|
+
const lines = [
|
|
110
|
+
`Run: ${run.runId}`,
|
|
111
|
+
"State: remembered foreground",
|
|
112
|
+
`Mode: ${run.mode}`,
|
|
113
|
+
`Updated: ${new Date(run.updatedAt).toISOString()}`,
|
|
114
|
+
`Cwd: ${run.cwd}`,
|
|
115
|
+
];
|
|
116
|
+
for (const child of run.children) {
|
|
117
|
+
const output = rememberedForegroundChildOutput(child).trim().split(/\r?\n/).find((line) => line.trim());
|
|
118
|
+
const parts = [
|
|
119
|
+
`${child.index + 1}. ${child.agent} ${child.status}`,
|
|
120
|
+
child.exitCode !== undefined ? `exit ${child.exitCode}` : undefined,
|
|
121
|
+
child.detachedReason ? `detached: ${child.detachedReason}` : undefined,
|
|
122
|
+
child.acceptance ? `acceptance: ${child.acceptance.status}` : undefined,
|
|
123
|
+
child.error ? `error: ${child.error}` : undefined,
|
|
124
|
+
output ? `output: ${output.slice(0, 160)}` : undefined,
|
|
125
|
+
].filter(Boolean);
|
|
126
|
+
lines.push(parts.join(", "));
|
|
127
|
+
if (child.sessionFile) lines.push(` Session: ${child.sessionFile}`);
|
|
128
|
+
if (child.transcriptPath) lines.push(` Transcript: ${child.transcriptPath}`);
|
|
129
|
+
if (child.artifactPaths?.outputPath) lines.push(` Output: ${child.artifactPaths.outputPath}`);
|
|
130
|
+
if (child.savedOutputPath && child.savedOutputPath !== child.artifactPaths?.outputPath) lines.push(` Saved output: ${child.savedOutputPath}`);
|
|
131
|
+
if (child.outputSaveError) lines.push(` Output warning: ${child.outputSaveError}`);
|
|
132
|
+
if (child.transcriptError) lines.push(` Transcript warning: ${child.transcriptError}`);
|
|
133
|
+
}
|
|
134
|
+
lines.push("", `Status: subagent({ action: "status", id: "${run.runId}" })`);
|
|
135
|
+
if (run.children.length === 1) lines.push(`Transcript: subagent({ action: "status", id: "${run.runId}", view: "transcript" })`);
|
|
136
|
+
else lines.push(`Transcript: subagent({ action: "status", id: "${run.runId}", index: 0, view: "transcript" })`);
|
|
137
|
+
const detached = run.children.some((child) => child.status === "detached");
|
|
138
|
+
const resumable = run.children.find((child) => hasExistingSessionFile(child.sessionFile));
|
|
139
|
+
if (run.checkpoint?.status === "pending") {
|
|
140
|
+
lines.push(`Checkpoint: ${run.checkpoint.name}${run.checkpoint.message ? ` — ${run.checkpoint.message}` : ""}`);
|
|
141
|
+
lines.push(`Approve: subagent({ action: "approve-checkpoint", id: "${run.runId}" })`);
|
|
142
|
+
lines.push(`Reject: subagent({ action: "reject-checkpoint", id: "${run.runId}" })`);
|
|
143
|
+
return lines.join("\n");
|
|
144
|
+
}
|
|
145
|
+
if (detached) {
|
|
146
|
+
lines.push(`Recovery: reply to the supervisor request first, then wait with subagent_wait({ id: "${run.runId}" }); do not resume or launch a replacement while any child remains detached.`);
|
|
147
|
+
} else if (resumable) {
|
|
148
|
+
lines.push(run.children.length === 1
|
|
149
|
+
? `Revive: subagent({ action: "resume", id: "${run.runId}", message: "..." })`
|
|
150
|
+
: `Revive child: subagent({ action: "resume", id: "${run.runId}", index: ${resumable.index}, message: "..." })`);
|
|
151
|
+
} else {
|
|
152
|
+
lines.push("Resume: unavailable; no child session file was persisted.");
|
|
153
|
+
}
|
|
154
|
+
return lines.join("\n");
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function formatRememberedForegroundTranscript(run: ForegroundResumeRun, options: { index?: number; lines?: number }): string {
|
|
158
|
+
let index = options.index;
|
|
159
|
+
if (index !== undefined && !Number.isInteger(index)) throw new Error("Transcript index must be an integer.");
|
|
160
|
+
if (index === undefined && run.children.length === 1) index = 0;
|
|
161
|
+
if (index === undefined) return `Transcript view requires index for foreground run '${run.runId}' with ${run.children.length} children.`;
|
|
162
|
+
if (index < 0 || index >= run.children.length) throw new Error(`Transcript index ${index} is out of range for ${run.children.length} foreground children.`);
|
|
163
|
+
const child = run.children[index]!;
|
|
164
|
+
const lineLimit = Math.max(1, Math.min(options.lines ?? 80, 1000));
|
|
165
|
+
const outputLines = rememberedForegroundChildOutput(child).split(/\r?\n/).filter((line) => line.trim()).slice(-lineLimit);
|
|
166
|
+
const lines = [
|
|
167
|
+
`Run: ${run.runId}`,
|
|
168
|
+
`State: ${child.status}`,
|
|
169
|
+
`Child: ${index} (${child.agent})`,
|
|
170
|
+
child.sessionFile ? `Session: ${child.sessionFile}` : undefined,
|
|
171
|
+
child.transcriptPath ? `Transcript: ${child.transcriptPath}` : undefined,
|
|
172
|
+
child.artifactPaths?.outputPath ? `Output: ${child.artifactPaths.outputPath}` : undefined,
|
|
173
|
+
child.savedOutputPath && child.savedOutputPath !== child.artifactPaths?.outputPath ? `Saved output: ${child.savedOutputPath}` : undefined,
|
|
174
|
+
child.outputSaveError ? `Output warning: ${child.outputSaveError}` : undefined,
|
|
175
|
+
].filter((line): line is string => Boolean(line));
|
|
176
|
+
lines.push("Result transcript tail:");
|
|
177
|
+
if (outputLines.length === 0) lines.push(" (no recovered final output available yet)");
|
|
178
|
+
else for (const line of outputLines) lines.push(` ${line}`);
|
|
179
|
+
return lines.join("\n");
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function formatNestedExactStatus(rootRunId: string, run: NestedRunSummary): string {
|
|
183
|
+
const lines = [
|
|
184
|
+
`Nested run: ${run.id}`,
|
|
185
|
+
`Root: ${rootRunId}`,
|
|
186
|
+
`Parent: ${run.parentRunId}${run.parentStepIndex !== undefined ? ` step ${run.parentStepIndex + 1}` : ""}`,
|
|
187
|
+
`State: ${run.state}`,
|
|
188
|
+
run.activityState || run.lastActivityAt ? `Activity: ${formatActivityLabel(run.lastActivityAt, run.activityState)}` : undefined,
|
|
189
|
+
run.mode ? `Mode: ${run.mode}` : undefined,
|
|
190
|
+
`Agent: ${nestedRunDisplayName(run)}`,
|
|
191
|
+
run.currentStep !== undefined ? `Progress: step ${run.currentStep + 1}/${run.chainStepCount ?? run.steps?.length ?? 1}` : undefined,
|
|
192
|
+
run.turnBudget ? `Turn budget: ${run.turnBudget.turnCount}/${run.turnBudget.maxTurns}+${run.turnBudget.graceTurns} (${run.turnBudget.outcome})` : undefined,
|
|
193
|
+
run.asyncDir ? `Dir: ${run.asyncDir}` : undefined,
|
|
194
|
+
run.sessionFile ? `Session: ${run.sessionFile}` : undefined,
|
|
195
|
+
run.error ? `Error: ${run.error}` : undefined,
|
|
196
|
+
].filter((line): line is string => Boolean(line));
|
|
197
|
+
if (run.path.length) {
|
|
198
|
+
lines.push(`Path: ${run.path.map((part) => `${part.runId}${part.stepIndex !== undefined ? `:${part.stepIndex + 1}` : ""}${part.agent ? `:${part.agent}` : ""}`).join(" > ")} > ${run.id}`);
|
|
199
|
+
}
|
|
200
|
+
if (run.steps?.length) {
|
|
201
|
+
lines.push("Steps:");
|
|
202
|
+
for (const [index, step] of run.steps.entries()) {
|
|
203
|
+
const activity = step.status === "running" ? formatActivityLabel(step.lastActivityAt, step.activityState) : undefined;
|
|
204
|
+
const budget = step.turnBudget ? `, turn budget: ${step.turnBudget.turnCount}/${step.turnBudget.maxTurns}+${step.turnBudget.graceTurns} (${step.turnBudget.outcome})` : "";
|
|
205
|
+
lines.push(` ${index + 1}. ${step.agent} ${step.status}${activity ? `, ${activity}` : ""}${budget}${step.error ? `, error: ${step.error}` : ""}`);
|
|
206
|
+
lines.push(...formatNestedRunStatusLines(step.children, { indent: " ", commandHints: true }));
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
lines.push(...formatNestedRunStatusLines(run.children, { indent: " ", commandHints: true }));
|
|
210
|
+
lines.push("Commands:", ` Status: subagent({ action: "status", id: "${run.id}" })`, ` Interrupt: subagent({ action: "interrupt", id: "${run.id}" })`, ` Resume: subagent({ action: "resume", id: "${run.id}", message: "..." })`, ` Steer: subagent({ action: "steer", id: "${run.id}", message: "..." })`, ` Root status: subagent({ action: "status", id: "${rootRunId}" })`);
|
|
211
|
+
return lines.join("\n");
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDeps = {}): AgentToolResult<Details> {
|
|
215
|
+
const asyncDirRoot = deps.asyncDirRoot ?? DIRS.async;
|
|
216
|
+
const resultsDir = deps.resultsDir ?? DIRS.results;
|
|
217
|
+
const currentSessionId = deps.state?.currentSessionId ?? undefined;
|
|
218
|
+
if (params.view && params.view !== "fleet" && params.view !== "transcript") {
|
|
219
|
+
return {
|
|
220
|
+
content: [{ type: "text", text: `Unknown status view: ${params.view}. Valid: fleet, transcript.` }],
|
|
221
|
+
isError: true,
|
|
222
|
+
details: { mode: "single", results: [] },
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
if (params.view === "fleet") {
|
|
226
|
+
return inspectSubagentFleet(params, { asyncDirRoot, resultsDir, kill: deps.kill, now: deps.now, state: deps.state, childSafe: Boolean(deps.nested) });
|
|
227
|
+
}
|
|
228
|
+
if (!params.id && !params.runId && !params.dir) {
|
|
229
|
+
if (deps.nested) {
|
|
230
|
+
return {
|
|
231
|
+
content: [{ type: "text", text: "Child-safe subagent status requires an id when no foreground run is active." }],
|
|
232
|
+
isError: true,
|
|
233
|
+
details: { mode: "single", results: [] },
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
try {
|
|
237
|
+
const runs = listAsyncRuns(asyncDirRoot, { states: ["queued", "running"], sessionId: currentSessionId, resultsDir, kill: deps.kill, now: deps.now });
|
|
238
|
+
if (params.view === "transcript") {
|
|
239
|
+
if (runs.length === 1) return inspectSubagentStatus({ ...params, id: runs[0]!.id }, deps);
|
|
240
|
+
return {
|
|
241
|
+
content: [{ type: "text", text: runs.length === 0 ? "No active async run transcript is available." : `Transcript view requires an id when ${runs.length} active async runs exist. Use subagent({ action: "status", view: "fleet" }) to choose one.` }],
|
|
242
|
+
isError: true,
|
|
243
|
+
details: { mode: "single", results: [] },
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
const waitSubscriptions = deps.state ? formatWaitSubscriptions(deps.state, deps.now?.() ?? Date.now()) : undefined;
|
|
247
|
+
return {
|
|
248
|
+
content: [{ type: "text", text: [formatAsyncRunList(runs), waitSubscriptions].filter(Boolean).join("\n\n") }],
|
|
249
|
+
details: { mode: "single", results: [] },
|
|
250
|
+
};
|
|
251
|
+
} catch (error) {
|
|
252
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
253
|
+
return {
|
|
254
|
+
content: [{ type: "text", text: message }],
|
|
255
|
+
isError: true,
|
|
256
|
+
details: { mode: "single", results: [] },
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
let location;
|
|
262
|
+
try {
|
|
263
|
+
const requestedId = params.id ?? params.runId;
|
|
264
|
+
if (!params.dir && requestedId) {
|
|
265
|
+
const resolved = resolveSubagentRunId(requestedId, { asyncDirRoot, resultsDir, state: deps.state, nested: deps.nested });
|
|
266
|
+
if (resolved?.kind === "foreground") {
|
|
267
|
+
const run = deps.state?.foregroundRuns?.get(resolved.id);
|
|
268
|
+
if (run) {
|
|
269
|
+
try {
|
|
270
|
+
return {
|
|
271
|
+
content: [{ type: "text", text: params.view === "transcript" ? formatRememberedForegroundTranscript(run, { index: params.index, lines: params.lines }) : formatRememberedForegroundStatus(run) }],
|
|
272
|
+
details: { mode: "single", results: [] },
|
|
273
|
+
};
|
|
274
|
+
} catch (error) {
|
|
275
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
276
|
+
return { content: [{ type: "text", text: message }], isError: true, details: { mode: "single", results: [] } };
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
if (resolved?.kind === "nested") {
|
|
281
|
+
reconcileNestedAsyncDescendants(resolved.match.route, { resultsDir, kill: deps.kill, now: deps.now });
|
|
282
|
+
const refreshed = resolveSubagentRunId(requestedId, { asyncDirRoot, resultsDir, state: deps.state, nested: deps.nested });
|
|
283
|
+
const nested = refreshed?.kind === "nested" ? refreshed : resolved;
|
|
284
|
+
if (params.view === "transcript") {
|
|
285
|
+
try {
|
|
286
|
+
return { content: [{ type: "text", text: formatNestedRunTranscript(nested.match.run, { index: params.index, lines: params.lines, sessionRoots: deps.sessionRoots }) }], details: { mode: "single", results: [] } };
|
|
287
|
+
} catch (error) {
|
|
288
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
289
|
+
return { content: [{ type: "text", text: message }], isError: true, details: { mode: "single", results: [] } };
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return { content: [{ type: "text", text: formatNestedExactStatus(nested.match.rootRunId, nested.match.run) }], details: { mode: "single", results: [] } };
|
|
293
|
+
}
|
|
294
|
+
if (resolved?.kind === "async") location = resolved.location;
|
|
295
|
+
else location = { asyncDir: null, resultPath: null, resolvedId: requestedId };
|
|
296
|
+
} else {
|
|
297
|
+
location = resolveAsyncRunLocation(params, asyncDirRoot, resultsDir);
|
|
298
|
+
}
|
|
299
|
+
} catch (error) {
|
|
300
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
301
|
+
return {
|
|
302
|
+
content: [{ type: "text", text: message }],
|
|
303
|
+
isError: true,
|
|
304
|
+
details: { mode: "single", results: [] },
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
const { asyncDir, resultPath, resolvedId } = location;
|
|
308
|
+
|
|
309
|
+
if (!asyncDir && !resultPath) {
|
|
310
|
+
return {
|
|
311
|
+
content: [{ type: "text", text: "Async run not found. Provide id or dir." }],
|
|
312
|
+
isError: true,
|
|
313
|
+
details: { mode: "single", results: [] },
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
if (asyncDir) {
|
|
318
|
+
let reconciliation;
|
|
319
|
+
try {
|
|
320
|
+
reconciliation = reconcileAsyncRun(asyncDir, { resultsDir, kill: deps.kill, now: deps.now });
|
|
321
|
+
} catch (error) {
|
|
322
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
323
|
+
return {
|
|
324
|
+
content: [{ type: "text", text: message }],
|
|
325
|
+
isError: true,
|
|
326
|
+
details: { mode: "single", results: [] },
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
const status = reconciliation.status;
|
|
330
|
+
const effectiveRunId = status?.runId ?? resolvedId ?? "unknown";
|
|
331
|
+
const logPath = path.join(asyncDir, `subagent-log-${effectiveRunId}.md`);
|
|
332
|
+
const eventsPath = path.join(asyncDir, "events.jsonl");
|
|
333
|
+
if (status) {
|
|
334
|
+
if (params.view === "transcript") {
|
|
335
|
+
if (currentSessionId && status.sessionId !== currentSessionId) {
|
|
336
|
+
return {
|
|
337
|
+
content: [{ type: "text", text: "Transcript view is only available for async runs owned by the current session." }],
|
|
338
|
+
isError: true,
|
|
339
|
+
details: { mode: "single", results: [] },
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
try {
|
|
343
|
+
return { content: [{ type: "text", text: formatAsyncRunTranscript(status, asyncDir, { index: params.index, lines: params.lines, sessionRoots: deps.sessionRoots }) }], details: { mode: "single", results: [] } };
|
|
344
|
+
} catch (error) {
|
|
345
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
346
|
+
return { content: [{ type: "text", text: message }], isError: true, details: { mode: "single", results: [] } };
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
let nestedChildren: NestedRunSummary[] = [];
|
|
350
|
+
let nestedWarning: string | undefined;
|
|
351
|
+
try {
|
|
352
|
+
const nestedRoute = findNestedRouteForRootId(status.runId);
|
|
353
|
+
if (nestedRoute) reconcileNestedAsyncDescendants(nestedRoute, { resultsDir, kill: deps.kill, now: deps.now });
|
|
354
|
+
nestedChildren = projectNestedRegistryForRoot(status.runId)?.children ?? [];
|
|
355
|
+
attachRootChildrenToSteps(status.runId, status.steps, nestedChildren);
|
|
356
|
+
} catch (error) {
|
|
357
|
+
nestedWarning = `Nested status unavailable: ${error instanceof Error ? error.message : String(error)}`;
|
|
358
|
+
}
|
|
359
|
+
const outputPath = formatAsyncRunOutputPath({ asyncDir, outputFile: status.outputFile });
|
|
360
|
+
const progressLabel = formatAsyncRunProgressLabel({
|
|
361
|
+
mode: status.mode,
|
|
362
|
+
state: status.state,
|
|
363
|
+
currentStep: status.currentStep,
|
|
364
|
+
chainStepCount: status.chainStepCount,
|
|
365
|
+
parallelGroups: status.parallelGroups,
|
|
366
|
+
steps: (status.steps ?? []).map((step, index) => ({ index, agent: step.agent, status: step.status })),
|
|
367
|
+
});
|
|
368
|
+
const started = new Date(status.startedAt).toISOString();
|
|
369
|
+
const updated = status.lastUpdate ? new Date(status.lastUpdate).toISOString() : "n/a";
|
|
370
|
+
const statusActivityText = status.state === "running" ? formatActivityLabel(status.lastActivityAt, status.activityState) : undefined;
|
|
371
|
+
const steeringText = formatSteeringSummary(status);
|
|
372
|
+
const processTerminal = readProcessTerminal(asyncDir, { runId: status.runId, runnerProcessInstanceId: status.processTerminal?.runnerProcessInstanceId })
|
|
373
|
+
?? sanitizeProcessTerminal(status.processTerminal, { runId: status.runId, runnerProcessInstanceId: status.processTerminal?.runnerProcessInstanceId }, path.join(asyncDir, "status.json"));
|
|
374
|
+
let missionId: string | undefined;
|
|
375
|
+
try {
|
|
376
|
+
missionId = readMissionBinding(asyncDir)?.missionId;
|
|
377
|
+
} catch (error) {
|
|
378
|
+
nestedWarning = `${nestedWarning ? `${nestedWarning}; ` : ""}Mission binding unavailable: ${error instanceof Error ? error.message : String(error)}`;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const workflowReturnPreview = status.workflow?.value !== undefined ? formatWorkflowJsonPreview(status.workflow.value, 240) : undefined;
|
|
382
|
+
const workflowEmitPreview = status.workflow?.emits.length ? formatWorkflowJsonPreview(status.workflow.emits.at(-1), 240) : undefined;
|
|
383
|
+
const lines = [
|
|
384
|
+
`Run: ${status.runId}`,
|
|
385
|
+
status.toolCallId ? `Tool call: ${status.toolCallId}` : undefined,
|
|
386
|
+
missionId ? `Mission: ${missionId}` : undefined,
|
|
387
|
+
`State: ${status.state}`,
|
|
388
|
+
processTerminal ? `Process terminal: ${processTerminal.state}${processTerminal.reason ? ` (${processTerminal.reason})` : ""}` : undefined,
|
|
389
|
+
status.capabilityCeiling ? `Capability ceiling: ${status.capabilityCeiling.allowedTools === undefined ? "names unrestricted" : status.capabilityCeiling.allowedTools.length === 0 ? "none" : status.capabilityCeiling.allowedTools.join(", ")}\nExtensions denied: ${status.capabilityCeiling.denyExtensions ? "yes" : "no"} (sources: ${status.capabilityCeiling.sources.join(", ")})` : undefined,
|
|
390
|
+
status.capabilityAudit ? `Capability audit: ${status.capabilityAudit.removedTools.length} tools removed, ${status.capabilityAudit.removedExtensionCount} extension entries removed` : undefined,
|
|
391
|
+
status.error ? `Error: ${status.error}` : undefined,
|
|
392
|
+
statusActivityText ? `Activity: ${statusActivityText}` : undefined,
|
|
393
|
+
steeringText ? `Steering: ${steeringText}` : undefined,
|
|
394
|
+
`Mode: ${status.mode}`,
|
|
395
|
+
status.parentWorkflowRunId ? `Workflow parent: ${status.parentWorkflowRunId}${status.workflowKey ? ` (${status.workflowKey})` : ""}` : undefined,
|
|
396
|
+
status.mode === "workflow" && workflowReturnPreview !== undefined ? `Return: ${workflowReturnPreview}` : undefined,
|
|
397
|
+
status.mode === "workflow" && workflowEmitPreview !== undefined ? `Latest emit: ${workflowEmitPreview}` : undefined,
|
|
398
|
+
`Progress: ${progressLabel}`,
|
|
399
|
+
status.pendingAppends ? `Pending appends: ${status.pendingAppends}` : undefined,
|
|
400
|
+
`Started: ${started}`,
|
|
401
|
+
`Updated: ${updated}`,
|
|
402
|
+
status.turnBudget ? `Turn budget: ${status.turnBudget.turnCount}/${status.turnBudget.maxTurns}+${status.turnBudget.graceTurns} (${status.turnBudget.outcome})` : undefined,
|
|
403
|
+
`Dir: ${asyncDir}`,
|
|
404
|
+
outputPath ? `Output: ${outputPath}` : undefined,
|
|
405
|
+
status.parallelHandoff ? `Parallel handoff: ${status.parallelHandoff.path}` : undefined,
|
|
406
|
+
reconciliation.message ? `Diagnosis: ${reconciliation.message}` : undefined,
|
|
407
|
+
reconciliation.resultPath && fs.existsSync(reconciliation.resultPath) ? `Result: ${reconciliation.resultPath}` : undefined,
|
|
408
|
+
].filter((line): line is string => Boolean(line));
|
|
409
|
+
for (const [index, step] of (status.steps ?? []).entries()) {
|
|
410
|
+
const stepActivityText = step.status === "running" ? formatActivityLabel(step.lastActivityAt, step.activityState) : undefined;
|
|
411
|
+
const modelThinking = formatModelThinking(step.model, step.thinking);
|
|
412
|
+
const modelText = modelThinking ? ` (${modelThinking})` : "";
|
|
413
|
+
const steeringText = formatSteeringSummary(step);
|
|
414
|
+
const steeringSuffix = steeringText ? `, steering: ${steeringText}` : "";
|
|
415
|
+
const errorText = step.error ? `, error: ${step.error}` : "";
|
|
416
|
+
const acceptanceText = step.acceptance?.status ? `, acceptance: ${step.acceptance.status}` : "";
|
|
417
|
+
const budgetText = step.turnBudget ? `, turn budget: ${step.turnBudget.turnCount}/${step.turnBudget.maxTurns}+${step.turnBudget.graceTurns} (${step.turnBudget.outcome})` : "";
|
|
418
|
+
const display = step.label ? `${step.label} (${step.agent})` : step.agent;
|
|
419
|
+
const phase = step.phase ? `[${step.phase}] ` : "";
|
|
420
|
+
lines.push(`${stepLineLabel(status, index)}: ${phase}${display} ${step.status}${modelText}${stepActivityText ? `, ${stepActivityText}` : ""}${steeringSuffix}${acceptanceText}${budgetText}${errorText}`);
|
|
421
|
+
if (step.runner?.type === "external-cli") {
|
|
422
|
+
lines.push(` Runner: external-cli (${step.runner.command}${step.runner.args.length ? ` ${step.runner.args.join(" ")}` : ""})`);
|
|
423
|
+
if (step.externalProcess?.pid !== undefined) lines.push(` Process: ${step.externalProcess.pid}`);
|
|
424
|
+
if (step.externalProcess) lines.push(` Stdout: ${step.externalProcess.stdoutPath}`, ` Stderr: ${step.externalProcess.stderrPath}`);
|
|
425
|
+
}
|
|
426
|
+
lines.push(...formatNestedRunStatusLines(step.children, { indent: " ", commandHints: true, maxLines: 20 }));
|
|
427
|
+
const stepOutputPath = path.join(asyncDir, `output-${index}.log`);
|
|
428
|
+
if (stepOutputPath !== outputPath && fs.existsSync(stepOutputPath)) lines.push(` Output: ${stepOutputPath}`);
|
|
429
|
+
if (step.status === "running" && step.runner?.type !== "external-cli") {
|
|
430
|
+
lines.push(` Intercom target: ${resolveSubagentIntercomTarget(status.runId, step.agent, index)} (if registered)`);
|
|
431
|
+
lines.push(` Steer: subagent({ action: "steer", id: "${status.runId}", index: ${index}, message: "..." })`);
|
|
432
|
+
} else if (step.status === "running" && step.runner?.type === "external-cli") {
|
|
433
|
+
lines.push(" Steer: unavailable; one-shot external CLI runners do not accept live messages.");
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
const attached = new Set((status.steps ?? []).flatMap((step) => step.children?.map((child) => child.id) ?? []));
|
|
437
|
+
const unattached = nestedChildren.filter((child) => !attached.has(child.id));
|
|
438
|
+
lines.push(...formatNestedRunStatusLines(unattached, { indent: "", commandHints: true, maxLines: 20 }));
|
|
439
|
+
if (nestedWarning) lines.push(`Warning: ${nestedWarning}`);
|
|
440
|
+
if (status.sessionFile) lines.push(`Session: ${status.sessionFile}`);
|
|
441
|
+
const allExternal = (status.steps?.length ?? 0) > 0 && status.steps!.every((step) => step.runner?.type === "external-cli");
|
|
442
|
+
if (status.state === "running" && !allExternal) lines.push(`Steer running child: subagent({ action: "steer", id: "${status.runId}", message: "..." })`);
|
|
443
|
+
if (status.state !== "running") {
|
|
444
|
+
lines.push(allExternal
|
|
445
|
+
? "Resume: unavailable; one-shot external CLI runners do not persist sessions."
|
|
446
|
+
: formatCheckpointGuidance(status.runId, status.checkpoint) ?? formatResumeGuidance(status.runId, status.steps ?? [], status.sessionFile, { stopped: status.state === "stopped" || status.stopped === true }));
|
|
447
|
+
}
|
|
448
|
+
if (fs.existsSync(logPath)) lines.push(`Log: ${logPath}`);
|
|
449
|
+
if (fs.existsSync(eventsPath)) lines.push(`Events: ${eventsPath}`);
|
|
450
|
+
|
|
451
|
+
return { content: [{ type: "text", text: lines.join("\n") }], details: { mode: "single", results: [], ...(processTerminal ? { lifecycleStatus: { processTerminal } } : {}) } };
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
if (resultPath) {
|
|
456
|
+
try {
|
|
457
|
+
const raw = fs.readFileSync(resultPath, "utf-8");
|
|
458
|
+
const data = JSON.parse(raw) as { id?: string; runId?: string; toolCallId?: string; agent?: string; success?: boolean; summary?: string; output?: string; exitCode?: number; state?: string; stopped?: boolean; timedOut?: boolean; turnBudgetExceeded?: boolean; processSignal?: string | null; sessionFile?: string; parallelHandoff?: { path?: string }; results?: Array<{ agent?: string; output?: string; summary?: string; sessionFile?: string; state?: string; success?: boolean; exitCode?: number | null; stopped?: boolean; timedOut?: boolean; turnBudgetExceeded?: boolean; interrupted?: boolean; processSignal?: string | null }> };
|
|
459
|
+
if (params.view === "transcript") {
|
|
460
|
+
try {
|
|
461
|
+
return { content: [{ type: "text", text: formatAsyncResultTranscript(data, resultPath, { index: params.index, lines: params.lines }) }], details: { mode: "single", results: [] } };
|
|
462
|
+
} catch (error) {
|
|
463
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
464
|
+
return { content: [{ type: "text", text: message }], isError: true, details: { mode: "single", results: [] } };
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
const childStatuses = Array.isArray(data.results)
|
|
468
|
+
? data.results.map((child) => resolveSubagentResultStatus({
|
|
469
|
+
success: child.success,
|
|
470
|
+
state: child.state,
|
|
471
|
+
interrupted: child.interrupted,
|
|
472
|
+
timedOut: child.timedOut,
|
|
473
|
+
stopped: child.stopped,
|
|
474
|
+
turnBudgetExceeded: child.turnBudgetExceeded,
|
|
475
|
+
processSignal: child.processSignal,
|
|
476
|
+
exitCode: typeof child.exitCode === "number" ? child.exitCode : undefined,
|
|
477
|
+
}))
|
|
478
|
+
: [];
|
|
479
|
+
const status = data.state === "stopped" || data.stopped === true || childStatuses.includes("stopped")
|
|
480
|
+
? "stopped"
|
|
481
|
+
: data.success ? "complete" : data.state === "paused" || data.exitCode === 0 ? "paused" : "failed";
|
|
482
|
+
const runId = data.runId ?? data.id ?? resolvedId;
|
|
483
|
+
const lines = [`Run: ${runId}`, data.toolCallId ? `Tool call: ${data.toolCallId}` : undefined, `State: ${status}`, `Result: ${resultPath}`].filter((line): line is string => Boolean(line));
|
|
484
|
+
if (data.parallelHandoff?.path) lines.push(`Parallel handoff: ${data.parallelHandoff.path}`);
|
|
485
|
+
const children = Array.isArray(data.results) ? data.results : data.agent ? [{ agent: data.agent, sessionFile: data.sessionFile }] : [];
|
|
486
|
+
lines.push(formatResumeGuidance(runId, children, data.sessionFile, { stopped: status === "stopped" }));
|
|
487
|
+
if (data.summary) lines.push("", data.summary);
|
|
488
|
+
return { content: [{ type: "text", text: lines.join("\n") }], details: { mode: "single", results: [] } };
|
|
489
|
+
} catch (error) {
|
|
490
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
491
|
+
return {
|
|
492
|
+
content: [{ type: "text", text: `Failed to read async result file: ${message}` }],
|
|
493
|
+
isError: true,
|
|
494
|
+
details: { mode: "single", results: [] },
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
return {
|
|
500
|
+
content: [{ type: "text", text: "Status file not found." }],
|
|
501
|
+
isError: true,
|
|
502
|
+
details: { mode: "single", results: [] },
|
|
503
|
+
};
|
|
504
|
+
}
|