@herbertgao/pi-extensions 2026.10.19 → 2026.11.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 (288) hide show
  1. package/CHANGELOG.md +759 -0
  2. package/README.md +21 -6
  3. package/THIRD_PARTY_NOTICES.md +53 -2
  4. package/extensions/clef.mjs +1 -1
  5. package/node_modules/@herbertgao/pi-agency/CHANGELOG.md +19 -0
  6. package/node_modules/@herbertgao/pi-agency/package.json +4 -2
  7. package/node_modules/@herbertgao/pi-agency/src/index.ts +1 -1
  8. package/node_modules/@herbertgao/pi-bark/CHANGELOG.md +52 -0
  9. package/node_modules/@herbertgao/pi-bark/package.json +2 -1
  10. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +207 -0
  11. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +7 -5
  12. package/node_modules/@herbertgao/pi-cc-extensions/README.md +10 -7
  13. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/config.ts +20 -0
  14. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +61 -6
  15. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/agent-summary/core.ts +11 -16
  16. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/agent-summary/index.ts +60 -11
  17. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/compact-thinking.ts +29 -11
  18. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/footer-layout.ts +54 -6
  19. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/footer.ts +23 -5
  20. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/session-tokens.ts +52 -0
  21. package/node_modules/@herbertgao/pi-cc-extensions/package.json +5 -4
  22. package/node_modules/@herbertgao/pi-impeccable/CHANGELOG.md +13 -0
  23. package/node_modules/@herbertgao/pi-impeccable/package.json +2 -1
  24. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +6 -0
  25. package/node_modules/@herbertgao/pi-subagents/README.md +142 -45
  26. package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +17 -7
  27. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  28. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +111 -59
  29. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +135 -117
  30. package/node_modules/@herbertgao/pi-subagents/src/cross-extension-rpc.ts +41 -14
  31. package/node_modules/@herbertgao/pi-subagents/src/index.ts +110 -19
  32. package/node_modules/@herbertgao/pi-subagents/src/nested-tools.ts +8 -0
  33. package/node_modules/@herbertgao/pi-subagents/src/prompts.ts +31 -0
  34. package/node_modules/@herbertgao/sol-pi/CHANGELOG.md +84 -0
  35. package/node_modules/@herbertgao/sol-pi/README.md +3 -3
  36. package/node_modules/@herbertgao/sol-pi/THIRD_PARTY_NOTICES.md +4 -4
  37. package/node_modules/@herbertgao/sol-pi/agents-install.md +3 -3
  38. package/node_modules/@herbertgao/sol-pi/docs/compatibility.md +1 -1
  39. package/node_modules/@herbertgao/sol-pi/package.json +2 -1
  40. package/node_modules/@tintinweb/pi-tasks/CHANGELOG.md +270 -0
  41. package/node_modules/@tintinweb/pi-tasks/CONTRIBUTING.md +67 -0
  42. package/node_modules/@tintinweb/pi-tasks/CUSTOMIZING.md +289 -0
  43. package/node_modules/@tintinweb/pi-tasks/LICENSE +21 -0
  44. package/node_modules/@tintinweb/pi-tasks/README.md +417 -0
  45. package/node_modules/@tintinweb/pi-tasks/SECURITY.md +107 -0
  46. package/node_modules/@tintinweb/pi-tasks/dist/auto-clear.d.ts +64 -0
  47. package/node_modules/@tintinweb/pi-tasks/dist/auto-clear.js +129 -0
  48. package/node_modules/@tintinweb/pi-tasks/dist/index.d.ts +17 -0
  49. package/node_modules/@tintinweb/pi-tasks/dist/index.js +1338 -0
  50. package/node_modules/@tintinweb/pi-tasks/dist/process-tracker.d.ts +29 -0
  51. package/node_modules/@tintinweb/pi-tasks/dist/process-tracker.js +121 -0
  52. package/node_modules/@tintinweb/pi-tasks/dist/reminder-cadence.d.ts +39 -0
  53. package/node_modules/@tintinweb/pi-tasks/dist/reminder-cadence.js +61 -0
  54. package/node_modules/@tintinweb/pi-tasks/dist/task-glyphs.d.ts +48 -0
  55. package/node_modules/@tintinweb/pi-tasks/dist/task-glyphs.js +68 -0
  56. package/node_modules/@tintinweb/pi-tasks/dist/task-paths.d.ts +44 -0
  57. package/node_modules/@tintinweb/pi-tasks/dist/task-paths.js +60 -0
  58. package/node_modules/@tintinweb/pi-tasks/dist/task-sort.d.ts +23 -0
  59. package/node_modules/@tintinweb/pi-tasks/dist/task-sort.js +69 -0
  60. package/node_modules/@tintinweb/pi-tasks/dist/task-store.d.ts +61 -0
  61. package/node_modules/@tintinweb/pi-tasks/dist/task-store.js +397 -0
  62. package/node_modules/@tintinweb/pi-tasks/dist/tasks-config.d.ts +16 -0
  63. package/node_modules/@tintinweb/pi-tasks/dist/tasks-config.js +51 -0
  64. package/node_modules/@tintinweb/pi-tasks/dist/types.d.ts +36 -0
  65. package/node_modules/@tintinweb/pi-tasks/dist/types.js +4 -0
  66. package/node_modules/@tintinweb/pi-tasks/dist/ui/settings-menu.d.ts +15 -0
  67. package/node_modules/@tintinweb/pi-tasks/dist/ui/settings-menu.js +140 -0
  68. package/node_modules/@tintinweb/pi-tasks/dist/ui/task-widget.d.ts +69 -0
  69. package/node_modules/@tintinweb/pi-tasks/dist/ui/task-widget.js +278 -0
  70. package/node_modules/@tintinweb/pi-tasks/package.json +57 -0
  71. package/node_modules/@tintinweb/pi-tasks/src/auto-clear.ts +134 -0
  72. package/node_modules/@tintinweb/pi-tasks/src/index.ts +1417 -0
  73. package/node_modules/@tintinweb/pi-tasks/src/process-tracker.ts +140 -0
  74. package/node_modules/@tintinweb/pi-tasks/src/reminder-cadence.ts +90 -0
  75. package/node_modules/@tintinweb/pi-tasks/src/task-glyphs.ts +110 -0
  76. package/node_modules/@tintinweb/pi-tasks/src/task-paths.ts +65 -0
  77. package/node_modules/@tintinweb/pi-tasks/src/task-sort.ts +90 -0
  78. package/node_modules/@tintinweb/pi-tasks/src/task-store.ts +402 -0
  79. package/node_modules/@tintinweb/pi-tasks/src/tasks-config.ts +77 -0
  80. package/node_modules/@tintinweb/pi-tasks/src/types.ts +40 -0
  81. package/node_modules/@tintinweb/pi-tasks/src/ui/settings-menu.ts +174 -0
  82. package/node_modules/@tintinweb/pi-tasks/src/ui/task-widget.ts +325 -0
  83. package/node_modules/pi-commandcode-provider/CHANGELOG.md +330 -0
  84. package/node_modules/pi-commandcode-provider/CONTRIBUTING.md +192 -0
  85. package/node_modules/pi-commandcode-provider/LICENSE +21 -0
  86. package/node_modules/pi-commandcode-provider/README.md +243 -0
  87. package/node_modules/pi-commandcode-provider/RELEASE.md +194 -0
  88. package/node_modules/pi-commandcode-provider/index.ts +309 -0
  89. package/node_modules/pi-commandcode-provider/package.json +91 -0
  90. package/node_modules/pi-commandcode-provider/scripts/live-e2e-profile.mjs +87 -0
  91. package/node_modules/pi-commandcode-provider/scripts/pi-authenticated.mjs +50 -0
  92. package/node_modules/pi-commandcode-provider/scripts/pi-isolated.mjs +79 -0
  93. package/node_modules/pi-commandcode-provider/src/api-key.ts +69 -0
  94. package/node_modules/pi-commandcode-provider/src/auth-server.ts +229 -0
  95. package/node_modules/pi-commandcode-provider/src/commandcode-catalog-overrides.ts +28 -0
  96. package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +260 -0
  97. package/node_modules/pi-commandcode-provider/src/converters.ts +477 -0
  98. package/node_modules/pi-commandcode-provider/src/core.ts +836 -0
  99. package/node_modules/pi-commandcode-provider/src/cost.ts +76 -0
  100. package/node_modules/pi-commandcode-provider/src/json-schema.ts +417 -0
  101. package/node_modules/pi-commandcode-provider/src/models.ts +515 -0
  102. package/node_modules/pi-commandcode-provider/src/oauth.ts +229 -0
  103. package/node_modules/pi-commandcode-provider/src/overflow.ts +120 -0
  104. package/node_modules/pi-commandcode-provider/src/pricing.ts +370 -0
  105. package/node_modules/pi-commandcode-provider/src/quota-command.ts +66 -0
  106. package/node_modules/pi-commandcode-provider/src/quota-format.ts +143 -0
  107. package/node_modules/pi-commandcode-provider/src/quota-types.ts +47 -0
  108. package/node_modules/pi-commandcode-provider/src/quota.ts +357 -0
  109. package/node_modules/pi-commandcode-provider/src/responses-stream.ts +249 -0
  110. package/node_modules/pi-commandcode-provider/src/runtime.ts +330 -0
  111. package/node_modules/pi-commandcode-provider/src/transcript.ts +56 -0
  112. package/node_modules/pi-commandcode-provider/src/transport.ts +147 -0
  113. package/node_modules/pi-commandcode-provider/src/types.ts +212 -0
  114. package/node_modules/pi-commandcode-provider/src/usage.ts +261 -0
  115. package/node_modules/pi-lens/CHANGELOG.md +149 -0
  116. package/node_modules/pi-lens/README.md +12 -2
  117. package/node_modules/pi-lens/config/markdownlint/run-no-fix.mjs +36 -0
  118. package/node_modules/pi-lens/dist/{chunk-WME2OQST.js → chunk-2453RRJ2.js} +11 -6
  119. package/node_modules/pi-lens/dist/{chunk-FZKFVUEC.js → chunk-2BKUFQKR.js} +276 -208
  120. package/node_modules/pi-lens/dist/chunk-2TS4GLOJ.js +31 -0
  121. package/node_modules/pi-lens/dist/{chunk-QHSNL7B2.js → chunk-2ZE3AUJQ.js} +12 -14
  122. package/node_modules/pi-lens/dist/{chunk-MPKRJBPK.js → chunk-35WKJWO5.js} +28 -30
  123. package/node_modules/pi-lens/dist/chunk-3JAHQBSY.js +27 -0
  124. package/node_modules/pi-lens/dist/{chunk-4LM3VAZH.js → chunk-3O5EII3W.js} +2 -2
  125. package/node_modules/pi-lens/dist/chunk-447YZL4S.js +25 -0
  126. package/node_modules/pi-lens/dist/{chunk-H7OR7DFZ.js → chunk-4B2YFN4U.js} +25 -21
  127. package/node_modules/pi-lens/dist/{chunk-OSTKYB55.js → chunk-4BKU7PV3.js} +1 -1
  128. package/node_modules/pi-lens/dist/{chunk-RRV3FNNM.js → chunk-4LL2VRNY.js} +27 -28
  129. package/node_modules/pi-lens/dist/{chunk-BZARLRJW.js → chunk-4NBWFYWW.js} +9 -9
  130. package/node_modules/pi-lens/dist/{chunk-KKCK636N.js → chunk-4QG55RRC.js} +12 -12
  131. package/node_modules/pi-lens/dist/{chunk-RQS4QQSD.js → chunk-4W52ZKZX.js} +2 -2
  132. package/node_modules/pi-lens/dist/{chunk-Z2XAOKHK.js → chunk-565VRUP4.js} +2 -2
  133. package/node_modules/pi-lens/dist/{chunk-HWDAVBFU.js → chunk-57X2CDRX.js} +23 -23
  134. package/node_modules/pi-lens/dist/{chunk-MB6PXBUA.js → chunk-5F3XF3SX.js} +7 -15
  135. package/node_modules/pi-lens/dist/{chunk-O4BJFESU.js → chunk-5RNB4HVK.js} +1 -1
  136. package/node_modules/pi-lens/dist/{chunk-ZMAUPOMG.js → chunk-5T5A6YAJ.js} +35 -34
  137. package/node_modules/pi-lens/dist/{chunk-4ZYJHQMB.js → chunk-6FIRFP6A.js} +12 -12
  138. package/node_modules/pi-lens/dist/{chunk-4YHYPW2G.js → chunk-6GMGEKQN.js} +9 -5
  139. package/node_modules/pi-lens/dist/{chunk-4LOE5R5P.js → chunk-6LJOJ6EO.js} +20 -15
  140. package/node_modules/pi-lens/dist/{chunk-3YY7IXIL.js → chunk-6YUNI7B5.js} +3 -3
  141. package/node_modules/pi-lens/dist/{chunk-PKES3ISE.js → chunk-7ANZ7XDD.js} +2 -2
  142. package/node_modules/pi-lens/dist/{chunk-FB5SCCPT.js → chunk-7CGIDRIK.js} +16 -15
  143. package/node_modules/pi-lens/dist/{chunk-L3CMBQMH.js → chunk-7MAD5ZAY.js} +16 -17
  144. package/node_modules/pi-lens/dist/{chunk-WDBICWH3.js → chunk-7TNILKGY.js} +1 -1
  145. package/node_modules/pi-lens/dist/{chunk-RORGS5II.js → chunk-A5GRLYPZ.js} +9 -9
  146. package/node_modules/pi-lens/dist/{chunk-MNJIXFX4.js → chunk-AGGUWKRK.js} +1 -1
  147. package/node_modules/pi-lens/dist/{chunk-ABPKUVA4.js → chunk-BBET6HD6.js} +1 -1
  148. package/node_modules/pi-lens/dist/{chunk-L5JYIU47.js → chunk-BHWW6FAX.js} +14 -13
  149. package/node_modules/pi-lens/dist/{chunk-URCQWAQ4.js → chunk-BOPDQ7AZ.js} +23 -21
  150. package/node_modules/pi-lens/dist/{chunk-KDX35VXP.js → chunk-BQG2QFVO.js} +158 -133
  151. package/node_modules/pi-lens/dist/{chunk-CB4WHS4H.js → chunk-BUZIQDFS.js} +3 -3
  152. package/node_modules/pi-lens/dist/{chunk-2PHMIAKO.js → chunk-CM73PPGD.js} +4 -4
  153. package/node_modules/pi-lens/dist/{chunk-DH5JPM3K.js → chunk-CUDD35TW.js} +10 -9
  154. package/node_modules/pi-lens/dist/{chunk-AWDSEDER.js → chunk-CZL44WFN.js} +2 -2
  155. package/node_modules/pi-lens/dist/{chunk-N5WSK2K7.js → chunk-DIWK3LBC.js} +12 -15
  156. package/node_modules/pi-lens/dist/{chunk-24BILSZW.js → chunk-DYRZGUMA.js} +2 -2
  157. package/node_modules/pi-lens/dist/{chunk-PR6PO3ES.js → chunk-FHEV6T4L.js} +22 -18
  158. package/node_modules/pi-lens/dist/{chunk-DQZFQSR5.js → chunk-FRLAUP2B.js} +4 -4
  159. package/node_modules/pi-lens/dist/{chunk-RZOXUSPC.js → chunk-G5GV2Q7K.js} +2 -2
  160. package/node_modules/pi-lens/dist/{chunk-EKWX4WD3.js → chunk-G6JKM4O7.js} +7 -7
  161. package/node_modules/pi-lens/dist/chunk-GGYOZWHW.js +27 -0
  162. package/node_modules/pi-lens/dist/{chunk-XT2HTCJ5.js → chunk-GIRBSBGL.js} +6 -5
  163. package/node_modules/pi-lens/dist/{chunk-PQJFG24Z.js → chunk-GMROJJRN.js} +1292 -946
  164. package/node_modules/pi-lens/dist/{chunk-U6VN4NVL.js → chunk-HHR7WGCI.js} +3 -3
  165. package/node_modules/pi-lens/dist/{chunk-TIQJPRDD.js → chunk-HKIL6DCL.js} +3 -2
  166. package/node_modules/pi-lens/dist/{chunk-SNDXCFRS.js → chunk-HUAM7QG3.js} +11 -11
  167. package/node_modules/pi-lens/dist/{chunk-QOE342SU.js → chunk-HXFUTMX2.js} +2 -2
  168. package/node_modules/pi-lens/dist/{chunk-U7BD2QL7.js → chunk-I22THIHI.js} +12 -12
  169. package/node_modules/pi-lens/dist/chunk-IE5D3RA5.js +58 -0
  170. package/node_modules/pi-lens/dist/{chunk-DPGEAHZT.js → chunk-IYVYZQRL.js} +10 -16
  171. package/node_modules/pi-lens/dist/{chunk-3F6BMY53.js → chunk-JBP7KESM.js} +1 -1
  172. package/node_modules/pi-lens/dist/{chunk-U5HPROLA.js → chunk-JE6HKLC7.js} +2 -2
  173. package/node_modules/pi-lens/dist/{chunk-ZE3KXHS7.js → chunk-JPRDTY5S.js} +85 -3
  174. package/node_modules/pi-lens/dist/{chunk-HO6LWE2E.js → chunk-JYLOYTZD.js} +17 -1
  175. package/node_modules/pi-lens/dist/{chunk-KW5JQPO5.js → chunk-JZRP4DGP.js} +2 -2
  176. package/node_modules/pi-lens/dist/{chunk-CPSR3AVL.js → chunk-KZ4ALBCH.js} +2 -2
  177. package/node_modules/pi-lens/dist/{chunk-6IR3ZYIB.js → chunk-L3CLUGDY.js} +3 -3
  178. package/node_modules/pi-lens/dist/{chunk-LV4UMYVH.js → chunk-L4NEVZ4T.js} +28 -27
  179. package/node_modules/pi-lens/dist/chunk-LPYTPNOJ.js +22 -0
  180. package/node_modules/pi-lens/dist/{chunk-WGRJOXED.js → chunk-LSFXZLPW.js} +1016 -636
  181. package/node_modules/pi-lens/dist/{chunk-LBLBAFG3.js → chunk-MC6VB2E5.js} +4 -4
  182. package/node_modules/pi-lens/dist/{chunk-U2SDMG7C.js → chunk-NM2NWH55.js} +5 -5
  183. package/node_modules/pi-lens/dist/{chunk-T7A2HK2B.js → chunk-NSPVR3FN.js} +19 -18
  184. package/node_modules/pi-lens/dist/{chunk-ZGSJDWQU.js → chunk-O2ARHQKF.js} +2 -2
  185. package/node_modules/pi-lens/dist/{chunk-OXOI55RU.js → chunk-O4N5BQ3T.js} +10 -10
  186. package/node_modules/pi-lens/dist/{chunk-3FRLWYBG.js → chunk-OC7VWJBZ.js} +39 -40
  187. package/node_modules/pi-lens/dist/chunk-OFNMHPBT.js +89 -0
  188. package/node_modules/pi-lens/dist/{chunk-HR3OJ3TH.js → chunk-OWTG6UMO.js} +21 -21
  189. package/node_modules/pi-lens/dist/{chunk-75GAYVNO.js → chunk-OY7WZI7Q.js} +6 -6
  190. package/node_modules/pi-lens/dist/{chunk-ZJTT47IG.js → chunk-OZWXLJMX.js} +2 -2
  191. package/node_modules/pi-lens/dist/{chunk-F6X3YJWD.js → chunk-PIQQM32Y.js} +2 -2
  192. package/node_modules/pi-lens/dist/chunk-PKLB2XJL.js +8 -0
  193. package/node_modules/pi-lens/dist/{chunk-EAOK7MIZ.js → chunk-PKSUMEPT.js} +17 -4
  194. package/node_modules/pi-lens/dist/{chunk-YISME6ON.js → chunk-PPKECBPP.js} +1 -1
  195. package/node_modules/pi-lens/dist/{chunk-4L36HG27.js → chunk-R2QQC33W.js} +14 -14
  196. package/node_modules/pi-lens/dist/{chunk-LUBPZN36.js → chunk-R4QWJQ2H.js} +11 -11
  197. package/node_modules/pi-lens/dist/{chunk-V63BC55Q.js → chunk-RGGH6M34.js} +1 -1
  198. package/node_modules/pi-lens/dist/{chunk-Y7F7IEE3.js → chunk-RZG472YW.js} +65 -7
  199. package/node_modules/pi-lens/dist/{chunk-PUZ3E2J4.js → chunk-SDFKOLSF.js} +6 -6
  200. package/node_modules/pi-lens/dist/{chunk-YHC2O2WO.js → chunk-SFLHSL5R.js} +9 -9
  201. package/node_modules/pi-lens/dist/{chunk-CCV2EU7T.js → chunk-SP4TFY5F.js} +14 -13
  202. package/node_modules/pi-lens/dist/{chunk-J6JP25XU.js → chunk-SQC7K3SP.js} +4 -3
  203. package/node_modules/pi-lens/dist/{chunk-3K2F6UDZ.js → chunk-T2S3FNNJ.js} +44 -42
  204. package/node_modules/pi-lens/dist/{chunk-2TF6RXWB.js → chunk-TV6RXRYH.js} +10 -10
  205. package/node_modules/pi-lens/dist/{chunk-GNSIWBAT.js → chunk-U3AS2FR6.js} +3 -3
  206. package/node_modules/pi-lens/dist/{chunk-F7K5IBZG.js → chunk-UHHLR2VY.js} +40 -40
  207. package/node_modules/pi-lens/dist/chunk-UYXV5NIS.js +20 -0
  208. package/node_modules/pi-lens/dist/{chunk-VSFLRN5Y.js → chunk-VLQ7UKZH.js} +1 -1
  209. package/node_modules/pi-lens/dist/{chunk-VUZWQ7UG.js → chunk-VN3L2JWZ.js} +46 -72
  210. package/node_modules/pi-lens/dist/{chunk-NA7SEXHE.js → chunk-VOP4PJKA.js} +7 -7
  211. package/node_modules/pi-lens/dist/{chunk-F5Z6URKM.js → chunk-VOXTCULR.js} +2 -2
  212. package/node_modules/pi-lens/dist/{chunk-LLS45EWB.js → chunk-VPLBLWFO.js} +6 -8
  213. package/node_modules/pi-lens/dist/chunk-W3BGKBBK.js +27 -0
  214. package/node_modules/pi-lens/dist/{chunk-ZKXQKGWZ.js → chunk-WC6WRNQT.js} +4 -3
  215. package/node_modules/pi-lens/dist/{chunk-YVHBNSME.js → chunk-WMDUT4KH.js} +1148 -1132
  216. package/node_modules/pi-lens/dist/{chunk-KXF5R4UN.js → chunk-WQV6BI4Q.js} +1 -1
  217. package/node_modules/pi-lens/dist/chunk-WXUDRAG6.js +24 -0
  218. package/node_modules/pi-lens/dist/{chunk-KPPJTH44.js → chunk-X35S7HSB.js} +28 -10
  219. package/node_modules/pi-lens/dist/{chunk-JMEKXFOL.js → chunk-X66YJ2SS.js} +40 -34
  220. package/node_modules/pi-lens/dist/{chunk-CE6VMBCB.js → chunk-XOMGO63G.js} +22 -21
  221. package/node_modules/pi-lens/dist/{chunk-LS3QJRUB.js → chunk-XWIME22V.js} +13 -13
  222. package/node_modules/pi-lens/dist/{chunk-R5MOQM2H.js → chunk-XYLC35E4.js} +119 -87
  223. package/node_modules/pi-lens/dist/{chunk-OE5ZBP7F.js → chunk-YHGYAEFH.js} +18 -18
  224. package/node_modules/pi-lens/dist/{chunk-7E2563GA.js → chunk-ZFORSIED.js} +13 -13
  225. package/node_modules/pi-lens/dist/{chunk-E7HJ56Y7.js → chunk-ZKLTNLAW.js} +64 -73
  226. package/node_modules/pi-lens/dist/chunk-ZONZ6YY3.js +74 -0
  227. package/node_modules/pi-lens/dist/chunk-ZSM35JF4.js +30 -0
  228. package/node_modules/pi-lens/dist/{chunk-RC2Z6K47.js → chunk-ZZDIOAAJ.js} +15 -6
  229. package/node_modules/pi-lens/dist/index.js +6993 -5396
  230. package/node_modules/pi-lens/dist/mcp/analyze-cli.js +10 -10
  231. package/node_modules/pi-lens/dist/mcp/cli.js +44 -42
  232. package/node_modules/pi-lens/dist/mcp/server.js +1627 -504
  233. package/node_modules/pi-lens/dist/mcp/worker.js +62 -61
  234. package/node_modules/pi-lens/dist/probes/installer.js +20 -19
  235. package/node_modules/pi-lens/docs/adr/0003-git-guard-latch-writer.md +11 -6
  236. package/node_modules/pi-lens/docs/agent-tools.md +18 -8
  237. package/node_modules/pi-lens/docs/alignment-families.md +29 -0
  238. package/node_modules/pi-lens/docs/ast-grep_rules_catalog.md +6 -4
  239. package/node_modules/pi-lens/docs/ci-bot-pr-checks.md +126 -0
  240. package/node_modules/pi-lens/docs/configuration.md +99 -3
  241. package/node_modules/pi-lens/docs/defect-shapes.md +55 -12
  242. package/node_modules/pi-lens/docs/engineering-principles.md +27 -2
  243. package/node_modules/pi-lens/docs/features.md +2 -2
  244. package/node_modules/pi-lens/docs/invariants/git-guard-host.md +7 -3
  245. package/node_modules/pi-lens/docs/invariants/language-config.md +15 -4
  246. package/node_modules/pi-lens/docs/invariants/lsp-trust-exec.md +16 -2
  247. package/node_modules/pi-lens/docs/invariants/paths-os.md +4 -2
  248. package/node_modules/pi-lens/docs/lsp-capability-matrix.md +119 -39
  249. package/node_modules/pi-lens/docs/merge-queue-rollout.md +1 -1
  250. package/node_modules/pi-lens/docs/pi-lens-fixer.md +24 -17
  251. package/node_modules/pi-lens/docs/pi-lens-merge-policy.md +20 -11
  252. package/node_modules/pi-lens/docs/pi-lens-monitor.md +9 -0
  253. package/node_modules/pi-lens/docs/pi-lens-orchestration.md +4 -1
  254. package/node_modules/pi-lens/docs/pi-lens-reviewer.md +5 -5
  255. package/node_modules/pi-lens/docs/pi-lens-subagent.md +6 -3
  256. package/node_modules/pi-lens/docs/public-api-stability.md +18 -2
  257. package/node_modules/pi-lens/docs/schema/pi-lens-config-v1.json +10 -0
  258. package/node_modules/pi-lens/docs/settings.md +10 -6
  259. package/node_modules/pi-lens/docs/word-index.md +17 -5
  260. package/node_modules/pi-lens/package.json +5 -3
  261. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-accumulating-spread-js-test.yml +37 -0
  262. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/ts-redundant-filter-map-test.yml +12 -1
  263. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests-disabled/filter-then-map-js-test.yml +12 -0
  264. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests-disabled/filter-then-map-test.yml +25 -0
  265. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-accumulating-spread-js.yml +49 -1
  266. package/node_modules/pi-lens/rules/ast-grep-rules/rules/ts-redundant-filter-map.yml +9 -1
  267. package/node_modules/pi-lens/rules/ast-grep-rules/rules-disabled/filter-then-map-js.yml +17 -0
  268. package/node_modules/pi-lens/rules/ast-grep-rules/rules-disabled/filter-then-map.yml +36 -0
  269. package/node_modules/pi-lens/rules/ast-grep-rules/self-scan-baseline.json +1 -1
  270. package/node_modules/pi-provider-qoder/README.md +22 -0
  271. package/node_modules/pi-provider-qoder/dist/index.js +375 -12
  272. package/node_modules/pi-provider-qoder/package.json +5 -2
  273. package/package.json +17 -13
  274. package/node_modules/@tifan/pi-preferred-thinking/README.md +0 -54
  275. package/node_modules/@tifan/pi-preferred-thinking/package.json +0 -43
  276. package/node_modules/@tifan/pi-preferred-thinking/src/index.ts +0 -236
  277. package/node_modules/pi-lens/dist/chunk-46TNM7XZ.js +0 -88
  278. package/node_modules/pi-lens/dist/chunk-72OKUXSD.js +0 -31
  279. package/node_modules/pi-lens/dist/chunk-7GLOLOSH.js +0 -57
  280. package/node_modules/pi-lens/dist/chunk-AKUUMGD5.js +0 -26
  281. package/node_modules/pi-lens/dist/chunk-ASUXV767.js +0 -22
  282. package/node_modules/pi-lens/dist/chunk-CTADOKYM.js +0 -25
  283. package/node_modules/pi-lens/dist/chunk-JJ2RRESP.js +0 -58
  284. package/node_modules/pi-lens/dist/chunk-LSC3VADM.js +0 -23
  285. package/node_modules/pi-lens/dist/chunk-SHLDT3OI.js +0 -27
  286. package/node_modules/pi-lens/dist/chunk-UF7RTZSO.js +0 -27
  287. package/node_modules/pi-lens/dist/chunk-W4WP2ERB.js +0 -30
  288. package/node_modules/pi-lens/dist/chunk-YES5CACN.js +0 -73
