@humain/humain-code 0.4.17 → 0.5.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 (439) hide show
  1. package/CHANGELOG.md +260 -1
  2. package/dist/bundle/agent-monitor.js +1 -1
  3. package/dist/bundle/chunks/anthropic-messages-ZP5KUK52.js +67 -0
  4. package/dist/bundle/chunks/anthropic.js +2 -2
  5. package/dist/bundle/chunks/azure-openai-responses-QJFYQ3DF.js +15 -0
  6. package/dist/bundle/chunks/bedrock-converse-stream.js +152 -200
  7. package/dist/bundle/chunks/{chunk-4XU7TDAL.js → chunk-2GCMACT4.js} +48 -46
  8. package/dist/bundle/chunks/{chunk-DUSJT2W4.js → chunk-476XBL3W.js} +3 -3
  9. package/dist/bundle/chunks/{chunk-4NFYTS4C.js → chunk-5C4VL2AR.js} +4 -4
  10. package/dist/bundle/chunks/{chunk-QEF72EIZ.js → chunk-A6B2QMA7.js} +40 -96
  11. package/dist/bundle/chunks/{chunk-AOL6QG6L.js → chunk-A6YBWW4T.js} +1405 -1311
  12. package/dist/bundle/chunks/{chunk-ZRGFX6T6.js → chunk-CN3Q5UNB.js} +387 -309
  13. package/dist/bundle/chunks/{chunk-TJG52LZB.js → chunk-DR37WKFZ.js} +9 -8
  14. package/dist/bundle/chunks/chunk-DU6POZ7E.js +10 -0
  15. package/dist/bundle/chunks/{chunk-X6OTEVGA.js → chunk-FO2NYB6O.js} +626 -619
  16. package/dist/bundle/chunks/{chunk-RXOCQRBG.js → chunk-GEISZXXH.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-OKALNPTJ.js → chunk-HIZWUSPN.js} +24 -24
  18. package/dist/bundle/chunks/{chunk-MVYV6MJY.js → chunk-HT5YN3LX.js} +1 -1
  19. package/dist/bundle/chunks/chunk-IDU5BNNI.js +15 -0
  20. package/dist/bundle/chunks/{chunk-TIFFHHW6.js → chunk-JCXXRCP6.js} +5 -5
  21. package/dist/bundle/chunks/{chunk-QYCOHSI7.js → chunk-KKCMWB63.js} +8 -7
  22. package/dist/bundle/chunks/{chunk-SCBU5WOP.js → chunk-M74U5X4S.js} +30 -23
  23. package/dist/bundle/chunks/{chunk-AWCJWXGD.js → chunk-MIJHJNNQ.js} +3 -2
  24. package/dist/bundle/chunks/{chunk-Y26OS23T.js → chunk-N7CQ3UV3.js} +4 -4
  25. package/dist/bundle/chunks/{chunk-XQZG5HPT.js → chunk-O4DO5RWS.js} +11 -6
  26. package/dist/bundle/chunks/chunk-OR25QDSS.js +365 -0
  27. package/dist/bundle/chunks/{chunk-7PRU6YW3.js → chunk-OZNC2W4B.js} +306 -286
  28. package/dist/bundle/chunks/{chunk-Z33NNMNB.js → chunk-PH7UP57J.js} +1 -1
  29. package/dist/bundle/chunks/{chunk-FHVNUUBF.js → chunk-PS7DGA7B.js} +1 -1
  30. package/dist/bundle/chunks/chunk-Q3SFYT2X.js +1965 -0
  31. package/dist/bundle/chunks/chunk-QW6PTCAB.js +10 -0
  32. package/dist/bundle/chunks/{chunk-5CDES42D.js → chunk-QWXPGBAG.js} +1 -1
  33. package/dist/bundle/chunks/{chunk-NCQ6WAQK.js → chunk-ROZV2IYD.js} +1 -1
  34. package/dist/bundle/chunks/{chunk-PTP2ZHFQ.js → chunk-RTXDU3AA.js} +148 -122
  35. package/dist/bundle/chunks/{chunk-36Q5UVQL.js → chunk-T3HXWZG4.js} +2 -2
  36. package/dist/bundle/chunks/{chunk-FZUJXM6D.js → chunk-UDB6NI4G.js} +309 -240
  37. package/dist/bundle/chunks/chunk-UTNHGOFS.js +88 -0
  38. package/dist/bundle/chunks/{chunk-H2FY3PEV.js → chunk-V62QBESW.js} +4 -3
  39. package/dist/bundle/chunks/{chunk-LG2PJ6JN.js → chunk-XA7CJAYH.js} +4 -3
  40. package/dist/bundle/chunks/chunk-XQX7S3GM.js +7 -0
  41. package/dist/bundle/chunks/chunk-YFOLLX5D.js +23 -0
  42. package/dist/bundle/chunks/{chunk-YRCLNWFV.js → chunk-ZI7TK7HM.js} +1 -1
  43. package/dist/bundle/chunks/{chunk-V76YPIMT.js → chunk-ZR4GF4WU.js} +21 -15
  44. package/dist/bundle/chunks/{cli-SRI4UOSL.js → cli-VXU7OWFU.js} +1 -1
  45. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-T7TPP7SQ.js +4 -0
  46. package/dist/bundle/chunks/codemode-worker.js +27 -27
  47. package/dist/bundle/chunks/compat-S2IBVV6V.js +13 -0
  48. package/dist/bundle/chunks/{dist-D7M52E3X.js → dist-645GFIWH.js} +452 -448
  49. package/dist/bundle/chunks/{dist-XVXV2CL4.js → dist-IBUWEKEE.js} +3 -3
  50. package/dist/bundle/chunks/dist-YFMJEHPH.js +8 -0
  51. package/dist/bundle/chunks/{dist-cjs-AXBW3N4F.js → dist-cjs-HTASUQXQ.js} +82 -80
  52. package/dist/bundle/chunks/{easter-egg-3d-4SUPLBUF.js → easter-egg-3d-YOPLCOVW.js} +2 -2
  53. package/dist/bundle/chunks/{esm-NCUV2DF7.js → esm-R6HJ4QEG.js} +5 -5
  54. package/dist/bundle/chunks/{event-streams-NXFTZDSF.js → event-streams-BR2IL6C5.js} +1 -1
  55. package/dist/bundle/chunks/{execute-NTO3U76E.js → execute-2JXEKQ2X.js} +17 -8
  56. package/dist/bundle/chunks/{extract-BKBHK4AK.js → extract-OTCGZGTL.js} +50 -47
  57. package/dist/bundle/chunks/github-copilot.js +42 -40
  58. package/dist/bundle/chunks/google-generative-ai-HVPCGIZ6.js +21 -0
  59. package/dist/bundle/chunks/google-vertex-UM5MAALA.js +25 -0
  60. package/dist/bundle/chunks/host-ZHEL5XQW.js +2 -0
  61. package/dist/bundle/chunks/{https-proxy-agent-7CAXVAFH.js → https-proxy-agent-JQICCRPH.js} +1 -1
  62. package/dist/bundle/chunks/{llama-cpp-classify-AGCW7HYN.js → llama-cpp-classify-B3G57LVR.js} +5 -5
  63. package/dist/bundle/chunks/{mistral-conversations-G3GN6CMT.js → mistral-conversations-AH72RLXK.js} +11 -11
  64. package/dist/bundle/chunks/{node-ELWNZC34.js → node-SJPZTR4K.js} +6 -6
  65. package/dist/bundle/chunks/{node-DZCAT4Q6.js → node-VSA4ZN7D.js} +1 -1
  66. package/dist/bundle/chunks/openai-chatgpt.js +2 -2
  67. package/dist/bundle/chunks/{openai-codex-responses-FJFDAWHI.js → openai-codex-responses-L366637C.js} +48 -47
  68. package/dist/bundle/chunks/openai-codex.js +2 -2
  69. package/dist/bundle/chunks/openai-completions-ZP62QXJX.js +83 -0
  70. package/dist/bundle/chunks/{openai-decisions-HESOHYZB.js → openai-decisions-WOWUC65P.js} +1 -1
  71. package/dist/bundle/chunks/openai-responses-DXUGSUTN.js +26 -0
  72. package/dist/bundle/chunks/openrouter-images-5K47HDAT.js +8 -0
  73. package/dist/bundle/chunks/openrouter.js +2 -2
  74. package/dist/bundle/chunks/{pi-messages-SAOV3JNW.js → pi-messages-MOQQDZBK.js} +5 -4
  75. package/dist/bundle/chunks/radius.js +2 -2
  76. package/dist/bundle/chunks/{runtime-VGSK3QCM.js → runtime-5VFZTMWL.js} +1 -1
  77. package/dist/bundle/chunks/typesafe-system-one-43OCHGKP.js +3 -0
  78. package/dist/bundle/chunks/{undici-N4LWJ3S3.js → undici-EK3EUI2E.js} +1 -1
  79. package/dist/bundle/chunks/virtual-modules-GU6AW5ZK.js +5 -0
  80. package/dist/bundle/cli-runtime.js +3 -3
  81. package/dist/bundle/flow/package.json +4 -4
  82. package/dist/bundle/index.js +6 -6
  83. package/dist/bundle/rpc-entry.js +3 -3
  84. package/dist/cli/args.d.ts +6 -0
  85. package/dist/cli/args.d.ts.map +1 -1
  86. package/dist/cli/args.js +11 -0
  87. package/dist/cli/args.js.map +1 -1
  88. package/dist/coordination/adapter/tool.d.ts.map +1 -1
  89. package/dist/coordination/adapter/tool.js +3 -1
  90. package/dist/coordination/adapter/tool.js.map +1 -1
  91. package/dist/coordination/broker/broker.d.ts +6 -2
  92. package/dist/coordination/broker/broker.d.ts.map +1 -1
  93. package/dist/coordination/broker/broker.js +20 -8
  94. package/dist/coordination/broker/broker.js.map +1 -1
  95. package/dist/coordination/client/client.d.ts.map +1 -1
  96. package/dist/coordination/client/client.js +4 -2
  97. package/dist/coordination/client/client.js.map +1 -1
  98. package/dist/coordination/transport/discovery.d.ts +10 -3
  99. package/dist/coordination/transport/discovery.d.ts.map +1 -1
  100. package/dist/coordination/transport/discovery.js +18 -5
  101. package/dist/coordination/transport/discovery.js.map +1 -1
  102. package/dist/core/agent-session.d.ts +35 -2
  103. package/dist/core/agent-session.d.ts.map +1 -1
  104. package/dist/core/agent-session.js +163 -40
  105. package/dist/core/agent-session.js.map +1 -1
  106. package/dist/core/anthropic-subscription-usage.d.ts +47 -0
  107. package/dist/core/anthropic-subscription-usage.d.ts.map +1 -0
  108. package/dist/core/anthropic-subscription-usage.js +170 -0
  109. package/dist/core/anthropic-subscription-usage.js.map +1 -0
  110. package/dist/core/bash-executor.d.ts.map +1 -1
  111. package/dist/core/bash-executor.js +7 -1
  112. package/dist/core/bash-executor.js.map +1 -1
  113. package/dist/core/client-identity.d.ts +13 -0
  114. package/dist/core/client-identity.d.ts.map +1 -0
  115. package/dist/core/client-identity.js +25 -0
  116. package/dist/core/client-identity.js.map +1 -0
  117. package/dist/core/codex-usage.d.ts +37 -1
  118. package/dist/core/codex-usage.d.ts.map +1 -1
  119. package/dist/core/codex-usage.js +104 -11
  120. package/dist/core/codex-usage.js.map +1 -1
  121. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  122. package/dist/core/compaction/branch-summarization.js +1 -2
  123. package/dist/core/compaction/branch-summarization.js.map +1 -1
  124. package/dist/core/compaction/compaction.d.ts +2 -2
  125. package/dist/core/compaction/compaction.d.ts.map +1 -1
  126. package/dist/core/compaction/compaction.js +20 -15
  127. package/dist/core/compaction/compaction.js.map +1 -1
  128. package/dist/core/export-html/index.d.ts.map +1 -1
  129. package/dist/core/export-html/index.js +2 -0
  130. package/dist/core/export-html/index.js.map +1 -1
  131. package/dist/core/export-html/template.html +1 -0
  132. package/dist/core/export-html/template.js +2 -1
  133. package/dist/core/export-html/vendor/marked-cjk-friendly.min.js +6 -0
  134. package/dist/core/export-html/vendor/marked.min.js +30 -29
  135. package/dist/core/extensions/loader.d.ts.map +1 -1
  136. package/dist/core/extensions/loader.js +3 -0
  137. package/dist/core/extensions/loader.js.map +1 -1
  138. package/dist/core/extensions/runner.d.ts +14 -0
  139. package/dist/core/extensions/runner.d.ts.map +1 -1
  140. package/dist/core/extensions/runner.js +86 -2
  141. package/dist/core/extensions/runner.js.map +1 -1
  142. package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
  143. package/dist/core/extensions/virtual-modules.js +3 -0
  144. package/dist/core/extensions/virtual-modules.js.map +1 -1
  145. package/dist/core/model-config.d.ts +920 -0
  146. package/dist/core/model-config.d.ts.map +1 -1
  147. package/dist/core/model-config.js +48 -24
  148. package/dist/core/model-config.js.map +1 -1
  149. package/dist/core/model-registry.d.ts +18 -0
  150. package/dist/core/model-registry.d.ts.map +1 -1
  151. package/dist/core/model-registry.js +20 -0
  152. package/dist/core/model-registry.js.map +1 -1
  153. package/dist/core/model-resolver.d.ts.map +1 -1
  154. package/dist/core/model-resolver.js +14 -6
  155. package/dist/core/model-resolver.js.map +1 -1
  156. package/dist/core/model-runtime.d.ts +9 -0
  157. package/dist/core/model-runtime.d.ts.map +1 -1
  158. package/dist/core/model-runtime.js +99 -12
  159. package/dist/core/model-runtime.js.map +1 -1
  160. package/dist/core/output-guard.d.ts +13 -1
  161. package/dist/core/output-guard.d.ts.map +1 -1
  162. package/dist/core/output-guard.js +101 -11
  163. package/dist/core/output-guard.js.map +1 -1
  164. package/dist/core/provider-composer.d.ts +2 -1
  165. package/dist/core/provider-composer.d.ts.map +1 -1
  166. package/dist/core/provider-composer.js +7 -3
  167. package/dist/core/provider-composer.js.map +1 -1
  168. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  169. package/dist/core/remote-catalog-provider.js +7 -2
  170. package/dist/core/remote-catalog-provider.js.map +1 -1
  171. package/dist/core/sdk.d.ts.map +1 -1
  172. package/dist/core/sdk.js +8 -9
  173. package/dist/core/sdk.js.map +1 -1
  174. package/dist/core/session-manager.d.ts +4 -0
  175. package/dist/core/session-manager.d.ts.map +1 -1
  176. package/dist/core/session-manager.js +242 -26
  177. package/dist/core/session-manager.js.map +1 -1
  178. package/dist/core/system-prompt.d.ts +6 -1
  179. package/dist/core/system-prompt.d.ts.map +1 -1
  180. package/dist/core/system-prompt.js +93 -1
  181. package/dist/core/system-prompt.js.map +1 -1
  182. package/dist/core/tools/grep.d.ts.map +1 -1
  183. package/dist/core/tools/grep.js +3 -1
  184. package/dist/core/tools/grep.js.map +1 -1
  185. package/dist/core/tools/ls.d.ts.map +1 -1
  186. package/dist/core/tools/ls.js +37 -12
  187. package/dist/core/tools/ls.js.map +1 -1
  188. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  189. package/dist/extensions/codemode/execute.js +102 -24
  190. package/dist/extensions/codemode/execute.js.map +1 -1
  191. package/dist/extensions/index.d.ts.map +1 -1
  192. package/dist/extensions/index.js +3 -1
  193. package/dist/extensions/index.js.map +1 -1
  194. package/dist/extensions/mcp/config.d.ts.map +1 -1
  195. package/dist/extensions/mcp/config.js +3 -2
  196. package/dist/extensions/mcp/config.js.map +1 -1
  197. package/dist/extensions/usage/index.d.ts +15 -0
  198. package/dist/extensions/usage/index.d.ts.map +1 -0
  199. package/dist/extensions/usage/index.js +110 -0
  200. package/dist/extensions/usage/index.js.map +1 -0
  201. package/dist/extensions/usage/overview.d.ts +90 -0
  202. package/dist/extensions/usage/overview.d.ts.map +1 -0
  203. package/dist/extensions/usage/overview.js +215 -0
  204. package/dist/extensions/usage/overview.js.map +1 -0
  205. package/dist/extensions/usage/popup.d.ts +21 -0
  206. package/dist/extensions/usage/popup.d.ts.map +1 -0
  207. package/dist/extensions/usage/popup.js +98 -0
  208. package/dist/extensions/usage/popup.js.map +1 -0
  209. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +21 -2
  210. package/dist/humain/bundled-extension-names.d.ts +6 -0
  211. package/dist/humain/bundled-extension-names.d.ts.map +1 -0
  212. package/dist/humain/bundled-extension-names.js +9 -0
  213. package/dist/humain/bundled-extension-names.js.map +1 -0
  214. package/dist/humain/index.d.ts +2 -2
  215. package/dist/humain/index.d.ts.map +1 -1
  216. package/dist/humain/index.js +3 -2
  217. package/dist/humain/index.js.map +1 -1
  218. package/dist/humain/web-access/vendor/anysearch.d.ts.map +1 -1
  219. package/dist/humain/web-access/vendor/anysearch.js +3 -3
  220. package/dist/humain/web-access/vendor/anysearch.js.map +1 -1
  221. package/dist/humain/web-access/vendor/bocha.d.ts.map +1 -1
  222. package/dist/humain/web-access/vendor/bocha.js +3 -3
  223. package/dist/humain/web-access/vendor/bocha.js.map +1 -1
  224. package/dist/humain/web-access/vendor/brightdata-unlocker.d.ts.map +1 -1
  225. package/dist/humain/web-access/vendor/brightdata-unlocker.js +2 -2
  226. package/dist/humain/web-access/vendor/brightdata-unlocker.js.map +1 -1
  227. package/dist/humain/web-access/vendor/brightdata.d.ts.map +1 -1
  228. package/dist/humain/web-access/vendor/brightdata.js +3 -3
  229. package/dist/humain/web-access/vendor/brightdata.js.map +1 -1
  230. package/dist/humain/web-access/vendor/ceramic.d.ts.map +1 -1
  231. package/dist/humain/web-access/vendor/ceramic.js +2 -2
  232. package/dist/humain/web-access/vendor/ceramic.js.map +1 -1
  233. package/dist/humain/web-access/vendor/curator-page.d.ts.map +1 -1
  234. package/dist/humain/web-access/vendor/curator-page.js +3 -1
  235. package/dist/humain/web-access/vendor/curator-page.js.map +1 -1
  236. package/dist/humain/web-access/vendor/curator-server.d.ts.map +1 -1
  237. package/dist/humain/web-access/vendor/curator-server.js +2 -0
  238. package/dist/humain/web-access/vendor/curator-server.js.map +1 -1
  239. package/dist/humain/web-access/vendor/deepseek.d.ts +11 -1
  240. package/dist/humain/web-access/vendor/deepseek.d.ts.map +1 -1
  241. package/dist/humain/web-access/vendor/deepseek.js +170 -5
  242. package/dist/humain/web-access/vendor/deepseek.js.map +1 -1
  243. package/dist/humain/web-access/vendor/extract.d.ts.map +1 -1
  244. package/dist/humain/web-access/vendor/extract.js +63 -6
  245. package/dist/humain/web-access/vendor/extract.js.map +1 -1
  246. package/dist/humain/web-access/vendor/gemini-search.d.ts +5 -3
  247. package/dist/humain/web-access/vendor/gemini-search.d.ts.map +1 -1
  248. package/dist/humain/web-access/vendor/gemini-search.js +33 -7
  249. package/dist/humain/web-access/vendor/gemini-search.js.map +1 -1
  250. package/dist/humain/web-access/vendor/index.d.ts +1 -0
  251. package/dist/humain/web-access/vendor/index.d.ts.map +1 -1
  252. package/dist/humain/web-access/vendor/index.js +18 -3
  253. package/dist/humain/web-access/vendor/index.js.map +1 -1
  254. package/dist/humain/web-access/vendor/jina-search.d.ts.map +1 -1
  255. package/dist/humain/web-access/vendor/jina-search.js +6 -4
  256. package/dist/humain/web-access/vendor/jina-search.js.map +1 -1
  257. package/dist/humain/web-access/vendor/kagi.d.ts.map +1 -1
  258. package/dist/humain/web-access/vendor/kagi.js +4 -4
  259. package/dist/humain/web-access/vendor/kagi.js.map +1 -1
  260. package/dist/humain/web-access/vendor/keenable.d.ts.map +1 -1
  261. package/dist/humain/web-access/vendor/keenable.js +2 -2
  262. package/dist/humain/web-access/vendor/keenable.js.map +1 -1
  263. package/dist/humain/web-access/vendor/linkup.d.ts +6 -0
  264. package/dist/humain/web-access/vendor/linkup.d.ts.map +1 -0
  265. package/dist/humain/web-access/vendor/linkup.js +167 -0
  266. package/dist/humain/web-access/vendor/linkup.js.map +1 -0
  267. package/dist/humain/web-access/vendor/mistral-search.d.ts.map +1 -1
  268. package/dist/humain/web-access/vendor/mistral-search.js +3 -3
  269. package/dist/humain/web-access/vendor/mistral-search.js.map +1 -1
  270. package/dist/humain/web-access/vendor/ollama.d.ts.map +1 -1
  271. package/dist/humain/web-access/vendor/ollama.js +4 -4
  272. package/dist/humain/web-access/vendor/ollama.js.map +1 -1
  273. package/dist/humain/web-access/vendor/parallel.js +6 -7
  274. package/dist/humain/web-access/vendor/parallel.js.map +1 -1
  275. package/dist/humain/web-access/vendor/perplexity.d.ts.map +1 -1
  276. package/dist/humain/web-access/vendor/perplexity.js +4 -3
  277. package/dist/humain/web-access/vendor/perplexity.js.map +1 -1
  278. package/dist/humain/web-access/vendor/querit.d.ts.map +1 -1
  279. package/dist/humain/web-access/vendor/querit.js +3 -3
  280. package/dist/humain/web-access/vendor/querit.js.map +1 -1
  281. package/dist/humain/web-access/vendor/search1api.d.ts.map +1 -1
  282. package/dist/humain/web-access/vendor/search1api.js +3 -3
  283. package/dist/humain/web-access/vendor/search1api.js.map +1 -1
  284. package/dist/humain/web-access/vendor/searchinfinity.d.ts.map +1 -1
  285. package/dist/humain/web-access/vendor/searchinfinity.js +3 -3
  286. package/dist/humain/web-access/vendor/searchinfinity.js.map +1 -1
  287. package/dist/humain/web-access/vendor/serpapi.d.ts.map +1 -1
  288. package/dist/humain/web-access/vendor/serpapi.js +6 -5
  289. package/dist/humain/web-access/vendor/serpapi.js.map +1 -1
  290. package/dist/humain/web-access/vendor/serpbase.d.ts.map +1 -1
  291. package/dist/humain/web-access/vendor/serpbase.js +4 -4
  292. package/dist/humain/web-access/vendor/serpbase.js.map +1 -1
  293. package/dist/humain/web-access/vendor/serpdive.d.ts.map +1 -1
  294. package/dist/humain/web-access/vendor/serpdive.js +3 -3
  295. package/dist/humain/web-access/vendor/serpdive.js.map +1 -1
  296. package/dist/humain/web-access/vendor/serper.d.ts.map +1 -1
  297. package/dist/humain/web-access/vendor/serper.js +5 -4
  298. package/dist/humain/web-access/vendor/serper.js.map +1 -1
  299. package/dist/humain/web-access/vendor/serply.d.ts.map +1 -1
  300. package/dist/humain/web-access/vendor/serply.js +2 -2
  301. package/dist/humain/web-access/vendor/serply.js.map +1 -1
  302. package/dist/humain/web-access/vendor/utils.d.ts +3 -1
  303. package/dist/humain/web-access/vendor/utils.d.ts.map +1 -1
  304. package/dist/humain/web-access/vendor/utils.js +27 -2
  305. package/dist/humain/web-access/vendor/utils.js.map +1 -1
  306. package/dist/humain/web-access/vendor/valyu.d.ts.map +1 -1
  307. package/dist/humain/web-access/vendor/valyu.js +3 -3
  308. package/dist/humain/web-access/vendor/valyu.js.map +1 -1
  309. package/dist/humain/web-access/vendor/web-tool-core.d.ts +2 -0
  310. package/dist/humain/web-access/vendor/web-tool-core.d.ts.map +1 -1
  311. package/dist/humain/web-access/vendor/web-tool-core.js +3 -0
  312. package/dist/humain/web-access/vendor/web-tool-core.js.map +1 -1
  313. package/dist/humain/web-access/vendor/xai-search.d.ts.map +1 -1
  314. package/dist/humain/web-access/vendor/xai-search.js +51 -8
  315. package/dist/humain/web-access/vendor/xai-search.js.map +1 -1
  316. package/dist/humain/web-access/vendor/xcrawl.d.ts.map +1 -1
  317. package/dist/humain/web-access/vendor/xcrawl.js +3 -3
  318. package/dist/humain/web-access/vendor/xcrawl.js.map +1 -1
  319. package/dist/humain/web-access/vendor/you.d.ts.map +1 -1
  320. package/dist/humain/web-access/vendor/you.js +2 -2
  321. package/dist/humain/web-access/vendor/you.js.map +1 -1
  322. package/dist/main.d.ts.map +1 -1
  323. package/dist/main.js +15 -2
  324. package/dist/main.js.map +1 -1
  325. package/dist/modes/interactive/components/assistant-message.d.ts +14 -2
  326. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  327. package/dist/modes/interactive/components/assistant-message.js +62 -7
  328. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  329. package/dist/modes/interactive/components/config-selector.js +1 -1
  330. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  331. package/dist/modes/interactive/components/custom-editor.d.ts +2 -0
  332. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  333. package/dist/modes/interactive/components/custom-editor.js +6 -1
  334. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  335. package/dist/modes/interactive/components/easter-egg-3d.js +1 -1
  336. package/dist/modes/interactive/components/easter-egg-3d.js.map +1 -1
  337. package/dist/modes/interactive/components/footer.d.ts +10 -2
  338. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  339. package/dist/modes/interactive/components/footer.js +141 -66
  340. package/dist/modes/interactive/components/footer.js.map +1 -1
  341. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
  342. package/dist/modes/interactive/components/mermaid.js +16 -3
  343. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  344. package/dist/modes/interactive/components/model-selector.js +1 -1
  345. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  346. package/dist/modes/interactive/components/themed-text.d.ts.map +1 -1
  347. package/dist/modes/interactive/components/themed-text.js +3 -2
  348. package/dist/modes/interactive/components/themed-text.js.map +1 -1
  349. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  350. package/dist/modes/interactive/components/tool-execution.js +17 -6
  351. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  352. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  353. package/dist/modes/interactive/components/user-message.js +3 -2
  354. package/dist/modes/interactive/components/user-message.js.map +1 -1
  355. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  356. package/dist/modes/interactive/components/visual-truncate.js +4 -2
  357. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  358. package/dist/modes/interactive/interactive-mode.d.ts +13 -17
  359. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  360. package/dist/modes/interactive/interactive-mode.js +90 -122
  361. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  362. package/dist/modes/print-mode.d.ts.map +1 -1
  363. package/dist/modes/print-mode.js +2 -5
  364. package/dist/modes/print-mode.js.map +1 -1
  365. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  366. package/dist/modes/rpc/rpc-mode.js +2 -3
  367. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  368. package/dist/package-manager-cli.d.ts.map +1 -1
  369. package/dist/package-manager-cli.js +2 -1
  370. package/dist/package-manager-cli.js.map +1 -1
  371. package/dist/utils/child-process.d.ts.map +1 -1
  372. package/dist/utils/child-process.js +3 -2
  373. package/dist/utils/child-process.js.map +1 -1
  374. package/dist/utils/clipboard-command.d.ts.map +1 -1
  375. package/dist/utils/clipboard-command.js +3 -0
  376. package/dist/utils/clipboard-command.js.map +1 -1
  377. package/dist/utils/pi-user-agent.d.ts +1 -0
  378. package/dist/utils/pi-user-agent.d.ts.map +1 -1
  379. package/dist/utils/pi-user-agent.js +3 -2
  380. package/dist/utils/pi-user-agent.js.map +1 -1
  381. package/dist/utils/shell.d.ts.map +1 -1
  382. package/dist/utils/shell.js +45 -13
  383. package/dist/utils/shell.js.map +1 -1
  384. package/dist/utils/tools-manager.d.ts.map +1 -1
  385. package/dist/utils/tools-manager.js +4 -3
  386. package/dist/utils/tools-manager.js.map +1 -1
  387. package/docs/codemode.md +2 -2
  388. package/docs/compaction.md +3 -3
  389. package/docs/coordination.md +1 -1
  390. package/docs/custom-provider.md +53 -1
  391. package/docs/docs.json +4 -0
  392. package/docs/environment-variables.md +2 -0
  393. package/docs/extensions.md +133 -10
  394. package/docs/models-configuration.md +197 -0
  395. package/docs/models.md +21 -5
  396. package/docs/settings.md +1 -1
  397. package/docs/slash-commands.md +10 -0
  398. package/docs/tui.md +70 -0
  399. package/docs/windows.md +16 -2
  400. package/examples/extensions/custom-provider-anthropic/package.json +2 -2
  401. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  402. package/examples/extensions/gondolin/package-lock.json +2 -2
  403. package/examples/extensions/gondolin/package.json +1 -1
  404. package/examples/extensions/sandbox/package-lock.json +2 -2
  405. package/examples/extensions/sandbox/package.json +2 -2
  406. package/examples/extensions/with-deps/package.json +1 -1
  407. package/examples/plugins/pi-example-plugin/package.json +2 -2
  408. package/npm-shrinkwrap.json +243 -219
  409. package/package.json +21 -20
  410. package/schemas/models.schema.json +84 -30
  411. package/src/coordination/UPSTREAM.md +36 -3
  412. package/src/coordination/upstream.json +3 -3
  413. package/src/humain/web-access/UPSTREAM.md +72 -1
  414. package/src/humain/web-access/upstream.json +5 -4
  415. package/dist/bundle/chunks/anthropic-messages-TSNY5MWH.js +0 -67
  416. package/dist/bundle/chunks/azure-openai-responses-Z4DCXO2G.js +0 -15
  417. package/dist/bundle/chunks/chunk-5K5RFXXO.js +0 -74
  418. package/dist/bundle/chunks/chunk-65U7MPF4.js +0 -1790
  419. package/dist/bundle/chunks/chunk-PY7SOXCA.js +0 -10
  420. package/dist/bundle/chunks/chunk-UGJAAWNC.js +0 -7
  421. package/dist/bundle/chunks/chunk-UGXYG7HN.js +0 -22
  422. package/dist/bundle/chunks/chunk-VEYTRNQC.js +0 -5
  423. package/dist/bundle/chunks/chunk-W2QRCQBX.js +0 -165
  424. package/dist/bundle/chunks/chunk-X3O5MCKJ.js +0 -7
  425. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-MUJQ6LT2.js +0 -4
  426. package/dist/bundle/chunks/compat-ARQPWKBQ.js +0 -13
  427. package/dist/bundle/chunks/dist-LKDZAEUQ.js +0 -7
  428. package/dist/bundle/chunks/google-generative-ai-SJ4JO2MY.js +0 -21
  429. package/dist/bundle/chunks/google-vertex-KNLNNDET.js +0 -25
  430. package/dist/bundle/chunks/host-63SNKK5Y.js +0 -2
  431. package/dist/bundle/chunks/openai-completions-IC7WRLTI.js +0 -82
  432. package/dist/bundle/chunks/openai-responses-XXCYDFSM.js +0 -24
  433. package/dist/bundle/chunks/openrouter-images-DT2HMZNO.js +0 -8
  434. package/dist/bundle/chunks/typesafe-system-one-HCMGHK6A.js +0 -2
  435. package/dist/bundle/chunks/virtual-modules-LP2ULVLW.js +0 -5
  436. package/dist/core/provider-attribution.d.ts +0 -4
  437. package/dist/core/provider-attribution.d.ts.map +0 -1
  438. package/dist/core/provider-attribution.js +0 -85
  439. package/dist/core/provider-attribution.js.map +0 -1
