@humain/humain-code 0.8.2 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (946) hide show
  1. package/CHANGELOG.md +152 -0
  2. package/dist/bundle/agent-monitor.js +1 -1
  3. package/dist/bundle/chunks/anthropic-messages-42CGJCSR.js +82 -0
  4. package/dist/bundle/chunks/ask-VH7GNX75.js +97 -0
  5. package/dist/bundle/chunks/azure-openai-responses-DOKKMBUN.js +15 -0
  6. package/dist/bundle/chunks/bedrock-converse-stream.js +200 -179
  7. package/dist/bundle/chunks/bowser-UX7KDMIY.js +92 -0
  8. package/dist/bundle/chunks/{chunk-46C6D7UC.js → chunk-2CYGUEQO.js} +1 -1
  9. package/dist/bundle/chunks/chunk-3RXT35Y3.js +3 -0
  10. package/dist/bundle/chunks/chunk-4BNDLR6C.js +177 -0
  11. package/dist/bundle/chunks/{chunk-MPRAQ6ZI.js → chunk-4LGBXPUD.js} +1 -1
  12. package/dist/bundle/chunks/chunk-4SL6URR3.js +90 -0
  13. package/dist/bundle/chunks/{chunk-PJXBU6CR.js → chunk-52642TYH.js} +394 -204
  14. package/dist/bundle/chunks/{chunk-LSRXA7OS.js → chunk-5C5K4EVJ.js} +3 -3
  15. package/dist/bundle/chunks/{chunk-2JNJJ6SZ.js → chunk-5KUCY54O.js} +3 -3
  16. package/dist/bundle/chunks/{chunk-4TDNOR36.js → chunk-625QJSFJ.js} +1 -1
  17. package/dist/bundle/chunks/chunk-73YX5XGR.js +2461 -0
  18. package/dist/bundle/chunks/chunk-7DIRHF4H.js +17 -0
  19. package/dist/bundle/chunks/{chunk-QJB5YI3I.js → chunk-7PAXKU7M.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-R2KD2HFT.js → chunk-7YB3HRRN.js} +83 -196
  21. package/dist/bundle/chunks/{chunk-DCXHRP6C.js → chunk-A2UZYK23.js} +13 -13
  22. package/dist/bundle/chunks/chunk-A5ZMBTTM.js +12 -0
  23. package/dist/bundle/chunks/{chunk-JKX5EGOT.js → chunk-AER66CNP.js} +13 -13
  24. package/dist/bundle/chunks/chunk-ARTF7ZMQ.js +5 -0
  25. package/dist/bundle/chunks/chunk-B3FT6L6S.js +131 -0
  26. package/dist/bundle/chunks/chunk-BIC5BSNX.js +13 -0
  27. package/dist/bundle/chunks/{chunk-JSHKS7VH.js → chunk-BNZZJ4LO.js} +1 -1
  28. package/dist/bundle/chunks/{chunk-4MKATHT2.js → chunk-CG43CMFH.js} +1 -1
  29. package/dist/bundle/chunks/{chunk-EFY2QPVP.js → chunk-CIAXW64K.js} +16 -16
  30. package/dist/bundle/chunks/{chunk-VFLVWPLZ.js → chunk-CKFLQGJN.js} +20 -16
  31. package/dist/bundle/chunks/chunk-D4UCXXDP.js +115 -0
  32. package/dist/bundle/chunks/{chunk-HQMUDHC3.js → chunk-D6ZWWDW5.js} +6 -5
  33. package/dist/bundle/chunks/{chunk-U4EAJPMO.js → chunk-EVDQRT3I.js} +252 -371
  34. package/dist/bundle/chunks/{chunk-FJIISX5W.js → chunk-F74XLJPC.js} +195 -192
  35. package/dist/bundle/chunks/chunk-FDRBTGFJ.js +4 -0
  36. package/dist/bundle/chunks/{chunk-E4VUW4RI.js → chunk-FLWO3H5J.js} +12 -12
  37. package/dist/bundle/chunks/{chunk-KLSRGGOH.js → chunk-G2PFPQX7.js} +2 -2
  38. package/dist/bundle/chunks/chunk-GMPJWLZS.js +57 -0
  39. package/dist/bundle/chunks/{chunk-M5TVWJ5T.js → chunk-H35P7ROY.js} +462 -441
  40. package/dist/bundle/chunks/chunk-HCHCYBNK.js +2 -0
  41. package/dist/bundle/chunks/{chunk-7WE77IE3.js → chunk-HRNYDRL7.js} +1 -1
  42. package/dist/bundle/chunks/chunk-HWFAAGYK.js +23 -0
  43. package/dist/bundle/chunks/{chunk-G2QMON4O.js → chunk-HWXQCJDP.js} +408 -392
  44. package/dist/bundle/chunks/{chunk-PVNXN2TC.js → chunk-II5C7G67.js} +1 -1
  45. package/dist/bundle/chunks/{chunk-F2H47FRF.js → chunk-IMRZP5SC.js} +182 -137
  46. package/dist/bundle/chunks/{chunk-H2B3WLIM.js → chunk-J5YFXMTM.js} +4 -4
  47. package/dist/bundle/chunks/chunk-J64VNQ6D.js +13 -0
  48. package/dist/bundle/chunks/{chunk-65FLSKDA.js → chunk-K5EFEIFP.js} +5 -4
  49. package/dist/bundle/chunks/{chunk-KI7CHPWC.js → chunk-KJ3QRSSY.js} +46 -43
  50. package/dist/bundle/chunks/{cli-6DJO467D.js → chunk-KSEO2LRK.js} +12 -10
  51. package/dist/bundle/chunks/{chunk-HHWVVNGG.js → chunk-MA2WCMSN.js} +2 -2
  52. package/dist/bundle/chunks/{chunk-L4J7SMJB.js → chunk-MAEKQSFU.js} +1 -1
  53. package/dist/bundle/chunks/chunk-MHQNLTZR.js +8 -0
  54. package/dist/bundle/chunks/chunk-MLOUZAVZ.js +122 -0
  55. package/dist/bundle/chunks/chunk-MQYR4Q6X.js +5 -0
  56. package/dist/bundle/chunks/chunk-MXF3KYLZ.js +4 -0
  57. package/dist/bundle/chunks/{chunk-GY663MNP.js → chunk-MZRTVX7F.js} +1 -1
  58. package/dist/bundle/chunks/chunk-MZYHSWHX.js +59 -0
  59. package/dist/bundle/chunks/{chunk-6HTHDVJC.js → chunk-NPVRWPGX.js} +1 -1
  60. package/dist/bundle/chunks/{chunk-BRSLXHED.js → chunk-O44A4E4K.js} +1 -1
  61. package/dist/bundle/chunks/{chunk-T2ZGMEMV.js → chunk-OADQOW67.js} +175 -260
  62. package/dist/bundle/chunks/chunk-OTVHRZ67.js +17 -0
  63. package/dist/bundle/chunks/{chunk-J4GII2EE.js → chunk-P7SLTLSZ.js} +51 -46
  64. package/dist/bundle/chunks/{chunk-7OZNMWAJ.js → chunk-PPGSQZZF.js} +1 -1
  65. package/dist/bundle/chunks/chunk-PYX6ZCC7.js +29 -0
  66. package/dist/bundle/chunks/chunk-PZ7NYBHJ.js +8 -0
  67. package/dist/bundle/chunks/{chunk-VCMXBP5S.js → chunk-QESIDBMW.js} +1 -7
  68. package/dist/bundle/chunks/chunk-QUWVILLB.js +3 -0
  69. package/dist/bundle/chunks/chunk-QZWUXGY7.js +99 -0
  70. package/dist/bundle/chunks/{chunk-MIAXMK5F.js → chunk-QZXLTW7V.js} +8 -7
  71. package/dist/bundle/chunks/chunk-RP6MWUAP.js +4 -0
  72. package/dist/bundle/chunks/chunk-S2US54IU.js +37 -0
  73. package/dist/bundle/chunks/{chunk-H7UPU2SH.js → chunk-SOE25WIS.js} +1218 -1239
  74. package/dist/bundle/chunks/{chunk-JSZBTGI6.js → chunk-SZZ5PNP6.js} +2 -2
  75. package/dist/bundle/chunks/chunk-T5WECB2D.js +7 -0
  76. package/dist/bundle/chunks/{chunk-2NVGOSBN.js → chunk-T7F2TEIS.js} +37 -13
  77. package/dist/bundle/chunks/{chunk-ZSWU5KKA.js → chunk-UOSJTMCL.js} +7 -3
  78. package/dist/bundle/chunks/{chunk-6P6MMQUH.js → chunk-UTRUALFN.js} +3 -3
  79. package/dist/bundle/chunks/{chunk-PWFM6AQQ.js → chunk-V2HTCZRF.js} +70 -67
  80. package/dist/bundle/chunks/{chunk-JX6YIPNK.js → chunk-WCKS2DPT.js} +1 -1
  81. package/dist/bundle/chunks/chunk-XGOJCV6Z.js +2 -0
  82. package/dist/bundle/chunks/chunk-XGSJX23G.js +1151 -0
  83. package/dist/bundle/chunks/{chunk-7WETECIB.js → chunk-Z7BWHPJ2.js} +1 -1
  84. package/dist/bundle/chunks/chunk-ZFFDBTG3.js +17 -0
  85. package/dist/bundle/chunks/cli-NJLV3XDZ.js +3 -0
  86. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-JEZVYITT.js → cloudflare-workers-ai-system-one-ZAZW4M4B.js} +1 -1
  87. package/dist/bundle/chunks/{compat-ELBUCH6U.js → compat-7UJJAO4E.js} +12 -12
  88. package/dist/bundle/chunks/{curator-server-QB4GITGS.js → curator-server-MW645JI3.js} +2 -2
  89. package/dist/bundle/chunks/{dist-NERIS6SW.js → dist-7PCCEUQF.js} +2 -2
  90. package/dist/bundle/chunks/{dist-QSYDYE3Y.js → dist-I53JI67E.js} +9 -9
  91. package/dist/bundle/chunks/{dist-35STTNYA.js → dist-NI2PTSLH.js} +1 -1
  92. package/dist/bundle/chunks/{dist-CBODG4CA.js → dist-VXQT3DQY.js} +6 -6
  93. package/dist/bundle/chunks/{dist-cjs-EROMDUKS.js → dist-cjs-4JQA6W3S.js} +31 -31
  94. package/dist/bundle/chunks/doctor-KJVAYG3F.js +83 -0
  95. package/dist/bundle/chunks/{easter-egg-3d-VZC5WOYV.js → easter-egg-3d-Z24JLXD4.js} +1 -1
  96. package/dist/bundle/chunks/entry-3EL6GOWK.js +2 -0
  97. package/dist/bundle/chunks/{entry-SRYLSS5P.js → entry-4IMREZBD.js} +80 -79
  98. package/dist/bundle/chunks/{execute-6MEJJF2T.js → execute-C4BZQRPQ.js} +23 -22
  99. package/dist/bundle/chunks/{extract-L373D6O7.js → extract-XVQCIS7D.js} +5 -5
  100. package/dist/bundle/chunks/{flow-implementer-3P3BHQ7E.js → flow-implementer-GE2ARQKR.js} +5 -5
  101. package/dist/bundle/chunks/github-copilot.js +57 -56
  102. package/dist/bundle/chunks/google-generative-ai-P2P45MYP.js +22 -0
  103. package/dist/bundle/chunks/google-vertex-SHY4IS5F.js +26 -0
  104. package/dist/bundle/chunks/{host-WOLZCWQQ.js → host-YESS2VAB.js} +1 -1
  105. package/dist/bundle/chunks/{index.bundle-HONF3PUD.js → index.bundle-TZT64KLH.js} +102 -89
  106. package/dist/bundle/chunks/{inprocess-3PDJKE5F.js → inprocess-MGMVI6HN.js} +6 -6
  107. package/dist/bundle/chunks/interactive-mode-HHWOE4FD.js +5 -0
  108. package/dist/bundle/chunks/{llama-cpp-classify-KYZT532X.js → llama-cpp-classify-RSRH4KV2.js} +5 -5
  109. package/dist/bundle/chunks/mistral-conversations-YTMJKHHI.js +42 -0
  110. package/dist/bundle/chunks/{node-N7TPBUJB.js → node-FF6QQQLH.js} +1 -1
  111. package/dist/bundle/chunks/openai-codex-responses-NUCJOJSZ.js +97 -0
  112. package/dist/bundle/chunks/openai-completions-E5NRJUHA.js +91 -0
  113. package/dist/bundle/chunks/{openai-decisions-JMSDGR7K.js → openai-decisions-342J5ZYG.js} +1 -1
  114. package/dist/bundle/chunks/openai-responses-BN5Z4HFI.js +26 -0
  115. package/dist/bundle/chunks/openrouter-images-7RNG3JVF.js +12 -0
  116. package/dist/bundle/chunks/{pdfjs-FE3L72A6.js → pdfjs-LSTLRXQW.js} +1415 -1416
  117. package/dist/bundle/chunks/pi-messages-2L7FV5OK.js +22 -0
  118. package/dist/bundle/chunks/questionnaire-session-XEVAK7JS.js +123 -0
  119. package/dist/bundle/chunks/runtime-2FSZRUG5.js +2 -0
  120. package/dist/bundle/chunks/session-picker-666KJIVM.js +4 -0
  121. package/dist/bundle/chunks/startup-ui-INEVSNGK.js +3 -0
  122. package/dist/bundle/chunks/{trace-command-VM7FBWPE.js → trace-command-BCVMZ5ZD.js} +4 -4
  123. package/dist/bundle/chunks/typesafe-system-one-UJUNSZG4.js +3 -0
  124. package/dist/bundle/chunks/{undici-WVNE45GY.js → undici-7IGAYA4S.js} +1 -1
  125. package/dist/bundle/chunks/virtual-modules-UXSSFNV5.js +29 -0
  126. package/dist/bundle/cli-runtime.js +5 -5
  127. package/dist/bundle/flow/package.json +3 -3
  128. package/dist/bundle/index.js +13 -13
  129. package/dist/bundle/orchestrate/package.json +1 -1
  130. package/dist/bundle/rpc-entry.js +5 -4
  131. package/dist/cli/agent-dir-arg.d.ts +12 -0
  132. package/dist/cli/agent-dir-arg.d.ts.map +1 -0
  133. package/dist/cli/agent-dir-arg.js +15 -0
  134. package/dist/cli/agent-dir-arg.js.map +1 -0
  135. package/dist/cli/args.d.ts +9 -0
  136. package/dist/cli/args.d.ts.map +1 -1
  137. package/dist/cli/args.js +19 -5
  138. package/dist/cli/args.js.map +1 -1
  139. package/dist/cli/auth-check.d.ts +1 -1
  140. package/dist/cli/auth-check.d.ts.map +1 -1
  141. package/dist/cli/auth-check.js +4 -2
  142. package/dist/cli/auth-check.js.map +1 -1
  143. package/dist/cli/doctor-config.d.ts +14 -0
  144. package/dist/cli/doctor-config.d.ts.map +1 -0
  145. package/dist/cli/doctor-config.js +92 -0
  146. package/dist/cli/doctor-config.js.map +1 -0
  147. package/dist/cli/doctor-system.d.ts +12 -0
  148. package/dist/cli/doctor-system.d.ts.map +1 -0
  149. package/dist/cli/doctor-system.js +109 -0
  150. package/dist/cli/doctor-system.js.map +1 -0
  151. package/dist/cli/doctor.d.ts +11 -0
  152. package/dist/cli/doctor.d.ts.map +1 -0
  153. package/dist/cli/doctor.js +323 -0
  154. package/dist/cli/doctor.js.map +1 -0
  155. package/dist/cli/doctor.lazy.d.ts +3 -0
  156. package/dist/cli/doctor.lazy.d.ts.map +1 -0
  157. package/dist/cli/doctor.lazy.js +3 -0
  158. package/dist/cli/doctor.lazy.js.map +1 -0
  159. package/dist/cli/list-models.d.ts.map +1 -1
  160. package/dist/cli/list-models.js +0 -4
  161. package/dist/cli/list-models.js.map +1 -1
  162. package/dist/cli/project-trust.d.ts.map +1 -1
  163. package/dist/cli/project-trust.js +6 -6
  164. package/dist/cli/project-trust.js.map +1 -1
  165. package/dist/cli/startup-ui.d.ts +3 -2
  166. package/dist/cli/startup-ui.d.ts.map +1 -1
  167. package/dist/cli/startup-ui.js +23 -10
  168. package/dist/cli/startup-ui.js.map +1 -1
  169. package/dist/config.d.ts +5 -1
  170. package/dist/config.d.ts.map +1 -1
  171. package/dist/config.js +13 -3
  172. package/dist/config.js.map +1 -1
  173. package/dist/coordination/adapter/delivery.d.ts +27 -0
  174. package/dist/coordination/adapter/delivery.d.ts.map +1 -1
  175. package/dist/coordination/adapter/delivery.js +164 -4
  176. package/dist/coordination/adapter/delivery.js.map +1 -1
  177. package/dist/coordination/adapter/index.d.ts.map +1 -1
  178. package/dist/coordination/adapter/index.js +31 -5
  179. package/dist/coordination/adapter/index.js.map +1 -1
  180. package/dist/coordination/adapter/presence.d.ts +5 -0
  181. package/dist/coordination/adapter/presence.d.ts.map +1 -1
  182. package/dist/coordination/adapter/presence.js +25 -3
  183. package/dist/coordination/adapter/presence.js.map +1 -1
  184. package/dist/coordination/adapter/question-routing.d.ts +7 -0
  185. package/dist/coordination/adapter/question-routing.d.ts.map +1 -0
  186. package/dist/coordination/adapter/question-routing.js +40 -0
  187. package/dist/coordination/adapter/question-routing.js.map +1 -0
  188. package/dist/coordination/adapter/receipts.d.ts +7 -0
  189. package/dist/coordination/adapter/receipts.d.ts.map +1 -1
  190. package/dist/coordination/adapter/receipts.js +25 -2
  191. package/dist/coordination/adapter/receipts.js.map +1 -1
  192. package/dist/coordination/adapter/tool.d.ts +19 -3
  193. package/dist/coordination/adapter/tool.d.ts.map +1 -1
  194. package/dist/coordination/adapter/tool.js +93 -19
  195. package/dist/coordination/adapter/tool.js.map +1 -1
  196. package/dist/coordination/broker/broker.d.ts +3 -3
  197. package/dist/coordination/broker/broker.d.ts.map +1 -1
  198. package/dist/coordination/broker/broker.js +15 -7
  199. package/dist/coordination/broker/broker.js.map +1 -1
  200. package/dist/coordination/client/client.d.ts +2 -2
  201. package/dist/coordination/client/client.d.ts.map +1 -1
  202. package/dist/coordination/client/client.js +4 -0
  203. package/dist/coordination/client/client.js.map +1 -1
  204. package/dist/coordination/transport/protocol.d.ts.map +1 -1
  205. package/dist/coordination/transport/protocol.js +23 -0
  206. package/dist/coordination/transport/protocol.js.map +1 -1
  207. package/dist/coordination/transport/types.d.ts +11 -1
  208. package/dist/coordination/transport/types.d.ts.map +1 -1
  209. package/dist/coordination/transport/types.js.map +1 -1
  210. package/dist/core/acceptance-command.d.ts +6 -3
  211. package/dist/core/acceptance-command.d.ts.map +1 -1
  212. package/dist/core/acceptance-command.js +43 -12
  213. package/dist/core/acceptance-command.js.map +1 -1
  214. package/dist/core/acceptance-ledger.d.ts +2 -0
  215. package/dist/core/acceptance-ledger.d.ts.map +1 -1
  216. package/dist/core/acceptance-ledger.js +14 -3
  217. package/dist/core/acceptance-ledger.js.map +1 -1
  218. package/dist/core/agent-session-runtime.d.ts +11 -4
  219. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  220. package/dist/core/agent-session-runtime.js +13 -4
  221. package/dist/core/agent-session-runtime.js.map +1 -1
  222. package/dist/core/agent-session-services.d.ts.map +1 -1
  223. package/dist/core/agent-session-services.js +6 -0
  224. package/dist/core/agent-session-services.js.map +1 -1
  225. package/dist/core/agent-session.d.ts +19 -1
  226. package/dist/core/agent-session.d.ts.map +1 -1
  227. package/dist/core/agent-session.js +131 -36
  228. package/dist/core/agent-session.js.map +1 -1
  229. package/dist/core/auth-storage.d.ts.map +1 -1
  230. package/dist/core/auth-storage.js +7 -1
  231. package/dist/core/auth-storage.js.map +1 -1
  232. package/dist/core/bash-executor.d.ts +3 -1
  233. package/dist/core/bash-executor.d.ts.map +1 -1
  234. package/dist/core/bash-executor.js +18 -8
  235. package/dist/core/bash-executor.js.map +1 -1
  236. package/dist/core/compaction/branch-summarization.d.ts +2 -2
  237. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  238. package/dist/core/compaction/branch-summarization.js +9 -15
  239. package/dist/core/compaction/branch-summarization.js.map +1 -1
  240. package/dist/core/compaction/compaction.d.ts.map +1 -1
  241. package/dist/core/compaction/compaction.js +3 -0
  242. package/dist/core/compaction/compaction.js.map +1 -1
  243. package/dist/core/export-html/index.d.ts.map +1 -1
  244. package/dist/core/export-html/index.js +12 -10
  245. package/dist/core/export-html/index.js.map +1 -1
  246. package/dist/core/export-html/template.js +23 -1
  247. package/dist/core/extensions/runner.d.ts.map +1 -1
  248. package/dist/core/extensions/runner.js +13 -2
  249. package/dist/core/extensions/runner.js.map +1 -1
  250. package/dist/core/extensions/types.d.ts +9 -1
  251. package/dist/core/extensions/types.d.ts.map +1 -1
  252. package/dist/core/extensions/types.js.map +1 -1
  253. package/dist/core/footer-data-provider.d.ts.map +1 -1
  254. package/dist/core/footer-data-provider.js +2 -4
  255. package/dist/core/footer-data-provider.js.map +1 -1
  256. package/dist/core/http-dispatcher.d.ts +5 -2
  257. package/dist/core/http-dispatcher.d.ts.map +1 -1
  258. package/dist/core/http-dispatcher.js +6 -3
  259. package/dist/core/http-dispatcher.js.map +1 -1
  260. package/dist/core/keybindings.d.ts +20 -0
  261. package/dist/core/keybindings.d.ts.map +1 -1
  262. package/dist/core/keybindings.js +4 -1
  263. package/dist/core/keybindings.js.map +1 -1
  264. package/dist/core/mcp-servers.d.ts +29 -0
  265. package/dist/core/mcp-servers.d.ts.map +1 -1
  266. package/dist/core/mcp-servers.js +63 -17
  267. package/dist/core/mcp-servers.js.map +1 -1
  268. package/dist/core/messages.d.ts +4 -0
  269. package/dist/core/messages.d.ts.map +1 -1
  270. package/dist/core/messages.js +10 -2
  271. package/dist/core/messages.js.map +1 -1
  272. package/dist/core/model-config.d.ts +36 -0
  273. package/dist/core/model-config.d.ts.map +1 -1
  274. package/dist/core/model-resolver.js +1 -1
  275. package/dist/core/model-resolver.js.map +1 -1
  276. package/dist/core/model-runtime.d.ts.map +1 -1
  277. package/dist/core/model-runtime.js +20 -10
  278. package/dist/core/model-runtime.js.map +1 -1
  279. package/dist/core/nested-tool-calls.d.ts +6 -5
  280. package/dist/core/nested-tool-calls.d.ts.map +1 -1
  281. package/dist/core/nested-tool-calls.js +1 -3
  282. package/dist/core/nested-tool-calls.js.map +1 -1
  283. package/dist/core/oauth-account-pool.d.ts +14 -0
  284. package/dist/core/oauth-account-pool.d.ts.map +1 -1
  285. package/dist/core/oauth-account-pool.js +166 -14
  286. package/dist/core/oauth-account-pool.js.map +1 -1
  287. package/dist/core/os-secret-store.js +1 -1
  288. package/dist/core/os-secret-store.js.map +1 -1
  289. package/dist/core/package-manager.d.ts +3 -1
  290. package/dist/core/package-manager.d.ts.map +1 -1
  291. package/dist/core/package-manager.js +25 -4
  292. package/dist/core/package-manager.js.map +1 -1
  293. package/dist/core/pi-ai-schemas.d.ts +4 -0
  294. package/dist/core/pi-ai-schemas.d.ts.map +1 -1
  295. package/dist/core/project-trust.d.ts.map +1 -1
  296. package/dist/core/project-trust.js +1 -1
  297. package/dist/core/project-trust.js.map +1 -1
  298. package/dist/core/provider-composer.d.ts +1 -0
  299. package/dist/core/provider-composer.d.ts.map +1 -1
  300. package/dist/core/provider-composer.js +1 -0
  301. package/dist/core/provider-composer.js.map +1 -1
  302. package/dist/core/resolve-config-value.d.ts +4 -0
  303. package/dist/core/resolve-config-value.d.ts.map +1 -1
  304. package/dist/core/resolve-config-value.js +14 -3
  305. package/dist/core/resolve-config-value.js.map +1 -1
  306. package/dist/core/resource-loader.d.ts.map +1 -1
  307. package/dist/core/resource-loader.js +40 -2
  308. package/dist/core/resource-loader.js.map +1 -1
  309. package/dist/core/run-outcome.d.ts +1 -1
  310. package/dist/core/run-outcome.d.ts.map +1 -1
  311. package/dist/core/run-outcome.js +2 -2
  312. package/dist/core/run-outcome.js.map +1 -1
  313. package/dist/core/run-preflight.d.ts.map +1 -1
  314. package/dist/core/run-preflight.js +15 -8
  315. package/dist/core/run-preflight.js.map +1 -1
  316. package/dist/core/runtime-credentials.d.ts.map +1 -1
  317. package/dist/core/runtime-credentials.js +11 -7
  318. package/dist/core/runtime-credentials.js.map +1 -1
  319. package/dist/core/sdk.d.ts.map +1 -1
  320. package/dist/core/sdk.js +8 -4
  321. package/dist/core/sdk.js.map +1 -1
  322. package/dist/core/session-manager.d.ts +22 -1
  323. package/dist/core/session-manager.d.ts.map +1 -1
  324. package/dist/core/session-manager.js +227 -37
  325. package/dist/core/session-manager.js.map +1 -1
  326. package/dist/core/settings-defaults.d.ts +10 -1
  327. package/dist/core/settings-defaults.d.ts.map +1 -1
  328. package/dist/core/settings-defaults.js +7 -1
  329. package/dist/core/settings-defaults.js.map +1 -1
  330. package/dist/core/settings-manager.d.ts +14 -4
  331. package/dist/core/settings-manager.d.ts.map +1 -1
  332. package/dist/core/settings-manager.js +48 -15
  333. package/dist/core/settings-manager.js.map +1 -1
  334. package/dist/core/settings-schema.d.ts +20 -2
  335. package/dist/core/settings-schema.d.ts.map +1 -1
  336. package/dist/core/settings-schema.js +27 -4
  337. package/dist/core/settings-schema.js.map +1 -1
  338. package/dist/core/slash-commands.d.ts.map +1 -1
  339. package/dist/core/slash-commands.js +2 -0
  340. package/dist/core/slash-commands.js.map +1 -1
  341. package/dist/core/tools/bash-jobs.js +2 -2
  342. package/dist/core/tools/bash-jobs.js.map +1 -1
  343. package/dist/core/tools/bash.d.ts +3 -0
  344. package/dist/core/tools/bash.d.ts.map +1 -1
  345. package/dist/core/tools/bash.js +78 -46
  346. package/dist/core/tools/bash.js.map +1 -1
  347. package/dist/core/tools/edit-diff.d.ts +7 -1
  348. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  349. package/dist/core/tools/edit-diff.js +139 -75
  350. package/dist/core/tools/edit-diff.js.map +1 -1
  351. package/dist/core/tools/edit.d.ts.map +1 -1
  352. package/dist/core/tools/edit.js +4 -1
  353. package/dist/core/tools/edit.js.map +1 -1
  354. package/dist/core/tools/output-accumulator.d.ts +21 -6
  355. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  356. package/dist/core/tools/output-accumulator.js +90 -76
  357. package/dist/core/tools/output-accumulator.js.map +1 -1
  358. package/dist/core/tools/render-utils.d.ts +7 -2
  359. package/dist/core/tools/render-utils.d.ts.map +1 -1
  360. package/dist/core/tools/render-utils.js +14 -1
  361. package/dist/core/tools/render-utils.js.map +1 -1
  362. package/dist/core/tools/renderers/bash.d.ts.map +1 -1
  363. package/dist/core/tools/renderers/bash.js +9 -3
  364. package/dist/core/tools/renderers/bash.js.map +1 -1
  365. package/dist/core/tools/truncate.d.ts +1 -1
  366. package/dist/core/tools/truncate.d.ts.map +1 -1
  367. package/dist/core/tools/truncate.js +16 -7
  368. package/dist/core/tools/truncate.js.map +1 -1
  369. package/dist/core/tools/write.d.ts.map +1 -1
  370. package/dist/core/tools/write.js +2 -0
  371. package/dist/core/tools/write.js.map +1 -1
  372. package/dist/core/trust-manager.d.ts +2 -0
  373. package/dist/core/trust-manager.d.ts.map +1 -1
  374. package/dist/core/trust-manager.js +5 -4
  375. package/dist/core/trust-manager.js.map +1 -1
  376. package/dist/core/usage-totals.d.ts.map +1 -1
  377. package/dist/core/usage-totals.js +3 -0
  378. package/dist/core/usage-totals.js.map +1 -1
  379. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  380. package/dist/extensions/codemode/execute.js +64 -20
  381. package/dist/extensions/codemode/execute.js.map +1 -1
  382. package/dist/extensions/codemode/renderer.d.ts.map +1 -1
  383. package/dist/extensions/codemode/renderer.js +8 -3
  384. package/dist/extensions/codemode/renderer.js.map +1 -1
  385. package/dist/extensions/codemode/tool.d.ts +5 -0
  386. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  387. package/dist/extensions/codemode/tool.js.map +1 -1
  388. package/dist/extensions/llama/client.d.ts.map +1 -1
  389. package/dist/extensions/llama/client.js +3 -13
  390. package/dist/extensions/llama/client.js.map +1 -1
  391. package/dist/extensions/llama/ui.d.ts.map +1 -1
  392. package/dist/extensions/llama/ui.js +2 -1
  393. package/dist/extensions/llama/ui.js.map +1 -1
  394. package/dist/extensions/mcp/cli.d.ts +7 -0
  395. package/dist/extensions/mcp/cli.d.ts.map +1 -1
  396. package/dist/extensions/mcp/cli.js +35 -8
  397. package/dist/extensions/mcp/cli.js.map +1 -1
  398. package/dist/extensions/mcp/config.d.ts +33 -0
  399. package/dist/extensions/mcp/config.d.ts.map +1 -1
  400. package/dist/extensions/mcp/config.js +11 -2
  401. package/dist/extensions/mcp/config.js.map +1 -1
  402. package/dist/extensions/mcp/index.d.ts +8 -0
  403. package/dist/extensions/mcp/index.d.ts.map +1 -1
  404. package/dist/extensions/mcp/index.js +16 -0
  405. package/dist/extensions/mcp/index.js.map +1 -1
  406. package/dist/extensions/mcp/resources.d.ts +1 -1
  407. package/dist/extensions/mcp/resources.d.ts.map +1 -1
  408. package/dist/extensions/mcp/resources.js +4 -3
  409. package/dist/extensions/mcp/resources.js.map +1 -1
  410. package/dist/extensions/mcp/runtime.d.ts +1 -1
  411. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  412. package/dist/extensions/mcp/runtime.js +15 -14
  413. package/dist/extensions/mcp/runtime.js.map +1 -1
  414. package/dist/extensions/mcp/tools.d.ts +1 -24
  415. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  416. package/dist/extensions/mcp/tools.js +10 -163
  417. package/dist/extensions/mcp/tools.js.map +1 -1
  418. package/dist/humain/ask-user-question/index.d.ts +4 -0
  419. package/dist/humain/ask-user-question/index.d.ts.map +1 -0
  420. package/dist/humain/ask-user-question/index.js +18 -0
  421. package/dist/humain/ask-user-question/index.js.map +1 -0
  422. package/dist/humain/ask-user-question/vendor/ask/answer-channel.d.ts +38 -0
  423. package/dist/humain/ask-user-question/vendor/ask/answer-channel.d.ts.map +1 -0
  424. package/dist/humain/ask-user-question/vendor/ask/answer-channel.js +97 -0
  425. package/dist/humain/ask-user-question/vendor/ask/answer-channel.js.map +1 -0
  426. package/dist/humain/ask-user-question/vendor/ask/ask-user-question.d.ts +41 -0
  427. package/dist/humain/ask-user-question/vendor/ask/ask-user-question.d.ts.map +1 -0
  428. package/dist/humain/ask-user-question/vendor/ask/ask-user-question.js +441 -0
  429. package/dist/humain/ask-user-question/vendor/ask/ask-user-question.js.map +1 -0
  430. package/dist/humain/ask-user-question/vendor/ask/config.d.ts +39 -0
  431. package/dist/humain/ask-user-question/vendor/ask/config.d.ts.map +1 -0
  432. package/dist/humain/ask-user-question/vendor/ask/config.js +95 -0
  433. package/dist/humain/ask-user-question/vendor/ask/config.js.map +1 -0
  434. package/dist/humain/ask-user-question/vendor/ask/events.d.ts +132 -0
  435. package/dist/humain/ask-user-question/vendor/ask/events.d.ts.map +1 -0
  436. package/dist/humain/ask-user-question/vendor/ask/events.js +50 -0
  437. package/dist/humain/ask-user-question/vendor/ask/events.js.map +1 -0
  438. package/dist/humain/ask-user-question/vendor/ask/index.d.ts +5 -0
  439. package/dist/humain/ask-user-question/vendor/ask/index.d.ts.map +1 -0
  440. package/dist/humain/ask-user-question/vendor/ask/index.js +15 -0
  441. package/dist/humain/ask-user-question/vendor/ask/index.js.map +1 -0
  442. package/dist/humain/ask-user-question/vendor/ask/presentation.d.ts +81 -0
  443. package/dist/humain/ask-user-question/vendor/ask/presentation.d.ts.map +1 -0
  444. package/dist/humain/ask-user-question/vendor/ask/presentation.js +105 -0
  445. package/dist/humain/ask-user-question/vendor/ask/presentation.js.map +1 -0
  446. package/dist/humain/ask-user-question/vendor/ask/reconcile.d.ts +28 -0
  447. package/dist/humain/ask-user-question/vendor/ask/reconcile.d.ts.map +1 -0
  448. package/dist/humain/ask-user-question/vendor/ask/reconcile.js +45 -0
  449. package/dist/humain/ask-user-question/vendor/ask/reconcile.js.map +1 -0
  450. package/dist/humain/ask-user-question/vendor/ask/rpc-fallback.d.ts +41 -0
  451. package/dist/humain/ask-user-question/vendor/ask/rpc-fallback.d.ts.map +1 -0
  452. package/dist/humain/ask-user-question/vendor/ask/rpc-fallback.js +166 -0
  453. package/dist/humain/ask-user-question/vendor/ask/rpc-fallback.js.map +1 -0
  454. package/dist/humain/ask-user-question/vendor/ask/state/build-questionnaire.d.ts +46 -0
  455. package/dist/humain/ask-user-question/vendor/ask/state/build-questionnaire.d.ts.map +1 -0
  456. package/dist/humain/ask-user-question/vendor/ask/state/build-questionnaire.js +247 -0
  457. package/dist/humain/ask-user-question/vendor/ask/state/build-questionnaire.js.map +1 -0
  458. package/dist/humain/ask-user-question/vendor/ask/state/external-editor.d.ts +11 -0
  459. package/dist/humain/ask-user-question/vendor/ask/state/external-editor.d.ts.map +1 -0
  460. package/dist/humain/ask-user-question/vendor/ask/state/external-editor.js +56 -0
  461. package/dist/humain/ask-user-question/vendor/ask/state/external-editor.js.map +1 -0
  462. package/dist/humain/ask-user-question/vendor/ask/state/i18n-bridge.d.ts +6 -0
  463. package/dist/humain/ask-user-question/vendor/ask/state/i18n-bridge.d.ts.map +1 -0
  464. package/dist/humain/ask-user-question/vendor/ask/state/i18n-bridge.js +10 -0
  465. package/dist/humain/ask-user-question/vendor/ask/state/i18n-bridge.js.map +1 -0
  466. package/dist/humain/ask-user-question/vendor/ask/state/key-router.d.ts +57 -0
  467. package/dist/humain/ask-user-question/vendor/ask/state/key-router.d.ts.map +1 -0
  468. package/dist/humain/ask-user-question/vendor/ask/state/key-router.js +357 -0
  469. package/dist/humain/ask-user-question/vendor/ask/state/key-router.js.map +1 -0
  470. package/dist/humain/ask-user-question/vendor/ask/state/questionnaire-session.d.ts +112 -0
  471. package/dist/humain/ask-user-question/vendor/ask/state/questionnaire-session.d.ts.map +1 -0
  472. package/dist/humain/ask-user-question/vendor/ask/state/questionnaire-session.js +240 -0
  473. package/dist/humain/ask-user-question/vendor/ask/state/questionnaire-session.js.map +1 -0
  474. package/dist/humain/ask-user-question/vendor/ask/state/row-intent.d.ts +87 -0
  475. package/dist/humain/ask-user-question/vendor/ask/state/row-intent.d.ts.map +1 -0
  476. package/dist/humain/ask-user-question/vendor/ask/state/row-intent.js +79 -0
  477. package/dist/humain/ask-user-question/vendor/ask/state/row-intent.js.map +1 -0
  478. package/dist/humain/ask-user-question/vendor/ask/state/selectors/contract.d.ts +22 -0
  479. package/dist/humain/ask-user-question/vendor/ask/state/selectors/contract.d.ts.map +1 -0
  480. package/dist/humain/ask-user-question/vendor/ask/state/selectors/contract.js +2 -0
  481. package/dist/humain/ask-user-question/vendor/ask/state/selectors/contract.js.map +1 -0
  482. package/dist/humain/ask-user-question/vendor/ask/state/selectors/derivations.d.ts +27 -0
  483. package/dist/humain/ask-user-question/vendor/ask/state/selectors/derivations.d.ts.map +1 -0
  484. package/dist/humain/ask-user-question/vendor/ask/state/selectors/derivations.js +48 -0
  485. package/dist/humain/ask-user-question/vendor/ask/state/selectors/derivations.js.map +1 -0
  486. package/dist/humain/ask-user-question/vendor/ask/state/selectors/focus.d.ts +13 -0
  487. package/dist/humain/ask-user-question/vendor/ask/state/selectors/focus.d.ts.map +1 -0
  488. package/dist/humain/ask-user-question/vendor/ask/state/selectors/focus.js +15 -0
  489. package/dist/humain/ask-user-question/vendor/ask/state/selectors/focus.js.map +1 -0
  490. package/dist/humain/ask-user-question/vendor/ask/state/selectors/projections.d.ts +14 -0
  491. package/dist/humain/ask-user-question/vendor/ask/state/selectors/projections.d.ts.map +1 -0
  492. package/dist/humain/ask-user-question/vendor/ask/state/selectors/projections.js +96 -0
  493. package/dist/humain/ask-user-question/vendor/ask/state/selectors/projections.js.map +1 -0
  494. package/dist/humain/ask-user-question/vendor/ask/state/state-reducer.d.ts +58 -0
  495. package/dist/humain/ask-user-question/vendor/ask/state/state-reducer.d.ts.map +1 -0
  496. package/dist/humain/ask-user-question/vendor/ask/state/state-reducer.js +310 -0
  497. package/dist/humain/ask-user-question/vendor/ask/state/state-reducer.js.map +1 -0
  498. package/dist/humain/ask-user-question/vendor/ask/state/state.d.ts +68 -0
  499. package/dist/humain/ask-user-question/vendor/ask/state/state.d.ts.map +1 -0
  500. package/dist/humain/ask-user-question/vendor/ask/state/state.js +2 -0
  501. package/dist/humain/ask-user-question/vendor/ask/state/state.js.map +1 -0
  502. package/dist/humain/ask-user-question/vendor/ask/tool/external-answer.d.ts +24 -0
  503. package/dist/humain/ask-user-question/vendor/ask/tool/external-answer.d.ts.map +1 -0
  504. package/dist/humain/ask-user-question/vendor/ask/tool/external-answer.js +114 -0
  505. package/dist/humain/ask-user-question/vendor/ask/tool/external-answer.js.map +1 -0
  506. package/dist/humain/ask-user-question/vendor/ask/tool/format-answer.d.ts +18 -0
  507. package/dist/humain/ask-user-question/vendor/ask/tool/format-answer.d.ts.map +1 -0
  508. package/dist/humain/ask-user-question/vendor/ask/tool/format-answer.js +29 -0
  509. package/dist/humain/ask-user-question/vendor/ask/tool/format-answer.js.map +1 -0
  510. package/dist/humain/ask-user-question/vendor/ask/tool/normalize-params.d.ts +41 -0
  511. package/dist/humain/ask-user-question/vendor/ask/tool/normalize-params.d.ts.map +1 -0
  512. package/dist/humain/ask-user-question/vendor/ask/tool/normalize-params.js +99 -0
  513. package/dist/humain/ask-user-question/vendor/ask/tool/normalize-params.js.map +1 -0
  514. package/dist/humain/ask-user-question/vendor/ask/tool/response-envelope.d.ts +37 -0
  515. package/dist/humain/ask-user-question/vendor/ask/tool/response-envelope.d.ts.map +1 -0
  516. package/dist/humain/ask-user-question/vendor/ask/tool/response-envelope.js +70 -0
  517. package/dist/humain/ask-user-question/vendor/ask/tool/response-envelope.js.map +1 -0
  518. package/dist/humain/ask-user-question/vendor/ask/tool/types.d.ts +129 -0
  519. package/dist/humain/ask-user-question/vendor/ask/tool/types.d.ts.map +1 -0
  520. package/dist/humain/ask-user-question/vendor/ask/tool/types.js +76 -0
  521. package/dist/humain/ask-user-question/vendor/ask/tool/types.js.map +1 -0
  522. package/dist/humain/ask-user-question/vendor/ask/tool/validate-questionnaire.d.ts +21 -0
  523. package/dist/humain/ask-user-question/vendor/ask/tool/validate-questionnaire.d.ts.map +1 -0
  524. package/dist/humain/ask-user-question/vendor/ask/tool/validate-questionnaire.js +49 -0
  525. package/dist/humain/ask-user-question/vendor/ask/tool/validate-questionnaire.js.map +1 -0
  526. package/dist/humain/ask-user-question/vendor/ask/view/component-binding.d.ts +23 -0
  527. package/dist/humain/ask-user-question/vendor/ask/view/component-binding.d.ts.map +1 -0
  528. package/dist/humain/ask-user-question/vendor/ask/view/component-binding.js +16 -0
  529. package/dist/humain/ask-user-question/vendor/ask/view/component-binding.js.map +1 -0
  530. package/dist/humain/ask-user-question/vendor/ask/view/components/inline-input.d.ts +21 -0
  531. package/dist/humain/ask-user-question/vendor/ask/view/components/inline-input.d.ts.map +1 -0
  532. package/dist/humain/ask-user-question/vendor/ask/view/components/inline-input.js +49 -0
  533. package/dist/humain/ask-user-question/vendor/ask/view/components/inline-input.js.map +1 -0
  534. package/dist/humain/ask-user-question/vendor/ask/view/components/multi-select-view.d.ts +43 -0
  535. package/dist/humain/ask-user-question/vendor/ask/view/components/multi-select-view.d.ts.map +1 -0
  536. package/dist/humain/ask-user-question/vendor/ask/view/components/multi-select-view.js +130 -0
  537. package/dist/humain/ask-user-question/vendor/ask/view/components/multi-select-view.js.map +1 -0
  538. package/dist/humain/ask-user-question/vendor/ask/view/components/option-list-view.d.ts +45 -0
  539. package/dist/humain/ask-user-question/vendor/ask/view/components/option-list-view.d.ts.map +1 -0
  540. package/dist/humain/ask-user-question/vendor/ask/view/components/option-list-view.js +39 -0
  541. package/dist/humain/ask-user-question/vendor/ask/view/components/option-list-view.js.map +1 -0
  542. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/markdown-content-cache.d.ts +36 -0
  543. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/markdown-content-cache.d.ts.map +1 -0
  544. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/markdown-content-cache.js +72 -0
  545. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/markdown-content-cache.js.map +1 -0
  546. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-block-renderer.d.ts +61 -0
  547. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-block-renderer.d.ts.map +1 -0
  548. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-block-renderer.js +108 -0
  549. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-block-renderer.js.map +1 -0
  550. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-box-renderer.d.ts +39 -0
  551. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-box-renderer.d.ts.map +1 -0
  552. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-box-renderer.js +76 -0
  553. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-box-renderer.js.map +1 -0
  554. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-layout-decider.d.ts +123 -0
  555. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-layout-decider.d.ts.map +1 -0
  556. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-layout-decider.js +180 -0
  557. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-layout-decider.js.map +1 -0
  558. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-pane.d.ts +108 -0
  559. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-pane.d.ts.map +1 -0
  560. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-pane.js +235 -0
  561. package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-pane.js.map +1 -0
  562. package/dist/humain/ask-user-question/vendor/ask/view/components/submit-picker.d.ts +37 -0
  563. package/dist/humain/ask-user-question/vendor/ask/view/components/submit-picker.d.ts.map +1 -0
  564. package/dist/humain/ask-user-question/vendor/ask/view/components/submit-picker.js +47 -0
  565. package/dist/humain/ask-user-question/vendor/ask/view/components/submit-picker.js.map +1 -0
  566. package/dist/humain/ask-user-question/vendor/ask/view/components/tab-bar.d.ts +31 -0
  567. package/dist/humain/ask-user-question/vendor/ask/view/components/tab-bar.d.ts.map +1 -0
  568. package/dist/humain/ask-user-question/vendor/ask/view/components/tab-bar.js +35 -0
  569. package/dist/humain/ask-user-question/vendor/ask/view/components/tab-bar.js.map +1 -0
  570. package/dist/humain/ask-user-question/vendor/ask/view/components/wrapping-select.d.ts +124 -0
  571. package/dist/humain/ask-user-question/vendor/ask/view/components/wrapping-select.d.ts.map +1 -0
  572. package/dist/humain/ask-user-question/vendor/ask/view/components/wrapping-select.js +205 -0
  573. package/dist/humain/ask-user-question/vendor/ask/view/components/wrapping-select.js.map +1 -0
  574. package/dist/humain/ask-user-question/vendor/ask/view/dialog-builder.d.ts +83 -0
  575. package/dist/humain/ask-user-question/vendor/ask/view/dialog-builder.d.ts.map +1 -0
  576. package/dist/humain/ask-user-question/vendor/ask/view/dialog-builder.js +186 -0
  577. package/dist/humain/ask-user-question/vendor/ask/view/dialog-builder.js.map +1 -0
  578. package/dist/humain/ask-user-question/vendor/ask/view/dialog-copy.d.ts +47 -0
  579. package/dist/humain/ask-user-question/vendor/ask/view/dialog-copy.d.ts.map +1 -0
  580. package/dist/humain/ask-user-question/vendor/ask/view/dialog-copy.js +48 -0
  581. package/dist/humain/ask-user-question/vendor/ask/view/dialog-copy.js.map +1 -0
  582. package/dist/humain/ask-user-question/vendor/ask/view/props-adapter.d.ts +58 -0
  583. package/dist/humain/ask-user-question/vendor/ask/view/props-adapter.d.ts.map +1 -0
  584. package/dist/humain/ask-user-question/vendor/ask/view/props-adapter.js +84 -0
  585. package/dist/humain/ask-user-question/vendor/ask/view/props-adapter.js.map +1 -0
  586. package/dist/humain/ask-user-question/vendor/ask/view/scroll-window.d.ts +20 -0
  587. package/dist/humain/ask-user-question/vendor/ask/view/scroll-window.d.ts.map +1 -0
  588. package/dist/humain/ask-user-question/vendor/ask/view/scroll-window.js +55 -0
  589. package/dist/humain/ask-user-question/vendor/ask/view/scroll-window.js.map +1 -0
  590. package/dist/humain/ask-user-question/vendor/ask/view/stateful-view.d.ts +23 -0
  591. package/dist/humain/ask-user-question/vendor/ask/view/stateful-view.d.ts.map +1 -0
  592. package/dist/humain/ask-user-question/vendor/ask/view/stateful-view.js +2 -0
  593. package/dist/humain/ask-user-question/vendor/ask/view/stateful-view.js.map +1 -0
  594. package/dist/humain/ask-user-question/vendor/ask/view/tab-components.d.ts +15 -0
  595. package/dist/humain/ask-user-question/vendor/ask/view/tab-components.d.ts.map +1 -0
  596. package/dist/humain/ask-user-question/vendor/ask/view/tab-components.js +2 -0
  597. package/dist/humain/ask-user-question/vendor/ask/view/tab-components.js.map +1 -0
  598. package/dist/humain/ask-user-question/vendor/ask/view/tab-content-strategy.d.ts +98 -0
  599. package/dist/humain/ask-user-question/vendor/ask/view/tab-content-strategy.d.ts.map +1 -0
  600. package/dist/humain/ask-user-question/vendor/ask/view/tab-content-strategy.js +248 -0
  601. package/dist/humain/ask-user-question/vendor/ask/view/tab-content-strategy.js.map +1 -0
  602. package/dist/humain/ask-user-question/vendor/ask/view/transcript.d.ts +23 -0
  603. package/dist/humain/ask-user-question/vendor/ask/view/transcript.d.ts.map +1 -0
  604. package/dist/humain/ask-user-question/vendor/ask/view/transcript.js +131 -0
  605. package/dist/humain/ask-user-question/vendor/ask/view/transcript.js.map +1 -0
  606. package/dist/humain/ask-user-question/vendor/config/config.d.ts +132 -0
  607. package/dist/humain/ask-user-question/vendor/config/config.d.ts.map +1 -0
  608. package/dist/humain/ask-user-question/vendor/config/config.js +286 -0
  609. package/dist/humain/ask-user-question/vendor/config/config.js.map +1 -0
  610. package/dist/humain/ask-user-question/vendor/config/index.d.ts +2 -0
  611. package/dist/humain/ask-user-question/vendor/config/index.d.ts.map +1 -0
  612. package/dist/humain/ask-user-question/vendor/config/index.js +2 -0
  613. package/dist/humain/ask-user-question/vendor/config/index.js.map +1 -0
  614. package/dist/humain/ask-user-question/vendor/i18n/i18n.d.ts +64 -0
  615. package/dist/humain/ask-user-question/vendor/i18n/i18n.d.ts.map +1 -0
  616. package/dist/humain/ask-user-question/vendor/i18n/i18n.js +185 -0
  617. package/dist/humain/ask-user-question/vendor/i18n/i18n.js.map +1 -0
  618. package/dist/humain/ask-user-question/vendor/i18n/loader.d.ts +44 -0
  619. package/dist/humain/ask-user-question/vendor/i18n/loader.d.ts.map +1 -0
  620. package/dist/humain/ask-user-question/vendor/i18n/loader.js +55 -0
  621. package/dist/humain/ask-user-question/vendor/i18n/loader.js.map +1 -0
  622. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +26 -16
  623. package/dist/humain/brand-logo.d.ts +2 -0
  624. package/dist/humain/brand-logo.d.ts.map +1 -1
  625. package/dist/humain/brand-logo.js +4 -0
  626. package/dist/humain/brand-logo.js.map +1 -1
  627. package/dist/humain/bundled-extension-names.d.ts +1 -0
  628. package/dist/humain/bundled-extension-names.d.ts.map +1 -1
  629. package/dist/humain/bundled-extension-names.js +1 -0
  630. package/dist/humain/bundled-extension-names.js.map +1 -1
  631. package/dist/humain/checklist/footer-progress.d.ts +7 -0
  632. package/dist/humain/checklist/footer-progress.d.ts.map +1 -0
  633. package/dist/humain/checklist/footer-progress.js +15 -0
  634. package/dist/humain/checklist/footer-progress.js.map +1 -0
  635. package/dist/humain/checklist/glyphs.d.ts +7 -0
  636. package/dist/humain/checklist/glyphs.d.ts.map +1 -0
  637. package/dist/humain/checklist/glyphs.js +8 -0
  638. package/dist/humain/checklist/glyphs.js.map +1 -0
  639. package/dist/humain/checklist/index.d.ts +6 -0
  640. package/dist/humain/checklist/index.d.ts.map +1 -0
  641. package/dist/humain/checklist/index.js +37 -0
  642. package/dist/humain/checklist/index.js.map +1 -0
  643. package/dist/humain/checklist/progress.d.ts +37 -0
  644. package/dist/humain/checklist/progress.d.ts.map +1 -0
  645. package/dist/humain/checklist/progress.js +234 -0
  646. package/dist/humain/checklist/progress.js.map +1 -0
  647. package/dist/humain/checklist/projector.d.ts +53 -0
  648. package/dist/humain/checklist/projector.d.ts.map +1 -0
  649. package/dist/humain/checklist/projector.js +198 -0
  650. package/dist/humain/checklist/projector.js.map +1 -0
  651. package/dist/humain/checklist/sidebar.d.ts +18 -0
  652. package/dist/humain/checklist/sidebar.d.ts.map +1 -0
  653. package/dist/humain/checklist/sidebar.js +38 -0
  654. package/dist/humain/checklist/sidebar.js.map +1 -0
  655. package/dist/humain/checklist/status-segment.d.ts +19 -0
  656. package/dist/humain/checklist/status-segment.d.ts.map +1 -0
  657. package/dist/humain/checklist/status-segment.js +59 -0
  658. package/dist/humain/checklist/status-segment.js.map +1 -0
  659. package/dist/humain/checklist/vendor/add-task-dialog.d.ts +54 -0
  660. package/dist/humain/checklist/vendor/add-task-dialog.d.ts.map +1 -0
  661. package/dist/humain/checklist/vendor/add-task-dialog.js +238 -0
  662. package/dist/humain/checklist/vendor/add-task-dialog.js.map +1 -0
  663. package/dist/humain/checklist/vendor/commands.d.ts +38 -0
  664. package/dist/humain/checklist/vendor/commands.d.ts.map +1 -0
  665. package/dist/humain/checklist/vendor/commands.js +193 -0
  666. package/dist/humain/checklist/vendor/commands.js.map +1 -0
  667. package/dist/humain/checklist/vendor/index.d.ts +3 -0
  668. package/dist/humain/checklist/vendor/index.d.ts.map +1 -0
  669. package/dist/humain/checklist/vendor/index.js +276 -0
  670. package/dist/humain/checklist/vendor/index.js.map +1 -0
  671. package/dist/humain/checklist/vendor/render.d.ts +97 -0
  672. package/dist/humain/checklist/vendor/render.d.ts.map +1 -0
  673. package/dist/humain/checklist/vendor/render.js +354 -0
  674. package/dist/humain/checklist/vendor/render.js.map +1 -0
  675. package/dist/humain/checklist/vendor/settings.d.ts +11 -0
  676. package/dist/humain/checklist/vendor/settings.d.ts.map +1 -0
  677. package/dist/humain/checklist/vendor/settings.js +8 -0
  678. package/dist/humain/checklist/vendor/settings.js.map +1 -0
  679. package/dist/humain/checklist/vendor/store.d.ts +120 -0
  680. package/dist/humain/checklist/vendor/store.d.ts.map +1 -0
  681. package/dist/humain/checklist/vendor/store.js +990 -0
  682. package/dist/humain/checklist/vendor/store.js.map +1 -0
  683. package/dist/humain/checklist/vendor/tools.d.ts +21 -0
  684. package/dist/humain/checklist/vendor/tools.d.ts.map +1 -0
  685. package/dist/humain/checklist/vendor/tools.js +162 -0
  686. package/dist/humain/checklist/vendor/tools.js.map +1 -0
  687. package/dist/humain/checklist/vendor/types.d.ts +188 -0
  688. package/dist/humain/checklist/vendor/types.d.ts.map +1 -0
  689. package/dist/humain/checklist/vendor/types.js +32 -0
  690. package/dist/humain/checklist/vendor/types.js.map +1 -0
  691. package/dist/humain/gateway/catalog.d.ts +1 -0
  692. package/dist/humain/gateway/catalog.d.ts.map +1 -1
  693. package/dist/humain/gateway/catalog.js +1 -0
  694. package/dist/humain/gateway/catalog.js.map +1 -1
  695. package/dist/humain/gateway/client.d.ts +1 -0
  696. package/dist/humain/gateway/client.d.ts.map +1 -1
  697. package/dist/humain/gateway/client.js +8 -1
  698. package/dist/humain/gateway/client.js.map +1 -1
  699. package/dist/humain/gateway/http.d.ts.map +1 -1
  700. package/dist/humain/gateway/http.js +11 -3
  701. package/dist/humain/gateway/http.js.map +1 -1
  702. package/dist/humain/gateway/images.d.ts +3 -0
  703. package/dist/humain/gateway/images.d.ts.map +1 -0
  704. package/dist/humain/gateway/images.js +73 -0
  705. package/dist/humain/gateway/images.js.map +1 -0
  706. package/dist/humain/gateway/provider.js +1 -1
  707. package/dist/humain/gateway/provider.js.map +1 -1
  708. package/dist/humain/hcode/account-store.d.ts.map +1 -1
  709. package/dist/humain/hcode/account-store.js +3 -1
  710. package/dist/humain/hcode/account-store.js.map +1 -1
  711. package/dist/humain/hcode/account.d.ts.map +1 -1
  712. package/dist/humain/hcode/account.js +23 -13
  713. package/dist/humain/hcode/account.js.map +1 -1
  714. package/dist/humain/hcode/images.d.ts.map +1 -1
  715. package/dist/humain/hcode/images.js +19 -13
  716. package/dist/humain/hcode/images.js.map +1 -1
  717. package/dist/humain/hcode/login-failure.d.ts +1 -0
  718. package/dist/humain/hcode/login-failure.d.ts.map +1 -1
  719. package/dist/humain/hcode/login-failure.js +1 -0
  720. package/dist/humain/hcode/login-failure.js.map +1 -1
  721. package/dist/humain/hcode/provider.d.ts.map +1 -1
  722. package/dist/humain/hcode/provider.js +2 -1
  723. package/dist/humain/hcode/provider.js.map +1 -1
  724. package/dist/humain/hcode/run-credential.d.ts +1 -0
  725. package/dist/humain/hcode/run-credential.d.ts.map +1 -1
  726. package/dist/humain/hcode/run-credential.js +12 -4
  727. package/dist/humain/hcode/run-credential.js.map +1 -1
  728. package/dist/humain/index.d.ts.map +1 -1
  729. package/dist/humain/index.js +4 -0
  730. package/dist/humain/index.js.map +1 -1
  731. package/dist/humain/node-provider.d.ts.map +1 -1
  732. package/dist/humain/node-provider.js +37 -8
  733. package/dist/humain/node-provider.js.map +1 -1
  734. package/dist/main.d.ts +1 -1
  735. package/dist/main.d.ts.map +1 -1
  736. package/dist/main.js +38 -26
  737. package/dist/main.js.map +1 -1
  738. package/dist/modes/interactive/chat-viewport.js +1 -1
  739. package/dist/modes/interactive/chat-viewport.js.map +1 -1
  740. package/dist/modes/interactive/components/bash-execution.d.ts +2 -1
  741. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  742. package/dist/modes/interactive/components/bash-execution.js +7 -4
  743. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  744. package/dist/modes/interactive/components/config-selector.js +1 -1
  745. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  746. package/dist/modes/interactive/components/custom-editor.d.ts +2 -0
  747. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  748. package/dist/modes/interactive/components/custom-editor.js +20 -1
  749. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  750. package/dist/modes/interactive/components/extension-editor.d.ts +1 -1
  751. package/dist/modes/interactive/components/extension-editor.js +2 -2
  752. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  753. package/dist/modes/interactive/components/footer.d.ts +7 -0
  754. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  755. package/dist/modes/interactive/components/footer.js +74 -1
  756. package/dist/modes/interactive/components/footer.js.map +1 -1
  757. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
  758. package/dist/modes/interactive/components/mermaid.js +11 -4
  759. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  760. package/dist/modes/interactive/components/model-selector.d.ts +2 -0
  761. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  762. package/dist/modes/interactive/components/model-selector.js +56 -8
  763. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  764. package/dist/modes/interactive/components/oauth-selector.d.ts +13 -1
  765. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  766. package/dist/modes/interactive/components/oauth-selector.js +10 -9
  767. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  768. package/dist/modes/interactive/components/session-selector.js +3 -3
  769. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  770. package/dist/modes/interactive/components/settings-selector.d.ts +4 -3
  771. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  772. package/dist/modes/interactive/components/settings-selector.js +83 -37
  773. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  774. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
  775. package/dist/modes/interactive/components/settings-submenu.js +3 -3
  776. package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
  777. package/dist/modes/interactive/components/status-indicator.d.ts +18 -7
  778. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  779. package/dist/modes/interactive/components/status-indicator.js +70 -24
  780. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  781. package/dist/modes/interactive/components/status-line.d.ts +16 -0
  782. package/dist/modes/interactive/components/status-line.d.ts.map +1 -0
  783. package/dist/modes/interactive/components/status-line.js +51 -0
  784. package/dist/modes/interactive/components/status-line.js.map +1 -0
  785. package/dist/modes/interactive/components/tool-execution.d.ts +5 -0
  786. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  787. package/dist/modes/interactive/components/tool-execution.js +8 -1
  788. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  789. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  790. package/dist/modes/interactive/components/visual-truncate.js +11 -3
  791. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  792. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  793. package/dist/modes/interactive/external-editor.js +13 -3
  794. package/dist/modes/interactive/external-editor.js.map +1 -1
  795. package/dist/modes/interactive/interactive-mode.d.ts +17 -1
  796. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  797. package/dist/modes/interactive/interactive-mode.js +232 -108
  798. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  799. package/dist/modes/interactive/program-status-reporter.d.ts +2 -0
  800. package/dist/modes/interactive/program-status-reporter.d.ts.map +1 -1
  801. package/dist/modes/interactive/program-status-reporter.js +4 -0
  802. package/dist/modes/interactive/program-status-reporter.js.map +1 -1
  803. package/dist/modes/interactive/session-share.d.ts.map +1 -1
  804. package/dist/modes/interactive/session-share.js +9 -1
  805. package/dist/modes/interactive/session-share.js.map +1 -1
  806. package/dist/modes/print-mode.d.ts.map +1 -1
  807. package/dist/modes/print-mode.js +34 -7
  808. package/dist/modes/print-mode.js.map +1 -1
  809. package/dist/modes/rpc/jsonl.js +6 -5
  810. package/dist/modes/rpc/jsonl.js.map +1 -1
  811. package/dist/modes/rpc/rpc-client.d.ts +2 -0
  812. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  813. package/dist/modes/rpc/rpc-client.js +9 -2
  814. package/dist/modes/rpc/rpc-client.js.map +1 -1
  815. package/dist/modes/rpc/rpc-mode.d.ts +2 -1
  816. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  817. package/dist/modes/rpc/rpc-mode.js +113 -13
  818. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  819. package/dist/modes/rpc/rpc-types.d.ts +22 -1
  820. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  821. package/dist/modes/rpc/rpc-types.js.map +1 -1
  822. package/dist/modes/uncaught-errors.d.ts +20 -0
  823. package/dist/modes/uncaught-errors.d.ts.map +1 -0
  824. package/dist/modes/uncaught-errors.js +56 -0
  825. package/dist/modes/uncaught-errors.js.map +1 -0
  826. package/dist/package-manager-cli.d.ts.map +1 -1
  827. package/dist/package-manager-cli.js +10 -1
  828. package/dist/package-manager-cli.js.map +1 -1
  829. package/dist/utils/clipboard-image.js +1 -1
  830. package/dist/utils/clipboard-image.js.map +1 -1
  831. package/dist/utils/clipboard.js +2 -2
  832. package/dist/utils/clipboard.js.map +1 -1
  833. package/dist/utils/image-process.d.ts +5 -0
  834. package/dist/utils/image-process.d.ts.map +1 -1
  835. package/dist/utils/image-process.js +22 -4
  836. package/dist/utils/image-process.js.map +1 -1
  837. package/dist/utils/output-files.d.ts +44 -7
  838. package/dist/utils/output-files.d.ts.map +1 -1
  839. package/dist/utils/output-files.js +206 -12
  840. package/dist/utils/output-files.js.map +1 -1
  841. package/dist/utils/piped-stdin.d.ts +21 -0
  842. package/dist/utils/piped-stdin.d.ts.map +1 -0
  843. package/dist/utils/piped-stdin.js +60 -0
  844. package/dist/utils/piped-stdin.js.map +1 -0
  845. package/dist/utils/shell.d.ts +5 -2
  846. package/dist/utils/shell.d.ts.map +1 -1
  847. package/dist/utils/shell.js +77 -8
  848. package/dist/utils/shell.js.map +1 -1
  849. package/dist/utils/syntax-highlight.d.ts +33 -2
  850. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  851. package/dist/utils/syntax-highlight.js +77 -10
  852. package/dist/utils/syntax-highlight.js.map +1 -1
  853. package/dist/utils/tools-manager.d.ts +1 -0
  854. package/dist/utils/tools-manager.d.ts.map +1 -1
  855. package/dist/utils/tools-manager.js +9 -8
  856. package/dist/utils/tools-manager.js.map +1 -1
  857. package/dist/utils/wsl.d.ts +8 -2
  858. package/dist/utils/wsl.d.ts.map +1 -1
  859. package/dist/utils/wsl.js +12 -3
  860. package/dist/utils/wsl.js.map +1 -1
  861. package/docs/cli.md +45 -3
  862. package/docs/codemode.md +7 -3
  863. package/docs/compaction.md +1 -1
  864. package/docs/coordination.md +16 -4
  865. package/docs/development.md +6 -0
  866. package/docs/environment-variables.md +5 -3
  867. package/docs/extensions.md +19 -5
  868. package/docs/keybindings.md +2 -0
  869. package/docs/llama-cpp.md +2 -2
  870. package/docs/message-types.md +1 -0
  871. package/docs/models-configuration.md +14 -3
  872. package/docs/models.md +29 -7
  873. package/docs/providers.md +25 -3
  874. package/docs/rpc-commands.md +25 -2
  875. package/docs/rpc.md +20 -0
  876. package/docs/run-preflight.md +2 -2
  877. package/docs/session-format.md +9 -0
  878. package/docs/settings.md +35 -5
  879. package/docs/shell-aliases.md +1 -1
  880. package/docs/slash-commands.md +3 -1
  881. package/docs/terminal-setup.md +25 -0
  882. package/docs/windows.md +2 -1
  883. package/examples/extensions/custom-provider-anthropic/package-lock.json +4 -4
  884. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  885. package/examples/rpc-extension-ui.ts +8 -7
  886. package/npm-shrinkwrap.json +209 -180
  887. package/package.json +26 -20
  888. package/schemas/keybindings.schema.json +12 -0
  889. package/schemas/models.schema.json +20 -7
  890. package/schemas/settings.schema.json +43 -5
  891. package/src/coordination/UPSTREAM.md +27 -1
  892. package/src/coordination/upstream.json +3 -3
  893. package/src/humain/ask-user-question/UPSTREAM.md +31 -0
  894. package/src/humain/ask-user-question/upstream.json +258 -0
  895. package/src/humain/ask-user-question/vendor/ask/LICENSE +21 -0
  896. package/src/humain/ask-user-question/vendor/ask/locales/de.json +38 -0
  897. package/src/humain/ask-user-question/vendor/ask/locales/en.json +41 -0
  898. package/src/humain/ask-user-question/vendor/ask/locales/es.json +38 -0
  899. package/src/humain/ask-user-question/vendor/ask/locales/fr.json +38 -0
  900. package/src/humain/ask-user-question/vendor/ask/locales/pt-BR.json +38 -0
  901. package/src/humain/ask-user-question/vendor/ask/locales/pt.json +38 -0
  902. package/src/humain/ask-user-question/vendor/ask/locales/ru.json +38 -0
  903. package/src/humain/ask-user-question/vendor/ask/locales/uk.json +38 -0
  904. package/src/humain/ask-user-question/vendor/ask/locales/zh.json +40 -0
  905. package/src/humain/ask-user-question/vendor/config/LICENSE +21 -0
  906. package/src/humain/ask-user-question/vendor/i18n/LICENSE +21 -0
  907. package/src/humain/caveman/UPSTREAM.md +44 -11
  908. package/src/humain/caveman/upstream.json +3 -3
  909. package/src/humain/caveman/vendor/NOTICE +4 -0
  910. package/dist/bundle/chunks/anthropic-messages-XFCDMGD6.js +0 -77
  911. package/dist/bundle/chunks/azure-openai-responses-F4KQM3NK.js +0 -15
  912. package/dist/bundle/chunks/bowser-DXKSTXFQ.js +0 -89
  913. package/dist/bundle/chunks/chunk-3E37CJCE.js +0 -34
  914. package/dist/bundle/chunks/chunk-3HVHETMU.js +0 -18
  915. package/dist/bundle/chunks/chunk-3PJ7NPWN.js +0 -80
  916. package/dist/bundle/chunks/chunk-6JTCRCNF.js +0 -74
  917. package/dist/bundle/chunks/chunk-F77J5EQZ.js +0 -3
  918. package/dist/bundle/chunks/chunk-GPLWWO5Q.js +0 -121
  919. package/dist/bundle/chunks/chunk-GV5OVRKK.js +0 -4
  920. package/dist/bundle/chunks/chunk-JBSWWCT5.js +0 -12
  921. package/dist/bundle/chunks/chunk-JQBZUFH7.js +0 -3580
  922. package/dist/bundle/chunks/chunk-JWOPWHVH.js +0 -51
  923. package/dist/bundle/chunks/chunk-KRBELWQH.js +0 -7
  924. package/dist/bundle/chunks/chunk-PFBAIRCY.js +0 -56
  925. package/dist/bundle/chunks/chunk-Q5RKNQ2T.js +0 -73
  926. package/dist/bundle/chunks/chunk-QFDZEUFU.js +0 -12
  927. package/dist/bundle/chunks/chunk-SKCJ25SX.js +0 -24
  928. package/dist/bundle/chunks/chunk-UEW6TUSP.js +0 -36
  929. package/dist/bundle/chunks/chunk-UZOIHLNU.js +0 -23
  930. package/dist/bundle/chunks/chunk-YSWDFV2L.js +0 -11
  931. package/dist/bundle/chunks/chunk-YZMQXAJM.js +0 -8
  932. package/dist/bundle/chunks/entry-2GZ3PTWQ.js +0 -2
  933. package/dist/bundle/chunks/google-generative-ai-WIASMWS3.js +0 -22
  934. package/dist/bundle/chunks/google-vertex-WSPHRZIZ.js +0 -25
  935. package/dist/bundle/chunks/interactive-mode-SDUO5OLD.js +0 -5
  936. package/dist/bundle/chunks/mistral-conversations-7JYDDRUT.js +0 -43
  937. package/dist/bundle/chunks/openai-codex-responses-7PAML4NF.js +0 -102
  938. package/dist/bundle/chunks/openai-completions-UJDAIGTK.js +0 -87
  939. package/dist/bundle/chunks/openai-responses-2WNCE6AY.js +0 -26
  940. package/dist/bundle/chunks/openrouter-images-V3UCCO6X.js +0 -8
  941. package/dist/bundle/chunks/pi-messages-TQ7LJUNQ.js +0 -28
  942. package/dist/bundle/chunks/runtime-H7LYNKCZ.js +0 -2
  943. package/dist/bundle/chunks/session-picker-EYKCMFQR.js +0 -4
  944. package/dist/bundle/chunks/startup-ui-7ODOR34R.js +0 -3
  945. package/dist/bundle/chunks/typesafe-system-one-YP7GGN4C.js +0 -3
  946. package/dist/bundle/chunks/virtual-modules-IU5KWB2C.js +0 -28