@@ -0,0 +1,1338 @@
1
+ /**
2
+ * @tintinweb/pi-tasks — A pi extension providing Claude Code-style task tracking and coordination.
3
+ *
4
+ * Tools:
5
+ * TaskCreate — Create a structured task
6
+ * TaskList — List all tasks with status
7
+ * TaskGet — Get full task details
8
+ * TaskUpdate — Update task fields, status, dependencies
9
+ * TaskOutput — Get output from a background task process
10
+ * TaskStop — Stop a running background task process
11
+ * TaskExecute — Execute tasks as subagents (requires @tintinweb/pi-subagents)
12
+ *
13
+ * Commands:
14
+ * /tasks — Interactive task management menu
15
+ */
16
+ import { randomUUID } from "node:crypto";
17
+ import { join, resolve } from "node:path";
18
+ import { Type } from "typebox";
19
+ import { AutoClearManager } from "./auto-clear.js";
20
+ import { ProcessTracker } from "./process-tracker.js";
21
+ import { createCadenceState, drainReminderForContext, evaluateToolResult, onTurnStart, resetCadenceState, } from "./reminder-cadence.js";
22
+ import { resolveTaskGlyphs } from "./task-glyphs.js";
23
+ import { reclaimGlobalSessionTasksDir, sessionTaskFile } from "./task-paths.js";
24
+ import { TaskStore } from "./task-store.js";
25
+ import { loadGlobalTasksConfig, loadTasksConfig } from "./tasks-config.js";
26
+ import { openSettingsMenu } from "./ui/settings-menu.js";
27
+ import { TaskWidget } from "./ui/task-widget.js";
28
+ // ---- Debug ----
29
+ const DEBUG = !!process.env.PI_TASKS_DEBUG;
30
+ function debug(...args) {
31
+ if (DEBUG)
32
+ console.error("[pi-tasks]", ...args);
33
+ }
34
+ // ---- Helpers ----
35
+ function textResult(msg) {
36
+ return { content: [{ type: "text", text: msg }], details: undefined };
37
+ }
38
+ /** Task tool names — used to detect task tool usage for reminder suppression. */
39
+ const TASK_TOOL_NAMES = new Set(["TaskCreate", "TaskList", "TaskGet", "TaskUpdate", "TaskOutput", "TaskStop", "TaskExecute"]);
40
+ /** How many turns without task tool usage before injecting a reminder. */
41
+ const REMINDER_INTERVAL = 4;
42
+ /** Shorter interval used while any task is in_progress, so stale work is caught faster. */
43
+ const ACTIVE_REMINDER_INTERVAL = 2;
44
+ /** Cap on how many tasks the reminder echoes, to bound its size on large lists. */
45
+ const REMINDER_MAX_TASKS = 10;
46
+ /** Effective reminder interval for a given task list (pure — no disk I/O). */
47
+ function intervalFor(tasks) {
48
+ return tasks.some(t => t.status === "in_progress") ? ACTIVE_REMINDER_INTERVAL : REMINDER_INTERVAL;
49
+ }
50
+ /** How many turns completed tasks linger before auto-clearing. */
51
+ const AUTO_CLEAR_DELAY = 4;
52
+ /** How long a timed-out spawn keeps listening for a late reply before giving up. */
53
+ const LATE_REPLY_WINDOW_MS = 5 * 60_000;
54
+ /** Neutralize a task field for the echo: collapse newlines and strip reminder tags. */
55
+ function sanitizeField(value) {
56
+ return value.replace(/[\r\n]+/g, " ").replace(/<\/?system-reminder>/gi, "").trim();
57
+ }
58
+ /**
59
+ * Build the system reminder, shaped after Claude Code's todo reminders: an
60
+ * empty-list nudge, or a state echo that dumps the current list as JSON. The
61
+ * wording mirrors Claude Code (adapted to this extension's task tool names).
62
+ */
63
+ function buildSystemReminder(tasks) {
64
+ if (tasks.length === 0) {
65
+ return [
66
+ "<system-reminder>",
67
+ "This is a reminder that your task list is currently empty. DO NOT mention this to the user explicitly because they are already aware. If you are working on tasks that would benefit from a task list please use the TaskCreate tool to create one. If not, please feel free to ignore. Again do not mention this message to the user.",
68
+ "</system-reminder>",
69
+ ].join("\n");
70
+ }
71
+ // Bound the echo on large lists. When over the cap, drop completed tasks
72
+ // first (the reminder exists to surface unfinished work); ties keep task
73
+ // order since Array.sort is stable.
74
+ let shown = tasks;
75
+ if (tasks.length > REMINDER_MAX_TASKS) {
76
+ const rank = (t) => (t.status === "in_progress" ? 0 : t.status === "pending" ? 1 : 2);
77
+ shown = [...tasks].sort((a, b) => rank(a) - rank(b)).slice(0, REMINDER_MAX_TASKS);
78
+ }
79
+ const hidden = tasks.length - shown.length;
80
+ const overflow = hidden > 0
81
+ ? ` (${hidden} more task${hidden === 1 ? "" : "s"} not shown — use TaskList for the full list.)`
82
+ : "";
83
+ const items = shown.map(t => {
84
+ const item = {
85
+ id: t.id,
86
+ content: sanitizeField(t.subject),
87
+ status: t.status,
88
+ };
89
+ if (t.activeForm)
90
+ item.activeForm = sanitizeField(t.activeForm);
91
+ return item;
92
+ });
93
+ // When truncated, don't claim these are the full contents.
94
+ const prefix = "The task tools haven't been used recently. DO NOT mention this explicitly to the user.";
95
+ const header = hidden > 0
96
+ ? `${prefix} Here are your most relevant tasks (list truncated):`
97
+ : `${prefix} Here are the latest contents of your task list:`;
98
+ return [
99
+ "<system-reminder>",
100
+ header,
101
+ "",
102
+ `${JSON.stringify(items)}.${overflow} Continue on with the tasks at hand if applicable.`,
103
+ "</system-reminder>",
104
+ ].join("\n");
105
+ }
106
+ export default function (pi) {
107
+ // Project overrides require ExtensionContext.cwd, which is unavailable while
108
+ // the extension factory runs. Start with global defaults, then merge the
109
+ // active workspace's overrides on the first context-bearing event.
110
+ const cfg = loadGlobalTasksConfig();
111
+ const piTasks = process.env.PI_TASKS;
112
+ let taskScope = cfg.taskScope ?? "session";
113
+ /** Both session scopes persist one file per session; they differ only in where it
114
+ * lives, so every lifecycle rule about session files applies to each of them. */
115
+ const isSessionScope = () => taskScope === "session" || taskScope === "session-global";
116
+ /** Resolve both the backing path and a stable identity for the active store. */
117
+ function resolveStoreTarget(cwd, sessionId) {
118
+ if (piTasks === "off")
119
+ return { key: "memory:env" };
120
+ if (piTasks?.startsWith("/"))
121
+ return { key: `path:${piTasks}`, path: piTasks };
122
+ if (piTasks?.startsWith(".")) {
123
+ const path = cwd ? resolve(cwd, piTasks) : undefined;
124
+ return path ? { key: `path:${path}`, path } : { key: "pending:relative" };
125
+ }
126
+ if (piTasks)
127
+ return { key: `named:${piTasks}`, path: piTasks };
128
+ if (taskScope === "memory")
129
+ return { key: "memory:config" };
130
+ if (!cwd)
131
+ return { key: "pending:workspace" };
132
+ if (isSessionScope() && sessionId) {
133
+ const path = sessionTaskFile(cwd, sessionId, taskScope);
134
+ return { key: `path:${path}`, path };
135
+ }
136
+ if (isSessionScope())
137
+ return { key: "pending:session" };
138
+ const path = join(cwd, ".pi", "tasks", "tasks.json");
139
+ return { key: `path:${path}`, path };
140
+ }
141
+ // Project and relative paths need ExtensionContext.cwd, which is unavailable
142
+ // while the extension factory runs. Absolute and named PI_TASKS overrides can
143
+ // still be opened immediately; all other stores start in memory.
144
+ let storeTarget = resolveStoreTarget();
145
+ let store = new TaskStore(storeTarget.path);
146
+ const tracker = new ProcessTracker();
147
+ const widget = new TaskWidget(store, cfg);
148
+ // ── Subagent integration state ──
149
+ /** Latest ExtensionContext — refreshed on every tool execution so cascade always has a valid one. */
150
+ let latestCtx;
151
+ /** Cascade config — set by TaskExecute, consumed by completion listener. */
152
+ let cascadeConfig;
153
+ /** Maps agent IDs to task IDs for O(1) completion lookup. */
154
+ const agentTaskMap = new Map();
155
+ /** Call a subagents RPC method: emit request, wait for scoped reply, unwrap envelope.
156
+ * With `onLateReply`, a timeout still rejects, but a success reply arriving within
157
+ * LATE_REPLY_WINDOW_MS afterwards is handed to it instead of being dropped. */
158
+ function rpcCall(channel, params, timeoutMs, onLateReply) {
159
+ const requestId = randomUUID();
160
+ debug(`rpc:send ${channel}`, { requestId });
161
+ return new Promise((resolve, reject) => {
162
+ let timedOut = false;
163
+ let lateTimer;
164
+ const timer = setTimeout(() => {
165
+ debug(`rpc:timeout ${channel}`, { requestId });
166
+ if (onLateReply) {
167
+ timedOut = true;
168
+ // Only cleans up a listener — must not keep `pi -p` alive.
169
+ lateTimer = setTimeout(unsub, LATE_REPLY_WINDOW_MS).unref();
170
+ }
171
+ else {
172
+ unsub();
173
+ }
174
+ const err = new Error(`${channel} timeout`);
175
+ err.timeout = true;
176
+ reject(err);
177
+ }, timeoutMs);
178
+ const unsub = pi.events.on(`${channel}:reply:${requestId}`, (raw) => {
179
+ unsub();
180
+ clearTimeout(timer);
181
+ clearTimeout(lateTimer);
182
+ debug(`rpc:reply ${channel}`, { requestId, raw, late: timedOut });
183
+ const reply = raw;
184
+ if (timedOut) {
185
+ if (reply.success)
186
+ onLateReply?.(reply.data);
187
+ }
188
+ else if (reply.success)
189
+ resolve(reply.data);
190
+ else
191
+ reject(new Error(reply.error));
192
+ });
193
+ pi.events.emit(channel, { requestId, ...params });
194
+ debug(`rpc:emitted ${channel}`, { requestId });
195
+ });
196
+ }
197
+ /** Spawn a subagent via pi.events RPC (requires @tintinweb/pi-subagents extension). */
198
+ function spawnSubagent(type, prompt, options, onLateSpawn) {
199
+ debug("spawn:call", { type, options: { ...options, prompt: undefined } });
200
+ return rpcCall("subagents:rpc:spawn", { type, prompt, options }, 30_000, onLateSpawn && (d => { debug("spawn:late", d); onLateSpawn(d.id); }))
201
+ .then(d => { debug("spawn:ok", d); return d.id; });
202
+ }
203
+ /** Record a spawned agent against its task so lifecycle events, TaskStop and TaskOutput find it. */
204
+ function bindAgent(taskId, agentId) {
205
+ agentTaskMap.set(agentId, taskId);
206
+ const task = store.get(taskId);
207
+ store.update(taskId, { owner: agentId, metadata: { ...task?.metadata, agentId } });
208
+ widget.setActiveTask(taskId);
209
+ }
210
+ /** A spawn reply that arrived after its timeout: link the agent if the task is still
211
+ * waiting for it, otherwise stop it — the task was reset or deleted, a retry may
212
+ * already have started a replacement, or the session switched to a store whose
213
+ * task IDs restart at 1 and would point at an unrelated task. */
214
+ function adoptLateAgent(spawnStore, taskId, agentId) {
215
+ const task = store === spawnStore ? store.get(taskId) : undefined;
216
+ if (task?.status === "in_progress" && !task.metadata?.agentId) {
217
+ bindAgent(taskId, agentId);
218
+ widget.update();
219
+ }
220
+ else {
221
+ void stopSubagent(agentId);
222
+ }
223
+ }
224
+ /** Stop a subagent via pi.events RPC (requires @tintinweb/pi-subagents extension).
225
+ * Resolves true if the stop was confirmed, false if the RPC errored or timed out. */
226
+ function stopSubagent(agentId) {
227
+ return rpcCall("subagents:rpc:stop", { agentId }, 10_000).then(() => true).catch(() => false);
228
+ }
229
+ /** Tell subagents its result has been handed to the model, which suppresses the
230
+ * completion notification it would otherwise deliver for the same result — the
231
+ * same consumption `get_subagent_result` performs when it returns one.
232
+ *
233
+ * Fire-and-forget rather than an `rpcCall`: the reply carries nothing to act on,
234
+ * and the channel is deliberately outside the version handshake so a pi-subagents
235
+ * without the handler keeps notifying instead of failing the read. */
236
+ function consumeSubagentResult(agentId) {
237
+ pi.events.emit("subagents:rpc:consume", { requestId: randomUUID(), agentId });
238
+ }
239
+ // ── Subagent extension presence & version detection ──
240
+ const PROTOCOL_VERSION = 2;
241
+ let subagentsAvailable = false;
242
+ let pendingWarning;
243
+ /** Ping subagents and check protocol version. Works with any handler version. */
244
+ function checkSubagentsVersion() {
245
+ const requestId = randomUUID();
246
+ const timer = setTimeout(() => { unsub(); }, 5_000);
247
+ const unsub = pi.events.on(`subagents:rpc:ping:reply:${requestId}`, (raw) => {
248
+ unsub();
249
+ clearTimeout(timer);
250
+ const remoteVersion = raw?.data?.version;
251
+ if (remoteVersion === undefined) {
252
+ pendingWarning =
253
+ "@tintinweb/pi-subagents is outdated — please update for task execution support.";
254
+ }
255
+ else if (remoteVersion > PROTOCOL_VERSION) {
256
+ pendingWarning =
257
+ `@tintinweb/pi-tasks is outdated (protocol v${PROTOCOL_VERSION}, ` +
258
+ `pi-subagents has v${remoteVersion}) — please update for task execution support.`;
259
+ }
260
+ else if (remoteVersion < PROTOCOL_VERSION) {
261
+ pendingWarning =
262
+ `@tintinweb/pi-subagents is outdated (protocol v${remoteVersion}, ` +
263
+ `pi-tasks has v${PROTOCOL_VERSION}) — please update for task execution support.`;
264
+ }
265
+ else {
266
+ subagentsAvailable = true;
267
+ }
268
+ });
269
+ pi.events.emit("subagents:rpc:ping", { requestId });
270
+ }
271
+ checkSubagentsVersion();
272
+ pi.events.on("subagents:ready", () => checkSubagentsVersion());
273
+ /** Build a prompt for a task being executed by a subagent.
274
+ * Injects completed dependency results so cascaded agents have context from prerequisites.
275
+ */
276
+ function buildTaskPrompt(task, additionalContext) {
277
+ let prompt = `You are executing task #${task.id}: "${task.subject}"\n\n${task.description}`;
278
+ // Inject completed dependency results so cascaded agents have full context
279
+ if (task.blockedBy && task.blockedBy.length > 0) {
280
+ const depResults = [];
281
+ for (const depId of task.blockedBy) {
282
+ const dep = store.get(depId);
283
+ if (dep?.metadata?.result) {
284
+ const result = dep.metadata.result.length > 4000
285
+ ? dep.metadata.result.slice(0, 4000) + "\n\n[... truncated — use TaskGet for full output]"
286
+ : dep.metadata.result;
287
+ depResults.push(`### Task #${depId}: ${dep.subject}\n${result}`);
288
+ }
289
+ }
290
+ if (depResults.length > 0) {
291
+ prompt += `\n\n## Prerequisite task results\n\n${depResults.join("\n\n")}`;
292
+ }
293
+ }
294
+ if (additionalContext)
295
+ prompt += `\n\n${additionalContext}`;
296
+ prompt += `\n\nComplete this task fully. Do not attempt to manage tasks yourself.`;
297
+ return prompt;
298
+ }
299
+ const autoClear = new AutoClearManager(() => store, () => cfg.autoClearCompleted ?? "on_list_complete", AUTO_CLEAR_DELAY);
300
+ // ── Subagent completion listener ──
301
+ // Listens for subagent lifecycle events to update task status and optionally cascade.
302
+ // Success → mark task completed, cascade if enabled
303
+ pi.events.on("subagents:completed", async (data) => {
304
+ const { id, result } = data;
305
+ const taskId = agentTaskMap.get(id);
306
+ if (!taskId)
307
+ return;
308
+ agentTaskMap.delete(id);
309
+ const task = store.get(taskId);
310
+ if (!task)
311
+ return;
312
+ store.update(task.id, { status: "completed", metadata: { ...task.metadata, result } });
313
+ widget.setActiveTask(task.id, false);
314
+ // Auto-cascade: find unblocked dependents with agentType
315
+ if ((cfg.autoCascade ?? false) && cascadeConfig && latestCtx) {
316
+ const unblocked = store.list().filter(t => t.status === "pending" &&
317
+ t.metadata?.agentType &&
318
+ t.blockedBy.includes(task.id) &&
319
+ t.blockedBy.every(depId => store.get(depId)?.status === "completed"));
320
+ for (const next of unblocked) {
321
+ store.update(next.id, { status: "in_progress" });
322
+ const spawnStore = store;
323
+ const prompt = buildTaskPrompt(next, cascadeConfig.additionalContext);
324
+ try {
325
+ const agentId = await spawnSubagent(next.metadata.agentType, prompt, {
326
+ description: next.subject,
327
+ isBackground: true,
328
+ maxTurns: cascadeConfig.maxTurns,
329
+ ...(cascadeConfig.model ? { model: cascadeConfig.model } : {}),
330
+ }, lateId => adoptLateAgent(spawnStore, next.id, lateId));
331
+ bindAgent(next.id, agentId);
332
+ }
333
+ catch (err) {
334
+ // A timeout does not prove the agent never started: stay in_progress and let a
335
+ // late reply link it (see TaskExecute).
336
+ if (!err?.timeout) {
337
+ store.update(next.id, { status: "pending", metadata: { ...next.metadata, result: null, lastError: err.message } });
338
+ }
339
+ }
340
+ }
341
+ }
342
+ autoClear.trackCompletion(task.id, cadence.currentTurn);
343
+ widget.update();
344
+ });
345
+ // Failure → store error, revert to pending, don't cascade (branch stops)
346
+ // Intentional stop (status === "stopped") → mark completed, preserve partial result
347
+ pi.events.on("subagents:failed", (data) => {
348
+ const { id, error, result, status } = data;
349
+ const taskId = agentTaskMap.get(id);
350
+ if (!taskId)
351
+ return;
352
+ agentTaskMap.delete(id);
353
+ const task = store.get(taskId);
354
+ if (!task)
355
+ return;
356
+ if (status === "stopped") {
357
+ // Intentional stop — mark completed, preserve partial result
358
+ store.update(task.id, { status: "completed", metadata: { ...task.metadata, result: result || task.metadata?.result } });
359
+ autoClear.trackCompletion(task.id, cadence.currentTurn);
360
+ }
361
+ else {
362
+ // Actual error — revert to pending. `result: null` drops it (the store deletes
363
+ // a key set to null): a task back to pending has no current result, and an
364
+ // earlier run's would otherwise outrank this error everywhere it is read.
365
+ store.update(task.id, { status: "pending", metadata: { ...task.metadata, result: null, lastError: error || status } });
366
+ autoClear.resetBatchCountdown();
367
+ }
368
+ widget.setActiveTask(task.id, false);
369
+ widget.update();
370
+ });
371
+ // ── Context-scoped store initialization ──
372
+ // Project paths cannot be resolved until an ExtensionContext is available.
373
+ // Initialize on the first context-bearing event and reinitialize when a host
374
+ // switches this extension instance to a session in another workspace.
375
+ let configuredCwd;
376
+ let persistedTasksShown = false;
377
+ let agentsReattached = false;
378
+ function initializeStoreForContext(ctx, reloadConfig = false) {
379
+ // Keep the config object identity stable because the widget and auto-clear
380
+ // manager retain references to it, but replace every value so overrides
381
+ // from a previous workspace cannot leak into the next one.
382
+ if (reloadConfig || configuredCwd !== ctx.cwd) {
383
+ for (const key of Object.keys(cfg))
384
+ delete cfg[key];
385
+ Object.assign(cfg, loadTasksConfig(ctx.cwd));
386
+ taskScope = cfg.taskScope ?? "session";
387
+ }
388
+ // `pi --no-session` mints a session ID but never a session file. Keying off the
389
+ // ID alone would write tasks-<id>.json for a session that can never be resumed
390
+ // and is orphaned the moment pi exits: if pi is not persisting the conversation,
391
+ // don't persist the task list either.
392
+ const sessionId = isSessionScope() && !piTasks && ctx.sessionManager.getSessionFile()
393
+ ? ctx.sessionManager.getSessionId()
394
+ : undefined;
395
+ const nextTarget = resolveStoreTarget(ctx.cwd, sessionId);
396
+ if (nextTarget.key !== storeTarget.key) {
397
+ store = new TaskStore(nextTarget.path);
398
+ widget.setStore(store);
399
+ storeTarget = nextTarget;
400
+ // The new store owns a different task list, so the agent map has to be
401
+ // rebuilt from it rather than kept from the previous one.
402
+ agentsReattached = false;
403
+ }
404
+ configuredCwd = ctx.cwd;
405
+ }
406
+ /** Delete an emptied session file, and — under `session-global` only — the
407
+ * directory that held it once its last session is gone. Nothing else is ours
408
+ * to reclaim: a PI_TASKS path can point anywhere, and `<workspace>/.pi/tasks/`
409
+ * is left standing exactly as it always has been. */
410
+ function deleteSessionFileIfEmpty() {
411
+ if (!store.deleteFileIfEmpty())
412
+ return;
413
+ if (taskScope === "session-global" && !piTasks && configuredCwd) {
414
+ reclaimGlobalSessionTasksDir(configuredCwd);
415
+ }
416
+ }
417
+ /** Re-link persisted in-progress tasks to the subagents still running for them.
418
+ * `agentTaskMap` lives only in this extension instance, so a reload starts empty
419
+ * while the agents keep going — their completion events would then be dropped and
420
+ * the tasks would stay in_progress forever. Everything needed is already on disk:
421
+ * TaskExecute records the agent ID in task metadata.
422
+ *
423
+ * Only in_progress tasks are relinked. A task reverted to pending keeps its
424
+ * `metadata.agentId`, and relinking that would let a late event resurrect work the
425
+ * user has already reset. Only runs once — the first caller wins. */
426
+ function reattachAgents() {
427
+ if (agentsReattached)
428
+ return;
429
+ agentsReattached = true;
430
+ for (const task of store.list()) {
431
+ const agentId = task.metadata?.agentId;
432
+ if (task.status === "in_progress" && typeof agentId === "string" && agentId) {
433
+ agentTaskMap.set(agentId, task.id);
434
+ }
435
+ }
436
+ }
437
+ /** Restore widget on session start/resume if there's unfinished work.
438
+ * On new sessions, auto-clear if all tasks are completed (clean slate).
439
+ * On resume, always show tasks (user may want to review).
440
+ * Only runs once — the first caller wins. */
441
+ function showPersistedTasks(isResume = false) {
442
+ if (persistedTasksShown)
443
+ return;
444
+ persistedTasksShown = true;
445
+ const tasks = store.list();
446
+ if (tasks.length > 0) {
447
+ if (!isResume && tasks.every(t => t.status === "completed")) {
448
+ store.clearCompleted();
449
+ if (isSessionScope())
450
+ deleteSessionFileIfEmpty();
451
+ }
452
+ else {
453
+ widget.update();
454
+ }
455
+ }
456
+ }
457
+ // ── Turn tracking for system-reminder injection ──
458
+ // Cadence decisions live in `reminder-cadence.ts` so they're
459
+ // unit-testable without spinning up a fake ExtensionAPI.
460
+ const cadence = createCadenceState();
461
+ const cadenceConfig = {
462
+ reminderInterval: REMINDER_INTERVAL,
463
+ taskToolNames: TASK_TOOL_NAMES,
464
+ };
465
+ pi.on("turn_start", async (_event, ctx) => {
466
+ onTurnStart(cadence);
467
+ latestCtx = ctx;
468
+ widget.setUICtx(ctx.ui);
469
+ initializeStoreForContext(ctx);
470
+ if (autoClear.onTurnStart(cadence.currentTurn)) {
471
+ if (isSessionScope())
472
+ deleteSessionFileIfEmpty();
473
+ widget.update();
474
+ }
475
+ });
476
+ // The end of a run is the only signal that separates a new batch of tasks from the
477
+ // same batch still being built — the store looks identical either way. Nothing is
478
+ // cleared here; this only marks the boundary for the next TaskCreate.
479
+ pi.on("agent_settled", async () => {
480
+ autoClear.onRunEnded();
481
+ });
482
+ // ── Token usage tracking + stale-task detection ──
483
+ // Feed per-turn token counts from assistant messages into the widget.
484
+ // Also detect when the agent has stopped referencing tasks but left
485
+ // them in_progress — schedule a reminder for the next LLM call.
486
+ pi.on("turn_end", async (event) => {
487
+ const msg = event.message;
488
+ if (msg?.role === "assistant" && msg.usage) {
489
+ widget.addTokenUsage(msg.usage.input ?? 0, msg.usage.output ?? 0);
490
+ }
491
+ // Stale-task detection: catch the case where the agent finishes work in a
492
+ // text-only turn (no tool calls, so tool_result never fires) but left tasks
493
+ // in_progress. Cheap-first: only read the store once the turn gap could
494
+ // matter — the in_progress interval is the smallest a reminder can need.
495
+ if (!cadence.reminderInjectedThisCycle && !cadence.reminderDue) {
496
+ const gap = cadence.currentTurn - cadence.lastTaskToolUseTurn;
497
+ if (gap >= ACTIVE_REMINDER_INTERVAL && store.list().some(t => t.status === "in_progress")) {
498
+ cadence.reminderDue = true;
499
+ }
500
+ }
501
+ });
502
+ // ── System-reminder injection ──
503
+ //
504
+ // tool_result is used ONLY to track cadence. We DO NOT mutate non-task
505
+ // tool result content — appending a <system-reminder> there would
506
+ // corrupt model-visible transcript semantics for unrelated tools (read,
507
+ // bash, grep, …) and make tool-output debugging miserable.
508
+ //
509
+ // The actual injection happens in the `context` hook below, which fires
510
+ // before each LLM call and returns a modified copy of the messages
511
+ // without persisting or polluting any tool output.
512
+ pi.on("tool_result", async (event) => {
513
+ // Task tool usage resets cadence (interval is irrelevant on this path — the
514
+ // helper resets and returns before reading it).
515
+ if (TASK_TOOL_NAMES.has(event.toolName)) {
516
+ evaluateToolResult(cadence, event.toolName, false, cadenceConfig);
517
+ return {};
518
+ }
519
+ if (cadence.reminderInjectedThisCycle)
520
+ return {};
521
+ // Cheap-first: avoid store.list() disk I/O until the turn gap could matter.
522
+ // ACTIVE_REMINDER_INTERVAL is the smallest interval any reminder can need.
523
+ if (cadence.currentTurn - cadence.lastTaskToolUseTurn < ACTIVE_REMINDER_INTERVAL)
524
+ return {};
525
+ const tasks = store.list();
526
+ // Shorter interval while in_progress; passed per-call so the shared config
527
+ // is never mutated.
528
+ evaluateToolResult(cadence, event.toolName, tasks.length > 0, {
529
+ ...cadenceConfig,
530
+ reminderInterval: intervalFor(tasks),
531
+ });
532
+ return {};
533
+ });
534
+ // Inject the transient system-reminder into the upcoming LLM call's
535
+ // messages, never into a tool result. The reminder is appended as a
536
+ // user message so models that don't support custom message types still
537
+ // receive it. It is not persisted in the session store — `context`
538
+ // returns a transformed messages array used only for this one request.
539
+ pi.on("context", async (event) => {
540
+ if (!drainReminderForContext(cadence))
541
+ return {};
542
+ const tasks = store.list();
543
+ return {
544
+ messages: [
545
+ ...event.messages,
546
+ {
547
+ role: "user",
548
+ content: [{ type: "text", text: buildSystemReminder(tasks) }],
549
+ timestamp: Date.now(),
550
+ },
551
+ ],
552
+ };
553
+ });
554
+ // session_start replaces the never-emitted session_switch event. Rehydrating
555
+ // here matters because before_agent_start only fires once the user prompts.
556
+ pi.on("session_start", async (event, ctx) => {
557
+ latestCtx = ctx;
558
+ widget.setUICtx(ctx.ui);
559
+ const reason = event.reason;
560
+ // new/resume/fork reuse the running extension instance (getExtensions() is
561
+ // cached), so session-scoped state must be reset. startup/reload re-run the
562
+ // factory and start clean.
563
+ const isSwitch = reason === "new" || reason === "resume" || reason === "fork";
564
+ // A fork branches the conversation, so its tasks carry over as an independent
565
+ // copy. Snapshot before the store re-points to the new (empty) session file.
566
+ const forkSeed = reason === "fork" ? store.snapshot() : undefined;
567
+ if (isSwitch) {
568
+ persistedTasksShown = false;
569
+ agentsReattached = false;
570
+ // Task IDs restart at 1 in every session, so a mapping held over from the
571
+ // previous one points at an unrelated task here — the agent's completion would
572
+ // close a task it never ran. reattachAgents() rebuilds what this session owns.
573
+ agentTaskMap.clear();
574
+ resetCadenceState(cadence);
575
+ autoClear.reset();
576
+ // Memory mode has no file to switch — clear tasks explicitly on /new.
577
+ if (reason === "new" && taskScope === "memory") {
578
+ store.clearAll();
579
+ }
580
+ }
581
+ initializeStoreForContext(ctx, true);
582
+ if (forkSeed?.tasks.length)
583
+ store.seed(forkSeed); // carry the parent's tasks into the fork
584
+ reattachAgents(); // subagents outlive a reload; relink them before events arrive
585
+ // resume/reload/fork keep tasks; startup/new auto-clear an all-completed list.
586
+ const keepsTasks = reason === "reload" || reason === "resume" || reason === "fork";
587
+ showPersistedTasks(keepsTasks);
588
+ // Those tasks are shown for review, but the run that produced them ended with the
589
+ // session before this one — so the next batch must not be added to them either.
590
+ if (keepsTasks)
591
+ autoClear.onRunEnded();
592
+ if (pendingWarning) {
593
+ ctx.ui.notify(pendingWarning, "warning");
594
+ pendingWarning = undefined;
595
+ }
596
+ });
597
+ // Stop the spinner interval when the session ends. A live interval keeps the
598
+ // event loop busy, so `pi -p` never exits once a task has been in progress.
599
+ // new/resume/fork re-run session_start, whose update() restarts it if needed.
600
+ pi.on("session_shutdown", async () => {
601
+ widget.dispose();
602
+ });
603
+ // Fallback for hosts that init UI lazily. Guarded by persistedTasksShown, so
604
+ // it never double-renders after session_start.
605
+ pi.on("before_agent_start", async (_event, ctx) => {
606
+ latestCtx = ctx;
607
+ widget.setUICtx(ctx.ui);
608
+ initializeStoreForContext(ctx);
609
+ reattachAgents();
610
+ showPersistedTasks();
611
+ if (pendingWarning) {
612
+ ctx.ui.notify(pendingWarning, "warning");
613
+ pendingWarning = undefined;
614
+ }
615
+ });
616
+ // Keep latestCtx fresh on every tool execution as well.
617
+ pi.on("tool_execution_start", async (_event, ctx) => {
618
+ latestCtx = ctx;
619
+ widget.setUICtx(ctx.ui);
620
+ initializeStoreForContext(ctx);
621
+ widget.update();
622
+ });
623
+ // ──────────────────────────────────────────────────
624
+ // Tool 1: TaskCreate
625
+ // ──────────────────────────────────────────────────
626
+ pi.registerTool({
627
+ name: "TaskCreate",
628
+ label: "TaskCreate",
629
+ description: `Use this tool to create a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
630
+ It also helps the user understand the progress of the task and overall progress of their requests.
631
+
632
+ ## When to Use This Tool
633
+
634
+ Use this tool proactively in these scenarios:
635
+
636
+ - Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
637
+ - Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
638
+ - Plan mode - When using plan mode, create a task list to track the work
639
+ - User explicitly requests todo list - When the user directly asks you to use the todo list
640
+ - User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated). Create them all in one response with one TaskCreate call per task
641
+ - After receiving new instructions - Immediately capture user requirements as tasks
642
+ - When you start working on a task - Mark it as in_progress BEFORE beginning work
643
+ - After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation
644
+
645
+ ## When NOT to Use This Tool
646
+
647
+ Skip using this tool when:
648
+ - There is only a single, straightforward task
649
+ - The task is trivial and tracking it provides no organizational benefit
650
+ - The task can be completed in less than 3 trivial steps
651
+ - The task is purely conversational or informational
652
+
653
+ NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.
654
+
655
+ ## Task Fields
656
+
657
+ - **subject**: A brief, actionable title in imperative form (e.g., "Fix authentication bug in login flow")
658
+ - **description**: Detailed description of what needs to be done, including context and acceptance criteria
659
+ - **activeForm** (optional): Present continuous form shown in the spinner when the task is in_progress (e.g., "Fixing authentication bug"). If omitted, the spinner shows the subject instead.
660
+
661
+ All tasks are created with status \`pending\`.
662
+
663
+ ## Tips
664
+
665
+ - Create tasks with clear, specific subjects that describe the outcome
666
+ - Include enough detail in the description for another agent to understand and complete the task
667
+ - After creating tasks, use TaskUpdate to set up dependencies (blocks/blockedBy) if needed
668
+ - Check TaskList first to avoid creating duplicate tasks
669
+ - Include \`agentType\` (e.g., "general-purpose", "Explore") to mark tasks for subagent execution via TaskExecute
670
+ - To create several tasks at once, call TaskCreate multiple times in a single response — independent tool calls run in parallel, so the whole batch is created in one turn (one task per call).`,
671
+ promptGuidelines: [
672
+ "When working on complex multi-step tasks, use TaskCreate to track progress and TaskUpdate to update status.",
673
+ "Mark tasks as in_progress before starting work and completed when done.",
674
+ "Use TaskList to check for available work after completing a task.",
675
+ ],
676
+ parameters: Type.Object({
677
+ subject: Type.String({ description: "A brief title for the task" }),
678
+ description: Type.String({ description: "A detailed description of what needs to be done" }),
679
+ activeForm: Type.Optional(Type.String({ description: "Present continuous form shown in spinner when in_progress (e.g., 'Running tests')" })),
680
+ agentType: Type.Optional(Type.String({ description: "Agent type for subagent execution (e.g., 'general-purpose', 'Explore'). Tasks with agentType can be started via TaskExecute." })),
681
+ metadata: Type.Optional(Type.Record(Type.String(), Type.Any(), { description: "Arbitrary metadata to attach to the task" })),
682
+ }),
683
+ execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
684
+ // A finished list must not collect the batch that follows it. The turn countdowns
685
+ // cannot be relied on for that: they only tick at `turn_start`, so a run that ends
686
+ // right after its last completion freezes one mid-count.
687
+ autoClear.startNewBatch();
688
+ const meta = params.metadata ?? {};
689
+ if (params.agentType)
690
+ meta.agentType = params.agentType;
691
+ const task = store.create(params.subject, params.description, params.activeForm, Object.keys(meta).length > 0 ? meta : undefined);
692
+ widget.update();
693
+ return Promise.resolve(textResult(`Task #${task.id} created successfully: ${task.subject}`));
694
+ },
695
+ });
696
+ // ──────────────────────────────────────────────────
697
+ // Tool 2: TaskList
698
+ // ──────────────────────────────────────────────────
699
+ pi.registerTool({
700
+ name: "TaskList",
701
+ label: "TaskList",
702
+ description: `Use this tool to list all tasks in the task list.
703
+
704
+ ## When to Use This Tool
705
+
706
+ - To see what tasks are available to work on (status: 'pending', no owner, not blocked)
707
+ - To check overall progress on the project
708
+ - To find tasks that are blocked and need dependencies resolved
709
+ - After completing a task, to check for newly unblocked work or claim the next available task
710
+ - **Prefer working on tasks in ID order** (lowest ID first) when multiple tasks are available, as earlier tasks often set up context for later ones
711
+
712
+ ## Output
713
+
714
+ Returns a summary of each task:
715
+ - **id**: Task identifier (use with TaskGet, TaskUpdate)
716
+ - **subject**: Brief description of the task
717
+ - **status**: 'pending', 'in_progress', or 'completed'
718
+ - **owner**: Agent ID if assigned, empty if available
719
+ - **blockedBy**: List of open task IDs that must be resolved first (tasks with blockedBy cannot be claimed until dependencies resolve)
720
+
721
+ Use TaskGet with a specific task ID to view full details including description and comments.`,
722
+ parameters: Type.Object({}),
723
+ execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
724
+ const tasks = store.list();
725
+ if (tasks.length === 0)
726
+ return Promise.resolve(textResult("No tasks found"));
727
+ // Sort: pending first (by ID), then in_progress (by ID), then completed (by ID)
728
+ const statusOrder = { pending: 0, in_progress: 1, completed: 2 };
729
+ const sorted = [...tasks].sort((a, b) => {
730
+ const so = (statusOrder[a.status] ?? 0) - (statusOrder[b.status] ?? 0);
731
+ if (so !== 0)
732
+ return so;
733
+ return Number(a.id) - Number(b.id);
734
+ });
735
+ const lines = sorted.map(task => {
736
+ let line = `#${task.id} [${task.status}] ${task.subject}`;
737
+ if (task.owner) {
738
+ line += ` (${task.owner})`;
739
+ }
740
+ // Only show non-completed blockers
741
+ if (task.blockedBy.length > 0) {
742
+ const openBlockers = task.blockedBy.filter(bid => {
743
+ const blocker = store.get(bid);
744
+ return blocker && blocker.status !== "completed";
745
+ });
746
+ if (openBlockers.length > 0) {
747
+ line += ` [blocked by ${openBlockers.map(id => "#" + id).join(", ")}]`;
748
+ }
749
+ }
750
+ return line;
751
+ });
752
+ return Promise.resolve(textResult(lines.join("\n")));
753
+ },
754
+ });
755
+ // ──────────────────────────────────────────────────
756
+ // Tool 3: TaskGet
757
+ // ──────────────────────────────────────────────────
758
+ pi.registerTool({
759
+ name: "TaskGet",
760
+ label: "TaskGet",
761
+ description: `Use this tool to retrieve a task by its ID from the task list.
762
+
763
+ ## When to Use This Tool
764
+
765
+ - When you need the full description and context before starting work on a task
766
+ - To understand task dependencies (what it blocks, what blocks it)
767
+ - After being assigned a task, to get complete requirements
768
+
769
+ ## Output
770
+
771
+ Returns full task details:
772
+ - **subject**: Task title
773
+ - **description**: Detailed requirements and context
774
+ - **status**: 'pending', 'in_progress', or 'completed'
775
+ - **blocks**: Tasks waiting on this one to complete
776
+ - **blockedBy**: Tasks that must complete before this one can start
777
+
778
+ ## Tips
779
+
780
+ - After fetching a task, verify its blockedBy list is empty before beginning work.
781
+ - Use TaskList to see all tasks in summary form.`,
782
+ parameters: Type.Object({
783
+ taskId: Type.String({ description: "The ID of the task to retrieve" }),
784
+ }),
785
+ execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
786
+ const task = store.get(params.taskId);
787
+ if (!task)
788
+ return Promise.resolve(textResult(`Task not found`));
789
+ // Unescape literal \n sequences the LLM may have double-escaped in JSON
790
+ const desc = task.description.replace(/\\n/g, "\n");
791
+ const lines = [
792
+ `Task #${task.id}: ${task.subject}`,
793
+ `Status: ${task.status}`,
794
+ ];
795
+ if (task.owner) {
796
+ lines.push(`Owner: ${task.owner}`);
797
+ }
798
+ lines.push(`Description: ${desc}`);
799
+ if (task.blockedBy.length > 0) {
800
+ const openBlockers = task.blockedBy.filter(bid => {
801
+ const blocker = store.get(bid);
802
+ return blocker && blocker.status !== "completed";
803
+ });
804
+ if (openBlockers.length > 0) {
805
+ lines.push(`Blocked by: ${openBlockers.map(id => "#" + id).join(", ")}`);
806
+ }
807
+ }
808
+ if (task.blocks.length > 0) {
809
+ lines.push(`Blocks: ${task.blocks.map(id => "#" + id).join(", ")}`);
810
+ }
811
+ // Show metadata if non-empty
812
+ const metaKeys = Object.keys(task.metadata);
813
+ if (metaKeys.length > 0) {
814
+ lines.push(`Metadata: ${JSON.stringify(task.metadata)}`);
815
+ }
816
+ return Promise.resolve(textResult(lines.join("\n")));
817
+ },
818
+ });
819
+ // ──────────────────────────────────────────────────
820
+ // Tool 4: TaskUpdate
821
+ // ──────────────────────────────────────────────────
822
+ pi.registerTool({
823
+ name: "TaskUpdate",
824
+ label: "TaskUpdate",
825
+ description: `Use this tool to update a task in the task list.
826
+
827
+ ## When to Use This Tool
828
+
829
+ **Before starting work on a task:**
830
+ - Mark it in_progress BEFORE beginning — do not start work without updating status first
831
+ - After resolving, call TaskList to find your next task
832
+
833
+ **Mark tasks as resolved:**
834
+ - When you have completed the work described in a task
835
+ - When a task is no longer needed or has been superseded
836
+ - IMPORTANT: Always mark your assigned tasks as resolved when you finish them
837
+ - After resolving, call TaskList to find your next task
838
+
839
+ - ONLY mark a task as completed when you have FULLY accomplished it
840
+ - If you encounter errors, blockers, or cannot finish, keep the task as in_progress
841
+ - When blocked, create a new task describing what needs to be resolved
842
+ - Never mark a task as completed if:
843
+ - Tests are failing
844
+ - Implementation is partial
845
+ - You encountered unresolved errors
846
+ - You couldn't find necessary files or dependencies
847
+
848
+ **Delete tasks:**
849
+ - When a task is no longer relevant or was created in error
850
+ - Setting status to \`deleted\` permanently removes the task
851
+
852
+ **Update task details:**
853
+ - When requirements change or become clearer
854
+ - When establishing dependencies between tasks
855
+
856
+ ## Fields You Can Update
857
+
858
+ - **status**: The task status (see Status Workflow below)
859
+ - **subject**: Change the task title (imperative form, e.g., "Run tests")
860
+ - **description**: Change the task description
861
+ - **activeForm**: Present continuous form shown in spinner when in_progress (e.g., "Running tests")
862
+ - **owner**: Change the task owner (agent name)
863
+ - **metadata**: Merge metadata keys into the task (set a key to null to delete it)
864
+ - **addBlocks**: Mark tasks that cannot start until this one completes
865
+ - **addBlockedBy**: Mark tasks that must complete before this one can start
866
+
867
+ ## Status Workflow
868
+
869
+ Status progresses: \`pending\` → \`in_progress\` → \`completed\`
870
+
871
+ Use \`deleted\` to permanently remove a task.
872
+
873
+ ## Staleness
874
+
875
+ Make sure to read a task's latest state using \`TaskGet\` before updating it.
876
+
877
+ ## Examples
878
+
879
+ Mark task as in progress when starting work:
880
+ \`\`\`json
881
+ {"taskId": "1", "status": "in_progress"}
882
+ \`\`\`
883
+
884
+ Mark task as completed after finishing work:
885
+ \`\`\`json
886
+ {"taskId": "1", "status": "completed"}
887
+ \`\`\`
888
+
889
+ Delete a task:
890
+ \`\`\`json
891
+ {"taskId": "1", "status": "deleted"}
892
+ \`\`\`
893
+
894
+ Claim a task by setting owner:
895
+ \`\`\`json
896
+ {"taskId": "1", "owner": "my-name"}
897
+ \`\`\`
898
+
899
+ Set up task dependencies:
900
+ \`\`\`json
901
+ {"taskId": "2", "addBlockedBy": ["1"]}
902
+ \`\`\``,
903
+ parameters: Type.Object({
904
+ taskId: Type.String({ description: "The ID of the task to update" }),
905
+ status: Type.Optional(Type.Unsafe({
906
+ type: "string",
907
+ enum: ["pending", "in_progress", "completed", "deleted"],
908
+ description: "New status for the task",
909
+ })),
910
+ subject: Type.Optional(Type.String({ description: "New subject for the task" })),
911
+ description: Type.Optional(Type.String({ description: "New description for the task" })),
912
+ activeForm: Type.Optional(Type.String({ description: "Present continuous form shown in spinner when in_progress" })),
913
+ owner: Type.Optional(Type.String({ description: "New owner for the task" })),
914
+ metadata: Type.Optional(Type.Record(Type.String(), Type.Any(), { description: "Metadata keys to merge into the task. Set a key to null to delete it." })),
915
+ addBlocks: Type.Optional(Type.Array(Type.String(), { description: "Task IDs that this task blocks" })),
916
+ addBlockedBy: Type.Optional(Type.Array(Type.String(), { description: "Task IDs that block this task" })),
917
+ }),
918
+ execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
919
+ const { taskId, ...fields } = params;
920
+ const { task, changedFields, warnings } = store.update(taskId, fields);
921
+ if (changedFields.length === 0 && !task) {
922
+ return Promise.resolve(textResult(`Task #${taskId} not found`));
923
+ }
924
+ // Update widget active task tracking
925
+ if (fields.status === "in_progress") {
926
+ widget.setActiveTask(taskId);
927
+ autoClear.resetBatchCountdown();
928
+ }
929
+ else if (fields.status === "pending") {
930
+ autoClear.resetBatchCountdown();
931
+ }
932
+ else if (fields.status === "completed" || fields.status === "deleted") {
933
+ widget.setActiveTask(taskId, false);
934
+ if (fields.status === "completed")
935
+ autoClear.trackCompletion(taskId, cadence.currentTurn);
936
+ }
937
+ widget.update();
938
+ let msg = `Updated task #${taskId} ${changedFields.join(", ")}`;
939
+ if (warnings.length > 0) {
940
+ msg += ` (warning: ${warnings.join("; ")})`;
941
+ }
942
+ return Promise.resolve(textResult(msg));
943
+ },
944
+ });
945
+ // ──────────────────────────────────────────────────
946
+ // Tool 5: TaskOutput
947
+ // ──────────────────────────────────────────────────
948
+ pi.registerTool({
949
+ name: "TaskOutput",
950
+ label: "TaskOutput",
951
+ description: `- Retrieves output from a running or completed task (background shell, agent, or remote session)
952
+ - Takes a task_id parameter identifying the task
953
+ - Returns the task output along with status information
954
+ - Use block=true (default) to wait for task completion
955
+ - Use block=false for non-blocking check of current status
956
+ - Task IDs can be found using the /tasks command
957
+ - Works with all task types: background shells, async agents, and remote sessions`,
958
+ parameters: Type.Object({
959
+ task_id: Type.String({ description: "The task ID to get output from" }),
960
+ block: Type.Boolean({ description: "Whether to wait for completion", default: true }),
961
+ timeout: Type.Number({ description: "Max wait time in ms", default: 30000, minimum: 0, maximum: 600000 }),
962
+ }),
963
+ async execute(_toolCallId, params, signal, _onUpdate, _ctx) {
964
+ const { task_id, block, timeout } = params;
965
+ // Reject an empty id up front: every agent ID starts with "", so the prefix
966
+ // match below would resolve it to whichever agent the map yields first.
967
+ if (!task_id)
968
+ throw new Error("task_id is required");
969
+ const processOutput = tracker.getOutput(task_id);
970
+ if (!processOutput) {
971
+ // No shell process — check if this is a subagent task
972
+ // Support both task IDs and agent IDs (resolve agent ID → task ID)
973
+ let resolvedId = task_id;
974
+ if (!store.get(resolvedId)) {
975
+ // Check if this is an agent ID mapped to a task
976
+ for (const [agentId, taskId] of agentTaskMap) {
977
+ if (agentId === task_id || agentId.startsWith(task_id)) {
978
+ resolvedId = taskId;
979
+ break;
980
+ }
981
+ }
982
+ }
983
+ const task = store.get(resolvedId);
984
+ if (!task)
985
+ throw new Error(`No task found with ID ${task_id}`);
986
+ if (task.metadata?.agentId) {
987
+ // Subagent task — wait for completion if blocking
988
+ if (block && task.status === "in_progress") {
989
+ await new Promise((resolve) => {
990
+ const timer = setTimeout(() => { unsubOk(); unsubFail(); resolve(); }, timeout ?? 30000);
991
+ const cleanup = () => { clearTimeout(timer); resolve(); };
992
+ const unsubOk = pi.events.on("subagents:completed", (d) => {
993
+ if (d.id === task.metadata?.agentId) {
994
+ unsubOk();
995
+ unsubFail();
996
+ cleanup();
997
+ }
998
+ });
999
+ const unsubFail = pi.events.on("subagents:failed", (d) => {
1000
+ if (d.id === task.metadata?.agentId) {
1001
+ unsubOk();
1002
+ unsubFail();
1003
+ cleanup();
1004
+ }
1005
+ });
1006
+ // Re-read before committing to the wait. Nothing awaits since the outer
1007
+ // check, so this only differs on a shared file-backed list, where
1008
+ // store.get() reloads and another session may have finished the task.
1009
+ const current = store.get(resolvedId);
1010
+ if (current && current.status !== "in_progress") {
1011
+ unsubOk();
1012
+ unsubFail();
1013
+ cleanup();
1014
+ }
1015
+ signal?.addEventListener("abort", () => { unsubOk(); unsubFail(); cleanup(); }, { once: true });
1016
+ });
1017
+ }
1018
+ // Re-read by resolved ID — `task` predates the wait, and a file-backed
1019
+ // store deserializes a fresh object on every load, so it is stale here.
1020
+ const updated = store.get(resolvedId) ?? task;
1021
+ const agentId = task.metadata.agentId;
1022
+ // Consume only what is actually handed over: the agent has reported back
1023
+ // (it leaves the map when it does) and the task carries its outcome. Short
1024
+ // of both — still running, or an update that never landed — the model is
1025
+ // getting a status, and the notification pi-subagents is holding is the
1026
+ // only thing that will announce the result.
1027
+ if (!agentTaskMap.has(agentId) && updated.status !== "in_progress")
1028
+ consumeSubagentResult(agentId);
1029
+ const output = updated.metadata?.result
1030
+ ?? (updated.metadata?.lastError ? `Error: ${updated.metadata.lastError}` : undefined);
1031
+ return textResult(`Task #${resolvedId} [${updated.status}] — subagent ${agentId}${output ? `\n\n${output}` : ""}`);
1032
+ }
1033
+ throw new Error(`No background process for task ${task_id}`);
1034
+ }
1035
+ if (block && processOutput.status === "running") {
1036
+ const result = await tracker.waitForCompletion(task_id, timeout ?? 30000, signal ?? undefined);
1037
+ if (result) {
1038
+ return textResult(`Task #${task_id} (${result.status})${result.exitCode !== undefined ? ` exit code: ${result.exitCode}` : ""}\n\n${result.output}`);
1039
+ }
1040
+ }
1041
+ return textResult(`Task #${task_id} (${processOutput.status})${processOutput.exitCode !== undefined ? ` exit code: ${processOutput.exitCode}` : ""}\n\n${processOutput.output}`);
1042
+ },
1043
+ });
1044
+ // ──────────────────────────────────────────────────
1045
+ // Tool 6: TaskStop
1046
+ // ──────────────────────────────────────────────────
1047
+ pi.registerTool({
1048
+ name: "TaskStop",
1049
+ label: "TaskStop",
1050
+ description: `
1051
+ - Stops a running background task by its ID
1052
+ - Takes a task_id parameter identifying the task to stop
1053
+ - Returns a success or failure status
1054
+ - Use this tool when you need to terminate a long-running task`,
1055
+ parameters: Type.Object({
1056
+ task_id: Type.Optional(Type.String({ description: "The ID of the background task to stop" })),
1057
+ shell_id: Type.Optional(Type.String({ description: "Deprecated: use task_id instead" })),
1058
+ }),
1059
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
1060
+ const taskId = params.task_id ?? params.shell_id;
1061
+ if (!taskId)
1062
+ throw new Error("task_id is required");
1063
+ const stopped = await tracker.stop(taskId);
1064
+ if (!stopped) {
1065
+ // No shell process — check if this is a subagent task
1066
+ // Support both task IDs and agent IDs
1067
+ let resolvedId = taskId;
1068
+ if (!store.get(resolvedId)) {
1069
+ for (const [agentId, tId] of agentTaskMap) {
1070
+ if (agentId === taskId || agentId.startsWith(taskId)) {
1071
+ resolvedId = tId;
1072
+ break;
1073
+ }
1074
+ }
1075
+ }
1076
+ const task = store.get(resolvedId);
1077
+ if (task?.metadata?.agentId && task.status === "in_progress") {
1078
+ // Stop first so the message can reflect the real outcome. The task is marked
1079
+ // completed either way (best-effort stop): a confirmed stop settles it, and an
1080
+ // unconfirmed one still reconciles through the subagents:failed listener if the
1081
+ // agent reports later — agentTaskMap keeps the mapping until then.
1082
+ const confirmed = await stopSubagent(task.metadata.agentId);
1083
+ // A lifecycle listener may have settled the task during the await; keep its outcome.
1084
+ if (store.get(resolvedId)?.status === "in_progress") {
1085
+ store.update(resolvedId, { status: "completed" });
1086
+ autoClear.trackCompletion(resolvedId, cadence.currentTurn);
1087
+ }
1088
+ widget.setActiveTask(resolvedId, false);
1089
+ widget.update();
1090
+ return textResult(confirmed
1091
+ ? `Task #${resolvedId} stopped`
1092
+ : `Task #${resolvedId} stop requested — not confirmed; it will reconcile when the agent reports.`);
1093
+ }
1094
+ throw new Error(`No running background process for task ${taskId}`);
1095
+ }
1096
+ store.update(taskId, { status: "completed" });
1097
+ autoClear.trackCompletion(taskId, cadence.currentTurn);
1098
+ widget.setActiveTask(taskId, false);
1099
+ widget.update();
1100
+ return textResult(`Task #${taskId} stopped successfully`);
1101
+ },
1102
+ });
1103
+ // ──────────────────────────────────────────────────
1104
+ // Tool 7: TaskExecute
1105
+ // ──────────────────────────────────────────────────
1106
+ pi.registerTool({
1107
+ name: "TaskExecute",
1108
+ label: "TaskExecute",
1109
+ description: `Execute one or more tasks as subagents.
1110
+
1111
+ ## When to Use This Tool
1112
+
1113
+ - To start execution of tasks that have \`agentType\` set (created via TaskCreate with agentType parameter)
1114
+ - Tasks must be \`pending\` with all blockedBy dependencies \`completed\`
1115
+ - Each task runs as an independent background subagent
1116
+
1117
+ ## Parameters
1118
+
1119
+ - **task_ids**: Array of task IDs to execute
1120
+ - **additional_context**: Extra context appended to each agent's prompt
1121
+ - **model**: Model override for agents (e.g., "sonnet", "haiku")
1122
+ - **max_turns**: Maximum turns per agent`,
1123
+ promptGuidelines: [
1124
+ "Never use the Agent tool for tasks launched via TaskExecute — agents are already running.",
1125
+ ],
1126
+ parameters: Type.Object({
1127
+ task_ids: Type.Array(Type.String(), { description: "Task IDs to execute as subagents" }),
1128
+ additional_context: Type.Optional(Type.String({ description: "Extra context for agent prompts" })),
1129
+ model: Type.Optional(Type.String({ description: "Model override for agents" })),
1130
+ max_turns: Type.Optional(Type.Number({ description: "Max turns per agent", minimum: 1 })),
1131
+ }),
1132
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
1133
+ if (!subagentsAvailable) {
1134
+ return textResult("Subagent execution is currently unavailable (@tintinweb/pi-subagents not loaded " +
1135
+ "or version mismatch). You can run these as plain Agent-tool spawns, but pi-tasks " +
1136
+ "won't track them — status stays pending, cascade won't fire, TaskOutput stays empty.");
1137
+ }
1138
+ const results = [];
1139
+ const launched = [];
1140
+ for (const taskId of params.task_ids) {
1141
+ const task = store.get(taskId);
1142
+ if (!task) {
1143
+ results.push(`#${taskId}: not found`);
1144
+ continue;
1145
+ }
1146
+ if (task.status !== "pending") {
1147
+ results.push(`#${taskId}: not pending (status: ${task.status})`);
1148
+ continue;
1149
+ }
1150
+ if (!task.metadata?.agentType) {
1151
+ results.push(`#${taskId}: no agentType set — create with agentType parameter or update metadata`);
1152
+ continue;
1153
+ }
1154
+ // Check all blockers are completed
1155
+ const openBlockers = task.blockedBy.filter(bid => {
1156
+ const blocker = store.get(bid);
1157
+ return !blocker || blocker.status !== "completed";
1158
+ });
1159
+ if (openBlockers.length > 0) {
1160
+ results.push(`#${taskId}: blocked by ${openBlockers.map(id => "#" + id).join(", ")}`);
1161
+ continue;
1162
+ }
1163
+ // Mark in_progress and spawn agent via RPC
1164
+ store.update(taskId, { status: "in_progress" });
1165
+ const spawnStore = store;
1166
+ const prompt = buildTaskPrompt(task, params.additional_context);
1167
+ try {
1168
+ const agentId = await spawnSubagent(task.metadata.agentType, prompt, {
1169
+ description: task.subject,
1170
+ isBackground: true,
1171
+ maxTurns: params.max_turns,
1172
+ ...(params.model ? { model: params.model } : {}),
1173
+ }, lateId => adoptLateAgent(spawnStore, taskId, lateId));
1174
+ bindAgent(taskId, agentId);
1175
+ launched.push(`#${taskId} → agent ${agentId}`);
1176
+ }
1177
+ catch (err) {
1178
+ debug(`spawn:error task=#${taskId}`, err);
1179
+ if (err?.timeout) {
1180
+ // A timeout does not prove the agent never started. Reverting to pending
1181
+ // would invite a duplicate spawn, so leave it in_progress; a late reply
1182
+ // links the agent via adoptLateAgent.
1183
+ results.push(`#${taskId}: spawn timed out — the agent is linked if its reply arrives late; if none appears, reset with TaskUpdate status=pending before retrying`);
1184
+ }
1185
+ else {
1186
+ store.update(taskId, { status: "pending" });
1187
+ results.push(`#${taskId}: spawn failed — ${err.message}`);
1188
+ }
1189
+ }
1190
+ }
1191
+ // Save cascade config for the completion listener
1192
+ cascadeConfig = {
1193
+ additionalContext: params.additional_context,
1194
+ model: params.model,
1195
+ maxTurns: params.max_turns,
1196
+ };
1197
+ widget.update();
1198
+ const lines = [];
1199
+ if (launched.length > 0) {
1200
+ lines.push(`Launched ${launched.length} agent(s):\n${launched.join("\n")}\n` +
1201
+ `Use TaskOutput to check progress. Do not spawn additional agents for these tasks.`);
1202
+ }
1203
+ if (results.length > 0)
1204
+ lines.push(`Skipped:\n${results.join("\n")}`);
1205
+ if (lines.length === 0)
1206
+ lines.push("No tasks to execute.");
1207
+ return textResult(lines.join("\n\n"));
1208
+ },
1209
+ });
1210
+ // ──────────────────────────────────────────────────
1211
+ // /tasks command
1212
+ // ──────────────────────────────────────────────────
1213
+ pi.registerCommand("tasks", {
1214
+ description: "Manage tasks — view, create, clear completed",
1215
+ handler: async (_args, ctx) => {
1216
+ latestCtx = ctx;
1217
+ widget.setUICtx(ctx.ui);
1218
+ initializeStoreForContext(ctx);
1219
+ const ui = ctx.ui;
1220
+ const mainMenu = async () => {
1221
+ const tasks = store.list();
1222
+ const taskCount = tasks.length;
1223
+ const completedCount = tasks.filter(t => t.status === "completed").length;
1224
+ const choices = [
1225
+ `View all tasks (${taskCount})`,
1226
+ "Create task",
1227
+ ];
1228
+ if (completedCount > 0)
1229
+ choices.push(`Clear completed (${completedCount})`);
1230
+ if (taskCount > 0)
1231
+ choices.push(`Clear all (${taskCount})`);
1232
+ choices.push("Settings");
1233
+ const choice = await ui.select("Tasks", choices);
1234
+ if (!choice)
1235
+ return;
1236
+ if (choice.startsWith("View")) {
1237
+ await viewTasks();
1238
+ }
1239
+ else if (choice === "Create task") {
1240
+ await createTask();
1241
+ }
1242
+ else if (choice === "Settings") {
1243
+ await settingsMenu();
1244
+ }
1245
+ else if (choice.startsWith("Clear completed")) {
1246
+ store.clearCompleted();
1247
+ if (isSessionScope())
1248
+ deleteSessionFileIfEmpty();
1249
+ widget.update();
1250
+ await mainMenu();
1251
+ }
1252
+ else if (choice.startsWith("Clear all")) {
1253
+ store.clearAll();
1254
+ if (isSessionScope())
1255
+ deleteSessionFileIfEmpty();
1256
+ widget.update();
1257
+ await mainMenu();
1258
+ }
1259
+ };
1260
+ const viewTasks = async () => {
1261
+ const tasks = store.list();
1262
+ if (tasks.length === 0) {
1263
+ await ui.select("No tasks", ["← Back"]);
1264
+ return mainMenu();
1265
+ }
1266
+ const glyphs = resolveTaskGlyphs(cfg.glyphs);
1267
+ const statusGlyph = (status) => {
1268
+ switch (status) {
1269
+ case "completed": return glyphs.completed;
1270
+ case "in_progress": return glyphs.inProgress;
1271
+ default: return glyphs.pending;
1272
+ }
1273
+ };
1274
+ const choices = tasks.map(t => `${statusGlyph(t.status)} #${t.id} [${t.status}] ${t.subject}`);
1275
+ choices.push("← Back");
1276
+ const selected = await ui.select("Tasks", choices);
1277
+ if (!selected || selected === "← Back")
1278
+ return mainMenu();
1279
+ // Matched by row position rather than parsed out of the label: both the glyph
1280
+ // and the subject are free text, and either can contain something like "#42".
1281
+ const picked = tasks[choices.indexOf(selected)];
1282
+ if (picked)
1283
+ await viewTaskDetail(picked.id);
1284
+ else
1285
+ return viewTasks();
1286
+ };
1287
+ const viewTaskDetail = async (taskId) => {
1288
+ const task = store.get(taskId);
1289
+ if (!task)
1290
+ return viewTasks();
1291
+ const actions = [];
1292
+ if (task.status === "pending") {
1293
+ actions.push("▸ Start (in_progress)");
1294
+ }
1295
+ if (task.status === "in_progress") {
1296
+ actions.push("✓ Complete");
1297
+ }
1298
+ actions.push("✗ Delete");
1299
+ actions.push("← Back");
1300
+ const title = `#${task.id} [${task.status}] ${task.subject}\n${task.description}`;
1301
+ const action = await ui.select(title, actions);
1302
+ if (action === "▸ Start (in_progress)") {
1303
+ store.update(taskId, { status: "in_progress" });
1304
+ widget.setActiveTask(taskId);
1305
+ widget.update();
1306
+ return viewTasks();
1307
+ }
1308
+ else if (action === "✓ Complete") {
1309
+ store.update(taskId, { status: "completed" });
1310
+ autoClear.trackCompletion(taskId, cadence.currentTurn);
1311
+ widget.setActiveTask(taskId, false);
1312
+ widget.update();
1313
+ return viewTasks();
1314
+ }
1315
+ else if (action === "✗ Delete") {
1316
+ store.update(taskId, { status: "deleted" });
1317
+ widget.setActiveTask(taskId, false);
1318
+ widget.update();
1319
+ return viewTasks();
1320
+ }
1321
+ return viewTasks();
1322
+ };
1323
+ const settingsMenu = () => openSettingsMenu(ui, cfg, mainMenu, AUTO_CLEAR_DELAY, ctx.cwd);
1324
+ const createTask = async () => {
1325
+ const subject = await ui.input("Task subject");
1326
+ if (!subject)
1327
+ return mainMenu();
1328
+ const description = await ui.input("Task description");
1329
+ if (!description)
1330
+ return mainMenu();
1331
+ store.create(subject, description);
1332
+ widget.update();
1333
+ return mainMenu();
1334
+ };
1335
+ await mainMenu();
1336
+ },
1337
+ });
1338
+ }