@herbertgao/pi-extensions 2026.11.2 → 2026.11.4

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 (235) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +13 -13
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +12 -0
  5. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +2 -2
  6. package/node_modules/@herbertgao/pi-cc-extensions/README.md +2 -2
  7. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +109 -16
  8. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/interaction.ts +33 -5
  9. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/ccstyle-tool.ts +72 -17
  10. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/diff/write-execution.ts +5 -1
  11. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/grouping.ts +10 -2
  12. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/tool-io.ts +16 -7
  13. package/node_modules/@herbertgao/pi-cc-extensions/package.json +7 -5
  14. package/node_modules/@herbertgao/pi-cc-extensions/themes/cc-dark-hc.json +92 -0
  15. package/node_modules/@herbertgao/pi-cc-extensions/themes/cc-light-hc.json +92 -0
  16. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +6 -0
  17. package/node_modules/@herbertgao/pi-subagents/README.md +12 -10
  18. package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +1 -1
  19. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  20. package/node_modules/@herbertgao/pi-subagents/src/agent-record-entry.ts +22 -6
  21. package/node_modules/@herbertgao/pi-subagents/src/index.ts +9 -4
  22. package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +167 -7
  23. package/node_modules/@herbertgao/pi-subagents/src/ui/viewer-keys.ts +8 -4
  24. package/node_modules/@narumitw/pi-btw/CHANGELOG.md +259 -0
  25. package/node_modules/@narumitw/pi-btw/package.json +6 -5
  26. package/node_modules/@narumitw/pi-caffeinate/CHANGELOG.md +70 -0
  27. package/node_modules/@narumitw/pi-caffeinate/package.json +5 -4
  28. package/node_modules/pi-commandcode-provider/CHANGELOG.md +48 -0
  29. package/node_modules/pi-commandcode-provider/CONTRIBUTING.md +64 -5
  30. package/node_modules/pi-commandcode-provider/README.md +44 -18
  31. package/node_modules/pi-commandcode-provider/RELEASE.md +25 -0
  32. package/node_modules/pi-commandcode-provider/index.ts +222 -42
  33. package/node_modules/pi-commandcode-provider/package.json +9 -8
  34. package/node_modules/pi-commandcode-provider/scripts/live-e2e-profile.mjs +6 -13
  35. package/node_modules/pi-commandcode-provider/scripts/typecheck-entrypoint.mjs +88 -0
  36. package/node_modules/pi-commandcode-provider/src/api-key.ts +67 -10
  37. package/node_modules/pi-commandcode-provider/src/auth-server.ts +33 -24
  38. package/node_modules/pi-commandcode-provider/src/commandcode-catalog-overrides.ts +1 -1
  39. package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +9 -2
  40. package/node_modules/pi-commandcode-provider/src/cost.ts +29 -43
  41. package/node_modules/pi-commandcode-provider/src/diagnostics.ts +215 -0
  42. package/node_modules/pi-commandcode-provider/src/oauth.ts +41 -7
  43. package/node_modules/pi-commandcode-provider/src/pricing.ts +5 -3
  44. package/node_modules/pi-commandcode-provider/src/quota-command.ts +1 -1
  45. package/node_modules/pi-commandcode-provider/src/routing.ts +166 -0
  46. package/node_modules/pi-commandcode-provider/src/runtime.ts +23 -10
  47. package/node_modules/pi-commandcode-provider/src/transport.ts +82 -85
  48. package/node_modules/pi-commandcode-provider/src/types.ts +20 -39
  49. package/node_modules/pi-commandcode-provider/src/usage.ts +1 -1
  50. package/node_modules/pi-lens/CHANGELOG-USER.md +31 -0
  51. package/node_modules/pi-lens/CHANGELOG.md +178 -0
  52. package/node_modules/pi-lens/README.md +2 -1
  53. package/node_modules/pi-lens/config/dependency-cruiser-eager-allowlist.json +1 -1
  54. package/node_modules/pi-lens/dist/{chunk-3O5EII3W.js → chunk-2VZ3VN3N.js} +2 -2
  55. package/node_modules/pi-lens/dist/{chunk-SDFKOLSF.js → chunk-3HTZDY3C.js} +8 -6
  56. package/node_modules/pi-lens/dist/{chunk-A5GRLYPZ.js → chunk-3NPWO5UO.js} +7 -13
  57. package/node_modules/pi-lens/dist/{chunk-AGGUWKRK.js → chunk-47UCC4MM.js} +1 -1
  58. package/node_modules/pi-lens/dist/chunk-4ENEJHF4.js +198 -0
  59. package/node_modules/pi-lens/dist/{chunk-WXUDRAG6.js → chunk-5GEYJJHG.js} +10 -12
  60. package/node_modules/pi-lens/dist/{chunk-HHR7WGCI.js → chunk-5YSEQHJN.js} +3 -3
  61. package/node_modules/pi-lens/dist/{chunk-L3CLUGDY.js → chunk-6GPB3JLL.js} +3 -3
  62. package/node_modules/pi-lens/dist/{chunk-5F3XF3SX.js → chunk-7R5GZIA6.js} +6 -6
  63. package/node_modules/pi-lens/dist/{chunk-CUDD35TW.js → chunk-7UTSNTWM.js} +4 -4
  64. package/node_modules/pi-lens/dist/{chunk-DYRZGUMA.js → chunk-7YTRG6YW.js} +2 -2
  65. package/node_modules/pi-lens/dist/{chunk-JZRP4DGP.js → chunk-AACN5GNE.js} +2 -2
  66. package/node_modules/pi-lens/dist/{chunk-7ANZ7XDD.js → chunk-ACRJ2GZ5.js} +2 -2
  67. package/node_modules/pi-lens/dist/{chunk-6FIRFP6A.js → chunk-C3YRO3EU.js} +10 -12
  68. package/node_modules/pi-lens/dist/{chunk-GMROJJRN.js → chunk-CB7PEVOJ.js} +9 -1
  69. package/node_modules/pi-lens/dist/{chunk-BBET6HD6.js → chunk-CDFJF5YD.js} +1 -1
  70. package/node_modules/pi-lens/dist/{chunk-NSPVR3FN.js → chunk-CJS6WE66.js} +17 -19
  71. package/node_modules/pi-lens/dist/{chunk-6YUNI7B5.js → chunk-CM6BDY4E.js} +14 -60
  72. package/node_modules/pi-lens/dist/{chunk-G5GV2Q7K.js → chunk-CZCAZVTD.js} +16 -2
  73. package/node_modules/pi-lens/dist/chunk-DGKFWQK4.js +23 -0
  74. package/node_modules/pi-lens/dist/{chunk-VOP4PJKA.js → chunk-E65WJVI5.js} +7 -9
  75. package/node_modules/pi-lens/dist/{chunk-TV6RXRYH.js → chunk-EKNYSXFB.js} +8 -10
  76. package/node_modules/pi-lens/dist/{chunk-4LL2VRNY.js → chunk-EY6LY2HO.js} +16 -18
  77. package/node_modules/pi-lens/dist/{chunk-MC6VB2E5.js → chunk-F6BEQWAK.js} +17 -5
  78. package/node_modules/pi-lens/dist/{chunk-R2QQC33W.js → chunk-FGNSESAC.js} +12 -14
  79. package/node_modules/pi-lens/dist/{chunk-OC7VWJBZ.js → chunk-FRUBVFXV.js} +35 -37
  80. package/node_modules/pi-lens/dist/{chunk-7CGIDRIK.js → chunk-G22UNQID.js} +14 -16
  81. package/node_modules/pi-lens/dist/{chunk-L4NEVZ4T.js → chunk-GQTQUNCG.js} +25 -27
  82. package/node_modules/pi-lens/dist/{chunk-ZKLTNLAW.js → chunk-H3BVMK47.js} +6 -6
  83. package/node_modules/pi-lens/dist/chunk-H6FLQ5NW.js +28 -0
  84. package/node_modules/pi-lens/dist/{chunk-2ZE3AUJQ.js → chunk-HEA3EM23.js} +13 -15
  85. package/node_modules/pi-lens/dist/{chunk-CZL44WFN.js → chunk-HSOBIN22.js} +2 -2
  86. package/node_modules/pi-lens/dist/{chunk-PKSUMEPT.js → chunk-HYSKJMZK.js} +3 -3
  87. package/node_modules/pi-lens/dist/{chunk-VN3L2JWZ.js → chunk-IICERRFF.js} +5 -5
  88. package/node_modules/pi-lens/dist/{chunk-O4N5BQ3T.js → chunk-IILEH3ZC.js} +8 -10
  89. package/node_modules/pi-lens/dist/{chunk-WC6WRNQT.js → chunk-J3Q2NYJR.js} +2 -2
  90. package/node_modules/pi-lens/dist/{chunk-SFLHSL5R.js → chunk-JUZ67QZQ.js} +18 -7
  91. package/node_modules/pi-lens/dist/chunk-KR5VGMVT.js +25 -0
  92. package/node_modules/pi-lens/dist/{chunk-UHHLR2VY.js → chunk-KV6GQOGN.js} +38 -41
  93. package/node_modules/pi-lens/dist/{chunk-HUAM7QG3.js → chunk-KXMJLOZF.js} +25 -23
  94. package/node_modules/pi-lens/dist/{chunk-BUZIQDFS.js → chunk-L4Y3ROKQ.js} +3 -3
  95. package/node_modules/pi-lens/dist/{chunk-JBP7KESM.js → chunk-L6WBJGQS.js} +1 -1
  96. package/node_modules/pi-lens/dist/{chunk-35WKJWO5.js → chunk-L7O774U7.js} +14 -14
  97. package/node_modules/pi-lens/dist/{chunk-BOPDQ7AZ.js → chunk-LAHHGNAY.js} +19 -21
  98. package/node_modules/pi-lens/dist/{chunk-RGGH6M34.js → chunk-LT62P654.js} +1 -1
  99. package/node_modules/pi-lens/dist/{chunk-5T5A6YAJ.js → chunk-LWOM6LVS.js} +33 -34
  100. package/node_modules/pi-lens/dist/{chunk-JYLOYTZD.js → chunk-MKPDIAZH.js} +5 -1
  101. package/node_modules/pi-lens/dist/{chunk-CM73PPGD.js → chunk-MN635QYA.js} +3 -4
  102. package/node_modules/pi-lens/dist/{chunk-BQG2QFVO.js → chunk-MQ4PPCJB.js} +21 -29
  103. package/node_modules/pi-lens/dist/{chunk-HXFUTMX2.js → chunk-MRLH4MYU.js} +2 -2
  104. package/node_modules/pi-lens/dist/{chunk-XOMGO63G.js → chunk-N56BNAA6.js} +19 -21
  105. package/node_modules/pi-lens/dist/{chunk-7MAD5ZAY.js → chunk-N5CEGQPG.js} +14 -16
  106. package/node_modules/pi-lens/dist/{chunk-ZFORSIED.js → chunk-NCLO6E6N.js} +13 -33
  107. package/node_modules/pi-lens/dist/{chunk-SQC7K3SP.js → chunk-NL5LSKVD.js} +2 -2
  108. package/node_modules/pi-lens/dist/{chunk-I22THIHI.js → chunk-NMUSOZ2D.js} +10 -12
  109. package/node_modules/pi-lens/dist/{chunk-4NBWFYWW.js → chunk-NOWH2VA2.js} +8 -33
  110. package/node_modules/pi-lens/dist/{chunk-NM2NWH55.js → chunk-NUSXS6YB.js} +6 -5
  111. package/node_modules/pi-lens/dist/{chunk-OZWXLJMX.js → chunk-OSEKJEUU.js} +2 -2
  112. package/node_modules/pi-lens/dist/{chunk-2BKUFQKR.js → chunk-OUYAUXAT.js} +405 -181
  113. package/node_modules/pi-lens/dist/{chunk-JPRDTY5S.js → chunk-PBZNYHMM.js} +8 -10
  114. package/node_modules/pi-lens/dist/{chunk-JE6HKLC7.js → chunk-PIIUNJIT.js} +2 -4
  115. package/node_modules/pi-lens/dist/{chunk-ZZDIOAAJ.js → chunk-PRHYIA6X.js} +6 -6
  116. package/node_modules/pi-lens/dist/{chunk-4W52ZKZX.js → chunk-PXQ45SGD.js} +2 -2
  117. package/node_modules/pi-lens/dist/chunk-Q6JQKWPK.js +25 -0
  118. package/node_modules/pi-lens/dist/{chunk-PIQQM32Y.js → chunk-QB7T2PHK.js} +2 -2
  119. package/node_modules/pi-lens/dist/{chunk-HKIL6DCL.js → chunk-QGITU23N.js} +1 -1
  120. package/node_modules/pi-lens/dist/chunk-QJJKOHLH.js +57 -0
  121. package/node_modules/pi-lens/dist/{chunk-6LJOJ6EO.js → chunk-QP33NKYC.js} +14 -16
  122. package/node_modules/pi-lens/dist/{chunk-DIWK3LBC.js → chunk-QVBOXT3L.js} +8 -10
  123. package/node_modules/pi-lens/dist/{chunk-IYVYZQRL.js → chunk-RNJFRXEN.js} +5 -7
  124. package/node_modules/pi-lens/dist/{chunk-G6JKM4O7.js → chunk-RNXOWDM6.js} +10 -10
  125. package/node_modules/pi-lens/dist/{chunk-5RNB4HVK.js → chunk-RTFMDIKV.js} +1 -1
  126. package/node_modules/pi-lens/dist/{chunk-XWIME22V.js → chunk-SIQHOB6P.js} +11 -13
  127. package/node_modules/pi-lens/dist/{chunk-T2S3FNNJ.js → chunk-SLSMJPEF.js} +41 -42
  128. package/node_modules/pi-lens/dist/chunk-T5QSLSMM.js +50 -0
  129. package/node_modules/pi-lens/dist/chunk-TGQDAG4B.js +88 -0
  130. package/node_modules/pi-lens/dist/{chunk-6GMGEKQN.js → chunk-THYHUIDR.js} +39 -12
  131. package/node_modules/pi-lens/dist/{chunk-WMDUT4KH.js → chunk-TMNUTMT5.js} +72 -89
  132. package/node_modules/pi-lens/dist/{chunk-7TNILKGY.js → chunk-TOE2RRCS.js} +1 -1
  133. package/node_modules/pi-lens/dist/chunk-TYHPVE5H.js +25 -0
  134. package/node_modules/pi-lens/dist/chunk-UAKO2M6B.js +73 -0
  135. package/node_modules/pi-lens/dist/chunk-UC5AXW5Z.js +20 -0
  136. package/node_modules/pi-lens/dist/chunk-UTJP6WOS.js +28 -0
  137. package/node_modules/pi-lens/dist/{chunk-FRLAUP2B.js → chunk-UXTQ3QPD.js} +4 -4
  138. package/node_modules/pi-lens/dist/{chunk-4QG55RRC.js → chunk-V2WDBOLZ.js} +10 -12
  139. package/node_modules/pi-lens/dist/{chunk-FHEV6T4L.js → chunk-V67D6TMU.js} +8 -10
  140. package/node_modules/pi-lens/dist/{chunk-VLQ7UKZH.js → chunk-VCRVNLE7.js} +135 -2
  141. package/node_modules/pi-lens/dist/{chunk-KZ4ALBCH.js → chunk-VO4JFPTV.js} +2 -2
  142. package/node_modules/pi-lens/dist/{chunk-GIRBSBGL.js → chunk-VWLSU3XV.js} +3 -3
  143. package/node_modules/pi-lens/dist/{chunk-2453RRJ2.js → chunk-W5E72HJA.js} +59 -22
  144. package/node_modules/pi-lens/dist/{chunk-VPLBLWFO.js → chunk-W7TY6HYX.js} +1 -1
  145. package/node_modules/pi-lens/dist/{chunk-SP4TFY5F.js → chunk-WSSLVMDA.js} +11 -13
  146. package/node_modules/pi-lens/dist/{chunk-PPKECBPP.js → chunk-WTB4GKMH.js} +10 -1
  147. package/node_modules/pi-lens/dist/{chunk-X35S7HSB.js → chunk-X5BJ3G2P.js} +41 -30
  148. package/node_modules/pi-lens/dist/{chunk-X66YJ2SS.js → chunk-XKFO2SZV.js} +33 -34
  149. package/node_modules/pi-lens/dist/{chunk-OWTG6UMO.js → chunk-XLAI7UYY.js} +75 -22
  150. package/node_modules/pi-lens/dist/{chunk-4B2YFN4U.js → chunk-XO756WE5.js} +45 -33
  151. package/node_modules/pi-lens/dist/{chunk-VOXTCULR.js → chunk-XVB3Q2PG.js} +2 -4
  152. package/node_modules/pi-lens/dist/{chunk-XYLC35E4.js → chunk-YOXCCJDF.js} +517 -308
  153. package/node_modules/pi-lens/dist/{chunk-O2ARHQKF.js → chunk-ZCQBNPRH.js} +2 -2
  154. package/node_modules/pi-lens/dist/chunk-ZD4KVFXI.js +234 -0
  155. package/node_modules/pi-lens/dist/{chunk-LSFXZLPW.js → chunk-ZDMFGACN.js} +184 -235
  156. package/node_modules/pi-lens/dist/{chunk-4BKU7PV3.js → chunk-ZMMHHXSW.js} +1 -1
  157. package/node_modules/pi-lens/dist/{chunk-OY7WZI7Q.js → chunk-ZPM7ZIFL.js} +6 -6
  158. package/node_modules/pi-lens/dist/{chunk-R4QWJQ2H.js → chunk-ZVCDHYWZ.js} +9 -11
  159. package/node_modules/pi-lens/dist/{chunk-RZG472YW.js → chunk-ZZN74OGD.js} +83 -46
  160. package/node_modules/pi-lens/dist/{chunk-BHWW6FAX.js → chunk-ZZSJAR76.js} +37 -19
  161. package/node_modules/pi-lens/dist/index.js +4910 -4218
  162. package/node_modules/pi-lens/dist/mcp/analyze-cli.js +12 -17
  163. package/node_modules/pi-lens/dist/mcp/cli.js +41 -42
  164. package/node_modules/pi-lens/dist/mcp/server.js +1451 -648
  165. package/node_modules/pi-lens/dist/mcp/worker.js +59 -60
  166. package/node_modules/pi-lens/dist/probes/installer.js +17 -19
  167. package/node_modules/pi-lens/docs/agent-tools.md +40 -8
  168. package/node_modules/pi-lens/docs/analysisall.md +1 -1
  169. package/node_modules/pi-lens/docs/ci-bot-pr-checks.md +7 -5
  170. package/node_modules/pi-lens/docs/configuration.md +51 -9
  171. package/node_modules/pi-lens/docs/defect-shapes.md +52 -3
  172. package/node_modules/pi-lens/docs/environment-variables.md +18 -1
  173. package/node_modules/pi-lens/docs/features.md +12 -5
  174. package/node_modules/pi-lens/docs/globalconfig.md +11 -3
  175. package/node_modules/pi-lens/docs/invariants/lsp-trust-exec.md +9 -2
  176. package/node_modules/pi-lens/docs/invariants/session-telemetry.md +2 -2
  177. package/node_modules/pi-lens/docs/language-coverage.md +1 -0
  178. package/node_modules/pi-lens/docs/lsp-capability-matrix.md +57 -35
  179. package/node_modules/pi-lens/docs/lsp-idle-eviction.md +4 -1
  180. package/node_modules/pi-lens/docs/merge-queue-rollout.md +10 -8
  181. package/node_modules/pi-lens/docs/module-report-read-symbol.md +34 -23
  182. package/node_modules/pi-lens/docs/pi-lens-fixer.md +11 -1
  183. package/node_modules/pi-lens/docs/pi-lens-investigator.md +3 -0
  184. package/node_modules/pi-lens/docs/pi-lens-merge-policy.md +15 -7
  185. package/node_modules/pi-lens/docs/pi-lens-reviewer.md +1 -1
  186. package/node_modules/pi-lens/docs/pi-lens-subagent.md +13 -0
  187. package/node_modules/pi-lens/docs/public-api-stability.md +39 -5
  188. package/node_modules/pi-lens/docs/release-qa-baseline.md +7 -4
  189. package/node_modules/pi-lens/docs/schema/pi-lens-config-v1.json +11 -2
  190. package/node_modules/pi-lens/docs/servercapabilities.md +3 -1
  191. package/node_modules/pi-lens/docs/settings.md +2 -2
  192. package/node_modules/pi-lens/docs/word-index.md +3 -2
  193. package/node_modules/pi-lens/package.json +8 -3
  194. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-sql-in-code-execute-js.yml +1 -2
  195. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-sql-in-code-execute.yml +1 -2
  196. package/node_modules/pi-lens/scripts/download-grammars.js +3 -2
  197. package/node_modules/pi-lens/skills/pi-lens-lsp-navigation/SKILL.md +5 -1
  198. package/node_modules/pi-provider-qoder/dist/index.js +473 -62
  199. package/node_modules/pi-provider-qoder/package.json +1 -1
  200. package/node_modules/pi-web-access/CHANGELOG.md +22 -0
  201. package/node_modules/pi-web-access/README.md +31 -12
  202. package/node_modules/pi-web-access/curator-page.ts +5 -1
  203. package/node_modules/pi-web-access/curator-server.ts +2 -0
  204. package/node_modules/pi-web-access/dist/index.js +673 -308
  205. package/node_modules/pi-web-access/dist/mcp-cli.js +666 -309
  206. package/node_modules/pi-web-access/gemini-search.ts +12 -4
  207. package/node_modules/pi-web-access/github-api.ts +1 -1
  208. package/node_modules/pi-web-access/github-extract.ts +3 -2
  209. package/node_modules/pi-web-access/index.ts +7 -3
  210. package/node_modules/pi-web-access/mcp-tool-definitions.ts +1 -1
  211. package/node_modules/pi-web-access/outcrawl.ts +204 -0
  212. package/node_modules/pi-web-access/package.json +2 -2
  213. package/node_modules/pi-web-access/sofya.ts +201 -0
  214. package/node_modules/pi-web-access/utils.ts +16 -6
  215. package/node_modules/pi-web-access/web-tool-core.ts +4 -0
  216. package/package.json +16 -14
  217. package/node_modules/pi-commandcode-provider/src/converters.ts +0 -477
  218. package/node_modules/pi-commandcode-provider/src/core.ts +0 -836
  219. package/node_modules/pi-commandcode-provider/src/json-schema.ts +0 -417
  220. package/node_modules/pi-commandcode-provider/src/transcript.ts +0 -56
  221. package/node_modules/pi-lens/dist/chunk-2TS4GLOJ.js +0 -31
  222. package/node_modules/pi-lens/dist/chunk-3JAHQBSY.js +0 -27
  223. package/node_modules/pi-lens/dist/chunk-447YZL4S.js +0 -25
  224. package/node_modules/pi-lens/dist/chunk-565VRUP4.js +0 -136
  225. package/node_modules/pi-lens/dist/chunk-57X2CDRX.js +0 -49
  226. package/node_modules/pi-lens/dist/chunk-GGYOZWHW.js +0 -27
  227. package/node_modules/pi-lens/dist/chunk-IE5D3RA5.js +0 -58
  228. package/node_modules/pi-lens/dist/chunk-LPYTPNOJ.js +0 -22
  229. package/node_modules/pi-lens/dist/chunk-OFNMHPBT.js +0 -89
  230. package/node_modules/pi-lens/dist/chunk-U3AS2FR6.js +0 -106
  231. package/node_modules/pi-lens/dist/chunk-W3BGKBBK.js +0 -27
  232. package/node_modules/pi-lens/dist/chunk-WQV6BI4Q.js +0 -48
  233. package/node_modules/pi-lens/dist/chunk-YHGYAEFH.js +0 -443
  234. package/node_modules/pi-lens/dist/chunk-ZONZ6YY3.js +0 -74
  235. package/node_modules/pi-lens/dist/chunk-ZSM35JF4.js +0 -30