@@ -1,80 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{ANTHROPIC_USAGE_PROVIDER_ID,HCODE_PROVIDER,fetchWithRetry,getCodexAvailability,getPiUserAgent,isWSL,parseAnthropicSubscriptionUsage,parseSubscriptionCreditAmount}from"./chunk-JQBZUFH7.js";import{addUsageToTotals,createUsageTotals,getSessionUsage,stripAnsi}from"./chunk-3E37CJCE.js";import{raceWithAbortSignal}from"./chunk-JWOPWHVH.js";import{areExperimentalFeaturesEnabled}from"./chunk-UZOIHLNU.js";import{hcodeDisplayName,require_semver}from"./chunk-T2ZGMEMV.js";
3
- import{getThemeInstance,keyHint,theme}from"./chunk-E4VUW4RI.js";import{Container,Text,getNativeClipboard,hyperlink,sanitizeTerminalText,truncateToWidth,visibleWidth,wrapTextWithAnsi}from"./chunk-M5TVWJ5T.js";import{killTrackedDetachedChildrenAsync}from"./chunk-SKCJ25SX.js";import{APP_COMMAND,ENV_OFFLINE,ENV_SKIP_VERSION_CHECK,getVersionCheckUrl}from"./chunk-VFLVWPLZ.js";import{__toESM}from"./chunk-JXWJOIH4.js";var HCODE_LOGIN_MISMATCH_DETAILS="HUMAIN Code's sign-in settings (/api/cli/config or issuer discovery) don't match what this CLI version accepts. Update the CLI with `humain-code update`, or ask the HUMAIN Code platform team to check the server's CLI sign-in configuration.",EMPTY_REASONS={no_cli_models_approved:{reason:"no model is approved for CLI",fix:"Ask an admin to set a model to Web + CLI or CLI only in Settings > Model Access."},provider_key_not_cli_enabled:{reason:"the provider key isn't\
4
- enabled for CLI",fix:"Ask an admin to enable CLI on the key in Settings > Provider Keys."},cli_capacity_unconfigured:{reason:"CLI capacity hasn't been configured",fix:"Ask the HUMAIN Code platform team to check the deployment's CLI capacity limits."},provider_key_not_dedicated:{reason:"the provider key is shared or isn't approved for CLI use",fix:"Ask an admin to configure a dedicated key for HUMAIN Code CLI."},models_not_qualified:{reason:"this server hasn't finished CLI setup for the approved\
5
- models",fix:"Ask an admin to report it to the HUMAIN Code platform team."}};function hcodeEmptyCatalogMessage(reason){if(!reason)return"Your admin hasn't enabled CLI models yet.";let{reason:why,fix}=EMPTY_REASONS[reason];return`No models are available in the CLI: ${why}. ${fix}`}function hcodeEmptyCatalogReason(cause){return cause.kind==="failed"?{reason:"the model list couldn't be loaded",fix:"Check your network, VPN or Zscaler."}:cause.reason?EMPTY_REASONS[cause.reason]:{reason:"your admin ha\
6
- sn't enabled CLI models yet",fix:"Ask an admin to enable a model for CLI."}}function hcodeEmptyCatalogNotice(environmentId,email,cause){let{reason,fix}=hcodeEmptyCatalogReason(cause);return[`\u2713 Signed in to ${hcodeDisplayName(environmentId)}${email?` as ${email}`:""}`,` No models available in the CLI yet: ${reason}.`,` ${fix}`," You can keep using your other providers. I'll check again automatically."," /model to retry \xB7 /login status for details"].join(`
7
- `)}function hcodeLoginAvailability(readiness){if(!readiness)return{state:"pending",text:"checking connection\u2026"};switch(readiness.kind){case"ready":return{state:"ready",text:"connected"};case"unreachable":return{state:"failed",text:`Can't reach ${readiness.host}: check VPN/Zscaler [Retry]`};case"not-configured":return{state:"failed",text:`HUMAIN Code isn't available on ${readiness.environmentId} yet (server: hcode_unavailable). Try another environment or contact support. [Retry]`};case"http-\
8
- error":return{state:"failed",text:`Sign-in server returned HTTP ${readiness.status}${readiness.message?`: ${readiness.message}`:"."} [Retry]`};case"mismatch":return{state:"failed",text:"Server sign-in settings don't match this CLI version [Details]"};case"unavailable":return{state:"failed",text:"Sign-in is not available in this environment [Retry]"}}}function hcodeSignedInElsewhereNotice(environmentId,elsewhere){let other=elsewhere[0];if(other)return`${hcodeDisplayName(environmentId)}: not signe\
9
- d in. HUMAIN Code now defaults to production. Your saved sign-in is for ${hcodeDisplayName(other)} and was not moved: start humain-code with --env ${other} to use it, or /login to sign in here.`}import{randomUUID}from"node:crypto";import{unlinkSync,writeFileSync}from"node:fs";import{platform,tmpdir}from"node:os";import{join}from"node:path";import{spawn}from"node:child_process";function runClipboardCommand(command,args,options){return new Promise(resolve2=>{let child=spawn(command,args,{stdio:["pipe",options?.input===void 0?"pipe":"ignore","ignore"],cwd:"/",detached:process.platform!=="win32",windowsHide:!0}),chunks=[],length=0,settled=!1,finish=result=>{settled||(settled=!0,clearTimeout(timer),resolve2(result))},abort=()=>{child.kill("SIGKILL"),child.stdout?.destroy(),child.stdin?.destroy(),finish(void 0)},timer=setTimeout(abort,options?.
10
- timeoutMs??3e3);child.on("error",()=>finish(void 0)),child.on("close",code=>{settled||finish(code===0?Buffer.concat(chunks,length):void 0)}),child.stdout?.on("data",chunk=>{settled||(length+=chunk.length,length>(options?.maxBufferBytes??50*1024*1024)?abort():chunks.push(chunk))}),child.stdin?.on("error",()=>{}),child.stdin?.end(options?.input)})}var MAX_OSC52_ENCODED_LENGTH=1e5;function isRemoteSession(env){return!!(env.SSH_CONNECTION||env.SSH_CLIENT||env.MOSH_CONNECTION||env.HUMAIN_TERMINAL_CLIPBOARD_OSC52==="1")}function emitOsc52(text){let encoded=Buffer.from(text).toString("base64");return encoded.length>MAX_OSC52_ENCODED_LENGTH?!1:(process.stdout.write(`\x1B]52;c;${encoded}\x07`),!0)}async function copyViaWindowsClipboard(text){let tmpFile=join(tmpdir(),`pi-wsl-clip-${randomUUID()}.txt`);try{writeFileSync(tmpFile,text,{encoding:"ut\
11
- f8",mode:384});let winPath=(await runClipboardCommand("wslpath",["-w",tmpFile],{timeoutMs:1e3}))?.toString("utf8").trim();if(!winPath)return!1;let script=`Set-Clipboard -Value ([System.IO.File]::ReadAllText('${winPath.replaceAll("'","''")}', [System.Text.Encoding]::UTF8))`;return await runClipboardCommand("powershell.exe",["-NoProfile","-Command",script],{timeoutMs:5e3})!==void 0}catch{return!1}finally{try{unlinkSync(tmpFile)}catch{}}}async function readClipboardText(){let commands=[];process.env.
12
- TERMUX_VERSION&&commands.push(["termux-clipboard-get",[]]),platform()==="linux"&&(process.env.WAYLAND_DISPLAY&&commands.push(["wl-paste",["--no-newline","--type","text"]]),process.env.DISPLAY&&commands.push(["xclip",["-selection","clipboard","-out"]],["xsel",["--clipboard","--output"]]));for(let[command,args]of commands){let bytes=await runClipboardCommand(command,args,{timeoutMs:5e3});if(bytes!==void 0)return bytes.toString("utf8")||null}try{return await getNativeClipboard()?.getText()||null}catch{
13
- return null}}async function readClipboardFilePaths(){let paths=await getNativeClipboard()?.getFilePaths?.();return paths?.length?paths:null}async function copyToClipboard(text){let p=platform(),env=process.env,copied=!1;if(p!=="linux")try{let clipboard=getNativeClipboard();clipboard?.setText&&(await clipboard.setText(text),copied=!0)}catch{}if(!copied){let commands=[];p==="darwin"?commands.push(["pbcopy",[]]):p==="win32"?commands.push(["clip",[]]):(env.TERMUX_VERSION&&commands.push(["termux-clip\
14
- board-set",[]]),env.WAYLAND_DISPLAY&&commands.push(["wl-copy",[]]),env.DISPLAY&&commands.push(["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]));for(let[command,args]of commands)if(await runClipboardCommand(command,args,{input:text,timeoutMs:5e3})!==void 0){copied=!0;break}}let osc52Emitted=!1;!copied&&p==="linux"&&isWSL(env)&&(env.WT_SESSION&&(osc52Emitted=emitOsc52(text)),copied=osc52Emitted||await copyViaWindowsClipboard(text));let headless=p==="linux"&&!env.DISPLAY&&!env.
15
- WAYLAND_DISPLAY&&!env.TERMUX_VERSION,oversized=!1;if(!osc52Emitted&&(isRemoteSession(env)||!copied&&headless)&&(emitOsc52(text)?copied=!0:oversized=!0),!copied){if(oversized)throw new Error("Clipboard unavailable: text exceeds the OSC 52 size limit");if(env.TERMUX_VERSION)throw new Error("Clipboard unavailable: install the Termux:API app and `termux-api` package");if(p==="linux"){if(env.WAYLAND_DISPLAY)throw new Error("Clipboard unavailable: install `wl-clipboard` (`wl-copy`) or check Wayland ac\
16
- cess");if(env.DISPLAY)throw new Error("Clipboard unavailable: install `xclip` or `xsel`, or check X11 access")}throw new Error("Clipboard unavailable")}}var current,listeners=new Set;function notify(){for(let listener of listeners)try{listener()}catch{}}function trackUserWait(reason,promise){let wait={reason};return current=wait,notify(),promise.finally(()=>{current===wait&&(current=void 0,notify())})}function currentUserWait(){return current?.reason}function onUserWaitChange(listener){return listeners.add(listener),()=>{listeners.delete(listener)}}var handlers=new WeakMap;function bindClaudeUsageReconnect(registry,handler){return handlers.set(registry,handler),()=>{handlers.get(registry)===handler&&handlers.delete(registry)}}function getClaudeUsageReconnect(registry){return handlers.get(registry)}function formatSubscriptionCredits(credits){if(credits?.unlimited===!0)return"unlimited";if(credits?.hasCredits===!1)return"none";let balance=parseSubscriptionCreditAmount(credits?.balance);if(balance===void 0||credits?.unit===void 0)return"unavailable";if(Number(balance)===0)return"none";let[integer,fraction]=balance.split("."),amount=`${Number(integer).toLocaleString("en-US")}${fraction===void 0?"":`.${fraction}`}`;return credits.unit==="USD"?`$${amount}`:`${amount} credits`}function formatSubscriptionAccountSummary(result){
17
- let usage=subscriptionAccountUsage(result),weekly=usage.weeklyLeft===void 0?`weekly usage: unavailable${usage.expired?" (sign-in expired)":""}`:`weekly: ${usage.weeklyLeft}% left`;return usage.availability&&(weekly+=`, provider: ${usage.availability}`),usage.reset&&(weekly+=usage.availability?`, resets ${usage.reset}`:`, Next reset ${usage.reset}`),`${weekly}, saved resets: ${usage.savedResets}, paid credits: ${usage.paidCredits}${usage.extraUsage===void 0?"":`, extra usage: ${usage.extraUsage}`}`}
18
- function subscriptionAccountUsage(result){let ok=result?.status==="ok"?result:void 0,claude=ok&&"fetchedAt"in ok?ok:void 0,codex=ok&&"usage"in ok?ok.usage:void 0,weekly=claude?.windows.find(window=>window.id==="seven_day"),percent=weekly?100-weekly.usedPercent:codex?.remainingPercent,count=ok?.resets?.availableCount,enabled=ok?.credits?.enabled;return{expired:result?.status==="unavailable"&&result.reason==="expired_credential",weeklyLeft:percent===void 0?void 0:Math.round(percent),reset:claude?formatNextQuotaReset(
19
- claude.windows):codex?.resetsAt===void 0?void 0:formatOAuthAccountResetTime(codex.resetsAt),availability:codex?getCodexAvailability(codex):void 0,savedResets:count===void 0?"unavailable":count===0?"none":String(count),paidCredits:formatSubscriptionCredits(ok?.credits),extraUsage:enabled===void 0?void 0:enabled?"enabled":"disabled"}}function formatNextQuotaReset(windows,now=Date.now()){let nearest=1/0;for(let{resetsAt}of windows)resetsAt!==void 0&&resetsAt>now&&resetsAt<nearest&&(nearest=resetsAt);
20
- return nearest===1/0?void 0:formatOAuthAccountResetTime(nearest)}function formatOAuthAccountResetTime(epochMs){let date=new Date(epochMs),time=`${String(date.getHours()).padStart(2,"0")}:${String(date.getMinutes()).padStart(2,"0")}`;return date.toDateString()===new Date().toDateString()?time:`${time} on ${date.toLocaleDateString()}`}function formatOAuthAccountUsage(usage){switch(usage.kind){case"none":return"";case"loading":return"weekly usage: loading\u2026";case"subscription":return[usage.status,
21
- formatSubscriptionAccountSummary(usage.result)].filter(Boolean).join(", ");case"unavailable":return usage.reason==="expired_credential"?"weekly usage: unavailable (sign-in expired)":"weekly usage: unavailable";case"available":{let remaining=`weekly: ${Math.round(usage.remainingPercent)}% left, provider: ${getCodexAvailability(usage)}`;return usage.resetsAt!==void 0?`${remaining}, resets ${formatOAuthAccountResetTime(usage.resetsAt)}`:remaining}}}function formatOAuthAccountOption(label,usage){let usageText=formatOAuthAccountUsage(
22
- usage);return usageText?`${label} (${usageText})`:label}import{readFile}from"node:fs/promises";import{homedir}from"node:os";import{join as join2}from"node:path";function usageDisplayText(text){return sanitizeTerminalText(text).replace(/[\t\r\n\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g," ")}function formatTokens(count){return count<1e3?count.toString():count<1e4?`${(count/1e3).toFixed(1)}k`:count<1e6?`${Math.round(count/1e3)}k`:count<1e7?`${(count/1e6).toFixed(1)}M`:`${Math.round(count/1e6)}M`}function formatDuration(ms){let totalSeconds=Math.max(0,Math.floor(ms/1e3)),hours=Math.floor(totalSeconds/3600),minutes=Math.floor(totalSeconds%3600/
23
- 60),seconds=totalSeconds%60;return hours>0?`${hours}h ${minutes}m ${seconds}s`:minutes>0?`${minutes}m ${seconds}s`:`${seconds}s`}function percentTone(percent){return percent>90?"error":percent>70?"warning":"accent"}function contextTone(percent){return percent===null?"accent":percentTone(percent)}function buildUsageOverview(opts){let{providerId,modelId,stats,durationMs,usageIncomplete,subscriptionBacked,accountBars}=opts,bars=[],lines=[],notes=[];accountBars&&bars.push(...accountBars);let cu=stats.
24
- contextUsage;return cu&&bars.push({id:"context",label:"Context",used:cu.tokens??0,total:cu.contextWindow,display:`${cu.percent!==null?`${cu.percent.toFixed(1)}%`:"?"} / ${formatTokens(cu.contextWindow)}`,tone:contextTone(cu.percent)}),lines.push({label:"tokens",value:`\u2191${formatTokens(stats.tokens.input)} \u2193${formatTokens(stats.tokens.output)}`}),lines.push(usageIncomplete?{label:"cost",value:`\u2265$${stats.cost.toFixed(3)} (usage incomplete)`,tone:"warning"}:{label:"cost",value:`$${stats.
25
- cost.toFixed(3)}`}),durationMs!==null&&lines.push({label:"time",value:formatDuration(durationMs)}),subscriptionBacked&&notes.push("Subscription limits (weekly / 5h) are not exposed by this provider's API. See its usage dashboard."),{providerId,modelId,bars,lines,notes}}function formatUsageOverview(overview){let rows=[...overview.bars.map(bar=>({label:bar.label,value:`${bar.display}${bar.note?` (${bar.note})`:""}`})),...overview.lines],labelWidth=Math.max(0,...rows.map(row=>visibleWidth(row.label)));
26
- return[`${overview.providerId} \xB7 ${overview.modelId}`,...rows.map(row=>` ${row.label}${" ".repeat(labelWidth-visibleWidth(row.label))} ${row.value}`),...overview.notes].map(line=>sanitizeTerminalText(line)).join(`
27
- `)}function weeklyResetLines(resets){let lines=[{label:"saved resets",value:resets?.availableCount===void 0?"unavailable":resets.availableCount===0?"none":`${resets.availableCount} banked`,section:"resets"}];return resets?.eligible!==void 0&&lines.push({label:"use now",value:resets.eligible?"available":"not available",section:"resets"}),resets?.expiresAt!==void 0&&lines.push({label:"reset expiry",value:formatOAuthAccountResetTime(resets.expiresAt),section:"resets"}),lines}function paidUsageLines(credits){
28
- let lines=[{label:"paid credits",value:formatSubscriptionCredits(credits),section:"paid"}];return credits?.enabled!==void 0&&lines.push({label:"extra usage",value:credits.enabled?"enabled":"disabled",section:"paid"}),credits?.limit!==void 0&&lines.push({label:"spending limit",value:formatSubscriptionCredits({balance:credits.limit,unit:credits.unit}),section:"paid"}),lines.push({label:"auto reload",value:credits?.autoReload===void 0?"unavailable":credits.autoReload?"on":"off",section:"paid"}),lines}
29
- function limitBar(id,label,usedPercent,resetsAt,limitReached,now){let used=Math.min(100,Math.max(0,usedPercent)),notes=[resetsAt===void 0?void 0:`${resetsAt<=now?"reset at":"resets"} ${formatOAuthAccountResetTime(resetsAt)}`,limitReached?"limit reached":void 0].filter(note=>note!==void 0);return{id,label,used,total:100,display:`${used.toFixed(0)}% used`,tone:limitReached?"error":percentTone(used),...notes.length>0?{note:notes.join(", ")}:{}}}function claudeUsageBars(windows,now=Date.now()){return windows.
30
- map(window=>({...limitBar(`claude-${window.id}`,window.label,window.usedPercent,window.resetsAt,window.usedPercent>=100,now),...window.id==="extra_usage"?{section:"paid"}:{}}))}function parseClaudeUtilization(raw,now=Date.now()){if(!raw||typeof raw!="object")return[];let u=raw.utilization??raw;if(!u||typeof u!="object")return[];let bars=claudeUsageBars(parseAnthropicSubscriptionUsage(u),now);for(let[key,value]of Object.entries(u)){if(key==="extra_usage"||!value||typeof value!="object")continue;let{
31
- used_dollars:used,limit_dollars:total}=value;if(!(typeof used!="number"||typeof total!="number"||!Number.isFinite(used)||!(total>0))){bars.push({id:`claude-${key}`,label:"Credits",used,total,display:`$${used.toFixed(2)} / $${total.toFixed(2)}`,tone:percentTone(used/total*100)});break}}return bars}var CLAUDE_UNAVAILABLE={expired_credential:"Claude sign-in expired.",refresh_failed:"Claude sign-in could not be refreshed. Try again later.",refresh_rejected:"Claude rejected the sign-in refresh.",unauthorized:"\
32
- Claude usage was refused (HTTP 401/403).",rate_limited:"Claude usage is rate limited (HTTP 429). Try again later.",http_error:"Claude usage is unavailable (HTTP error).",timeout:"Claude usage timed out.",network:"Claude usage is unreachable.",malformed:"Claude usage returned an unexpected response."},CODEX_UNAVAILABLE={expired_credential:"Codex sign-in expired. Run /login.",unauthorized:"Codex usage was refused (HTTP 401/403).",rate_limited:"Codex usage is rate limited (HTTP 429). Try again late\
33
- r.",http_error:"Codex usage is unavailable (HTTP error).",timeout:"Codex usage timed out.",network:"Codex usage is unreachable.",malformed:"Codex usage returned an unexpected response.",no_weekly_window:"Codex reported no weekly limit."};function codexUsageBars(result,now=Date.now()){return result?result.status==="unavailable"?{error:CODEX_UNAVAILABLE[result.reason]}:result.windows.length===0&&!result.credits?{error:"Codex reported no usage limits."}:{bars:result.windows.map(window=>limitBar(`co\
34
- dex-${window.id}`,window.label,window.usedPercent,window.resetsAt,window.limitReached===!0,now)),lines:[...nextQuotaResetLines(result.windows,now),...paidUsageLines(result.credits)]}:{error:"No active Codex account. Run /login."}}function usageAge(ms){return`${ms>=1728e5?`${Math.floor(ms/864e5)} days`:formatAge(ms)} ago`}function formatAge(ms){let minutes=Math.floor(Math.max(0,ms)/6e4);if(minutes<1)return"under a minute";if(minutes<60)return`${minutes} min`;let hours=Math.floor(minutes/60);return hours<
35
- 48?`${hours} h`:`${Math.floor(hours/24)} d`}async function readClaudeCachedUsage(readOwner,now,home=homedir()){let text;try{text=await readFile(join2(home,".claude.json"),"utf8")}catch(err){return err.code==="ENOENT"?{error:"~/.claude.json not found."}:{error:"Could not read ~/.claude.json."}}let data;try{data=JSON.parse(text)}catch{return{error:"~/.claude.json is not valid JSON."}}let identity=data&&typeof data=="object"?data.oauthAccount:void 0,{accountUuid,organizationUuid}=identity??{},{accountId,
36
- organizationId}=await readOwner()??{},sameOrganization=typeof organizationUuid=="string"?organizationUuid.toLowerCase()===organizationId?.toLowerCase():organizationUuid===void 0&&organizationId===void 0;if(!accountId||typeof accountUuid!="string"||accountUuid.toLowerCase()!==accountId.toLowerCase()||!sameOrganization)return{error:"Claude Code's cache does not match this account."};let cached=data&&typeof data=="object"?data.cachedUsageUtilization:void 0;if(!cached||typeof cached!="object")return{
37
- error:"No cached Claude Code usage in ~/.claude.json."};let fetchedAt=cached.fetchedAtMs,fetchedAtMs=typeof fetchedAt=="number"&&Number.isFinite(fetchedAt)&&fetchedAt>=0&&fetchedAt<=now?fetchedAt:void 0,payload=cached.utilization??cached,stale=fetchedAtMs===void 0||now-fetchedAtMs>36e5||parseAnthropicSubscriptionUsage(payload).some(window=>window.resetsAt!==void 0&&window.resetsAt<=now),bars=parseClaudeUtilization(cached,now);return bars.length===0?{error:"No cached Claude Code usage in ~/.claud\
38
- e.json."}:{bars:stale?[]:bars,fetchedAtMs,stale}}async function readClaudeUsage(registry,accountKey,request,home){let result,failure,lastKnown;try{if(result=await registry.getAnthropicUsage({accountKey,...request}),result?.status==="ok"&&result.windows.length>0){let now2=Date.now(),windows=result.windows.filter(({resetsAt})=>resetsAt===void 0||resetsAt>now2);if(windows.length>0&&now2-result.fetchedAt<=36e5)return{result:{...result,windows}};lastKnown=result.fetchedAt,result={...result,windows:[]}}
39
- failure=result?.status==="unavailable"?CLAUDE_UNAVAILABLE[result.reason]:result?"Claude reported no usage limits.":"No saved Claude account. Run /login."}catch{failure="Claude usage is unavailable."}let now=Date.now(),cache=await readClaudeCachedUsage(async()=>{try{return(await registry.getUsageAccounts(ANTHROPIC_USAGE_PROVIDER_ID,{signal:request.signal})).find(({key})=>key===accountKey)}catch{return}},now,home),required=result?.status==="unavailable"&&result.reason==="refresh_rejected";if("erro\
40
- r"in cache)return{result,fallback:{status:lastKnown===void 0?"No live data":`No live data; last known ${usageAge(now-lastKnown)}`,bars:[],failure,cacheError:cache.error,reconnect:required?"required":lastKnown!==void 0?"optional":void 0}};let age=cache.fetchedAtMs===void 0?void 0:usageAge(now-cache.fetchedAtMs);return{result,fallback:{status:cache.stale?`No live data; last known ${age??"(age unknown)"}`:`Claude Code's cached numbers, from ${age}`,bars:cache.bars,failure,reconnect:required?"requir\
41
- ed":cache.stale?"optional":void 0}}}function nextQuotaResetLines(windows,now){let reset=formatNextQuotaReset(windows,now);return reset?[{label:"Next reset",value:reset}]:[]}var import_semver=__toESM(require_semver(),1);var DEFAULT_VERSION_CHECK_TIMEOUT_MS=1e4;function formatVersionCheckError(error){let rootMessage=error instanceof Error&&error.message?error.message:String(error),cause=error instanceof Error?error.cause:void 0,causes=cause instanceof AggregateError?cause.errors:cause===void 0?[]:[cause],codes=causes.map(value=>typeof value=="object"&&value!==null&&"code"in value&&typeof value.code=="string"?value.code:void 0).filter(code=>code!==void 0);if(codes.length>0)return`${rootMessage} (${[...new Set(codes)].
42
- join(", ")})`;let causeMessage=causes.find(value=>value instanceof Error&&!!value.message)?.message;return causeMessage?`${rootMessage} (cause: ${causeMessage})`:rootMessage}function comparePackageVersions(leftVersion,rightVersion){let left=(0,import_semver.valid)(leftVersion.trim()),right=(0,import_semver.valid)(rightVersion.trim());if(!(!left||!right))return(0,import_semver.compare)(left,right)}function isNewerPackageVersion(candidateVersion,currentVersion){let comparison=comparePackageVersions(
43
- candidateVersion,currentVersion);return comparison!==void 0?comparison>0:candidateVersion.trim()!==currentVersion.trim()}async function getLatestPiRelease(currentVersion,options={}){if(process.env[ENV_OFFLINE])return;let response=await fetchWithRetry(getVersionCheckUrl(),{headers:{"User-Agent":getPiUserAgent(currentVersion),accept:"application/json"}},{maxRetries:options.retry?2:0,timeoutMs:options.timeoutMs??DEFAULT_VERSION_CHECK_TIMEOUT_MS});if(!response.ok)return;let data=await response.json();
44
- if(typeof data.version!="string"||!data.version.trim())return;let packageField=data.packageName??data.name,packageName=typeof packageField=="string"&&packageField.trim()?packageField.trim():void 0,note=typeof data.note=="string"&&data.note.trim()?data.note.trim():void 0;return{version:data.version.trim(),packageName,...note?{note}:{}}}async function checkForNewPiVersion(currentVersion){if(!process.env[ENV_SKIP_VERSION_CHECK])try{let latestRelease=await getLatestPiRelease(currentVersion);return latestRelease&&isNewerPackageVersion(latestRelease.version,currentVersion)?latestRelease:void 0}catch{return}}var SIGNAL_SHUTDOWN_GRACE_MS=1500;async function waitForSignalShutdown(shutdown){let timer;try{await Promise.race([shutdown,new Promise(resolve2=>{timer=setTimeout(resolve2,SIGNAL_SHUTDOWN_GRACE_MS)})])}finally{clearTimeout(timer)}}async function exitAfterSignalShutdown(shutdown,exitCode){try{await waitForSignalShutdown(shutdown)}finally{await killTrackedDetachedChildrenAsync(),process.exit(exitCode)}}import{basename,isAbsolute,relative,resolve,sep}from"node:path";function sanitizeStatusText(text){return text.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()}function formatTokens2(count){return count<1e3?count.toString():count<1e4?`${(count/1e3).toFixed(1)}k`:count<1e6?`${Math.round(count/1e3)}k`:count<1e7?`${(count/1e6).toFixed(1)}M`:`${Math.round(count/1e6)}M`}function formatCwdForFooter(cwd,home){if(!home)return cwd;let resolvedCwd=resolve(cwd),resolvedHome=resolve(home),relativeToHome=relative(resolvedHome,resolvedCwd);return relativeToHome===""||relativeToHome!==
45
- ".."&&!relativeToHome.startsWith(`..${sep}`)&&!isAbsolute(relativeToHome)?relativeToHome===""?"~":`~${sep}${relativeToHome}`:cwd}var FOOTER_VALUE_INPUTS=["width","theme","identity","effort","modelName","accountLabel","routedModelId","provider","age","contextPercent","contextWindow","usingSubscription","usageIncomplete","cost","input","output","cacheRead","cacheWrite","latestCacheHitRate","experimental"];var NO_EXTENSION_STATUSES=[];function sameFooterInputs(a,b){for(let key of FOOTER_VALUE_INPUTS)if(!Object.is(a[key],b[key]))return!1;let statuses=a.extensionStatuses;if(statuses.length!==b.extensionStatuses.length)return!1;for(let i=0;i<statuses.length;i++)if(statuses[i]!==b.extensionStatuses[i])return!1;return!0}var FooterComponent=class{lastEventAt;activitySessionId;activityTimer;session;footerData;sessionStats;rendered;constructor(session,footerData,requestRender){this.session=session,this.footerData=
46
- footerData,this.activitySessionId=session.sessionManager.getSessionId(),this.refreshActivityFromSession(),requestRender&&this.startActivityTimer(requestRender)}setSession(session){let changed=this.session!==session||this.activitySessionId!==session.sessionManager.getSessionId();this.session=session,changed&&this.refreshActivityFromSession()}markActivity(){this.lastEventAt=performance.now()}refreshActivityFromSession(){this.activitySessionId=this.session.sessionManager.getSessionId(),this.lastEventAt=
47
- void 0;let now=Date.now(),latest=0;for(let entry of this.session.sessionManager.getBranch()){if(entry.type!=="message"||entry.message.role!=="user"&&entry.message.role!=="assistant"&&entry.message.role!=="toolResult")continue;let timestamp=Date.parse(entry.timestamp);Number.isFinite(timestamp)&&timestamp>latest&&timestamp<=now&&(latest=timestamp)}latest>0&&(this.lastEventAt=performance.now()-(now-latest))}startActivityTimer(onTick){this.activityTimer||(this.activityTimer=setInterval(()=>{this.lastEventAt!==
48
- void 0&&onTick()},1e3),this.activityTimer.unref())}invalidate(){}dispose(){this.activityTimer&&clearInterval(this.activityTimer),this.activityTimer=void 0}getSessionStats(){let sessionManager=this.session.sessionManager,entryCount=sessionManager.getEntryCount(),sessionId=sessionManager.getSessionId(),leafId=sessionManager.getLeafId(),limitsModel=this.session.routedModel?.model??this.session.model,cached=this.sessionStats;if(cached&&cached.session===this.session&&cached.sessionId===sessionId&&cached.
49
- leafId===leafId&&cached.entryCount===entryCount&&cached.limitsModel===limitsModel)return cached;let usageTotals=createUsageTotals(),latestCacheHitRate,entries=sessionManager.getEntries();for(let{usage}of getSessionUsage(entries))addUsageToTotals(usageTotals,usage);for(let entry of entries)if(entry.type==="message"&&entry.message.role==="assistant"){let latestPromptTokens=entry.message.usage.input+entry.message.usage.cacheRead+entry.message.usage.cacheWrite;latestCacheHitRate=latestPromptTokens>0?
50
- entry.message.usage.cacheRead/latestPromptTokens*100:void 0}let contextUsage=this.session.getContextUsage();return this.sessionStats={session:this.session,sessionId,leafId,entryCount,limitsModel,usageTotals,latestCacheHitRate,contextUsage},this.sessionStats}renderInputs(width){let state=this.session.state,{usageTotals,latestCacheHitRate,contextUsage}=this.getSessionStats(),routed=this.session.routedModel,pwd=basename(this.session.sessionManager.getCwd())||sep,branch=this.footerData.getGitBranch(),
51
- sessionName=this.session.sessionManager.getSessionName(),effectiveModel=routed?.model??state.model,thinkingLevel=routed?.thinkingLevel??state.thinkingLevel??"off",elapsed=this.lastEventAt===void 0?void 0:Math.max(0,Math.floor((performance.now()-this.lastEventAt)/1e3)),accountLabel=state.model?this.footerData.getOAuthAccountLabel(state.model.provider):void 0,statuses=this.footerData.getExtensionStatuses();return{width,theme:getThemeInstance(),identity:[pwd,branch,sessionName].filter(Boolean).map(
52
- text=>stripAnsi(sanitizeStatusText(text))).join(" \xB7 "),effort:this.session.autoEffortSelecting?"Choosing effort\u2026":effectiveModel?.reasoning&&thinkingLevel!=="off"?thinkingLevel[0].toUpperCase()+thinkingLevel.slice(1):"Thinking off",modelName:stripAnsi(sanitizeStatusText(state.model?.id??"no-model")),accountLabel:accountLabel?stripAnsi(sanitizeStatusText(accountLabel)):void 0,routedModelId:routed?stripAnsi(sanitizeStatusText(routed.model.id)):void 0,provider:this.footerData.getAvailableProviderCount()>
53
- 1&&state.model?stripAnsi(sanitizeStatusText(state.model.provider)):void 0,age:elapsed===void 0?"\u2014":elapsed===0?"now":elapsed<60?`${elapsed}s ago`:elapsed<3600?`${Math.floor(elapsed/60)}m ago`:elapsed<86400?`${Math.floor(elapsed/3600)}h ago`:`${Math.floor(elapsed/86400)}d ago`,contextPercent:contextUsage?.percent??void 0,contextWindow:contextUsage?.contextWindow??routed?.model.contextWindow??state.model?.contextWindow??0,usingSubscription:state.model?this.session.modelRuntime.isUsingSubscription(
54
- state.model.provider):!1,usageIncomplete:!!usageTotals.usageIncomplete,cost:usageTotals.cost,input:usageTotals.input,output:usageTotals.output,cacheRead:usageTotals.cacheRead,cacheWrite:usageTotals.cacheWrite,latestCacheHitRate,experimental:areExperimentalFeaturesEnabled(),extensionStatuses:statuses.size===0?NO_EXTENSION_STATUSES:Array.from(statuses.entries()).filter(([key])=>key!=="adhd"&&key!=="caveman"&&key!=="ponytail").sort(([a],[b])=>a.localeCompare(b)).map(([,text])=>sanitizeStatusText(text))}}render(width){
55
- if(width<1)return[];let inputs=this.renderInputs(width),known=this.rendered;if(known&&sameFooterInputs(known.inputs,inputs))return known.lines.slice();let lines=this.renderLines(inputs);return this.rendered={inputs,lines:lines.slice()},lines}renderLines(inputs){let{width,contextPercent}=inputs,context=`Context ${contextPercent===void 0?"?":`${contextPercent.toFixed(1)}%`}/${formatTokens2(inputs.contextWindow)}`,lines=[truncateToWidth(theme.fg("dim",inputs.identity),width,theme.fg("dim","..."))],
56
- {effort,modelName}=inputs,model=modelName,modelFields=[theme.fg("accent",effort)],activity=theme.fg("dim",`Last event ${inputs.age}`);if(inputs.accountLabel){let withAccount=`${modelName} [${inputs.accountLabel}]`;visibleWidth(effort)+3+visibleWidth(withAccount)+2+visibleWidth(activity)<=width&&(model=withAccount)}if(modelFields.push(theme.fg("text",model)),inputs.routedModelId!==void 0&&modelFields.push(theme.fg("muted",`\u2192 ${inputs.routedModelId}`)),inputs.provider!==void 0){let provider=theme.
57
- fg("dim",`(${inputs.provider})`);visibleWidth([...modelFields,provider].join(" \xB7 "))+2+visibleWidth(activity)<=width&&modelFields.push(provider)}lines.push(...this.renderBand(modelFields,activity,width));let contextColor=(contextPercent??0)>90?"error":(contextPercent??0)>70?"warning":"text",{usingSubscription}=inputs,statsParts=[theme.fg(contextColor,context)];inputs.usageIncomplete?statsParts.push(theme.fg("muted",`${inputs.cost>0?`\u2265$${inputs.cost.toFixed(3)}`:"Cost unknown"}${usingSubscription?
58
- " (sub)":""} (usage incomplete)`)):(inputs.cost||usingSubscription)&&statsParts.push(theme.fg("muted",`$${inputs.cost.toFixed(3)}${usingSubscription?" (sub)":""}`)),statsParts.push(theme.fg("dim",`In ${formatTokens2(inputs.input)}`),theme.fg("dim",`Out ${formatTokens2(inputs.output)}`)),inputs.experimental&&statsParts.push(theme.bold(theme.fg("warning","xp"))),lines.push(...this.renderBand(statsParts,void 0,width));let cacheParts=[theme.fg("dim",`Cache read ${formatTokens2(inputs.cacheRead)}`)];
59
- return inputs.cacheWrite&&cacheParts.push(theme.fg("dim",`Cache write ${formatTokens2(inputs.cacheWrite)}`)),cacheParts.push(theme.fg("dim",`Hit ${inputs.latestCacheHitRate===void 0?"\u2014":`${inputs.latestCacheHitRate.toFixed(1)}%`}`)),lines.push(...this.renderBand(cacheParts,theme.fg("dim","/settings"),width)),inputs.extensionStatuses.length&&lines.push(truncateToWidth(inputs.extensionStatuses.join(" "),width,theme.fg("dim","..."))),lines}renderBand(fields,right,width){let lines=[],line="";for(let field of fields)
60
- if(line&&visibleWidth(`${line} \xB7 ${field}`)>width&&(lines.push(line),line=""),visibleWidth(field)>width){let wrapped=wrapTextWithAnsi(field,width);lines.push(...wrapped.slice(0,-1)),line=wrapped.at(-1)??""}else line=line?`${line} \xB7 ${field}`:field;if(right)if(line&&visibleWidth(line)+2+visibleWidth(right)<=width)line+=" ".repeat(width-visibleWidth(line)-visibleWidth(right))+right;else{line&&lines.push(line);let wrapped=wrapTextWithAnsi(right,width);lines.push(...wrapped.slice(0,-1)),line=wrapped.
61
- at(-1)??""}return line&&lines.push(line),lines.map(rendered=>truncateToWidth(rendered,width,""))}};var ModelCatalogRefreshCoordinator=class{activeByRuntime=new WeakMap;hcodeOnlyByRuntime=new WeakMap;checkWatchedHcode(runtime,signal){return this.activeByRuntime.has(runtime)||this.hcodeOnlyByRuntime.has(runtime)?Promise.resolve(void 0):this.refreshHcode(runtime,signal)}refreshHcode(runtime,signal){signal.throwIfAborted();let hcode=this.hcodeOnlyByRuntime.get(runtime);if(hcode)return raceWithAbortSignal(hcode,signal);if(this.activeByRuntime.has(runtime))return this.refresh(runtime,signal).then(({
62
- aborted,errors})=>({aborted,errors:new Map([...errors].filter(([provider])=>provider===HCODE_PROVIDER))}));let operation=raceWithAbortSignal(runtime.refresh({providers:[HCODE_PROVIDER],signal}),signal).finally(()=>this.hcodeOnlyByRuntime.delete(runtime));return this.hcodeOnlyByRuntime.set(runtime,operation),operation}refresh(modelRuntime,signal){signal.throwIfAborted();let active=this.activeByRuntime.get(modelRuntime);if(!active){let controller=new AbortController,created,hcode=this.hcodeOnlyByRuntime.
63
- get(modelRuntime),operation=hcode?raceWithAbortSignal(hcode,controller.signal).then(result=>(controller.signal.throwIfAborted(),result.aborted?result:modelRuntime.refresh({signal:controller.signal}))):modelRuntime.refresh({signal:controller.signal}),promise=raceWithAbortSignal(operation,controller.signal).finally(()=>{this.activeByRuntime.get(modelRuntime)===created&&this.activeByRuntime.delete(modelRuntime)});created={controller,promise,waiters:0},active=created,this.activeByRuntime.set(modelRuntime,
64
- active)}return active.waiters++,raceWithAbortSignal(active.promise,signal).finally(()=>{active.waiters--,active.waiters===0&&this.activeByRuntime.get(modelRuntime)===active&&active.controller.abort()})}},modelCatalogRefreshCoordinator=new ModelCatalogRefreshCoordinator;async function checkWatchedHcodeCatalog(modelRuntime,signal){return modelCatalogRefreshCoordinator.checkWatchedHcode(modelRuntime,signal)}async function retryHcodeCatalog(modelRuntime,signal){return modelCatalogRefreshCoordinator.
65
- refreshHcode(modelRuntime,signal)}function refreshModelCatalogs(modelRuntime,signal){return modelCatalogRefreshCoordinator.refresh(modelRuntime,signal)}function refreshStartupModelCatalogs(modelRuntime,signal){return signal.throwIfAborted(),raceWithAbortSignal(modelRuntime.refresh({providers:modelRuntime.getProviders().filter(provider=>provider.id!==HCODE_PROVIDER).map(provider=>provider.id),signal}),signal)}var FULLSCREEN_OVERLAY={overlay:!0,overlayOptions:{width:"100%",maxHeight:"100%",margin:0}};function fullscreenSurface(component,height){let render=component.render.bind(component);return component.render=width=>{let lines=render(width);if(lines.length===0)return[];let black="\x1B[48;2;0;0;0m";return Array.from({length:Math.max(0,height())},(_,index)=>{let line=truncateToWidth(lines[index]??"",width);return black+line.replace(/\x1b\[(?:0|49)?m/g,`$&${black}`)+" ".repeat(Math.max(0,width-visibleWidth(
66
- line)))+"\x1B[0m"})},component}var AuthCommandError=class extends Error{},AUTH_COMMAND_USAGE={check:`${APP_COMMAND} auth check --provider <provider> [--json] [--credentials] [--no-refresh]`,api_key:`${APP_COMMAND} auth print-api-key --provider <provider> [--model <model>]`,bearer_token:`${APP_COMMAND} auth print-bearer-token --provider <provider> [--model <model>] [--min-expiry <duration>]`};function getAuthCommandName(kind){return kind==="check"?"auth check":kind==="api_key"?"auth print-api-key":"auth print-bearer-token"}function getAuthCommandUsage(kind){
67
- return AUTH_COMMAND_USAGE[kind]}function isAuthCommandHelp(args){return args[0]==="auth"&&(args[1]===void 0||args[1]==="help"||args.includes("--help")||args.includes("-h"))}function printAuthCommandHelp(){console.log(`Usage:
68
- ${APP_COMMAND} auth print-api-key [--provider <provider>] [--model <model>]
69
- ${APP_COMMAND} auth print-bearer-token [--provider <provider>] [--model <model>] [--min-expiry <duration>]
70
- ${APP_COMMAND} auth check [--provider <provider>] [--model <model>] [--json] [--credentials] [--no-refresh]
71
-
72
- Auth commands require at least one of --provider or --model. Checks refresh expired OAuth credentials by default; --no-refresh prevents this. --credentials emits the credential, or includes it in JSON output.`)}function parseAuthCommand(args){if(args[0]!=="auth")return;let kind=args[1]==="check"?"check":args[1]==="print-api-key"?"api_key":args[1]==="print-bearer-token"?"bearer_token":void 0;if(!kind)throw new AuthCommandError(`Unknown auth command "${args[1]??""}". Use "${APP_COMMAND} auth print\
73
- -api-key", "${APP_COMMAND} auth print-bearer-token", or "${APP_COMMAND} auth check".`);let commandArgs=[],json=!1,credentials=!1,noRefresh=!1,minExpiryMs;for(let index=2;index<args.length;index++){let arg=args[index];if(arg==="--min-expiry"){if(kind!=="bearer_token")throw new AuthCommandError("--min-expiry is only supported by print-bearer-token");let value=args[++index],match=value?/^(\d+)(ms|s|m|h)$/iu.exec(value):void 0;if(!match)throw new AuthCommandError("--min-expiry must use a duration su\
74
- ch as 30m or 1h");let amount=Number(match[1]),unit=match[2];minExpiryMs=amount*(unit==="ms"?1:unit==="s"?1e3:unit==="m"?6e4:36e5);continue}if(arg==="--json"||arg==="--credentials"||arg==="--no-refresh"){if(kind!=="check")throw new AuthCommandError(`${arg} is only supported by auth check`);arg==="--json"?json=!0:arg==="--credentials"?credentials=!0:noRefresh=!0;continue}commandArgs.push(arg)}return minExpiryMs===void 0?{kind,args:commandArgs,json,credentials,noRefresh}:{kind,args:commandArgs,json,
75
- credentials,noRefresh,minExpiryMs}}function validateAuthCommandArgs(args,kind){let provider=args.provider?.trim()||void 0,model=args.model?.trim()||void 0;if(args.unknownFlags.size>0){let option=args.unknownFlags.keys().next().value;throw new AuthCommandError(`Unknown option --${option} for "${getAuthCommandName(kind)}".`)}if(args.apiKey!==void 0||args.messages.length>0||args.fileArgs.length>0)throw new AuthCommandError("Auth commands only accept --provider and --model");if(kind==="check"){if(!provider&&
76
- !model)throw new AuthCommandError("Auth checks require --provider <provider> or --model <model>");return{provider,model}}if(!provider&&!model)throw new AuthCommandError("Credential printing requires --provider <provider> or --model <model>");return{provider,model}}function getAuthCredential(auth){if(auth?.auth.apiKey)return auth.auth.apiKey;let authorization=Object.entries(auth?.auth.headers??{}).find(([name])=>name.toLowerCase()==="authorization")?.[1];return typeof authorization=="string"?/^Bearer\s+(.+)$/iu.
77
- exec(authorization)?.[1]:void 0}var AuthUrlComponent=class extends Container{url;tui;hint;constructor(tui,url){super(),this.tui=tui,this.url=url,this.addChild(new Text(theme.fg("accent",hyperlink(url,url)),1,0)),this.hint=new Text("",1,0),this.addChild(this.hint),this.setHint(keyHint("app.message.copy","to copy"))}setHint(suffix){let clickHint=process.platform==="darwin"?"Cmd+click to open":"Ctrl+click to open";this.hint.setText(`${theme.fg("dim",hyperlink(clickHint,this.url))} ${theme.fg("dim","\u2022")} ${suffix}`),this.tui.
78
- requestRender()}async copy(){try{await copyToClipboard(this.url),this.setHint(theme.fg("success","Copied URL to clipboard"))}catch(error){this.setHint(theme.fg("error",error instanceof Error?error.message:String(error)))}}};function usagePaneRow(theme2,list,detail,listWidth){return truncateToWidth(list,listWidth,"\u2026",!0)+theme2.fg("dim"," \u2502 ")+detail}function renderUsageBar(theme2,bar,width){let fraction=bar.total&&bar.total>0?Math.min(1,Math.max(0,bar.used/bar.total)):0,filled=Math.round(fraction*width);return theme2.fg(bar.tone,"\u2588".repeat(filled))+theme2.fg("muted","\u2591".repeat(width-filled))}export{AuthCommandError,getAuthCommandName,getAuthCommandUsage,isAuthCommandHelp,printAuthCommandHelp,parseAuthCommand,validateAuthCommandArgs,getAuthCredential,HCODE_LOGIN_MISMATCH_DETAILS,hcodeEmptyCatalogMessage,hcodeEmptyCatalogReason,hcodeEmptyCatalogNotice,hcodeLoginAvailability,hcodeSignedInElsewhereNotice,runClipboardCommand,readClipboardText,readClipboardFilePaths,copyToClipboard,AuthUrlComponent,trackUserWait,currentUserWait,onUserWaitChange,bindClaudeUsageReconnect,getClaudeUsageReconnect,
79
- subscriptionAccountUsage,formatOAuthAccountResetTime,formatOAuthAccountUsage,formatOAuthAccountOption,usageDisplayText,buildUsageOverview,formatUsageOverview,weeklyResetLines,paidUsageLines,claudeUsageBars,codexUsageBars,usageAge,readClaudeUsage,nextQuotaResetLines,formatVersionCheckError,isNewerPackageVersion,getLatestPiRelease,checkForNewPiVersion,waitForSignalShutdown,exitAfterSignalShutdown,usagePaneRow,renderUsageBar,formatTokens2 as formatTokens,formatCwdForFooter,FooterComponent,checkWatchedHcodeCatalog,
80
- retryHcodeCatalog,refreshModelCatalogs,refreshStartupModelCatalogs,FULLSCREEN_OVERLAY,fullscreenSurface};
@@ -1,74 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{VisualLinePreview,getTextOutput,replaceTabs,startToolTimer,str,toolTimerText}from"./chunk-3E37CJCE.js";import{SETTINGS_DEFAULTS}from"./chunk-GV5OVRKK.js";import{CodeHighlighter,keyHint}from"./chunk-E4VUW4RI.js";import{Container,Spacer,Text,sanitizeTerminalText}from"./chunk-M5TVWJ5T.js";import{typebox_exports}from"./chunk-VEGJT52D.js";import{getDocsPath}from"./chunk-VFLVWPLZ.js";function toCodemodeIdentifier(name){let identifier="";for(let char of name){let valid=identifier===""?/^[A-Za-z_$]$/.test(char):/^[A-Za-z0-9_$]$/.test(char);identifier+=valid?char:"_"}return identifier===""?"_":identifier}var IDENTIFIER=/^[A-Za-z_$][A-Za-z0-9_$]*$/,INDENT=" ",DEFAULT_INPUT_SCHEMA_MAX_CHARS=16e3,MAX_REF_EXPANSIONS=32,TAG_KEYWORDS=["minimum","exclusiveMinimum","maximum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","format","minItems","maxItems"],LOWER_BOUNDS=new Set(["minimum","exclusiveMinimum","minLength","minItems"]),UPPER_BOUNDS=new Set(["maximum","exclusiveMaximum","maxLength","maxItems"]),MAX_TAG_CHARS=80,LINE_TERMINATORS=/[\r\n\u2028\u2029]/g;function renderToolSignature(tool,options={}){let input=tool.inputSchema===void 0?"unknown":schemaToType(tool.inputSchema,{maxChars:options.inputMaxChars??DEFAULT_INPUT_SCHEMA_MAX_CHARS});return`${toCodemodeIdentifier(tool.name)}(args: ${input}): Promise<${renderToolOutputType(tool.outputSchema)}>;`}function renderToolSample(tool,options={}){let declaration=`declare const tools: { ${renderToolSignature(tool,options)} };`;return`${tool.description?.trim()??""}
3
-
4
- codemode tool declaration:
5
- \`\`\`ts
6
- ${declaration}
7
- \`\`\``}function renderToolOutputType(schema){return schema===void 0?"unknown":schemaToType(schema)}function propertyKey(name){return IDENTIFIER.test(name)?name:JSON.stringify(name)}function union(types){let unique=[...new Set(types)];return unique.includes("unknown")?"unknown":unique.length===0?"never":unique.join(" | ")}function schemaToType(schema,options={}){let render=tags=>toType(schema,{root:schema,resolving:new Set,expansions:0,tags}),type=render(!0);if(options.maxChars===void 0||type.length<=options.maxChars)return type;let untagged=render(!1);return untagged.length<=options.maxChars?
8
- untagged:"unknown"}function resolveSchemaRef(ref,root){if(!ref.startsWith("#"))return;let pointer;try{pointer=decodeURIComponent(ref.slice(1))}catch{return}if(pointer!==""&&!pointer.startsWith("/"))return;let current=root;for(let segment of pointer===""?[]:pointer.slice(1).split("/")){let key=segment.replaceAll("~1","/").replaceAll("~0","~");if(typeof current!="object"||current===null||!Object.hasOwn(current,key)||Array.isArray(current)&&(!/^(0|[1-9][0-9]*)$/.test(key)||Number(key)>=current.length))
9
- return;current=current[key]}return typeof current=="boolean"||typeof current=="object"&&current!==null&&!Array.isArray(current)?current:void 0}function toType(schema,context){if(schema===!0)return"unknown";if(schema===!1)return"never";if(typeof schema!="object"||schema===null||Array.isArray(schema))return"unknown";if(typeof schema.$ref=="string"){let ref=schema.$ref;if(context.resolving.has(ref)||context.expansions>=MAX_REF_EXPANSIONS)return"unknown";let target=resolveSchemaRef(ref,context.root);
10
- if(target===void 0)return"unknown";context.expansions++,context.resolving.add(ref);try{return toType(target,context)}finally{context.resolving.delete(ref)}}if("const"in schema)return JSON.stringify(schema.const)??"unknown";if(Array.isArray(schema.enum))return union(schema.enum.map(value=>JSON.stringify(value)??"unknown"));let variants=Array.isArray(schema.anyOf)?schema.anyOf:Array.isArray(schema.oneOf)?schema.oneOf:void 0;if(variants)return union(variants.map(variant=>toType(variant,context)));if(Array.
11
- isArray(schema.allOf)){let parts=schema.allOf.map(part=>toType(part,context)).filter(part=>part!=="unknown");return parts.length===0?"unknown":parts.map(part=>part.includes(" | ")?`(${part})`:part).join(" & ")}let type=schema.type;if(Array.isArray(type))return union(type.map(entry=>toType({...schema,type:entry},context)));switch(type){case"string":return"string";case"number":case"integer":return"number";case"boolean":return"boolean";case"null":return"null";case"array":return arrayType(schema,context);case"\
12
- object":return objectType(schema,context);case void 0:return"properties"in schema||"additionalProperties"in schema||"required"in schema?objectType(schema,context):"items"in schema||"prefixItems"in schema?arrayType(schema,context):"unknown";default:return"unknown"}}function arrayType(schema,context){if(schema.items!==void 0&&!Array.isArray(schema.items))return`Array<${toType(schema.items,context)}>`;let tuple=Array.isArray(schema.prefixItems)?schema.prefixItems:Array.isArray(schema.items)?schema.
13
- items:[];return tuple.length>0?`[${tuple.map(item=>toType(item,context)).join(", ")}]`:"unknown[]"}function descriptionOf(property){let description=property?.description;return typeof description=="string"?description.trim():""}function constraintTags(schema){if(typeof schema!="object"||schema===null||Array.isArray(schema))return"";let property=schema,variants=Array.isArray(property.anyOf)?property.anyOf:property.oneOf,nonNull=Array.isArray(variants)?variants.filter(variant=>variant?.type!=="nul\
14
- l"):[],branch=nonNull.length===1?nonNull[0]:void 0,schemas=(typeof branch=="object"&&branch!==null&&!Array.isArray(branch)?[property,branch]:[property]).map(schema2=>({...schema2,...schema2.exclusiveMinimum===!0?{minimum:void 0,exclusiveMinimum:schema2.minimum}:{},...schema2.exclusiveMaximum===!0?{maximum:void 0,exclusiveMaximum:schema2.maximum}:{}})),tags=[],isInteger=type=>type==="integer"||Array.isArray(type)&&type.includes("integer");schemas.some(schema2=>isInteger(schema2.type))&&tags.push(
15
- "@integer");for(let keyword of TAG_KEYWORDS){let values=schemas.map(schema2=>schema2[keyword]);if(LOWER_BOUNDS.has(keyword)||UPPER_BOUNDS.has(keyword)){let numbers=values.filter(value=>typeof value=="number");if(numbers.length===0)continue;tags.push(`@${keyword} ${LOWER_BOUNDS.has(keyword)?Math.max(...numbers):Math.min(...numbers)}`);continue}for(let value of new Set(values))(typeof value=="number"||typeof value=="string")&&tags.push(`@${keyword} ${value}`)}return schemas.some(schema2=>schema2.uniqueItems===
16
- !0)&&tags.push("@uniqueItems"),property.default!==void 0&&property.default!==null&&tags.push(`@default ${JSON.stringify(property.default)}`),property.deprecated===!0&&tags.push("@deprecated"),tags.filter(tag=>tag.length<=MAX_TAG_CHARS).map(tag=>tag.replace(LINE_TERMINATORS,char=>`\\u${char.charCodeAt(0).toString(16).padStart(4,"0")}`)).join(" ")}function objectType(schema,context){let properties=typeof schema.properties=="object"&&schema.properties!==null&&!Array.isArray(schema.properties)?schema.
17
- properties:{},required=new Set(Array.isArray(schema.required)?schema.required:[]),names=Object.keys(properties).sort(),members=names.map(name=>{let optional=required.has(name)?"":"?";return`${propertyKey(name)}${optional}: ${toType(properties[name],context)};`}),additional=schema.additionalProperties;if(additional!==void 0&&additional!==!1){let type=additional===!0?"unknown":toType(additional,context);members.push(`[key: string]: ${type};`)}else additional===void 0&&names.length===0&&members.push(
18
- "[key: string]: unknown;");if(members.length===0)return"{}";let comments=names.map(name=>{let lines2=descriptionOf(properties[name]).split(LINE_TERMINATORS).map(line=>line.trim()).filter(Boolean),tags=context.tags?constraintTags(properties[name]):"";return tags?[...lines2,tags]:lines2});if(!comments.some(comment=>comment.length>0))return`{ ${members.join(" ")} }`;let lines=["{"];comments.forEach((comment,index)=>{for(let line of comment)lines.push(`${INDENT}// ${line}`);lines.push(`${INDENT}${members[index].
19
- replaceAll(`
20
- `,`
21
- ${INDENT}`)}`)});for(let member of members.slice(names.length))lines.push(`${INDENT}${member}`);return lines.push("}"),lines.join(`
22
- `)}var CODEMODE_OPTIONS_PREFIX="// @options:",SUPPORTED_FIELDS=["max_output_tokens","timeout_ms"],SUPPORTED_FIELDS_TEXT="`max_output_tokens` and `timeout_ms`";var CODEMODE_SOURCE_GRAMMAR=String.raw`
23
- start: options_source | plain_source
24
- options_source: OPTIONS_LINE NEWLINE SOURCE
25
- plain_source: SOURCE
26
-
27
- OPTIONS_LINE: /[ \t]*\/\/ @options:[^\r\n]*/
28
- NEWLINE: /\r?\n/
29
- SOURCE: /[\s\S]+/
30
- `,CodemodeSourceError=class extends Error{constructor(message){super(message),this.name="CodemodeSourceError"}};function isSafeInteger(value){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=0}function parseOptions(directive){if(directive==="")throw new CodemodeSourceError(`@options must be a JSON object with supported fields ${SUPPORTED_FIELDS_TEXT}`);let value;try{value=JSON.parse(directive)}catch(error){throw new CodemodeSourceError(`@options must be valid JSON with supporte\
31
- d fields ${SUPPORTED_FIELDS_TEXT}: ${error instanceof Error?error.message:String(error)}`)}if(typeof value!="object"||value===null||Array.isArray(value))throw new CodemodeSourceError(`@options must be a JSON object with supported fields ${SUPPORTED_FIELDS_TEXT}`);let fields=value;for(let key of Object.keys(fields))if(!SUPPORTED_FIELDS.includes(key))throw new CodemodeSourceError(`@options only supports ${SUPPORTED_FIELDS_TEXT}; got \`${key}\``);let options={},{max_output_tokens,timeout_ms}=fields;
32
- if(max_output_tokens!==void 0){if(!isSafeInteger(max_output_tokens))throw new CodemodeSourceError("@options field `max_output_tokens` must be a non-negative safe integer");options.maxOutputTokens=max_output_tokens}if(timeout_ms!==void 0){if(!isSafeInteger(timeout_ms)||timeout_ms===0||timeout_ms>2147483647)throw new CodemodeSourceError("@options field `timeout_ms` must be a positive integer up to 2147483647");options.timeoutMs=timeout_ms}return options}function parseCodemodeSource(input){if(input.
33
- trim()==="")throw new CodemodeSourceError('Expected JavaScript source text (non-empty). Provide JS only, optionally with a first line `// @options: {"max_output_tokens": 1000}`.');let lines=input.split(`
34
- `),misplaced=lines.findIndex((line,index)=>index>0&&line.trimStart().startsWith(CODEMODE_OPTIONS_PREFIX));if(misplaced!==-1)throw new CodemodeSourceError(`The ${CODEMODE_OPTIONS_PREFIX} line must be the first line of the input; found one on line ${misplaced+1}`);let newline=input.indexOf(`
35
- `),trimmed=lines[0].replace(/\r$/,"").trimStart();if(!trimmed.startsWith(CODEMODE_OPTIONS_PREFIX))return{code:input,options:{}};let code=newline===-1?"":input.slice(newline);if(code.trim()==="")throw new CodemodeSourceError("The @options line must be followed by JavaScript source on subsequent lines");return{code,options:parseOptions(trimmed.slice(CODEMODE_OPTIONS_PREFIX.length).trim())}}import{join}from"node:path";var loadCodemodeExecutor=()=>import("./execute-6MEJJF2T.js");var CODE_PREVIEW_LINES=10,CALL_PREVIEW_COUNT=8,OUTPUT_PREVIEW_LINES=5,COLLAPSED_ARGS_CHARS=80,SCRIPT_HEADER=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function expandHint(theme,hidden,noun){return`${theme.fg("muted",`... (${hidden} more ${noun},`)} ${keyHint("app.tools.expand","to expand")}${theme.fg("muted",")")}`}function formatDuration(ms){return ms===void 0?"":ms<1e3?`${Math.round(ms)}ms`:`${(ms/1e3).toFixed(1)}s`}function formatCost(cost){return`$${cost>=.01?cost.toFixed(
36
- 2):cost.toPrecision(2)}`}function statusIcon(call,theme){switch(call.status){case"running":return theme.fg("warning","\u2026");case"ok":return theme.fg("success","\u2713");case"error":return theme.fg("error","\u2717");case"cancelled":return theme.fg("muted","\u2298")}}function formatCall(call,theme,expanded){let callArgs=sanitizeTerminalText(call.args),args=!expanded&&callArgs.length>COLLAPSED_ARGS_CHARS?`${callArgs.slice(0,COLLAPSED_ARGS_CHARS-3)}...`:callArgs,duration=formatDuration(call.durationMs),
37
- line=`${statusIcon(call,theme)} ${theme.fg("toolTitle",sanitizeTerminalText(call.name))}`;return args&&(line+=` ${theme.fg("muted",args)}`),duration&&(line+=` ${theme.fg("dim",duration)}`),call.cost&&(line+=` ${theme.fg("dim",formatCost(call.cost))}`),expanded&&call.error&&(line+=`
38
- ${theme.fg("error",sanitizeTerminalText(call.error).split(`
39
- `).join(`
40
- `))}`),line}var codemodeRenderers={renderCall(args,theme,context){startToolTimer(context);let code=str(args?.code),title=theme.fg("toolTitle",theme.bold("codemode")),component=context.lastComponent??new Container;if(component.clear(),code===null)return component.addChild(new Text(`${title} ${theme.fg("error","[invalid arg]")}`,0,0)),component;if(component.addChild(new Text(title,0,0)),code){let state=context.state;state.scriptHighlighter??=new CodeHighlighter;let highlighted=state.scriptHighlighter.
41
- highlight(replaceTabs(code.replace(/\r/g,"").trimEnd()),"javascript").join(`
42
- `);component.addChild(context.expanded?new Text(highlighted,0,0):new VisualLinePreview({text:highlighted,maxVisualLines:CODE_PREVIEW_LINES,keep:"start",formatHint:hidden=>expandHint(theme,hidden,"lines")}))}return component},renderResult(result,options,theme,context){let timerText=toolTimerText(context,options.isPartial),component=context.lastComponent??new Container;component.clear();let calls=result.details?.calls??[];if(calls.length>0){let shown=options.expanded?calls:calls.slice(-CALL_PREVIEW_COUNT),
43
- lines=shown.map(call=>formatCall(call,theme,options.expanded));shown.length<calls.length&&lines.unshift(`${theme.fg("muted",`... (${calls.length-shown.length} earlier calls,`)} ${keyHint("app.tools.expand","to expand")}${theme.fg("muted",")")}`);let priced=calls.filter(call=>call.cost);if(priced.length>1){let total=priced.reduce((sum,call)=>sum+(call.cost??0),0);lines.push(theme.fg("muted",`Model calls: ${formatCost(total)}`))}component.addChild(new Spacer(1)),component.addChild(new Text(lines.join(
44
- `
45
- `),0,0))}let[first,...rest]=result.content,hasHeader=first?.type==="text"&&SCRIPT_HEADER.test(first.text),output=options.isPartial?"":getTextOutput({...result,content:hasHeader?rest:result.content},context.showImages).trim();if(output){let color=context.isError?"error":"toolOutput",styled=replaceTabs(output).split(`
46
- `).map(line=>theme.fg(color,line)).join(`
47
- `);if(component.addChild(new Spacer(1)),options.expanded)component.addChild(new Text(styled,0,0));else{component.addChild(new VisualLinePreview({text:styled,maxVisualLines:OUTPUT_PREVIEW_LINES,keep:"start",formatHint:hidden=>expandHint(theme,hidden,"lines")}));let fullOutputPath=result.details?.fullOutputPath;fullOutputPath&&component.addChild(new Text(theme.fg("muted",`Full output: ${fullOutputPath}`),0,0))}}return timerText&&(component.addChild(new Spacer(1)),component.addChild(new Text(theme.
48
- fg("muted",timerText),0,0))),component}};var CODEMODE_TOOL_NAME="codemode",CODEMODE_STORE_ENTRY_TYPE="codemode-store",TEXT_OUTPUT_SCHEMA={type:"string"},codemodeSchema=typebox_exports.Object({code:typebox_exports.String({description:"Raw JavaScript source."})}),codemodeToolSystemPromptContribution={snippet:"Run JavaScript that calls other tools",guidelines:["Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls."]},CODEMODE_DOCS_PATH=join(getDocsPath(),"cod\
49
- emode.md"),DESCRIPTION_INTRO='Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level `await` and `return` work. No Node, file system, network, or timers.\n- `await tools.<name>({ ...args })` resolves to a string, or an object if the tool\'s declaration says so, and rejects with an Error on failure. A tool whose declaration returns an object resolves on failure too when it returned that object; chec\
50
- k its fields. Calls still running when the script ends are cancelled.\n- Optional first line: `// @options: {"max_output_tokens": 10000, "timeout_ms": 60000}`';function describeGlobals(models){let lines=["Globals:","- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. With several text items, each starts with a `==> text N/M <==` line, and `console` lines follow the other output in one `<console_output>` block. `image()` \
51
- also saves the image to a temp file and the result names its path.","- `store(key, value)` and `load(key)` keep JSON values across codemode calls.","- `ALL_TOOLS`, `await searchTools(query, { limit?, namespace? })`, `await describeTool(name)`, `await describeNamespace(name)`: find unlisted tools, such as MCP tools."];return models&&lines.push(`- \`models\`: classifiers and image generation. Read ${CODEMODE_DOCS_PATH} first.`),lines.join(`
52
- `)}var DEFAULT_CODEMODE_INLINE_BUDGET=SETTINGS_DEFAULTS.codemode.inlineBudget,CHARS_PER_TOKEN=4;function toCodemodeDeclaration(tool,guidelines=[]){let bullets=guidelines.flatMap(guideline=>guideline.trim()?[`- ${guideline.trim()}`]:[]);return{name:tool.name,description:bullets.length>0?`${tool.description.trim()}
53
-
54
- ${bullets.join(`
55
- `)}`:tool.description,inputSchema:tool.parameters,outputSchema:tool.outputSchema??TEXT_OUTPUT_SCHEMA}}function getCodemodeCallableTools(tools){return tools.filter(tool=>tool.name!==CODEMODE_TOOL_NAME)}function renderToolSection(declaration){let id=toCodemodeIdentifier(declaration.name);return`${id===declaration.name?`### \`${id}\``:`### \`${id}\` (\`${declaration.name}\`)`}
56
- ${renderToolSample(declaration).trim()}`}function selectCatalog(groups,budget){if(budget===void 0)return new Set(groups.flatMap(group=>group.entries.map(entry=>entry.name)));let queues=groups.map(group=>[...group.entries].sort((a,b)=>a.cost-b.cost)),shown=new Set,remaining=budget,active=queues.filter(queue=>queue.length>0);for(;active.length>0;)active=active.filter(queue=>{let next=queue[0];return next.cost>remaining?!1:(remaining-=next.cost,shown.add(next.name),queue.shift(),queue.length>0)});return shown}
57
- function createCodemodeDescription(tools,options={}){let declarations=getCodemodeCallableTools(tools).filter(tool=>!options.deferred?.has(tool.name)).map(tool=>toCodemodeDeclaration(tool,options.guidelines?.get(tool.name))),groups=new Map([["",{namespace:void 0,entries:[]}]]);for(let declaration of declarations){let namespace=options.namespaces?.get(declaration.name),key=namespace?`ns:${namespace.name}`:"",group=groups.get(key)??{namespace,entries:[]};groups.set(key,group);let section=renderToolSection(
58
- declaration);group.entries.push({name:declaration.name,section,cost:Math.ceil(section.length/CHARS_PER_TOKEN)})}let ordered=[...groups.values()].sort((a,b)=>a.namespace===void 0?-1:b.namespace===void 0?1:a.namespace.name.localeCompare(b.namespace.name)),shown=selectCatalog(ordered,options.inlineBudget),sections=[DESCRIPTION_INTRO,describeGlobals(options.models===!0)];if(declarations.length===0)return sections.join(`
59
-
60
- `);let toolSections=["Nested tools:"];for(let{namespace,entries}of ordered){let visible=entries.filter(entry=>shown.has(entry.name));if(namespace){let listing=visible.length===entries.length?"":visible.length===0?" (tools not listed)":" (some tools not listed)",description=namespace.description?.trim();toolSections.push(`## ${namespace.name}${listing}${description?`
61
- ${description}`:""}`)}for(let entry of visible)toolSections.push(entry.section)}return sections.push(toolSections.join(`
62
-
63
- `)),sections.join(`
64
-
65
- `)}function describeFields(schema,root,depth){let resolved=followRef(schema,root);if(typeof resolved!="object"||resolved===null)return;let{type,properties,required}=resolved;if(type!=="object"||typeof properties!="object"||properties===null)return;let requiredNames=new Set(Array.isArray(required)?required:[]);return`{ ${Object.entries(properties).map(([name,field])=>{let constValue=followRef(field,root)?.const,nested=constValue!==void 0?JSON.stringify(constValue):depth>0?describeFields(field,root,
66
- depth-1):void 0;return`${name}${requiredNames.has(name)?"":"?"}${nested?`: ${nested}`:""}`}).join(", ")} }`}function describeOutput(name,schema){let type=renderToolOutputType(schema);if(type==="string")return"a string";let fields=schema===void 0?void 0:describeFields(schema,schema,1)??describeUnionFields(schema,schema);return fields?`\`${fields}\``:type.includes(`
67
- `)?`a value; \`await describeTool(${JSON.stringify(name)})\` shows its type`:`\`${type}\``}function describeUnionFields(schema,root){let resolved=followRef(schema,root);if(typeof resolved!="object"||resolved===null)return;let{anyOf,oneOf}=resolved,variants=anyOf??oneOf;if(!Array.isArray(variants)||variants.length===0)return;let described=variants.map(variant=>describeFields(variant,root,0));return described.every(fields=>fields!==void 0)?described.join(" | "):void 0}function followRef(schema,root){
68
- let seen=new Set,current=schema;for(;typeof current=="object"&&current!==null&&!seen.has(current);){let ref=current.$ref;if(typeof ref!="string")break;let target=resolveSchemaRef(ref,root);if(target===void 0)break;seen.add(current),current=target}return current}function describeScriptCall(tool){return`${tool.description.trim()}
69
-
70
- Codemode: \`tools.${toCodemodeIdentifier(tool.name)}(args)\` resolves to ${describeOutput(tool.name,toCodemodeDeclaration(tool).outputSchema)}.`}function prepareCodemodeLoadout(loadout,options){let mode=options.getMode?.()??SETTINGS_DEFAULTS.codemode.mode,isDirect=tool=>loadout.getExposure(tool.name)==="direct",callable=getCodemodeCallableTools(loadout.callable),callableNames=new Set(callable.map(tool=>tool.name)),descriptions={};if(mode==="on")for(let tool of loadout.declared)callableNames.has(
71
- tool.name)&&(descriptions[tool.name]=describeScriptCall(tool));let listed=mode==="only"?callable:callable.filter(tool=>!isDirect(tool)),namespaces=new Map(listed.flatMap(tool=>{let namespace=loadout.getNamespace(tool.name);return namespace?[[tool.name,namespace]]:[]})),guidelines=new Map(listed.map(tool=>[tool.name,loadout.getPromptGuidelines(tool.name)]));descriptions[CODEMODE_TOOL_NAME]=createCodemodeDescription(listed,{models:options.models===!0,namespaces,guidelines,deferred:new Set(listed.filter(
72
- tool=>loadout.getExposure(tool.name)==="deferred").map(tool=>tool.name)),inlineBudget:options.getInlineBudget?.()??DEFAULT_CODEMODE_INLINE_BUDGET});let declaredNames=new Set(loadout.declared.map(tool=>tool.name));return{descriptions,hiddenDeclarations:mode==="only"?callable.filter(tool=>isDirect(tool)&&declaredNames.has(tool.name)).map(tool=>tool.name):[]}}var DISCOVERY_GLOBALS=/\b(searchTools|describeNamespace|describeTool|ALL_TOOLS)\b/;function getScriptReach(code){return typeof code!="string"?
73
- []:DISCOVERY_GLOBALS.test(code)?"all":code.match(/\w+/g)??[]}function createCodemodeToolDefinition(options={}){return{name:CODEMODE_TOOL_NAME,label:CODEMODE_TOOL_NAME,description:createCodemodeDescription([],{models:options.models===!0}),promptSnippet:codemodeToolSystemPromptContribution.snippet,promptGuidelines:[...codemodeToolSystemPromptContribution.guidelines],parameters:codemodeSchema,exposure:"model-only",prepareLoadout:loadout=>prepareCodemodeLoadout(loadout,options),reachesTools:input=>getScriptReach(
74
- input.code),constrainedSampling:{type:"grammar",variants:{openai_lark:CODEMODE_SOURCE_GRAMMAR}},execute:async(toolCallId,params,signal,onUpdate,ctx)=>(await loadCodemodeExecutor()).executeCodemode(toolCallId,params,signal,onUpdate,ctx,options),...codemodeRenderers}}export{toCodemodeIdentifier,renderToolSample,resolveSchemaRef,parseCodemodeSource,CODEMODE_TOOL_NAME,CODEMODE_STORE_ENTRY_TYPE,CODEMODE_DOCS_PATH,toCodemodeDeclaration,getCodemodeCallableTools,createCodemodeToolDefinition};
@@ -1,3 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- function combineAbortSignals(signals){let activeSignals=signals.filter(signal=>signal!==void 0);return activeSignals.length===0?void 0:AbortSignal.any(activeSignals)}async function readErrorResponseText(response,signal){if(!response.body)return signal?.throwIfAborted(),"";let reader=response.body.getReader(),decoder=new TextDecoder,size=0,text="",onAbort=()=>{reader.cancel().catch(()=>{})};signal?.addEventListener("abort",onAbort,{once:!0});try{for(;;){signal?.throwIfAborted();let{done,value}=await reader.read();if(signal?.throwIfAborted(),done)return text+decoder.decode();if(size+=value.byteLength,size>65536)return"Provider error response exceeded 65536 byt\
3
- es";text+=decoder.decode(value,{stream:!0})}}finally{signal?.removeEventListener("abort",onAbort),reader.cancel().catch(()=>{}),reader.releaseLock()}}export{combineAbortSignals,readErrorResponseText};
@@ -1,121 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{getCurrentSystemMessage}from"./chunk-KI7CHPWC.js";import{uuidv7}from"./chunk-65FLSKDA.js";import{APP_TITLE,getAgentDir,getSessionsDir,normalizePath,pathsEqual,resolvePath}from"./chunk-VFLVWPLZ.js";function readOrientationFromTiff(bytes,tiffStart){if(tiffStart+8>bytes.length)return 1;let le=(bytes[tiffStart]<<8|bytes[tiffStart+1])===18761,read16=pos=>le?bytes[pos]|bytes[pos+1]<<8:bytes[pos]<<8|bytes[pos+1],ifdOffset=(pos=>le?bytes[pos]|bytes[pos+1]<<8|bytes[pos+2]<<16|bytes[pos+3]<<24:(bytes[pos]<<24|bytes[pos+1]<<16|bytes[pos+2]<<8|bytes[pos+3])>>>0)(tiffStart+4),ifdStart=tiffStart+ifdOffset;if(ifdStart+2>bytes.length)return 1;let entryCount=read16(ifdStart);for(let i=0;i<entryCount;i++){
3
- let entryPos=ifdStart+2+i*12;if(entryPos+12>bytes.length)return 1;if(read16(entryPos)===274){let value=read16(entryPos+8);return value>=1&&value<=8?value:1}}return 1}function findJpegTiffOffset(bytes){let offset=2;for(;offset<bytes.length-1;){if(bytes[offset]!==255)return-1;let marker=bytes[offset+1];if(marker===255){offset++;continue}if(marker===225){if(offset+4>=bytes.length)return-1;let segmentStart=offset+4;if(segmentStart+6>bytes.length)return-1;if(hasExifHeader(bytes,segmentStart))return segmentStart+
4
- 6}if(offset+4>bytes.length)return-1;let length=bytes[offset+2]<<8|bytes[offset+3];offset+=2+length}return-1}function findWebpTiffOffset(bytes){let offset=12;for(;offset+8<=bytes.length;){let chunkId=String.fromCharCode(bytes[offset],bytes[offset+1],bytes[offset+2],bytes[offset+3]),chunkSize=bytes[offset+4]|bytes[offset+5]<<8|bytes[offset+6]<<16|bytes[offset+7]<<24,dataStart=offset+8;if(chunkId==="EXIF")return dataStart+chunkSize>bytes.length?-1:chunkSize>=6&&hasExifHeader(bytes,dataStart)?dataStart+
5
- 6:dataStart;offset=dataStart+chunkSize+chunkSize%2}return-1}function hasExifHeader(bytes,offset){return bytes[offset]===69&&bytes[offset+1]===120&&bytes[offset+2]===105&&bytes[offset+3]===102&&bytes[offset+4]===0&&bytes[offset+5]===0}function getExifOrientation(bytes){let tiffOffset=-1;return bytes.length>=2&&bytes[0]===255&&bytes[1]===216?tiffOffset=findJpegTiffOffset(bytes):bytes.length>=12&&bytes[0]===82&&bytes[1]===73&&bytes[2]===70&&bytes[3]===70&&bytes[8]===87&&bytes[9]===69&&bytes[10]===66&&
6
- bytes[11]===80&&(tiffOffset=findWebpTiffOffset(bytes)),tiffOffset===-1?1:readOrientationFromTiff(bytes,tiffOffset)}function rotate90(photon,image,dstIndex){let w=image.get_width(),h=image.get_height(),src=image.get_raw_pixels(),dst=new Uint8Array(src.length);for(let y=0;y<h;y++)for(let x=0;x<w;x++){let srcIdx=(y*w+x)*4,dstIdx=dstIndex(x,y,w,h)*4;dst[dstIdx]=src[srcIdx],dst[dstIdx+1]=src[srcIdx+1],dst[dstIdx+2]=src[srcIdx+2],dst[dstIdx+3]=src[srcIdx+3]}return new photon.PhotonImage(dst,h,w)}function applyExifOrientation(photon,image,originalBytes){
7
- let orientation=getExifOrientation(originalBytes);if(orientation===1)return image;switch(orientation){case 2:return photon.fliph(image),image;case 3:return photon.fliph(image),photon.flipv(image),image;case 4:return photon.flipv(image),image;case 5:{let rotated=rotate90(photon,image,(x,y,_w,h)=>x*h+(h-1-y));return photon.fliph(rotated),rotated}case 6:return rotate90(photon,image,(x,y,_w,h)=>x*h+(h-1-y));case 7:{let rotated=rotate90(photon,image,(x,y,w,h)=>(w-1-x)*h+y);return photon.fliph(rotated),
8
- rotated}case 8:return rotate90(photon,image,(x,y,w,h)=>(w-1-x)*h+y);default:return image}}import{createRequire}from"module";import*as path from"path";import{fileURLToPath}from"url";var require2=createRequire(import.meta.url),fs=require2("fs"),WASM_FILENAME="photon_rs_bg.wasm",photonModule=null,loadPromise=null;function pathOrNull(file){return typeof file=="string"?file:file instanceof URL?fileURLToPath(file):null}function getFallbackWasmPaths(){let execDir=path.dirname(process.execPath);return[path.join(execDir,WASM_FILENAME),path.join(execDir,"photon",WASM_FILENAME),path.join(process.
9
- cwd(),WASM_FILENAME)]}function patchPhotonWasmRead(){let originalReadFileSync=fs.readFileSync.bind(fs),fallbackPaths=getFallbackWasmPaths(),mutableFs=fs,patchedReadFileSync=((...args)=>{let[file,options]=args;if(pathOrNull(file)?.endsWith(WASM_FILENAME))try{return originalReadFileSync(...args)}catch(error){let err=error;if(err?.code&&err.code!=="ENOENT")throw error;for(let fallbackPath of fallbackPaths)if(fs.existsSync(fallbackPath))return options===void 0?originalReadFileSync(fallbackPath):originalReadFileSync(
10
- fallbackPath,options);throw error}return originalReadFileSync(...args)});try{mutableFs.readFileSync=patchedReadFileSync}catch{Object.defineProperty(fs,"readFileSync",{value:patchedReadFileSync,writable:!0,configurable:!0})}return()=>{try{mutableFs.readFileSync=originalReadFileSync}catch{Object.defineProperty(fs,"readFileSync",{value:originalReadFileSync,writable:!0,configurable:!0})}}}async function loadPhoton(){return photonModule||loadPromise||(loadPromise=(async()=>{let restoreReadFileSync=patchPhotonWasmRead();
11
- try{return photonModule=await import("@silvia-odwyer/photon-node"),photonModule}catch{return photonModule=null,photonModule}finally{restoreReadFileSync()}})(),loadPromise)}var IMAGE_RESIZE_WORKER_RESPONSE_TYPE="pi:image-resize-response",DEFAULT_MAX_BYTES=4.5*1024*1024,DEFAULT_OPTIONS={maxWidth:2e3,maxHeight:2e3,maxBytes:DEFAULT_MAX_BYTES,jpegQuality:80};function encodeCandidate(buffer,mimeType){let data=Buffer.from(buffer).toString("base64");return{data,encodedSize:Buffer.byteLength(data,"utf-8"),mimeType}}async function resizeImageInProcess(inputBytes,mimeType,options){let opts={...DEFAULT_OPTIONS,...options},inputBase64Size=Math.ceil(inputBytes.byteLength/3)*4,photon=await loadPhoton();
12
- if(!photon)return null;let image;try{let tryEncodings=function(width,height,jpegQualities){let resized=photon.resize(image,width,height,photon.SamplingFilter.Lanczos3);try{let candidates=[encodeCandidate(resized.get_bytes(),"image/png")];for(let quality of jpegQualities)candidates.push(encodeCandidate(resized.get_bytes_jpeg(quality),"image/jpeg"));return candidates}finally{resized.free()}},rawImage=photon.PhotonImage.new_from_byteslice(inputBytes);image=applyExifOrientation(photon,rawImage,inputBytes),
13
- image!==rawImage&&rawImage.free();let originalWidth=image.get_width(),originalHeight=image.get_height(),format=mimeType.split("/")[1]??"png";if(originalWidth<=opts.maxWidth&&originalHeight<=opts.maxHeight&&inputBase64Size<opts.maxBytes)return{data:Buffer.from(inputBytes).toString("base64"),mimeType:mimeType||`image/${format}`,originalWidth,originalHeight,width:originalWidth,height:originalHeight,wasResized:!1};let targetWidth=originalWidth,targetHeight=originalHeight;targetWidth>opts.maxWidth&&(targetHeight=
14
- Math.max(1,Math.round(targetHeight*opts.maxWidth/targetWidth)),targetWidth=opts.maxWidth),targetHeight>opts.maxHeight&&(targetWidth=Math.max(1,Math.round(targetWidth*opts.maxHeight/targetHeight)),targetHeight=opts.maxHeight);let qualitySteps=Array.from(new Set([opts.jpegQuality,85,70,55,40])),currentWidth=targetWidth,currentHeight=targetHeight;for(;;){let[png,jpeg,...lowerQualityJpegs]=tryEncodings(currentWidth,currentHeight,qualitySteps),preferred=jpeg&&jpeg.encodedSize<png.encodedSize?[jpeg,png]:
15
- [png,jpeg];for(let candidate of[...preferred,...lowerQualityJpegs])if(candidate&&candidate.encodedSize<opts.maxBytes)return{data:candidate.data,mimeType:candidate.mimeType,originalWidth,originalHeight,width:currentWidth,height:currentHeight,wasResized:!0};if(currentWidth===1&&currentHeight===1)break;let nextWidth=currentWidth===1?1:Math.max(1,Math.floor(currentWidth*.75)),nextHeight=currentHeight===1?1:Math.max(1,Math.floor(currentHeight*.75));if(nextWidth===currentWidth&&nextHeight===currentHeight)
16
- break;currentWidth=nextWidth,currentHeight=nextHeight}return null}catch{return null}finally{image&&image.free()}}function toTransferableBytes(input){return new Uint8Array(input)}function isResizeImageWorkerResponse(value){return value!==null&&typeof value=="object"&&"type"in value&&value.type===IMAGE_RESIZE_WORKER_RESPONSE_TYPE}function createResizeWorker(workerSpecifier){return new(process.getBuiltinModule("node:worker_threads")).Worker(workerSpecifier)}async function resizeImageInWorker(workerSpecifier,inputBytes,mimeType,options){let worker=createResizeWorker(workerSpecifier);try{let inputBytesForWorker=toTransferableBytes(
17
- inputBytes);return await new Promise((resolve2,reject)=>{let settled=!1,settle=result=>{settled||(settled=!0,resolve2(result))},fail=error=>{settled||(settled=!0,reject(error))};worker.on("message",message=>{isResizeImageWorkerResponse(message)&&("error"in message?fail(new Error(message.error)):settle(message.result))}),worker.once("error",fail),worker.once("exit",code=>{settled||fail(new Error(`Image resize worker exited with code ${code}`))}),worker.postMessage({inputBytes:inputBytesForWorker,
18
- mimeType,options},[inputBytesForWorker.buffer])})}finally{await worker.terminate().catch(()=>{})}}async function resizeImage(inputBytes,mimeType,options){let isTypeScriptRuntime=import.meta.url.endsWith(".ts"),workerUrl=new URL(isTypeScriptRuntime?"./image-resize-worker.ts":"./image-resize-worker.js",import.meta.url);if(typeof process.versions.bun=="string")try{return await resizeImageInWorker("./src/utils/image-resize-worker.ts",inputBytes,mimeType,options)}catch{}try{return await resizeImageInWorker(
19
- workerUrl,inputBytes,mimeType,options)}catch{return resizeImageInProcess(inputBytes,mimeType,options)}}function formatDimensionNote(result){if(!result.wasResized)return;let scale=result.originalWidth/result.width;return`[Image: original ${result.originalWidth}x${result.originalHeight}, displayed at ${result.width}x${result.height}. Multiply coordinates by ${scale.toFixed(2)} to map to original image.]`}var COMPACTION_SUMMARY_PREFIX=`The conversation history before this point was compacted into the following summary:
20
-
21
- <summary>
22
- `,COMPACTION_SUMMARY_SUFFIX=`
23
- </summary>`,BRANCH_SUMMARY_PREFIX=`The following is a summary of a branch that this conversation came back from:
24
-
25
- <summary>
26
- `,BRANCH_SUMMARY_SUFFIX="</summary>";function bashExecutionToText(msg){let text=`Ran \`${msg.command}\`
27
- `;return msg.output?text+=`\`\`\`
28
- ${msg.output}
29
- \`\`\``:text+="(no output)",msg.cancelled?text+=`
30
-
31
- (command cancelled)`:msg.exitCode!==null&&msg.exitCode!==void 0&&msg.exitCode!==0&&(text+=`
32
-
33
- Command exited with code ${msg.exitCode}`),msg.truncated&&msg.fullOutputPath&&(text+=`
34
-
35
- [Output truncated. Full output: ${msg.fullOutputPath}]`),text}function createBranchSummaryMessage(summary,fromId,timestamp){return{role:"branchSummary",summary,fromId,timestamp:new Date(timestamp).getTime()}}function createCompactionSummaryMessage(summary,tokensBefore,timestamp){return{role:"compactionSummary",summary,tokensBefore,timestamp:new Date(timestamp).getTime()}}function createCustomMessage(customType,content,display,details,timestamp){return{role:"custom",customType,content,display,details,
36
- timestamp:new Date(timestamp).getTime()}}function convertToLlm(messages){return messages.map(m=>{switch(m.role){case"bashExecution":return m.excludeFromContext?void 0:{role:"user",content:[{type:"text",text:bashExecutionToText(m)}],timestamp:m.timestamp};case"custom":return{role:"user",content:typeof m.content=="string"?[{type:"text",text:m.content}]:m.content,timestamp:m.timestamp};case"branchSummary":return{role:"user",content:[{type:"text",text:BRANCH_SUMMARY_PREFIX+m.summary+BRANCH_SUMMARY_SUFFIX}],
37
- timestamp:m.timestamp};case"compactionSummary":return{role:"user",content:[{type:"text",text:COMPACTION_SUMMARY_PREFIX+m.summary+COMPACTION_SUMMARY_SUFFIX}],timestamp:m.timestamp};case"system":case"user":case"assistant":case"toolResult":return m;default:let _exhaustiveCheck=m;return}}).filter(m=>m!==void 0)}import{randomUUID}from"crypto";import{appendFileSync,closeSync,existsSync,fchmodSync,fstatSync,fsyncSync,mkdirSync,openSync,readdirSync,readSync,renameSync,statSync,writeFileSync,writeSync}from"fs";import{open,readdir,stat}from"fs/promises";import{basename,join as join2,resolve}from"path";import{StringDecoder}from"string_decoder";var CURRENT_SESSION_VERSION=3;function includeSummaryUsageEntries(branch,getEntry){let included=new Set(branch.map(entry=>entry.id));return branch.flatMap(entry=>{let owners=[];if(entry.type==="compaction"||entry.type==="branch_summary")for(let id of entry.usageEntryIds??[]){if(included.has(id))continue;let owner=getEntry(id);owner?.type==="usage"&&(included.add(id),owners.push(owner))}return[...owners,entry]})}function createSessionId(){return uuidv7()}function assertValidSessionId(id){if(!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.
38
- test(id))throw new Error("Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character")}function generateId(byId){for(let i=0;i<100;i++){let id=randomUUID().slice(0,8);if(!byId.has(id))return id}return randomUUID()}function migrateV1ToV2(entries){let ids=new Set,prevId=null;for(let entry of entries){if(entry.type==="session"){entry.version=2;continue}if(entry.id=generateId(ids),entry.parentId=prevId,prevId=entry.id,entry.
39
- type==="compaction"){let comp=entry;if(typeof comp.firstKeptEntryIndex=="number"){let targetEntry=entries[comp.firstKeptEntryIndex];targetEntry&&targetEntry.type!=="session"&&(comp.firstKeptEntryId=targetEntry.id),delete comp.firstKeptEntryIndex}}}}function migrateV2ToV3(entries){for(let entry of entries){if(entry.type==="session"){entry.version=3;continue}if(entry.type==="message"){let msgEntry=entry;msgEntry.message&&msgEntry.message.role==="hookMessage"&&(msgEntry.message.role="custom")}}}function migrateToCurrentVersion(entries){
40
- let version=entries.find(e=>e.type==="session")?.version??1;return version>=CURRENT_SESSION_VERSION?!1:(version<2&&migrateV1ToV2(entries),version<3&&migrateV2ToV3(entries),!0)}function migrateSessionEntries(entries){migrateToCurrentVersion(entries)}function parseSessionEntries(content){let entries=[],lines=content.trim().split(`
41
- `);for(let line of lines)if(line.trim())try{let entry=JSON.parse(line);entries.push(entry)}catch{}return entries}function getLatestCompactionEntry(entries){for(let i=entries.length-1;i>=0;i--)if(entries[i].type==="compaction")return entries[i];return null}function buildEntryIndex(entries,byId){if(byId)return byId;let index=new Map;for(let entry of entries)index.set(entry.id,entry);return index}function buildSessionPath(entries,leafId,byId){let index=buildEntryIndex(entries,byId),leaf;if(leafId===
42
- null)return[];if(leafId&&(leaf=index.get(leafId)),leaf??=entries[entries.length-1],!leaf)return[];let path2=[],current=leaf;for(;current;)path2.push(current),current=current.parentId?index.get(current.parentId):void 0;return path2.reverse(),path2}function getSessionContextSettings(path2){let settings={thinkingLevel:"off",model:null};for(let entry of path2)applySessionContextSetting(settings,entry);return settings}function applySessionContextSetting(settings,entry){entry.type==="thinking_level_ch\
43
- ange"?settings.thinkingLevel=entry.thinkingLevel:entry.type==="model_change"?settings.model={provider:entry.provider,modelId:entry.modelId}:entry.type==="message"&&entry.message.role==="assistant"&&(settings.model={provider:entry.message.provider,modelId:entry.message.model})}function sessionEntryToContextMessages(entry){if(entry.type==="message"){let message=entry.message;return message.role==="system"&&message.content==null?[{...message,content:""}]:(message.role==="user"||message.role==="assi\
44
- stant"||message.role==="toolResult")&&message.content==null?[{...message,content:[]}]:[message]}if(entry.type==="custom_message")return[createCustomMessage(entry.customType,entry.content??[],entry.display,entry.details,entry.timestamp)];if(entry.type==="branch_summary"&&entry.summary)return[createBranchSummaryMessage(entry.summary,entry.fromId,entry.timestamp)];if(entry.type==="compaction"){let summary=createCompactionSummaryMessage(entry.summary,entry.tokensBefore,entry.timestamp);return entry.
45
- systemMessage?[entry.systemMessage,summary]:[summary]}return[]}function buildContextEntries(entries,leafId,byId){let denied=getControlDeniedEntryIds(entries),path2=buildSessionPath(entries,leafId,byId).map(entry=>omitControlDeniedContent(entry,denied)),compaction=null;for(let entry of path2)entry.type==="compaction"&&(compaction=entry);if(!compaction)return path2;let compactionIdx=path2.findIndex(entry=>entry.id===compaction.id);if(compactionIdx<0)return path2;let contextEntries=[compaction],foundFirstKept=!1;
46
- for(let i=0;i<compactionIdx;i++){let entry=path2[i];entry.id===compaction.firstKeptEntryId&&(foundFirstKept=!0),foundFirstKept&&!(entry.type==="message"&&entry.message.role==="system")&&contextEntries.push(entry)}return contextEntries.push(...path2.slice(compactionIdx+1)),contextEntries}function projectContextEntry(entry,edit){if(entry.type==="message"&&entry.controlDenied)return[];let messages=sessionEntryToContextMessages(entry);if(!edit)return messages;let replacement=edit.replacement;return replacement===
47
- null?[]:messages.map(message=>{if(message.role!=="user"&&message.role!=="assistant"&&message.role!=="toolResult"&&message.role!=="custom")return message;let content=(message.role==="assistant"||message.role==="toolResult")&&typeof replacement.content=="string"?[{type:"text",text:replacement.content}]:replacement.content;return{...message,content}})}function getControlDeniedEntryIds(entries){let denied=new Set;for(let entry of entries)entry.type==="context_edit"&&entry.reason==="control-denied"&&
48
- entry.replacement===null&&denied.add(entry.targetId),entry.type==="message"&&entry.controlDenied&&denied.add(entry.id);return denied}function omitControlDeniedContent(entry,denied){return entry.type==="context_edit"&&denied.has(entry.targetId)&&entry.replacement!==null?{...entry,replacement:null}:entry.type!=="message"||!denied.has(entry.id)?entry:{...entry,controlDenied:!0,message:{...entry.message,content:[]}}}function projectContextEntries(contextEntries){let edits=new Map;for(let entry of contextEntries)
49
- entry.type==="context_edit"&&edits.set(entry.targetId,entry);return contextEntries.map((sourceEntry,index)=>({sourceEntry,messages:sourceEntry.type==="compaction"&&index>0?[]:projectContextEntry(sourceEntry,edits.get(sourceEntry.id))}))}function buildSessionProjection(entries,leafId,byId){let path2=buildSessionPath(entries,leafId,byId),{thinkingLevel,model}=getSessionContextSettings(path2),projectedEntries=projectContextEntries(buildContextEntries(entries,leafId,byId));return{entries:projectedEntries,
50
- messages:projectedEntries.flatMap(entry=>entry.messages),thinkingLevel,model}}function buildSessionContext(entries,leafId,byId){let{messages,thinkingLevel,model}=buildSessionProjection(entries,leafId,byId);return{messages,thinkingLevel,model}}function openSessionFile(path2,flags){let fd=openSync(path2,flags,384);try{if(process.platform!=="win32"&&flags!=="wx"){let mode=fstatSync(fd).mode;(mode&63)!==0&&fchmodSync(fd,mode&448)}return fd}catch(error){throw closeSync(fd),error}}function getDefaultSessionDirPath(cwd,agentDir=getAgentDir()){
51
- let resolvedCwd=resolvePath(cwd),resolvedAgentDir=resolvePath(agentDir),safePath=`--${resolvedCwd.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`;return join2(resolvedAgentDir,"sessions",safePath)}function getDefaultSessionDir(cwd,agentDir=getAgentDir()){let sessionDir=getDefaultSessionDirPath(cwd,agentDir);return existsSync(sessionDir)||mkdirSync(sessionDir,{recursive:!0,mode:448}),sessionDir}var SESSION_READ_BUFFER_SIZE=1024*1024,SESSION_HEADER_READ_BUFFER_SIZE=4096,MAX_SESSION_HEADER_SCAN_BYTES=1024*
52
- 1024,SessionHeaderScanLimitError=class extends Error{constructor(filePath){super(`Session header exceeds ${MAX_SESSION_HEADER_SCAN_BYTES}-byte scan limit: ${filePath}`),this.name="SessionHeaderScanLimitError"}};function parseSessionEntryLine(line){if(!line.trim())return null;try{return JSON.parse(line)}catch{return null}}function loadEntriesFromFile(filePath){let resolvedFilePath=normalizePath(filePath);if(!existsSync(resolvedFilePath))return[];let entries=[],pending="",fd=openSync(resolvedFilePath,
53
- "r");try{let decoder=new StringDecoder("utf8"),buffer=Buffer.allocUnsafe(SESSION_READ_BUFFER_SIZE),lineChunks=[];for(;;){let bytesRead=readSync(fd,buffer,0,buffer.length,null);if(bytesRead===0)break;let chunk=decoder.write(buffer.subarray(0,bytesRead)),lineStart=0,newlineIndex=chunk.indexOf(`
54
- `,lineStart);for(;newlineIndex!==-1;){lineChunks.push(chunk.slice(lineStart,newlineIndex));let entry=parseSessionEntryLine(lineChunks.join(""));entry&&entries.push(entry),lineChunks.length=0,lineStart=newlineIndex+1,newlineIndex=chunk.indexOf(`
55
- `,lineStart)}lineStart<chunk.length&&lineChunks.push(chunk.slice(lineStart))}lineChunks.push(decoder.end()),pending=lineChunks.join("");let finalEntry=parseSessionEntryLine(pending);finalEntry&&entries.push(finalEntry)}finally{closeSync(fd)}if(entries.length===0)return entries;let header=entries[0];if(header.type!=="session"||typeof header.id!="string")return[];if(pending){let fd2=openSessionFile(resolvedFilePath,"a");try{writeFileSync(fd2,`
56
- `)}finally{closeSync(fd2)}}return entries}function parseSessionHeaderCandidate(line){if(!line.trim())return;let entry=parseSessionEntryLine(line);if(entry)return entry.type!=="session"||typeof entry.id!="string"?null:entry}function readSessionHeader(filePath){let fd=openSync(filePath,"r");try{let decoder=new StringDecoder("utf8"),buffer=Buffer.allocUnsafe(SESSION_HEADER_READ_BUFFER_SIZE),lineChunks=[],scannedBytes=0;for(;scannedBytes<MAX_SESSION_HEADER_SCAN_BYTES;){let readLength=Math.min(buffer.
57
- length,MAX_SESSION_HEADER_SCAN_BYTES-scannedBytes),bytesRead=readSync(fd,buffer,0,readLength,null);if(bytesRead===0)return lineChunks.push(decoder.end()),parseSessionHeaderCandidate(lineChunks.join(""))??null;scannedBytes+=bytesRead;let chunk=decoder.write(buffer.subarray(0,bytesRead)),lineStart=0,newlineIndex=chunk.indexOf(`
58
- `,lineStart);for(;newlineIndex!==-1;){lineChunks.push(chunk.slice(lineStart,newlineIndex));let header=parseSessionHeaderCandidate(lineChunks.join(""));if(header!==void 0)return header;lineChunks.length=0,lineStart=newlineIndex+1,newlineIndex=chunk.indexOf(`
59
- `,lineStart)}lineChunks.push(chunk.slice(lineStart))}let probe=Buffer.allocUnsafe(1);if(readSync(fd,probe,0,probe.length,null)===0)return lineChunks.push(decoder.end()),parseSessionHeaderCandidate(lineChunks.join(""))??null;throw new SessionHeaderScanLimitError(filePath)}finally{closeSync(fd)}}function readSessionHeaderForDiscovery(filePath){try{return readSessionHeader(filePath)}catch{return null}}function getSessionHeaderCwd(header){let cwd=header.cwd;return typeof cwd=="string"?cwd:void 0}function sessionCwdMatches(cwd,resolvedCwd){
60
- return cwd!==void 0&&cwd!==""&&pathsEqual(resolvePath(cwd),resolvedCwd)}function findMostRecentSession(sessionDir,cwd){let resolvedSessionDir=normalizePath(sessionDir),resolvedCwd=cwd?resolvePath(cwd):void 0;try{let files=readdirSync(resolvedSessionDir).filter(file=>file.endsWith(".jsonl")).map(file=>join2(resolvedSessionDir,file)).map(path2=>({path:path2,mtime:statSync(path2).mtimeMs})).sort((a,b)=>b.mtime-a.mtime);for(let{path:path2}of files){let header=readSessionHeaderForDiscovery(path2);if(header&&
61
- (!resolvedCwd||sessionCwdMatches(getSessionHeaderCwd(header),resolvedCwd)))return path2}return null}catch{return null}}function isMessageWithContent(message){return typeof message.role=="string"&&"content"in message}function extractTextContent(message){let content=message.content;return typeof content=="string"?content:content.filter(block=>block.type==="text").map(block=>block.text).join(" ")}function getMessageActivityTime(entry){let message=entry.message;if(!isMessageWithContent(message)||message.
62
- role!=="user"&&message.role!=="assistant")return;let msgTimestamp=message.timestamp;if(typeof msgTimestamp=="number")return msgTimestamp;let t=new Date(entry.timestamp).getTime();return Number.isNaN(t)?void 0:t}var LINE_HEAD_BYTES=256,MESSAGE_LINE_HEAD=/^\{"type":"message","id":"[^"\\]*","parentId":(?:null|"[^"\\]*"),"timestamp":"[^"\\]*","message":\{"role":"([^"\\]*)"/;function classifySessionLine(buffer,start,end){let head=buffer.toString("latin1",start,Math.min(end,start+LINE_HEAD_BYTES));if(!head.
63
- startsWith('{"type":"'))return"parse";let typeEnd=head.indexOf('"',9);if(typeEnd===-1)return"parse";let type=head.slice(9,typeEnd);if(type==="session_info"||type==="context_edit"||type.includes("\\"))return"parse";if(type!=="message")return"skip";let role=MESSAGE_LINE_HEAD.exec(head)?.[1];return role===void 0||role==="user"||role==="assistant"?"parse":end-start>=2&&buffer[end-1]===125&&buffer[end-2]===125?"count":"parse"}async function forEachLineOfFile(filePath,signal,onLine){signal?.throwIfAborted();
64
- let file=await open(filePath,"r");try{let chunk=Buffer.allocUnsafe(SESSION_READ_BUFFER_SIZE),carry=[],skipLineFeed=!1,emit=(buffer,start,end)=>{if(carry.length===0)return onLine(buffer,start,end);let line=Buffer.concat([...carry,buffer.subarray(start,end)]);return carry=[],onLine(line,0,line.length)};for(;;){signal?.throwIfAborted();let{bytesRead}=await file.read(chunk,0,chunk.length,null);if(bytesRead===0)break;let buffer=chunk.subarray(0,bytesRead),pos=0;skipLineFeed&&(skipLineFeed=!1,buffer[0]===
65
- 10&&(pos=1));let nextLineFeed=buffer.indexOf(10,pos),nextCarriageReturn=buffer.indexOf(13,pos);for(;;){nextLineFeed!==-1&&nextLineFeed<pos&&(nextLineFeed=buffer.indexOf(10,pos)),nextCarriageReturn!==-1&&nextCarriageReturn<pos&&(nextCarriageReturn=buffer.indexOf(13,pos));let lineEnd=nextCarriageReturn===-1?nextLineFeed:nextLineFeed===-1?nextCarriageReturn:Math.min(nextLineFeed,nextCarriageReturn);if(lineEnd===-1)break;if(!emit(buffer,pos,lineEnd))return;pos=lineEnd+1,lineEnd===nextCarriageReturn&&
66
- (pos===bytesRead?skipLineFeed=!0:buffer[pos]===10&&pos++)}pos<bytesRead&&carry.push(Buffer.from(buffer.subarray(pos)))}if(carry.length>0){let line=Buffer.concat(carry);carry=[],onLine(line,0,line.length)}}finally{await file.close()}}async function buildSessionInfo(filePath,signal,fileStats){try{let stats=fileStats??await stat(filePath),header=null,messageCount=0,allMessages=[],denialEntries=[],name,lastActivityTime;await forEachLineOfFile(filePath,signal,(buffer,start,end)=>{if(header){let kind=classifySessionLine(
67
- buffer,start,end);if(kind==="skip")return!0;if(kind==="count")return messageCount++,!0}let entry=parseSessionEntryLine(buffer.toString("utf8",start,end));if(!entry)return!0;if(!header)return entry.type!=="session"?!1:(header=entry,!0);if((entry.type==="context_edit"&&entry.reason==="control-denied"&&entry.replacement===null||entry.type==="message"&&entry.controlDenied)&&denialEntries.push(entry),entry.type==="session_info"&&(name=entry.name?.trim()||void 0),entry.type!=="message")return!0;messageCount++;
68
- let activityTime=getMessageActivityTime(entry);typeof activityTime=="number"&&(lastActivityTime=Math.max(lastActivityTime??0,activityTime));let message=entry.message;if(!isMessageWithContent(message)||message.role!=="user"&&message.role!=="assistant")return!0;let textContent=extractTextContent(message);return textContent&&allMessages.push({id:entry.id,role:message.role,text:textContent}),!0});let sessionHeader=header;if(!sessionHeader)return null;let denied=getControlDeniedEntryIds(denialEntries),
69
- visibleMessages=allMessages.filter(message=>!denied.has(message.id)),firstMessage=visibleMessages.find(message=>message.role==="user")?.text,cwd=typeof sessionHeader.cwd=="string"?sessionHeader.cwd:"",parentSessionPath=sessionHeader.parentSession,headerTime=typeof sessionHeader.timestamp=="string"?new Date(sessionHeader.timestamp).getTime():NaN,modified=typeof lastActivityTime=="number"&&lastActivityTime>0?new Date(lastActivityTime):Number.isNaN(headerTime)?stats.mtime:new Date(headerTime);return{
70
- path:filePath,id:sessionHeader.id,cwd,name,parentSessionPath,created:new Date(sessionHeader.timestamp),modified,messageCount,firstMessage:firstMessage||"(no messages)",allMessagesText:visibleMessages.map(message=>message.text).join(" ")}}catch{return signal?.throwIfAborted(),null}}var MAX_CONCURRENT_SESSION_INFO_LOADS=10,MAX_CONCURRENT_SESSION_DISCOVERY_LOADS=64,CURRENT_SESSION_LIST_PUBLISH_INTERVAL=10,ALL_SESSION_LIST_PUBLISH_INTERVAL=100;async function mapWithConcurrency(items,limit,map,signal){
71
- let results=new Array(items.length),nextIndex=0,worker=async()=>{for(;nextIndex<items.length;){signal?.throwIfAborted();let index=nextIndex++;results[index]=await map(items[index],index)}};return await Promise.all(Array.from({length:Math.min(limit,items.length)},()=>worker())),results}function sortSessionInfos(sessions){return sessions.sort((a,b)=>b.modified.getTime()-a.modified.getTime())}async function buildSessionInfosWithConcurrency(files,onLoaded,signal){let results=await mapWithConcurrency(
72
- files,MAX_CONCURRENT_SESSION_INFO_LOADS,async(file,index)=>{let info=await buildSessionInfo(file.path,signal,file.stats);return onLoaded(info,index),info},signal);return signal?.throwIfAborted(),results}async function listSessionsFromDir(dir,onProgress,signal){if(signal?.throwIfAborted(),!existsSync(dir))return[];try{let files=(await readdir(dir)).filter(file=>file.endsWith(".jsonl")).sort((a,b)=>b.localeCompare(a)).map(file=>({path:join2(dir,file)})),total=files.length,partialSessions=[],loaded=0;
73
- return(await buildSessionInfosWithConcurrency(files,info=>{loaded++,info&&partialSessions.push(info);let publishPartial=loaded===1||loaded%CURRENT_SESSION_LIST_PUBLISH_INTERVAL===0||loaded===files.length;onProgress?.(loaded,total,publishPartial?sortSessionInfos([...partialSessions]):void 0)},signal)).filter(info=>info!==null)}catch{return signal?.throwIfAborted(),[]}}var APPEND_FILE_IDLE_MS=1e3,SessionAppendFile=class{path;fd;dev;ino;lastAppend=0;timer;closed=!1;constructor(path2){this.path=path2,
74
- this.fd=openSessionFile(path2,"a");try{let stats=fstatSync(this.fd);this.dev=stats.dev,this.ino=stats.ino}catch(error){throw closeSync(this.fd),error}}isFor(path2){if(this.closed||path2!==this.path)return!1;let stats=statSync(path2,{throwIfNoEntry:!1});return stats!==void 0&&stats.ino===this.ino&&stats.dev===this.dev}append(line){let bytes=Buffer.from(line);for(let offset=0;offset<bytes.length;)offset+=writeSync(this.fd,bytes,offset,bytes.length-offset);this.lastAppend=performance.now(),this.timer||
75
- this.scheduleClose(APPEND_FILE_IDLE_MS)}close(){if(!this.closed){this.closed=!0,this.timer&&clearTimeout(this.timer),this.timer=void 0;try{closeSync(this.fd)}catch{}}}scheduleClose(delay){this.timer=setTimeout(()=>{this.timer=void 0;let idle=performance.now()-this.lastAppend;idle>=APPEND_FILE_IDLE_MS?this.close():this.scheduleClose(APPEND_FILE_IDLE_MS-idle)},delay),this.timer.unref()}},SessionManager=class _SessionManager{sessionId="";sessionFile;sessionDir;cwd;persist;flushed=!1;fileEntries=[];byId=new Map;controlDeniedEntryIds=new Set;labelsById=new Map;labelTimestampsById=new Map;leafId=null;leafPath;projection;projectionRevision=0;latestSessionInfo;appendFile;constructor(cwd,sessionDir,sessionFile,persist,newSessionOptions,preloadedFileEntries){
76
- this.cwd=resolvePath(cwd),this.sessionDir=normalizePath(sessionDir),this.persist=persist,persist&&this.sessionDir&&!existsSync(this.sessionDir)&&mkdirSync(this.sessionDir,{recursive:!0,mode:448}),sessionFile?this._setSessionFile(sessionFile,preloadedFileEntries):preloadedFileEntries?.length?this._loadEntries(preloadedFileEntries,newSessionOptions):this.newSession(newSessionOptions)}setSessionFile(sessionFile){this._setSessionFile(sessionFile)}_setSessionFile(sessionFile,preloadedFileEntries){if(this.
77
- _closeAppendFile(),this.sessionFile=resolvePath(sessionFile),existsSync(this.sessionFile)){let entries=preloadedFileEntries??loadEntriesFromFile(this.sessionFile);if(entries.length===0){let explicitPath=this.sessionFile;if(statSync(explicitPath).size>0)throw new Error(`Session file is not a valid ${APP_TITLE} session: ${explicitPath}`);this.newSession(),this.sessionFile=explicitPath,this._rewriteFile(),this.flushed=!0;return}this._loadEntries(entries),this.flushed=!0}else{let explicitPath=this.sessionFile;
78
- this.newSession(),this.sessionFile=explicitPath}}newSession(options){options?.id!==void 0&&assertValidSessionId(options.id),this.sessionId=options?.id??createSessionId();let timestamp=new Date().toISOString(),header={type:"session",version:CURRENT_SESSION_VERSION,id:this.sessionId,timestamp,cwd:this.cwd,parentSession:options?.parentSession};if(this._closeAppendFile(),this.fileEntries=[header],this.leafPath=void 0,this.projection=void 0,this.latestSessionInfo=void 0,this.byId.clear(),this.controlDeniedEntryIds.
79
- clear(),this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null,this.flushed=!1,this.persist){let fileTimestamp=timestamp.replace(/[:.]/g,"-");this.sessionFile=join2(this.getSessionDir(),`${fileTimestamp}_${this.sessionId}.jsonl`)}return this.sessionFile}_loadEntries(entries,options){let header=entries.find(e=>e.type==="session");header?(this.fileEntries=entries,this.sessionId=header.id,migrateToCurrentVersion(this.fileEntries)&&this._rewriteFile()):(this.newSession(options),this.
80
- fileEntries=this.fileEntries.concat(entries)),this._buildIndex()}_buildIndex(){this.leafPath=void 0,this.projection=void 0,this.latestSessionInfo=void 0,this.byId.clear(),this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null,this.controlDeniedEntryIds=getControlDeniedEntryIds(this.fileEntries.filter(entry=>entry.type!=="session"));for(let entry of this.fileEntries)entry.type!=="session"&&(this.byId.set(entry.id,entry),this.leafId=entry.id,entry.type==="session_info"&&(this.latestSessionInfo=
81
- entry),entry.type==="label"&&(entry.label?(this.labelsById.set(entry.targetId,entry.label),this.labelTimestampsById.set(entry.targetId,entry.timestamp)):(this.labelsById.delete(entry.targetId),this.labelTimestampsById.delete(entry.targetId))))}_rewriteFile(){if(!this.persist||!this.sessionFile)return;let tmpPath=`${this.sessionFile}.${process.pid}.tmp`,fd=openSessionFile(tmpPath,"w");try{for(let entry of this.fileEntries)writeFileSync(fd,`${JSON.stringify(entry)}
82
- `);fsyncSync(fd)}finally{closeSync(fd)}renameSync(tmpPath,this.sessionFile)}isPersisted(){return this.persist}getCwd(){return this.cwd}getSessionDir(){return this.sessionDir}usesDefaultSessionDir(){return pathsEqual(this.sessionDir,getDefaultSessionDirPath(this.cwd))}getSessionId(){return this.sessionId}getSessionFile(){return this.sessionFile}_hasConversation(){return this.fileEntries.some(e=>e.type==="message"||e.type==="usage")}_persist(entry){if(!(!this.persist||!this.sessionFile))if(this.flushed)
83
- this._appendLine(this.sessionFile,`${JSON.stringify(entry)}
84
- `);else{if(!this._hasConversation())return;this._flushAll()}}_appendLine(path2,line){if(process.platform==="win32"){appendFileSync(path2,line,{mode:384});return}this.appendFile?.isFor(path2)||(this._closeAppendFile(),this.appendFile=new SessionAppendFile(path2));try{this.appendFile.append(line)}catch(error){throw this._closeAppendFile(),error}}_closeAppendFile(){this.appendFile?.close(),this.appendFile=void 0}_flushAll(){if(!this.persist||!this.sessionFile)return;let fd=openSessionFile(this.sessionFile,
85
- "wx");try{for(let e of this.fileEntries)writeFileSync(fd,`${JSON.stringify(e)}
86
- `)}finally{closeSync(fd)}this.flushed=!0}flush(){this._closeAppendFile(),!(!this.persist||!this.sessionFile||this.flushed)&&this.fileEntries.some(e=>e.type!=="session")&&this._flushAll()}_appendEntry(entry){let previousLeafId=this.leafId;this.fileEntries.push(entry),this.byId.set(entry.id,entry),entry.type==="context_edit"&&entry.reason==="control-denied"&&entry.replacement===null&&(this.controlDeniedEntryIds.add(entry.targetId),this.projection=void 0),entry.type==="message"&&entry.controlDenied&&
87
- this.controlDeniedEntryIds.add(entry.id),this.leafId=entry.id;try{this._persist(entry)}catch(error){throw this.fileEntries.pop(),this.byId.delete(entry.id),this.leafId=previousLeafId,error}entry.type==="session_info"&&(this.latestSessionInfo=entry)}appendMessage(message){let entry={type:"message",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),message};return this._appendEntry(entry),entry.id}appendThinkingLevelChange(thinkingLevel){let entry={type:"thinking_leve\
88
- l_change",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),thinkingLevel};return this._appendEntry(entry),entry.id}appendModelChange(provider,modelId){let entry={type:"model_change",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),provider,modelId};return this._appendEntry(entry),entry.id}appendUsage(kind,provider,model,usage,note){let entry={type:"usage",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),
89
- kind,provider,model,usage,...note?{note}:{}};return this._appendEntry(entry),entry}appendCompaction(summary,firstKeptEntryId,tokensBefore,details,fromHook,usage,usageEntryIds){let timestamp=new Date().toISOString(),systemMessage=getCurrentSystemMessage(this.buildSessionProjection().messages),id=generateId(this.byId),entry={type:"compaction",id,parentId:this.leafId,timestamp,summary,firstKeptEntryId:firstKeptEntryId??id,tokensBefore,details,usage,...usageEntryIds?.length?{usageEntryIds:[...usageEntryIds]}:
90
- {},fromHook,...systemMessage?{systemMessage:{...systemMessage,timestamp:new Date(timestamp).getTime()}}:{}};return this._appendEntry(entry),entry.id}appendCustomEntry(customType,data){let entry={type:"custom",customType,data,id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(entry),entry.id}appendSessionInfo(name){let sanitizedName=name.replace(/[\r\n]+/g," ").trim(),entry={type:"session_info",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().
91
- toISOString(),name:sanitizedName};return this._appendEntry(entry),entry.id}getSessionName(){return this.latestSessionInfo?.name?.trim()||void 0}appendCustomMessageEntry(customType,content,display,details){let entry={type:"custom_message",customType,content,display,details,id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(entry),entry.id}appendContextEdit(targetId,replacement,reason){if(reason!==void 0&&(reason!=="control-denied"||replacement!==
92
- null))throw new Error("Control denial must omit its target");if(replacement!==null&&(typeof replacement!="object"||!("content"in replacement)||typeof replacement.content!="string"&&!Array.isArray(replacement.content)))throw new Error("Context edit replacement must be null or contain string/array content");let target=this.byId.get(targetId);if(!target)throw new Error(`Entry ${targetId} not found`);if(!this.getBranch().some(entry2=>entry2.id===targetId))throw new Error(`Entry ${targetId} is not on\
93
- the active branch`);if(!(target.type==="custom_message"||target.type==="message"&&(target.message.role==="user"||target.message.role==="assistant"||target.message.role==="toolResult")))throw new Error(`Entry ${targetId} does not contribute editable model content`);if(reason==="control-denied"&&(target.type!=="message"||target.message.role!=="user"))throw new Error("Control denial requires a user message");let targetRole=target.type==="message"?target.message.role:"custom",normalizedReplacement=replacement!==
94
- null&&(targetRole==="assistant"||targetRole==="toolResult")&&typeof replacement.content=="string"?{content:[{type:"text",text:replacement.content}]}:replacement,entry={type:"context_edit",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),targetId,replacement:normalizedReplacement,...reason?{reason}:{}};return this._appendEntry(entry),entry.id}getLeafId(){return this.leafId}getLeafEntry(){return this.leafId?this.getEntry(this.leafId):void 0}getEntry(id){let entry=this.
95
- byId.get(id);return entry&&omitControlDeniedContent(entry,this.controlDeniedEntryIds)}getChildren(parentId){let children=[];for(let entry of this.byId.values())entry.parentId===parentId&&children.push(omitControlDeniedContent(entry,this.controlDeniedEntryIds));return children}getLabel(id){return this.labelsById.get(id)}appendLabelChange(targetId,label){if(!this.byId.has(targetId))throw new Error(`Entry ${targetId} not found`);let entry={type:"label",id:generateId(this.byId),parentId:this.leafId,
96
- timestamp:new Date().toISOString(),targetId,label};return this._appendEntry(entry),label?(this.labelsById.set(targetId,label),this.labelTimestampsById.set(targetId,entry.timestamp)):(this.labelsById.delete(targetId),this.labelTimestampsById.delete(targetId)),entry.id}getBranch(fromId){return(fromId===void 0||fromId===this.leafId?this._leafPath():this._walkBranch(fromId)).map(entry=>omitControlDeniedContent(entry,this.controlDeniedEntryIds))}getContextUsageEntries(){let entries=[],current=this.leafId?
97
- this.byId.get(this.leafId):void 0;for(;current&&(entries.push(omitControlDeniedContent(current,this.controlDeniedEntryIds)),current.type!=="compaction");)current=current.parentId?this.byId.get(current.parentId):void 0;return entries.reverse()}_walkBranch(startId){let path2=[],current=startId?this.byId.get(startId):void 0;for(;current;)path2.push(current),current=current.parentId?this.byId.get(current.parentId):void 0;return path2.reverse(),path2}_leafPath(){let leafId=this.leafId;if(leafId===null)
98
- return[];let cached=this.leafPath;if(cached?.leafId===leafId)return cached.path;let appended=cached&&this._appendedSince(cached.leafId,leafId),path2;if(cached&&appended){path2=cached.path;for(let entry of appended)path2.push(entry)}else path2=this._walkBranch(leafId);return this.leafPath={leafId,path:path2},path2}_appendedSince(fromId,leafId){let appended=[],current=this.byId.get(leafId);for(;current&&appended.length<64;){if(appended.push(current),current.parentId===fromId)return appended.reverse();
99
- current=current.parentId?this.byId.get(current.parentId):void 0}}_projection(){let leafId=this.leafId,cached=this.projection;if(cached&&cached.leafId===leafId)return cached;let appended=leafId!==null&&cached?.leafId!=null?this._appendedSince(cached.leafId,leafId):void 0,projection;if(cached&&appended?.every(entry=>entry.type!=="compaction"&&entry.type!=="context_edit")){projection=cached.projection;for(let entry of appended){applySessionContextSetting(projection,entry);let sourceEntry=omitControlDeniedContent(
100
- entry,this.controlDeniedEntryIds),messages=projectContextEntry(sourceEntry,void 0);projection.entries.push({sourceEntry,messages});for(let message of messages)projection.messages.push(message)}}else projection=buildSessionProjection(this.getEntries(),leafId,this.byId);return this.projection={leafId,projection,revision:++this.projectionRevision},this.projection}buildContextEntries(){return buildContextEntries(this.getEntries(),this.leafId,this.byId)}buildSessionProjection(){let{projection}=this._projection(),
101
- entries=projectContextEntries(projection.entries.map(({sourceEntry})=>this.getEntry(sourceEntry.id)));return{entries,messages:entries.flatMap(entry=>entry.messages),thinkingLevel:projection.thinkingLevel,model:projection.model&&{...projection.model}}}getProjectionRevision(){return this._projection().revision}peekSessionProjection(){return this._projection().projection}buildSessionContext(){let{messages,thinkingLevel,model}=this.buildSessionProjection();return{messages,thinkingLevel,model}}getHeader(){
102
- let h=this.fileEntries.find(e=>e.type==="session");return h||null}getEntryCount(){return this.byId.size}getEntries(){return this.fileEntries.filter(e=>e.type!=="session").map(entry=>omitControlDeniedContent(entry,this.controlDeniedEntryIds))}getTree(){let entries=this.getEntries(),nodeMap=new Map,roots=[];for(let entry of entries){let label=this.labelsById.get(entry.id),labelTimestamp=this.labelTimestampsById.get(entry.id);nodeMap.set(entry.id,{entry,children:[],label,labelTimestamp})}for(let entry of entries){
103
- let node=nodeMap.get(entry.id);if(entry.parentId===null||entry.parentId===entry.id)roots.push(node);else{let parent=nodeMap.get(entry.parentId);parent?parent.children.push(node):roots.push(node)}}let stack=[...roots];for(;stack.length>0;){let node=stack.pop();node.children.sort((a,b)=>new Date(a.entry.timestamp).getTime()-new Date(b.entry.timestamp).getTime()),stack.push(...node.children)}return roots}branch(branchFromId){if(!this.byId.has(branchFromId))throw new Error(`Entry ${branchFromId} not\
104
- found`);this.leafId=branchFromId}resetLeaf(){this.leafId=null}branchWithSummary(branchFromId,summary,details,fromHook,usage,usageEntryIds){if(branchFromId!==null&&!this.byId.has(branchFromId))throw new Error(`Entry ${branchFromId} not found`);let fromId=this.leafId??"root";this.leafId=branchFromId;let entry={type:"branch_summary",id:generateId(this.byId),parentId:branchFromId,timestamp:new Date().toISOString(),fromId,summary,details,usage,...usageEntryIds?.length?{usageEntryIds:[...usageEntryIds]}:
105
- {},fromHook};return this._appendEntry(entry),entry.id}createBranchedSession(leafId){let previousSessionFile=this.sessionFile,path2=includeSummaryUsageEntries(this.getBranch(leafId),id=>this.getEntry(id));if(path2.length===0)throw new Error(`Entry ${leafId} not found`);let pathWithoutLabels=[],replacementByLabelId=new Map,pendingLabelIds=[],pathParentId=null;for(let entry of path2){if(entry.type==="label"){pendingLabelIds.push(entry.id);continue}for(let labelId of pendingLabelIds)replacementByLabelId.
106
- set(labelId,entry.id);pendingLabelIds.length=0,pathWithoutLabels.push(entry.type==="compaction"?{...entry,parentId:pathParentId,firstKeptEntryId:entry.firstKeptEntryId===entry.id?entry.id:replacementByLabelId.get(entry.firstKeptEntryId)??entry.firstKeptEntryId}:{...entry,parentId:pathParentId}),pathParentId=entry.id}let newSessionId=createSessionId(),timestamp=new Date().toISOString(),fileTimestamp=timestamp.replace(/[:.]/g,"-"),newSessionFile=join2(this.getSessionDir(),`${fileTimestamp}_${newSessionId}\
107
- .jsonl`),header={type:"session",version:CURRENT_SESSION_VERSION,id:newSessionId,timestamp,cwd:this.cwd,parentSession:this.persist?previousSessionFile:void 0},pathEntryIds=new Set(pathWithoutLabels.map(e=>e.id)),labelsToWrite=[];for(let[targetId,label]of this.labelsById)pathEntryIds.has(targetId)&&labelsToWrite.push({targetId,label,timestamp:this.labelTimestampsById.get(targetId)});if(this.persist){let parentId2=pathWithoutLabels[pathWithoutLabels.length-1]?.id||null,labelEntries2=[];for(let{targetId,
108
- label,timestamp:labelTimestamp}of labelsToWrite){let labelEntry={type:"label",id:generateId(new Set(pathEntryIds)),parentId:parentId2,timestamp:labelTimestamp,targetId,label};pathEntryIds.add(labelEntry.id),labelEntries2.push(labelEntry),parentId2=labelEntry.id}return this.fileEntries=[header,...pathWithoutLabels,...labelEntries2],this.sessionId=newSessionId,this.sessionFile=newSessionFile,this._buildIndex(),this._hasConversation()?(this._rewriteFile(),this.flushed=!0):this.flushed=!1,newSessionFile}
109
- let labelEntries=[],parentId=pathWithoutLabels[pathWithoutLabels.length-1]?.id||null;for(let{targetId,label,timestamp:labelTimestamp}of labelsToWrite){let labelEntry={type:"label",id:generateId(new Set([...pathEntryIds,...labelEntries.map(e=>e.id)])),parentId,timestamp:labelTimestamp,targetId,label};labelEntries.push(labelEntry),parentId=labelEntry.id}this.fileEntries=[header,...pathWithoutLabels,...labelEntries],this.sessionId=newSessionId,this._buildIndex()}static create(cwd,sessionDir,options){
110
- let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd);return new _SessionManager(cwd,dir,void 0,!0,options)}static open(path2,sessionDir,cwdOverride){let resolvedPath=resolvePath(path2),header=null,preloadedFileEntries;if(cwdOverride===void 0&&existsSync(resolvedPath))try{header=readSessionHeader(resolvedPath)}catch(error){if(!(error instanceof SessionHeaderScanLimitError))throw error;preloadedFileEntries=loadEntriesFromFile(resolvedPath);let firstEntry=preloadedFileEntries[0];header=
111
- firstEntry?.type==="session"?firstEntry:null}let cwd=cwdOverride??(header?getSessionHeaderCwd(header):void 0)??process.cwd(),dir=sessionDir?normalizePath(sessionDir):resolve(resolvedPath,"..");return new _SessionManager(cwd,dir,resolvedPath,!0,void 0,preloadedFileEntries)}static continueRecent(cwd,sessionDir){let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd),mostRecent=findMostRecentSession(dir,cwd);return mostRecent?new _SessionManager(cwd,dir,mostRecent,!0):new _SessionManager(
112
- cwd,dir,void 0,!0)}static inMemory(cwd=process.cwd(),options,entries){return new _SessionManager(cwd,"",void 0,!1,options,entries)}static forkFrom(sourcePath,targetCwd,sessionDir,options){let resolvedSourcePath=resolvePath(sourcePath),resolvedTargetCwd=resolvePath(targetCwd),sourceEntries=loadEntriesFromFile(resolvedSourcePath);if(sourceEntries.length===0)throw new Error(`Cannot fork: source session file is empty or invalid: ${resolvedSourcePath}`);if(!sourceEntries.find(e=>e.type==="session"))throw new Error(
113
- `Cannot fork: source session has no header: ${resolvedSourcePath}`);migrateToCurrentVersion(sourceEntries);let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(resolvedTargetCwd);existsSync(dir)||mkdirSync(dir,{recursive:!0,mode:448}),options?.id!==void 0&&assertValidSessionId(options.id);let newSessionId=options?.id??createSessionId(),timestamp=new Date().toISOString(),fileTimestamp=timestamp.replace(/[:.]/g,"-"),newSessionFile=join2(dir,`${fileTimestamp}_${newSessionId}.jsonl`),newHeader={
114
- type:"session",version:CURRENT_SESSION_VERSION,id:newSessionId,timestamp,cwd:resolvedTargetCwd,parentSession:resolvedSourcePath},fd=openSessionFile(newSessionFile,"wx");try{writeFileSync(fd,`${JSON.stringify(newHeader)}
115
- `);for(let entry of sourceEntries)entry.type!=="session"&&writeFileSync(fd,`${JSON.stringify(entry)}
116
- `)}finally{closeSync(fd)}return new _SessionManager(resolvedTargetCwd,dir,newSessionFile,!0)}static findById(cwd,id,sessionDir){let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd),resolvedCwd=resolvePath(cwd);try{for(let file of readdirSync(dir)){if(!file.endsWith(".jsonl"))continue;let path2=join2(dir,file),header=readSessionHeaderForDiscovery(path2);if(header?.id===id&&sessionCwdMatches(getSessionHeaderCwd(header),resolvedCwd))return path2}}catch{}}static async list(cwd,sessionDir,onProgress,signal){
117
- let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd),resolvedCwd=resolvePath(cwd),includeSession=session=>sessionCwdMatches(session.cwd,resolvedCwd),sessions=(await listSessionsFromDir(dir,onProgress?(loaded,total,partialSessions)=>onProgress(loaded,total,partialSessions?.filter(includeSession)):void 0,signal)).filter(includeSession);return sortSessionInfos(sessions)}static async listAll(sessionDirOrOnProgress,onProgressOrSignal,signal){let customSessionDir=typeof sessionDirOrOnProgress==
118
- "string"?normalizePath(sessionDirOrOnProgress):void 0,progress=typeof sessionDirOrOnProgress=="function"?sessionDirOrOnProgress:typeof onProgressOrSignal=="function"?onProgressOrSignal:void 0,abortSignal=typeof sessionDirOrOnProgress=="string"||typeof onProgressOrSignal=="function"?signal:onProgressOrSignal??signal;if(abortSignal?.throwIfAborted(),customSessionDir)return sortSessionInfos(await listSessionsFromDir(customSessionDir,progress,abortSignal));let sessionsDir=getSessionsDir();try{if(!existsSync(
119
- sessionsDir))return[];let dirs=(await readdir(sessionsDir,{withFileTypes:!0})).filter(entry=>entry.isDirectory()||entry.isSymbolicLink()).map(entry=>join2(sessionsDir,entry.name)),allFiles=(await mapWithConcurrency(dirs,MAX_CONCURRENT_SESSION_DISCOVERY_LOADS,async dir=>{try{return(await readdir(dir)).filter(file=>file.endsWith(".jsonl")).map(file=>join2(dir,file))}catch{return[]}},abortSignal)).flat(),candidates=await mapWithConcurrency(allFiles,MAX_CONCURRENT_SESSION_DISCOVERY_LOADS,async path2=>{
120
- try{return{path:path2,stats:await stat(path2)}}catch{return{path:path2}}},abortSignal);candidates.sort((a,b)=>(b.stats?.mtimeMs??Number.NEGATIVE_INFINITY)-(a.stats?.mtimeMs??Number.NEGATIVE_INFINITY)||basename(b.path).localeCompare(basename(a.path)));let totalFiles=candidates.length,loaded=0,firstCandidateLoaded=!1,partialSessions=[],results=await buildSessionInfosWithConcurrency(candidates,(info,index)=>{loaded++,index===0&&(firstCandidateLoaded=!0),info&&partialSessions.push(info);let publishPartial=firstCandidateLoaded&&
121
- (index===0||loaded%ALL_SESSION_LIST_PUBLISH_INTERVAL===0||loaded===totalFiles);progress?.(loaded,totalFiles,publishPartial?sortSessionInfos([...partialSessions]):void 0)},abortSignal);return sortSessionInfos(results.filter(info=>info!==null))}catch{return abortSignal?.throwIfAborted(),[]}}};export{applyExifOrientation,loadPhoton,resizeImage,formatDimensionNote,createBranchSummaryMessage,createCompactionSummaryMessage,createCustomMessage,convertToLlm,CURRENT_SESSION_VERSION,includeSummaryUsageEntries,assertValidSessionId,migrateSessionEntries,parseSessionEntries,getLatestCompactionEntry,sessionEntryToContextMessages,buildContextEntries,projectContextEntry,getControlDeniedEntryIds,buildSessionProjection,buildSessionContext,getDefaultSessionDir,SessionManager};
@@ -1,4 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS}from"./chunk-YSWDFV2L.js";var SETTINGS_DEFAULTS={transport:"auto",noProgressTimeoutMs:12e4,sessionShareDestination:"auto",steeringMode:"one-at-a-time",followUpMode:"one-at-a-time",compaction:{enabled:!0,reserveTokens:16384,keepRecentTokens:2e4,thresholdPercent:90},branchSummary:{reserveTokens:16384,skipPrompt:!1},retry:{enabled:!0,maxRetries:3,baseDelayMs:2e3,maxAgentDelayMs:DEFAULT_MAX_AGENT_RETRY_DELAY_MS,provider:{maxRetryDelayMs:6e4}},hideThinkingBlock:!1,showCacheMissNotices:!1,bashOutputHeadTail:!1,bashOutputCleanup:!1,
3
- quietStartup:!1,defaultProjectTrust:"ask",collapseChangelog:!1,enableInstallTelemetry:!0,enableSkillCommands:!0,terminal:{showImages:!0,imageWidthCells:60,clearOnShrink:!1,showTerminalProgress:!1},images:{autoResize:!0,blockImages:!1},doubleEscapeAction:"tree",treeFilterMode:"default",editorPaddingX:0,outputPad:1,autocompleteMaxVisible:5,markdown:{codeBlockIndent:" ",mermaid:"streaming"},warnings:{anthropicExtraUsage:!0},codemode:{mode:"on",inlineBudget:3e3,flowImplementer:"only"},cacheWarming:"\
4
- streaming",tuiMode:"fullscreen",fullscreenExitOutput:"transcript",fullscreenScrollbar:"auto",fullscreenCopyOnSelect:!0,fullscreenWheelScrollLines:"auto"};export{SETTINGS_DEFAULTS};
@@ -1,12 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{mcpNamespace,validateMcpServerConfig}from"./chunk-JWOPWHVH.js";import{require_proper_lockfile}from"./chunk-F6ZAYLU2.js";import{CONFIG_DIR_NAME,stripBom}from"./chunk-VFLVWPLZ.js";import{__toESM}from"./chunk-JXWJOIH4.js";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{randomUUID}from"node:crypto";import{chmodSync,existsSync,lstatSync,mkdirSync,readFileSync,realpathSync,renameSync,rmSync,statSync,writeFileSync}from"node:fs";import{basename,dirname,join}from"node:path";var OVERRIDE_KEYS=["enabled","exposure","toolExposure"];function isOverride(value){return value.command===void 0&&value.url===void 0&&value.type===void 0}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readConfigFile(path,scope,state){let{servers,errors}=state;if(!existsSync(path))return;let parsed;try{parsed=JSON.parse(stripBom(readFileSync(path,"utf8")))}catch(error){errors.push(`${path}: ${error instanceof Error?error.message:String(error)}`);
3
- return}if(!isRecord(parsed)||parsed.mcpServers!==void 0&&!isRecord(parsed.mcpServers)){errors.push(`${path}: expected an object with an "mcpServers" object`);return}typeof parsed.autoEnableCodemode=="boolean"?state.autoEnableCodemode=parsed.autoEnableCodemode:parsed.autoEnableCodemode!==void 0&&errors.push(`${path}: autoEnableCodemode must be a boolean`);for(let[name,value]of Object.entries(parsed.mcpServers??{})){if(scope==="project"&&isRecord(value)&&isOverride(value)){let base=servers.get(name),
4
- extra=Object.keys(value).filter(key=>!OVERRIDE_KEYS.includes(key));if(!base)errors.push(`${path}: server "${name}" needs "command" or "url", or a global server to override`);else if(extra.length>0)errors.push(`${path}: server "${name}": an override can only set ${OVERRIDE_KEYS.join(", ")}`);else{let config2=validateMcpServerConfig(name,{...base.config,...value});typeof config2=="string"?errors.push(`${path}: ${config2}`):servers.set(name,{...base,config:config2,override:path})}continue}let config=validateMcpServerConfig(
5
- name,value);if(typeof config=="string"){errors.push(`${path}: ${config}`);continue}let clash=[...servers.keys()].find(other=>other!==name&&mcpNamespace(other)===mcpNamespace(name));if(clash){errors.push(`${path}: server "${name}" conflicts with "${clash}"`);continue}if(scope==="project"&&"url"in config&&config.auth){errors.push(`${path}: server "${name}": auth is only allowed in the global mcp.json`);continue}servers.set(name,{name,config,source:path,scope})}}function loadMcpConfig(options){let state={
6
- servers:new Map,errors:[]};readConfigFile(join(options.agentDir,"mcp.json"),"global",state);let projectConfig=options.projectTrusted?join(options.cwd,CONFIG_DIR_NAME,"mcp.json"):void 0;return projectConfig&&readConfigFile(projectConfig,"project",state),{servers:[...state.servers.values()],...state.autoEnableCodemode===void 0?{}:{autoEnableCodemode:state.autoEnableCodemode},errors:state.errors,...projectConfig?{projectConfig}:{}}}function updateMcpServerConfig(path,name,patch,options={}){editMcpServers(
7
- path,(servers,parsed)=>{let server=servers?.[name];if(server===void 0&&options.override&&(server={},parsed.mcpServers={...servers,[name]:server}),!isRecord(server))throw new Error(`${path} does not define MCP server "${name}"`);let keepDefaults=isOverride(server);return patch.enabled!==void 0&&(patch.enabled&&!keepDefaults?delete server.enabled:server.enabled=patch.enabled),patch.exposure!==void 0&&(patch.exposure==="codemode"&&!keepDefaults?delete server.exposure:server.exposure=patch.exposure),
8
- !0})}function addMcpServerConfig(path,name,config){return updateMcpConfigLocked(path,servers=>{let replaced=servers[name]!==void 0;return servers[name]=config,replaced})}function updateMcpConfigLocked(path,mutate){let result;return editMcpServers(path,(servers,parsed)=>{let target=servers??{},before=JSON.stringify(target);return result=mutate(target),JSON.stringify(target)===before?!1:(parsed.mcpServers=target,!0)}),result}function removeMcpServerConfig(path,name){if(!existsSync(path))return!1;let removed=!1;return editMcpServers(path,servers=>!servers||servers[name]===void 0?!1:(delete servers[name],removed=!0,!0)),removed}function parseMcpFile(path,text){let parsed=text===void 0?{}:JSON.parse(stripBom(text));if(!isRecord(parsed)||parsed.mcpServers!==void 0&&!isRecord(parsed.mcpServers))throw new Error(`${path}: expected an object with an "mcpServers" object`);return{parsed,servers:isRecord(parsed.mcpServers)?parsed.
9
- mcpServers:void 0}}function canonicalMcpPath(path){mkdirSync(dirname(path),{recursive:!0});let isSymlink=!1;try{isSymlink=lstatSync(path).isSymbolicLink()}catch(error){if(error.code!=="ENOENT")throw error;return join(realpathSync(dirname(path)),basename(path))}try{return realpathSync(path)}catch(error){throw isSymlink&&error.code==="ENOENT"?new Error(`Refusing to modify ${path}: it is a dangling symlink. Create its target or remove the link.`):error}}function acquireMcpLockSync(path){let dir=dirname(
10
- path),maxAttempts=50,delayMs=20;for(let attempt=1;;attempt++)try{return import_proper_lockfile.default.lockSync(dir,{realpath:!1,lockfilePath:`${path}.lock`})}catch(error){if((typeof error=="object"&&error!==null&&"code"in error?String(error.code):void 0)!=="ELOCKED"||attempt===maxAttempts)throw error;let start=Date.now();for(;Date.now()-start<delayMs;);}}function editMcpServers(path,edit){let canonical=canonicalMcpPath(path),release=acquireMcpLockSync(canonical);try{if(canonicalMcpPath(path)!==
11
- canonical)throw new Error(`Refusing to modify ${path}: it changed while waiting for the lock. Retry.`);let text=existsSync(canonical)?readFileSync(canonical,"utf8"):void 0,{parsed,servers}=parseMcpFile(path,text);if(!edit(servers,parsed))return;let indent=text&&/^([ \t]+)\S/m.exec(text)?.[1]||" ",targetPath=canonical,tempPath=join(dirname(targetPath),`${randomUUID()}.tmp`),mode=text!==void 0?statSync(targetPath).mode&511:384;try{writeFileSync(tempPath,`${JSON.stringify(parsed,null,indent)}
12
- `,{flag:"wx",mode}),chmodSync(tempPath,mode),renameSync(tempPath,targetPath)}catch(error){throw rmSync(tempPath,{force:!0}),error}}finally{release()}}export{loadMcpConfig,updateMcpServerConfig,addMcpServerConfig,updateMcpConfigLocked,removeMcpServerConfig};