@herbertgao/pi-extensions 2026.11.10 → 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 (60) hide show
  1. package/CHANGELOG.md +11 -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 +6 -0
  5. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +2 -2
  6. package/node_modules/@herbertgao/pi-cc-extensions/README.md +2 -2
  7. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +13 -8
  8. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/grouping.ts +58 -15
  9. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/tool-io.ts +0 -5
  10. package/node_modules/@herbertgao/pi-cc-extensions/extensions/utils/ansi-text.ts +18 -4
  11. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  12. package/node_modules/@herbertgao/pi-impeccable/CHANGELOG.md +6 -0
  13. package/node_modules/@herbertgao/pi-impeccable/README.md +2 -2
  14. package/node_modules/@herbertgao/pi-impeccable/package.json +4 -4
  15. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/SKILL.md +3 -1
  16. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/adapt.md +1 -1
  17. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/audit.md +12 -1
  18. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/audit.native.md +4 -0
  19. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/critique.md +5 -5
  20. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/degraded/documenter.md +1 -1
  21. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/degraded/finish-reviewer.md +1 -1
  22. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/distill.md +1 -1
  23. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/document.md +3 -1
  24. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/foundations.md +44 -0
  25. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/live-setup.md +1 -1
  26. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/live.md +26 -12
  27. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/new-work.md +10 -9
  28. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/onboard.md +7 -6
  29. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/overdrive.md +2 -2
  30. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/quieter.md +1 -1
  31. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/visualize.md +1 -1
  32. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/VERSION +1 -1
  33. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/engine-checksums.txt +5 -5
  34. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/impeccable +69 -16
  35. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/impeccable.cmd +55 -7
  36. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/live-browser.js +34 -4
  37. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +6 -0
  38. package/node_modules/@herbertgao/pi-subagents/README.md +27 -9
  39. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +11 -11
  40. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  41. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +13 -0
  42. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +51 -32
  43. package/node_modules/@herbertgao/pi-subagents/src/default-agents.ts +7 -0
  44. package/node_modules/@herbertgao/pi-subagents/src/index.ts +334 -893
  45. package/node_modules/@herbertgao/pi-subagents/src/nested-tools.ts +4 -1
  46. package/node_modules/@herbertgao/pi-subagents/src/prompts.ts +13 -0
  47. package/node_modules/@herbertgao/pi-subagents/src/schedule-store.ts +18 -13
  48. package/node_modules/@herbertgao/pi-subagents/src/schedule.ts +25 -5
  49. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +215 -69
  50. package/node_modules/@herbertgao/pi-subagents/src/types.ts +17 -0
  51. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +9 -0
  52. package/node_modules/@herbertgao/pi-subagents/src/ui/agents-menu.ts +705 -0
  53. package/node_modules/@herbertgao/pi-subagents/src/ui/settings-menu.ts +361 -0
  54. package/node_modules/@herbertgao/pi-subagents/src/ui/viewer-keys.ts +1 -1
  55. package/node_modules/pi-commandcode-provider/CHANGELOG.md +11 -1
  56. package/node_modules/pi-commandcode-provider/index.ts +2 -1
  57. package/node_modules/pi-commandcode-provider/package.json +5 -4
  58. package/node_modules/pi-commandcode-provider/src/pricing.ts +8 -1
  59. package/node_modules/pi-commandcode-provider/src/responses-compat.ts +137 -0
  60. 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"
@@ -413,6 +420,81 @@ const MAX_TURNS_CEILING = 10_000
413
420
  const GRACE_TURNS_CEILING = 1_000
414
421
  const SUBAGENT_DEPTH_CEILING = 16
