@esso0428/pi-subagents 0.17.6 → 0.17.8

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 (260) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/CONTRIBUTING.md +4 -0
  3. package/dist/abortable.d.ts +13 -0
  4. package/dist/abortable.d.ts.map +1 -0
  5. package/dist/abortable.js +43 -0
  6. package/dist/abortable.js.map +1 -0
  7. package/dist/agent-color.d.ts +36 -0
  8. package/dist/agent-color.d.ts.map +1 -0
  9. package/dist/agent-color.js +124 -0
  10. package/dist/agent-color.js.map +1 -0
  11. package/dist/agent-file-toggle.d.ts +126 -0
  12. package/dist/agent-file-toggle.d.ts.map +1 -0
  13. package/dist/agent-file-toggle.js +259 -0
  14. package/dist/agent-file-toggle.js.map +1 -0
  15. package/dist/agent-history.d.ts +4 -0
  16. package/dist/agent-history.d.ts.map +1 -1
  17. package/dist/agent-history.js +47 -1
  18. package/dist/agent-history.js.map +1 -1
  19. package/dist/agent-manager.d.ts +370 -56
  20. package/dist/agent-manager.d.ts.map +1 -1
  21. package/dist/agent-manager.js +1123 -409
  22. package/dist/agent-manager.js.map +1 -1
  23. package/dist/agent-runner.d.ts +100 -10
  24. package/dist/agent-runner.d.ts.map +1 -1
  25. package/dist/agent-runner.js +166 -21
  26. package/dist/agent-runner.js.map +1 -1
  27. package/dist/agent-types.d.ts +57 -5
  28. package/dist/agent-types.d.ts.map +1 -1
  29. package/dist/agent-types.js +164 -32
  30. package/dist/agent-types.js.map +1 -1
  31. package/dist/child-context.d.ts +3 -0
  32. package/dist/child-context.d.ts.map +1 -0
  33. package/dist/child-context.js +13 -0
  34. package/dist/child-context.js.map +1 -0
  35. package/dist/cross-extension-rpc.d.ts +23 -3
  36. package/dist/cross-extension-rpc.d.ts.map +1 -1
  37. package/dist/cross-extension-rpc.js +79 -17
  38. package/dist/cross-extension-rpc.js.map +1 -1
  39. package/dist/custom-agents.d.ts +38 -1
  40. package/dist/custom-agents.d.ts.map +1 -1
  41. package/dist/custom-agents.js +164 -12
  42. package/dist/custom-agents.js.map +1 -1
  43. package/dist/index.d.ts +34 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +1912 -492
  46. package/dist/index.js.map +1 -1
  47. package/dist/invocation-config.d.ts +87 -2
  48. package/dist/invocation-config.d.ts.map +1 -1
  49. package/dist/invocation-config.js +71 -3
  50. package/dist/invocation-config.js.map +1 -1
  51. package/dist/mention-clone.d.ts +88 -0
  52. package/dist/mention-clone.d.ts.map +1 -0
  53. package/dist/mention-clone.js +154 -0
  54. package/dist/mention-clone.js.map +1 -0
  55. package/dist/mention.d.ts +82 -0
  56. package/dist/mention.d.ts.map +1 -0
  57. package/dist/mention.js +132 -0
  58. package/dist/mention.js.map +1 -0
  59. package/dist/model-resolver.d.ts +17 -0
  60. package/dist/model-resolver.d.ts.map +1 -1
  61. package/dist/model-resolver.js +15 -0
  62. package/dist/model-resolver.js.map +1 -1
  63. package/dist/model-scope.d.ts +50 -0
  64. package/dist/model-scope.d.ts.map +1 -0
  65. package/dist/model-scope.js +49 -0
  66. package/dist/model-scope.js.map +1 -0
  67. package/dist/nested-tools.d.ts +57 -0
  68. package/dist/nested-tools.d.ts.map +1 -0
  69. package/dist/nested-tools.js +301 -0
  70. package/dist/nested-tools.js.map +1 -0
  71. package/dist/output-file.d.ts +22 -3
  72. package/dist/output-file.d.ts.map +1 -1
  73. package/dist/output-file.js +58 -7
  74. package/dist/output-file.js.map +1 -1
  75. package/dist/prompts.d.ts +23 -0
  76. package/dist/prompts.d.ts.map +1 -1
  77. package/dist/prompts.js +20 -2
  78. package/dist/prompts.js.map +1 -1
  79. package/dist/schedule.d.ts.map +1 -1
  80. package/dist/schedule.js +36 -15
  81. package/dist/schedule.js.map +1 -1
  82. package/dist/settings.d.ts +228 -2
  83. package/dist/settings.d.ts.map +1 -1
  84. package/dist/settings.js +94 -0
  85. package/dist/settings.js.map +1 -1
  86. package/dist/status-note.d.ts +49 -1
  87. package/dist/status-note.d.ts.map +1 -1
  88. package/dist/status-note.js +62 -1
  89. package/dist/status-note.js.map +1 -1
  90. package/dist/structured-output.d.ts +62 -0
  91. package/dist/structured-output.d.ts.map +1 -0
  92. package/dist/structured-output.js +113 -0
  93. package/dist/structured-output.js.map +1 -0
  94. package/dist/types.d.ts +176 -10
  95. package/dist/types.d.ts.map +1 -1
  96. package/dist/ui/agent-mention.d.ts +83 -0
  97. package/dist/ui/agent-mention.d.ts.map +1 -0
  98. package/dist/ui/agent-mention.js +188 -0
  99. package/dist/ui/agent-mention.js.map +1 -0
  100. package/dist/ui/agent-widget.d.ts +97 -75
  101. package/dist/ui/agent-widget.d.ts.map +1 -1
  102. package/dist/ui/agent-widget.js +398 -420
  103. package/dist/ui/agent-widget.js.map +1 -1
  104. package/dist/ui/conversation-blocks.d.ts.map +1 -1
  105. package/dist/ui/conversation-blocks.js +6 -0
  106. package/dist/ui/conversation-blocks.js.map +1 -1
  107. package/dist/ui/conversation-timeline.d.ts +10 -2
  108. package/dist/ui/conversation-timeline.d.ts.map +1 -1
  109. package/dist/ui/conversation-timeline.js +130 -23
  110. package/dist/ui/conversation-timeline.js.map +1 -1
  111. package/dist/ui/conversation-viewer.d.ts +15 -5
  112. package/dist/ui/conversation-viewer.d.ts.map +1 -1
  113. package/dist/ui/conversation-viewer.js +202 -50
  114. package/dist/ui/conversation-viewer.js.map +1 -1
  115. package/dist/ui/fleet-list.d.ts +198 -0
  116. package/dist/ui/fleet-list.d.ts.map +1 -0
  117. package/dist/ui/fleet-list.js +487 -0
  118. package/dist/ui/fleet-list.js.map +1 -0
  119. package/dist/ui/schedule-menu.d.ts.map +1 -1
  120. package/dist/ui/schedule-menu.js +6 -7
  121. package/dist/ui/schedule-menu.js.map +1 -1
  122. package/dist/ui/select-item.d.ts +28 -0
  123. package/dist/ui/select-item.d.ts.map +1 -0
  124. package/dist/ui/select-item.js +35 -0
  125. package/dist/ui/select-item.js.map +1 -0
  126. package/dist/ui/workflow-card.d.ts +176 -0
  127. package/dist/ui/workflow-card.d.ts.map +1 -0
  128. package/dist/ui/workflow-card.js +333 -0
  129. package/dist/ui/workflow-card.js.map +1 -0
  130. package/dist/ui/workflow-dialog.d.ts +306 -0
  131. package/dist/ui/workflow-dialog.d.ts.map +1 -0
  132. package/dist/ui/workflow-dialog.js +844 -0
  133. package/dist/ui/workflow-dialog.js.map +1 -0
  134. package/dist/ui/workflow-menu.d.ts +61 -0
  135. package/dist/ui/workflow-menu.d.ts.map +1 -0
  136. package/dist/ui/workflow-menu.js +148 -0
  137. package/dist/ui/workflow-menu.js.map +1 -0
  138. package/dist/usage.d.ts +86 -1
  139. package/dist/usage.d.ts.map +1 -1
  140. package/dist/usage.js +72 -1
  141. package/dist/usage.js.map +1 -1
  142. package/dist/workflow/collisions.d.ts +96 -0
  143. package/dist/workflow/collisions.d.ts.map +1 -0
  144. package/dist/workflow/collisions.js +89 -0
  145. package/dist/workflow/collisions.js.map +1 -0
  146. package/dist/workflow/entry.d.ts +33 -0
  147. package/dist/workflow/entry.d.ts.map +1 -0
  148. package/dist/workflow/entry.js +30 -0
  149. package/dist/workflow/entry.js.map +1 -0
  150. package/dist/workflow/host.d.ts +63 -0
  151. package/dist/workflow/host.d.ts.map +1 -0
  152. package/dist/workflow/host.js +363 -0
  153. package/dist/workflow/host.js.map +1 -0
  154. package/dist/workflow/journal.d.ts +98 -0
  155. package/dist/workflow/journal.d.ts.map +1 -0
  156. package/dist/workflow/journal.js +121 -0
  157. package/dist/workflow/journal.js.map +1 -0
  158. package/dist/workflow/json-schema.d.ts +52 -0
  159. package/dist/workflow/json-schema.d.ts.map +1 -0
  160. package/dist/workflow/json-schema.js +112 -0
  161. package/dist/workflow/json-schema.js.map +1 -0
  162. package/dist/workflow/meta.d.ts +68 -0
  163. package/dist/workflow/meta.d.ts.map +1 -0
  164. package/dist/workflow/meta.js +318 -0
  165. package/dist/workflow/meta.js.map +1 -0
  166. package/dist/workflow/progress.d.ts +225 -0
  167. package/dist/workflow/progress.d.ts.map +1 -0
  168. package/dist/workflow/progress.js +362 -0
  169. package/dist/workflow/progress.js.map +1 -0
  170. package/dist/workflow/runtime.d.ts +335 -0
  171. package/dist/workflow/runtime.d.ts.map +1 -0
  172. package/dist/workflow/runtime.js +831 -0
  173. package/dist/workflow/runtime.js.map +1 -0
  174. package/dist/workflow/saved.d.ts +91 -0
  175. package/dist/workflow/saved.d.ts.map +1 -0
  176. package/dist/workflow/saved.js +204 -0
  177. package/dist/workflow/saved.js.map +1 -0
  178. package/dist/workflow/task.d.ts +137 -0
  179. package/dist/workflow/task.d.ts.map +1 -0
  180. package/dist/workflow/task.js +208 -0
  181. package/dist/workflow/task.js.map +1 -0
  182. package/dist/workflow/tool-description.d.ts +39 -0
  183. package/dist/workflow/tool-description.d.ts.map +1 -0
  184. package/dist/workflow/tool-description.js +200 -0
  185. package/dist/workflow/tool-description.js.map +1 -0
  186. package/dist/workflow/worker-source.d.ts +48 -0
  187. package/dist/workflow/worker-source.d.ts.map +1 -0
  188. package/dist/workflow/worker-source.js +779 -0
  189. package/dist/workflow/worker-source.js.map +1 -0
  190. package/dist/worktree.d.ts +10 -3
  191. package/dist/worktree.d.ts.map +1 -1
  192. package/dist/worktree.js +58 -54
  193. package/dist/worktree.js.map +1 -1
  194. package/dist/xml.d.ts +11 -0
  195. package/dist/xml.d.ts.map +1 -0
  196. package/dist/xml.js +13 -0
  197. package/dist/xml.js.map +1 -0
  198. package/docs/rpc.md +183 -0
  199. package/docs/superpowers/plans/2026-09-30-upstream-event-workflow-partial-history.md +195 -0
  200. package/docs/superpowers/specs/2026-09-30-upstream-event-workflow-partial-history-design.md +49 -0
  201. package/docs/workflows.md +437 -0
  202. package/examples/agent-tool-description.md +7 -7
  203. package/examples/workflows/compose.js +51 -0
  204. package/examples/workflows/fan-out-audit.js +47 -0
  205. package/examples/workflows/gated-fix.js +60 -0
  206. package/examples/workflows/lib/count-child.js +27 -0
  207. package/examples/workflows/review-panel.js +63 -0
  208. package/examples/workflows/structured-findings.js +78 -0
  209. package/package.json +1 -1
  210. package/src/abortable.ts +43 -0
  211. package/src/agent-color.ts +161 -0
  212. package/src/agent-file-toggle.ts +269 -0
  213. package/src/agent-history.ts +54 -2
  214. package/src/agent-manager.ts +1263 -402
  215. package/src/agent-runner.ts +251 -27
  216. package/src/agent-types.ts +188 -32
  217. package/src/child-context.ts +15 -0
  218. package/src/cross-extension-rpc.ts +96 -20
  219. package/src/custom-agents.ts +170 -13
  220. package/src/index.ts +2029 -536
  221. package/src/invocation-config.ts +118 -3
  222. package/src/mention-clone.ts +196 -0
  223. package/src/mention.ts +141 -0
  224. package/src/model-resolver.ts +18 -0
  225. package/src/model-scope.ts +70 -0
  226. package/src/nested-tools.ts +424 -0
  227. package/src/output-file.ts +61 -6
  228. package/src/prompts.ts +45 -2
  229. package/src/schedule.ts +35 -14
  230. package/src/settings.ts +312 -2
  231. package/src/status-note.ts +66 -1
  232. package/src/structured-output.ts +130 -0
  233. package/src/types.ts +177 -10
  234. package/src/ui/agent-mention.ts +216 -0
  235. package/src/ui/agent-widget.ts +393 -441
  236. package/src/ui/conversation-blocks.ts +6 -0
  237. package/src/ui/conversation-timeline.ts +139 -25
  238. package/src/ui/conversation-viewer.ts +212 -48
  239. package/src/ui/fleet-list.ts +558 -0
  240. package/src/ui/schedule-menu.ts +9 -8
  241. package/src/ui/select-item.ts +45 -0
  242. package/src/ui/workflow-card.ts +470 -0
  243. package/src/ui/workflow-dialog.ts +1115 -0
  244. package/src/ui/workflow-menu.ts +193 -0
  245. package/src/usage.ts +109 -2
  246. package/src/workflow/collisions.ts +123 -0
  247. package/src/workflow/entry.ts +47 -0
  248. package/src/workflow/host.ts +403 -0
  249. package/src/workflow/journal.ts +164 -0
  250. package/src/workflow/json-schema.ts +128 -0
  251. package/src/workflow/meta.ts +325 -0
  252. package/src/workflow/progress.ts +550 -0
  253. package/src/workflow/runtime.ts +1219 -0
  254. package/src/workflow/saved.ts +217 -0
  255. package/src/workflow/task.ts +302 -0
  256. package/src/workflow/tool-description.ts +200 -0
  257. package/src/workflow/worker-source.ts +781 -0
  258. package/src/worktree.ts +69 -55
  259. package/src/xml.ts +13 -0
  260. package/vitest.config.ts +0 -18
