@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,1003 +0,0 @@
1
- /**
2
- * agent-runner.ts — Core execution engine: creates sessions, runs agents, collects results.
3
- */
4
- import { readFileSync } from "node:fs";
5
- import { homedir } from "node:os";
6
- import { basename, dirname, isAbsolute, join, resolve } from "node:path";
7
- import { createAgentSession, DefaultResourceLoader, getAgentDir, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
8
- import { BUILTIN_TOOL_NAMES, getAgentConfig, getConfig, getMemoryToolNames, getReadOnlyMemoryToolNames, getToolNamesForType } from "./agent-types.js";
9
- import { runInChildSessionContext } from "./child-context.js";
10
- import { buildParentContext, extractText } from "./context.js";
11
- import { DEFAULT_AGENTS } from "./default-agents.js";
12
- import { detectEnv } from "./env.js";
13
- import { buildMemoryBlock, buildReadOnlyMemoryBlock } from "./memory.js";
14
- import { createNestedSubagentTools, getMaxSubagentDepth } from "./nested-tools.js";
15
- import { buildAgentPrompt } from "./prompts.js";
16
- import { preloadSkills } from "./skill-loader.js";
17
- import { createStructuredCapture, createStructuredOutputTool, structuredRetryPrompt } from "./structured-output.js";
18
- /**
19
- * Tool names registered by THIS extension. Single source of truth so the
20
- * registration sites (index.ts) and the subagent exclusion list below can't
21
- * drift apart. These are our own tools, not pi built-ins, so they can't be
22
- * derived from pi — but they only need defining once.
23
- */
24
- export const SUBAGENT_TOOL_NAMES = {
25
- AGENT: "Agent",
26
- WORKFLOW: "SubagentWorkflow",
27
- GET_RESULT: "get_subagent_result",
28
- STEER: "steer_subagent",
29
- };
30
- /** Names of tools registered by this extension that subagents must NOT inherit. */
31
- const EXCLUDED_TOOL_NAMES = Object.values(SUBAGENT_TOOL_NAMES);
32
- /**
33
- * Canonical name of an extension for `extensions: [...]` allowlist matching.
34
- * Lowercased — extension names match case-insensitively so `extensions: [Mcp]`
35
- * resolves the same as `[mcp]`. Tool names within `ext:foo/bar` are not affected.
36
- * Directory extensions (`foo/index.ts`) resolve to the parent directory name;
37
- * single-file extensions to the basename minus `.ts`/`.js`.
38
- */
39
- export function extensionCanonicalName(extPath) {
40
- const base = basename(extPath);
41
- const name = base === "index.ts" || base === "index.js"
42
- ? basename(dirname(extPath))
43
- : base.replace(/\.(ts|js)$/, "");
44
- return name.toLowerCase();
45
- }
46
- /**
47
- * The unscoped, lowercased npm short name of the pi package that DECLARES
48
- * `extPath` as an extension entry — or undefined if the entry doesn't belong to
49
- * such a package.
50
- *
51
- * Climbs from the entry's directory looking for the package that owns it, and
52
- * stays strictly within that package's tree by stopping at two structural
53
- * boundaries — no hardcoded depth:
54
- * - the FIRST `package.json` found (the package root); the entry's own
55
- * manifest always sits at the root, above the entry, below any node_modules.
56
- * - a `node_modules` directory: a package never spans one (it's where OTHER
57
- * packages live), so reaching it means we've climbed out of the package —
58
- * stop before reading a consumer's or parent package's manifest.
59
- * The name is then taken only when that root's `pi.extensions` manifest actually
60
- * lists this entry. That "declares this entry" check is deliberate: our own test
61
- * fixtures live under this repo, whose root manifest declares `./src/index.ts`
62
- * as `@tintinweb/pi-subagents`, so a looser rule would misattribute every
63
- * co-located file to `pi-subagents`.
64
- */
65
- function extensionPackageName(extPath) {
66
- const entry = resolve(extPath);
67
- let dir = dirname(extPath);
68
- for (;;) {
69
- // Climbing into node_modules means we've left the owning package's tree.
70
- if (basename(dir) === "node_modules")
71
- return undefined;
72
- let pkg;
73
- try {
74
- pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
75
- }
76
- catch {
77
- const parent = dirname(dir);
78
- if (parent === dir)
79
- return undefined; // walked to the filesystem root
80
- dir = parent;
81
- continue;
82
- }
83
- // First package.json wins — it's the package root; decide here.
84
- const entries = pkg.pi?.extensions;
85
- if (typeof pkg.name === "string" &&
86
- Array.isArray(entries) &&
87
- entries.some((e) => typeof e === "string" && resolve(dir, e) === entry)) {
88
- const short = pkg.name.startsWith("@") ? pkg.name.slice(pkg.name.indexOf("/") + 1) : pkg.name;
89
- return short.toLowerCase();
90
- }
91
- return undefined;
92
- }
93
- }
94
- /**
95
- * All names an extension answers to for allowlist matching (lowercased): its
96
- * path-derived {@link extensionCanonicalName} plus, when a pi package manifest
97
- * declares this entry, that package's unscoped short name (`@scope/foo` → `foo`).
98
- * #143: an extension installed via `pi.extensions: ["./src/index.ts"]` would
99
- * otherwise only ever match as `src` (the source directory), never by its
100
- * package name. The path-derived name is preserved, so it keeps matching too.
101
- */
102
- export function extensionCanonicalNames(extPath) {
103
- const canonical = extensionCanonicalName(extPath);
104
- const pkg = extensionPackageName(extPath);
105
- return pkg && pkg !== canonical ? [canonical, pkg] : [canonical];
106
- }
107
- /**
108
- * Classify `extensions: string[]` frontmatter entries for the loader-level filter.
109
- *
110
- * An entry is a PATH iff it contains a path separator or starts with `~`; otherwise
111
- * it is a NAME. `"*"` sets the wildcard flag (keep all default-discovered extensions).
112
- *
113
- * Path entries are resolved (`~` expanded, made absolute against `cwd`) into `paths`
114
- * — and their canonical name is also added to `names`. The loader override matches
115
- * everything by canonical name, so path-loaded extensions are matched via their name
116
- * rather than their post-staging `Extension.path`.
117
- */
118
- export function parseExtensionsSpec(entries, cwd) {
119
- const names = new Set();
120
- const paths = [];
121
- let wildcard = false;
122
- for (const entry of entries) {
123
- if (!entry)
124
- continue;
125
- if (entry === "*") {
126
- wildcard = true;
127
- continue;
128
- }
129
- const isPathEntry = entry.includes("/") || entry.includes("\\") || entry.startsWith("~");
130
- if (!isPathEntry) {
131
- names.add(entry.toLowerCase());
132
- continue;
133
- }
134
- let p = entry;
135
- if (p === "~" || p.startsWith("~/") || p.startsWith("~\\")) {
136
- p = homedir() + p.slice(1);
137
- }
138
- const abs = isAbsolute(p) ? p : resolve(cwd, p);
139
- paths.push(abs);
140
- names.add(extensionCanonicalName(abs));
141
- }
142
- return { names, paths, wildcard };
143
- }
144
- /**
145
- * Parse raw `ext:` selector strings (from the `tools:` CSV) into the set of
146
- * extension names to keep loaded and a per-extension tool-narrowing map.
147
- *
148
- * `ext:foo` → `extNames` has `foo`, no narrowing entry (all of foo's tools).
149
- * `ext:foo/bar` → `extNames` has `foo`, `narrowing.foo` has `bar` (only `bar`).
150
- * A name lands in `narrowing` only when a `/tool` form is seen, so a bare
151
- * `ext:foo` alongside `ext:foo/bar` leaves narrowing in effect (narrowing wins).
152
- * The split is on the first `/`; extension canonical names never contain `/`.
153
- */
154
- export function parseExtSelectors(entries) {
155
- const extNames = new Set();
156
- const narrowing = new Map();
157
- for (const raw of entries) {
158
- if (!raw)
159
- continue;
160
- const body = raw.slice("ext:".length);
161
- const slash = body.indexOf("/");
162
- // Extension name matches case-insensitively (matches the loader-side canonical
163
- // name). Tool names are case-preserved — they're matched against pi-mono's
164
- // registered identifiers, which are case-sensitive.
165
- const name = (slash === -1 ? body : body.slice(0, slash)).trim().toLowerCase();
166
- if (!name)
167
- continue;
168
- extNames.add(name);
169
- if (slash === -1)
170
- continue;
171
- const tool = body.slice(slash + 1).trim();
172
- if (!tool)
173
- continue;
174
- let set = narrowing.get(name);
175
- if (!set) {
176
- set = new Set();
177
- narrowing.set(name, set);
178
- }
179
- set.add(tool);
180
- }
181
- return { extNames, narrowing };
182
- }
183
- /**
184
- * Keep a subagent's tool scope correct as extensions register tools over time.
185
- *
186
- * Extensions may call `registerTool` long after load — pi-mcp from `session_start`,
187
- * context-mode from `before_agent_start` — so scope has to be re-derived rather than
188
- * snapshotted. `registerTool` writes into the very `extension.tools` maps this reads,
189
- * so `inScope()` sees late arrivals on the next call.
190
- *
191
- * Two enforcement points, because neither covers the whole picture:
192
- *
193
- * - `turn_end` re-narrows the ACTIVE set. pi emits `turn_end` immediately before
194
- * `prepareNextTurn` re-snapshots `agent.state.tools`, and session listeners run
195
- * synchronously, so the narrow lands in time for turns 2..N.
196
- * - `beforeToolCall` blocks out-of-scope calls. Turn 1 cannot be narrowed at all:
197
- * `before_agent_start` fires INSIDE `prompt()` and may widen the tool set, but
198
- * `createContextSnapshot()` freezes that turn's tools immediately after — there
199
- * is no hook in between. A call-time check is the only correct guard there.
200
- *
201
- * Both are installed on the session and deliberately NOT unsubscribed: they must
202
- * outlive the `runAgent` call so resumed/steered turns stay scoped. pi's `dispose()`
203
- * clears `_eventListeners`, so they die with the session rather than leaking.
204
- *
205
- * Only meaningful when extensions are loaded — under `noExtensions`/`isolated` the
206
- * static `allowedToolNames` allowlist already gates the registry itself.
207
- */
208
- export function installExtensionToolScope(session, ctx) {
209
- const { loader, toolNames, disallowedSet, extNames, narrowing, readmitToolNames } = ctx;
210
- // The names allowed right now. Mirrors the `ext:` opt-in flip: when any `ext:`
211
- // selector is present, extension tools become an explicit allowlist — a loaded
212
- // extension not named by a selector contributes nothing (its handlers still ran),
213
- // and `ext:foo/bar` narrows `foo` to just `bar`.
214
- const inScope = () => {
215
- const keep = new Set(toolNames.filter((t) => !disallowedSet?.has(t)));
216
- const optInActive = extNames.size > 0;
217
- for (const extension of loader.getExtensions().extensions) {
218
- const canons = extensionCanonicalNames(extension.path);
219
- if (optInActive && !canons.some((c) => extNames.has(c)))
220
- continue;
221
- // First alias that carries a narrowing set — a user won't narrow one
222
- // extension under two different names, so first-match is correct.
223
- const narrowed = canons.map((c) => narrowing.get(c)).find(Boolean);
224
- for (const name of extension.tools.keys()) {
225
- if (narrowed && !narrowed.has(name))
226
- continue;
227
- if (disallowedSet?.has(name))
228
- continue;
229
- keep.add(name);
230
- }
231
- }
232
- for (const name of EXCLUDED_TOOL_NAMES)
233
- keep.delete(name);
234
- // Injected tools are legitimately active for this agent — re-admit them so
235
- // the renarrow keeps them in the active set and beforeToolCall doesn't
236
- // block them. Already vetted against `disallowed_tools` by the caller,
237
- // which is the only place that knows which kind may be taken back.
238
- for (const name of readmitToolNames)
239
- keep.add(name);
240
- return keep;
241
- };
242
- const renarrow = () => {
243
- const allowed = inScope();
244
- const next = session.getAllTools().map((t) => t.name).filter((n) => allowed.has(n));
245
- const current = session.getActiveToolNames();
246
- // setActiveToolsByName unconditionally rebuilds the system prompt, so skip
247
- // the no-op that steady-state turns would otherwise pay for every turn.
248
- if (next.length !== current.length || next.some((n, i) => n !== current[i])) {
249
- session.setActiveToolsByName(next);
250
- }
251
- };
252
- // Activate what registered during session_start (eager MCP servers); pi would
253
- // otherwise leave only its four default built-ins active at turn 1.
254
- renarrow();
255
- session.subscribe((event) => {
256
- if (event.type === "turn_end")
257
- renarrow();
258
- });
259
- const priorBeforeToolCall = session.agent.beforeToolCall;
260
- session.agent.beforeToolCall = async (context, signal) => {
261
- if (!inScope().has(context.toolCall.name)) {
262
- return {
263
- block: true,
264
- reason: `Tool "${context.toolCall.name}" is not available to this subagent.`,
265
- };
266
- }
267
- return priorBeforeToolCall?.(context, signal);
268
- };
269
- }
270
- /** Default max turns. undefined = unlimited (no turn limit). */
271
- let defaultMaxTurns;
272
- /** Normalize max turns. undefined or 0 = unlimited, otherwise minimum 1. */
273
- export function normalizeMaxTurns(n) {
274
- if (n == null || n === 0)
275
- return undefined;
276
- return Math.max(1, n);
277
- }
278
- /** Get the default max turns value. undefined = unlimited. */
279
- export function getDefaultMaxTurns() { return defaultMaxTurns; }
280
- /** Set the default max turns value. undefined or 0 = unlimited, otherwise minimum 1. */
281
- export function setDefaultMaxTurns(n) { defaultMaxTurns = normalizeMaxTurns(n); }
282
- /**
283
- * The turn limit a run of `type` will actually enforce: an explicit value if the
284
- * caller supplied one, else the agent's own `max_turns`, else the project
285
- * default. `undefined` = unlimited.
286
- *
287
- * Exported because the widget's turn counter (`↻3≤20`) has to predict this
288
- * before the run starts, and a second copy of the expression would drift from
289
- * the one below that enforces it.
290
- */
291
- export function resolveEffectiveMaxTurns(type, explicit) {
292
- return normalizeMaxTurns(explicit ?? getAgentConfig(type)?.maxTurns ?? defaultMaxTurns);
293
- }
294
- /**
295
- * Project default for `persist_session`, from the `rememberAgents` setting.
296
- * On by default: a persisted session is what lets `@handle` reopen an agent's
297
- * conversation after its record has been evicted, which is the whole point of
298
- * addressing an agent by a name that outlives one run. Per-agent frontmatter
299
- * still overrides it in both directions.
300
- */
301
- let rememberAgents = true;
302
- /** Whether subagent sessions are persisted by default. */
303
- export function getRememberAgents() { return rememberAgents; }
304
- /** Set whether subagent sessions are persisted by default. */
305
- export function setRememberAgents(b) { rememberAgents = b; }
306
- /** Additional turns allowed after the soft limit steer message. */
307
- let graceTurns = 5;
308
- /** Get the grace turns value. */
309
- export function getGraceTurns() { return graceTurns; }
310
- /** Set the grace turns value (minimum 1). */
311
- export function setGraceTurns(n) { graceTurns = Math.max(1, n); }
312
- /**
313
- * Try to find the right model for an agent type.
314
- * Priority: explicit option > config.model > parent model.
315
- */
316
- export function resolveDefaultModel(parentModel, registry, configModel) {
317
- if (configModel) {
318
- const slashIdx = configModel.indexOf("/");
319
- if (slashIdx !== -1) {
320
- const provider = configModel.slice(0, slashIdx);
321
- const modelId = configModel.slice(slashIdx + 1);
322
- // Build a set of available model keys for fast lookup
323
- const available = registry.getAvailable?.();
324
- const availableKeys = available
325
- ? new Set(available.map((m) => `${m.provider}/${m.id}`))
326
- : undefined;
327
- const isAvailable = (p, id) => !availableKeys || availableKeys.has(`${p}/${id}`);
328
- const found = registry.find(provider, modelId);
329
- if (found && isAvailable(provider, modelId))
330
- return found;
331
- }
332
- }
333
- return parentModel;
334
- }
335
- /**
336
- * Subscribe to a session and collect the last assistant message text.
337
- * Returns an object with a `getText()` getter and an `unsubscribe` function.
338
- */
339
- function collectResponseText(session) {
340
- let text = "";
341
- const unsubscribe = session.subscribe((event) => {
342
- // message_start also fires for user and toolResult messages — resetting on
343
- // those would wipe assistant text already collected. Reset only when a new
344
- // ASSISTANT message begins, so getText() is the last assistant message's text.
345
- if (event.type === "message_start" && event.message.role === "assistant") {
346
- text = "";
347
- }
348
- if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
349
- text += event.assistantMessageEvent.delta;
350
- }
351
- });
352
- return { getText: () => text, unsubscribe };
353
- }
354
- /**
355
- * Get the last non-empty assistant text produced during THIS invocation.
356
- * `startIndex` is the message count captured before the prompt, so the walk-back
357
- * never crosses into a previous turn: on a resume whose new turn failed empty,
358
- * this returns "" instead of the prior turn's answer (#144). Defaults to 0 (a
359
- * fresh spawn, where the whole history belongs to this run).
360
- */
361
- function getLastAssistantText(session, startIndex = 0) {
362
- for (let i = session.messages.length - 1; i >= startIndex; i--) {
363
- const msg = session.messages[i];
364
- if (msg.role !== "assistant")
365
- continue;
366
- const text = extractText(msg.content).trim();
367
- if (text)
368
- return text;
369
- }
370
- return "";
371
- }
372
- /**
373
- * Error message of THIS invocation's final assistant message, when that turn
374
- * failed. Two failure shapes, both keyed off how the final turn STOPPED:
375
- * - stopReason "error": a provider failure pi resolved instead of rejecting
376
- * (any text; partial output is surfaced separately).
377
- * - stopReason "length" with NO text: a silent max-token death — the run hit
378
- * the output-token ceiling before writing anything, which would otherwise
379
- * land as a "completed" run with an empty result (the #144 symptom).
380
- * Everything else completes: a clean "stop"/"toolUse" final, and — crucially — a
381
- * "length" stop that DID produce text (a legitimate truncated-but-useful answer).
382
- * "aborted" is handled by the manager's abort flag / "stopped" guard, not here.
383
- * Bounded by `startIndex` (like the text fallback) so a resume that produced no
384
- * assistant message of its own never inherits a PRIOR turn's stop reason.
385
- */
386
- function finalTurnError(session, startIndex = 0) {
387
- for (let i = session.messages.length - 1; i >= startIndex; i--) {
388
- const msg = session.messages[i];
389
- if (msg.role !== "assistant")
390
- continue;
391
- if (msg.stopReason === "error") {
392
- return msg.errorMessage?.trim() || "provider error with no output";
393
- }
394
- if (msg.stopReason === "length" && !extractText(msg.content).trim()) {
395
- return "run hit the output token limit before producing any text";
396
- }
397
- return undefined;
398
- }
399
- return undefined;
400
- }
401
- /**
402
- * Wire an AbortSignal to abort a session.
403
- * Returns a cleanup function to remove the listener.
404
- */
405
- function forwardAbortSignal(session, signal) {
406
- if (!signal)
407
- return () => { };
408
- const onAbort = () => session.abort();
409
- signal.addEventListener("abort", onAbort, { once: true });
410
- return () => signal.removeEventListener("abort", onAbort);
411
- }
412
- function resolveConfiguredSessionDir(sessionDir, cwd) {
413
- if (!sessionDir)
414
- return undefined;
415
- if (sessionDir === "~" || sessionDir.startsWith("~/"))
416
- return resolve(homedir(), sessionDir.slice(2));
417
- if (isAbsolute(sessionDir))
418
- return sessionDir;
419
- return resolve(cwd, sessionDir);
420
- }
421
- export async function runAgent(ctx, type, prompt, options) {
422
- const config = getConfig(type);
423
- const agentConfig = getAgentConfig(type);
424
- // Resolve working directory: worktree override > parent cwd
425
- const effectiveCwd = options.cwd ?? ctx.cwd;
426
- // Filesystem work happens in effectiveCwd; config discovery in configCwd.
427
- // They differ only for SpawnOptions.cwd spawns (config stays with the parent).
428
- const configCwd = options.configCwd ?? effectiveCwd;
429
- const env = await detectEnv(options.pi, effectiveCwd);
430
- // Get parent system prompt for append-mode agents
431
- const parentSystemPrompt = ctx.getSystemPrompt();
432
- // Build prompt extras (memory, skill preloading)
433
- const extras = {};
434
- if (options.worktreeBase)
435
- extras.worktreeBase = options.worktreeBase;
436
- if (options.workflow && !options.structuredOutput)
437
- extras.workflowChild = true;
438
- // Resolve extensions/skills: isolated overrides to false
439
- const extensions = options.isolated ? false : config.extensions;
440
- // Nulling excludes under isolated also suppresses the orphaned-exclude warning —
441
- // isolation is an intentional override, not a misconfiguration.
442
- const excludeExtensions = options.isolated ? undefined : config.excludeExtensions;
443
- const skills = options.isolated ? false : config.skills;
444
- // Skill preloading: when skills is string[], preload their content into prompt
445
- if (Array.isArray(skills)) {
446
- const loaded = preloadSkills(skills, configCwd);
447
- if (loaded.length > 0) {
448
- extras.skillBlocks = loaded;
449
- }
450
- }
451
- let toolNames = getToolNamesForType(type);
452
- // Persistent memory: detect write capability and branch accordingly.
453
- // Account for disallowedTools — a tool in the base set but on the denylist is not truly available.
454
- if (agentConfig?.memory) {
455
- const existingNames = new Set(toolNames);
456
- const denied = agentConfig.disallowedTools ? new Set(agentConfig.disallowedTools) : undefined;
457
- const effectivelyHas = (name) => existingNames.has(name) && !denied?.has(name);
458
- const hasWriteTools = effectivelyHas("write") || effectivelyHas("edit");
459
- if (hasWriteTools) {
460
- // Read-write memory: add any missing memory tool names (read/write/edit)
461
- const extraNames = getMemoryToolNames(existingNames);
462
- if (extraNames.length > 0)
463
- toolNames = [...toolNames, ...extraNames];
464
- extras.memoryBlock = buildMemoryBlock(agentConfig.name, agentConfig.memory, configCwd);
465
- }
466
- else {
467
- // Read-only memory: only add read tool name, use read-only prompt
468
- const extraNames = getReadOnlyMemoryToolNames(existingNames);
469
- if (extraNames.length > 0)
470
- toolNames = [...toolNames, ...extraNames];
471
- extras.memoryBlock = buildReadOnlyMemoryBlock(agentConfig.name, agentConfig.memory, configCwd);
472
- }
473
- }
474
- // Build system prompt from agent config
475
- let systemPrompt;
476
- if (agentConfig) {
477
- systemPrompt = buildAgentPrompt(agentConfig, effectiveCwd, env, parentSystemPrompt, extras);
478
- }
479
- else {
480
- // Unknown type fallback: spread the canonical general-purpose config (defensive —
481
- // unreachable in practice since index.ts resolves unknown types before calling runAgent).
482
- const fallback = DEFAULT_AGENTS.get("general-purpose");
483
- if (!fallback)
484
- throw new Error(`No fallback config available for unknown type "${type}"`);
485
- systemPrompt = buildAgentPrompt({ ...fallback, name: type }, effectiveCwd, env, parentSystemPrompt, extras);
486
- }
487
- // When skills is string[], we've already preloaded them into the prompt.
488
- // Still pass noSkills: true since we don't need the skill loader to load them again.
489
- const noSkills = skills === false || Array.isArray(skills);
490
- const agentDir = getAgentDir();
491
- // Extension loading:
492
- // - true → all default-discovered extensions
493
- // - false → none (noExtensions)
494
- // - string[] → loader-level allowlist. Bare names keep the matching
495
- // default-discovered extension; path entries load that extension fresh;
496
- // "*" keeps all default-discovered extensions. Excluded extensions never
497
- // bind handlers or register tools (their factory still runs once).
498
- //
499
- // Suppress AGENTS.md/CLAUDE.md and APPEND_SYSTEM.md — upstream's
500
- // buildSystemPrompt() re-appends both AFTER systemPromptOverride, which
501
- // would defeat prompt_mode: replace and isolated: true. Parent context, if
502
- // wanted, reaches the subagent via prompt_mode: append (parentSystemPrompt
503
- // is embedded in systemPromptOverride) or inherit_context (conversation).
504
- // `ext:` selectors from the `tools:` CSV narrow which extension tools surface to
505
- // the LLM. They do NOT control loading — `extensions:` is the sole authority for
506
- // which extensions load. `ext:foo` against an extension that `extensions:` excluded
507
- // is an orphan and warns after reload. `isolated` means no extension tools at all.
508
- const { extNames, narrowing } = parseExtSelectors(options.isolated ? [] : (agentConfig?.extSelectors ?? []));
509
- const noExtensions = extensions === false;
510
- const extensionsSpec = Array.isArray(extensions)
511
- ? parseExtensionsSpec(extensions, configCwd)
512
- : undefined;
513
- const keepNames = extensionsSpec?.names ?? new Set();
514
- // `exclude_extensions:` is a denylist applied AFTER the include set — exclude wins.
515
- // Plain canonical names only (case-insensitive). Note: excluded extensions'
516
- // factories still run once during reload() (see comment above) — exclusion
517
- // suppresses handler binding and tool registration; it is not a sandbox.
518
- const excludeNames = new Set((excludeExtensions ?? []).map((n) => n.toLowerCase()));
519
- const hasExcludes = excludeNames.size > 0;
520
- // The override filters loaded extensions down to `keepNames` minus `excludeNames`.
521
- // It's only needed when we're neither loading everything without excludes
522
- // (`extensions: true` or a `"*"` wildcard) nor nothing (`noExtensions`).
523
- const loadAll = extensions === true || extensionsSpec?.wildcard === true;
524
- const additionalExtensionPaths = extensionsSpec?.paths.length ? extensionsSpec.paths : undefined;
525
- // Pre-filter discovered set, captured by the override — the exclude-typo warning
526
- // must compare against this, not the surviving set (absence from survivors is
527
- // an exclude *succeeding*).
528
- let discoveredNames;
529
- const extensionsOverride = noExtensions || (loadAll && !hasExcludes)
530
- ? undefined
531
- : (base) => {
532
- discoveredNames = new Set(base.extensions.flatMap((e) => extensionCanonicalNames(e.path)));
533
- return {
534
- ...base,
535
- extensions: base.extensions.filter((e) => {
536
- const canons = extensionCanonicalNames(e.path);
537
- if (canons.some((n) => excludeNames.has(n)))
538
- return false; // exclude wins
539
- return loadAll || canons.some((n) => keepNames.has(n));
540
- }),
541
- };
542
- };
543
- const loader = new DefaultResourceLoader({
544
- cwd: configCwd,
545
- agentDir,
546
- noExtensions,
547
- additionalExtensionPaths,
548
- extensionsOverride,
549
- noSkills,
550
- noPromptTemplates: true,
551
- noThemes: true,
552
- noContextFiles: true,
553
- systemPromptOverride: () => systemPrompt,
554
- appendSystemPromptOverride: () => [],
555
- });
556
- await runInChildSessionContext(() => loader.reload());
557
- // Plain entries in `tools:` are expected to be built-in names (extension tools
558
- // go through `ext:`), so an unknown name there is unambiguously a typo. Previously
559
- // this produced a silently broken agent (#75) — pi-mono accepted the bogus name
560
- // into the allowlist, then dropped it at registration with no signal back.
561
- if (agentConfig?.builtinToolNames?.length) {
562
- const knownBuiltins = new Set(BUILTIN_TOOL_NAMES);
563
- for (const name of agentConfig.builtinToolNames) {
564
- if (!knownBuiltins.has(name)) {
565
- options.onToolActivity?.({
566
- type: "end",
567
- toolName: `tools-error:tool "${name}" requested by agent "${type}" is not a known built-in`,
568
- });
569
- }
570
- }
571
- }
572
- // A subagent spawns mid-task, so a bad `extensions:`/`ext:` entry warns rather
573
- // than aborts. Two distinct misconfigurations to catch:
574
- // - `extensions: [foo]` but no extension named foo was discovered (typo or
575
- // path that failed to load — path entries fold their canonical name into
576
- // `keepNames`, so this covers them too).
577
- // - `tools: ext:foo` but foo isn't in the loaded set (because `extensions:`
578
- // didn't include it). Since v0.9, `ext:` no longer pulls extensions in;
579
- // loading is `extensions:`-authoritative.
580
- // An exclude_extensions: alongside extensions: false is contradictory — nothing
581
- // loads, so there is nothing to exclude.
582
- if (hasExcludes && noExtensions) {
583
- options.onToolActivity?.({
584
- type: "end",
585
- toolName: `extension-error:exclude_extensions has no effect for agent "${type}" — extensions: false loads nothing`,
586
- });
587
- }
588
- // Exclude typo check: compares against the PRE-filter discovered set (an excluded
589
- // name absent from the surviving set is the exclude working as intended). Also
590
- // flags path-like and "*" entries — excludes are plain names only.
591
- if (hasExcludes && discoveredNames) {
592
- for (const name of excludeNames) {
593
- if (!discoveredNames.has(name)) {
594
- options.onToolActivity?.({
595
- type: "end",
596
- toolName: `extension-error:exclude_extensions: "${name}" for agent "${type}" did not match any discovered extension`,
597
- });
598
- }
599
- }
600
- }
601
- if (keepNames.size > 0 || extNames.size > 0) {
602
- const survivingNames = new Set(loader.getExtensions().extensions.flatMap((e) => extensionCanonicalNames(e.path)));
603
- for (const name of keepNames) {
604
- if (!survivingNames.has(name)) {
605
- options.onToolActivity?.({
606
- type: "end",
607
- toolName: excludeNames.has(name)
608
- ? `extension-error:extension "${name}" is in both extensions: and exclude_extensions: for agent "${type}" — exclude wins`
609
- : `extension-error:extension "${name}" requested by agent "${type}" was not loaded`,
610
- });
611
- }
612
- }
613
- for (const name of extNames) {
614
- if (!survivingNames.has(name)) {
615
- options.onToolActivity?.({
616
- type: "end",
617
- toolName: `extension-error:ext:${name} referenced by agent "${type}" but extension "${name}" is not loaded (check extensions:/exclude_extensions:)`,
618
- });
619
- }
620
- }
621
- }
622
- // Resolve model: explicit option > config.model > parent model
623
- const model = options.model ?? resolveDefaultModel(ctx.model, ctx.modelRegistry, agentConfig?.model);
624
- // Resolve thinking level: explicit option > agent config > undefined (inherit)
625
- const thinkingLevel = options.thinkingLevel ?? agentConfig?.thinking;
626
- const disallowedSet = agentConfig?.disallowedTools
627
- ? new Set(agentConfig.disallowedTools)
628
- : undefined;
629
- // Nested delegation tools (opt-in, ownership-scoped). Empty unless the agent
630
- // set `allowed_subagents` and a nestedRuntime was provided — and never when
631
- // isolated. Their names collide with EXCLUDED_TOOL_NAMES by design, so the
632
- // scoping below re-admits them explicitly (registry deny + active-set narrow).
633
- const effectiveMaxDepth = options.nestedRuntime?.maxSubagentDepth ?? getMaxSubagentDepth();
634
- // At (or past) the cap this agent can never spawn, so it can never own a child
635
- // to fetch from or steer either — inject nothing rather than three tools whose
636
- // every call is an error. This is also what makes `maxSubagentDepth` 0/1 mean
637
- // "nesting off" instead of "nesting always fails".
638
- const nestedRuntime = options.nestedRuntime && options.nestedRuntime.depth < effectiveMaxDepth
639
- ? options.nestedRuntime
640
- : undefined;
641
- const nestedTools = agentConfig?.allowedSubagents && nestedRuntime && !options.isolated
642
- ? createNestedSubagentTools({
643
- manager: nestedRuntime.manager,
644
- pi: options.pi,
645
- parentAgentId: nestedRuntime.parentAgentId,
646
- depth: nestedRuntime.depth,
647
- maxSubagentDepth: effectiveMaxDepth,
648
- allowedSubagents: agentConfig.allowedSubagents,
649
- configCwd,
650
- })
651
- : [];
652
- const nestedToolNames = new Set(nestedTools.map(tool => tool.name));
653
- // The `agent({ schema })` contract: this child reports its answer by calling
654
- // StructuredOutput, and `structuredJson` below is what the caller reads. The
655
- // schema was already compiled by whoever asked for it, so a bad one failed
656
- // before any of this ran.
657
- const structuredCapture = options.structuredOutput ? createStructuredCapture() : undefined;
658
- const structuredTools = options.structuredOutput && structuredCapture
659
- ? [createStructuredOutputTool(options.structuredOutput, structuredCapture)]
660
- : [];
661
- const structuredToolNames = new Set(structuredTools.map(tool => tool.name));
662
- // Re-admitted together at every gate below. Kept as one set so a new injected
663
- // tool cannot be added to some of the three gates and forgotten at the rest.
664
- //
665
- // `disallowed_tools` is applied HERE rather than at the gates, because the two
666
- // kinds answer to it differently: a nested delegation tool is an opt-in the
667
- // agent's own frontmatter can take back, while StructuredOutput exists only
668
- // because this call asked for a schema — removing it would make the request
669
- // unsatisfiable by construction rather than merely restricted.
670
- const readmitToolNames = new Set([
671
- ...[...nestedToolNames].filter(name => !disallowedSet?.has(name)),
672
- ...structuredToolNames,
673
- ]);
674
- // ─── Tool scoping ───────────────────────────────────────────────────────
675
- //
676
- // Some extensions register their tools ASYNCHRONOUSLY, long after the
677
- // `loader.reload()` above: pi-mcp calls registerTool from `session_start`
678
- // (once its MCP servers connect), context-mode from `before_agent_start`.
679
- // That is deliberate on their part — eagerly spawning an MCP bridge during
680
- // extension discovery orphans child processes on pi's non-agent code paths
681
- // (--help, config, trust probing).
682
- //
683
- // So the tool set cannot be snapshotted here. pi's `allowedToolNames` gates
684
- // tool *registration* (`_refreshToolRegistry`'s `isAllowedTool`), not merely
685
- // the active set, and is frozen at construction — a name absent from the
686
- // snapshot is dropped forever, even once the tool actually registers (#125).
687
- //
688
- // Whenever extensions are in play we therefore:
689
- // - leave `allowedToolNames` unset, so pi's live gate admits tools whenever
690
- // they register;
691
- // - express the name-stable, permanent part of the scope (our own
692
- // orchestration tools, built-ins the agent didn't ask for, and
693
- // `disallowedTools`) as `excludeTools`, which pi re-applies on every
694
- // registry refresh;
695
- // - enforce `ext:` narrowing on the ACTIVE set via the live `inScope()`
696
- // predicate installed after bind — the active set is what the LLM sees,
697
- // so a registry tool that is never activated is invisible and uncallable.
698
- //
699
- // `noExtensions`/`isolated` keeps the historical static allowlist: nothing
700
- // async can appear there, and a hard registry gate is the correct boundary.
701
- const builtinToolNameSet = new Set(toolNames);
702
- let sessionTools;
703
- let sessionExcludeTools;
704
- if (noExtensions) {
705
- // Strict allowlist: built-ins the agent asked for, plus any opt-in nested
706
- // tools (whose names would otherwise be dropped as EXCLUDED_TOOL_NAMES).
707
- sessionTools = [
708
- ...toolNames.filter((t) => !EXCLUDED_TOOL_NAMES.includes(t) && !disallowedSet?.has(t)),
709
- ...[...nestedToolNames].filter((t) => !disallowedSet?.has(t)),
710
- // Not filtered through `disallowedSet`, unlike the nested tools above:
711
- // the caller asked for a schema, and removing the only tool that can
712
- // satisfy it would make the request unsatisfiable by construction rather
713
- // than merely restricted.
714
- ...structuredToolNames,
715
- ];
716
- }
717
- else {
718
- // Deny the orchestration tools EXCEPT the nested ones this agent opted into —
719
- // those are injected as customTools and must survive the registry gate.
720
- const denyTools = new Set(EXCLUDED_TOOL_NAMES.filter((t) => !nestedToolNames.has(t)));
721
- // Keep only the built-ins the agent asked for — deny the rest.
722
- for (const name of BUILTIN_TOOL_NAMES) {
723
- if (!builtinToolNameSet.has(name))
724
- denyTools.add(name);
725
- }
726
- if (disallowedSet) {
727
- // disallowed_tools wins even over an opt-in nested tool of the same name.
728
- // Not over StructuredOutput, though — see the allowlist branch above.
729
- for (const name of disallowedSet) {
730
- if (!structuredToolNames.has(name))
731
- denyTools.add(name);
732
- }
733
- }
734
- sessionExcludeTools = [...denyTools];
735
- }
736
- const settingsManager = SettingsManager.create(configCwd, agentDir);
737
- const configuredSessionDir = resolveConfiguredSessionDir(agentConfig?.sessionDir, effectiveCwd);
738
- const defaultSessionDir = process.env.PI_CODING_AGENT_SESSION_DIR ?? settingsManager.getSessionDir?.();
739
- // Frontmatter wins when it says anything; otherwise the project default,
740
- // which `rememberAgents` supplies for top-level agents only. Same precedence
741
- // as `outputTranscript`.
742
- const persistSession = agentConfig?.persistSession ?? (options.nested ? false : rememberAgents);
743
- const sessionManager = options.resumeSessionFile
744
- // Reopening an existing conversation: the file already carries its own
745
- // header (cwd, parent) and history, so none of the create-time options
746
- // apply. `sessionDir` still matters for a later /new or /branch off it.
747
- ? SessionManager.open(options.resumeSessionFile, configuredSessionDir ?? defaultSessionDir)
748
- : persistSession
749
- ? SessionManager.create(effectiveCwd, configuredSessionDir ?? defaultSessionDir, {
750
- // Optional metadata — it only nests the subagent under its spawner in
751
- // `/resume`. Until `rememberAgents` this ran solely for the rare
752
- // `persist_session: true` agent; now it runs for every spawn, so a
753
- // context without a session manager (a bare programmatic ctx) must
754
- // still persist rather than take the whole spawn down.
755
- parentSession: ctx.sessionManager?.getSessionFile?.(),
756
- })
757
- : SessionManager.inMemory(effectiveCwd);
758
- // Pi 0.80.8 replaced createAgentSession's modelRegistry option with
759
- // modelRuntime, but ExtensionContext still exposes only the registry facade.
760
- // Pass both so the full supported Pi range retains the parent's providers.
761
- const parentModelRuntime = ctx.modelRegistry.runtime;
762
- const sessionOpts = {
763
- cwd: effectiveCwd,
764
- agentDir,
765
- sessionManager,
766
- settingsManager,
767
- modelRegistry: ctx.modelRegistry,
768
- // `as never` is what keeps this assignable across the supported Pi range:
769
- // pre-0.80.8 the field exists only via the `modelRuntime?: unknown` shim
770
- // above, while newer Pi types it as `ModelRuntime` — a shape an opaque
771
- // `unknown` read off the private facade field can never satisfy.
772
- ...(parentModelRuntime !== undefined && { modelRuntime: parentModelRuntime }),
773
- model,
774
- tools: sessionTools,
775
- customTools: [...nestedTools, ...structuredTools],
776
- resourceLoader: loader,
777
- };
778
- if (sessionExcludeTools) {
779
- sessionOpts.excludeTools = sessionExcludeTools;
780
- }
781
- if (thinkingLevel) {
782
- sessionOpts.thinkingLevel = thinkingLevel;
783
- }
784
- const { session } = await runInChildSessionContext(() => createAgentSession(sessionOpts));
785
- const baseSessionName = agentConfig?.name ?? type;
786
- session.setSessionName(options.agentId ? `${baseSessionName}#${options.agentId.slice(0, 8)}` : baseSessionName);
787
- // Bind extensions so that session_start fires and extensions can initialize
788
- // (e.g. loading credentials, setting up state). Tool gating already happened
789
- // at session construction via the `tools:` allowlist above — no separate
790
- // post-bind filter is needed. All ExtensionBindings fields are optional.
791
- await session.bindExtensions({
792
- onError: (err) => {
793
- options.onToolActivity?.({
794
- type: "end",
795
- toolName: `extension-error:${err.extensionPath}`,
796
- });
797
- },
798
- });
799
- // With `allowedToolNames` unset, the registry is scoped by `excludeTools` but
800
- // the ACTIVE set still needs managing: pi activates only its four default
801
- // built-ins at turn 1, and `ext:` narrowing has no registry-level expression
802
- // (we can't deny the name of a tool that hasn't registered yet). Both are
803
- // handled below by re-deriving scope from the loader's live extension maps —
804
- // `registerTool` writes into those same maps, so late arrivals are judged too.
805
- if (!noExtensions) {
806
- installExtensionToolScope(session, {
807
- loader,
808
- toolNames,
809
- disallowedSet,
810
- extNames,
811
- narrowing,
812
- readmitToolNames,
813
- });
814
- }
815
- options.onSessionCreated?.(session);
816
- // Track turns for graceful max_turns enforcement
817
- let turnCount = 0;
818
- const maxTurns = resolveEffectiveMaxTurns(type, options.maxTurns);
819
- let softLimitReached = false;
820
- let aborted = false;
821
- let currentMessageText = "";
822
- const unsubTurns = session.subscribe((event) => {
823
- if (event.type === "turn_end") {
824
- turnCount++;
825
- options.onTurnEnd?.(turnCount);
826
- if (maxTurns != null) {
827
- if (!softLimitReached && turnCount >= maxTurns) {
828
- softLimitReached = true;
829
- session.steer("You have reached your turn limit. Wrap up immediately — provide your final answer now.");
830
- }
831
- else if (softLimitReached && turnCount >= maxTurns + graceTurns) {
832
- aborted = true;
833
- session.abort();
834
- }
835
- }
836
- }
837
- if (event.type === "message_start") {
838
- currentMessageText = "";
839
- }
840
- if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
841
- currentMessageText += event.assistantMessageEvent.delta;
842
- options.onTextDelta?.(event.assistantMessageEvent.delta, currentMessageText);
843
- }
844
- if (event.type === "tool_execution_start") {
845
- options.onToolActivity?.({ type: "start", toolName: event.toolName });
846
- }
847
- if (event.type === "tool_execution_end") {
848
- options.onToolActivity?.({ type: "end", toolName: event.toolName });
849
- }
850
- if (event.type === "message_end" && event.message.role === "assistant") {
851
- const u = event.message.usage;
852
- if (u)
853
- options.onAssistantUsage?.({
854
- input: u.input ?? 0,
855
- output: u.output ?? 0,
856
- cacheWrite: u.cacheWrite ?? 0,
857
- cacheRead: u.cacheRead ?? 0,
858
- cost: u.cost?.total ?? 0,
859
- });
860
- }
861
- if (event.type === "compaction_end" && !event.aborted && event.result) {
862
- options.onCompaction?.({ reason: event.reason, tokensBefore: event.result.tokensBefore });
863
- }
864
- });
865
- const collector = collectResponseText(session);
866
- const cleanupAbort = forwardAbortSignal(session, options.signal);
867
- // Build the effective prompt: optionally prepend parent context
868
- let effectivePrompt = prompt;
869
- if (options.inheritContext) {
870
- const parentContext = buildParentContext(ctx);
871
- if (parentContext) {
872
- effectivePrompt = parentContext + prompt;
873
- }
874
- }
875
- // Boundary for the history fallback: only assistant text produced from here
876
- // on counts as this run's output (a fresh session, so usually 0).
877
- const startLen = session.messages.length;
878
- let structuredRetried = false;
879
- try {
880
- await session.prompt(effectivePrompt);
881
- // One more prompt when a schema was asked for and nothing usable came back
882
- // — the model answered in prose, or only ever called the tool invalidly.
883
- // Inside this `try`, so the turn tracking, the text collector and above all
884
- // the abort forwarding are still live: torn down first, a retry would be
885
- // unkillable.
886
- if (structuredCapture !== undefined && structuredCapture.json === undefined
887
- && !aborted && options.signal?.aborted !== true) {
888
- structuredRetried = true;
889
- await session.prompt(structuredRetryPrompt(structuredCapture));
890
- }
891
- }
892
- finally {
893
- unsubTurns();
894
- collector.unsubscribe();
895
- cleanupAbort();
896
- }
897
- const responseText = collector.getText().trim() || getLastAssistantText(session, startLen);
898
- // A child asked for structured output that never gave any has failed, however
899
- // articulate its prose was. Reported through `failure` so it travels the same
900
- // path as a provider error rather than arriving as a successful empty answer.
901
- const structuredFailure = structuredCapture !== undefined && structuredCapture.json === undefined
902
- ? structuredCapture.lastError !== undefined
903
- ? `The agent's StructuredOutput call did not match the required schema: ${structuredCapture.lastError}`
904
- : "The agent did not report its answer through StructuredOutput."
905
- : undefined;
906
- return {
907
- responseText,
908
- session,
909
- aborted,
910
- steered: softLimitReached,
911
- failure: finalTurnError(session, startLen) ?? structuredFailure,
912
- ...(structuredCapture?.json !== undefined ? { structuredJson: structuredCapture.json } : {}),
913
- ...(structuredRetried ? { structuredRetried } : {}),
914
- };
915
- }
916
- /**
917
- * Send a new prompt to an existing session (resume).
918
- */
919
- export async function resumeAgent(session, prompt, options = {}) {
920
- // Boundary for the history fallback: the session already holds prior turns,
921
- // so only assistant text produced by THIS resume prompt counts as its output
922
- // — a failed resume must not surface the previous turn's answer (#144).
923
- const startLen = session.messages.length;
924
- const collector = collectResponseText(session);
925
- const cleanupAbort = forwardAbortSignal(session, options.signal);
926
- const unsubEvents = (options.onToolActivity || options.onAssistantUsage || options.onCompaction)
927
- ? session.subscribe((event) => {
928
- if (event.type === "tool_execution_start")
929
- options.onToolActivity?.({ type: "start", toolName: event.toolName });
930
- if (event.type === "tool_execution_end")
931
- options.onToolActivity?.({ type: "end", toolName: event.toolName });
932
- if (event.type === "message_end" && event.message.role === "assistant") {
933
- const u = event.message.usage;
934
- if (u)
935
- options.onAssistantUsage?.({
936
- input: u.input ?? 0,
937
- output: u.output ?? 0,
938
- cacheWrite: u.cacheWrite ?? 0,
939
- cacheRead: u.cacheRead ?? 0,
940
- cost: u.cost?.total ?? 0,
941
- });
942
- }
943
- if (event.type === "compaction_end" && !event.aborted && event.result) {
944
- options.onCompaction?.({ reason: event.reason, tokensBefore: event.result.tokensBefore });
945
- }
946
- })
947
- : () => { };
948
- try {
949
- await session.prompt(prompt);
950
- }
951
- finally {
952
- collector.unsubscribe();
953
- unsubEvents();
954
- cleanupAbort();
955
- }
956
- return {
957
- text: collector.getText().trim() || getLastAssistantText(session, startLen),
958
- failure: finalTurnError(session, startLen),
959
- };
960
- }
961
- /**
962
- * Send a steering message to a running subagent.
963
- * The message will interrupt the agent after its current tool execution.
964
- */
965
- export async function steerAgent(session, message) {
966
- await session.steer(message);
967
- }
968
- /**
969
- * Get the subagent's conversation messages as formatted text.
970
- */
971
- export function getAgentConversation(session) {
972
- const parts = [];
973
- for (const msg of session.messages) {
974
- if (msg.role === "user") {
975
- const text = typeof msg.content === "string"
976
- ? msg.content
977
- : extractText(msg.content);
978
- if (text.trim())
979
- parts.push(`[User]: ${text.trim()}`);
980
- }
981
- else if (msg.role === "assistant") {
982
- const textParts = [];
983
- const toolCalls = [];
984
- for (const c of msg.content) {
985
- if (c.type === "text" && c.text)
986
- textParts.push(c.text);
987
- else if (c.type === "toolCall")
988
- toolCalls.push(` Tool: ${c.name ?? c.toolName ?? "unknown"}`);
989
- }
990
- if (textParts.length > 0)
991
- parts.push(`[Assistant]: ${textParts.join("\n")}`);
992
- if (toolCalls.length > 0)
993
- parts.push(`[Tool Calls]:\n${toolCalls.join("\n")}`);
994
- }
995
- else if (msg.role === "toolResult") {
996
- const text = extractText(msg.content);
997
- const truncated = text.length > 200 ? text.slice(0, 200) + "..." : text;
998
- parts.push(`[Tool Result (${msg.toolName})]: ${truncated}`);
999
- }
1000
- }
1001
- return parts.join("\n\n");
1002
- }
1003
- //# sourceMappingURL=agent-runner.js.map