@herbertgao/pi-extensions 2026.10.18 → 2026.11.0

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