@timmyjl12/pi-subagents 0.0.0-stage → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/CHANGELOG.md +862 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1125 -3
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +40 -0
  9. package/dist/active-agents-prompt.js +98 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +131 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +872 -0
  17. package/dist/agent-manager.js +2910 -0
  18. package/dist/agent-runner.d.ts +358 -0
  19. package/dist/agent-runner.js +1219 -0
  20. package/dist/agent-types.d.ts +142 -0
  21. package/dist/agent-types.js +315 -0
  22. package/dist/awaited-result.d.ts +37 -0
  23. package/dist/awaited-result.js +150 -0
  24. package/dist/child-context.d.ts +15 -0
  25. package/dist/child-context.js +181 -0
  26. package/dist/child-session-shutdown.d.ts +21 -0
  27. package/dist/child-session-shutdown.js +97 -0
  28. package/dist/cleanup-plans.d.ts +10 -0
  29. package/dist/cleanup-plans.js +112 -0
  30. package/dist/context.d.ts +12 -0
  31. package/dist/context.js +56 -0
  32. package/dist/cross-extension-rpc.d.ts +73 -0
  33. package/dist/cross-extension-rpc.js +192 -0
  34. package/dist/custom-agents.d.ts +79 -0
  35. package/dist/custom-agents.js +583 -0
  36. package/dist/default-agents.d.ts +7 -0
  37. package/dist/default-agents.js +125 -0
  38. package/dist/enabled-models.d.ts +49 -0
  39. package/dist/enabled-models.js +145 -0
  40. package/dist/env.d.ts +6 -0
  41. package/dist/env.js +28 -0
  42. package/dist/error-log.d.ts +64 -0
  43. package/dist/error-log.js +176 -0
  44. package/dist/force-main-model.d.ts +21 -0
  45. package/dist/force-main-model.js +28 -0
  46. package/dist/goal-bridge.d.ts +155 -0
  47. package/dist/goal-bridge.js +305 -0
  48. package/dist/group-join.d.ts +36 -0
  49. package/dist/group-join.js +161 -0
  50. package/dist/index.d.ts +52 -0
  51. package/dist/index.js +6390 -0
  52. package/dist/invocation-config.d.ts +164 -0
  53. package/dist/invocation-config.js +158 -0
  54. package/dist/memory.d.ts +53 -0
  55. package/dist/memory.js +165 -0
  56. package/dist/mention-clone.d.ts +87 -0
  57. package/dist/mention-clone.js +178 -0
  58. package/dist/mention.d.ts +81 -0
  59. package/dist/mention.js +131 -0
  60. package/dist/model-resolver.d.ts +36 -0
  61. package/dist/model-resolver.js +95 -0
  62. package/dist/model-scope.d.ts +49 -0
  63. package/dist/model-scope.js +48 -0
  64. package/dist/nested-tools.d.ts +76 -0
  65. package/dist/nested-tools.js +393 -0
  66. package/dist/output-diagnostics.d.ts +11 -0
  67. package/dist/output-diagnostics.js +64 -0
  68. package/dist/output-file.d.ts +64 -0
  69. package/dist/output-file.js +351 -0
  70. package/dist/prompts.d.ts +61 -0
  71. package/dist/prompts.js +94 -0
  72. package/dist/recovery.d.ts +56 -0
  73. package/dist/recovery.js +341 -0
  74. package/dist/report-cleanup.d.ts +204 -0
  75. package/dist/report-cleanup.js +1632 -0
  76. package/dist/report-store.d.ts +738 -0
  77. package/dist/report-store.js +3612 -0
  78. package/dist/schedule-store.d.ts +52 -0
  79. package/dist/schedule-store.js +240 -0
  80. package/dist/schedule.d.ts +121 -0
  81. package/dist/schedule.js +420 -0
  82. package/dist/settings.d.ts +388 -0
  83. package/dist/settings.js +268 -0
  84. package/dist/skill-loader.d.ts +24 -0
  85. package/dist/skill-loader.js +93 -0
  86. package/dist/standalone-fallback.d.ts +30 -0
  87. package/dist/standalone-fallback.js +239 -0
  88. package/dist/status-note.d.ts +61 -0
  89. package/dist/status-note.js +85 -0
  90. package/dist/structured-output.d.ts +61 -0
  91. package/dist/structured-output.js +112 -0
  92. package/dist/terminal-progress.d.ts +115 -0
  93. package/dist/terminal-progress.js +206 -0
  94. package/dist/types.d.ts +411 -0
  95. package/dist/types.js +5 -0
  96. package/dist/ui/agent-mention.d.ts +82 -0
  97. package/dist/ui/agent-mention.js +187 -0
  98. package/dist/ui/agent-widget.d.ts +304 -0
  99. package/dist/ui/agent-widget.js +770 -0
  100. package/dist/ui/cleanup-preview.d.ts +59 -0
  101. package/dist/ui/cleanup-preview.js +466 -0
  102. package/dist/ui/conversation-viewer.d.ts +105 -0
  103. package/dist/ui/conversation-viewer.js +544 -0
  104. package/dist/ui/fleet-list.d.ts +183 -0
  105. package/dist/ui/fleet-list.js +494 -0
  106. package/dist/ui/fleet-overlay.d.ts +203 -0
  107. package/dist/ui/fleet-overlay.js +887 -0
  108. package/dist/ui/hub-feed.d.ts +52 -0
  109. package/dist/ui/hub-feed.js +148 -0
  110. package/dist/ui/native-transcript.d.ts +33 -0
  111. package/dist/ui/native-transcript.js +234 -0
  112. package/dist/ui/schedule-menu.d.ts +16 -0
  113. package/dist/ui/schedule-menu.js +94 -0
  114. package/dist/ui/select-item.d.ts +27 -0
  115. package/dist/ui/select-item.js +34 -0
  116. package/dist/ui/tool-progress.d.ts +22 -0
  117. package/dist/ui/tool-progress.js +56 -0
  118. package/dist/ui/viewer-keys.d.ts +20 -0
  119. package/dist/ui/viewer-keys.js +17 -0
  120. package/dist/ui/workflow-card.d.ts +175 -0
  121. package/dist/ui/workflow-card.js +332 -0
  122. package/dist/ui/workflow-dialog.d.ts +305 -0
  123. package/dist/ui/workflow-dialog.js +848 -0
  124. package/dist/ui/workflow-menu.d.ts +60 -0
  125. package/dist/ui/workflow-menu.js +147 -0
  126. package/dist/usage.d.ts +147 -0
  127. package/dist/usage.js +147 -0
  128. package/dist/workflow/collisions.d.ts +95 -0
  129. package/dist/workflow/collisions.js +88 -0
  130. package/dist/workflow/entry.d.ts +32 -0
  131. package/dist/workflow/entry.js +29 -0
  132. package/dist/workflow/host.d.ts +65 -0
  133. package/dist/workflow/host.js +477 -0
  134. package/dist/workflow/journal.d.ts +113 -0
  135. package/dist/workflow/journal.js +177 -0
  136. package/dist/workflow/json-schema.d.ts +51 -0
  137. package/dist/workflow/json-schema.js +111 -0
  138. package/dist/workflow/meta.d.ts +67 -0
  139. package/dist/workflow/meta.js +317 -0
  140. package/dist/workflow/progress.d.ts +224 -0
  141. package/dist/workflow/progress.js +361 -0
  142. package/dist/workflow/runtime.d.ts +373 -0
  143. package/dist/workflow/runtime.js +919 -0
  144. package/dist/workflow/saved.d.ts +90 -0
  145. package/dist/workflow/saved.js +203 -0
  146. package/dist/workflow/task.d.ts +145 -0
  147. package/dist/workflow/task.js +213 -0
  148. package/dist/workflow/tool-description.d.ts +43 -0
  149. package/dist/workflow/tool-description.js +204 -0
  150. package/dist/workflow/worker-source.d.ts +47 -0
  151. package/dist/workflow/worker-source.js +778 -0
  152. package/dist/worktree.d.ts +52 -0
  153. package/dist/worktree.js +164 -0
  154. package/dist/xml.d.ts +10 -0
  155. package/dist/xml.js +12 -0
  156. package/docs/DEVELOPMENT.md +40 -0
  157. package/docs/artifacts.md +93 -0
  158. package/docs/recovery.md +62 -0
  159. package/docs/rpc.md +252 -0
  160. package/docs/runtime-performance.md +53 -0
  161. package/docs/workflows.md +467 -0
  162. package/examples/agent-tool-description.md +43 -0
  163. package/examples/workflows/compose.js +51 -0
  164. package/examples/workflows/fan-out-audit.js +47 -0
  165. package/examples/workflows/gated-fix.js +60 -0
  166. package/examples/workflows/lib/count-child.js +27 -0
  167. package/examples/workflows/review-panel.js +66 -0
  168. package/examples/workflows/structured-findings.js +78 -0
  169. package/package.json +75 -6
  170. package/src/abortable.ts +43 -0
  171. package/src/active-agents-prompt.ts +115 -0
  172. package/src/advisor-status.ts +74 -0
  173. package/src/agent-color.ts +169 -0
  174. package/src/agent-file-toggle.ts +273 -0
  175. package/src/agent-manager.ts +3312 -0
  176. package/src/agent-runner.ts +1500 -0
  177. package/src/agent-types.ts +390 -0
  178. package/src/awaited-result.ts +187 -0
  179. package/src/child-context.ts +173 -0
  180. package/src/child-session-shutdown.ts +114 -0
  181. package/src/cleanup-plans.ts +112 -0
  182. package/src/context.ts +58 -0
  183. package/src/cross-extension-rpc.ts +257 -0
  184. package/src/custom-agents.ts +689 -0
  185. package/src/default-agents.ts +129 -0
  186. package/src/enabled-models.ts +180 -0
  187. package/src/env.ts +33 -0
  188. package/src/error-log.ts +202 -0
  189. package/src/force-main-model.ts +29 -0
  190. package/src/goal-bridge.ts +468 -0
  191. package/src/group-join.ts +188 -0
  192. package/src/index.ts +6856 -0
  193. package/src/invocation-config.ts +276 -0
  194. package/src/memory.ts +179 -0
  195. package/src/mention-clone.ts +221 -0
  196. package/src/mention.ts +141 -0
  197. package/src/model-resolver.ts +118 -0
  198. package/src/model-scope.ts +70 -0
  199. package/src/nested-tools.ts +553 -0
  200. package/src/output-diagnostics.ts +68 -0
  201. package/src/output-file.ts +380 -0
  202. package/src/prompts.ts +151 -0
  203. package/src/recovery.ts +320 -0
  204. package/src/report-cleanup.ts +2044 -0
  205. package/src/report-store.ts +4130 -0
  206. package/src/schedule-store.ts +244 -0
  207. package/src/schedule.ts +450 -0
  208. package/src/settings.ts +632 -0
  209. package/src/skill-loader.ts +102 -0
  210. package/src/standalone-fallback.ts +195 -0
  211. package/src/status-note.ts +90 -0
  212. package/src/structured-output.ts +130 -0
  213. package/src/terminal-progress.ts +215 -0
  214. package/src/types.ts +424 -0
  215. package/src/ui/agent-mention.ts +216 -0
  216. package/src/ui/agent-widget.ts +866 -0
  217. package/src/ui/cleanup-preview.ts +518 -0
  218. package/src/ui/conversation-viewer.ts +527 -0
  219. package/src/ui/fleet-list.ts +563 -0
  220. package/src/ui/fleet-overlay.ts +1048 -0
  221. package/src/ui/hub-feed.ts +179 -0
  222. package/src/ui/native-transcript.ts +224 -0
  223. package/src/ui/schedule-menu.ts +105 -0
  224. package/src/ui/select-item.ts +45 -0
  225. package/src/ui/tool-progress.ts +67 -0
  226. package/src/ui/viewer-keys.ts +39 -0
  227. package/src/ui/workflow-card.ts +470 -0
  228. package/src/ui/workflow-dialog.ts +1119 -0
  229. package/src/ui/workflow-menu.ts +193 -0
  230. package/src/usage.ts +217 -0
  231. package/src/workflow/collisions.ts +123 -0
  232. package/src/workflow/entry.ts +47 -0
  233. package/src/workflow/host.ts +524 -0
  234. package/src/workflow/journal.ts +221 -0
  235. package/src/workflow/json-schema.ts +128 -0
  236. package/src/workflow/meta.ts +325 -0
  237. package/src/workflow/progress.ts +550 -0
  238. package/src/workflow/runtime.ts +1342 -0
  239. package/src/workflow/saved.ts +217 -0
  240. package/src/workflow/task.ts +313 -0
  241. package/src/workflow/tool-description.ts +205 -0
  242. package/src/workflow/worker-source.ts +781 -0
  243. package/src/worktree.ts +205 -0
  244. package/src/xml.ts +13 -0
