@ashx-j/lunr-dev 0.2.19-dev.10.1 → 0.2.21-dev.12.1

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 (307) hide show
  1. package/CHANGELOG.md +36 -1
  2. package/README.md +2 -2
  3. package/dist/builtin-extensions/index.d.ts.map +1 -1
  4. package/dist/builtin-extensions/index.js +0 -2
  5. package/dist/builtin-extensions/index.js.map +1 -1
  6. package/dist/builtin-extensions/lunr-computer-use.d.ts.map +1 -1
  7. package/dist/builtin-extensions/lunr-computer-use.js +15 -14
  8. package/dist/builtin-extensions/lunr-computer-use.js.map +1 -1
  9. package/dist/builtin-extensions/lunr-todos.d.ts +6 -5
  10. package/dist/builtin-extensions/lunr-todos.d.ts.map +1 -1
  11. package/dist/builtin-extensions/lunr-todos.js +9 -7
  12. package/dist/builtin-extensions/lunr-todos.js.map +1 -1
  13. package/dist/builtin-extensions/pi-intercom/broker/spawn.d.ts +6 -4
  14. package/dist/builtin-extensions/pi-intercom/broker/spawn.d.ts.map +1 -1
  15. package/dist/builtin-extensions/pi-intercom/broker/spawn.js +114 -61
  16. package/dist/builtin-extensions/pi-intercom/broker/spawn.js.map +1 -1
  17. package/dist/builtin-extensions/pi-intercom/index.d.ts.map +1 -1
  18. package/dist/builtin-extensions/pi-intercom/index.js +360 -351
  19. package/dist/builtin-extensions/pi-intercom/index.js.map +1 -1
  20. package/dist/builtin-extensions/pi-subagents/src/extension/fanout-child.d.ts.map +1 -1
  21. package/dist/builtin-extensions/pi-subagents/src/extension/fanout-child.js +2 -2
  22. package/dist/builtin-extensions/pi-subagents/src/extension/fanout-child.js.map +1 -1
  23. package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts +8 -6
  24. package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts.map +1 -1
  25. package/dist/builtin-extensions/pi-subagents/src/extension/index.js +128 -57
  26. package/dist/builtin-extensions/pi-subagents/src/extension/index.js.map +1 -1
  27. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts +18 -8
  28. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts.map +1 -1
  29. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js +38 -13
  30. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js.map +1 -1
  31. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts +4 -3
  32. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts.map +1 -1
  33. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js +24 -14
  34. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js.map +1 -1
  35. package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.d.ts +8 -1
  36. package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.d.ts.map +1 -1
  37. package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.js +247 -18
  38. package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.js.map +1 -1
  39. package/dist/builtin-extensions/pi-subagents/src/intercom/result-intercom.d.ts +1 -0
  40. package/dist/builtin-extensions/pi-subagents/src/intercom/result-intercom.d.ts.map +1 -1
  41. package/dist/builtin-extensions/pi-subagents/src/intercom/result-intercom.js +1 -1
  42. package/dist/builtin-extensions/pi-subagents/src/intercom/result-intercom.js.map +1 -1
  43. package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-ask.d.ts +29 -0
  44. package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-ask.d.ts.map +1 -0
  45. package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-ask.js +179 -0
  46. package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-ask.js.map +1 -0
  47. package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-questions.d.ts +89 -0
  48. package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-questions.d.ts.map +1 -0
  49. package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-questions.js +541 -0
  50. package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-questions.js.map +1 -0
  51. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.d.ts +11 -1
  52. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.d.ts.map +1 -1
  53. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js +38 -12
  54. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js.map +1 -1
  55. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-job-tracker.d.ts.map +1 -1
  56. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-job-tracker.js +3 -2
  57. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-job-tracker.js.map +1 -1
  58. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.d.ts +2 -1
  59. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.d.ts.map +1 -1
  60. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.js +35 -8
  61. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.js.map +1 -1
  62. package/dist/builtin-extensions/pi-subagents/src/runs/background/notify.d.ts +7 -3
  63. package/dist/builtin-extensions/pi-subagents/src/runs/background/notify.d.ts.map +1 -1
  64. package/dist/builtin-extensions/pi-subagents/src/runs/background/notify.js +26 -4
  65. package/dist/builtin-extensions/pi-subagents/src/runs/background/notify.js.map +1 -1
  66. package/dist/builtin-extensions/pi-subagents/src/runs/background/result-watcher.d.ts +1 -0
  67. package/dist/builtin-extensions/pi-subagents/src/runs/background/result-watcher.d.ts.map +1 -1
  68. package/dist/builtin-extensions/pi-subagents/src/runs/background/result-watcher.js +55 -38
  69. package/dist/builtin-extensions/pi-subagents/src/runs/background/result-watcher.js.map +1 -1
  70. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.d.ts +100 -0
  71. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.d.ts.map +1 -1
  72. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js +46 -31
  73. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js.map +1 -1
  74. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-wait.d.ts +3 -6
  75. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-wait.d.ts.map +1 -1
  76. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-wait.js +64 -5
  77. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-wait.js.map +1 -1
  78. package/dist/builtin-extensions/pi-subagents/src/runs/background/top-level-async.d.ts +15 -2
  79. package/dist/builtin-extensions/pi-subagents/src/runs/background/top-level-async.d.ts.map +1 -1
  80. package/dist/builtin-extensions/pi-subagents/src/runs/background/top-level-async.js +14 -4
  81. package/dist/builtin-extensions/pi-subagents/src/runs/background/top-level-async.js.map +1 -1
  82. package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.d.ts.map +1 -1
  83. package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.js +2 -1
  84. package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.js.map +1 -1
  85. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.d.ts.map +1 -1
  86. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.js +21 -8
  87. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.js.map +1 -1
  88. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.d.ts.map +1 -1
  89. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js +1 -1
  90. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js.map +1 -1
  91. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts +0 -1
  92. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts.map +1 -1
  93. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +71 -25
  94. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js.map +1 -1
  95. package/dist/builtin-extensions/pi-subagents/src/runs/shared/acceptance.d.ts +2 -0
  96. package/dist/builtin-extensions/pi-subagents/src/runs/shared/acceptance.d.ts.map +1 -1
  97. package/dist/builtin-extensions/pi-subagents/src/runs/shared/acceptance.js +75 -18
  98. package/dist/builtin-extensions/pi-subagents/src/runs/shared/acceptance.js.map +1 -1
  99. package/dist/builtin-extensions/pi-subagents/src/runs/shared/completion-guard.d.ts +1 -1
  100. package/dist/builtin-extensions/pi-subagents/src/runs/shared/completion-guard.d.ts.map +1 -1
  101. package/dist/builtin-extensions/pi-subagents/src/runs/shared/completion-guard.js +1 -1
  102. package/dist/builtin-extensions/pi-subagents/src/runs/shared/completion-guard.js.map +1 -1
  103. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.d.ts +13 -1
  104. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.d.ts.map +1 -1
  105. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.js +67 -11
  106. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.js.map +1 -1
  107. package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.d.ts +1 -0
  108. package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.d.ts.map +1 -1
  109. package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.js.map +1 -1
  110. package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.d.ts +3 -0
  111. package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.d.ts.map +1 -1
  112. package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.js +7 -2
  113. package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.js.map +1 -1
  114. package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.d.ts.map +1 -1
  115. package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.js +13 -3
  116. package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.js.map +1 -1
  117. package/dist/builtin-extensions/pi-subagents/src/runs/shared/task-intent.d.ts +2 -2
  118. package/dist/builtin-extensions/pi-subagents/src/runs/shared/task-intent.d.ts.map +1 -1
  119. package/dist/builtin-extensions/pi-subagents/src/runs/shared/task-intent.js +5 -10
  120. package/dist/builtin-extensions/pi-subagents/src/runs/shared/task-intent.js.map +1 -1
  121. package/dist/builtin-extensions/pi-subagents/src/shared/async-guidance.d.ts +2 -0
  122. package/dist/builtin-extensions/pi-subagents/src/shared/async-guidance.d.ts.map +1 -0
  123. package/dist/builtin-extensions/pi-subagents/src/shared/async-guidance.js +3 -0
  124. package/dist/builtin-extensions/pi-subagents/src/shared/async-guidance.js.map +1 -0
  125. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.d.ts +3 -0
  126. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.d.ts.map +1 -1
  127. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.js +68 -11
  128. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.js.map +1 -1
  129. package/dist/builtin-extensions/pi-subagents/src/shared/formatters.d.ts +12 -1
  130. package/dist/builtin-extensions/pi-subagents/src/shared/formatters.d.ts.map +1 -1
  131. package/dist/builtin-extensions/pi-subagents/src/shared/formatters.js +21 -2
  132. package/dist/builtin-extensions/pi-subagents/src/shared/formatters.js.map +1 -1
  133. package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts +21 -4
  134. package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts.map +1 -1
  135. package/dist/builtin-extensions/pi-subagents/src/shared/types.js +1 -1
  136. package/dist/builtin-extensions/pi-subagents/src/shared/types.js.map +1 -1
  137. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-adapters.d.ts.map +1 -1
  138. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-adapters.js.map +1 -1
  139. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.d.ts +7 -0
  140. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.d.ts.map +1 -1
  141. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.js +11 -7
  142. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.js.map +1 -1
  143. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts +6 -0
  144. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts.map +1 -1
  145. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js +46 -29
  146. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js.map +1 -1
  147. package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts +46 -4
  148. package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts.map +1 -1
  149. package/dist/builtin-extensions/pi-subagents/src/tui/render.js +407 -450
  150. package/dist/builtin-extensions/pi-subagents/src/tui/render.js.map +1 -1
  151. package/dist/builtin-extensions/pi-subagents/src/watchdog/register-main.d.ts.map +1 -1
  152. package/dist/builtin-extensions/pi-subagents/src/watchdog/register-main.js +1 -1
  153. package/dist/builtin-extensions/pi-subagents/src/watchdog/register-main.js.map +1 -1
  154. package/dist/builtin-extensions/pi-subagents/src/watchdog/tool-actions.d.ts +2 -13
  155. package/dist/builtin-extensions/pi-subagents/src/watchdog/tool-actions.d.ts.map +1 -1
  156. package/dist/builtin-extensions/pi-subagents/src/watchdog/tool-actions.js +5 -91
  157. package/dist/builtin-extensions/pi-subagents/src/watchdog/tool-actions.js.map +1 -1
  158. package/dist/core/computer-use/image.d.ts +26 -0
  159. package/dist/core/computer-use/image.d.ts.map +1 -0
  160. package/dist/core/computer-use/image.js +64 -0
  161. package/dist/core/computer-use/image.js.map +1 -0
  162. package/dist/core/computer-use/policy.d.ts.map +1 -1
  163. package/dist/core/computer-use/policy.js +2 -6
  164. package/dist/core/computer-use/policy.js.map +1 -1
  165. package/dist/core/computer-use/schemas.d.ts +13 -10
  166. package/dist/core/computer-use/schemas.d.ts.map +1 -1
  167. package/dist/core/computer-use/schemas.js +26 -35
  168. package/dist/core/computer-use/schemas.js.map +1 -1
  169. package/dist/core/computer-use/workflow.d.ts +16 -8
  170. package/dist/core/computer-use/workflow.d.ts.map +1 -1
  171. package/dist/core/computer-use/workflow.js +271 -260
  172. package/dist/core/computer-use/workflow.js.map +1 -1
  173. package/dist/core/customize.d.ts +2 -0
  174. package/dist/core/customize.d.ts.map +1 -1
  175. package/dist/core/customize.js +3 -0
  176. package/dist/core/customize.js.map +1 -1
  177. package/dist/core/permissions.d.ts +1 -0
  178. package/dist/core/permissions.d.ts.map +1 -1
  179. package/dist/core/permissions.js +8 -4
  180. package/dist/core/permissions.js.map +1 -1
  181. package/dist/core/plan-mode.d.ts.map +1 -1
  182. package/dist/core/plan-mode.js +0 -5
  183. package/dist/core/plan-mode.js.map +1 -1
  184. package/dist/core/runtime-bridges.d.ts.map +1 -1
  185. package/dist/core/runtime-bridges.js +0 -2
  186. package/dist/core/runtime-bridges.js.map +1 -1
  187. package/dist/core/settings-manager.d.ts +4 -0
  188. package/dist/core/settings-manager.d.ts.map +1 -1
  189. package/dist/core/settings-manager.js +11 -0
  190. package/dist/core/settings-manager.js.map +1 -1
  191. package/dist/core/subagent-cancellation.d.ts +21 -0
  192. package/dist/core/subagent-cancellation.d.ts.map +1 -0
  193. package/dist/core/subagent-cancellation.js +53 -0
  194. package/dist/core/subagent-cancellation.js.map +1 -0
  195. package/dist/core/subagent-spinner-setting.d.ts +6 -0
  196. package/dist/core/subagent-spinner-setting.d.ts.map +1 -0
  197. package/dist/core/subagent-spinner-setting.js +12 -0
  198. package/dist/core/subagent-spinner-setting.js.map +1 -0
  199. package/dist/core/subagent-spinner.d.ts +4 -0
  200. package/dist/core/subagent-spinner.d.ts.map +1 -0
  201. package/dist/core/subagent-spinner.js +6 -0
  202. package/dist/core/subagent-spinner.js.map +1 -0
  203. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  204. package/dist/modes/interactive/components/assistant-message.js +12 -18
  205. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  206. package/dist/modes/interactive/components/settings-selector.d.ts +4 -0
  207. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  208. package/dist/modes/interactive/components/settings-selector.js +73 -1
  209. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  210. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  211. package/dist/modes/interactive/components/tool-execution.js +12 -0
  212. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  213. package/dist/modes/interactive/extension-widget-order.d.ts +8 -0
  214. package/dist/modes/interactive/extension-widget-order.d.ts.map +1 -0
  215. package/dist/modes/interactive/extension-widget-order.js +37 -0
  216. package/dist/modes/interactive/extension-widget-order.js.map +1 -0
  217. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  218. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  219. package/dist/modes/interactive/interactive-mode.js +44 -22
  220. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  221. package/dist/node-runtime/{agent-session-services-RSGP5GDN.js → agent-session-services-QANFGM2V.js} +14 -13
  222. package/dist/node-runtime/{builtin-extensions-7STLFW3A.js → builtin-extensions-SRCYQPZ6.js} +4 -3
  223. package/dist/node-runtime/{chunk-5OLJGVCB.js → chunk-3ONQTOMR.js} +2 -2
  224. package/dist/node-runtime/chunk-5ZH3ZFIZ.js +308 -0
  225. package/dist/node-runtime/{chunk-4SJWFTUP.js → chunk-7NBZ5P7I.js} +1 -1
  226. package/dist/node-runtime/chunk-A3KMVBZV.js +60 -0
  227. package/dist/node-runtime/{chunk-FLYMHKCS.js → chunk-BJ6H7DPI.js} +25 -25
  228. package/dist/node-runtime/{chunk-T5GM5BFH.js → chunk-BYQ2MOFI.js} +6 -6
  229. package/dist/node-runtime/{chunk-W7S2REEG.js → chunk-CZUBYPFP.js} +157 -74
  230. package/dist/node-runtime/{chunk-ZRDIMBEQ.js → chunk-D466UAID.js} +9 -6
  231. package/dist/node-runtime/{chunk-K72NVGUB.js → chunk-GT5F3OKM.js} +1 -1
  232. package/dist/node-runtime/chunk-H2BI7G7T.js +73 -0
  233. package/dist/node-runtime/{chunk-ISQDQIZN.js → chunk-HXJS2PJM.js} +2 -2
  234. package/dist/node-runtime/chunk-LISUTZS3.js +19 -0
  235. package/dist/node-runtime/{chunk-BKAZ6BKX.js → chunk-LOYUC2ID.js} +7 -7
  236. package/dist/node-runtime/{chunk-OTT6JMPU.js → chunk-LTYWTR3V.js} +1 -369
  237. package/dist/node-runtime/{chunk-5Q45AVQG.js → chunk-MW2XJZIK.js} +1 -1
  238. package/dist/node-runtime/{chunk-MUMMMTW4.js → chunk-N3PNL74S.js} +536 -265
  239. package/dist/node-runtime/{chunk-HQCKFM2O.js → chunk-VGYZ3APQ.js} +3 -0
  240. package/dist/node-runtime/{chunk-5NWQCSKR.js → chunk-VQ4UBWSA.js} +11 -1
  241. package/dist/node-runtime/{chunk-6SPPH4FY.js → chunk-VTGEKB7R.js} +4 -4
  242. package/dist/node-runtime/chunk-W3SILANP.js +24 -0
  243. package/dist/node-runtime/{chunk-J7QGQD45.js → chunk-WJVFOIB5.js} +1 -1
  244. package/dist/node-runtime/{chunk-JT6YCS5B.js → chunk-XAUQOKYK.js} +408 -45
  245. package/dist/node-runtime/{chunk-LCACDWHJ.js → chunk-XSRCAQK2.js} +13 -13
  246. package/dist/node-runtime/{chunk-TAP7QTUT.js → chunk-ZOIIMEN6.js} +24 -425
  247. package/dist/node-runtime/{chunk-MGSB2C3M.js → chunk-ZVSORYRM.js} +1 -1
  248. package/dist/node-runtime/{command-6UXQ6XZN.js → command-ZURZJDXF.js} +1 -1
  249. package/dist/node-runtime/{commands-LGR5VT5X.js → commands-BZGSLIP7.js} +3 -3
  250. package/dist/node-runtime/{customize-XEXL2DGQ.js → customize-LF5VST47.js} +1 -1
  251. package/dist/node-runtime/{direct-tool-executor-TDJS7TBD.js → direct-tool-executor-BSZDHIYR.js} +4 -4
  252. package/dist/node-runtime/{extract-IUCVZCWC.js → extract-XLQSJN4V.js} +2 -2
  253. package/dist/node-runtime/{gateway-3OLC4GQN.js → gateway-FWHRIBK5.js} +9 -9
  254. package/dist/node-runtime/{gemini-search-NCIDF7NE.js → gemini-search-U7SUMPQA.js} +1 -1
  255. package/dist/node-runtime/{gemini-url-context-OKIN7AIP.js → gemini-url-context-PXWCBQHK.js} +2 -2
  256. package/dist/node-runtime/index.js +34 -31
  257. package/dist/node-runtime/{init-EKE277AG.js → init-DVJUAOUO.js} +3 -3
  258. package/dist/node-runtime/{interactive-mode-S5M26CQ7.js → interactive-mode-BBASNWHN.js} +18 -15
  259. package/dist/node-runtime/lunr-computer-use-TJNDAMWM.js +135 -0
  260. package/dist/node-runtime/{lunr-cron-KKBOGAEF.js → lunr-cron-J64I72C6.js} +5 -5
  261. package/dist/node-runtime/main.js +22 -20
  262. package/dist/node-runtime/{package-manager-cli-C4EJOO5Q.js → package-manager-cli-VMYX4Y2S.js} +8 -7
  263. package/dist/node-runtime/{pi-intercom-EEMBGQID.js → pi-intercom-NV2LW6X7.js} +108 -87
  264. package/dist/node-runtime/{pi-mcp-adapter-DPTJGAAL.js → pi-mcp-adapter-JLB5YL2F.js} +6 -6
  265. package/dist/node-runtime/{pi-subagents-VKCLYIBY.js → pi-subagents-WEHV3W7H.js} +1267 -604
  266. package/dist/node-runtime/{pi-web-access-BV6DSZOP.js → pi-web-access-FN5YC5T6.js} +5 -5
  267. package/dist/node-runtime/{proxy-modes-R64LU6WZ.js → proxy-modes-OR7ISBXK.js} +7 -7
  268. package/dist/node-runtime/rpc-entry.js +22 -20
  269. package/dist/node-runtime/{runtime-bridges-UJ5WJJLN.js → runtime-bridges-2VQTLPOZ.js} +3 -5
  270. package/dist/node-runtime/{settings-manager-K6IPIQTI.js → settings-manager-3CCU326G.js} +3 -2
  271. package/dist/node-runtime/{subagent-executor-EFLTO32A.js → subagent-executor-CXKXQDHH.js} +186 -299
  272. package/dist/node-runtime/{update-cli-I6OVDRPL.js → update-cli-NM7B4CKL.js} +3 -2
  273. package/dist/node-runtime/{video-extract-ETA5RA7U.js → video-extract-OYT5WKS5.js} +2 -2
  274. package/dist/node-runtime/workflow-C26QCUTW.js +468 -0
  275. package/dist/node-runtime/{youtube-extract-SRVGNN26.js → youtube-extract-TQYKGFGS.js} +2 -2
  276. package/docs/computer-use.md +233 -268
  277. package/docs/features.md +22 -4
  278. package/docs/keybindings.md +3 -1
  279. package/docs/settings.md +3 -2
  280. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  281. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  282. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  283. package/examples/extensions/gondolin/package-lock.json +2 -2
  284. package/examples/extensions/gondolin/package.json +1 -1
  285. package/examples/extensions/sandbox/package-lock.json +2 -2
  286. package/examples/extensions/sandbox/package.json +1 -1
  287. package/examples/extensions/with-deps/package-lock.json +2 -2
  288. package/examples/extensions/with-deps/package.json +1 -1
  289. package/install-lock/package-lock.json +24 -24
  290. package/install-lock/package.json +2 -2
  291. package/npm-shrinkwrap.json +21 -21
  292. package/package.json +7 -7
  293. package/dist/builtin-extensions/lunr-settings-tools.d.ts +0 -4
  294. package/dist/builtin-extensions/lunr-settings-tools.d.ts.map +0 -1
  295. package/dist/builtin-extensions/lunr-settings-tools.js +0 -120
  296. package/dist/builtin-extensions/lunr-settings-tools.js.map +0 -1
  297. package/dist/core/settings-tools-bridge.d.ts +0 -35
  298. package/dist/core/settings-tools-bridge.d.ts.map +0 -1
  299. package/dist/core/settings-tools-bridge.js +0 -56
  300. package/dist/core/settings-tools-bridge.js.map +0 -1
  301. package/dist/node-runtime/chunk-EH2LJQPM.js +0 -64
  302. package/dist/node-runtime/image-resize-6ZPBFMWW.js +0 -11
  303. package/dist/node-runtime/lunr-computer-use-4X3KUNF4.js +0 -206
  304. package/dist/node-runtime/workflow-SA34S4VX.js +0 -325
  305. package/dist/node-runtime/{chunk-EHMBW7FA.js → chunk-VSELYKWU.js} +3 -3
  306. package/dist/node-runtime/{chunk-ZSEZY3II.js → chunk-VTPM5V35.js} +0 -0
  307. package/dist/node-runtime/{src-GPFAU3N6.js → src-BPQFJR76.js} +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"tool-description.js","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/extension/tool-description.ts"],"names":[],"mappings":"AAAA,cAAc;AACd,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAEtE,MAAM,4BAA4B,GAAG,8BAA8B,CAAC;AACpE,MAAM,iCAAiC,GAAG,EAAE,GAAG,IAAI,CAAC;AAEpD,MAAM,CAAC,MAAM,wBAAwB,GAAG;;;;;;;;gQAQsN,CAAC;AAE/P,MAAM,CAAC,MAAM,8BAA8B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA2C5C,wBAAwB,EAAE,CAAC;AAE7B,MAAM,CAAC,MAAM,iCAAiC,GAAG;;;;;;;;;;;;;;;;;;;;sNAoBmK,CAAC;AAErN,SAAS,qBAAqB,CAAC,KAAc,EAAgC;IAC5E,OAAO,KAAK,KAAK,MAAM,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,QAAQ,CAAC;AAAA,CACrE;AAED,SAAS,IAAI,CAAC,OAA2C,EAAE,OAAe,EAAQ;IACjF,CAAC,OAAO,EAAE,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,kBAAkB,OAAO,EAAE,CAAC,CAAC;AAAA,CAC7D;AAQD,MAAM,UAAU,0BAA0B,CAAC,MAAoD,EAAE,OAAgC,EAAuB;IACvJ,MAAM,IAAI,GAAG,MAAM,CAAC,mBAAmB,CAAC;IACxC,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,MAAM,CAAC;IACtC,IAAI,qBAAqB,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IAC7C,IAAI,CAAC,OAAO,EAAE,wCAAwC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,4CAA4C,CAAC,CAAC;IACxH,OAAO,MAAM,CAAC;AAAA,CACd;AAED,SAAS,sBAAsB,CAAC,OAAgC,EAAY;IAC3E,MAAM,GAAG,GAAG,OAAO,EAAE,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC;IAC1C,MAAM,QAAQ,GAAG,OAAO,EAAE,QAAQ,IAAI,WAAW,EAAE,CAAC;IACpD,OAAO;QACN,IAAI,CAAC,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,EAAE,4BAA4B,CAAC;QACjE,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,4BAA4B,CAAC;KACjD,CAAC;AAAA,CACF;AAED,SAAS,oBAAoB,CAAC,QAAgB,EAAE,OAAgC,EAAU;IACzF,MAAM,GAAG,GAAG,OAAO,EAAE,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC;IAC1C,MAAM,QAAQ,GAAG,OAAO,EAAE,QAAQ,IAAI,WAAW,EAAE,CAAC;IACpD,MAAM,gBAAgB,GAAG,mBAAmB,CAAC,GAAG,CAAC,CAAC;IAClD,MAAM,SAAS,GAAiC;QAC/C,eAAe,EAAE,GAAG,EAAE,CAAC,8BAA8B;QACrD,IAAI,EAAE,GAAG,EAAE,CAAC,8BAA8B;QAC1C,kBAAkB,EAAE,GAAG,EAAE,CAAC,iCAAiC;QAC3D,OAAO,EAAE,GAAG,EAAE,CAAC,iCAAiC;QAChD,cAAc,EAAE,GAAG,EAAE,CAAC,wBAAwB;QAC9C,MAAM,EAAE,GAAG,EAAE,CAAC,wBAAwB;QACtC,QAAQ,EAAE,GAAG,EAAE,CAAC,QAAQ;QACxB,gBAAgB,EAAE,GAAG,EAAE,CAAC,gBAAgB;KACxC,CAAC;IACF,OAAO,QAAQ,CAAC,OAAO,CAAC,gBAAgB,EAAE,CAAC,GAAG,EAAE,IAAY,EAAE,EAAE,CAAC;QAChE,MAAM,WAAW,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;QACpC,IAAI,WAAW;YAAE,OAAO,WAAW,EAAE,CAAC;QACtC,IAAI,CAAC,OAAO,EAAE,GAAG,4BAA4B,yBAAyB,GAAG,kBAAkB,CAAC,CAAC;QAC7F,OAAO,GAAG,CAAC;IAAA,CACX,CAAC,CAAC;AAAA,CACH;AAED,SAAS,yBAAyB,CAAC,OAAgC,EAAsB;IACxF,KAAK,MAAM,QAAQ,IAAI,sBAAsB,CAAC,OAAO,CAAC,EAAE,CAAC;QACxD,IAAI,IAAc,CAAC;QACnB,IAAI,CAAC;YACJ,IAAI,GAAG,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QAC9B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,MAAM,IAAI,KAAK,IAAK,KAA+B,CAAC,IAAI,KAAK,QAAQ;gBAAE,SAAS;YACnI,IAAI,CAAC,OAAO,EAAE,8CAA8C,QAAQ,MAAM,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YACpI,SAAS;QACV,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC;YACpB,IAAI,CAAC,OAAO,EAAE,qCAAqC,QAAQ,6BAA6B,CAAC,CAAC;YAC1F,SAAS;QACV,CAAC;QACD,IAAI,IAAI,CAAC,IAAI,GAAG,iCAAiC,EAAE,CAAC;YACnD,IAAI,CAAC,OAAO,EAAE,qCAAqC,QAAQ,+BAA+B,iCAAiC,SAAS,CAAC,CAAC;YACtI,SAAS;QACV,CAAC;QACD,IAAI,CAAC;YACJ,MAAM,QAAQ,GAAG,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;YAC3D,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACf,IAAI,CAAC,OAAO,EAAE,2CAA2C,QAAQ,IAAI,CAAC,CAAC;gBACvE,SAAS;YACV,CAAC;YACD,MAAM,QAAQ,GAAG,oBAAoB,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;YAChE,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACf,IAAI,CAAC,OAAO,EAAE,qCAAqC,QAAQ,8BAA8B,CAAC,CAAC;gBAC3F,SAAS;YACV,CAAC;YACD,OAAO,QAAQ,CAAC;QACjB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,IAAI,CAAC,OAAO,EAAE,2CAA2C,QAAQ,MAAM,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAClI,CAAC;IACF,CAAC;IACD,OAAO,SAAS,CAAC;AAAA,CACjB;AAED,SAAS,2BAA2B,CAAC,WAAmB,EAAU;IACjE,MAAM,iBAAiB,GAAG,WAAW;SACnC,KAAK,CAAC,wBAAwB,CAAC;SAC/B,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;SAC1B,MAAM,CAAC,OAAO,CAAC;SACf,IAAI,CAAC,MAAM,CAAC,CAAC;IACf,OAAO,iBAAiB;QACvB,CAAC,CAAC,GAAG,iBAAiB,OAAO,wBAAwB,EAAE;QACvD,CAAC,CAAC,wBAAwB,CAAC;AAAA,CAC5B;AAED,MAAM,UAAU,4BAA4B,CAAC,MAAM,GAAiD,EAAE,EAAE,OAAgC,EAAU;IACjJ,MAAM,IAAI,GAAG,0BAA0B,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACzD,IAAI,WAAmB,CAAC;IACxB,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACxB,WAAW,GAAG,iCAAiC,CAAC;IACjD,CAAC;SAAM,IAAI,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC9B,MAAM,MAAM,GAAG,yBAAyB,CAAC,OAAO,CAAC,CAAC;QAClD,IAAI,MAAM,EAAE,CAAC;YACZ,WAAW,GAAG,2BAA2B,CAAC,MAAM,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACP,IAAI,CAAC,OAAO,EAAE,GAAG,4BAA4B,mFAAmF,CAAC,CAAC;YAClI,WAAW,GAAG,8BAA8B,CAAC;QAC9C,CAAC;IACF,CAAC;SAAM,CAAC;QACP,WAAW,GAAG,8BAA8B,CAAC;IAC9C,CAAC;IACD,OAAO,WAAW,CAAC;AAAA,CACnB","sourcesContent":["// @ts-nocheck\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { ExtensionConfig, ToolDescriptionMode } from \"../shared/types.ts\";\nimport { getAgentDir, getProjectConfigDir } from \"../shared/utils.ts\";\n\nconst CUSTOM_TOOL_DESCRIPTION_FILE = \"subagent-tool-description.md\";\nconst CUSTOM_TOOL_DESCRIPTION_MAX_BYTES = 50 * 1024;\n\nexport const SUBAGENT_SAFETY_GUIDANCE = `SAFETY-CRITICAL SUBAGENT GUIDANCE:\n• Prompt children directly. There is no agent roster. Every execution task needs task (the full child prompt) and description (a concise UI label).\n• Every executable child also needs tier: \"light\", \"standard\", or \"heavy\". Direct model overrides and parent-model inheritance are not available. A missing, disabled, unconfigured, unavailable, or unauthenticated tier fails before launch.\n• permissions is \"full\" or \"read-only\". Omitted permissions means full. Plan-mode parents must pass permissions: \"read-only\"; full or omitted launches are rejected.\n• Keep execution and control separate: omit action for SINGLE/PARALLEL/CHAIN execution; use action only for status/interrupt/stop/resume/steer/append-step/doctor/watchdog.*/schedule*.\n• Async/background runs: launch with async:true only when work can proceed independently. Do not sleep or poll status just to wait. In an interactive session, normally return control and let lunR wake you; use subagent_wait when this request must run to completion in the current turn or skill. Headless sessions auto-drain current-session work.\n• Child-safety boundary: ordinary children are not orchestrators and must not run subagents. Only explicitly configured fanout children may use the child-safe subagent tool, still bounded by depth/session limits.\n• Writing/review safety: keep one full-access writer for the same cwd/worktree. Use fresh-context permissions: \"read-only\" children for independent review, then have the parent synthesize and apply fixes as the sole writer unless an isolated worktree was intentionally requested.\n• Artifacts/status essentials: chain outputs live under {chain_dir}; async runs expose asyncId/asyncDir with status.json, events.jsonl, output logs, and status via { action: \"status\", id }. Include output paths and residual risks when reporting results.`;\n\nexport const FULL_SUBAGENT_TOOL_DESCRIPTION = `Delegate work to generic children by prompting them directly. There are no named agent types.\n\nEXECUTION (use exactly ONE mode):\n• SINGLE: { task, description, tier, permissions? } — one child. Multiple SINGLE calls in the same turn run concurrently; explicit concurrency/run limits still apply.\n• PARALLEL: { tasks: [{task, description, tier, permissions?, count?, output?, reads?, progress?}, ...], concurrency?: number, worktree?: true } — one-call concurrent execution (default: all tasks at once; worktree: isolate each task in a git worktree)\n• CHAIN: { chain: [{task, description, tier, permissions?}, {parallel:[{task, description, tier, permissions?, count:3}]}] } — sequential pipeline with optional parallel fan-out. Use chain when a later child needs an earlier result.\n• description is required, single-line, max 80 characters. It is UI metadata only. task is the complete child prompt.\n• permissions: \"full\" (default) or \"read-only\". Full includes coding tools (read, search, shell, edit, write, web, LSP, MCP) and excludes parent-owned tools (cron, memory, behavior, goals, nested subagents). Plan-mode parents may launch only permissions: \"read-only\".\n• Every executable child requires tier: \"light\", \"standard\", or \"heavy\". Direct model overrides and parent-model inheritance are rejected. The configured tier model and credentials must be available.\n• Children always start with a fresh session (no inherited parent transcript).\n• Optional timeout: { timeoutMs } or { maxRuntimeMs } sets a run-level max runtime for foreground and async/background runs\n\nCHAIN TEMPLATE VARIABLES (use in task and description strings):\n• {task} - The original task/request from the user\n• {previous} - Text response from the previous step (empty for first step)\n• {chain_dir} - Shared directory for chain files (e.g., <tmpdir>/pi-subagents-<scope>/chain-runs/abc123/)\n\nCHAIN EXAMPLES:\n• Sequential: { chain: [{task:\"Analyze {task}\", description:\"Analyze request\", tier:\"standard\"}, {task:\"Plan based on {previous}\", description:\"Draft plan\", tier:\"heavy\"}] }\n• Parallel fan-out: { chain: [{parallel: [{task:\"Check part of {task}\", description:\"Check one part\", tier:\"light\", permissions:\"read-only\", count: 3}]}] }\n• Mixed: { chain: [{task:\"Research {task}\", description:\"Research request\", tier:\"standard\", permissions:\"read-only\"}, {parallel: [{task:\"Review {previous}\", description:\"Review findings\", tier:\"light\", permissions:\"read-only\", count: 2}]}, {task:\"Summarize {previous}\", description:\"Summarize reviews\", tier:\"standard\"}] }\n\nCONTROL (use action field, omit task/chain/tasks):\n• { action: \"watchdog.status\" | \"watchdog.check\" | \"watchdog.recommend-model\" } - inspect the opt-in subagent watchdog and its strong complementary model recommendation\n• { action: \"watchdog.configure\", model: \"recommended\" | \"inherit\" | \"provider/model[:thinking]\", scope?: \"session\" | \"user\" | \"project\", target?: \"main\" | \"children\", thinking?: \"inherit\" | \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" } - configure watchdog model selection; default scope is session, use persistent scopes only when the user asks\n• { action: \"status\", id: \"...\" } - inspect an async/background run by id or prefix\n• { action: \"status\", view: \"fleet\" } - read-only active foreground/async fleet view with transcript commands\n• { action: \"status\", id: \"...\", view: \"transcript\", index?: 0, lines?: 80 } - tail a run or child output/session transcript\n• { action: \"interrupt\", id?: \"...\" } - soft-interrupt the current child turn and leave the run paused\n• { action: \"stop\", id: \"...\" } - stop a current-session top-level async run; stopped runs finish with state \"stopped\"\n• { action: \"resume\", id: \"...\", message: \"...\", index?: 0 } - interrupt then follow up with a live async child, or revive a completed async/foreground child from its session\n• { action: \"steer\", id: \"...\", message: \"...\", index?: 0 } - await correlated child input acceptance for up to 3 seconds; returns delivered, scheduled, pending, partial, recovered, or failed with a request id. Only top-level single runs may recover after a further 15-second pause/revival bound; chain, parallel, and nested runs never auto-interrupt.\n• { action: \"append-step\", id: \"...\", chain: [{task:\"Use {previous}\", description:\"Follow-up step\", tier:\"standard\"}] } - append one step to the tail of a running async chain\n\nSCHEDULE (opt-in; requires { \"scheduledRuns\": { \"enabled\": true } } in config.json):\n• { action: \"schedule\", task, description, tier, permissions?, schedule: \"+10m\" | \"2030-01-01T09:00:00Z\", scheduleName? } - defer a child launch until a future time. Also accepts tasks[] or chain[]. Scheduled runs always launch async with fresh context; they become normal tracked async runs once they fire. Only schedule explicit delayed runs the user asked for.\n• { action: \"schedule-list\" } - list scheduled runs for this session\n• { action: \"schedule-status\", id: \"...\" } - inspect one scheduled run\n• { action: \"schedule-cancel\", id: \"...\" } - cancel a scheduled run before it fires\n\nDIAGNOSTICS:\n• { action: \"doctor\" } - read-only report for runtime paths, sessions, and intercom\n\n${SUBAGENT_SAFETY_GUIDANCE}`;\n\nexport const COMPACT_SUBAGENT_TOOL_DESCRIPTION = `Delegate to generic children by prompting them. Use exactly one mode per call.\n\nEXECUTE:\n• SINGLE {task, description, tier, permissions?} (same-turn singles overlap); PARALLEL {tasks:[{task,description,tier,permissions?,count?,output?,reads?,progress?}], concurrency?, worktree?}; CHAIN {chain:[{task,description,tier,permissions?},{parallel:[...]}]} for sequential work.\n• description is required (single-line, max 80 chars, UI only). task is the full child prompt. permissions omitted = full. Plan-mode parents must pass permissions:\"read-only\".\n• Every executable child requires tier:\"light\"|\"standard\"|\"heavy\". Direct model overrides and parent-model inheritance are rejected; tier resolution fails closed. Children always start with a fresh session. timeoutMs/maxRuntimeMs apply to foreground and async/background runs.\n• Chain templates may use {task}, {previous}, {chain_dir}, and named outputs. Parallel worktree isolation requires a clean git repo.\n• Chain example: { chain: [{task:\"Analyze {task}\", description:\"Analyze request\", tier:\"standard\"}, {parallel: [{task:\"Check {previous}\", description:\"Check prior result\", tier:\"light\", permissions:\"read-only\", count: 3}]}] }\n\nCONTROL:\n• Use action without execution fields: doctor, watchdog.status, watchdog.check, watchdog.recommend-model, watchdog.configure, status, interrupt, stop, resume, steer, append-step.\n• Async control actions: status, interrupt, stop, resume, steer, append-step. Use stop with an id for current-session top-level async runs. Use status view:\"fleet\" for active-run overview, view:\"transcript\" to tail child output, and steer for acknowledged live guidance. Steering delivery means lunR accepted the correlated user input, not model compliance; use index for a specific child.\n• Opt-in schedule actions: schedule, schedule-list, schedule-status, schedule-cancel. Schedule only explicit delayed runs the user asked for.\n\nASYNC / WAIT:\n• async:true detaches background work. Do not sleep or poll just to wait. Interactive sessions normally yield for completion notifications; use subagent_wait for run-to-completion turns or skills. Headless sessions auto-drain current-session work.\n• Status and artifacts live under asyncId/asyncDir with status.json, events.jsonl, output logs, session files, and { action:\"status\", id:\"...\" }.\n\nSAFETY:\n• Ordinary children are not orchestrators and must not run subagents. Only explicit fanout children may use child-safe subagent, still bounded by depth/session limits.\n• Keep one full-access writer per cwd/worktree. Use fresh permissions:\"read-only\" review/validation fanout, then synthesize and apply fixes from the parent unless isolated worktrees were intentionally requested.`;\n\nfunction isToolDescriptionMode(value: unknown): value is ToolDescriptionMode {\n\treturn value === \"full\" || value === \"compact\" || value === \"custom\";\n}\n\nfunction warn(options: ToolDescriptionOptions | undefined, message: string): void {\n\t(options?.warn ?? console.warn)(`[pi-subagents] ${message}`);\n}\n\nexport interface ToolDescriptionOptions {\n\tcwd?: string;\n\tagentDir?: string;\n\twarn?: (message: string) => void;\n}\n\nexport function resolveToolDescriptionMode(config: Pick<ExtensionConfig, \"toolDescriptionMode\">, options?: ToolDescriptionOptions): ToolDescriptionMode {\n\tconst mode = config.toolDescriptionMode;\n\tif (mode === undefined) return \"full\";\n\tif (isToolDescriptionMode(mode)) return mode;\n\twarn(options, `Ignoring invalid toolDescriptionMode ${JSON.stringify(mode)}; expected \"full\", \"compact\", or \"custom\".`);\n\treturn \"full\";\n}\n\nfunction customDescriptionPaths(options?: ToolDescriptionOptions): string[] {\n\tconst cwd = options?.cwd ?? process.cwd();\n\tconst agentDir = options?.agentDir ?? getAgentDir();\n\treturn [\n\t\tpath.join(getProjectConfigDir(cwd), CUSTOM_TOOL_DESCRIPTION_FILE),\n\t\tpath.join(agentDir, CUSTOM_TOOL_DESCRIPTION_FILE),\n\t];\n}\n\nfunction renderCustomTemplate(template: string, options?: ToolDescriptionOptions): string {\n\tconst cwd = options?.cwd ?? process.cwd();\n\tconst agentDir = options?.agentDir ?? getAgentDir();\n\tconst projectConfigDir = getProjectConfigDir(cwd);\n\tconst variables: Record<string, () => string> = {\n\t\tfullDescription: () => FULL_SUBAGENT_TOOL_DESCRIPTION,\n\t\tfull: () => FULL_SUBAGENT_TOOL_DESCRIPTION,\n\t\tcompactDescription: () => COMPACT_SUBAGENT_TOOL_DESCRIPTION,\n\t\tcompact: () => COMPACT_SUBAGENT_TOOL_DESCRIPTION,\n\t\tsafetyGuidance: () => SUBAGENT_SAFETY_GUIDANCE,\n\t\tsafety: () => SUBAGENT_SAFETY_GUIDANCE,\n\t\tagentDir: () => agentDir,\n\t\tprojectConfigDir: () => projectConfigDir,\n\t};\n\treturn template.replace(/\\{\\{(\\w+)\\}\\}/g, (raw, name: string) => {\n\t\tconst replacement = variables[name];\n\t\tif (replacement) return replacement();\n\t\twarn(options, `${CUSTOM_TOOL_DESCRIPTION_FILE}: unknown placeholder ${raw} left unchanged.`);\n\t\treturn raw;\n\t});\n}\n\nfunction loadCustomToolDescription(options?: ToolDescriptionOptions): string | undefined {\n\tfor (const filePath of customDescriptionPaths(options)) {\n\t\tlet stat: fs.Stats;\n\t\ttry {\n\t\t\tstat = fs.statSync(filePath);\n\t\t} catch (error) {\n\t\t\tif (typeof error === \"object\" && error !== null && \"code\" in error && (error as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n\t\t\twarn(options, `Failed to inspect custom tool description '${filePath}': ${error instanceof Error ? error.message : String(error)}`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!stat.isFile()) {\n\t\t\twarn(options, `Ignoring custom tool description '${filePath}' because it is not a file.`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (stat.size > CUSTOM_TOOL_DESCRIPTION_MAX_BYTES) {\n\t\t\twarn(options, `Ignoring custom tool description '${filePath}' because it is larger than ${CUSTOM_TOOL_DESCRIPTION_MAX_BYTES} bytes.`);\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\tconst template = fs.readFileSync(filePath, \"utf-8\").trim();\n\t\t\tif (!template) {\n\t\t\t\twarn(options, `Ignoring empty custom tool description '${filePath}'.`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst rendered = renderCustomTemplate(template, options).trim();\n\t\t\tif (!rendered) {\n\t\t\t\twarn(options, `Ignoring custom tool description '${filePath}' because it rendered empty.`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn rendered;\n\t\t} catch (error) {\n\t\t\twarn(options, `Failed to read custom tool description '${filePath}': ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction withMandatorySafetyGuidance(description: string): string {\n\tconst customDescription = description\n\t\t.split(SUBAGENT_SAFETY_GUIDANCE)\n\t\t.map((part) => part.trim())\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\\n\");\n\treturn customDescription\n\t\t? `${customDescription}\\n\\n${SUBAGENT_SAFETY_GUIDANCE}`\n\t\t: SUBAGENT_SAFETY_GUIDANCE;\n}\n\nexport function buildSubagentToolDescription(config: Pick<ExtensionConfig, \"toolDescriptionMode\"> = {}, options?: ToolDescriptionOptions): string {\n\tconst mode = resolveToolDescriptionMode(config, options);\n\tlet description: string;\n\tif (mode === \"compact\") {\n\t\tdescription = COMPACT_SUBAGENT_TOOL_DESCRIPTION;\n\t} else if (mode === \"custom\") {\n\t\tconst custom = loadCustomToolDescription(options);\n\t\tif (custom) {\n\t\t\tdescription = withMandatorySafetyGuidance(custom);\n\t\t} else {\n\t\t\twarn(options, `${CUSTOM_TOOL_DESCRIPTION_FILE} was not found or valid for toolDescriptionMode \"custom\"; using full description.`);\n\t\t\tdescription = FULL_SUBAGENT_TOOL_DESCRIPTION;\n\t\t}\n\t} else {\n\t\tdescription = FULL_SUBAGENT_TOOL_DESCRIPTION;\n\t}\n\treturn description;\n}\n"]}
