@herbertgao/pi-extensions 2026.11.8 → 2026.11.10

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 (42) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +9 -9
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
  5. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +8 -6
  6. package/node_modules/@herbertgao/pi-cc-extensions/README.md +8 -6
  7. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/config.ts +12 -0
  8. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +36 -13
  9. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/compact-thinking.ts +4 -8
  10. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/context.ts +7 -2
  11. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/footer.ts +115 -6
  12. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +47 -15
  13. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/startup-header.ts +3 -18
  14. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +27 -8
  15. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/default-mode.ts +6 -1
  16. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/markdown-enhance.ts +30 -17
  17. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/scroll.ts +4 -21
  18. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/grouping.ts +13 -0
  19. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/names.ts +3 -13
  20. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/transcript-mode.ts +34 -7
  21. package/node_modules/@herbertgao/pi-cc-extensions/extensions/utils/ansi-text.ts +25 -0
  22. package/node_modules/@herbertgao/pi-cc-extensions/extensions/utils/keybindings.ts +75 -0
  23. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  24. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +6 -0
  25. package/node_modules/@herbertgao/pi-subagents/README.md +26 -17
  26. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
  27. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  28. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +71 -8
  29. package/node_modules/@herbertgao/pi-subagents/src/index.ts +83 -34
  30. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +18 -0
  31. package/node_modules/@herbertgao/pi-subagents/src/types.ts +10 -0
  32. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-tree.ts +47 -0
  33. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +7 -5
  34. package/node_modules/@herbertgao/pi-subagents/src/ui/fleet-list.ts +211 -47
  35. package/node_modules/@narumitw/pi-btw/CHANGELOG.md +7 -0
  36. package/node_modules/@narumitw/pi-btw/package.json +2 -2
  37. package/node_modules/@narumitw/pi-caffeinate/CHANGELOG.md +7 -0
  38. package/node_modules/@narumitw/pi-caffeinate/package.json +3 -3
  39. package/node_modules/pi-commandcode-provider/CHANGELOG.md +5 -0
  40. package/node_modules/pi-commandcode-provider/package.json +1 -1
  41. package/node_modules/pi-commandcode-provider/src/pricing.ts +4 -4
  42. package/package.json +7 -7
@@ -14,17 +14,20 @@
14
14
  * 对话区本身一个状态都不改,关掉弹层即恢复原样。
15
15
  *
16
16
  * Pi 把 app.tools.expand 列为保留键,registerShortcut 注册不上;这里在原始输入到达
17
- * 输入框之前拦截。只认 Pi 自己会响应该键的组件(带 actionHandlers 的编辑器)。
17
+ * 输入框之前拦截。只认 Pi 自己会响应该键的组件(带 actionHandlers 的编辑器),
18
+ * 且对话区里有可展开的 `!` / `!!` 命令输出时把键还给 Pi——它用同一个键展开命令行输出。
18
19
  */
19
20
 
20
21
  import {
21
22
  AssistantMessageComponent,
23
+ BashExecutionComponent,
22
24
  ToolExecutionComponent,
23
25
  UserMessageComponent,
24
26
  } from "@earendil-works/pi-coding-agent";
