@humain/humain-code 0.5.3 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (696) hide show
  1. package/CHANGELOG.md +180 -0
  2. package/README.md +2 -2
  3. package/dist/bundle/agent-monitor.js +1 -1
  4. package/dist/bundle/chunks/anthropic-messages-FGFIMZUF.js +66 -0
  5. package/dist/bundle/chunks/azure-openai-responses-6JNTC7KO.js +15 -0
  6. package/dist/bundle/chunks/bedrock-converse-stream.js +261 -237
  7. package/dist/bundle/chunks/chunk-2H3LUS62.js +1966 -0
  8. package/dist/bundle/chunks/{chunk-GEISZXXH.js → chunk-4ZBGTJJM.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-QWXPGBAG.js → chunk-5JSLXC2A.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-L2VKM23Q.js → chunk-6DE7LJKV.js} +21 -21
  11. package/dist/bundle/chunks/{chunk-V62QBESW.js → chunk-6E6RHNOU.js} +11 -10
  12. package/dist/bundle/chunks/chunk-7RZ5BS7U.js +2 -0
  13. package/dist/bundle/chunks/chunk-AHSNQWZU.js +24 -0
  14. package/dist/bundle/chunks/{chunk-UJLCKIMZ.js → chunk-AOH2O5CP.js} +3469 -3133
  15. package/dist/bundle/chunks/{chunk-ODJUBJK2.js → chunk-B7NJMF7B.js} +11 -11
  16. package/dist/bundle/chunks/chunk-BQ3TMEWD.js +7 -0
  17. package/dist/bundle/chunks/{chunk-KKCMWB63.js → chunk-C6VERWRZ.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-CN3Q5UNB.js → chunk-CFHOPLW5.js} +658 -574
  19. package/dist/bundle/chunks/chunk-CVC2GV26.js +1986 -0
  20. package/dist/bundle/chunks/{chunk-DU6POZ7E.js → chunk-DHW3REC5.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-UTNHGOFS.js → chunk-EDONIPUJ.js} +38 -38
  22. package/dist/bundle/chunks/{chunk-FO2NYB6O.js → chunk-FDGW5ZTG.js} +1147 -1110
  23. package/dist/bundle/chunks/{chunk-XQX7S3GM.js → chunk-GICL5V54.js} +1 -1
  24. package/dist/bundle/chunks/chunk-H7Y4QY7K.js +11 -0
  25. package/dist/bundle/chunks/chunk-HW6HMUXS.js +188 -0
  26. package/dist/bundle/chunks/chunk-I6AQOITY.js +53 -0
  27. package/dist/bundle/chunks/{chunk-ZI7TK7HM.js → chunk-IADQJFNH.js} +21 -17
  28. package/dist/bundle/chunks/chunk-J7AP2BUJ.js +3 -0
  29. package/dist/bundle/chunks/chunk-JFE52VSN.js +120 -0
  30. package/dist/bundle/chunks/{chunk-MIJHJNNQ.js → chunk-LDGCU6PD.js} +127 -3
  31. package/dist/bundle/chunks/{chunk-PS7DGA7B.js → chunk-M4CHQBAI.js} +1 -1
  32. package/dist/bundle/chunks/{chunk-YDBNMIA3.js → chunk-NN53K2QQ.js} +19 -1
  33. package/dist/bundle/chunks/{chunk-RTXDU3AA.js → chunk-ONR6Q3II.js} +255 -195
  34. package/dist/bundle/chunks/{chunk-Y3OPKKDR.js → chunk-P4P7OZ7R.js} +34 -32
  35. package/dist/bundle/chunks/{chunk-OZNC2W4B.js → chunk-PCTLFSQG.js} +444 -411
  36. package/dist/bundle/chunks/{chunk-YFBDR4IW.js → chunk-PNGNZXOI.js} +3 -3
  37. package/dist/bundle/chunks/{chunk-UDB6NI4G.js → chunk-RGUZULEE.js} +593 -481
  38. package/dist/bundle/chunks/chunk-RO5YPAJH.js +23 -0
  39. package/dist/bundle/chunks/{chunk-A6B2QMA7.js → chunk-RU7ADKA7.js} +176 -162
  40. package/dist/bundle/chunks/{chunk-JCXXRCP6.js → chunk-T3KDZFM4.js} +16 -16
  41. package/dist/bundle/chunks/{chunk-HT5YN3LX.js → chunk-TEOMXMW6.js} +3 -3
  42. package/dist/bundle/chunks/{chunk-HIZWUSPN.js → chunk-VEGJT52D.js} +77 -77
  43. package/dist/bundle/chunks/{chunk-IDU5BNNI.js → chunk-XMZGB3H4.js} +12 -3
  44. package/dist/bundle/chunks/chunk-YEPHPMQC.js +647 -0
  45. package/dist/bundle/chunks/{chunk-XA7CJAYH.js → chunk-YRUIJ5AH.js} +48 -42
  46. package/dist/bundle/chunks/{cli-ENEFJH2B.js → cli-BNCWK54K.js} +21 -17
  47. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-T7TPP7SQ.js → cloudflare-workers-ai-system-one-KI6W3USX.js} +1 -1
  48. package/dist/bundle/chunks/codemode-worker.js +81 -75
  49. package/dist/bundle/chunks/compat-I5VPOXFT.js +13 -0
  50. package/dist/bundle/chunks/dist-J5IUPLMH.js +37 -0
  51. package/dist/bundle/chunks/{dist-RKNCFFGM.js → dist-SKBR3C7C.js} +720 -696
  52. package/dist/bundle/chunks/dist-TVRQXUY6.js +8 -0
  53. package/dist/bundle/chunks/{dist-cjs-HTASUQXQ.js → dist-cjs-2SKN226B.js} +77 -77
  54. package/dist/bundle/chunks/{easter-egg-3d-YOPLCOVW.js → easter-egg-3d-673VRP6Y.js} +1 -1
  55. package/dist/bundle/chunks/{esm-R6HJ4QEG.js → esm-WPALMLUO.js} +3 -3
  56. package/dist/bundle/chunks/{event-streams-BR2IL6C5.js → event-streams-7YGFEPBZ.js} +1 -1
  57. package/dist/bundle/chunks/{execute-2JXEKQ2X.js → execute-PIUR5MUV.js} +23 -23
  58. package/dist/bundle/chunks/{extract-OTCGZGTL.js → extract-4O5Z5725.js} +74 -71
  59. package/dist/bundle/chunks/github-copilot.js +50 -51
  60. package/dist/bundle/chunks/google-generative-ai-635YZEHN.js +22 -0
  61. package/dist/bundle/chunks/google-vertex-I3ZJ3SB2.js +26 -0
  62. package/dist/bundle/chunks/host-OQOEIWHK.js +2 -0
  63. package/dist/bundle/chunks/image-resize-worker.js +3 -2
  64. package/dist/bundle/chunks/kimi-coding.js +13 -14
  65. package/dist/bundle/chunks/{llama-cpp-classify-B3G57LVR.js → llama-cpp-classify-PP63BYDF.js} +1 -1
  66. package/dist/bundle/chunks/meta.js +10 -10
  67. package/dist/bundle/chunks/mistral-conversations-OKG5GKXR.js +42 -0
  68. package/dist/bundle/chunks/{node-VSA4ZN7D.js → node-UGQUSQE6.js} +1 -1
  69. package/dist/bundle/chunks/{node-SJPZTR4K.js → node-UNHECG4X.js} +168 -157
  70. package/dist/bundle/chunks/openai-codex-responses-6JYZIFT4.js +100 -0
  71. package/dist/bundle/chunks/openai-completions-YBNI6CAP.js +82 -0
  72. package/dist/bundle/chunks/{openai-decisions-WOWUC65P.js → openai-decisions-5G5YBFRQ.js} +1 -1
  73. package/dist/bundle/chunks/openai-responses-C3APJ6MK.js +27 -0
  74. package/dist/bundle/chunks/{openrouter-images-5K47HDAT.js → openrouter-images-FCJT7C7I.js} +2 -2
  75. package/dist/bundle/chunks/{pdfjs-EK6K7CXX.js → pdfjs-AKD6EBKN.js} +196 -175
  76. package/dist/bundle/chunks/pdfjs-decoders-OFXX4HDZ.js +2 -0
  77. package/dist/bundle/chunks/pdfjs-jbig2-TXR26KRI.js +278 -0
  78. package/dist/bundle/chunks/pdfjs-jbig2_nowasm_fallback-FH3KJM4H.js +326 -0
  79. package/dist/bundle/chunks/pdfjs-openjpeg-SKR7C34X.js +671 -0
  80. package/dist/bundle/chunks/pdfjs-openjpeg_nowasm_fallback-VUBL7UEE.js +974 -0
  81. package/dist/bundle/chunks/pi-messages-UHYZYEOC.js +25 -0
  82. package/dist/bundle/chunks/radius.js +8 -8
  83. package/dist/bundle/chunks/{runtime-K3F2QDQP.js → runtime-KE3HDSRT.js} +1 -1
  84. package/dist/bundle/chunks/{turndown.cjs-U7XOXH4O.js → turndown.cjs-WKGZX7NZ.js} +1 -1
  85. package/dist/bundle/chunks/{typesafe-system-one-43OCHGKP.js → typesafe-system-one-VYVAMWQV.js} +1 -1
  86. package/dist/bundle/chunks/{undici-EK3EUI2E.js → undici-C6S56CGI.js} +1 -1
  87. package/dist/bundle/chunks/virtual-modules-KDUZIB3W.js +23 -0
  88. package/dist/bundle/cli-runtime.js +3 -3
  89. package/dist/bundle/flow/package.json +5 -5
  90. package/dist/bundle/index.js +10 -10
  91. package/dist/bundle/rpc-entry.js +3 -3
  92. package/dist/cli/args.d.ts.map +1 -1
  93. package/dist/cli/args.js +9 -8
  94. package/dist/cli/args.js.map +1 -1
  95. package/dist/config.d.ts +12 -0
  96. package/dist/config.d.ts.map +1 -1
  97. package/dist/config.js +29 -5
  98. package/dist/config.js.map +1 -1
  99. package/dist/coordination/adapter/tool.d.ts +8 -5
  100. package/dist/coordination/adapter/tool.d.ts.map +1 -1
  101. package/dist/coordination/adapter/tool.js +32 -6
  102. package/dist/coordination/adapter/tool.js.map +1 -1
  103. package/dist/coordination/client/client.d.ts.map +1 -1
  104. package/dist/coordination/client/client.js +19 -1
  105. package/dist/coordination/client/client.js.map +1 -1
  106. package/dist/core/agent-session-runtime.js +3 -3
  107. package/dist/core/agent-session-runtime.js.map +1 -1
  108. package/dist/core/agent-session.d.ts +23 -3
  109. package/dist/core/agent-session.d.ts.map +1 -1
  110. package/dist/core/agent-session.js +142 -39
  111. package/dist/core/agent-session.js.map +1 -1
  112. package/dist/core/anthropic-subscription-usage.d.ts +4 -0
  113. package/dist/core/anthropic-subscription-usage.d.ts.map +1 -1
  114. package/dist/core/anthropic-subscription-usage.js +71 -1
  115. package/dist/core/anthropic-subscription-usage.js.map +1 -1
  116. package/dist/core/bug-report.d.ts +4 -4
  117. package/dist/core/codex-reset.d.ts +45 -0
  118. package/dist/core/codex-reset.d.ts.map +1 -0
  119. package/dist/core/codex-reset.js +190 -0
  120. package/dist/core/codex-reset.js.map +1 -0
  121. package/dist/core/codex-usage.d.ts +4 -2
  122. package/dist/core/codex-usage.d.ts.map +1 -1
  123. package/dist/core/codex-usage.js +9 -4
  124. package/dist/core/codex-usage.js.map +1 -1
  125. package/dist/core/compaction/branch-summarization.d.ts +3 -1
  126. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  127. package/dist/core/compaction/branch-summarization.js +25 -10
  128. package/dist/core/compaction/branch-summarization.js.map +1 -1
  129. package/dist/core/compaction/compaction.d.ts +37 -3
  130. package/dist/core/compaction/compaction.d.ts.map +1 -1
  131. package/dist/core/compaction/compaction.js +274 -65
  132. package/dist/core/compaction/compaction.js.map +1 -1
  133. package/dist/core/compaction/utils.d.ts +19 -6
  134. package/dist/core/compaction/utils.d.ts.map +1 -1
  135. package/dist/core/compaction/utils.js +49 -11
  136. package/dist/core/compaction/utils.js.map +1 -1
  137. package/dist/core/exec.d.ts +9 -1
  138. package/dist/core/exec.d.ts.map +1 -1
  139. package/dist/core/exec.js +105 -61
  140. package/dist/core/exec.js.map +1 -1
  141. package/dist/core/export-html/template.css +9 -0
  142. package/dist/core/export-html/template.html +2 -0
  143. package/dist/core/export-html/template.js +200 -62
  144. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  145. package/dist/core/export-html/tool-renderer.js +3 -0
  146. package/dist/core/export-html/tool-renderer.js.map +1 -1
  147. package/dist/core/extensions/index.d.ts +1 -1
  148. package/dist/core/extensions/index.d.ts.map +1 -1
  149. package/dist/core/extensions/index.js.map +1 -1
  150. package/dist/core/extensions/loader.d.ts.map +1 -1
  151. package/dist/core/extensions/loader.js +7 -6
  152. package/dist/core/extensions/loader.js.map +1 -1
  153. package/dist/core/extensions/pi-ai-extension-view.d.ts +19 -0
  154. package/dist/core/extensions/pi-ai-extension-view.d.ts.map +1 -0
  155. package/dist/core/extensions/pi-ai-extension-view.js +22 -0
  156. package/dist/core/extensions/pi-ai-extension-view.js.map +1 -0
  157. package/dist/core/extensions/types.d.ts +27 -4
  158. package/dist/core/extensions/types.d.ts.map +1 -1
  159. package/dist/core/extensions/types.js.map +1 -1
  160. package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
  161. package/dist/core/extensions/virtual-modules.js +8 -7
  162. package/dist/core/extensions/virtual-modules.js.map +1 -1
  163. package/dist/core/http-dispatcher.d.ts +7 -0
  164. package/dist/core/http-dispatcher.d.ts.map +1 -1
  165. package/dist/core/http-dispatcher.js +107 -0
  166. package/dist/core/http-dispatcher.js.map +1 -1
  167. package/dist/core/keybindings.d.ts +56 -0
  168. package/dist/core/keybindings.d.ts.map +1 -1
  169. package/dist/core/keybindings.js +14 -2
  170. package/dist/core/keybindings.js.map +1 -1
  171. package/dist/core/mcp-servers.d.ts +9 -4
  172. package/dist/core/mcp-servers.d.ts.map +1 -1
  173. package/dist/core/mcp-servers.js +15 -5
  174. package/dist/core/mcp-servers.js.map +1 -1
  175. package/dist/core/model-config.d.ts +1691 -2042
  176. package/dist/core/model-config.d.ts.map +1 -1
  177. package/dist/core/model-config.js +2 -3
  178. package/dist/core/model-config.js.map +1 -1
  179. package/dist/core/model-registry.d.ts +35 -4
  180. package/dist/core/model-registry.d.ts.map +1 -1
  181. package/dist/core/model-registry.js +70 -8
  182. package/dist/core/model-registry.js.map +1 -1
  183. package/dist/core/model-resolver.d.ts.map +1 -1
  184. package/dist/core/model-resolver.js +16 -10
  185. package/dist/core/model-resolver.js.map +1 -1
  186. package/dist/core/model-runtime.d.ts.map +1 -1
  187. package/dist/core/model-runtime.js +21 -17
  188. package/dist/core/model-runtime.js.map +1 -1
  189. package/dist/core/package-manager.d.ts +29 -0
  190. package/dist/core/package-manager.d.ts.map +1 -1
  191. package/dist/core/package-manager.js +311 -60
  192. package/dist/core/package-manager.js.map +1 -1
  193. package/dist/core/pi-ai-schemas.d.ts +164 -0
  194. package/dist/core/pi-ai-schemas.d.ts.map +1 -0
  195. package/dist/core/pi-ai-schemas.js +21 -0
  196. package/dist/core/pi-ai-schemas.js.map +1 -0
  197. package/dist/core/pi-manifest.d.ts +1 -0
  198. package/dist/core/pi-manifest.d.ts.map +1 -1
  199. package/dist/core/pi-manifest.js +4 -0
  200. package/dist/core/pi-manifest.js.map +1 -1
  201. package/dist/core/project-trust.js +1 -1
  202. package/dist/core/project-trust.js.map +1 -1
  203. package/dist/core/resource-loader.d.ts +4 -1
  204. package/dist/core/resource-loader.d.ts.map +1 -1
  205. package/dist/core/resource-loader.js +38 -23
  206. package/dist/core/resource-loader.js.map +1 -1
  207. package/dist/core/sdk.d.ts.map +1 -1
  208. package/dist/core/sdk.js +4 -1
  209. package/dist/core/sdk.js.map +1 -1
  210. package/dist/core/session-manager.d.ts +7 -0
  211. package/dist/core/session-manager.d.ts.map +1 -1
  212. package/dist/core/session-manager.js +66 -26
  213. package/dist/core/session-manager.js.map +1 -1
  214. package/dist/core/settings-defaults.d.ts +2 -0
  215. package/dist/core/settings-defaults.d.ts.map +1 -1
  216. package/dist/core/settings-defaults.js +2 -0
  217. package/dist/core/settings-defaults.js.map +1 -1
  218. package/dist/core/settings-manager.d.ts +19 -8
  219. package/dist/core/settings-manager.d.ts.map +1 -1
  220. package/dist/core/settings-manager.js +70 -16
  221. package/dist/core/settings-manager.js.map +1 -1
  222. package/dist/core/settings-schema.d.ts +15 -2
  223. package/dist/core/settings-schema.d.ts.map +1 -1
  224. package/dist/core/settings-schema.js +37 -3
  225. package/dist/core/settings-schema.js.map +1 -1
  226. package/dist/core/skills.d.ts.map +1 -1
  227. package/dist/core/skills.js +6 -14
  228. package/dist/core/skills.js.map +1 -1
  229. package/dist/core/slash-commands.js +2 -2
  230. package/dist/core/slash-commands.js.map +1 -1
  231. package/dist/core/source-info.d.ts +9 -0
  232. package/dist/core/source-info.d.ts.map +1 -1
  233. package/dist/core/source-info.js +13 -0
  234. package/dist/core/source-info.js.map +1 -1
  235. package/dist/core/subscription-credits.d.ts +14 -0
  236. package/dist/core/subscription-credits.d.ts.map +1 -0
  237. package/dist/core/subscription-credits.js +10 -0
  238. package/dist/core/subscription-credits.js.map +1 -0
  239. package/dist/core/subscription-reset-status.d.ts +10 -0
  240. package/dist/core/subscription-reset-status.d.ts.map +1 -0
  241. package/dist/core/subscription-reset-status.js +2 -0
  242. package/dist/core/subscription-reset-status.js.map +1 -0
  243. package/dist/core/system-prompt.d.ts.map +1 -1
  244. package/dist/core/system-prompt.js +5 -6
  245. package/dist/core/system-prompt.js.map +1 -1
  246. package/dist/core/tools/bash.d.ts +2 -2
  247. package/dist/core/tools/bash.d.ts.map +1 -1
  248. package/dist/core/tools/bash.js.map +1 -1
  249. package/dist/core/tools/edit.d.ts +3 -3
  250. package/dist/core/tools/edit.d.ts.map +1 -1
  251. package/dist/core/tools/edit.js +2 -4
  252. package/dist/core/tools/edit.js.map +1 -1
  253. package/dist/core/tools/find.d.ts +2 -2
  254. package/dist/core/tools/find.d.ts.map +1 -1
  255. package/dist/core/tools/find.js.map +1 -1
  256. package/dist/core/tools/grep.d.ts +2 -2
  257. package/dist/core/tools/grep.d.ts.map +1 -1
  258. package/dist/core/tools/grep.js +7 -3
  259. package/dist/core/tools/grep.js.map +1 -1
  260. package/dist/core/tools/ls.d.ts +2 -2
  261. package/dist/core/tools/ls.d.ts.map +1 -1
  262. package/dist/core/tools/ls.js.map +1 -1
  263. package/dist/core/tools/read.d.ts +2 -2
  264. package/dist/core/tools/read.d.ts.map +1 -1
  265. package/dist/core/tools/read.js.map +1 -1
  266. package/dist/core/tools/render-utils.d.ts +4 -0
  267. package/dist/core/tools/render-utils.d.ts.map +1 -1
  268. package/dist/core/tools/render-utils.js +42 -12
  269. package/dist/core/tools/render-utils.js.map +1 -1
  270. package/dist/core/tools/renderers/edit.d.ts.map +1 -1
  271. package/dist/core/tools/renderers/edit.js +3 -3
  272. package/dist/core/tools/renderers/edit.js.map +1 -1
  273. package/dist/core/tools/renderers/write.d.ts.map +1 -1
  274. package/dist/core/tools/renderers/write.js +37 -29
  275. package/dist/core/tools/renderers/write.js.map +1 -1
  276. package/dist/core/tools/subagent.d.ts +9 -8
  277. package/dist/core/tools/subagent.d.ts.map +1 -1
  278. package/dist/core/tools/subagent.js +8 -5
  279. package/dist/core/tools/subagent.js.map +1 -1
  280. package/dist/core/tools/tool-definition-wrapper.d.ts +11 -1
  281. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  282. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  283. package/dist/core/tools/write.d.ts +2 -2
  284. package/dist/core/tools/write.d.ts.map +1 -1
  285. package/dist/core/tools/write.js.map +1 -1
  286. package/dist/core/trust-manager.d.ts.map +1 -1
  287. package/dist/core/trust-manager.js +14 -8
  288. package/dist/core/trust-manager.js.map +1 -1
  289. package/dist/core/usage-totals.d.ts.map +1 -1
  290. package/dist/core/usage-totals.js +2 -0
  291. package/dist/core/usage-totals.js.map +1 -1
  292. package/dist/extensions/codemode/renderer.d.ts.map +1 -1
  293. package/dist/extensions/codemode/renderer.js +17 -9
  294. package/dist/extensions/codemode/renderer.js.map +1 -1
  295. package/dist/extensions/codemode/tool.d.ts +2 -1
  296. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  297. package/dist/extensions/codemode/tool.js +33 -8
  298. package/dist/extensions/codemode/tool.js.map +1 -1
  299. package/dist/extensions/llama/ui.d.ts.map +1 -1
  300. package/dist/extensions/llama/ui.js +16 -4
  301. package/dist/extensions/llama/ui.js.map +1 -1
  302. package/dist/extensions/mcp/cli.d.ts.map +1 -1
  303. package/dist/extensions/mcp/cli.js +34 -8
  304. package/dist/extensions/mcp/cli.js.map +1 -1
  305. package/dist/extensions/mcp/index.js +4 -3
  306. package/dist/extensions/mcp/index.js.map +1 -1
  307. package/dist/extensions/mcp/oauth.d.ts +1 -1
  308. package/dist/extensions/mcp/oauth.d.ts.map +1 -1
  309. package/dist/extensions/mcp/oauth.js +7 -3
  310. package/dist/extensions/mcp/oauth.js.map +1 -1
  311. package/dist/extensions/mcp/ui.d.ts +1 -0
  312. package/dist/extensions/mcp/ui.d.ts.map +1 -1
  313. package/dist/extensions/mcp/ui.js +56 -28
  314. package/dist/extensions/mcp/ui.js.map +1 -1
  315. package/dist/extensions/tool-search/tool.d.ts +21 -6
  316. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  317. package/dist/extensions/tool-search/tool.js +104 -36
  318. package/dist/extensions/tool-search/tool.js.map +1 -1
  319. package/dist/extensions/usage/confirmation.d.ts +40 -0
  320. package/dist/extensions/usage/confirmation.d.ts.map +1 -0
  321. package/dist/extensions/usage/confirmation.js +198 -0
  322. package/dist/extensions/usage/confirmation.js.map +1 -0
  323. package/dist/extensions/usage/index.d.ts +4 -4
  324. package/dist/extensions/usage/index.d.ts.map +1 -1
  325. package/dist/extensions/usage/index.js +352 -33
  326. package/dist/extensions/usage/index.js.map +1 -1
  327. package/dist/extensions/usage/overview.d.ts +8 -1
  328. package/dist/extensions/usage/overview.d.ts.map +1 -1
  329. package/dist/extensions/usage/overview.js +54 -11
  330. package/dist/extensions/usage/overview.js.map +1 -1
  331. package/dist/extensions/usage/popup.d.ts +37 -6
  332. package/dist/extensions/usage/popup.d.ts.map +1 -1
  333. package/dist/extensions/usage/popup.js +396 -45
  334. package/dist/extensions/usage/popup.js.map +1 -1
  335. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +564 -130
  336. package/dist/humain/node-provider.d.ts.map +1 -1
  337. package/dist/humain/node-provider.js +1 -0
  338. package/dist/humain/node-provider.js.map +1 -1
  339. package/dist/humain/web-access/host.d.ts +2 -1
  340. package/dist/humain/web-access/host.d.ts.map +1 -1
  341. package/dist/humain/web-access/host.js +1 -1
  342. package/dist/humain/web-access/host.js.map +1 -1
  343. package/dist/humain/web-access/vendor/brave-rate-limit.d.ts +2 -0
  344. package/dist/humain/web-access/vendor/brave-rate-limit.d.ts.map +1 -1
  345. package/dist/humain/web-access/vendor/brave-rate-limit.js +2 -2
  346. package/dist/humain/web-access/vendor/brave-rate-limit.js.map +1 -1
  347. package/dist/humain/web-access/vendor/cloudflare-search.d.ts +5 -0
  348. package/dist/humain/web-access/vendor/cloudflare-search.d.ts.map +1 -0
  349. package/dist/humain/web-access/vendor/cloudflare-search.js +230 -0
  350. package/dist/humain/web-access/vendor/cloudflare-search.js.map +1 -0
  351. package/dist/humain/web-access/vendor/curator-page.d.ts.map +1 -1
  352. package/dist/humain/web-access/vendor/curator-page.js +18 -1
  353. package/dist/humain/web-access/vendor/curator-page.js.map +1 -1
  354. package/dist/humain/web-access/vendor/curator-server.d.ts.map +1 -1
  355. package/dist/humain/web-access/vendor/curator-server.js +12 -0
  356. package/dist/humain/web-access/vendor/curator-server.js.map +1 -1
  357. package/dist/humain/web-access/vendor/duckduckgo-rate-limit.d.ts +33 -0
  358. package/dist/humain/web-access/vendor/duckduckgo-rate-limit.d.ts.map +1 -0
  359. package/dist/humain/web-access/vendor/duckduckgo-rate-limit.js +84 -0
  360. package/dist/humain/web-access/vendor/duckduckgo-rate-limit.js.map +1 -0
  361. package/dist/humain/web-access/vendor/duckduckgo.d.ts +3 -0
  362. package/dist/humain/web-access/vendor/duckduckgo.d.ts.map +1 -1
  363. package/dist/humain/web-access/vendor/duckduckgo.js +54 -49
  364. package/dist/humain/web-access/vendor/duckduckgo.js.map +1 -1
  365. package/dist/humain/web-access/vendor/exa.d.ts +8 -3
  366. package/dist/humain/web-access/vendor/exa.d.ts.map +1 -1
  367. package/dist/humain/web-access/vendor/exa.js +129 -14
  368. package/dist/humain/web-access/vendor/exa.js.map +1 -1
  369. package/dist/humain/web-access/vendor/extract.d.ts +1 -1
  370. package/dist/humain/web-access/vendor/extract.d.ts.map +1 -1
  371. package/dist/humain/web-access/vendor/extract.js +68 -10
  372. package/dist/humain/web-access/vendor/extract.js.map +1 -1
  373. package/dist/humain/web-access/vendor/fetch-params.d.ts +2 -1
  374. package/dist/humain/web-access/vendor/fetch-params.d.ts.map +1 -1
  375. package/dist/humain/web-access/vendor/fetch-params.js +2 -2
  376. package/dist/humain/web-access/vendor/fetch-params.js.map +1 -1
  377. package/dist/humain/web-access/vendor/field-extract.d.ts +38 -0
  378. package/dist/humain/web-access/vendor/field-extract.d.ts.map +1 -0
  379. package/dist/humain/web-access/vendor/field-extract.js +350 -0
  380. package/dist/humain/web-access/vendor/field-extract.js.map +1 -0
  381. package/dist/humain/web-access/vendor/gemini-search.d.ts +15 -4
  382. package/dist/humain/web-access/vendor/gemini-search.d.ts.map +1 -1
  383. package/dist/humain/web-access/vendor/gemini-search.js +198 -16
  384. package/dist/humain/web-access/vendor/gemini-search.js.map +1 -1
  385. package/dist/humain/web-access/vendor/github-api.js +1 -1
  386. package/dist/humain/web-access/vendor/github-api.js.map +1 -1
  387. package/dist/humain/web-access/vendor/github-extract.d.ts.map +1 -1
  388. package/dist/humain/web-access/vendor/github-extract.js +3 -2
  389. package/dist/humain/web-access/vendor/github-extract.js.map +1 -1
  390. package/dist/humain/web-access/vendor/index.d.ts.map +1 -1
  391. package/dist/humain/web-access/vendor/index.js +137 -118
  392. package/dist/humain/web-access/vendor/index.js.map +1 -1
  393. package/dist/humain/web-access/vendor/mistral-search.js +1 -1
  394. package/dist/humain/web-access/vendor/mistral-search.js.map +1 -1
  395. package/dist/humain/web-access/vendor/ninerouter.d.ts +4 -0
  396. package/dist/humain/web-access/vendor/ninerouter.d.ts.map +1 -0
  397. package/dist/humain/web-access/vendor/ninerouter.js +110 -0
  398. package/dist/humain/web-access/vendor/ninerouter.js.map +1 -0
  399. package/dist/humain/web-access/vendor/offtopic-judge.d.ts +27 -0
  400. package/dist/humain/web-access/vendor/offtopic-judge.d.ts.map +1 -0
  401. package/dist/humain/web-access/vendor/offtopic-judge.js +61 -0
  402. package/dist/humain/web-access/vendor/offtopic-judge.js.map +1 -0
  403. package/dist/humain/web-access/vendor/openai-search.d.ts +1 -1
  404. package/dist/humain/web-access/vendor/openai-search.d.ts.map +1 -1
  405. package/dist/humain/web-access/vendor/openai-search.js +39 -13
  406. package/dist/humain/web-access/vendor/openai-search.js.map +1 -1
  407. package/dist/humain/web-access/vendor/outcrawl.d.ts +4 -0
  408. package/dist/humain/web-access/vendor/outcrawl.d.ts.map +1 -0
  409. package/dist/humain/web-access/vendor/outcrawl.js +196 -0
  410. package/dist/humain/web-access/vendor/outcrawl.js.map +1 -0
  411. package/dist/humain/web-access/vendor/page-query.d.ts.map +1 -1
  412. package/dist/humain/web-access/vendor/page-query.js +13 -3
  413. package/dist/humain/web-access/vendor/page-query.js.map +1 -1
  414. package/dist/humain/web-access/vendor/pdf-extract.d.ts +1 -3
  415. package/dist/humain/web-access/vendor/pdf-extract.d.ts.map +1 -1
  416. package/dist/humain/web-access/vendor/pdf-extract.js +0 -2
  417. package/dist/humain/web-access/vendor/pdf-extract.js.map +1 -1
  418. package/dist/humain/web-access/vendor/perplexity.d.ts +3 -0
  419. package/dist/humain/web-access/vendor/perplexity.d.ts.map +1 -1
  420. package/dist/humain/web-access/vendor/perplexity.js.map +1 -1
  421. package/dist/humain/web-access/vendor/query-rewrite.d.ts +2 -2
  422. package/dist/humain/web-access/vendor/query-rewrite.d.ts.map +1 -1
  423. package/dist/humain/web-access/vendor/query-rewrite.js +39 -13
  424. package/dist/humain/web-access/vendor/query-rewrite.js.map +1 -1
  425. package/dist/humain/web-access/vendor/searchapi.d.ts +4 -0
  426. package/dist/humain/web-access/vendor/searchapi.d.ts.map +1 -0
  427. package/dist/humain/web-access/vendor/searchapi.js +195 -0
  428. package/dist/humain/web-access/vendor/searchapi.js.map +1 -0
  429. package/dist/humain/web-access/vendor/sofya.d.ts +4 -0
  430. package/dist/humain/web-access/vendor/sofya.d.ts.map +1 -0
  431. package/dist/humain/web-access/vendor/sofya.js +193 -0
  432. package/dist/humain/web-access/vendor/sofya.js.map +1 -0
  433. package/dist/humain/web-access/vendor/source-check.d.ts +5 -1
  434. package/dist/humain/web-access/vendor/source-check.d.ts.map +1 -1
  435. package/dist/humain/web-access/vendor/source-check.js +34 -16
  436. package/dist/humain/web-access/vendor/source-check.js.map +1 -1
  437. package/dist/humain/web-access/vendor/ssrf-protection.d.ts +7 -0
  438. package/dist/humain/web-access/vendor/ssrf-protection.d.ts.map +1 -1
  439. package/dist/humain/web-access/vendor/ssrf-protection.js +24 -1
  440. package/dist/humain/web-access/vendor/ssrf-protection.js.map +1 -1
  441. package/dist/humain/web-access/vendor/summary-model-scope.d.ts +8 -3
  442. package/dist/humain/web-access/vendor/summary-model-scope.d.ts.map +1 -1
  443. package/dist/humain/web-access/vendor/summary-model-scope.js +15 -1
  444. package/dist/humain/web-access/vendor/summary-model-scope.js.map +1 -1
  445. package/dist/humain/web-access/vendor/summary-review.d.ts +7 -2
  446. package/dist/humain/web-access/vendor/summary-review.d.ts.map +1 -1
  447. package/dist/humain/web-access/vendor/summary-review.js +32 -28
  448. package/dist/humain/web-access/vendor/summary-review.js.map +1 -1
  449. package/dist/humain/web-access/vendor/tabstack.d.ts +6 -0
  450. package/dist/humain/web-access/vendor/tabstack.d.ts.map +1 -0
  451. package/dist/humain/web-access/vendor/tabstack.js +236 -0
  452. package/dist/humain/web-access/vendor/tabstack.js.map +1 -0
  453. package/dist/humain/web-access/vendor/tool-arguments.js +1 -1
  454. package/dist/humain/web-access/vendor/tool-arguments.js.map +1 -1
  455. package/dist/humain/web-access/vendor/upgrade-notice.d.ts +8 -0
  456. package/dist/humain/web-access/vendor/upgrade-notice.d.ts.map +1 -0
  457. package/dist/humain/web-access/vendor/upgrade-notice.js +46 -0
  458. package/dist/humain/web-access/vendor/upgrade-notice.js.map +1 -0
  459. package/dist/humain/web-access/vendor/utils.d.ts +9 -0
  460. package/dist/humain/web-access/vendor/utils.d.ts.map +1 -1
  461. package/dist/humain/web-access/vendor/utils.js +113 -27
  462. package/dist/humain/web-access/vendor/utils.js.map +1 -1
  463. package/dist/humain/web-access/vendor/web-tool-contract.d.ts +4 -0
  464. package/dist/humain/web-access/vendor/web-tool-contract.d.ts.map +1 -1
  465. package/dist/humain/web-access/vendor/web-tool-contract.js.map +1 -1
  466. package/dist/humain/web-access/vendor/web-tool-core.d.ts +17 -1
  467. package/dist/humain/web-access/vendor/web-tool-core.d.ts.map +1 -1
  468. package/dist/humain/web-access/vendor/web-tool-core.js +99 -22
  469. package/dist/humain/web-access/vendor/web-tool-core.js.map +1 -1
  470. package/dist/humain/web-access/vendor/xai-search.d.ts +1 -1
  471. package/dist/humain/web-access/vendor/xai-search.d.ts.map +1 -1
  472. package/dist/humain/web-access/vendor/xai-search.js +6 -5
  473. package/dist/humain/web-access/vendor/xai-search.js.map +1 -1
  474. package/dist/index.d.ts +3 -3
  475. package/dist/index.d.ts.map +1 -1
  476. package/dist/index.js.map +1 -1
  477. package/dist/main.d.ts.map +1 -1
  478. package/dist/main.js +20 -9
  479. package/dist/main.js.map +1 -1
  480. package/dist/modes/interactive/components/assistant-code-block.d.ts +34 -0
  481. package/dist/modes/interactive/components/assistant-code-block.d.ts.map +1 -0
  482. package/dist/modes/interactive/components/assistant-code-block.js +160 -0
  483. package/dist/modes/interactive/components/assistant-code-block.js.map +1 -0
  484. package/dist/modes/interactive/components/assistant-message.d.ts +31 -10
  485. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  486. package/dist/modes/interactive/components/assistant-message.js +276 -73
  487. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  488. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  489. package/dist/modes/interactive/components/compaction-summary-message.js +2 -1
  490. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  491. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  492. package/dist/modes/interactive/components/config-selector.js +4 -17
  493. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  494. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  495. package/dist/modes/interactive/components/custom-editor.js +7 -0
  496. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  497. package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -1
  498. package/dist/modes/interactive/components/custom-entry.js +2 -1
  499. package/dist/modes/interactive/components/custom-entry.js.map +1 -1
  500. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  501. package/dist/modes/interactive/components/custom-message.js +2 -1
  502. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  503. package/dist/modes/interactive/components/diff.d.ts.map +1 -1
  504. package/dist/modes/interactive/components/diff.js +3 -1
  505. package/dist/modes/interactive/components/diff.js.map +1 -1
  506. package/dist/modes/interactive/components/extension-editor.d.ts +2 -0
  507. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  508. package/dist/modes/interactive/components/extension-editor.js +4 -0
  509. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  510. package/dist/modes/interactive/components/footer.d.ts +4 -1
  511. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  512. package/dist/modes/interactive/components/footer.js +6 -5
  513. package/dist/modes/interactive/components/footer.js.map +1 -1
  514. package/dist/modes/interactive/components/login-dialog.d.ts +5 -0
  515. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  516. package/dist/modes/interactive/components/login-dialog.js +107 -11
  517. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  518. package/dist/modes/interactive/components/markdown-transform.d.ts +2 -1
  519. package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -1
  520. package/dist/modes/interactive/components/markdown-transform.js +3 -2
  521. package/dist/modes/interactive/components/markdown-transform.js.map +1 -1
  522. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
  523. package/dist/modes/interactive/components/mermaid.js +18 -6
  524. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  525. package/dist/modes/interactive/components/model-selector.d.ts +1 -0
  526. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  527. package/dist/modes/interactive/components/model-selector.js +17 -6
  528. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  529. package/dist/modes/interactive/components/oauth-selector.d.ts +1 -0
  530. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  531. package/dist/modes/interactive/components/oauth-selector.js +13 -4
  532. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  533. package/dist/modes/interactive/components/scoped-models-selector.d.ts +1 -0
  534. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  535. package/dist/modes/interactive/components/scoped-models-selector.js +14 -3
  536. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  537. package/dist/modes/interactive/components/session-selector-search.d.ts +4 -0
  538. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
  539. package/dist/modes/interactive/components/session-selector-search.js +86 -22
  540. package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
  541. package/dist/modes/interactive/components/session-selector.d.ts +2 -1
  542. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  543. package/dist/modes/interactive/components/session-selector.js +16 -24
  544. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  545. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
  546. package/dist/modes/interactive/components/settings-submenu.js +2 -0
  547. package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
  548. package/dist/modes/interactive/components/tool-execution.d.ts +2 -0
  549. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  550. package/dist/modes/interactive/components/tool-execution.js +15 -5
  551. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  552. package/dist/modes/interactive/components/tree-selector.d.ts +1 -0
  553. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  554. package/dist/modes/interactive/components/tree-selector.js +5 -6
  555. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  556. package/dist/modes/interactive/components/user-message-selector.d.ts +1 -0
  557. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
  558. package/dist/modes/interactive/components/user-message-selector.js +9 -1
  559. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  560. package/dist/modes/interactive/components/user-message.d.ts +4 -3
  561. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  562. package/dist/modes/interactive/components/user-message.js +20 -18
  563. package/dist/modes/interactive/components/user-message.js.map +1 -1
  564. package/dist/modes/interactive/external-editor.d.ts +1 -0
  565. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  566. package/dist/modes/interactive/external-editor.js +16 -4
  567. package/dist/modes/interactive/external-editor.js.map +1 -1
  568. package/dist/modes/interactive/interactive-mode.d.ts +6 -0
  569. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  570. package/dist/modes/interactive/interactive-mode.js +259 -83
  571. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  572. package/dist/modes/interactive/model-search.d.ts +10 -0
  573. package/dist/modes/interactive/model-search.d.ts.map +1 -1
  574. package/dist/modes/interactive/model-search.js +21 -0
  575. package/dist/modes/interactive/model-search.js.map +1 -1
  576. package/dist/modes/interactive/oauth-account-format.d.ts +10 -1
  577. package/dist/modes/interactive/oauth-account-format.d.ts.map +1 -1
  578. package/dist/modes/interactive/oauth-account-format.js +42 -0
  579. package/dist/modes/interactive/oauth-account-format.js.map +1 -1
  580. package/dist/modes/interactive/theme/theme.d.ts +10 -0
  581. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  582. package/dist/modes/interactive/theme/theme.js +28 -24
  583. package/dist/modes/interactive/theme/theme.js.map +1 -1
  584. package/dist/modes/print-mode.d.ts.map +1 -1
  585. package/dist/modes/print-mode.js +3 -2
  586. package/dist/modes/print-mode.js.map +1 -1
  587. package/dist/package-manager-cli.d.ts.map +1 -1
  588. package/dist/package-manager-cli.js +55 -4
  589. package/dist/package-manager-cli.js.map +1 -1
  590. package/dist/utils/ansi.d.ts.map +1 -1
  591. package/dist/utils/ansi.js +5 -2
  592. package/dist/utils/ansi.js.map +1 -1
  593. package/dist/utils/clipboard-command.d.ts.map +1 -1
  594. package/dist/utils/clipboard-command.js +4 -0
  595. package/dist/utils/clipboard-command.js.map +1 -1
  596. package/dist/utils/clipboard-image.d.ts +8 -0
  597. package/dist/utils/clipboard-image.d.ts.map +1 -1
  598. package/dist/utils/clipboard-image.js +31 -1
  599. package/dist/utils/clipboard-image.js.map +1 -1
  600. package/dist/utils/git.d.ts +1 -1
  601. package/dist/utils/git.d.ts.map +1 -1
  602. package/dist/utils/git.js.map +1 -1
  603. package/dist/utils/image-resize-core.d.ts.map +1 -1
  604. package/dist/utils/image-resize-core.js +5 -3
  605. package/dist/utils/image-resize-core.js.map +1 -1
  606. package/dist/utils/open-browser.d.ts.map +1 -1
  607. package/dist/utils/open-browser.js +96 -6
  608. package/dist/utils/open-browser.js.map +1 -1
  609. package/dist/utils/paths.d.ts +17 -0
  610. package/dist/utils/paths.d.ts.map +1 -1
  611. package/dist/utils/paths.js +42 -1
  612. package/dist/utils/paths.js.map +1 -1
  613. package/dist/utils/shell.d.ts +2 -1
  614. package/dist/utils/shell.d.ts.map +1 -1
  615. package/dist/utils/shell.js +12 -2
  616. package/dist/utils/shell.js.map +1 -1
  617. package/dist/utils/syntax-highlight.d.ts +5 -0
  618. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  619. package/dist/utils/syntax-highlight.js +156 -11
  620. package/dist/utils/syntax-highlight.js.map +1 -1
  621. package/dist/utils/tools-manager.d.ts.map +1 -1
  622. package/dist/utils/tools-manager.js +30 -35
  623. package/dist/utils/tools-manager.js.map +1 -1
  624. package/docs/assets/humain-code-logo.svg +8 -0
  625. package/docs/cli.md +22 -12
  626. package/docs/compaction.md +32 -8
  627. package/docs/coordination.md +2 -0
  628. package/docs/custom-provider.md +4 -2
  629. package/docs/environment-variables.md +2 -0
  630. package/docs/extensions.md +3169 -229
  631. package/docs/flow.md +2 -0
  632. package/docs/keybindings.md +24 -2
  633. package/docs/llama-cpp.md +30 -19
  634. package/docs/mcp.md +4 -2
  635. package/docs/message-types.md +7 -7
  636. package/docs/packages.md +27 -1
  637. package/docs/sessions.md +11 -3
  638. package/docs/settings.md +21 -9
  639. package/docs/slash-commands.md +51 -11
  640. package/docs/terminal-setup.md +3 -1
  641. package/docs/tmux.md +6 -0
  642. package/docs/tui.md +3 -1
  643. package/docs/windows.md +27 -0
  644. package/examples/extensions/README.md +2 -1
  645. package/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  646. package/examples/extensions/custom-provider-anthropic/package-lock.json +7 -7
  647. package/examples/extensions/custom-provider-anthropic/package.json +2 -2
  648. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  649. package/examples/extensions/debug-provider.ts +2 -2
  650. package/examples/extensions/gondolin/package-lock.json +14 -24
  651. package/examples/extensions/gondolin/package.json +2 -2
  652. package/examples/extensions/preset.ts +2 -0
  653. package/examples/extensions/reload-runtime.ts +17 -5
  654. package/examples/extensions/todo.ts +7 -0
  655. package/examples/extensions/tools.ts +2 -0
  656. package/examples/extensions/with-deps/package-lock.json +2 -2
  657. package/examples/extensions/with-deps/package.json +1 -1
  658. package/examples/tsconfig.json +252 -0
  659. package/npm-shrinkwrap.json +289 -277
  660. package/package.json +29 -29
  661. package/schemas/keybindings.schema.json +28 -0
  662. package/schemas/models.schema.json +36 -36
  663. package/schemas/settings.schema.json +49 -0
  664. package/src/humain/ponytail/UPSTREAM.md +16 -2
  665. package/src/humain/ponytail/upstream.json +4 -4
  666. package/src/humain/web-access/UPSTREAM.md +48 -1
  667. package/src/humain/web-access/upstream.json +9 -6
  668. package/src/humain/web-access/vendor/CHANGELOG.md +1223 -0
  669. package/dist/bundle/chunks/anthropic-messages-ZP5KUK52.js +0 -67
  670. package/dist/bundle/chunks/azure-openai-responses-QJFYQ3DF.js +0 -15
  671. package/dist/bundle/chunks/chunk-2GCMACT4.js +0 -1956
  672. package/dist/bundle/chunks/chunk-AO6FF5JL.js +0 -21
  673. package/dist/bundle/chunks/chunk-EY3LZOUP.js +0 -1963
  674. package/dist/bundle/chunks/chunk-M74U5X4S.js +0 -119
  675. package/dist/bundle/chunks/chunk-N7CQ3UV3.js +0 -80
  676. package/dist/bundle/chunks/chunk-OR25QDSS.js +0 -365
  677. package/dist/bundle/chunks/chunk-PH7UP57J.js +0 -6
  678. package/dist/bundle/chunks/chunk-QW6PTCAB.js +0 -10
  679. package/dist/bundle/chunks/chunk-ROZV2IYD.js +0 -125
  680. package/dist/bundle/chunks/chunk-YFOLLX5D.js +0 -23
  681. package/dist/bundle/chunks/chunk-ZR4GF4WU.js +0 -54
  682. package/dist/bundle/chunks/compat-CJBWWYHE.js +0 -13
  683. package/dist/bundle/chunks/dist-IBUWEKEE.js +0 -24
  684. package/dist/bundle/chunks/dist-YFMJEHPH.js +0 -8
  685. package/dist/bundle/chunks/google-generative-ai-HVPCGIZ6.js +0 -21
  686. package/dist/bundle/chunks/google-vertex-UM5MAALA.js +0 -25
  687. package/dist/bundle/chunks/host-ZHEL5XQW.js +0 -2
  688. package/dist/bundle/chunks/mistral-conversations-AH72RLXK.js +0 -44
  689. package/dist/bundle/chunks/openai-codex-responses-L366637C.js +0 -98
  690. package/dist/bundle/chunks/openai-completions-ZP62QXJX.js +0 -83
  691. package/dist/bundle/chunks/openai-responses-DXUGSUTN.js +0 -26
  692. package/dist/bundle/chunks/pi-messages-MOQQDZBK.js +0 -23
  693. package/dist/bundle/chunks/virtual-modules-5D6QIJPN.js +0 -5
  694. package/examples/extensions/sandbox/index.ts +0 -321
  695. package/examples/extensions/sandbox/package-lock.json +0 -66
  696. package/examples/extensions/sandbox/package.json +0 -19
