@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,994 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { keyText, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { Key, matchesKey, truncateToWidth, type Component, type TUI } from "@earendil-works/pi-tui";
|
|
6
|
+
import { BUILTIN_AGENT_NAMES, discoverAgents } from "../agents/agents.ts";
|
|
7
|
+
import {
|
|
8
|
+
DEFAULT_PROVIDER_MODELS_MAX_AGE_DAYS,
|
|
9
|
+
applySubagentProfile,
|
|
10
|
+
checkSubagentProfile,
|
|
11
|
+
generateProfilesForProvider,
|
|
12
|
+
listSubagentProfiles,
|
|
13
|
+
readSubagentProfile,
|
|
14
|
+
refreshProviderModelCatalog,
|
|
15
|
+
} from "../profiles/profiles.ts";
|
|
16
|
+
import type { SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
|
|
17
|
+
import { findModelInfo, toModelInfo } from "../shared/model-info.ts";
|
|
18
|
+
import { formatTokens, shortenPath } from "../shared/formatters.ts";
|
|
19
|
+
import { listAsyncRuns, formatAsyncRunProgressLabel, type AsyncRunSummary } from "../runs/background/async-status.ts";
|
|
20
|
+
import { listScheduledRunSummaries } from "../runs/background/scheduled-runs.ts";
|
|
21
|
+
import { SUBAGENT_FANOUT_CHILD_ENV } from "../runs/shared/pi-args.ts";
|
|
22
|
+
import type { SlashSubagentResponse, SlashSubagentUpdate } from "./slash-bridge.ts";
|
|
23
|
+
import { registerPromptWorkflowCommands } from "./prompt-workflows.ts";
|
|
24
|
+
import { openSubagentsAdmin } from "./subagents-admin.ts";
|
|
25
|
+
import { openSubagentFleet } from "../tui/fleet.ts";
|
|
26
|
+
import {
|
|
27
|
+
applySlashUpdate,
|
|
28
|
+
buildSlashInitialResult,
|
|
29
|
+
failSlashResult,
|
|
30
|
+
finalizeSlashResult,
|
|
31
|
+
resolveSlashMessageDetails,
|
|
32
|
+
} from "./slash-live-state.ts";
|
|
33
|
+
import {
|
|
34
|
+
SLASH_RESULT_TYPE,
|
|
35
|
+
SLASH_TEXT_RESULT_TYPE,
|
|
36
|
+
SLASH_SUBAGENT_CANCEL_EVENT,
|
|
37
|
+
SLASH_SUBAGENT_REQUEST_EVENT,
|
|
38
|
+
SLASH_SUBAGENT_RESPONSE_EVENT,
|
|
39
|
+
SLASH_SUBAGENT_STARTED_EVENT,
|
|
40
|
+
SLASH_SUBAGENT_UPDATE_EVENT,
|
|
41
|
+
DIRS,
|
|
42
|
+
type Details,
|
|
43
|
+
type JsonSchemaObject,
|
|
44
|
+
type SingleResult,
|
|
45
|
+
type SubagentState,
|
|
46
|
+
type Usage,
|
|
47
|
+
} from "../shared/types.ts";
|
|
48
|
+
|
|
49
|
+
interface InlineConfig {
|
|
50
|
+
output?: string | false;
|
|
51
|
+
outputMode?: "inline" | "file-only";
|
|
52
|
+
reads?: string[] | false;
|
|
53
|
+
model?: string;
|
|
54
|
+
skill?: string[] | false;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const parseInlineConfig = (raw: string): InlineConfig => {
|
|
58
|
+
const config: InlineConfig = {};
|
|
59
|
+
for (const part of raw.split(",")) {
|
|
60
|
+
const trimmed = part.trim();
|
|
61
|
+
if (!trimmed) continue;
|
|
62
|
+
const eq = trimmed.indexOf("=");
|
|
63
|
+
if (eq === -1) continue;
|
|
64
|
+
const key = trimmed.slice(0, eq).trim();
|
|
65
|
+
const val = trimmed.slice(eq + 1).trim();
|
|
66
|
+
switch (key) {
|
|
67
|
+
case "output": config.output = val === "false" ? false : val; break;
|
|
68
|
+
case "outputMode": if (val === "inline" || val === "file-only") config.outputMode = val; break;
|
|
69
|
+
case "reads": config.reads = val === "false" ? false : val.split("+").filter(Boolean); break;
|
|
70
|
+
case "model": config.model = val || undefined; break;
|
|
71
|
+
case "skill": case "skills": config.skill = val === "false" ? false : val.split("+").filter(Boolean); break;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return config;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const parseAgentToken = (token: string): { name: string; config: InlineConfig } => {
|
|
78
|
+
const bracket = token.indexOf("[");
|
|
79
|
+
if (bracket === -1) return { name: token, config: {} };
|
|
80
|
+
const end = token.lastIndexOf("]");
|
|
81
|
+
return { name: token.slice(0, bracket), config: parseInlineConfig(token.slice(bracket + 1, end !== -1 ? end : undefined)) };
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const extractExecutionFlags = (rawArgs: string): { args: string; bg: boolean; fork: boolean } => {
|
|
85
|
+
let args = rawArgs.trim();
|
|
86
|
+
let bg = false;
|
|
87
|
+
let fork = false;
|
|
88
|
+
|
|
89
|
+
while (true) {
|
|
90
|
+
if (args.endsWith(" --bg") || args === "--bg") {
|
|
91
|
+
bg = true;
|
|
92
|
+
args = args === "--bg" ? "" : args.slice(0, -5).trim();
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (args.endsWith(" --fork") || args === "--fork") {
|
|
96
|
+
fork = true;
|
|
97
|
+
args = args === "--fork" ? "" : args.slice(0, -7).trim();
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return { args, bg, fork };
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const makeAgentCompletions = (state: SubagentState) => (prefix: string) => {
|
|
107
|
+
if (!state.baseCwd || prefix.includes(" ")) return null;
|
|
108
|
+
return discoverAgents(state.baseCwd, "both").agents
|
|
109
|
+
.filter((agent) => agent.name.startsWith(prefix))
|
|
110
|
+
.map((agent) => ({ value: agent.name, label: agent.name }));
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const makeBuiltinAgentNameCompletions = () => (prefix: string) => {
|
|
114
|
+
if (prefix.includes(" ")) return null;
|
|
115
|
+
return BUILTIN_AGENT_NAMES
|
|
116
|
+
.filter((name) => name.startsWith(prefix))
|
|
117
|
+
.map((name) => ({ value: name, label: name }));
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const makeProviderCompletions = (state: SubagentState) => (prefix: string) => {
|
|
121
|
+
if (prefix.includes(" ")) return null;
|
|
122
|
+
const available = state.lastUiContext?.modelRegistry?.getAvailable?.();
|
|
123
|
+
if (!Array.isArray(available)) return null;
|
|
124
|
+
const providers = [...new Set(available
|
|
125
|
+
.map((model) => typeof model?.provider === "string" ? model.provider : "")
|
|
126
|
+
.filter(Boolean))]
|
|
127
|
+
.sort((a, b) => a.localeCompare(b));
|
|
128
|
+
return providers
|
|
129
|
+
.filter((provider) => provider.startsWith(prefix))
|
|
130
|
+
.map((provider) => ({ value: provider, label: provider }));
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
function sendSlashText(pi: ExtensionAPI, text: string): void {
|
|
134
|
+
pi.sendMessage({ customType: SLASH_TEXT_RESULT_TYPE, content: text, display: true });
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function withSlashStatus<T>(
|
|
138
|
+
ctx: ExtensionContext,
|
|
139
|
+
text: string,
|
|
140
|
+
run: () => Promise<T>,
|
|
141
|
+
): Promise<T> {
|
|
142
|
+
if (ctx.hasUI) ctx.ui.setStatus("subagent-slash-text", text);
|
|
143
|
+
try {
|
|
144
|
+
return await run();
|
|
145
|
+
} finally {
|
|
146
|
+
if (ctx.hasUI) ctx.ui.setStatus("subagent-slash-text", undefined);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
type Theme = ExtensionContext["ui"]["theme"];
|
|
151
|
+
|
|
152
|
+
type StopSelectorTarget = {
|
|
153
|
+
kind: "async" | "scheduled";
|
|
154
|
+
id: string;
|
|
155
|
+
label: string;
|
|
156
|
+
detail: string;
|
|
157
|
+
actionLabel: string;
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
type StopSelectorResult = { confirmed: boolean; target?: StopSelectorTarget };
|
|
161
|
+
|
|
162
|
+
function commandForTarget(target: StopSelectorTarget): string {
|
|
163
|
+
return target.kind === "scheduled"
|
|
164
|
+
? `subagent({ action: "schedule.pause", id: ${JSON.stringify(target.id)} })`
|
|
165
|
+
: `subagent({ action: "stop", id: ${JSON.stringify(target.id)} })`;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function formatAsyncStopTarget(run: AsyncRunSummary): StopSelectorTarget {
|
|
169
|
+
const progress = formatAsyncRunProgressLabel(run);
|
|
170
|
+
const cwd = run.cwd ? shortenPath(run.cwd) : shortenPath(run.asyncDir);
|
|
171
|
+
return {
|
|
172
|
+
kind: "async",
|
|
173
|
+
id: run.id,
|
|
174
|
+
label: `${run.id} · ${run.mode} · ${progress}`,
|
|
175
|
+
detail: `${run.state} · ${cwd}`,
|
|
176
|
+
actionLabel: "stop async run",
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function scheduledStopTargets(ctx: ExtensionContext, _state: SubagentState): StopSelectorTarget[] {
|
|
181
|
+
try {
|
|
182
|
+
return listScheduledRunSummaries(ctx.cwd)
|
|
183
|
+
.filter((schedule) => !schedule.paused && !schedule.activeRunId && schedule.trigger.nextRunAt)
|
|
184
|
+
.sort((left, right) => left.trigger.nextRunAt!.localeCompare(right.trigger.nextRunAt!))
|
|
185
|
+
.map((schedule) => ({
|
|
186
|
+
kind: "scheduled" as const,
|
|
187
|
+
id: schedule.id,
|
|
188
|
+
label: `${schedule.id} · ${schedule.name}`,
|
|
189
|
+
detail: `scheduled · ${schedule.trigger.nextRunAt}`,
|
|
190
|
+
actionLabel: "pause schedule",
|
|
191
|
+
}));
|
|
192
|
+
} catch {
|
|
193
|
+
return [];
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function discoverStopTargets(ctx: ExtensionContext, state: SubagentState): StopSelectorTarget[] {
|
|
198
|
+
const sessionId = state.currentSessionId ?? ctx.sessionManager.getSessionId() ?? undefined;
|
|
199
|
+
const asyncTargets = listAsyncRuns(DIRS.async, {
|
|
200
|
+
states: ["queued", "running"],
|
|
201
|
+
...(sessionId ? { sessionId } : {}),
|
|
202
|
+
}).map(formatAsyncStopTarget);
|
|
203
|
+
return [...asyncTargets, ...scheduledStopTargets(ctx, state)];
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function stopFallbackText(targets: StopSelectorTarget[]): string {
|
|
207
|
+
if (targets.length === 0) return "No active current-session async runs or scheduled subagent runs to stop.";
|
|
208
|
+
const lines = ["Subagent stop targets:", ""];
|
|
209
|
+
for (const target of targets) {
|
|
210
|
+
lines.push(`- ${target.label}`);
|
|
211
|
+
lines.push(` ${target.detail}`);
|
|
212
|
+
lines.push(` ${target.actionLabel}: ${commandForTarget(target)}`);
|
|
213
|
+
if (target.kind === "async") lines.push(` slash: /subagents-stop ${target.id}`);
|
|
214
|
+
}
|
|
215
|
+
return lines.join("\n");
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function selectForegroundDetachControl(state: SubagentState, requested: string) {
|
|
219
|
+
const controls = [...state.foregroundControls.values()];
|
|
220
|
+
if (requested) {
|
|
221
|
+
const matches = controls.filter((control) => control.runId === requested || control.runId.startsWith(requested));
|
|
222
|
+
if (matches.length > 1) throw new Error(`Ambiguous foreground run id prefix '${requested}' matched: ${matches.map((control) => control.runId).join(", ")}. Provide a longer id.`);
|
|
223
|
+
return matches[0];
|
|
224
|
+
}
|
|
225
|
+
const singleControls = controls.filter((control) => control.mode === "single");
|
|
226
|
+
if (state.lastForegroundControlId) {
|
|
227
|
+
const latest = state.foregroundControls.get(state.lastForegroundControlId);
|
|
228
|
+
if (latest?.mode === "single") return latest;
|
|
229
|
+
}
|
|
230
|
+
return singleControls.sort((left, right) => right.updatedAt - left.updatedAt)[0];
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
class SubagentsStopSelector implements Component {
|
|
234
|
+
readonly width = 84;
|
|
235
|
+
private selected = 0;
|
|
236
|
+
private confirming = false;
|
|
237
|
+
private readonly tui: TUI;
|
|
238
|
+
private readonly theme: Theme;
|
|
239
|
+
private readonly targets: StopSelectorTarget[];
|
|
240
|
+
private readonly done: (result: StopSelectorResult) => void;
|
|
241
|
+
|
|
242
|
+
constructor(tui: TUI, theme: Theme, targets: StopSelectorTarget[], done: (result: StopSelectorResult) => void) {
|
|
243
|
+
this.tui = tui;
|
|
244
|
+
this.theme = theme;
|
|
245
|
+
this.targets = targets;
|
|
246
|
+
this.done = done;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
handleInput(data: string): void {
|
|
250
|
+
if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
|
|
251
|
+
this.done({ confirmed: false });
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
if (this.confirming) {
|
|
255
|
+
if (matchesKey(data, "return") || data.toLowerCase() === "y") {
|
|
256
|
+
this.done({ confirmed: true, target: this.targets[this.selected] });
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
if (data.toLowerCase() === "n" || matchesKey(data, "backspace")) {
|
|
260
|
+
this.confirming = false;
|
|
261
|
+
this.tui.requestRender();
|
|
262
|
+
}
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
if (matchesKey(data, "up") || matchesKey(data, "k")) {
|
|
266
|
+
this.selected = Math.max(0, this.selected - 1);
|
|
267
|
+
this.tui.requestRender();
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
if (matchesKey(data, "down") || matchesKey(data, "j")) {
|
|
271
|
+
this.selected = Math.min(this.targets.length - 1, this.selected + 1);
|
|
272
|
+
this.tui.requestRender();
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
if (matchesKey(data, "return")) {
|
|
276
|
+
this.confirming = true;
|
|
277
|
+
this.tui.requestRender();
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
invalidate(): void {}
|
|
282
|
+
|
|
283
|
+
render(width: number): string[] {
|
|
284
|
+
const contentWidth = Math.max(0, Math.min(this.width, Math.floor(width)));
|
|
285
|
+
const lines = [this.theme.bold("Stop subagent run"), this.theme.fg("dim", "Select a current-session async run to stop, or a scheduled run to cancel."), ""];
|
|
286
|
+
const maxRows = 10;
|
|
287
|
+
const start = Math.max(0, Math.min(this.selected - maxRows + 1, Math.max(0, this.targets.length - maxRows)));
|
|
288
|
+
for (let index = start; index < Math.min(this.targets.length, start + maxRows); index++) {
|
|
289
|
+
const target = this.targets[index]!;
|
|
290
|
+
const selected = index === this.selected;
|
|
291
|
+
const marker = selected ? "›" : " ";
|
|
292
|
+
const actionLabel = target.actionLabel;
|
|
293
|
+
const action = target.kind === "scheduled" ? this.theme.fg("warning", actionLabel) : this.theme.fg("accent", actionLabel);
|
|
294
|
+
const labelWidth = Math.max(0, contentWidth - marker.length - actionLabel.length - 2);
|
|
295
|
+
lines.push(`${marker} ${action} ${target.label.slice(0, labelWidth)}`);
|
|
296
|
+
if (selected) lines.push(this.theme.fg("dim", ` ${target.detail}`.slice(0, contentWidth)));
|
|
297
|
+
}
|
|
298
|
+
if (this.targets.length > maxRows) lines.push(this.theme.fg("dim", `Showing ${start + 1}-${Math.min(this.targets.length, start + maxRows)} of ${this.targets.length}`));
|
|
299
|
+
lines.push("");
|
|
300
|
+
if (this.confirming) {
|
|
301
|
+
const target = this.targets[this.selected]!;
|
|
302
|
+
lines.push(this.theme.fg("warning", `Confirm: ${target.actionLabel} ${target.id}?`));
|
|
303
|
+
if (target.kind === "async") lines.push(this.theme.fg("dim", "Stop ends this run; use interrupt for a resumable pause."));
|
|
304
|
+
lines.push(this.theme.fg("dim", "Enter/Y confirms · N returns · Esc cancels"));
|
|
305
|
+
} else {
|
|
306
|
+
lines.push(this.theme.fg("dim", "↑↓/jk select · Enter confirm · Esc cancel"));
|
|
307
|
+
}
|
|
308
|
+
return lines.map((line) => truncateToWidth(line, contentWidth));
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function emptyUsage(): Usage {
|
|
313
|
+
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function addUsage(target: Usage, source: Usage): void {
|
|
317
|
+
target.input += source.input;
|
|
318
|
+
target.output += source.output;
|
|
319
|
+
target.cacheRead += source.cacheRead;
|
|
320
|
+
target.cacheWrite += source.cacheWrite;
|
|
321
|
+
target.cost += source.cost;
|
|
322
|
+
target.turns += source.turns;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function usageHasValue(usage: Usage): boolean {
|
|
326
|
+
return usage.input !== 0 || usage.output !== 0 || usage.cacheRead !== 0 || usage.cacheWrite !== 0 || usage.cost !== 0 || usage.turns !== 0;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function assistantUsageFromMessage(message: unknown): Usage | undefined {
|
|
330
|
+
if (!message || typeof message !== "object") return undefined;
|
|
331
|
+
const msg = message as { role?: unknown; usage?: unknown };
|
|
332
|
+
if (msg.role !== "assistant" || !msg.usage || typeof msg.usage !== "object") return undefined;
|
|
333
|
+
const usage = msg.usage as {
|
|
334
|
+
input?: unknown;
|
|
335
|
+
output?: unknown;
|
|
336
|
+
cacheRead?: unknown;
|
|
337
|
+
cacheWrite?: unknown;
|
|
338
|
+
cost?: { total?: unknown };
|
|
339
|
+
};
|
|
340
|
+
return {
|
|
341
|
+
input: typeof usage.input === "number" ? usage.input : 0,
|
|
342
|
+
output: typeof usage.output === "number" ? usage.output : 0,
|
|
343
|
+
cacheRead: typeof usage.cacheRead === "number" ? usage.cacheRead : 0,
|
|
344
|
+
cacheWrite: typeof usage.cacheWrite === "number" ? usage.cacheWrite : 0,
|
|
345
|
+
cost: typeof usage.cost?.total === "number" ? usage.cost.total : 0,
|
|
346
|
+
turns: 1,
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function isSubagentDetails(value: unknown): value is Details {
|
|
351
|
+
if (!value || typeof value !== "object") return false;
|
|
352
|
+
const details = value as { mode?: unknown; results?: unknown };
|
|
353
|
+
return typeof details.mode === "string" && Array.isArray(details.results);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function detailsFromSessionEntry(entry: unknown): Details | undefined {
|
|
357
|
+
if (!entry || typeof entry !== "object") return undefined;
|
|
358
|
+
const record = entry as { type?: unknown; customType?: unknown; details?: unknown; message?: unknown };
|
|
359
|
+
if (record.type === "custom_message" && record.customType === SLASH_RESULT_TYPE) {
|
|
360
|
+
const details = resolveSlashMessageDetails(record.details)?.result.details;
|
|
361
|
+
return isSubagentDetails(details) ? details : undefined;
|
|
362
|
+
}
|
|
363
|
+
if (record.type !== "message" || !record.message || typeof record.message !== "object") return undefined;
|
|
364
|
+
const message = record.message as { role?: unknown; toolName?: unknown; details?: unknown };
|
|
365
|
+
if (message.role !== "toolResult" || message.toolName !== "subagent") return undefined;
|
|
366
|
+
return isSubagentDetails(message.details) ? message.details : undefined;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function formatCostUsage(label: string, usage: Usage): string {
|
|
370
|
+
const extras = [
|
|
371
|
+
usage.cacheRead ? `cache read ${formatTokens(usage.cacheRead)}` : "",
|
|
372
|
+
usage.cacheWrite ? `cache write ${formatTokens(usage.cacheWrite)}` : "",
|
|
373
|
+
usage.turns ? `${usage.turns} turn${usage.turns === 1 ? "" : "s"}` : "",
|
|
374
|
+
].filter(Boolean);
|
|
375
|
+
return `${label}: ↑${formatTokens(usage.input)} ↓${formatTokens(usage.output)} $${usage.cost.toFixed(4)}${extras.length ? ` (${extras.join(", ")})` : ""}`;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function buildSubagentCostReport(ctx: ExtensionContext): string {
|
|
379
|
+
const parent = emptyUsage();
|
|
380
|
+
const childTotal = emptyUsage();
|
|
381
|
+
const total = emptyUsage();
|
|
382
|
+
const children: Array<{ label: string; usage: Usage; sessionFile?: string }> = [];
|
|
383
|
+
for (const entry of ctx.sessionManager.getBranch()) {
|
|
384
|
+
const message = entry.type === "message" ? (entry as { message?: unknown }).message : undefined;
|
|
385
|
+
const parentUsage = assistantUsageFromMessage(message);
|
|
386
|
+
if (parentUsage) addUsage(parent, parentUsage);
|
|
387
|
+
const details = detailsFromSessionEntry(entry);
|
|
388
|
+
if (!details) continue;
|
|
389
|
+
for (const result of details.results) {
|
|
390
|
+
if (!usageHasValue(result.usage)) continue;
|
|
391
|
+
const usage = { ...result.usage };
|
|
392
|
+
children.push({
|
|
393
|
+
label: `Child ${children.length + 1} (${result.agent})`,
|
|
394
|
+
usage,
|
|
395
|
+
...(result.sessionFile ? { sessionFile: result.sessionFile } : {}),
|
|
396
|
+
});
|
|
397
|
+
addUsage(childTotal, usage);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
addUsage(total, parent);
|
|
401
|
+
addUsage(total, childTotal);
|
|
402
|
+
const lines = [
|
|
403
|
+
"Subagent cost",
|
|
404
|
+
"",
|
|
405
|
+
formatCostUsage("Parent", parent),
|
|
406
|
+
];
|
|
407
|
+
if (children.length === 0) {
|
|
408
|
+
lines.push("No subagent child usage found in this session.");
|
|
409
|
+
} else {
|
|
410
|
+
for (const child of children) {
|
|
411
|
+
lines.push(formatCostUsage(child.label, child.usage));
|
|
412
|
+
if (child.sessionFile) lines.push(` Session: ${child.sessionFile}`);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
lines.push("────────────────────────────", formatCostUsage("Children", childTotal), formatCostUsage("Total", total));
|
|
416
|
+
return lines.join("\n");
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function parseSingleRequiredArg(args: string, usage: string): { ok: true; value: string } | { ok: false; message: string } {
|
|
420
|
+
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
421
|
+
if (parts.length !== 1) return { ok: false, message: usage };
|
|
422
|
+
return { ok: true, value: parts[0]! };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function getProfileWorkerModel(profile: { subagents?: { agentOverrides?: Record<string, { model?: string }> } }): string | undefined {
|
|
426
|
+
const model = profile.subagents?.agentOverrides?.worker?.model;
|
|
427
|
+
return typeof model === "string" && model.trim() ? model.trim() : undefined;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
async function requestSlashRun(
|
|
432
|
+
pi: ExtensionAPI,
|
|
433
|
+
ctx: ExtensionContext,
|
|
434
|
+
requestId: string,
|
|
435
|
+
params: SubagentParamsLike,
|
|
436
|
+
): Promise<SlashSubagentResponse> {
|
|
437
|
+
return new Promise((resolve, reject) => {
|
|
438
|
+
let done = false;
|
|
439
|
+
let started = false;
|
|
440
|
+
|
|
441
|
+
const startTimeoutMs = 15_000;
|
|
442
|
+
const startTimeout = setTimeout(() => {
|
|
443
|
+
finish(() => reject(new Error(
|
|
444
|
+
"Slash subagent bridge did not start within 15s. Ensure the extension is loaded correctly.",
|
|
445
|
+
)));
|
|
446
|
+
}, startTimeoutMs);
|
|
447
|
+
|
|
448
|
+
const onStarted = (data: unknown) => {
|
|
449
|
+
if (done || !data || typeof data !== "object") return;
|
|
450
|
+
if ((data as { requestId?: unknown }).requestId !== requestId) return;
|
|
451
|
+
started = true;
|
|
452
|
+
clearTimeout(startTimeout);
|
|
453
|
+
if (ctx.hasUI) ctx.ui.setStatus("subagent-slash", "running...");
|
|
454
|
+
};
|
|
455
|
+
|
|
456
|
+
const onResponse = (data: unknown) => {
|
|
457
|
+
if (done || !data || typeof data !== "object") return;
|
|
458
|
+
const response = data as Partial<SlashSubagentResponse>;
|
|
459
|
+
if (response.requestId !== requestId) return;
|
|
460
|
+
clearTimeout(startTimeout);
|
|
461
|
+
finish(() => resolve(response as SlashSubagentResponse));
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
const onUpdate = (data: unknown) => {
|
|
465
|
+
if (done || !data || typeof data !== "object") return;
|
|
466
|
+
const update = data as SlashSubagentUpdate;
|
|
467
|
+
if (update.requestId !== requestId) return;
|
|
468
|
+
applySlashUpdate(requestId, update);
|
|
469
|
+
if (!ctx.hasUI) return;
|
|
470
|
+
const tool = update.currentTool ? ` ${update.currentTool}` : "";
|
|
471
|
+
const count = update.toolCount ?? 0;
|
|
472
|
+
const liveDetailKey = keyText("app.tools.expand");
|
|
473
|
+
ctx.ui.setStatus("subagent-slash", `${count} tools${tool} | ${liveDetailKey} live detail`);
|
|
474
|
+
};
|
|
475
|
+
|
|
476
|
+
const onTerminalInput = ctx.hasUI
|
|
477
|
+
? ctx.ui.onTerminalInput((input) => {
|
|
478
|
+
if (!matchesKey(input, Key.escape)) return undefined;
|
|
479
|
+
pi.events.emit(SLASH_SUBAGENT_CANCEL_EVENT, { requestId });
|
|
480
|
+
finish(() => reject(new Error("Cancelled")));
|
|
481
|
+
return { consume: true };
|
|
482
|
+
})
|
|
483
|
+
: undefined;
|
|
484
|
+
|
|
485
|
+
const unsubStarted = pi.events.on(SLASH_SUBAGENT_STARTED_EVENT, onStarted);
|
|
486
|
+
const unsubResponse = pi.events.on(SLASH_SUBAGENT_RESPONSE_EVENT, onResponse);
|
|
487
|
+
const unsubUpdate = pi.events.on(SLASH_SUBAGENT_UPDATE_EVENT, onUpdate);
|
|
488
|
+
|
|
489
|
+
const finish = (next: () => void) => {
|
|
490
|
+
if (done) return;
|
|
491
|
+
done = true;
|
|
492
|
+
clearTimeout(startTimeout);
|
|
493
|
+
unsubStarted();
|
|
494
|
+
unsubResponse();
|
|
495
|
+
unsubUpdate();
|
|
496
|
+
onTerminalInput?.();
|
|
497
|
+
next();
|
|
498
|
+
};
|
|
499
|
+
|
|
500
|
+
pi.events.emit(SLASH_SUBAGENT_REQUEST_EVENT, { requestId, params, ctx });
|
|
501
|
+
|
|
502
|
+
// Bridge emits STARTED synchronously during REQUEST emit.
|
|
503
|
+
// If not started, no bridge received the request.
|
|
504
|
+
if (!started && done) return;
|
|
505
|
+
if (!started) {
|
|
506
|
+
finish(() => reject(new Error(
|
|
507
|
+
"No slash subagent bridge responded. Ensure the subagent extension is loaded correctly.",
|
|
508
|
+
)));
|
|
509
|
+
}
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function extractSlashMessageText(content: string | Array<{ type?: string; text?: string }>): string {
|
|
514
|
+
if (typeof content === "string") return content;
|
|
515
|
+
if (!Array.isArray(content)) return "";
|
|
516
|
+
return content
|
|
517
|
+
.filter((part): part is { type: "text"; text: string } => part?.type === "text" && typeof part.text === "string")
|
|
518
|
+
.map((part) => part.text)
|
|
519
|
+
.join("\n");
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
function formatExportPathList(paths: string[]): string {
|
|
523
|
+
return paths.map((file) => `- \`${file}\``).join("\n");
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function collectResultPaths(results: SingleResult[], getPath: (result: SingleResult) => string | undefined): string[] {
|
|
527
|
+
return results
|
|
528
|
+
.map(getPath)
|
|
529
|
+
.filter((file): file is string => typeof file === "string" && file.length > 0);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
function buildSlashExportText(response: SlashSubagentResponse): string {
|
|
533
|
+
const output = extractSlashMessageText(response.result.content) || response.errorText || "(no output)";
|
|
534
|
+
const results = response.result.details?.results ?? [];
|
|
535
|
+
const sessionFiles = collectResultPaths(results, (result) => result.sessionFile);
|
|
536
|
+
const savedOutputs = collectResultPaths(results, (result) => result.savedOutputPath);
|
|
537
|
+
const artifactOutputs = collectResultPaths(results, (result) => result.artifactPaths?.outputPath);
|
|
538
|
+
const sections = ["## Subagent result", output];
|
|
539
|
+
if (sessionFiles.length > 0) sections.push("## Child session exports", formatExportPathList(sessionFiles));
|
|
540
|
+
if (savedOutputs.length > 0) sections.push("## Saved outputs", formatExportPathList(savedOutputs));
|
|
541
|
+
if (artifactOutputs.length > 0) sections.push("## Artifact outputs", formatExportPathList(artifactOutputs));
|
|
542
|
+
return sections.join("\n\n");
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
function persistSlashSessionSnapshot(ctx: ExtensionContext): void {
|
|
546
|
+
try {
|
|
547
|
+
if (!ctx.sessionManager) return;
|
|
548
|
+
const sessionManager = ctx.sessionManager as typeof ctx.sessionManager & {
|
|
549
|
+
_rewriteFile?: () => void;
|
|
550
|
+
flushed?: boolean;
|
|
551
|
+
};
|
|
552
|
+
const sessionFile = sessionManager.getSessionFile();
|
|
553
|
+
if (!sessionFile || typeof sessionManager._rewriteFile !== "function") return;
|
|
554
|
+
fs.mkdirSync(path.dirname(sessionFile), { recursive: true });
|
|
555
|
+
sessionManager._rewriteFile();
|
|
556
|
+
sessionManager.flushed = true;
|
|
557
|
+
} catch (error) {
|
|
558
|
+
console.error("Failed to persist slash session snapshot for export:", error);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
async function runSlashSubagent(
|
|
563
|
+
pi: ExtensionAPI,
|
|
564
|
+
ctx: ExtensionContext,
|
|
565
|
+
params: SubagentParamsLike,
|
|
566
|
+
): Promise<void> {
|
|
567
|
+
if (ctx.hasUI) ctx.ui.setToolsExpanded(false);
|
|
568
|
+
const requestId = randomUUID();
|
|
569
|
+
const initialDetails = buildSlashInitialResult(requestId, params);
|
|
570
|
+
const initialText = extractSlashMessageText(initialDetails.result.content) || "Running subagent...";
|
|
571
|
+
pi.sendMessage({
|
|
572
|
+
customType: SLASH_RESULT_TYPE,
|
|
573
|
+
content: initialText,
|
|
574
|
+
display: true,
|
|
575
|
+
details: initialDetails,
|
|
576
|
+
});
|
|
577
|
+
persistSlashSessionSnapshot(ctx);
|
|
578
|
+
|
|
579
|
+
try {
|
|
580
|
+
const response = await requestSlashRun(pi, ctx, requestId, params);
|
|
581
|
+
const finalDetails = finalizeSlashResult(response);
|
|
582
|
+
pi.sendMessage({
|
|
583
|
+
customType: SLASH_RESULT_TYPE,
|
|
584
|
+
content: buildSlashExportText(response),
|
|
585
|
+
display: !ctx.hasUI,
|
|
586
|
+
details: finalDetails,
|
|
587
|
+
});
|
|
588
|
+
persistSlashSessionSnapshot(ctx);
|
|
589
|
+
if (ctx.hasUI) {
|
|
590
|
+
ctx.ui.setStatus("subagent-slash", undefined);
|
|
591
|
+
}
|
|
592
|
+
if (response.isError && ctx.hasUI) {
|
|
593
|
+
ctx.ui.notify(response.errorText || "Subagent failed", "error");
|
|
594
|
+
}
|
|
595
|
+
} catch (error) {
|
|
596
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
597
|
+
const failedDetails = failSlashResult(requestId, params, message);
|
|
598
|
+
pi.sendMessage({
|
|
599
|
+
customType: SLASH_RESULT_TYPE,
|
|
600
|
+
content: `## Subagent result\n\n${message}`,
|
|
601
|
+
display: !ctx.hasUI,
|
|
602
|
+
details: failedDetails,
|
|
603
|
+
});
|
|
604
|
+
persistSlashSessionSnapshot(ctx);
|
|
605
|
+
if (ctx.hasUI) {
|
|
606
|
+
ctx.ui.setStatus("subagent-slash", undefined);
|
|
607
|
+
}
|
|
608
|
+
if (message === "Cancelled") {
|
|
609
|
+
if (ctx.hasUI) ctx.ui.notify("Cancelled", "warning");
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
if (ctx.hasUI) ctx.ui.notify(message, "error");
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
function launchSlashSubagent(
|
|
617
|
+
pi: ExtensionAPI,
|
|
618
|
+
ctx: ExtensionContext,
|
|
619
|
+
params: SubagentParamsLike,
|
|
620
|
+
): void {
|
|
621
|
+
void runSlashSubagent(pi, ctx, params);
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
function slashRunWorkflowScript(key: string, child: Record<string, unknown>): string {
|
|
625
|
+
return `return runs.run(${JSON.stringify(key)}, ${JSON.stringify(child)})`;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
export function registerSlashCommands(
|
|
629
|
+
pi: ExtensionAPI,
|
|
630
|
+
state: SubagentState,
|
|
631
|
+
): void {
|
|
632
|
+
let fleetOpen = false;
|
|
633
|
+
const showFleet = async (ctx: ExtensionContext) => {
|
|
634
|
+
state.lastUiContext = ctx;
|
|
635
|
+
if (!ctx.hasUI) {
|
|
636
|
+
await runSlashSubagent(pi, ctx, { action: "status", view: "fleet" });
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
if (fleetOpen) {
|
|
640
|
+
ctx.ui.notify("Subagent fleet inspector is already open.", "info");
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
fleetOpen = true;
|
|
644
|
+
try {
|
|
645
|
+
await openSubagentFleet(ctx, state, { asyncDirRoot: DIRS.async, resultsDir: DIRS.results });
|
|
646
|
+
} finally {
|
|
647
|
+
fleetOpen = false;
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
|
|
651
|
+
pi.registerCommand("subagents", {
|
|
652
|
+
description: "Administer subagents: inspect metadata and update models, thinking, or prompts",
|
|
653
|
+
handler: async (args, ctx) => {
|
|
654
|
+
await openSubagentsAdmin(pi, ctx, args);
|
|
655
|
+
},
|
|
656
|
+
});
|
|
657
|
+
|
|
658
|
+
pi.registerCommand("run", {
|
|
659
|
+
description: "Run one subagent through workflowScript: /run agent[output=file] [task] [--bg] [--fork]",
|
|
660
|
+
getArgumentCompletions: makeAgentCompletions(state),
|
|
661
|
+
handler: async (args, ctx) => {
|
|
662
|
+
const { args: cleanedArgs, bg, fork } = extractExecutionFlags(args);
|
|
663
|
+
const input = cleanedArgs.trim();
|
|
664
|
+
const firstSpace = input.indexOf(" ");
|
|
665
|
+
if (!input) { ctx.ui.notify("Usage: /run <agent> [task] [--bg] [--fork]", "error"); return; }
|
|
666
|
+
const { name: agentName, config: inline } = parseAgentToken(firstSpace === -1 ? input : input.slice(0, firstSpace));
|
|
667
|
+
const task = firstSpace === -1 ? "" : input.slice(firstSpace + 1).trim();
|
|
668
|
+
|
|
669
|
+
if (!state.baseCwd) { ctx.ui.notify("Subagent session cwd is not initialized yet", "error"); return; }
|
|
670
|
+
const agents = discoverAgents(state.baseCwd, "both").agents;
|
|
671
|
+
if (!agents.find((a) => a.name === agentName)) { ctx.ui.notify(`Unknown agent: ${agentName}`, "error"); return; }
|
|
672
|
+
|
|
673
|
+
let finalTask = task;
|
|
674
|
+
if (inline.reads && Array.isArray(inline.reads) && inline.reads.length > 0) {
|
|
675
|
+
finalTask = `[Read from: ${inline.reads.join(", ")}]\n\n${finalTask}`;
|
|
676
|
+
}
|
|
677
|
+
const child: Record<string, unknown> = { agent: agentName, task: finalTask, agentScope: "both" };
|
|
678
|
+
if (inline.output !== undefined) child.output = inline.output;
|
|
679
|
+
if (inline.outputMode !== undefined) child.outputMode = inline.outputMode;
|
|
680
|
+
if (inline.skill !== undefined) child.skill = inline.skill;
|
|
681
|
+
if (inline.model) child.model = inline.model;
|
|
682
|
+
if (fork) child.context = "fork";
|
|
683
|
+
launchSlashSubagent(pi, ctx, { workflowScript: slashRunWorkflowScript("run", child), async: bg ? true : false });
|
|
684
|
+
},
|
|
685
|
+
});
|
|
686
|
+
|
|
687
|
+
pi.registerCommand("subagent-cost", {
|
|
688
|
+
description: "Show parent and subagent child usage cost for this session",
|
|
689
|
+
handler: async (_args, ctx) => {
|
|
690
|
+
sendSlashText(pi, buildSubagentCostReport(ctx));
|
|
691
|
+
},
|
|
692
|
+
});
|
|
693
|
+
|
|
694
|
+
pi.registerCommand("subagents-doctor", {
|
|
695
|
+
description: "Show subagent diagnostics",
|
|
696
|
+
handler: async (_args, ctx) => {
|
|
697
|
+
await runSlashSubagent(pi, ctx, { action: "doctor" });
|
|
698
|
+
},
|
|
699
|
+
});
|
|
700
|
+
|
|
701
|
+
pi.registerCommand("subagents-refine", {
|
|
702
|
+
description: "Generate a bounded project-local refinement overlay for one subagent",
|
|
703
|
+
getArgumentCompletions: makeAgentCompletions(state),
|
|
704
|
+
handler: async (args, ctx) => {
|
|
705
|
+
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
706
|
+
if (parts.length !== 1) {
|
|
707
|
+
ctx.ui.notify("Usage: /subagents-refine <agent>", "error");
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
await runSlashSubagent(pi, ctx, { action: "refine", agent: parts[0] });
|
|
711
|
+
},
|
|
712
|
+
});
|
|
713
|
+
|
|
714
|
+
pi.registerCommand("subagents-fleet", {
|
|
715
|
+
description: "Open the live subagent fleet inspector",
|
|
716
|
+
handler: async (_args, ctx) => showFleet(ctx),
|
|
717
|
+
});
|
|
718
|
+
|
|
719
|
+
pi.registerShortcut(Key.ctrlAlt("f"), {
|
|
720
|
+
description: "Open subagent fleet inspector",
|
|
721
|
+
handler: async (ctx) => showFleet(ctx),
|
|
722
|
+
});
|
|
723
|
+
|
|
724
|
+
pi.registerCommand("subagents-detach", {
|
|
725
|
+
description: "Detach the active foreground single-subagent run without terminating it",
|
|
726
|
+
handler: async (args, ctx) => {
|
|
727
|
+
const id = args.trim();
|
|
728
|
+
let control: ReturnType<typeof selectForegroundDetachControl>;
|
|
729
|
+
try {
|
|
730
|
+
control = selectForegroundDetachControl(state, id);
|
|
731
|
+
} catch (error) {
|
|
732
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
if (!control) {
|
|
736
|
+
ctx.ui.notify(id ? `No active foreground run found for '${id}'.` : "No active foreground single-subagent run to detach.", "info");
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
if (control.mode !== "single") {
|
|
740
|
+
ctx.ui.notify("/subagents-detach currently supports single-subagent runs only.", "error");
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
if (!control.detach?.()) {
|
|
744
|
+
ctx.ui.notify(`Foreground run ${control.runId} is not currently detachable.`, "info");
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
sendSlashText(pi, `Detached foreground run ${control.runId} without terminating its child. Use subagent({ action: "status", id: ${JSON.stringify(control.runId)} }) or subagent_wait({ id: ${JSON.stringify(control.runId)} }) to recover the eventual result. This does not daemonize the process or guarantee survival across Pi reload/restart.`);
|
|
748
|
+
},
|
|
749
|
+
});
|
|
750
|
+
|
|
751
|
+
pi.registerCommand("subagents-stop", {
|
|
752
|
+
description: "Stop a current-session async subagent run",
|
|
753
|
+
handler: async (args, ctx) => {
|
|
754
|
+
const id = args.trim();
|
|
755
|
+
if (id) {
|
|
756
|
+
await runSlashSubagent(pi, ctx, { action: "stop", id });
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
if (process.env[SUBAGENT_FANOUT_CHILD_ENV] === "1") {
|
|
761
|
+
sendSlashText(pi, "Selector unavailable in child-safe fanout mode. Pass an explicit current-session top-level async run id, for example `/subagents-stop <run-id>` or `subagent({ action: \"stop\", id: \"<run-id>\" })`.");
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
let targets: StopSelectorTarget[];
|
|
766
|
+
try {
|
|
767
|
+
targets = discoverStopTargets(ctx, state);
|
|
768
|
+
} catch (error) {
|
|
769
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
770
|
+
ctx.ui.notify(message, "error");
|
|
771
|
+
return;
|
|
772
|
+
}
|
|
773
|
+
if (!ctx.hasUI) {
|
|
774
|
+
sendSlashText(pi, stopFallbackText(targets));
|
|
775
|
+
return;
|
|
776
|
+
}
|
|
777
|
+
if (targets.length === 0) {
|
|
778
|
+
ctx.ui.notify("No active current-session async runs or scheduled subagent runs to stop.", "info");
|
|
779
|
+
return;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
const result = await ctx.ui.custom<StopSelectorResult>(
|
|
783
|
+
(tui, theme, _kb, done) => new SubagentsStopSelector(tui, theme, targets, done),
|
|
784
|
+
{ overlay: true, overlayOptions: { anchor: "center", width: 88, maxHeight: "80%" } },
|
|
785
|
+
);
|
|
786
|
+
if (!result?.confirmed || !result.target) return;
|
|
787
|
+
if (result.target.kind === "scheduled") {
|
|
788
|
+
await runSlashSubagent(pi, ctx, { action: "schedule.pause", id: result.target.id });
|
|
789
|
+
return;
|
|
790
|
+
}
|
|
791
|
+
await runSlashSubagent(pi, ctx, { action: "stop", id: result.target.id });
|
|
792
|
+
},
|
|
793
|
+
});
|
|
794
|
+
|
|
795
|
+
registerPromptWorkflowCommands({
|
|
796
|
+
pi,
|
|
797
|
+
run: async (params, ctx) => {
|
|
798
|
+
launchSlashSubagent(pi, ctx, params);
|
|
799
|
+
},
|
|
800
|
+
});
|
|
801
|
+
|
|
802
|
+
pi.registerCommand("subagents-models", {
|
|
803
|
+
description: "Show runtime-loaded builtin subagent models",
|
|
804
|
+
getArgumentCompletions: makeBuiltinAgentNameCompletions(),
|
|
805
|
+
handler: async (args, ctx) => {
|
|
806
|
+
const trimmed = args.trim();
|
|
807
|
+
if (!trimmed) {
|
|
808
|
+
await runSlashSubagent(pi, ctx, { action: "models" });
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
const parts = trimmed.split(/\s+/).filter(Boolean);
|
|
812
|
+
if (parts.length !== 1) {
|
|
813
|
+
ctx.ui.notify("Usage: /subagents-models [builtin-agent-name]", "error");
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
const agent = parts[0]!;
|
|
817
|
+
if (!(BUILTIN_AGENT_NAMES as readonly string[]).includes(agent)) {
|
|
818
|
+
ctx.ui.notify(`Unknown builtin agent: ${agent}`, "error");
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
await runSlashSubagent(pi, ctx, { action: "models", agent });
|
|
822
|
+
},
|
|
823
|
+
});
|
|
824
|
+
|
|
825
|
+
pi.registerCommand("subagents-profiles", {
|
|
826
|
+
description: "List saved subagent profiles",
|
|
827
|
+
handler: async (_args, _ctx) => {
|
|
828
|
+
const profiles = listSubagentProfiles();
|
|
829
|
+
if (profiles.length === 0) {
|
|
830
|
+
sendSlashText(pi, "Subagent profiles\n\nNo subagent profiles found in ~/.pi/agent/profiles/pi-subagents/");
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
sendSlashText(pi, `Subagent profiles\n\n${profiles.join("\n")}`);
|
|
834
|
+
},
|
|
835
|
+
});
|
|
836
|
+
|
|
837
|
+
pi.registerCommand("subagents-load-profile", {
|
|
838
|
+
description: "Load a subagent profile into ~/.pi/agent/settings.json",
|
|
839
|
+
getArgumentCompletions: (prefix) => {
|
|
840
|
+
if (prefix.includes(" ")) return null;
|
|
841
|
+
return listSubagentProfiles()
|
|
842
|
+
.filter((name) => name.startsWith(prefix))
|
|
843
|
+
.map((name) => ({ value: name, label: name }));
|
|
844
|
+
},
|
|
845
|
+
handler: async (args, ctx) => {
|
|
846
|
+
const parsed = parseSingleRequiredArg(args, "Usage: /subagents-load-profile <name>");
|
|
847
|
+
if (parsed.ok === false) {
|
|
848
|
+
ctx.ui.notify(parsed.message, "error");
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
try {
|
|
852
|
+
await withSlashStatus(ctx, `Loading profile ${parsed.value}…`, async () => {
|
|
853
|
+
const { profile } = readSubagentProfile(parsed.value);
|
|
854
|
+
const workerModel = getProfileWorkerModel(profile);
|
|
855
|
+
const result = applySubagentProfile(parsed.value);
|
|
856
|
+
const lines = [
|
|
857
|
+
`Loaded subagent profile: ${parsed.value}`,
|
|
858
|
+
`Profile: ${result.filePath}`,
|
|
859
|
+
`Updated: ${result.settingsPath}`,
|
|
860
|
+
];
|
|
861
|
+
|
|
862
|
+
if (workerModel && typeof pi.setModel === "function" && typeof ctx.modelRegistry?.find === "function" && typeof ctx.modelRegistry?.getAvailable === "function") {
|
|
863
|
+
const shouldSwitch = await ctx.ui.confirm(
|
|
864
|
+
"",
|
|
865
|
+
`Profile loaded. Also switch this session to the profile worker model?\n\n${workerModel}`,
|
|
866
|
+
);
|
|
867
|
+
if (shouldSwitch) {
|
|
868
|
+
const modelInfo = findModelInfo(workerModel, ctx.modelRegistry.getAvailable().map(toModelInfo));
|
|
869
|
+
const model = modelInfo ? ctx.modelRegistry.find(modelInfo.provider, modelInfo.id) : undefined;
|
|
870
|
+
if (!modelInfo || !model) {
|
|
871
|
+
lines.push(`Could not switch current session model: '${workerModel}' is not available in the current model registry.`);
|
|
872
|
+
} else {
|
|
873
|
+
const success = await pi.setModel(model);
|
|
874
|
+
if (success) lines.push(`Current session model switched to: ${modelInfo.fullId}`);
|
|
875
|
+
else lines.push(`Could not switch current session model to '${workerModel}': no API key or provider access is available.`);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
} else if (workerModel) {
|
|
879
|
+
lines.push(`Profile worker model: ${workerModel}`);
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
sendSlashText(pi, lines.join("\n"));
|
|
883
|
+
});
|
|
884
|
+
} catch (error) {
|
|
885
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
886
|
+
}
|
|
887
|
+
},
|
|
888
|
+
});
|
|
889
|
+
|
|
890
|
+
pi.registerCommand("subagents-refresh-provider-models", {
|
|
891
|
+
description: "Refresh the cached model catalog for one provider",
|
|
892
|
+
getArgumentCompletions: makeProviderCompletions(state),
|
|
893
|
+
handler: async (args, ctx) => {
|
|
894
|
+
const trimmed = args.trim();
|
|
895
|
+
const force = /(?:^|\s)--force$/.test(trimmed) || /(?:^|\s)force$/.test(trimmed);
|
|
896
|
+
const withoutForce = trimmed.replace(/(?:^|\s)(?:--force|force)$/, "").trim();
|
|
897
|
+
const parsed = parseSingleRequiredArg(withoutForce, "Usage: /subagents-refresh-provider-models <provider> [--force]");
|
|
898
|
+
if (parsed.ok === false) {
|
|
899
|
+
ctx.ui.notify(parsed.message, "error");
|
|
900
|
+
return;
|
|
901
|
+
}
|
|
902
|
+
try {
|
|
903
|
+
await withSlashStatus(ctx, `Refreshing provider models for ${parsed.value}…`, async () => {
|
|
904
|
+
const result = await refreshProviderModelCatalog(pi, ctx, parsed.value, { force, maxAgeDays: DEFAULT_PROVIDER_MODELS_MAX_AGE_DAYS });
|
|
905
|
+
const lines = [
|
|
906
|
+
"Provider model catalog",
|
|
907
|
+
`Provider: ${parsed.value}`,
|
|
908
|
+
`Status: ${result.reused ? "fresh cache reused" : "refreshed"}`,
|
|
909
|
+
`File: ${result.filePath}`,
|
|
910
|
+
`Models: ${result.catalog.models.length}`,
|
|
911
|
+
`Refreshed at: ${result.catalog.refreshedAt}`,
|
|
912
|
+
];
|
|
913
|
+
if (result.heuristicFallbackCount > 0) {
|
|
914
|
+
lines.push(`Warning: ${result.heuristicFallbackCount} model${result.heuristicFallbackCount === 1 ? " was" : "s were"} classified with name heuristics fallback.`);
|
|
915
|
+
}
|
|
916
|
+
sendSlashText(pi, lines.join("\n"));
|
|
917
|
+
});
|
|
918
|
+
} catch (error) {
|
|
919
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
920
|
+
}
|
|
921
|
+
},
|
|
922
|
+
});
|
|
923
|
+
|
|
924
|
+
pi.registerCommand("subagents-generate-profiles", {
|
|
925
|
+
description: "Generate <provider>.quota and <provider>.quality subagent profiles",
|
|
926
|
+
getArgumentCompletions: makeProviderCompletions(state),
|
|
927
|
+
handler: async (args, ctx) => {
|
|
928
|
+
const parsed = parseSingleRequiredArg(args, "Usage: /subagents-generate-profiles <provider>");
|
|
929
|
+
if (parsed.ok === false) {
|
|
930
|
+
ctx.ui.notify(parsed.message, "error");
|
|
931
|
+
return;
|
|
932
|
+
}
|
|
933
|
+
try {
|
|
934
|
+
await withSlashStatus(ctx, `Generating profiles for ${parsed.value}…`, async () => {
|
|
935
|
+
const result = await generateProfilesForProvider(pi, ctx, parsed.value, { maxAgeDays: DEFAULT_PROVIDER_MODELS_MAX_AGE_DAYS });
|
|
936
|
+
const lines = [
|
|
937
|
+
"Generated subagent profiles",
|
|
938
|
+
`Provider: ${parsed.value}`,
|
|
939
|
+
`Catalog: ${result.catalogPath}`,
|
|
940
|
+
`Quota: ${result.quotaPath}`,
|
|
941
|
+
` cheap=${result.quotaModels.cheap}`,
|
|
942
|
+
` medium=${result.quotaModels.medium}`,
|
|
943
|
+
` strong=${result.quotaModels.strong}`,
|
|
944
|
+
`Quality: ${result.qualityPath}`,
|
|
945
|
+
` cheap=${result.qualityModels.cheap}`,
|
|
946
|
+
` medium=${result.qualityModels.medium}`,
|
|
947
|
+
` strong=${result.qualityModels.strong}`,
|
|
948
|
+
];
|
|
949
|
+
if (result.selectedHeuristicFallbackCount > 0) {
|
|
950
|
+
lines.push(`Warning: generated profiles depend on heuristic-only classification for ${result.selectedHeuristicFallbackCount} selected model${result.selectedHeuristicFallbackCount === 1 ? "" : "s"}.`);
|
|
951
|
+
} else if (result.heuristicFallbackCount > 0) {
|
|
952
|
+
lines.push(`Warning: provider catalog still contains ${result.heuristicFallbackCount} heuristic-classified model${result.heuristicFallbackCount === 1 ? "" : "s"}.`);
|
|
953
|
+
}
|
|
954
|
+
sendSlashText(pi, lines.join("\n"));
|
|
955
|
+
});
|
|
956
|
+
} catch (error) {
|
|
957
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
958
|
+
}
|
|
959
|
+
},
|
|
960
|
+
});
|
|
961
|
+
|
|
962
|
+
pi.registerCommand("subagents-check-profile", {
|
|
963
|
+
description: "Check whether a saved profile still points to usable models",
|
|
964
|
+
getArgumentCompletions: (prefix) => {
|
|
965
|
+
if (prefix.includes(" ")) return null;
|
|
966
|
+
return listSubagentProfiles()
|
|
967
|
+
.filter((name) => name.startsWith(prefix))
|
|
968
|
+
.map((name) => ({ value: name, label: name }));
|
|
969
|
+
},
|
|
970
|
+
handler: async (args, ctx) => {
|
|
971
|
+
const parsed = parseSingleRequiredArg(args, "Usage: /subagents-check-profile <name>");
|
|
972
|
+
if (parsed.ok === false) {
|
|
973
|
+
ctx.ui.notify(parsed.message, "error");
|
|
974
|
+
return;
|
|
975
|
+
}
|
|
976
|
+
try {
|
|
977
|
+
await withSlashStatus(ctx, `Checking profile ${parsed.value}…`, async () => {
|
|
978
|
+
const result = await checkSubagentProfile(pi, ctx, parsed.value);
|
|
979
|
+
const lines = [
|
|
980
|
+
"Subagent profile check",
|
|
981
|
+
`Profile: ${result.profileName}`,
|
|
982
|
+
`File: ${result.filePath}`,
|
|
983
|
+
"",
|
|
984
|
+
...result.results.map((entry) => `${entry.agent} → ${entry.model} — registry ${entry.inRegistry ? "ok" : "missing"}; probe ${entry.probe.status}${entry.probe.message ? ` (${entry.probe.message.split(/\r?\n/, 1)[0]})` : ""}`),
|
|
985
|
+
];
|
|
986
|
+
sendSlashText(pi, lines.join("\n"));
|
|
987
|
+
});
|
|
988
|
+
} catch (error) {
|
|
989
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
990
|
+
}
|
|
991
|
+
},
|
|
992
|
+
});
|
|
993
|
+
|
|
994
|
+
}
|