@@ -0,0 +1,27 @@
1
+ /**
2
+ * lib/count-child.js — a nested workflow, invoked by compose.js.
3
+ *
4
+ * A child is an ordinary workflow: it needs its own `export const meta =`
5
+ * declaration, which is exactly what marks a file in a workflows directory as
6
+ * runnable rather than as some unrelated script that happens to live there.
7
+ *
8
+ * args: { root?: string }
9
+ */
10
+ export const meta = {
11
+ name: 'count-child',
12
+ description: 'Count the source files under a directory',
13
+ }
14
+
15
+ const root = args?.root ?? 'src/'
16
+
17
+ const found = await agent(`List every source file under ${root}. One path per line, nothing else.`, {
18
+ label: 'scan',
19
+ schema: {
20
+ type: 'object',
21
+ properties: { files: { type: 'array', items: { type: 'string' } } },
22
+ required: ['files'],
23
+ },
24
+ })
25
+
26
+ // A schema call can still return null if the child never complied.
27
+ return found === null ? 0 : found.files.length
@@ -0,0 +1,63 @@
1
+ /**
2
+ * review-panel.js — the case where a barrier is actually earned.
3
+ *
4
+ * Demonstrates: `parallel` used correctly, `effort` tiering (cheap reviewers,
5
+ * an expensive judge), and a `model` override.
6
+ *
7
+ * Most of the time `pipeline` beats `parallel`, because a barrier idles every
8
+ * fast agent until the slowest finishes. This is the exception: the synthesis
9
+ * prompt interpolates ALL of the reviews, so it genuinely cannot start until
10
+ * every one of them is in. That — a prompt that compares results against each
11
+ * other — is what justifies a barrier.
12
+ *
13
+ * args: { target?: string, lenses?: string[] }
14
+ *
15
+ * Run: ask the model — "run the workflow at examples/workflows/review-panel.js
16
+ * against src/auth.ts".
17
+ */
18
+ export const meta = {
19
+ name: 'review-panel',
20
+ description: 'Review one thing from several angles, then reconcile the verdicts',
21
+ phases: [{ title: 'Review' }, { title: 'Synthesize' }],
22
+ }
23
+
24
+ const target = args?.target ?? 'the changed files'
25
+ const lenses = args?.lenses ?? ['correctness', 'security', 'performance']
26
+
27
+ phase('Review')
28
+
29
+ // Perspective diversity, not redundancy: three reviewers with DIFFERENT briefs
30
+ // catch failure modes that three identical ones cannot.
31
+ const reviews = await parallel(
32
+ lenses.map(lens => () =>
33
+ agent(`Review ${target} through the lens of ${lens} alone. Be specific and brief.`, {
34
+ label: `review:${lens}`,
35
+ // Cheap for the survey work; the judge below gets the depth.
36
+ effort: 'low',
37
+ }),
38
+ ),
39
+ )
40
+
41
+ // A thunk that throws becomes null without taking its siblings down.
42
+ const usable = reviews
43
+ .map((text, i) => ({ lens: lenses[i], text }))
44
+ .filter(r => r.text !== null)
45
+
46
+ if (usable.length === 0) {
47
+ log('every reviewer failed — nothing to synthesize')
48
+ return { reviewed: 0, verdict: null }
49
+ }
50
+
51
+ phase('Synthesize')
52
+
53
+ // This is the barrier's payoff: one prompt that sees all of them at once and can
54
+ // weigh them against each other.
55
+ const verdict = await agent(
56
+ [
57
+ `Reconcile these reviews of ${target}. Where they disagree, say which is right and why.`,
58
+ ...usable.map(r => `\n## ${r.lens}\n${r.text}`),
59
+ ].join('\n'),
60
+ { label: 'synthesize', effort: 'high', agentType: 'Plan' },
61
+ )
62
+
63
+ return { reviewed: usable.length, verdict }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * structured-findings.js — get objects back, not prose.
3
+ *
4
+ * Demonstrates: `schema` on every agent call, so the script manipulates
5
+ * validated objects instead of parsing text it hopes is well-formed.
6
+ *
7
+ * Reach for this whenever the script has to *do* something with the results —
8
+ * sort, count, filter, compare — rather than hand them straight to you.
9
+ *
10
+ * args: { dimensions?: string[] } — review angles, default bugs + perf
11
+ *
12
+ * Run: ask the model — "run the workflow at
13
+ * examples/workflows/structured-findings.js".
14
+ */
15
+ export const meta = {
16
+ name: 'structured-findings',
17
+ description: 'Review changed files across dimensions and verify each finding',
18
+ phases: [{ title: 'Review' }, { title: 'Verify' }],
19
+ }
20
+
21
+ const FINDINGS = {
22
+ type: 'object',
23
+ properties: {
24
+ findings: {
25
+ type: 'array',
26
+ items: {
27
+ type: 'object',
28
+ properties: {
29
+ title: { type: 'string' },
30
+ file: { type: 'string' },
31
+ severity: { type: 'string' },
32
+ },
33
+ required: ['title', 'file'],
34
+ },
35
+ },
36
+ },
37
+ required: ['findings'],
38
+ }
39
+
40
+ const VERDICT = {
41
+ type: 'object',
42
+ properties: { isReal: { type: 'boolean' }, why: { type: 'string' } },
43
+ required: ['isReal'],
44
+ }
45
+
46
+ const dimensions = args?.dimensions ?? ['bugs', 'performance']
47
+
48
+ const reviewed = await pipeline(
49
+ dimensions,
50
+ dim => agent(`Review the changed files for ${dim}. Report every finding.`, {
51
+ label: `review:${dim}`,
52
+ phase: 'Review',
53
+ // With a schema the call resolves to the validated object, so `.findings`
54
+ // below is a real array rather than something scraped out of prose.
55
+ schema: FINDINGS,
56
+ }),
57
+ // A barrier is earned here only per-dimension: each dimension's findings are
58
+ // verified concurrently, but dimensions never wait for each other.
59
+ review => parallel(
60
+ review.findings.map(f => () =>
61
+ agent(`Try to REFUTE this finding: ${f.title} (${f.file})`, {
62
+ label: `verify:${f.file}`,
63
+ phase: 'Verify',
64
+ schema: VERDICT,
65
+ }).then(verdict => ({ ...f, verdict })),
66
+ ),
67
+ ),
68
+ )
69
+
70
+ // filter(Boolean) twice: once for a whole dimension that failed, once for an
71
+ // individual verification that did. A schema call can still return null.
72
+ const confirmed = reviewed
73
+ .filter(Boolean)
74
+ .flat()
75
+ .filter(Boolean)
76
+ .filter(f => f.verdict?.isReal)
77
+
78
+ return { confirmed: confirmed.length, findings: confirmed }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@esso0428/pi-subagents",
3
- "version": "0.17.6",
3
+ "version": "0.17.8",
4
4
  "description": "A pi extension that brings smart Claude Code-style autonomous sub-agents to pi, with npm:pi-subagents-style JSON agent overrides.",
