@herbertgao/pi-extensions 2026.11.10 → 2026.11.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +6 -6
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
  5. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +2 -2
  6. package/node_modules/@herbertgao/pi-cc-extensions/README.md +2 -2
  7. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +13 -8
  8. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/grouping.ts +58 -15
  9. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/tool-io.ts +0 -5
  10. package/node_modules/@herbertgao/pi-cc-extensions/extensions/utils/ansi-text.ts +18 -4
  11. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  12. package/node_modules/@herbertgao/pi-impeccable/CHANGELOG.md +6 -0
  13. package/node_modules/@herbertgao/pi-impeccable/README.md +2 -2
  14. package/node_modules/@herbertgao/pi-impeccable/package.json +4 -4
  15. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/SKILL.md +3 -1
  16. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/adapt.md +1 -1
  17. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/audit.md +12 -1
  18. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/audit.native.md +4 -0
  19. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/critique.md +5 -5
  20. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/degraded/documenter.md +1 -1
  21. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/degraded/finish-reviewer.md +1 -1
  22. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/distill.md +1 -1
  23. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/document.md +3 -1
  24. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/foundations.md +44 -0
  25. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/live-setup.md +1 -1
  26. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/live.md +26 -12
  27. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/new-work.md +10 -9
  28. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/onboard.md +7 -6
  29. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/overdrive.md +2 -2
  30. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/quieter.md +1 -1
  31. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/visualize.md +1 -1
  32. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/VERSION +1 -1
  33. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/engine-checksums.txt +5 -5
  34. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/impeccable +69 -16
  35. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/impeccable.cmd +55 -7
  36. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/live-browser.js +34 -4
  37. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +6 -0
  38. package/node_modules/@herbertgao/pi-subagents/README.md +27 -9
  39. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +11 -11
  40. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  41. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +13 -0
  42. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +51 -32
  43. package/node_modules/@herbertgao/pi-subagents/src/default-agents.ts +7 -0
  44. package/node_modules/@herbertgao/pi-subagents/src/index.ts +334 -893
  45. package/node_modules/@herbertgao/pi-subagents/src/nested-tools.ts +4 -1
  46. package/node_modules/@herbertgao/pi-subagents/src/prompts.ts +13 -0
  47. package/node_modules/@herbertgao/pi-subagents/src/schedule-store.ts +18 -13
  48. package/node_modules/@herbertgao/pi-subagents/src/schedule.ts +25 -5
  49. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +215 -69
  50. package/node_modules/@herbertgao/pi-subagents/src/types.ts +17 -0
  51. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +9 -0
  52. package/node_modules/@herbertgao/pi-subagents/src/ui/agents-menu.ts +705 -0
  53. package/node_modules/@herbertgao/pi-subagents/src/ui/settings-menu.ts +361 -0
  54. package/node_modules/@herbertgao/pi-subagents/src/ui/viewer-keys.ts +1 -1
  55. package/node_modules/pi-commandcode-provider/CHANGELOG.md +11 -1
  56. package/node_modules/pi-commandcode-provider/index.ts +2 -1
  57. package/node_modules/pi-commandcode-provider/package.json +5 -4
  58. package/node_modules/pi-commandcode-provider/src/pricing.ts +8 -1
  59. package/node_modules/pi-commandcode-provider/src/responses-compat.ts +137 -0
  60. package/package.json +5 -5
