@esso0428/pi-subagents 0.17.15 → 0.17.17

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 (359) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/ROADMAP.md +87 -0
  3. package/docs/post-0.17.6-agents-roster-viewer-spec.md +42 -0
  4. package/docs/post-0.17.6-durable-history-spec.md +41 -0
  5. package/docs/post-0.17.6-feature-specs.md +50 -0
  6. package/docs/post-0.17.6-nested-agents-spec.md +38 -0
  7. package/docs/post-0.17.6-recovery-shutdown-spec.md +46 -0
  8. package/docs/post-0.17.6-ui-latency-baseline-spec.md +46 -0
  9. package/docs/post-0.17.6-workflow-rpc-lifecycle-spec.md +54 -0
  10. package/package.json +2 -3
  11. package/src/agent-history.ts +2 -54
  12. package/src/agent-manager.ts +406 -1288
  13. package/src/agent-runner.ts +27 -251
  14. package/src/agent-types.ts +32 -188
  15. package/src/cross-extension-rpc.ts +20 -96
  16. package/src/custom-agents.ts +13 -170
  17. package/src/index.ts +480 -1920
  18. package/src/invocation-config.ts +3 -118
  19. package/src/model-resolver.ts +0 -18
  20. package/src/output-file.ts +6 -61
  21. package/src/prompts.ts +2 -45
  22. package/src/schedule.ts +14 -35
  23. package/src/settings.ts +2 -301
  24. package/src/status-note.ts +1 -66
  25. package/src/types.ts +10 -177
  26. package/src/ui/agent-widget.ts +57 -278
  27. package/src/ui/conversation-blocks.ts +0 -6
  28. package/src/ui/conversation-timeline.ts +25 -139
  29. package/src/ui/conversation-viewer.ts +48 -212
  30. package/src/ui/schedule-menu.ts +8 -9
  31. package/src/usage.ts +2 -109
  32. package/src/worktree.ts +55 -69
  33. package/dist/abortable.d.ts +0 -13
  34. package/dist/abortable.d.ts.map +0 -1
  35. package/dist/abortable.js +0 -43
  36. package/dist/abortable.js.map +0 -1
  37. package/dist/agent-color.d.ts +0 -36
  38. package/dist/agent-color.d.ts.map +0 -1
  39. package/dist/agent-color.js +0 -124
  40. package/dist/agent-color.js.map +0 -1
  41. package/dist/agent-file-toggle.d.ts +0 -126
  42. package/dist/agent-file-toggle.d.ts.map +0 -1
  43. package/dist/agent-file-toggle.js +0 -259
  44. package/dist/agent-file-toggle.js.map +0 -1
  45. package/dist/agent-history-list.d.ts +0 -19
  46. package/dist/agent-history-list.d.ts.map +0 -1
  47. package/dist/agent-history-list.js +0 -69
  48. package/dist/agent-history-list.js.map +0 -1
  49. package/dist/agent-history.d.ts +0 -35
  50. package/dist/agent-history.d.ts.map +0 -1
  51. package/dist/agent-history.js +0 -188
  52. package/dist/agent-history.js.map +0 -1
  53. package/dist/agent-manager.d.ts +0 -503
  54. package/dist/agent-manager.d.ts.map +0 -1
  55. package/dist/agent-manager.js +0 -1572
  56. package/dist/agent-manager.js.map +0 -1
  57. package/dist/agent-recovery.d.ts +0 -37
  58. package/dist/agent-recovery.d.ts.map +0 -1
  59. package/dist/agent-recovery.js +0 -171
  60. package/dist/agent-recovery.js.map +0 -1
  61. package/dist/agent-runner.d.ts +0 -303
  62. package/dist/agent-runner.d.ts.map +0 -1
  63. package/dist/agent-runner.js +0 -1003
  64. package/dist/agent-runner.js.map +0 -1
  65. package/dist/agent-types.d.ts +0 -120
  66. package/dist/agent-types.d.ts.map +0 -1
  67. package/dist/agent-types.js +0 -301
  68. package/dist/agent-types.js.map +0 -1
  69. package/dist/child-context.d.ts +0 -3
  70. package/dist/child-context.d.ts.map +0 -1
  71. package/dist/child-context.js +0 -13
  72. package/dist/child-context.js.map +0 -1
  73. package/dist/context.d.ts +0 -13
  74. package/dist/context.d.ts.map +0 -1
  75. package/dist/context.js +0 -57
  76. package/dist/context.js.map +0 -1
  77. package/dist/cross-extension-rpc.d.ts +0 -67
  78. package/dist/cross-extension-rpc.d.ts.map +0 -1
  79. package/dist/cross-extension-rpc.js +0 -139
  80. package/dist/cross-extension-rpc.js.map +0 -1
  81. package/dist/custom-agents.d.ts +0 -55
  82. package/dist/custom-agents.d.ts.map +0 -1
  83. package/dist/custom-agents.js +0 -309
  84. package/dist/custom-agents.js.map +0 -1
  85. package/dist/default-agents.d.ts +0 -8
  86. package/dist/default-agents.d.ts.map +0 -1
  87. package/dist/default-agents.js +0 -123
  88. package/dist/default-agents.js.map +0 -1
  89. package/dist/enabled-models.d.ts +0 -50
  90. package/dist/enabled-models.d.ts.map +0 -1
  91. package/dist/enabled-models.js +0 -146
  92. package/dist/enabled-models.js.map +0 -1
  93. package/dist/env.d.ts +0 -7
  94. package/dist/env.d.ts.map +0 -1
  95. package/dist/env.js +0 -29
  96. package/dist/env.js.map +0 -1
  97. package/dist/group-join.d.ts +0 -33
  98. package/dist/group-join.d.ts.map +0 -1
  99. package/dist/group-join.js +0 -117
  100. package/dist/group-join.js.map +0 -1
  101. package/dist/index.d.ts +0 -51
  102. package/dist/index.d.ts.map +0 -1
  103. package/dist/index.js +0 -3687
  104. package/dist/index.js.map +0 -1
  105. package/dist/invocation-config.d.ts +0 -108
  106. package/dist/invocation-config.d.ts.map +0 -1
  107. package/dist/invocation-config.js +0 -84
  108. package/dist/invocation-config.js.map +0 -1
  109. package/dist/memory.d.ts +0 -54
  110. package/dist/memory.d.ts.map +0 -1
  111. package/dist/memory.js +0 -166
  112. package/dist/memory.js.map +0 -1
  113. package/dist/mention-clone.d.ts +0 -88
  114. package/dist/mention-clone.d.ts.map +0 -1
  115. package/dist/mention-clone.js +0 -154
  116. package/dist/mention-clone.js.map +0 -1
  117. package/dist/mention.d.ts +0 -82
  118. package/dist/mention.d.ts.map +0 -1
  119. package/dist/mention.js +0 -132
  120. package/dist/mention.js.map +0 -1
  121. package/dist/model-resolver.d.ts +0 -37
  122. package/dist/model-resolver.d.ts.map +0 -1
  123. package/dist/model-resolver.js +0 -96
  124. package/dist/model-resolver.js.map +0 -1
  125. package/dist/model-scope.d.ts +0 -50
  126. package/dist/model-scope.d.ts.map +0 -1
  127. package/dist/model-scope.js +0 -49
  128. package/dist/model-scope.js.map +0 -1
  129. package/dist/nested-tools.d.ts +0 -57
  130. package/dist/nested-tools.d.ts.map +0 -1
  131. package/dist/nested-tools.js +0 -301
  132. package/dist/nested-tools.js.map +0 -1
  133. package/dist/nico-overrides.d.ts +0 -54
  134. package/dist/nico-overrides.d.ts.map +0 -1
  135. package/dist/nico-overrides.js +0 -170
  136. package/dist/nico-overrides.js.map +0 -1
  137. package/dist/output-file.d.ts +0 -44
  138. package/dist/output-file.d.ts.map +0 -1
  139. package/dist/output-file.js +0 -156
  140. package/dist/output-file.js.map +0 -1
  141. package/dist/prompts.d.ts +0 -56
  142. package/dist/prompts.d.ts.map +0 -1
  143. package/dist/prompts.js +0 -92
  144. package/dist/prompts.js.map +0 -1
  145. package/dist/schedule-store.d.ts +0 -39
  146. package/dist/schedule-store.d.ts.map +0 -1
  147. package/dist/schedule-store.js +0 -156
  148. package/dist/schedule-store.js.map +0 -1
  149. package/dist/schedule.d.ts +0 -110
  150. package/dist/schedule.d.ts.map +0 -1
  151. package/dist/schedule.js +0 -360
  152. package/dist/schedule.js.map +0 -1
  153. package/dist/settings.d.ts +0 -354
  154. package/dist/settings.d.ts.map +0 -1
  155. package/dist/settings.js +0 -247
  156. package/dist/settings.js.map +0 -1
  157. package/dist/skill-loader.d.ts +0 -25
  158. package/dist/skill-loader.d.ts.map +0 -1
  159. package/dist/skill-loader.js +0 -94
  160. package/dist/skill-loader.js.map +0 -1
  161. package/dist/status-note.d.ts +0 -62
  162. package/dist/status-note.d.ts.map +0 -1
  163. package/dist/status-note.js +0 -86
  164. package/dist/status-note.js.map +0 -1
  165. package/dist/structured-output.d.ts +0 -62
  166. package/dist/structured-output.d.ts.map +0 -1
  167. package/dist/structured-output.js +0 -113
  168. package/dist/structured-output.js.map +0 -1
  169. package/dist/types.d.ts +0 -372
  170. package/dist/types.d.ts.map +0 -1
  171. package/dist/types.js +0 -6
  172. package/dist/types.js.map +0 -1
  173. package/dist/ui/agent-mention.d.ts +0 -83
  174. package/dist/ui/agent-mention.d.ts.map +0 -1
  175. package/dist/ui/agent-mention.js +0 -188
  176. package/dist/ui/agent-mention.js.map +0 -1
  177. package/dist/ui/agent-widget.d.ts +0 -241
  178. package/dist/ui/agent-widget.d.ts.map +0 -1
  179. package/dist/ui/agent-widget.js +0 -992
  180. package/dist/ui/agent-widget.js.map +0 -1
  181. package/dist/ui/ccstyle/diff/ansi-utils.d.ts +0 -11
  182. package/dist/ui/ccstyle/diff/ansi-utils.d.ts.map +0 -1
  183. package/dist/ui/ccstyle/diff/ansi-utils.js +0 -145
  184. package/dist/ui/ccstyle/diff/ansi-utils.js.map +0 -1
  185. package/dist/ui/ccstyle/diff/diff-presentation.d.ts +0 -12
  186. package/dist/ui/ccstyle/diff/diff-presentation.d.ts.map +0 -1
  187. package/dist/ui/ccstyle/diff/diff-presentation.js +0 -48
  188. package/dist/ui/ccstyle/diff/diff-presentation.js.map +0 -1
  189. package/dist/ui/ccstyle/diff/diff-renderer.d.ts +0 -46
  190. package/dist/ui/ccstyle/diff/diff-renderer.d.ts.map +0 -1
  191. package/dist/ui/ccstyle/diff/diff-renderer.js +0 -2049
  192. package/dist/ui/ccstyle/diff/diff-renderer.js.map +0 -1
  193. package/dist/ui/ccstyle/diff/line-width-safety.d.ts +0 -12
  194. package/dist/ui/ccstyle/diff/line-width-safety.d.ts.map +0 -1
  195. package/dist/ui/ccstyle/diff/line-width-safety.js +0 -58
  196. package/dist/ui/ccstyle/diff/line-width-safety.js.map +0 -1
  197. package/dist/ui/ccstyle/diff/render-utils.d.ts +0 -6
  198. package/dist/ui/ccstyle/diff/render-utils.d.ts.map +0 -1
  199. package/dist/ui/ccstyle/diff/render-utils.js +0 -25
  200. package/dist/ui/ccstyle/diff/render-utils.js.map +0 -1
  201. package/dist/ui/ccstyle/diff/shiki-highlight.d.ts +0 -19
  202. package/dist/ui/ccstyle/diff/shiki-highlight.d.ts.map +0 -1
  203. package/dist/ui/ccstyle/diff/shiki-highlight.js +0 -85
  204. package/dist/ui/ccstyle/diff/shiki-highlight.js.map +0 -1
  205. package/dist/ui/ccstyle/diff/types.d.ts +0 -22
  206. package/dist/ui/ccstyle/diff/types.d.ts.map +0 -1
  207. package/dist/ui/ccstyle/diff/types.js +0 -10
  208. package/dist/ui/ccstyle/diff/types.js.map +0 -1
  209. package/dist/ui/ccstyle/diff/write-display-utils.d.ts +0 -2
  210. package/dist/ui/ccstyle/diff/write-display-utils.d.ts.map +0 -1
  211. package/dist/ui/ccstyle/diff/write-display-utils.js +0 -12
  212. package/dist/ui/ccstyle/diff/write-display-utils.js.map +0 -1
  213. package/dist/ui/ccstyle/tool-renderer.d.ts +0 -17
  214. package/dist/ui/ccstyle/tool-renderer.d.ts.map +0 -1
  215. package/dist/ui/ccstyle/tool-renderer.js +0 -74
  216. package/dist/ui/ccstyle/tool-renderer.js.map +0 -1
  217. package/dist/ui/ccstyle/tool-result.d.ts +0 -44
  218. package/dist/ui/ccstyle/tool-result.d.ts.map +0 -1
  219. package/dist/ui/ccstyle/tool-result.js +0 -423
  220. package/dist/ui/ccstyle/tool-result.js.map +0 -1
  221. package/dist/ui/conversation-blocks.d.ts +0 -46
  222. package/dist/ui/conversation-blocks.d.ts.map +0 -1
  223. package/dist/ui/conversation-blocks.js +0 -313
  224. package/dist/ui/conversation-blocks.js.map +0 -1
  225. package/dist/ui/conversation-nvim.d.ts +0 -8
  226. package/dist/ui/conversation-nvim.d.ts.map +0 -1
  227. package/dist/ui/conversation-nvim.js +0 -117
  228. package/dist/ui/conversation-nvim.js.map +0 -1
  229. package/dist/ui/conversation-role.d.ts +0 -13
  230. package/dist/ui/conversation-role.d.ts.map +0 -1
  231. package/dist/ui/conversation-role.js +0 -39
  232. package/dist/ui/conversation-role.js.map +0 -1
  233. package/dist/ui/conversation-search.d.ts +0 -39
  234. package/dist/ui/conversation-search.d.ts.map +0 -1
  235. package/dist/ui/conversation-search.js +0 -124
  236. package/dist/ui/conversation-search.js.map +0 -1
  237. package/dist/ui/conversation-timeline.d.ts +0 -102
  238. package/dist/ui/conversation-timeline.d.ts.map +0 -1
  239. package/dist/ui/conversation-timeline.js +0 -555
  240. package/dist/ui/conversation-timeline.js.map +0 -1
  241. package/dist/ui/conversation-viewer.d.ts +0 -138
  242. package/dist/ui/conversation-viewer.d.ts.map +0 -1
  243. package/dist/ui/conversation-viewer.js +0 -1175
  244. package/dist/ui/conversation-viewer.js.map +0 -1
  245. package/dist/ui/schedule-menu.d.ts +0 -17
  246. package/dist/ui/schedule-menu.d.ts.map +0 -1
  247. package/dist/ui/schedule-menu.js +0 -95
  248. package/dist/ui/schedule-menu.js.map +0 -1
  249. package/dist/ui/select-item.d.ts +0 -28
  250. package/dist/ui/select-item.d.ts.map +0 -1
  251. package/dist/ui/select-item.js +0 -35
  252. package/dist/ui/select-item.js.map +0 -1
  253. package/dist/ui/viewer-keys.d.ts +0 -21
  254. package/dist/ui/viewer-keys.d.ts.map +0 -1
  255. package/dist/ui/viewer-keys.js +0 -18
  256. package/dist/ui/viewer-keys.js.map +0 -1
  257. package/dist/ui/workflow-card.d.ts +0 -176
  258. package/dist/ui/workflow-card.d.ts.map +0 -1
  259. package/dist/ui/workflow-card.js +0 -333
  260. package/dist/ui/workflow-card.js.map +0 -1
  261. package/dist/ui/workflow-dialog.d.ts +0 -306
  262. package/dist/ui/workflow-dialog.d.ts.map +0 -1
  263. package/dist/ui/workflow-dialog.js +0 -844
  264. package/dist/ui/workflow-dialog.js.map +0 -1
  265. package/dist/ui/workflow-menu.d.ts +0 -42
  266. package/dist/ui/workflow-menu.d.ts.map +0 -1
  267. package/dist/ui/workflow-menu.js +0 -127
  268. package/dist/ui/workflow-menu.js.map +0 -1
  269. package/dist/usage.d.ts +0 -136
  270. package/dist/usage.d.ts.map +0 -1
  271. package/dist/usage.js +0 -121
  272. package/dist/usage.js.map +0 -1
  273. package/dist/workflow/collisions.d.ts +0 -96
  274. package/dist/workflow/collisions.d.ts.map +0 -1
  275. package/dist/workflow/collisions.js +0 -89
  276. package/dist/workflow/collisions.js.map +0 -1
  277. package/dist/workflow/entry.d.ts +0 -33
  278. package/dist/workflow/entry.d.ts.map +0 -1
  279. package/dist/workflow/entry.js +0 -30
  280. package/dist/workflow/entry.js.map +0 -1
  281. package/dist/workflow/host.d.ts +0 -63
  282. package/dist/workflow/host.d.ts.map +0 -1
  283. package/dist/workflow/host.js +0 -363
  284. package/dist/workflow/host.js.map +0 -1
  285. package/dist/workflow/journal.d.ts +0 -98
  286. package/dist/workflow/journal.d.ts.map +0 -1
  287. package/dist/workflow/journal.js +0 -121
  288. package/dist/workflow/journal.js.map +0 -1
  289. package/dist/workflow/json-schema.d.ts +0 -52
  290. package/dist/workflow/json-schema.d.ts.map +0 -1
  291. package/dist/workflow/json-schema.js +0 -112
  292. package/dist/workflow/json-schema.js.map +0 -1
  293. package/dist/workflow/meta.d.ts +0 -68
  294. package/dist/workflow/meta.d.ts.map +0 -1
  295. package/dist/workflow/meta.js +0 -318
  296. package/dist/workflow/meta.js.map +0 -1
  297. package/dist/workflow/progress.d.ts +0 -225
  298. package/dist/workflow/progress.d.ts.map +0 -1
  299. package/dist/workflow/progress.js +0 -362
  300. package/dist/workflow/progress.js.map +0 -1
  301. package/dist/workflow/runtime.d.ts +0 -335
  302. package/dist/workflow/runtime.d.ts.map +0 -1
  303. package/dist/workflow/runtime.js +0 -831
  304. package/dist/workflow/runtime.js.map +0 -1
  305. package/dist/workflow/saved.d.ts +0 -91
  306. package/dist/workflow/saved.d.ts.map +0 -1
  307. package/dist/workflow/saved.js +0 -204
  308. package/dist/workflow/saved.js.map +0 -1
  309. package/dist/workflow/task.d.ts +0 -137
  310. package/dist/workflow/task.d.ts.map +0 -1
  311. package/dist/workflow/task.js +0 -208
  312. package/dist/workflow/task.js.map +0 -1
  313. package/dist/workflow/tool-description.d.ts +0 -39
  314. package/dist/workflow/tool-description.d.ts.map +0 -1
  315. package/dist/workflow/tool-description.js +0 -200
  316. package/dist/workflow/tool-description.js.map +0 -1
  317. package/dist/workflow/worker-source.d.ts +0 -48
  318. package/dist/workflow/worker-source.d.ts.map +0 -1
  319. package/dist/workflow/worker-source.js +0 -779
  320. package/dist/workflow/worker-source.js.map +0 -1
  321. package/dist/worktree.d.ts +0 -53
  322. package/dist/worktree.d.ts.map +0 -1
  323. package/dist/worktree.js +0 -165
  324. package/dist/worktree.js.map +0 -1
  325. package/dist/write-execution.d.ts +0 -42
  326. package/dist/write-execution.d.ts.map +0 -1
  327. package/dist/write-execution.js +0 -138
  328. package/dist/write-execution.js.map +0 -1
  329. package/dist/xml.d.ts +0 -11
  330. package/dist/xml.d.ts.map +0 -1
  331. package/dist/xml.js +0 -13
  332. package/dist/xml.js.map +0 -1
  333. package/src/abortable.ts +0 -43
  334. package/src/agent-color.ts +0 -161
  335. package/src/agent-file-toggle.ts +0 -269
  336. package/src/child-context.ts +0 -15
  337. package/src/mention-clone.ts +0 -196
  338. package/src/mention.ts +0 -141
  339. package/src/model-scope.ts +0 -70
  340. package/src/nested-tools.ts +0 -424
  341. package/src/structured-output.ts +0 -130
  342. package/src/ui/agent-mention.ts +0 -216
  343. package/src/ui/select-item.ts +0 -45
  344. package/src/ui/workflow-card.ts +0 -470
  345. package/src/ui/workflow-dialog.ts +0 -1115
  346. package/src/ui/workflow-menu.ts +0 -166
  347. package/src/workflow/collisions.ts +0 -123
  348. package/src/workflow/entry.ts +0 -47
  349. package/src/workflow/host.ts +0 -403
  350. package/src/workflow/journal.ts +0 -164
  351. package/src/workflow/json-schema.ts +0 -128
  352. package/src/workflow/meta.ts +0 -325
  353. package/src/workflow/progress.ts +0 -550
  354. package/src/workflow/runtime.ts +0 -1219
  355. package/src/workflow/saved.ts +0 -217
  356. package/src/workflow/task.ts +0 -302
  357. package/src/workflow/tool-description.ts +0 -200
  358. package/src/workflow/worker-source.ts +0 -781
  359. package/src/xml.ts +0 -13
