@timmyjl12/pi-subagents 0.0.0-stage → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/CHANGELOG.md +862 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1125 -3
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +40 -0
  9. package/dist/active-agents-prompt.js +98 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +131 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +872 -0
  17. package/dist/agent-manager.js +2910 -0
  18. package/dist/agent-runner.d.ts +358 -0
  19. package/dist/agent-runner.js +1219 -0
  20. package/dist/agent-types.d.ts +142 -0
  21. package/dist/agent-types.js +315 -0
  22. package/dist/awaited-result.d.ts +37 -0
  23. package/dist/awaited-result.js +150 -0
  24. package/dist/child-context.d.ts +15 -0
  25. package/dist/child-context.js +181 -0
  26. package/dist/child-session-shutdown.d.ts +21 -0
  27. package/dist/child-session-shutdown.js +97 -0
  28. package/dist/cleanup-plans.d.ts +10 -0
  29. package/dist/cleanup-plans.js +112 -0
  30. package/dist/context.d.ts +12 -0
  31. package/dist/context.js +56 -0
  32. package/dist/cross-extension-rpc.d.ts +73 -0
  33. package/dist/cross-extension-rpc.js +192 -0
  34. package/dist/custom-agents.d.ts +79 -0
  35. package/dist/custom-agents.js +583 -0
  36. package/dist/default-agents.d.ts +7 -0
  37. package/dist/default-agents.js +125 -0
  38. package/dist/enabled-models.d.ts +49 -0
  39. package/dist/enabled-models.js +145 -0
  40. package/dist/env.d.ts +6 -0
  41. package/dist/env.js +28 -0
  42. package/dist/error-log.d.ts +64 -0
  43. package/dist/error-log.js +176 -0
  44. package/dist/force-main-model.d.ts +21 -0
  45. package/dist/force-main-model.js +28 -0
  46. package/dist/goal-bridge.d.ts +155 -0
  47. package/dist/goal-bridge.js +305 -0
  48. package/dist/group-join.d.ts +36 -0
  49. package/dist/group-join.js +161 -0
  50. package/dist/index.d.ts +52 -0
  51. package/dist/index.js +6390 -0
  52. package/dist/invocation-config.d.ts +164 -0
  53. package/dist/invocation-config.js +158 -0
  54. package/dist/memory.d.ts +53 -0
  55. package/dist/memory.js +165 -0
  56. package/dist/mention-clone.d.ts +87 -0
  57. package/dist/mention-clone.js +178 -0
  58. package/dist/mention.d.ts +81 -0
  59. package/dist/mention.js +131 -0
  60. package/dist/model-resolver.d.ts +36 -0
  61. package/dist/model-resolver.js +95 -0
  62. package/dist/model-scope.d.ts +49 -0
  63. package/dist/model-scope.js +48 -0
  64. package/dist/nested-tools.d.ts +76 -0
  65. package/dist/nested-tools.js +393 -0
  66. package/dist/output-diagnostics.d.ts +11 -0
  67. package/dist/output-diagnostics.js +64 -0
  68. package/dist/output-file.d.ts +64 -0
  69. package/dist/output-file.js +351 -0
  70. package/dist/prompts.d.ts +61 -0
  71. package/dist/prompts.js +94 -0
  72. package/dist/recovery.d.ts +56 -0
  73. package/dist/recovery.js +341 -0
  74. package/dist/report-cleanup.d.ts +204 -0
  75. package/dist/report-cleanup.js +1632 -0
  76. package/dist/report-store.d.ts +738 -0
  77. package/dist/report-store.js +3612 -0
  78. package/dist/schedule-store.d.ts +52 -0
  79. package/dist/schedule-store.js +240 -0
  80. package/dist/schedule.d.ts +121 -0
  81. package/dist/schedule.js +420 -0
  82. package/dist/settings.d.ts +388 -0
  83. package/dist/settings.js +268 -0
  84. package/dist/skill-loader.d.ts +24 -0
  85. package/dist/skill-loader.js +93 -0
  86. package/dist/standalone-fallback.d.ts +30 -0
  87. package/dist/standalone-fallback.js +239 -0
  88. package/dist/status-note.d.ts +61 -0
  89. package/dist/status-note.js +85 -0
  90. package/dist/structured-output.d.ts +61 -0
  91. package/dist/structured-output.js +112 -0
  92. package/dist/terminal-progress.d.ts +115 -0
  93. package/dist/terminal-progress.js +206 -0
  94. package/dist/types.d.ts +411 -0
  95. package/dist/types.js +5 -0
  96. package/dist/ui/agent-mention.d.ts +82 -0
  97. package/dist/ui/agent-mention.js +187 -0
  98. package/dist/ui/agent-widget.d.ts +304 -0
  99. package/dist/ui/agent-widget.js +770 -0
  100. package/dist/ui/cleanup-preview.d.ts +59 -0
  101. package/dist/ui/cleanup-preview.js +466 -0
  102. package/dist/ui/conversation-viewer.d.ts +105 -0
  103. package/dist/ui/conversation-viewer.js +544 -0
  104. package/dist/ui/fleet-list.d.ts +183 -0
  105. package/dist/ui/fleet-list.js +494 -0
  106. package/dist/ui/fleet-overlay.d.ts +203 -0
  107. package/dist/ui/fleet-overlay.js +887 -0
  108. package/dist/ui/hub-feed.d.ts +52 -0
  109. package/dist/ui/hub-feed.js +148 -0
  110. package/dist/ui/native-transcript.d.ts +33 -0
  111. package/dist/ui/native-transcript.js +234 -0
  112. package/dist/ui/schedule-menu.d.ts +16 -0
  113. package/dist/ui/schedule-menu.js +94 -0
  114. package/dist/ui/select-item.d.ts +27 -0
  115. package/dist/ui/select-item.js +34 -0
  116. package/dist/ui/tool-progress.d.ts +22 -0
  117. package/dist/ui/tool-progress.js +56 -0
  118. package/dist/ui/viewer-keys.d.ts +20 -0
  119. package/dist/ui/viewer-keys.js +17 -0
  120. package/dist/ui/workflow-card.d.ts +175 -0
  121. package/dist/ui/workflow-card.js +332 -0
  122. package/dist/ui/workflow-dialog.d.ts +305 -0
  123. package/dist/ui/workflow-dialog.js +848 -0
  124. package/dist/ui/workflow-menu.d.ts +60 -0
  125. package/dist/ui/workflow-menu.js +147 -0
  126. package/dist/usage.d.ts +147 -0
  127. package/dist/usage.js +147 -0
  128. package/dist/workflow/collisions.d.ts +95 -0
  129. package/dist/workflow/collisions.js +88 -0
  130. package/dist/workflow/entry.d.ts +32 -0
  131. package/dist/workflow/entry.js +29 -0
  132. package/dist/workflow/host.d.ts +65 -0
  133. package/dist/workflow/host.js +477 -0
  134. package/dist/workflow/journal.d.ts +113 -0
  135. package/dist/workflow/journal.js +177 -0
  136. package/dist/workflow/json-schema.d.ts +51 -0
  137. package/dist/workflow/json-schema.js +111 -0
  138. package/dist/workflow/meta.d.ts +67 -0
  139. package/dist/workflow/meta.js +317 -0
  140. package/dist/workflow/progress.d.ts +224 -0
  141. package/dist/workflow/progress.js +361 -0
  142. package/dist/workflow/runtime.d.ts +373 -0
  143. package/dist/workflow/runtime.js +919 -0
  144. package/dist/workflow/saved.d.ts +90 -0
  145. package/dist/workflow/saved.js +203 -0
  146. package/dist/workflow/task.d.ts +145 -0
  147. package/dist/workflow/task.js +213 -0
  148. package/dist/workflow/tool-description.d.ts +43 -0
  149. package/dist/workflow/tool-description.js +204 -0
  150. package/dist/workflow/worker-source.d.ts +47 -0
  151. package/dist/workflow/worker-source.js +778 -0
  152. package/dist/worktree.d.ts +52 -0
  153. package/dist/worktree.js +164 -0
  154. package/dist/xml.d.ts +10 -0
  155. package/dist/xml.js +12 -0
  156. package/docs/DEVELOPMENT.md +40 -0
  157. package/docs/artifacts.md +93 -0
  158. package/docs/recovery.md +62 -0
  159. package/docs/rpc.md +252 -0
  160. package/docs/runtime-performance.md +53 -0
  161. package/docs/workflows.md +467 -0
  162. package/examples/agent-tool-description.md +43 -0
  163. package/examples/workflows/compose.js +51 -0
  164. package/examples/workflows/fan-out-audit.js +47 -0
  165. package/examples/workflows/gated-fix.js +60 -0
  166. package/examples/workflows/lib/count-child.js +27 -0
  167. package/examples/workflows/review-panel.js +66 -0
  168. package/examples/workflows/structured-findings.js +78 -0
  169. package/package.json +75 -6
  170. package/src/abortable.ts +43 -0
  171. package/src/active-agents-prompt.ts +115 -0
  172. package/src/advisor-status.ts +74 -0
  173. package/src/agent-color.ts +169 -0
  174. package/src/agent-file-toggle.ts +273 -0
  175. package/src/agent-manager.ts +3312 -0
  176. package/src/agent-runner.ts +1500 -0
  177. package/src/agent-types.ts +390 -0
  178. package/src/awaited-result.ts +187 -0
  179. package/src/child-context.ts +173 -0
  180. package/src/child-session-shutdown.ts +114 -0
  181. package/src/cleanup-plans.ts +112 -0
  182. package/src/context.ts +58 -0
  183. package/src/cross-extension-rpc.ts +257 -0
  184. package/src/custom-agents.ts +689 -0
  185. package/src/default-agents.ts +129 -0
  186. package/src/enabled-models.ts +180 -0
  187. package/src/env.ts +33 -0
  188. package/src/error-log.ts +202 -0
  189. package/src/force-main-model.ts +29 -0
  190. package/src/goal-bridge.ts +468 -0
  191. package/src/group-join.ts +188 -0
  192. package/src/index.ts +6856 -0
  193. package/src/invocation-config.ts +276 -0
  194. package/src/memory.ts +179 -0
  195. package/src/mention-clone.ts +221 -0
  196. package/src/mention.ts +141 -0
  197. package/src/model-resolver.ts +118 -0
  198. package/src/model-scope.ts +70 -0
  199. package/src/nested-tools.ts +553 -0
  200. package/src/output-diagnostics.ts +68 -0
  201. package/src/output-file.ts +380 -0
  202. package/src/prompts.ts +151 -0
  203. package/src/recovery.ts +320 -0
  204. package/src/report-cleanup.ts +2044 -0
  205. package/src/report-store.ts +4130 -0
  206. package/src/schedule-store.ts +244 -0
  207. package/src/schedule.ts +450 -0
  208. package/src/settings.ts +632 -0
  209. package/src/skill-loader.ts +102 -0
  210. package/src/standalone-fallback.ts +195 -0
  211. package/src/status-note.ts +90 -0
  212. package/src/structured-output.ts +130 -0
  213. package/src/terminal-progress.ts +215 -0
  214. package/src/types.ts +424 -0
  215. package/src/ui/agent-mention.ts +216 -0
  216. package/src/ui/agent-widget.ts +866 -0
  217. package/src/ui/cleanup-preview.ts +518 -0
  218. package/src/ui/conversation-viewer.ts +527 -0
  219. package/src/ui/fleet-list.ts +563 -0
  220. package/src/ui/fleet-overlay.ts +1048 -0
  221. package/src/ui/hub-feed.ts +179 -0
  222. package/src/ui/native-transcript.ts +224 -0
  223. package/src/ui/schedule-menu.ts +105 -0
  224. package/src/ui/select-item.ts +45 -0
  225. package/src/ui/tool-progress.ts +67 -0
  226. package/src/ui/viewer-keys.ts +39 -0
  227. package/src/ui/workflow-card.ts +470 -0
  228. package/src/ui/workflow-dialog.ts +1119 -0
  229. package/src/ui/workflow-menu.ts +193 -0
  230. package/src/usage.ts +217 -0
  231. package/src/workflow/collisions.ts +123 -0
  232. package/src/workflow/entry.ts +47 -0
  233. package/src/workflow/host.ts +524 -0
  234. package/src/workflow/journal.ts +221 -0
  235. package/src/workflow/json-schema.ts +128 -0
  236. package/src/workflow/meta.ts +325 -0
  237. package/src/workflow/progress.ts +550 -0
  238. package/src/workflow/runtime.ts +1342 -0
  239. package/src/workflow/saved.ts +217 -0
  240. package/src/workflow/task.ts +313 -0
  241. package/src/workflow/tool-description.ts +205 -0
  242. package/src/workflow/worker-source.ts +781 -0
  243. package/src/worktree.ts +205 -0
  244. package/src/xml.ts +13 -0
