@nredd/pi-subagents 0.0.0-stage → 0.22.0-nredd.6

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 (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1244 -2
  3. package/package.json +75 -4
  4. package/src/abortable.ts +43 -0
  5. package/src/agent-color.ts +161 -0
  6. package/src/agent-file-toggle.ts +297 -0
  7. package/src/agent-manager.ts +1874 -0
  8. package/src/agent-runner.ts +1552 -0
  9. package/src/agent-source-badge.ts +75 -0
  10. package/src/agent-types.ts +346 -0
  11. package/src/child-context.ts +15 -0
  12. package/src/clock.ts +25 -0
  13. package/src/completion-outbox.ts +125 -0
  14. package/src/context.ts +58 -0
  15. package/src/cross-extension-rpc.ts +221 -0
  16. package/src/custom-agents.ts +436 -0
  17. package/src/default-agents.ts +126 -0
  18. package/src/detached-results.ts +134 -0
  19. package/src/enabled-models.ts +180 -0
  20. package/src/enterprise-local.ts +66 -0
  21. package/src/env.ts +33 -0
  22. package/src/group-join.ts +148 -0
  23. package/src/index.ts +4423 -0
  24. package/src/invocation-config.ts +189 -0
  25. package/src/memory.ts +179 -0
  26. package/src/mention-clone.ts +195 -0
  27. package/src/mention.ts +141 -0
  28. package/src/model-call.ts +83 -0
  29. package/src/model-resolver.ts +266 -0
  30. package/src/model-scope.ts +70 -0
  31. package/src/nested-tools.ts +448 -0
  32. package/src/output-file.ts +164 -0
  33. package/src/package-resources.ts +624 -0
  34. package/src/prompts.ts +156 -0
  35. package/src/quota-admission.ts +99 -0
  36. package/src/schedule-store.ts +153 -0
  37. package/src/schedule.ts +446 -0
  38. package/src/settings.ts +728 -0
  39. package/src/skill-loader.ts +137 -0
  40. package/src/startup-error.ts +29 -0
  41. package/src/status-note.ts +90 -0
  42. package/src/structured-output.ts +130 -0
  43. package/src/types.ts +404 -0
  44. package/src/ui/agent-mention.ts +216 -0
  45. package/src/ui/agent-row.ts +235 -0
  46. package/src/ui/agent-widget.ts +692 -0
  47. package/src/ui/conversation-viewer.ts +832 -0
  48. package/src/ui/fleet-list.ts +675 -0
  49. package/src/ui/notification-view.ts +120 -0
  50. package/src/ui/schedule-menu.ts +105 -0
  51. package/src/ui/select-item.ts +45 -0
  52. package/src/ui/viewer-keys.ts +39 -0
  53. package/src/ui/workflow-card.ts +462 -0
  54. package/src/ui/workflow-dialog.ts +1115 -0
  55. package/src/ui/workflow-menu.ts +193 -0
  56. package/src/usage.ts +167 -0
  57. package/src/workflow/collisions.ts +123 -0
  58. package/src/workflow/entry.ts +47 -0
  59. package/src/workflow/host.ts +401 -0
  60. package/src/workflow/journal.ts +164 -0
  61. package/src/workflow/json-schema.ts +129 -0
  62. package/src/workflow/meta.ts +326 -0
  63. package/src/workflow/progress.ts +549 -0
  64. package/src/workflow/runtime.ts +1216 -0
  65. package/src/workflow/saved.ts +259 -0
  66. package/src/workflow/task.ts +302 -0
  67. package/src/workflow/tool-description.ts +200 -0
  68. package/src/workflow/worker-source.ts +781 -0
  69. package/src/worktree.ts +230 -0
  70. package/src/xml.ts +13 -0
@@ -0,0 +1,728 @@
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
+
5
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { dirname, join } from "node:path";
7
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
8
+ import { NO_FALLBACK } from "./agent-types.js";
9
+ import { readEnterpriseLocalManifest } from "./enterprise-local.js";
10
+ import type { AgentMentionMode, JoinMode, ViewerMarkdownMode, WidgetMode } from "./types.js";
11
+
12
+ export interface SubagentsSettings {
13
+ maxConcurrent?: number;
14
+ /**
15
+ * Max concurrent FOREGROUND (blocking) agents — `0` = unlimited, the default,
16
+ * which preserves the behaviour that has always applied: nothing bounded
17
+ * foreground work, and pi dispatches a message's tool calls through
18
+ * `Promise.all`, so an unqualified fan-out of blocking `Agent` calls runs all
19
+ * at once. Set it to bound that (#253 — on local models, parallel agents
20
+ * thrash the prompt cache).
21
+ *
22
+ * Deliberately independent of `maxConcurrent` rather than folded into it: a
23
+ * foreground agent blocks the parent anyway, so charging it to the background
24
+ * pool would let a saturated pool starve the main session of work it could
25
+ * have done itself.
26
+ *
27
+ * Bounds only spawns a caller is blocking on inline. Nested children are
28
+ * exempt — their parent is blocked awaiting them, so queueing a child behind
29
+ * its own parent would deadlock — and so are detached spawns from
30
+ * cross-extension RPC or `@handle` mentions, which block nobody and are
31
+ * documented to start immediately. Foreground `resume` is also outside the
32
+ * pool: it reuses an existing session and never reaches the spawn path, so
33
+ * several blocking resumes in one message can still exceed the limit.
34
+ */
35
+ maxConcurrentForeground?: number;
36
+ /**
37
+ * 0 = unlimited — the extension's single source of truth for that convention:
38
+ * `normalizeMaxTurns()` in agent-runner.ts treats 0 → `undefined`, and the
39
+ * `/agents` → Settings input prompt explicitly says "0 = unlimited".
40
+ */
41
+ defaultMaxTurns?: number;
42
+ graceTurns?: number;
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 the Claude Code-style FleetView (the navigable main+subagents list
124
+ * rendered below the editor) is shown. Defaults to `true`. Pure-UI: when off,
125
+ * the list never registers and the global key handler never captures input.
126
+ */
127
+ fleetView?: boolean;
128
+ /**
129
+ * Whether `@handle message` typed at the prompt is routed to that subagent
130
+ * instead of the main model, and whether `@` offers running agents alongside
131
+ * pi's file completion. Defaults to `model`. Applied live.
132
+ *
133
+ * - `model`: mentioning an agent that is not running asks the main model to
134
+ * spawn it with the `Agent` tool, Claude Code's behaviour. Costs a turn,
135
+ * and the model writes the agent's prompt rather than your text being it.
136
+ * - `direct`: that agent is started here instead, with the typed message as
137
+ * its prompt and no main-model turn spent.
138
+ * - `off`: the input hook falls straight through and the stacked
139
+ * autocomplete provider delegates everything back to pi's built-in one.
140
+ *
141
+ * Messaging a running agent and resuming a finished one are direct in both
142
+ * `model` and `direct`. The legacy booleans are still accepted: `true` reads
143
+ * as `model`, `false` as `off`.
144
+ */
145
+ agentMentions?: AgentMentionMode;
146
+ /**
147
+ * Whether subagents persist their pi session by default, so `@handle` can
148
+ * reopen an agent's conversation long after its in-memory record is gone.
149
+ * Defaults to `true`. Per-agent `persist_session:` frontmatter overrides it
150
+ * in both directions. Turning it off restores the previous behaviour, where
151
+ * a handle stops resolving roughly ten minutes after the agent finishes and
152
+ * mentioning it starts a fresh run instead. Persisted sessions also appear
153
+ * nested under the spawning session in pi's `/resume`.
154
+ */
155
+ rememberAgents?: boolean;
156
+ /**
157
+ * Display mode for the persistent above-editor agent widget:
158
+ * - `all`: show every agent (foreground + background).
159
+ * - `background`: hide foreground agents — they already render inline as the
160
+ * Agent tool result, so the widget would otherwise double-render them
161
+ * (#118); everything else (background, queued, scheduled, RPC) stays.
162
+ * - `off`: hide the widget entirely.
163
+ * Defaults to `background`. Pure-UI and applied live (toggling refreshes the
164
+ * widget).
165
+ */
166
+ widgetMode?: WidgetMode;
167
+ /**
168
+ * Project/global default for writing each subagent's `.output` transcript
169
+ * (a JSON-lines copy of the run, stored under the OS temp dir).
170
+ * Defaults to `true`. Set `false` to make transcripts opt-in for the whole
171
+ * project (e.g. a repo that shouldn't leave run transcripts on disk for backup
172
+ * or DLP tooling to ingest). A custom agent's `output_transcript` frontmatter
173
+ * overrides this per agent. This governs only the transcript — it does NOT
174
+ * affect the persisted pi session (`persist_session`), worktree commits
175
+ * (`isolation: worktree`), or memory files.
176
+ */
177
+ outputTranscript?: boolean;
178
+ /**
179
+ * Whether `isolation: "worktree"` may create a worktree at all. Defaults to
180
+ * `true`. Set `false` on a repo where worktrees are too slow or too large to
181
+ * be worth it (#184): a requested worktree is then dropped and the agent runs
182
+ * in the main checkout.
183
+ *
184
+ * The drop is deliberately silent — there is no per-result note, because the
185
+ * setting exists for projects whose model asks for a worktree on every call,
186
+ * where a note would be noise on every result. What keeps the orchestrator
187
+ * from claiming a `pi-agent-*` branch anyway is that it is never told the
188
+ * capability exists: `isolationParam` (invocation-config.ts) drops the field
189
+ * from both tool schemas, and `isolationGuideline` (index.ts) drops the
190
+ * matching prose from the full and compact descriptions — a custom one opts
191
+ * in via the `{{isolationGuideline}}` placeholder. Anything that
192
+ * reintroduces the prose has to reintroduce a note with it.
193
+ *
194
+ * Deliberately a downgrade rather than an error. The fail-loud rule covers
195
+ * worktrees that *cannot* be created; this is the user declining one, and
196
+ * throwing would reject exactly the calls that the `isolation: "off"` value
197
+ * exists to tolerate. Enforced below the tool boundary, so it also covers the
198
+ * scheduler and the unvalidated cross-extension RPC path.
199
+ */
200
+ worktreeIsolation?: boolean;
201
+ /**
202
+ * Master switch for scripted workflows. Defaults to `true`.
203
+ *
204
+ * Off is not a soft hide: the `SubagentWorkflow` tool is never registered, so
205
+ * the model is not told it exists and cannot call it, the `/agents`
206
+ * Workflows entry is hidden, and `--subagents-workflow-file` is refused.
207
+ *
208
+ * Absent is not the same as `true`. Unset means *auto*: on, but yielding to
209
+ * another extension that already offers a workflow tool, because two
210
+ * orchestrators in one tool spec is a worse default than none — the model
211
+ * has to guess which to call, and pays for both descriptions to find out.
212
+ * Setting it explicitly pins the answer in both directions: `true` keeps
213
+ * ours whatever else is loaded, `false` is off regardless. See
214
+ * `resolveWorkflowCollisions` in index.ts.
215
+ *
216
+ * Read once at extension init, before registration, so flipping it in
217
+ * `/agents → Settings` takes effect on the next pi session — the same
218
+ * contract `schedulingEnabled` has, and for the same reason: a tool spec is
219
+ * fixed once pi has it.
220
+ */
221
+ workflowsEnabled?: boolean;
222
+ /**
223
+ * Hard ceiling on nested subagent delegation, counted from the main session:
224
+ * main = 0, its subagents = 1, their children = 2. Defaults to `2`; `0` or `1`
225
+ * disables nesting project-wide. Read when a subagent session is built, so a
226
+ * change applies to agents started after it.
227
+ */
228
+ maxSubagentDepth?: number;
229
+ /**
230
+ * Agent type substituted when a caller-supplied `subagent_type` doesn't
231
+ * resolve to exactly one enabled agent (unknown, disabled, or ambiguous by
232
+ * case). Omitted keeps the historical `general-purpose` fallback; a type name
233
+ * routes those calls to that agent instead; `"none"` disables the fallback so
234
+ * dispatch fails closed with an error naming the available types.
235
+ *
236
+ * The boolean `false` is accepted as a spelling of `"none"`, because a boolean
237
+ * would otherwise be dropped as the wrong type and silently leave the
238
+ * PERMISSIVE default in place while the author believes strict dispatch is on
239
+ * — the wrong direction to fail for this setting. Every other value is an
240
+ * agent name, so a mistaken `"off"` fails loudly at dispatch rather than
241
+ * meaning one thing here and another in the resolver.
242
+ */
243
+ fallbackSubagent?: string;
244
+ /** Trusted-global logical name -> ordered canonical provider/model candidates. */
245
+ modelAliases?: Record<string, string[]>;
246
+ /**
247
+ * Trusted-global map of agent `type` (or `"*"` for every type) -> model, in
248
+ * any form `Agent({ model })` accepts. Precedence, highest first: the Agent
249
+ * tool's `model` parameter, `agentModels[type]`, `agentModels["*"]`, the agent
250
+ * definition's `model:`, then the parent's model. Like `modelAliases` it
251
+ * decides which provider a subagent runs on, so a project `.pi/subagents.json`
252
+ * value is ignored with a warning.
253
+ */
254
+ agentModels?: Record<string, string>;
255
+ /**
256
+ * Whether this extension's tool results carry a `usage` field, so subagent
257
+ * spend reaches the parent session's own accounting. Defaults to `false`.
258
+ *
259
+ * Subagents run in their own pi sessions, so by default the parent's footer,
260
+ * statusline and `/cost` show only what the main model spent — a session that
261
+ * delegated most of its work reads as nearly free. Pi folds
262
+ * `toolResult.usage` into `getSessionStats()`, so attaching it makes those
263
+ * surfaces count subagents too, under `/cost`'s "Tools/summaries" bucket.
264
+ *
265
+ * Off by default because it changes numbers the user may already be tracking
266
+ * (a statusline reading session cost will step up), not because the numbers
267
+ * are wrong.
268
+ *
269
+ * Three properties of what gets reported:
270
+ * - Tokens exclude `cacheRead`, for the reason in `usage.ts` — the parent's
271
+ * token total therefore rises by billed tokens only.
272
+ * - Cost is pi's own per-message `usage.cost.total`; we price nothing, and
273
+ * a model pi has no rates for contributes 0.
274
+ * - The context-window percentage is untouched. Pi derives it from assistant
275
+ * messages alone (`getContextUsage`), so a delegating session's context
276
+ * does not appear to fill up faster.
277
+ */
278
+ reportUsage?: boolean;
279
+ /**
280
+ * Whether the subagent surfaces show an estimated dollar cost next to their
281
+ * token counts (widget, FleetView, conversation viewer, foreground results,
282
+ * completion notifications). Defaults to `false`. Applied live.
283
+ *
284
+ * Rendered as `~$0.0042` — the tilde marks it as pi's reported estimate
285
+ * rather than a billed figure, and it is omitted entirely when the model has
286
+ * no pricing data, so a local model shows tokens and no dollars.
287
+ *
288
+ * Independent of `reportUsage`: this one is what a human reads, that one is
289
+ * what the parent session counts.
290
+ */
291
+ showCost?: boolean;
292
+
293
+ /**
294
+ * Whether the widget's running rows name the model driving each agent and the
295
+ * thinking level it is running at.
296
+ *
297
+ * Off by default, unlike the tool result and the conversation viewer, which
298
+ * show the pair unconditionally: those have a line to themselves, while the
299
+ * widget row already carries the description, turns, tool uses, tokens and
300
+ * elapsed time, and every character it gains is one the description loses on a
301
+ * narrow terminal.
302
+ */
303
+ showModel?: boolean;
304
+ /**
305
+ * Whether agents declared by installed pi packages load, and from which
306
+ * packages. Defaults to `true`.
307
+ *
308
+ * - `true` — every package whose `package.json` declares `pi.subagents`
309
+ * (or the top-level `pi-subagents` key) contributes its agents.
310
+ * - `false` — none do.
311
+ * - list — only packages matching an entry, compared case-insensitively
312
+ * against the unscoped short name (`@scope/foo` matches `foo`),
313
+ * the full package name, or the settings source string.
314
+ *
315
+ * On by default because installing is already the trust decision: pi executes
316
+ * an installed package's `extensions/` and injects its `skills/` into the
317
+ * system prompt with no further prompt, so a declared `.md` agent is strictly
318
+ * less privileged than what the same package already runs. The gate exists for
319
+ * users who want to narrow that anyway, not as a second install ritual.
320
+ *
321
+ * Package agents always load at the *lowest* precedence, below global and
322
+ * project files, so a same-named local agent silently takes the name back.
323
+ */
324
+ packageAgents?: boolean | string[];
325
+ /**
326
+ * The same gate for workflow scripts declared by installed pi packages
327
+ * (`pi.subagents.workflows`). Defaults to `true`.
328
+ *
329
+ * Deliberately separate from `packageAgents` rather than folded into it: an
330
+ * agent is markdown we hand to a model, a workflow is `.js` we execute. Both
331
+ * still sit below the package's own `extensions/`, which pi runs unsandboxed,
332
+ * so the default matches — but a user who wants package agents without package
333
+ * workflow scripts can have that without giving up either wholesale.
334
+ *
335
+ * No-op when `workflowsEnabled` is off: the tool is never registered, so there
336
+ * is nothing to resolve a workflow name against.
337
+ */
338
+ packageWorkflows?: boolean | string[];
339
+ /**
340
+ * How much of the conversation viewer's transcript renders as Markdown.
341
+ * Defaults to `assistant`. Applied live — the viewer's `m` key cycles this
342
+ * same setting, so a choice made in the overlay persists like one made in
343
+ * `/agents → Settings`.
344
+ *
345
+ * Scoped rather than all-or-nothing because the two kinds of content have
346
+ * different contracts: assistant text is authored as Markdown, while a tool
347
+ * result is whatever bytes the tool produced. Rendering the latter as
348
+ * Markdown is lossy in ways that look like the tool misbehaved — see
349
+ * `ViewerMarkdownMode` for the specific rewrites — so `all` is opt-in.
350
+ */
351
+ viewerMarkdown?: ViewerMarkdownMode;
352
+ }
353
+
354
+ export type ToolDescriptionMode = "full" | "compact" | "custom";
355
+
356
+ /** Setter hooks used by applySettings to wire persisted values into in-memory state. */
357
+ export interface SettingsAppliers {
358
+ setMaxConcurrent: (n: number) => void;
359
+ setMaxConcurrentForeground: (n: number) => void;
360
+ setDefaultMaxTurns: (n: number) => void;
361
+ setGraceTurns: (n: number) => void;
362
+ setDefaultJoinMode: (mode: JoinMode) => void;
363
+ setBackgroundByDefault: (b: boolean) => void;
364
+ setSchedulingEnabled: (b: boolean) => void;
365
+ setScopeModels: (enabled: boolean) => void;
366
+ setStrictAgentFiles: (b: boolean) => void;
367
+ setDisableDefaultAgents: (b: boolean) => void;
368
+ setToolDescriptionMode: (mode: ToolDescriptionMode) => void;
369
+ setFleetView: (b: boolean) => void;
370
+ setAgentMentions: (mode: AgentMentionMode) => void;
371
+ setRememberAgents: (b: boolean) => void;
372
+ setWidgetMode: (mode: WidgetMode) => void;
373
+ setOutputTranscript: (b: boolean) => void;
374
+ setWorktreeIsolation: (b: boolean) => void;
375
+ setWorkflowsEnabled: (b: boolean) => void;
376
+ setMaxSubagentDepth: (n: number) => void;
377
+ setFallbackSubagent: (v: string | undefined) => void;
378
+ setModelAliases: (v: Record<string, string[]> | undefined) => void;
379
+ setAgentModels: (v: Record<string, string> | undefined) => void;
380
+ setReportUsage: (b: boolean) => void;
381
+ setShowCost: (b: boolean) => void;
382
+ setShowModel: (b: boolean) => void;
383
+ setViewerMarkdown: (mode: ViewerMarkdownMode) => void;
384
+ setPackageAgents: (gate: boolean | string[]) => void;
385
+ setPackageWorkflows: (gate: boolean | string[]) => void;
386
+ }
387
+
388
+ /** Emit callback — a subset of `pi.events.emit` to keep helpers testable. */
389
+ export type SettingsEmit = (event: string, payload: unknown) => void;
390
+
391
+ const VALID_JOIN_MODES: ReadonlySet<string> = new Set<JoinMode>(["async", "group", "smart"]);
392
+ const VALID_TOOL_DESCRIPTION_MODES: ReadonlySet<string> = new Set<ToolDescriptionMode>(["full", "compact", "custom"]);
393
+ const VALID_WIDGET_MODES: ReadonlySet<string> = new Set<WidgetMode>(["all", "background", "off"]);
394
+ const VALID_VIEWER_MARKDOWN_MODES: ReadonlySet<string> = new Set<ViewerMarkdownMode>(["off", "assistant", "all"]);
395
+ const VALID_AGENT_MENTION_MODES: ReadonlySet<string> = new Set<AgentMentionMode>(["model", "direct", "off"]);
396
+
397
+ // Sanity ceilings — prevent hand-edited configs from asking for values that
398
+ // make no operational sense (e.g. 1e6 concurrent subagents). Permissive enough
399
+ // that any realistic power-user setting passes through.
400
+ const MAX_CONCURRENT_CEILING = 1024;
401
+ const MAX_TURNS_CEILING = 10_000;
402
+ const GRACE_TURNS_CEILING = 1_000;
403
+ const SUBAGENT_DEPTH_CEILING = 16;
404
+
405
+ /**
406
+ * Normalize a package gate: a boolean passes through, an array is trimmed to its
407
+ * non-empty string entries, a bare string becomes a one-entry allowlist, and
408
+ * anything else is dropped.
409
+ *
410
+ * The two coercions exist for the same reason: this setting's default is `true`,
411
+ * so *dropping* a malformed value silently admits every package — the opposite
412
+ * of what someone narrowing the gate meant. So an array that trims to empty is
413
+ * kept as `[]` (matching nothing, like `false`) rather than dropped, and
414
+ * `"my-package"` — the obvious typo for a one-entry list — is read as
415
+ * `["my-package"]` rather than widened to everything.
416
+ */
417
+ function sanitizePackageGate(val: unknown): boolean | string[] | undefined {
418
+ if (typeof val === "boolean") return val;
419
+ if (typeof val === "string") return val.trim() ? [val.trim()] : [];
420
+ if (!Array.isArray(val)) return undefined;
421
+ return val.filter((e): e is string => typeof e === "string").map(e => e.trim()).filter(Boolean);
422
+ }
423
+
424
+ /** Drop fields that don't match the expected shape. Silent — garbage becomes absent. */
425
+ function sanitize(raw: unknown): SubagentsSettings {
426
+ if (!raw || typeof raw !== "object") return {};
427
+ const r = raw as Record<string, unknown>;
428
+ const out: SubagentsSettings = {};
429
+ if (
430
+ Number.isInteger(r.maxConcurrent) &&
431
+ (r.maxConcurrent as number) >= 1 &&
432
+ (r.maxConcurrent as number) <= MAX_CONCURRENT_CEILING
433
+ ) {
434
+ out.maxConcurrent = r.maxConcurrent as number;
435
+ }
436
+ // Floor 0, not 1 like maxConcurrent above: 0 is the documented "unlimited"
437
+ // value and the default, so dropping it would silently be unrepresentable.
438
+ if (
439
+ Number.isInteger(r.maxConcurrentForeground) &&
440
+ (r.maxConcurrentForeground as number) >= 0 &&
441
+ (r.maxConcurrentForeground as number) <= MAX_CONCURRENT_CEILING
442
+ ) {
443
+ out.maxConcurrentForeground = r.maxConcurrentForeground as number;
444
+ }
445
+ if (
446
+ Number.isInteger(r.defaultMaxTurns) &&
447
+ (r.defaultMaxTurns as number) >= 0 &&
448
+ (r.defaultMaxTurns as number) <= MAX_TURNS_CEILING
449
+ ) {
450
+ out.defaultMaxTurns = r.defaultMaxTurns as number;
451
+ }
452
+ if (
453
+ Number.isInteger(r.graceTurns) &&
454
+ (r.graceTurns as number) >= 1 &&
455
+ (r.graceTurns as number) <= GRACE_TURNS_CEILING
456
+ ) {
457
+ out.graceTurns = r.graceTurns as number;
458
+ }
459
+ if (
460
+ Number.isInteger(r.maxSubagentDepth) &&
461
+ (r.maxSubagentDepth as number) >= 0 &&
462
+ (r.maxSubagentDepth as number) <= SUBAGENT_DEPTH_CEILING
463
+ ) {
464
+ out.maxSubagentDepth = r.maxSubagentDepth as number;
465
+ }
466
+ if (typeof r.defaultJoinMode === "string" && VALID_JOIN_MODES.has(r.defaultJoinMode)) {
467
+ out.defaultJoinMode = r.defaultJoinMode as JoinMode;
468
+ }
469
+ if (typeof r.backgroundByDefault === "boolean") {
470
+ out.backgroundByDefault = r.backgroundByDefault;
471
+ }
472
+ if (typeof r.schedulingEnabled === "boolean") {
473
+ out.schedulingEnabled = r.schedulingEnabled;
474
+ }
475
+ if (typeof r.scopeModels === "boolean") {
476
+ out.scopeModels = r.scopeModels;
477
+ }
478
+ if (typeof r.strictAgentFiles === "boolean") {
479
+ out.strictAgentFiles = r.strictAgentFiles;
480
+ }
481
+ if (typeof r.disableDefaultAgents === "boolean") {
482
+ out.disableDefaultAgents = r.disableDefaultAgents;
483
+ }
484
+ if (typeof r.toolDescriptionMode === "string" && VALID_TOOL_DESCRIPTION_MODES.has(r.toolDescriptionMode)) {
485
+ out.toolDescriptionMode = r.toolDescriptionMode as ToolDescriptionMode;
486
+ }
487
+ if (typeof r.fleetView === "boolean") {
488
+ out.fleetView = r.fleetView;
489
+ }
490
+ // Was a boolean before the `model` mode existed. A hand-written or
491
+ // previously-written `true` means "on", which is now the default `model`.
492
+ if (typeof r.agentMentions === "boolean") {
493
+ out.agentMentions = r.agentMentions ? "model" : "off";
494
+ } else if (typeof r.agentMentions === "string" && VALID_AGENT_MENTION_MODES.has(r.agentMentions)) {
495
+ out.agentMentions = r.agentMentions as AgentMentionMode;
496
+ }
497
+ if (typeof r.rememberAgents === "boolean") {
498
+ out.rememberAgents = r.rememberAgents;
499
+ }
500
+ if (typeof r.widgetMode === "string" && VALID_WIDGET_MODES.has(r.widgetMode)) {
501
+ out.widgetMode = r.widgetMode as WidgetMode;
502
+ }
503
+ if (typeof r.outputTranscript === "boolean") {
504
+ out.outputTranscript = r.outputTranscript;
505
+ }
506
+ if (typeof r.worktreeIsolation === "boolean") {
507
+ out.worktreeIsolation = r.worktreeIsolation;
508
+ }
509
+ if (typeof r.reportUsage === "boolean") {
510
+ out.reportUsage = r.reportUsage;
511
+ }
512
+ if (typeof r.showCost === "boolean") {
513
+ out.showCost = r.showCost;
514
+ }
515
+ if (typeof r.showModel === "boolean") {
516
+ out.showModel = r.showModel;
517
+ }
518
+ if (typeof r.viewerMarkdown === "string" && VALID_VIEWER_MARKDOWN_MODES.has(r.viewerMarkdown)) {
519
+ out.viewerMarkdown = r.viewerMarkdown as ViewerMarkdownMode;
520
+ }
521
+ if (typeof r.workflowsEnabled === "boolean") {
522
+ out.workflowsEnabled = r.workflowsEnabled;
523
+ }
524
+ const packageAgents = sanitizePackageGate(r.packageAgents);
525
+ if (packageAgents !== undefined) out.packageAgents = packageAgents;
526
+ const packageWorkflows = sanitizePackageGate(r.packageWorkflows);
527
+ if (packageWorkflows !== undefined) out.packageWorkflows = packageWorkflows;
528
+ if (r.fallbackSubagent === false) {
529
+ // The only non-string spelling worth accepting: a boolean would otherwise be
530
+ // dropped, silently leaving the PERMISSIVE default in place. Every string is
531
+ // an agent name except the `none` sentinel, which the resolver recognizes —
532
+ // so a mistaken "off" fails loudly at dispatch instead of meaning something
533
+ // different here than it does there.
534
+ out.fallbackSubagent = NO_FALLBACK;
535
+ } else if (typeof r.fallbackSubagent === "string" && r.fallbackSubagent.trim()) {
536
+ out.fallbackSubagent = r.fallbackSubagent.trim();
537
+ }
538
+ if (r.modelAliases !== undefined) {
539
+ const aliases = sanitizeModelAliases(r.modelAliases);
540
+ if (aliases) out.modelAliases = aliases;
541
+ }
542
+ if (r.agentModels !== undefined) {
543
+ const models = sanitizeAgentModels(r.agentModels);
544
+ if (models) out.agentModels = models;
545
+ }
546
+ return out;
547
+ }
548
+
549
+ /** Validate the `agentModels` map: non-empty string keys and non-empty string values. */
550
+ function sanitizeAgentModels(raw: unknown): Record<string, string> | undefined {
551
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
552
+ console.warn("[pi-subagents] Ignoring agentModels: expected an object of agent type -> model.");
553
+ return undefined;
554
+ }
555
+ const models: Record<string, string> = {};
556
+ for (const [type, model] of Object.entries(raw)) {
557
+ const key = type.trim();
558
+ if (!key || typeof model !== "string" || !model.trim()) {
559
+ console.warn(`[pi-subagents] Ignoring invalid agentModels entry "${type}".`);
560
+ continue;
561
+ }
562
+ models[key] = model.trim();
563
+ }
564
+ return models;
565
+ }
566
+
567
+ /** Validate one-way logical aliases without interpreting provider details. */
568
+ function sanitizeModelAliases(raw: unknown): Record<string, string[]> | undefined {
569
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
570
+ console.warn("[pi-subagents] Ignoring modelAliases: expected an object of alias -> provider/model candidates.");
571
+ return undefined;
572
+ }
573
+ const aliases: Record<string, string[]> = {};
574
+ const seen = new Set<string>();
575
+ for (const [alias, rawCandidates] of Object.entries(raw)) {
576
+ const normalized = alias.trim().toLowerCase();
577
+ const candidates = Array.isArray(rawCandidates)
578
+ ? rawCandidates.filter((candidate): candidate is string => typeof candidate === "string")
579
+ .map(candidate => candidate.trim()).filter(Boolean)
580
+ : [];
581
+ if (!normalized || normalized.includes("/") || seen.has(normalized) || candidates.length === 0
582
+ || candidates.some(candidate => !candidate.includes("/"))) {
583
+ console.warn(`[pi-subagents] Ignoring invalid modelAliases entry "${alias}".`);
584
+ continue;
585
+ }
586
+ seen.add(normalized);
587
+ aliases[normalized] = [...new Set(candidates)];
588
+ }
589
+ return aliases;
590
+ }
591
+
592
+ function globalPath(): string {
593
+ return join(getAgentDir(), "subagents.json");
594
+ }
595
+
596
+ function projectPath(cwd: string): string {
597
+ return join(cwd, ".pi", "subagents.json");
598
+ }
599
+
600
+ /**
601
+ * Read a settings file. Missing file is silent (returns `{}`). A file that
602
+ * exists but can't be parsed emits a warning to stderr so users aren't
603
+ * silently reverted to defaults — and still returns `{}` so startup proceeds.
604
+ */
605
+ function readSettingsFile(path: string): SubagentsSettings {
606
+ if (!existsSync(path)) return {};
607
+ try {
608
+ return sanitize(JSON.parse(readFileSync(path, "utf-8")));
609
+ } catch (err) {
610
+ const reason = err instanceof Error ? err.message : String(err);
611
+ console.warn(`[pi-subagents] Ignoring malformed settings at ${path}: ${reason}`);
612
+ return {};
613
+ }
614
+ }
615
+
616
+ /** Load merged settings: global provides defaults, project overrides. */
617
+ export function loadSettings(cwd: string = process.cwd()): SubagentsSettings {
618
+ // Aliases pick the provider a subagent runs on, so they are machine
619
+ // configuration: a cloned repo's project file must not redirect them.
620
+ const { modelAliases: projectModelAliases, agentModels: projectAgentModels, ...project } = readSettingsFile(projectPath(cwd));
621
+ if (projectModelAliases !== undefined) {
622
+ console.warn("[pi-subagents] Ignoring modelAliases in project .pi/subagents.json: aliases are read from trusted global configuration only.");
623
+ }
624
+ if (projectAgentModels !== undefined) {
625
+ console.warn("[pi-subagents] Ignoring agentModels in project .pi/subagents.json: per-agent models are read from trusted global configuration only.");
626
+ }
627
+ const enterprise = readEnterpriseLocalManifest()?.subagents;
628
+ const enterpriseSettings = enterprise === undefined ? {} : sanitize(enterprise);
629
+ return { ...readSettingsFile(globalPath()), ...enterpriseSettings, ...project };
630
+ }
631
+
632
+ /**
633
+ * Write project-local settings. Global is never touched from code.
634
+ * Returns `true` on success, `false` if the write (or mkdir) failed so the
635
+ * caller can surface a warning — persistence isn't fatal but isn't silent.
636
+ */
637
+ export function saveSettings(s: SubagentsSettings, cwd: string = process.cwd()): boolean {
638
+ const path = projectPath(cwd);
639
+ try {
640
+ mkdirSync(dirname(path), { recursive: true });
641
+ writeFileSync(path, JSON.stringify(s, null, 2), "utf-8");
642
+ return true;
643
+ } catch {
644
+ return false;
645
+ }
646
+ }
647
+
648
+ /** Apply persisted settings to the in-memory state via caller-supplied setters. */
649
+ export function applySettings(s: SubagentsSettings, appliers: SettingsAppliers): void {
650
+ if (typeof s.maxConcurrent === "number") appliers.setMaxConcurrent(s.maxConcurrent);
651
+ if (typeof s.maxConcurrentForeground === "number") {
652
+ appliers.setMaxConcurrentForeground(s.maxConcurrentForeground);
653
+ }
654
+ if (typeof s.defaultMaxTurns === "number") appliers.setDefaultMaxTurns(s.defaultMaxTurns);
655
+ if (typeof s.graceTurns === "number") appliers.setGraceTurns(s.graceTurns);
656
+ if (typeof s.maxSubagentDepth === "number") appliers.setMaxSubagentDepth(s.maxSubagentDepth);
657
+ if (typeof s.fallbackSubagent === "string") appliers.setFallbackSubagent(s.fallbackSubagent);
658
+ // Module state: reset when a session omits it, or the previous activation's aliases leak.
659
+ appliers.setModelAliases(s.modelAliases);
660
+ appliers.setAgentModels(s.agentModels);
661
+ if (s.defaultJoinMode) appliers.setDefaultJoinMode(s.defaultJoinMode);
662
+ if (typeof s.backgroundByDefault === "boolean") appliers.setBackgroundByDefault(s.backgroundByDefault);
663
+ if (typeof s.schedulingEnabled === "boolean") appliers.setSchedulingEnabled(s.schedulingEnabled);
664
+ if (typeof s.scopeModels === "boolean") appliers.setScopeModels(s.scopeModels);
665
+ if (typeof s.strictAgentFiles === "boolean") appliers.setStrictAgentFiles(s.strictAgentFiles);
666
+ if (typeof s.disableDefaultAgents === "boolean") appliers.setDisableDefaultAgents(s.disableDefaultAgents);
667
+ if (s.toolDescriptionMode) appliers.setToolDescriptionMode(s.toolDescriptionMode);
668
+ if (typeof s.fleetView === "boolean") appliers.setFleetView(s.fleetView);
669
+ if (s.agentMentions) appliers.setAgentMentions(s.agentMentions);
670
+ if (typeof s.rememberAgents === "boolean") appliers.setRememberAgents(s.rememberAgents);
671
+ if (s.widgetMode) appliers.setWidgetMode(s.widgetMode);
672
+ if (typeof s.outputTranscript === "boolean") appliers.setOutputTranscript(s.outputTranscript);
673
+ if (typeof s.worktreeIsolation === "boolean") appliers.setWorktreeIsolation(s.worktreeIsolation);
674
+ if (typeof s.reportUsage === "boolean") appliers.setReportUsage(s.reportUsage);
675
+ if (typeof s.showCost === "boolean") appliers.setShowCost(s.showCost);
676
+ if (typeof s.showModel === "boolean") appliers.setShowModel(s.showModel);
677
+ if (s.viewerMarkdown) appliers.setViewerMarkdown(s.viewerMarkdown);
678
+ if (typeof s.workflowsEnabled === "boolean") appliers.setWorkflowsEnabled(s.workflowsEnabled);
679
+ if (s.packageAgents !== undefined) appliers.setPackageAgents(s.packageAgents);
680
+ if (s.packageWorkflows !== undefined) appliers.setPackageWorkflows(s.packageWorkflows);
681
+ }
682
+
683
+ /**
684
+ * Format the user-facing toast for a settings mutation. Pure function —
685
+ * routes the success/failure of `saveSettings` into the right message + level
686
+ * so the UI layer (index.ts) stays a thin wire between input and notification.
687
+ */
688
+ export function persistToastFor(
689
+ successMsg: string,
690
+ persisted: boolean,
691
+ ): { message: string; level: "info" | "warning" } {
692
+ return persisted
693
+ ? { message: successMsg, level: "info" }
694
+ : { message: `${successMsg} (session only; failed to persist)`, level: "warning" };
695
+ }
696
+
697
+ /**
698
+ * Load merged settings, apply them to in-memory state, and emit the
699
+ * `subagents:settings_loaded` lifecycle event. Returns the loaded settings so
700
+ * callers can log/inspect. Extension init wires this once.
701
+ */
702
+ export function applyAndEmitLoaded(
703
+ appliers: SettingsAppliers,
704
+ emit: SettingsEmit,
705
+ cwd: string = process.cwd(),
706
+ ): SubagentsSettings {
707
+ const settings = loadSettings(cwd);
708
+ applySettings(settings, appliers);
709
+ emit("subagents:settings_loaded", { settings });
710
+ return settings;
711
+ }
712
+
713
+ /**
714
+ * Persist a settings snapshot, emit the `subagents:settings_changed` event
715
+ * (regardless of persist outcome so listeners see the in-memory change), and
716
+ * return the toast the UI should display. Event payload carries the `persisted`
717
+ * flag so listeners can react to write failures.
718
+ */
719
+ export function saveAndEmitChanged(
720
+ snapshot: SubagentsSettings,
721
+ successMsg: string,
722
+ emit: SettingsEmit,
723
+ cwd: string = process.cwd(),
724
+ ): { message: string; level: "info" | "warning" } {
725
+ const persisted = saveSettings(snapshot, cwd);
726
+ emit("subagents:settings_changed", { settings: snapshot, persisted });
727
+ return persistToastFor(successMsg, persisted);
728
+ }