@xzzpig/pi-subagents 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +443 -0
- package/README.md +2 -2
- package/agents/claude-code-writer.md +15 -0
- package/agents/claude-code.md +15 -0
- package/agents/codex-exec-writer.md +15 -0
- package/agents/codex-exec.md +15 -0
- package/agents/cursor-agent-writer.md +14 -0
- package/agents/cursor-agent.md +14 -0
- package/agents/reviewer.md +1 -1
- package/agents/scout.md +1 -1
- package/docs/agents.md +151 -39
- package/docs/configuration.md +81 -22
- package/docs/extension-api.md +69 -14
- package/docs/missions.md +2 -0
- package/docs/models.md +32 -9
- package/docs/observability.md +22 -20
- package/docs/tool-reference.md +123 -14
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +142 -4
- package/install.mjs +1 -1
- package/package.json +5 -4
- package/prompts/review-loop.md +2 -2
- package/skills/council-mode/SKILL.md +48 -243
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +89 -35
- package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
- package/skills/pi-subagents/references/execution-controls.md +91 -15
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +370 -114
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +12 -2
- package/src/agents/agents.ts +919 -372
- package/src/agents/builtin-names.ts +6 -0
- package/src/agents/runtime-agent-events.ts +70 -0
- package/src/agents/runtime-agent-registry.ts +31 -20
- package/src/api/agents.ts +10 -5
- package/src/api/background-work.ts +12 -3
- package/src/api/capability-ceiling.ts +0 -1
- package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
- package/src/api/delegation.ts +0 -7
- package/src/api/external-runs.ts +67 -4
- package/src/api/preflight.ts +48 -18
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +5 -13
- package/src/extension/fanout-child.ts +14 -14
- package/src/extension/index.ts +115 -37
- package/src/extension/public-execution.ts +103 -15
- package/src/extension/rpc.ts +120 -25
- package/src/extension/schemas.ts +57 -21
- package/src/extension/tool-description.ts +48 -26
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +51 -3
- package/src/intercom/native-supervisor-channel.ts +138 -60
- package/src/intercom/result-intercom.ts +2 -0
- package/src/intercom/supervisor-ui.ts +243 -0
- package/src/profiles/profiles.ts +5 -6
- package/src/runs/background/active-async-capacity.ts +103 -18
- package/src/runs/background/async-execution.ts +366 -128
- package/src/runs/background/async-job-tracker.ts +95 -15
- package/src/runs/background/async-resume.ts +45 -28
- package/src/runs/background/async-retention.ts +20 -3
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +189 -14
- package/src/runs/background/auto-drain.ts +1 -1
- package/src/runs/background/chain-append.ts +8 -3
- package/src/runs/background/chain-root-attachment.ts +74 -8
- package/src/runs/background/control-channel.ts +4 -205
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +238 -12
- package/src/runs/background/process-terminal.ts +16 -0
- package/src/runs/background/result-delivery-ownership.ts +45 -0
- package/src/runs/background/result-files.ts +28 -14
- package/src/runs/background/result-watcher.ts +39 -16
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/retained-children.ts +1 -1
- package/src/runs/background/run-child-session.ts +613 -0
- package/src/runs/background/run-status.ts +84 -17
- package/src/runs/background/runner-aliases.ts +125 -0
- package/src/runs/background/runner-child-sessions.ts +31 -0
- package/src/runs/background/scheduled-runs.ts +174 -18
- package/src/runs/background/stale-run-reconciler.ts +10 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +676 -1161
- package/src/runs/background/subagent-wait.ts +86 -31
- package/src/runs/background/terminal-run-index.ts +1 -1
- package/src/runs/background/wait-completions.ts +43 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +26 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/execution.ts +468 -499
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +23 -1
- package/src/runs/foreground/subagent-executor.ts +1172 -400
- package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
- package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
- package/src/runs/shared/abort-recovery.ts +119 -0
- package/src/runs/shared/acceptance.ts +138 -36
- package/src/runs/shared/async-status-projection.ts +565 -0
- package/src/runs/shared/background-process-options.ts +9 -0
- package/src/runs/shared/capability-ceiling.ts +2 -2
- package/src/runs/shared/child-hooks.ts +25 -0
- package/src/runs/shared/child-identity.ts +32 -6
- package/src/runs/shared/child-launch-plan.ts +151 -0
- package/src/runs/shared/child-launch.ts +314 -0
- package/src/runs/shared/child-lifecycle.ts +25 -0
- package/src/runs/shared/child-runtime-config.ts +126 -0
- package/src/runs/shared/child-session.ts +342 -0
- package/src/runs/shared/child-tool-plan.ts +540 -0
- package/src/runs/shared/claude-code-adapter.ts +133 -0
- package/src/runs/shared/codex-exec-adapter.ts +129 -0
- package/src/runs/shared/completion-evidence.ts +89 -0
- package/src/runs/shared/completion-guard.ts +6 -5
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +3 -3
- package/src/runs/shared/external-cli-contract.ts +167 -0
- package/src/runs/shared/external-cli-preflight.ts +138 -0
- package/src/runs/shared/external-cli-runner.ts +348 -55
- package/src/runs/shared/fast-mode-extension.ts +5 -5
- package/src/runs/shared/host-step-status.ts +231 -0
- package/src/runs/shared/lane-metadata.ts +126 -0
- package/src/runs/shared/launch-cwd.ts +16 -0
- package/src/runs/shared/long-running-guard.ts +2 -1
- package/src/runs/shared/mcp-config-sources.ts +422 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
- package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
- package/src/runs/shared/model-exclusions.ts +139 -9
- package/src/runs/shared/model-fallback.ts +142 -14
- package/src/runs/shared/mutation-evidence.ts +57 -3
- package/src/runs/shared/nested-events.ts +38 -48
- package/src/runs/shared/nested-path.ts +0 -14
- package/src/runs/shared/nested-render.ts +9 -5
- package/src/runs/shared/orca-progress-tabs.ts +12 -7
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +15 -7
- package/src/runs/shared/permissions.ts +1 -14
- package/src/runs/shared/pi-spawn.ts +69 -35
- package/src/runs/shared/process-signal.ts +16 -0
- package/src/runs/shared/run-fanout-budget.ts +0 -13
- package/src/runs/shared/run-history.ts +21 -1
- package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
- package/src/runs/shared/single-output.ts +89 -22
- package/src/runs/shared/structured-output.ts +49 -9
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -62
- package/src/runs/shared/tool-budget.ts +0 -14
- package/src/runs/shared/tool-timeout.ts +1 -1
- package/src/runs/shared/workflow-graph.ts +16 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
- package/src/runs/shared/worktree.ts +571 -62
- package/src/shared/atomic-json.ts +3 -1
- package/src/shared/child-session-name.ts +46 -0
- package/src/shared/extension-context.ts +24 -0
- package/src/shared/fork-context.ts +21 -12
- package/src/shared/fork-session-cwd.ts +27 -0
- package/src/shared/formatters.ts +18 -3
- package/src/shared/jsonl-writer.ts +11 -0
- package/src/shared/launch-contract.ts +8 -1
- package/src/shared/pruned-fork.ts +450 -0
- package/src/shared/session-file-trust.ts +19 -0
- package/src/shared/session-tokens.ts +14 -3
- package/src/shared/settings.ts +19 -105
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +0 -6
- package/src/shared/types.ts +524 -70
- package/src/shared/utils.ts +60 -93
- package/src/shared/workflow-child-permit.ts +207 -0
- package/src/slash/delegation-adapters.ts +1 -9
- package/src/slash/delegation-request.ts +0 -4
- package/src/slash/prompt-template-bridge.ts +37 -1
- package/src/slash/slash-bridge.ts +1 -2
- package/src/slash/slash-commands.ts +383 -116
- package/src/slash/slash-live-state.ts +22 -11
- package/src/slash/subagents-admin.ts +29 -12
- package/src/tui/fleet-native-transcript.ts +4 -0
- package/src/tui/fleet-status.ts +217 -82
- package/src/tui/fleet-transcript.ts +11 -5
- package/src/tui/fleet.ts +54 -28
- package/src/tui/render-helpers.ts +31 -0
- package/src/tui/render.ts +1429 -163
- package/src/watchdog/change-signature.ts +40 -1
- package/src/watchdog/child-status.ts +54 -34
- package/src/watchdog/diff-tool.ts +77 -0
- package/src/watchdog/emission-guard.ts +5 -3
- package/src/watchdog/guidance.ts +20 -0
- package/src/watchdog/register-child.ts +28 -25
- package/src/watchdog/register-main.ts +10 -9
- package/src/watchdog/render.ts +4 -5
- package/src/watchdog/review.ts +15 -4
- package/src/watchdog/rules.ts +70 -0
- package/src/watchdog/runtime.ts +75 -92
- package/src/watchdog/scope.ts +0 -11
- package/src/watchdog/settings.ts +48 -104
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/watchdog/types.ts +18 -32
- package/src/watchdog/warning-format.ts +0 -1
- package/src/workflows/chat-progress.ts +7 -3
- package/src/workflows/host-command.ts +235 -0
- package/src/workflows/scripted-workflow.ts +988 -59
- package/src/workflows/workflow-checklist.ts +439 -0
- package/src/workflows/workflow-child-summary.ts +121 -0
- package/src/workflows/workflow-preflight.ts +297 -0
- package/src/workflows/workflow-receipt.ts +232 -6
- package/src/workflows/workflow-resources.ts +150 -0
- package/src/workflows/workflow-settlement.ts +246 -0
- package/src/runs/shared/child-protocol.ts +0 -401
- package/src/runs/shared/pi-args.ts +0 -935
- package/src/runs/shared/subagent-startup-retry.ts +0 -116
- package/src/runs/shared/turn-budget.ts +0 -98
- package/src/shared/post-exit-stdio-guard.ts +0 -85
|
@@ -3,7 +3,7 @@ import * as fs from "node:fs";
|
|
|
3
3
|
import * as path from "node:path";
|
|
4
4
|
import { keyText, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
5
5
|
import { Key, matchesKey, truncateToWidth, type Component, type KeyId, type TUI } from "@earendil-works/pi-tui";
|
|
6
|
-
import {
|
|
6
|
+
import { discoverAgentSnapshot, discoverAgents, findBlockingAgentDiagnostic, formatUnknownAgentError, resolveAgentName, unknownAgentDiagnosticContext, type AgentConfig, type AgentDiscoveryDiagnostic, type AgentScope, type UnknownAgentDiagnosticContext } from "../agents/agents.ts";
|
|
7
7
|
import { listRuntimeAgentConfigs, mergeRuntimeAgents } from "../agents/runtime-agent-registry.ts";
|
|
8
8
|
import { resolveExistingReadPaths } from "../shared/settings.ts";
|
|
9
9
|
import {
|
|
@@ -21,7 +21,11 @@ import { formatTokens, shortenPath } from "../shared/formatters.ts";
|
|
|
21
21
|
import { listAsyncRuns, formatAsyncRunProgressLabel, type AsyncRunSummary } from "../runs/background/async-status.ts";
|
|
22
22
|
import { encodeInspectReply, handleInspectRpcArgs, INSPECT_WIDGET_KEY } from "../runs/background/inspect-rpc.ts";
|
|
23
23
|
import { listScheduledRunSummaries } from "../runs/background/scheduled-runs.ts";
|
|
24
|
-
import {
|
|
24
|
+
import { resolveAsyncStatusChild } from "../runs/shared/child-identity.ts";
|
|
25
|
+
import { readStatus } from "../shared/utils.ts";
|
|
26
|
+
import { getArtifactPaths, getArtifactsDir } from "../shared/artifacts.ts";
|
|
27
|
+
import { readWorkflowReceipt } from "../workflows/workflow-receipt.ts";
|
|
28
|
+
import { FLEET_OPEN_SHORTCUT } from "../shared/shortcuts.ts";
|
|
25
29
|
import type { SlashSubagentResponse, SlashSubagentUpdate } from "./slash-bridge.ts";
|
|
26
30
|
import { registerPromptWorkflowCommands } from "./prompt-workflows.ts";
|
|
27
31
|
import { openSubagentsAdmin } from "./subagents-admin.ts";
|
|
@@ -45,7 +49,6 @@ import {
|
|
|
45
49
|
DIRS,
|
|
46
50
|
type Details,
|
|
47
51
|
type FleetKeybindingsConfig,
|
|
48
|
-
type JsonSchemaObject,
|
|
49
52
|
type SingleResult,
|
|
50
53
|
type SubagentState,
|
|
51
54
|
type Usage,
|
|
@@ -108,17 +111,22 @@ const extractExecutionFlags = (rawArgs: string): { args: string; bg: boolean; fo
|
|
|
108
111
|
return { args, bg, fork };
|
|
109
112
|
};
|
|
110
113
|
|
|
111
|
-
function discoverSlashAgents(pi: ExtensionAPI, cwd: string, scope: AgentScope): { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[] } {
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
114
|
+
function discoverSlashAgents(pi: ExtensionAPI, cwd: string, scope: AgentScope): { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[]; unknownAgentDiagnosticContext: UnknownAgentDiagnosticContext } {
|
|
115
|
+
if (listRuntimeAgentConfigs(pi).length === 0) {
|
|
116
|
+
const discovered = discoverAgents(cwd, scope);
|
|
117
|
+
return { ...discovered, unknownAgentDiagnosticContext: unknownAgentDiagnosticContext(discovered) };
|
|
118
|
+
}
|
|
119
|
+
const snapshot = discoverAgentSnapshot(cwd, scope, undefined, { includeChains: false });
|
|
120
|
+
const discovered = snapshot.effective;
|
|
121
|
+
const all = snapshot.all;
|
|
115
122
|
const configuredAgents: AgentConfig[] = [
|
|
116
123
|
...all.builtin,
|
|
117
124
|
...all.package,
|
|
118
125
|
...(scope !== "project" ? all.user : []),
|
|
119
126
|
...(scope !== "user" ? all.project : []),
|
|
120
127
|
];
|
|
121
|
-
|
|
128
|
+
const merged = mergeRuntimeAgents(pi, discovered, configuredAgents);
|
|
129
|
+
return { ...merged, unknownAgentDiagnosticContext: { ...unknownAgentDiagnosticContext(discovered), agents: merged.agents } };
|
|
122
130
|
}
|
|
123
131
|
|
|
124
132
|
const makeAgentCompletions = (pi: ExtensionAPI, state: SubagentState) => (prefix: string) => {
|
|
@@ -128,13 +136,6 @@ const makeAgentCompletions = (pi: ExtensionAPI, state: SubagentState) => (prefix
|
|
|
128
136
|
.map((agent) => ({ value: agent.name, label: agent.name }));
|
|
129
137
|
};
|
|
130
138
|
|
|
131
|
-
const makeBuiltinAgentNameCompletions = () => (prefix: string) => {
|
|
132
|
-
if (prefix.includes(" ")) return null;
|
|
133
|
-
return BUILTIN_AGENT_NAMES
|
|
134
|
-
.filter((name) => name.startsWith(prefix))
|
|
135
|
-
.map((name) => ({ value: name, label: name }));
|
|
136
|
-
};
|
|
137
|
-
|
|
138
139
|
const makeProviderCompletions = (state: SubagentState) => (prefix: string) => {
|
|
139
140
|
if (prefix.includes(" ")) return null;
|
|
140
141
|
const available = state.lastUiContext?.modelRegistry?.getAvailable?.();
|
|
@@ -344,25 +345,60 @@ function usageHasValue(usage: Usage): boolean {
|
|
|
344
345
|
return usage.input !== 0 || usage.output !== 0 || usage.cacheRead !== 0 || usage.cacheWrite !== 0 || usage.cost !== 0 || usage.turns !== 0;
|
|
345
346
|
}
|
|
346
347
|
|
|
348
|
+
function nonNegativeNumber(value: unknown): number | undefined {
|
|
349
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function usageFromValue(value: unknown, turnsOverride?: number): Usage | undefined {
|
|
353
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
354
|
+
const record = value as Record<string, unknown>;
|
|
355
|
+
const costValue = typeof record.cost === "object" && record.cost !== null && !Array.isArray(record.cost)
|
|
356
|
+
? (record.cost as Record<string, unknown>).total
|
|
357
|
+
: record.cost;
|
|
358
|
+
const turnsValue = turnsOverride ?? record.turns;
|
|
359
|
+
const usage = {
|
|
360
|
+
input: nonNegativeNumber(record.input) ?? 0,
|
|
361
|
+
output: nonNegativeNumber(record.output) ?? 0,
|
|
362
|
+
cacheRead: nonNegativeNumber(record.cacheRead) ?? 0,
|
|
363
|
+
cacheWrite: nonNegativeNumber(record.cacheWrite) ?? 0,
|
|
364
|
+
cost: nonNegativeNumber(costValue) ?? 0,
|
|
365
|
+
turns: nonNegativeNumber(turnsValue) ?? 0,
|
|
366
|
+
};
|
|
367
|
+
return Number.isSafeInteger(usage.turns) ? usage : undefined;
|
|
368
|
+
}
|
|
369
|
+
|
|
347
370
|
function assistantUsageFromMessage(message: unknown): Usage | undefined {
|
|
348
371
|
if (!message || typeof message !== "object") return undefined;
|
|
349
372
|
const msg = message as { role?: unknown; usage?: unknown };
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
373
|
+
return msg.role === "assistant" ? usageFromValue(msg.usage, 1) : undefined;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function compactionUsageFromEntry(entry: unknown): Usage | undefined {
|
|
377
|
+
if (!entry || typeof entry !== "object") return undefined;
|
|
378
|
+
const record = entry as { type?: unknown; usage?: unknown };
|
|
379
|
+
return record.type === "compaction" ? usageFromValue(record.usage, 0) : undefined;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const MAX_USAGE_METADATA_BYTES = 2 * 1024 * 1024;
|
|
383
|
+
|
|
384
|
+
function readUsageMetadata(metadataPath: string): Record<string, unknown> | undefined {
|
|
385
|
+
let fd: number | undefined;
|
|
386
|
+
try {
|
|
387
|
+
fd = fs.openSync(metadataPath, "r");
|
|
388
|
+
const stat = fs.fstatSync(fd);
|
|
389
|
+
if (!stat.isFile() || stat.size > MAX_USAGE_METADATA_BYTES) return undefined;
|
|
390
|
+
const buffer = Buffer.allocUnsafe(stat.size);
|
|
391
|
+
let offset = 0;
|
|
392
|
+
while (offset < buffer.length) {
|
|
393
|
+
const bytesRead = fs.readSync(fd, buffer, offset, buffer.length - offset, null);
|
|
394
|
+
if (bytesRead <= 0) return undefined;
|
|
395
|
+
offset += bytesRead;
|
|
396
|
+
}
|
|
397
|
+
const value: unknown = JSON.parse(buffer.toString("utf-8"));
|
|
398
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
|
|
399
|
+
} finally {
|
|
400
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
401
|
+
}
|
|
366
402
|
}
|
|
367
403
|
|
|
368
404
|
function isSubagentDetails(value: unknown): value is Details {
|
|
@@ -380,10 +416,32 @@ function detailsFromSessionEntry(entry: unknown): Details | undefined {
|
|
|
380
416
|
}
|
|
381
417
|
if (record.type !== "message" || !record.message || typeof record.message !== "object") return undefined;
|
|
382
418
|
const message = record.message as { role?: unknown; toolName?: unknown; details?: unknown };
|
|
383
|
-
if (message.role !== "toolResult" || message.toolName !== "subagent") return undefined;
|
|
419
|
+
if (message.role !== "toolResult" || (message.toolName !== "subagent" && message.toolName !== "bg_wait")) return undefined;
|
|
384
420
|
return isSubagentDetails(message.details) ? message.details : undefined;
|
|
385
421
|
}
|
|
386
422
|
|
|
423
|
+
function metadataUsage(
|
|
424
|
+
artifactsDirs: string[],
|
|
425
|
+
input: { runId: string; agent: string },
|
|
426
|
+
): Usage | undefined {
|
|
427
|
+
if (!/^[A-Za-z0-9._-]+$/.test(input.runId)) return undefined;
|
|
428
|
+
for (const artifactsDir of artifactsDirs) {
|
|
429
|
+
for (const index of [0, undefined] as const) {
|
|
430
|
+
const metadataPath = getArtifactPaths(artifactsDir, input.runId, input.agent, index).metadataPath;
|
|
431
|
+
try {
|
|
432
|
+
const metadata = readUsageMetadata(metadataPath);
|
|
433
|
+
if (!metadata) continue;
|
|
434
|
+
if (metadata.runId !== input.runId || metadata.agent !== input.agent) continue;
|
|
435
|
+
const usage = usageFromValue(metadata.usage);
|
|
436
|
+
if (usage && usageHasValue(usage)) return usage;
|
|
437
|
+
} catch (error) {
|
|
438
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Failed to read subagent usage metadata '${metadataPath}':`, error);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
return undefined;
|
|
443
|
+
}
|
|
444
|
+
|
|
387
445
|
function formatCostUsage(label: string, usage: Usage): string {
|
|
388
446
|
const extras = [
|
|
389
447
|
usage.cacheRead ? `cache read ${formatTokens(usage.cacheRead)}` : "",
|
|
@@ -393,28 +451,94 @@ function formatCostUsage(label: string, usage: Usage): string {
|
|
|
393
451
|
return `${label}: ↑${formatTokens(usage.input)} ↓${formatTokens(usage.output)} $${usage.cost.toFixed(4)}${extras.length ? ` (${extras.join(", ")})` : ""}`;
|
|
394
452
|
}
|
|
395
453
|
|
|
396
|
-
function buildSubagentCostReport(ctx: ExtensionContext): string {
|
|
454
|
+
function buildSubagentCostReport(ctx: ExtensionContext, state: SubagentState): string {
|
|
397
455
|
const parent = emptyUsage();
|
|
398
456
|
const childTotal = emptyUsage();
|
|
399
457
|
const total = emptyUsage();
|
|
400
458
|
const children: Array<{ label: string; usage: Usage; sessionFile?: string }> = [];
|
|
459
|
+
const seenChildren = new Set<string>();
|
|
460
|
+
const workflowRunIds = new Set<string>();
|
|
461
|
+
let unresolvedAsyncChildren = 0;
|
|
462
|
+
|
|
463
|
+
const addChild = (input: { agent?: string; runId?: string; usage?: Usage; sessionFile?: string }): boolean => {
|
|
464
|
+
if (!input.usage || !usageHasValue(input.usage)) return false;
|
|
465
|
+
const identity = input.runId ? `run:${input.runId}` : input.sessionFile ? `session:${input.sessionFile}` : undefined;
|
|
466
|
+
if (identity && seenChildren.has(identity)) return true;
|
|
467
|
+
if (identity) seenChildren.add(identity);
|
|
468
|
+
const usage = { ...input.usage };
|
|
469
|
+
children.push({
|
|
470
|
+
label: `Child ${children.length + 1} (${input.agent ?? "unknown"})`,
|
|
471
|
+
usage,
|
|
472
|
+
...(input.sessionFile ? { sessionFile: input.sessionFile } : {}),
|
|
473
|
+
});
|
|
474
|
+
addUsage(childTotal, usage);
|
|
475
|
+
return true;
|
|
476
|
+
};
|
|
477
|
+
|
|
401
478
|
for (const entry of ctx.sessionManager.getBranch()) {
|
|
402
479
|
const message = entry.type === "message" ? (entry as { message?: unknown }).message : undefined;
|
|
403
|
-
const parentUsage = assistantUsageFromMessage(message);
|
|
480
|
+
const parentUsage = assistantUsageFromMessage(message) ?? compactionUsageFromEntry(entry);
|
|
404
481
|
if (parentUsage) addUsage(parent, parentUsage);
|
|
405
482
|
const details = detailsFromSessionEntry(entry);
|
|
406
483
|
if (!details) continue;
|
|
484
|
+
if (details.mode === "workflow" && details.runId) workflowRunIds.add(details.runId);
|
|
407
485
|
for (const result of details.results) {
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
486
|
+
const resultRunId = (result as SingleResult & { runId?: unknown }).runId;
|
|
487
|
+
addChild({ agent: result.agent, runId: typeof resultRunId === "string" ? resultRunId : undefined, usage: usageFromValue(result.usage), sessionFile: result.sessionFile });
|
|
488
|
+
}
|
|
489
|
+
for (const completion of details.completions ?? []) {
|
|
490
|
+
if (completion.mode === "workflow") workflowRunIds.add(completion.runId);
|
|
491
|
+
for (const result of completion.results ?? []) {
|
|
492
|
+
addChild({ agent: result.agent, runId: result.runId, usage: usageFromValue(result.usage), sessionFile: result.sessionFile });
|
|
493
|
+
}
|
|
416
494
|
}
|
|
417
495
|
}
|
|
496
|
+
|
|
497
|
+
let sessionFile: string | null = null;
|
|
498
|
+
try {
|
|
499
|
+
sessionFile = ctx.sessionManager.getSessionFile() ?? null;
|
|
500
|
+
} catch { /* an unpersisted session can still report direct child usage */ }
|
|
501
|
+
const artifactsDirs = new Set<string>();
|
|
502
|
+
const addArtifactsDir = (cwd: string | undefined): void => {
|
|
503
|
+
try {
|
|
504
|
+
artifactsDirs.add(getArtifactsDir(sessionFile, cwd, state.artifactDirPreference));
|
|
505
|
+
} catch { /* invalid or unavailable project roots are ignored */ }
|
|
506
|
+
};
|
|
507
|
+
addArtifactsDir(ctx.cwd);
|
|
508
|
+
addArtifactsDir(state.baseCwd);
|
|
509
|
+
|
|
510
|
+
for (const workflowRunId of workflowRunIds) {
|
|
511
|
+
try {
|
|
512
|
+
const status = readStatus(path.join(DIRS.async, workflowRunId));
|
|
513
|
+
addArtifactsDir(status?.cwd);
|
|
514
|
+
const receipt = readWorkflowReceipt(DIRS.async, workflowRunId);
|
|
515
|
+
const summaryChildren = new Map((receipt.workflowChildren?.children ?? []).map((child) => [child.childId, child]));
|
|
516
|
+
const refsByRunId = new Map<string, { runId: string; agent: string }>();
|
|
517
|
+
const addRef = (runId: string | undefined, agent: string | undefined): void => {
|
|
518
|
+
if (!runId || !agent || refsByRunId.has(runId)) return;
|
|
519
|
+
refsByRunId.set(runId, { runId, agent });
|
|
520
|
+
};
|
|
521
|
+
for (const [key, entry] of Object.entries(receipt.entries)) {
|
|
522
|
+
const summaryChild = summaryChildren.get(key);
|
|
523
|
+
const runIds = entry.continuation?.runIds?.length
|
|
524
|
+
? entry.continuation.runIds
|
|
525
|
+
: entry.latestRunId ? [entry.latestRunId] : summaryChild?.runId ? [summaryChild.runId] : [];
|
|
526
|
+
for (const runId of runIds) addRef(runId, entry.agent ?? summaryChild?.agent);
|
|
527
|
+
}
|
|
528
|
+
for (const child of receipt.workflowChildren?.children ?? []) {
|
|
529
|
+
if (!Object.hasOwn(receipt.entries, child.childId)) addRef(child.runId, child.agent);
|
|
530
|
+
}
|
|
531
|
+
const refs = [...refsByRunId.values()];
|
|
532
|
+
for (const ref of refs) {
|
|
533
|
+
if (seenChildren.has(`run:${ref.runId}`)) continue;
|
|
534
|
+
const usage = metadataUsage([...artifactsDirs], ref);
|
|
535
|
+
if (!usage || !addChild({ ...ref, usage })) unresolvedAsyncChildren += 1;
|
|
536
|
+
}
|
|
537
|
+
} catch (error) {
|
|
538
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Failed to resolve async subagent usage for '${workflowRunId}':`, error);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
418
542
|
addUsage(total, parent);
|
|
419
543
|
addUsage(total, childTotal);
|
|
420
544
|
const lines = [
|
|
@@ -430,6 +554,7 @@ function buildSubagentCostReport(ctx: ExtensionContext): string {
|
|
|
430
554
|
if (child.sessionFile) lines.push(` Session: ${child.sessionFile}`);
|
|
431
555
|
}
|
|
432
556
|
}
|
|
557
|
+
if (unresolvedAsyncChildren > 0) lines.push(`Async child usage unavailable: ${unresolvedAsyncChildren}.`);
|
|
433
558
|
lines.push("────────────────────────────", formatCostUsage("Children", childTotal), formatCostUsage("Total", total));
|
|
434
559
|
return lines.join("\n");
|
|
435
560
|
}
|
|
@@ -445,50 +570,76 @@ function getProfileWorkerModel(profile: { subagents?: { agentOverrides?: Record<
|
|
|
445
570
|
return typeof model === "string" && model.trim() ? model.trim() : undefined;
|
|
446
571
|
}
|
|
447
572
|
|
|
573
|
+
function isStaleExtensionContextError(error: unknown): boolean {
|
|
574
|
+
return error instanceof Error
|
|
575
|
+
&& (error.message.includes("This extension ctx is stale")
|
|
576
|
+
|| error.message.includes("Extension context no longer active"));
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function slashHasUI(ctx: ExtensionContext): boolean | undefined {
|
|
580
|
+
try {
|
|
581
|
+
return ctx.hasUI;
|
|
582
|
+
} catch (error) {
|
|
583
|
+
if (isStaleExtensionContextError(error)) return undefined;
|
|
584
|
+
throw error;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
|
|
448
588
|
|
|
449
589
|
async function requestSlashRun(
|
|
450
590
|
pi: ExtensionAPI,
|
|
451
591
|
ctx: ExtensionContext,
|
|
452
592
|
requestId: string,
|
|
453
593
|
params: SubagentParamsLike,
|
|
594
|
+
signal?: AbortSignal,
|
|
454
595
|
): Promise<SlashSubagentResponse> {
|
|
455
596
|
return new Promise((resolve, reject) => {
|
|
456
597
|
let done = false;
|
|
457
598
|
let started = false;
|
|
458
|
-
|
|
459
|
-
const startTimeoutMs = 15_000;
|
|
460
|
-
const startTimeout = setTimeout(() => {
|
|
461
|
-
finish(() => reject(new Error(
|
|
462
|
-
"Slash subagent bridge did not start within 15s. Ensure the extension is loaded correctly.",
|
|
463
|
-
)));
|
|
464
|
-
}, startTimeoutMs);
|
|
599
|
+
let startTimeout: ReturnType<typeof setTimeout> | undefined;
|
|
465
600
|
|
|
466
601
|
const onStarted = (data: unknown) => {
|
|
467
|
-
if (done || !data || typeof data !== "object") return;
|
|
602
|
+
if (done || signal?.aborted || !data || typeof data !== "object") return;
|
|
468
603
|
if ((data as { requestId?: unknown }).requestId !== requestId) return;
|
|
469
604
|
started = true;
|
|
470
|
-
clearTimeout(startTimeout);
|
|
471
|
-
|
|
605
|
+
if (startTimeout) clearTimeout(startTimeout);
|
|
606
|
+
try {
|
|
607
|
+
if (ctx.hasUI) ctx.ui.setStatus("subagent-slash", "running...");
|
|
608
|
+
} catch (error) {
|
|
609
|
+
if (isStaleExtensionContextError(error)) {
|
|
610
|
+
finish(() => reject(error));
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
throw error;
|
|
614
|
+
}
|
|
472
615
|
};
|
|
473
616
|
|
|
474
617
|
const onResponse = (data: unknown) => {
|
|
475
|
-
if (done || !data || typeof data !== "object") return;
|
|
618
|
+
if (done || signal?.aborted || !data || typeof data !== "object") return;
|
|
476
619
|
const response = data as Partial<SlashSubagentResponse>;
|
|
477
620
|
if (response.requestId !== requestId) return;
|
|
478
|
-
clearTimeout(startTimeout);
|
|
621
|
+
if (startTimeout) clearTimeout(startTimeout);
|
|
479
622
|
finish(() => resolve(response as SlashSubagentResponse));
|
|
480
623
|
};
|
|
481
624
|
|
|
482
625
|
const onUpdate = (data: unknown) => {
|
|
483
|
-
if (done || !data || typeof data !== "object") return;
|
|
626
|
+
if (done || signal?.aborted || !data || typeof data !== "object") return;
|
|
484
627
|
const update = data as SlashSubagentUpdate;
|
|
485
628
|
if (update.requestId !== requestId) return;
|
|
486
629
|
applySlashUpdate(requestId, update);
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
630
|
+
try {
|
|
631
|
+
if (!ctx.hasUI) return;
|
|
632
|
+
const tool = update.currentTool ? ` ${update.currentTool}` : "";
|
|
633
|
+
const count = update.toolCount ?? 0;
|
|
634
|
+
const liveDetailKey = keyText("app.tools.expand");
|
|
635
|
+
ctx.ui.setStatus("subagent-slash", `${count} tools${tool} | ${liveDetailKey} live detail`);
|
|
636
|
+
} catch (error) {
|
|
637
|
+
if (isStaleExtensionContextError(error)) {
|
|
638
|
+
finish(() => reject(error));
|
|
639
|
+
return;
|
|
640
|
+
}
|
|
641
|
+
throw error;
|
|
642
|
+
}
|
|
492
643
|
};
|
|
493
644
|
|
|
494
645
|
const onTerminalInput = ctx.hasUI
|
|
@@ -504,18 +655,43 @@ async function requestSlashRun(
|
|
|
504
655
|
const unsubResponse = pi.events.on(SLASH_SUBAGENT_RESPONSE_EVENT, onResponse);
|
|
505
656
|
const unsubUpdate = pi.events.on(SLASH_SUBAGENT_UPDATE_EVENT, onUpdate);
|
|
506
657
|
|
|
658
|
+
let onAbort: () => void;
|
|
507
659
|
const finish = (next: () => void) => {
|
|
508
660
|
if (done) return;
|
|
509
661
|
done = true;
|
|
510
|
-
clearTimeout(startTimeout);
|
|
662
|
+
if (startTimeout) clearTimeout(startTimeout);
|
|
511
663
|
unsubStarted();
|
|
512
664
|
unsubResponse();
|
|
513
665
|
unsubUpdate();
|
|
514
|
-
|
|
666
|
+
try {
|
|
667
|
+
onTerminalInput?.();
|
|
668
|
+
} catch (error) {
|
|
669
|
+
if (!isStaleExtensionContextError(error)) throw error;
|
|
670
|
+
}
|
|
671
|
+
signal?.removeEventListener("abort", onAbort);
|
|
515
672
|
next();
|
|
516
673
|
};
|
|
674
|
+
onAbort = () => finish(() => reject(new Error("Slash subagent request canceled during session replacement or reload.")));
|
|
675
|
+
startTimeout = setTimeout(() => {
|
|
676
|
+
finish(() => reject(new Error(
|
|
677
|
+
"Slash subagent bridge did not start within 15s. Ensure the extension is loaded correctly.",
|
|
678
|
+
)));
|
|
679
|
+
}, 15_000);
|
|
517
680
|
|
|
518
|
-
|
|
681
|
+
if (signal?.aborted) {
|
|
682
|
+
onAbort();
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
686
|
+
try {
|
|
687
|
+
pi.events.emit(SLASH_SUBAGENT_REQUEST_EVENT, { requestId, params, ctx });
|
|
688
|
+
} catch (error) {
|
|
689
|
+
if (isStaleExtensionContextError(error)) {
|
|
690
|
+
finish(() => reject(error));
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
throw error;
|
|
694
|
+
}
|
|
519
695
|
|
|
520
696
|
// Bridge emits STARTED synchronously during REQUEST emit.
|
|
521
697
|
// If not started, no bridge received the request.
|
|
@@ -581,64 +757,76 @@ async function runSlashSubagent(
|
|
|
581
757
|
pi: ExtensionAPI,
|
|
582
758
|
ctx: ExtensionContext,
|
|
583
759
|
params: SubagentParamsLike,
|
|
760
|
+
signal?: AbortSignal,
|
|
584
761
|
): Promise<void> {
|
|
585
|
-
if (
|
|
762
|
+
if (signal?.aborted) return;
|
|
763
|
+
const initialHasUI = slashHasUI(ctx);
|
|
764
|
+
if (initialHasUI === undefined) return;
|
|
765
|
+
try {
|
|
766
|
+
if (initialHasUI) ctx.ui.setToolsExpanded(false);
|
|
767
|
+
} catch (error) {
|
|
768
|
+
if (isStaleExtensionContextError(error)) return;
|
|
769
|
+
throw error;
|
|
770
|
+
}
|
|
586
771
|
const requestId = randomUUID();
|
|
587
772
|
const initialDetails = buildSlashInitialResult(requestId, params);
|
|
588
773
|
const initialText = extractSlashMessageText(initialDetails.result.content) || "Running subagent...";
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
774
|
+
try {
|
|
775
|
+
pi.sendMessage({
|
|
776
|
+
customType: SLASH_RESULT_TYPE,
|
|
777
|
+
content: initialText,
|
|
778
|
+
display: true,
|
|
779
|
+
details: initialDetails,
|
|
780
|
+
});
|
|
781
|
+
} catch (error) {
|
|
782
|
+
if (isStaleExtensionContextError(error)) return;
|
|
783
|
+
throw error;
|
|
784
|
+
}
|
|
595
785
|
persistSlashSessionSnapshot(ctx);
|
|
596
786
|
|
|
597
787
|
try {
|
|
598
|
-
const response = await requestSlashRun(pi, ctx, requestId, params);
|
|
788
|
+
const response = await requestSlashRun(pi, ctx, requestId, params, signal);
|
|
789
|
+
if (signal?.aborted) return;
|
|
790
|
+
const hasUI = slashHasUI(ctx);
|
|
791
|
+
if (hasUI === undefined) return;
|
|
599
792
|
const finalDetails = finalizeSlashResult(response);
|
|
600
793
|
pi.sendMessage({
|
|
601
794
|
customType: SLASH_RESULT_TYPE,
|
|
602
795
|
content: buildSlashExportText(response),
|
|
603
|
-
display: !
|
|
796
|
+
display: !hasUI,
|
|
604
797
|
details: finalDetails,
|
|
605
798
|
});
|
|
606
799
|
persistSlashSessionSnapshot(ctx);
|
|
607
|
-
if (
|
|
800
|
+
if (hasUI) {
|
|
608
801
|
ctx.ui.setStatus("subagent-slash", undefined);
|
|
609
802
|
}
|
|
610
|
-
if (response.isError &&
|
|
803
|
+
if (response.isError && hasUI) {
|
|
611
804
|
ctx.ui.notify(response.errorText || "Subagent failed", "error");
|
|
612
805
|
}
|
|
613
806
|
} catch (error) {
|
|
807
|
+
if (signal?.aborted || isStaleExtensionContextError(error)) return;
|
|
614
808
|
const message = error instanceof Error ? error.message : String(error);
|
|
809
|
+
const hasUI = slashHasUI(ctx);
|
|
810
|
+
if (hasUI === undefined) return;
|
|
615
811
|
const failedDetails = failSlashResult(requestId, params, message);
|
|
616
812
|
pi.sendMessage({
|
|
617
813
|
customType: SLASH_RESULT_TYPE,
|
|
618
814
|
content: `## Subagent result\n\n${message}`,
|
|
619
|
-
display: !
|
|
815
|
+
display: !hasUI,
|
|
620
816
|
details: failedDetails,
|
|
621
817
|
});
|
|
622
818
|
persistSlashSessionSnapshot(ctx);
|
|
623
|
-
if (
|
|
819
|
+
if (hasUI) {
|
|
624
820
|
ctx.ui.setStatus("subagent-slash", undefined);
|
|
625
821
|
}
|
|
626
822
|
if (message === "Cancelled") {
|
|
627
|
-
if (
|
|
823
|
+
if (hasUI) ctx.ui.notify("Cancelled", "warning");
|
|
628
824
|
return;
|
|
629
825
|
}
|
|
630
|
-
if (
|
|
826
|
+
if (hasUI) ctx.ui.notify(message, "error");
|
|
631
827
|
}
|
|
632
828
|
}
|
|
633
829
|
|
|
634
|
-
function launchSlashSubagent(
|
|
635
|
-
pi: ExtensionAPI,
|
|
636
|
-
ctx: ExtensionContext,
|
|
637
|
-
params: SubagentParamsLike,
|
|
638
|
-
): void {
|
|
639
|
-
void runSlashSubagent(pi, ctx, params);
|
|
640
|
-
}
|
|
641
|
-
|
|
642
830
|
function slashRunWorkflowScript(key: string, child: Record<string, unknown>): string {
|
|
643
831
|
return `return runs.run(${JSON.stringify(key)}, ${JSON.stringify(child)})`;
|
|
644
832
|
}
|
|
@@ -647,12 +835,23 @@ export function registerSlashCommands(
|
|
|
647
835
|
pi: ExtensionAPI,
|
|
648
836
|
state: SubagentState,
|
|
649
837
|
options: { fleetKeybindings?: FleetKeybindingsConfig; foregroundDetachShortcut?: string } = {},
|
|
650
|
-
): void {
|
|
838
|
+
): { dispose: () => void } {
|
|
651
839
|
let fleetOpen = false;
|
|
840
|
+
let disposed = false;
|
|
841
|
+
const pendingRequests = new Set<AbortController>();
|
|
842
|
+
const runCommand = (ctx: ExtensionContext, params: SubagentParamsLike): Promise<void> => {
|
|
843
|
+
if (disposed) return Promise.resolve();
|
|
844
|
+
const controller = new AbortController();
|
|
845
|
+
pendingRequests.add(controller);
|
|
846
|
+
return runSlashSubagent(pi, ctx, params, controller.signal).finally(() => pendingRequests.delete(controller));
|
|
847
|
+
};
|
|
848
|
+
const launchCommand = (ctx: ExtensionContext, params: SubagentParamsLike): void => {
|
|
849
|
+
void runCommand(ctx, params);
|
|
850
|
+
};
|
|
652
851
|
const showFleet = async (ctx: ExtensionContext) => {
|
|
653
852
|
state.lastUiContext = ctx;
|
|
654
853
|
if (!ctx.hasUI) {
|
|
655
|
-
await
|
|
854
|
+
await runCommand(ctx, { action: "status", view: "fleet" });
|
|
656
855
|
return;
|
|
657
856
|
}
|
|
658
857
|
if (fleetOpen) {
|
|
@@ -693,7 +892,7 @@ export function registerSlashCommands(
|
|
|
693
892
|
: resolvedAgent.agent;
|
|
694
893
|
const diagnostic = findBlockingAgentDiagnostic(agentName, candidates, discovered.agentDiagnostics);
|
|
695
894
|
if (diagnostic || resolvedAgent.error || !resolvedAgent.agent) {
|
|
696
|
-
ctx.ui.notify(diagnostic ? `Agent '${agentName}' has invalid configuration: ${diagnostic.error}` : resolvedAgent.error ??
|
|
895
|
+
ctx.ui.notify(diagnostic ? `Agent '${agentName}' has invalid configuration: ${diagnostic.error}` : resolvedAgent.error ?? formatUnknownAgentError(agentName, discovered.unknownAgentDiagnosticContext), "error");
|
|
697
896
|
return;
|
|
698
897
|
}
|
|
699
898
|
|
|
@@ -708,21 +907,21 @@ export function registerSlashCommands(
|
|
|
708
907
|
if (inline.skill !== undefined) child.skill = inline.skill;
|
|
709
908
|
if (inline.model) child.model = inline.model;
|
|
710
909
|
if (fork) child.context = "fork";
|
|
711
|
-
|
|
910
|
+
launchCommand(ctx, { workflowScript: slashRunWorkflowScript("run", child), async: bg ? true : false });
|
|
712
911
|
},
|
|
713
912
|
});
|
|
714
913
|
|
|
715
914
|
pi.registerCommand("subagent-cost", {
|
|
716
915
|
description: "Show parent and subagent child usage cost for this session",
|
|
717
916
|
handler: async (_args, ctx) => {
|
|
718
|
-
sendSlashText(pi, buildSubagentCostReport(ctx));
|
|
917
|
+
sendSlashText(pi, buildSubagentCostReport(ctx, state));
|
|
719
918
|
},
|
|
720
919
|
});
|
|
721
920
|
|
|
722
921
|
pi.registerCommand("subagents-doctor", {
|
|
723
922
|
description: "Show subagent diagnostics",
|
|
724
923
|
handler: async (_args, ctx) => {
|
|
725
|
-
await
|
|
924
|
+
await runCommand(ctx, { action: "doctor" });
|
|
726
925
|
},
|
|
727
926
|
});
|
|
728
927
|
|
|
@@ -754,7 +953,7 @@ export function registerSlashCommands(
|
|
|
754
953
|
ctx.ui.notify("Usage: /subagents-guide [topic]", "error");
|
|
755
954
|
return;
|
|
756
955
|
}
|
|
757
|
-
await
|
|
956
|
+
await runCommand(ctx, { action: "guide", ...(topic ? { topic } : {}) });
|
|
758
957
|
},
|
|
759
958
|
});
|
|
760
959
|
|
|
@@ -767,7 +966,7 @@ export function registerSlashCommands(
|
|
|
767
966
|
ctx.ui.notify("Usage: /subagents-refine <agent>", "error");
|
|
768
967
|
return;
|
|
769
968
|
}
|
|
770
|
-
await
|
|
969
|
+
await runCommand(ctx, { action: "refine", agent: parts[0] });
|
|
771
970
|
},
|
|
772
971
|
});
|
|
773
972
|
|
|
@@ -776,7 +975,7 @@ export function registerSlashCommands(
|
|
|
776
975
|
handler: async (_args, ctx) => showFleet(ctx),
|
|
777
976
|
});
|
|
778
977
|
|
|
779
|
-
pi.registerShortcut(
|
|
978
|
+
pi.registerShortcut(FLEET_OPEN_SHORTCUT, {
|
|
780
979
|
description: "Open subagent fleet inspector",
|
|
781
980
|
handler: async (ctx) => showFleet(ctx),
|
|
782
981
|
});
|
|
@@ -802,7 +1001,7 @@ export function registerSlashCommands(
|
|
|
802
1001
|
ctx.ui.notify(`Foreground run ${control.runId} is not currently detachable.`, "info");
|
|
803
1002
|
return;
|
|
804
1003
|
}
|
|
805
|
-
sendSlashText(pi, `Detached foreground run ${control.runId} without terminating its child. Use subagent({ action: "status", id: ${JSON.stringify(control.runId)} }) or
|
|
1004
|
+
sendSlashText(pi, `Detached foreground run ${control.runId} without terminating its child. Use subagent({ action: "status", id: ${JSON.stringify(control.runId)} }) or bg_wait({ id: ${JSON.stringify(control.runId)} }) to recover the eventual result. This does not daemonize the process or guarantee survival across Pi reload/restart.`);
|
|
806
1005
|
};
|
|
807
1006
|
|
|
808
1007
|
pi.registerCommand("subagents-detach", {
|
|
@@ -818,16 +1017,15 @@ export function registerSlashCommands(
|
|
|
818
1017
|
}
|
|
819
1018
|
|
|
820
1019
|
pi.registerCommand("subagents-stop", {
|
|
821
|
-
description: "Stop a current-session async subagent run",
|
|
1020
|
+
description: "Stop a current-session async subagent run, or one child of it with /subagents-stop <run-id> <child-id>",
|
|
822
1021
|
handler: async (args, ctx) => {
|
|
823
|
-
const id = args.trim();
|
|
824
|
-
if (
|
|
825
|
-
|
|
1022
|
+
const [id, childId, ...extra] = args.trim().split(/\s+/).filter(Boolean);
|
|
1023
|
+
if (extra.length > 0) {
|
|
1024
|
+
sendSlashText(pi, "Usage: /subagents-stop [run-id] [child-id]");
|
|
826
1025
|
return;
|
|
827
1026
|
}
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
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>\" })`.");
|
|
1027
|
+
if (id) {
|
|
1028
|
+
await runCommand(ctx, childId ? { action: "stop", id, childId } : { action: "stop", id });
|
|
831
1029
|
return;
|
|
832
1030
|
}
|
|
833
1031
|
|
|
@@ -854,40 +1052,99 @@ export function registerSlashCommands(
|
|
|
854
1052
|
);
|
|
855
1053
|
if (!result?.confirmed || !result.target) return;
|
|
856
1054
|
if (result.target.kind === "scheduled") {
|
|
857
|
-
await
|
|
1055
|
+
await runCommand(ctx, { action: "schedule.pause", id: result.target.id });
|
|
858
1056
|
return;
|
|
859
1057
|
}
|
|
860
|
-
await
|
|
1058
|
+
await runCommand(ctx, { action: "stop", id: result.target.id });
|
|
1059
|
+
},
|
|
1060
|
+
});
|
|
1061
|
+
|
|
1062
|
+
pi.registerCommand("subagents-steer", {
|
|
1063
|
+
description: "Steer a live async subagent run with a message, or one child of it with --child <child-id>",
|
|
1064
|
+
handler: async (args, ctx) => {
|
|
1065
|
+
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
1066
|
+
const usage = "Usage: /subagents-steer <run-id> [--child <child-id>] <message>";
|
|
1067
|
+
const [id, ...rest] = tokens;
|
|
1068
|
+
if (!id || id.startsWith("--")) {
|
|
1069
|
+
sendSlashText(pi, usage);
|
|
1070
|
+
return;
|
|
1071
|
+
}
|
|
1072
|
+
// Only the optional child selector is parsed as a flag. Everything
|
|
1073
|
+
// after the run id (or selector) is free-form message text, including
|
|
1074
|
+
// a leading token such as `--verbose`.
|
|
1075
|
+
let childId: string | undefined;
|
|
1076
|
+
let messageStart = 0;
|
|
1077
|
+
if (rest[0] === "--child" && rest[1] && !rest[1].startsWith("--")) {
|
|
1078
|
+
childId = rest[1];
|
|
1079
|
+
messageStart = 2;
|
|
1080
|
+
}
|
|
1081
|
+
const message = rest.slice(messageStart).join(" ").trim();
|
|
1082
|
+
if (!message) {
|
|
1083
|
+
sendSlashText(pi, usage);
|
|
1084
|
+
return;
|
|
1085
|
+
}
|
|
1086
|
+
let targetId = id;
|
|
1087
|
+
let childIndex: number | undefined;
|
|
1088
|
+
if (childId !== undefined) {
|
|
1089
|
+
const sessionId = state.currentSessionId ?? ctx.sessionManager.getSessionId() ?? undefined;
|
|
1090
|
+
const run = listAsyncRuns(DIRS.async, {
|
|
1091
|
+
runId: id,
|
|
1092
|
+
states: ["queued", "running", "paused"],
|
|
1093
|
+
...(sessionId ? { sessionId } : {}),
|
|
1094
|
+
})[0];
|
|
1095
|
+
const status = run ? readStatus(run.asyncDir) : null;
|
|
1096
|
+
if (!run || !status) {
|
|
1097
|
+
sendSlashText(pi, `No current-session async run found for '${id}'.`);
|
|
1098
|
+
return;
|
|
1099
|
+
}
|
|
1100
|
+
const resolutionStatus = {
|
|
1101
|
+
...status,
|
|
1102
|
+
steps: status.steps?.map((step, index) => ({ ...step, children: run.steps[index]?.children ?? step.children })),
|
|
1103
|
+
};
|
|
1104
|
+
const resolution = resolveAsyncStatusChild(resolutionStatus, childId, { includeNested: true });
|
|
1105
|
+
if (!resolution.ok) {
|
|
1106
|
+
sendSlashText(pi, resolution.message);
|
|
1107
|
+
return;
|
|
1108
|
+
}
|
|
1109
|
+
if (resolution.child.nested) targetId = resolution.child.nested.id;
|
|
1110
|
+
else if (resolution.child.step.runId) targetId = resolution.child.step.runId;
|
|
1111
|
+
else childIndex = resolution.child.index;
|
|
1112
|
+
}
|
|
1113
|
+
await runCommand(ctx, {
|
|
1114
|
+
action: "steer",
|
|
1115
|
+
id: targetId,
|
|
1116
|
+
message,
|
|
1117
|
+
...(childIndex !== undefined ? { index: childIndex } : {}),
|
|
1118
|
+
// Host-style exact-child authority, matching the extension RPC
|
|
1119
|
+
// nonRecoveringSteer guarantee: never swap the addressed child for
|
|
1120
|
+
// a pause-and-revive replacement after a missed acknowledgment.
|
|
1121
|
+
steeringRecovery: false,
|
|
1122
|
+
});
|
|
861
1123
|
},
|
|
862
1124
|
});
|
|
863
1125
|
|
|
864
1126
|
registerPromptWorkflowCommands({
|
|
865
1127
|
pi,
|
|
866
1128
|
run: async (params, ctx) => {
|
|
867
|
-
|
|
1129
|
+
launchCommand(ctx, params);
|
|
868
1130
|
},
|
|
869
1131
|
});
|
|
870
1132
|
|
|
871
1133
|
pi.registerCommand("subagents-models", {
|
|
872
|
-
description: "Show
|
|
873
|
-
getArgumentCompletions:
|
|
1134
|
+
description: "Show model mappings for discovered subagents",
|
|
1135
|
+
getArgumentCompletions: makeAgentCompletions(pi, state),
|
|
874
1136
|
handler: async (args, ctx) => {
|
|
875
1137
|
const trimmed = args.trim();
|
|
876
1138
|
if (!trimmed) {
|
|
877
|
-
await
|
|
1139
|
+
await runCommand(ctx, { action: "models" });
|
|
878
1140
|
return;
|
|
879
1141
|
}
|
|
880
1142
|
const parts = trimmed.split(/\s+/).filter(Boolean);
|
|
881
1143
|
if (parts.length !== 1) {
|
|
882
|
-
ctx.ui.notify("Usage: /subagents-models [
|
|
883
|
-
return;
|
|
884
|
-
}
|
|
885
|
-
const agent = parts[0]!;
|
|
886
|
-
if (!(BUILTIN_AGENT_NAMES as readonly string[]).includes(agent)) {
|
|
887
|
-
ctx.ui.notify(`Unknown builtin agent: ${agent}`, "error");
|
|
1144
|
+
ctx.ui.notify("Usage: /subagents-models [agent-name]", "error");
|
|
888
1145
|
return;
|
|
889
1146
|
}
|
|
890
|
-
await
|
|
1147
|
+
await runCommand(ctx, { action: "models", agent: parts[0]! });
|
|
891
1148
|
},
|
|
892
1149
|
});
|
|
893
1150
|
|
|
@@ -1060,4 +1317,14 @@ export function registerSlashCommands(
|
|
|
1060
1317
|
},
|
|
1061
1318
|
});
|
|
1062
1319
|
|
|
1320
|
+
return {
|
|
1321
|
+
dispose: () => {
|
|
1322
|
+
if (disposed) return;
|
|
1323
|
+
disposed = true;
|
|
1324
|
+
// A reload revokes the command context; do not let delayed responses
|
|
1325
|
+
// resume a command against the old Pi context.
|
|
1326
|
+
for (const controller of pendingRequests) controller.abort();
|
|
1327
|
+
pendingRequests.clear();
|
|
1328
|
+
},
|
|
1329
|
+
};
|
|
1063
1330
|
}
|