@@ -1,4 +1,6 @@
1
1
  import type { OAuthAccount } from "./oauth-account-pool.ts";
2
+ import type { SubscriptionCreditsStatus } from "./subscription-credits.ts";
3
+ import type { SubscriptionResetStatus } from "./subscription-reset-status.ts";
2
4
  /**
3
5
  * Live Claude subscription limits from Anthropic's subscription usage endpoint, which Claude Code reads with its OAuth
4
6
  * token. The endpoint is undocumented: every field is parsed defensively and unknown keys are ignored.
@@ -19,6 +21,8 @@ export type AnthropicUsageResult = {
19
21
  status: "ok";
20
22
  windows: AnthropicUsageWindow[];
21
23
  fetchedAt: number;
24
+ resets?: SubscriptionResetStatus;
25
+ credits?: SubscriptionCreditsStatus;
22
26
  } | {
23
27
  status: "unavailable";
24
28
  reason: AnthropicUsageUnavailableReason;
@@ -1 +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"}
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;AAC5D,OAAO,K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,IAAI,IAAI,CAG/C;AA+DD;;;GAGG;AACH,wBAAsB,+BAA+B,CACpD,OAAO,EAAE,YAAY,EACrB,OAAO,GAAE,sCAA2C,GAClD,OAAO,CAAC,oBAAoB,CAAC,CAiB/B"}
@@ -11,6 +11,7 @@ const DEFAULT_RETRY_AFTER_MS = 5 * 60_000;
11
11
  const MAX_RETRY_AFTER_MS = 30 * 60_000;
12
12
  const MAX_CACHE_ENTRIES = 32;
13
13
  const MAX_RESET_LENGTH = 64;
14
+ const RESET_EXPIRY_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;
14
15
  /** Percent buckets in display order. */
