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