@herbertgao/pi-extensions 2026.11.9 → 2026.11.11

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 (75) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +6 -6
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +12 -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 +34 -10
  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 +63 -7
  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/tool/tool-io.ts +0 -5
  21. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/transcript-mode.ts +34 -7
  22. package/node_modules/@herbertgao/pi-cc-extensions/extensions/utils/ansi-text.ts +43 -4
  23. package/node_modules/@herbertgao/pi-cc-extensions/extensions/utils/keybindings.ts +75 -0
  24. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  25. package/node_modules/@herbertgao/pi-impeccable/CHANGELOG.md +6 -0
  26. package/node_modules/@herbertgao/pi-impeccable/README.md +2 -2
  27. package/node_modules/@herbertgao/pi-impeccable/package.json +4 -4
  28. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/SKILL.md +3 -1
  29. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/adapt.md +1 -1
  30. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/audit.md +12 -1
  31. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/audit.native.md +4 -0
  32. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/critique.md +5 -5
  33. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/degraded/documenter.md +1 -1
  34. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/degraded/finish-reviewer.md +1 -1
  35. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/distill.md +1 -1
  36. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/document.md +3 -1
  37. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/foundations.md +44 -0
  38. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/live-setup.md +1 -1
  39. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/live.md +26 -12
  40. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/new-work.md +10 -9
  41. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/onboard.md +7 -6
  42. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/overdrive.md +2 -2
  43. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/quieter.md +1 -1
  44. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/visualize.md +1 -1
  45. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/VERSION +1 -1
  46. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/engine-checksums.txt +5 -5
  47. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/impeccable +69 -16
  48. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/impeccable.cmd +55 -7
  49. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/live-browser.js +34 -4
  50. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +12 -0
  51. package/node_modules/@herbertgao/pi-subagents/README.md +53 -26
  52. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +12 -12
  53. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  54. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +84 -8
  55. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +51 -32
  56. package/node_modules/@herbertgao/pi-subagents/src/default-agents.ts +7 -0
  57. package/node_modules/@herbertgao/pi-subagents/src/index.ts +369 -879
  58. package/node_modules/@herbertgao/pi-subagents/src/nested-tools.ts +4 -1
  59. package/node_modules/@herbertgao/pi-subagents/src/prompts.ts +13 -0
  60. package/node_modules/@herbertgao/pi-subagents/src/schedule-store.ts +18 -13
  61. package/node_modules/@herbertgao/pi-subagents/src/schedule.ts +25 -5
  62. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +225 -61
  63. package/node_modules/@herbertgao/pi-subagents/src/types.ts +27 -0
  64. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-tree.ts +47 -0
  65. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +16 -5
  66. package/node_modules/@herbertgao/pi-subagents/src/ui/agents-menu.ts +705 -0
  67. package/node_modules/@herbertgao/pi-subagents/src/ui/fleet-list.ts +211 -47
  68. package/node_modules/@herbertgao/pi-subagents/src/ui/settings-menu.ts +361 -0
  69. package/node_modules/@herbertgao/pi-subagents/src/ui/viewer-keys.ts +1 -1
  70. package/node_modules/pi-commandcode-provider/CHANGELOG.md +11 -1
  71. package/node_modules/pi-commandcode-provider/index.ts +2 -1
  72. package/node_modules/pi-commandcode-provider/package.json +5 -4
  73. package/node_modules/pi-commandcode-provider/src/pricing.ts +8 -1
  74. package/node_modules/pi-commandcode-provider/src/responses-compat.ts +137 -0
  75. package/package.json +5 -5