415
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
+
416
498
  /**
417
499
  * Normalize a package gate: a boolean passes through, an array is trimmed to its
418
500
  * non-empty string entries, a bare string becomes a one-entry allowlist, and
@@ -440,50 +522,13 @@ function sanitize(raw: unknown): SubagentsSettings {
440
522
  if (!raw || typeof raw !== "object") return {}
441
523
  const r = raw as Record<string, unknown>
442
524
  const out: SubagentsSettings = {}
443
- if (
444
- Number.isInteger(r.maxConcurrent) &&
445
- (r.maxConcurrent as number) >= 1 &&
446
- (r.maxConcurrent as number) <= MAX_CONCURRENT_CEILING
447
- ) {
448
- out.maxConcurrent = r.maxConcurrent as number
449
- }
450
- // Floor 0, not 1 like maxConcurrent above: 0 is the documented "unlimited"
451
- // value and the default, so dropping it would silently be unrepresentable.
452
- if (
453
- Number.isInteger(r.maxConcurrentForeground) &&
454
- (r.maxConcurrentForeground as number) >= 0 &&
455
- (r.maxConcurrentForeground as number) <= MAX_CONCURRENT_CEILING
456
- ) {
457
- out.maxConcurrentForeground = r.maxConcurrentForeground as number
458
- }
459
- // Floor 0 for the same reason: 0 is the documented "unlimited".
460
- if (
461
- Number.isInteger(r.maxConcurrentNested) &&
462
- (r.maxConcurrentNested as number) >= 0 &&
463
- (r.maxConcurrentNested as number) <= MAX_CONCURRENT_CEILING
464
- ) {
465
- out.maxConcurrentNested = r.maxConcurrentNested as number
466
- }
467
- if (
468
- Number.isInteger(r.defaultMaxTurns) &&
469
- (r.defaultMaxTurns as number) >= 0 &&
470
- (r.defaultMaxTurns as number) <= MAX_TURNS_CEILING
471
- ) {
472
- out.defaultMaxTurns = r.defaultMaxTurns as number
473
- }
474
- if (
475
- Number.isInteger(r.graceTurns) &&
476
- (r.graceTurns as number) >= 1 &&
477
- (r.graceTurns as number) <= GRACE_TURNS_CEILING
478
- ) {
479
- out.graceTurns = r.graceTurns as number
480
- }
481
- if (
482
- Number.isInteger(r.maxSubagentDepth) &&
483
- (r.maxSubagentDepth as number) >= 0 &&
484
- (r.maxSubagentDepth as number) <= SUBAGENT_DEPTH_CEILING
485
- ) {
486
- 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
487
532
  }
488
533
  if (
489
534
  typeof r.defaultJoinMode === "string" &&
@@ -604,6 +649,24 @@ function readSettingsFile(path: string): SubagentsSettings {
604
649
  }
605
650
  }
606
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
+
607
670
  /** Load merged settings: global provides defaults, project overrides. */
608
671
  export function loadSettings(cwd: string = process.cwd()): SubagentsSettings {
609
672
  return {
@@ -613,21 +676,88 @@ export function loadSettings(cwd: string = process.cwd()): SubagentsSettings {
613
676
  }
614
677
 
615
678
  /**
616
- * Write project-local settings. Global is never touched from code.
617
- * Returns `true` on success, `false` if the write (or mkdir) failed so the
618
- * 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.
619
723
  */
620
724
  export function saveSettings(
621
- s: SubagentsSettings,
725
+ changes: SubagentsSettings,
622
726
  cwd: string = process.cwd(),
623
- ): boolean {
624
- const path = projectPath(cwd)
727
+ scope: SettingsScope = defaultSettingsScope(cwd),
728
+ applied: SubagentsSettings = {},
729
+ ): SettingsScope | undefined {
730
+ const path = settingsFilePath(scope, cwd)
625
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
626
750
  mkdirSync(dirname(path), { recursive: true })
627
- writeFileSync(path, JSON.stringify(s, null, 2), "utf-8")
628
- 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
629
759
  } catch {
630
- return false
760
+ return undefined
631
761
  }
632
762
  }
633
763
 
@@ -689,14 +819,19 @@ export function applySettings(
689
819
  */
690
820
  export function persistToastFor(
691
821
  successMsg: string,
692
- persisted: boolean,
822
+ scope: SettingsScope | undefined,
823
+ shadowed = false,
693
824
  ): { message: string; level: "info" | "warning" } {
694
- return persisted
695
- ? { message: successMsg, level: "info" }
696
- : {
697
- message: `${successMsg} (session only; failed to persist)`,
698
- level: "warning",
699
- }
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
+ }
700
835
  }
701
836
 
702
837
  /**
@@ -716,18 +851,29 @@ export function applyAndEmitLoaded(
716
851
  }
717
852
 
718
853
  /**
719
- * Persist a settings snapshot, emit the `subagents:settings_changed` event
720
- * (regardless of persist outcome so listeners see the in-memory change), and
721
- * return the toast the UI should display. Event payload carries the `persisted`
722
- * 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.
723
859
  */
724
860
  export function saveAndEmitChanged(
725
861
  snapshot: SubagentsSettings,
862
+ previous: SubagentsSettings,
726
863
  successMsg: string,
727
864
  emit: SettingsEmit,
728
865
  cwd: string = process.cwd(),
729
- ): { message: string; level: "info" | "warning" } {
730
- 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
731
872
  emit("subagents:settings_changed", { settings: snapshot, persisted })
732
- 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 }
733
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
 
@@ -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,