@@ -0,0 +1,47 @@
1
+ import type { OAuthAccount } from "./oauth-account-pool.ts";
2
+ /**
3
+ * Live Claude subscription limits from Anthropic's subscription usage endpoint, which Claude Code reads with its OAuth
4
+ * token. The endpoint is undocumented: every field is parsed defensively and unknown keys are ignored.
5
+ */
6
+ export declare const ANTHROPIC_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
7
+ export declare const ANTHROPIC_USAGE_PROVIDER_ID = "anthropic";
8
+ export interface AnthropicUsageWindow {
9
+ /** Response key, e.g. "five_hour", "seven_day", "extra_usage". */
10
+ id: string;
11
+ label: string;
12
+ /** Percent of the limit used, 0..100. */
13
+ usedPercent: number;
14
+ /** Epoch ms when the window resets, when reported. */
15
+ resetsAt?: number;
16
+ }
17
+ export type AnthropicUsageUnavailableReason = "expired_credential" | "unauthorized" | "rate_limited" | "http_error" | "timeout" | "network" | "malformed";
18
+ export type AnthropicUsageResult = {
19
+ status: "ok";
20
+ windows: AnthropicUsageWindow[];
21
+ fetchedAt: number;
22
+ } | {
23
+ status: "unavailable";
24
+ reason: AnthropicUsageUnavailableReason;
25
+ };
26
+ export interface FetchAnthropicSubscriptionUsageOptions {
27
+ signal?: AbortSignal;
28
+ /** Injected for tests. Defaults to globalThis.fetch. */
29
+ fetch?: typeof fetch;
30
+ /** Reference time in epoch ms. Defaults to Date.now(). */
31
+ now?: number;
32
+ }
33
+ /**
34
+ * Pure parser, exported for tests and for Claude Code's cached copy of the same response. Null, absent or malformed
35
+ * buckets are skipped; extra usage is shown only when enabled, as a percentage (its money units are not documented).
36
+ */
37
+ export declare function parseAnthropicSubscriptionUsage(payload: unknown): AnthropicUsageWindow[];
38
+ /** Retry-After as delay seconds or an HTTP date, bounded to 1 s..30 min; 5 min when absent or invalid. */
39
+ export declare function parseRetryAfterMs(value: string | null, nowMs: number): number;
40
+ /** Forget cached results. For tests. */
41
+ export declare function clearAnthropicUsageCache(): void;
42
+ /**
43
+ * The subscription usage of one pooled Anthropic account. Never throws; never mutates the credential. Results are
44
+ * cached per account key in this process, and concurrent calls for one account share one request.
45
+ */
46
+ export declare function fetchAnthropicSubscriptionUsage(account: OAuthAccount, options?: FetchAnthropicSubscriptionUsageOptions): Promise<AnthropicUsageResult>;
47
+ //# sourceMappingURL=anthropic-subscription-usage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic-subscription-usage.d.ts","sourceRoot":"","sources":["../../src/core/anthropic-subscription-usage.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAE5D;;;GAGG;AACH,eAAO,MAAM,mBAAmB,8CAA8C,CAAC;AAC/E,eAAO,MAAM,2BAA2B,cAAc,CAAC;AAiBvD,MAAM,WAAW,oBAAoB;IACpC,kEAAkE;IAClE,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,yCAAyC;IACzC,WAAW,EAAE,MAAM,CAAC;IACpB,sDAAsD;IACtD,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,MAAM,+BAA+B,GACxC,oBAAoB,GACpB,cAAc,GACd,cAAc,GACd,YAAY,GACZ,SAAS,GACT,SAAS,GACT,WAAW,CAAC;AAEf,MAAM,MAAM,oBAAoB,GAC7B;IAAE,MAAM,EAAE,IAAI,CAAC;IAAC,OAAO,EAAE,oBAAoB,EAAE,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GACpE;IAAE,MAAM,EAAE,aAAa,CAAC;IAAC,MAAM,EAAE,+BAA+B,CAAA;CAAE,CAAC;AAEtE,MAAM,WAAW,sCAAsC;IACtD,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,wDAAwD;IACxD,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,0DAA0D;IAC1D,GAAG,CAAC,EAAE,MAAM,CAAC;CACb;AAgBD;;;GAGG;AACH,wBAAgB,+BAA+B,CAAC,OAAO,EAAE,OAAO,GAAG,oBAAoB,EAAE,CAiBxF;AAED,0GAA0G;AAC1G,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAM7E;AAsBD,wCAAwC;AACxC,wBAAgB,wBAAwB,IAAI,IAAI,CAG/C;AA0DD;;;GAGG;AACH,wBAAsB,+BAA+B,CACpD,OAAO,EAAE,YAAY,EACrB,OAAO,GAAE,sCAA2C,GAClD,OAAO,CAAC,oBAAoB,CAAC,CAiB/B"}
@@ -0,0 +1,170 @@
1
+ import { VERSION } from "../config.js";
2
+ import { getPiUserAgent } from "../utils/pi-user-agent.js";
3
+ /**
4
+ * Live Claude subscription limits from Anthropic's subscription usage endpoint, which Claude Code reads with its OAuth
5
+ * token. The endpoint is undocumented: every field is parsed defensively and unknown keys are ignored.
6
+ */
7
+ export const ANTHROPIC_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
8
+ export const ANTHROPIC_USAGE_PROVIDER_ID = "anthropic";
9
+ const SUCCESS_TTL_MS = 60_000;
10
+ const DEFAULT_RETRY_AFTER_MS = 5 * 60_000;
11
+ const MAX_RETRY_AFTER_MS = 30 * 60_000;
12
+ const MAX_CACHE_ENTRIES = 32;
13
+ const MAX_RESET_LENGTH = 64;
14
+ /** Percent buckets in display order. */
15
+ const BUCKETS = [
16
+ ["five_hour", "5h"],
17
+ ["seven_day", "Weekly"],
18
+ ["seven_day_opus", "Weekly Opus"],
19
+ ["seven_day_sonnet", "Weekly Sonnet"],
20
+ ["seven_day_oauth_apps", "Weekly OAuth apps"],
21
+ ];
22
+ function isRecord(value) {
23
+ return typeof value === "object" && value !== null && !Array.isArray(value);
24
+ }
25
+ function parsePercent(value) {
26
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.min(100, value) : undefined;
27
+ }
28
+ function parseResetsAt(value) {
29
+ if (typeof value !== "string" || value.length > MAX_RESET_LENGTH)
30
+ return undefined;
31
+ const ms = Date.parse(value);
32
+ return Number.isFinite(ms) ? ms : undefined;
33
+ }
34
+ /**
35
+ * Pure parser, exported for tests and for Claude Code's cached copy of the same response. Null, absent or malformed
36
+ * buckets are skipped; extra usage is shown only when enabled, as a percentage (its money units are not documented).
37
+ */
38
+ export function parseAnthropicSubscriptionUsage(payload) {
39
+ if (!isRecord(payload))
40
+ return [];
41
+ const windows = [];
42
+ for (const [key, label] of BUCKETS) {
43
+ const bucket = payload[key];
44
+ if (!isRecord(bucket))
45
+ continue;
46
+ const usedPercent = parsePercent(bucket.utilization);
47
+ if (usedPercent === undefined)
48
+ continue;
49
+ const resetsAt = parseResetsAt(bucket.resets_at);
50
+ windows.push({ id: key, label, usedPercent, ...(resetsAt !== undefined ? { resetsAt } : {}) });
51
+ }
52
+ const extra = payload.extra_usage;
53
+ if (isRecord(extra) && extra.is_enabled === true) {
54
+ const usedPercent = parsePercent(extra.utilization);
55
+ if (usedPercent !== undefined)
56
+ windows.push({ id: "extra_usage", label: "Extra usage", usedPercent });
57
+ }
58
+ return windows;
59
+ }
60
+ /** Retry-After as delay seconds or an HTTP date, bounded to 1 s..30 min; 5 min when absent or invalid. */
61
+ export function parseRetryAfterMs(value, nowMs) {
62
+ if (value === null)
63
+ return DEFAULT_RETRY_AFTER_MS;
64
+ const trimmed = value.trim();
65
+ const ms = /^\d{1,10}$/.test(trimmed) ? Number(trimmed) * 1000 : Date.parse(trimmed) - nowMs;
66
+ if (!Number.isFinite(ms))
67
+ return DEFAULT_RETRY_AFTER_MS;
68
+ return Math.min(MAX_RETRY_AFTER_MS, Math.max(1000, ms));
69
+ }
70
+ // The endpoint rate-limits aggressively: successes are reused for 60 s and a 429 is remembered for its Retry-After.
71
+ const cache = new Map();
72
+ const inFlight = new Map();
73
+ function remember(key, result, until, now) {
74
+ cache.delete(key);
75
+ for (const [entryKey, entry] of cache)
76
+ if (entry.until <= now)
77
+ cache.delete(entryKey);
78
+ while (cache.size >= MAX_CACHE_ENTRIES) {
79
+ const oldest = cache.keys().next().value;
80
+ if (oldest === undefined)
81
+ break;
82
+ cache.delete(oldest);
83
+ }
84
+ cache.set(key, { result, until });
85
+ }
86
+ /** Forget cached results. For tests. */
87
+ export function clearAnthropicUsageCache() {
88
+ cache.clear();
89
+ inFlight.clear();
90
+ }
91
+ function isAbortError(error) {
92
+ return isRecord(error) && (error.name === "AbortError" || error.name === "TimeoutError");
93
+ }
94
+ async function requestUsage(account, options, now) {
95
+ const unavailable = (reason) => ({
96
+ status: "unavailable",
97
+ reason,
98
+ });
99
+ let response;
100
+ try {
101
+ const fetcher = options.fetch ?? globalThis.fetch;
102
+ response = await fetcher(ANTHROPIC_USAGE_URL, {
103
+ method: "GET",
104
+ headers: {
105
+ Authorization: `Bearer ${account.credential.access}`,
106
+ "anthropic-beta": "oauth-2025-04-20",
107
+ Accept: "application/json",
108
+ "User-Agent": getPiUserAgent(VERSION),
109
+ },
110
+ // Refusing redirects keeps the subscription token on this origin.
111
+ redirect: "error",
112
+ signal: options.signal,
113
+ });
114
+ }
115
+ catch (error) {
116
+ return unavailable(options.signal?.aborted || isAbortError(error) ? "timeout" : "network");
117
+ }
118
+ if (response.status === 401 || response.status === 403)
119
+ return unavailable("unauthorized");
120
+ if (response.status === 429) {
121
+ const result = unavailable("rate_limited");
122
+ remember(account.key, result, now + parseRetryAfterMs(response.headers.get("retry-after"), now), now);
123
+ return result;
124
+ }
125
+ if (!response.ok)
126
+ return unavailable("http_error");
127
+ let payload;
128
+ try {
129
+ payload = await response.json();
130
+ }
131
+ catch (error) {
132
+ return unavailable(options.signal?.aborted || isAbortError(error) ? "timeout" : "malformed");
133
+ }
134
+ if (!isRecord(payload))
135
+ return unavailable("malformed");
136
+ const result = {
137
+ status: "ok",
138
+ windows: parseAnthropicSubscriptionUsage(payload),
139
+ fetchedAt: now,
140
+ };
141
+ remember(account.key, result, now + SUCCESS_TTL_MS, now);
142
+ return result;
143
+ }
144
+ /**
145
+ * The subscription usage of one pooled Anthropic account. Never throws; never mutates the credential. Results are
146
+ * cached per account key in this process, and concurrent calls for one account share one request.
147
+ */
148
+ export async function fetchAnthropicSubscriptionUsage(account, options = {}) {
149
+ const now = options.now ?? Date.now();
150
+ const cached = cache.get(account.key);
151
+ if (cached && cached.until > now)
152
+ return cached.result;
153
+ if (account.credential.expires <= now)
154
+ return { status: "unavailable", reason: "expired_credential" };
155
+ if (options.signal?.aborted)
156
+ return { status: "unavailable", reason: "timeout" };
157
+ const pending = inFlight.get(account.key);
158
+ // shortcut: a joined call shares the first caller's signal, so its abort cancels both; fine for one /usage popup.
159
+ if (pending)
160
+ return pending;
161
+ const request = requestUsage(account, options, now)
162
+ .catch(() => ({ status: "unavailable", reason: "network" }))
163
+ .finally(() => {
164
+ if (inFlight.get(account.key) === request)
165
+ inFlight.delete(account.key);
166
+ });
167
+ inFlight.set(account.key, request);
168
+ return request;
169
+ }
170
+ //# sourceMappingURL=anthropic-subscription-usage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic-subscription-usage.js","sourceRoot":"","sources":["../../src/core/anthropic-subscription-usage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAG3D;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,2CAA2C,CAAC;AAC/E,MAAM,CAAC,MAAM,2BAA2B,GAAG,WAAW,CAAC;AAEvD,MAAM,cAAc,GAAG,MAAM,CAAC;AAC9B,MAAM,sBAAsB,GAAG,CAAC,GAAG,MAAM,CAAC;AAC1C,MAAM,kBAAkB,GAAG,EAAE,GAAG,MAAM,CAAC;AACvC,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAC7B,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAE5B,wCAAwC;AACxC,MAAM,OAAO,GAAyD;IACrE,CAAC,WAAW,EAAE,IAAI,CAAC;IACnB,CAAC,WAAW,EAAE,QAAQ,CAAC;IACvB,CAAC,gBAAgB,EAAE,aAAa,CAAC;IACjC,CAAC,kBAAkB,EAAE,eAAe,CAAC;IACrC,CAAC,sBAAsB,EAAE,mBAAmB,CAAC;CAC7C,CAA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MAAM,OAAO,GAAkC,YAAY,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,CAAC;SAChF,KAAK,CAAC,GAAyB,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC;SACjF,OAAO,CAAC,GAAG,EAAE;QACb,IAAI,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,OAAO;YAAE,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACzE,CAAC,CAAC,CAAC;IACJ,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IACnC,OAAO,OAAO,CAAC;AAChB,CAAC","sourcesContent":["import { VERSION } from \"../config.ts\";\nimport { getPiUserAgent } from \"../utils/pi-user-agent.ts\";\nimport type { OAuthAccount } from \"./oauth-account-pool.ts\";\n\n/**\n * Live Claude subscription limits from Anthropic's subscription usage endpoint, which Claude Code reads with its OAuth\n * token. The endpoint is undocumented: every field is parsed defensively and unknown keys are ignored.\n */\nexport const ANTHROPIC_USAGE_URL = \"https://api.anthropic.com/api/oauth/usage\";\nexport const ANTHROPIC_USAGE_PROVIDER_ID = \"anthropic\";\n\nconst SUCCESS_TTL_MS = 60_000;\nconst DEFAULT_RETRY_AFTER_MS = 5 * 60_000;\nconst MAX_RETRY_AFTER_MS = 30 * 60_000;\nconst MAX_CACHE_ENTRIES = 32;\nconst MAX_RESET_LENGTH = 64;\n\n/** Percent buckets in display order. */\nconst BUCKETS: ReadonlyArray<readonly [key: string, label: string]> = [\n\t[\"five_hour\", \"5h\"],\n\t[\"seven_day\", \"Weekly\"],\n\t[\"seven_day_opus\", \"Weekly Opus\"],\n\t[\"seven_day_sonnet\", \"Weekly Sonnet\"],\n\t[\"seven_day_oauth_apps\", \"Weekly OAuth apps\"],\n];\n\nexport interface AnthropicUsageWindow {\n\t/** Response key, e.g. \"five_hour\", \"seven_day\", \"extra_usage\". */\n\tid: string;\n\tlabel: string;\n\t/** Percent of the limit used, 0..100. */\n\tusedPercent: number;\n\t/** Epoch ms when the window resets, when reported. */\n\tresetsAt?: number;\n}\n\nexport type AnthropicUsageUnavailableReason =\n\t| \"expired_credential\"\n\t| \"unauthorized\"\n\t| \"rate_limited\"\n\t| \"http_error\"\n\t| \"timeout\"\n\t| \"network\"\n\t| \"malformed\";\n\nexport type AnthropicUsageResult =\n\t| { status: \"ok\"; windows: AnthropicUsageWindow[]; fetchedAt: number }\n\t| { status: \"unavailable\"; reason: AnthropicUsageUnavailableReason };\n\nexport interface FetchAnthropicSubscriptionUsageOptions {\n\tsignal?: AbortSignal;\n\t/** Injected for tests. Defaults to globalThis.fetch. */\n\tfetch?: typeof fetch;\n\t/** Reference time in epoch ms. Defaults to Date.now(). */\n\tnow?: number;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parsePercent(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0 ? Math.min(100, value) : undefined;\n}\n\nfunction parseResetsAt(value: unknown): number | undefined {\n\tif (typeof value !== \"string\" || value.length > MAX_RESET_LENGTH) return undefined;\n\tconst ms = Date.parse(value);\n\treturn Number.isFinite(ms) ? ms : undefined;\n}\n\n/**\n * Pure parser, exported for tests and for Claude Code's cached copy of the same response. Null, absent or malformed\n * buckets are skipped; extra usage is shown only when enabled, as a percentage (its money units are not documented).\n */\nexport function parseAnthropicSubscriptionUsage(payload: unknown): AnthropicUsageWindow[] {\n\tif (!isRecord(payload)) return [];\n\tconst windows: AnthropicUsageWindow[] = [];\n\tfor (const [key, label] of BUCKETS) {\n\t\tconst bucket = payload[key];\n\t\tif (!isRecord(bucket)) continue;\n\t\tconst usedPercent = parsePercent(bucket.utilization);\n\t\tif (usedPercent === undefined) continue;\n\t\tconst resetsAt = parseResetsAt(bucket.resets_at);\n\t\twindows.push({ id: key, label, usedPercent, ...(resetsAt !== undefined ? { resetsAt } : {}) });\n\t}\n\tconst extra = payload.extra_usage;\n\tif (isRecord(extra) && extra.is_enabled === true) {\n\t\tconst usedPercent = parsePercent(extra.utilization);\n\t\tif (usedPercent !== undefined) windows.push({ id: \"extra_usage\", label: \"Extra usage\", usedPercent });\n\t}\n\treturn windows;\n}\n\n/** Retry-After as delay seconds or an HTTP date, bounded to 1 s..30 min; 5 min when absent or invalid. */\nexport function parseRetryAfterMs(value: string | null, nowMs: number): number {\n\tif (value === null) return DEFAULT_RETRY_AFTER_MS;\n\tconst trimmed = value.trim();\n\tconst ms = /^\\d{1,10}$/.test(trimmed) ? Number(trimmed) * 1000 : Date.parse(trimmed) - nowMs;\n\tif (!Number.isFinite(ms)) return DEFAULT_RETRY_AFTER_MS;\n\treturn Math.min(MAX_RETRY_AFTER_MS, Math.max(1000, ms));\n}\n\ninterface CacheEntry {\n\tresult: AnthropicUsageResult;\n\tuntil: number;\n}\n\n// The endpoint rate-limits aggressively: successes are reused for 60 s and a 429 is remembered for its Retry-After.\nconst cache = new Map<string, CacheEntry>();\nconst inFlight = new Map<string, Promise<AnthropicUsageResult>>();\n\nfunction remember(key: string, result: AnthropicUsageResult, until: number, now: number): void {\n\tcache.delete(key);\n\tfor (const [entryKey, entry] of cache) if (entry.until <= now) cache.delete(entryKey);\n\twhile (cache.size >= MAX_CACHE_ENTRIES) {\n\t\tconst oldest = cache.keys().next().value;\n\t\tif (oldest === undefined) break;\n\t\tcache.delete(oldest);\n\t}\n\tcache.set(key, { result, until });\n}\n\n/** Forget cached results. For tests. */\nexport function clearAnthropicUsageCache(): void {\n\tcache.clear();\n\tinFlight.clear();\n}\n\nfunction isAbortError(error: unknown): boolean {\n\treturn isRecord(error) && (error.name === \"AbortError\" || error.name === \"TimeoutError\");\n}\n\nasync function requestUsage(\n\taccount: OAuthAccount,\n\toptions: FetchAnthropicSubscriptionUsageOptions,\n\tnow: number,\n): Promise<AnthropicUsageResult> {\n\tconst unavailable = (reason: AnthropicUsageUnavailableReason): AnthropicUsageResult => ({\n\t\tstatus: \"unavailable\",\n\t\treason,\n\t});\n\tlet response: Response;\n\ttry {\n\t\tconst fetcher = options.fetch ?? globalThis.fetch;\n\t\tresponse = await fetcher(ANTHROPIC_USAGE_URL, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${account.credential.access}`,\n\t\t\t\t\"anthropic-beta\": \"oauth-2025-04-20\",\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\"User-Agent\": getPiUserAgent(VERSION),\n\t\t\t},\n\t\t\t// Refusing redirects keeps the subscription token on this origin.\n\t\t\tredirect: \"error\",\n\t\t\tsignal: options.signal,\n\t\t});\n\t} catch (error) {\n\t\treturn unavailable(options.signal?.aborted || isAbortError(error) ? \"timeout\" : \"network\");\n\t}\n\n\tif (response.status === 401 || response.status === 403) return unavailable(\"unauthorized\");\n\tif (response.status === 429) {\n\t\tconst result = unavailable(\"rate_limited\");\n\t\tremember(account.key, result, now + parseRetryAfterMs(response.headers.get(\"retry-after\"), now), now);\n\t\treturn result;\n\t}\n\tif (!response.ok) return unavailable(\"http_error\");\n\n\tlet payload: unknown;\n\ttry {\n\t\tpayload = await response.json();\n\t} catch (error) {\n\t\treturn unavailable(options.signal?.aborted || isAbortError(error) ? \"timeout\" : \"malformed\");\n\t}\n\tif (!isRecord(payload)) return unavailable(\"malformed\");\n\tconst result: AnthropicUsageResult = {\n\t\tstatus: \"ok\",\n\t\twindows: parseAnthropicSubscriptionUsage(payload),\n\t\tfetchedAt: now,\n\t};\n\tremember(account.key, result, now + SUCCESS_TTL_MS, now);\n\treturn result;\n}\n\n/**\n * The subscription usage of one pooled Anthropic account. Never throws; never mutates the credential. Results are\n * cached per account key in this process, and concurrent calls for one account share one request.\n */\nexport async function fetchAnthropicSubscriptionUsage(\n\taccount: OAuthAccount,\n\toptions: FetchAnthropicSubscriptionUsageOptions = {},\n): Promise<AnthropicUsageResult> {\n\tconst now = options.now ?? Date.now();\n\tconst cached = cache.get(account.key);\n\tif (cached && cached.until > now) return cached.result;\n\tif (account.credential.expires <= now) return { status: \"unavailable\", reason: \"expired_credential\" };\n\tif (options.signal?.aborted) return { status: \"unavailable\", reason: \"timeout\" };\n\n\tconst pending = inFlight.get(account.key);\n\t// shortcut: a joined call shares the first caller's signal, so its abort cancels both; fine for one /usage popup.\n\tif (pending) return pending;\n\tconst request: Promise<AnthropicUsageResult> = requestUsage(account, options, now)\n\t\t.catch((): AnthropicUsageResult => ({ status: \"unavailable\", reason: \"network\" }))\n\t\t.finally(() => {\n\t\t\tif (inFlight.get(account.key) === request) inFlight.delete(account.key);\n\t\t});\n\tinFlight.set(account.key, request);\n\treturn request;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bash-executor.d.ts","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAMH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAOtD,MAAM,WAAW,mBAAmB;IACnC,+DAA+D;IAC/D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,mCAAmC;IACnC,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED,MAAM,WAAW,UAAU;IAC1B,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,mDAAmD;IACnD,SAAS,EAAE,OAAO,CAAC;IACnB,uCAAuC;IACvC,SAAS,EAAE,OAAO,CAAC;IACnB,yFAAyF;IACzF,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAMD;;;GAGG;AACH,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,cAAc,EAC1B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,UAAU,CAAC,CA6FrB"}
1
+ {"version":3,"file":"bash-executor.d.ts","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAOH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAOtD,MAAM,WAAW,mBAAmB;IACnC,+DAA+D;IAC/D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,mCAAmC;IACnC,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED,MAAM,WAAW,UAAU;IAC1B,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,mDAAmD;IACnD,SAAS,EAAE,OAAO,CAAC;IACnB,uCAAuC;IACvC,SAAS,EAAE,OAAO,CAAC;IACnB,yFAAyF;IACzF,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAMD;;;GAGG;AACH,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,cAAc,EAC1B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,UAAU,CAAC,CAkGrB"}
@@ -5,6 +5,7 @@
5
5
  * - AgentSession.executeBash() for interactive and RPC modes
