@xzzpig/pi-subagents 0.16.0 → 0.18.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.
Files changed (133) hide show
  1. package/CHANGELOG.md +164 -1
  2. package/README.md +5 -3
  3. package/agents/claude-code-writer.md +1 -0
  4. package/agents/codex-exec-writer.md +1 -0
  5. package/agents/cursor-agent-writer.md +1 -0
  6. package/agents/reviewer.md +3 -2
  7. package/agents/worker.md +3 -2
  8. package/docs/agents.md +17 -10
  9. package/docs/configuration.md +21 -3
  10. package/docs/extension-api.md +70 -4
  11. package/docs/models.md +5 -3
  12. package/docs/observability.md +23 -13
  13. package/docs/standalone-background.md +4 -4
  14. package/docs/tool-reference.md +40 -19
  15. package/docs/watchdog.md +2 -0
  16. package/docs/workflows.md +57 -3
  17. package/inspector-runner.mjs +1 -1
  18. package/package.json +14 -8
  19. package/prompts/council.md +6 -3
  20. package/runner-peer-loader.mjs +4 -7
  21. package/runner-peer-preload.mjs +5 -7
  22. package/skills/pi-subagents/SKILL.md +1 -0
  23. package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
  24. package/skills/pi-subagents/references/execution-controls.md +6 -4
  25. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  26. package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
  27. package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
  28. package/src/agents/agent-eject.ts +3 -3
  29. package/src/agents/agent-management.ts +61 -52
  30. package/src/agents/agent-memory.ts +90 -3
  31. package/src/agents/agent-serializer.ts +4 -4
  32. package/src/agents/agents.ts +125 -51
  33. package/src/agents/global-npm-root.ts +58 -0
  34. package/src/agents/proactive-skills.ts +4 -1
  35. package/src/agents/runtime-agent-registry.ts +14 -11
  36. package/src/agents/skills.ts +42 -9
  37. package/src/api/delegation.ts +15 -0
  38. package/src/api/inspectors.ts +27 -0
  39. package/src/api/preflight.ts +60 -60
  40. package/src/extension/doctor.ts +9 -4
  41. package/src/extension/fanout-child.ts +8 -0
  42. package/src/extension/index.ts +101 -48
  43. package/src/extension/rpc.ts +10 -1
  44. package/src/extension/schemas.ts +12 -6
  45. package/src/extension/subagent-guide.ts +12 -4
  46. package/src/extension/tool-activation.ts +197 -0
  47. package/src/extension/tool-description.ts +1 -1
  48. package/src/inspectors/ghostty/plugin.ts +13 -1
  49. package/src/inspectors/plugins.ts +70 -3
  50. package/src/intercom/intercom-bridge.ts +2 -0
  51. package/src/intercom/native-supervisor-channel.ts +22 -15
  52. package/src/intercom/result-intercom.ts +4 -0
  53. package/src/runs/background/active-async-capacity.ts +3 -25
  54. package/src/runs/background/async-execution.ts +100 -140
  55. package/src/runs/background/async-job-tracker.ts +28 -34
  56. package/src/runs/background/async-resume.ts +16 -8
  57. package/src/runs/background/async-status.ts +2 -0
  58. package/src/runs/background/binary-bootstrap.ts +34 -6
  59. package/src/runs/background/fleet-view.ts +51 -7
  60. package/src/runs/background/notify.ts +93 -7
  61. package/src/runs/background/pid-namespace.ts +18 -0
  62. package/src/runs/background/process-terminal-candidate.ts +98 -0
  63. package/src/runs/background/process-terminal.ts +17 -96
  64. package/src/runs/background/result-watcher.ts +1 -1
  65. package/src/runs/background/retained-children.ts +3 -2
  66. package/src/runs/background/run-child-session.ts +16 -5
  67. package/src/runs/background/run-id-resolver.ts +10 -5
  68. package/src/runs/background/run-status.ts +10 -4
  69. package/src/runs/background/runner-aliases.ts +25 -15
  70. package/src/runs/background/runner-child-launch.ts +1 -2
  71. package/src/runs/background/runner-startup-failure.ts +56 -0
  72. package/src/runs/background/stale-run-reconciler.ts +19 -3
  73. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  74. package/src/runs/background/subagent-runner.ts +96 -287
  75. package/src/runs/background/wait-tool.ts +2 -0
  76. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  77. package/src/runs/foreground/execution.ts +217 -250
  78. package/src/runs/foreground/prompt-audit.ts +3 -9
  79. package/src/runs/foreground/subagent-executor.ts +377 -119
  80. package/src/runs/shared/acceptance.ts +167 -68
  81. package/src/runs/shared/capability-ceiling.ts +4 -1
  82. package/src/runs/shared/child-hooks.ts +1 -16
  83. package/src/runs/shared/child-launch.ts +22 -14
  84. package/src/runs/shared/child-runtime-config.ts +3 -0
  85. package/src/runs/shared/child-session.ts +52 -2
  86. package/src/runs/shared/child-tool-plan.ts +23 -113
  87. package/src/runs/shared/dynamic-fanout.ts +1 -1
  88. package/src/runs/shared/external-cli-runner.ts +3 -1
  89. package/src/runs/shared/external-job-bridge.ts +54 -0
  90. package/src/runs/shared/git-environment.ts +29 -0
  91. package/src/runs/shared/mcp-config-sources.ts +3 -0
  92. package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
  93. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  94. package/src/runs/shared/model-resolution.ts +6 -1
  95. package/src/runs/shared/nested-events.ts +67 -55
  96. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  97. package/src/runs/shared/parallel-utils.ts +2 -1
  98. package/src/runs/shared/pi-spawn.ts +92 -6
  99. package/src/runs/shared/single-output.ts +11 -2
  100. package/src/runs/shared/structured-output.ts +227 -7
  101. package/src/runs/shared/subagent-control.ts +2 -16
  102. package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
  103. package/src/runs/shared/tool-availability.ts +2 -2
  104. package/src/runs/shared/tool-budget.ts +21 -0
  105. package/src/runs/shared/usage-reconciliation.ts +73 -0
  106. package/src/runs/shared/worktree.ts +35 -8
  107. package/src/shared/child-session-name.ts +4 -2
  108. package/src/shared/fork-context.ts +11 -4
  109. package/src/shared/launch-contract.ts +1 -1
  110. package/src/shared/pruned-fork.ts +69 -56
  111. package/src/shared/types.ts +52 -16
  112. package/src/slash/delegation-adapters.ts +25 -1
  113. package/src/slash/prompt-template-bridge.ts +16 -1
  114. package/src/slash/prompt-workflows.ts +12 -1
  115. package/src/slash/slash-commands.ts +7 -241
  116. package/src/slash/subagent-cost.ts +313 -0
  117. package/src/slash/subagents-admin.ts +28 -29
  118. package/src/tui/fleet-status.ts +24 -2
  119. package/src/tui/fleet.ts +7 -4
  120. package/src/tui/render.ts +53 -19
  121. package/src/watchdog/diff-tool.ts +24 -3
  122. package/src/watchdog/permission-arbiter.ts +13 -15
  123. package/src/watchdog/register-child.ts +10 -2
  124. package/src/watchdog/review.ts +14 -14
  125. package/src/watchdog/runtime.ts +2 -1
  126. package/src/watchdog/turn-delta.ts +11 -5
  127. package/src/workflows/scripted-workflow.ts +109 -23
  128. package/src/workflows/workflow-child-summary.ts +4 -2
  129. package/src/workflows/workflow-settlement.ts +4 -1
  130. package/src/runs/shared/completion-evidence.ts +0 -89
  131. package/src/runs/shared/completion-guard.ts +0 -255
  132. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  133. package/src/runs/shared/task-intent.ts +0 -244