@@ -0,0 +1,388 @@
1
+ import type { AgentMentionMode, JoinMode, ViewerMarkdownMode, WidgetMode, WidgetPlacement } from "./types.ts";
2
+ export interface SubagentsSettings {
3
+ maxConcurrent?: number;
4
+ /**
5
+ * Max concurrent FOREGROUND (blocking) agents — `0` = unlimited, the default,
6
+ * which preserves the behaviour that has always applied: nothing bounded
7
+ * foreground work, and pi dispatches a message's tool calls through
8
+ * `Promise.all`, so an unqualified fan-out of blocking `Agent` calls runs all
9
+ * at once. Set it to bound that (#253 — on local models, parallel agents
10
+ * thrash the prompt cache).
11
+ *
12
+ * Deliberately independent of `maxConcurrent` rather than folded into it: a
13
+ * foreground agent blocks the parent anyway, so charging it to the background
14
+ * pool would let a saturated pool starve the main session of work it could
15
+ * have done itself.
16
+ *
17
+ * Bounds only spawns a caller is blocking on inline. Nested children are
18
+ * exempt — their parent is blocked awaiting them, so queueing a child behind
19
+ * its own parent would deadlock — and so are detached spawns from
20
+ * cross-extension RPC or `@handle` mentions, which block nobody and are
21
+ * documented to start immediately. Foreground `resume` is also outside the
22
+ * pool: it reuses an existing session and never reaches the spawn path, so
23
+ * several blocking resumes in one message can still exceed the limit.
24
+ */
25
+ maxConcurrentForeground?: number;
26
+ /**
27
+ * 0 = unlimited — the extension's single source of truth for that convention:
28
+ * `normalizeMaxTurns()` in agent-runner.ts treats 0 → `undefined`, and the
29
+ * `/agents` → Settings input prompt explicitly says "0 = unlimited".
30
+ */
31
+ defaultMaxTurns?: number;
32
+ graceTurns?: number;
33
+ /**
34
+ * Whether `Agent`/nested `max_turns` parameters (and RPC `maxTurns` options)
35
+ * may impose a per-call turn budget. Defaults to `false`.
36
+ *
37
+ * Off keeps the configured budget authoritative: agent-file `max_turns` and
38
+ * `defaultMaxTurns` apply, the parameter is omitted from both tool schemas,
39
+ * and a runtime call that bypasses schema validation still has its cap
40
+ * dropped. Turn it on to restore the historical caller-cap behaviour.
41
+ */
42
+ allowPerCallTurnLimits?: boolean;
43
+ defaultJoinMode?: JoinMode;
44
+ /**
45
+ * Whether a top-level `Agent` spawn that doesn't say runs detached.
46
+ * Defaults to `true`, following Claude Code, where the agent backgrounds
47
+ * unless the caller passes `run_in_background: false`. Set `false` to restore
48
+ * the previous behaviour, where an unqualified spawn blocked the turn and
49
+ * returned its result inline.
50
+ *
51
+ * Top-level only. Nested spawns (a subagent spawning its own) always default
52
+ * to foreground regardless of this setting — see `nested-tools.ts`, where a
53
+ * detached child would be killed by `abortOwnedChildren` when its parent
54
+ * settles, with no notification path to deliver its result.
55
+ *
56
+ * An explicit `run_in_background` on the call, or in the agent file's
57
+ * frontmatter, overrides this in both directions; the setting only decides
58
+ * what "unspecified" means.
59
+ */
60
+ backgroundByDefault?: boolean;
61
+ /**
62
+ * Master switch for the schedule subagent feature. Defaults to `true`.
63
+ * When `false`: the `Agent` tool's `schedule` param + its guideline are
64
+ * stripped from the tool spec at registration (zero LLM-context cost), the
65
+ * scheduler doesn't bind to the session, and the `/agents → Scheduled jobs`
66
+ * menu entry is hidden. Schema-level removal applies at extension load
67
+ * (next pi session); runtime menu/runtime-fire short-circuit is immediate.
68
+ */
69
+ schedulingEnabled?: boolean;
70
+ /**
71
+ * When true, the effective model of each subagent spawn is validated
72
+ * against `enabledModels` from pi's settings — both global
73
+ * (`<agentDir>/settings.json`) and project-local (`<cwd>/.pi/settings.json`),
74
+ * with project overriding global (mirrors pi's SettingsManager deep-merge).
75
+ *
76
+ * scopeModels guards against runtime LLM choices, not user-level config.
77
+ * Out-of-scope handling reflects this:
78
+ * - Caller-supplied via `Agent({ model: "..." })` (only when frontmatter
79
+ * has no `model:`, since frontmatter is authoritative): hard error
80
+ * returned to the orchestrator, listing the allowed models. The LLM
81
+ * made an explicit out-of-scope choice and gets explicit feedback.
82
+ * - Frontmatter-pinned: warning toast + the pinned model runs. The
83
+ * agent's author/installer chose this; trust it.
84
+ * - Parent-inherited (neither caller nor frontmatter sets a model):
85
+ * warning toast + parent's model runs. The user chose the parent's
86
+ * model when starting the session; trust it.
87
+ *
88
+ * No-op when pi's `enabledModels` is empty or absent — nothing to validate
89
+ * against. Defaults to false: subagents may use any model.
90
+ */
91
+ scopeModels?: boolean;
92
+ /**
93
+ * When true, an unreadable or unparseable agent `.md` aborts extension load
94
+ * instead of being skipped with a warning — pi exits, naming the file.
95
+ *
96
+ * Startup only, by design. Mid-session reloads (one per `Agent` call) keep
97
+ * warning: a bad edit at 3pm should not kill the session on the next
98
+ * unrelated spawn, where the failure would look disconnected from its cause.
99
+ * For a checked-in `.pi/agents/`, failing at startup is the point — the
100
+ * alternative is running a *different* agent than the file names.
101
+ * Defaults to false.
102
+ */
103
+ strictAgentFiles?: boolean;
104
+ /**
105
+ * When true, the three built-in default agents (general-purpose, Explore, Plan)
106
+ * are not registered at startup. User-defined agents from project/global custom
107
+ * agent dirs are completely unaffected — only the hardcoded DEFAULT_AGENTS are suppressed.
108
+ * Defaults to false.
109
+ */
110
+ disableDefaultAgents?: boolean;
111
+ /**
112
+ * Which Agent tool description the LLM sees. "full" (default) is the rich
113
+ * Claude Code-style prompt; "compact" is a ~75% smaller version (one-line
114
+ * agent type list, terse usage notes) for small/local models where tool-spec
115
+ * tokens are expensive; "custom" reads `.pi/agent-tool-description.md`
116
+ * (project, falling back to `<agentDir>/agent-tool-description.md`) with
117
+ * `{{placeholder}}` substitution — a missing/empty file falls back to "full".
118
+ * The mode is read once at tool registration — changing it applies on the
119
+ * next pi session.
120
+ */
121
+ toolDescriptionMode?: ToolDescriptionMode;
122
+ /**
123
+ * Whether `@handle message` typed at the prompt is routed to that subagent
124
+ * instead of the main model, and whether `@` offers running agents alongside
125
+ * pi's file completion. Defaults to `model`. Applied live.
126
+ *
127
+ * - `model`: mentioning an agent that is not running asks the main model to
128
+ * spawn it with the `Agent` tool, Claude Code's behaviour. Costs a turn,
129
+ * and the model writes the agent's prompt rather than your text being it.
130
+ * - `direct`: that agent is started here instead, with the typed message as
131
+ * its prompt and no main-model turn spent.
132
+ * - `off`: the input hook falls straight through and the stacked
133
+ * autocomplete provider delegates everything back to pi's built-in one.
134
+ *
135
+ * Messaging a running agent and resuming a finished one are direct in both
136
+ * `model` and `direct`. The legacy booleans are still accepted: `true` reads
137
+ * as `model`, `false` as `off`.
138
+ */
139
+ agentMentions?: AgentMentionMode;
140
+ /**
141
+ * Whether subagents persist their pi session by default, so `@handle` can
142
+ * reopen an agent's conversation long after its in-memory record is gone.
143
+ * Defaults to `true`. Per-agent `persist_session:` frontmatter overrides it
144
+ * in both directions. Turning it off restores the previous behaviour, where
145
+ * a handle stops resolving roughly ten minutes after the agent finishes and
146
+ * mentioning it starts a fresh run instead. Persisted sessions also appear
147
+ * nested under the spawning session in pi's `/resume`.
148
+ */
149
+ rememberAgents?: boolean;
150
+ /**
151
+ * Display mode for the persistent agent widget:
152
+ * - `all`: show every agent (foreground + background).
153
+ * - `background`: hide foreground agents — they already render inline as the
154
+ * Agent tool result, so the widget would otherwise double-render them
155
+ * (#118); everything else (background, queued, scheduled, RPC) stays.
156
+ * - `off`: hide the widget entirely.
157
+ * `background` filtering never gates `←` → Agent Hub (the key follows the
158
+ * Hub's content); `off` stands the key down with the list.
159
+ * Defaults to `all`. Pure-UI and applied live (toggling refreshes the
160
+ * widget).
161
+ */
162
+ widgetMode?: WidgetMode;
163
+ /** Compact list placement relative to the editor. Defaults to `above`; applied live. */
164
+ widgetPlacement?: WidgetPlacement;
165
+ /**
166
+ * Project/global default for writing each subagent's `.output` transcript
167
+ * (a JSON-lines copy of the run, stored under the OS temp dir).
168
+ * Defaults to `true`. Set `false` to make transcripts opt-in for the whole
169
+ * project (e.g. a repo that shouldn't leave run transcripts on disk for backup
170
+ * or DLP tooling to ingest). A custom agent's `output_transcript` frontmatter
171
+ * overrides this per agent. This governs only the transcript — it does NOT
172
+ * affect the persisted pi session (`persist_session`), worktree commits
173
+ * (`isolation: worktree`), or memory files.
174
+ */
175
+ outputTranscript?: boolean;
176
+ /**
177
+ * Whether `isolation: "worktree"` may create a worktree at all. Defaults to
178
+ * `true`. Set `false` on a repo where worktrees are too slow or too large to
179
+ * be worth it (#184): a requested worktree is then dropped and the agent runs
180
+ * in the main checkout.
181
+ *
182
+ * The drop is deliberately silent — there is no per-result note, because the
183
+ * setting exists for projects whose model asks for a worktree on every call,
184
+ * where a note would be noise on every result. What keeps the orchestrator
185
+ * from claiming a `pi-agent-*` branch anyway is that it is never told the
186
+ * capability exists: `isolationParam` (invocation-config.ts) drops the field
187
+ * from both tool schemas, and `isolationGuideline` (index.ts) drops the
188
+ * matching prose from the full and compact descriptions — a custom one opts
189
+ * in via the `{{isolationGuideline}}` placeholder. Anything that
190
+ * reintroduces the prose has to reintroduce a note with it.
191
+ *
192
+ * Deliberately a downgrade rather than an error. The fail-loud rule covers
193
+ * worktrees that *cannot* be created; this is the user declining one, and
194
+ * throwing would reject exactly the calls that the `isolation: "off"` value
195
+ * exists to tolerate. Enforced below the tool boundary, so it also covers the
196
+ * scheduler and the unvalidated cross-extension RPC path.
197
+ */
198
+ worktreeIsolation?: boolean;
199
+ /**
200
+ * Master switch for scripted workflows. Defaults to `true`.
201
+ *
202
+ * Off is not a soft hide: the `SubagentWorkflow` tool is never registered, so
203
+ * the model is not told it exists and cannot call it, the `/agents`
204
+ * Workflows entry is hidden, and `--subagents-workflow-file` is refused.
205
+ *
206
+ * Absent is not the same as `true`. Unset means *auto*: on, but yielding to
207
+ * another extension that already offers a workflow tool, because two
208
+ * orchestrators in one tool spec is a worse default than none — the model
209
+ * has to guess which to call, and pays for both descriptions to find out.
210
+ * Setting it explicitly pins the answer in both directions: `true` keeps
211
+ * ours whatever else is loaded, `false` is off regardless. See
212
+ * `resolveWorkflowCollisions` in index.ts.
213
+ *
214
+ * Read once at extension init, before registration, so flipping it in
215
+ * `/agents → Settings` takes effect on the next pi session — the same
216
+ * contract `schedulingEnabled` has, and for the same reason: a tool spec is
217
+ * fixed once pi has it.
218
+ */
219
+ workflowsEnabled?: boolean;
220
+ /**
221
+ * Agent type a workflow's `agent()` call uses when it names no `agentType` of
222
+ * its own. Defaults to `task`, the economical workflow role
223
+ * (`DEFAULT_WORKFLOW_AGENT_TYPE` in workflow/runtime.ts).
224
+ *
225
+ * The precedence is per-run, not global: a `SubagentWorkflow(agentType)` on
226
+ * the call outranks this, a run that resumes another inherits THAT run's
227
+ * frozen choice, and a script's `agent(prompt, { agentType })` outranks all
228
+ * three. Only "unspecified" reads this setting.
229
+ *
230
+ * Kept as a name rather than validated against the registry on load: agent
231
+ * files are added, renamed and disabled mid-session, and a stored name that is
232
+ * temporarily unavailable must survive an unrelated settings save instead of
233
+ * being rewritten to a cheaper-looking role. Resolution stays at spawn time;
234
+ * an unavailable workflow default fails closed instead of using the general
235
+ * fallbackSubagent policy.
236
+ */
237
+ workflowDefaultAgentType?: string;
238
+ /**
239
+ * Hard ceiling on nested subagent delegation, counted from the main session:
240
+ * main = 0, its subagents = 1, their children = 2. Defaults to `2`; `0` or `1`
241
+ * disables nesting project-wide. Read when a subagent session is built, so a
242
+ * change applies to agents started after it.
243
+ */
244
+ maxSubagentDepth?: number;
245
+ /**
246
+ * Agent type substituted when a caller-supplied `subagent_type` doesn't
247
+ * resolve to exactly one enabled agent (unknown, disabled, or ambiguous by
248
+ * case). Omitted keeps the historical `general-purpose` fallback; a type name
249
+ * routes those calls to that agent instead; `"none"` disables the fallback so
250
+ * dispatch fails closed with an error naming the available types.
251
+ *
252
+ * The boolean `false` is accepted as a spelling of `"none"`, because a boolean
253
+ * would otherwise be dropped as the wrong type and silently leave the
254
+ * PERMISSIVE default in place while the author believes strict dispatch is on
255
+ * — the wrong direction to fail for this setting. Every other value is an
256
+ * agent name, so a mistaken `"off"` fails loudly at dispatch rather than
257
+ * meaning one thing here and another in the resolver.
258
+ */
259
+ fallbackSubagent?: string;
260
+ /**
261
+ * Whether this extension's tool results carry a `usage` field, so subagent
262
+ * spend reaches the parent session's own accounting. Defaults to `false`.
263
+ *
264
+ * Subagents run in their own pi sessions, so by default the parent's footer,
265
+ * statusline and `/cost` show only what the main model spent — a session that
266
+ * delegated most of its work reads as nearly free. Pi folds
267
+ * `toolResult.usage` into `getSessionStats()`, so attaching it makes those
268
+ * surfaces count subagents too, under `/cost`'s "Tools/summaries" bucket.
269
+ *
270
+ * Off by default because it changes numbers the user may already be tracking
271
+ * (a statusline reading session cost will step up), not because the numbers
272
+ * are wrong.
273
+ *
274
+ * Three properties of what gets reported:
275
+ * - Tokens exclude `cacheRead`, for the reason in `usage.ts` — the parent's
276
+ * token total therefore rises by billed tokens only.
277
+ * - Cost is pi's own per-message `usage.cost.total`; we price nothing, and
278
+ * a model pi has no rates for contributes 0.
279
+ * - The context-window percentage is untouched. Pi derives it from assistant
280
+ * messages alone (`getContextUsage`), so a delegating session's context
281
+ * does not appear to fill up faster.
282
+ */
283
+ reportUsage?: boolean;
284
+ /**
285
+ * Whether the subagent surfaces show an estimated dollar cost next to their
286
+ * token counts (widget, Agent Hub, conversation viewer, foreground results,
287
+ * completion notifications). Defaults to `false`. Applied live.
288
+ *
289
+ * Rendered as `~$0.0042` — the tilde marks it as pi's reported estimate
290
+ * rather than a billed figure, and it is omitted entirely when the model has
291
+ * no pricing data, so a local model shows tokens and no dollars.
292
+ *
293
+ * Independent of `reportUsage`: this one is what a human reads, that one is
294
+ * what the parent session counts.
295
+ */
296
+ showCost?: boolean;
297
+ /**
298
+ * Whether the widget's running rows name the model driving each agent and the
299
+ * thinking level it is running at.
300
+ *
301
+ * Off by default, unlike the tool result and the conversation viewer, which
302
+ * show the pair unconditionally: those have a line to themselves, while the
303
+ * widget row already carries the description, turns, tool uses, tokens and
304
+ * elapsed time, and every character it gains is one the description loses on a
305
+ * narrow terminal.
306
+ */
307
+ showModel?: boolean;
308
+ /**
309
+ * How much of the conversation viewer's transcript renders as Markdown.
310
+ * Defaults to `assistant`. Applied live — the viewer's `m` key cycles this
311
+ * same setting, so a choice made in the overlay persists like one made in
312
+ * `/agents → Settings`.
313
+ *
314
+ * Scoped rather than all-or-nothing because the two kinds of content have
315
+ * different contracts: assistant text is authored as Markdown, while a tool
316
+ * result is whatever bytes the tool produced. Rendering the latter as
317
+ * Markdown is lossy in ways that look like the tool misbehaved — see
318
+ * `ViewerMarkdownMode` for the specific rewrites — so `all` is opt-in.
319
+ */
320
+ viewerMarkdown?: ViewerMarkdownMode;
321
+ }
322
+ export type ToolDescriptionMode = "full" | "compact" | "custom";
323
+ /** Setter hooks used by applySettings to wire persisted values into in-memory state. */
324
+ export interface SettingsAppliers {
325
+ setMaxConcurrent: (n: number) => void;
326
+ setMaxConcurrentForeground: (n: number) => void;
327
+ setDefaultMaxTurns: (n: number) => void;
328
+ setGraceTurns: (n: number) => void;
329
+ setAllowPerCallTurnLimits: (b: boolean) => void;
330
+ setDefaultJoinMode: (mode: JoinMode) => void;
331
+ setBackgroundByDefault: (b: boolean) => void;
332
+ setSchedulingEnabled: (b: boolean) => void;
333
+ setScopeModels: (enabled: boolean) => void;
334
+ setStrictAgentFiles: (b: boolean) => void;
335
+ setDisableDefaultAgents: (b: boolean) => void;
336
+ setToolDescriptionMode: (mode: ToolDescriptionMode) => void;
337
+ setWidgetPlacement: (placement: WidgetPlacement) => void;
338
+ setAgentMentions: (mode: AgentMentionMode) => void;
339
+ setRememberAgents: (b: boolean) => void;
340
+ setWidgetMode: (mode: WidgetMode) => void;
341
+ setOutputTranscript: (b: boolean) => void;
342
+ setWorktreeIsolation: (b: boolean) => void;
343
+ setWorkflowsEnabled: (b: boolean) => void;
344
+ setWorkflowDefaultAgentType: (agentType: string) => void;
345
+ setMaxSubagentDepth: (n: number) => void;
346
+ setFallbackSubagent: (v: string | undefined) => void;
347
+ setReportUsage: (b: boolean) => void;
348
+ setShowCost: (b: boolean) => void;
349
+ setShowModel: (b: boolean) => void;
350
+ setViewerMarkdown: (mode: ViewerMarkdownMode) => void;
351
+ }
352
+ /** Emit callback — a subset of `pi.events.emit` to keep helpers testable. */
353
+ export type SettingsEmit = (event: string, payload: unknown) => void;
354
+ /** Load merged settings: global provides defaults, project overrides. */
355
+ export declare function loadSettings(cwd?: string): SubagentsSettings;
356
+ /**
357
+ * Write project-local settings. Global is never touched from code.
358
+ * Returns `true` on success, `false` if the write (or mkdir) failed so the
359
+ * caller can surface a warning — persistence isn't fatal but isn't silent.
360
+ */
361
+ export declare function saveSettings(s: SubagentsSettings, cwd?: string): boolean;
362
+ /** Apply persisted settings to the in-memory state via caller-supplied setters. */
363
+ export declare function applySettings(s: SubagentsSettings, appliers: SettingsAppliers): void;
364
+ /**
365
+ * Format the user-facing toast for a settings mutation. Pure function —
366
+ * routes the success/failure of `saveSettings` into the right message + level
367
+ * so the UI layer (index.ts) stays a thin wire between input and notification.
368
+ */
369
+ export declare function persistToastFor(successMsg: string, persisted: boolean): {
370
+ message: string;
371
+ level: "info" | "warning";
372
+ };
373
+ /**
374
+ * Load merged settings, apply them to in-memory state, and emit the
375
+ * `subagents:settings_loaded` lifecycle event. Returns the loaded settings so
376
+ * callers can log/inspect. Extension init wires this once.
377
+ */
378
+ export declare function applyAndEmitLoaded(appliers: SettingsAppliers, emit: SettingsEmit, cwd?: string): SubagentsSettings;
379
+ /**
380
+ * Persist a settings snapshot, emit the `subagents:settings_changed` event
381
+ * (regardless of persist outcome so listeners see the in-memory change), and
382
+ * return the toast the UI should display. Event payload carries the `persisted`
383
+ * flag so listeners can react to write failures.
384
+ */
385
+ export declare function saveAndEmitChanged(snapshot: SubagentsSettings, successMsg: string, emit: SettingsEmit, cwd?: string): {
386
+ message: string;
387
+ level: "info" | "warning";
388
+ };
@@ -0,0 +1,268 @@
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
4
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
7
+ import { NO_FALLBACK } from "./agent-types.js";
8
+ const VALID_JOIN_MODES = new Set(["async", "group", "smart"]);
9
+ const VALID_TOOL_DESCRIPTION_MODES = new Set(["full", "compact", "custom"]);
10
+ const VALID_WIDGET_MODES = new Set(["all", "background", "off"]);
11
+ const VALID_WIDGET_PLACEMENTS = new Set(["above", "below"]);
12
+ const VALID_VIEWER_MARKDOWN_MODES = new Set(["off", "assistant", "all"]);
13
+ const VALID_AGENT_MENTION_MODES = new Set(["model", "direct", "off"]);
14
+ // Sanity ceilings — prevent hand-edited configs from asking for values that
15
+ // make no operational sense (e.g. 1e6 concurrent subagents). Permissive enough
16
+ // that any realistic power-user setting passes through.
17
+ const MAX_CONCURRENT_CEILING = 1024;
18
+ const MAX_TURNS_CEILING = 10_000;
19
+ const GRACE_TURNS_CEILING = 1_000;
20
+ const SUBAGENT_DEPTH_CEILING = 16;
21
+ /** Drop fields that don't match the expected shape. Silent — garbage becomes absent. */
22
+ function sanitize(raw) {
23
+ if (!raw || typeof raw !== "object")
24
+ return {};
25
+ const r = raw;
26
+ const out = {};
27
+ if (Number.isInteger(r.maxConcurrent) &&
28
+ r.maxConcurrent >= 1 &&
29
+ r.maxConcurrent <= MAX_CONCURRENT_CEILING) {
30
+ out.maxConcurrent = r.maxConcurrent;
31
+ }
32
+ // Floor 0, not 1 like maxConcurrent above: 0 is the documented "unlimited"
33
+ // value and the default, so dropping it would silently be unrepresentable.
34
+ if (Number.isInteger(r.maxConcurrentForeground) &&
35
+ r.maxConcurrentForeground >= 0 &&
36
+ r.maxConcurrentForeground <= MAX_CONCURRENT_CEILING) {
37
+ out.maxConcurrentForeground = r.maxConcurrentForeground;
38
+ }
39
+ if (Number.isInteger(r.defaultMaxTurns) &&
40
+ r.defaultMaxTurns >= 0 &&
41
+ r.defaultMaxTurns <= MAX_TURNS_CEILING) {
42
+ out.defaultMaxTurns = r.defaultMaxTurns;
43
+ }
44
+ if (Number.isInteger(r.graceTurns) &&
45
+ r.graceTurns >= 1 &&
46
+ r.graceTurns <= GRACE_TURNS_CEILING) {
47
+ out.graceTurns = r.graceTurns;
48
+ }
49
+ if (typeof r.allowPerCallTurnLimits === "boolean") {
50
+ out.allowPerCallTurnLimits = r.allowPerCallTurnLimits;
51
+ }
52
+ if (Number.isInteger(r.maxSubagentDepth) &&
53
+ r.maxSubagentDepth >= 0 &&
54
+ r.maxSubagentDepth <= SUBAGENT_DEPTH_CEILING) {
55
+ out.maxSubagentDepth = r.maxSubagentDepth;
56
+ }
57
+ if (typeof r.defaultJoinMode === "string" && VALID_JOIN_MODES.has(r.defaultJoinMode)) {
58
+ out.defaultJoinMode = r.defaultJoinMode;
59
+ }
60
+ if (typeof r.backgroundByDefault === "boolean") {
61
+ out.backgroundByDefault = r.backgroundByDefault;
62
+ }
63
+ if (typeof r.schedulingEnabled === "boolean") {
64
+ out.schedulingEnabled = r.schedulingEnabled;
65
+ }
66
+ if (typeof r.scopeModels === "boolean") {
67
+ out.scopeModels = r.scopeModels;
68
+ }
69
+ if (typeof r.strictAgentFiles === "boolean") {
70
+ out.strictAgentFiles = r.strictAgentFiles;
71
+ }
72
+ if (typeof r.disableDefaultAgents === "boolean") {
73
+ out.disableDefaultAgents = r.disableDefaultAgents;
74
+ }
75
+ if (typeof r.toolDescriptionMode === "string" && VALID_TOOL_DESCRIPTION_MODES.has(r.toolDescriptionMode)) {
76
+ out.toolDescriptionMode = r.toolDescriptionMode;
77
+ }
78
+ // Was a boolean before the `model` mode existed. A hand-written or
79
+ // previously-written `true` means "on", which is now the default `model`.
80
+ if (typeof r.agentMentions === "boolean") {
81
+ out.agentMentions = r.agentMentions ? "model" : "off";
82
+ }
83
+ else if (typeof r.agentMentions === "string" && VALID_AGENT_MENTION_MODES.has(r.agentMentions)) {
84
+ out.agentMentions = r.agentMentions;
85
+ }
86
+ if (typeof r.rememberAgents === "boolean") {
87
+ out.rememberAgents = r.rememberAgents;
88
+ }
89
+ if (typeof r.widgetMode === "string" && VALID_WIDGET_MODES.has(r.widgetMode)) {
90
+ out.widgetMode = r.widgetMode;
91
+ }
92
+ if (typeof r.widgetPlacement === "string" && VALID_WIDGET_PLACEMENTS.has(r.widgetPlacement)) {
93
+ out.widgetPlacement = r.widgetPlacement;
94
+ }
95
+ if (typeof r.outputTranscript === "boolean") {
96
+ out.outputTranscript = r.outputTranscript;
97
+ }
98
+ if (typeof r.worktreeIsolation === "boolean") {
99
+ out.worktreeIsolation = r.worktreeIsolation;
100
+ }
101
+ if (typeof r.reportUsage === "boolean") {
102
+ out.reportUsage = r.reportUsage;
103
+ }
104
+ if (typeof r.showCost === "boolean") {
105
+ out.showCost = r.showCost;
106
+ }
107
+ if (typeof r.showModel === "boolean") {
108
+ out.showModel = r.showModel;
109
+ }
110
+ if (typeof r.viewerMarkdown === "string" && VALID_VIEWER_MARKDOWN_MODES.has(r.viewerMarkdown)) {
111
+ out.viewerMarkdown = r.viewerMarkdown;
112
+ }
113
+ if (typeof r.workflowsEnabled === "boolean") {
114
+ out.workflowsEnabled = r.workflowsEnabled;
115
+ }
116
+ if (typeof r.workflowDefaultAgentType === "string" && r.workflowDefaultAgentType.trim()) {
117
+ // Trimmed like `fallbackSubagent` above: a hand-edited file's stray spaces
118
+ // are not part of the role name, and passing them through would turn a
119
+ // valid-looking setting into an unknown-type rejection at spawn.
120
+ out.workflowDefaultAgentType = r.workflowDefaultAgentType.trim();
121
+ }
122
+ if (r.fallbackSubagent === false) {
123
+ // The only non-string spelling worth accepting: a boolean would otherwise be
124
+ // dropped, silently leaving the PERMISSIVE default in place. Every string is
125
+ // an agent name except the `none` sentinel, which the resolver recognizes —
126
+ // so a mistaken "off" fails loudly at dispatch instead of meaning something
127
+ // different here than it does there.
128
+ out.fallbackSubagent = NO_FALLBACK;
129
+ }
130
+ else if (typeof r.fallbackSubagent === "string" && r.fallbackSubagent.trim()) {
131
+ out.fallbackSubagent = r.fallbackSubagent.trim();
132
+ }
133
+ return out;
134
+ }
135
+ function globalPath() {
136
+ return join(getAgentDir(), "subagents.json");
137
+ }
138
+ function projectPath(cwd) {
139
+ return join(cwd, ".pi", "subagents.json");
140
+ }
141
+ /**
142
+ * Read a settings file. Missing file is silent (returns `{}`). A file that
143
+ * exists but can't be parsed emits a warning to stderr so users aren't
144
+ * silently reverted to defaults — and still returns `{}` so startup proceeds.
145
+ */
146
+ function readSettingsFile(path) {
147
+ if (!existsSync(path))
148
+ return {};
149
+ try {
150
+ return sanitize(JSON.parse(readFileSync(path, "utf-8")));
151
+ }
152
+ catch (err) {
153
+ const reason = err instanceof Error ? err.message : String(err);
154
+ console.warn(`[pi-subagents] Ignoring malformed settings at ${path}: ${reason}`);
155
+ return {};
156
+ }
157
+ }
158
+ /** Load merged settings: global provides defaults, project overrides. */
159
+ export function loadSettings(cwd = process.cwd()) {
160
+ return { ...readSettingsFile(globalPath()), ...readSettingsFile(projectPath(cwd)) };
161
+ }
162
+ /**
163
+ * Write project-local settings. Global is never touched from code.
164
+ * Returns `true` on success, `false` if the write (or mkdir) failed so the
165
+ * caller can surface a warning — persistence isn't fatal but isn't silent.
166
+ */
167
+ export function saveSettings(s, cwd = process.cwd()) {
168
+ const path = projectPath(cwd);
169
+ try {
170
+ mkdirSync(dirname(path), { recursive: true });
171
+ writeFileSync(path, JSON.stringify(s, null, 2), "utf-8");
172
+ return true;
173
+ }
174
+ catch {
175
+ return false;
176
+ }
177
+ }
178
+ /** Apply persisted settings to the in-memory state via caller-supplied setters. */
179
+ export function applySettings(s, appliers) {
180
+ if (typeof s.maxConcurrent === "number")
181
+ appliers.setMaxConcurrent(s.maxConcurrent);
182
+ if (typeof s.maxConcurrentForeground === "number") {
183
+ appliers.setMaxConcurrentForeground(s.maxConcurrentForeground);
184
+ }
185
+ if (typeof s.defaultMaxTurns === "number")
186
+ appliers.setDefaultMaxTurns(s.defaultMaxTurns);
187
+ if (typeof s.graceTurns === "number")
188
+ appliers.setGraceTurns(s.graceTurns);
189
+ // Applied unconditionally, unlike the optional fields around it: caller caps
190
+ // are a policy, not a personal preference, and a different session/project
191
+ // whose file omits the key must not inherit the previous project's `true`.
192
+ appliers.setAllowPerCallTurnLimits(s.allowPerCallTurnLimits ?? false);
193
+ if (typeof s.maxSubagentDepth === "number")
194
+ appliers.setMaxSubagentDepth(s.maxSubagentDepth);
195
+ if (typeof s.fallbackSubagent === "string")
196
+ appliers.setFallbackSubagent(s.fallbackSubagent);
197
+ if (s.defaultJoinMode)
198
+ appliers.setDefaultJoinMode(s.defaultJoinMode);
199
+ if (typeof s.backgroundByDefault === "boolean")
200
+ appliers.setBackgroundByDefault(s.backgroundByDefault);
201
+ if (typeof s.schedulingEnabled === "boolean")
202
+ appliers.setSchedulingEnabled(s.schedulingEnabled);
203
+ if (typeof s.scopeModels === "boolean")
204
+ appliers.setScopeModels(s.scopeModels);
205
+ if (typeof s.strictAgentFiles === "boolean")
206
+ appliers.setStrictAgentFiles(s.strictAgentFiles);
207
+ if (typeof s.disableDefaultAgents === "boolean")
208
+ appliers.setDisableDefaultAgents(s.disableDefaultAgents);
209
+ if (s.toolDescriptionMode)
210
+ appliers.setToolDescriptionMode(s.toolDescriptionMode);
211
+ if (s.agentMentions)
212
+ appliers.setAgentMentions(s.agentMentions);
213
+ if (typeof s.rememberAgents === "boolean")
214
+ appliers.setRememberAgents(s.rememberAgents);
215
+ if (s.widgetMode)
216
+ appliers.setWidgetMode(s.widgetMode);
217
+ if (s.widgetPlacement)
218
+ appliers.setWidgetPlacement(s.widgetPlacement);
219
+ if (typeof s.outputTranscript === "boolean")
220
+ appliers.setOutputTranscript(s.outputTranscript);
221
+ if (typeof s.worktreeIsolation === "boolean")
222
+ appliers.setWorktreeIsolation(s.worktreeIsolation);
223
+ if (typeof s.reportUsage === "boolean")
224
+ appliers.setReportUsage(s.reportUsage);
225
+ if (typeof s.showCost === "boolean")
226
+ appliers.setShowCost(s.showCost);
227
+ if (typeof s.showModel === "boolean")
228
+ appliers.setShowModel(s.showModel);
229
+ if (s.viewerMarkdown)
230
+ appliers.setViewerMarkdown(s.viewerMarkdown);
231
+ if (typeof s.workflowsEnabled === "boolean")
232
+ appliers.setWorkflowsEnabled(s.workflowsEnabled);
233
+ if (typeof s.workflowDefaultAgentType === "string" && s.workflowDefaultAgentType.trim()) {
234
+ appliers.setWorkflowDefaultAgentType(s.workflowDefaultAgentType.trim());
235
+ }
236
+ }
237
+ /**
238
+ * Format the user-facing toast for a settings mutation. Pure function —
239
+ * routes the success/failure of `saveSettings` into the right message + level
240
+ * so the UI layer (index.ts) stays a thin wire between input and notification.
241
+ */
242
+ export function persistToastFor(successMsg, persisted) {
243
+ return persisted
244
+ ? { message: successMsg, level: "info" }
245
+ : { message: `${successMsg} (session only; failed to persist)`, level: "warning" };
246
+ }
247
+ /**
248
+ * Load merged settings, apply them to in-memory state, and emit the
249
+ * `subagents:settings_loaded` lifecycle event. Returns the loaded settings so
250
+ * callers can log/inspect. Extension init wires this once.
251
+ */
252
+ export function applyAndEmitLoaded(appliers, emit, cwd = process.cwd()) {
253
+ const settings = loadSettings(cwd);
254
+ applySettings(settings, appliers);
255
+ emit("subagents:settings_loaded", { settings });
256
+ return settings;
257
+ }
258
+ /**
259
+ * Persist a settings snapshot, emit the `subagents:settings_changed` event
260
+ * (regardless of persist outcome so listeners see the in-memory change), and
261
+ * return the toast the UI should display. Event payload carries the `persisted`
262
+ * flag so listeners can react to write failures.
263
+ */
264
+ export function saveAndEmitChanged(snapshot, successMsg, emit, cwd = process.cwd()) {
265
+ const persisted = saveSettings(snapshot, cwd);
266
+ emit("subagents:settings_changed", { settings: snapshot, persisted });
267
+ return persistToastFor(successMsg, persisted);
268
+ }