@@ -0,0 +1,125 @@
1
+ /**
2
+ * agent-file-toggle.ts — Pure helpers for the `/agents` file-editing operations:
3
+ * locating an agent's .md file, toggling its `enabled:` frontmatter flag, and
4
+ * serializing an AgentConfig back to frontmatter for eject.
5
+ *
6
+ * These live outside src/index.ts so they can be tested directly: the `/agents`
7
+ * command handler is an ~890-line closure reached only through `registerCommand`,
8
+ * which every test mocks.
9
+ *
10
+ * The read side of this data (src/custom-agents.ts) parses frontmatter with a
11
+ * real YAML parser, so it honors `enabled: false` at any position in the block.
12
+ * This module must agree with it, and splits the work accordingly:
13
+ *
14
+ * - Deciding whether a file is disabled is a *read*, so it calls that same parser
15
+ * (`isDisabledContent`) instead of mirroring it. A mirror has to be right about
16
+ * YAML's boolean spellings and about pi's fence scan, and a regex was wrong
17
+ * about both.
18
+ * - *Editing* cannot go through the parser, because re-serializing a parsed
19
+ * document would reformat a file the README tells users to hand-author —
20
+ * discarding their comments, key order, and quoting. So the edits are line-wise
21
+ * and preserve everything they don't touch.
22
+ *
23
+ * That leaves removal best-effort: it recognizes a lowercase bare `false`, and
24
+ * reports `changed: false` for the spellings it cannot rewrite, so the caller
25
+ * refuses honestly rather than announcing a change it did not make.
26
+ */
27
+ import type { AgentConfig } from "./types.ts";
28
+ export type AgentFileLocation = "project" | "workspace" | "personal";
29
+ export declare const projectAgentsDir: (cwd?: string) => string;
30
+ export declare const workspaceAgentsDir: (cwd?: string) => string;
31
+ export declare const personalAgentsDir: () => string;
32
+ /**
33
+ * Find the file path of a custom agent by name, in discovery-precedence order
34
+ * (project, workspace, then global). Mirrors the load-side precedence in
35
+ * src/custom-agents.ts — if the two drift, `/agents` edits a file the loader
36
+ * isn't reading.
37
+ */
38
+ export declare function findAgentFile(name: string, cwd?: string): {
39
+ path: string;
40
+ location: AgentFileLocation;
41
+ } | undefined;
42
+ /**
43
+ * Find the file behind a *loaded* agent, preferring the path the loader
44
+ * actually read (`AgentConfig.sourcePath`) over the `<type>.md` guess.
45
+ *
46
+ * An agent's type comes from its frontmatter `name:` now, so the two can
47
+ * disagree: `reviewer.md` declaring `name: code-reviewer` is loaded as
48
+ * `code-reviewer`, and probing for `code-reviewer.md` finds nothing. That is
49
+ * not a harmless miss — `/agents → Disable` would then take the no-file branch
50
+ * and write a NEW `code-reviewer.md` stub, which loses to `reviewer.md` on
51
+ * load, leaving the agent enabled while reporting success.
52
+ *
53
+ * The probe stays as the fallback: a built-in that was never ejected has no
54
+ * `sourcePath`, and a path can go stale between a load and this call.
55
+ */
56
+ export declare function locateAgentFile(name: string, sourcePath: string | undefined, cwd?: string): {
57
+ path: string;
58
+ location: AgentFileLocation;
59
+ } | undefined;
60
+ export type DisableOutcome = "disabled" | "already-disabled" | "no-frontmatter";
61
+ /**
62
+ * Does the loader consider this file disabled?
63
+ *
64
+ * Detection is a READ operation, so it asks the same parser the loader uses
65
+ * rather than mirroring it with a regex — that mirror has to be right about
66
+ * YAML's boolean spellings (`False`, `FALSE`, a trailing `# comment`, a quoted
67
+ * key) *and* about pi's fence scan, which closes the block on any line starting
68
+ * `---` and so ends it early on `----`. A throw means the file is already
69
+ * unparseable, which is what the loader sees too: it skips the agent, so there
70
+ * is no "disabled" state to report.
71
+ */
72
+ export declare function isDisabledContent(content: string): boolean;
73
+ /**
74
+ * Add `enabled: false` to a file's frontmatter.
75
+ *
76
+ * `outcome` distinguishes a real edit from a no-op so the caller can report
77
+ * honestly instead of unconditionally claiming success.
78
+ */
79
+ export declare function disableInContent(content: string): {
80
+ content: string;
81
+ outcome: DisableOutcome;
82
+ };
83
+ /**
84
+ * Remove `enabled: false` from a file's frontmatter, wherever it appears in the
85
+ * block — the loader honors the key at any position, so the two must agree or a
86
+ * hand-authored agent can be disabled and never re-enabled.
87
+ *
88
+ * `changed` is false when the key wasn't found, so the caller can avoid
89
+ * reporting "Enabled <name>" for a write that did nothing.
90
+ */
91
+ export declare function enableInContent(content: string): {
92
+ content: string;
93
+ changed: boolean;
94
+ };
95
+ /** Is this the empty stub `/agents` writes when disabling a built-in default? */
96
+ export declare function isEmptyStub(content: string): boolean;
97
+ /** The answers `/agents → Create agent → Manual` collects, before serialization. */
98
+ export interface NewAgentInput {
99
+ description: string;
100
+ /** Already-resolved `tools:` value ("none", "all", or a CSV of tool names). */
101
+ tools: string;
102
+ /** `provider/modelId`, or undefined to inherit the parent's model. */
103
+ model?: string;
104
+ /** A pi thinking level, or undefined to inherit. */
105
+ thinking?: string;
106
+ systemPrompt: string;
107
+ }
108
+ /**
109
+ * Build the .md file the create wizard writes.
110
+ *
111
+ * `description` and `model` come straight from a free-text prompt, so they are
112
+ * quoted rather than interpolated — `serializeAgentFile` above quotes the
113
+ * description for the same reason. An unquoted YAML scalar mishandles ordinary
114
+ * input in two ways, and both are silent: a colon ("Scout: find things") makes
115
+ * the file unparseable, and since #212 an unparseable agent file is *skipped*,
116
+ * so the wizard reports success for an agent that does not exist; a `#`
117
+ * ("audit #security") opens a comment and truncates the value. `model` can
118
+ * carry a colon too — pi accepts a `provider/model:thinking` suffix.
119
+ *
120
+ * `tools` and `thinking` are not quoted: both are chosen from fixed menus, and
121
+ * `tools` is a CSV that must stay a bare scalar for the loader's parser.
122
+ */
123
+ export declare function buildNewAgentFile(input: NewAgentInput): string;
124
+ /** Serialize an AgentConfig to a full .md file (frontmatter + system prompt) for eject. */
125
+ export declare function serializeAgentFile(cfg: AgentConfig): string;
@@ -0,0 +1,264 @@
1
+ /**
2
+ * agent-file-toggle.ts — Pure helpers for the `/agents` file-editing operations:
3
+ * locating an agent's .md file, toggling its `enabled:` frontmatter flag, and
4
+ * serializing an AgentConfig back to frontmatter for eject.
5
+ *
6
+ * These live outside src/index.ts so they can be tested directly: the `/agents`
7
+ * command handler is an ~890-line closure reached only through `registerCommand`,
8
+ * which every test mocks.
9
+ *
10
+ * The read side of this data (src/custom-agents.ts) parses frontmatter with a
11
+ * real YAML parser, so it honors `enabled: false` at any position in the block.
12
+ * This module must agree with it, and splits the work accordingly:
13
+ *
14
+ * - Deciding whether a file is disabled is a *read*, so it calls that same parser
15
+ * (`isDisabledContent`) instead of mirroring it. A mirror has to be right about
16
+ * YAML's boolean spellings and about pi's fence scan, and a regex was wrong
17
+ * about both.
18
+ * - *Editing* cannot go through the parser, because re-serializing a parsed
19
+ * document would reformat a file the README tells users to hand-author —
20
+ * discarding their comments, key order, and quoting. So the edits are line-wise
21
+ * and preserve everything they don't touch.
22
+ *
23
+ * That leaves removal best-effort: it recognizes a lowercase bare `false`, and
24
+ * reports `changed: false` for the spellings it cannot rewrite, so the caller
25
+ * refuses honestly rather than announcing a change it did not make.
26
+ */
27
+ import { existsSync } from "node:fs";
28
+ import { join, sep } from "node:path";
29
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
30
+ import { parseAgentFrontmatter } from "./custom-agents.js";
31
+ export const projectAgentsDir = (cwd = process.cwd()) => join(cwd, ".pi", "agents");
32
+ export const workspaceAgentsDir = (cwd = process.cwd()) => join(cwd, ".agents", "agents");
33
+ export const personalAgentsDir = () => join(getAgentDir(), "agents");
34
+ /**
35
+ * Find the file path of a custom agent by name, in discovery-precedence order
36
+ * (project, workspace, then global). Mirrors the load-side precedence in
37
+ * src/custom-agents.ts — if the two drift, `/agents` edits a file the loader
38
+ * isn't reading.
39
+ */
40
+ export function findAgentFile(name, cwd = process.cwd()) {
41
+ const projectPath = join(projectAgentsDir(cwd), `${name}.md`);
42
+ if (existsSync(projectPath))
43
+ return { path: projectPath, location: "project" };
44
+ const workspacePath = join(workspaceAgentsDir(cwd), `${name}.md`);
45
+ if (existsSync(workspacePath))
46
+ return { path: workspacePath, location: "workspace" };
47
+ const personalPath = join(personalAgentsDir(), `${name}.md`);
48
+ if (existsSync(personalPath))
49
+ return { path: personalPath, location: "personal" };
50
+ return undefined;
51
+ }
52
+ /**
53
+ * Find the file behind a *loaded* agent, preferring the path the loader
54
+ * actually read (`AgentConfig.sourcePath`) over the `<type>.md` guess.
55
+ *
56
+ * An agent's type comes from its frontmatter `name:` now, so the two can
57
+ * disagree: `reviewer.md` declaring `name: code-reviewer` is loaded as
58
+ * `code-reviewer`, and probing for `code-reviewer.md` finds nothing. That is
59
+ * not a harmless miss — `/agents → Disable` would then take the no-file branch
60
+ * and write a NEW `code-reviewer.md` stub, which loses to `reviewer.md` on
61
+ * load, leaving the agent enabled while reporting success.
62
+ *
63
+ * The probe stays as the fallback: a built-in that was never ejected has no
64
+ * `sourcePath`, and a path can go stale between a load and this call.
65
+ */
66
+ export function locateAgentFile(name, sourcePath, cwd = process.cwd()) {
67
+ if (sourcePath && existsSync(sourcePath)) {
68
+ return { path: sourcePath, location: classifyAgentDir(sourcePath, cwd) };
69
+ }
70
+ return findAgentFile(name, cwd);
71
+ }
72
+ /**
73
+ * Which discovery location a loaded agent's file came from. Only ever names
74
+ * a directory in a confirmation prompt, so an unrecognized parent — which
75
+ * loadCustomAgents cannot currently produce — reports as personal rather than
76
+ * widening the type for a case that has no better answer.
77
+ */
78
+ function classifyAgentDir(path, cwd) {
79
+ if (path.startsWith(projectAgentsDir(cwd) + sep))
80
+ return "project";
81
+ if (path.startsWith(workspaceAgentsDir(cwd) + sep))
82
+ return "workspace";
83
+ return "personal";
84
+ }
85
+ /** A line that sets `enabled: false`, ignoring trailing whitespace / CR. */
86
+ const ENABLED_FALSE = /^enabled:[ \t]*false[ \t]*$/;
87
+ /** An opening or closing `---` fence line. */
88
+ const FENCE = /^---[ \t]*$/;
89
+ /**
90
+ * Split a file into its frontmatter lines and everything else, agreeing with
91
+ * what `parseAgentFrontmatter` (the load side) considers a frontmatter block —
92
+ * including its BOM normalisation, which is why the fence test looks past one.
93
+ * The BOM itself stays in `lines[0]`: it belongs to the file's encoding, not to
94
+ * the block, and an edit must not strip it from the user's file.
95
+ *
96
+ * Lines keep their terminators, so an edit preserves the file's existing line
97
+ * endings instead of rewriting CRLF to LF. Returns undefined when there is no
98
+ * usable block.
99
+ */
100
+ function splitFrontmatter(content) {
101
+ const lines = content.split(/(?<=\n)/);
102
+ if (lines.length === 0)
103
+ return undefined;
104
+ // The BOM stays where it is — it belongs to the file, not the block — so the
105
+ // fence test looks past it and every index below is unaffected.
106
+ const bom = content.startsWith("\uFEFF");
107
+ const first = (bom ? lines[0].slice(1) : lines[0]).replace(/\r?\n$/, "");
108
+ if (!FENCE.test(first))
109
+ return undefined;
110
+ const closeIdx = lines.findIndex((l, i) => i > 0 && FENCE.test(l.replace(/\r?\n$/, "")));
111
+ if (closeIdx === -1)
112
+ return undefined;
113
+ return { lines, openIdx: 0, closeIdx, eol: lines[0].endsWith("\r\n") ? "\r\n" : "\n" };
114
+ }
115
+ /**
116
+ * Does the loader consider this file disabled?
117
+ *
118
+ * Detection is a READ operation, so it asks the same parser the loader uses
119
+ * rather than mirroring it with a regex — that mirror has to be right about
120
+ * YAML's boolean spellings (`False`, `FALSE`, a trailing `# comment`, a quoted
121
+ * key) *and* about pi's fence scan, which closes the block on any line starting
122
+ * `---` and so ends it early on `----`. A throw means the file is already
123
+ * unparseable, which is what the loader sees too: it skips the agent, so there
124
+ * is no "disabled" state to report.
125
+ */
126
+ export function isDisabledContent(content) {
127
+ try {
128
+ return parseAgentFrontmatter(content).frontmatter.enabled === false;
129
+ }
130
+ catch {
131
+ return false;
132
+ }
133
+ }
134
+ /**
135
+ * Add `enabled: false` to a file's frontmatter.
136
+ *
137
+ * `outcome` distinguishes a real edit from a no-op so the caller can report
138
+ * honestly instead of unconditionally claiming success.
139
+ */
140
+ export function disableInContent(content) {
141
+ const block = splitFrontmatter(content);
142
+ if (!block)
143
+ return { content, outcome: "no-frontmatter" };
144
+ if (isDisabledContent(content))
145
+ return { content, outcome: "already-disabled" };
146
+ const lines = [...block.lines];
147
+ lines.splice(1, 0, `enabled: false${block.eol}`);
148
+ return { content: lines.join(""), outcome: "disabled" };
149
+ }
150
+ /**
151
+ * Remove `enabled: false` from a file's frontmatter, wherever it appears in the
152
+ * block — the loader honors the key at any position, so the two must agree or a
153
+ * hand-authored agent can be disabled and never re-enabled.
154
+ *
155
+ * `changed` is false when the key wasn't found, so the caller can avoid
156
+ * reporting "Enabled <name>" for a write that did nothing.
157
+ */
158
+ export function enableInContent(content) {
159
+ const block = splitFrontmatter(content);
160
+ if (!block)
161
+ return { content, changed: false };
162
+ const kept = block.lines.filter((l, i) => !(i > 0 && i < block.closeIdx && ENABLED_FALSE.test(l.replace(/\r?\n$/, ""))));
163
+ if (kept.length === block.lines.length)
164
+ return { content, changed: false };
165
+ return { content: kept.join(""), changed: true };
166
+ }
167
+ /** Is this the empty stub `/agents` writes when disabling a built-in default? */
168
+ export function isEmptyStub(content) {
169
+ return content.replace(/\r\n/g, "\n").trim() === "---\n---";
170
+ }
171
+ /**
172
+ * Build the .md file the create wizard writes.
173
+ *
174
+ * `description` and `model` come straight from a free-text prompt, so they are
175
+ * quoted rather than interpolated — `serializeAgentFile` above quotes the
176
+ * description for the same reason. An unquoted YAML scalar mishandles ordinary
177
+ * input in two ways, and both are silent: a colon ("Scout: find things") makes
178
+ * the file unparseable, and since #212 an unparseable agent file is *skipped*,
179
+ * so the wizard reports success for an agent that does not exist; a `#`
180
+ * ("audit #security") opens a comment and truncates the value. `model` can
181
+ * carry a colon too — pi accepts a `provider/model:thinking` suffix.
182
+ *
183
+ * `tools` and `thinking` are not quoted: both are chosen from fixed menus, and
184
+ * `tools` is a CSV that must stay a bare scalar for the loader's parser.
185
+ */
186
+ export function buildNewAgentFile(input) {
187
+ const modelLine = input.model ? `\nmodel: ${JSON.stringify(input.model)}` : "";
188
+ const thinkingLine = input.thinking ? `\nthinking: ${input.thinking}` : "";
189
+ return `---
190
+ description: ${JSON.stringify(input.description)}
191
+ tools: ${input.tools}${modelLine}${thinkingLine}
192
+ prompt_mode: replace
193
+ ---
194
+
195
+ ${input.systemPrompt}
196
+ `;
197
+ }
198
+ /** Render a built-in tool list as a `tools:` frontmatter value. */
199
+ function formatToolsField(tools) {
200
+ if (tools === undefined)
201
+ return "all";
202
+ if (tools.length === 0)
203
+ return "none";
204
+ return tools.join(", ");
205
+ }
206
+ /** Serialize an AgentConfig to a full .md file (frontmatter + system prompt) for eject. */
207
+ export function serializeAgentFile(cfg) {
208
+ const fmFields = [];
209
+ fmFields.push(`description: ${JSON.stringify(cfg.description)}`);
210
+ if (cfg.displayName)
211
+ fmFields.push(`display_name: ${cfg.displayName}`);
212
+ if (cfg.color)
213
+ fmFields.push(`color: ${JSON.stringify(cfg.color)}`);
214
+ // Absent means "all built-ins"; an EMPTY list means explicitly zero. Writing
215
+ // `all` for both would hand a deliberately tool-less agent the whole toolbox
216
+ // the first time it is ejected.
217
+ fmFields.push(`tools: ${formatToolsField(cfg.builtinToolNames)}`);
218
+ if (cfg.model)
219
+ fmFields.push(`model: ${cfg.model}`);
220
+ if (cfg.fallbackModel !== undefined)
221
+ fmFields.push(`fallback_model: ${JSON.stringify(cfg.fallbackModel)}`);
222
+ if (cfg.thinking)
223
+ fmFields.push(`thinking: ${cfg.thinking}`);
224
+ if (cfg.maxTurns)
225
+ fmFields.push(`max_turns: ${cfg.maxTurns}`);
226
+ if (cfg.allowedSubagents !== undefined) {
227
+ fmFields.push(`allowed_subagents: ${cfg.allowedSubagents === "all" ? "all" : cfg.allowedSubagents.join(", ")}`);
228
+ }
229
+ fmFields.push(`prompt_mode: ${cfg.promptMode}`);
230
+ if (cfg.extensions === false)
231
+ fmFields.push("extensions: false");
232
+ else if (Array.isArray(cfg.extensions))
233
+ fmFields.push(`extensions: ${cfg.extensions.join(", ")}`);
234
+ if (cfg.excludeExtensions?.length)
235
+ fmFields.push(`exclude_extensions: ${cfg.excludeExtensions.join(", ")}`);
236
+ if (cfg.skills === false)
237
+ fmFields.push("skills: false");
238
+ else if (Array.isArray(cfg.skills))
239
+ fmFields.push(`skills: ${cfg.skills.join(", ")}`);
240
+ if (cfg.disallowedTools?.length)
241
+ fmFields.push(`disallowed_tools: ${cfg.disallowedTools.join(", ")}`);
242
+ if (cfg.inheritContext)
243
+ fmFields.push("inherit_context: true");
244
+ // Both cases, not just `true`: with `backgroundByDefault` on, omitting the
245
+ // field means background, so `false` is the only way to pin an agent file to
246
+ // foreground and is no longer interchangeable with absence. No caller can
247
+ // reach it yet — Eject only handles built-in defaults, which omit the field —
248
+ // so this keeps the writer symmetric with the loader, nothing more.
249
+ if (cfg.runInBackground !== undefined)
250
+ fmFields.push(`run_in_background: ${cfg.runInBackground}`);
251
+ if (cfg.outputTranscript === false)
252
+ fmFields.push("output_transcript: false");
253
+ if (cfg.isolated)
254
+ fmFields.push("isolated: true");
255
+ if (cfg.memory)
256
+ fmFields.push(`memory: ${cfg.memory}`);
257
+ if (cfg.isolation)
258
+ fmFields.push(`isolation: ${cfg.isolation}`);
259
+ // Both cases serialize: absence defers to pi-advisor's own default, so
260
+ // `advisor: false` and `advisor: true` are each load-bearing on reload.
261
+ if (cfg.advisor !== undefined)
262
+ fmFields.push(`advisor: ${cfg.advisor}`);
263
+ return `---\n${fmFields.join("\n")}\n---\n\n${cfg.systemPrompt}\n`;
264
+ }