@@ -381,7 +381,7 @@ export interface ControlEvent {
381
381
  nestedRunId?: string;
382
382
  nestingPath?: NestedRunAddress["path"];
383
383
  message: string;
384
- reason?: "idle" | "completion_guard" | "active_long_running" | "tool_failures" | "supervisor_request" | "time_threshold" | "turn_threshold" | "token_threshold" | "tool_open_threshold";
384
+ reason?: "idle" | "active_long_running" | "tool_failures" | "supervisor_request" | "time_threshold" | "turn_threshold" | "token_threshold" | "tool_open_threshold";
385
385
  turns?: number;
386
386
  tokens?: number;
387
387
  toolCount?: number;
@@ -397,7 +397,7 @@ export interface ControlEvent {
397
397
  taskPreview?: string;
398
398
  }
399
399
 
400
- export type SubagentResultStatus = "completed" | "failed" | "paused" | "stopped" | "detached";
400
+ export type SubagentResultStatus = "running" | "completed" | "failed" | "paused" | "stopped" | "detached";
401
401
  export type SubagentOutputState = "present" | "absent" | "unknown";
402
402
  export type SubagentRunMode = "single" | "parallel" | "chain" | "workflow";
403
403
  export type SubagentResultMode = SubagentRunMode;
@@ -555,18 +555,14 @@ export interface ReviewProjection {
555
555
  }
556
556
 
557
557
  export interface FileMutationEffect {
558
- status: "not-requested" | "not-applicable" | "observed" | "missing" | "blocked";
559
- expected: boolean;
560
- attempted: boolean;
561
- message?: string;
562
- resolvedBy?: "llm-intent-arbiter";
558
+ status: "observed";
559
+ attempted: true;
563
560
  evidence?: TrackedMutationEvidence;
564
561
  }
565
562
 
566
563
  export interface SettlementDiagnostic {
567
564
  finalTextPresent: boolean;
568
565
  mutation: {
569
- expected: boolean;
570
566
  attempted: boolean;
571
567
  observed: boolean;
572
568
  };
@@ -710,8 +706,29 @@ export type ProcessTerminal =
710
706
  state: "unknown";
711
707
  reason: ProcessTerminalReason;
712
708
  diagnostic?: string;
709
+ /** The runner's own exit, when observed even though the process tree could not be verified. */
710
+ instances?: RunnerProcessInstanceExit[];
713
711
  });