@@ -201,7 +201,10 @@ export function createNestedSubagentTools(
201
201
  label: "Agent",
202
202
  description:
203
203
  "Launch a child-safe nested subagent for bounded delegated work. " +
204
- "Only use agent types allowed by this parent agent; nesting is depth-limited.",
204
+ "Only use agent types allowed by this parent agent; nesting is depth-limited. " +
205
+ // Overrides the main session's inherited Agent guideline ("you will be
206
+ // notified on completion"), which does not hold for nested children.
207
+ "A background nested agent does NOT notify you when it finishes: collect each one with get_subagent_result (wait: true) before you end your turn, or it is stopped and its work is lost.",
205
208
  parameters: Type.Object({
206
209
  prompt: Type.String({
207
210
  description: "Self-contained task for the nested agent.",
@@ -33,6 +33,13 @@ export interface PromptExtras {
33
33
  * `get_subagent_result` — so terse raw data would be the wrong answer there.
34
34
  */
35
35
  workflowChild?: boolean
36
+ /**
37
+ * Set only for the built-in general-purpose, and only when it received the
38
+ * nested `Agent` tool. Claude Code's general-purpose prompt closes with this
39
+ * line; without it a delegating agent tends to hand its whole task to one
40
+ * child. An agent that cannot spawn gets nothing to misread.
41
+ */
42
+ delegationGuideline?: boolean
36
43
  }
37
44
 
38
45
  /**
@@ -86,6 +93,11 @@ Return only the answer, in exactly the shape the prompt asks for — no preamble
86
93
  </workflow_child>`
87
94
  : ""
88
95
 
96
+ // Append mode only: the one agent that gets this, general-purpose, is append.
97
+ const delegationBlock = extras?.delegationGuideline
98
+ ? "\n\nYou are already the dedicated agent for this task. Do the work directly — do not re-delegate your entire assignment to another single subagent."
99
+ : ""
100
+
89
101
  // Build optional extras suffix
90
102
  const extraSections: string[] = []
91
103
  if (extras?.memoryBlock) {
@@ -133,6 +145,7 @@ You are operating as a sub-agent invoked to handle a specific task.
133
145
  envBlock +
134
146
  worktreeBlock +
135
147
  workflowBlock +
148
+ delegationBlock +
136
149
  customSection +
137
150
  extrasSuffix
138
151
  )
@@ -21,7 +21,6 @@ import {
21
21
  import { dirname, join } from "node:path"
22
22
  import type { ScheduledSubagent, ScheduleStoreData } from "./types.js"
23
23
 
24
- const LOCK_RETRY_MS = 50
25
24
  const LOCK_MAX_RETRIES = 100
26
25
 
27
26
  function isProcessRunning(pid: number): boolean {
@@ -39,23 +38,29 @@ function acquireLock(lockPath: string): void {
39
38
  writeFileSync(lockPath, `${process.pid}`, { flag: "wx" })
40
39
  return
41
40
  } catch (e: any) {
42
- if (e.code === "EEXIST") {
41
+ if (e.code !== "EEXIST") throw e
42
+ let pid: number
43
+ try {
44
+ pid = parseInt(readFileSync(lockPath, "utf-8"), 10)
45
+ } catch {
46
+ // unreadable lock: never unlink what we cant prove stale
47
+ throw new Error(`Schedule store lock is unreadable: ${lockPath}`)
48
+ }
49
+ // empty/garbage content is the create-write race window, not staleness
50
+ if (!Number.isInteger(pid)) {
51
+ throw new Error(`Schedule store lock has no valid PID: ${lockPath}`)
52
+ }
53
+ if (pid === process.pid || !isProcessRunning(pid)) {
43
54
  try {
44
- const pid = parseInt(readFileSync(lockPath, "utf-8"), 10)
45
- if (pid && !isProcessRunning(pid)) {
46
- unlinkSync(lockPath)
47
- continue
48
- }
55
+ unlinkSync(lockPath)
49
56
  } catch {
50
- /* ignore — try again */
51
- }
52
- const start = Date.now()
53
- while (Date.now() - start < LOCK_RETRY_MS) {
54
- /* busy wait */
57
+ // raced, retry writeFile
55
58
  }
56
59
  continue
57
60
  }
58
- throw e
61
+ throw new Error(
62
+ `Schedule store is locked by live process ${pid}: ${lockPath}`,
63
+ )
59
64
  }
60
65
  }
61
66
  throw new Error(`Failed to acquire schedule lock: ${lockPath}`)
@@ -196,8 +196,7 @@ export class SubagentScheduler {
196
196
  const t = setTimeout(() => {
197
197
  this.executeJob(job.id)
198
198
  // Auto-disable one-shots after they fire (mirrors pi-cron-schedule)
199
- store.update(job.id, { enabled: false })
200
- const updated = store.get(job.id)
199
+ const updated = this.persist(job.id, { enabled: false })
201
200
  if (updated) this.emit({ type: "updated", job: updated })
202
201
  }, delay)
203
202
  this.intervals.set(job.id, t)
@@ -251,7 +250,7 @@ export class SubagentScheduler {
251
250
  const job = store.get(id)
252
251
  if (!job?.enabled) return
253
252
 
254
- store.update(id, { lastStatus: "running" })
253
+ this.persist(id, { lastStatus: "running" })
255
254
 
256
255
  // Resolve model at fire time — registry contents may have changed since the
257
256
  // job was created (auth added/removed). Fall back silently to spawn-default
@@ -298,7 +297,7 @@ export class SubagentScheduler {
298
297
  })
299
298
  } catch (err) {
300
299
  const error = err instanceof Error ? err.message : String(err)
301
- store.update(id, {
300
+ this.persist(id, {
302
301
  lastRun: new Date().toISOString(),
303
302
  lastStatus: "error",
304
303
  })
@@ -311,7 +310,7 @@ export class SubagentScheduler {
311
310
  const finalize = (status: "success" | "error") => {
312
311
  const next = this.getNextRun(id)
313
312
  const current = store.get(id)
314
- store.update(id, {
313
+ this.persist(id, {
315
314
  lastRun: new Date().toISOString(),
316
315
  lastStatus: status,
317
316
  runCount: (current?.runCount ?? 0) + 1,
@@ -338,6 +337,27 @@ export class SubagentScheduler {
338
337
  .catch(() => finalize("error"))
339
338
  }
340
339
 
340
+ /**
341
+ * Fire-time bookkeeping. A failed persist (e.g. the store lock is held by
342
+ * another process) becomes an error event rather than a throw out of a timer
343
+ * tick; the run itself is unaffected.
344
+ */
345
+ private persist(
346
+ id: string,
347
+ patch: Partial<ScheduledSubagent>,
348
+ ): ScheduledSubagent | undefined {
349
+ try {
350
+ return this.store?.update(id, patch)
351
+ } catch (err) {
352
+ this.emit({
353
+ type: "error",
354
+ jobId: id,
355
+ error: err instanceof Error ? err.message : String(err),
356
+ })
357
+ return undefined
358
+ }
359
+ }
360
+
341
361
  private emit(event: ScheduleChangeEvent): void {
342
362
  if (this.pi) this.pi.events.emit("subagents:scheduled", event)
343
363
  }
@@ -1,6 +1,13 @@
1
1
  // Persistence for pi-subagents operational settings.
2
- // - Global: ~/.pi/agent/subagents.json (via getAgentDir()) — manual defaults, never written here
3
- // - Project: <cwd>/.pi/subagents.json — written by /agents → Settings; overrides global on load
2
+ // - Global: ~/.pi/agent/subagents.json (via getAgentDir()) — machine-wide defaults
3
+ // - Project: <cwd>/.pi/subagents.json — per-project overrides; wins over global on load
4
+ // /agents → Settings writes the scope the page is switched to (Tab). It opens
5
+ // on the project file when the project already has one, and on the global
6
+ // file otherwise — a settings change must not leave a `.pi` directory in every
7
+ // repo the user happens to be in unless they chose Project (#391). Only the
8
+ // keys that changed are merged into the file: the global file is shared by
9
+ // every pi session, and writing a whole snapshot would revert other sessions'
10
+ // changes and freeze built-in defaults into it.
4
11
 
5
12
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
6
13
  import { dirname, join } from "node:path"
@@ -37,6 +44,13 @@ export interface SubagentsSettings {
37
44
  * several blocking resumes in one message can still exceed the limit.
38
45
  */
39
46
  maxConcurrentForeground?: number
47
+ /**
48
+ * Cap on running nested children (outside workflows) — `0` = unlimited,
49
+ * default 10. A nested spawn over it is refused, not queued, and the parent
50
+ * is told to do the work itself (#352). Top-level and workflow agents neither
51
+ * count nor are refused.
52
+ */
53
+ maxConcurrentNested?: number
40
54
  /**
41
55
  * 0 = unlimited — the extension's single source of truth for that convention:
42
56
  * `normalizeMaxTurns()` in agent-runner.ts treats 0 → `undefined`, and the
@@ -351,6 +365,7 @@ export type ToolDescriptionMode = "full" | "compact" | "custom"
351
365
  export interface SettingsAppliers {
352
366
  setMaxConcurrent: (n: number) => void
353
367
  setMaxConcurrentForeground: (n: number) => void
368
+ setMaxConcurrentNested: (n: number) => void
354
369
  setDefaultMaxTurns: (n: number) => void
355
370
  setGraceTurns: (n: number) => void
356
371
  setDefaultJoinMode: (mode: JoinMode) => void
@@ -405,6 +420,81 @@ const MAX_TURNS_CEILING = 10_000
405
420
  const GRACE_TURNS_CEILING = 1_000
406
421
  const SUBAGENT_DEPTH_CEILING = 16
407
422
 
423
+ /** The settings typed as whole numbers. */
424
+ export type NumericSettingKey =
425
+ | "maxConcurrent"
426
+ | "maxConcurrentForeground"
427
+ | "maxConcurrentNested"
428
+ | "defaultMaxTurns"
429
+ | "graceTurns"
430
+ | "maxSubagentDepth"
431
+
432
+ export interface NumericBounds {
433
+ min: number
434
+ max: number
435
+ }
436
+
437
+ /**
438
+ * The accepted range of each number setting, inclusive. Loading drops a value
439
+ * outside it, and `/agents` → Settings refuses to type one, so a value the menu
440
+ * saves always survives a restart. A floor of 0 is where 0 is meaningful:
441
+ * "unlimited" for the foreground/nested caps and max turns, "nesting off" for depth.
442
+ */
443
+ export const NUMERIC_SETTING_BOUNDS: Readonly<
444
+ Record<NumericSettingKey, NumericBounds>
445
+ > = {
446
+ maxConcurrent: { min: 1, max: MAX_CONCURRENT_CEILING },
447
+ maxConcurrentForeground: { min: 0, max: MAX_CONCURRENT_CEILING },
448
+ maxConcurrentNested: { min: 0, max: MAX_CONCURRENT_CEILING },
449
+ defaultMaxTurns: { min: 0, max: MAX_TURNS_CEILING },
450
+ graceTurns: { min: 1, max: GRACE_TURNS_CEILING },
451
+ maxSubagentDepth: { min: 0, max: SUBAGENT_DEPTH_CEILING },
452
+ }
453
+
454
+ /** A typed `/agents → Settings` row: its id is the setting it writes. */
455
+ export const isNumericSettingKey = (id: string): id is NumericSettingKey =>
456
+ Object.hasOwn(NUMERIC_SETTING_BOUNDS, id)
457
+
458
+ /**
459
+ * The value each setting has when no settings file sets it, as the session
460
+ * snapshot reports it — `/agents` → Settings resets a row to this once Del has
461
+ * removed the key from every file. Every key is listed; `undefined` marks one
462
+ * that is unset by default (fallback = general-purpose, workflows and package
463
+ * gates on, and workflows still free to yield to another extension's tool).
464
+ * `test/settings-defaults.test.ts` checks it against a boot with no files.
465
+ */
466
+ export const SETTING_DEFAULTS: {
467
+ readonly [K in keyof Required<SubagentsSettings>]: SubagentsSettings[K]
468
+ } = {
469
+ maxConcurrent: 10,
470
+ maxConcurrentForeground: 0,
471
+ maxConcurrentNested: 10,
472
+ defaultMaxTurns: 0,
473
+ graceTurns: 5,
474
+ defaultJoinMode: "smart",
475
+ backgroundByDefault: true,
476
+ schedulingEnabled: true,
477
+ scopeModels: false,
478
+ strictAgentFiles: false,
479
+ disableDefaultAgents: false,
480
+ toolDescriptionMode: "full",
481
+ fleetView: true,
482
+ agentMentions: "model",
483
+ rememberAgents: true,
484
+ widgetMode: "background",
485
+ outputTranscript: true,
486
+ worktreeIsolation: true,
487
+ workflowsEnabled: undefined,
488
+ maxSubagentDepth: 2,
489
+ fallbackSubagent: undefined,
490
+ reportUsage: false,
491
+ showCost: false,
492
+ showModel: false,
493
+ viewerMarkdown: "assistant",
494
+ packageAgents: undefined,
495
+ packageWorkflows: undefined,
496
+ }
497
+
408
498
  /**
409
499
  * Normalize a package gate: a boolean passes through, an array is trimmed to its
410
500
  * non-empty string entries, a bare string becomes a one-entry allowlist, and
@@ -432,42 +522,13 @@ function sanitize(raw: unknown): SubagentsSettings {
432
522
  if (!raw || typeof raw !== "object") return {}
433
523
  const r = raw as Record<string, unknown>
434
524
  const out: SubagentsSettings = {}
435
- if (
436
- Number.isInteger(r.maxConcurrent) &&
437
- (r.maxConcurrent as number) >= 1 &&
438
- (r.maxConcurrent as number) <= MAX_CONCURRENT_CEILING
439
- ) {
440
- out.maxConcurrent = r.maxConcurrent as number
441
- }
442
- // Floor 0, not 1 like maxConcurrent above: 0 is the documented "unlimited"
443
- // value and the default, so dropping it would silently be unrepresentable.
444
- if (
445
- Number.isInteger(r.maxConcurrentForeground) &&
446
- (r.maxConcurrentForeground as number) >= 0 &&
447
- (r.maxConcurrentForeground as number) <= MAX_CONCURRENT_CEILING
448
- ) {
449
- out.maxConcurrentForeground = r.maxConcurrentForeground as number
450
- }
451
- if (
452
- Number.isInteger(r.defaultMaxTurns) &&
453
- (r.defaultMaxTurns as number) >= 0 &&
454
- (r.defaultMaxTurns as number) <= MAX_TURNS_CEILING
455
- ) {
456
- out.defaultMaxTurns = r.defaultMaxTurns as number
457
- }
458
- if (
459
- Number.isInteger(r.graceTurns) &&
460
- (r.graceTurns as number) >= 1 &&
461
- (r.graceTurns as number) <= GRACE_TURNS_CEILING
462
- ) {
463
- out.graceTurns = r.graceTurns as number
464
- }
465
- if (
466
- Number.isInteger(r.maxSubagentDepth) &&
467
- (r.maxSubagentDepth as number) >= 0 &&
468
- (r.maxSubagentDepth as number) <= SUBAGENT_DEPTH_CEILING
469
- ) {
470
- out.maxSubagentDepth = r.maxSubagentDepth as number
525
+ for (const [key, { min, max }] of Object.entries(NUMERIC_SETTING_BOUNDS) as [
526
+ NumericSettingKey,
527
+ NumericBounds,
528
+ ][]) {
529
+ const v = r[key]
530
+ if (Number.isInteger(v) && (v as number) >= min && (v as number) <= max)
531
+ out[key] = v as number
471
532
  }
472
533
  if (
473
534
  typeof r.defaultJoinMode === "string" &&
@@ -588,6 +649,24 @@ function readSettingsFile(path: string): SubagentsSettings {
588
649
  }
589
650
  }
590
651
 
652
+ /** Which settings file a save wrote: `~/.pi/agent/subagents.json` or `<cwd>/.pi/subagents.json`. */
653
+ export type SettingsScope = "global" | "project"
654
+
655
+ /** The scope a save targets unless one is chosen: project if its file exists, else global (#391). */
656
+ export function defaultSettingsScope(
657
+ cwd: string = process.cwd(),
658
+ ): SettingsScope {
659
+ return existsSync(projectPath(cwd)) ? "project" : "global"
660
+ }
661
+
662
+ /** The file a scope reads and writes. */
663
+ export function settingsFilePath(
664
+ scope: SettingsScope,
665
+ cwd: string = process.cwd(),
666
+ ): string {
667
+ return scope === "project" ? projectPath(cwd) : globalPath()
668
+ }
669
+
591
670
  /** Load merged settings: global provides defaults, project overrides. */
592
671
  export function loadSettings(cwd: string = process.cwd()): SubagentsSettings {
593
672
  return {
@@ -597,21 +676,88 @@ export function loadSettings(cwd: string = process.cwd()): SubagentsSettings {
597
676
  }
598
677
 
599
678
  /**
600
- * Write project-local settings. Global is never touched from code.
601
- * Returns `true` on success, `false` if the write (or mkdir) failed so the
602
- * caller can surface a warning — persistence isn't fatal but isn't silent.
679
+ * Which file supplies each key's loaded value: `project` when the project file
680
+ * sets it (it wins on load), else `global`. A key absent from both is at its
681
+ * shipped default. Invalid values are dropped before this, as on load.
682
+ */
683
+ export function settingSources(
684
+ cwd: string = process.cwd(),
685
+ ): Partial<Record<keyof SubagentsSettings, SettingsScope>> {
686
+ const sources: Partial<Record<keyof SubagentsSettings, SettingsScope>> = {}
687
+ for (const key of Object.keys(readSettingsFile(globalPath())))
688
+ sources[key as keyof SubagentsSettings] = "global"
689
+ for (const key of Object.keys(readSettingsFile(projectPath(cwd))))
690
+ sources[key as keyof SubagentsSettings] = "project"
691
+ return sources
692
+ }
693
+
694
+ /**
695
+ * The keys whose value differs between two snapshots. A key that became
696
+ * unset is present with `undefined`, which `saveSettings` reads as "remove".
697
+ */
698
+ export function changedSettings(
699
+ previous: SubagentsSettings,
700
+ next: SubagentsSettings,
701
+ ): SubagentsSettings {
702
+ const changes: Record<string, unknown> = {}
703
+ for (const key of new Set([...Object.keys(previous), ...Object.keys(next)])) {
704
+ const before = (previous as Record<string, unknown>)[key]
705
+ const after = (next as Record<string, unknown>)[key]
706
+ if (JSON.stringify(before) !== JSON.stringify(after)) changes[key] = after
707
+ }
708
+ return changes as SubagentsSettings
709
+ }
710
+
711
+ /**
712
+ * Merge changed settings into the file of `scope`, which defaults to
713
+ * `defaultSettingsScope`: an explicit `project` creates `.pi/subagents.json`
714
+ * on the first change, the default never does (#391). The target is re-read and
715
+ * only the given keys are set — or removed, when a key's value is `undefined`
716
+ * — so other keys in the file, including ones another session wrote, survive.
717
+ * `applied` is the setting the user just set. It is written too when the file
718
+ * stores a different value for it: the value may be unchanged in memory (it
719
+ * was set in the other scope first) while the chosen file still disagrees.
720
+ * A target that exists but is not a JSON object is left untouched.
721
+ * Returns the scope written, or `undefined` if the write failed so the caller
722
+ * can surface a warning — persistence isn't fatal but isn't silent.
603
723
  */
604
724
  export function saveSettings(
605
- s: SubagentsSettings,
725
+ changes: SubagentsSettings,
606
726
  cwd: string = process.cwd(),
607
- ): boolean {
608
- const path = projectPath(cwd)
727
+ scope: SettingsScope = defaultSettingsScope(cwd),
728
+ applied: SubagentsSettings = {},
729
+ ): SettingsScope | undefined {
730
+ const path = settingsFilePath(scope, cwd)
609
731
  try {
732
+ const current: unknown = existsSync(path)
733
+ ? JSON.parse(readFileSync(path, "utf-8"))
734
+ : {}
735
+ if (
736
+ typeof current !== "object" ||
737
+ current === null ||
738
+ Array.isArray(current)
739
+ )
740
+ return undefined
741
+ const stored = current as Record<string, unknown>
742
+ const stale = Object.entries(applied).filter(
743
+ ([key, value]) =>
744
+ key in stored && JSON.stringify(stored[key]) !== JSON.stringify(value),
745
+ )
746
+ const writes = { ...Object.fromEntries(stale), ...changes }
747
+ // Nothing to write — the file already agrees with what is in effect; don't
748
+ // rewrite it, or create an empty one.
749
+ if (Object.keys(writes).length === 0) return scope
610
750
  mkdirSync(dirname(path), { recursive: true })
611
- writeFileSync(path, JSON.stringify(s, null, 2), "utf-8")
612
- return true
751
+ // An `undefined` change overrides the file's value and is then dropped by
752
+ // JSON.stringify — that is how a key is removed.
753
+ writeFileSync(
754
+ path,
755
+ JSON.stringify({ ...stored, ...writes }, null, 2),
756
+ "utf-8",
757
+ )
758
+ return scope
613
759
  } catch {
614
- return false
760
+ return undefined
615
761
  }
616
762
  }
617
763
 
@@ -625,6 +771,8 @@ export function applySettings(
625
771
  if (typeof s.maxConcurrentForeground === "number") {
626
772
  appliers.setMaxConcurrentForeground(s.maxConcurrentForeground)
627
773
  }
774
+ if (typeof s.maxConcurrentNested === "number")
775
+ appliers.setMaxConcurrentNested(s.maxConcurrentNested)
628
776
  if (typeof s.defaultMaxTurns === "number")
629
777
  appliers.setDefaultMaxTurns(s.defaultMaxTurns)
630
778
  if (typeof s.graceTurns === "number") appliers.setGraceTurns(s.graceTurns)
@@ -671,14 +819,19 @@ export function applySettings(
671
819
  */
672
820
  export function persistToastFor(
673
821
  successMsg: string,
674
- persisted: boolean,
822
+ scope: SettingsScope | undefined,
823
+ shadowed = false,
675
824
  ): { message: string; level: "info" | "warning" } {
676
- return persisted
677
- ? { message: successMsg, level: "info" }
678
- : {
679
- message: `${successMsg} (session only; failed to persist)`,
680
- level: "warning",
681
- }
825
+ if (!scope)
826
+ return {
827
+ message: `${successMsg} (session only; failed to persist)`,
828
+ level: "warning",
829
+ }
830
+ const note = shadowed ? "; project settings override it" : ""
831
+ return {
832
+ message: `${successMsg} (saved to ${scope} settings${note})`,
833
+ level: "info",
834
+ }
682
835
  }
683
836
 
684
837
  /**
@@ -698,18 +851,29 @@ export function applyAndEmitLoaded(
698
851
  }
699
852
 
700
853
  /**
701
- * Persist a settings snapshot, emit the `subagents:settings_changed` event
702
- * (regardless of persist outcome so listeners see the in-memory change), and
703
- * return the toast the UI should display. Event payload carries the `persisted`
704
- * flag so listeners can react to write failures.
854
+ * Persist what changed between the last saved snapshot and the current one,
855
+ * emit the `subagents:settings_changed` event (regardless of persist outcome
856
+ * so listeners see the in-memory change), and return the toast the UI should
857
+ * display plus whether the write landed. Event payload carries the full
858
+ * snapshot and the same `persisted` flag so listeners can react to failures.
705
859
  */
706
860
  export function saveAndEmitChanged(
707
861
  snapshot: SubagentsSettings,
862
+ previous: SubagentsSettings,
708
863
  successMsg: string,
709
864
  emit: SettingsEmit,
710
865
  cwd: string = process.cwd(),
711
- ): { message: string; level: "info" | "warning" } {
712
- const persisted = saveSettings(snapshot, cwd)
866
+ target?: SettingsScope,
867
+ applied: SubagentsSettings = {},
868
+ ): { message: string; level: "info" | "warning"; persisted: boolean } {
869
+ const changes = changedSettings(previous, snapshot)
870
+ const scope = saveSettings(changes, cwd, target, applied)
871
+ const persisted = scope !== undefined
713
872
  emit("subagents:settings_changed", { settings: snapshot, persisted })
714
- return persistToastFor(successMsg, persisted)
873
+ // A changed value saved to global that the project file overrides holds only
874
+ // for this session; say so rather than let the next restart revert it
875
+ // silently. An unchanged value is already what the next start loads.
876
+ const project = scope === "global" ? readSettingsFile(projectPath(cwd)) : {}
877
+ const shadowed = Object.keys(changes).some((key) => key in project)
878
+ return { ...persistToastFor(successMsg, scope, shadowed), persisted }
715
879
  }
@@ -18,6 +18,23 @@ export const DEFAULT_AGENT_NAMES = [
18
18
  "Plan",
19
19
  ] as const
20
20
 
21
+ /**
22
+ * Advertised thinking levels, ordered to mirror pi-ai's EXTENDED_THINKING_LEVELS
23
+ * (`off` + every `ThinkingLevel`). Single source for the Agent tool description,
24
+ * the generated-agent template, and the `/agents` wizard so these lists can't
25
+ * drift behind pi again (#147). Availability of any level still depends on the
26
+ * host pi version and the selected model — pi clamps unsupported levels down.
27
+ */
28
+ export const THINKING_LEVELS = [
29
+ "off",
30
+ "minimal",
31
+ "low",
32
+ "medium",
33
+ "high",
34
+ "xhigh",
35
+ "max",
36
+ ] as const
37
+
21
38
  /** Memory scope for persistent agent memory. */
22
39
  export type MemoryScope = "user" | "project" | "local"
23
40
 
@@ -265,8 +282,18 @@ export interface AgentRecord {
265
282
  * Lifetime usage breakdown, accumulated via `message_end` events. Survives
266
283
  * compaction. Total = input + output + cacheWrite (cacheRead deliberately
267
284
  * excluded — see issue #38). Initialized to zeros at spawn.
285
+ *
286
+ * Includes every descendant's spend: `nested-tools.ts` folds a nested
287
+ * child's turns into all its ancestors, because the child itself is hidden
288
+ * from the surfaces that read this field.
268
289
  */
269
290
  lifetimeUsage: LifetimeUsage
291
+ /**
292
+ * This agent's own turns only — `lifetimeUsage` minus its descendants. What
293
+ * the fleet list shows, since it gives nested children rows of their own and
294
+ * the rolled-up figure would count their spend twice.
295
+ */
296
+ ownUsage: LifetimeUsage
270
297
  /** Number of times this agent's session has compacted. Initialized to 0 at spawn. */
271
298
  compactionCount: number
272
299
  /**
@@ -0,0 +1,47 @@
1
+ /**
2
+ * agent-tree.ts — Nested subagents laid out under their parent.
3
+ *
4
+ * Shared by the two surfaces that list nested children — FleetView and
5
+ * `/agents → Running agents` — so both draw the same tree. Every other
6
+ * user-facing surface filters on `isTopLevelAgent`.
7
+ */
8
+
9
+ import type { AgentRecord } from "../types.js"
10
+
11
+ export interface AgentTreeRow {
12
+ record: AgentRecord
13
+ /** Tree glyphs before the row (`├ `, `└ `, `│ ` continuation); `""` at top level. */
14
+ prefix: string
15
+ }
16
+
17
+ /**
18
+ * `records` as a tree: each top-level record in the order given, then its
19
+ * children depth-first under it, siblings earliest-launched first. A child
20
+ * whose parent is not in `records` is dropped — it has no row to hang from.
21
+ */
22
+ export function agentTree(records: readonly AgentRecord[]): AgentTreeRow[] {
23
+ const children = new Map<string, AgentRecord[]>()
24
+ for (const record of records) {
25
+ if (record.parentAgentId === undefined) continue
26
+ const siblings = children.get(record.parentAgentId)
27
+ if (siblings) siblings.push(record)
28
+ else children.set(record.parentAgentId, [record])
29
+ }
30
+ for (const siblings of children.values())
31
+ siblings.sort((a, b) => a.startedAt - b.startedAt)
32
+
33
+ const rows: AgentTreeRow[] = []
34
+ // `indent` is what a child's own children continue with: a rail under a
35
+ // `├`, blank under the last sibling's `└`.
36
+ const visit = (record: AgentRecord, prefix: string, indent: string): void => {
37
+ rows.push({ record, prefix })
38
+ const kids = children.get(record.id) ?? []
39
+ kids.forEach((kid, i) => {
40
+ const last = i === kids.length - 1
41
+ visit(kid, indent + (last ? "└ " : "├ "), indent + (last ? " " : "│ "))
42
+ })
43
+ }
44
+ for (const record of records)
45
+ if (record.parentAgentId === undefined) visit(record, "", "")
46
+ return rows
47
+ }
@@ -205,6 +205,15 @@ export function formatMs(ms: number): string {
205
205
  return `${(ms / 1000).toFixed(1)}s`
206
206
  }
207
207
 
208
+ /** Coarse age of a past timestamp: `<1m`, `42m`, `5h`, `3d` (floored). */
209
+ export function formatAge(timestamp: number, now = Date.now()): string {
210
+ const minutes = Math.floor((now - timestamp) / 60_000)
211
+ if (minutes < 1) return "<1m"
212
+ if (minutes < 60) return `${minutes}m`
213
+ const hours = Math.floor(minutes / 60)
214
+ return hours < 24 ? `${hours}h` : `${Math.floor(hours / 24)}d`
215
+ }
216
+
208
217
  /** Format duration from start/completed timestamps. */
209
218
  export function formatDuration(
210
219
  startedAt: number,
@@ -235,6 +244,7 @@ export function getPromptModeLabel(type: SubagentType): string | undefined {
235
244
  export function buildInvocationTags(invocation: AgentInvocation | undefined): {
236
245
  modelName?: string
237
246
  modelId?: string
247
+ thinking?: string
238
248
  tags: string[]
239
249
  } {
240
250
  const tags: string[] = []
@@ -257,6 +267,7 @@ export function buildInvocationTags(invocation: AgentInvocation | undefined): {
257
267
  return {
258
268
  modelName: asked(invocation.modelName, invocation.requestedModel),
259
269
  modelId: asked(invocation.modelId, invocation.requestedModel),
270
+ thinking,
260
271
  tags,
261
272
  }
262
273
  }
@@ -558,12 +569,12 @@ export class AgentWidget {
558
569
  const parts: string[] = []
559
570
  if (this.showModel()) {
560
571
  // Leading, and paired: a thinking level means nothing without the model
561
- // it applies to. The tag is taken from buildInvocationTags rather than
562
- // rebuilt so the "(asked X)" annotation survives.
563
- const { modelName, tags } = buildInvocationTags(a.invocation)
572
+ // it applies to. Both come from buildInvocationTags so the "(asked X)"
573
+ // annotation survives. The level is bare, not "thinking: high", as on
574
+ // the fleet row; the tag list keeps the label for the viewer and tool result.
575
+ const { modelName, thinking } = buildInvocationTags(a.invocation)
564
576
  if (modelName) parts.push(modelName)
565
- const thinkingTag = tags.find((tag) => tag.startsWith("thinking: "))
566
- if (thinkingTag) parts.push(thinkingTag)
577
+ if (thinking) parts.push(thinking)
567
578
  }
568
579
  if (bg) parts.push(formatTurns(bg.turnCount, bg.maxTurns))
569
580
  if (toolUses > 0)