15
16
  const BUCKETS = [
16
17
  ["five_hour", "5h"],
@@ -57,6 +58,70 @@ export function parseAnthropicSubscriptionUsage(payload) {
57
58
  }
58
59
  return windows;
59
60
  }
61
+ // Client gating is not account ineligibility; only explicitly weekly-clearing grants describe weekly resets.
62
+ // Schema observed at https://github.com/stablyai/orca/issues/22309#issuecomment-5988391166
63
+ function parseResetStatus(value) {
64
+ if (!isRecord(value) || value.eligible !== true || !Array.isArray(value.grants) || value.grants.length === 0)
65
+ return undefined;
66
+ let availableCount = 0;
67
+ let expiresAt;
68
+ let completeExpiry = true;
69
+ let usable = false;
70
+ let allUnusable = true;
71
+ let hasWeeklyGrant = false;
72
+ for (const grant of value.grants) {
73
+ const clears = isRecord(grant) ? grant.clears : undefined;
74
+ if (Array.isArray(clears) && clears.length > 0 && clears.every((window) => window === "five_hour"))
75
+ continue;
76
+ if (!isRecord(grant) ||
77
+ !Array.isArray(clears) ||
78
+ !clears.every((window) => typeof window === "string" && window.length > 0) ||
79
+ !clears.some((window) => /^seven_day(?:_.+)?$/.test(window))) {
80
+ availableCount = undefined;
81
+ completeExpiry = false;
82
+ allUnusable = false;
83
+ continue;
84
+ }
85
+ hasWeeklyGrant = true;
86
+ const count = grant.resets_left;
87
+ if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0) {
88
+ availableCount = undefined;
89
+ completeExpiry = false;
90
+ }
91
+ else {
92
+ if (availableCount !== undefined) {
93
+ availableCount += count;
94
+ if (!Number.isSafeInteger(availableCount))
95
+ availableCount = undefined;
96
+ }
97
+ if (count > 0) {
98
+ const expiry = typeof grant.ends_at === "string" &&
99
+ grant.ends_at.length <= MAX_RESET_LENGTH &&
100
+ RESET_EXPIRY_PATTERN.test(grant.ends_at)
101
+ ? parseResetsAt(grant.ends_at)
102
+ : undefined;
103
+ const day = typeof grant.ends_at === "string" ? grant.ends_at.slice(0, 10) : "";
104
+ // Date.parse normalizes invalid calendar days, so require the reported day to round-trip.
105
+ if (expiry === undefined || new Date(`${day}T00:00:00Z`).toISOString().slice(0, 10) !== day)
106
+ completeExpiry = false;
107
+ else
108
+ expiresAt = expiresAt === undefined ? expiry : Math.min(expiresAt, expiry);
109
+ }
110
+ }
111
+ usable ||= grant.usable_now === true;
112
+ allUnusable &&= grant.usable_now === false;
113
+ }
114
+ if (!hasWeeklyGrant)
115
+ return undefined;
116
+ // Campaign eligibility alone is not permission to redeem: a grant must explicitly be usable now.
117
+ const eligible = usable ? true : allUnusable ? false : undefined;
118
+ const resets = {
119
+ ...(availableCount !== undefined ? { availableCount } : {}),
120
+ ...(eligible !== undefined ? { eligible } : {}),
121
+ ...(completeExpiry && expiresAt !== undefined ? { expiresAt } : {}),
122
+ };
123
+ return Object.keys(resets).length > 0 ? resets : undefined;
124
+ }
60
125
  /** Retry-After as delay seconds or an HTTP date, bounded to 1 s..30 min; 5 min when absent or invalid. */