6
6
  * - Direct calls from modes that need bash execution
7
7
  */
8
+ import { finished } from "node:stream/promises";
8
9
  import { splitIncompleteAnsiSuffix, stripAnsi } from "../utils/ansi.js";
9
10
  import { createOutputFileStream } from "../utils/output-files.js";
10
11
  import { sanitizeBinaryOutput } from "../utils/shell.js";
@@ -88,7 +89,12 @@ export async function executeBashWithOperations(command, cwd, operations, option
88
89
  if (truncationResult.truncated) {
89
90
  ensureTempFile();
90
91
  }
91
- tempFileStream?.end();
92
+ if (tempFileStream) {
93
+ // The returned path must hold the complete output, so wait for the writes to flush. A failed
94
+ // write keeps the earlier behavior: the command's output is still returned.
95
+ tempFileStream.end();
96
+ await finished(tempFileStream).catch(() => { });
97
+ }
92
98
  const cancelled = options?.signal?.aborted ?? false;
93
99
  return {
94
100
  output: truncationResult.truncated ? truncationResult.content : fullOutput,
@@ -1 +1 @@
1
- {"version":3,"file":"bash-executor.js","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAAE,yBAAyB,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAEzD,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AA0BtE,+EAA+E;AAC/E,iBAAiB;AACjB,+EAA+E;AAE/E;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC9C,OAAe,EACf,GAAW,EACX,UAA0B,EAC1B,OAA6B;IAE7B,MAAM,YAAY,GAAa,EAAE,CAAC;IAClC,IAAI,WAAW,GAAG,CAAC,CAAC;IACpB,MAAM,cAAc,GAAG,iBAAiB,GAAG,CAAC,CAAC;IAE7C,IAAI,YAAgC,CAAC;IACrC,IAAI,cAAuC,CAAC;IAC5C,IAAI,UAAU,GAAG,CAAC,CAAC;IAEnB,MAAM,cAAc,GAAG,GAAG,EAAE;QAC3B,IAAI,YAAY,EAAE,CAAC;YAClB,OAAO;QACR,CAAC;QACD,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,MAAM,EAAE,cAAc,EAAE,GAAG,sBAAsB,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC;QAC7F,KAAK,MAAM,KAAK,IAAI,YAAY,EAAE,CAAC;YAClC,cAAc,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAC7B,CAAC;IACF,CAAC,CAAC;IAEF,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,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AAY;KAC5B,CAAC;AACH,CAAC","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport type { WriteStream } from \"node:fs\";\nimport { splitIncompleteAnsiSuffix, stripAnsi } from \"../utils/ansi.ts\";\nimport { createOutputFileStream } from \"../utils/output-files.ts\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./tools/truncate.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\t({ path: tempFilePath, stream: tempFileStream } = createOutputFileStream(\"pi-bash\", \".log\"));\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\t// Unfinished escape sequence at the end of the previous chunk, completed by the next chunk.\n\tlet pendingAnsi = \"\";\n\n\tconst appendText = (rawText: string) => {\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(rawText)).replace(/\\r/g, \"\");\n\t\tif (!text) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\t\tconst { complete, pending } = splitIncompleteAnsiSuffix(pendingAnsi + decoder.decode(data, { stream: true }));\n\t\tpendingAnsi = pending;\n\t\tappendText(complete);\n\t};\n\n\tconst flushOutput = () => {\n\t\tconst rest = pendingAnsi + decoder.decode();\n\t\tpendingAnsi = \"\";\n\t\tappendText(rest);\n\t};\n\n\tlet exitCode: number | null = null;\n\ttry {\n\t\t({ exitCode } = await operations.exec(command, cwd, { onData, signal: options?.signal }));\n\t} catch (err) {\n\t\t// An aborted command still returns the output it produced so far\n\t\tif (!options?.signal?.aborted) {\n\t\t\ttempFileStream?.end();\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tflushOutput();\n\tconst fullOutput = outputChunks.join(\"\");\n\tconst truncationResult = truncateTail(fullOutput);\n\tif (truncationResult.truncated) {\n\t\tensureTempFile();\n\t}\n\ttempFileStream?.end();\n\tconst cancelled = options?.signal?.aborted ?? false;\n\n\treturn {\n\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\texitCode: cancelled ? undefined : (exitCode ?? undefined),\n\t\tcancelled,\n\t\ttruncated: truncationResult.truncated,\n\t\tfullOutputPath: tempFilePath,\n\t};\n}\n"]}
1
+ {"version":3,"file":"bash-executor.js","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,yBAAyB,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAEzD,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AA0BtE,+EAA+E;AAC/E,iBAAiB;AACjB,+EAA+E;AAE/E;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC9C,OAAe,EACf,GAAW,EACX,UAA0B,EAC1B,OAA6B;IAE7B,MAAM,YAAY,GAAa,EAAE,CAAC;IAClC,IAAI,WAAW,GAAG,CAAC,CAAC;IACpB,MAAM,cAAc,GAAG,iBAAiB,GAAG,CAAC,CAAC;IAE7C,IAAI,YAAgC,CAAC;IACrC,IAAI,cAAuC,CAAC;IAC5C,IAAI,UAAU,GAAG,CAAC,CAAC;IAEnB,MAAM,cAAc,GAAG,GAAG,EAAE;QAC3B,IAAI,YAAY,EAAE,CAAC;YAClB,OAAO;QACR,CAAC;QACD,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,MAAM,EAAE,cAAc,EAAE,GAAG,sBAAsB,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC;QAC7F,KAAK,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E,MAAM,EAAE,OAAO,IAAI,KAAK,CAAC;IAEpD,OAAO;QACN,MAAM,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU;QAC1E,QAAQ,EAAE,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,QAAQ,IAAI,SAAS,CAAC;QACzD,SAAS;QACT,SAAS,EAAE,gBAAgB,CAAC,SAAS;QACrC,cAAc,EAAE,YAAY;KAC5B,CAAC;AACH,CAAC","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport type { WriteStream } from \"node:fs\";\nimport { finished } from \"node:stream/promises\";\nimport { splitIncompleteAnsiSuffix, stripAnsi } from \"../utils/ansi.ts\";\nimport { createOutputFileStream } from \"../utils/output-files.ts\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./tools/truncate.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\t({ path: tempFilePath, stream: tempFileStream } = createOutputFileStream(\"pi-bash\", \".log\"));\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\t// Unfinished escape sequence at the end of the previous chunk, completed by the next chunk.\n\tlet pendingAnsi = \"\";\n\n\tconst appendText = (rawText: string) => {\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(rawText)).replace(/\\r/g, \"\");\n\t\tif (!text) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\t\tconst { complete, pending } = splitIncompleteAnsiSuffix(pendingAnsi + decoder.decode(data, { stream: true }));\n\t\tpendingAnsi = pending;\n\t\tappendText(complete);\n\t};\n\n\tconst flushOutput = () => {\n\t\tconst rest = pendingAnsi + decoder.decode();\n\t\tpendingAnsi = \"\";\n\t\tappendText(rest);\n\t};\n\n\tlet exitCode: number | null = null;\n\ttry {\n\t\t({ exitCode } = await operations.exec(command, cwd, { onData, signal: options?.signal }));\n\t} catch (err) {\n\t\t// An aborted command still returns the output it produced so far\n\t\tif (!options?.signal?.aborted) {\n\t\t\ttempFileStream?.end();\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tflushOutput();\n\tconst fullOutput = outputChunks.join(\"\");\n\tconst truncationResult = truncateTail(fullOutput);\n\tif (truncationResult.truncated) {\n\t\tensureTempFile();\n\t}\n\tif (tempFileStream) {\n\t\t// The returned path must hold the complete output, so wait for the writes to flush. A failed\n\t\t// write keeps the earlier behavior: the command's output is still returned.\n\t\ttempFileStream.end();\n\t\tawait finished(tempFileStream).catch(() => {});\n\t}\n\tconst cancelled = options?.signal?.aborted ?? false;\n\n\treturn {\n\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\texitCode: cancelled ? undefined : (exitCode ?? undefined),\n\t\tcancelled,\n\t\ttruncated: truncationResult.truncated,\n\t\tfullOutputPath: tempFilePath,\n\t};\n}\n"]}
@@ -0,0 +1,13 @@
1
+ import type { ClientAttribution, ClientIdentity } from "@earendil-works/pi-ai";
2
+ import type { SettingsManager } from "./settings-manager.ts";
3
+ /**
4
+ * HUMAIN Code CLI's provider attribution. The title is a stable identifier sent to providers, intentionally
5
+ * independent of the display title; `clientId` is the OpenCode client and Cloudflare `User-Agent`.
6
+ */
7
+ export declare const HUMAIN_ATTRIBUTION: ClientAttribution;
8
+ /**
9
+ * How HUMAIN Code CLI's requests identify it to providers: a detailed `User-Agent` with its name and version, and
10
+ * HUMAIN attribution as a CLI agent while install telemetry is enabled.
11
+ */
12
+ export declare function getClientIdentity(settingsManager: SettingsManager): ClientIdentity;
13
+ //# sourceMappingURL=client-identity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-identity.d.ts","sourceRoot":"","sources":["../../src/core/client-identity.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAE/E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAG7D;;;GAGG;AACH,eAAO,MAAM,kBAAkB,EAAE,iBAKhC,CAAC;AAEF;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,eAAe,EAAE,eAAe,GAAG,cAAc,CAOlF"}
@@ -0,0 +1,25 @@
1
+ import { APP_NAME, HUMAIN_TERMINAL_WEB_URL, VERSION } from "../config.js";
2
+ import { isInstallTelemetryEnabled } from "./telemetry.js";
3
+ /**
4
+ * HUMAIN Code CLI's provider attribution. The title is a stable identifier sent to providers, intentionally
5
+ * independent of the display title; `clientId` is the OpenCode client and Cloudflare `User-Agent`.
6
+ */
7
+ export const HUMAIN_ATTRIBUTION = {
8
+ name: "HUMAIN Code CLI",
9
+ url: HUMAIN_TERMINAL_WEB_URL,
10
+ categories: ["cli-agent"],
11
+ clientId: APP_NAME,
12
+ };
13
+ /**
14
+ * How HUMAIN Code CLI's requests identify it to providers: a detailed `User-Agent` with its name and version, and
15
+ * HUMAIN attribution as a CLI agent while install telemetry is enabled.
16
+ */
17
+ export function getClientIdentity(settingsManager) {
18
+ return {
19
+ userAgent: "detailed",
20
+ product: APP_NAME,
21
+ version: VERSION,
22
+ attribution: isInstallTelemetryEnabled(settingsManager) ? HUMAIN_ATTRIBUTION : null,
23
+ };
24
+ }
25
+ //# sourceMappingURL=client-identity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-identity.js","sourceRoot":"","sources":["../../src/core/client-identity.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,uBAAuB,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAE1E,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAE3D;;;GAGG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAsB;IACpD,IAAI,EAAE,iBAAiB;IACvB,GAAG,EAAE,uBAAuB;IAC5B,UAAU,EAAE,CAAC,WAAW,CAAC;IACzB,QAAQ,EAAE,QAAQ;CAClB,CAAC;AAEF;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAC,eAAgC;IACjE,OAAO;QACN,SAAS,EAAE,UAAU;QACrB,OAAO,EAAE,QAAQ;QACjB,OAAO,EAAE,OAAO;QAChB,WAAW,EAAE,yBAAyB,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,IAAI;KACnF,CAAC;AACH,CAAC","sourcesContent":["import type { ClientAttribution, ClientIdentity } from \"@earendil-works/pi-ai\";\nimport { APP_NAME, HUMAIN_TERMINAL_WEB_URL, VERSION } from \"../config.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.ts\";\n\n/**\n * HUMAIN Code CLI's provider attribution. The title is a stable identifier sent to providers, intentionally\n * independent of the display title; `clientId` is the OpenCode client and Cloudflare `User-Agent`.\n */\nexport const HUMAIN_ATTRIBUTION: ClientAttribution = {\n\tname: \"HUMAIN Code CLI\",\n\turl: HUMAIN_TERMINAL_WEB_URL,\n\tcategories: [\"cli-agent\"],\n\tclientId: APP_NAME,\n};\n\n/**\n * How HUMAIN Code CLI's requests identify it to providers: a detailed `User-Agent` with its name and version, and\n * HUMAIN attribution as a CLI agent while install telemetry is enabled.\n */\nexport function getClientIdentity(settingsManager: SettingsManager): ClientIdentity {\n\treturn {\n\t\tuserAgent: \"detailed\",\n\t\tproduct: APP_NAME,\n\t\tversion: VERSION,\n\t\tattribution: isInstallTelemetryEnabled(settingsManager) ? HUMAIN_ATTRIBUTION : null,\n\t};\n}\n"]}
@@ -31,6 +31,30 @@ export type CodexUsageResult = {
31
31
  status: "unavailable";
32
32
  reason: CodexUsageUnavailableReason;
33
33
  };