@@ -1,836 +0,0 @@
1
- /**
2
- * Testable Command Code provider core.
3
- *
4
- * The runtime imports live in index.ts; this module takes injected stream/cost
5
- * dependencies so tests can exercise the real serialization and stream parser.
6
- */
7
-
8
- import { randomUUID } from "node:crypto"
9
-
10
- import { COMMAND_CODE_CLI_VERSION } from "./commandcode-catalog.ts"
11
- import { commandCodeErrorMessage, redactCommandCodeErrorText } from "./overflow.ts"
12
- import { modelSupportsImageInput } from "./models.ts"
13
- import {
14
- getApiKey,
15
- getEnvironmentInfo,
16
- isRecord,
17
- assertTextOnlyMessages,
18
- mapFinishReason,
19
- messagesToCC,
20
- numberValue,
21
- parseStreamEventLine,
22
- pickCommandCodeApiKey,
23
- recordOrEmpty,
24
- stringValue,
25
- toolsToJson,
26
- systemPromptToText,
27
- } from "./converters.ts"
28
- import type {
29
- AssistantMessageEventStreamLike,
30
- AssistantMessageLike,
31
- ContextLike,
32
- CoreDependencies,
33
- ErrorReason,
34
- ModelLike,
35
- StopReason,
36
- StreamOptions,
37
- TerminalReason,
38
- TextContent,
39
- ToolCallContent,
40
- Usage,
41
- } from "./types.ts"
42
-
43
- export * from "./converters.ts"
44
- export * from "./overflow.ts"
45
- export * from "./types.ts"
46
-
47
- export const DEFAULT_API_BASE = "https://api.commandcode.ai"
48
- export { COMMAND_CODE_CLI_VERSION }
49
-
50
- const DEFAULT_GENERATE_MAX_TOKENS = 64_000
51
- const DEFAULT_MAX_RETRIES = 0
52
- const DEFAULT_MAX_RETRY_DELAY_MS = 60_000
53
- const BASE_RETRY_DELAY_MS = 500
54
-
55
- function isRetryableStatus(status: number): boolean {
56
- return status === 429 || (status >= 500 && status < 600)
57
- }
58
-
59
- function parseRetryAfterSeconds(value: string | null): number | undefined {
60
- if (!value) return undefined
61
- const seconds = Number(value)
62
- if (Number.isFinite(seconds) && seconds >= 0) return seconds
63
- const date = Date.parse(value)
64
- if (!Number.isNaN(date)) return Math.max(0, (date - Date.now()) / 1000)
65
- return undefined
66
- }
67
-
68
- function effectiveMaxRetryDelayMs(value: number | undefined): number {
69
- if (value === undefined) return DEFAULT_MAX_RETRY_DELAY_MS
70
- if (value === 0) return Number.POSITIVE_INFINITY
71
- return value
72
- }
73
-
74
- function retryDelayMs(
75
- attempt: number,
76
- retryAfterHeader: string | null,
77
- maxDelayMs: number,
78
- ): number {
79
- const retryAfterMs = parseRetryAfterSeconds(retryAfterHeader)
80
- if (retryAfterMs !== undefined) {
81
- if (retryAfterMs * 1000 > maxDelayMs) return -1
82
- return retryAfterMs * 1000
83
- }
84
- const exponential = BASE_RETRY_DELAY_MS * 2 ** attempt
85
- const jitter = exponential * 0.2 * Math.random()
86
- return Math.min(exponential + jitter, maxDelayMs)
87
- }
88
-
89
- function defaultUsage(): Usage {
90
- return {
91
- input: 0,
92
- output: 0,
93
- cacheRead: 0,
94
- cacheWrite: 0,
95
- totalTokens: 0,
96
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
97
- }
98
- }
99
-
100
- function commandCodeUsage(event: Record<string, unknown>): Record<string, unknown> | undefined {
101
- return isRecord(event.totalUsage) ? event.totalUsage : undefined
102
- }
103
-
104
- function commandCodeInputTokenDetails(
105
- usage: Record<string, unknown>,
106
- ): Record<string, unknown> | undefined {
107
- return isRecord(usage.inputTokenDetails) ? usage.inputTokenDetails : undefined
108
- }
109
-
110
- function headersToRecord(headers: Headers): Record<string, string> {
111
- const out: Record<string, string> = {}
112
- headers.forEach((value, key) => {
113
- out[key] = value
114
- })
115
- return out
116
- }
117
-
118
- function abortError(message = "The operation was aborted"): DOMException {
119
- return new DOMException(message, "AbortError")
120
- }
121
-
122
- function timeoutError(timeoutMs: number | undefined): Error {
123
- return new Error(
124
- timeoutMs === undefined
125
- ? "Command Code API request timed out"
126
- : `Command Code API request timed out after ${timeoutMs}ms`,
127
- )
128
- }
129
-
130
- function successStopReason(reason: TerminalReason): StopReason {
131
- if (reason === "length" || reason === "toolUse") return reason
132
- return "stop"
133
- }
134
-
135
- function generateMaxTokens(model: ModelLike, options?: StreamOptions): number {
136
- return Math.min(
137
- options?.maxTokens ?? model.maxTokens,
138
- model.maxTokens,
139
- DEFAULT_GENERATE_MAX_TOKENS,
140
- )
141
- }
142
-
143
- function mappedReasoningEffort(model: ModelLike, options?: StreamOptions): string | undefined {
144
- const level = options?.reasoning
145
- if (!level || level === "off" || !model.reasoning) return undefined
146
-
147
- const effortMap = model.thinking?.effortMap ?? model.thinkingLevelMap
148
- const mapped = effortMap?.[level]
149
- return typeof mapped === "string" && mapped !== "off" ? mapped : undefined
150
- }
151
-
152
- function isUuid(value: string): boolean {
153
- return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)
154
- }
155
-
156
- export function projectSlugFromPath(pathName: string): string {
157
- const slug = pathName
158
- .toLowerCase()
159
- .replace(/^[a-z]:/i, "")
160
- .replace(/[^a-z0-9]+/g, "-")
161
- .replace(/^-+|-+$/g, "")
162
- return slug || "project"
163
- }
164
-
165
- export function createStreamCommandCode(deps: CoreDependencies) {
166
- const apiBase = deps.apiBase ?? DEFAULT_API_BASE
167
- const fetchImpl = deps.fetchImpl ?? fetch
168
- const cwd = deps.cwd ?? (() => process.cwd())
169
- const now = deps.now ?? (() => Date.now())
170
- const uuid = deps.uuid ?? (() => randomUUID())
171
- const delay =
172
- deps.delay ??
173
- ((ms: number, signal: AbortSignal) => {
174
- if (signal.aborted) return Promise.reject(abortError())
175
- return new Promise<void>((resolve, reject) => {
176
- const id = setTimeout(() => {
177
- signal.removeEventListener("abort", onAbort)
178
- resolve()
179
- }, ms)
180
- const onAbort = () => {
181
- clearTimeout(id)
182
- reject(abortError())
183
- }
184
- signal.addEventListener("abort", onAbort, { once: true })
185
- })
186
- })
187
-
188
- function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
189
- if (signal.aborted) return Promise.reject(abortError())
190
-
191
- return new Promise<T>((resolve, reject) => {
192
- const onAbort = () => reject(abortError())
193
- signal.addEventListener("abort", onAbort, { once: true })
194
- promise.then(
195
- (value) => {
196
- signal.removeEventListener("abort", onAbort)
197
- resolve(value)
198
- },
199
- (error: unknown) => {
200
- signal.removeEventListener("abort", onAbort)
201
- reject(error)
202
- },
203
- )
204
- })
205
- }
206
-
207
- function raceAbortWithTimeout<T>(
208
- promise: Promise<T>,
209
- controller: AbortController,
210
- timeoutMs: number | undefined,
211
- ): Promise<T> {
212
- if (timeoutMs === undefined) return raceAbort(promise, controller.signal)
213
-
214
- return new Promise<T>((resolve, reject) => {
215
- const timer = setTimeout(() => {
216
- controller.abort()
217
- reject(timeoutError(timeoutMs))
218
- }, timeoutMs)
219
- raceAbort(promise, controller.signal).then(
220
- (value) => {
221
- clearTimeout(timer)
222
- resolve(value)
223
- },
224
- (error: unknown) => {
225
- clearTimeout(timer)
226
- reject(error)
227
- },
228
- )
229
- })
230
- }
231
-
232
- return function streamCommandCode(
233
- model: ModelLike,
234
- context: ContextLike,
235
- options?: StreamOptions,
236
- ): AssistantMessageEventStreamLike {
237
- const stream = deps.createStream()
238
-
239
- async function run() {
240
- // Some hosts pass a literal env-var reference instead of resolving it.
241
- const apiKey = pickCommandCodeApiKey(
242
- options?.apiKey,
243
- getApiKey({
244
- env: deps.env,
245
- authPaths: deps.authPaths,
246
- homeDir: deps.homeDir,
247
- }),
248
- )
249
-
250
- if (!apiKey) {
251
- const msg: AssistantMessageLike = {
252
- role: "assistant",
253
- content: [],
254
- api: model.api,
255
- provider: model.provider,
256
- model: model.id,
257
- usage: defaultUsage(),
258
- stopReason: "error",
259
- errorMessage:
260
- "No Command Code API key. Run /login and select Command Code, set COMMAND_CODE_API_KEY (or legacy COMMANDCODE_API_KEY), or configure ~/.commandcode/auth.json, ~/.pi/agent/auth.json or ~/.omp/agent/auth.json",
261
- timestamp: now(),
262
- }
263
- stream.push({ type: "error", reason: "error", error: msg })
264
- stream.end()
265
- return
266
- }
267
-
268
- const output: AssistantMessageLike = {
269
- role: "assistant",
270
- content: [],
271
- api: model.api,
272
- provider: model.provider,
273
- model: model.id,
274
- usage: defaultUsage(),
275
- stopReason: "stop",
276
- timestamp: now(),
277
- }
278
-
279
- const controller = new AbortController()
280
- let reader: ReadableStreamDefaultReader<Uint8Array> | undefined
281
- let textBlock: TextContent | undefined
282
- let currentTextIdx = -1
283
- let thinkingIdx = -1
284
- const streamingToolCalls = new Map<
285
- string,
286
- { contentIndex: number; toolCall: ToolCallContent; partialArgs: string }
287
- >()
288
- let finished = false
289
-
290
- const abortUpstream = () => {
291
- if (!controller.signal.aborted) controller.abort()
292
- try {
293
- reader?.cancel().catch(() => undefined)
294
- } catch {
295
- // Reader cancellation is best-effort.
296
- }
297
- }
298
-
299
- if (options?.signal?.aborted) {
300
- abortUpstream()
301
- } else {
302
- options?.signal?.addEventListener("abort", abortUpstream, {
303
- once: true,
304
- })
305
- }
306
-
307
- const endTextBlock = () => {
308
- if (!textBlock) return
309
- stream.push({
310
- type: "text_end",
311
- contentIndex: currentTextIdx,
312
- content: textBlock.text,
313
- partial: output,
314
- })
315
- textBlock = undefined
316
- currentTextIdx = -1
317
- }
318
-
319
- const endThinking = () => {
320
- if (thinkingIdx < 0) return
321
- const tc = output.content[thinkingIdx]
322
- if (tc && tc.type === "thinking") {
323
- stream.push({
324
- type: "thinking_end",
325
- contentIndex: thinkingIdx,
326
- content: (tc as { thinking: string }).thinking,
327
- partial: output,
328
- })
329
- }
330
- thinkingIdx = -1
331
- }
332
-
333
- const handleEvent = (event: unknown) => {
334
- if (!isRecord(event)) return
335
-
336
- switch (event.type) {
337
- case "text-delta": {
338
- endThinking()
339
- if (!textBlock) {
340
- textBlock = { type: "text", text: "" }
341
- output.content.push(textBlock)
342
- currentTextIdx = output.content.length - 1
343
- stream.push({
344
- type: "text_start",
345
- contentIndex: currentTextIdx,
346
- partial: output,
347
- })
348
- }
349
- const delta = stringValue(event.text) ?? ""
350
- textBlock.text += delta
351
- stream.push({
352
- type: "text_delta",
353
- contentIndex: currentTextIdx,
354
- delta,
355
- partial: output,
356
- })
357
- break
358
- }
359
-
360
- case "reasoning-start": {
361
- endTextBlock()
362
- break
363
- }
364
-
365
- case "reasoning-delta": {
366
- endTextBlock()
367
- const delta = stringValue(event.text) ?? ""
368
- if (thinkingIdx < 0) {
369
- output.content.push({ type: "thinking", thinking: delta })
370
- thinkingIdx = output.content.length - 1
371
- stream.push({
372
- type: "thinking_start",
373
- contentIndex: thinkingIdx,
374
- partial: output,
375
- })
376
- } else {
377
- const tc = output.content[thinkingIdx]
378
- if (tc && tc.type === "thinking") {
379
- ;(tc as { thinking: string }).thinking += delta
380
- }
381
- }
382
- stream.push({
383
- type: "thinking_delta",
384
- contentIndex: thinkingIdx,
385
- delta,
386
- partial: output,
387
- })
388
- break
389
- }
390
-
391
- case "reasoning-end": {
392
- endThinking()
393
- break
394
- }
395
-
396
- case "tool-result": {
397
- break
398
- }
399
-
400
- case "tool-input-start": {
401
- endTextBlock()
402
- endThinking()
403
- const id = stringValue(event.id)
404
- if (!id || streamingToolCalls.has(id)) break
405
-
406
- const toolCall: ToolCallContent = {
407
- type: "toolCall",
408
- id,
409
- name: stringValue(event.toolName) ?? "",
410
- arguments: {},
411
- }
412
- output.content.push(toolCall)
413
- const contentIndex = output.content.length - 1
414
- streamingToolCalls.set(id, { contentIndex, toolCall, partialArgs: "" })
415
- stream.push({
416
- type: "toolcall_start",
417
- contentIndex,
418
- partial: output,
419
- })
420
- break
421
- }
422
-
423
- case "tool-input-delta": {
424
- const id = stringValue(event.id)
425
- const delta = stringValue(event.delta)
426
- if (!id || delta === undefined) break
427
- const active = streamingToolCalls.get(id)
428
- if (!active) break
429
-
430
- active.partialArgs += delta
431
- active.toolCall.arguments = recordOrEmpty(active.partialArgs)
432
- stream.push({
433
- type: "toolcall_delta",
434
- contentIndex: active.contentIndex,
435
- delta,
436
- partial: output,
437
- })
438
- break
439
- }
440
-
441
- case "tool-input-end": {
442
- break
443
- }
444
-
445
- case "tool-call": {
446
- endTextBlock()
447
- endThinking()
448
- const id = stringValue(event.toolCallId) ?? ""
449
- const active = streamingToolCalls.get(id)
450
- const toolCall: ToolCallContent = active?.toolCall ?? {
451
- type: "toolCall",
452
- id,
453
- name: stringValue(event.toolName) ?? "",
454
- arguments: {},
455
- }
456
- toolCall.name = stringValue(event.toolName) ?? toolCall.name
457
- toolCall.arguments = recordOrEmpty(event.input ?? event.args ?? event.arguments)
458
-
459
- let contentIndex: number
460
- if (active) {
461
- contentIndex = active.contentIndex
462
- streamingToolCalls.delete(id)
463
- } else {
464
- output.content.push(toolCall)
465
- contentIndex = output.content.length - 1
466
- stream.push({
467
- type: "toolcall_start",
468
- contentIndex,
469
- partial: output,
470
- })
471
- }
472
- stream.push({
473
- type: "toolcall_end",
474
- contentIndex,
475
- toolCall,
476
- partial: output,
477
- })
478
- break
479
- }
480
-
481
- case "finish": {
482
- const rawFinishReason = stringValue(event.rawFinishReason)
483
- if (
484
- rawFinishReason &&
485
- /^(?:network|connection|upstream)[-_\s]?error$/i.test(rawFinishReason)
486
- ) {
487
- throw new Error(
488
- `Provider finished with reason "${rawFinishReason}" — upstream connection failed mid-stream`,
489
- )
490
- }
491
- const usage = commandCodeUsage(event)
492
- if (usage) {
493
- const details = commandCodeInputTokenDetails(usage)
494
- const totalInput = numberValue(usage.inputTokens) ?? 0
495
- const input = numberValue(details?.noCacheTokens)
496
- const cacheRead = numberValue(details?.cacheReadTokens) ?? 0
497
- const cacheWrite = numberValue(details?.cacheWriteTokens) ?? 0
498
- output.usage.input = input ?? Math.max(0, totalInput - cacheRead - cacheWrite)
499
- output.usage.output = numberValue(usage.outputTokens) ?? 0
500
- output.usage.cacheRead = cacheRead
501
- output.usage.cacheWrite = cacheWrite
502
- output.usage.totalTokens =
503
- output.usage.input +
504
- output.usage.output +
505
- output.usage.cacheRead +
506
- output.usage.cacheWrite
507
- deps.calculateCost(model, output.usage, output.timestamp)
508
- }
509
- output.stopReason = mapFinishReason(event.finishReason)
510
- finished = true
511
- break
512
- }
513
-
514
- case "abort": {
515
- throw abortError("Request aborted")
516
- }
517
-
518
- case "error": {
519
- const message =
520
- commandCodeErrorMessage(event.error) ??
521
- commandCodeErrorMessage(event.message) ??
522
- "Stream error"
523
- output.stopReason = "error"
524
- output.errorMessage = message
525
- throw new Error(message)
526
- }
527
- }
528
- }
529
-
530
- try {
531
- stream.push({ type: "start", partial: output })
532
- if (controller.signal.aborted) throw abortError("Aborted")
533
-
534
- const workingDir = cwd()
535
- const threadId = options?.sessionId
536
- ? isUuid(options.sessionId)
537
- ? options.sessionId
538
- : undefined
539
- : uuid()
540
- const reasoningEffort = mappedReasoningEffort(model, options)
541
- const timeoutMs = options?.timeoutMs
542
-
543
- const allowImages = modelSupportsImageInput(model.id, model.input)
544
- if (!allowImages) assertTextOnlyMessages(context.messages)
545
-
546
- let body: unknown = {
547
- config: {
548
- workingDir,
549
- date: new Date(now()).toISOString().split("T")[0],
550
- environment: getEnvironmentInfo(),
551
- structure: [],
552
- isGitRepo: false,
553
- currentBranch: "",
554
- mainBranch: "",
555
- gitStatus: "",
556
- recentCommits: [],
557
- },
558
- memory: null,
559
- taste: null,
560
- skills: null,
561
- params: {
562
- model: model.id,
563
- messages: messagesToCC(context.messages, { allowImages }),
564
- tools: toolsToJson(context.tools, model.id),
565
- system: systemPromptToText(context.systemPrompt),
566
- max_tokens: generateMaxTokens(model, options),
567
- stream: true,
568
- ...(options?.temperature !== undefined ? { temperature: options.temperature } : {}),
569
- ...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}),
570
- },
571
- threadId,
572
- }
573
-
574
- const payloadController = new AbortController()
575
- const onPayloadAbort = () => payloadController.abort()
576
- controller.signal.addEventListener("abort", onPayloadAbort, { once: true })
577
- let nextBody: unknown
578
- try {
579
- nextBody = await raceAbortWithTimeout(
580
- Promise.resolve(options?.onPayload?.(body, model)),
581
- payloadController,
582
- timeoutMs,
583
- )
584
- } finally {
585
- controller.signal.removeEventListener("abort", onPayloadAbort)
586
- }
587
- if (nextBody !== undefined) body = nextBody
588
-
589
- const maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES
590
- const maxRetryDelayMs = effectiveMaxRetryDelayMs(options?.maxRetryDelayMs)
591
- const requestHeaders = {
592
- "Content-Type": "application/json",
593
- Authorization: `Bearer ${apiKey}`,
594
- "x-command-code-version": COMMAND_CODE_CLI_VERSION,
595
- "x-cli-environment": "production",
596
- "x-project-slug": projectSlugFromPath(workingDir),
597
- "x-taste-learning": "true",
598
- ...(options?.sessionId ? { "x-session-id": options.sessionId } : {}),
599
- "User-Agent": "cli",
600
- ...options?.headers,
601
- }
602
- const bodyStr = JSON.stringify(body)
603
-
604
- let response!: Response
605
- retryLoop: for (let attempt = 0; ; attempt++) {
606
- const attemptController = new AbortController()
607
- let attemptTimedOut = false
608
- let attemptTimeoutId: ReturnType<typeof setTimeout> | undefined
609
-
610
- const clearAttemptTimeout = () => {
611
- if (attemptTimeoutId !== undefined) {
612
- clearTimeout(attemptTimeoutId)
613
- attemptTimeoutId = undefined
614
- }
615
- }
616
-
617
- if (timeoutMs !== undefined) {
618
- attemptTimeoutId = setTimeout(() => {
619
- attemptTimedOut = true
620
- attemptController.abort()
621
- }, timeoutMs)
622
- }
623
- const onOuterAbort = () => attemptController.abort()
624
- controller.signal.addEventListener("abort", onOuterAbort, { once: true })
625
- const raceAttempt = <T>(promise: Promise<T>): Promise<T> =>
626
- raceAbort(promise, attemptController.signal).catch((error: unknown) => {
627
- if (attemptTimedOut) throw timeoutError(timeoutMs)
628
- throw error
629
- })
630
-
631
- try {
632
- try {
633
- response = await fetchImpl(`${apiBase}/alpha/generate`, {
634
- method: "POST",
635
- headers: requestHeaders,
636
- body: bodyStr,
637
- signal: attemptController.signal,
638
- })
639
- } catch (fetchError: unknown) {
640
- if (controller.signal.aborted) throw abortError("Aborted")
641
- if (attemptTimedOut) {
642
- if (attempt < maxRetries) continue retryLoop
643
- throw timeoutError(timeoutMs)
644
- }
645
- throw fetchError
646
- }
647
-
648
- // --- HTTP-level retry ---
649
- if (!response.ok && isRetryableStatus(response.status)) {
650
- const retryAfter = response.headers.get("retry-after")
651
- const waitMs = retryDelayMs(attempt, retryAfter, maxRetryDelayMs)
652
- if (waitMs < 0) {
653
- const requestedSeconds = parseRetryAfterSeconds(retryAfter) ?? 0
654
- const capLabel =
655
- maxRetryDelayMs === Number.POSITIVE_INFINITY ? "disabled" : `${maxRetryDelayMs}ms`
656
- throw new Error(`Retry-After delay ${requestedSeconds}s exceeds max ${capLabel}`)
657
- }
658
- if (attempt < maxRetries) {
659
- await response.text().catch(() => "")
660
- if (waitMs > 0) await delay(waitMs, controller.signal)
661
- continue retryLoop
662
- }
663
- }
664
-
665
- try {
666
- await raceAttempt(
667
- Promise.resolve(
668
- options?.onResponse?.(
669
- {
670
- status: response.status,
671
- headers: headersToRecord(response.headers),
672
- },
673
- model,
674
- ),
675
- ),
676
- )
677
- } catch (error: unknown) {
678
- if (attemptTimedOut && attempt < maxRetries) continue retryLoop
679
- throw error
680
- }
681
-
682
- if (!response.ok) {
683
- const errBody = await raceAttempt(response.text().catch(() => ""))
684
- let errorDetail: string | undefined
685
- try {
686
- const parsedBody: unknown = JSON.parse(errBody)
687
- errorDetail = commandCodeErrorMessage(parsedBody)
688
- } catch {
689
- // Preserve useful plain-text provider errors only after secret
690
- // redaction; upstream/proxy bodies may echo credentials.
691
- }
692
- const safeBody = redactCommandCodeErrorText(errBody).slice(0, 500)
693
- const detail = redactCommandCodeErrorText(
694
- errorDetail ?? (safeBody || "Provider returned an error"),
695
- )
696
- throw new Error(`Command Code API error ${response.status}: ${detail}`)
697
- }
698
-
699
- // --- Read response stream ---
700
- reader = response.body?.getReader()
701
- if (!reader) throw new Error("No response body")
702
-
703
- const decoder = new TextDecoder()
704
- let buffer = ""
705
-
706
- try {
707
- readLoop: for (;;) {
708
- if (controller.signal.aborted) throw abortError("Aborted")
709
- const { done, value } = await raceAbort(reader.read(), attemptController.signal)
710
- if (done) {
711
- clearAttemptTimeout()
712
- if (buffer.trim()) handleEvent(parseStreamEventLine(buffer))
713
- if (!finished) {
714
- throw new Error(
715
- "Stream ended unexpectedly before completion (no finish event) — response was truncated",
716
- )
717
- }
718
- break
719
- }
720
- if (timeoutMs !== undefined) {
721
- clearAttemptTimeout()
722
- attemptTimeoutId = setTimeout(() => {
723
- attemptTimedOut = true
724
- attemptController.abort()
725
- }, timeoutMs)
726
- }
727
- if (controller.signal.aborted) throw abortError("Aborted")
728
-
729
- buffer += decoder.decode(value, { stream: true })
730
- const lines = buffer.split("\n")
731
- buffer = lines.pop() ?? ""
732
-
733
- for (const line of lines) {
734
- if (controller.signal.aborted) throw abortError("Aborted")
735
- handleEvent(parseStreamEventLine(line))
736
- if (finished) break readLoop
737
- }
738
- }
739
- } catch (streamError: unknown) {
740
- // Stream-level error (e.g. API returned 200 OK but sent an error event)
741
- // or per-attempt timeout during stream reading.
742
- await reader.cancel().catch(() => {})
743
- try {
744
- reader.releaseLock()
745
- } catch {}
746
- reader = undefined
747
-
748
- if (
749
- controller.signal.aborted ||
750
- (streamError instanceof Error && streamError.name === "AbortError")
751
- ) {
752
- throw streamError
753
- }
754
-
755
- // Never retry after visible content was emitted (including timeout mid-stream).
756
- const canRetry = output.content.length === 0 && attempt < maxRetries
757
- if (canRetry) {
758
- output.content.length = 0
759
- textBlock = undefined
760
- currentTextIdx = -1
761
- thinkingIdx = -1
762
- output.stopReason = "stop"
763
- output.errorMessage = undefined
764
- finished = false
765
- const waitMs = attemptTimedOut ? 0 : retryDelayMs(attempt, null, maxRetryDelayMs)
766
- if (waitMs > 0) await delay(waitMs, controller.signal)
767
- continue retryLoop
768
- }
769
- if (attemptTimedOut) throw timeoutError(timeoutMs)
770
- throw streamError
771
- }
772
-
773
- // Stream completed successfully.
774
- endTextBlock()
775
- endThinking()
776
-
777
- stream.push({
778
- type: "done",
779
- reason: successStopReason(output.stopReason),
780
- message: output,
781
- })
782
- stream.end()
783
- break retryLoop
784
- } finally {
785
- controller.signal.removeEventListener("abort", onOuterAbort)
786
- clearAttemptTimeout()
787
- }
788
- }
789
- } catch (error: unknown) {
790
- const reason: ErrorReason =
791
- controller.signal.aborted || (error instanceof Error && error.name === "AbortError")
792
- ? "aborted"
793
- : "error"
794
- output.stopReason = reason
795
- output.errorMessage =
796
- reason === "aborted"
797
- ? "Request aborted"
798
- : redactCommandCodeErrorText(error instanceof Error ? error.message : String(error))
799
- stream.push({ type: "error", reason, error: output })
800
- stream.end()
801
- } finally {
802
- options?.signal?.removeEventListener("abort", abortUpstream)
803
- try {
804
- await reader?.cancel()
805
- } catch {
806
- // Reader may already be closed/cancelled.
807
- }
808
- try {
809
- reader?.releaseLock()
810
- } catch {
811
- // Reader may already be released/cancelled by the abort path.
812
- }
813
- }
814
- }
815
-
816
- run().catch((error: unknown) => {
817
- const msg: AssistantMessageLike = {
818
- role: "assistant",
819
- content: [],
820
- api: model.api,
821
- provider: model.provider,
822
- model: model.id,
823
- usage: defaultUsage(),
824
- stopReason: "error",
825
- errorMessage: redactCommandCodeErrorText(
826
- error instanceof Error ? error.message : String(error),
827
- ),
828
- timestamp: now(),
829
- }
830
- stream.push({ type: "error", reason: "error", error: msg })
831
- stream.end()
832
- })
833
-
834
- return stream
835
- }
836
- }