714
712
 
713
+ export type WorkflowTerminalProof =
714
+ | {
715
+ version: 1;
716
+ kind: "workflow";
717
+ runId: string;
718
+ state: "observed";
719
+ dispatchClosed: true;
720
+ observedAt: number;
721
+ children: ProcessTerminal[];
722
+ }
723
+ | {
724
+ version: 1;
725
+ kind: "workflow";
726
+ runId: string;
727
+ state: "pending" | "unknown";
728
+ dispatchClosed: boolean;
729
+ reason: string;
730
+ };
731
+
715
732
  /** Identifies the durable schedule that launched a run, so its completion is attributable. */
716
733
  export interface ScheduleOrigin {
717
734
  id: string;
@@ -829,6 +846,7 @@ export interface SteeringRecoveryDescriptor {
829
846
  tools?: string[];
830
847
  excludeTools?: string[];
831
848
  allowNestedSubagents?: boolean;
849
+ allowedAgents?: string[];
832
850
  extensions?: string[];
833
851
  subagentOnlyExtensions?: string[];
834
852
  mcpDirectTools?: string[];
@@ -841,7 +859,6 @@ export interface SteeringRecoveryDescriptor {
841
859
  skills?: string[];
842
860
  skillPath?: string[];
843
861
  agentFilePath?: string;
844
- completionGuard?: boolean;
845
862
  memory?: { scope: "project" | "user"; path: string };
846
863
  outputPath?: string;
847
864
  outputMode: "inline" | "file-only";
@@ -965,6 +982,9 @@ export interface AgentProgress {
965
982
  thinking?: string;
966
983
  inputTokens?: number;
967
984
  outputTokens?: number;
985
+ /** Cumulative cache-read/cache-write tokens for the current attempt, alongside inputTokens/outputTokens. */
986
+ cacheRead?: number;
987
+ cacheWrite?: number;
968
988
  window?: number;
969
989
  windowPeak?: number;
970
990
  durationMs: number;
@@ -1030,6 +1050,10 @@ export interface AcceptanceVerifyCommand {
1030
1050
  cwd?: string;
1031
1051
  env?: Record<string, string>;
1032
1052
  allowFailure?: boolean;
1053
+ /** When "json", a passing command's stdout is parsed and becomes the run's structured output. */
1054
+ output?: "json";
1055
+ /** Optional JSON Schema the parsed stdout must satisfy; only meaningful with `output: "json"`. */
1056
+ schema?: JsonSchemaObject;
1033
1057
  }
1034
1058
 
1035
1059
  export interface AcceptanceReviewGate {
@@ -1041,6 +1065,8 @@ export interface AcceptanceReviewGate {
1041
1065
  export interface AcceptanceConfig {
1042
1066
  level?: AcceptanceLevel;
1043
1067
  report?: "on" | "off";
1068
+ /** Preserve an intentional launch-time staged index, while rejecting any terminal index change. */
1069
+ preserveStagedIndex?: true;
1044
1070
  criteria?: Array<string | AcceptanceGate>;
1045
1071
  evidence?: AcceptanceEvidenceKind[];
1046
1072
  verify?: AcceptanceVerifyCommand[];
@@ -1065,6 +1091,7 @@ export interface ResolvedAcceptanceConfig {
1065
1091
  inferredReason: string[];
1066
1092
  criteria: ResolvedAcceptanceGate[];
1067
1093
  evidence: AcceptanceEvidenceKind[];
1094
+ preserveStagedIndex?: true;
1068
1095
  verify: AcceptanceVerifyCommand[];
1069
1096
  review?: AcceptanceReviewGate | false;
1070
1097
  stopRules: string[];
@@ -1123,6 +1150,10 @@ export interface AcceptanceVerifyResult {
1123
1150
  diffHash: string;
1124
1151
  };
1125
1152
  artifactError?: string;
1153
+ /** Parsed stdout of a passing `output: "json"` command. */
1154
+ structuredOutput?: unknown;
1155
+ /** Why a passing `output: "json"` command still failed: invalid JSON, truncated stdout, or schema mismatch. */
1156
+ structuredOutputError?: string;
1126
1157
  }
1127
1158
 
1128
1159
  export interface AcceptanceReviewResult {
@@ -1414,6 +1445,7 @@ export interface Details {
1414
1445
  context?: "fresh" | "fork" | "mixed";
1415
1446
  results: SingleResult[];
1416
1447
  workflowChildren?: WorkflowChildSummary;
1448
+ workflowTerminalProof?: WorkflowTerminalProof;
1417
1449
  /**
1418
1450
  * Terminal completion payloads for runs this bg_wait call observed
1419
1451
  * finishing. Async completions travel as result files that are consumed and
@@ -1694,9 +1726,9 @@ export interface AsyncStartedEvent {
1694
1726
  mode?: SubagentRunMode;
1695
1727
  agent?: string;
1696
1728
  agents?: string[];
1697
- /** Truncated first child task retained for backwards compatibility. */
1729
+ /** Redacted prompt marker for the first child task; workflow roots may omit this field. */
1698
1730
  task?: string;
1699
- /** Workflow-level caller task, falling back to the first child task. */
1731
+ /** Redacted prompt marker for the workflow-level caller task or first-child fallback. */
1700
1732
  goal?: string;
1701
1733
  chain?: string[];
1702
1734
  chainStepCount?: number;
@@ -1889,6 +1921,8 @@ export interface AsyncStatus {
1889
1921
  toolBudgetBlocked?: boolean;
1890
1922
  usageBudget?: UsageBudgetState;
1891
1923
  pid?: number;
1924
+ /** Linux PID namespace identity used to scope liveness probes. */
1925
+ pidNamespaceScope?: string;
1892
1926
  cwd?: string;
1893
1927
  /** Parent-resolved child session root retained for trusted restored transcript lookup. */
1894
1928
  sessionRoot?: string;
@@ -1907,6 +1941,8 @@ export interface AsyncStatus {
1907
1941
  launchResolvedExtensions?: LaunchResolvedChildExtensions;
1908
1942
  runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensions;
1909
1943
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
1944
+ /** Parent admission authority before the selected workflow child's descendant restrictions. */
1945
+ admissionCapabilityCeiling?: ResolvedSubagentCapabilityCeiling;
1910
1946
  capabilityAudit?: SubagentCapabilityAudit;
1911
1947
  workflow?: Details["workflow"];
1912
1948
  workflowChildren?: WorkflowChildSummary;
@@ -2286,6 +2322,8 @@ export interface SubagentState {
2286
2322
  liveAsyncSessionRoots?: Map<string, string>;
2287
2323
  /** Foreground nested routes retained after their direct parent settles, keyed by root run id. */
2288
2324
  retainedForegroundNestedRoutes?: Map<string, NestedRouteInfo>;
2325
+ /** Lookup authority outlives live controls, but never crosses the owning session. */
2326
+ retainedNestedLookupRoutes?: { sessionId: string; routes: Map<string, NestedRouteInfo> };
2289
2327
  /** Last valid parent session model observed for this session; used when continuation contexts omit ctx.model. */
2290
2328
  lastParentModel?: { provider: string; id: string };
2291
2329
  subagentInProgress?: boolean;
@@ -2378,6 +2416,8 @@ export interface IntercomEventBus {
2378
2416
 
2379
2417
  export const INTERCOM_DETACH_REQUEST_EVENT = "pi-intercom:detach-request";
2380
2418
  export const INTERCOM_DETACH_RESPONSE_EVENT = "pi-intercom:detach-response";
2419
+ /** pi-intercom asks each session for a fixed intercom ID at session start; `claim(id)` answers synchronously. */
2420
+ export const INTERCOM_SESSION_IDENTITY_EVENT = "intercom:session-identity";
2381
2421
  export const SUBAGENT_ASYNC_STARTED_EVENT = "subagent:async-started";
2382
2422
  export const SUBAGENT_ASYNC_COMPLETE_EVENT = "subagent:async-complete";
2383
2423
  export const SUBAGENT_PROCESS_TERMINAL_EVENT = "subagent:process-terminal";
@@ -2394,7 +2434,7 @@ export interface SubagentChildStatusEvent {
2394
2434
  version: 1;
2395
2435
  runId: string;
2396
2436
  childId: string;
2397
- status: "stopping" | "stopped";
2437
+ status: "started" | "stopping" | "stopped";
2398
2438
  ts: number;
2399
2439
  reason?: string;
2400
2440
  source?: "rpc" | "async";
@@ -2502,8 +2542,6 @@ export interface RunSyncOptions {
2502
2542
  modelOverrideFromParent?: boolean;
2503
2543
  /** How the launch model was selected: explicit per-call, configured agent primary, or inherited parent. */
2504
2544
  modelOrigin?: "explicit" | "inherited" | "configured";
2505
- /** LLM intent arbiter for the completion mutation guard (rescues read-only review runs). */
2506
- llmIntentArbiter?: import("../runs/shared/llm-intent-arbiter.ts").TaskMutationArbiter;
2507
2545
  /** Override the agent's default thinking level for this run */
2508
2546
  thinkingOverride?: AgentConfig["thinking"];
2509
2547
  thinkingCeiling?: ThinkingLevel;
@@ -2518,8 +2556,6 @@ export interface RunSyncOptions {
2518
2556
  preferredModelProvider?: string;
2519
2557
  /** Parent Pi event host used to snapshot runtime-registered MCP servers before child launch. */
2520
2558
  runtimeSnapshotHost?: import("../runs/shared/mcp-direct-tool-allowlist.ts").McpRuntimeSnapshotHost;
2521
- /** Builtin tool names the host runtime provides; used to intersect agent-declared tools. */
2522
- hostAvailableBuiltins?: readonly string[];
2523
2559
  /** Optional subagent model-scope enforcement. */
2524
2560
  modelScope?: ModelScopeRule | ModelScopeRule[];
2525
2561
  /** Skills to make available (overrides agent default if provided) */
@@ -4,9 +4,10 @@ import {
4
4
  type SubagentDelegationStatus,
5
5
  type SubagentDelegationThinking,
6
6
  type SubagentDelegationUpdate,
7
+ type SubagentDelegationUpdateUsage,
7
8
  type SubagentDelegationValue,
8
9
  } from "../api/delegation.ts";
9
- import type { AcceptanceInput, AgentContract, EffectsProjection, ExecutionProjection, IntercomBridgeConfig, JsonSchemaObject, ReviewProjection, ToolBudgetConfig, Usage } from "../shared/types.ts";
10
+ import type { AcceptanceInput, AgentContract, AgentProgress, EffectsProjection, ExecutionProjection, IntercomBridgeConfig, JsonSchemaObject, ReviewProjection, ToolBudgetConfig, Usage } from "../shared/types.ts";
10
11
  import { cloneJsonWithinByteLimit } from "./delegation-json.ts";
11
12
 
12
13
  export interface PromptTemplateDelegationRequest {
@@ -52,6 +53,7 @@ export interface PromptTemplateDelegationUpdate {
52
53
  toolCount?: number;
53
54
  durationMs?: number;
54
55
  tokens?: number;
56
+ usage?: SubagentDelegationUpdateUsage;
55
57
  taskProgress?: PromptTemplateDelegationTaskProgress[];
56
58
  }
57
59
 
@@ -108,6 +110,11 @@ export interface PromptTemplateBridgeResult {
108
110
  toolCount?: number;
109
111
  durationMs?: number;
110
112
  tokens?: number;
113
+ inputTokens?: number;
114
+ outputTokens?: number;
115
+ cacheRead?: number;
116
+ cacheWrite?: number;
117
+ turnCount?: number;
111
118
  }>;
112
119
  };
113
120
  }
@@ -238,6 +245,21 @@ function buildDelegationMessages(
238
245
  return [{ role: "assistant", content }];
239
246
  }
240
247
 
248
+ function isFiniteNonNegative(value: unknown): value is number {
249
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
250
+ }
251
+
252
+ function buildDelegationUpdateUsage(entry: Pick<AgentProgress, "inputTokens" | "outputTokens" | "cacheRead" | "cacheWrite" | "turnCount"> | undefined): SubagentDelegationUpdateUsage | undefined {
253
+ if (!entry) return undefined;
254
+ const { inputTokens, outputTokens, cacheRead, cacheWrite, turnCount } = entry;
255
+ if (!isFiniteNonNegative(inputTokens)
256
+ || !isFiniteNonNegative(outputTokens)
257
+ || !isFiniteNonNegative(cacheRead)
258
+ || !isFiniteNonNegative(cacheWrite)
259
+ || !isFiniteNonNegative(turnCount)) return undefined;
260
+ return { input: inputTokens, output: outputTokens, cacheRead, cacheWrite, turns: turnCount };
261
+ }
262
+
241
263
  export function toDelegationUpdate(requestId: string, update: PromptTemplateBridgeResult): PromptTemplateDelegationUpdate | undefined {
242
264
  const progress = update.details?.progress?.[0];
243
265
  const taskProgress = update.details?.progress?.map((entry) => {
@@ -277,6 +299,7 @@ export function toDelegationUpdate(requestId: string, update: PromptTemplateBrid
277
299
  recentTools: sanitizeRecentTools(progress?.recentTools),
278
300
  model: progress ? resolveProgressModel(update, progress) : undefined,
279
301
  toolCount: progress?.toolCount,
302
+ usage: buildDelegationUpdateUsage(progress),
280
303
  durationMs: progress?.durationMs,
281
304
  tokens: progress?.tokens,
282
305
  taskProgress,
@@ -325,6 +348,7 @@ export function toSubagentDelegationUpdate(
325
348
  ...(typeof legacy.toolCount === "number" ? { toolCount: legacy.toolCount } : {}),
326
349
  ...(typeof legacy.durationMs === "number" ? { durationMs: legacy.durationMs } : {}),
327
350
  ...(typeof legacy.tokens === "number" ? { tokens: legacy.tokens } : {}),
351
+ ...(legacy.usage ? { usage: legacy.usage } : {}),
328
352
  };
329
353
  }
330
354
 
@@ -82,6 +82,20 @@ function sameRecentTools(
82
82
  return left.every((tool, index) => tool.tool === right[index]?.tool && tool.args === right[index]?.args);
83
83
  }
84
84
 
85
+ /** A cache-only or turn-only change with unchanged tokens/tool progress must still count as a change, not a heartbeat. */
86
+ function sameUpdateUsage(
87
+ left: SubagentDelegationUpdate["usage"],
88
+ right: SubagentDelegationUpdate["usage"],
89
+ ): boolean {
90
+ if (left === right) return true;
91
+ if (!left || !right) return false;
92
+ return left.input === right.input
93
+ && left.output === right.output
94
+ && left.cacheRead === right.cacheRead
95
+ && left.cacheWrite === right.cacheWrite
96
+ && left.turns === right.turns;
97
+ }
98
+
85
99
  /** Duration is a heartbeat clock, not delegation-visible progress; terminal usage remains authoritative. */
86
100
  function sameStructuredDelegationUpdateProgress(left: SubagentDelegationUpdate, right: SubagentDelegationUpdate): boolean {
87
101
  return left.requestId === right.requestId
@@ -95,7 +109,8 @@ function sameStructuredDelegationUpdateProgress(left: SubagentDelegationUpdate,
95
109
  && sameRecentTools(left.recentTools, right.recentTools)
96
110
  && left.model === right.model
97
111
  && left.toolCount === right.toolCount
98
- && left.tokens === right.tokens;
112
+ && left.tokens === right.tokens
113
+ && sameUpdateUsage(left.usage, right.usage);
99
114
  }
100
115
 
101
116
  export function registerPromptTemplateDelegationBridge<Ctx extends { cwd?: string }>(
@@ -41,7 +41,18 @@ function readPromptFiles(cwd: string): string[] {
41
41
  continue;
42
42
  }
43
43
  for (const entry of entries) {
44
- if (entry.isFile() && entry.name.endsWith(".md")) files.push(path.join(dir, entry.name));
44
+ if (!entry.name.endsWith(".md")) continue;
45
+ const filePath = path.join(dir, entry.name);
46
+ let isFile = entry.isFile();
47
+ if (entry.isSymbolicLink()) {
48
+ try {
49
+ isFile = fs.statSync(filePath).isFile();
50
+ } catch (error) {
51
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
52
+ isFile = false;
53
+ }
54
+ }
55
+ if (isFile) files.push(filePath);
45
56
  }
46
57
  }
47
58
  return files;
@@ -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 { formatTokens, shortenPath } from "../shared/formatters.ts";
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 { openSubagentFleet } from "../tui/fleet.ts";
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 };
@@ -860,7 +625,8 @@ export function registerSlashCommands(
860
625
  }
861
626
  fleetOpen = true;
862
627
  try {
863
- await openSubagentFleet(ctx, state, { asyncDirRoot: DIRS.async, inspectorPlugins: createBuiltinInspectorPlugins(), resultsDir: DIRS.results, fleetKeybindings: options.fleetKeybindings, events: pi.events });
628
+ const { openSubagentFleet } = await import("../tui/fleet.ts");
629
+ await openSubagentFleet(ctx, state, { asyncDirRoot: DIRS.async, inspectorPlugins: () => getInspectorPlugins(pi), resultsDir: DIRS.results, fleetKeybindings: options.fleetKeybindings, events: pi.events });
864
630
  } finally {
865
631
  fleetOpen = false;
866
632
  }
@@ -914,7 +680,7 @@ export function registerSlashCommands(
914
680
  pi.registerCommand("subagent-cost", {
915
681
  description: "Show parent and subagent child usage cost for this session",
916
682
  handler: async (_args, ctx) => {
917
- sendSlashText(pi, buildSubagentCostReport(ctx, state));
683
+ sendSlashText(pi, formatSubagentCostReport(collectSubagentCost(ctx, state)));
918
684
  },
919
685
  });
920
686