5
5
  "author": "ESSO0428",
6
6
  "repository": {
@@ -0,0 +1,43 @@
1
+ /**
2
+ * abortable.ts — race a promise against an AbortSignal without cancelling the
3
+ * underlying work.
4
+ *
5
+ * Used by the `get_subagent_result` wait paths (top-level and nested): pressing
6
+ * Esc cancels only the caller's wait; the background child keeps running and its
7
+ * result stays unconsumed. The listener is removed on every settle path so the
8
+ * signal accumulates no handlers, and a late settlement of the wrapped promise
9
+ * after an abort is absorbed as a no-op (no unhandled rejection).
10
+ */
11
+
12
+ /** Await a promise until it settles or the caller cancels, without aborting the underlying work. */
13
+ export function abortable<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
14
+ if (!signal) return promise;
15
+ if (signal.aborted) return Promise.reject(signal.reason);
16
+
17
+ return new Promise<T>((resolve, reject) => {
18
+ let settled = false;
19
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
20
+ const onAbort = () => {
21
+ if (settled) return;
22
+ settled = true;
23
+ cleanup();
24
+ reject(signal.reason);
25
+ };
26
+
27
+ signal.addEventListener("abort", onAbort, { once: true });
28
+ promise.then(
29
+ (value) => {
30
+ if (settled) return;
31
+ settled = true;
32
+ cleanup();
33
+ resolve(value);
34
+ },
35
+ (error: unknown) => {
36
+ if (settled) return;
37
+ settled = true;
38
+ cleanup();
39
+ reject(error);
40
+ },
41
+ );
42
+ });
43
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * agent-color.ts — Claude Code-compatible agent name badges.
3
+ *
4
+ * Claude Code renders a subagent's name as a badge: the configured color is the
5
+ * background, the text an inverse foreground. Its eight named colors are
6
+ * reproduced here, along with six-digit hex and the extra palette names Agency
7
+ * Agents uses, so those definitions render as written.
8
+ */
9
+
10
+ import { getConfig } from "./agent-types.js";
11
+
12
+ const NAMED_AGENT_COLORS: Readonly<Record<string, string>> = {
13
+ // Claude Code's eight subagent colors, as its default theme renders them.
14
+ red: "#DC2626",
15
+ blue: "#6A9BCC",
16
+ green: "#16A34A",
17
+ yellow: "#CA8A04",
18
+ purple: "#827DBD",
19
+ orange: "#D97757",
20
+ pink: "#C46686",
21
+ cyan: "#0891B2",
22
+ // Agency Agents palette aliases.
23
+ amber: "#F59E0B",
24
+ teal: "#008080",
25
+ indigo: "#6366F1",
26
+ gold: "#EAB308",
27
+ "neon-green": "#10B981",
28
+ "neon-cyan": "#06B6D4",
29
+ "metallic-blue": "#3B82F6",
30
+ violet: "#8B5CF6",
31
+ rose: "#F43F5E",
32
+ lime: "#84CC16",
33
+ gray: "#6B7280",
34
+ grey: "#6B7280",
35
+ fuchsia: "#D946EF",
36
+ slate: "#64748B",
37
+ navy: "#1E3A8A",
38
+ };
39
+
40
+ const CUBE_VALUES = [0, 95, 135, 175, 215, 255];
41
+ const GRAY_VALUES = Array.from({ length: 24 }, (_, i) => 8 + i * 10);
42
+ const BLACK = { r: 0, g: 0, b: 0 };
43
+ const WHITE = { r: 255, g: 255, b: 255 };
44
+
45
+ type Rgb = { r: number; g: number; b: number };
46
+ type ColorMode = "truecolor" | "256color";
47
+
48
+ export interface AgentNameTheme {
49
+ fg(color: string, text: string): string;
50
+ bold(text: string): string;
51
+ getColorMode?(): ColorMode;
52
+ }
53
+
54
+ export interface AgentNameStyle {
55
+ /** Existing theme foreground used when no valid agent color is configured. */
56
+ fallbackColor?: string;
57
+ /** Reapply an enclosing background after the badge instead of resetting it. */
58
+ restoreBackground?: string;
59
+ bold?: boolean;
60
+ }
61
+
62
+ /** Resolve Claude Code/Agency Agents color syntax to normalized #RRGGBB. */
63
+ export function resolveAgentColor(value: string | undefined): string | undefined {
64
+ if (!value) return undefined;
65
+ const normalized = value.trim().toLowerCase();
66
+ const resolved = NAMED_AGENT_COLORS[normalized] ?? normalized;
67
+ return /^#[0-9a-f]{6}$/i.test(resolved) ? resolved.toUpperCase() : undefined;
68
+ }
69
+
70
+ function parseHex(hex: string): Rgb {
71
+ return {
72
+ r: Number.parseInt(hex.slice(1, 3), 16),
73
+ g: Number.parseInt(hex.slice(3, 5), 16),
74
+ b: Number.parseInt(hex.slice(5, 7), 16),
75
+ };
76
+ }
77
+
78
+ /** Index of the entry in `values` closest to `value`. */
79
+ function nearest(values: readonly number[], value: number): number {
80
+ return values.reduce((best, v, i) => (Math.abs(value - v) < Math.abs(value - values[best]) ? i : best), 0);
81
+ }
82
+
83
+ /**
84
+ * Quantize to the xterm-256 palette the way pi's own theme does, returning both
85
+ * the index to emit and the color the terminal will actually show — badge
86
+ * contrast is judged against the latter.
87
+ */
88
+ function rgbTo256({ r, g, b }: Rgb): { index: number; rgb: Rgb } {
89
+ const [rIndex, gIndex, bIndex] = [r, g, b].map((channel) => nearest(CUBE_VALUES, channel));
90
+ const distance = ({ r: cr, g: cg, b: cb }: Rgb) => 0.299 * (r - cr) ** 2 + 0.587 * (g - cg) ** 2 + 0.114 * (b - cb) ** 2;
91
+ const grayIndex = nearest(GRAY_VALUES, Math.round(0.299 * r + 0.587 * g + 0.114 * b));
92
+ const gray = { r: GRAY_VALUES[grayIndex], g: GRAY_VALUES[grayIndex], b: GRAY_VALUES[grayIndex] };
93
+ const cube = { r: CUBE_VALUES[rIndex], g: CUBE_VALUES[gIndex], b: CUBE_VALUES[bIndex] };
94
+ // Only near-neutral colors may take the gray ramp; anything else keeps its tint.
95
+ if (Math.max(r, g, b) - Math.min(r, g, b) < 10 && distance(gray) < distance(cube)) {
96
+ return { index: 232 + grayIndex, rgb: gray };
97
+ }
98
+ return { index: 16 + 36 * rIndex + 6 * gIndex + bIndex, rgb: cube };
99
+ }
100
+
101
+ function ansiColor(layer: "foreground" | "background", color: Rgb | number): string {
102
+ const code = layer === "foreground" ? 38 : 48;
103
+ return typeof color === "number"
104
+ ? `\u001b[${code};5;${color}m`
105
+ : `\u001b[${code};2;${color.r};${color.g};${color.b}m`;
106
+ }
107
+
108
+ function relativeLuminance({ r, g, b }: Rgb): number {
109
+ const linear = (value: number) => {
110
+ const channel = value / 255;
111
+ return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
112
+ };
113
+ return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
114
+ }
115
+
116
+ /**
117
+ * Render one name as a padded background badge when `color` is valid. Claude
118
+ * Code uses one inverse color for every badge's text; black or white is picked
119
+ * by WCAG contrast here instead, so each palette entry stays readable. Invalid
120
+ * or omitted colors preserve the caller's existing theme styling.
121
+ */
122
+ export function renderAgentNameLabel(
123
+ name: string,
124
+ color: string | undefined,
125
+ theme: AgentNameTheme,
126
+ style: AgentNameStyle = {},
127
+ ): string {
128
+ const resolved = resolveAgentColor(color);
129
+ if (!resolved) {
130
+ const text = style.bold ? theme.bold(name) : name;
131
+ return style.fallbackColor ? theme.fg(style.fallbackColor, text) : text;
132
+ }
133
+
134
+ const rgb = parseHex(resolved);
135
+ const quantized = (theme.getColorMode?.() ?? "truecolor") === "256color" ? rgbTo256(rgb) : undefined;
136
+ const shown = quantized?.rgb ?? rgb;
137
+ const contrasting = relativeLuminance(shown) > 0.179 ? BLACK : WHITE;
138
+ const label = style.bold ? theme.bold(` ${name} `) : ` ${name} `;
139
+
140
+ return ansiColor("background", quantized?.index ?? rgb)
141
+ + ansiColor("foreground", quantized ? rgbTo256(contrasting).index : contrasting)
142
+ + label
143
+ + "\u001b[39m"
144
+ + (style.restoreBackground ?? "\u001b[49m");
145
+ }
146
+
147
+ /** Whether an agent renders as a badge — i.e. it has a valid configured color. */
148
+ export function hasAgentBadge(type: string | undefined): boolean {
149
+ return type !== undefined && resolveAgentColor(getConfig(type).color) !== undefined;
150
+ }
151
+
152
+ /** Render a registered agent's display name with its configured color. */
153
+ export function renderAgentName(
154
+ type: string | undefined,
155
+ theme: AgentNameTheme,
156
+ style: AgentNameStyle = {},
157
+ ): string {
158
+ if (!type) return renderAgentNameLabel("Agent", undefined, theme, style);
159
+ const config = getConfig(type);
160
+ return renderAgentNameLabel(config.displayName, config.color, theme, style);
161
+ }
@@ -0,0 +1,269 @@
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
+
28
+ import { existsSync } from "node:fs";
29
+ import { join, sep } from "node:path";
30
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
31
+ import { parseAgentFrontmatter } from "./custom-agents.js";
32
+ import type { AgentConfig } from "./types.js";
33
+
34
+ export type AgentFileLocation = "project" | "workspace" | "personal";
35
+
36
+ export const projectAgentsDir = (cwd: string = process.cwd()) => join(cwd, ".pi", "agents");
37
+ export const workspaceAgentsDir = (cwd: string = process.cwd()) => join(cwd, ".agents", "agents");
38
+ export const personalAgentsDir = () => join(getAgentDir(), "agents");
39
+
40
+ /**
41
+ * Find the file path of a custom agent by name, in discovery-precedence order
42
+ * (project, workspace, then global). Mirrors the load-side precedence in
43
+ * src/custom-agents.ts — if the two drift, `/agents` edits a file the loader
44
+ * isn't reading.
45
+ */
46
+ export function findAgentFile(
47
+ name: string,
48
+ cwd: string = process.cwd(),
49
+ ): { path: string; location: AgentFileLocation } | undefined {
50
+ const projectPath = join(projectAgentsDir(cwd), `${name}.md`);
51
+ if (existsSync(projectPath)) return { path: projectPath, location: "project" };
52
+ const workspacePath = join(workspaceAgentsDir(cwd), `${name}.md`);
53
+ if (existsSync(workspacePath)) return { path: workspacePath, location: "workspace" };
54
+ const personalPath = join(personalAgentsDir(), `${name}.md`);
55
+ if (existsSync(personalPath)) return { path: personalPath, location: "personal" };
56
+ return undefined;
57
+ }
58
+
59
+ /**
60
+ * Find the file behind a *loaded* agent, preferring the path the loader
61
+ * actually read (`AgentConfig.sourcePath`) over the `<type>.md` guess.
62
+ *
63
+ * An agent's type comes from its frontmatter `name:` now, so the two can
64
+ * disagree: `reviewer.md` declaring `name: code-reviewer` is loaded as
65
+ * `code-reviewer`, and probing for `code-reviewer.md` finds nothing. That is
66
+ * not a harmless miss — `/agents → Disable` would then take the no-file branch
67
+ * and write a NEW `code-reviewer.md` stub, which loses to `reviewer.md` on
68
+ * load, leaving the agent enabled while reporting success.
69
+ *
70
+ * The probe stays as the fallback: a built-in that was never ejected has no
71
+ * `sourcePath`, and a path can go stale between a load and this call.
72
+ */
73
+ export function locateAgentFile(
74
+ name: string,
75
+ sourcePath: string | undefined,
76
+ cwd: string = process.cwd(),
77
+ ): { path: string; location: AgentFileLocation } | undefined {
78
+ if (sourcePath && existsSync(sourcePath)) {
79
+ return { path: sourcePath, location: classifyAgentDir(sourcePath, cwd) };
80
+ }
81
+ return findAgentFile(name, cwd);
82
+ }
83
+
84
+ /**
85
+ * Which discovery location a loaded agent's file came from. Only ever names
86
+ * a directory in a confirmation prompt, so an unrecognized parent — which
87
+ * loadCustomAgents cannot currently produce — reports as personal rather than
88
+ * widening the type for a case that has no better answer.
89
+ */
90
+ function classifyAgentDir(path: string, cwd: string): AgentFileLocation {
91
+ if (path.startsWith(projectAgentsDir(cwd) + sep)) return "project";
92
+ if (path.startsWith(workspaceAgentsDir(cwd) + sep)) return "workspace";
93
+ return "personal";
94
+ }
95
+
96
+ export type DisableOutcome = "disabled" | "already-disabled" | "no-frontmatter";
97
+
98
+ /** A line that sets `enabled: false`, ignoring trailing whitespace / CR. */
99
+ const ENABLED_FALSE = /^enabled:[ \t]*false[ \t]*$/;
100
+ /** An opening or closing `---` fence line. */
101
+ const FENCE = /^---[ \t]*$/;
102
+
103
+ /**
104
+ * Split a file into its frontmatter lines and everything else, agreeing with
105
+ * what `parseAgentFrontmatter` (the load side) considers a frontmatter block —
106
+ * including its BOM normalisation, which is why the fence test looks past one.
107
+ * The BOM itself stays in `lines[0]`: it belongs to the file's encoding, not to
108
+ * the block, and an edit must not strip it from the user's file.
109
+ *
110
+ * Lines keep their terminators, so an edit preserves the file's existing line
111
+ * endings instead of rewriting CRLF to LF. Returns undefined when there is no
112
+ * usable block.
113
+ */
114
+ function splitFrontmatter(content: string):
115
+ | { lines: string[]; openIdx: number; closeIdx: number; eol: string }
116
+ | undefined {
117
+ const lines = content.split(/(?<=\n)/);
118
+ if (lines.length === 0) return undefined;
119
+ // The BOM stays where it is — it belongs to the file, not the block — so the
120
+ // fence test looks past it and every index below is unaffected.
121
+ const bom = content.startsWith("\uFEFF");
122
+ const first = (bom ? lines[0].slice(1) : lines[0]).replace(/\r?\n$/, "");
123
+ if (!FENCE.test(first)) return undefined;
124
+ const closeIdx = lines.findIndex((l, i) => i > 0 && FENCE.test(l.replace(/\r?\n$/, "")));
125
+ if (closeIdx === -1) return undefined;
126
+ return { lines, openIdx: 0, closeIdx, eol: lines[0].endsWith("\r\n") ? "\r\n" : "\n" };
127
+ }
128
+
129
+ /**
130
+ * Does the loader consider this file disabled?
131
+ *
132
+ * Detection is a READ operation, so it asks the same parser the loader uses
133
+ * rather than mirroring it with a regex — that mirror has to be right about
134
+ * YAML's boolean spellings (`False`, `FALSE`, a trailing `# comment`, a quoted
135
+ * key) *and* about pi's fence scan, which closes the block on any line starting
136
+ * `---` and so ends it early on `----`. A throw means the file is already
137
+ * unparseable, which is what the loader sees too: it skips the agent, so there
138
+ * is no "disabled" state to report.
139
+ */
140
+ export function isDisabledContent(content: string): boolean {
141
+ try {
142
+ return parseAgentFrontmatter<Record<string, unknown>>(content).frontmatter.enabled === false;
143
+ } catch {
144
+ return false;
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Add `enabled: false` to a file's frontmatter.
150
+ *
151
+ * `outcome` distinguishes a real edit from a no-op so the caller can report
152
+ * honestly instead of unconditionally claiming success.
153
+ */
154
+ export function disableInContent(content: string): { content: string; outcome: DisableOutcome } {
155
+ const block = splitFrontmatter(content);
156
+ if (!block) return { content, outcome: "no-frontmatter" };
157
+ if (isDisabledContent(content)) return { content, outcome: "already-disabled" };
158
+ const lines = [...block.lines];
159
+ lines.splice(1, 0, `enabled: false${block.eol}`);
160
+ return { content: lines.join(""), outcome: "disabled" };
161
+ }
162
+
163
+ /**
164
+ * Remove `enabled: false` from a file's frontmatter, wherever it appears in the
165
+ * block — the loader honors the key at any position, so the two must agree or a
166
+ * hand-authored agent can be disabled and never re-enabled.
167
+ *
168
+ * `changed` is false when the key wasn't found, so the caller can avoid
169
+ * reporting "Enabled <name>" for a write that did nothing.
170
+ */
171
+ export function enableInContent(content: string): { content: string; changed: boolean } {
172
+ const block = splitFrontmatter(content);
173
+ if (!block) return { content, changed: false };
174
+ const kept = block.lines.filter(
175
+ (l, i) => !(i > 0 && i < block.closeIdx && ENABLED_FALSE.test(l.replace(/\r?\n$/, ""))),
176
+ );
177
+ if (kept.length === block.lines.length) return { content, changed: false };
178
+ return { content: kept.join(""), changed: true };
179
+ }
180
+
181
+ /** Is this the empty stub `/agents` writes when disabling a built-in default? */
182
+ export function isEmptyStub(content: string): boolean {
183
+ return content.replace(/\r\n/g, "\n").trim() === "---\n---";
184
+ }
185
+
186
+ /** The answers `/agents → Create agent → Manual` collects, before serialization. */
187
+ export interface NewAgentInput {
188
+ description: string;
189
+ /** Already-resolved `tools:` value ("none", "all", or a CSV of tool names). */
190
+ tools: string;
191
+ /** `provider/modelId`, or undefined to inherit the parent's model. */
192
+ model?: string;
193
+ /** A pi thinking level, or undefined to inherit. */
194
+ thinking?: string;
195
+ systemPrompt: string;
196
+ }
197
+
198
+ /**
199
+ * Build the .md file the create wizard writes.
200
+ *
201
+ * `description` and `model` come straight from a free-text prompt, so they are
202
+ * quoted rather than interpolated — `serializeAgentFile` above quotes the
203
+ * description for the same reason. An unquoted YAML scalar mishandles ordinary
204
+ * input in two ways, and both are silent: a colon ("Scout: find things") makes
205
+ * the file unparseable, and since #212 an unparseable agent file is *skipped*,
206
+ * so the wizard reports success for an agent that does not exist; a `#`
207
+ * ("audit #security") opens a comment and truncates the value. `model` can
208
+ * carry a colon too — pi accepts a `provider/model:thinking` suffix.
209
+ *
210
+ * `tools` and `thinking` are not quoted: both are chosen from fixed menus, and
211
+ * `tools` is a CSV that must stay a bare scalar for the loader's parser.
212
+ */
213
+ export function buildNewAgentFile(input: NewAgentInput): string {
214
+ const modelLine = input.model ? `\nmodel: ${JSON.stringify(input.model)}` : "";
215
+ const thinkingLine = input.thinking ? `\nthinking: ${input.thinking}` : "";
216
+ return `---
217
+ description: ${JSON.stringify(input.description)}
218
+ tools: ${input.tools}${modelLine}${thinkingLine}
219
+ prompt_mode: replace
220
+ ---
221
+
222
+ ${input.systemPrompt}
223
+ `;
224
+ }
225
+
226
+ /** Render a built-in tool list as a `tools:` frontmatter value. */
227
+ function formatToolsField(tools: string[] | undefined): string {
228
+ if (tools === undefined) return "all";
229
+ if (tools.length === 0) return "none";
230
+ return tools.join(", ");
231
+ }
232
+
233
+ /** Serialize an AgentConfig to a full .md file (frontmatter + system prompt) for eject. */
234
+ export function serializeAgentFile(cfg: AgentConfig): string {
235
+ const fmFields: string[] = [];
236
+ fmFields.push(`description: ${JSON.stringify(cfg.description)}`);
237
+ if (cfg.displayName) fmFields.push(`display_name: ${cfg.displayName}`);
238
+ if (cfg.color) fmFields.push(`color: ${JSON.stringify(cfg.color)}`);
239
+ // Absent means "all built-ins"; an EMPTY list means explicitly zero. Writing
240
+ // `all` for both would hand a deliberately tool-less agent the whole toolbox
241
+ // the first time it is ejected.
242
+ fmFields.push(`tools: ${formatToolsField(cfg.builtinToolNames)}`);
243
+ if (cfg.model) fmFields.push(`model: ${cfg.model}`);
244
+ if (cfg.thinking) fmFields.push(`thinking: ${cfg.thinking}`);
245
+ if (cfg.maxTurns) fmFields.push(`max_turns: ${cfg.maxTurns}`);
246
+ if (cfg.allowedSubagents !== undefined) {
247
+ fmFields.push(`allowed_subagents: ${cfg.allowedSubagents === "all" ? "all" : cfg.allowedSubagents.join(", ")}`);
248
+ }
249
+ fmFields.push(`prompt_mode: ${cfg.promptMode}`);
250
+ if (cfg.extensions === false) fmFields.push("extensions: false");
251
+ else if (Array.isArray(cfg.extensions)) fmFields.push(`extensions: ${cfg.extensions.join(", ")}`);
252
+ if (cfg.excludeExtensions?.length) fmFields.push(`exclude_extensions: ${cfg.excludeExtensions.join(", ")}`);
253
+ if (cfg.skills === false) fmFields.push("skills: false");
254
+ else if (Array.isArray(cfg.skills)) fmFields.push(`skills: ${cfg.skills.join(", ")}`);
255
+ if (cfg.disallowedTools?.length) fmFields.push(`disallowed_tools: ${cfg.disallowedTools.join(", ")}`);
256
+ if (cfg.inheritContext) fmFields.push("inherit_context: true");
257
+ // Both cases, not just `true`: with `backgroundByDefault` on, omitting the
258
+ // field means background, so `false` is the only way to pin an agent file to
259
+ // foreground and is no longer interchangeable with absence. No caller can
260
+ // reach it yet — Eject only handles built-in defaults, which omit the field —
261
+ // so this keeps the writer symmetric with the loader, nothing more.
262
+ if (cfg.runInBackground !== undefined) fmFields.push(`run_in_background: ${cfg.runInBackground}`);
263
+ if (cfg.outputTranscript === false) fmFields.push("output_transcript: false");
264
+ if (cfg.isolated) fmFields.push("isolated: true");
265
+ if (cfg.memory) fmFields.push(`memory: ${cfg.memory}`);
266
+ if (cfg.isolation) fmFields.push(`isolation: ${cfg.isolation}`);
267
+
268
+ return `---\n${fmFields.join("\n")}\n---\n\n${cfg.systemPrompt}\n`;
269
+ }