61
126
  export function parseRetryAfterMs(value, nowMs) {
62
127
  if (value === null)
@@ -99,7 +164,7 @@ async function requestUsage(account, options, now) {
99
164
  let response;
100
165
  try {
101
166
  const fetcher = options.fetch ?? globalThis.fetch;
102
- response = await fetcher(ANTHROPIC_USAGE_URL, {
167
+ response = await fetcher(`${ANTHROPIC_USAGE_URL}?cedar_ember=1`, {
103
168
  method: "GET",
104
169
  headers: {
105
170
  Authorization: `Bearer ${account.credential.access}`,
@@ -133,10 +198,15 @@ async function requestUsage(account, options, now) {
133
198
  }
134
199
  if (!isRecord(payload))
135
200
  return unavailable("malformed");
201
+ const resets = parseResetStatus(payload.cedar_ember);
202
+ // extra_usage is a spending budget, not a purchased balance; its monetary units are not verified.
203
+ const enabled = isRecord(payload.extra_usage) ? payload.extra_usage.is_enabled : undefined;
136
204
  const result = {
137
205
  status: "ok",
138
206
  windows: parseAnthropicSubscriptionUsage(payload),
139
207
  fetchedAt: now,
208
+ ...(resets ? { resets } : {}),
209
+ ...(typeof enabled === "boolean" ? { credits: { enabled } } : {}),
140
210
  };
141
211
  remember(account.key, result, now + SUCCESS_TTL_MS, now);
142
212
  return result;
@@ -1 +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;CAC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IAC5B,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
+ {"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;AAK3D;;;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;AAC5B,MAAM,oBAAoB,GAAG,0EAA0E,CAAC;AAExG,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,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AAO;QAAE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;IAEjF,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IAC1C,kHAAkH;IAClH,IAAI,OAAO;QAAE,OAAO,OAAO,CAAC;IAC5B,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\";\nimport type { SubscriptionCreditsStatus } from \"./subscription-credits.ts\";\nimport type { SubscriptionResetStatus } from \"./subscription-reset-status.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;\nconst RESET_EXPIRY_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:Z|[+-]\\d{2}:\\d{2})$/;\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| {\n\t\t\tstatus: \"ok\";\n\t\t\twindows: AnthropicUsageWindow[];\n\t\t\tfetchedAt: number;\n\t\t\tresets?: SubscriptionResetStatus;\n\t\t\tcredits?: SubscriptionCreditsStatus;\n\t }\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// Client gating is not account ineligibility; only explicitly weekly-clearing grants describe weekly resets.\n// Schema observed at https://github.com/stablyai/orca/issues/22309#issuecomment-5988391166\nfunction parseResetStatus(value: unknown): SubscriptionResetStatus | undefined {\n\tif (!isRecord(value) || value.eligible !== true || !Array.isArray(value.grants) || value.grants.length === 0)\n\t\treturn undefined;\n\n\tlet availableCount: number | undefined = 0;\n\tlet expiresAt: number | undefined;\n\tlet completeExpiry = true;\n\tlet usable = false;\n\tlet allUnusable = true;\n\tlet hasWeeklyGrant = false;\n\tfor (const grant of value.grants) {\n\t\tconst clears: unknown = isRecord(grant) ? grant.clears : undefined;\n\t\tif (Array.isArray(clears) && clears.length > 0 && clears.every((window: unknown) => window === \"five_hour\"))\n\t\t\tcontinue;\n\t\tif (\n\t\t\t!isRecord(grant) ||\n\t\t\t!Array.isArray(clears) ||\n\t\t\t!clears.every((window: unknown) => typeof window === \"string\" && window.length > 0) ||\n\t\t\t!clears.some((window: string) => /^seven_day(?:_.+)?$/.test(window))\n\t\t) {\n\t\t\tavailableCount = undefined;\n\t\t\tcompleteExpiry = false;\n\t\t\tallUnusable = false;\n\t\t\tcontinue;\n\t\t}\n\t\thasWeeklyGrant = true;\n\t\tconst count = grant.resets_left;\n\t\tif (typeof count !== \"number\" || !Number.isSafeInteger(count) || count < 0) {\n\t\t\tavailableCount = undefined;\n\t\t\tcompleteExpiry = false;\n\t\t} else {\n\t\t\tif (availableCount !== undefined) {\n\t\t\t\tavailableCount += count;\n\t\t\t\tif (!Number.isSafeInteger(availableCount)) availableCount = undefined;\n\t\t\t}\n\t\t\tif (count > 0) {\n\t\t\t\tconst expiry =\n\t\t\t\t\ttypeof grant.ends_at === \"string\" &&\n\t\t\t\t\tgrant.ends_at.length <= MAX_RESET_LENGTH &&\n\t\t\t\t\tRESET_EXPIRY_PATTERN.test(grant.ends_at)\n\t\t\t\t\t\t? parseResetsAt(grant.ends_at)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst day = typeof grant.ends_at === \"string\" ? grant.ends_at.slice(0, 10) : \"\";\n\t\t\t\t// Date.parse normalizes invalid calendar days, so require the reported day to round-trip.\n\t\t\t\tif (expiry === undefined || new Date(`${day}T00:00:00Z`).toISOString().slice(0, 10) !== day)\n\t\t\t\t\tcompleteExpiry = false;\n\t\t\t\telse expiresAt = expiresAt === undefined ? expiry : Math.min(expiresAt, expiry);\n\t\t\t}\n\t\t}\n\t\tusable ||= grant.usable_now === true;\n\t\tallUnusable &&= grant.usable_now === false;\n\t}\n\tif (!hasWeeklyGrant) return undefined;\n\t// Campaign eligibility alone is not permission to redeem: a grant must explicitly be usable now.\n\tconst eligible = usable ? true : allUnusable ? false : undefined;\n\tconst resets: SubscriptionResetStatus = {\n\t\t...(availableCount !== undefined ? { availableCount } : {}),\n\t\t...(eligible !== undefined ? { eligible } : {}),\n\t\t...(completeExpiry && expiresAt !== undefined ? { expiresAt } : {}),\n\t};\n\treturn Object.keys(resets).length > 0 ? resets : undefined;\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}?cedar_ember=1`, {\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 resets = parseResetStatus(payload.cedar_ember);\n\t// extra_usage is a spending budget, not a purchased balance; its monetary units are not verified.\n\tconst enabled = isRecord(payload.extra_usage) ? payload.extra_usage.is_enabled : undefined;\n\tconst result: AnthropicUsageResult = {\n\t\tstatus: \"ok\",\n\t\twindows: parseAnthropicSubscriptionUsage(payload),\n\t\tfetchedAt: now,\n\t\t...(resets ? { resets } : {}),\n\t\t...(typeof enabled === \"boolean\" ? { credits: { enabled } } : {}),\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"]}
@@ -76,13 +76,13 @@ export declare function collectBugReportMetadata(options: CollectBugReportMetada
76
76
  samplingParams: unknown;
77
77
  compat: unknown;
78
78
  thinkingLevelMap: {
79
- high?: string | null | undefined;
79
+ off?: string | null | undefined;
80
+ minimal?: string | null | undefined;
80
81
  low?: string | null | undefined;
81
- max?: string | null | undefined;
82
82
  medium?: string | null | undefined;
83
- minimal?: string | null | undefined;
84
- off?: string | null | undefined;
83
+ high?: string | null | undefined;
85
84
  xhigh?: string | null | undefined;
85
+ max?: string | null | undefined;
86
86
  } | null;
87
87
  headerNames: string[];
88
88
  } | null;
@@ -0,0 +1,45 @@
1
+ import type { CodexUsageUnavailableReason } from "./codex-usage.ts";
2
+ import { type OAuthAccount } from "./oauth-account-pool.ts";
3
+ export interface CodexResetCredit {
4
+ id: string;
5
+ /** Epoch milliseconds; omitted for a credit with no reported expiry. */
6
+ expiresAt?: number;
7
+ }
8
+ export type CodexResetUnavailableReason = Exclude<CodexUsageUnavailableReason, "no_weekly_window">;
9
+ export type CodexResetDetailsResult = {
10
+ status: "ok";
11
+ credits: CodexResetCredit[];
12
+ /** Provider summary, not proof that every counted credit is eligible for selection. */
13
+ availableCount?: number;
14
+ } | {
15
+ status: "unavailable";
16
+ reason: CodexResetUnavailableReason;
17
+ };
18
+ export type CodexResetResult = {
19
+ status: "ok";
20
+ outcome: "reset" | "already_redeemed" | "nothing_to_reset" | "no_credit";
21
+ } | {
22
+ status: "unavailable";
23
+ reason: CodexResetUnavailableReason;
24
+ uncertain?: boolean;
25
+ };
26
+ export interface FetchCodexResetDetailsOptions {
27
+ signal?: AbortSignal;
28
+ fetch?: typeof fetch;
29
+ /** Reference time in epoch milliseconds. */
30
+ now?: number;
31
+ }
32
+ export interface ConsumeCodexResetCreditOptions extends FetchCodexResetDetailsOptions {
33
+ /** Exact selected credit, never an instruction to consume the next available credit. */
34
+ creditId: string;
35
+ /** Caller-owned UUID. Reuse both IDs after an uncertain attempt, including across process restarts. */
36
+ requestId: string;
37
+ }
38
+ /** Read-only details for one account. Never activates an account, refreshes credentials, or clears cooldowns. */
39
+ export declare function fetchCodexResetDetails(account: OAuthAccount, options?: FetchCodexResetDetailsOptions): Promise<CodexResetDetailsResult>;
40
+ /**
41
+ * Redeem exactly one explicitly selected credit with one POST and no retry. The caller owns per-account confirmation
42
+ * and must preserve both IDs after uncertainty; this helper never treats a read-only usage check as authorization.
43
+ */
44
+ export declare function consumeCodexResetCredit(account: OAuthAccount, options: ConsumeCodexResetCreditOptions): Promise<CodexResetResult>;
45
+ //# sourceMappingURL=codex-reset.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codex-reset.d.ts","sourceRoot":"","sources":["../../src/core/codex-reset.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,kBAAkB,CAAC;AACpE,OAAO,EAAE,KAAK,YAAY,EAAqC,MAAM,yBAAyB,CAAC;AAQ/F,MAAM,WAAW,gBAAgB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,wEAAwE;IACx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from "../utils/pi-user-agent.js";
3
+ import { resolveOpenAICodexAccountIdentity } from "./oauth-account-pool.js";
4
+ const RESET_CREDITS_URL = "https://chatgpt.com/backend-api/wham/rate-limit-reset-credits";
5
+ const MAX_CREDITS = 1000;
6
+ const MAX_BODY_BYTES = 262_144;
7
+ const ID_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/;
8
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
9
+ function isRecord(value) {
10
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11
+ }
12
+ function validId(value) {
13
+ return typeof value === "string" && ID_PATTERN.test(value);
14
+ }
15
+ function unavailable(reason, uncertain) {
16
+ return { status: "unavailable", reason, uncertain };
17
+ }
18
+ /** Only the documented ISO date shape or plausible numeric epoch seconds; never parse numeric strings as dates. */
19
+ function expiryMillis(value) {
20
+ if (typeof value === "number") {
21
+ return Number.isFinite(value) && value > 0 && value <= 253_402_300_799 ? value * 1000 : undefined;
22
+ }
23
+ if (typeof value !== "string" || value.length > 64)
24
+ return undefined;
25
+ const parts = /^(\d{4})-(\d{2})-(\d{2})T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.exec(value);
26
+ if (!parts)
27
+ return undefined;
28
+ const month = Number(parts[2]);
29
+ const day = Number(parts[3]);
30
+ if (month < 1 || month > 12 || day < 1 || day > new Date(Date.UTC(Number(parts[1]), month, 0)).getUTCDate()) {
31
+ return undefined;
32
+ }
33
+ const parsed = Date.parse(value);
34
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
35
+ }
36
+ /** Bound the body before decoding or trusting any provider fields. */
37
+ async function readPayload(response) {
38
+ if (!response.body)
39
+ throw new Error("Missing reset response body");
40
+ const reader = response.body.getReader();
41
+ const decoder = new TextDecoder("utf-8", { fatal: true });
42
+ let bytes = 0;
43
+ let body = "";
44
+ try {
45
+ while (true) {
46
+ const { done, value } = await reader.read();
47
+ if (done)
48
+ break;
49
+ bytes += value.byteLength;
50
+ if (bytes > MAX_BODY_BYTES)
51
+ throw new Error("Reset response body too large");
52
+ body += decoder.decode(value, { stream: true });
53
+ }
54
+ return JSON.parse(body + decoder.decode());
55
+ }
56
+ finally {
57
+ void reader.cancel().catch(() => { });
58
+ reader.releaseLock();
59
+ }
60
+ }
61
+ async function request(account, options, selection) {
62
+ const now = options.now ?? Date.now();
63
+ const credential = account.credential;
64
+ if (!Number.isFinite(now) || !Number.isFinite(credential.expires))
65
+ return unavailable("malformed", false);
66
+ if (credential.expires <= now)
67
+ return unavailable("expired_credential", false);
68
+ if (options.signal?.aborted)
69
+ return unavailable("timeout", false);
70
+ if (credential.type !== "oauth" ||
71
+ typeof credential.access !== "string" ||
72
+ credential.access.length === 0 ||
73
+ credential.access.length > 65_536 ||
74
+ /\s/.test(credential.access)) {
75
+ return unavailable("malformed", false);
76
+ }
77
+ // Require a Codex token identity, not a label, local pool key, or an unrelated provider's opaque token.
78
+ const accountId = resolveOpenAICodexAccountIdentity(credential)?.key;
79
+ if (!validId(accountId) || (credential.accountId !== undefined && credential.accountId !== accountId)) {
80
+ return unavailable("malformed", false);
81
+ }
82
+ if (selection &&
83
+ (!validId(selection.creditId) ||
84
+ typeof selection.requestId !== "string" ||
85
+ !UUID_PATTERN.test(selection.requestId))) {
86
+ return unavailable("malformed", false);
87
+ }
88
+ const timeout = AbortSignal.timeout(10_000);
89
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
90
+ let sent = false;
91
+ let readingBody = false;
92
+ try {
93
+ const fetcher = options.fetch ?? globalThis.fetch;
94
+ // Recheck immediately before dispatch; no asynchronous preflight may authorize a later POST.
95
+ if (signal.aborted)
96
+ return unavailable("timeout", false);
97
+ if (credential.expires <= (options.now ?? Date.now()))
98
+ return unavailable("expired_credential", false);
99
+ sent = true;
100
+ const response = await fetcher(selection ? `${RESET_CREDITS_URL}/consume` : RESET_CREDITS_URL, {
101
+ method: selection ? "POST" : "GET",
102
+ headers: {
103
+ Authorization: `Bearer ${credential.access}`,
104
+ "chatgpt-account-id": accountId,
105
+ Accept: "application/json",
106
+ "User-Agent": getPiUserAgent(VERSION),
107
+ originator: "pi",
108
+ ...(selection ? { "Content-Type": "application/json" } : {}),
109
+ },
110
+ ...(selection
111
+ ? { body: JSON.stringify({ credit_id: selection.creditId, redeem_request_id: selection.requestId }) }
112
+ : {}),
113
+ redirect: "error",
114
+ signal,
115
+ });
116
+ const uncertain = selection !== undefined;
117
+ if (signal.aborted)
118
+ return unavailable("timeout", uncertain);
119
+ if (response.redirected)
120
+ return unavailable("http_error", uncertain);
121
+ if (response.status === 401 || response.status === 403)
122
+ return unavailable("unauthorized", false);
123
+ if (response.status === 429)
124
+ return unavailable("rate_limited", false);
125
+ if (!response.ok) {
126
+ return unavailable("http_error", uncertain && (response.status >= 500 || response.status === 408));
127
+ }
128
+ readingBody = true;
129
+ const payload = await readPayload(response);
130
+ if (signal.aborted)
131
+ return unavailable("timeout", uncertain);
132
+ if (!isRecord(payload) || ("account_id" in payload && payload.account_id !== accountId)) {
133
+ return unavailable("malformed", uncertain);
134
+ }
135
+ return { status: "ok", payload, now: options.now ?? Date.now() };
136
+ }
137
+ catch (error) {
138
+ const aborted = signal.aborted || (isRecord(error) && (error.name === "AbortError" || error.name === "TimeoutError"));
139
+ return unavailable(aborted ? "timeout" : readingBody ? "malformed" : "network", sent && selection !== undefined);
140
+ }
141
+ }
142
+ /** Read-only details for one account. Never activates an account, refreshes credentials, or clears cooldowns. */
143
+ export async function fetchCodexResetDetails(account, options = {}) {
144
+ const result = await request(account, options);
145
+ if (result.status === "unavailable")
146
+ return { status: "unavailable", reason: result.reason };
147
+ const { payload, now } = result;
148
+ const count = payload.available_count;
149
+ if (!Array.isArray(payload.credits) ||
150
+ payload.credits.length > MAX_CREDITS ||
151
+ (count !== undefined &&
152
+ (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0 || count > MAX_CREDITS))) {
153
+ return { status: "unavailable", reason: "malformed" };
154
+ }
155
+ const credits = [];
156
+ const seen = new Set();
157
+ for (const entry of payload.credits) {
158
+ if (!isRecord(entry) || !validId(entry.id))
159
+ continue;
160
+ // Conflicting duplicate rows cannot prove which state applies to a selected credit.
161
+ if (seen.has(entry.id))
162
+ return { status: "unavailable", reason: "malformed" };
163
+ seen.add(entry.id);
164
+ if (entry.reset_type !== "codex_rate_limits" || entry.status !== "available")
165
+ continue;
166
+ if (entry.expires_at == null) {
167
+ credits.push({ id: entry.id });
168
+ continue;
169
+ }
170
+ const expiresAt = expiryMillis(entry.expires_at);
171
+ if (expiresAt !== undefined && expiresAt > now)
172
+ credits.push({ id: entry.id, expiresAt });
173
+ }
174
+ return { status: "ok", credits, ...(typeof count === "number" ? { availableCount: count } : {}) };
175
+ }
176
+ /**
177
+ * Redeem exactly one explicitly selected credit with one POST and no retry. The caller owns per-account confirmation
178
+ * and must preserve both IDs after uncertainty; this helper never treats a read-only usage check as authorization.
179
+ */
180
+ export async function consumeCodexResetCredit(account, options) {
181
+ const result = await request(account, options, { creditId: options.creditId, requestId: options.requestId });
182
+ if (result.status === "unavailable")
183
+ return result;
184
+ const code = result.payload.code;
185
+ if (code === "reset" || code === "already_redeemed" || code === "nothing_to_reset" || code === "no_credit") {
186
+ return { status: "ok", outcome: code };
187
+ }
188
+ return unavailable("malformed", true);
189
+ }
190
+ //# sourceMappingURL=codex-reset.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codex-reset.js","sourceRoot":"","sources":["../../src/core/codex-reset.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,OAAO,EAAqB,iCAAiC,EAAE,MAAM,yBAAyB,CAAC;AAE/F,MAAM,iBAAiB,GAAG,+DAA+D,CAAC;AAC1F,MAAM,WAAW,GAAG,IAAI,CAAC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GAAG,YAAY,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QACjD,IAAI,SAAS,KAAK,SAAS,IAAI,SAAS,GAAG,GAAG;YAAE,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,KAAK,CAAC,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC;IAC3F,CAAC;IACD,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AACnG,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC5C,OAAqB,EACrB,OAAuC;IAEvC,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IAC7G,IAAI,MAAM,CAAC,MAAM,KAAK,aAAa;QAAE,OAAO,MAAM,CAAC;IACnD,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC;IACjC,IAAI,IAAI,KAAK,OAAO,IAAI,IAAI,KAAK,kBAAkB,IAAI,IAAI,KAAK,kBAAkB,IAAI,IAAI,KAAK,WAAW,EAAE,CAAC;QAC5G,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IACxC,CAAC;IACD,OAAO,WAAW,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC;AACvC,CAAC","sourcesContent":["import { VERSION } from \"../config.ts\";\nimport { getPiUserAgent } from \"../utils/pi-user-agent.ts\";\nimport type { CodexUsageUnavailableReason } from \"./codex-usage.ts\";\nimport { type OAuthAccount, resolveOpenAICodexAccountIdentity } from \"./oauth-account-pool.ts\";\n\nconst RESET_CREDITS_URL = \"https://chatgpt.com/backend-api/wham/rate-limit-reset-credits\";\nconst MAX_CREDITS = 1000;\nconst MAX_BODY_BYTES = 262_144;\nconst ID_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/;\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nexport interface CodexResetCredit {\n\tid: string;\n\t/** Epoch milliseconds; omitted for a credit with no reported expiry. */\n\texpiresAt?: number;\n}\n\nexport type CodexResetUnavailableReason = Exclude<CodexUsageUnavailableReason, \"no_weekly_window\">;\n\nexport type CodexResetDetailsResult =\n\t| {\n\t\t\tstatus: \"ok\";\n\t\t\tcredits: CodexResetCredit[];\n\t\t\t/** Provider summary, not proof that every counted credit is eligible for selection. */\n\t\t\tavailableCount?: number;\n\t }\n\t| { status: \"unavailable\"; reason: CodexResetUnavailableReason };\n\nexport type CodexResetResult =\n\t| { status: \"ok\"; outcome: \"reset\" | \"already_redeemed\" | \"nothing_to_reset\" | \"no_credit\" }\n\t| { status: \"unavailable\"; reason: CodexResetUnavailableReason; uncertain?: boolean };\n\nexport interface FetchCodexResetDetailsOptions {\n\tsignal?: AbortSignal;\n\tfetch?: typeof fetch;\n\t/** Reference time in epoch milliseconds. */\n\tnow?: number;\n}\n\nexport interface ConsumeCodexResetCreditOptions extends FetchCodexResetDetailsOptions {\n\t/** Exact selected credit, never an instruction to consume the next available credit. */\n\tcreditId: string;\n\t/** Caller-owned UUID. Reuse both IDs after an uncertain attempt, including across process restarts. */\n\trequestId: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction validId(value: unknown): value is string {\n\treturn typeof value === \"string\" && ID_PATTERN.test(value);\n}\n\nfunction unavailable(reason: CodexResetUnavailableReason, uncertain: boolean) {\n\treturn { status: \"unavailable\" as const, reason, uncertain };\n}\n\n/** Only the documented ISO date shape or plausible numeric epoch seconds; never parse numeric strings as dates. */\nfunction expiryMillis(value: unknown): number | undefined {\n\tif (typeof value === \"number\") {\n\t\treturn Number.isFinite(value) && value > 0 && value <= 253_402_300_799 ? value * 1000 : undefined;\n\t}\n\tif (typeof value !== \"string\" || value.length > 64) return undefined;\n\tconst parts = /^(\\d{4})-(\\d{2})-(\\d{2})T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:Z|[+-]\\d{2}:\\d{2})$/.exec(value);\n\tif (!parts) return undefined;\n\tconst month = Number(parts[2]);\n\tconst day = Number(parts[3]);\n\tif (month < 1 || month > 12 || day < 1 || day > new Date(Date.UTC(Number(parts[1]), month, 0)).getUTCDate()) {\n\t\treturn undefined;\n\t}\n\tconst parsed = Date.parse(value);\n\treturn Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\n/** Bound the body before decoding or trusting any provider fields. */\nasync function readPayload(response: Response): Promise<unknown> {\n\tif (!response.body) throw new Error(\"Missing reset response body\");\n\tconst reader = response.body.getReader();\n\tconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\tlet bytes = 0;\n\tlet body = \"\";\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\tbytes += value.byteLength;\n\t\t\tif (bytes > MAX_BODY_BYTES) throw new Error(\"Reset response body too large\");\n\t\t\tbody += decoder.decode(value, { stream: true });\n\t\t}\n\t\treturn JSON.parse(body + decoder.decode());\n\t} finally {\n\t\tvoid reader.cancel().catch(() => {});\n\t\treader.releaseLock();\n\t}\n}\n\nasync function request(\n\taccount: OAuthAccount,\n\toptions: FetchCodexResetDetailsOptions,\n\tselection?: { creditId: string; requestId: string },\n): Promise<{ status: \"ok\"; payload: Record<string, unknown>; now: number } | ReturnType<typeof unavailable>> {\n\tconst now = options.now ?? Date.now();\n\tconst credential = account.credential;\n\tif (!Number.isFinite(now) || !Number.isFinite(credential.expires)) return unavailable(\"malformed\", false);\n\tif (credential.expires <= now) return unavailable(\"expired_credential\", false);\n\tif (options.signal?.aborted) return unavailable(\"timeout\", false);\n\tif (\n\t\tcredential.type !== \"oauth\" ||\n\t\ttypeof credential.access !== \"string\" ||\n\t\tcredential.access.length === 0 ||\n\t\tcredential.access.length > 65_536 ||\n\t\t/\\s/.test(credential.access)\n\t) {\n\t\treturn unavailable(\"malformed\", false);\n\t}\n\t// Require a Codex token identity, not a label, local pool key, or an unrelated provider's opaque token.\n\tconst accountId = resolveOpenAICodexAccountIdentity(credential)?.key;\n\tif (!validId(accountId) || (credential.accountId !== undefined && credential.accountId !== accountId)) {\n\t\treturn unavailable(\"malformed\", false);\n\t}\n\tif (\n\t\tselection &&\n\t\t(!validId(selection.creditId) ||\n\t\t\ttypeof selection.requestId !== \"string\" ||\n\t\t\t!UUID_PATTERN.test(selection.requestId))\n\t) {\n\t\treturn unavailable(\"malformed\", false);\n\t}\n\n\tconst timeout = AbortSignal.timeout(10_000);\n\tconst signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;\n\tlet sent = false;\n\tlet readingBody = false;\n\ttry {\n\t\tconst fetcher = options.fetch ?? globalThis.fetch;\n\t\t// Recheck immediately before dispatch; no asynchronous preflight may authorize a later POST.\n\t\tif (signal.aborted) return unavailable(\"timeout\", false);\n\t\tif (credential.expires <= (options.now ?? Date.now())) return unavailable(\"expired_credential\", false);\n\t\tsent = true;\n\t\tconst response = await fetcher(selection ? `${RESET_CREDITS_URL}/consume` : RESET_CREDITS_URL, {\n\t\t\tmethod: selection ? \"POST\" : \"GET\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${credential.access}`,\n\t\t\t\t\"chatgpt-account-id\": accountId,\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\"User-Agent\": getPiUserAgent(VERSION),\n\t\t\t\toriginator: \"pi\",\n\t\t\t\t...(selection ? { \"Content-Type\": \"application/json\" } : {}),\n\t\t\t},\n\t\t\t...(selection\n\t\t\t\t? { body: JSON.stringify({ credit_id: selection.creditId, redeem_request_id: selection.requestId }) }\n\t\t\t\t: {}),\n\t\t\tredirect: \"error\",\n\t\t\tsignal,\n\t\t});\n\t\tconst uncertain = selection !== undefined;\n\t\tif (signal.aborted) return unavailable(\"timeout\", uncertain);\n\t\tif (response.redirected) return unavailable(\"http_error\", uncertain);\n\t\tif (response.status === 401 || response.status === 403) return unavailable(\"unauthorized\", false);\n\t\tif (response.status === 429) return unavailable(\"rate_limited\", false);\n\t\tif (!response.ok) {\n\t\t\treturn unavailable(\"http_error\", uncertain && (response.status >= 500 || response.status === 408));\n\t\t}\n\t\treadingBody = true;\n\t\tconst payload = await readPayload(response);\n\t\tif (signal.aborted) return unavailable(\"timeout\", uncertain);\n\t\tif (!isRecord(payload) || (\"account_id\" in payload && payload.account_id !== accountId)) {\n\t\t\treturn unavailable(\"malformed\", uncertain);\n\t\t}\n\t\treturn { status: \"ok\", payload, now: options.now ?? Date.now() };\n\t} catch (error) {\n\t\tconst aborted =\n\t\t\tsignal.aborted || (isRecord(error) && (error.name === \"AbortError\" || error.name === \"TimeoutError\"));\n\t\treturn unavailable(aborted ? \"timeout\" : readingBody ? \"malformed\" : \"network\", sent && selection !== undefined);\n\t}\n}\n\n/** Read-only details for one account. Never activates an account, refreshes credentials, or clears cooldowns. */\nexport async function fetchCodexResetDetails(\n\taccount: OAuthAccount,\n\toptions: FetchCodexResetDetailsOptions = {},\n): Promise<CodexResetDetailsResult> {\n\tconst result = await request(account, options);\n\tif (result.status === \"unavailable\") return { status: \"unavailable\", reason: result.reason };\n\tconst { payload, now } = result;\n\tconst count = payload.available_count;\n\tif (\n\t\t!Array.isArray(payload.credits) ||\n\t\tpayload.credits.length > MAX_CREDITS ||\n\t\t(count !== undefined &&\n\t\t\t(typeof count !== \"number\" || !Number.isSafeInteger(count) || count < 0 || count > MAX_CREDITS))\n\t) {\n\t\treturn { status: \"unavailable\", reason: \"malformed\" };\n\t}\n\tconst credits: CodexResetCredit[] = [];\n\tconst seen = new Set<string>();\n\tfor (const entry of payload.credits) {\n\t\tif (!isRecord(entry) || !validId(entry.id)) continue;\n\t\t// Conflicting duplicate rows cannot prove which state applies to a selected credit.\n\t\tif (seen.has(entry.id)) return { status: \"unavailable\", reason: \"malformed\" };\n\t\tseen.add(entry.id);\n\t\tif (entry.reset_type !== \"codex_rate_limits\" || entry.status !== \"available\") continue;\n\t\tif (entry.expires_at == null) {\n\t\t\tcredits.push({ id: entry.id });\n\t\t\tcontinue;\n\t\t}\n\t\tconst expiresAt = expiryMillis(entry.expires_at);\n\t\tif (expiresAt !== undefined && expiresAt > now) credits.push({ id: entry.id, expiresAt });\n\t}\n\treturn { status: \"ok\", credits, ...(typeof count === \"number\" ? { availableCount: count } : {}) };\n}\n\n/**\n * Redeem exactly one explicitly selected credit with one POST and no retry. The caller owns per-account confirmation\n * and must preserve both IDs after uncertainty; this helper never treats a read-only usage check as authorization.\n */\nexport async function consumeCodexResetCredit(\n\taccount: OAuthAccount,\n\toptions: ConsumeCodexResetCreditOptions,\n): Promise<CodexResetResult> {\n\tconst result = await request(account, options, { creditId: options.creditId, requestId: options.requestId });\n\tif (result.status === \"unavailable\") return result;\n\tconst code = result.payload.code;\n\tif (code === \"reset\" || code === \"already_redeemed\" || code === \"nothing_to_reset\" || code === \"no_credit\") {\n\t\treturn { status: \"ok\", outcome: code };\n\t}\n\treturn unavailable(\"malformed\", true);\n}\n"]}
@@ -1,10 +1,11 @@
1
1
  import { type OAuthAccount, type OAuthAccountPool } from "./oauth-account-pool.ts";
2
+ import { type SubscriptionCreditsStatus } from "./subscription-credits.ts";
3
+ import type { SubscriptionResetStatus } from "./subscription-reset-status.ts";
2
4
  export declare const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
3
5
  export declare const CODEX_USAGE_PROVIDER_ID = "openai-codex";
4
- export interface CodexCreditsStatus {
6
+ export interface CodexCreditsStatus extends SubscriptionCreditsStatus {
5
7
  hasCredits: boolean;
6
8
  unlimited: boolean;
7
- balance?: string;
8
9
  }
9
10
  type CodexAvailability = "allowed" | "blocked" | "unknown";
10
11
  export interface CodexWeeklyUsage {
@@ -50,6 +51,7 @@ export type CodexUsageDetailsResult = {
50
51
  /** Main limit windows first (shortest first), then additional limits, then code review. */
51
52
  windows: CodexUsageWindow[];
52
53
  credits?: CodexCreditsStatus;
54
+ resets?: SubscriptionResetStatus;
53
55
  cooldownCleared?: boolean;
54
56
  } | {
55
57
  status: "unavailable";
@@ -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;AAYtD,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;IAChG,YAAY,CAAC,EAAE,iBAAiB,CAAC;IACjC,oDAAoD;IACpD,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,+FAA+F;IAC/F,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,OAAO,CAAC,EAAE,kBAAkB,CAAC;IAC7B,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED,MAAM,MAAM,2BAA2B,GACpC,oBAAoB,GACpB,cAAc,GACd,cAAc,GACd,YAAY,GACZ,SAAS,GACT,SAAS,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EAAE,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,gBAAgB,KAAK,IAAI,CAAC;CAClE;AA+CD,sEAAsE;AACtE,wBAAgB,gBAAgB,CAAC,eAAe,EAAE,MAAM,GAAG,MAAM,CAMhE;AAED,0HAA0H;AAC1H,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CASzE;AA4BD,+FAA+F;AAC/F,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,GAAG,gBAAgB,EAAE,CAa1F;AAED,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,OAAO,GAAG,kBAAkB,GAAG,SAAS,CAMlF;AAED,6FAA6F;AAC7F,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,GAAG,gBAAgB,GAAG,SAAS,CAiCnG;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,gBAAgB,GAAG,iBAAiB,CAI/E;AA+DD;;;;GAIG;AACH,wBAAsB,eAAe,CACpC,OAAO,EAAE,YAAY,EACrB,OAAO,GAAE,4BAAiC,GACxC,OAAO,CAAC,uBAAuB,CAAC,CAqElC;AAED,uHAAuH;AACvH,wBAAsB,qBAAqB,CAC1C,OAAO,EAAE,YAAY,EACrB,OAAO,GAAE,4BAAiC,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"}
@@ -1,6 +1,7 @@
1
1
  import { VERSION } from "../config.js";
2
2
  import { getPiUserAgent } from "../utils/pi-user-agent.js";
3
3
  import { resolveOpenAICodexAccountIdentity } from "./oauth-account-pool.js";
4
+ import { parseSubscriptionCreditAmount } from "./subscription-credits.js";
4
5
  export const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
5
6
  export const CODEX_USAGE_PROVIDER_ID = "openai-codex";
6
7
  const MIN_WEEK_SECONDS = 6 * 24 * 60 * 60;
@@ -8,7 +9,6 @@ const MAX_WEEK_SECONDS = 8 * 24 * 60 * 60;
8
9
  const DEFAULT_TIMEOUT_MS = 10_000;
9
10
  const DEFAULT_CONCURRENCY = 3;
10
11
  const MAX_TIMEOUT_MS = 2 ** 31 - 1;
11
- const BALANCE_PATTERN = /^-?\d{1,15}(\.\d{1,8})?$/;
12
12
  const REACHED_TYPE_PATTERN = /^[a-z0-9_]{1,64}$/;
13
13
  const MAX_LIMIT_NAME_LENGTH = 40;
14
14
  const MAX_ADDITIONAL_LIMITS = 16;
@@ -113,9 +113,8 @@ export function parseCodexCredits(payload) {
113
113
  const { has_credits: hasCredits, unlimited } = payload.credits;
114
114
  if (typeof hasCredits !== "boolean" || typeof unlimited !== "boolean")
115
115
  return undefined;
116
- const rawBalance = typeof payload.credits.balance === "string" ? payload.credits.balance.trim() : "";
117
- const balance = BALANCE_PATTERN.test(rawBalance) ? rawBalance : "";
118
- return { hasCredits, unlimited, ...(balance ? { balance } : {}) };
116
+ const balance = parseSubscriptionCreditAmount(payload.credits.balance);
117
+ return { hasCredits, unlimited, ...(balance !== undefined ? { balance, unit: "credits" } : {}) };
119
118
  }
120
119
  /** Pure parser, exported for tests. Returns undefined when no valid weekly window exists. */
121
120
  export function parseCodexWeeklyUsage(payload, nowMs) {
@@ -261,11 +260,17 @@ export async function fetchCodexUsage(account, options = {}) {
261
260
  return unavailable("malformed");
262
261
  const usage = parseCodexWeeklyUsage(payload, now);
263
262
  const credits = parseCodexCredits(payload);
263
+ // /wham/usage reports only the banked count, not whether a reset can be redeemed now or its expiry.
264
+ const count = isRecord(payload.rate_limit_reset_credits)
265
+ ? payload.rate_limit_reset_credits.available_count
266
+ : undefined;
267
+ const resets = typeof count === "number" && Number.isSafeInteger(count) && count >= 0 ? { availableCount: count } : undefined;
264
268
  const details = {
265
269
  status: "ok",
266
270
  ...(usage ? { usage } : {}),
267
271
  windows: parseCodexUsageWindows(payload, now),
268
272
  ...(credits ? { credits } : {}),
273
+ ...(resets ? { resets } : {}),
269
274
  };
270
275
  if (usage &&
271
276
  options.accountPool &&