@@ -1,161 +0,0 @@
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
- }
@@ -1,269 +0,0 @@
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
- }
@@ -1,15 +0,0 @@
1
- import { AsyncLocalStorage } from "node:async_hooks";
2
-
3
- /**
4
- * Marks resource loading/session construction performed for a subagent. This is
5
- * async-context-local so concurrent top-level extension work is unaffected.
6
- */
7
- const childSessionContext = new AsyncLocalStorage<boolean>();
8
-
9
- export function inChildSessionContext(): boolean {
10
- return childSessionContext.getStore() === true;
11
- }
12
-
13
- export function runInChildSessionContext<T>(fn: () => Promise<T>): Promise<T> {
14
- return childSessionContext.run(true, fn);
15
- }
@@ -1,196 +0,0 @@
1
- /**
2
- * mention-clone.ts — start a mentioned agent through a clone of this
3
- * conversation, without putting anything in the chat.
4
- *
5
- * Claude Code routes `@agent-<type>` through the main model: the mention
6
- * becomes a `<system-reminder>` appended to the prompt and the model makes the
7
- * tool call (see `agentMentionReminder`). That buys the spawned agent a prompt
8
- * written with conversation context, and costs a visible turn — the model's
9
- * reasoning and its tool block land in the transcript, for a decision the user
10
- * already made when they typed the handle.
11
- *
12
- * So the turn happens somewhere else. The conversation is cloned into a
13
- * throwaway in-memory session — same messages, same system prompt, same model —
14
- * and that copy takes the turn off-screen. A literal clone: the session's own
15
- * entries, projected by pi's own `sessionEntryToContextMessages`, not
16
- * `inherit_context`'s text rendering of them.
17
- *
18
- * Cloned from memory rather than from the session file, which cannot be relied
19
- * on: `SessionManager._persist` withholds every write until the first assistant
20
- * message lands, so a fork taken before then reads an empty file and throws.
21
- * `buildSessionContext()` has no such timing, and is compaction-aware — it walks
22
- * the leaf path and substitutes the summary for entries folded into it, so a
23
- * long conversation clones as what the main model is actually working from. A
24
- * conversation with nothing in it yet clones to nothing in it yet, which is the
25
- * correct answer rather than a failure.
26
- *
27
- * It is also the oldest of the equivalent Pi APIs — `buildContextEntries` on
28
- * ReadonlySessionManager and the `sessionEntryToContextMessages` export both
29
- * arrived in 0.80.5 — where this one has been exported unchanged from before
30
- * the declared peer floor, and is the same code path (`byId` is only an index
31
- * cache, so passing it or not cannot change the result). Keeping the floor
32
- * honest costs nothing here: see the `compat-floor-pi` job.
33
- *
34
- * Its `thinkingLevel` is NOT used, and is the one place the newer API would be
35
- * better. `getSessionContextSettings` starts at "off" and moves only on an
36
- * explicit `thinking_level_change` entry, so a session where nobody ran
37
- * `/think` reports "off" rather than the level it is really using. Omitting the
38
- * field instead lets `createAgentSession` resolve it from settings, which is
39
- * that real level.
40
- *
41
- * Three details make the spawn belong to the real session rather than the
42
- * clone:
43
- *
44
- * - the clone is handed the *registered* `Agent` tool, whose handler closes
45
- * over the main activation, so it spawns top-level: widget, fleet row,
46
- * handle, completion notification, all as if the main model had called it;
47
- * - that tool is re-bound to the main `ExtensionContext`, because the handler
48
- * reads `cwd`, `model` and `sessionManager.getSessionId()` off it to place
49
- * the transcript and the `rootSessionId`. The clone's own context would
50
- * file both under the throwaway fork;
51
- * - it is called with no tool-call id. The clone's turn produces one, but the
52
- * real session never issued it, and a `<tool-use-id>` pointing at nothing
53
- * is exactly the bug the mention-resume path had to fix;
54
- * - and it is forced into the background. A foreground agent returns its
55
- * answer as the tool result and is marked `resultConsumed` so no completion
56
- * notification is sent — correct when the caller is the real conversation,
57
- * silent loss when the caller is a fork about to be discarded. Background
58
- * delivery is the only route from a mention back to the main model.
59
- *
60
- * The clone gets one tool and one job. It cannot read, write or run anything —
61
- * an invisible turn with the full toolset could do invisible work.
62
- */
63
-
64
- import type { Model } from "@earendil-works/pi-ai";
65
- import {
66
- buildSessionContext,
67
- createAgentSession,
68
- type ExtensionContext,
69
- SessionManager,
70
- type ToolDefinition,
71
- } from "@earendil-works/pi-coding-agent";
72
- import { runInChildSessionContext } from "./child-context.js";
73
- import { agentMentionReminder } from "./mention.js";
74
- import type { SubagentType, ThinkingLevel } from "./types.js";
75
-
76
- export interface MentionCloneOptions {
77
- /** The MAIN session's context — what the spawn is attributed to, and the
78
- * source of both the conversation and the live system prompt. */
79
- ctx: ExtensionContext;
80
- /** Agent type the handle resolved to. */
81
- type: SubagentType;
82
- /** What the user typed after the handle. */
83
- message: string;
84
- /** The registered `Agent` tool, reused so the spawn is an ordinary one. */
85
- agentTool: ToolDefinition;
86
- }
87
-
88
- export interface MentionCloneResult {
89
- /** True once the clone actually called `Agent`. */
90
- spawned: boolean;
91
- /** Why not, when it didn't. Absent on success. */
92
- error?: string;
93
- }
94
-
95
- /**
96
- * Fork the conversation, let the copy make the tool call, throw the copy away.
97
- * Never rejects: a clone that cannot run is reported so the caller can fall
98
- * back to starting the agent directly.
99
- */
100
- export async function runMentionClone(opts: MentionCloneOptions): Promise<MentionCloneResult> {
101
- const { ctx, type, message, agentTool } = opts;
102
-
103
- let spawned = false;
104
- const cloneAgentTool: ToolDefinition = {
105
- ...agentTool,
106
- execute: (_cloneToolCallId, params, signal, onUpdate, _cloneCtx) => {
107
- // One spawn per mention. The clone has a single tool and every reason to
108
- // stop after using it, but a model that decides to "also" launch a second
109
- // agent would do it where nobody can see and nobody asked.
110
- if (spawned) {
111
- return Promise.resolve({
112
- content: [{ type: "text" as const, text: "Already started an agent for this mention. Stop here." }],
113
- details: undefined,
114
- isError: true,
115
- });
116
- }
117
- spawned = true;
118
- // undefined tool-call id + the main ctx: see the header. Background is
119
- // forced rather than left to the clone: `run_in_background` defaults to
120
- // false, and a foreground agent answers through its TOOL RESULT — which
121
- // here is delivered into a session that is disposed moments later, so the
122
- // agent would run, appear in the widget and the fleet, and reach nobody.
123
- return agentTool.execute(
124
- undefined as never,
125
- { ...(params as Record<string, unknown>), run_in_background: true } as typeof params,
126
- signal,
127
- onUpdate,
128
- ctx,
129
- );
130
- },
131
- };
132
-
133
- let session: Awaited<ReturnType<typeof createAgentSession>>["session"] | undefined;
134
- try {
135
- // Pi 0.80.8 moved createAgentSession from modelRegistry to modelRuntime;
136
- // agent-runner.ts carries the same shim for the same reason — pass both so
137
- // the clone keeps the parent's providers across the supported range.
138
- const parentModelRuntime = (ctx.modelRegistry as unknown as { runtime?: unknown }).runtime;
139
- // The conversation as the main session resolves it: compaction applied,
140
- // branch summaries substituted.
141
- const conversation = buildSessionContext(
142
- ctx.sessionManager.getEntries(),
143
- ctx.sessionManager.getLeafId(),
144
- );
145
- // Pi 0.82.0 added this; below it the field is absent and the clone takes
146
- // the settings level instead, which is what a session that never ran
147
- // `/think` is on anyway. Same shim shape as `modelRuntime` below.
148
- const thinkingLevel = (ctx as { thinkingLevel?: ThinkingLevel }).thinkingLevel;
149
- const created = await runInChildSessionContext(() =>
150
- createAgentSession({
151
- cwd: ctx.cwd,
152
- // Nothing about the copy is worth persisting, and an in-memory manager
153
- // is also what keeps the real session untouched.
154
- sessionManager: SessionManager.inMemory(ctx.cwd),
155
- model: ctx.model as Model<never> | undefined,
156
- ...(thinkingLevel && { thinkingLevel }),
157
- modelRegistry: ctx.modelRegistry,
158
- ...(parentModelRuntime !== undefined && { modelRuntime: parentModelRuntime as never }),
159
- // An allowlist naming exactly the clone's own tool. NOT `noTools:
160
- // "all"`, whose doc comment ("start with no tools enabled") reads like
161
- // it spares custom tools and does not: it resolves to an EMPTY
162
- // allowlist, and `isAllowedTool` then drops every tool from the
163
- // registry — the custom one included. The clone would be prompted with
164
- // nothing to call, answer in prose, and every mention would fall
165
- // through to the direct start with a warning. Same idiom as
166
- // agent-runner's `tools: sessionTools` beside its nested `customTools`.
167
- tools: [cloneAgentTool.name],
168
- customTools: [cloneAgentTool],
169
- } as Parameters<typeof createAgentSession>[0]),
170
- );
171
- session = created.session;
172
-
173
- // The clone rebuilds a system prompt from cwd and agentDir, which is close
174
- // but not the live one — extensions contribute to it per turn. Copy the
175
- // real thing, so the copy reasons under the instructions the user's model
176
- // is actually working under.
177
- const systemPrompt = ctx.getSystemPrompt?.();
178
- if (systemPrompt) session.agent.state.systemPrompt = systemPrompt;
179
-
180
- // The conversation itself. Pushed rather than assigned so the array the
181
- // session was built around stays the one it goes on using.
182
- session.agent.state.messages.push(...conversation.messages);
183
-
184
- // User text first, reminder after — the order Claude Code's attachment
185
- // renderer produces, where the reminder trails the message it is about.
186
- await session.prompt(`${message}\n\n${agentMentionReminder(type)}`);
187
- } catch (err) {
188
- return { spawned, error: err instanceof Error ? err.message : String(err) };
189
- } finally {
190
- session?.dispose?.();
191
- }
192
-
193
- return spawned
194
- ? { spawned: true }
195
- : { spawned: false, error: "the conversation clone did not start it" };
196
- }