1
+ {"version":3,"file":"tool-description.js","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/extension/tool-description.ts"],"names":[],"mappings":"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","sourcesContent":["// @ts-nocheck\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { SUBAGENT_ASYNC_GUIDANCE } from \"../shared/async-guidance.ts\";\nimport type { ExtensionConfig, ToolDescriptionMode } from \"../shared/types.ts\";\nimport { getAgentDir, getProjectConfigDir } from \"../shared/utils.ts\";\n\nconst CUSTOM_TOOL_DESCRIPTION_FILE = \"subagent-tool-description.md\";\nconst CUSTOM_TOOL_DESCRIPTION_MAX_BYTES = 50 * 1024;\n\nexport const SUBAGENT_TIER_GUIDANCE = `TIER SELECTION:\n• Choose the lowest tier that can reliably complete the task.\n• light: Use for simple, straightforward tasks that require little reasoning. Good for quick checks, finding information, collecting facts for research, inspecting a small amount of code, or verifying a specific fact.\n• standard: Use for moderately difficult work and everyday coding tasks. Good for writing simple code, fixing a clearly described bug, reviewing a focused change, or completing work with clear requirements. Use heavy when the task requires deep architectural understanding or complex reasoning.\n• heavy: Use for complex or ambiguous tasks that require deep reasoning and strong code understanding. Good for implementing complex plans, debugging difficult or poorly understood problems, reviewing large or high-risk changes, and making architectural decisions.`;\n\nexport const SUBAGENT_SAFETY_GUIDANCE = `SAFETY-CRITICAL SUBAGENT GUIDANCE:\n• Prompt children directly. There is no agent roster. Every execution task needs task (the full child prompt) and description (a concise UI label).\n• Every executable child chooses exactly one of tier: \"light\"|\"standard\"|\"heavy\" (default) or model: \"provider/id\" when the user names a model. Do not pass both, and do not use inherit. Missing, disabled, unconfigured, unavailable, or unauthenticated selections fail before launch.\n• Optional thinking (off/minimal/low/medium/high/xhigh/max) is only valid with an explicit model. Tier launches use the configured tier thinking level.\n${SUBAGENT_TIER_GUIDANCE}\n• permissions is \"full\" or \"read-only\". Omitted permissions means full. Plan-mode parents must pass permissions: \"read-only\"; full or omitted launches are rejected.\n• Keep execution and control separate: omit action for SINGLE/PARALLEL/CHAIN execution; use action only for status/interrupt/stop/resume/steer/append-step/doctor/watchdog.status|check|recommend-model/schedule*.\n• ${SUBAGENT_ASYNC_GUIDANCE}\n• Child-safety boundary: ordinary children are not orchestrators and must not run subagents. Only explicitly configured fanout children may use the child-safe subagent tool, still bounded by depth/session limits.\n• Writing/review safety: keep one full-access writer for the same cwd/worktree. Use fresh-context permissions: \"read-only\" children for independent review, then have the parent synthesize and apply fixes as the sole writer unless an isolated worktree was intentionally requested.\n• Artifacts/status essentials: chain outputs live under {chain_dir}; async runs expose asyncId/asyncDir with status.json, events.jsonl, output logs, and status via { action: \"status\", id }. Include output paths and residual risks when reporting results.`;\n\nexport const FULL_SUBAGENT_TOOL_DESCRIPTION = `Delegate work to generic children by prompting them directly. There are no named agent types.\n\nEXECUTION (use exactly ONE mode):\n• SINGLE: { task, description, tier|model, thinking?, permissions? } — one child. Multiple SINGLE calls in the same turn run concurrently; explicit concurrency/run limits still apply.\n• PARALLEL: { tasks: [{task, description, tier|model, thinking?, permissions?, count?, output?, reads?, progress?}, ...], concurrency?: number, worktree?: true } — one-call concurrent execution (default: all tasks at once; worktree: isolate each task in a git worktree)\n• CHAIN: { chain: [{task, description, tier|model, thinking?, permissions?}, {parallel:[{task, description, tier|model, thinking?, permissions?, count:3}]}] } — sequential pipeline with optional parallel fan-out. Use chain when a later child needs an earlier result.\n• description is required, single-line, max 80 characters. It is UI metadata only. task is the complete child prompt.\n• permissions: \"full\" (default) or \"read-only\". Full includes coding tools (read, search, shell, edit, write, web, LSP, MCP) and excludes parent-owned tools (cron, memory, behavior, goals, nested subagents). Plan-mode parents may launch only permissions: \"read-only\".\n• Model selection: pass tier by default (\"light\"|\"standard\"|\"heavy\"). Pass model: \"provider/id\" only when the user specifies a model. Exactly one of tier or model. Optional thinking only with model; tier uses configured thinking. Direct model launches do not require tier mode to be enabled. No inherit and no silent fallback for an explicit model.\n• Children always start with a fresh session (no inherited parent transcript).\n• Optional timeout: { timeoutMs } or { maxRuntimeMs } sets a run-level max runtime for foreground and async/background runs\n\nCHAIN TEMPLATE VARIABLES (use in task and description strings):\n• {task} - The original task/request from the user\n• {previous} - Text response from the previous step (empty for first step)\n• {chain_dir} - Shared directory for chain files (e.g., <tmpdir>/pi-subagents-<scope>/chain-runs/abc123/)\n\nCHAIN EXAMPLES:\n• Sequential: { chain: [{task:\"Analyze {task}\", description:\"Analyze request\", tier:\"standard\"}, {task:\"Plan based on {previous}\", description:\"Draft plan\", tier:\"heavy\"}] }\n• Parallel fan-out: { chain: [{parallel: [{task:\"Check part of {task}\", description:\"Check one part\", tier:\"light\", permissions:\"read-only\", count: 3}]}] }\n• Mixed: { chain: [{task:\"Research {task}\", description:\"Research request\", tier:\"standard\", permissions:\"read-only\"}, {parallel: [{task:\"Review {previous}\", description:\"Review findings\", tier:\"light\", permissions:\"read-only\", count: 2}]}, {task:\"Summarize {previous}\", description:\"Summarize reviews\", tier:\"standard\"}] }\n\nCONTROL (use action field, omit task/chain/tasks):\n• { action: \"watchdog.status\" | \"watchdog.check\" | \"watchdog.recommend-model\" } - inspect the opt-in subagent watchdog and its strong complementary model recommendation (read-only; there is no configure action)\n• { action: \"status\", id: \"...\" } - inspect an async/background run by id or prefix\n• { action: \"status\", view: \"fleet\" } - read-only active foreground/async fleet view with transcript commands\n• { action: \"status\", id: \"...\", view: \"transcript\", index?: 0, lines?: 80 } - tail a run or child output/session transcript\n• { action: \"interrupt\", id?: \"...\" } - soft-interrupt the current child turn and leave the run paused\n• { action: \"stop\", id: \"...\" } - stop a current-session top-level async run; stopped runs finish with state \"stopped\"\n• { action: \"resume\", id: \"...\", message: \"...\", index?: 0 } - interrupt then follow up with a live async child, or revive a completed async/foreground child from its session\n• { action: \"steer\", id: \"...\", message: \"...\", index?: 0 } - await correlated child input acceptance for up to 3 seconds; returns delivered, scheduled, pending, partial, recovered, or failed with a request id. Only top-level single runs may recover after a further 15-second pause/revival bound; chain, parallel, and nested runs never auto-interrupt.\n• subagent_supervisor({ action: \"ask\", id, reason, message, index?, childId? }) - ask one running async child; returns question id immediately. Ask only when the child owns missing context, the answer changes a concrete next decision, and waiting risks block/rework. No broadcast, revive, task replacement, status polling, or micromanagement.\n• subagent_wait({ questionId }) - wait for that supervisor question answer/expiry/cancel. Answers stay separate from final run results.\n• { action: \"append-step\", id: \"...\", chain: [{task:\"Use {previous}\", description:\"Follow-up step\", tier:\"standard\"}] } - append one step to the tail of a running async chain\n\nSCHEDULE (opt-in; requires { \"scheduledRuns\": { \"enabled\": true } } in config.json):\n• { action: \"schedule\", task, description, tier|model, thinking?, permissions?, schedule: \"+10m\" | \"2030-01-01T09:00:00Z\", scheduleName? } - defer a child launch until a future time. Also accepts tasks[] or chain[]. Scheduled runs always launch async with fresh context; they become normal tracked async runs once they fire. Only schedule explicit delayed runs the user asked for.\n• { action: \"schedule-list\" } - list scheduled runs for this session\n• { action: \"schedule-status\", id: \"...\" } - inspect one scheduled run\n• { action: \"schedule-cancel\", id: \"...\" } - cancel a scheduled run before it fires\n\nDIAGNOSTICS:\n• { action: \"doctor\" } - read-only report for runtime paths, sessions, and intercom\n\n${SUBAGENT_SAFETY_GUIDANCE}`;\n\nexport const COMPACT_SUBAGENT_TOOL_DESCRIPTION = `Delegate to generic children by prompting them. Use exactly one mode per call.\n\nEXECUTE:\n• SINGLE {task, description, tier|model, thinking?, permissions?} (same-turn singles overlap); PARALLEL {tasks:[{task,description,tier|model,thinking?,permissions?,count?,output?,reads?,progress?}], concurrency?, worktree?}; CHAIN {chain:[{task,description,tier|model,thinking?,permissions?},{parallel:[...]}]} for sequential work.\n• description is required (single-line, max 80 chars, UI only). task is the full child prompt. permissions omitted = full. Plan-mode parents must pass permissions:\"read-only\".\n• Exactly one of tier:\"light\"|\"standard\"|\"heavy\" (default) or model:\"provider/id\" when the user names a model. thinking only with model. No inherit; fail closed on unavailable selections. Children always start fresh. timeoutMs/maxRuntimeMs apply to foreground and async/background runs.\n${SUBAGENT_TIER_GUIDANCE}\n• Chain templates may use {task}, {previous}, {chain_dir}, and named outputs. Parallel worktree isolation requires a clean git repo.\n• Chain example: { chain: [{task:\"Analyze {task}\", description:\"Analyze request\", tier:\"standard\"}, {parallel: [{task:\"Check {previous}\", description:\"Check prior result\", tier:\"light\", permissions:\"read-only\", count: 3}]}] }\n\nCONTROL:\n• Use action without execution fields: doctor, watchdog.status, watchdog.check, watchdog.recommend-model, status, interrupt, stop, resume, steer, append-step.\n• Async control actions: status, interrupt, stop, resume, steer, append-step. Use stop with an id for current-session top-level async runs. Use status view:\"fleet\" for active-run overview, view:\"transcript\" to tail child output, and steer for acknowledged live guidance. Steering delivery means lunR accepted the correlated user input, not model compliance; use index for a specific child.\n• Opt-in schedule actions: schedule, schedule-list, schedule-status, schedule-cancel. Schedule only explicit delayed runs the user asked for.\n\nASYNC / WAIT:\n• ${SUBAGENT_ASYNC_GUIDANCE}\n• Status and artifacts live under asyncId/asyncDir with status.json, events.jsonl, output logs, session files, and { action:\"status\", id:\"...\" }.\n\nSAFETY:\n• Ordinary children are not orchestrators and must not run subagents. Only explicit fanout children may use child-safe subagent, still bounded by depth/session limits.\n• Keep one full-access writer per cwd/worktree. Use fresh permissions:\"read-only\" review/validation fanout, then synthesize and apply fixes from the parent unless isolated worktrees were intentionally requested.`;\n\nfunction isToolDescriptionMode(value: unknown): value is ToolDescriptionMode {\n\treturn value === \"full\" || value === \"compact\" || value === \"custom\";\n}\n\nfunction warn(options: ToolDescriptionOptions | undefined, message: string): void {\n\t(options?.warn ?? console.warn)(`[pi-subagents] ${message}`);\n}\n\nexport interface ToolDescriptionOptions {\n\tcwd?: string;\n\tagentDir?: string;\n\twarn?: (message: string) => void;\n}\n\nexport function resolveToolDescriptionMode(config: Pick<ExtensionConfig, \"toolDescriptionMode\">, options?: ToolDescriptionOptions): ToolDescriptionMode {\n\tconst mode = config.toolDescriptionMode;\n\tif (mode === undefined) return \"full\";\n\tif (isToolDescriptionMode(mode)) return mode;\n\twarn(options, `Ignoring invalid toolDescriptionMode ${JSON.stringify(mode)}; expected \"full\", \"compact\", or \"custom\".`);\n\treturn \"full\";\n}\n\nfunction customDescriptionPaths(options?: ToolDescriptionOptions): string[] {\n\tconst cwd = options?.cwd ?? process.cwd();\n\tconst agentDir = options?.agentDir ?? getAgentDir();\n\treturn [\n\t\tpath.join(getProjectConfigDir(cwd), CUSTOM_TOOL_DESCRIPTION_FILE),\n\t\tpath.join(agentDir, CUSTOM_TOOL_DESCRIPTION_FILE),\n\t];\n}\n\nfunction renderCustomTemplate(template: string, options?: ToolDescriptionOptions): string {\n\tconst cwd = options?.cwd ?? process.cwd();\n\tconst agentDir = options?.agentDir ?? getAgentDir();\n\tconst projectConfigDir = getProjectConfigDir(cwd);\n\tconst variables: Record<string, () => string> = {\n\t\tfullDescription: () => FULL_SUBAGENT_TOOL_DESCRIPTION,\n\t\tfull: () => FULL_SUBAGENT_TOOL_DESCRIPTION,\n\t\tcompactDescription: () => COMPACT_SUBAGENT_TOOL_DESCRIPTION,\n\t\tcompact: () => COMPACT_SUBAGENT_TOOL_DESCRIPTION,\n\t\tsafetyGuidance: () => SUBAGENT_SAFETY_GUIDANCE,\n\t\tsafety: () => SUBAGENT_SAFETY_GUIDANCE,\n\t\tagentDir: () => agentDir,\n\t\tprojectConfigDir: () => projectConfigDir,\n\t};\n\treturn template.replace(/\\{\\{(\\w+)\\}\\}/g, (raw, name: string) => {\n\t\tconst replacement = variables[name];\n\t\tif (replacement) return replacement();\n\t\twarn(options, `${CUSTOM_TOOL_DESCRIPTION_FILE}: unknown placeholder ${raw} left unchanged.`);\n\t\treturn raw;\n\t});\n}\n\nfunction loadCustomToolDescription(options?: ToolDescriptionOptions): string | undefined {\n\tfor (const filePath of customDescriptionPaths(options)) {\n\t\tlet stat: fs.Stats;\n\t\ttry {\n\t\t\tstat = fs.statSync(filePath);\n\t\t} catch (error) {\n\t\t\tif (typeof error === \"object\" && error !== null && \"code\" in error && (error as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n\t\t\twarn(options, `Failed to inspect custom tool description '${filePath}': ${error instanceof Error ? error.message : String(error)}`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!stat.isFile()) {\n\t\t\twarn(options, `Ignoring custom tool description '${filePath}' because it is not a file.`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (stat.size > CUSTOM_TOOL_DESCRIPTION_MAX_BYTES) {\n\t\t\twarn(options, `Ignoring custom tool description '${filePath}' because it is larger than ${CUSTOM_TOOL_DESCRIPTION_MAX_BYTES} bytes.`);\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\tconst template = fs.readFileSync(filePath, \"utf-8\").trim();\n\t\t\tif (!template) {\n\t\t\t\twarn(options, `Ignoring empty custom tool description '${filePath}'.`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst rendered = renderCustomTemplate(template, options).trim();\n\t\t\tif (!rendered) {\n\t\t\t\twarn(options, `Ignoring custom tool description '${filePath}' because it rendered empty.`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn rendered;\n\t\t} catch (error) {\n\t\t\twarn(options, `Failed to read custom tool description '${filePath}': ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction withMandatorySafetyGuidance(description: string): string {\n\tconst customDescription = description\n\t\t.split(SUBAGENT_SAFETY_GUIDANCE)\n\t\t.map((part) => part.trim())\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\\n\");\n\treturn customDescription\n\t\t? `${customDescription}\\n\\n${SUBAGENT_SAFETY_GUIDANCE}`\n\t\t: SUBAGENT_SAFETY_GUIDANCE;\n}\n\nexport function buildSubagentToolDescription(config: Pick<ExtensionConfig, \"toolDescriptionMode\"> = {}, options?: ToolDescriptionOptions): string {\n\tconst mode = resolveToolDescriptionMode(config, options);\n\tlet description: string;\n\tif (mode === \"compact\") {\n\t\tdescription = COMPACT_SUBAGENT_TOOL_DESCRIPTION;\n\t} else if (mode === \"custom\") {\n\t\tconst custom = loadCustomToolDescription(options);\n\t\tif (custom) {\n\t\t\tdescription = withMandatorySafetyGuidance(custom);\n\t\t} else {\n\t\t\twarn(options, `${CUSTOM_TOOL_DESCRIPTION_FILE} was not found or valid for toolDescriptionMode \"custom\"; using full description.`);\n\t\t\tdescription = FULL_SUBAGENT_TOOL_DESCRIPTION;\n\t\t}\n\t} else {\n\t\tdescription = FULL_SUBAGENT_TOOL_DESCRIPTION;\n\t}\n\treturn description;\n}\n"]}
@@ -1,6 +1,8 @@
1
1
  import type { ExtensionAPI } from "@ashx-j/lunr-dev";