25
- import { getKeybindings, isKeyRelease, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
27
+ import { isKeyRelease, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
26
28
  import { config } from "../config/config.ts";
27
29
  import { walkComponentTree } from "../utils/component-tree.ts";
30
+ import { keybindings, setInjectedKeybindings } from "../utils/keybindings.ts";
28
31
  import { isCompactRoundTail } from "./compact-mode.ts";
29
32
  import { stripToolFrameMarkers } from "./mouse/packets.ts";
30
33
  import { fullscreenLazyTui, getToolMouseTui } from "./mouse/scroll.ts";
@@ -34,6 +37,9 @@ import { expandShortcutText } from "./tool/names.ts";
34
37
  import { markTranscriptComponent, withTranscriptScope } from "./transcript-scope.ts";
35
38
 
36
39
  const EXPAND_ACTION = "app.tools.expand";
40
+ // pi 的 BashExecutionComponent 在输出超过预览行数且已结束时,才在尾行给出
41
+ // 「ctrl+o to expand」;同样的键这时归 Pi,插件不接管。
42
+ const BASH_PREVIEW_LINES = 20;
37
43
  // 与 Pi 的 tui.altScreen.pageUp/pageDown 同一重叠行数,翻页后保留上下文。
38
44
  const PAGE_SCROLL_OVERLAP = 4;
39
45
  const WHEEL_LINES = 3;
@@ -78,7 +84,7 @@ export function transcriptScrollAction(data: string): ScrollAction | undefined {
78
84
  }
79
85
 
80
86
  export function isTranscriptExitKey(data: string): boolean {
81
- return matchesAny(data, EXIT_KEYS) || getKeybindings().matches(data, EXPAND_ACTION as any);
87
+ return matchesAny(data, EXIT_KEYS) || keybindings().matches(data, EXPAND_ACTION);
82
88
  }
83
89
 
84
90
  // ---------------------------------------------------------------------------
@@ -411,12 +417,28 @@ function canOpen(tui: any): boolean {
411
417
  );
412
418
  }
413
419
 
420
+ /** 对话区里是否有 `!` / `!!` 命令的长输出:这类输出用同一个展开键展开。 */
421
+ function hasExpandableBashOutput(root: any): boolean {
422
+ let found = false;
423
+ walkComponentTree(root, (value: any) => {
424
+ if (found) return false;
425
+ if (!(value instanceof BashExecutionComponent)) return undefined;
426
+ const component = value as any;
427
+ if (component.status === "running") return undefined;
428
+ const output = typeof component.getOutput === "function" ? component.getOutput() : "";
429
+ if (String(output ?? "").split("\n").length > BASH_PREVIEW_LINES) found = true;
430
+ return undefined;
431
+ });
432
+ return found;
433
+ }
434
+
414
435
  function openTranscript(): void {
415
436
  if (!ui || open) return;
416
437
  open = true;
417
438
  void ui
418
439
  .custom<void>(
419
- (tui: any, theme: any, _keybindings: unknown, done: () => void) => {
440
+ (tui: any, theme: any, injectedKeybindings: unknown, done: () => void) => {
441
+ setInjectedKeybindings(injectedKeybindings);
420
442
  closeOpen = done;
421
443
  return new TranscriptView({
422
444
  rows: () => Number(tui?.terminal?.rows) || 24,
@@ -440,9 +462,14 @@ function openTranscript(): void {
440
462
 
441
463
  function handleInput(data: string): { consume?: boolean } | undefined {
442
464
  if (open) return undefined;
443
- if (!getKeybindings().matches(data, EXPAND_ACTION as any)) return undefined;
444
- if (!canOpen(getToolMouseTui())) return undefined;
445
- if (!isKeyRelease(data)) openTranscript();
465
+ if (!keybindings().matches(data, EXPAND_ACTION)) return undefined;
466
+ const tui = getToolMouseTui();
467
+ if (!canOpen(tui)) return undefined;
468
+ // 按键释放事件只吞掉,不再开层,也不交给 Pi 重复处理。
469
+ if (isKeyRelease(data)) return { consume: true };
470
+ // 有可展开的 ! 输出时把键还给 Pi,由它展开/收起命令行输出。
471
+ if (hasExpandableBashOutput(tui)) return undefined;
472
+ openTranscript();
446
473
  return { consume: true };
447
474
  }
448
475
 
@@ -58,6 +58,31 @@ export function imagePlacement(line: string): { rows: number; grows: "down" | "u
58
58
  return undefined;
59
59
  }
60
60
 
61
+ /** 行区里内联图片的两种行:锚点行带图片序列,占位行是它自己铺开的空白。 */
62
+ export type ImageRowKind = "anchor" | "filler";
63
+
64
+ /**
65
+ * 行区里属于内联图片块的行及其种类。
66
+ *
67
+ * 最终输出里这两类行都必须是零宽或只带锚点前的少量前缀:pi-tui 靠「锚点行含图片序列、
68
+ * 其后连续零宽行」认出整块图片。锚点行补底色/空格会画在图片首行上,占位行只要有宽度,
69
+ * 图片块就认不出来,占位行会被当成普通行铺上底色,图片位置只剩一大片空白。
70
+ */
71
+ export function imageBlockRows(rows: string[]): Map<number, ImageRowKind> {
72
+ const kinds = new Map<number, ImageRowKind>();
73
+ for (let index = 0; index < rows.length; index++) {
74
+ const placement = imagePlacement(rows[index]);
75
+ if (!placement) continue;
76
+ kinds.set(index, "anchor");
77
+ const start = placement.grows === "up" ? index - placement.rows + 1 : index + 1;
78
+ const end = placement.grows === "down" ? index + placement.rows - 1 : index - 1;
79
+ for (let row = Math.max(0, start); row <= Math.min(rows.length - 1, end); row++) {
80
+ if (!kinds.has(row)) kinds.set(row, "filler");
81
+ }
82
+ }
83
+ return kinds;
84
+ }
85
+
61
86
  /**
62
87
  * 行区里必须保留的范围(首行/末行下标;没有内容时 first 为 -1)。
63
88
  * 内联图片的行要按 placement 整体算进来:锚点前后那些空行是图片自己占的位置,
@@ -0,0 +1,75 @@
1
+ /**
2
+ * 按键提示与按键匹配的统一取源。
3
+ *
4
+ * pi 1.5.0 起把 `keyText()` / `keyHint()` 放进渲染上下文,把 KeybindingsManager 注入
5
+ * `ctx.ui.custom()` 和编辑器工厂(docs/extensions.md「Keybinding Hints」)。扩展自己
6
+ * import 的那份副本可能看不到用户的 `keybindings.json`,所以这里优先用注入值;
7
+ * 没有注入点的位置(例如原型补丁里的思考块提示)再退回 `getKeybindings()`。
8
+ */
9
+ import { getKeybindings } from "@earendil-works/pi-tui";
10
+
11
+ export type KeybindingsLike = {
12
+ getKeys(id: string): string[];
13
+ matches(data: string, id: string): boolean;
14
+ };
15
+
16
+ type KeyTextSource = (id: string) => string;
17
+
18
+ let injectedManager: KeybindingsLike | undefined;
19
+ let injectedKeyText: KeyTextSource | undefined;
20
+
21
+ function isManager(value: unknown): value is KeybindingsLike {
22
+ const candidate = value as KeybindingsLike | undefined;
23
+ return (
24
+ Boolean(candidate) &&
25
+ typeof candidate?.getKeys === "function" &&
26
+ typeof candidate?.matches === "function"
27
+ );
28
+ }
29
+
30
+ /** 记下 pi 注入的 KeybindingsManager;值不匹配就忽略。 */
31
+ export function setInjectedKeybindings(value: unknown): void {
32
+ if (isManager(value)) injectedManager = value;
33
+ }
34
+
35
+ /** 记下渲染上下文里的 `context.keyText`;值不匹配就忽略。 */
36
+ export function setInjectedKeyText(value: unknown): void {
37
+ if (typeof value === "function") injectedKeyText = value as KeyTextSource;
38
+ }
39
+
40
+ /** 当前的按键管理器:注入值优先,没有时回退到本进程解析到的 pi。 */
41
+ export function keybindings(): KeybindingsLike {
42
+ return injectedManager ?? getKeybindings();
43
+ }
44
+
45
+ function formatKeyPart(part: string, capitalize = false): string {
46
+ // 与 pi 内置 keybinding-hints 一致:macOS 上 alt 显示为 option
47
+ const display = process.platform === "darwin" && part.toLowerCase() === "alt" ? "option" : part;
48
+ return capitalize ? display.charAt(0).toUpperCase() + display.slice(1) : display;
49
+ }
50
+
51
+ /** 把字面按键串(如 `"ctrl+o"`)格式化成显示文本。 */
52
+ export function formatKeyText(key: string, options?: { capitalize?: boolean }): string {
53
+ const capitalize = options?.capitalize === true;
54
+ return key
55
+ .split("/")
56
+ .map((part) =>
57
+ part
58
+ .split("+")
59
+ .map((piece) => formatKeyPart(piece, capitalize))
60
+ .join("+"),
61
+ )
62
+ .join("/");
63
+ }
64
+
65
+ /** 按键显示文本:pi 注入的 keyText 说了算(包括 id 没绑键时的空串);没有注入时本地格式化。 */
66
+ export function keyText(id: string): string {
67
+ if (injectedKeyText) return injectedKeyText(id);
68
+ const keys = keybindings().getKeys(id);
69
+ return keys.length === 0 ? "" : formatKeyText(keys.join("/"));
70
+ }
71
+
72
+ /** 与 pi 的 keyDisplayText 同形:首字母大写,用于 fullscreen 浮层按钮这类原生样式。 */
73
+ export function keyDisplayText(id: string): string {
74
+ return formatKeyText(keyText(id), { capitalize: true });
75
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@herbertgao/pi-cc-extensions",
3
- "version": "1.0.16-local.1",
3
+ "version": "1.0.17-local.1",
4
4
  "license": "MIT",
5
5
  "description": "A Pi productivity suite with Claude Code-style UI, context inspection, and agent/session references",
6
6
  "type": "module",
@@ -74,10 +74,10 @@
74
74
  },
75
75
  "x-upstream": {
76
76
  "package": "pi-cc-extensions",
77
- "version": "1.0.16",
78
- "reviewedVersion": "1.0.16",
77
+ "version": "1.0.17",
78
+ "reviewedVersion": "1.0.17",
79
79
  "repository": "https://github.com/minuque/pi-cc-extensions",
80
- "commit": "5e3ef6b9f96d198f93ec242eac81ff21bebdb4e1",
80
+ "commit": "04c4274d08135b5880bad285f92b11e9b22d115e",
81
81
  "trackVersion": true
82
82
  }
83
83
  }
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.24.0-local.1
4
+
5
+ ### Minor Changes
6
+
7
+ - [#374](https://github.com/HerbertGao/pi-extensions/pull/374) [`4d323bd`](https://github.com/HerbertGao/pi-extensions/commit/4d323bdfd68139885b475e721ad150d9ee4958ea) Thanks [@HerbertGao](https://github.com/HerbertGao)! - Replay upstream pi-subagents 0.24.0. A nested spawn over the nested concurrency limit is refused instead of queued, and Fleet view lists those nested agents under their parent with the model and thinking level. Unconsumed results and a failed worktree cleanup still stay recoverable.
8
+
3
9
  ## 0.23.2-local.1
4
10
 
5
11
  ### Patch Changes
@@ -147,12 +147,15 @@ While subagents are running, a Claude Code-style navigable list renders **below*
147
147
 
148
148
  ● main
149
149
  ○ workflow audit-src 12/40 agents · 32s · ↓ 26.4k tokens
150
- ○ general-purpose Sleep then report 1 11s · ↓ 13.1k tokens
151
- ○ general-purpose Sleep then report 2 11s · ↓ 13.1k tokens
150
+ ❯ ○ general-purpose Review the auth module 41s · ↓ 13.1k tokens
151
+ ├ ○ Explore Find session handling 28s · ↓ 22.7k tokens
152
+ └ ○ Explore Find token refresh 27s · ↓ 19.4k tokens
152
153
  ↓ 3 more
153
154
  ```
154
155
 
155
- Running [workflows](#subagentworkflow) appear as a single `workflow` row above the agents, carrying their agent counts in place of a description. `Enter` on one opens the same two-pane inspector `/agents → Workflows` does, rather than a conversation overlay. A run's own agents are _not_ listed separately — they belong to the run, which reports for them, so they are filtered out of the fleet list, the above-editor widget, the `/agents` menus and `@handle` resolution exactly as nested children are. They are also outside the `maxConcurrent` pool: the run has its own concurrency cap, and routing a fan-out through the session pool as well would let one workflow starve everything else. The agents are ordered earliest-launched first, and only agents you can actually open are shown (pending/queued agents with no session yet appear once they start). At an **empty prompt**, press `↓` (or `←`) to move focus from the prompt into the list — the selected row is marked `●`, the rest `○`. The selected row renders in the theme's primary text color rather than the muted/dim treatment of the others; an agent with a configured `color` shows its badge there too, bolded. `↑`/`↓` move the selection, `Enter` opens the selected agent's live conversation overlay (it auto-updates as the agent works), and `Esc` (or `↑` above `main`) returns to the prompt. Selecting `main` returns to the normal view. Inside the overlay, press `Enter` to steer the running agent — type a message and `Enter` to send it (`Esc` or an empty submit returns), and it redirects the agent the same way the `steer_subagent` tool does. On a running foreground `Agent` call, press `b` to hand that run to the background; the hint only shows where the handoff is available. A viewer stays open when its agent finishes so you can read the final output, and finished agents linger in the list for a few seconds before dropping out. Typing anything at a non-empty prompt behaves normally — the list only captures arrow keys when the prompt is empty. Disable it entirely via `/agents → Settings → Fleet view`.
156
+ Subagents spawned by a subagent (nested delegation) are listed indented under their parent with `├`/`└`, and can be opened, steered and stopped like any other row. Each row's tokens and cost are that agent's own; a parent's figure excludes its children, which have rows of their own. Outside FleetView a parent still reports the rolled-up total, since nested children appear nowhere else.
157
+
158
+ Running [workflows](#subagentworkflow) appear as a single `workflow` row above the agents, carrying their agent counts in place of a description. `Enter` on one opens the same two-pane inspector `/agents → Workflows` does, rather than a conversation overlay. A run's own agents are _not_ listed separately — they belong to the run, which reports for them, so they are filtered out of the fleet list, the above-editor widget, the `/agents` menus and `@handle` resolution (nested children are filtered from all of those but the fleet list). They are also outside the `maxConcurrent` pool: the run has its own concurrency cap, and routing a fan-out through the session pool as well would let one workflow starve everything else. The agents are ordered earliest-launched first, and only agents you can actually open are shown (pending/queued agents with no session yet appear once they start). At an **empty prompt**, press `↓` (or `←`) to move focus from the prompt into the list — the selected row is marked with the `❯` cursor. `●` marks the view in front (`main`, or the agent whose overlay is open), `○` the rest. The selected row renders in the theme's primary text color rather than the muted/dim treatment of the others; an agent with a configured `color` shows its badge there too, bolded. `↑`/`↓` move the selection, `Enter` opens the selected agent's live conversation overlay (it auto-updates as the agent works), and `Esc` (or `↑` above `main`) returns to the prompt. Selecting `main` returns to the normal view. Inside the overlay, press `Enter` to steer the running agent — type a message and `Enter` to send it (`Esc` or an empty submit returns), and it redirects the agent the same way the `steer_subagent` tool does. On a running foreground `Agent` call, press `b` to hand that run to the background; the hint only shows where the handoff is available. A viewer stays open when its agent finishes so you can read the final output, and finished agents linger in the list for a few seconds before dropping out. Typing anything at a non-empty prompt behaves normally — the list only captures arrow keys when the prompt is empty. In fullscreen mode the mouse works too: hovering a row moves the `❯` cursor to it, and clicking a row opens it as `Enter` would (under tmux or screen, pi tracks clicks but not hover; regular mode has no mouse). Disable it entirely via `/agents → Settings → Fleet view`.
156
159
 
157
160
  ### Fullscreen conversation observer
158
161
 
@@ -239,7 +242,7 @@ The grammar mirrors Claude Code's, and is deliberately narrow so nothing gets sw
239
242
  | `@src/index.ts summarize this` | the main model, with pi's normal file attachment |
240
243
  | `@nosuchagent hello` | the main model, verbatim — no agent, no type, no interception |
241
244
 
242
- While an agent is live its handle addresses _it_, so `@explore` never starts a second Explore alongside a running one — use the `Agent` tool for deliberate parallelism. `@<agent-id>` works too. `main` is reserved and can never be an agent's handle (a type slugging to it gets `main-2`); handles are capped at 64 characters. A handle written as typed always wins over the `@agent-` form, so an agent genuinely called `agent-explore` stays reachable. [Nested subagents](#nested-subagents) are not addressable — they are hidden from every top-level surface and only their owner may steer them, so a handle that would name one starts a fresh top-level agent instead of reaching through that boundary. Suggestions list live agents first, then resumable ones, then startable types — and then pi's own file rows, in the same popup: `@` stays the file picker it always was, and the handles are added to it rather than replacing it. Disable the whole thing via `/agents → Settings → Agent mentions`.
245
+ While an agent is live its handle addresses _it_, so `@explore` never starts a second Explore alongside a running one — use the `Agent` tool for deliberate parallelism. `@<agent-id>` works too. `main` is reserved and can never be an agent's handle (a type slugging to it gets `main-2`); handles are capped at 64 characters. A handle written as typed always wins over the `@agent-` form, so an agent genuinely called `agent-explore` stays reachable. [Nested subagents](#nested-subagents) are not addressable — they are hidden from every top-level surface but [FleetView](#fleetview) and only their owner may steer them through tools, so a handle that would name one starts a fresh top-level agent instead of reaching through that boundary. Suggestions list live agents first, then resumable ones, then startable types — and then pi's own file rows, in the same popup: `@` stays the file picker it always was, and the handles are added to it rather than replacing it. Disable the whole thing via `/agents → Settings → Agent mentions`.
243
246
 
244
247
  A `direct`-mode start takes the non-tool spawn path shared with the scheduler and cross-extension RPC, so — like those — it writes no `.output` transcript. That is the trade for skipping the model call: a `model`-mode start goes through the real `Agent` tool and keeps everything. Live tool activity and the turn counter are _not_ part of that trade — a direct start renders them like any other agent. A mention-_resumed_ agent goes through the full resume wiring and keeps both in either mode.
245
248
 
@@ -376,11 +379,11 @@ allowed_subagents: support-file-finder, support-callsite-tracer # or `all`
376
379
 
377
380
  **The allowlist is a privilege boundary, not just a routing hint.** A child runs with _its own_ `tools:`, `extensions:`, and `isolated:` — the parent's restrictions are not inherited — so delegation grants the parent the union of what the listed agents can do. The read-only agent above can write and run commands through any listed agent that can, and `all` reaches every enabled agent including `general-purpose`. Choose the list as carefully as you would choose `tools:` itself; that is the main reason this is default-off.
378
381
 
379
- `allowed_subagents` is runtime-enforced. A comma-separated list restricts nesting to those types; `all` (or `"*"` / `true`, matching how `extensions:` and `skills:` take booleans) allows any enabled agent; omitted, empty, `none`, or `false` means no nested tools are injected at all. Unknown, disabled, and out-of-list types are rejected rather than falling back — regardless of the project's [fallback agent](#persistent-settings) setting, so a configured fallback can never hand a nested caller an agent outside its allowlist — and a nested `model:` is validated against [Model Scope](#model-scope) exactly like a top-level spawn. Result, resume, and steering operations are ownership-scoped, so a parent can control only its own children. Nested records remain internal to that parent and do not appear in top-level tools, lifecycle events, or agent UI — so when a parent finishes, is stopped, or ends a resumed turn, its nested children are stopped with it. They do write their own `.output` transcript (subject to the same `output_transcript` gate), filed under the root session's directory alongside their ancestors', so a nested run can still be inspected after the fact. Their token usage is folded into every ancestor's totals up to the top-level agent (lifecycle events, completion notifications, `/agents`), so nested spend stays attributable at any depth even though the children themselves stay hidden. A nested result that ends `stopped`, `aborted`, or `steered` is labelled as partial, the same guarantee top-level results carry.
382
+ `allowed_subagents` is runtime-enforced. A comma-separated list restricts nesting to those types; `all` (or `"*"` / `true`, matching how `extensions:` and `skills:` take booleans) allows any enabled agent; omitted, empty, `none`, or `false` means no nested tools are injected at all. Unknown, disabled, and out-of-list types are rejected rather than falling back — regardless of the project's [fallback agent](#persistent-settings) setting, so a configured fallback can never hand a nested caller an agent outside its allowlist — and a nested `model:` is validated against [Model Scope](#model-scope) exactly like a top-level spawn. Result, resume, and steering operations are ownership-scoped, so a parent can control only its own children. Nested records remain internal to that parent and do not appear in top-level tools, lifecycle events, or agent UI other than [FleetView](#fleetview) (which lists them under their parent with their own usage) and `/agents → Running agents` — so when a parent finishes, is stopped, or ends a resumed turn, its nested children are stopped with it. They do write their own `.output` transcript (subject to the same `output_transcript` gate), filed under the root session's directory alongside their ancestors', so a nested run can still be inspected after the fact. Their token usage is folded into every ancestor's totals up to the top-level agent (lifecycle events, completion notifications, `/agents`), so nested spend stays attributable at any depth on surfaces where the children themselves stay hidden. A nested result that ends `stopped`, `aborted`, or `steered` is labelled as partial, the same guarantee top-level results carry.
380
383
 
381
384
  The hard cap is depth 2 by default: main session (0) → subagent (1) → nested child (2). Change it project-wide with `maxSubagentDepth` in `subagents.json` (or `/agents → Settings → Nested depth`); `0` or `1` turns nesting off everywhere. An agent already at the cap gets no nested tools at all — not even `get_subagent_result`, since it can never own a child. A child must independently set `allowed_subagents` to delegate again; isolated agents never receive nested tools.
382
385
 
383
- Nested children occupy no concurrency slot, in either pool — their parent already holds one, and queueing them behind it would deadlock a parent waiting on its own child. The depth cap bounds how _deep_ nesting goes, not how _wide_: a parent's only limit on concurrent children is that each spawn costs it a turn. Pair `allowed_subagents` with a `max_turns` on that agent if you want a hard ceiling on its fan-out.
386
+ Nested children occupy no slot in either queueing pool — their parent already holds one, and queueing them behind it would deadlock a parent waiting on its own child. They do count toward the [nested limit](#concurrency) `maxConcurrentNested` (default `10`), which bounds how _wide_ nesting goes: a nested spawn over it is refused, not queued, and the parent gets a tool error telling it to do the work itself. The depth cap bounds how _deep_.
384
387
 
385
388
  Because a subagent session never activates this extension (that is what keeps a child from building a second agent manager, and it is why nested tools are injected directly instead), a subagent also gets none of the extension's other surfaces: no `/agents` command, no cross-extension RPC handlers, no `subagents:ready` event.
386
389
 
@@ -617,10 +620,10 @@ The `/agents` command opens an interactive menu:
617
620
  Running agents (2) — 1 running, 1 done ← only shown when agents exist
618
621
  Agent types (6) ← unified list: defaults + custom
619
622
  Create new agent ← manual wizard or AI-generated
620
- Settings ← max concurrency (background + foreground), max turns, grace turns, join mode
623
+ Settings ← max concurrency (background, foreground, nested), nested depth, max turns, grace turns, join mode
621
624
  ```
622
625
 
623
- - **Running agents** — select one to open its live conversation viewer. While it's still running, press `Enter` to open the steering composer, then `Enter` again to send a message that redirects the agent (same mechanism as the `steer_subagent` tool; `Esc` or an empty submit returns). On a live foreground run, press `b` to hand the same session and in-flight work to the background without stopping or restarting it — the blocked `Agent` call returns the agent ID and the run notifies on completion like any background agent. Press `x` (then `x` again to confirm) to stop/abort it — including **background** agents, which a global Esc can't unambiguously target (Esc still stops a blocking foreground `Agent` call, but no longer reaches one that has been handed off — `x` here does). A stopped agent reports its partial output flagged as incomplete, not as a completion. `m` cycles how much of the transcript renders as Markdown — see [Viewer markdown](#persistent-settings).
626
+ - **Running agents** — select one to open its live conversation viewer. Nested subagents are listed indented under their parent (`├`/`└`), as in [FleetView](#fleetview), and stay here after they finish. While it's still running, press `Enter` to open the steering composer, then `Enter` again to send a message that redirects the agent (same mechanism as the `steer_subagent` tool; `Esc` or an empty submit returns). On a live foreground run, press `b` to hand the same session and in-flight work to the background without stopping or restarting it — the blocked `Agent` call returns the agent ID and the run notifies on completion like any background agent. Press `x` (then `x` again to confirm) to stop/abort it — including **background** agents, which a global Esc can't unambiguously target (Esc still stops a blocking foreground `Agent` call, but no longer reaches one that has been handed off — `x` here does). A stopped agent reports its partial output flagged as incomplete, not as a completion. `m` cycles how much of the transcript renders as Markdown — see [Viewer markdown](#persistent-settings).
624
627
  - **Agent types** — unified list with source indicators: `•` (project), `◦` (global), `▪` ([package](docs/packages.md)), `✕` (disabled), explained by a legend naming only the badges actually on screen. Each row shows the agent's model, and the highlighted agent's full description appears below the list — prefixed with the declaring package's name for a `▪` agent, since the badge alone doesn't say _which_ package. The model column flags `(unavailable, fallback: inherit)` when a configured model can't be resolved (it would silently inherit the parent model), and shows `(→ provider/id)` when it resolves to a different provider or version than configured. Select an agent to manage it:
625
628
  - **Default agents** (no override): Eject (export as `.md`), Disable
626
629
  - **Default agents** (ejected/overridden): Edit, Disable, Reset to default, Delete
@@ -629,7 +632,7 @@ Settings ← max concurrency (background + fo
629
632
  - **Eject** — writes the embedded default config as a `.md` file to project or personal location, so you can customize it
630
633
  - **Disable/Enable** — toggle agent availability. Disabled agents stay visible in the list (marked `✕`) and can be re-enabled
631
634
  - **Create new agent** — choose project/personal location, then manual wizard (step-by-step prompts for name, tools, model, thinking, system prompt) or AI-generated (describe what the agent should do and a sub-agent writes the `.md` file). Any name is allowed, including default agent names (overrides them)
632
- - **Settings** — configure max concurrency (background and foreground), default max turns, grace turns, and join mode at runtime
635
+ - **Settings** — configure max concurrency (background, foreground and nested), nested depth, default max turns, grace turns, and join mode at runtime
633
636
 
634
637
  ## Graceful Max Turns
635
638
 
@@ -650,7 +653,7 @@ A resumed agent gets a fresh budget: `max_turns` is counted from the resume prom
650
653
 
651
654
  ## Concurrency
652
655
 
653
- There are two independent pools.
656
+ Each running agent falls under exactly one limit: top-level agents under one of two queueing pools, nested children under a nested limit, and a workflow's agents under the run's own cap.
654
657
 
655
658
  **Background** (`maxConcurrent`, default 10). Excess agents are automatically queued and start as running agents complete. The widget shows queued agents as a collapsed count. Since agents run in the background by default, nearly every spawn takes a slot; the limit was raised from 4 so that ordinary parallel fan-outs don't queue.
656
659
 
@@ -660,7 +663,11 @@ The two are deliberately **not** one limit. A foreground agent blocks the parent
660
663
 
661
664
  The foreground pool does not cover `resume`: a foreground resume reopens an existing session and never reaches the spawn path, so several blocking resumes in one message can still run at once. A _background_ resume does take a background slot and queues behind them like any other background agent.
662
665
 
663
- Nested children and a [workflow](#subagentworkflow)'s agents are outside the pool entirely. A nested child would deadlock behind a parent waiting on it; a workflow already bounds its own fan-out at `max(1, min(16, cpus - 2))`, and counting its agents twice would let one run fill the session's pool and starve everything else.
666
+ **Nested** (`maxConcurrentNested`, default `10`, `0` = unlimited). It counts running [nested children](#nested-subagents) across the session, including the children of workflow agents. A nested spawn over it is refused, not queued: the nested `Agent` call returns an error telling the parent to do the work itself. Queueing would deadlock a child behind a parent that waits on it. Top-level agents neither count nor are refused. A nested `resume` counts while it runs but is never refused, as in Claude Code.
667
+
668
+ Claude Code instead has one limit, `CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS` (default `20`), which counts every subagent and refuses top-level spawns too. Here top-level spawns queue, and the default 10 background plus 10 nested gives the same 20 at full load. Set all three limits to bound the total.
669
+
670
+ A [workflow](#subagentworkflow)'s agents are outside all three: a workflow already bounds its own fan-out at `max(1, min(16, cpus - 2))`, and counting its agents twice would let one run fill the session's pool and starve everything else.
664
671
 
665
672
  Sending a foreground agent to the background moves its slot: it gives up the foreground slot (so a queued blocking `Agent` call can start) and takes a background one. If the background pool is already full it runs above capacity rather than being suspended, and queued background work waits until the count drops back under the limit.
666
673
 
@@ -704,12 +711,12 @@ When on, each subagent spawn's effective model is validated against pi's own `en
704
711
 
705
712
  ## Persistent Settings
706
713
 
707
- Runtime tuning values set via `/agents` → Settings (max concurrency, max foreground concurrency, default max turns, grace turns, nested depth, fallback agent, default join mode, scheduling on/off, scope models on/off, disable defaults on/off, strict agent files on/off, package agents on/off, package workflows on/off, agent mentions on/off, output transcript on/off, tool description full/compact/custom, widget all/background/off, usage reporting on/off, cost display on/off, model display on/off, viewer markdown off/assistant/all) persist across pi restarts. Two files, merged on load:
714
+ Runtime tuning values set via `/agents` → Settings (max background concurrency, max foreground concurrency, max nested concurrency, nested depth, default max turns, grace turns, fallback agent, default join mode, scheduling on/off, scope models on/off, disable defaults on/off, strict agent files on/off, package agents on/off, package workflows on/off, agent mentions on/off, output transcript on/off, tool description full/compact/custom, widget all/background/off, usage reporting on/off, cost display on/off, model display on/off, viewer markdown off/assistant/all) persist across pi restarts. Two files, merged on load:
708
715
 
709
716
  - **Global:** `~/.pi/agent/subagents.json` — your machine-wide defaults. Edit by hand; the `/agents` menu never writes here.
710
717
  - **Project:** `<cwd>/.pi/subagents.json` — per-project overrides. Written by `/agents` → Settings.
711
718
 
712
- **Precedence:** project overrides global on any field present in both. Missing fields fall back to the hardcoded defaults (max concurrency `10`, max foreground concurrency `0` = unlimited, default max turns unlimited, grace turns `5`, nested depth `2`, join mode `smart`, defaults enabled).
719
+ **Precedence:** project overrides global on any field present in both. Missing fields fall back to the hardcoded defaults (max background concurrency `10`, max foreground concurrency `0` = unlimited, max nested concurrency `10`, default max turns unlimited, grace turns `5`, nested depth `2`, join mode `smart`, defaults enabled).
713
720
 
714
721
  **Nested depth** (`maxSubagentDepth`, default `2`): the hard ceiling on [nested delegation](#nested-subagents), counted from the main session (main = 0, its subagents = 1). `0` or `1` disables nesting project-wide regardless of any agent's `allowed_subagents`. Read when a subagent session is built, so a change applies to agents started after it.
715
722
 
@@ -748,13 +755,14 @@ The `~` marks it as pi's estimate rather than a billed figure. **A cost is shown
748
755
 
749
756
  Independent of `reportUsage`: this one is what you read, that one is what your session counts. Toggle via `/agents → Settings → Show cost`; applied live.
750
757
 
751
- **Show model** (`showModel`, default `false`): whether the widget's running rows name the model driving each agent and the thinking level it is running at:
758
+ **Show model** (`showModel`, default `false`): whether the widget's running rows and the fleet view rows name the model driving each agent and the thinking level it is running at:
752
759
 
753
760
  ```text
754
- ├─ ⠹ Explore inspect code · sonnet 4.6 · thinking: high · ↻3 · 8.2k token · 4.1s
761
+ ├─ ⠹ Explore inspect code · sonnet 4.6 · high · ↻3 · 8.2k token · 4.1s widget
762
+ ○ Explore inspect code · sonnet 4.6 · high 4s · ↓ 8.2k tokens fleet view
755
763
  ```
756
764
 
757
- Off by default because the row already carries the description, turns, tool uses, tokens and elapsed time, and every character it gains is one the description loses on a narrow terminal. The other surfaces show the pair either way: the `Agent` tool result names the model beside its tags, and the conversation viewer's `↳` row spells out the canonical `provider/model-id`.
765
+ Off by default because the row already carries the description, turns, tool uses, tokens and elapsed time, and every character it gains is one the description loses on a narrow terminal. On a fleet row the pair follows the description, so a narrow terminal cuts it before the agent's name or stats. The other surfaces show the pair either way: the `Agent` tool result names the model beside its tags, and the conversation viewer's `↳` row spells out the canonical `provider/model-id`.
758
766
 
759
767
  Both places report what the run _actually_ used, read back from the child session once pi has resolved its defaults and clamped the level to what the model supports — not what the call asked for. Where those differ, the request is kept beside the effective value rather than dropped, whether pi clamped it or an agent file's frontmatter outranked it:
760
768
 
@@ -901,7 +909,7 @@ pi.events.emit("subagents:rpc:spawn", {
901
909
  })
902
910
  ```
903
911
 
904
- `options` is the manager's spawn-option object, not the `Agent` tool's parameter schema — the background flag is `isBackground`, and the tool's snake_case `run_in_background` is forwarded verbatim and ignored. Every RPC spawn returns its id immediately and runs detached either way; `isBackground: true` is what makes the agent occupy one of the `maxConcurrent` slots (and queue behind them when they are full). It does not affect `subagents:created`, which is never emitted for an RPC spawn at all — the first event you see for one is `subagents:started`. Leaving it unset starts the agent immediately regardless of the limit. `maxConcurrentForeground` never applies here whatever `isBackground` says: it bounds only spawns a caller is blocking on inline, and every RPC spawn is detached. A top-level RPC spawn renders in the widget and FleetView while it runs, with the same live tool activity and turn counter an `Agent`-tool spawn gets — only an explicit `isBackground: false` is dropped by the widget's default `background` mode, the way a foreground `Agent` call is. Nested spawns stay hidden from both.
912
+ `options` is the manager's spawn-option object, not the `Agent` tool's parameter schema — the background flag is `isBackground`, and the tool's snake_case `run_in_background` is forwarded verbatim and ignored. Every RPC spawn returns its id immediately and runs detached either way; `isBackground: true` is what makes the agent occupy one of the `maxConcurrent` slots (and queue behind them when they are full). It does not affect `subagents:created`, which is never emitted for an RPC spawn at all — the first event you see for one is `subagents:started`. Leaving it unset starts the agent immediately regardless of the limit. `maxConcurrentForeground` never applies here whatever `isBackground` says: it bounds only spawns a caller is blocking on inline, and every RPC spawn is detached. A top-level RPC spawn renders in the widget and FleetView while it runs, with the same live tool activity and turn counter an `Agent`-tool spawn gets — only an explicit `isBackground: false` is dropped by the widget's default `background` mode, the way a foreground `Agent` call is. Nested spawns stay hidden from the widget; FleetView lists them under their parent.
905
913
 
906
914
  `options.model` accepts either a `Model` object (e.g. `ctx.model`) or a `"provider/modelId"` string — strings are resolved against `ctx.modelRegistry` at the RPC boundary, so cross-extension callers can forward serializable values without losing auth context. Resolution is fuzzy, so a bare `"sonnet"` can land on a provider you never named: with [Model Scope](#model-scope) on, an override that resolves outside `enabledModels` is refused with an error envelope listing the allowed models, exactly as a caller-supplied `Agent({ model })` is. `null` means unset — the agent inherits, same as omitting the field.
907
915
 
@@ -1118,6 +1126,7 @@ src/
1118
1126
  ui/
1119
1127
  agent-widget.ts # Persistent widget: spinners, activity, status icons, theming
1120
1128
  fleet-list.ts # FleetView: navigable agent list below the editor
1129
+ agent-tree.ts # Nested agents laid out under their parent (FleetView, /agents)
1121
1130
  conversation-viewer.ts # Live conversation overlay for viewing agent sessions
1122
1131
  viewer-keys.ts # Viewer scroll, expand and jump keys, resolved through user keybindings
1123
1132
  agent-mention.ts # `@` roster (running, resumable, and startable agents) + popup rows
@@ -341,7 +341,7 @@ These are three different things and are easy to conflate: 1000 is a budget for
341
341
 
342
342
  Above 25 scheduled agents, or 1.5M tokens actual or projected, the card adds `⚠ Large workflow · /agents → Workflows to stop`.
343
343
 
344
- A run's concurrency limit is its own, independent of the session's `maxConcurrent` and `maxConcurrentForeground` pools — its agents do not enter either.
344
+ A run's concurrency limit is its own, independent of the session's `maxConcurrent` and `maxConcurrentForeground` pools — its agents do not enter either, and do not count toward `maxConcurrentNested`. Nested children that a workflow agent spawns through `allowed_subagents` do count, and are refused over that limit.
345
345
 
346
346
  ### Settings and the CLI flag
347
347
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@herbertgao/pi-subagents",
3
- "version": "0.23.2-local.1",
3
+ "version": "0.24.0-local.1",
4
4
  "description": "Claude Code-style autonomous subagents and workflow orchestration for Pi, with HerbertGao-maintained UI extensions.",
5
5
  "keywords": [
6
6
  "agent",
@@ -69,10 +69,10 @@
69
69
  },
70
70
  "x-upstream": {
71
71
  "package": "@tintinweb/pi-subagents",
72
- "version": "0.23.2",
73
- "reviewedVersion": "0.23.2",
72
+ "version": "0.24.0",
73
+ "reviewedVersion": "0.24.0",
74
74
  "repository": "https://github.com/tintinweb/pi-subagents",
75
- "commit": "a35acfb3b699e49f579f494473c38c87592f6c8e",
75
+ "commit": "f0b5304bbfcf4598007a85773a2eac8539536fdd",
76
76
  "trackVersion": true
77
77
  }
78
78
  }
@@ -12,6 +12,9 @@
12
12
  * session of work it could have done itself. Excess agents in either pool are
13
13
  * queued and auto-started as slots free up. Nested children take no slot in
14
14
  * either — see `occupiesPoolSlot` / `occupiesForegroundSlot`.
15
+ *
16
+ * Nested children are bounded by `maxConcurrentNested` instead, which refuses
17
+ * rather than queues — see `spawn`.
15
18
  */
16
19
 
17
20
  import { randomUUID } from "node:crypto"
@@ -64,7 +67,8 @@ export type OnAgentCompact = (record: AgentRecord, info: CompactionInfo) => void
64
67
  * double-booked into ancestors (see `nested-tools.ts`) so a hidden child's spend
65
68
  * shows up on the record a human can see, which makes those records useless as
66
69
  * a basis for anything that must not count a message twice — parent-session
67
- * accounting above all.
70
+ * accounting above all. (`AgentRecord.ownUsage` is the per-record figure that
71
+ * is not double-booked.)
68
72
  */
69
73
  export type OnAgentUsage = (record: AgentRecord, usage: LifetimeUsage) => void
70
74
  export type CompactionInfo = {
@@ -96,6 +100,13 @@ const DEFAULT_MAX_CONCURRENT = 10
96
100
  */
97
101
  const DEFAULT_MAX_CONCURRENT_FOREGROUND = 0
98
102
 
103
+ /**
104
+ * Default cap on running nested children. Added to a full background pool
105
+ * (`DEFAULT_MAX_CONCURRENT`) it gives 20, Claude Code's default for
106
+ * `CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS`.
107
+ */
108
+ const DEFAULT_MAX_CONCURRENT_NESTED = 10
109
+
99
110
  /**
100
111
  * How many evicted agents stay addressable by name. Only a bound on memory —
101
112
  * a session that spawns hundreds of agents shouldn't retain every one — and
@@ -145,9 +156,7 @@ function assertValidSpawnCwd(
145
156
  * Nested children don't: their parent already holds a slot, so counting (and
146
157
  * therefore queueing) them would deadlock a parent that waits on its own child.
147
158
  *
148
- * Note this bounds nothing horizontally — the depth cap limits how DEEP nesting
149
- * goes, not how WIDE. A parent's only limit on concurrent children is that each
150
- * spawn costs it a turn, which is unbounded when max turns is unlimited.
159
+ * How WIDE nesting goes is bounded by `maxConcurrentNested` — see `spawn`.
151
160
  */
152
161
  function occupiesPoolSlot(
153
162
  record: Pick<AgentRecord, "isBackground" | "parentAgentId" | "workflowId">,
@@ -159,10 +168,12 @@ function occupiesPoolSlot(
159
168
  * Whether a record is one of the session's own agents, rather than something
160
169
  * another agent or a workflow owns.
161
170
  *
162
- * The single definition behind every user-facing surface — the fleet list, the
163
- * widget, the `/agents` menus, `@handle` resolution, and the completion events
164
- * and session entries. An owned child reports through its owner, so surfacing
165
- * it separately would double-count the same work in the places a person reads.
171
+ * The single definition behind the user-facing surfaces — the widget, `@handle`
172
+ * resolution, and the completion events and session entries. An owned child
173
+ * reports through its owner, so surfacing it separately would double-count the
174
+ * same work in the places a person reads. FleetView and `/agents → Running
175
+ * agents` are the exceptions: they list Agent-tool children under their parent
176
+ * (`agentTree`), with no rolled-up figures to double-count.
166
177
  */
167
178
  export function isTopLevelAgent(
168
179
  record: Pick<AgentRecord, "parentAgentId" | "workflowId">,
@@ -443,6 +454,7 @@ export class AgentManager {
443
454
  private onSteered?: OnAgentSteered
444
455
  private maxConcurrent: number
445
456
  private maxConcurrentForeground = DEFAULT_MAX_CONCURRENT_FOREGROUND
457
+ private maxConcurrentNested = DEFAULT_MAX_CONCURRENT_NESTED
446
458
  /** Base repos worktrees were created from — so dispose() can prune them all,
447
459
  * not just the parent repo (caller-supplied cwd can target other repos). */
448
460
  private worktreeRepos = new Set<string>()
@@ -534,6 +546,34 @@ export class AgentManager {
534
546
  return this.maxConcurrentForeground
535
547
  }
536
548
 
549
+ /** Update the cap on running nested children, over which nested spawns are refused. 0 = unlimited. */
550
+ setMaxConcurrentNested(n: number) {
551
+ // Nothing queues on this cap, so a change has nothing to drain.
552
+ this.maxConcurrentNested = Math.max(0, n)
553
+ }
554
+
555
+ getMaxConcurrentNested(): number {
556
+ return this.maxConcurrentNested
557
+ }
558
+
559
+ /**
560
+ * Running nested children outside workflows — what `maxConcurrentNested`
561
+ * caps. Read from the records rather than kept as a counter, so no start or
562
+ * settle path can leak a slot.
563
+ */
564
+ private runningNestedCount(): number {
565
+ let n = 0
566
+ for (const record of this.agents.values()) {
567
+ if (
568
+ record.status === "running" &&
569
+ record.parentAgentId !== undefined &&
570
+ record.workflowId === undefined
571
+ )
572
+ n++
573
+ }
574
+ return n
575
+ }
576
+
537
577
  /**
538
578
  * Which pool a spawn is charged to, or undefined for one that is charged to
539
579
  * neither (nested children, detached non-background spawns).
@@ -581,6 +621,25 @@ export class AgentManager {
581
621
  // can fix and retry; the RPC layer converts throws into error envelopes.
582
622
  assertValidSpawnCwd(options.cwd)
583
623
 
624
+ // Nested fan-out is capped by refusing, not queueing: a nested child cannot
625
+ // queue — its parent waits on it while holding a slot — so refusing is the
626
+ // only bound that cannot deadlock. The parent is told to do the work itself,
627
+ // as Claude Code tells it over CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS. Only
628
+ // nested children count; top-level agents have their pools, and a
629
+ // workflow's agents the run's own cap.
630
+ if (
631
+ options.parentAgentId !== undefined &&
632
+ options.workflowId === undefined &&
633
+ this.maxConcurrentNested > 0 &&
634
+ this.runningNestedCount() >= this.maxConcurrentNested
635
+ ) {
636
+ throw new Error(
637
+ `Concurrent nested subagent limit reached. You can run ${this.maxConcurrentNested} nested subagents at once. Do not retry. ` +
638
+ "Complete this task directly with your tools, or if the user wants more, " +
639
+ "ask them to raise maxConcurrentNested in /agents → Settings.",
640
+ )
641
+ }
642
+
584
643
  // A reclaimed id must not be live: the record would replace the one in the
585
644
  // map, orphaning its run beyond the reach of stop and `abortAll()`.
586
645
  // Callers reopen only what they found evicted; this keeps that true.
@@ -622,6 +681,7 @@ export class AgentManager {
622
681
  startedAt: Date.now(),
623
682
  abortController,
624
683
  lifetimeUsage: { input: 0, output: 0, cacheWrite: 0, cost: 0 },
684
+ ownUsage: { input: 0, output: 0, cacheWrite: 0, cost: 0 },
625
685
  compactionCount: 0,
626
686
  // Raw tri-state (not coerced to a boolean): true = background, false =
627
687
  // foreground (has an inline tool-result surface), undefined = caller never
@@ -952,6 +1012,7 @@ export class AgentManager {
952
1012
  onTextDelta: options.onTextDelta,
953
1013
  onAssistantUsage: (usage) => {
954
1014
  addUsage(record.lifetimeUsage, usage)
1015
+ addUsage(record.ownUsage, usage)
955
1016
  this.onUsage?.(record, usage)
956
1017
  options.onAssistantUsage?.(usage)
957
1018
  },
@@ -1446,6 +1507,7 @@ export class AgentManager {
1446
1507
  },
1447
1508
  onAssistantUsage: (usage) => {
1448
1509
  addUsage(record.lifetimeUsage, usage)
1510
+ addUsage(record.ownUsage, usage)
1449
1511
  this.onUsage?.(record, usage)
1450
1512
  options?.onAssistantUsage?.(usage)
1451
1513
  },
@@ -1587,6 +1649,7 @@ export class AgentManager {
1587
1649
  },
1588
1650
  onAssistantUsage: (usage) => {
1589
1651
  addUsage(record.lifetimeUsage, usage)
1652
+ addUsage(record.ownUsage, usage)
1590
1653
  this.onUsage?.(record, usage)
1591
1654
  options.onAssistantUsage?.(usage)
1592
1655
  },