@xzzpig/pi-subagents 0.16.0 → 0.19.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 +233 -1
- package/README.md +5 -3
- package/agents/claude-code-writer.md +1 -0
- package/agents/codex-exec-writer.md +1 -0
- package/agents/cursor-agent-writer.md +1 -0
- package/agents/reviewer.md +3 -2
- package/agents/worker.md +3 -2
- package/docs/agents.md +34 -21
- package/docs/configuration.md +82 -7
- package/docs/extension-api.md +75 -8
- package/docs/missions.md +13 -13
- package/docs/models.md +7 -5
- package/docs/observability.md +23 -13
- package/docs/standalone-background.md +5 -5
- package/docs/tool-reference.md +98 -100
- package/docs/watchdog.md +2 -0
- package/docs/workflows.md +214 -162
- package/inspector-runner.mjs +1 -1
- package/node_modules/@xzzpig/pi-components/package.json +4 -4
- package/package.json +15 -9
- package/prompts/council.md +6 -3
- package/prompts/review-loop.md +1 -1
- package/runner-peer-loader.mjs +4 -7
- package/runner-peer-preload.mjs +5 -7
- package/skills/council-mode/SKILL.md +1 -1
- package/skills/pi-subagents/SKILL.md +13 -5
- package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
- package/skills/pi-subagents/references/execution-controls.md +72 -69
- package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
- package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
- package/src/agents/advertised-agent-prompt.ts +21 -41
- package/src/agents/agent-eject.ts +3 -3
- package/src/agents/agent-management.ts +63 -54
- package/src/agents/agent-memory.ts +90 -3
- package/src/agents/agent-serializer.ts +4 -4
- package/src/agents/agents.ts +132 -51
- package/src/agents/global-npm-root.ts +58 -0
- package/src/agents/proactive-skills.ts +4 -1
- package/src/agents/runtime-agent-registry.ts +14 -11
- package/src/agents/skills.ts +42 -9
- package/src/api/delegation.ts +15 -0
- package/src/api/inspectors.ts +27 -0
- package/src/api/preflight.ts +7 -2
- package/src/extension/config.ts +12 -4
- package/src/extension/control-notices.ts +3 -0
- package/src/extension/doctor.ts +10 -4
- package/src/extension/fanout-child.ts +20 -3
- package/src/extension/herdr-pi-bridge.ts +2 -0
- package/src/extension/index.ts +168 -206
- package/src/extension/public-execution.ts +69 -35
- package/src/extension/reply-workflow-script.ts +58 -0
- package/src/extension/rpc.ts +39 -11
- package/src/extension/schemas.ts +47 -138
- package/src/extension/subagent-guide.ts +12 -4
- package/src/extension/tool-activation.ts +146 -0
- package/src/extension/tool-description.ts +62 -27
- package/src/extension/upgrade-notice.ts +40 -0
- package/src/inspectors/ghostty/plugin.ts +13 -1
- package/src/inspectors/plugins.ts +70 -3
- package/src/integrations/herdr-status.ts +19 -3
- package/src/intercom/intercom-bridge.ts +2 -0
- package/src/intercom/native-supervisor-channel.ts +26 -16
- package/src/intercom/result-intercom.ts +4 -0
- package/src/runs/background/active-async-capacity.ts +3 -25
- package/src/runs/background/async-execution.ts +60 -95
- package/src/runs/background/async-job-tracker.ts +91 -56
- package/src/runs/background/async-resume.ts +16 -8
- package/src/runs/background/async-retention.ts +46 -16
- package/src/runs/background/async-status.ts +2 -0
- package/src/runs/background/await-async-run.ts +76 -0
- package/src/runs/background/binary-bootstrap.ts +34 -6
- package/src/runs/background/chain-root-attachment.ts +4 -4
- package/src/runs/background/control-channel.ts +18 -2
- package/src/runs/background/fleet-view.ts +51 -7
- package/src/runs/background/notify.ts +98 -7
- package/src/runs/background/pid-namespace.ts +18 -0
- package/src/runs/background/process-terminal-candidate.ts +98 -0
- package/src/runs/background/process-terminal.ts +17 -96
- package/src/runs/background/result-watcher.ts +1 -1
- package/src/runs/background/retained-children.ts +3 -2
- package/src/runs/background/run-child-session.ts +20 -6
- package/src/runs/background/run-id-resolver.ts +10 -5
- package/src/runs/background/run-status.ts +16 -4
- package/src/runs/background/runner-aliases.ts +54 -16
- package/src/runs/background/runner-child-launch.ts +4 -2
- package/src/runs/background/runner-startup-failure.ts +56 -0
- package/src/runs/background/scheduled-runs.ts +5 -5
- package/src/runs/background/stale-run-reconciler.ts +19 -3
- package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
- package/src/runs/background/subagent-runner.ts +111 -288
- package/src/runs/background/wait-tool.ts +2 -0
- package/src/runs/background/workflow-terminal-proof.ts +68 -0
- package/src/runs/foreground/async-stop-action.ts +17 -3
- package/src/runs/foreground/execution.ts +111 -139
- package/src/runs/foreground/prompt-audit.ts +3 -9
- package/src/runs/foreground/subagent-executor.ts +715 -258
- package/src/runs/shared/acceptance.ts +167 -68
- package/src/runs/shared/async-status-projection.ts +5 -0
- package/src/runs/shared/capability-ceiling.ts +4 -1
- package/src/runs/shared/child-hooks.ts +1 -16
- package/src/runs/shared/child-launch.ts +37 -16
- package/src/runs/shared/child-runtime-config.ts +3 -0
- package/src/runs/shared/child-session.ts +144 -8
- package/src/runs/shared/child-tool-plan.ts +38 -116
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/external-cli-runner.ts +3 -1
- package/src/runs/shared/external-job-bridge.ts +54 -0
- package/src/runs/shared/git-environment.ts +29 -0
- package/src/runs/shared/mcp-config-sources.ts +5 -1
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
- package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
- package/src/runs/shared/model-resolution.ts +35 -10
- package/src/runs/shared/model-scope.ts +28 -9
- package/src/runs/shared/nested-events.ts +12 -0
- package/src/runs/shared/orca-progress-tabs.ts +3 -2
- package/src/runs/shared/parallel-utils.ts +4 -1
- package/src/runs/shared/pi-spawn.ts +1 -3
- package/src/runs/shared/single-output.ts +11 -2
- package/src/runs/shared/structured-output.ts +227 -7
- package/src/runs/shared/subagent-control.ts +2 -16
- package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
- package/src/runs/shared/tool-availability.ts +2 -2
- package/src/runs/shared/tool-budget.ts +21 -0
- package/src/runs/shared/usage-reconciliation.ts +73 -0
- package/src/runs/shared/worktree.ts +36 -9
- package/src/shared/child-session-name.ts +4 -2
- package/src/shared/disabled-features.ts +123 -0
- package/src/shared/extension-context.ts +13 -0
- package/src/shared/fork-context.ts +11 -4
- package/src/shared/launch-contract.ts +1 -1
- package/src/shared/model-info.ts +9 -0
- package/src/shared/pruned-fork.ts +69 -56
- package/src/shared/settings.ts +1 -1
- package/src/shared/types.ts +73 -16
- package/src/slash/delegation-adapters.ts +25 -1
- package/src/slash/prompt-template-bridge.ts +18 -3
- package/src/slash/prompt-workflows.ts +12 -1
- package/src/slash/slash-commands.ts +17 -246
- package/src/slash/subagent-cost.ts +313 -0
- package/src/slash/subagents-admin.ts +4 -5
- package/src/tui/fleet-status.ts +38 -8
- package/src/tui/fleet.ts +21 -6
- package/src/tui/render.ts +166 -71
- package/src/tui/running-tone.ts +28 -0
- package/src/watchdog/diff-tool.ts +47 -12
- package/src/watchdog/permission-arbiter.ts +13 -15
- package/src/watchdog/register-child.ts +13 -5
- package/src/watchdog/register-main.ts +3 -3
- package/src/watchdog/review.ts +16 -16
- package/src/watchdog/runtime.ts +2 -1
- package/src/watchdog/turn-delta.ts +12 -6
- package/src/workflows/chat-progress.ts +2 -2
- package/src/workflows/scripted-workflow.ts +225 -59
- package/src/workflows/structured-workflow-scripts.ts +177 -0
- package/src/workflows/workflow-checklist.ts +6 -0
- package/src/workflows/workflow-child-summary.ts +4 -2
- package/src/workflows/workflow-receipt.ts +8 -2
- package/src/workflows/workflow-resources.ts +37 -12
- package/src/workflows/workflow-reuse.ts +120 -0
- package/src/workflows/workflow-revival.ts +123 -0
- package/src/workflows/workflow-settlement.ts +4 -1
- package/src/runs/shared/completion-evidence.ts +0 -89
- package/src/runs/shared/completion-guard.ts +0 -255
- package/src/runs/shared/llm-intent-arbiter.ts +0 -321
- package/src/runs/shared/task-intent.ts +0 -244
|
@@ -17,26 +17,23 @@ import {
|
|
|
17
17
|
} from "../profiles/profiles.ts";
|
|
18
18
|
import type { SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
|
|
19
19
|
import { findModelInfo, toModelInfo } from "../shared/model-info.ts";
|
|
20
|
-
import {
|
|
20
|
+
import { 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
24
|
import { resolveAsyncStatusChild } from "../runs/shared/child-identity.ts";
|
|
25
25
|
import { readStatus } from "../shared/utils.ts";
|
|
26
|
-
import { getArtifactPaths, getArtifactsDir } from "../shared/artifacts.ts";
|
|
27
|
-
import { readWorkflowReceipt } from "../workflows/workflow-receipt.ts";
|
|
28
26
|
import type { SlashSubagentResponse, SlashSubagentUpdate } from "./slash-bridge.ts";
|
|
29
27
|
import { registerPromptWorkflowCommands } from "./prompt-workflows.ts";
|
|
28
|
+
import { collectSubagentCost, formatSubagentCostReport } from "./subagent-cost.ts";
|
|
30
29
|
import { openSubagentsAdmin } from "./subagents-admin.ts";
|
|
31
30
|
import { SUBAGENT_GUIDE_TOPICS } from "../extension/subagent-guide.ts";
|
|
32
|
-
import {
|
|
33
|
-
import { createBuiltinInspectorPlugins } from "../inspectors/plugins.ts";
|
|
31
|
+
import { getInspectorPlugins } from "../inspectors/plugins.ts";
|
|
34
32
|
import {
|
|
35
33
|
applySlashUpdate,
|
|
36
34
|
buildSlashInitialResult,
|
|
37
35
|
failSlashResult,
|
|
38
36
|
finalizeSlashResult,
|
|
39
|
-
resolveSlashMessageDetails,
|
|
40
37
|
} from "./slash-live-state.ts";
|
|
41
38
|
import {
|
|
42
39
|
SLASH_RESULT_TYPE,
|
|
@@ -51,7 +48,6 @@ import {
|
|
|
51
48
|
type FleetKeybindingsConfig,
|
|
52
49
|
type SingleResult,
|
|
53
50
|
type SubagentState,
|
|
54
|
-
type Usage,
|
|
55
51
|
} from "../shared/types.ts";
|
|
56
52
|
|
|
57
53
|
interface InlineConfig {
|
|
@@ -125,7 +121,7 @@ function discoverSlashAgents(pi: ExtensionAPI, cwd: string, scope: AgentScope):
|
|
|
125
121
|
...(scope !== "project" ? all.user : []),
|
|
126
122
|
...(scope !== "user" ? all.project : []),
|
|
127
123
|
];
|
|
128
|
-
const merged = mergeRuntimeAgents(pi, discovered, configuredAgents);
|
|
124
|
+
const merged = mergeRuntimeAgents(pi, discovered, configuredAgents, { cwd, scope });
|
|
129
125
|
return { ...merged, unknownAgentDiagnosticContext: { ...unknownAgentDiagnosticContext(discovered), agents: merged.agents } };
|
|
130
126
|
}
|
|
131
127
|
|
|
@@ -328,237 +324,6 @@ class SubagentsStopSelector implements Component {
|
|
|
328
324
|
}
|
|
329
325
|
}
|
|
330
326
|
|
|
331
|
-
function emptyUsage(): Usage {
|
|
332
|
-
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
function addUsage(target: Usage, source: Usage): void {
|
|
336
|
-
target.input += source.input;
|
|
337
|
-
target.output += source.output;
|
|
338
|
-
target.cacheRead += source.cacheRead;
|
|
339
|
-
target.cacheWrite += source.cacheWrite;
|
|
340
|
-
target.cost += source.cost;
|
|
341
|
-
target.turns += source.turns;
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
function usageHasValue(usage: Usage): boolean {
|
|
345
|
-
return usage.input !== 0 || usage.output !== 0 || usage.cacheRead !== 0 || usage.cacheWrite !== 0 || usage.cost !== 0 || usage.turns !== 0;
|
|
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
|
-
|
|
370
|
-
function assistantUsageFromMessage(message: unknown): Usage | undefined {
|
|
371
|
-
if (!message || typeof message !== "object") return undefined;
|
|
372
|
-
const msg = message as { role?: unknown; usage?: unknown };
|
|
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
|
-
}
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
function isSubagentDetails(value: unknown): value is Details {
|
|
405
|
-
if (!value || typeof value !== "object") return false;
|
|
406
|
-
const details = value as { mode?: unknown; results?: unknown };
|
|
407
|
-
return typeof details.mode === "string" && Array.isArray(details.results);
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
function detailsFromSessionEntry(entry: unknown): Details | undefined {
|
|
411
|
-
if (!entry || typeof entry !== "object") return undefined;
|
|
412
|
-
const record = entry as { type?: unknown; customType?: unknown; details?: unknown; message?: unknown };
|
|
413
|
-
if (record.type === "custom_message" && record.customType === SLASH_RESULT_TYPE) {
|
|
414
|
-
const details = resolveSlashMessageDetails(record.details)?.result.details;
|
|
415
|
-
return isSubagentDetails(details) ? details : undefined;
|
|
416
|
-
}
|
|
417
|
-
if (record.type !== "message" || !record.message || typeof record.message !== "object") return undefined;
|
|
418
|
-
const message = record.message as { role?: unknown; toolName?: unknown; details?: unknown };
|
|
419
|
-
if (message.role !== "toolResult" || (message.toolName !== "subagent" && message.toolName !== "bg_wait")) return undefined;
|
|
420
|
-
return isSubagentDetails(message.details) ? message.details : undefined;
|
|
421
|
-
}
|
|
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
|
-
|
|
445
|
-
function formatCostUsage(label: string, usage: Usage): string {
|
|
446
|
-
const extras = [
|
|
447
|
-
usage.cacheRead ? `cache read ${formatTokens(usage.cacheRead)}` : "",
|
|
448
|
-
usage.cacheWrite ? `cache write ${formatTokens(usage.cacheWrite)}` : "",
|
|
449
|
-
usage.turns ? `${usage.turns} turn${usage.turns === 1 ? "" : "s"}` : "",
|
|
450
|
-
].filter(Boolean);
|
|
451
|
-
return `${label}: ↑${formatTokens(usage.input)} ↓${formatTokens(usage.output)} $${usage.cost.toFixed(4)}${extras.length ? ` (${extras.join(", ")})` : ""}`;
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
function buildSubagentCostReport(ctx: ExtensionContext, state: SubagentState): string {
|
|
455
|
-
const parent = emptyUsage();
|
|
456
|
-
const childTotal = emptyUsage();
|
|
457
|
-
const total = emptyUsage();
|
|
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
|
-
|
|
478
|
-
for (const entry of ctx.sessionManager.getBranch()) {
|
|
479
|
-
const message = entry.type === "message" ? (entry as { message?: unknown }).message : undefined;
|
|
480
|
-
const parentUsage = assistantUsageFromMessage(message) ?? compactionUsageFromEntry(entry);
|
|
481
|
-
if (parentUsage) addUsage(parent, parentUsage);
|
|
482
|
-
const details = detailsFromSessionEntry(entry);
|
|
483
|
-
if (!details) continue;
|
|
484
|
-
if (details.mode === "workflow" && details.runId) workflowRunIds.add(details.runId);
|
|
485
|
-
for (const result of details.results) {
|
|
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
|
-
}
|
|
494
|
-
}
|
|
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
|
-
|
|
542
|
-
addUsage(total, parent);
|
|
543
|
-
addUsage(total, childTotal);
|
|
544
|
-
const lines = [
|
|
545
|
-
"Subagent cost",
|
|
546
|
-
"",
|
|
547
|
-
formatCostUsage("Parent", parent),
|
|
548
|
-
];
|
|
549
|
-
if (children.length === 0) {
|
|
550
|
-
lines.push("No subagent child usage found in this session.");
|
|
551
|
-
} else {
|
|
552
|
-
for (const child of children) {
|
|
553
|
-
lines.push(formatCostUsage(child.label, child.usage));
|
|
554
|
-
if (child.sessionFile) lines.push(` Session: ${child.sessionFile}`);
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
if (unresolvedAsyncChildren > 0) lines.push(`Async child usage unavailable: ${unresolvedAsyncChildren}.`);
|
|
558
|
-
lines.push("────────────────────────────", formatCostUsage("Children", childTotal), formatCostUsage("Total", total));
|
|
559
|
-
return lines.join("\n");
|
|
560
|
-
}
|
|
561
|
-
|
|
562
327
|
function parseSingleRequiredArg(args: string, usage: string): { ok: true; value: string } | { ok: false; message: string } {
|
|
563
328
|
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
564
329
|
if (parts.length !== 1) return { ok: false, message: usage };
|
|
@@ -827,14 +592,19 @@ async function runSlashSubagent(
|
|
|
827
592
|
}
|
|
828
593
|
}
|
|
829
594
|
|
|
830
|
-
function slashRunWorkflowScript(key: string, child:
|
|
595
|
+
function slashRunWorkflowScript(key: string, child: SubagentParamsLike): string {
|
|
831
596
|
return `return runs.run(${JSON.stringify(key)}, ${JSON.stringify(child)})`;
|
|
832
597
|
}
|
|
833
598
|
|
|
834
599
|
export function registerSlashCommands(
|
|
835
600
|
pi: ExtensionAPI,
|
|
836
601
|
state: SubagentState,
|
|
837
|
-
options: {
|
|
602
|
+
options: {
|
|
603
|
+
fleetKeybindings?: FleetKeybindingsConfig;
|
|
604
|
+
foregroundDetachShortcut?: string;
|
|
605
|
+
/** disabledFeatures "workflow-scripts": /run launches its one child directly instead of through a script. */
|
|
606
|
+
workflowScriptsDisabled?: boolean;
|
|
607
|
+
} = {},
|
|
838
608
|
): { dispose: () => void } {
|
|
839
609
|
let fleetOpen = false;
|
|
840
610
|
let disposed = false;
|
|
@@ -860,7 +630,8 @@ export function registerSlashCommands(
|
|
|
860
630
|
}
|
|
861
631
|
fleetOpen = true;
|
|
862
632
|
try {
|
|
863
|
-
|
|
633
|
+
const { openSubagentFleet } = await import("../tui/fleet.ts");
|
|
634
|
+
await openSubagentFleet(ctx, state, { asyncDirRoot: DIRS.async, inspectorPlugins: () => getInspectorPlugins(pi), resultsDir: DIRS.results, fleetKeybindings: options.fleetKeybindings, events: pi.events });
|
|
864
635
|
} finally {
|
|
865
636
|
fleetOpen = false;
|
|
866
637
|
}
|
|
@@ -874,7 +645,7 @@ export function registerSlashCommands(
|
|
|
874
645
|
});
|
|
875
646
|
|
|
876
647
|
pi.registerCommand("run", {
|
|
877
|
-
description: "Run one subagent through
|
|
648
|
+
description: "Run one subagent through a workflow script: /run agent[output=file] [task] [--bg] [--fork]",
|
|
878
649
|
getArgumentCompletions: makeAgentCompletions(pi, state),
|
|
879
650
|
handler: async (args, ctx) => {
|
|
880
651
|
const { args: cleanedArgs, bg, fork } = extractExecutionFlags(args);
|
|
@@ -901,20 +672,20 @@ export function registerSlashCommands(
|
|
|
901
672
|
const existingReads = inline.reads.filter((read) => resolveExistingReadPaths([read], state.baseCwd).length > 0);
|
|
902
673
|
if (existingReads.length > 0) finalTask = `[Read from: ${existingReads.join(", ")}]\n\n${finalTask}`;
|
|
903
674
|
}
|
|
904
|
-
const child:
|
|
675
|
+
const child: SubagentParamsLike = { agent: agentName, task: finalTask, agentScope: "both" };
|
|
905
676
|
if (inline.output !== undefined) child.output = inline.output;
|
|
906
677
|
if (inline.outputMode !== undefined) child.outputMode = inline.outputMode;
|
|
907
678
|
if (inline.skill !== undefined) child.skill = inline.skill;
|
|
908
679
|
if (inline.model) child.model = inline.model;
|
|
909
680
|
if (fork) child.context = "fork";
|
|
910
|
-
launchCommand(ctx, { workflowScript: slashRunWorkflowScript("run", child), async: bg
|
|
681
|
+
launchCommand(ctx, options.workflowScriptsDisabled ? { ...child, async: bg } : { workflowScript: slashRunWorkflowScript("run", child), async: bg });
|
|
911
682
|
},
|
|
912
683
|
});
|
|
913
684
|
|
|
914
685
|
pi.registerCommand("subagent-cost", {
|
|
915
686
|
description: "Show parent and subagent child usage cost for this session",
|
|
916
687
|
handler: async (_args, ctx) => {
|
|
917
|
-
sendSlashText(pi,
|
|
688
|
+
sendSlashText(pi, formatSubagentCostReport(collectSubagentCost(ctx, state)));
|
|
918
689
|
},
|
|
919
690
|
});
|
|
920
691
|
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { getArtifactPaths, getArtifactsDir } from "../shared/artifacts.ts";
|
|
5
|
+
import { formatTokens } from "../shared/formatters.ts";
|
|
6
|
+
import { DIRS, SLASH_RESULT_TYPE, type Details, type SingleResult, type SubagentState, type Usage } from "../shared/types.ts";
|
|
7
|
+
import { readStatus } from "../shared/utils.ts";
|
|
8
|
+
import { readWorkflowReceipt } from "../workflows/workflow-receipt.ts";
|
|
9
|
+
import { resolveSlashMessageDetails } from "./slash-live-state.ts";
|
|
10
|
+
|
|
11
|
+
/** Structured parent-plus-child accounting for one session; the source of `/subagent-cost` and the RPC `cost` method. */
|
|
12
|
+
export interface SubagentCostReport {
|
|
13
|
+
version: 1;
|
|
14
|
+
parent: Usage;
|
|
15
|
+
children: SubagentCostChild[];
|
|
16
|
+
childTotal: Usage;
|
|
17
|
+
total: Usage;
|
|
18
|
+
/** Async children whose usage metadata could not be resolved; the child total is a lower bound when this is non-zero. */
|
|
19
|
+
unresolvedAsyncChildren: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface SubagentCostChild {
|
|
23
|
+
label: string;
|
|
24
|
+
agent?: string;
|
|
25
|
+
runId?: string;
|
|
26
|
+
usage: Usage;
|
|
27
|
+
sessionFile?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const SUBAGENT_COST_REPORT_VERSION = 1 as const;
|
|
31
|
+
|
|
32
|
+
function emptyUsage(): Usage {
|
|
33
|
+
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function addUsage(target: Usage, source: Usage): void {
|
|
37
|
+
target.input += source.input;
|
|
38
|
+
target.output += source.output;
|
|
39
|
+
target.cacheRead += source.cacheRead;
|
|
40
|
+
target.cacheWrite += source.cacheWrite;
|
|
41
|
+
target.cost += source.cost;
|
|
42
|
+
target.turns += source.turns;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function usageHasValue(usage: Usage): boolean {
|
|
46
|
+
return usage.input !== 0 || usage.output !== 0 || usage.cacheRead !== 0 || usage.cacheWrite !== 0 || usage.cost !== 0 || usage.turns !== 0;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function nonNegativeNumber(value: unknown): number | undefined {
|
|
50
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function usageFromValue(value: unknown, turnsOverride?: number): Usage | undefined {
|
|
54
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
55
|
+
const record = value as Record<string, unknown>;
|
|
56
|
+
const costValue = typeof record.cost === "object" && record.cost !== null && !Array.isArray(record.cost)
|
|
57
|
+
? (record.cost as Record<string, unknown>).total
|
|
58
|
+
: record.cost;
|
|
59
|
+
const turnsValue = turnsOverride ?? record.turns;
|
|
60
|
+
const usage = {
|
|
61
|
+
input: nonNegativeNumber(record.input) ?? 0,
|
|
62
|
+
output: nonNegativeNumber(record.output) ?? 0,
|
|
63
|
+
cacheRead: nonNegativeNumber(record.cacheRead) ?? 0,
|
|
64
|
+
cacheWrite: nonNegativeNumber(record.cacheWrite) ?? 0,
|
|
65
|
+
cost: nonNegativeNumber(costValue) ?? 0,
|
|
66
|
+
turns: nonNegativeNumber(turnsValue) ?? 0,
|
|
67
|
+
};
|
|
68
|
+
return Number.isSafeInteger(usage.turns) ? usage : undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function assistantUsageFromMessage(message: unknown): Usage | undefined {
|
|
72
|
+
if (!message || typeof message !== "object") return undefined;
|
|
73
|
+
const msg = message as { role?: unknown; usage?: unknown };
|
|
74
|
+
return msg.role === "assistant" ? usageFromValue(msg.usage, 1) : undefined;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function compactionUsageFromEntry(entry: unknown): Usage | undefined {
|
|
78
|
+
if (!entry || typeof entry !== "object") return undefined;
|
|
79
|
+
const record = entry as { type?: unknown; usage?: unknown };
|
|
80
|
+
return record.type === "compaction" ? usageFromValue(record.usage, 0) : undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const MAX_USAGE_METADATA_BYTES = 2 * 1024 * 1024;
|
|
84
|
+
|
|
85
|
+
function readUsageMetadata(metadataPath: string): Record<string, unknown> | undefined {
|
|
86
|
+
let fd: number | undefined;
|
|
87
|
+
try {
|
|
88
|
+
fd = fs.openSync(metadataPath, "r");
|
|
89
|
+
const stat = fs.fstatSync(fd);
|
|
90
|
+
if (!stat.isFile() || stat.size > MAX_USAGE_METADATA_BYTES) return undefined;
|
|
91
|
+
const buffer = Buffer.allocUnsafe(stat.size);
|
|
92
|
+
let offset = 0;
|
|
93
|
+
while (offset < buffer.length) {
|
|
94
|
+
const bytesRead = fs.readSync(fd, buffer, offset, buffer.length - offset, null);
|
|
95
|
+
if (bytesRead <= 0) return undefined;
|
|
96
|
+
offset += bytesRead;
|
|
97
|
+
}
|
|
98
|
+
const value: unknown = JSON.parse(buffer.toString("utf-8"));
|
|
99
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
|
|
100
|
+
} finally {
|
|
101
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function isSubagentDetails(value: unknown): value is Details {
|
|
106
|
+
if (!value || typeof value !== "object") return false;
|
|
107
|
+
const details = value as { mode?: unknown; results?: unknown };
|
|
108
|
+
return typeof details.mode === "string" && Array.isArray(details.results);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function detailsFromSessionEntry(entry: unknown): Details | undefined {
|
|
112
|
+
if (!entry || typeof entry !== "object") return undefined;
|
|
113
|
+
const record = entry as { type?: unknown; customType?: unknown; details?: unknown; message?: unknown };
|
|
114
|
+
if (record.type === "custom_message" && record.customType === SLASH_RESULT_TYPE) {
|
|
115
|
+
const details = resolveSlashMessageDetails(record.details)?.result.details;
|
|
116
|
+
return isSubagentDetails(details) ? details : undefined;
|
|
117
|
+
}
|
|
118
|
+
if (record.type !== "message" || !record.message || typeof record.message !== "object") return undefined;
|
|
119
|
+
const message = record.message as { role?: unknown; toolName?: unknown; details?: unknown };
|
|
120
|
+
if (message.role !== "toolResult" || (message.toolName !== "subagent" && message.toolName !== "bg_wait")) return undefined;
|
|
121
|
+
return isSubagentDetails(message.details) ? message.details : undefined;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function metadataUsage(
|
|
125
|
+
artifactsDirs: string[],
|
|
126
|
+
input: { runId: string; agent: string },
|
|
127
|
+
indexes: ReadonlyArray<number | undefined> = [0, undefined],
|
|
128
|
+
): Usage | undefined {
|
|
129
|
+
if (!/^[A-Za-z0-9._-]+$/.test(input.runId)) return undefined;
|
|
130
|
+
for (const artifactsDir of artifactsDirs) {
|
|
131
|
+
for (const index of indexes) {
|
|
132
|
+
const metadataPath = getArtifactPaths(artifactsDir, input.runId, input.agent, index).metadataPath;
|
|
133
|
+
try {
|
|
134
|
+
const metadata = readUsageMetadata(metadataPath);
|
|
135
|
+
if (!metadata) continue;
|
|
136
|
+
if (metadata.runId !== input.runId || metadata.agent !== input.agent) continue;
|
|
137
|
+
const usage = usageFromValue(metadata.usage);
|
|
138
|
+
if (usage && usageHasValue(usage)) return usage;
|
|
139
|
+
} catch (error) {
|
|
140
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Failed to read subagent usage metadata '${metadataPath}':`, error);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Collect parent and child usage for the current session branch. Foreground
|
|
149
|
+
* children come from persisted `subagent`/`bg_wait` tool-result details; async
|
|
150
|
+
* workflow children are resolved through receipts, and other async runs through
|
|
151
|
+
* their status steps, then artifact metadata.
|
|
152
|
+
*/
|
|
153
|
+
export function collectSubagentCost(
|
|
154
|
+
ctx: ExtensionContext,
|
|
155
|
+
state: Pick<SubagentState, "baseCwd" | "artifactDirPreference">,
|
|
156
|
+
): SubagentCostReport {
|
|
157
|
+
const parent = emptyUsage();
|
|
158
|
+
const childTotal = emptyUsage();
|
|
159
|
+
const total = emptyUsage();
|
|
160
|
+
const children: SubagentCostChild[] = [];
|
|
161
|
+
const seenChildren = new Set<string>();
|
|
162
|
+
const workflowRunIds = new Set<string>();
|
|
163
|
+
const asyncRunIds = new Set<string>();
|
|
164
|
+
const completedRunIds = new Set<string>();
|
|
165
|
+
let unresolvedAsyncChildren = 0;
|
|
166
|
+
|
|
167
|
+
const addChild = (input: { agent?: string; runId?: string; identity?: string; usage?: Usage; sessionFile?: string }): boolean => {
|
|
168
|
+
if (!input.usage || !usageHasValue(input.usage)) return false;
|
|
169
|
+
const identity = input.identity ?? (input.runId ? `run:${input.runId}` : input.sessionFile ? `session:${input.sessionFile}` : undefined);
|
|
170
|
+
if (identity && seenChildren.has(identity)) return true;
|
|
171
|
+
if (identity) seenChildren.add(identity);
|
|
172
|
+
const usage = { ...input.usage };
|
|
173
|
+
children.push({
|
|
174
|
+
label: `Child ${children.length + 1} (${input.agent ?? "unknown"})`,
|
|
175
|
+
...(input.agent ? { agent: input.agent } : {}),
|
|
176
|
+
...(input.runId ? { runId: input.runId } : {}),
|
|
177
|
+
usage,
|
|
178
|
+
...(input.sessionFile ? { sessionFile: input.sessionFile } : {}),
|
|
179
|
+
});
|
|
180
|
+
addUsage(childTotal, usage);
|
|
181
|
+
return true;
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
for (const entry of ctx.sessionManager.getBranch()) {
|
|
185
|
+
const message = entry.type === "message" ? (entry as { message?: unknown }).message : undefined;
|
|
186
|
+
const parentUsage = assistantUsageFromMessage(message) ?? compactionUsageFromEntry(entry);
|
|
187
|
+
if (parentUsage) addUsage(parent, parentUsage);
|
|
188
|
+
const details = detailsFromSessionEntry(entry);
|
|
189
|
+
if (!details) continue;
|
|
190
|
+
if (details.mode === "workflow" && details.runId) workflowRunIds.add(details.runId);
|
|
191
|
+
// An async launch result has no child results; its usage lands in run artifacts.
|
|
192
|
+
else if (details.asyncId && details.results.length === 0) asyncRunIds.add(details.asyncId);
|
|
193
|
+
for (const result of details.results) {
|
|
194
|
+
const resultRunId = (result as SingleResult & { runId?: unknown }).runId;
|
|
195
|
+
addChild({ agent: result.agent, runId: typeof resultRunId === "string" ? resultRunId : undefined, usage: usageFromValue(result.usage), sessionFile: result.sessionFile });
|
|
196
|
+
}
|
|
197
|
+
for (const completion of details.completions ?? []) {
|
|
198
|
+
if (completion.mode === "workflow") workflowRunIds.add(completion.runId);
|
|
199
|
+
completedRunIds.add(completion.runId);
|
|
200
|
+
for (const result of completion.results ?? []) {
|
|
201
|
+
addChild({ agent: result.agent, runId: result.runId, usage: usageFromValue(result.usage), sessionFile: result.sessionFile });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
let sessionFile: string | null = null;
|
|
207
|
+
try {
|
|
208
|
+
sessionFile = ctx.sessionManager.getSessionFile() ?? null;
|
|
209
|
+
} catch { /* an unpersisted session can still report direct child usage */ }
|
|
210
|
+
const artifactsDirs = new Set<string>();
|
|
211
|
+
const addArtifactsDir = (cwd: string | undefined): void => {
|
|
212
|
+
try {
|
|
213
|
+
artifactsDirs.add(getArtifactsDir(sessionFile, cwd, state.artifactDirPreference));
|
|
214
|
+
} catch { /* invalid or unavailable project roots are ignored */ }
|
|
215
|
+
};
|
|
216
|
+
addArtifactsDir(ctx.cwd);
|
|
217
|
+
addArtifactsDir(state.baseCwd);
|
|
218
|
+
|
|
219
|
+
for (const workflowRunId of workflowRunIds) {
|
|
220
|
+
try {
|
|
221
|
+
const status = readStatus(path.join(DIRS.async, workflowRunId));
|
|
222
|
+
addArtifactsDir(status?.cwd);
|
|
223
|
+
const receipt = readWorkflowReceipt(DIRS.async, workflowRunId);
|
|
224
|
+
const summaryChildren = new Map((receipt.workflowChildren?.children ?? []).map((child) => [child.childId, child]));
|
|
225
|
+
const refsByRunId = new Map<string, { runId: string; agent?: string }>();
|
|
226
|
+
const addRef = (runId: string | undefined, agent: string | undefined): void => {
|
|
227
|
+
if (!runId) return;
|
|
228
|
+
const existing = refsByRunId.get(runId);
|
|
229
|
+
if (!existing || (!existing.agent && agent)) refsByRunId.set(runId, { runId, ...(agent ? { agent } : {}) });
|
|
230
|
+
};
|
|
231
|
+
for (const [key, entry] of Object.entries(receipt.entries)) {
|
|
232
|
+
const summaryChild = summaryChildren.get(key);
|
|
233
|
+
const runIds = entry.continuation?.runIds?.length
|
|
234
|
+
? entry.continuation.runIds
|
|
235
|
+
: entry.latestRunId ? [entry.latestRunId] : summaryChild?.runId ? [summaryChild.runId] : [];
|
|
236
|
+
for (const runId of runIds) addRef(runId, entry.agent ?? summaryChild?.agent);
|
|
237
|
+
}
|
|
238
|
+
for (const child of receipt.workflowChildren?.children ?? []) {
|
|
239
|
+
if (!Object.hasOwn(receipt.entries, child.childId)) addRef(child.runId, child.agent);
|
|
240
|
+
}
|
|
241
|
+
for (const ref of refsByRunId.values()) {
|
|
242
|
+
if (seenChildren.has(`run:${ref.runId}`)) continue;
|
|
243
|
+
if (!ref.agent) {
|
|
244
|
+
unresolvedAsyncChildren += 1;
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
const usage = metadataUsage([...artifactsDirs], { runId: ref.runId, agent: ref.agent });
|
|
248
|
+
if (!usage || !addChild({ ...ref, usage })) unresolvedAsyncChildren += 1;
|
|
249
|
+
}
|
|
250
|
+
} catch (error) {
|
|
251
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Failed to resolve async subagent usage for '${workflowRunId}':`, error);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
for (const asyncRunId of asyncRunIds) {
|
|
256
|
+
// A bg_wait completion already reported this run's results; its children carry no child runId.
|
|
257
|
+
if (completedRunIds.has(asyncRunId)) continue;
|
|
258
|
+
try {
|
|
259
|
+
const status = readStatus(path.join(DIRS.async, asyncRunId));
|
|
260
|
+
if (!status?.steps?.length) {
|
|
261
|
+
unresolvedAsyncChildren += 1;
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
addArtifactsDir(status.cwd);
|
|
265
|
+
const steps = status.steps;
|
|
266
|
+
// The runner suffixes artifact names with the flat step index only for multi-step runs.
|
|
267
|
+
steps.forEach((step, index) => {
|
|
268
|
+
const flatIndex = steps.length > 1 ? index : undefined;
|
|
269
|
+
const usage = metadataUsage([...artifactsDirs], { runId: asyncRunId, agent: step.agent }, flatIndex === undefined ? [undefined, 0] : [flatIndex]);
|
|
270
|
+
const identity = flatIndex === undefined ? `run:${asyncRunId}` : `run:${asyncRunId}:${flatIndex}`;
|
|
271
|
+
// Pending and running steps have not finalized their metadata yet.
|
|
272
|
+
const settled = step.status !== "pending" && step.status !== "running";
|
|
273
|
+
if (!addChild({ agent: step.agent, runId: asyncRunId, identity, usage }) && settled) unresolvedAsyncChildren += 1;
|
|
274
|
+
});
|
|
275
|
+
} catch (error) {
|
|
276
|
+
unresolvedAsyncChildren += 1;
|
|
277
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Failed to resolve async subagent usage for '${asyncRunId}':`, error);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
addUsage(total, parent);
|
|
282
|
+
addUsage(total, childTotal);
|
|
283
|
+
return { version: SUBAGENT_COST_REPORT_VERSION, parent, children, childTotal, total, unresolvedAsyncChildren };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function formatCostUsage(label: string, usage: Usage): string {
|
|
287
|
+
const extras = [
|
|
288
|
+
usage.cacheRead ? `cache read ${formatTokens(usage.cacheRead)}` : "",
|
|
289
|
+
usage.cacheWrite ? `cache write ${formatTokens(usage.cacheWrite)}` : "",
|
|
290
|
+
usage.turns ? `${usage.turns} turn${usage.turns === 1 ? "" : "s"}` : "",
|
|
291
|
+
].filter(Boolean);
|
|
292
|
+
return `${label}: ↑${formatTokens(usage.input)} ↓${formatTokens(usage.output)} $${usage.cost.toFixed(4)}${extras.length ? ` (${extras.join(", ")})` : ""}`;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** The `/subagent-cost` text rendering of a collected report. */
|
|
296
|
+
export function formatSubagentCostReport(report: SubagentCostReport): string {
|
|
297
|
+
const lines = [
|
|
298
|
+
"Subagent cost",
|
|
299
|
+
"",
|
|
300
|
+
formatCostUsage("Parent", report.parent),
|
|
301
|
+
];
|
|
302
|
+
if (report.children.length === 0) {
|
|
303
|
+
lines.push("No subagent child usage found in this session.");
|
|
304
|
+
} else {
|
|
305
|
+
for (const child of report.children) {
|
|
306
|
+
lines.push(formatCostUsage(child.label, child.usage));
|
|
307
|
+
if (child.sessionFile) lines.push(` Session: ${child.sessionFile}`);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
if (report.unresolvedAsyncChildren > 0) lines.push(`Async child usage unavailable: ${report.unresolvedAsyncChildren}.`);
|
|
311
|
+
lines.push("────────────────────────────", formatCostUsage("Children", report.childTotal), formatCostUsage("Total", report.total));
|
|
312
|
+
return lines.join("\n");
|
|
313
|
+
}
|