34
+ /** One reported limit window, labelled by its duration (e.g. "5h", "Weekly", "Code review Weekly"). */
35
+ export interface CodexUsageWindow {
36
+ /** Stable id from the limit group and window slot, e.g. "main-primary", "code-review-secondary", "additional-0-primary". */
37
+ id: string;
38
+ label: string;
39
+ /** Provider-reported used percentage, 0..100. */
40
+ usedPercent: number;
41
+ /** Epoch ms when the window resets, when the provider reports it. */
42
+ resetsAt?: number;
43
+ limitReached?: boolean;
44
+ }
45
+ /** Every limit window the usage route reports, plus the weekly window /accounts reads. */
46
+ export type CodexUsageDetailsResult = {
47
+ status: "ok";
48
+ /** Undefined when the provider reports no weekly window. */
49
+ usage?: CodexWeeklyUsage;
50
+ /** Main limit windows first (shortest first), then additional limits, then code review. */
51
+ windows: CodexUsageWindow[];
52
+ credits?: CodexCreditsStatus;
53
+ cooldownCleared?: boolean;
54
+ } | {
55
+ status: "unavailable";
56
+ reason: Exclude<CodexUsageUnavailableReason, "no_weekly_window">;
57
+ };
34
58
  export interface FetchCodexWeeklyUsageOptions {
35
59
  signal?: AbortSignal;
36
60
  /** Opt in to clearing an unchanged cached cooldown after explicit provider availability. Never switches accounts. */
@@ -51,11 +75,23 @@ export interface FetchCodexWeeklyUsageForAccountsOptions {
51
75
  /** Called as each account result arrives (for progressive UI updates). */
52
76
  onResult?: (accountKey: string, result: CodexUsageResult) => void;
53
77
  }
78
+ /** Label a window by its duration, not its primary/secondary slot. */
79
+ export declare function codexWindowLabel(durationSeconds: number): string;
80
+ /** Provider-supplied limit names are untrusted: keep printable characters only, collapse whitespace, bound the length. */
81
+ export declare function sanitizeCodexLimitName(value: unknown): string | undefined;
82
+ /** Pure parser, exported for tests: every well-formed limit window, malformed ones skipped. */
83
+ export declare function parseCodexUsageWindows(payload: unknown, nowMs: number): CodexUsageWindow[];
54
84
  export declare function parseCodexCredits(payload: unknown): CodexCreditsStatus | undefined;
55
85
  /** Pure parser, exported for tests. Returns undefined when no valid weekly window exists. */
56
86
  export declare function parseCodexWeeklyUsage(payload: unknown, nowMs: number): CodexWeeklyUsage | undefined;
57
87
  export declare function getCodexAvailability(usage: CodexWeeklyUsage): CodexAvailability;
58
- /** One usage lookup for one pooled account. Never throws; never mutates the credential. */
88
+ /**
89
+ * One usage lookup for one pooled account: every reported limit window, the weekly window and credits. Never throws;
90
+ * never mutates the credential. Clears a cached cooldown only with `accountPool` and a weekly window, as
91
+ * `fetchCodexWeeklyUsage` does.
92
+ */
93
+ export declare function fetchCodexUsage(account: OAuthAccount, options?: FetchCodexWeeklyUsageOptions): Promise<CodexUsageDetailsResult>;
94
+ /** The weekly window /accounts reads, from one `fetchCodexUsage` request; `no_weekly_window` when none is reported. */
59
95
  export declare function fetchCodexWeeklyUsage(account: OAuthAccount, options?: FetchCodexWeeklyUsageOptions): Promise<CodexUsageResult>;
60
96
  /** Bounded-concurrency fan-out; one failure never affects other accounts. */
61
97
  export declare function fetchCodexWeeklyUsageForAccounts(accounts: readonly OAuthAccount[], options?: FetchCodexWeeklyUsageForAccountsOptions): Promise<Map<string, CodexUsageResult>>;
@@ -1 +1 @@
1
- {"version":3,"file":"codex-usage.d.ts","sourceRoot":"","sources":["../../src/core/codex-usage.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,gBAAgB,EAAqC,MAAM,yBAAyB,CAAC;AAEtH,eAAO,MAAM,eAAe,+CAA+C,CAAC;AAC5E,eAAO,MAAM,uBAAuB,iBAAiB,CAAC;AAUtD,MAAM,WAAW,kBAAkB;IAClC,UAAU,EAAE,OAAO,CAAC;IACpB,SAAS,EAAE,OAAO,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,KAAK,iBAAiB,GAAG,SAAS,GAAG,SAAS,GAAG,SAAS,CAAC;AAE3D,MAAM,WAAW,gBAAgB;IAChC,2EAA2E;IAC3E,gBAAgB,EAAE,MAAM,CAAC;IACzB,4EAA4E;IAC5E,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,gGAAgG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GACxC,OAAO,CAAC,gBAAgB,CAAC,CAO3B;AAED,6EAA6E;AAC7E,wBAAsB,gCAAgC,CACrD,QAAQ,EAAE,SAAS,YAAY,EAAE,EACjC,OAAO,GAAE,uCAA4C,GACnD,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAoCxC"}
@@ -10,18 +10,20 @@ const DEFAULT_CONCURRENCY = 3;
10
10
  const MAX_TIMEOUT_MS = 2 ** 31 - 1;
11
11
  const BALANCE_PATTERN = /^-?\d{1,15}(\.\d{1,8})?$/;
12
12
  const REACHED_TYPE_PATTERN = /^[a-z0-9_]{1,64}$/;
13
+ const MAX_LIMIT_NAME_LENGTH = 40;
14
+ const MAX_ADDITIONAL_LIMITS = 16;
13
15
  function isRecord(value) {
14
16
  return typeof value === "object" && value !== null && !Array.isArray(value);
15
17
  }
16
- function parseWeeklyWindow(value, nowMs) {
18
+ /** A well-formed window of any duration, or undefined. */
19
+ function parseWindow(value, nowMs) {
17
20
  if (!isRecord(value))
18
21
  return undefined;
19
22
  const duration = value.limit_window_seconds;
20
23
  const usedPercent = value.used_percent;
21
24
  if (typeof duration !== "number" ||
22
25
  !Number.isFinite(duration) ||
23
- duration < MIN_WEEK_SECONDS ||
24
- duration > MAX_WEEK_SECONDS ||
26
+ duration <= 0 ||
25
27
  typeof usedPercent !== "number" ||
26
28
  !Number.isFinite(usedPercent) ||
27
29
  usedPercent < 0 ||
@@ -35,7 +37,75 @@ function parseWeeklyWindow(value, nowMs) {
35
37
  : typeof resetAfterSeconds === "number" && Number.isFinite(resetAfterSeconds) && resetAfterSeconds >= 0
36
38
  ? nowMs + resetAfterSeconds * 1000
37
39
  : undefined;
38
- return { remainingPercent: Math.max(0, Math.min(100, 100 - usedPercent)), resetsAt };
40
+ return { durationSeconds: duration, usedPercent, resetsAt };
41
+ }
42
+ function parseWeeklyWindow(value, nowMs) {
43
+ const window = parseWindow(value, nowMs);
44
+ if (!window || window.durationSeconds < MIN_WEEK_SECONDS || window.durationSeconds > MAX_WEEK_SECONDS)
45
+ return undefined;
46
+ return { remainingPercent: Math.max(0, Math.min(100, 100 - window.usedPercent)), resetsAt: window.resetsAt };
47
+ }
48
+ /** Label a window by its duration, not its primary/secondary slot. */
49
+ export function codexWindowLabel(durationSeconds) {
50
+ const hours = durationSeconds / 3600;
51
+ if (durationSeconds < 3600)
52
+ return `${Math.max(1, Math.round(durationSeconds / 60))}m`;
53
+ if (durationSeconds <= 6 * 3600)
54
+ return hours >= 4.5 && hours <= 5.5 ? "5h" : `${Math.round(hours)}h`;
55
+ if (durationSeconds >= MIN_WEEK_SECONDS && durationSeconds <= MAX_WEEK_SECONDS)
56
+ return "Weekly";
57
+ return hours < 48 ? `${Math.round(hours)}h` : `${Math.round(hours / 24)}d`;
58
+ }
59
+ /** Provider-supplied limit names are untrusted: keep printable characters only, collapse whitespace, bound the length. */
60
+ export function sanitizeCodexLimitName(value) {
61
+ if (typeof value !== "string")
62
+ return undefined;
63
+ const printable = value
64
+ .slice(0, 256)
65
+ .replace(/[^\p{L}\p{M}\p{N}\p{P}\p{S} ]+/gu, " ")
66
+ .replace(/\s+/g, " ")
67
+ .trim();
68
+ const bounded = Array.from(printable).slice(0, MAX_LIMIT_NAME_LENGTH).join("").trim();
69
+ return bounded || undefined;
70
+ }
71
+ function limitWindows(limit, idPrefix, labelPrefix, nowMs) {
72
+ if (!isRecord(limit))
73
+ return [];
74
+ const parsed = ["primary", "secondary"]
75
+ .map((slot) => ({ slot, window: parseWindow(limit[`${slot}_window`], nowMs) }))
76
+ .filter((entry) => entry.window !== undefined)
77
+ .sort((a, b) => a.window.durationSeconds - b.window.durationSeconds);
78
+ const groupReached = limit.allowed === false || limit.limit_reached === true;
79
+ // A reached group without an exhausted window is attributed to its most-used window.
80
+ const mostUsed = parsed.reduce((max, { window }) => (max === undefined || window.usedPercent > max.usedPercent ? window : max), undefined);
81
+ const anyExhausted = parsed.some(({ window }) => window.usedPercent >= 100);
82
+ return parsed.map(({ slot, window }) => {
83
+ const label = codexWindowLabel(window.durationSeconds);
84
+ const limitReached = window.usedPercent >= 100 || (groupReached && !anyExhausted && window === mostUsed);
85
+ return {
86
+ id: `${idPrefix}-${slot}`,
87
+ label: labelPrefix ? `${labelPrefix} ${label}` : label,
88
+ usedPercent: window.usedPercent,
89
+ ...(window.resetsAt !== undefined ? { resetsAt: window.resetsAt } : {}),
90
+ ...(limitReached ? { limitReached } : {}),
91
+ };
92
+ });
93
+ }
94
+ /** Pure parser, exported for tests: every well-formed limit window, malformed ones skipped. */
95
+ export function parseCodexUsageWindows(payload, nowMs) {
96
+ if (!isRecord(payload))
97
+ return [];
98
+ const windows = limitWindows(payload.rate_limit, "main", "", nowMs);
99
+ if (Array.isArray(payload.additional_rate_limits)) {
100
+ payload.additional_rate_limits.slice(0, MAX_ADDITIONAL_LIMITS).forEach((entry, index) => {
101
+ if (!isRecord(entry))
102
+ return;
103
+ const name = sanitizeCodexLimitName(entry.limit_name) ?? sanitizeCodexLimitName(entry.metered_feature) ?? "Additional";
104
+ windows.push(...limitWindows(entry.rate_limit, `additional-${index}`, name, nowMs));
105
+ });
106
+ }
107
+ windows.push(...limitWindows(payload.code_review_rate_limit, "code-review", "Code review", nowMs));
108
+ return windows;
39
109
  }
40
110
  export function parseCodexCredits(payload) {
41
111
  if (!isRecord(payload) || !isRecord(payload.credits))
@@ -140,8 +210,12 @@ function reportedAvailability(payload) {
140
210
  }
141
211
  return unknown ? "unknown" : "allowed";
142
212
  }
143
- /** One usage lookup for one pooled account. Never throws; never mutates the credential. */
144
- export async function fetchCodexWeeklyUsage(account, options = {}) {
213
+ /**
214
+ * One usage lookup for one pooled account: every reported limit window, the weekly window and credits. Never throws;
215
+ * never mutates the credential. Clears a cached cooldown only with `accountPool` and a weekly window, as
216
+ * `fetchCodexWeeklyUsage` does.
217
+ */
218
+ export async function fetchCodexUsage(account, options = {}) {
145
219
  const now = options.now ?? Date.now();
146
220
  if (account.credential.expires <= now)
147
221
  return unavailable("expired_credential");
@@ -186,19 +260,38 @@ export async function fetchCodexWeeklyUsage(account, options = {}) {
186
260
  if (!isRecord(payload))
187
261
  return unavailable("malformed");
188
262
  const usage = parseCodexWeeklyUsage(payload, now);
189
- if (!usage)
190
- return unavailable("no_weekly_window");
191
- if (options.accountPool && account.exhaustedUntil !== undefined && getCodexAvailability(usage) === "allowed") {
263
+ const credits = parseCodexCredits(payload);
264
+ const details = {
265
+ status: "ok",
266
+ ...(usage ? { usage } : {}),
267
+ windows: parseCodexUsageWindows(payload, now),
268
+ ...(credits ? { credits } : {}),
269
+ };
270
+ if (usage &&
271
+ options.accountPool &&
272
+ account.exhaustedUntil !== undefined &&
273
+ getCodexAvailability(usage) === "allowed") {
192
274
  try {
193
275
  if (await options.accountPool.clearExhaustion(CODEX_USAGE_PROVIDER_ID, account, { signal: options.signal })) {
194
- return { status: "ok", usage, cooldownCleared: true };
276
+ return { ...details, cooldownCleared: true };
195
277
  }
196
278
  }
197
279
  catch {
198
280
  // A cancelled or failed pool write must not hide real usage or claim the cached cooldown was cleared.
199
281
  }
200
282
  }
201
- return { status: "ok", usage };
283
+ return details;
284
+ }
285
+ /** The weekly window /accounts reads, from one `fetchCodexUsage` request; `no_weekly_window` when none is reported. */
286
+ export async function fetchCodexWeeklyUsage(account, options = {}) {
287
+ const result = await fetchCodexUsage(account, options);
288
+ if (result.status === "unavailable")
289
+ return result;
290
+ if (!result.usage)
291
+ return unavailable("no_weekly_window");
292
+ return result.cooldownCleared
293
+ ? { status: "ok", usage: result.usage, cooldownCleared: true }
294
+ : { status: "ok", usage: result.usage };
202
295
  }
203
296
  /** Bounded-concurrency fan-out; one failure never affects other accounts. */
204
297
  export async function fetchCodexWeeklyUsageForAccounts(accounts, options = {}) {