@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
package/src/tui/fleet.ts
ADDED
|
@@ -0,0 +1,879 @@
|
|
|
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 { getMarkdownTheme, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { Key, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component, type MarkdownTheme } from "@earendil-works/pi-tui";
|
|
6
|
+
import { getArtifactPaths, getArtifactsDir } from "../shared/artifacts.ts";
|
|
7
|
+
import { formatDuration, formatModelThinking, formatTokens, shortenPath } from "../shared/formatters.ts";
|
|
8
|
+
import { DIRS, type AsyncJobState, type Details, type ForegroundChildControl, type ForegroundResumeChild, type ForegroundResumeRun, type ForegroundRunControl, type SubagentState } from "../shared/types.ts";
|
|
9
|
+
import { readStatus } from "../shared/utils.ts";
|
|
10
|
+
import { formatAsyncRunTranscript } from "../runs/background/fleet-view.ts";
|
|
11
|
+
import { listAsyncRuns, type AsyncRunSummary } from "../runs/background/async-status.ts";
|
|
12
|
+
import { steerAsyncRun } from "../runs/foreground/async-steering-action.ts";
|
|
13
|
+
import type { SteerDeliveryMode } from "../runs/background/control-channel.ts";
|
|
14
|
+
import { stopAsyncRun } from "../runs/foreground/async-stop-action.ts";
|
|
15
|
+
import { contextModeBadge, contextModeLabel } from "../runs/shared/context-mode.ts";
|
|
16
|
+
import { FLEET_STATUS_WIDGET_KEY } from "./fleet-status.ts";
|
|
17
|
+
import { readFleetTranscript, renderFleetTranscript, type FleetTranscript } from "./fleet-transcript.ts";
|
|
18
|
+
import { handleHerdrInspectorAction } from "../inspectors/herdr/actions.ts";
|
|
19
|
+
|
|
20
|
+
const REFRESH_MS = 750;
|
|
21
|
+
const MAX_RECENT_ASYNC_RUNS = 20;
|
|
22
|
+
const MAX_FLEET_HISTORY_CANDIDATES = 100;
|
|
23
|
+
const TRANSCRIPT_LINES = 200;
|
|
24
|
+
|
|
25
|
+
type Theme = ExtensionContext["ui"]["theme"];
|
|
26
|
+
type FleetTui = {
|
|
27
|
+
terminal?: { rows: number };
|
|
28
|
+
requestRender(): void;
|
|
29
|
+
};
|
|
30
|
+
type AsyncStep = AsyncRunSummary["steps"][number];
|
|
31
|
+
|
|
32
|
+
export type FleetItem = (
|
|
33
|
+
| { key: string; kind: "foreground-active"; runId: string; index?: number; agent: string; state: "running"; updatedAt: number; control: ForegroundRunControl; activeChild?: ForegroundChildControl }
|
|
34
|
+
| { key: string; kind: "foreground-recent"; runId: string; index: number; agent: string; state: ForegroundResumeChild["status"]; updatedAt: number; run: ForegroundResumeRun; child: ForegroundResumeChild }
|
|
35
|
+
| { key: string; kind: "async"; runId: string; index?: number; agent: string; state: string; updatedAt: number; run: AsyncRunSummary; step?: AsyncStep }
|
|
36
|
+
) & { description?: string };
|
|
37
|
+
|
|
38
|
+
export interface FleetSnapshot {
|
|
39
|
+
items: FleetItem[];
|
|
40
|
+
error?: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface FleetActionResult {
|
|
44
|
+
text: string;
|
|
45
|
+
isError?: boolean;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface FleetActionHandlers {
|
|
49
|
+
steer(input: { runId: string; asyncDir: string; index?: number; message: string; mode: SteerDeliveryMode }): Promise<FleetActionResult>;
|
|
50
|
+
stop(input: { runId: string; asyncDir: string; index?: number }): Promise<FleetActionResult> | FleetActionResult;
|
|
51
|
+
inspect?(input: { runId: string; asyncDir: string; index?: number }): Promise<FleetActionResult>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface FleetViewOptions {
|
|
55
|
+
asyncDirRoot?: string;
|
|
56
|
+
resultsDir?: string;
|
|
57
|
+
refreshMs?: number;
|
|
58
|
+
initialKey?: string;
|
|
59
|
+
markdownTheme?: MarkdownTheme;
|
|
60
|
+
actions?: FleetActionHandlers;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function belongsToCurrentSession(sessionId: string | undefined, currentSessionId: string | null): boolean {
|
|
64
|
+
return !currentSessionId || sessionId === currentSessionId;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function trackedJobSummary(job: AsyncJobState): AsyncRunSummary {
|
|
68
|
+
const startedAt = job.startedAt ?? job.updatedAt ?? Date.now();
|
|
69
|
+
return {
|
|
70
|
+
id: job.asyncId,
|
|
71
|
+
asyncDir: job.asyncDir,
|
|
72
|
+
...(job.sessionId ? { sessionId: job.sessionId } : {}),
|
|
73
|
+
state: job.status,
|
|
74
|
+
activityState: job.activityState,
|
|
75
|
+
lastActivityAt: job.lastActivityAt,
|
|
76
|
+
currentTool: job.currentTool,
|
|
77
|
+
currentToolStartedAt: job.currentToolStartedAt,
|
|
78
|
+
currentPath: job.currentPath,
|
|
79
|
+
turnCount: job.turnCount,
|
|
80
|
+
toolCount: job.toolCount,
|
|
81
|
+
steering: job.steering,
|
|
82
|
+
mode: job.mode ?? "single",
|
|
83
|
+
...(job.context ? { context: job.context } : {}),
|
|
84
|
+
...(job.cwd ? { cwd: job.cwd } : {}),
|
|
85
|
+
startedAt,
|
|
86
|
+
...(job.updatedAt !== undefined ? { lastUpdate: job.updatedAt } : {}),
|
|
87
|
+
...(job.timeoutMs !== undefined ? { timeoutMs: job.timeoutMs } : {}),
|
|
88
|
+
...(job.deadlineAt !== undefined ? { deadlineAt: job.deadlineAt } : {}),
|
|
89
|
+
...(job.timedOut !== undefined ? { timedOut: job.timedOut } : {}),
|
|
90
|
+
...(job.stopped !== undefined ? { stopped: job.stopped } : {}),
|
|
91
|
+
...(job.turnBudget ? { turnBudget: job.turnBudget } : {}),
|
|
92
|
+
...(job.turnBudgetExceeded !== undefined ? { turnBudgetExceeded: job.turnBudgetExceeded } : {}),
|
|
93
|
+
...(job.wrapUpRequested !== undefined ? { wrapUpRequested: job.wrapUpRequested } : {}),
|
|
94
|
+
...(job.currentStep !== undefined ? { currentStep: job.currentStep } : {}),
|
|
95
|
+
...(job.chainStepCount !== undefined ? { chainStepCount: job.chainStepCount } : {}),
|
|
96
|
+
...(job.parallelGroups?.length ? { parallelGroups: job.parallelGroups } : {}),
|
|
97
|
+
steps: (job.steps ?? job.agents?.map((agent, index) => ({ agent, index, status: job.status === "queued" ? "pending" as const : job.status })) ?? []).map((step, index) => ({
|
|
98
|
+
...step,
|
|
99
|
+
index: step.index ?? index,
|
|
100
|
+
})),
|
|
101
|
+
...(job.sessionDir ? { sessionDir: job.sessionDir } : {}),
|
|
102
|
+
...(job.outputFile ? { outputFile: job.outputFile } : {}),
|
|
103
|
+
...(job.totalTokens ? { totalTokens: job.totalTokens } : {}),
|
|
104
|
+
...(job.sessionFile ? { sessionFile: job.sessionFile } : {}),
|
|
105
|
+
...(job.nestedChildren?.length ? { nestedChildren: job.nestedChildren } : {}),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function asyncItems(run: AsyncRunSummary, description?: string): FleetItem[] {
|
|
110
|
+
const updatedAt = run.lastUpdate ?? run.endedAt ?? run.startedAt;
|
|
111
|
+
if (run.steps.length === 0 || run.mode === "workflow") {
|
|
112
|
+
return [{ key: `async:${run.id}`, kind: "async", runId: run.id, agent: run.mode, state: run.state, updatedAt, run, ...(description ? { description } : {}) }];
|
|
113
|
+
}
|
|
114
|
+
return run.steps.map((step) => ({
|
|
115
|
+
key: `async:${run.id}:${step.index}`,
|
|
116
|
+
kind: "async" as const,
|
|
117
|
+
runId: run.id,
|
|
118
|
+
index: step.index,
|
|
119
|
+
agent: step.label ? `${step.label} (${step.agent})` : step.agent,
|
|
120
|
+
state: step.status,
|
|
121
|
+
updatedAt: step.lastActivityAt ?? updatedAt,
|
|
122
|
+
run,
|
|
123
|
+
step,
|
|
124
|
+
...(description ? { description } : {}),
|
|
125
|
+
}));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function orderFleetAsyncRuns(runs: AsyncRunSummary[], terminalLimit: number): AsyncRunSummary[] {
|
|
129
|
+
const updatedAt = (run: AsyncRunSummary) => run.lastUpdate ?? run.endedAt ?? run.startedAt;
|
|
130
|
+
const byNewest = (left: AsyncRunSummary, right: AsyncRunSummary) => updatedAt(right) - updatedAt(left);
|
|
131
|
+
const active = runs.filter((run) => run.state === "queued" || run.state === "running").sort(byNewest);
|
|
132
|
+
const terminal = runs.filter((run) => run.state !== "queued" && run.state !== "running").sort(byNewest);
|
|
133
|
+
return [...active, ...terminal.slice(0, terminalLimit)];
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function collectFleetSnapshot(
|
|
137
|
+
state: SubagentState,
|
|
138
|
+
options: { asyncDirRoot?: string; resultsDir?: string; limit?: number } = {},
|
|
139
|
+
): FleetSnapshot {
|
|
140
|
+
const items: FleetItem[] = [];
|
|
141
|
+
const activeForegroundIds = new Set<string>();
|
|
142
|
+
for (const control of [...state.foregroundControls.values()].sort((left, right) => right.updatedAt - left.updatedAt)) {
|
|
143
|
+
activeForegroundIds.add(control.runId);
|
|
144
|
+
if (control.activeChildren) {
|
|
145
|
+
for (const child of [...control.activeChildren.values()].sort((left, right) => left.index - right.index)) {
|
|
146
|
+
items.push({
|
|
147
|
+
key: `foreground-active:${control.runId}:${child.index}`,
|
|
148
|
+
kind: "foreground-active",
|
|
149
|
+
runId: control.runId,
|
|
150
|
+
index: child.index,
|
|
151
|
+
agent: child.agent,
|
|
152
|
+
state: "running",
|
|
153
|
+
updatedAt: child.updatedAt,
|
|
154
|
+
control,
|
|
155
|
+
activeChild: child,
|
|
156
|
+
...(child.description ? { description: child.description } : {}),
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
items.push({
|
|
162
|
+
key: `foreground-active:${control.runId}:${control.currentIndex ?? 0}`,
|
|
163
|
+
kind: "foreground-active",
|
|
164
|
+
runId: control.runId,
|
|
165
|
+
...(control.currentIndex !== undefined ? { index: control.currentIndex } : {}),
|
|
166
|
+
agent: control.currentAgent ?? control.mode,
|
|
167
|
+
state: "running",
|
|
168
|
+
updatedAt: control.updatedAt,
|
|
169
|
+
control,
|
|
170
|
+
...(control.description ? { description: control.description } : {}),
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
let error: string | undefined;
|
|
175
|
+
try {
|
|
176
|
+
let runs: AsyncRunSummary[];
|
|
177
|
+
const descriptions = new Map<string, string>();
|
|
178
|
+
const tracked = [...(state.fleetJobs ?? state.asyncJobs).values()]
|
|
179
|
+
.filter((job) => belongsToCurrentSession(job.sessionId, state.currentSessionId));
|
|
180
|
+
const byUpdate = (left: AsyncJobState, right: AsyncJobState) => (right.updatedAt ?? right.startedAt ?? 0) - (left.updatedAt ?? left.startedAt ?? 0);
|
|
181
|
+
const active = tracked.filter((job) => job.status === "queued" || job.status === "running").sort(byUpdate);
|
|
182
|
+
const recent = tracked.filter((job) => job.status !== "queued" && job.status !== "running").sort(byUpdate).slice(0, options.limit ?? MAX_RECENT_ASYNC_RUNS);
|
|
183
|
+
const trackedRuns: AsyncRunSummary[] = [];
|
|
184
|
+
for (const job of [...active, ...recent]) {
|
|
185
|
+
try {
|
|
186
|
+
trackedRuns.push(trackedJobSummary(job));
|
|
187
|
+
if (job.description) descriptions.set(job.asyncId, job.description);
|
|
188
|
+
} catch (cause) {
|
|
189
|
+
error = `Failed to inspect async run '${job.asyncId}': ${cause instanceof Error ? cause.message : String(cause)}`;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (options.asyncDirRoot !== undefined) {
|
|
193
|
+
const trackedIds = new Set(trackedRuns.map((run) => run.id));
|
|
194
|
+
const history = listAsyncRuns(options.asyncDirRoot, {
|
|
195
|
+
...(state.currentSessionId ? { sessionId: state.currentSessionId } : {}),
|
|
196
|
+
entryLimit: MAX_FLEET_HISTORY_CANDIDATES,
|
|
197
|
+
resultsDir: options.resultsDir ?? DIRS.results,
|
|
198
|
+
reconcile: false,
|
|
199
|
+
}).filter((run) => !trackedIds.has(run.id));
|
|
200
|
+
runs = [...trackedRuns, ...history];
|
|
201
|
+
} else {
|
|
202
|
+
runs = trackedRuns;
|
|
203
|
+
}
|
|
204
|
+
for (const run of orderFleetAsyncRuns(runs, options.limit ?? MAX_RECENT_ASYNC_RUNS)) {
|
|
205
|
+
items.push(...asyncItems(run, descriptions.get(run.id)));
|
|
206
|
+
}
|
|
207
|
+
} catch (cause) {
|
|
208
|
+
error = cause instanceof Error ? cause.message : String(cause);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const recentForeground = [...(state.foregroundRuns?.values() ?? [])]
|
|
212
|
+
.filter((run) => belongsToCurrentSession(run.sessionId, state.currentSessionId) && !activeForegroundIds.has(run.runId))
|
|
213
|
+
.sort((left, right) => right.updatedAt - left.updatedAt);
|
|
214
|
+
for (const run of recentForeground) {
|
|
215
|
+
for (const child of run.children) {
|
|
216
|
+
items.push({
|
|
217
|
+
key: `foreground-recent:${run.runId}:${child.index}`,
|
|
218
|
+
kind: "foreground-recent",
|
|
219
|
+
runId: run.runId,
|
|
220
|
+
index: child.index,
|
|
221
|
+
agent: child.agent,
|
|
222
|
+
state: child.status,
|
|
223
|
+
updatedAt: child.updatedAt ?? run.updatedAt,
|
|
224
|
+
run,
|
|
225
|
+
child,
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return { items, ...(error ? { error } : {}) };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function statusGlyph(item: FleetItem, theme: Theme): string {
|
|
233
|
+
if (item.state === "running") return theme.fg("accent", "●");
|
|
234
|
+
if (item.state === "queued" || item.state === "pending") return theme.fg("muted", "◦");
|
|
235
|
+
if (item.state === "complete" || item.state === "completed") return theme.fg("success", "✓");
|
|
236
|
+
if (item.state === "paused" || item.state === "stopped" || item.state === "detached") return theme.fg("warning", "■");
|
|
237
|
+
return theme.fg("error", "✗");
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function foregroundActiveDetail(item: Extract<FleetItem, { kind: "foreground-active" }>): string[] {
|
|
241
|
+
const { control } = item;
|
|
242
|
+
const live = item.activeChild ?? control;
|
|
243
|
+
const modelThinking = formatModelThinking(live.model, live.thinking);
|
|
244
|
+
const lines = [
|
|
245
|
+
`Run: ${item.runId}`,
|
|
246
|
+
"Source: foreground",
|
|
247
|
+
`State: running`,
|
|
248
|
+
`Mode: ${control.mode}`,
|
|
249
|
+
item.index !== undefined ? `Child: ${item.index} (${item.agent})` : `Agent: ${item.agent}`,
|
|
250
|
+
modelThinking ? `Model: ${modelThinking}` : undefined,
|
|
251
|
+
`Started: ${new Date(live.startedAt).toISOString()}`,
|
|
252
|
+
live.currentTool ? `Current tool: ${live.currentTool}${live.currentPath ? ` · ${shortenPath(live.currentPath)}` : ""}` : undefined,
|
|
253
|
+
live.turnCount !== undefined ? `Turns: ${live.turnCount}` : undefined,
|
|
254
|
+
live.toolCount !== undefined ? `Tools: ${live.toolCount}` : undefined,
|
|
255
|
+
live.tokens !== undefined ? `Tokens: ${formatTokens(live.tokens)}` : undefined,
|
|
256
|
+
"",
|
|
257
|
+
"Transcript",
|
|
258
|
+
"Live foreground output remains in the expanded subagent tool result. Persisted output and session paths appear here after the child settles.",
|
|
259
|
+
];
|
|
260
|
+
return lines.filter((line): line is string => line !== undefined);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function foregroundRecentDetail(item: Extract<FleetItem, { kind: "foreground-recent" }>): string[] {
|
|
264
|
+
const { child, run } = item;
|
|
265
|
+
const outputPath = child.artifactPaths?.outputPath ?? child.savedOutputPath;
|
|
266
|
+
const modelThinking = formatModelThinking(child.model, child.thinking);
|
|
267
|
+
const lines = [
|
|
268
|
+
`Run: ${item.runId}`,
|
|
269
|
+
"Source: foreground",
|
|
270
|
+
`State: ${child.status}`,
|
|
271
|
+
`Mode: ${run.mode}`,
|
|
272
|
+
`Child: ${child.index} (${child.agent})${contextModeLabel(child.context) ? ` ${contextModeLabel(child.context)}` : ""}`,
|
|
273
|
+
modelThinking ? `Model: ${modelThinking}` : undefined,
|
|
274
|
+
`Updated: ${new Date(child.updatedAt ?? run.updatedAt).toISOString()}`,
|
|
275
|
+
outputPath ? `Output: ${outputPath}` : undefined,
|
|
276
|
+
child.sessionFile ? `Session: ${child.sessionFile}` : undefined,
|
|
277
|
+
child.transcriptPath ? `Transcript file: ${child.transcriptPath}` : undefined,
|
|
278
|
+
child.error ? `Error: ${child.error}` : undefined,
|
|
279
|
+
child.outputSaveError ? `Output warning: ${child.outputSaveError}` : undefined,
|
|
280
|
+
child.transcriptError ? `Transcript warning: ${child.transcriptError}` : undefined,
|
|
281
|
+
"",
|
|
282
|
+
"Result transcript tail",
|
|
283
|
+
];
|
|
284
|
+
const outputLines = (child.finalOutput ?? "").split(/\r?\n/).filter((line) => line.trim()).slice(-TRANSCRIPT_LINES);
|
|
285
|
+
lines.push(...(outputLines.length ? outputLines : ["(no recovered output available)"]));
|
|
286
|
+
return lines.filter((line): line is string => line !== undefined);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function asyncDetail(item: Extract<FleetItem, { kind: "async" }>): string[] {
|
|
290
|
+
const status = readStatus(item.run.asyncDir);
|
|
291
|
+
if (status) {
|
|
292
|
+
return formatAsyncRunTranscript(status, item.run.asyncDir, { index: item.index, lines: TRANSCRIPT_LINES }).split("\n");
|
|
293
|
+
}
|
|
294
|
+
const outputPath = item.index !== undefined ? path.join(item.run.asyncDir, `output-${item.index}.log`) : undefined;
|
|
295
|
+
return [
|
|
296
|
+
`Run: ${item.runId}`,
|
|
297
|
+
"Source: async",
|
|
298
|
+
`State: ${item.state}`,
|
|
299
|
+
`Mode: ${item.run.mode}${contextModeLabel(item.run.context) ? ` ${contextModeLabel(item.run.context)}` : ""}`,
|
|
300
|
+
item.index !== undefined ? `Child: ${item.index} (${item.agent})${contextModeLabel(item.step?.context) ? ` ${contextModeLabel(item.step?.context)}` : ""}` : `Agent: ${item.agent}${contextModeLabel(item.run.context) ? ` ${contextModeLabel(item.run.context)}` : ""}`,
|
|
301
|
+
outputPath ? `Output: ${outputPath}` : undefined,
|
|
302
|
+
item.step?.sessionFile ? `Session: ${item.step.sessionFile}` : item.run.sessionFile ? `Session: ${item.run.sessionFile}` : undefined,
|
|
303
|
+
"",
|
|
304
|
+
"Transcript",
|
|
305
|
+
"(status is no longer available)",
|
|
306
|
+
].filter((line): line is string => line !== undefined);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function detailLines(item: FleetItem | undefined, error: string | undefined): string[] {
|
|
310
|
+
if (!item) return [error ? `Fleet scan failed: ${error}` : "No current-session foreground or recent async children.", "", "New runs appear here automatically while this inspector remains open."];
|
|
311
|
+
const lines = item.kind === "foreground-active"
|
|
312
|
+
? foregroundActiveDetail(item)
|
|
313
|
+
: item.kind === "foreground-recent"
|
|
314
|
+
? foregroundRecentDetail(item)
|
|
315
|
+
: asyncDetail(item);
|
|
316
|
+
if (error) lines.unshift(`Fleet scan warning: ${error}`, "");
|
|
317
|
+
return lines;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function isActionableAsyncState(state: string): boolean {
|
|
321
|
+
return state === "running" || state === "queued" || state === "pending";
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function firstToolResultText(result: AgentToolResult<Details> | null, fallback: string): FleetActionResult {
|
|
325
|
+
if (!result) return { text: fallback, isError: true };
|
|
326
|
+
const text = result.content.find((item) => item.type === "text")?.text ?? fallback;
|
|
327
|
+
return { text, ...(result.isError ? { isError: true } : {}) };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function uniquePaths(values: Array<string | undefined>): string[] {
|
|
331
|
+
return [...new Set(values.filter((value): value is string => Boolean(value)).map((value) => path.resolve(value)))];
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function fleetArtifactsRoot(state: SubagentState, cwd: string): string {
|
|
335
|
+
return getArtifactsDir(
|
|
336
|
+
state.parentSessionFile ?? null,
|
|
337
|
+
cwd,
|
|
338
|
+
state.artifactDirPreference ?? "project",
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function transcriptTarget(item: FleetItem, state: SubagentState): { path: string; trustedRoots: string[] } | undefined {
|
|
343
|
+
if (item.kind === "foreground-active") {
|
|
344
|
+
const artifactsRoot = fleetArtifactsRoot(state, item.control.cwd ?? state.baseCwd);
|
|
345
|
+
return {
|
|
346
|
+
path: getArtifactPaths(artifactsRoot, item.runId, item.agent, item.index ?? 0).transcriptPath,
|
|
347
|
+
trustedRoots: [artifactsRoot],
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
if (item.kind === "foreground-recent") {
|
|
351
|
+
if (!item.child.transcriptPath) return undefined;
|
|
352
|
+
const transcriptPath = path.isAbsolute(item.child.transcriptPath)
|
|
353
|
+
? item.child.transcriptPath
|
|
354
|
+
: path.resolve(item.run.cwd, item.child.transcriptPath);
|
|
355
|
+
return {
|
|
356
|
+
path: transcriptPath,
|
|
357
|
+
trustedRoots: uniquePaths([
|
|
358
|
+
fleetArtifactsRoot(state, item.run.cwd),
|
|
359
|
+
fleetArtifactsRoot(state, state.baseCwd),
|
|
360
|
+
]),
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
const step = item.step ?? (item.run.steps.length === 1 ? item.run.steps[0] : undefined);
|
|
364
|
+
if (!step?.transcriptPath) return undefined;
|
|
365
|
+
const transcriptPath = path.isAbsolute(step.transcriptPath)
|
|
366
|
+
? step.transcriptPath
|
|
367
|
+
: path.resolve(item.run.asyncDir, step.transcriptPath);
|
|
368
|
+
const trackedJob = state.fleetJobs?.get(item.runId) ?? state.asyncJobs.get(item.runId);
|
|
369
|
+
return {
|
|
370
|
+
path: transcriptPath,
|
|
371
|
+
trustedRoots: uniquePaths([
|
|
372
|
+
item.run.asyncDir,
|
|
373
|
+
fleetArtifactsRoot(state, state.baseCwd),
|
|
374
|
+
trackedJob?.cwd ? fleetArtifactsRoot(state, trackedJob.cwd) : undefined,
|
|
375
|
+
]),
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function itemContext(item: FleetItem): string | undefined {
|
|
380
|
+
if (item.kind === "async") return contextModeLabel(item.step?.context ?? item.run.context);
|
|
381
|
+
if (item.kind === "foreground-recent") return contextModeLabel(item.child.context);
|
|
382
|
+
return undefined;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function itemMode(item: FleetItem): string {
|
|
386
|
+
return item.kind === "foreground-active" ? item.control.mode : item.run.mode;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function itemSource(item: FleetItem): string {
|
|
390
|
+
if (item.kind === "async") return "background";
|
|
391
|
+
return item.kind === "foreground-active" ? "foreground · live" : "foreground · recent";
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function itemStats(item: FleetItem): string[] {
|
|
395
|
+
let model: string | undefined;
|
|
396
|
+
let tokens: number | undefined;
|
|
397
|
+
let tools: number | undefined;
|
|
398
|
+
let durationMs: number | undefined;
|
|
399
|
+
if (item.kind === "foreground-active") {
|
|
400
|
+
const live = item.activeChild ?? item.control;
|
|
401
|
+
model = formatModelThinking(live.model, live.thinking) || undefined;
|
|
402
|
+
tokens = live.tokens;
|
|
403
|
+
tools = live.toolCount;
|
|
404
|
+
durationMs = Math.max(0, Date.now() - live.startedAt);
|
|
405
|
+
} else if (item.kind === "foreground-recent") {
|
|
406
|
+
model = formatModelThinking(item.child.model, item.child.thinking) || undefined;
|
|
407
|
+
tokens = item.child.tokens;
|
|
408
|
+
tools = item.child.toolCount;
|
|
409
|
+
} else {
|
|
410
|
+
model = formatModelThinking(item.step?.model, item.step?.thinking) || undefined;
|
|
411
|
+
tokens = item.step?.tokens?.total ?? (item.index === undefined ? item.run.totalTokens?.total : undefined);
|
|
412
|
+
tools = item.step?.toolCount ?? (item.index === undefined ? item.run.toolCount : undefined);
|
|
413
|
+
const terminalRun = item.state !== "queued" && item.state !== "running" && item.state !== "pending";
|
|
414
|
+
const endTime = item.run.endedAt ?? (terminalRun ? item.run.lastUpdate : undefined) ?? Date.now();
|
|
415
|
+
durationMs = item.step?.durationMs ?? Math.max(0, endTime - item.run.startedAt);
|
|
416
|
+
}
|
|
417
|
+
return [
|
|
418
|
+
model,
|
|
419
|
+
tokens !== undefined ? `${formatTokens(tokens)} tok` : undefined,
|
|
420
|
+
tools !== undefined ? `${tools} tool${tools === 1 ? "" : "s"}` : undefined,
|
|
421
|
+
durationMs !== undefined ? formatDuration(durationMs) : undefined,
|
|
422
|
+
].filter((value): value is string => Boolean(value));
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function structuredHeader(item: FleetItem, width: number, theme: Theme, conversationState: string): string[] {
|
|
426
|
+
const lines: string[] = [];
|
|
427
|
+
lines.push(rightAligned(` ${statusGlyph(item, theme)} ${theme.bold(item.agent)}`, theme.fg("dim", item.state), width));
|
|
428
|
+
const child = item.index !== undefined ? ` · child ${item.index + 1}` : "";
|
|
429
|
+
const context = itemContext(item);
|
|
430
|
+
const identity = `${itemSource(item)} · ${item.runId.slice(0, 8)}${child} · ${itemMode(item)}${context ? ` ${context}` : ""}`;
|
|
431
|
+
lines.push(` ${theme.fg("dim", identity)}`);
|
|
432
|
+
const stats = itemStats(item);
|
|
433
|
+
if (stats.length) lines.push(` ${theme.fg("muted", stats.join(" · "))}`);
|
|
434
|
+
if (item.description) {
|
|
435
|
+
const task = item.description.replace(/\s+/g, " ").trim();
|
|
436
|
+
lines.push(` ${theme.fg("dim", "Task")} ${task}`);
|
|
437
|
+
}
|
|
438
|
+
lines.push(`${theme.fg("accent", "Conversation")} ${theme.fg("dim", `· ${conversationState}`)}`);
|
|
439
|
+
return lines.map((line) => truncateToWidth(line, width));
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function fit(text: string, width: number): string {
|
|
443
|
+
const clipped = truncateToWidth(text, Math.max(0, width));
|
|
444
|
+
return clipped + " ".repeat(Math.max(0, width - visibleWidth(clipped)));
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function rightAligned(left: string, right: string, width: number): string {
|
|
448
|
+
const rightWidth = visibleWidth(right);
|
|
449
|
+
const leftWidth = Math.max(0, width - rightWidth - 1);
|
|
450
|
+
return fit(left, leftWidth) + " ".repeat(Math.max(1, width - leftWidth - rightWidth)) + fit(right, rightWidth);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
interface FleetDetailSections {
|
|
454
|
+
header: string[];
|
|
455
|
+
body: string[];
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
interface FleetTranscriptCache {
|
|
459
|
+
path: string;
|
|
460
|
+
fingerprint: string;
|
|
461
|
+
width: number;
|
|
462
|
+
expandedTools: boolean;
|
|
463
|
+
transcript: FleetTranscript;
|
|
464
|
+
body: string[];
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function transcriptFingerprint(filePath: string): string {
|
|
468
|
+
try {
|
|
469
|
+
const stat = fs.statSync(filePath);
|
|
470
|
+
return `${stat.size}:${stat.mtimeMs}`;
|
|
471
|
+
} catch {
|
|
472
|
+
return "missing";
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
export class SubagentFleetComponent implements Component {
|
|
477
|
+
private snapshot: FleetSnapshot = { items: [] };
|
|
478
|
+
private selected = 0;
|
|
479
|
+
private selectedKey: string | undefined;
|
|
480
|
+
private detailScroll = 0;
|
|
481
|
+
private detailAutoFollow = true;
|
|
482
|
+
private detailLineCount = 0;
|
|
483
|
+
private detailViewportHeight = 8;
|
|
484
|
+
private bodyHeight = 8;
|
|
485
|
+
private expandedTools = false;
|
|
486
|
+
private actionNotice: FleetActionResult | undefined;
|
|
487
|
+
private steerDraft: string | undefined;
|
|
488
|
+
private steerMode: SteerDeliveryMode = "steer";
|
|
489
|
+
private stopConfirming = false;
|
|
490
|
+
private actionBusy = false;
|
|
491
|
+
private transcriptCache: FleetTranscriptCache | undefined;
|
|
492
|
+
private disposed = false;
|
|
493
|
+
private readonly timer: ReturnType<typeof setInterval>;
|
|
494
|
+
private readonly tui: FleetTui;
|
|
495
|
+
private readonly theme: Theme;
|
|
496
|
+
private readonly markdownTheme: MarkdownTheme;
|
|
497
|
+
private readonly state: SubagentState;
|
|
498
|
+
private readonly done: (result: undefined) => void;
|
|
499
|
+
private readonly options: FleetViewOptions;
|
|
500
|
+
|
|
501
|
+
constructor(
|
|
502
|
+
tui: FleetTui,
|
|
503
|
+
theme: Theme,
|
|
504
|
+
state: SubagentState,
|
|
505
|
+
done: (result: undefined) => void,
|
|
506
|
+
options: FleetViewOptions = {},
|
|
507
|
+
) {
|
|
508
|
+
this.tui = tui;
|
|
509
|
+
this.theme = theme;
|
|
510
|
+
this.markdownTheme = options.markdownTheme ?? getMarkdownTheme();
|
|
511
|
+
this.state = state;
|
|
512
|
+
this.done = done;
|
|
513
|
+
this.options = options;
|
|
514
|
+
this.selectedKey = options.initialKey;
|
|
515
|
+
this.refresh();
|
|
516
|
+
this.timer = setInterval(() => {
|
|
517
|
+
if (this.disposed) return;
|
|
518
|
+
this.invalidate();
|
|
519
|
+
this.tui.requestRender();
|
|
520
|
+
}, options.refreshMs ?? REFRESH_MS);
|
|
521
|
+
this.timer.unref?.();
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
private refresh(): void {
|
|
525
|
+
const previousKey = this.snapshot.items[this.selected]?.key ?? this.selectedKey;
|
|
526
|
+
this.snapshot = collectFleetSnapshot(this.state, this.options);
|
|
527
|
+
const preserved = previousKey ? this.snapshot.items.findIndex((item) => item.key === previousKey) : -1;
|
|
528
|
+
this.selected = preserved >= 0 ? preserved : Math.min(this.selected, Math.max(0, this.snapshot.items.length - 1));
|
|
529
|
+
this.selectedKey = this.snapshot.items[this.selected]?.key;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
private moveSelection(delta: number): void {
|
|
533
|
+
if (this.snapshot.items.length === 0) return;
|
|
534
|
+
this.selected = Math.max(0, Math.min(this.snapshot.items.length - 1, this.selected + delta));
|
|
535
|
+
this.selectedKey = this.snapshot.items[this.selected]?.key;
|
|
536
|
+
this.detailAutoFollow = true;
|
|
537
|
+
this.resetActionInput();
|
|
538
|
+
this.tui.requestRender();
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
private resetActionInput(): void {
|
|
542
|
+
this.steerDraft = undefined;
|
|
543
|
+
this.steerMode = "steer";
|
|
544
|
+
this.stopConfirming = false;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
private selectedAsyncAction(): { item: Extract<FleetItem, { kind: "async" }> } | { reason: string } {
|
|
548
|
+
const item = this.snapshot.items[this.selected];
|
|
549
|
+
if (!item) return { reason: "No child is selected." };
|
|
550
|
+
if (item.kind !== "async") return { reason: "Fleet controls are available for current-session top-level async runs only." };
|
|
551
|
+
if (!isActionableAsyncState(item.run.state) || !isActionableAsyncState(item.state)) return { reason: `Selected child is ${item.state}; controls require a running or queued async child.` };
|
|
552
|
+
return { item };
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
private actionLines(): string[] {
|
|
556
|
+
const lines: string[] = [];
|
|
557
|
+
if (this.actionBusy) lines.push(this.theme.fg("accent", "Action pending..."));
|
|
558
|
+
if (this.steerDraft !== undefined) {
|
|
559
|
+
lines.push(this.theme.fg("accent", `Steer message (${this.steerMode}): ${this.steerDraft}${this.theme.fg("dim", "▌")}`));
|
|
560
|
+
lines.push(this.theme.fg("dim", "Enter sends · Tab changes mode · Esc cancels · Backspace edits"));
|
|
561
|
+
} else if (this.stopConfirming) {
|
|
562
|
+
const selected = this.snapshot.items[this.selected];
|
|
563
|
+
lines.push(this.theme.fg("warning", `Confirm stop for async run ${selected?.runId ?? "selected run"}?`));
|
|
564
|
+
lines.push(this.theme.fg("dim", "Stop ends the run; use interrupt for a resumable pause. Enter/Y confirms · N returns · Esc cancels"));
|
|
565
|
+
} else if (this.actionNotice) {
|
|
566
|
+
lines.push(this.theme.fg(this.actionNotice.isError ? "error" : "success", this.actionNotice.text));
|
|
567
|
+
}
|
|
568
|
+
return lines;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
private withActionLines(body: string[]): string[] {
|
|
572
|
+
const actionLines = this.actionLines();
|
|
573
|
+
return actionLines.length ? [...actionLines, "", ...body] : body;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
private setActionNotice(result: FleetActionResult): void {
|
|
577
|
+
this.actionNotice = result;
|
|
578
|
+
this.resetActionInput();
|
|
579
|
+
this.detailAutoFollow = false;
|
|
580
|
+
this.detailScroll = 0;
|
|
581
|
+
this.refresh();
|
|
582
|
+
this.tui.requestRender();
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
private runAction(action: () => Promise<FleetActionResult>): void {
|
|
586
|
+
if (this.actionBusy) return;
|
|
587
|
+
this.actionBusy = true;
|
|
588
|
+
this.actionNotice = undefined;
|
|
589
|
+
this.tui.requestRender();
|
|
590
|
+
void action()
|
|
591
|
+
.then((result) => this.setActionNotice(result))
|
|
592
|
+
.catch((error) => this.setActionNotice({ text: error instanceof Error ? error.message : String(error), isError: true }))
|
|
593
|
+
.finally(() => {
|
|
594
|
+
this.actionBusy = false;
|
|
595
|
+
if (!this.disposed) this.tui.requestRender();
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
private scrollDetail(delta: number): void {
|
|
600
|
+
const maxScroll = Math.max(0, this.detailLineCount - this.detailViewportHeight);
|
|
601
|
+
this.detailScroll = Math.max(0, Math.min(maxScroll, this.detailScroll + delta));
|
|
602
|
+
this.detailAutoFollow = this.detailScroll >= maxScroll;
|
|
603
|
+
this.tui.requestRender();
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
handleInput(data: string): void {
|
|
607
|
+
if (this.steerDraft !== undefined) {
|
|
608
|
+
if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
|
|
609
|
+
this.resetActionInput();
|
|
610
|
+
this.tui.requestRender();
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
if (matchesKey(data, "return") || data === "\r" || data === "\n") {
|
|
614
|
+
const message = this.steerDraft.trim();
|
|
615
|
+
if (!message) {
|
|
616
|
+
this.setActionNotice({ text: "Steer message cannot be empty.", isError: true });
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
const target = this.selectedAsyncAction();
|
|
620
|
+
if ("reason" in target || !this.options.actions) {
|
|
621
|
+
this.setActionNotice({ text: "reason" in target ? target.reason : "Fleet controls are unavailable in this context.", isError: true });
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
this.runAction(() => this.options.actions!.steer({ runId: target.item.runId, asyncDir: target.item.run.asyncDir, ...(target.item.index !== undefined ? { index: target.item.index } : {}), message, mode: this.steerMode }));
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
if (matchesKey(data, "tab") || data === "\t") {
|
|
628
|
+
const modes: SteerDeliveryMode[] = ["steer", "follow_up", "auto"];
|
|
629
|
+
this.steerMode = modes[(modes.indexOf(this.steerMode) + 1) % modes.length]!;
|
|
630
|
+
this.tui.requestRender();
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
if (matchesKey(data, "backspace") || data === "\x7f") {
|
|
634
|
+
this.steerDraft = this.steerDraft.slice(0, -1);
|
|
635
|
+
this.tui.requestRender();
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
if (data.length === 1 && data >= " " && data !== "\x7f") {
|
|
639
|
+
this.steerDraft += data;
|
|
640
|
+
this.tui.requestRender();
|
|
641
|
+
}
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
if (this.stopConfirming) {
|
|
645
|
+
if (matchesKey(data, "return") || data.toLowerCase() === "y") {
|
|
646
|
+
const target = this.selectedAsyncAction();
|
|
647
|
+
if ("reason" in target || !this.options.actions) {
|
|
648
|
+
this.setActionNotice({ text: "reason" in target ? target.reason : "Fleet controls are unavailable in this context.", isError: true });
|
|
649
|
+
return;
|
|
650
|
+
}
|
|
651
|
+
this.runAction(() => Promise.resolve(this.options.actions!.stop({ runId: target.item.runId, asyncDir: target.item.run.asyncDir, ...(target.item.index !== undefined ? { index: target.item.index } : {}) })));
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c") || data.toLowerCase() === "n" || matchesKey(data, "backspace")) {
|
|
655
|
+
this.resetActionInput();
|
|
656
|
+
this.tui.requestRender();
|
|
657
|
+
}
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c") || matchesKey(data, "q")) {
|
|
661
|
+
this.done(undefined);
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
if (matchesKey(data, Key.shift("k"))) return this.scrollDetail(-1);
|
|
665
|
+
if (matchesKey(data, Key.shift("j"))) return this.scrollDetail(1);
|
|
666
|
+
if (matchesKey(data, "up") || matchesKey(data, "k")) return this.moveSelection(-1);
|
|
667
|
+
if (matchesKey(data, "down") || matchesKey(data, "j")) return this.moveSelection(1);
|
|
668
|
+
if (matchesKey(data, "home")) return this.moveSelection(-this.snapshot.items.length);
|
|
669
|
+
if (matchesKey(data, "end")) return this.moveSelection(this.snapshot.items.length);
|
|
670
|
+
if (matchesKey(data, "pageUp")) return this.scrollDetail(-this.detailViewportHeight);
|
|
671
|
+
if (matchesKey(data, "pageDown")) return this.scrollDetail(this.detailViewportHeight);
|
|
672
|
+
if (data.toLowerCase() === "r") {
|
|
673
|
+
this.transcriptCache = undefined;
|
|
674
|
+
this.refresh();
|
|
675
|
+
this.tui.requestRender();
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
if (data === "s") {
|
|
679
|
+
const target = this.selectedAsyncAction();
|
|
680
|
+
if ("reason" in target || !this.options.actions) this.setActionNotice({ text: "reason" in target ? target.reason : "Fleet controls are unavailable in this context.", isError: true });
|
|
681
|
+
else {
|
|
682
|
+
this.actionNotice = undefined;
|
|
683
|
+
this.steerDraft = "";
|
|
684
|
+
this.detailAutoFollow = false;
|
|
685
|
+
this.detailScroll = 0;
|
|
686
|
+
this.tui.requestRender();
|
|
687
|
+
}
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
if (data === "H") {
|
|
691
|
+
const target = this.selectedAsyncAction();
|
|
692
|
+
if ("reason" in target || !this.options.actions?.inspect) this.setActionNotice({ text: "reason" in target ? target.reason : "Herdr inspector controls are unavailable in this context.", isError: true });
|
|
693
|
+
else this.runAction(() => this.options.actions!.inspect!({ runId: target.item.runId, asyncDir: target.item.run.asyncDir, ...(target.item.index !== undefined ? { index: target.item.index } : {}) }));
|
|
694
|
+
return;
|
|
695
|
+
}
|
|
696
|
+
if (data === "D") {
|
|
697
|
+
const target = this.selectedAsyncAction();
|
|
698
|
+
if ("reason" in target || !this.options.actions) this.setActionNotice({ text: "reason" in target ? target.reason : "Fleet controls are unavailable in this context.", isError: true });
|
|
699
|
+
else {
|
|
700
|
+
this.actionNotice = undefined;
|
|
701
|
+
this.stopConfirming = true;
|
|
702
|
+
this.detailAutoFollow = false;
|
|
703
|
+
this.detailScroll = 0;
|
|
704
|
+
this.tui.requestRender();
|
|
705
|
+
}
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
if (data.toLowerCase() === "x" || matchesKey(data, "ctrl+o")) {
|
|
709
|
+
this.expandedTools = !this.expandedTools;
|
|
710
|
+
this.transcriptCache = undefined;
|
|
711
|
+
this.tui.requestRender();
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
private rosterLines(width: number): string[] {
|
|
716
|
+
if (this.snapshot.items.length === 0) return [this.theme.fg("dim", "No tracked children")];
|
|
717
|
+
const start = Math.max(0, Math.min(this.selected - this.bodyHeight + 1, Math.max(0, this.snapshot.items.length - this.bodyHeight)));
|
|
718
|
+
return this.snapshot.items.slice(start, start + this.bodyHeight).map((item, offset) => {
|
|
719
|
+
const index = start + offset;
|
|
720
|
+
const marker = index === this.selected ? this.theme.fg("accent", "›") : " ";
|
|
721
|
+
const context = item.kind === "async" ? contextModeBadge(this.theme, item.step?.context ?? item.run.context) : item.kind === "foreground-recent" ? contextModeBadge(this.theme, item.child.context) : "";
|
|
722
|
+
const agent = index === this.selected ? this.theme.bold(item.agent) : item.agent;
|
|
723
|
+
const identity = item.description?.replace(/\s+/g, " ").trim() || item.runId.slice(0, 8);
|
|
724
|
+
const left = `${marker} ${statusGlyph(item, this.theme)} ${agent}${context} ${this.theme.fg("dim", `· ${identity}`)}`;
|
|
725
|
+
return rightAligned(left, this.theme.fg("dim", item.state), width);
|
|
726
|
+
});
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
private renderedTranscript(target: { path: string; trustedRoots: string[] }, width: number): { transcript: FleetTranscript; body: string[] } {
|
|
730
|
+
const fingerprint = `${target.trustedRoots.join("\0")}|${transcriptFingerprint(target.path)}`;
|
|
731
|
+
if (this.transcriptCache
|
|
732
|
+
&& this.transcriptCache.path === target.path
|
|
733
|
+
&& this.transcriptCache.fingerprint === fingerprint
|
|
734
|
+
&& this.transcriptCache.width === width
|
|
735
|
+
&& this.transcriptCache.expandedTools === this.expandedTools) {
|
|
736
|
+
return { transcript: this.transcriptCache.transcript, body: [...this.transcriptCache.body] };
|
|
737
|
+
}
|
|
738
|
+
const transcript = readFleetTranscript(target.path, { trustedRoots: target.trustedRoots });
|
|
739
|
+
const body = transcript.events.length > 0
|
|
740
|
+
? renderFleetTranscript(transcript, width, this.theme, this.markdownTheme, { expandedTools: this.expandedTools })
|
|
741
|
+
: [];
|
|
742
|
+
this.transcriptCache = { path: target.path, fingerprint, width, expandedTools: this.expandedTools, transcript, body };
|
|
743
|
+
return { transcript, body: [...body] };
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
private wrappedDetail(width: number): FleetDetailSections {
|
|
747
|
+
const selected = this.snapshot.items[this.selected];
|
|
748
|
+
let transcriptWarning: string | undefined;
|
|
749
|
+
if (selected) {
|
|
750
|
+
const target = transcriptTarget(selected, this.state);
|
|
751
|
+
if (target) {
|
|
752
|
+
const { transcript, body } = this.renderedTranscript(target, width);
|
|
753
|
+
transcriptWarning = transcript.warning;
|
|
754
|
+
if (transcript.events.length > 0) {
|
|
755
|
+
if (this.snapshot.error) body.unshift(this.theme.fg("warning", `Fleet scan warning: ${this.snapshot.error}`), "");
|
|
756
|
+
const latest = transcript.events.at(-1);
|
|
757
|
+
const conversationState = latest?.kind === "assistant"
|
|
758
|
+
? "assistant response"
|
|
759
|
+
: latest?.kind === "user"
|
|
760
|
+
? "supervisor message"
|
|
761
|
+
: latest?.kind === "tool"
|
|
762
|
+
? `${latest.name} · ${latest.status}`
|
|
763
|
+
: "activity";
|
|
764
|
+
return { header: structuredHeader(selected, width, this.theme, conversationState), body: this.withActionLines(body) };
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
const raw = detailLines(selected, this.snapshot.error);
|
|
770
|
+
if (transcriptWarning) raw.unshift(`Transcript preview warning: ${transcriptWarning}`, "");
|
|
771
|
+
const lines: string[] = [];
|
|
772
|
+
for (const line of raw) {
|
|
773
|
+
const styled = /^(Run|State|Mode|Source|Child|Agent|Model):/.test(line)
|
|
774
|
+
? this.theme.bold(line)
|
|
775
|
+
: /^(Transcript|Result transcript tail)/.test(line)
|
|
776
|
+
? this.theme.fg("accent", line)
|
|
777
|
+
: /^(Output|Session|Transcript file|Artifacts):/.test(line)
|
|
778
|
+
? this.theme.fg("muted", line)
|
|
779
|
+
: /^Transcript preview warning:/.test(line)
|
|
780
|
+
? this.theme.fg("warning", line)
|
|
781
|
+
: line;
|
|
782
|
+
const wrapped = wrapTextWithAnsi(styled, Math.max(1, width));
|
|
783
|
+
lines.push(...(wrapped.length ? wrapped : [""]));
|
|
784
|
+
}
|
|
785
|
+
return { header: [], body: this.withActionLines(lines) };
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
render(width: number): string[] {
|
|
789
|
+
if (width < 36) return [truncateToWidth("Subagent fleet needs at least 36 columns. Esc closes.", width)];
|
|
790
|
+
const innerWidth = width - 2;
|
|
791
|
+
const rows = this.tui.terminal?.rows ?? 32;
|
|
792
|
+
this.bodyHeight = Math.max(2, Math.floor(rows * 0.85) - 6);
|
|
793
|
+
const rosterWidth = Math.max(22, Math.min(46, Math.floor((innerWidth - 1) * 0.38)));
|
|
794
|
+
const detailWidth = Math.max(1, innerWidth - rosterWidth - 1);
|
|
795
|
+
const roster = this.rosterLines(rosterWidth);
|
|
796
|
+
const detail = this.wrappedDetail(detailWidth);
|
|
797
|
+
const detailHeader = detail.header.slice(0, Math.max(0, this.bodyHeight - 1));
|
|
798
|
+
this.detailViewportHeight = Math.max(1, this.bodyHeight - detailHeader.length);
|
|
799
|
+
this.detailLineCount = detail.body.length;
|
|
800
|
+
const maxDetailScroll = Math.max(0, detail.body.length - this.detailViewportHeight);
|
|
801
|
+
if (this.detailAutoFollow) this.detailScroll = maxDetailScroll;
|
|
802
|
+
else if (this.detailScroll > maxDetailScroll) this.detailScroll = maxDetailScroll;
|
|
803
|
+
const visibleDetails = [
|
|
804
|
+
...detailHeader,
|
|
805
|
+
...detail.body.slice(this.detailScroll, this.detailScroll + this.detailViewportHeight),
|
|
806
|
+
];
|
|
807
|
+
const lines = [this.theme.fg("border", `╭${"─".repeat(innerWidth)}╮`)];
|
|
808
|
+
const selected = this.snapshot.items[this.selected];
|
|
809
|
+
const title = ` ${this.theme.bold("Subagent fleet inspector")} ${this.theme.fg("dim", "· live controls")}`;
|
|
810
|
+
const selectedStatus = selected
|
|
811
|
+
? `${statusGlyph(selected, this.theme)} ${selected.agent} · ${selected.state} `
|
|
812
|
+
: this.theme.fg("dim", "no children ");
|
|
813
|
+
lines.push(this.theme.fg("border", "│") + rightAligned(title, selectedStatus, innerWidth) + this.theme.fg("border", "│"));
|
|
814
|
+
lines.push(this.theme.fg("border", `├${"─".repeat(rosterWidth)}┬${"─".repeat(detailWidth)}┤`));
|
|
815
|
+
for (let index = 0; index < this.bodyHeight; index++) {
|
|
816
|
+
lines.push(
|
|
817
|
+
this.theme.fg("border", "│")
|
|
818
|
+
+ fit(roster[index] ?? "", rosterWidth)
|
|
819
|
+
+ this.theme.fg("border", "│")
|
|
820
|
+
+ fit(visibleDetails[index] ?? "", detailWidth)
|
|
821
|
+
+ this.theme.fg("border", "│"),
|
|
822
|
+
);
|
|
823
|
+
}
|
|
824
|
+
lines.push(this.theme.fg("border", `├${"─".repeat(rosterWidth)}┴${"─".repeat(detailWidth)}┤`));
|
|
825
|
+
const position = this.snapshot.items.length ? `${this.selected + 1}/${this.snapshot.items.length}` : "0/0";
|
|
826
|
+
const footer = ` ↑↓/jk agent · H Herdr · s steer · D stop · x/Ctrl+O tools · r refresh · Esc close · ${position}`;
|
|
827
|
+
lines.push(this.theme.fg("border", "│") + fit(this.theme.fg("dim", footer), innerWidth) + this.theme.fg("border", "│"));
|
|
828
|
+
lines.push(this.theme.fg("border", `╰${"─".repeat(innerWidth)}╯`));
|
|
829
|
+
return lines.map((line) => truncateToWidth(line, width));
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
invalidate(): void {
|
|
833
|
+
this.transcriptCache = undefined;
|
|
834
|
+
this.refresh();
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
dispose(): void {
|
|
838
|
+
this.disposed = true;
|
|
839
|
+
clearInterval(this.timer);
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
export async function openSubagentFleet(ctx: ExtensionContext, state: SubagentState, options: FleetViewOptions = {}): Promise<void> {
|
|
844
|
+
const wasOpen = state.fleetInspectorOpen === true;
|
|
845
|
+
state.fleetInspectorOpen = true;
|
|
846
|
+
if (typeof ctx.ui.setWidget === "function") ctx.ui.setWidget(FLEET_STATUS_WIDGET_KEY, undefined);
|
|
847
|
+
const actions = options.actions ?? {
|
|
848
|
+
steer: async (input: { runId: string; asyncDir: string; index?: number; message: string; mode: SteerDeliveryMode }) => firstToolResultText(await steerAsyncRun({
|
|
849
|
+
state,
|
|
850
|
+
runId: input.runId,
|
|
851
|
+
...(input.index !== undefined ? { index: input.index } : {}),
|
|
852
|
+
message: input.message,
|
|
853
|
+
mode: input.mode,
|
|
854
|
+
location: { asyncDir: input.asyncDir, resolvedId: input.runId } as Parameters<typeof steerAsyncRun>[0]["location"],
|
|
855
|
+
}), `Failed to steer async run ${input.runId}.`),
|
|
856
|
+
stop: (input: { runId: string; asyncDir: string; index?: number }) => firstToolResultText(stopAsyncRun(state, input.runId, undefined, { asyncDir: input.asyncDir, resolvedId: input.runId }), `Failed to stop async run ${input.runId}.`),
|
|
857
|
+
inspect: async (input: { runId: string; asyncDir: string; index?: number }) => firstToolResultText(await handleHerdrInspectorAction("inspector.open", {
|
|
858
|
+
id: input.runId,
|
|
859
|
+
dir: input.asyncDir,
|
|
860
|
+
...(input.index !== undefined ? { index: input.index } : {}),
|
|
861
|
+
}, {
|
|
862
|
+
state,
|
|
863
|
+
cwd: state.baseCwd,
|
|
864
|
+
...(state.authorityPolicy ? { authorityPolicy: state.authorityPolicy } : {}),
|
|
865
|
+
...(state.missionStoreConfig ? { missions: state.missionStoreConfig } : {}),
|
|
866
|
+
}), `Failed to open Herdr inspector for async run ${input.runId}.`),
|
|
867
|
+
} satisfies FleetActionHandlers;
|
|
868
|
+
try {
|
|
869
|
+
await ctx.ui.custom<undefined>(
|
|
870
|
+
(tui, theme, _keybindings, done) => new SubagentFleetComponent(tui, theme, state, done, { ...options, actions }),
|
|
871
|
+
{
|
|
872
|
+
overlay: true,
|
|
873
|
+
overlayOptions: { anchor: "center", width: "95%", minWidth: 60, maxHeight: "85%", margin: 1 },
|
|
874
|
+
},
|
|
875
|
+
);
|
|
876
|
+
} finally {
|
|
877
|
+
state.fleetInspectorOpen = wasOpen;
|
|
878
|
+
}
|
|
879
|
+
}
|