2
2
  import { type SubagentState } from "../shared/types.ts";
3
+ import { resolveSupervisorChannelDir as resolveQuestionChannelDir } from "./supervisor-questions.ts";
3
4
  export declare const NATIVE_SUPERVISOR_TOOL_NAME = "subagent_supervisor";
5
+ export declare const resolveSupervisorChannelDir: typeof resolveQuestionChannelDir;
4
6
  type SupervisorReason = "need_decision" | "interview_request" | "progress_update";
5
7
  interface SupervisorRequest {
6
8
  type: "subagent.supervisor.request";
@@ -12,6 +14,7 @@ interface SupervisorRequest {
12
14
  expectsReply: boolean;
13
15
  orchestratorTarget?: string;
14
16
  orchestratorSessionId?: string;
17
+ supervisorSessionId?: string;
15
18
  runId: string;
16
19
  agent: string;
17
20
  childIndex: number;
@@ -22,15 +25,19 @@ interface PendingSupervisorRequest extends SupervisorRequest {
22
25
  channelDir: string;
23
26
  requestFile: string;
24
27
  }
25
- export declare function resolveSupervisorChannelDir(runId: string, agent: string, childIndex: number): string;
26
28
  export declare function ensureSupervisorChannelDir(channelDir: string): void;
27
29
  export declare function registerNativeSupervisorClient(pi: ExtensionAPI, options?: {
28
30
  includeIntercomFallback?: boolean;
29
31
  }): void;
32
+ export declare function hasPendingBlockingSupervisorRequest(runId: string, sessionId?: string | null, now?: number): boolean;
30
33
  export declare function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentState): {
31
34
  start: () => void;
32
35
  dispose: () => void;
33
36
  pending: Map<string, PendingSupervisorRequest>;
37
+ cancelOwnedQuestions: (reason: string) => void;
38
+ settleRunQuestions: (runId: string, reason: string) => void;
34
39
  };
40
+ export declare function isPendingQuestionForCurrentChild(questionId: string): boolean;
41
+ export declare function markDeliveredSupervisorQuestionFromChild(message: string): void;
35
42
  export {};
36
43
  //# sourceMappingURL=native-supervisor-channel.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"native-supervisor-channel.d.ts","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAoC,MAAM,iCAAiC,CAAC;AAUtG,OAAO,EAAyF,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAM/I,eAAO,MAAM,2BAA2B,wBAAwB,CAAC;AAOjE,KAAK,gBAAgB,GAAG,eAAe,GAAG,mBAAmB,GAAG,iBAAiB,CAAC;AAElF,UAAU,iBAAiB;IAC1B,IAAI,EAAE,6BAA6B,CAAC;IACpC,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,gBAAgB,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,OAAO,CAAC;IACtB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,OAAO,CAAC;CACpB;AAED,UAAU,wBAAyB,SAAQ,iBAAiB;IAC3D,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;CACpB;AAuCD,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAEpG;AAED,wBAAgB,0BAA0B,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAGnE;AAkMD,wBAAgB,8BAA8B,CAAC,EAAE,EAAE,YAAY,EAAE,OAAO,GAAE;IAAE,uBAAuB,CAAC,EAAE,OAAO,CAAA;CAAO,GAAG,IAAI,CAgC1H;AA+QD,wBAAgB,6BAA6B,CAAC,EAAE,EAAE,YAAY,EAAE,KAAK,EAAE,aAAa,GAAG;IAAE,KAAK,EAAE,MAAM,IAAI,CAAC;IAAC,OAAO,EAAE,MAAM,IAAI,CAAC;IAAC,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,wBAAwB,CAAC,CAAA;CAAE,CAmFhL","sourcesContent":["// @ts-nocheck\nimport { randomUUID } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { AgentToolResult } from \"@ashx-j/lunr-agent\";\nimport type { ExtensionAPI, ExtensionContext, ToolDefinition } from \"@ashx-j/lunr-dev\";\nimport { Type } from \"typebox\";\nimport {\n\tSUBAGENT_CHILD_AGENT_ENV,\n\tSUBAGENT_CHILD_INDEX_ENV,\n\tSUBAGENT_ORCHESTRATOR_SESSION_ID_ENV,\n\tSUBAGENT_ORCHESTRATOR_TARGET_ENV,\n\tSUBAGENT_RUN_ID_ENV,\n\tSUBAGENT_SUPERVISOR_CHANNEL_DIR_ENV,\n} from \"../runs/shared/pi-args.ts\";\nimport { INTERCOM_DETACH_REQUEST_EVENT, POLL_INTERVAL_MS, TEMP_ROOT_DIR, type IntercomEventBus, type SubagentState } from \"../shared/types.ts\";\nimport { writeAtomicJson } from \"../shared/atomic-json.ts\";\n\nconst SUPERVISOR_CHANNEL_ROOT = path.join(TEMP_ROOT_DIR, \"supervisor-channels\");\nconst REQUESTS_DIR = \"requests\";\nconst REPLIES_DIR = \"replies\";\nexport const NATIVE_SUPERVISOR_TOOL_NAME = \"subagent_supervisor\";\nconst MAX_MESSAGE_BYTES = 64 * 1024;\nconst DEFAULT_ASK_TIMEOUT_MS = 10 * 60 * 1000;\nconst CHANNEL_POLL_MS = Math.min(POLL_INTERVAL_MS, 500);\nconst STALE_EMPTY_CHANNEL_AGE_MS = 60 * 1000;\nconst STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS = 60 * 1000;\n\ntype SupervisorReason = \"need_decision\" | \"interview_request\" | \"progress_update\";\n\ninterface SupervisorRequest {\n\ttype: \"subagent.supervisor.request\";\n\tid: string;\n\tcreatedAt: number;\n\texpiresAt?: number;\n\treason: SupervisorReason;\n\tmessage: string;\n\texpectsReply: boolean;\n\torchestratorTarget?: string;\n\torchestratorSessionId?: string;\n\trunId: string;\n\tagent: string;\n\tchildIndex: number;\n\tchildTarget?: string;\n\tinterview?: unknown;\n}\n\ninterface PendingSupervisorRequest extends SupervisorRequest {\n\tchannelDir: string;\n\trequestFile: string;\n}\n\ninterface SupervisorReply {\n\ttype: \"subagent.supervisor.reply\";\n\trequestId: string;\n\tcreatedAt: number;\n\tmessage: string;\n}\n\ninterface ContactSupervisorParams {\n\treason: SupervisorReason;\n\tmessage?: string;\n\tinterview?: unknown;\n}\n\ninterface IntercomParams {\n\taction: \"list\" | \"send\" | \"ask\" | \"reply\" | \"pending\" | \"status\";\n\tto?: string;\n\tmessage?: string;\n\treplyTo?: string;\n}\n\nconst ContactSupervisorParamsSchema = Type.Object({\n\treason: Type.String({ enum: [\"need_decision\", \"interview_request\", \"progress_update\"] }),\n\tmessage: Type.Optional(Type.String()),\n\tinterview: Type.Optional(Type.Unsafe({ type: \"object\", additionalProperties: true })),\n}, { additionalProperties: false });\n\nconst IntercomParamsSchema = Type.Object({\n\taction: Type.String({ enum: [\"list\", \"send\", \"ask\", \"reply\", \"pending\", \"status\"] }),\n\tto: Type.Optional(Type.String()),\n\tmessage: Type.Optional(Type.String()),\n\treplyTo: Type.Optional(Type.String()),\n}, { additionalProperties: false });\n\nfunction safeSegment(value: string): string {\n\treturn value.trim().replace(/[^A-Za-z0-9._-]+/g, \"-\").replace(/^-+|-+$/g, \"\") || \"unknown\";\n}\n\nexport function resolveSupervisorChannelDir(runId: string, agent: string, childIndex: number): string {\n\treturn path.join(SUPERVISOR_CHANNEL_ROOT, `${safeSegment(runId)}-${safeSegment(agent)}-${childIndex}`);\n}\n\nexport function ensureSupervisorChannelDir(channelDir: string): void {\n\tfs.mkdirSync(path.join(channelDir, REQUESTS_DIR), { recursive: true, mode: 0o700 });\n\tfs.mkdirSync(path.join(channelDir, REPLIES_DIR), { recursive: true, mode: 0o700 });\n}\n\nfunction requestPath(channelDir: string, requestId: string): string {\n\treturn path.join(channelDir, REQUESTS_DIR, `${safeSegment(requestId)}.json`);\n}\n\nfunction replyPath(channelDir: string, requestId: string): string {\n\treturn path.join(channelDir, REPLIES_DIR, `${safeSegment(requestId)}.json`);\n}\n\nfunction readTextEnv(name: string): string | undefined {\n\tconst value = process.env[name]?.trim();\n\treturn value ? value : undefined;\n}\n\nfunction readChildMetadata(): {\n\tchannelDir: string;\n\trunId: string;\n\tagent: string;\n\tchildIndex: number;\n\torchestratorTarget?: string;\n\torchestratorSessionId?: string;\n\tchildTarget?: string;\n} | undefined {\n\tconst channelDir = readTextEnv(SUBAGENT_SUPERVISOR_CHANNEL_DIR_ENV);\n\tconst runId = readTextEnv(SUBAGENT_RUN_ID_ENV);\n\tconst agent = readTextEnv(SUBAGENT_CHILD_AGENT_ENV);\n\tconst rawIndex = readTextEnv(SUBAGENT_CHILD_INDEX_ENV);\n\tconst orchestratorSessionId = readTextEnv(SUBAGENT_ORCHESTRATOR_SESSION_ID_ENV);\n\tif (!channelDir || !runId || !agent || !orchestratorSessionId || rawIndex === undefined || !/^\\d+$/.test(rawIndex)) return undefined;\n\treturn {\n\t\tchannelDir,\n\t\trunId,\n\t\tagent,\n\t\tchildIndex: Number(rawIndex),\n\t\torchestratorTarget: readTextEnv(SUBAGENT_ORCHESTRATOR_TARGET_ENV),\n\t\torchestratorSessionId,\n\t\tchildTarget: readTextEnv(\"PI_SUBAGENT_INTERCOM_SESSION_NAME\"),\n\t};\n}\n\nfunction reasonHeading(reason: SupervisorReason): string {\n\tif (reason === \"interview_request\") return \"Subagent requests a structured supervisor interview.\";\n\tif (reason === \"progress_update\") return \"Subagent progress update.\";\n\treturn \"Subagent needs a supervisor decision.\";\n}\n\nfunction formatChildMessage(input: {\n\treason: SupervisorReason;\n\tmessage?: string;\n\tinterview?: unknown;\n\trunId: string;\n\tagent: string;\n\tchildIndex: number;\n\tchildTarget?: string;\n}): string {\n\tconst lines = [\n\t\treasonHeading(input.reason),\n\t\t`Run: ${input.runId}`,\n\t\t`Agent: ${input.agent}`,\n\t\t`Child index: ${input.childIndex}`,\n\t];\n\tif (input.childTarget) lines.push(`Child intercom target: ${input.childTarget}`);\n\tlines.push(\"\");\n\tif (input.message?.trim()) lines.push(input.message.trim());\n\tif (input.reason === \"interview_request\") {\n\t\tlines.push(\n\t\t\t\"\",\n\t\t\t\"Structured response requested. Reply with JSON, optionally fenced in ```json, matching the requested interview shape.\",\n\t\t);\n\t\tif (input.interview !== undefined) lines.push(JSON.stringify(input.interview, null, \"\\t\"));\n\t}\n\treturn lines.join(\"\\n\").trimEnd();\n}\n\nfunction parseStructuredReply(message: string): { value?: unknown; error?: string } {\n\tconst trimmed = message.trim();\n\tconst fenced = trimmed.match(/^```(?:json)?\\s*([\\s\\S]*?)\\s*```$/i)?.[1]?.trim();\n\ttry {\n\t\treturn { value: JSON.parse(fenced ?? trimmed) };\n\t} catch (error) {\n\t\treturn { error: error instanceof Error ? `${error.name}: ${error.message}` : String(error) };\n\t}\n}\n\nfunction askTimeoutMs(): number {\n\tconst parsed = Number(process.env.PI_INTERCOM_ASK_TIMEOUT_MS);\n\treturn Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_ASK_TIMEOUT_MS;\n}\n\nfunction delay(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new Error(\"Supervisor request cancelled.\"));\n\t\t\treturn;\n\t\t}\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tconst cleanup = () => {\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tcleanup();\n\t\t\treject(new Error(\"Supervisor request cancelled.\"));\n\t\t};\n\t\ttimer = setTimeout(() => {\n\t\t\tcleanup();\n\t\t\tresolve();\n\t\t}, ms);\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nasync function waitForReply(channelDir: string, requestId: string, deadline: number, signal?: AbortSignal): Promise<SupervisorReply> {\n\tconst file = replyPath(channelDir, requestId);\n\twhile (Date.now() <= deadline) {\n\t\tif (signal?.aborted) throw new Error(\"Supervisor request cancelled.\");\n\t\tif (fs.existsSync(file)) {\n\t\t\tconst parsed = JSON.parse(fs.readFileSync(file, \"utf-8\")) as Partial<SupervisorReply>;\n\t\t\tif (parsed.type === \"subagent.supervisor.reply\" && parsed.requestId === requestId && typeof parsed.message === \"string\") {\n\t\t\t\treturn parsed as SupervisorReply;\n\t\t\t}\n\t\t}\n\t\tawait delay(250, signal);\n\t}\n\tthrow new Error(\"Timed out waiting for supervisor reply.\");\n}\n\nasync function sendSupervisorRequest(params: ContactSupervisorParams, signal?: AbortSignal): Promise<AgentToolResult<Record<string, unknown>>> {\n\tconst metadata = readChildMetadata();\n\tif (!metadata) throw new Error(\"Native supervisor channel is not available for this subagent.\");\n\tif (params.reason !== \"progress_update\" && !params.message?.trim() && params.reason !== \"interview_request\") {\n\t\tthrow new Error(\"message is required for supervisor decisions.\");\n\t}\n\tensureSupervisorChannelDir(metadata.channelDir);\n\tconst requestId = randomUUID();\n\tconst expectsReply = params.reason !== \"progress_update\";\n\tconst createdAt = Date.now();\n\tconst replyDeadline = createdAt + askTimeoutMs();\n\tconst expiresAt = expectsReply ? replyDeadline : undefined;\n\tconst message = formatChildMessage({ ...metadata, reason: params.reason, message: params.message, interview: params.interview });\n\tconst request: SupervisorRequest = {\n\t\ttype: \"subagent.supervisor.request\",\n\t\tid: requestId,\n\t\tcreatedAt,\n\t\t...(expiresAt !== undefined ? { expiresAt } : {}),\n\t\treason: params.reason,\n\t\tmessage,\n\t\texpectsReply,\n\t\t...(metadata.orchestratorTarget ? { orchestratorTarget: metadata.orchestratorTarget } : {}),\n\t\t...(metadata.orchestratorSessionId ? { orchestratorSessionId: metadata.orchestratorSessionId } : {}),\n\t\trunId: metadata.runId,\n\t\tagent: metadata.agent,\n\t\tchildIndex: metadata.childIndex,\n\t\t...(metadata.childTarget ? { childTarget: metadata.childTarget } : {}),\n\t\t...(params.interview !== undefined ? { interview: params.interview } : {}),\n\t};\n\tconst serialized = JSON.stringify(request, null, \"\\t\");\n\tif (Buffer.byteLength(serialized, \"utf-8\") > MAX_MESSAGE_BYTES) throw new Error(\"Supervisor request is too large.\");\n\twriteAtomicJson(requestPath(metadata.channelDir, requestId), request);\n\n\tif (!expectsReply) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: \"Supervisor progress update queued.\" }],\n\t\t\tdetails: { delivered: true, requestId, reason: params.reason },\n\t\t};\n\t}\n\n\ttry {\n\t\tconst reply = await waitForReply(metadata.channelDir, requestId, replyDeadline, signal);\n\t\tconst details: Record<string, unknown> = { requestId, reason: params.reason };\n\t\tif (params.reason === \"interview_request\") {\n\t\t\tconst structured = parseStructuredReply(reply.message);\n\t\t\tif (structured.error) details.structuredReplyParseError = structured.error;\n\t\t\telse details.structuredReply = structured.value;\n\t\t}\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `**Reply from supervisor:**\\n${reply.message}` }],\n\t\t\tdetails,\n\t\t};\n\t} catch (error) {\n\t\tremoveRequestFile(requestPath(metadata.channelDir, requestId));\n\t\tthrow error;\n\t}\n}\n\nfunction hasTool(pi: ExtensionAPI, name: string): boolean {\n\ttry {\n\t\treturn pi.getAllTools?.().some((tool: { name?: unknown }) => tool.name === name) === true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function registerNativeSupervisorClient(pi: ExtensionAPI, options: { includeIntercomFallback?: boolean } = {}): void {\n\tif (!readChildMetadata()) return;\n\tconst includeIntercomFallback = options.includeIntercomFallback !== false;\n\tif (!hasTool(pi, \"contact_supervisor\")) {\n\t\tconst tool: ToolDefinition<typeof ContactSupervisorParamsSchema, Record<string, unknown>> = {\n\t\t\tname: \"contact_supervisor\",\n\t\t\tlabel: \"Contact Supervisor\",\n\t\t\tdescription: \"Contact the parent/supervisor session for a blocking decision, structured interview, or progress update.\",\n\t\t\tparameters: ContactSupervisorParamsSchema,\n\t\t\texecute(_id, params, signal) {\n\t\t\t\treturn sendSupervisorRequest(params as ContactSupervisorParams, signal);\n\t\t\t},\n\t\t};\n\t\tpi.registerTool(tool);\n\t}\n\tif (includeIntercomFallback && !hasTool(pi, \"intercom\")) {\n\t\tconst tool: ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> = {\n\t\t\tname: \"intercom\",\n\t\t\tlabel: \"Intercom\",\n\t\t\tdescription: \"Native supervisor-channel intercom fallback for subagents. Prefer contact_supervisor when available.\",\n\t\t\tparameters: IntercomParamsSchema,\n\t\t\tasync execute(_id, params, signal) {\n\t\t\t\tconst action = (params as IntercomParams).action;\n\t\t\t\tif (action === \"status\") return { content: [{ type: \"text\", text: \"Native supervisor channel is active.\" }], details: { active: true } };\n\t\t\t\tif (action === \"list\") return { content: [{ type: \"text\", text: \"Supervisor session available through contact_supervisor.\" }], details: { sessions: [] } };\n\t\t\t\tif (action === \"send\") return sendSupervisorRequest({ reason: \"progress_update\", message: (params as IntercomParams).message ?? \"\" }, signal);\n\t\t\t\tif (action === \"ask\") return sendSupervisorRequest({ reason: \"need_decision\", message: (params as IntercomParams).message ?? \"\" }, signal);\n\t\t\t\tthrow new Error(\"Native child intercom supports status, list, send, and ask. Use parent intercom reply from the supervisor session.\");\n\t\t\t},\n\t\t};\n\t\tpi.registerTool(tool);\n\t}\n}\n\nfunction parseRequestFile(file: string, channelDir: string): PendingSupervisorRequest | undefined {\n\ttry {\n\t\tconst parsed = JSON.parse(fs.readFileSync(file, \"utf-8\")) as Partial<SupervisorRequest>;\n\t\tif (parsed.type !== \"subagent.supervisor.request\") return undefined;\n\t\tif (typeof parsed.id !== \"string\" || !parsed.id) return undefined;\n\t\tif (parsed.reason !== \"need_decision\" && parsed.reason !== \"interview_request\" && parsed.reason !== \"progress_update\") return undefined;\n\t\tif (typeof parsed.message !== \"string\" || !parsed.message) return undefined;\n\t\tif (typeof parsed.runId !== \"string\" || typeof parsed.agent !== \"string\" || typeof parsed.childIndex !== \"number\") return undefined;\n\t\treturn { ...parsed as SupervisorRequest, channelDir, requestFile: file };\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction listRequestFiles(): Array<{ channelDir: string; file: string }> {\n\tlet channelEntries: fs.Dirent[];\n\ttry {\n\t\tchannelEntries = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true });\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\tthrow error;\n\t}\n\tconst files: Array<{ channelDir: string; file: string }> = [];\n\tfor (const entry of channelEntries) {\n\t\tif (!entry.isDirectory()) continue;\n\t\tconst channelDir = path.join(SUPERVISOR_CHANNEL_ROOT, entry.name);\n\t\tconst requestsDir = path.join(channelDir, REQUESTS_DIR);\n\t\tlet requestEntries: fs.Dirent[];\n\t\ttry {\n\t\t\trequestEntries = fs.readdirSync(requestsDir, { withFileTypes: true });\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const requestEntry of requestEntries) {\n\t\t\tif (requestEntry.isFile() && requestEntry.name.endsWith(\".json\")) files.push({ channelDir, file: path.join(requestsDir, requestEntry.name) });\n\t\t}\n\t}\n\treturn files;\n}\n\nfunction readDirectoryEntries(dir: string): fs.Dirent[] | undefined {\n\ttry {\n\t\treturn fs.readdirSync(dir, { withFileTypes: true });\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\treturn undefined;\n\t}\n}\n\nfunction directoryMtimeMs(dir: string): number {\n\ttry {\n\t\treturn fs.statSync(dir).mtimeMs;\n\t} catch {\n\t\treturn 0;\n\t}\n}\n\nfunction removeEmptyDirectory(dir: string): boolean {\n\ttry {\n\t\tfs.rmdirSync(dir);\n\t\treturn true;\n\t} catch (error) {\n\t\tconst code = (error as NodeJS.ErrnoException).code;\n\t\tif (code === \"ENOENT\") return true;\n\t\tif (code === \"ENOTEMPTY\" || code === \"EEXIST\" || code === \"EPERM\" || code === \"EBUSY\") return false;\n\t\tthrow error;\n\t}\n}\n\nfunction removeStaleEmptySupervisorChannel(channelDir: string, nowMs: number): boolean {\n\tconst requestsDir = path.join(channelDir, REQUESTS_DIR);\n\tconst repliesDir = path.join(channelDir, REPLIES_DIR);\n\tconst newestKnownMtimeMs = Math.max(\n\t\tdirectoryMtimeMs(channelDir),\n\t\tdirectoryMtimeMs(requestsDir),\n\t\tdirectoryMtimeMs(repliesDir),\n\t);\n\tif (nowMs - newestKnownMtimeMs < STALE_EMPTY_CHANNEL_AGE_MS) return false;\n\n\tconst requestEntries = readDirectoryEntries(requestsDir);\n\tif (!requestEntries || requestEntries.length > 0) return false;\n\tconst replyEntries = readDirectoryEntries(repliesDir);\n\tif (!replyEntries || replyEntries.length > 0) return false;\n\n\tif (!removeEmptyDirectory(requestsDir)) return false;\n\tif (!removeEmptyDirectory(repliesDir)) return false;\n\tif (!removeEmptyDirectory(channelDir)) return false;\n\treturn true;\n}\n\nfunction cleanupStaleEmptySupervisorChannels(nowMs = Date.now()): number {\n\tlet channelEntries: fs.Dirent[];\n\ttry {\n\t\tchannelEntries = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true });\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return 0;\n\t\tthrow error;\n\t}\n\n\tlet removed = 0;\n\tfor (const entry of channelEntries) {\n\t\tif (!entry.isDirectory()) continue;\n\t\ttry {\n\t\t\tif (removeStaleEmptySupervisorChannel(path.join(SUPERVISOR_CHANNEL_ROOT, entry.name), nowMs)) removed++;\n\t\t} catch {\n\t\t\t// Cleanup is opportunistic; active writers can race with us and will be picked up by a later pass.\n\t\t}\n\t}\n\treturn removed;\n}\n\nfunction currentContextSessionId(state: Pick<SubagentState, \"currentSessionId\">, ctx: ExtensionContext): string | undefined {\n\ttry {\n\t\tconst sessionId = ctx.sessionManager.getSessionId();\n\t\tif (sessionId) return sessionId;\n\t} catch {\n\t\t// Fall through to the last known identity.\n\t}\n\treturn state.currentSessionId ?? undefined;\n}\n\nfunction requestMatchesContext(request: SupervisorRequest, state: Pick<SubagentState, \"currentSessionId\">, ctx: ExtensionContext): boolean {\n\tconst currentSessionId = currentContextSessionId(state, ctx);\n\treturn Boolean(currentSessionId && request.orchestratorSessionId === currentSessionId);\n}\n\nfunction removeRequestFile(file: string): void {\n\ttry {\n\t\tfs.rmSync(file, { force: true });\n\t} catch {\n\t\t// Request cleanup is best-effort; reply files and timeout errors remain authoritative.\n\t}\n}\n\ntype SupervisorRequestLifecycle = \"pending\" | \"resolved\" | \"expired\" | \"inactive\" | \"missing\" | \"wrong-session\";\n\nfunction requestExpiresAt(request: SupervisorRequest, now: number): number {\n\tconst expiresAt = (request as { expiresAt?: unknown }).expiresAt;\n\tif (typeof expiresAt === \"number\" && Number.isFinite(expiresAt)) return expiresAt;\n\treturn Number.isFinite(request.createdAt) ? request.createdAt + askTimeoutMs() : now;\n}\n\nfunction requestRunInactive(request: SupervisorRequest, state: SubagentState): boolean {\n\tif (state.foregroundControls.has(request.runId)) return false;\n\tconst foregroundRun = state.foregroundRuns?.get(request.runId);\n\tconst foregroundChild = foregroundRun?.children.find((child) => child.index === request.childIndex && child.agent === request.agent)\n\t\t?? foregroundRun?.children[request.childIndex];\n\tif (foregroundChild) return foregroundChild.status !== \"detached\";\n\n\tconst asyncJob = state.asyncJobs.get(request.runId);\n\tif (!asyncJob) return false;\n\tif (asyncJob.status === \"complete\" || asyncJob.status === \"failed\" || asyncJob.status === \"paused\") return true;\n\tconst stepStatus = asyncJob.steps?.[request.childIndex]?.status;\n\treturn stepStatus === \"complete\" || stepStatus === \"completed\" || stepStatus === \"failed\" || stepStatus === \"paused\";\n}\n\nfunction requestLifecycle(request: PendingSupervisorRequest, state: SubagentState, ctx: ExtensionContext | undefined, now: number): SupervisorRequestLifecycle {\n\tif (ctx && !requestMatchesContext(request, state, ctx)) return \"wrong-session\";\n\tif (!fs.existsSync(request.requestFile)) return \"missing\";\n\tif (request.expectsReply && fs.existsSync(replyPath(request.channelDir, request.id))) return \"resolved\";\n\tif (request.expectsReply && now > requestExpiresAt(request, now)) return \"expired\";\n\tif (request.expectsReply && requestRunInactive(request, state)) return \"inactive\";\n\treturn \"pending\";\n}\n\nfunction cleanupRequestLifecycle(request: PendingSupervisorRequest, lifecycle: SupervisorRequestLifecycle): void {\n\tif (lifecycle === \"resolved\" || lifecycle === \"expired\" || lifecycle === \"inactive\") removeRequestFile(request.requestFile);\n}\n\nfunction refreshPendingRequests(pending: Map<string, PendingSupervisorRequest>, state: SubagentState, ctx: ExtensionContext | undefined): void {\n\tconst now = Date.now();\n\tfor (const request of pending.values()) {\n\t\tconst lifecycle = requestLifecycle(request, state, ctx, now);\n\t\tif (lifecycle === \"pending\") continue;\n\t\tpending.delete(request.id);\n\t\tcleanupRequestLifecycle(request, lifecycle);\n\t}\n}\n\nfunction formatPendingLine(request: PendingSupervisorRequest): string {\n\tconst replyHint = request.expectsReply ? ` Reply: ${NATIVE_SUPERVISOR_TOOL_NAME}({ action: \"reply\", replyTo: \"${request.id}\", message: \"...\" })` : \"\";\n\treturn `- ${request.id}: ${request.agent} [${request.runId}#${request.childIndex}] ${request.reason}.${replyHint}`;\n}\n\nfunction requestVisibleText(request: PendingSupervisorRequest): string {\n\tconst lines = [request.message];\n\tif (request.expectsReply) {\n\t\tlines.push(\"\", `Reply with: ${NATIVE_SUPERVISOR_TOOL_NAME}({ action: \"reply\", replyTo: \"${request.id}\", message: \"...\" })`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction writeReply(request: PendingSupervisorRequest, message: string): void {\n\tif (!message.trim()) throw new Error(\"message is required for supervisor replies.\");\n\tconst reply: SupervisorReply = {\n\t\ttype: \"subagent.supervisor.reply\",\n\t\trequestId: request.id,\n\t\tcreatedAt: Date.now(),\n\t\tmessage: message.trim(),\n\t};\n\twriteAtomicJson(replyPath(request.channelDir, request.id), reply);\n\tremoveRequestFile(request.requestFile);\n}\n\nfunction resolvePendingRequest(pending: Map<string, PendingSupervisorRequest>, params: IntercomParams): PendingSupervisorRequest {\n\tif (params.replyTo) {\n\t\tconst request = pending.get(params.replyTo);\n\t\tif (!request) throw new Error(`No pending supervisor request found for replyTo '${params.replyTo}'.`);\n\t\treturn request;\n\t}\n\tconst requests = [...pending.values()].filter((request) => request.expectsReply);\n\tif (params.to) {\n\t\tconst normalizedTo = params.to.toLowerCase();\n\t\tconst matches = requests.filter((request) =>\n\t\t\trequest.id.toLowerCase().startsWith(normalizedTo)\n\t\t\t|| request.agent.toLowerCase() === normalizedTo\n\t\t\t|| request.childTarget?.toLowerCase() === normalizedTo,\n\t\t);\n\t\tif (matches.length === 1) return matches[0]!;\n\t\tif (matches.length > 1) throw new Error(`Multiple pending supervisor requests match '${params.to}'. Use replyTo.`);\n\t}\n\tif (requests.length === 1) return requests[0]!;\n\tif (requests.length === 0) throw new Error(\"No pending supervisor requests need a reply.\");\n\tthrow new Error(\"Multiple pending supervisor requests need replies. Use replyTo.\");\n}\n\nfunction publicPendingRequests(pending: Map<string, PendingSupervisorRequest>): Array<Record<string, unknown>> {\n\treturn [...pending.values()].map((request) => ({\n\t\tid: request.id,\n\t\trunId: request.runId,\n\t\tagent: request.agent,\n\t\tchildIndex: request.childIndex,\n\t\treason: request.reason,\n\t\texpectsReply: request.expectsReply,\n\t}));\n}\n\nfunction buildParentIntercomTool(pending: Map<string, PendingSupervisorRequest>, state: SubagentState, name = \"intercom\"): ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> {\n\treturn {\n\t\tname,\n\t\tlabel: name === \"intercom\" ? \"Intercom\" : \"Subagent Supervisor\",\n\t\tdescription: name === \"intercom\"\n\t\t\t? \"Native pi-subagents supervisor channel. Use reply/pending/status to answer child subagent requests.\"\n\t\t\t: \"Native pi-subagents supervisor channel. Use reply/pending/status to answer child subagent requests without overriding pi-intercom.\",\n\t\tparameters: IntercomParamsSchema,\n\t\tasync execute(_id, params) {\n\t\t\trefreshPendingRequests(pending, state, state.lastUiContext ?? undefined);\n\t\t\tconst input = params as IntercomParams;\n\t\t\tif (input.action === \"status\") {\n\t\t\t\treturn { content: [{ type: \"text\", text: `Native supervisor channel active. Pending replies: ${pending.size}.` }], details: { active: true, pending: pending.size, root: SUPERVISOR_CHANNEL_ROOT } };\n\t\t\t}\n\t\t\tif (input.action === \"pending\" || input.action === \"list\") {\n\t\t\t\tconst lines = [...pending.values()].filter((request) => request.expectsReply).map(formatPendingLine);\n\t\t\t\treturn { content: [{ type: \"text\", text: lines.length ? lines.join(\"\\n\") : \"No pending supervisor requests.\" }], details: { pending: publicPendingRequests(pending) } };\n\t\t\t}\n\t\t\tif (input.action === \"reply\") {\n\t\t\t\tconst request = resolvePendingRequest(pending, input);\n\t\t\t\twriteReply(request, input.message ?? \"\");\n\t\t\t\tpending.delete(request.id);\n\t\t\t\treturn { content: [{ type: \"text\", text: `Replied to supervisor request ${request.id}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent } };\n\t\t\t}\n\t\t\tif (input.action === \"send\" || input.action === \"ask\") {\n\t\t\t\tthrow new Error(\"Native pi-subagents intercom currently handles supervisor replies. Child agents initiate asks with contact_supervisor.\");\n\t\t\t}\n\t\t\tthrow new Error(`Unsupported intercom action: ${input.action}`);\n\t\t},\n\t};\n}\n\nexport function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentState): { start: () => void; dispose: () => void; pending: Map<string, PendingSupervisorRequest> } {\n\tconst pending = new Map<string, PendingSupervisorRequest>();\n\tconst seenFiles = new Set<string>();\n\tlet poller: ReturnType<typeof setInterval> | undefined;\n\tlet lastStaleCleanupAt = 0;\n\n\tconst registerParentTools = (): void => {\n\t\tif (!hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME)) pi.registerTool(buildParentIntercomTool(pending, state, NATIVE_SUPERVISOR_TOOL_NAME));\n\t\tif (!hasTool(pi, \"intercom\")) pi.registerTool(buildParentIntercomTool(pending, state));\n\t};\n\n\tconst cleanupStaleChannelsIfDue = (): void => {\n\t\tconst nowMs = Date.now();\n\t\tif (nowMs - lastStaleCleanupAt < STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS) return;\n\t\tlastStaleCleanupAt = nowMs;\n\t\ttry {\n\t\t\tcleanupStaleEmptySupervisorChannels(nowMs);\n\t\t} catch {\n\t\t\t// Supervisor delivery must not fail because best-effort temp cleanup failed.\n\t\t}\n\t};\n\n\tconst poll = (): void => {\n\t\tcleanupStaleChannelsIfDue();\n\t\tconst ctx = state.lastUiContext;\n\t\tif (!ctx) return;\n\t\trefreshPendingRequests(pending, state, ctx);\n\t\tconst now = Date.now();\n\t\tfor (const { channelDir, file } of listRequestFiles()) {\n\t\t\tif (seenFiles.has(file)) continue;\n\t\t\tconst request = parseRequestFile(file, channelDir);\n\t\t\tif (!request || !requestMatchesContext(request, state, ctx)) continue;\n\t\t\tconst lifecycle = requestLifecycle(request, state, undefined, now);\n\t\t\tif (lifecycle !== \"pending\") {\n\t\t\t\tseenFiles.add(file);\n\t\t\t\tcleanupRequestLifecycle(request, lifecycle);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tseenFiles.add(file);\n\t\t\tif (request.expectsReply) pending.set(request.id, request);\n\t\t\telse {\n\t\t\t\tremoveRequestFile(request.requestFile);\n\t\t\t}\n\t\t\tpi.sendMessage({\n\t\t\t\tcustomType: \"subagent_supervisor_request\",\n\t\t\t\tcontent: requestVisibleText(request),\n\t\t\t\tdisplay: true,\n\t\t\t\tdetails: {\n\t\t\t\t\tid: request.id,\n\t\t\t\t\treason: request.reason,\n\t\t\t\t\texpectsReply: request.expectsReply,\n\t\t\t\t\trunId: request.runId,\n\t\t\t\t\tagent: request.agent,\n\t\t\t\t\tchildIndex: request.childIndex,\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (request.expectsReply) {\n\t\t\t\t(pi as { events?: IntercomEventBus }).events?.emit(INTERCOM_DETACH_REQUEST_EVENT, {\n\t\t\t\t\trequestId: request.id,\n\t\t\t\t\trunId: request.runId,\n\t\t\t\t\tagent: request.agent,\n\t\t\t\t\tchildIndex: request.childIndex,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t};\n\n\treturn {\n\t\tstart: () => {\n\t\t\tif (poller) return;\n\t\t\tregisterParentTools();\n\t\t\tpoll();\n\t\t\tpoller = setInterval(poll, CHANNEL_POLL_MS);\n\t\t\tpoller.unref?.();\n\t\t},\n\t\tdispose: () => {\n\t\t\tif (poller) clearInterval(poller);\n\t\t\tpoller = undefined;\n\t\t\tpending.clear();\n\t\t\tseenFiles.clear();\n\t\t},\n\t\tpending,\n\t};\n}\n"]}
1
+ {"version":3,"file":"native-supervisor-channel.d.ts","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAoC,MAAM,iCAAiC,CAAC;AAWtG,OAAO,EAAkG,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGxJ,OAAO,EAeN,2BAA2B,IAAI,yBAAyB,EAQxD,MAAM,2BAA2B,CAAC;AAInC,eAAO,MAAM,2BAA2B,wBAAwB,CAAC;AACjE,eAAO,MAAM,2BAA2B,kCAA4B,CAAC;AAOrE,KAAK,gBAAgB,GAAG,eAAe,GAAG,mBAAmB,GAAG,iBAAiB,CAAC;AAElF,UAAU,iBAAiB;IAC1B,IAAI,EAAE,6BAA6B,CAAC;IACpC,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,gBAAgB,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,OAAO,CAAC;IACtB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,OAAO,CAAC;CACpB;AAED,UAAU,wBAAyB,SAAQ,iBAAiB;IAC3D,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;CACpB;AAwED,wBAAgB,0BAA0B,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAInE;AAmPD,wBAAgB,8BAA8B,CAAC,EAAE,EAAE,YAAY,EAAE,OAAO,GAAE;IAAE,uBAAuB,CAAC,EAAE,OAAO,CAAA;CAAO,GAAG,IAAI,CAgC1H;AAiBD,wBAAgB,mCAAmC,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,EAAE,GAAG,SAAa,GAAG,OAAO,CAYvH;AAuUD,wBAAgB,6BAA6B,CAAC,EAAE,EAAE,YAAY,EAAE,KAAK,EAAE,aAAa,GAAG;IACtF,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,wBAAwB,CAAC,CAAC;IAC/C,oBAAoB,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;IAC/C,kBAAkB,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;CAC5D,CAmHA;AAED,wBAAgB,gCAAgC,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAO5E;AAED,wBAAgB,wCAAwC,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAY9E","sourcesContent":["// @ts-nocheck\nimport { randomUUID } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { AgentToolResult } from \"@ashx-j/lunr-agent\";\nimport type { ExtensionAPI, ExtensionContext, ToolDefinition } from \"@ashx-j/lunr-dev\";\nimport { Type } from \"typebox\";\nimport {\n\tSUBAGENT_CHILD_AGENT_ENV,\n\tSUBAGENT_CHILD_INDEX_ENV,\n\tSUBAGENT_ORCHESTRATOR_SESSION_ID_ENV,\n\tSUBAGENT_ORCHESTRATOR_TARGET_ENV,\n\tSUBAGENT_RUN_ID_ENV,\n\tSUBAGENT_SUPERVISOR_CHANNEL_DIR_ENV,\n\tSUBAGENT_SUPERVISOR_SESSION_ID_ENV,\n} from \"../runs/shared/pi-args.ts\";\nimport { INTERCOM_DETACH_REQUEST_EVENT, POLL_INTERVAL_MS, SUBAGENT_CONTROL_EVENT, type IntercomEventBus, type SubagentState } from \"../shared/types.ts\";\nimport { writeAtomicJson } from \"../shared/atomic-json.ts\";\nimport { askRunningAsyncChild, reconcileAsyncQuestion } from \"./supervisor-ask.ts\";\nimport {\n\tanswerSupervisorQuestion,\n\tcancelPendingSupervisorQuestionsForOwner,\n\tcancelSupervisorQuestion,\n\tclaimQuestionNotification,\n\tformatSupervisorQuestionAnswer,\n\thasOutstandingQuestionForChild,\n\tisQuestionWaitActive,\n\tlistSupervisorChannelDirs,\n\tlistSupervisorQuestions,\n\tmarkSupervisorQuestionDelivered,\n\toutstandingQuestionsForChild,\n\tpendingSupervisorQuestionsForDelivery,\n\tQUESTIONS_DIR,\n\treadSupervisorQuestion,\n\tresolveSupervisorChannelDir as resolveQuestionChannelDir,\n\tSUBAGENT_QUESTION_EVENT,\n\tSUBAGENT_SUPERVISOR_ANSWER_TYPE,\n\tSUPERVISOR_CHANNEL_ROOT,\n\tsupervisorQuestionIsTerminal,\n\tsupervisorQuestionPublicState,\n\ttype SupervisorQuestion,\n\ttype SupervisorQuestionOwner,\n} from \"./supervisor-questions.ts\";\n\nconst REQUESTS_DIR = \"requests\";\nconst REPLIES_DIR = \"replies\";\nexport const NATIVE_SUPERVISOR_TOOL_NAME = \"subagent_supervisor\";\nexport const resolveSupervisorChannelDir = resolveQuestionChannelDir;\nconst MAX_MESSAGE_BYTES = 64 * 1024;\nconst DEFAULT_ASK_TIMEOUT_MS = 10 * 60 * 1000;\nconst CHANNEL_POLL_MS = Math.min(POLL_INTERVAL_MS, 500);\nconst STALE_EMPTY_CHANNEL_AGE_MS = 60 * 1000;\nconst STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS = 60 * 1000;\n\ntype SupervisorReason = \"need_decision\" | \"interview_request\" | \"progress_update\";\n\ninterface SupervisorRequest {\n\ttype: \"subagent.supervisor.request\";\n\tid: string;\n\tcreatedAt: number;\n\texpiresAt?: number;\n\treason: SupervisorReason;\n\tmessage: string;\n\texpectsReply: boolean;\n\torchestratorTarget?: string;\n\torchestratorSessionId?: string;\n\tsupervisorSessionId?: string;\n\trunId: string;\n\tagent: string;\n\tchildIndex: number;\n\tchildTarget?: string;\n\tinterview?: unknown;\n}\n\ninterface PendingSupervisorRequest extends SupervisorRequest {\n\tchannelDir: string;\n\trequestFile: string;\n}\n\ninterface SupervisorReply {\n\ttype: \"subagent.supervisor.reply\";\n\trequestId: string;\n\tcreatedAt: number;\n\tmessage: string;\n}\n\ninterface ContactSupervisorParams {\n\treason?: SupervisorReason;\n\tmessage?: string;\n\tinterview?: unknown;\n\taction?: \"reply\";\n\treplyTo?: string;\n}\n\ninterface IntercomParams {\n\taction: \"list\" | \"send\" | \"ask\" | \"reply\" | \"pending\" | \"status\";\n\tto?: string;\n\tmessage?: string;\n\treplyTo?: string;\n\tid?: string;\n\tindex?: number;\n\tchildId?: string;\n\treason?: string;\n}\n\nconst PARENT_ASK_DESCRIPTION = [\n\t\"Ask a specific running async child, or reply to a child supervisor request.\",\n\t\"Ask only when the child owns missing context, the answer changes a concrete next decision, and waiting risks a block or rework.\",\n\t\"Use available results first, batch related questions, and keep working while awaiting the answer. Do not use ask for status checks, polling, duplicate queries, or step-by-step supervision. Follow up only when the answer leaves the original decision unresolved.\",\n\t\"Returns a question id immediately. The child's explicit answer is delivered separately from the final run result.\",\n\t'Ask: { action: \"ask\", id: \"<runId>\", index?: 0, childId?: \"...\", reason: \"<concrete decision>\", message: \"...\" }',\n\t\"Use pending or list to find child requests awaiting your reply; status reports channel availability. Free-form send is unsupported. Asking never revives a child or changes its assignment.\",\n\t'Reply: { action: \"reply\", replyTo: \"<requestId>\", message: \"...\" }',\n].join(\" \");\n\nconst CHILD_CONTACT_DESCRIPTION = [\n\t\"Contact the parent/supervisor session for a blocking decision, structured interview, progress update, or reply to a parent question.\",\n\t\"For parent questions use action='reply' with replyTo set to the question id. Answer from current findings and uncertainty; do not start extra investigation just to reply. Continue the assigned task after replying.\",\n\t\"Do not open a blocking need_decision while a parent question is already outstanding for this child.\",\n].join(\" \");\n\nconst ContactSupervisorParamsSchema = Type.Object({\n\treason: Type.Optional(Type.String({ enum: [\"need_decision\", \"interview_request\", \"progress_update\"] })),\n\tmessage: Type.Optional(Type.String()),\n\tinterview: Type.Optional(Type.Unsafe({ type: \"object\", additionalProperties: true })),\n\taction: Type.Optional(Type.String({ enum: [\"reply\"] })),\n\treplyTo: Type.Optional(Type.String()),\n}, { additionalProperties: false });\n\nconst IntercomParamsSchema = Type.Object({\n\taction: Type.String({ enum: [\"list\", \"send\", \"ask\", \"reply\", \"pending\", \"status\"] }),\n\tto: Type.Optional(Type.String()),\n\tmessage: Type.Optional(Type.String()),\n\treplyTo: Type.Optional(Type.String()),\n\tid: Type.Optional(Type.String({ description: \"Async run id for action='ask'.\" })),\n\tindex: Type.Optional(Type.Integer({ minimum: 0, description: \"Zero-based child index for action='ask'. Select index or childId when more than one child is running.\" })),\n\tchildId: Type.Optional(Type.String({ description: \"Private child identity for action='ask'.\" })),\n\treason: Type.Optional(Type.String({ description: \"Concrete decision the child's answer will change. Required for action='ask'.\" })),\n}, { additionalProperties: false });\n\nconst ParentSupervisorParamsSchema = Type.Object({\n\t...IntercomParamsSchema.properties,\n\taction: Type.String({ enum: [\"list\", \"ask\", \"reply\", \"pending\", \"status\"] }),\n}, { additionalProperties: false });\n\nfunction safeSegment(value: string): string {\n\treturn value.trim().replace(/[^A-Za-z0-9._-]+/g, \"-\").replace(/^-+|-+$/g, \"\") || \"unknown\";\n}\n\nexport function ensureSupervisorChannelDir(channelDir: string): void {\n\tfs.mkdirSync(path.join(channelDir, REQUESTS_DIR), { recursive: true, mode: 0o700 });\n\tfs.mkdirSync(path.join(channelDir, REPLIES_DIR), { recursive: true, mode: 0o700 });\n\tfs.mkdirSync(path.join(channelDir, QUESTIONS_DIR), { recursive: true, mode: 0o700 });\n}\n\nfunction requestPath(channelDir: string, requestId: string): string {\n\treturn path.join(channelDir, REQUESTS_DIR, `${safeSegment(requestId)}.json`);\n}\n\nfunction replyPath(channelDir: string, requestId: string): string {\n\treturn path.join(channelDir, REPLIES_DIR, `${safeSegment(requestId)}.json`);\n}\n\nfunction readTextEnv(name: string): string | undefined {\n\tconst value = process.env[name]?.trim();\n\treturn value ? value : undefined;\n}\n\nfunction readChildMetadata(): {\n\tchannelDir: string;\n\trunId: string;\n\tagent: string;\n\tchildIndex: number;\n\torchestratorTarget?: string;\n\torchestratorSessionId?: string;\n\tchildTarget?: string;\n\tsupervisorSessionId?: string;\n} | undefined {\n\tconst channelDir = readTextEnv(SUBAGENT_SUPERVISOR_CHANNEL_DIR_ENV);\n\tconst runId = readTextEnv(SUBAGENT_RUN_ID_ENV);\n\tconst agent = readTextEnv(SUBAGENT_CHILD_AGENT_ENV);\n\tconst rawIndex = readTextEnv(SUBAGENT_CHILD_INDEX_ENV);\n\tconst orchestratorSessionId = readTextEnv(SUBAGENT_ORCHESTRATOR_SESSION_ID_ENV);\n\tif (!channelDir || !runId || !agent || !orchestratorSessionId || rawIndex === undefined || !/^\\d+$/.test(rawIndex)) return undefined;\n\treturn {\n\t\tchannelDir,\n\t\trunId,\n\t\tagent,\n\t\tchildIndex: Number(rawIndex),\n\t\torchestratorTarget: readTextEnv(SUBAGENT_ORCHESTRATOR_TARGET_ENV),\n\t\torchestratorSessionId,\n\t\tsupervisorSessionId: readTextEnv(SUBAGENT_SUPERVISOR_SESSION_ID_ENV),\n\t\tchildTarget: readTextEnv(\"PI_SUBAGENT_INTERCOM_SESSION_NAME\"),\n\t};\n}\n\nfunction readChildQuestionOwner(metadata = readChildMetadata()): SupervisorQuestionOwner | undefined {\n\tif (!metadata) return undefined;\n\tconst readyAt = Number(process.env.PI_SUBAGENT_STEER_READY_AT);\n\tif (!Number.isFinite(readyAt) || readyAt <= 0) return undefined;\n\treturn {\n\t\trunId: metadata.runId,\n\t\tchildIndex: metadata.childIndex,\n\t\tchildId: metadata.agent,\n\t\tpid: process.pid,\n\t\treadyAt,\n\t};\n}\n\nfunction answerParentQuestion(params: ContactSupervisorParams): AgentToolResult<Record<string, unknown>> {\n\tconst metadata = readChildMetadata();\n\tconst owner = readChildQuestionOwner(metadata);\n\tif (!metadata || !owner) throw new Error(\"Native supervisor channel is not available for this subagent.\");\n\tconst replyTo = params.replyTo?.trim();\n\tif (!replyTo) throw new Error(\"action='reply' requires replyTo with the parent question id.\");\n\tconst message = params.message?.trim();\n\tif (!message) throw new Error(\"message is required for supervisor question replies.\");\n\tconst question = readSupervisorQuestion(metadata.channelDir, replyTo);\n\tif (question?.parentSessionId !== (metadata.supervisorSessionId ?? metadata.orchestratorSessionId)) throw new Error(\"Question belongs to a different supervisor session.\");\n\tconst answered = answerSupervisorQuestion(metadata.channelDir, replyTo, message, owner);\n\treturn {\n\t\tcontent: [{ type: \"text\", text: `Replied to parent question ${answered.id}. Continue the assigned task.` }],\n\t\tdetails: {\n\t\t\treplyTo: answered.id,\n\t\t\tstate: supervisorQuestionPublicState(answered),\n\t\t\tanswered: true,\n\t\t},\n\t};\n}\n\nfunction reasonHeading(reason: SupervisorReason): string {\n\tif (reason === \"interview_request\") return \"Subagent requests a structured supervisor interview.\";\n\tif (reason === \"progress_update\") return \"Subagent progress update.\";\n\treturn \"Subagent needs a supervisor decision.\";\n}\n\nfunction formatChildMessage(input: {\n\treason: SupervisorReason;\n\tmessage?: string;\n\tinterview?: unknown;\n\trunId: string;\n\tagent: string;\n\tchildIndex: number;\n\tchildTarget?: string;\n}): string {\n\tconst lines = [\n\t\treasonHeading(input.reason),\n\t\t`Run: ${input.runId}`,\n\t\t`Agent: ${input.agent}`,\n\t\t`Child index: ${input.childIndex}`,\n\t];\n\tif (input.childTarget) lines.push(`Child intercom target: ${input.childTarget}`);\n\tlines.push(\"\");\n\tif (input.message?.trim()) lines.push(input.message.trim());\n\tif (input.reason === \"interview_request\") {\n\t\tlines.push(\n\t\t\t\"\",\n\t\t\t\"Structured response requested. Reply with JSON, optionally fenced in ```json, matching the requested interview shape.\",\n\t\t);\n\t\tif (input.interview !== undefined) lines.push(JSON.stringify(input.interview, null, \"\\t\"));\n\t}\n\treturn lines.join(\"\\n\").trimEnd();\n}\n\nfunction parseStructuredReply(message: string): { value?: unknown; error?: string } {\n\tconst trimmed = message.trim();\n\tconst fenced = trimmed.match(/^```(?:json)?\\s*([\\s\\S]*?)\\s*```$/i)?.[1]?.trim();\n\ttry {\n\t\treturn { value: JSON.parse(fenced ?? trimmed) };\n\t} catch (error) {\n\t\treturn { error: error instanceof Error ? `${error.name}: ${error.message}` : String(error) };\n\t}\n}\n\nfunction askTimeoutMs(): number {\n\tconst parsed = Number(process.env.PI_INTERCOM_ASK_TIMEOUT_MS);\n\treturn Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_ASK_TIMEOUT_MS;\n}\n\nfunction delay(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new Error(\"Supervisor request cancelled.\"));\n\t\t\treturn;\n\t\t}\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tconst cleanup = () => {\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tcleanup();\n\t\t\treject(new Error(\"Supervisor request cancelled.\"));\n\t\t};\n\t\ttimer = setTimeout(() => {\n\t\t\tcleanup();\n\t\t\tresolve();\n\t\t}, ms);\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nasync function waitForReply(channelDir: string, requestId: string, deadline: number, signal?: AbortSignal): Promise<SupervisorReply> {\n\tconst file = replyPath(channelDir, requestId);\n\twhile (Date.now() <= deadline) {\n\t\tif (signal?.aborted) throw new Error(\"Supervisor request cancelled.\");\n\t\tif (fs.existsSync(file)) {\n\t\t\tconst parsed = JSON.parse(fs.readFileSync(file, \"utf-8\")) as Partial<SupervisorReply>;\n\t\t\tif (parsed.type === \"subagent.supervisor.reply\" && parsed.requestId === requestId && typeof parsed.message === \"string\") {\n\t\t\t\treturn parsed as SupervisorReply;\n\t\t\t}\n\t\t}\n\t\tawait delay(250, signal);\n\t}\n\tthrow new Error(\"Timed out waiting for supervisor reply.\");\n}\n\nasync function sendSupervisorRequest(params: ContactSupervisorParams, signal?: AbortSignal): Promise<AgentToolResult<Record<string, unknown>>> {\n\tif (params.action === \"reply\" || params.replyTo?.trim()) {\n\t\treturn answerParentQuestion(params);\n\t}\n\tconst metadata = readChildMetadata();\n\tif (!metadata) throw new Error(\"Native supervisor channel is not available for this subagent.\");\n\tif (!params.reason) throw new Error(\"reason is required for supervisor contact.\");\n\tif (params.reason !== \"progress_update\" && hasOutstandingQuestionForChild(metadata.channelDir, metadata.childIndex, metadata.agent)) {\n\t\tthrow new Error(\"A parent question is already outstanding for this child. Answer it with action='reply' before opening a blocking supervisor request.\");\n\t}\n\tif (params.reason !== \"progress_update\" && !params.message?.trim() && params.reason !== \"interview_request\") {\n\t\tthrow new Error(\"message is required for supervisor decisions.\");\n\t}\n\tensureSupervisorChannelDir(metadata.channelDir);\n\tconst requestId = randomUUID();\n\tconst expectsReply = params.reason !== \"progress_update\";\n\tconst createdAt = Date.now();\n\tconst replyDeadline = createdAt + askTimeoutMs();\n\tconst expiresAt = expectsReply ? replyDeadline : undefined;\n\tconst message = formatChildMessage({ ...metadata, reason: params.reason, message: params.message, interview: params.interview });\n\tconst request: SupervisorRequest = {\n\t\ttype: \"subagent.supervisor.request\",\n\t\tid: requestId,\n\t\tcreatedAt,\n\t\t...(expiresAt !== undefined ? { expiresAt } : {}),\n\t\treason: params.reason,\n\t\tmessage,\n\t\texpectsReply,\n\t\t...(metadata.orchestratorTarget ? { orchestratorTarget: metadata.orchestratorTarget } : {}),\n\t\t...(metadata.orchestratorSessionId ? { orchestratorSessionId: metadata.orchestratorSessionId } : {}),\n\t\t...(metadata.supervisorSessionId ? { supervisorSessionId: metadata.supervisorSessionId } : {}),\n\t\trunId: metadata.runId,\n\t\tagent: metadata.agent,\n\t\tchildIndex: metadata.childIndex,\n\t\t...(metadata.childTarget ? { childTarget: metadata.childTarget } : {}),\n\t\t...(params.interview !== undefined ? { interview: params.interview } : {}),\n\t};\n\tconst serialized = JSON.stringify(request, null, \"\\t\");\n\tif (Buffer.byteLength(serialized, \"utf-8\") > MAX_MESSAGE_BYTES) throw new Error(\"Supervisor request is too large.\");\n\twriteAtomicJson(requestPath(metadata.channelDir, requestId), request);\n\tif (expectsReply) {\n\t\tfor (const question of outstandingQuestionsForChild(metadata.channelDir, metadata.childIndex, metadata.agent)) {\n\t\t\tcancelSupervisorQuestion(metadata.channelDir, question.id, \"child needs a supervisor decision; reply to its request first\");\n\t\t}\n\t}\n\n\tif (!expectsReply) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: \"Supervisor progress update queued.\" }],\n\t\t\tdetails: { delivered: true, requestId, reason: params.reason },\n\t\t};\n\t}\n\n\ttry {\n\t\tconst reply = await waitForReply(metadata.channelDir, requestId, replyDeadline, signal);\n\t\tconst details: Record<string, unknown> = { requestId, reason: params.reason };\n\t\tif (params.reason === \"interview_request\") {\n\t\t\tconst structured = parseStructuredReply(reply.message);\n\t\t\tif (structured.error) details.structuredReplyParseError = structured.error;\n\t\t\telse details.structuredReply = structured.value;\n\t\t}\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `**Reply from supervisor:**\\n${reply.message}` }],\n\t\t\tdetails,\n\t\t};\n\t} catch (error) {\n\t\tremoveRequestFile(requestPath(metadata.channelDir, requestId));\n\t\tthrow error;\n\t}\n}\n\nfunction hasTool(pi: ExtensionAPI, name: string): boolean {\n\ttry {\n\t\treturn pi.getAllTools?.().some((tool: { name?: unknown }) => tool.name === name) === true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function registerNativeSupervisorClient(pi: ExtensionAPI, options: { includeIntercomFallback?: boolean } = {}): void {\n\tif (!readChildMetadata()) return;\n\tconst includeIntercomFallback = options.includeIntercomFallback !== false;\n\tif (!hasTool(pi, \"contact_supervisor\")) {\n\t\tconst tool: ToolDefinition<typeof ContactSupervisorParamsSchema, Record<string, unknown>> = {\n\t\t\tname: \"contact_supervisor\",\n\t\t\tlabel: \"Contact Supervisor\",\n\t\t\tdescription: CHILD_CONTACT_DESCRIPTION,\n\t\t\tparameters: ContactSupervisorParamsSchema,\n\t\t\texecute(_id, params, signal) {\n\t\t\t\treturn sendSupervisorRequest(params as ContactSupervisorParams, signal);\n\t\t\t},\n\t\t};\n\t\tpi.registerTool(tool);\n\t}\n\tif (includeIntercomFallback && !hasTool(pi, \"intercom\")) {\n\t\tconst tool: ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> = {\n\t\t\tname: \"intercom\",\n\t\t\tlabel: \"Intercom\",\n\t\t\tdescription: \"Native supervisor-channel intercom fallback for subagents. Prefer contact_supervisor when available.\",\n\t\t\tparameters: IntercomParamsSchema,\n\t\t\tasync execute(_id, params, signal) {\n\t\t\t\tconst action = (params as IntercomParams).action;\n\t\t\t\tif (action === \"status\") return { content: [{ type: \"text\", text: \"Native supervisor channel is active.\" }], details: { active: true } };\n\t\t\t\tif (action === \"list\") return { content: [{ type: \"text\", text: \"Supervisor session available through contact_supervisor.\" }], details: { sessions: [] } };\n\t\t\t\tif (action === \"send\") return sendSupervisorRequest({ reason: \"progress_update\", message: (params as IntercomParams).message ?? \"\" }, signal);\n\t\t\t\tif (action === \"ask\") return sendSupervisorRequest({ reason: \"need_decision\", message: (params as IntercomParams).message ?? \"\" }, signal);\n\t\t\t\tthrow new Error(\"Native child intercom supports status, list, send, and ask. Use parent intercom reply from the supervisor session.\");\n\t\t\t},\n\t\t};\n\t\tpi.registerTool(tool);\n\t}\n}\n\nfunction parseRequestFile(file: string, channelDir: string): PendingSupervisorRequest | undefined {\n\ttry {\n\t\tconst parsed = JSON.parse(fs.readFileSync(file, \"utf-8\")) as Partial<SupervisorRequest>;\n\t\tif (parsed.type !== \"subagent.supervisor.request\") return undefined;\n\t\tif (parsed.supervisorSessionId !== undefined && (typeof parsed.supervisorSessionId !== \"string\" || !parsed.supervisorSessionId.trim())) return undefined;\n\t\tif (typeof parsed.id !== \"string\" || !parsed.id) return undefined;\n\t\tif (parsed.reason !== \"need_decision\" && parsed.reason !== \"interview_request\" && parsed.reason !== \"progress_update\") return undefined;\n\t\tif (typeof parsed.message !== \"string\" || !parsed.message) return undefined;\n\t\tif (typeof parsed.runId !== \"string\" || typeof parsed.agent !== \"string\" || typeof parsed.childIndex !== \"number\") return undefined;\n\t\treturn { ...parsed as SupervisorRequest, channelDir, requestFile: file };\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function hasPendingBlockingSupervisorRequest(runId: string, sessionId?: string | null, now = Date.now()): boolean {\n\tif (!runId) return false;\n\tfor (const { channelDir, file } of listRequestFiles()) {\n\t\tconst request = parseRequestFile(file, channelDir);\n\t\tif (!request?.expectsReply) continue;\n\t\tif (request.runId !== runId) continue;\n\t\tif (sessionId && (request.supervisorSessionId ?? request.orchestratorSessionId) !== sessionId) continue;\n\t\tif (fs.existsSync(replyPath(request.channelDir, request.id))) continue;\n\t\tif (now > requestExpiresAt(request, now)) continue;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nfunction listRequestFiles(): Array<{ channelDir: string; file: string }> {\n\tlet channelEntries: fs.Dirent[];\n\ttry {\n\t\tchannelEntries = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true });\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\tthrow error;\n\t}\n\tconst files: Array<{ channelDir: string; file: string }> = [];\n\tfor (const entry of channelEntries) {\n\t\tif (!entry.isDirectory()) continue;\n\t\tconst channelDir = path.join(SUPERVISOR_CHANNEL_ROOT, entry.name);\n\t\tconst requestsDir = path.join(channelDir, REQUESTS_DIR);\n\t\tlet requestEntries: fs.Dirent[];\n\t\ttry {\n\t\t\trequestEntries = fs.readdirSync(requestsDir, { withFileTypes: true });\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const requestEntry of requestEntries) {\n\t\t\tif (requestEntry.isFile() && requestEntry.name.endsWith(\".json\")) files.push({ channelDir, file: path.join(requestsDir, requestEntry.name) });\n\t\t}\n\t}\n\treturn files;\n}\n\nfunction readDirectoryEntries(dir: string): fs.Dirent[] | undefined {\n\ttry {\n\t\treturn fs.readdirSync(dir, { withFileTypes: true });\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\treturn undefined;\n\t}\n}\n\nfunction directoryMtimeMs(dir: string): number {\n\ttry {\n\t\treturn fs.statSync(dir).mtimeMs;\n\t} catch {\n\t\treturn 0;\n\t}\n}\n\nfunction removeEmptyDirectory(dir: string): boolean {\n\ttry {\n\t\tfs.rmdirSync(dir);\n\t\treturn true;\n\t} catch (error) {\n\t\tconst code = (error as NodeJS.ErrnoException).code;\n\t\tif (code === \"ENOENT\") return true;\n\t\tif (code === \"ENOTEMPTY\" || code === \"EEXIST\" || code === \"EPERM\" || code === \"EBUSY\") return false;\n\t\tthrow error;\n\t}\n}\n\nfunction removeStaleEmptySupervisorChannel(channelDir: string, nowMs: number): boolean {\n\tconst requestsDir = path.join(channelDir, REQUESTS_DIR);\n\tconst repliesDir = path.join(channelDir, REPLIES_DIR);\n\tconst questionsPath = path.join(channelDir, QUESTIONS_DIR);\n\tconst newestKnownMtimeMs = Math.max(\n\t\tdirectoryMtimeMs(channelDir),\n\t\tdirectoryMtimeMs(requestsDir),\n\t\tdirectoryMtimeMs(repliesDir),\n\t\tdirectoryMtimeMs(questionsPath),\n\t);\n\tif (nowMs - newestKnownMtimeMs < STALE_EMPTY_CHANNEL_AGE_MS) return false;\n\n\tconst requestEntries = readDirectoryEntries(requestsDir);\n\tif (!requestEntries || requestEntries.length > 0) return false;\n\tconst replyEntries = readDirectoryEntries(repliesDir);\n\tif (!replyEntries || replyEntries.length > 0) return false;\n\tconst questionEntries = readDirectoryEntries(questionsPath);\n\tif (!questionEntries || questionEntries.length > 0) return false;\n\n\tif (!removeEmptyDirectory(requestsDir)) return false;\n\tif (!removeEmptyDirectory(repliesDir)) return false;\n\tif (!removeEmptyDirectory(questionsPath)) return false;\n\tif (!removeEmptyDirectory(channelDir)) return false;\n\treturn true;\n}\n\nfunction cleanupStaleEmptySupervisorChannels(nowMs = Date.now()): number {\n\tlet channelEntries: fs.Dirent[];\n\ttry {\n\t\tchannelEntries = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true });\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return 0;\n\t\tthrow error;\n\t}\n\n\tlet removed = 0;\n\tfor (const entry of channelEntries) {\n\t\tif (!entry.isDirectory()) continue;\n\t\ttry {\n\t\t\tif (removeStaleEmptySupervisorChannel(path.join(SUPERVISOR_CHANNEL_ROOT, entry.name), nowMs)) removed++;\n\t\t} catch {\n\t\t\t// Cleanup is opportunistic; active writers can race with us and will be picked up by a later pass.\n\t\t}\n\t}\n\treturn removed;\n}\n\nfunction currentContextSessionId(state: Pick<SubagentState, \"currentSessionId\">, ctx: ExtensionContext): string | undefined {\n\ttry {\n\t\tconst sessionId = ctx.sessionManager.getSessionId();\n\t\tif (sessionId) return sessionId;\n\t} catch {\n\t\t// Fall through to the last known identity.\n\t}\n\treturn state.currentSessionId ?? undefined;\n}\n\nfunction currentSupervisorSessionId(state: Pick<SubagentState, \"currentSessionId\">, ctx: ExtensionContext): string | undefined {\n\ttry {\n\t\treturn ctx.sessionManager.getSessionFile?.() ?? currentContextSessionId(state, ctx);\n\t} catch {\n\t\treturn state.currentSessionId ?? undefined;\n\t}\n}\n\nfunction requestMatchesContext(request: SupervisorRequest, state: Pick<SubagentState, \"currentSessionId\">, ctx: ExtensionContext): boolean {\n\tconst currentSessionId = request.supervisorSessionId !== undefined\n\t\t? currentSupervisorSessionId(state, ctx)\n\t\t: currentContextSessionId(state, ctx);\n\treturn Boolean(currentSessionId && (request.supervisorSessionId ?? request.orchestratorSessionId) === currentSessionId);\n}\n\nfunction removeRequestFile(file: string): void {\n\ttry {\n\t\tfs.rmSync(file, { force: true });\n\t} catch {\n\t\t// Request cleanup is best-effort; reply files and timeout errors remain authoritative.\n\t}\n}\n\ntype SupervisorRequestLifecycle = \"pending\" | \"resolved\" | \"expired\" | \"inactive\" | \"missing\" | \"wrong-session\";\n\nfunction requestExpiresAt(request: SupervisorRequest, now: number): number {\n\tconst expiresAt = (request as { expiresAt?: unknown }).expiresAt;\n\tif (typeof expiresAt === \"number\" && Number.isFinite(expiresAt)) return expiresAt;\n\treturn Number.isFinite(request.createdAt) ? request.createdAt + askTimeoutMs() : now;\n}\n\nfunction requestRunInactive(request: SupervisorRequest, state: SubagentState): boolean {\n\tif (state.foregroundControls.has(request.runId)) return false;\n\tconst foregroundRun = state.foregroundRuns?.get(request.runId);\n\tconst foregroundChild = foregroundRun?.children.find((child) => child.index === request.childIndex && child.agent === request.agent)\n\t\t?? foregroundRun?.children[request.childIndex];\n\tif (foregroundChild) return foregroundChild.status !== \"detached\";\n\n\tconst asyncJob = state.asyncJobs.get(request.runId);\n\tif (!asyncJob) return false;\n\tif (asyncJob.status === \"complete\" || asyncJob.status === \"failed\" || asyncJob.status === \"paused\") return true;\n\tconst stepStatus = asyncJob.steps?.[request.childIndex]?.status;\n\treturn stepStatus === \"complete\" || stepStatus === \"completed\" || stepStatus === \"failed\" || stepStatus === \"paused\";\n}\n\nfunction requestLifecycle(request: PendingSupervisorRequest, state: SubagentState, ctx: ExtensionContext | undefined, now: number): SupervisorRequestLifecycle {\n\tif (ctx && !requestMatchesContext(request, state, ctx)) return \"wrong-session\";\n\tif (!fs.existsSync(request.requestFile)) return \"missing\";\n\tif (request.expectsReply && fs.existsSync(replyPath(request.channelDir, request.id))) return \"resolved\";\n\tif (request.expectsReply && now > requestExpiresAt(request, now)) return \"expired\";\n\tif (request.expectsReply && requestRunInactive(request, state)) return \"inactive\";\n\treturn \"pending\";\n}\n\nfunction cleanupRequestLifecycle(request: PendingSupervisorRequest, lifecycle: SupervisorRequestLifecycle): void {\n\tif (lifecycle === \"resolved\" || lifecycle === \"expired\" || lifecycle === \"inactive\") removeRequestFile(request.requestFile);\n}\n\nfunction refreshPendingRequests(pending: Map<string, PendingSupervisorRequest>, state: SubagentState, ctx: ExtensionContext | undefined): void {\n\tconst now = Date.now();\n\tfor (const request of pending.values()) {\n\t\tconst lifecycle = requestLifecycle(request, state, ctx, now);\n\t\tif (lifecycle === \"pending\") continue;\n\t\tpending.delete(request.id);\n\t\tcleanupRequestLifecycle(request, lifecycle);\n\t}\n}\n\nfunction formatPendingLine(request: PendingSupervisorRequest): string {\n\tconst replyHint = request.expectsReply ? ` Reply: ${NATIVE_SUPERVISOR_TOOL_NAME}({ action: \"reply\", replyTo: \"${request.id}\", message: \"...\" })` : \"\";\n\treturn `- ${request.id}: ${request.agent} [${request.runId}#${request.childIndex}] ${request.reason}.${replyHint}`;\n}\n\nfunction requestVisibleText(request: PendingSupervisorRequest): string {\n\tconst lines = [request.message];\n\tif (request.expectsReply) {\n\t\tlines.push(\"\", `Reply with: ${NATIVE_SUPERVISOR_TOOL_NAME}({ action: \"reply\", replyTo: \"${request.id}\", message: \"...\" })`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction writeReply(request: PendingSupervisorRequest, message: string): void {\n\tif (!message.trim()) throw new Error(\"message is required for supervisor replies.\");\n\tconst reply: SupervisorReply = {\n\t\ttype: \"subagent.supervisor.reply\",\n\t\trequestId: request.id,\n\t\tcreatedAt: Date.now(),\n\t\tmessage: message.trim(),\n\t};\n\twriteAtomicJson(replyPath(request.channelDir, request.id), reply);\n\tremoveRequestFile(request.requestFile);\n}\n\nfunction resolvePendingRequest(pending: Map<string, PendingSupervisorRequest>, params: IntercomParams): PendingSupervisorRequest {\n\tif (params.replyTo) {\n\t\tconst request = pending.get(params.replyTo);\n\t\tif (!request) throw new Error(`No pending supervisor request found for replyTo '${params.replyTo}'.`);\n\t\treturn request;\n\t}\n\tconst requests = [...pending.values()].filter((request) => request.expectsReply);\n\tif (params.to) {\n\t\tconst normalizedTo = params.to.toLowerCase();\n\t\tconst matches = requests.filter((request) =>\n\t\t\trequest.id.toLowerCase().startsWith(normalizedTo)\n\t\t\t|| request.agent.toLowerCase() === normalizedTo\n\t\t\t|| request.childTarget?.toLowerCase() === normalizedTo,\n\t\t);\n\t\tif (matches.length === 1) return matches[0]!;\n\t\tif (matches.length > 1) throw new Error(`Multiple pending supervisor requests match '${params.to}'. Use replyTo.`);\n\t}\n\tif (requests.length === 1) return requests[0]!;\n\tif (requests.length === 0) throw new Error(\"No pending supervisor requests need a reply.\");\n\tthrow new Error(\"Multiple pending supervisor requests need replies. Use replyTo.\");\n}\n\nfunction publicPendingRequests(pending: Map<string, PendingSupervisorRequest>): Array<Record<string, unknown>> {\n\treturn [...pending.values()].map((request) => ({\n\t\tid: request.id,\n\t\trunId: request.runId,\n\t\tagent: request.agent,\n\t\tchildIndex: request.childIndex,\n\t\treason: request.reason,\n\t\texpectsReply: request.expectsReply,\n\t}));\n}\n\nfunction buildParentIntercomTool(pending: Map<string, PendingSupervisorRequest>, state: SubagentState, name = \"intercom\"): ToolDefinition<typeof ParentSupervisorParamsSchema, Record<string, unknown>> {\n\treturn {\n\t\tname,\n\t\tlabel: name === \"intercom\" ? \"Intercom\" : \"Subagent Supervisor\",\n\t\tdescription: PARENT_ASK_DESCRIPTION,\n\t\tparameters: ParentSupervisorParamsSchema,\n\t\tasync execute(_id, params) {\n\t\t\trefreshPendingRequests(pending, state, state.lastUiContext ?? undefined);\n\t\t\tconst input = params as IntercomParams;\n\t\t\tif (input.action === \"status\") {\n\t\t\t\treturn { content: [{ type: \"text\", text: `Native supervisor channel active. Pending replies: ${pending.size}.` }], details: { active: true, pending: pending.size, root: SUPERVISOR_CHANNEL_ROOT } };\n\t\t\t}\n\t\t\tif (input.action === \"pending\" || input.action === \"list\") {\n\t\t\t\tconst lines = [...pending.values()].filter((request) => request.expectsReply).map(formatPendingLine);\n\t\t\t\treturn { content: [{ type: \"text\", text: lines.length ? lines.join(\"\\n\") : \"No pending supervisor requests.\" }], details: { pending: publicPendingRequests(pending) } };\n\t\t\t}\n\t\t\tif (input.action === \"reply\") {\n\t\t\t\tconst request = resolvePendingRequest(pending, input);\n\t\t\t\twriteReply(request, input.message ?? \"\");\n\t\t\t\tpending.delete(request.id);\n\t\t\t\treturn { content: [{ type: \"text\", text: `Replied to supervisor request ${request.id}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent } };\n\t\t\t}\n\t\t\tif (input.action === \"ask\") {\n\t\t\t\treturn askRunningAsyncChild({\n\t\t\t\t\tparams: {\n\t\t\t\t\t\tid: input.id,\n\t\t\t\t\t\tindex: input.index,\n\t\t\t\t\t\tchildId: input.childId,\n\t\t\t\t\t\treason: input.reason,\n\t\t\t\t\t\tmessage: input.message,\n\t\t\t\t\t},\n\t\t\t\t\tstate,\n\t\t\t\t\tchildRequests: pending.values(),\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (input.action === \"send\") {\n\t\t\t\tthrow new Error(\"Native pi-subagents intercom does not support free-form send. Use action='ask' for a running async child or action='reply' for a pending child request.\");\n\t\t\t}\n\t\t\tthrow new Error(`Unsupported intercom action: ${input.action}`);\n\t\t},\n\t};\n}\n\nfunction questionMatchesParentContext(question: SupervisorQuestion, state: SubagentState, ctx: ExtensionContext): boolean {\n\tconst sessionId = currentSupervisorSessionId(state, ctx);\n\tif (!sessionId || question.parentSessionId !== sessionId) return false;\n\tif ((state.sessionGeneration ?? 0) !== question.parentGeneration) return false;\n\treturn true;\n}\n\nfunction notifyQuestionTerminal(pi: ExtensionAPI, question: SupervisorQuestion, channelDir: string): void {\n\tif (!supervisorQuestionIsTerminal(question) || question.notifiedAt) return;\n\t(pi as { events?: IntercomEventBus }).events?.emit(SUBAGENT_QUESTION_EVENT, {\n\t\tquestionId: question.id,\n\t\tstate: supervisorQuestionPublicState(question),\n\t\trunId: question.runId,\n\t});\n\tif (isQuestionWaitActive(question.id)) return;\n\tif (!claimQuestionNotification(channelDir, question.id)) return;\n\tconst state = supervisorQuestionPublicState(question);\n\tpi.sendMessage({\n\t\tcustomType: SUBAGENT_SUPERVISOR_ANSWER_TYPE,\n\t\tcontent: formatSupervisorQuestionAnswer(question),\n\t\tdisplay: state === \"answered\",\n\t\tdetails: {\n\t\t\tquestionId: question.id,\n\t\t\tstate,\n\t\t\trunId: question.runId,\n\t\t\tchildIndex: question.childIndex,\n\t\t\tchildId: question.childId,\n\t\t\treason: question.reason,\n\t\t\tanswered: state === \"answered\",\n\t\t\tdelivered: Boolean(question.deliveredAt),\n\t\t},\n\t}, { triggerTurn: state === \"answered\" });\n}\n\nfunction pollSupervisorQuestions(pi: ExtensionAPI, state: SubagentState, ctx: ExtensionContext): void {\n\tfor (const channelDir of listSupervisorChannelDirs()) {\n\t\tfor (const question of listSupervisorQuestions(channelDir)) {\n\t\t\tif (!questionMatchesParentContext(question, state, ctx)) continue;\n\t\t\tconst current = reconcileAsyncQuestion(channelDir, question, state);\n\t\t\tnotifyQuestionTerminal(pi, current, channelDir);\n\t\t}\n\t}\n}\n\nexport function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentState): {\n\tstart: () => void;\n\tdispose: () => void;\n\tpending: Map<string, PendingSupervisorRequest>;\n\tcancelOwnedQuestions: (reason: string) => void;\n\tsettleRunQuestions: (runId: string, reason: string) => void;\n} {\n\tconst pending = new Map<string, PendingSupervisorRequest>();\n\tconst seenFiles = new Set<string>();\n\tlet poller: ReturnType<typeof setInterval> | undefined;\n\tlet lastStaleCleanupAt = 0;\n\n\tconst registerParentTools = (): void => {\n\t\tif (!hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME)) pi.registerTool(buildParentIntercomTool(pending, state, NATIVE_SUPERVISOR_TOOL_NAME));\n\t\tif (!hasTool(pi, \"intercom\")) pi.registerTool(buildParentIntercomTool(pending, state));\n\t};\n\n\tconst cleanupStaleChannelsIfDue = (): void => {\n\t\tconst nowMs = Date.now();\n\t\tif (nowMs - lastStaleCleanupAt < STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS) return;\n\t\tlastStaleCleanupAt = nowMs;\n\t\ttry {\n\t\t\tcleanupStaleEmptySupervisorChannels(nowMs);\n\t\t} catch {\n\t\t\t// Supervisor delivery must not fail because best-effort temp cleanup failed.\n\t\t}\n\t};\n\n\tconst cancelOwnedQuestions = (reason: string): void => {\n\t\tif (!state.currentSessionId) return;\n\t\tcancelPendingSupervisorQuestionsForOwner({\n\t\t\tparentSessionId: state.currentSessionId,\n\t\t\tparentGeneration: state.sessionGeneration ?? 0,\n\t\t\treason,\n\t\t});\n\t};\n\n\tconst settleRunQuestions = (runId: string, reason: string): void => {\n\t\tif (!state.currentSessionId) return;\n\t\tcancelPendingSupervisorQuestionsForOwner({\n\t\t\tparentSessionId: state.currentSessionId,\n\t\t\trunId,\n\t\t\treason,\n\t\t});\n\t};\n\n\tconst poll = (): void => {\n\t\tcleanupStaleChannelsIfDue();\n\t\tconst ctx = state.lastUiContext;\n\t\tif (!ctx) return;\n\t\trefreshPendingRequests(pending, state, ctx);\n\t\tpollSupervisorQuestions(pi, state, ctx);\n\t\tconst now = Date.now();\n\t\tfor (const { channelDir, file } of listRequestFiles()) {\n\t\t\tif (seenFiles.has(file)) continue;\n\t\t\tconst request = parseRequestFile(file, channelDir);\n\t\t\tif (!request || !requestMatchesContext(request, state, ctx)) continue;\n\t\t\tconst lifecycle = requestLifecycle(request, state, undefined, now);\n\t\t\tif (lifecycle !== \"pending\") {\n\t\t\t\tseenFiles.add(file);\n\t\t\t\tcleanupRequestLifecycle(request, lifecycle);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tseenFiles.add(file);\n\t\t\tif (request.expectsReply) pending.set(request.id, request);\n\t\t\telse {\n\t\t\t\tremoveRequestFile(request.requestFile);\n\t\t\t}\n\t\t\tpi.sendMessage({\n\t\t\t\tcustomType: \"subagent_supervisor_request\",\n\t\t\t\tcontent: requestVisibleText(request),\n\t\t\t\tdisplay: true,\n\t\t\t\tdetails: {\n\t\t\t\t\tid: request.id,\n\t\t\t\t\treason: request.reason,\n\t\t\t\t\texpectsReply: request.expectsReply,\n\t\t\t\t\trunId: request.runId,\n\t\t\t\t\tagent: request.agent,\n\t\t\t\t\tchildIndex: request.childIndex,\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (request.expectsReply) {\n\t\t\t\tconst job = state.asyncJobs.get(request.runId);\n\t\t\t\tif (job) job.activityState = \"needs_attention\";\n\t\t\t\tconst events = (pi as { events?: IntercomEventBus }).events;\n\t\t\t\tevents?.emit(INTERCOM_DETACH_REQUEST_EVENT, {\n\t\t\t\t\trequestId: request.id,\n\t\t\t\t\trunId: request.runId,\n\t\t\t\t\tagent: request.agent,\n\t\t\t\t\tchildIndex: request.childIndex,\n\t\t\t\t});\n\t\t\t\tevents?.emit(SUBAGENT_CONTROL_EVENT, {\n\t\t\t\t\ttype: \"needs_attention\",\n\t\t\t\t\tto: \"needs_attention\",\n\t\t\t\t\trunId: request.runId,\n\t\t\t\t\tagent: request.agent,\n\t\t\t\t\tindex: request.childIndex,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t};\n\n\treturn {\n\t\tstart: () => {\n\t\t\tif (poller) return;\n\t\t\tregisterParentTools();\n\t\t\tpoll();\n\t\t\tpoller = setInterval(poll, CHANNEL_POLL_MS);\n\t\t\tpoller.unref?.();\n\t\t},\n\t\tdispose: () => {\n\t\t\tcancelOwnedQuestions(\"parent supervisor channel disposed\");\n\t\t\tif (poller) clearInterval(poller);\n\t\t\tpoller = undefined;\n\t\t\tpending.clear();\n\t\t\tseenFiles.clear();\n\t\t},\n\t\tpending,\n\t\tcancelOwnedQuestions,\n\t\tsettleRunQuestions,\n\t};\n}\n\nexport function isPendingQuestionForCurrentChild(questionId: string): boolean {\n\tconst metadata = readChildMetadata();\n\tconst owner = readChildQuestionOwner(metadata);\n\tif (!metadata || !owner) return false;\n\treturn pendingSupervisorQuestionsForDelivery(metadata.channelDir, owner).some((question) =>\n\t\tquestion.id === questionId && question.parentSessionId === (metadata.supervisorSessionId ?? metadata.orchestratorSessionId),\n\t);\n}\n\nexport function markDeliveredSupervisorQuestionFromChild(message: string): void {\n\tconst match = message.match(/Parent question \\(([^)\\s]+)\\)/);\n\tif (!match?.[1]) return;\n\tconst metadata = readChildMetadata();\n\tconst owner = readChildQuestionOwner(metadata);\n\tif (!metadata || !owner) return;\n\tif (!isPendingQuestionForCurrentChild(match[1])) return;\n\ttry {\n\t\tmarkSupervisorQuestionDelivered(metadata.channelDir, match[1], owner);\n\t} catch {\n\t\t// Delivery markers are best-effort; answer ownership still enforces identity.\n\t}\n}\n"]}