@@ -0,0 +1,705 @@
1
+ /**
2
+ * agents-menu.ts — the `/agents` command: its root menu and every page below
3
+ * it except Settings (`settings-menu.ts`), Workflows (`workflow-menu.ts`) and
4
+ * Scheduled jobs (`schedule-menu.ts`), which it opens.
5
+ *
6
+ * Running agents, agent types with their detail page (eject, disable,
7
+ * enable), and the create wizards. The session state these read lives in
8
+ * `index.ts` and comes in through `AgentsMenuDeps`.
9
+ */
10
+
11
+ import {
12
+ existsSync,
13
+ mkdirSync,
14
+ readFileSync,
15
+ unlinkSync,
16
+ writeFileSync,
17
+ } from "node:fs"
18
+ import { join } from "node:path"
19
+ import {
20
+ type ExtensionAPI,
21
+ type ExtensionCommandContext,
22
+ getSettingsListTheme,
23
+ } from "@earendil-works/pi-coding-agent"
24
+ import {
25
+ Container,
26
+ type SettingItem,
27
+ SettingsList,
28
+ Spacer,
29
+ Text,
30
+ } from "@earendil-works/pi-tui"
31
+ import {
32
+ buildNewAgentFile,
33
+ disableInContent,
34
+ enableInContent,
35
+ isEmptyStub,
36
+ locateAgentFile,
37
+ personalAgentsDir,
38
+ projectAgentsDir,
39
+ serializeAgentFile,
40
+ } from "../agent-file-toggle.js"
41
+ import type { AgentManager } from "../agent-manager.js"
42
+ import {
43
+ rowDescription,
44
+ sourceIndicator,
45
+ sourceLegend,
46
+ } from "../agent-source-badge.js"
47
+ import {
48
+ BUILTIN_TOOL_NAMES,
49
+ getAgentConfig,
50
+ getAllTypes,
51
+ } from "../agent-types.js"
52
+ import type { ModelRegistry } from "../model-resolver.js"
53
+ import { packageNameForPath } from "../package-resources.js"
54
+ import type { SubagentScheduler } from "../schedule.js"
55
+ import {
56
+ type AgentConfig,
57
+ type AgentRecord,
58
+ THINKING_LEVELS,
59
+ } from "../types.js"
60
+ import { isWorktreeIsolationEnabled } from "../worktree.js"
61
+ import { agentTree } from "./agent-tree.js"
62
+ import { formatDuration, getDisplayName } from "./agent-widget.js"
63
+ import { showSchedulesMenu } from "./schedule-menu.js"
64
+ import { selectItem } from "./select-item.js"
65
+ import { showWorkflowsMenu, type WorkflowMenuDeps } from "./workflow-menu.js"
66
+
67
+ export interface AgentsMenuDeps {
68
+ pi: ExtensionAPI
69
+ manager: AgentManager
70
+ scheduler: SubagentScheduler
71
+ /** The Workflows page's deps; its `tasks` also give the menu's run count. */
72
+ workflowMenuDeps: WorkflowMenuDeps
73
+ isWorkflowsEnabled(): boolean
74
+ reloadCustomAgents(): void
75
+ getModelLabel(type: string, registry?: ModelRegistry): string
76
+ /** The conversation overlay, shared with the Workflows page. */
77
+ viewAgentConversation(
78
+ ctx: ExtensionCommandContext,
79
+ record: AgentRecord,
80
+ ): Promise<void>
81
+ showSettings(ctx: ExtensionCommandContext): Promise<void>
82
+ }
83
+
84
+ export function createAgentsMenu(deps: AgentsMenuDeps): {
85
+ showAgentsMenu(ctx: ExtensionCommandContext): Promise<void>
86
+ } {
87
+ const {
88
+ pi,
89
+ manager,
90
+ scheduler,
91
+ workflowMenuDeps,
92
+ isWorkflowsEnabled,
93
+ reloadCustomAgents,
94
+ getModelLabel,
95
+ viewAgentConversation,
96
+ showSettings,
97
+ } = deps
98
+
99
+ async function showAgentsMenu(ctx: ExtensionCommandContext) {
100
+ reloadCustomAgents()
101
+ const allNames = getAllTypes()
102
+
103
+ // Each row pairs its label with the value the menu dispatches on.
104
+ const items: { value: string; label: string }[] = []
105
+ const agents = runningAgentsRoster().map((row) => row.record)
106
+ if (agents.length > 0) {
107
+ const running = agents.filter(
108
+ (a) => a.status === "running" || a.status === "queued",
109
+ ).length
110
+ const done = agents.filter(
111
+ (a) => a.status === "completed" || a.status === "steered",
112
+ ).length
113
+ items.push({
114
+ value: "running",
115
+ label: `Running agents (${agents.length}) — ${running} running, ${done} done`,
116
+ })
117
+ }
118
+ if (allNames.length > 0) {
119
+ items.push({ value: "types", label: `Agent types (${allNames.length})` })
120
+ }
121
+ // Shown only while the scheduler is active.
122
+ if (scheduler.isActive()) {
123
+ items.push({
124
+ value: "schedules",
125
+ label: `Scheduled jobs (${scheduler.list().length})`,
126
+ })
127
+ }
128
+ // Workflow runs, on the same terms as scheduled jobs: shown only when the
129
+ // feature is on, so the menu never advertises something switched off.
130
+ if (isWorkflowsEnabled()) {
131
+ items.push({
132
+ value: "workflows",
133
+ label: `Workflows (${workflowMenuDeps.tasks.size})`,
134
+ })
135
+ }
136
+ items.push({ value: "create", label: "Create new agent" })
137
+ items.push({ value: "settings", label: "Settings" })
138
+
139
+ const noAgentsMsg =
140
+ allNames.length === 0 && agents.length === 0
141
+ ? "No agents found. Create specialized subagents that can be delegated to.\n\n" +
142
+ "Each subagent has its own context window, custom system prompt, and specific tools.\n\n" +
143
+ "Try creating: Code Reviewer, Security Auditor, Test Writer, or Documentation Writer.\n\n"
144
+ : ""
145
+
146
+ if (noAgentsMsg) {
147
+ ctx.ui.notify(noAgentsMsg, "info")
148
+ }
149
+
150
+ const label = await ctx.ui.select(
151
+ "Agents",
152
+ items.map((item) => item.label),
153
+ )
154
+ const choice = items.find((item) => item.label === label)?.value
155
+ if (!choice) return
156
+
157
+ if (choice === "running") {
158
+ await showRunningAgents(ctx)
159
+ await showAgentsMenu(ctx)
160
+ } else if (choice === "types") {
161
+ await showAllAgentsList(ctx)
162
+ await showAgentsMenu(ctx)
163
+ } else if (choice === "schedules") {
164
+ await showSchedulesMenu(ctx, scheduler)
165
+ await showAgentsMenu(ctx)
166
+ } else if (choice === "workflows") {
167
+ await showWorkflowsMenu(ctx, workflowMenuDeps)
168
+ await showAgentsMenu(ctx)
169
+ } else if (choice === "create") {
170
+ await showCreateWizard(ctx)
171
+ } else if (choice === "settings") {
172
+ await showSettings(ctx)
173
+ await showAgentsMenu(ctx)
174
+ }
175
+ }
176
+
177
+ /**
178
+ * The package that provided an agent, for display only. Undefined for every
179
+ * other source, and for a package path no currently-admitted package owns —
180
+ * which is what a stale `sourcePath` looks like after the gate narrows.
181
+ */
182
+ function packageNameOf(cfg: AgentConfig | undefined): string | undefined {
183
+ if (cfg?.source !== "package" || !cfg.sourcePath) return undefined
184
+ return packageNameForPath(cfg.sourcePath, process.cwd())
185
+ }
186
+
187
+ async function showAllAgentsList(ctx: ExtensionCommandContext) {
188
+ const allNames = getAllTypes()
189
+ if (allNames.length === 0) {
190
+ ctx.ui.notify("No agents.", "info")
191
+ return
192
+ }
193
+
194
+ const configs = allNames.map((name) => getAgentConfig(name))
195
+
196
+ // One row per agent (name in the left column, model on the right); the
197
+ // full description renders below the highlighted row via SettingsList,
198
+ // exactly like the Settings menu — so long descriptions never wrap the list.
199
+ // A package agent's description is prefixed with the package that provided
200
+ // it: the `▪` badge says a package won, not which one.
201
+ const items: SettingItem[] = allNames.map((name, i) => {
202
+ const cfg = configs[i]
203
+ const model = getModelLabel(name, ctx.modelRegistry)
204
+ return {
205
+ id: name,
206
+ label: `${sourceIndicator(cfg)}${name}`,
207
+ currentValue: model,
208
+ description: rowDescription(name, cfg, packageNameOf(cfg)),
209
+ // Single-value list so Enter "activates" the row (fires onChange with the
210
+ // agent's id) without offering anything to actually cycle.
211
+ values: [model],
212
+ }
213
+ })
214
+
215
+ const legend = sourceLegend(configs)
216
+
217
+ const selected = await ctx.ui.custom<string | undefined>(
218
+ (_tui, _theme, _kb, done) => {
219
+ const slTheme = getSettingsListTheme()
220
+ const list = new SettingsList(
221
+ items,
222
+ Math.min(items.length, 12),
223
+ slTheme,
224
+ (id) => done(id), // Enter/Space on a row → return that agent's name
225
+ () => done(undefined), // Esc → cancel
226
+ )
227
+ const container = new Container()
228
+ container.addChild(new Text("Agent types", 0, 0))
229
+ if (legend) container.addChild(new Text(slTheme.hint(legend), 0, 0))
230
+ container.addChild(new Spacer(1))
231
+ container.addChild(list)
232
+ return {
233
+ render: (w: number) => container.render(w),
234
+ invalidate: () => container.invalidate(),
235
+ handleInput: (data: string) => list.handleInput?.(data),
236
+ }
237
+ },
238
+ )
239
+
240
+ if (selected && getAgentConfig(selected)) {
241
+ await showAgentDetail(ctx, selected)
242
+ await showAllAgentsList(ctx)
243
+ }
244
+ }
245
+
246
+ /**
247
+ * The session's agents plus their nested children, as a tree (newest
248
+ * top-level first). Nested children are listed here as in FleetView: this
249
+ * list keeps finished agents until eviction, so it is where a finished child
250
+ * stays reachable. Workflow agents stay in the workflow inspector.
251
+ */
252
+ function runningAgentsRoster() {
253
+ return agentTree(
254
+ manager.listAgents().filter((a) => a.workflowId === undefined),
255
+ )
256
+ }
257
+
258
+ async function showRunningAgents(ctx: ExtensionCommandContext) {
259
+ const rows = runningAgentsRoster()
260
+ if (rows.length === 0) {
261
+ ctx.ui.notify("No agents.", "info")
262
+ return
263
+ }
264
+
265
+ // Numbered + item-paired. Two same-type agents spawned together with the
266
+ // same description render identically here, and resolving the choice by
267
+ // string match would open whichever came first.
268
+ const row = await selectItem(
269
+ ctx.ui,
270
+ "Running agents",
271
+ rows,
272
+ ({ record: a, prefix }) => {
273
+ const dn = getDisplayName(a.type)
274
+ const dur = formatDuration(a.startedAt, a.completedAt)
275
+ return `${prefix}${dn} (${a.description}) · ${a.toolUses} tools · ${a.status} · ${dur}`
276
+ },
277
+ )
278
+ if (!row) return
279
+ const record = row.record
280
+
281
+ await viewAgentConversation(ctx, record)
282
+ // Back-navigation: re-show the list
283
+ await showRunningAgents(ctx)
284
+ }
285
+
286
+ async function showAgentDetail(ctx: ExtensionCommandContext, name: string) {
287
+ const cfg = getAgentConfig(name)
288
+ if (!cfg) {
289
+ ctx.ui.notify(`Agent config not found for "${name}".`, "warning")
290
+ return
291
+ }
292
+
293
+ const isPackage = cfg.source === "package"
294
+ const file = locateAgentFile(name, cfg.sourcePath, undefined, cfg.source)
295
+ const isDefault = cfg.isDefault === true
296
+ const disabled = cfg.enabled === false
297
+
298
+ let menuOptions: string[]
299
+ if (isPackage) {
300
+ // Read-only: nothing here may write inside pi's install root. `Disable`
301
+ // still appears because it writes a *local* stub that shadows the package
302
+ // agent, and `Enable` never does — a package agent that reads as disabled
303
+ // was disabled by its own author's `enabled: false`, which only the
304
+ // package can take back. Eject is the way out of that: the copy it writes
305
+ // carries no `enabled:` line, so the ejected agent is on.
306
+ menuOptions = disabled
307
+ ? ["Eject (export as .md)", "Back"]
308
+ : ["Eject (export as .md)", "Disable", "Back"]
309
+ } else if (disabled && file) {
310
+ // Disabled agent with a file — offer Enable
311
+ menuOptions = isDefault
312
+ ? ["Enable", "Edit", "Reset to default", "Delete", "Back"]
313
+ : ["Enable", "Edit", "Delete", "Back"]
314
+ } else if (isDefault && !file) {
315
+ // Default agent with no .md override
316
+ menuOptions = ["Eject (export as .md)", "Disable", "Back"]
317
+ } else if (isDefault && file) {
318
+ // Default agent with .md override (ejected)
319
+ menuOptions = ["Edit", "Disable", "Reset to default", "Delete", "Back"]
320
+ } else {
321
+ // User-defined agent
322
+ menuOptions = ["Edit", "Disable", "Delete", "Back"]
323
+ }
324
+
325
+ // Name the package in the title: this menu's options are the read-only set,
326
+ // and "which package do I have to uninstall or allowlist away" is the
327
+ // question they raise.
328
+ const pkgName = packageNameOf(cfg)
329
+ const choice = await ctx.ui.select(
330
+ pkgName ? `${name} — ${pkgName}` : name,
331
+ menuOptions,
332
+ )
333
+ if (!choice || choice === "Back") return
334
+
335
+ if (choice === "Edit" && file) {
336
+ const content = readFileSync(file.path, "utf-8")
337
+ const edited = await ctx.ui.editor(`Edit ${name}`, content)
338
+ if (edited !== undefined && edited !== content) {
339
+ writeFileSync(file.path, edited, "utf-8")
340
+ reloadCustomAgents()
341
+ ctx.ui.notify(`Updated ${file.path}`, "info")
342
+ }
343
+ } else if (choice === "Delete") {
344
+ if (file) {
345
+ const confirmed = await ctx.ui.confirm(
346
+ "Delete agent",
347
+ `Delete ${name} from ${file.location} (${file.path})?`,
348
+ )
349
+ if (confirmed) {
350
+ unlinkSync(file.path)
351
+ reloadCustomAgents()
352
+ ctx.ui.notify(`Deleted ${file.path}`, "info")
353
+ }
354
+ }
355
+ } else if (choice === "Reset to default" && file) {
356
+ const confirmed = await ctx.ui.confirm(
357
+ "Reset to default",
358
+ `Delete override ${file.path} and restore embedded default?`,
359
+ )
360
+ if (confirmed) {
361
+ unlinkSync(file.path)
362
+ reloadCustomAgents()
363
+ ctx.ui.notify(`Restored default ${name}`, "info")
364
+ }
365
+ } else if (choice.startsWith("Eject")) {
366
+ await ejectAgent(ctx, name, cfg)
367
+ } else if (choice === "Disable") {
368
+ await disableAgent(ctx, name)
369
+ } else if (choice === "Enable") {
370
+ await enableAgent(ctx, name)
371
+ }
372
+ }
373
+
374
+ /** Eject a default agent: write its embedded config as a .md file. */
375
+ async function ejectAgent(
376
+ ctx: ExtensionCommandContext,
377
+ name: string,
378
+ cfg: AgentConfig,
379
+ ) {
380
+ const location = await ctx.ui.select("Choose location", [
381
+ "Project (.pi/agents/)",
382
+ `Personal (${personalAgentsDir()})`,
383
+ ])
384
+ if (!location) return
385
+
386
+ const targetDir = location.startsWith("Project")
387
+ ? projectAgentsDir()
388
+ : personalAgentsDir()
389
+ mkdirSync(targetDir, { recursive: true })
390
+
391
+ const targetPath = join(targetDir, `${name}.md`)
392
+ if (existsSync(targetPath)) {
393
+ const overwrite = await ctx.ui.confirm(
394
+ "Overwrite",
395
+ `${targetPath} already exists. Overwrite?`,
396
+ )
397
+ if (!overwrite) return
398
+ }
399
+
400
+ const content = serializeAgentFile(cfg)
401
+
402
+ writeFileSync(targetPath, content, "utf-8")
403
+ reloadCustomAgents()
404
+ ctx.ui.notify(`Ejected ${name} to ${targetPath}`, "info")
405
+ }
406
+
407
+ /** Disable an agent: set enabled: false in its .md file, or create a stub for built-in defaults. */
408
+ async function disableAgent(ctx: ExtensionCommandContext, name: string) {
409
+ const cfg = getAgentConfig(name)
410
+ // `locateAgentFile` refuses a package agent's own path, so this is either the
411
+ // local stub already shadowing it or nothing — never a file inside pi's
412
+ // install root. An unshadowed package agent therefore falls to the stub
413
+ // branch below, which writes `enabled: false` at project or personal scope.
414
+ const file = locateAgentFile(name, cfg?.sourcePath, undefined, cfg?.source)
415
+ if (file) {
416
+ // Existing file — set enabled: false in frontmatter (idempotent)
417
+ const content = readFileSync(file.path, "utf-8")
418
+ const { content: updated, outcome } = disableInContent(content)
419
+ if (outcome === "already-disabled") {
420
+ ctx.ui.notify(`${name} is already disabled.`, "info")
421
+ return
422
+ }
423
+ if (outcome === "no-frontmatter") {
424
+ // Nothing to edit — say so rather than rewriting the file unchanged and
425
+ // reporting success for a change that never happened.
426
+ ctx.ui.notify(
427
+ `Cannot disable ${name}: ${file.path} has no frontmatter block.`,
428
+ "error",
429
+ )
430
+ return
431
+ }
432
+ writeFileSync(file.path, updated, "utf-8")
433
+ reloadCustomAgents()
434
+ ctx.ui.notify(`Disabled ${name} (${file.path})`, "info")
435
+ return
436
+ }
437
+
438
+ // No editable file (a built-in default, or a package-provided agent) —
439
+ // create a stub that shadows it.
440
+ const location = await ctx.ui.select("Choose location", [
441
+ "Project (.pi/agents/)",
442
+ `Personal (${personalAgentsDir()})`,
443
+ ])
444
+ if (!location) return
445
+
446
+ const targetDir = location.startsWith("Project")
447
+ ? projectAgentsDir()
448
+ : personalAgentsDir()
449
+ mkdirSync(targetDir, { recursive: true })
450
+
451
+ const targetPath = join(targetDir, `${name}.md`)
452
+ writeFileSync(targetPath, "---\nenabled: false\n---\n", "utf-8")
453
+ reloadCustomAgents()
454
+ ctx.ui.notify(`Disabled ${name} (${targetPath})`, "info")
455
+ }
456
+
457
+ /** Enable a disabled agent by removing enabled: false from its frontmatter. */
458
+ async function enableAgent(ctx: ExtensionCommandContext, name: string) {
459
+ const cfg = getAgentConfig(name)
460
+ const file = locateAgentFile(name, cfg?.sourcePath, undefined, cfg?.source)
461
+ if (!file) return
462
+
463
+ const content = readFileSync(file.path, "utf-8")
464
+ const { content: updated, changed } = enableInContent(content)
465
+ if (!changed && !isEmptyStub(updated)) {
466
+ // The file carries no `enabled: false` to remove, so it was never disabled
467
+ // by us — reporting success here would hide a no-op.
468
+ ctx.ui.notify(`${name} is not disabled in ${file.path}.`, "info")
469
+ return
470
+ }
471
+
472
+ // If the file was just a stub ("---\n---\n"), delete it to restore the built-in default
473
+ if (isEmptyStub(updated)) {
474
+ unlinkSync(file.path)
475
+ reloadCustomAgents()
476
+ ctx.ui.notify(`Enabled ${name} (removed ${file.path})`, "info")
477
+ } else {
478
+ writeFileSync(file.path, updated, "utf-8")
479
+ reloadCustomAgents()
480
+ ctx.ui.notify(`Enabled ${name} (${file.path})`, "info")
481
+ }
482
+ }
483
+
484
+ async function showCreateWizard(ctx: ExtensionCommandContext) {
485
+ const location = await ctx.ui.select("Choose location", [
486
+ "Project (.pi/agents/)",
487
+ `Personal (${personalAgentsDir()})`,
488
+ ])
489
+ if (!location) return
490
+
491
+ const targetDir = location.startsWith("Project")
492
+ ? projectAgentsDir()
493
+ : personalAgentsDir()
494
+
495
+ const method = await ctx.ui.select("Creation method", [
496
+ "Generate with Claude (recommended)",
497
+ "Manual configuration",
498
+ ])
499
+ if (!method) return
500
+
501
+ if (method.startsWith("Generate")) {
502
+ await showGenerateWizard(ctx, targetDir)
503
+ } else {
504
+ await showManualWizard(ctx, targetDir)
505
+ }
506
+ }
507
+
508
+ async function showGenerateWizard(
509
+ ctx: ExtensionCommandContext,
510
+ targetDir: string,
511
+ ) {
512
+ const description = await ctx.ui.input("Describe what this agent should do")
513
+ if (!description) return
514
+
515
+ const name = await ctx.ui.input("Agent name (filename, no spaces)")
516
+ if (!name) return
517
+
518
+ mkdirSync(targetDir, { recursive: true })
519
+
520
+ const targetPath = join(targetDir, `${name}.md`)
521
+ if (existsSync(targetPath)) {
522
+ const overwrite = await ctx.ui.confirm(
523
+ "Overwrite",
524
+ `${targetPath} already exists. Overwrite?`,
525
+ )
526
+ if (!overwrite) return
527
+ }
528
+
529
+ ctx.ui.notify("Generating agent definition...", "info")
530
+
531
+ const generatePrompt = `Create a custom pi sub-agent definition file based on this description: "${description}"
532
+
533
+ Write a markdown file to: ${targetPath}
534
+
535
+ The file format is a markdown file with YAML frontmatter and a system prompt body:
536
+
537
+ \`\`\`markdown
538
+ ---
539
+ description: <one-line description shown in UI>
540
+ color: <optional agent name badge color: red, blue, green, yellow, purple, orange, pink, cyan, an Agency Agents alias, or quoted "#RRGGBB">
541
+ tools: <comma-separated built-in tools: read, bash, edit, write, grep, find, ls. Use "none" for no tools. Omit for all tools>
542
+ model: <optional model as "provider/modelId", e.g. "anthropic/claude-haiku-4-5". Omit to inherit parent model>
543
+ thinking: <optional thinking level: ${THINKING_LEVELS.join(", ")}. Omit to inherit>
544
+ max_turns: <optional max agentic turns. 0 or omit for unlimited (default)>
545
+ prompt_mode: <"replace" (body IS the full system prompt) or "append" (body is appended to default prompt). Default: replace>
546
+ extensions: <true (inherit all MCP/extension tools), false (none), or comma-separated names. Default: true>
547
+ skills: <true (inherit all), false (none), or comma-separated skill names to preload into prompt. Default: true>
548
+ disallowed_tools: <comma-separated tool names to block, even if otherwise available. Omit for none>
549
+ inherit_context: <true to fork parent conversation into agent so it sees chat history. Default: false>
550
+ run_in_background: <pin this agent to background (true) or foreground (false). Omit to follow the backgroundByDefault setting, which is background>
551
+ output_transcript: <false to write no transcript file or path for this agent. Independent of persist_session. Default: true>
552
+ isolated: <true for no extension/MCP tools, only built-in tools. Default: false>
553
+ memory: <"user" (global), "project" (per-project), or "local" (gitignored per-project) for persistent memory. Omit for none>${
554
+ // Offering the field on a project that turned worktrees off would bake a
555
+ // request that is refused at spawn time into a file that outlives the
556
+ // session — the #231 pathology (models fill the fields they are shown)
557
+ // one layer up. Built per invocation, so this read is live.
558
+ isWorktreeIsolationEnabled()
559
+ ? `\nisolation: <"worktree" to run in isolated git worktree; "off" to refuse one even when the caller asks. Omit for normal>`
560
+ : ""
561
+ }
562
+ ---
563
+
564
+ <system prompt body — instructions for the agent>
565
+ \`\`\`
566
+
567
+ Guidelines for choosing settings:
568
+ - For read-only tasks (review, analysis): tools: read, bash, grep, find, ls
569
+ - For code modification tasks: include edit, write
570
+ - Use prompt_mode: append if the agent should keep the default system prompt and add specialization on top
571
+ - Use prompt_mode: replace for fully custom agents with their own personality/instructions
572
+ - Set inherit_context: true if the agent needs to know what was discussed in the parent conversation
573
+ - Set isolated: true if the agent should NOT have access to MCP servers or other extensions
574
+ - Set output_transcript: false to skip writing this agent's transcript; this alone doesn't keep the run off disk (persist_session, isolation: worktree commits, and memory still write) — set those too if that's the goal
575
+ - Only include frontmatter fields that differ from defaults — omit fields where the default is fine
576
+
577
+ Write the file using the write tool. Only write the file, nothing else.`
578
+
579
+ const { record } = await manager.spawnAndWait(
580
+ pi,
581
+ ctx,
582
+ "general-purpose",
583
+ generatePrompt,
584
+ {
585
+ description: `Generate ${name} agent`,
586
+ maxTurns: 5,
587
+ // Exempt from maxConcurrentForeground. This runs from a modal wizard, not
588
+ // a tool call: it passes no signal, and Esc in `ctx.ui` never reaches the
589
+ // manager — so a user waiting behind a full pool would have no way to
590
+ // cancel at all. It is also one human action that cannot fan out, which
591
+ // is what the limit exists to bound. It still counts once started.
592
+ bypassQueue: true,
593
+ },
594
+ )
595
+
596
+ if (record.status === "error") {
597
+ ctx.ui.notify(`Generation failed: ${record.error}`, "warning")
598
+ return
599
+ }
600
+
601
+ reloadCustomAgents()
602
+
603
+ if (existsSync(targetPath)) {
604
+ ctx.ui.notify(`Created ${targetPath}`, "info")
605
+ } else {
606
+ ctx.ui.notify(
607
+ "Agent generation completed but file was not created. Check the agent output.",
608
+ "warning",
609
+ )
610
+ }
611
+ }
612
+
613
+ async function showManualWizard(
614
+ ctx: ExtensionCommandContext,
615
+ targetDir: string,
616
+ ) {
617
+ // 1. Name
618
+ const name = await ctx.ui.input("Agent name (filename, no spaces)")
619
+ if (!name) return
620
+
621
+ // 2. Description
622
+ const description = await ctx.ui.input("Description (one line)")
623
+ if (!description) return
624
+
625
+ // 3. Tools
626
+ const toolChoice = await ctx.ui.select("Tools", [
627
+ "all",
628
+ "none",
629
+ "read-only (read, bash, grep, find, ls)",
630
+ "custom...",
631
+ ])
632
+ if (!toolChoice) return
633
+
634
+ let tools: string
635
+ if (toolChoice === "all") {
636
+ tools = BUILTIN_TOOL_NAMES.join(", ")
637
+ } else if (toolChoice === "none") {
638
+ tools = "none"
639
+ } else if (toolChoice.startsWith("read-only")) {
640
+ tools = "read, bash, grep, find, ls"
641
+ } else {
642
+ const customTools = await ctx.ui.input(
643
+ "Tools (comma-separated)",
644
+ BUILTIN_TOOL_NAMES.join(", "),
645
+ )
646
+ if (!customTools) return
647
+ tools = customTools
648
+ }
649
+
650
+ // 4. Model
651
+ const modelChoice = await ctx.ui.select("Model", [
652
+ "inherit (parent model)",
653
+ "haiku",
654
+ "sonnet",
655
+ "opus",
656
+ "custom...",
657
+ ])
658
+ if (!modelChoice) return
659
+
660
+ let model: string | undefined
661
+ if (modelChoice === "haiku") model = "anthropic/claude-haiku-4-5"
662
+ else if (modelChoice === "sonnet") model = "anthropic/claude-sonnet-4-6"
663
+ else if (modelChoice === "opus") model = "anthropic/claude-opus-4-6"
664
+ else if (modelChoice === "custom...") {
665
+ model = (await ctx.ui.input("Model (provider/modelId)")) || undefined
666
+ }
667
+
668
+ // 5. Thinking
669
+ // "inherit" is a UI-only pseudo-choice (omit the field); the rest mirror pi.
670
+ const thinkingChoice = await ctx.ui.select("Thinking level", [
671
+ "inherit",
672
+ ...THINKING_LEVELS,
673
+ ])
674
+ if (!thinkingChoice) return
675
+
676
+ // 6. System prompt
677
+ const systemPrompt = await ctx.ui.editor("System prompt", "")
678
+ if (systemPrompt === undefined) return
679
+
680
+ const content = buildNewAgentFile({
681
+ description,
682
+ tools,
683
+ model,
684
+ thinking: thinkingChoice === "inherit" ? undefined : thinkingChoice,
685
+ systemPrompt,
686
+ })
687
+
688
+ mkdirSync(targetDir, { recursive: true })
689
+ const targetPath = join(targetDir, `${name}.md`)
690
+
691
+ if (existsSync(targetPath)) {
692
+ const overwrite = await ctx.ui.confirm(
693
+ "Overwrite",
694
+ `${targetPath} already exists. Overwrite?`,
695
+ )
696
+ if (!overwrite) return
697
+ }
698
+
699
+ writeFileSync(targetPath, content, "utf-8")
700
+ reloadCustomAgents()
701
+ ctx.ui.notify(`Created ${targetPath}`, "info")
702
+ }
703
+
704
+ return { showAgentsMenu }
705
+ }