@diffra-ai/cli 0.1.0 → 0.1.2

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 (457) hide show
  1. package/CHANGELOG.md +47 -7
  2. package/dist/bundle/chunks/{anthropic-messages-RDYSW7WM.js → anthropic-messages-HME6WDIM.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-HB77OIU4.js → azure-openai-responses-WKSFBZF5.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  5. package/dist/bundle/chunks/{chunk-QRII7KJY.js → chunk-3MKQN3ZR.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-VJQ6ZYW4.js → chunk-4NMBWIZG.js} +5 -5
  7. package/dist/bundle/chunks/{chunk-INTHKDF2.js → chunk-65DC2T66.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-762GZFUO.js → chunk-6L2FT6AE.js} +1 -1
  9. package/dist/bundle/chunks/chunk-6ZD23B2R.js +2 -0
  10. package/dist/bundle/chunks/{chunk-ZVEA4XD4.js → chunk-E3MJ4MPN.js} +1 -1
  11. package/dist/bundle/chunks/chunk-GRDBYTYT.js +2003 -0
  12. package/dist/bundle/chunks/{chunk-RJRIMI6M.js → chunk-GRYHVZSI.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-Z72M6UD7.js → chunk-MITPYV3F.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-JJOJ6QJX.js → chunk-MJRIJM22.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-B4DODQSC.js → chunk-PQGGR7SQ.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-Z36XYVPO.js → chunk-PXE534VH.js} +2 -2
  17. package/dist/bundle/chunks/{chunk-OYSUJGUM.js → chunk-QMZGTPRI.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-VSFRR6IC.js → chunk-QQ6NVGNW.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-DWKLYVGO.js → chunk-RUI3NOFB.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-6S2AQWGR.js → chunk-SI7T4LPD.js} +4 -4
  21. package/dist/bundle/chunks/{chunk-V5GJW5IX.js → chunk-SMYD2SB5.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-B3FUE2LF.js → chunk-XAA355T2.js} +1 -1
  23. package/dist/bundle/chunks/{cli-SYWCWCZU.js → cli-GKHAGQO6.js} +1 -1
  24. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-AASXI4DD.js → cloudflare-workers-ai-system-one-PVUECIVD.js} +1 -1
  25. package/dist/bundle/chunks/{easter-egg-3d-QN5RJMZR.js → easter-egg-3d-VAZ2JWDP.js} +1 -1
  26. package/dist/bundle/chunks/{execute-3J63CQJG.js → execute-OEFRHFHI.js} +1 -1
  27. package/dist/bundle/chunks/{google-generative-ai-6HC6JYFU.js → google-generative-ai-2YH7DK5J.js} +1 -1
  28. package/dist/bundle/chunks/{google-vertex-UJFQATKN.js → google-vertex-QNIS4SPE.js} +1 -1
  29. package/dist/bundle/chunks/{llama-cpp-classify-GCDAR6VP.js → llama-cpp-classify-EMBT3ZMY.js} +1 -1
  30. package/dist/bundle/chunks/{mistral-conversations-CF3OZSLK.js → mistral-conversations-RCHJWX2M.js} +1 -1
  31. package/dist/bundle/chunks/{openai-codex-responses-L3IPEYDP.js → openai-codex-responses-LBZQ7HUY.js} +1 -1
  32. package/dist/bundle/chunks/{openai-completions-UXPSYQS7.js → openai-completions-U7NS5GFY.js} +1 -1
  33. package/dist/bundle/chunks/{openai-decisions-DML6VHFQ.js → openai-decisions-YC4ZEGAR.js} +1 -1
  34. package/dist/bundle/chunks/{openai-responses-46Z64FIE.js → openai-responses-4YX6XMEO.js} +1 -1
  35. package/dist/bundle/chunks/{openrouter-images-EI7VO7CT.js → openrouter-images-QPPGKFJY.js} +1 -1
  36. package/dist/bundle/chunks/{pi-messages-4MV3SCQE.js → pi-messages-5W3GZ7B6.js} +1 -1
  37. package/dist/bundle/chunks/{runtime-KEVIZBAR.js → runtime-SI4R3AXJ.js} +1 -1
  38. package/dist/bundle/chunks/{typesafe-system-one-FZU6TH2G.js → typesafe-system-one-GWMQ2NLX.js} +1 -1
  39. package/dist/bundle/chunks/virtual-modules-ENTYMDSQ.js +2 -0
  40. package/dist/bundle/cli-runtime.js +1 -1
  41. package/dist/bundle/index.js +1 -1
  42. package/dist/bundle/rpc-entry.js +1 -1
  43. package/dist/cli/args.d.ts +2 -0
  44. package/dist/cli/args.d.ts.map +1 -1
  45. package/dist/cli/args.js +13 -0
  46. package/dist/cli/args.js.map +1 -1
  47. package/dist/cli/sandbox-command.d.ts +8 -0
  48. package/dist/cli/sandbox-command.d.ts.map +1 -0
  49. package/dist/cli/sandbox-command.js +52 -0
  50. package/dist/cli/sandbox-command.js.map +1 -0
  51. package/dist/config.d.ts +7 -0
  52. package/dist/config.d.ts.map +1 -1
  53. package/dist/config.js +14 -0
  54. package/dist/config.js.map +1 -1
  55. package/dist/core/agent-session.d.ts +20 -0
  56. package/dist/core/agent-session.d.ts.map +1 -1
  57. package/dist/core/agent-session.js +72 -2
  58. package/dist/core/agent-session.js.map +1 -1
  59. package/dist/core/approval-mode.d.ts +28 -0
  60. package/dist/core/approval-mode.d.ts.map +1 -0
  61. package/dist/core/approval-mode.js +34 -0
  62. package/dist/core/approval-mode.js.map +1 -0
  63. package/dist/core/extensions/loader.d.ts.map +1 -1
  64. package/dist/core/extensions/loader.js +15 -0
  65. package/dist/core/extensions/loader.js.map +1 -1
  66. package/dist/core/extensions/runner.d.ts.map +1 -1
  67. package/dist/core/extensions/runner.js +3 -0
  68. package/dist/core/extensions/runner.js.map +1 -1
  69. package/dist/core/extensions/types.d.ts +28 -1
  70. package/dist/core/extensions/types.d.ts.map +1 -1
  71. package/dist/core/extensions/types.js.map +1 -1
  72. package/dist/core/fast-model.d.ts +10 -0
  73. package/dist/core/fast-model.d.ts.map +1 -0
  74. package/dist/core/fast-model.js +13 -0
  75. package/dist/core/fast-model.js.map +1 -0
  76. package/dist/core/keybindings.d.ts +8 -0
  77. package/dist/core/keybindings.d.ts.map +1 -1
  78. package/dist/core/keybindings.js +4 -0
  79. package/dist/core/keybindings.js.map +1 -1
  80. package/dist/core/sandbox/escalation.d.ts +32 -0
  81. package/dist/core/sandbox/escalation.d.ts.map +1 -0
  82. package/dist/core/sandbox/escalation.js +70 -0
  83. package/dist/core/sandbox/escalation.js.map +1 -0
  84. package/dist/core/sandbox/launch.d.ts +14 -0
  85. package/dist/core/sandbox/launch.d.ts.map +1 -0
  86. package/dist/core/sandbox/launch.js +18 -0
  87. package/dist/core/sandbox/launch.js.map +1 -0
  88. package/dist/core/sandbox/policy.d.ts +50 -0
  89. package/dist/core/sandbox/policy.d.ts.map +1 -0
  90. package/dist/core/sandbox/policy.js +96 -0
  91. package/dist/core/sandbox/policy.js.map +1 -0
  92. package/dist/core/sandbox/seatbelt.d.ts +17 -0
  93. package/dist/core/sandbox/seatbelt.d.ts.map +1 -0
  94. package/dist/core/sandbox/seatbelt.js +169 -0
  95. package/dist/core/sandbox/seatbelt.js.map +1 -0
  96. package/dist/core/sandbox/windows.d.ts +30 -0
  97. package/dist/core/sandbox/windows.d.ts.map +1 -0
  98. package/dist/core/sandbox/windows.js +104 -0
  99. package/dist/core/sandbox/windows.js.map +1 -0
  100. package/dist/core/settings-defaults.d.ts +28 -0
  101. package/dist/core/settings-defaults.d.ts.map +1 -1
  102. package/dist/core/settings-defaults.js +28 -0
  103. package/dist/core/settings-defaults.js.map +1 -1
  104. package/dist/core/settings-manager.d.ts +9 -1
  105. package/dist/core/settings-manager.d.ts.map +1 -1
  106. package/dist/core/settings-manager.js +58 -1
  107. package/dist/core/settings-manager.js.map +1 -1
  108. package/dist/core/settings-schema.d.ts +124 -0
  109. package/dist/core/settings-schema.d.ts.map +1 -1
  110. package/dist/core/settings-schema.js +177 -0
  111. package/dist/core/settings-schema.js.map +1 -1
  112. package/dist/core/tools/bash.d.ts +12 -2
  113. package/dist/core/tools/bash.d.ts.map +1 -1
  114. package/dist/core/tools/bash.js +27 -7
  115. package/dist/core/tools/bash.js.map +1 -1
  116. package/dist/core/tools/edit.d.ts +3 -0
  117. package/dist/core/tools/edit.d.ts.map +1 -1
  118. package/dist/core/tools/edit.js +2 -0
  119. package/dist/core/tools/edit.js.map +1 -1
  120. package/dist/core/tools/powershell.d.ts +3 -2
  121. package/dist/core/tools/powershell.d.ts.map +1 -1
  122. package/dist/core/tools/powershell.js +4 -6
  123. package/dist/core/tools/powershell.js.map +1 -1
  124. package/dist/core/tools/render-utils.d.ts +2 -2
  125. package/dist/core/tools/render-utils.js +5 -5
  126. package/dist/core/tools/render-utils.js.map +1 -1
  127. package/dist/core/tools/renderers/edit.d.ts.map +1 -1
  128. package/dist/core/tools/renderers/edit.js +16 -19
  129. package/dist/core/tools/renderers/edit.js.map +1 -1
  130. package/dist/core/tools/write.d.ts +3 -0
  131. package/dist/core/tools/write.d.ts.map +1 -1
  132. package/dist/core/tools/write.js +2 -0
  133. package/dist/core/tools/write.js.map +1 -1
  134. package/dist/extensions/agents/agent-tool.d.ts +61 -0
  135. package/dist/extensions/agents/agent-tool.d.ts.map +1 -0
  136. package/dist/extensions/agents/agent-tool.js +277 -0
  137. package/dist/extensions/agents/agent-tool.js.map +1 -0
  138. package/dist/extensions/agents/background.d.ts +56 -0
  139. package/dist/extensions/agents/background.d.ts.map +1 -0
  140. package/dist/extensions/agents/background.js +142 -0
  141. package/dist/extensions/agents/background.js.map +1 -0
  142. package/dist/extensions/agents/builtin-agents.d.ts +8 -0
  143. package/dist/extensions/agents/builtin-agents.d.ts.map +1 -0
  144. package/dist/extensions/agents/builtin-agents.js +38 -0
  145. package/dist/extensions/agents/builtin-agents.js.map +1 -0
  146. package/dist/extensions/agents/call-scopes.d.ts +34 -0
  147. package/dist/extensions/agents/call-scopes.d.ts.map +1 -0
  148. package/dist/extensions/agents/call-scopes.js +36 -0
  149. package/dist/extensions/agents/call-scopes.js.map +1 -0
  150. package/dist/extensions/agents/definitions.d.ts +64 -0
  151. package/dist/extensions/agents/definitions.d.ts.map +1 -0
  152. package/dist/extensions/agents/definitions.js +216 -0
  153. package/dist/extensions/agents/definitions.js.map +1 -0
  154. package/dist/extensions/agents/index.d.ts +15 -0
  155. package/dist/extensions/agents/index.d.ts.map +1 -0
  156. package/dist/extensions/agents/index.js +327 -0
  157. package/dist/extensions/agents/index.js.map +1 -0
  158. package/dist/extensions/agents/runner.d.ts +63 -0
  159. package/dist/extensions/agents/runner.d.ts.map +1 -0
  160. package/dist/extensions/agents/runner.js +156 -0
  161. package/dist/extensions/agents/runner.js.map +1 -0
  162. package/dist/extensions/approval/auto-classifier.d.ts +32 -0
  163. package/dist/extensions/approval/auto-classifier.d.ts.map +1 -0
  164. package/dist/extensions/approval/auto-classifier.js +116 -0
  165. package/dist/extensions/approval/auto-classifier.js.map +1 -0
  166. package/dist/extensions/approval/exit-plan-mode.d.ts +24 -0
  167. package/dist/extensions/approval/exit-plan-mode.d.ts.map +1 -0
  168. package/dist/extensions/approval/exit-plan-mode.js +99 -0
  169. package/dist/extensions/approval/exit-plan-mode.js.map +1 -0
  170. package/dist/extensions/approval/index.d.ts +15 -0
  171. package/dist/extensions/approval/index.d.ts.map +1 -0
  172. package/dist/extensions/approval/index.js +329 -0
  173. package/dist/extensions/approval/index.js.map +1 -0
  174. package/dist/extensions/approval/plan-reminders.d.ts +9 -0
  175. package/dist/extensions/approval/plan-reminders.d.ts.map +1 -0
  176. package/dist/extensions/approval/plan-reminders.js +42 -0
  177. package/dist/extensions/approval/plan-reminders.js.map +1 -0
  178. package/dist/extensions/approval/policy.d.ts +52 -0
  179. package/dist/extensions/approval/policy.d.ts.map +1 -0
  180. package/dist/extensions/approval/policy.js +124 -0
  181. package/dist/extensions/approval/policy.js.map +1 -0
  182. package/dist/extensions/approval/shell-safety.d.ts +11 -0
  183. package/dist/extensions/approval/shell-safety.d.ts.map +1 -0
  184. package/dist/extensions/approval/shell-safety.js +264 -0
  185. package/dist/extensions/approval/shell-safety.js.map +1 -0
  186. package/dist/extensions/cron/cron-expression.d.ts +30 -0
  187. package/dist/extensions/cron/cron-expression.d.ts.map +1 -0
  188. package/dist/extensions/cron/cron-expression.js +119 -0
  189. package/dist/extensions/cron/cron-expression.js.map +1 -0
  190. package/dist/extensions/cron/index.d.ts +19 -0
  191. package/dist/extensions/cron/index.d.ts.map +1 -0
  192. package/dist/extensions/cron/index.js +215 -0
  193. package/dist/extensions/cron/index.js.map +1 -0
  194. package/dist/extensions/cron/loop-args.d.ts +35 -0
  195. package/dist/extensions/cron/loop-args.d.ts.map +1 -0
  196. package/dist/extensions/cron/loop-args.js +95 -0
  197. package/dist/extensions/cron/loop-args.js.map +1 -0
  198. package/dist/extensions/cron/loop-texts.d.ts +29 -0
  199. package/dist/extensions/cron/loop-texts.d.ts.map +1 -0
  200. package/dist/extensions/cron/loop-texts.js +83 -0
  201. package/dist/extensions/cron/loop-texts.js.map +1 -0
  202. package/dist/extensions/cron/scheduler.d.ts +79 -0
  203. package/dist/extensions/cron/scheduler.d.ts.map +1 -0
  204. package/dist/extensions/cron/scheduler.js +146 -0
  205. package/dist/extensions/cron/scheduler.js.map +1 -0
  206. package/dist/extensions/cron/tools.d.ts +47 -0
  207. package/dist/extensions/cron/tools.d.ts.map +1 -0
  208. package/dist/extensions/cron/tools.js +141 -0
  209. package/dist/extensions/cron/tools.js.map +1 -0
  210. package/dist/extensions/goals/evidence.d.ts +20 -0
  211. package/dist/extensions/goals/evidence.d.ts.map +1 -0
  212. package/dist/extensions/goals/evidence.js +77 -0
  213. package/dist/extensions/goals/evidence.js.map +1 -0
  214. package/dist/extensions/goals/index.d.ts +45 -0
  215. package/dist/extensions/goals/index.d.ts.map +1 -0
  216. package/dist/extensions/goals/index.js +438 -0
  217. package/dist/extensions/goals/index.js.map +1 -0
  218. package/dist/extensions/goals/prompts.d.ts +15 -0
  219. package/dist/extensions/goals/prompts.d.ts.map +1 -0
  220. package/dist/extensions/goals/prompts.js +51 -0
  221. package/dist/extensions/goals/prompts.js.map +1 -0
  222. package/dist/extensions/goals/state.d.ts +88 -0
  223. package/dist/extensions/goals/state.d.ts.map +1 -0
  224. package/dist/extensions/goals/state.js +204 -0
  225. package/dist/extensions/goals/state.js.map +1 -0
  226. package/dist/extensions/goals/tools.d.ts +40 -0
  227. package/dist/extensions/goals/tools.d.ts.map +1 -0
  228. package/dist/extensions/goals/tools.js +118 -0
  229. package/dist/extensions/goals/tools.js.map +1 -0
  230. package/dist/extensions/goals/verifier.d.ts +30 -0
  231. package/dist/extensions/goals/verifier.d.ts.map +1 -0
  232. package/dist/extensions/goals/verifier.js +89 -0
  233. package/dist/extensions/goals/verifier.js.map +1 -0
  234. package/dist/extensions/hooks/aggregate.d.ts +30 -0
  235. package/dist/extensions/hooks/aggregate.d.ts.map +1 -0
  236. package/dist/extensions/hooks/aggregate.js +103 -0
  237. package/dist/extensions/hooks/aggregate.js.map +1 -0
  238. package/dist/extensions/hooks/config.d.ts +47 -0
  239. package/dist/extensions/hooks/config.d.ts.map +1 -0
  240. package/dist/extensions/hooks/config.js +169 -0
  241. package/dist/extensions/hooks/config.js.map +1 -0
  242. package/dist/extensions/hooks/file-watcher.d.ts +31 -0
  243. package/dist/extensions/hooks/file-watcher.d.ts.map +1 -0
  244. package/dist/extensions/hooks/file-watcher.js +106 -0
  245. package/dist/extensions/hooks/file-watcher.js.map +1 -0
  246. package/dist/extensions/hooks/index.d.ts +17 -0
  247. package/dist/extensions/hooks/index.d.ts.map +1 -0
  248. package/dist/extensions/hooks/index.js +349 -0
  249. package/dist/extensions/hooks/index.js.map +1 -0
  250. package/dist/extensions/hooks/matcher.d.ts +10 -0
  251. package/dist/extensions/hooks/matcher.d.ts.map +1 -0
  252. package/dist/extensions/hooks/matcher.js +85 -0
  253. package/dist/extensions/hooks/matcher.js.map +1 -0
  254. package/dist/extensions/hooks/runner.d.ts +54 -0
  255. package/dist/extensions/hooks/runner.d.ts.map +1 -0
  256. package/dist/extensions/hooks/runner.js +197 -0
  257. package/dist/extensions/hooks/runner.js.map +1 -0
  258. package/dist/extensions/index.d.ts.map +1 -1
  259. package/dist/extensions/index.js +29 -2
  260. package/dist/extensions/index.js.map +1 -1
  261. package/dist/extensions/lsp/config.d.ts +40 -0
  262. package/dist/extensions/lsp/config.d.ts.map +1 -0
  263. package/dist/extensions/lsp/config.js +92 -0
  264. package/dist/extensions/lsp/config.js.map +1 -0
  265. package/dist/extensions/lsp/connection.d.ts +32 -0
  266. package/dist/extensions/lsp/connection.d.ts.map +1 -0
  267. package/dist/extensions/lsp/connection.js +124 -0
  268. package/dist/extensions/lsp/connection.js.map +1 -0
  269. package/dist/extensions/lsp/index.d.ts +15 -0
  270. package/dist/extensions/lsp/index.d.ts.map +1 -0
  271. package/dist/extensions/lsp/index.js +103 -0
  272. package/dist/extensions/lsp/index.js.map +1 -0
  273. package/dist/extensions/lsp/server.d.ts +68 -0
  274. package/dist/extensions/lsp/server.d.ts.map +1 -0
  275. package/dist/extensions/lsp/server.js +373 -0
  276. package/dist/extensions/lsp/server.js.map +1 -0
  277. package/dist/extensions/lsp/tool.d.ts +43 -0
  278. package/dist/extensions/lsp/tool.d.ts.map +1 -0
  279. package/dist/extensions/lsp/tool.js +534 -0
  280. package/dist/extensions/lsp/tool.js.map +1 -0
  281. package/dist/extensions/memory/index.d.ts +15 -0
  282. package/dist/extensions/memory/index.d.ts.map +1 -0
  283. package/dist/extensions/memory/index.js +336 -0
  284. package/dist/extensions/memory/index.js.map +1 -0
  285. package/dist/extensions/memory/memory-agent.d.ts +29 -0
  286. package/dist/extensions/memory/memory-agent.d.ts.map +1 -0
  287. package/dist/extensions/memory/memory-agent.js +102 -0
  288. package/dist/extensions/memory/memory-agent.js.map +1 -0
  289. package/dist/extensions/memory/prompts.d.ts +18 -0
  290. package/dist/extensions/memory/prompts.d.ts.map +1 -0
  291. package/dist/extensions/memory/prompts.js +124 -0
  292. package/dist/extensions/memory/prompts.js.map +1 -0
  293. package/dist/extensions/memory/recall.d.ts +14 -0
  294. package/dist/extensions/memory/recall.d.ts.map +1 -0
  295. package/dist/extensions/memory/recall.js +80 -0
  296. package/dist/extensions/memory/recall.js.map +1 -0
  297. package/dist/extensions/memory/store.d.ts +48 -0
  298. package/dist/extensions/memory/store.d.ts.map +1 -0
  299. package/dist/extensions/memory/store.js +132 -0
  300. package/dist/extensions/memory/store.js.map +1 -0
  301. package/dist/extensions/skills/bundled/batch/SKILL.md +74 -0
  302. package/dist/extensions/skills/bundled/review/SKILL.md +93 -0
  303. package/dist/extensions/skills/index.d.ts +15 -0
  304. package/dist/extensions/skills/index.d.ts.map +1 -0
  305. package/dist/extensions/skills/index.js +68 -0
  306. package/dist/extensions/skills/index.js.map +1 -0
  307. package/dist/extensions/skills/learn.d.ts +9 -0
  308. package/dist/extensions/skills/learn.d.ts.map +1 -0
  309. package/dist/extensions/skills/learn.js +46 -0
  310. package/dist/extensions/skills/learn.js.map +1 -0
  311. package/dist/extensions/todo/index.d.ts +14 -0
  312. package/dist/extensions/todo/index.d.ts.map +1 -0
  313. package/dist/extensions/todo/index.js +55 -0
  314. package/dist/extensions/todo/index.js.map +1 -0
  315. package/dist/extensions/todo/todos.d.ts +64 -0
  316. package/dist/extensions/todo/todos.d.ts.map +1 -0
  317. package/dist/extensions/todo/todos.js +145 -0
  318. package/dist/extensions/todo/todos.js.map +1 -0
  319. package/dist/extensions/todo/tool.d.ts +23 -0
  320. package/dist/extensions/todo/tool.d.ts.map +1 -0
  321. package/dist/extensions/todo/tool.js +104 -0
  322. package/dist/extensions/todo/tool.js.map +1 -0
  323. package/dist/extensions/web-fetch/fetch-tool.d.ts +27 -0
  324. package/dist/extensions/web-fetch/fetch-tool.d.ts.map +1 -0
  325. package/dist/extensions/web-fetch/fetch-tool.js +319 -0
  326. package/dist/extensions/web-fetch/fetch-tool.js.map +1 -0
  327. package/dist/extensions/web-fetch/html-to-markdown.d.ts +7 -0
  328. package/dist/extensions/web-fetch/html-to-markdown.d.ts.map +1 -0
  329. package/dist/extensions/web-fetch/html-to-markdown.js +21 -0
  330. package/dist/extensions/web-fetch/html-to-markdown.js.map +1 -0
  331. package/dist/extensions/web-fetch/index.d.ts +10 -0
  332. package/dist/extensions/web-fetch/index.d.ts.map +1 -0
  333. package/dist/extensions/web-fetch/index.js +13 -0
  334. package/dist/extensions/web-fetch/index.js.map +1 -0
  335. package/dist/extensions/web-fetch/page-fetch.d.ts +45 -0
  336. package/dist/extensions/web-fetch/page-fetch.d.ts.map +1 -0
  337. package/dist/extensions/web-fetch/page-fetch.js +117 -0
  338. package/dist/extensions/web-fetch/page-fetch.js.map +1 -0
  339. package/dist/extensions/web-fetch/pdf-text.d.ts +29 -0
  340. package/dist/extensions/web-fetch/pdf-text.d.ts.map +1 -0
  341. package/dist/extensions/web-fetch/pdf-text.js +71 -0
  342. package/dist/extensions/web-fetch/pdf-text.js.map +1 -0
  343. package/dist/extensions/web-fetch/preapproved-hosts.d.ts +7 -0
  344. package/dist/extensions/web-fetch/preapproved-hosts.d.ts.map +1 -0
  345. package/dist/extensions/web-fetch/preapproved-hosts.js +110 -0
  346. package/dist/extensions/web-fetch/preapproved-hosts.js.map +1 -0
  347. package/dist/extensions/web-search/dashscope-search.d.ts +29 -0
  348. package/dist/extensions/web-search/dashscope-search.d.ts.map +1 -0
  349. package/dist/extensions/web-search/dashscope-search.js +279 -0
  350. package/dist/extensions/web-search/dashscope-search.js.map +1 -0
  351. package/dist/extensions/web-search/index.d.ts +15 -0
  352. package/dist/extensions/web-search/index.d.ts.map +1 -0
  353. package/dist/extensions/web-search/index.js +51 -0
  354. package/dist/extensions/web-search/index.js.map +1 -0
  355. package/dist/extensions/web-search/search-config.d.ts +53 -0
  356. package/dist/extensions/web-search/search-config.d.ts.map +1 -0
  357. package/dist/extensions/web-search/search-config.js +174 -0
  358. package/dist/extensions/web-search/search-config.js.map +1 -0
  359. package/dist/extensions/web-search/search-tool.d.ts +29 -0
  360. package/dist/extensions/web-search/search-tool.d.ts.map +1 -0
  361. package/dist/extensions/web-search/search-tool.js +149 -0
  362. package/dist/extensions/web-search/search-tool.js.map +1 -0
  363. package/dist/extensions/worktree/git-worktree.d.ts +69 -0
  364. package/dist/extensions/worktree/git-worktree.d.ts.map +1 -0
  365. package/dist/extensions/worktree/git-worktree.js +199 -0
  366. package/dist/extensions/worktree/git-worktree.js.map +1 -0
  367. package/dist/extensions/worktree/index.d.ts +27 -0
  368. package/dist/extensions/worktree/index.d.ts.map +1 -0
  369. package/dist/extensions/worktree/index.js +188 -0
  370. package/dist/extensions/worktree/index.js.map +1 -0
  371. package/dist/extensions/worktree/startup.d.ts +17 -0
  372. package/dist/extensions/worktree/startup.d.ts.map +1 -0
  373. package/dist/extensions/worktree/startup.js +56 -0
  374. package/dist/extensions/worktree/startup.js.map +1 -0
  375. package/dist/main.d.ts.map +1 -1
  376. package/dist/main.js +28 -4
  377. package/dist/main.js.map +1 -1
  378. package/dist/modes/interactive/components/custom-editor.d.ts +18 -0
  379. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  380. package/dist/modes/interactive/components/custom-editor.js +87 -20
  381. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  382. package/dist/modes/interactive/components/diffra-logo.d.ts +6 -0
  383. package/dist/modes/interactive/components/diffra-logo.d.ts.map +1 -1
  384. package/dist/modes/interactive/components/diffra-logo.js +30 -4
  385. package/dist/modes/interactive/components/diffra-logo.js.map +1 -1
  386. package/dist/modes/interactive/components/dynamic-border.d.ts +1 -1
  387. package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -1
  388. package/dist/modes/interactive/components/dynamic-border.js +3 -3
  389. package/dist/modes/interactive/components/dynamic-border.js.map +1 -1
  390. package/dist/modes/interactive/components/footer.d.ts +16 -0
  391. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  392. package/dist/modes/interactive/components/footer.js +84 -46
  393. package/dist/modes/interactive/components/footer.js.map +1 -1
  394. package/dist/modes/interactive/components/tool-execution.d.ts +5 -2
  395. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  396. package/dist/modes/interactive/components/tool-execution.js +152 -62
  397. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  398. package/dist/modes/interactive/components/tool-status.d.ts +5 -0
  399. package/dist/modes/interactive/components/tool-status.d.ts.map +1 -0
  400. package/dist/modes/interactive/components/tool-status.js +15 -0
  401. package/dist/modes/interactive/components/tool-status.js.map +1 -0
  402. package/dist/modes/interactive/components/user-message.d.ts +4 -8
  403. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  404. package/dist/modes/interactive/components/user-message.js +38 -36
  405. package/dist/modes/interactive/components/user-message.js.map +1 -1
  406. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  407. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  408. package/dist/modes/interactive/interactive-mode.js +24 -8
  409. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  410. package/dist/modes/interactive/theme/dark.json +3 -2
  411. package/dist/modes/interactive/theme/light.json +3 -2
  412. package/dist/modes/interactive/theme/system-theme.d.ts +1 -0
  413. package/dist/modes/interactive/theme/system-theme.d.ts.map +1 -1
  414. package/dist/modes/interactive/theme/system-theme.js +41 -14
  415. package/dist/modes/interactive/theme/system-theme.js.map +1 -1
  416. package/dist/utils/shell.d.ts +1 -1
  417. package/dist/utils/shell.d.ts.map +1 -1
  418. package/dist/utils/shell.js +12 -2
  419. package/dist/utils/shell.js.map +1 -1
  420. package/dist/utils/tools-manager.d.ts +5 -1
  421. package/dist/utils/tools-manager.d.ts.map +1 -1
  422. package/dist/utils/tools-manager.js +81 -47
  423. package/dist/utils/tools-manager.js.map +1 -1
  424. package/docs/approval-modes.md +99 -0
  425. package/docs/builtin-skills.md +53 -0
  426. package/docs/cli.md +380 -356
  427. package/docs/docs.json +264 -220
  428. package/docs/environment-variables.md +110 -103
  429. package/docs/extensions.md +24 -0
  430. package/docs/goals.md +84 -0
  431. package/docs/hooks.md +112 -0
  432. package/docs/keybindings.md +1 -0
  433. package/docs/lsp.md +71 -0
  434. package/docs/memory.md +71 -0
  435. package/docs/sandbox.md +108 -0
  436. package/docs/scheduled-tasks.md +84 -0
  437. package/docs/security.md +100 -99
  438. package/docs/settings.md +198 -173
  439. package/docs/shell-aliases.md +1 -1
  440. package/docs/skills.md +4 -0
  441. package/docs/slash-commands.md +15 -0
  442. package/docs/subagents.md +102 -0
  443. package/docs/web-tools.md +83 -0
  444. package/docs/windows.md +2 -1
  445. package/docs/worktrees.md +52 -0
  446. package/examples/extensions/README.md +1 -1
  447. package/examples/extensions/plan-mode/README.md +2 -2
  448. package/examples/extensions/plan-mode/index.ts +7 -4
  449. package/examples/extensions/subagent/README.md +2 -0
  450. package/examples/extensions/subagent/index.ts +3 -0
  451. package/examples/extensions/todo.ts +4 -0
  452. package/package.json +9 -8
  453. package/schemas/keybindings.schema.json +4 -0
  454. package/schemas/settings.schema.json +421 -0
  455. package/dist/bundle/chunks/chunk-EIL6ZC3J.js +0 -1240
  456. package/dist/bundle/chunks/chunk-GCKVPVMH.js +0 -2
  457. package/dist/bundle/chunks/virtual-modules-RGWFZDWP.js +0 -2
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{isRecord,parseClassifierUsage,postClassifierRequest,requiredNumber}from"./chunk-DWKLYVGO.js";import{formatProviderError,normalizeProviderError}from"./chunk-ZVEA4XD4.js";var IMAGE_OPT_IN_HEADERS={"TypeSafe-Danger-Zone-Images":"true"};function probabilities(label,value,id){if(!isRecord(value))throw new Error(`${label} returned invalid probabilities for ${id}`);return Object.fromEntries(Object.entries(value).map(([key,probability])=>[key,requiredNumber(label,probability,`probability for ${id}.${key}`)]))}function parseAnswers(label,value,context){if(!isRecord(value))throw new Error(`${label} returned an unexpected response`);let answers=[];for(let[id,question]of Object.entries(context.questions)){let answer=value[id];if(!isRecord(answer))throw new Error(`${label} did not return an answer for ${id}`);if(question.type==="choice"){if(answer.type!=="choice"||typeof answer.choice!="string")throw new Error(`${label} did not return a choice answer for ${id}`);answers.push([id,{type:"choice",choice:answer.choice,probabilities:probabilities(label,answer.probabilities,id),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else if(question.type==="score"){if(answer.type!=="score")throw new Error(`${label} did not return a score answer for ${id}`);answers.push([id,{type:"score",score:requiredNumber(label,answer.score,`score for ${id}`),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else{if(answer.type!=="noul")throw new Error(`${label} did not return a bool answer for ${id}`);answers.push([id,{type:"bool",probability:requiredNumber(label,answer.noul,`probability for ${id}`)}])}}return Object.fromEntries(answers)}var ASSET_FORMATS={"image/png":"png","image/jpeg":"jpeg"},DATA_URL_TYPES=new Set(["image/png","image/jpeg","image/webp"]),MAX_DATA_URL_IMAGES=4;function addImages(label,model,input,images,request){if(input==="images"){if(images.length>MAX_DATA_URL_IMAGES)throw new Error(`${label} accepts at most ${MAX_DATA_URL_IMAGES} images for ${model.id}, got ${images.length}`);request.images=images.map(image=>{if(!DATA_URL_TYPES.has(image.mimeType))throw new Error(`${label} accepts PNG, JPEG, and WebP images for ${model.id}, got ${image.mimeType}`);return`data:${image.mimeType};base64,${image.data}`});return}if(input==="state-image-urls"){let parts=images.map(image=>({type:"image_url",image_url:{url:`data:${image.mimeType};base64,${image.data}`}}));request.state=[...parts,request.state];return}let assets={};images.forEach((image,index)=>{let format=ASSET_FORMATS[image.mimeType];if(!format)throw new Error(`${label} accepts PNG and JPEG images for ${model.id}, got ${image.mimeType}`);assets[`<image-${index+1}>`]={type:"image",format,data_base64:image.data}}),request.assets=assets,request.state=[...Object.keys(assets),request.state]}function wireRequest(context){return{state:context.state,questions:Object.fromEntries(Object.entries(context.questions).map(([id,question])=>[id,question.type==="bool"?{...question,type:"noul"}:question]))}}async function classifySystemOne(transport,model,context,options){let output={api:model.api,provider:model.provider,model:model.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(model.api!==transport.api)throw new Error(`Unsupported classifier API: ${model.api}`);let request=wireRequest(context),requestOptions=options;if(context.images?.length){if(!model.input.includes("image"))throw new Error(`${transport.label} does not support image input for ${model.id}`);let detected=transport.detectCompat(model),imageInput=model.compat?.imageInput??detected.imageInput;addImages(transport.label,model,imageInput,context.images,request),(model.compat?.sendImageOptInHeader??detected.sendImageOptInHeader)&&(requestOptions={...options,headers:{...IMAGE_OPT_IN_HEADERS,...options?.headers}})}let body=await postClassifierRequest(transport.label,transport.url(model),model,transport.payload(model,request),requestOptions),result=transport.output(body),usage=parseClassifierUsage(result.usage,model);return usage&&(output.usage=usage),output.answers=parseAnswers(transport.label,result.answers,context),output}catch(error){return output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error),`${transport.label} error`),output}}export{classifySystemOne};
2
+ import{isRecord,parseClassifierUsage,postClassifierRequest,requiredNumber}from"./chunk-RUI3NOFB.js";import{formatProviderError,normalizeProviderError}from"./chunk-E3MJ4MPN.js";var IMAGE_OPT_IN_HEADERS={"TypeSafe-Danger-Zone-Images":"true"};function probabilities(label,value,id){if(!isRecord(value))throw new Error(`${label} returned invalid probabilities for ${id}`);return Object.fromEntries(Object.entries(value).map(([key,probability])=>[key,requiredNumber(label,probability,`probability for ${id}.${key}`)]))}function parseAnswers(label,value,context){if(!isRecord(value))throw new Error(`${label} returned an unexpected response`);let answers=[];for(let[id,question]of Object.entries(context.questions)){let answer=value[id];if(!isRecord(answer))throw new Error(`${label} did not return an answer for ${id}`);if(question.type==="choice"){if(answer.type!=="choice"||typeof answer.choice!="string")throw new Error(`${label} did not return a choice answer for ${id}`);answers.push([id,{type:"choice",choice:answer.choice,probabilities:probabilities(label,answer.probabilities,id),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else if(question.type==="score"){if(answer.type!=="score")throw new Error(`${label} did not return a score answer for ${id}`);answers.push([id,{type:"score",score:requiredNumber(label,answer.score,`score for ${id}`),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else{if(answer.type!=="noul")throw new Error(`${label} did not return a bool answer for ${id}`);answers.push([id,{type:"bool",probability:requiredNumber(label,answer.noul,`probability for ${id}`)}])}}return Object.fromEntries(answers)}var ASSET_FORMATS={"image/png":"png","image/jpeg":"jpeg"},DATA_URL_TYPES=new Set(["image/png","image/jpeg","image/webp"]),MAX_DATA_URL_IMAGES=4;function addImages(label,model,input,images,request){if(input==="images"){if(images.length>MAX_DATA_URL_IMAGES)throw new Error(`${label} accepts at most ${MAX_DATA_URL_IMAGES} images for ${model.id}, got ${images.length}`);request.images=images.map(image=>{if(!DATA_URL_TYPES.has(image.mimeType))throw new Error(`${label} accepts PNG, JPEG, and WebP images for ${model.id}, got ${image.mimeType}`);return`data:${image.mimeType};base64,${image.data}`});return}if(input==="state-image-urls"){let parts=images.map(image=>({type:"image_url",image_url:{url:`data:${image.mimeType};base64,${image.data}`}}));request.state=[...parts,request.state];return}let assets={};images.forEach((image,index)=>{let format=ASSET_FORMATS[image.mimeType];if(!format)throw new Error(`${label} accepts PNG and JPEG images for ${model.id}, got ${image.mimeType}`);assets[`<image-${index+1}>`]={type:"image",format,data_base64:image.data}}),request.assets=assets,request.state=[...Object.keys(assets),request.state]}function wireRequest(context){return{state:context.state,questions:Object.fromEntries(Object.entries(context.questions).map(([id,question])=>[id,question.type==="bool"?{...question,type:"noul"}:question]))}}async function classifySystemOne(transport,model,context,options){let output={api:model.api,provider:model.provider,model:model.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(model.api!==transport.api)throw new Error(`Unsupported classifier API: ${model.api}`);let request=wireRequest(context),requestOptions=options;if(context.images?.length){if(!model.input.includes("image"))throw new Error(`${transport.label} does not support image input for ${model.id}`);let detected=transport.detectCompat(model),imageInput=model.compat?.imageInput??detected.imageInput;addImages(transport.label,model,imageInput,context.images,request),(model.compat?.sendImageOptInHeader??detected.sendImageOptInHeader)&&(requestOptions={...options,headers:{...IMAGE_OPT_IN_HEADERS,...options?.headers}})}let body=await postClassifierRequest(transport.label,transport.url(model),model,transport.payload(model,request),requestOptions),result=transport.output(body),usage=parseClassifierUsage(result.usage,model);return usage&&(output.usage=usage),output.answers=parseAnswers(transport.label,result.answers,context),output}catch(error){return output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error),`${transport.label} error`),output}}export{classifySystemOne};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{FileAuthStorageBackend,JSON_RPC_ERROR_CODES,LATEST_PROTOCOL_VERSION,McpAuthRequiredError,McpClient,McpError,McpHttpError,McpSessionExpiredError,StdioTransport,StreamableHttpTransport,isClientMetadataDocumentCallback,isObject,mcpNamespace,require_proper_lockfile,resolveConfigValueOrThrow,resolveHeadersOrThrow}from"./chunk-INTHKDF2.js";import{sliceTail}from"./chunk-RJRIMI6M.js";import{APP_NAME,VERSION,getAgentDir}from"./chunk-B3FUE2LF.js";import{__toESM}from"./chunk-JXWJOIH4.js";import{homedir}from"node:os";import{basename,join as join2,resolve}from"node:path";import{setTimeout as sleep}from"node:timers/promises";import{pathToFileURL}from"node:url";import{createHash}from"node:crypto";var MemoryOAuthStateStore=class{value;load(){return this.value===void 0?void 0:structuredClone(this.value)}save(state){this.value=structuredClone(state)}},McpOAuthProvider=class{redirectUrl;clientMetadata;clientMetadataDocument;serverUrl;configuredClient;store;onRedirect;writes=Promise.resolve();constructor(options){this.serverUrl=String(new URL(options.serverUrl)),this.redirectUrl=String(options.redirectUrl),this.clientMetadata={...options.clientMetadata,redirect_uris:options.clientMetadata.redirect_uris??[this.redirectUrl],grant_types:options.clientMetadata.grant_types??["authorization_code","refresh_token"],response_types:options.clientMetadata.response_types??["code"],token_endpoint_auth_method:options.clientMetadata.token_endpoint_auth_method??(options.clientSecret?"client_secret_post":"none")},this.clientMetadataDocument=options.clientMetadataDocument,this.configuredClient=options.clientId?{client_id:options.clientId,...options.clientSecret?{client_secret:options.clientSecret}:{}}:void 0,this.store=options.store??new MemoryOAuthStateStore,this.onRedirect=options.onRedirect}async state(){let existing=(await this.load()).oauthState;if(existing)return existing;let state=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");return await this.update(value=>({...value,oauthState:state})),state}async clientInformation(){return this.configuredClient??(await this.load()).clientInformation}async saveClientInformation(information){this.configuredClient||await this.update(value=>({...value,clientInformation:information}))}async tokens(){return(await this.load()).tokens}async saveTokens(tokens){let expiresAt=tokens.expires_in===void 0?void 0:Date.now()+tokens.expires_in*1e3;await this.update(value=>{let next={...value,tokens};return expiresAt===void 0?delete next.tokensExpireAt:next.tokensExpireAt=expiresAt,next})}async redirectToAuthorization(url){await this.onRedirect(url)}async saveCodeVerifier(verifier){await this.update(value=>({...value,codeVerifier:verifier}))}async codeVerifier(){let verifier=(await this.load()).codeVerifier;if(!verifier)throw new Error("No OAuth PKCE code verifier is stored");return verifier}async invalidateCredentials(kind){await this.update(value=>{let next={...value};return(kind==="all"||kind==="client")&&delete next.clientInformation,(kind==="all"||kind==="tokens")&&(delete next.tokens,delete next.tokensExpireAt),(kind==="all"||kind==="verifier")&&delete next.codeVerifier,(kind==="all"||kind==="discovery")&&delete next.discovery,kind==="all"&&delete next.oauthState,next})}async saveDiscoveryState(discovery){await this.update(value=>({...value,discovery}))}async discoveryState(){return(await this.load()).discovery}async load(){return await this.writes,this.own(await this.store.load())}async update(update){this.writes=this.writes.then(async()=>{await this.store.save(update(this.own(await this.store.load())))}),await this.writes}own(state){return state?.serverUrl===this.serverUrl?state:{serverUrl:this.serverUrl}}};function createOAuthClientProvider(options,redirectUrl,onRedirect=()=>{}){let{serverUrl,settings,clientMetadataDocuments:documents}=options;return new McpOAuthProvider({serverUrl,redirectUrl,clientMetadata:{client_name:settings.clientName??options.clientName},clientMetadataDocument:offersClientMetadataDocument(settings,documents,redirectUrl)?metadata=>{if(!documents?.listsRedirectUrl(redirectUrl))throw new Error(`oauth.clientRegistration "cimd" needs Client ID Metadata Documents that list the redirect URI ${redirectUrl}`);let document=clientMetadataDocument(serverUrl,redirectUrl,metadata,documents.baseUrl);if(!document&&settings.clientRegistration==="cimd")throw new Error('The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration "cimd"');return document}:void 0,clientId:settings.clientId,clientSecret:settings.clientSecret,store:options.store,onRedirect})}function offersClientMetadataDocument(settings,documents,redirectUrl){let registration=settings.clientRegistration??"auto";return registration!=="auto"?registration==="cimd":!settings.clientId&&!settings.clientName&&documents?.listsRedirectUrl(redirectUrl)===!0}function clientMetadataDocument(serverUrl,redirectUrl,metadata,baseUrl){if(!metadata?.client_id_metadata_document_supported||!metadata.token_endpoint_auth_methods_supported?.includes("none"))return;if(metadata.authorization_response_iss_parameter_supported)return{url:`${baseUrl}/client.json`,redirectUrl};let redirect=new URL(redirectUrl);return redirect.pathname=serverSpecificPath(redirect.pathname,serverUrl),{url:`${baseUrl}/${callbackId(serverUrl)}/client.json`,redirectUrl:redirect.href}}function serverSpecificPath(path,serverUrl){return`${path.replace(/\/$/,"")}/${callbackId(serverUrl)}`}function callbackId(serverUrl){let url=new URL(serverUrl);return url.hash="",createHash("sha256").update(url.href).digest().subarray(0,9).toString("base64url")}function registeredRedirectUrls(client){return client&&"redirect_uris"in client?client.redirect_uris:[]}var OAUTH_REQUEST_TIMEOUT_MS=15e3;function timedFetch(fetch=globalThis.fetch){return(input,init)=>{let timeout=AbortSignal.timeout(OAUTH_REQUEST_TIMEOUT_MS);return fetch(input,{...init,signal:init?.signal?AbortSignal.any([init.signal,timeout]):timeout})}}var CALLBACK_HOST="127.0.0.1",CALLBACK_PATH="/callback",DEFAULT_REDIRECT_URL=`http://${CALLBACK_HOST}${CALLBACK_PATH}`;function loopbackSettings(settings){let configured=settings.callbackUrl??DEFAULT_REDIRECT_URL,url=new URL(configured),address=url.hostname.replace(/^\[|\]$/g,""),port=url.port?Number(url.port):settings.callbackPort,fixedRedirectUrl;return url.port?fixedRedirectUrl=settings.callbackUrl:port!==void 0&&(url.port=String(port),fixedRedirectUrl=url.href),{url:configured,host:address==="localhost"?CALLBACK_HOST:address,redirectHost:address,port,path:url.pathname,fixedRedirectUrl}}var OAuthError=class extends Error{code;errorUri;constructor(code,message,errorUri){super(message||code),this.name="OAuthError",this.code=code,this.errorUri=errorUri}},OAuthIssuerMismatchError=class extends Error{expected;received;constructor(expected,received){let format=issuer=>issuer===void 0?"none":JSON.stringify(issuer);super(`OAuth issuer mismatch: expected ${format(expected)}, received ${format(received)}`),this.name="OAuthIssuerMismatchError",this.expected=expected,this.received=received}},OAuthInsecureEndpointError=class extends Error{endpoint;constructor(endpoint){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`),this.name="OAuthInsecureEndpointError",this.endpoint=endpoint}},OAuthRegistrationError=class extends Error{status;body;constructor(status,body){super(`OAuth dynamic client registration failed with status ${status}: ${body}`),this.name="OAuthRegistrationError",this.status=status,this.body=body}},McpOAuthAuthorizationRequiredError=class extends Error{constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}},McpRefreshLockBusyError=class extends Error{constructor(){super("Another process is refreshing the MCP server's tokens"),this.name="McpRefreshLockBusyError"}};function object(value,name){if(!isObject(value))throw new Error(`Invalid ${name}`);return value}function compact(value){return Object.fromEntries(Object.entries(value).filter(([,item])=>item!==void 0))}function requiredString(value,name){if(typeof value!="string"||value.length===0)throw new Error(`Invalid ${name}`);return value}function absent(value){return value==null||value===""}function optionalString(value,name){if(!absent(value))return requiredString(value,name)}function optionalStrings(value,name){if(value!=null){if(!Array.isArray(value)||value.some(item=>typeof item!="string"))throw new Error(`Invalid ${name}`);return[...value]}}function safeUrl(value,name){let text=requiredString(value,name);if(!URL.canParse(text)||!isHttpUrl(new URL(text)))throw new Error(`Invalid ${name}`);return text}function isHttpUrl(url){return url.protocol==="http:"||url.protocol==="https:"}function optionalUrl(value,name){return absent(value)?void 0:safeUrl(value,name)}function parseProtectedResourceMetadata(value){let input=object(value,"OAuth protected resource metadata");return compact({...input,resource:safeUrl(input.resource,"OAuth protected resource metadata resource"),authorization_servers:optionalStrings(input.authorization_servers,"authorization_servers")?.map(url=>safeUrl(url,"authorization server URL")),scopes_supported:optionalStrings(input.scopes_supported,"scopes_supported")})}function parseAuthorizationServerMetadata(value){let input=object(value,"authorization server metadata"),responseTypes=optionalStrings(input.response_types_supported,"response_types_supported");if(!responseTypes)throw new Error("Invalid response_types_supported");return compact({...input,issuer:safeUrl(input.issuer,"authorization server issuer"),authorization_endpoint:safeUrl(input.authorization_endpoint,"authorization endpoint"),token_endpoint:safeUrl(input.token_endpoint,"token endpoint"),registration_endpoint:optionalUrl(input.registration_endpoint,"registration endpoint"),scopes_supported:optionalStrings(input.scopes_supported,"scopes_supported"),response_types_supported:responseTypes,grant_types_supported:optionalStrings(input.grant_types_supported,"grant_types_supported"),token_endpoint_auth_methods_supported:optionalStrings(input.token_endpoint_auth_methods_supported,"token_endpoint_auth_methods_supported"),code_challenge_methods_supported:optionalStrings(input.code_challenge_methods_supported,"code_challenge_methods_supported"),client_id_metadata_document_supported:typeof input.client_id_metadata_document_supported=="boolean"?input.client_id_metadata_document_supported:void 0,authorization_response_iss_parameter_supported:typeof input.authorization_response_iss_parameter_supported=="boolean"?input.authorization_response_iss_parameter_supported:void 0})}function parseOAuthTokens(value){let input=object(value,"OAuth token response"),expires=absent(input.expires_in)?void 0:Number(input.expires_in);if(expires!==void 0&&!Number.isFinite(expires))throw new Error("Invalid expires_in");return compact({access_token:requiredString(input.access_token,"access_token"),token_type:requiredString(input.token_type,"token_type"),expires_in:expires,scope:optionalString(input.scope,"scope"),refresh_token:optionalString(input.refresh_token,"refresh_token"),id_token:optionalString(input.id_token,"id_token")})}function parseClientInformation(value){let input=object(value,"OAuth client registration response");return compact({...input,client_id:requiredString(input.client_id,"client_id"),client_secret:optionalString(input.client_secret,"client_secret"),client_id_issued_at:typeof input.client_id_issued_at=="number"?input.client_id_issued_at:void 0,client_secret_expires_at:typeof input.client_secret_expires_at=="number"?input.client_secret_expires_at:void 0,redirect_uris:optionalStrings(input.redirect_uris,"redirect_uris")??[]})}function discard(response){response?.body?.cancel().catch(()=>{})}function isDiscoveryMiss(status){return status>=400&&status<500||status===502}function pathSuffix(pathname){return pathname.endsWith("/")?pathname.slice(0,-1):pathname}function field(header,name){let match=header.match(new RegExp(String.raw`(?:^|[,\s])${name}=(?:"([^"]*)"|([^\s,]+))`,"i"));return match?.[1]||match?.[2]||void 0}function parseWwwAuthenticate(header){if(!header)return{};let scheme=header.trimStart().split(/\s+/,1)[0]?.toLowerCase();if(scheme!=="bearer"&&scheme!=="dpop")return{};let resourceMetadata=field(header,"resource_metadata"),resourceMetadataUrl;if(resourceMetadata)try{resourceMetadataUrl=new URL(resourceMetadata)}catch{}return{resourceMetadataUrl,scope:field(header,"scope"),error:field(header,"error"),errorDescription:field(header,"error_description")}}async function fetchMetadata(url,fetch,protocolVersion,signal){return fetch(url,{headers:{Accept:"application/json","MCP-Protocol-Version":protocolVersion},signal})}async function discoverProtectedResourceMetadata(serverUrl,options={}){let server=new URL(serverUrl),fetch=options.fetch??globalThis.fetch,version=options.protocolVersion??LATEST_PROTOCOL_VERSION,response=await fetchMetadata(options.resourceMetadataUrl?new URL(options.resourceMetadataUrl):new URL(`/.well-known/oauth-protected-resource${pathSuffix(server.pathname)}`,server.origin),fetch,version,options.signal);if(!options.resourceMetadataUrl&&server.pathname!=="/"&&isDiscoveryMiss(response.status)&&(discard(response),response=await fetchMetadata(new URL("/.well-known/oauth-protected-resource",server.origin),fetch,version,options.signal)),!response.ok)throw discard(response),new Error(`HTTP ${response.status} loading OAuth protected resource metadata`);return parseProtectedResourceMetadata(await response.json())}function buildAuthorizationServerDiscoveryUrls(authorizationServerUrl){let issuer=new URL(authorizationServerUrl),path=pathSuffix(issuer.pathname),urls=[{url:new URL(`/.well-known/oauth-authorization-server${path}`,issuer.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${path}`,issuer.origin),type:"oidc"}];return path&&urls.push({url:new URL(`${path}/.well-known/openid-configuration`,issuer.origin),type:"oidc"}),urls}async function discoverAuthorizationServerMetadata(authorizationServerUrl,options={}){let fetch=options.fetch??globalThis.fetch;for(let{url}of buildAuthorizationServerDiscoveryUrls(authorizationServerUrl)){let response=await fetchMetadata(url,fetch,options.protocolVersion??LATEST_PROTOCOL_VERSION,options.signal);if(!response.ok){if(discard(response),isDiscoveryMiss(response.status))continue;throw new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`)}let metadata=parseAuthorizationServerMetadata(await response.json());if(!options.skipIssuerValidation){let expected=String(authorizationServerUrl),trim=value=>value.endsWith("/")?value.slice(0,-1):value;if(trim(metadata.issuer)!==trim(expected))throw new OAuthIssuerMismatchError(expected,metadata.issuer)}return metadata}}async function discoverOAuthServerInfo(serverUrl,options={}){let resourceMetadata;try{resourceMetadata=await discoverProtectedResourceMetadata(serverUrl,{resourceMetadataUrl:options.resourceMetadataUrl,fetch:options.fetch,signal:options.signal})}catch(error){if(error instanceof TypeError)throw error}if(options.authorizationServerMetadataUrl){let url=options.authorizationServerMetadataUrl,response=await fetchMetadata(url,options.fetch??globalThis.fetch,LATEST_PROTOCOL_VERSION,options.signal);if(!response.ok)throw discard(response),new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`);let metadata=parseAuthorizationServerMetadata(await response.json());return{authorizationServerUrl:metadata.issuer,authorizationServerMetadata:metadata,resourceMetadata}}let authorizationServerUrl=resourceMetadata?.authorization_servers?.[0]??String(new URL("/",serverUrl));return{authorizationServerUrl,authorizationServerMetadata:await discoverAuthorizationServerMetadata(authorizationServerUrl,{fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation,signal:options.signal}),resourceMetadata}}function resourceUrlFromServerUrl(value){let url=new URL(value);return url.hash="",url}function selectResource(serverUrl,metadata){if(!metadata)return;let requested=resourceUrlFromServerUrl(serverUrl),configured=new URL(metadata.resource);if(requested.origin!==configured.origin)throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);let requestedPath=requested.pathname.endsWith("/")?requested.pathname:`${requested.pathname}/`,configuredPath=configured.pathname.endsWith("/")?configured.pathname:`${configured.pathname}/`;if(!requestedPath.startsWith(configuredPath))throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);return metadata.resource}function loopback(hostname){return hostname==="localhost"||hostname==="127.0.0.1"||hostname==="[::1]"||hostname==="::1"}function applicationType(redirectUris){return redirectUris.some(uri=>{if(!URL.canParse(uri))return!1;let url=new URL(uri);return url.protocol!=="http:"&&url.protocol!=="https:"||loopback(url.hostname)})?"native":"web"}function secureEndpoint(value){let url=new URL(value);if(url.protocol!=="https:"&&!loopback(url.hostname))throw new OAuthInsecureEndpointError(url.href);return url}function selectClientAuthMethod(information,supported){let hinted="token_endpoint_auth_method"in information?information.token_endpoint_auth_method:void 0;return hinted&&["client_secret_basic","client_secret_post","none"].includes(hinted)&&(supported.length===0||supported.includes(hinted))?hinted:supported.length===0?information.client_secret?"client_secret_basic":"none":information.client_secret&&supported.includes("client_secret_basic")?"client_secret_basic":information.client_secret&&supported.includes("client_secret_post")?"client_secret_post":supported.includes("none")?"none":information.client_secret?"client_secret_post":"none"}function applyClientAuthentication(method,information,headers,params){if(method==="client_secret_basic"){if(!information.client_secret)throw new Error("client_secret_basic requires a client secret");headers.set("Authorization",`Basic ${Buffer.from(`${information.client_id}:${information.client_secret}`).toString("base64")}`)}else params.set("client_id",information.client_id),method==="client_secret_post"&&information.client_secret&&params.set("client_secret",information.client_secret)}async function pkce(){let bytes=crypto.getRandomValues(new Uint8Array(32)),verifier=Buffer.from(bytes).toString("base64url"),digest=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(verifier));return{verifier,challenge:Buffer.from(digest).toString("base64url")}}async function startAuthorization(authorizationServerUrl,options){let metadata=options.metadata;if(metadata&&!metadata.response_types_supported.includes("code"))throw new Error("Authorization server does not support authorization codes");if(metadata?.code_challenge_methods_supported&&!metadata.code_challenge_methods_supported.includes("S256"))throw new Error("Authorization server does not support PKCE S256");let url=new URL(metadata?.authorization_endpoint??new URL("/authorize",authorizationServerUrl));if(!isHttpUrl(url))throw new Error(`Invalid authorization endpoint ${url.href}`);let{verifier,challenge}=await pkce();return url.searchParams.set("response_type","code"),url.searchParams.set("client_id",options.clientInformation.client_id),url.searchParams.set("code_challenge",challenge),url.searchParams.set("code_challenge_method","S256"),url.searchParams.set("redirect_uri",String(options.redirectUrl)),options.state&&url.searchParams.set("state",options.state),options.scope&&url.searchParams.set("scope",options.scope),options.scope?.split(/\s+/).includes("offline_access")&&url.searchParams.set("prompt","consent"),options.resource&&url.searchParams.set("resource",options.resource),{authorizationUrl:url,codeVerifier:verifier}}async function tokenRequest(authorizationServerUrl,options,params){let url=secureEndpoint(options.metadata?.token_endpoint??new URL("/token",authorizationServerUrl)),headers=new Headers({Accept:"application/json","content-type":"application/x-www-form-urlencoded"});options.resource&&params.set("resource",options.resource),options.addClientAuthentication?await options.addClientAuthentication(headers,params,url,options.metadata):applyClientAuthentication(selectClientAuthMethod(options.clientInformation,options.metadata?.token_endpoint_auth_methods_supported??[]),options.clientInformation,headers,params);let response=await(options.fetch??globalThis.fetch)(url,{method:"POST",headers,body:params,signal:options.signal}),text=await response.text(),value;try{value=JSON.parse(text)}catch{}if(isObject(value)&&typeof value.error=="string")throw new OAuthError(value.error,typeof value.error_description=="string"?value.error_description:value.error,typeof value.error_uri=="string"?value.error_uri:void 0);if(!response.ok)throw new OAuthError("server_error",`HTTP ${response.status}: ${text}`);return parseOAuthTokens(value)}async function registerClient(authorizationServerUrl,options){let endpoint=options.metadata?.registration_endpoint;if(options.metadata&&!endpoint)throw new Error("Authorization server does not support dynamic client registration");let response=await(options.fetch??globalThis.fetch)(new URL(endpoint??new URL("/register",authorizationServerUrl)),{method:"POST",headers:{Accept:"application/json","content-type":"application/json"},body:JSON.stringify({...options.clientMetadata,application_type:options.clientMetadata.application_type??applicationType(options.clientMetadata.redirect_uris),...options.scope?{scope:options.scope}:{}}),signal:options.signal});if(!response.ok)throw new OAuthRegistrationError(response.status,await response.text());return parseClientInformation(await response.json())}async function exchangeAuthorizationCode(authorizationServerUrl,options){return tokenRequest(authorizationServerUrl,options,new URLSearchParams({grant_type:"authorization_code",code:options.code,code_verifier:options.codeVerifier,redirect_uri:String(options.redirectUrl)}))}async function refreshAuthorization(authorizationServerUrl,options){let tokens=await tokenRequest(authorizationServerUrl,options,new URLSearchParams({grant_type:"refresh_token",refresh_token:options.refreshToken}));return{refresh_token:options.refreshToken,...tokens}}function withScope(tokens,scope){return tokens.scope===void 0&&scope?{...tokens,scope}:tokens}function stepUpScope(granted,challenged){if(!challenged)return;let scopes=[granted,challenged].flatMap(scope=>scope?.split(/\s+/).filter(Boolean)??[]);return[...new Set(scopes)].join(" ")}async function runFlow(provider,options,use={}){let metadataUrl=options.authorizationServerMetadataUrl&&secureEndpoint(options.authorizationServerMetadataUrl),cached=metadataUrl?void 0:await provider.discoveryState?.(),discovered=cached?.authorizationServerUrl?{authorizationServerUrl:cached.authorizationServerUrl,authorizationServerMetadata:cached.authorizationServerMetadata??await discoverAuthorizationServerMetadata(cached.authorizationServerUrl,{fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation,signal:options.signal}),resourceMetadata:cached.resourceMetadata}:await discoverOAuthServerInfo(options.serverUrl,{resourceMetadataUrl:options.resourceMetadataUrl,authorizationServerMetadataUrl:metadataUrl,fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation,signal:options.signal});metadataUrl||await provider.saveDiscoveryState?.({...discovered,...options.resourceMetadataUrl?{resourceMetadataUrl:options.resourceMetadataUrl.href}:{}});let metadata=discovered.authorizationServerMetadata,resource=selectResource(options.serverUrl,discovered.resourceMetadata),scope=options.scope||discovered.resourceMetadata?.scopes_supported?.join(" ")||provider.clientMetadata.scope,stored=await provider.clientInformation();use.storedClientId=stored?.client_id;let clientDocument=stored?void 0:provider.clientMetadataDocument?.(metadata);if(clientDocument){let url=new URL(clientDocument.url);if(url.protocol!=="https:"||url.pathname==="/")throw new Error("Invalid OAuth client metadata URL")}let redirectUrl=clientDocument?.redirectUrl??String(provider.redirectUrl);if(options.authorizationCode&&options.authorizationRedirectUrl!==void 0&&redirectUrl!==options.authorizationRedirectUrl)throw new Error(`The code exchange would use the redirect URI ${redirectUrl}, but the authorization request used ${options.authorizationRedirectUrl}`);let client=stored??(clientDocument&&{client_id:clientDocument.url});if(!client){if(options.refreshOnly)return"REDIRECT";if(options.authorizationCode)throw new Error("OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed");if(!provider.saveClientInformation)throw new Error("OAuth client information cannot be persisted");client=await registerClient(discovered.authorizationServerUrl,{metadata,clientMetadata:provider.clientMetadata,scope,fetch:options.fetch,signal:options.signal}),await provider.saveClientInformation(client)}let tokenOptions={metadata,clientInformation:client,resource,addClientAuthentication:provider.addClientAuthentication,fetch:options.fetch,signal:options.signal};if(options.authorizationCode){let iss=options.iss;if((iss!==void 0||metadata?.authorization_response_iss_parameter_supported)&&iss!==metadata?.issuer)throw new OAuthIssuerMismatchError(metadata?.issuer,iss);let tokens=await exchangeAuthorizationCode(discovered.authorizationServerUrl,{...tokenOptions,code:options.authorizationCode,codeVerifier:await provider.codeVerifier(),redirectUrl});return await provider.saveTokens(withScope(tokens,scope)),"AUTHORIZED"}let existing=options.skipRefresh?void 0:await provider.tokens();if(existing?.refresh_token)try{let tokens=await refreshAuthorization(discovered.authorizationServerUrl,{...tokenOptions,refreshToken:existing.refresh_token});return await provider.saveTokens(withScope(tokens,existing.scope)),"AUTHORIZED"}catch(error){if(options.signal?.aborted||error instanceof OAuthInsecureEndpointError||error instanceof OAuthError&&error.code!=="server_error")throw error}if(options.refreshOnly)return"REDIRECT";let state=await provider.state?.(),authorization=await startAuthorization(discovered.authorizationServerUrl,{metadata,clientInformation:client,redirectUrl,scope,state,resource});return await provider.saveCodeVerifier(authorization.codeVerifier),await provider.redirectToAuthorization(authorization.authorizationUrl),"REDIRECT"}async function authorizeMcp(provider,options){let use={};try{return await runFlow(provider,options,use)}catch(error){if(error instanceof OAuthError&&["invalid_client","unauthorized_client"].includes(error.code)){if(options.refreshOnly){if((await provider.clientInformation())?.client_id===use.storedClientId)for(let kind of["client","tokens","discovery"])await provider.invalidateCredentials?.(kind)}else await provider.invalidateCredentials?.("all");return runFlow(provider,options)}if(error instanceof OAuthError&&error.code==="invalid_grant")return await provider.invalidateCredentials?.("tokens"),runFlow(provider,options);throw error}}var REFRESH_SKEW_MS=3e4;function createMcpAuthProvider(options){let{store,redirectUrl}=options,refreshing,refresh=(staleToken,fetch=globalThis.fetch,challenge)=>(refreshing??=store.withRefreshLock(async()=>{let state=await store.load();if(state?.tokens?.access_token!==staleToken)return;if(!state?.tokens?.refresh_token)throw new McpOAuthAuthorizationRequiredError;let client={...options,settings:options.settings()};if(await refreshStoredTokens(client,state,{fetch,challenge,redirectUrl})==="REDIRECT")throw new McpOAuthAuthorizationRequiredError}).finally(()=>{refreshing=void 0}),refreshing);return{token:async()=>{await refreshing?.catch(()=>{});let state=await store.load(),token=state?.tokens?.access_token;return!(state?.tokensExpireAt!==void 0&&state.tokensExpireAt-REFRESH_SKEW_MS<=Date.now())||!state?.tokens?.refresh_token?token:(await refresh(token).catch(()=>{}),(await store.load())?.tokens?.access_token)},onUnauthorized:async context=>{let challenge=parseWwwAuthenticate(context.response.headers.get("www-authenticate"));if(options.onChallenge(challenge),challenge.error==="insufficient_scope")throw new McpOAuthAuthorizationRequiredError;await refresh(context.token,context.fetch,challenge)},settled:async()=>{await refreshing?.catch(()=>{})}}}async function refreshStoredTokens(client,state,options={}){let redirectUrl=[options.redirectUrl,loopbackSettings(client.settings).fixedRedirectUrl,registeredRedirectUrls(state.clientInformation)[0]].filter(url=>url!==void 0).find(url=>client.clientMetadataDocuments?.listsRedirectUrl(url))??DEFAULT_REDIRECT_URL;return authorizeMcp(createOAuthClientProvider(client,redirectUrl),{serverUrl:client.serverUrl,resourceMetadataUrl:options.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:client.settings.authServerMetadataUrl,fetch:timedFetch(options.fetch),refreshOnly:!0})}import{createServer}from"node:http";function plainText(page){return page.ok?"Authorization complete. You may close this window.":page.details?`${page.message}
2
+ import{FileAuthStorageBackend,JSON_RPC_ERROR_CODES,LATEST_PROTOCOL_VERSION,McpAuthRequiredError,McpClient,McpError,McpHttpError,McpSessionExpiredError,StdioTransport,StreamableHttpTransport,isClientMetadataDocumentCallback,isObject,mcpNamespace,require_proper_lockfile,resolveConfigValueOrThrow,resolveHeadersOrThrow}from"./chunk-65DC2T66.js";import{sliceTail}from"./chunk-GRYHVZSI.js";import{APP_NAME,VERSION,getAgentDir}from"./chunk-XAA355T2.js";import{__toESM}from"./chunk-JXWJOIH4.js";import{homedir}from"node:os";import{basename,join as join2,resolve}from"node:path";import{setTimeout as sleep}from"node:timers/promises";import{pathToFileURL}from"node:url";import{createHash}from"node:crypto";var MemoryOAuthStateStore=class{value;load(){return this.value===void 0?void 0:structuredClone(this.value)}save(state){this.value=structuredClone(state)}},McpOAuthProvider=class{redirectUrl;clientMetadata;clientMetadataDocument;serverUrl;configuredClient;store;onRedirect;writes=Promise.resolve();constructor(options){this.serverUrl=String(new URL(options.serverUrl)),this.redirectUrl=String(options.redirectUrl),this.clientMetadata={...options.clientMetadata,redirect_uris:options.clientMetadata.redirect_uris??[this.redirectUrl],grant_types:options.clientMetadata.grant_types??["authorization_code","refresh_token"],response_types:options.clientMetadata.response_types??["code"],token_endpoint_auth_method:options.clientMetadata.token_endpoint_auth_method??(options.clientSecret?"client_secret_post":"none")},this.clientMetadataDocument=options.clientMetadataDocument,this.configuredClient=options.clientId?{client_id:options.clientId,...options.clientSecret?{client_secret:options.clientSecret}:{}}:void 0,this.store=options.store??new MemoryOAuthStateStore,this.onRedirect=options.onRedirect}async state(){let existing=(await this.load()).oauthState;if(existing)return existing;let state=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");return await this.update(value=>({...value,oauthState:state})),state}async clientInformation(){return this.configuredClient??(await this.load()).clientInformation}async saveClientInformation(information){this.configuredClient||await this.update(value=>({...value,clientInformation:information}))}async tokens(){return(await this.load()).tokens}async saveTokens(tokens){let expiresAt=tokens.expires_in===void 0?void 0:Date.now()+tokens.expires_in*1e3;await this.update(value=>{let next={...value,tokens};return expiresAt===void 0?delete next.tokensExpireAt:next.tokensExpireAt=expiresAt,next})}async redirectToAuthorization(url){await this.onRedirect(url)}async saveCodeVerifier(verifier){await this.update(value=>({...value,codeVerifier:verifier}))}async codeVerifier(){let verifier=(await this.load()).codeVerifier;if(!verifier)throw new Error("No OAuth PKCE code verifier is stored");return verifier}async invalidateCredentials(kind){await this.update(value=>{let next={...value};return(kind==="all"||kind==="client")&&delete next.clientInformation,(kind==="all"||kind==="tokens")&&(delete next.tokens,delete next.tokensExpireAt),(kind==="all"||kind==="verifier")&&delete next.codeVerifier,(kind==="all"||kind==="discovery")&&delete next.discovery,kind==="all"&&delete next.oauthState,next})}async saveDiscoveryState(discovery){await this.update(value=>({...value,discovery}))}async discoveryState(){return(await this.load()).discovery}async load(){return await this.writes,this.own(await this.store.load())}async update(update){this.writes=this.writes.then(async()=>{await this.store.save(update(this.own(await this.store.load())))}),await this.writes}own(state){return state?.serverUrl===this.serverUrl?state:{serverUrl:this.serverUrl}}};function createOAuthClientProvider(options,redirectUrl,onRedirect=()=>{}){let{serverUrl,settings,clientMetadataDocuments:documents}=options;return new McpOAuthProvider({serverUrl,redirectUrl,clientMetadata:{client_name:settings.clientName??options.clientName},clientMetadataDocument:offersClientMetadataDocument(settings,documents,redirectUrl)?metadata=>{if(!documents?.listsRedirectUrl(redirectUrl))throw new Error(`oauth.clientRegistration "cimd" needs Client ID Metadata Documents that list the redirect URI ${redirectUrl}`);let document=clientMetadataDocument(serverUrl,redirectUrl,metadata,documents.baseUrl);if(!document&&settings.clientRegistration==="cimd")throw new Error('The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration "cimd"');return document}:void 0,clientId:settings.clientId,clientSecret:settings.clientSecret,store:options.store,onRedirect})}function offersClientMetadataDocument(settings,documents,redirectUrl){let registration=settings.clientRegistration??"auto";return registration!=="auto"?registration==="cimd":!settings.clientId&&!settings.clientName&&documents?.listsRedirectUrl(redirectUrl)===!0}function clientMetadataDocument(serverUrl,redirectUrl,metadata,baseUrl){if(!metadata?.client_id_metadata_document_supported||!metadata.token_endpoint_auth_methods_supported?.includes("none"))return;if(metadata.authorization_response_iss_parameter_supported)return{url:`${baseUrl}/client.json`,redirectUrl};let redirect=new URL(redirectUrl);return redirect.pathname=serverSpecificPath(redirect.pathname,serverUrl),{url:`${baseUrl}/${callbackId(serverUrl)}/client.json`,redirectUrl:redirect.href}}function serverSpecificPath(path,serverUrl){return`${path.replace(/\/$/,"")}/${callbackId(serverUrl)}`}function callbackId(serverUrl){let url=new URL(serverUrl);return url.hash="",createHash("sha256").update(url.href).digest().subarray(0,9).toString("base64url")}function registeredRedirectUrls(client){return client&&"redirect_uris"in client?client.redirect_uris:[]}var OAUTH_REQUEST_TIMEOUT_MS=15e3;function timedFetch(fetch=globalThis.fetch){return(input,init)=>{let timeout=AbortSignal.timeout(OAUTH_REQUEST_TIMEOUT_MS);return fetch(input,{...init,signal:init?.signal?AbortSignal.any([init.signal,timeout]):timeout})}}var CALLBACK_HOST="127.0.0.1",CALLBACK_PATH="/callback",DEFAULT_REDIRECT_URL=`http://${CALLBACK_HOST}${CALLBACK_PATH}`;function loopbackSettings(settings){let configured=settings.callbackUrl??DEFAULT_REDIRECT_URL,url=new URL(configured),address=url.hostname.replace(/^\[|\]$/g,""),port=url.port?Number(url.port):settings.callbackPort,fixedRedirectUrl;return url.port?fixedRedirectUrl=settings.callbackUrl:port!==void 0&&(url.port=String(port),fixedRedirectUrl=url.href),{url:configured,host:address==="localhost"?CALLBACK_HOST:address,redirectHost:address,port,path:url.pathname,fixedRedirectUrl}}var OAuthError=class extends Error{code;errorUri;constructor(code,message,errorUri){super(message||code),this.name="OAuthError",this.code=code,this.errorUri=errorUri}},OAuthIssuerMismatchError=class extends Error{expected;received;constructor(expected,received){let format=issuer=>issuer===void 0?"none":JSON.stringify(issuer);super(`OAuth issuer mismatch: expected ${format(expected)}, received ${format(received)}`),this.name="OAuthIssuerMismatchError",this.expected=expected,this.received=received}},OAuthInsecureEndpointError=class extends Error{endpoint;constructor(endpoint){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`),this.name="OAuthInsecureEndpointError",this.endpoint=endpoint}},OAuthRegistrationError=class extends Error{status;body;constructor(status,body){super(`OAuth dynamic client registration failed with status ${status}: ${body}`),this.name="OAuthRegistrationError",this.status=status,this.body=body}},McpOAuthAuthorizationRequiredError=class extends Error{constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}},McpRefreshLockBusyError=class extends Error{constructor(){super("Another process is refreshing the MCP server's tokens"),this.name="McpRefreshLockBusyError"}};function object(value,name){if(!isObject(value))throw new Error(`Invalid ${name}`);return value}function compact(value){return Object.fromEntries(Object.entries(value).filter(([,item])=>item!==void 0))}function requiredString(value,name){if(typeof value!="string"||value.length===0)throw new Error(`Invalid ${name}`);return value}function absent(value){return value==null||value===""}function optionalString(value,name){if(!absent(value))return requiredString(value,name)}function optionalStrings(value,name){if(value!=null){if(!Array.isArray(value)||value.some(item=>typeof item!="string"))throw new Error(`Invalid ${name}`);return[...value]}}function safeUrl(value,name){let text=requiredString(value,name);if(!URL.canParse(text)||!isHttpUrl(new URL(text)))throw new Error(`Invalid ${name}`);return text}function isHttpUrl(url){return url.protocol==="http:"||url.protocol==="https:"}function optionalUrl(value,name){return absent(value)?void 0:safeUrl(value,name)}function parseProtectedResourceMetadata(value){let input=object(value,"OAuth protected resource metadata");return compact({...input,resource:safeUrl(input.resource,"OAuth protected resource metadata resource"),authorization_servers:optionalStrings(input.authorization_servers,"authorization_servers")?.map(url=>safeUrl(url,"authorization server URL")),scopes_supported:optionalStrings(input.scopes_supported,"scopes_supported")})}function parseAuthorizationServerMetadata(value){let input=object(value,"authorization server metadata"),responseTypes=optionalStrings(input.response_types_supported,"response_types_supported");if(!responseTypes)throw new Error("Invalid response_types_supported");return compact({...input,issuer:safeUrl(input.issuer,"authorization server issuer"),authorization_endpoint:safeUrl(input.authorization_endpoint,"authorization endpoint"),token_endpoint:safeUrl(input.token_endpoint,"token endpoint"),registration_endpoint:optionalUrl(input.registration_endpoint,"registration endpoint"),scopes_supported:optionalStrings(input.scopes_supported,"scopes_supported"),response_types_supported:responseTypes,grant_types_supported:optionalStrings(input.grant_types_supported,"grant_types_supported"),token_endpoint_auth_methods_supported:optionalStrings(input.token_endpoint_auth_methods_supported,"token_endpoint_auth_methods_supported"),code_challenge_methods_supported:optionalStrings(input.code_challenge_methods_supported,"code_challenge_methods_supported"),client_id_metadata_document_supported:typeof input.client_id_metadata_document_supported=="boolean"?input.client_id_metadata_document_supported:void 0,authorization_response_iss_parameter_supported:typeof input.authorization_response_iss_parameter_supported=="boolean"?input.authorization_response_iss_parameter_supported:void 0})}function parseOAuthTokens(value){let input=object(value,"OAuth token response"),expires=absent(input.expires_in)?void 0:Number(input.expires_in);if(expires!==void 0&&!Number.isFinite(expires))throw new Error("Invalid expires_in");return compact({access_token:requiredString(input.access_token,"access_token"),token_type:requiredString(input.token_type,"token_type"),expires_in:expires,scope:optionalString(input.scope,"scope"),refresh_token:optionalString(input.refresh_token,"refresh_token"),id_token:optionalString(input.id_token,"id_token")})}function parseClientInformation(value){let input=object(value,"OAuth client registration response");return compact({...input,client_id:requiredString(input.client_id,"client_id"),client_secret:optionalString(input.client_secret,"client_secret"),client_id_issued_at:typeof input.client_id_issued_at=="number"?input.client_id_issued_at:void 0,client_secret_expires_at:typeof input.client_secret_expires_at=="number"?input.client_secret_expires_at:void 0,redirect_uris:optionalStrings(input.redirect_uris,"redirect_uris")??[]})}function discard(response){response?.body?.cancel().catch(()=>{})}function isDiscoveryMiss(status){return status>=400&&status<500||status===502}function pathSuffix(pathname){return pathname.endsWith("/")?pathname.slice(0,-1):pathname}function field(header,name){let match=header.match(new RegExp(String.raw`(?:^|[,\s])${name}=(?:"([^"]*)"|([^\s,]+))`,"i"));return match?.[1]||match?.[2]||void 0}function parseWwwAuthenticate(header){if(!header)return{};let scheme=header.trimStart().split(/\s+/,1)[0]?.toLowerCase();if(scheme!=="bearer"&&scheme!=="dpop")return{};let resourceMetadata=field(header,"resource_metadata"),resourceMetadataUrl;if(resourceMetadata)try{resourceMetadataUrl=new URL(resourceMetadata)}catch{}return{resourceMetadataUrl,scope:field(header,"scope"),error:field(header,"error"),errorDescription:field(header,"error_description")}}async function fetchMetadata(url,fetch,protocolVersion,signal){return fetch(url,{headers:{Accept:"application/json","MCP-Protocol-Version":protocolVersion},signal})}async function discoverProtectedResourceMetadata(serverUrl,options={}){let server=new URL(serverUrl),fetch=options.fetch??globalThis.fetch,version=options.protocolVersion??LATEST_PROTOCOL_VERSION,response=await fetchMetadata(options.resourceMetadataUrl?new URL(options.resourceMetadataUrl):new URL(`/.well-known/oauth-protected-resource${pathSuffix(server.pathname)}`,server.origin),fetch,version,options.signal);if(!options.resourceMetadataUrl&&server.pathname!=="/"&&isDiscoveryMiss(response.status)&&(discard(response),response=await fetchMetadata(new URL("/.well-known/oauth-protected-resource",server.origin),fetch,version,options.signal)),!response.ok)throw discard(response),new Error(`HTTP ${response.status} loading OAuth protected resource metadata`);return parseProtectedResourceMetadata(await response.json())}function buildAuthorizationServerDiscoveryUrls(authorizationServerUrl){let issuer=new URL(authorizationServerUrl),path=pathSuffix(issuer.pathname),urls=[{url:new URL(`/.well-known/oauth-authorization-server${path}`,issuer.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${path}`,issuer.origin),type:"oidc"}];return path&&urls.push({url:new URL(`${path}/.well-known/openid-configuration`,issuer.origin),type:"oidc"}),urls}async function discoverAuthorizationServerMetadata(authorizationServerUrl,options={}){let fetch=options.fetch??globalThis.fetch;for(let{url}of buildAuthorizationServerDiscoveryUrls(authorizationServerUrl)){let response=await fetchMetadata(url,fetch,options.protocolVersion??LATEST_PROTOCOL_VERSION,options.signal);if(!response.ok){if(discard(response),isDiscoveryMiss(response.status))continue;throw new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`)}let metadata=parseAuthorizationServerMetadata(await response.json());if(!options.skipIssuerValidation){let expected=String(authorizationServerUrl),trim=value=>value.endsWith("/")?value.slice(0,-1):value;if(trim(metadata.issuer)!==trim(expected))throw new OAuthIssuerMismatchError(expected,metadata.issuer)}return metadata}}async function discoverOAuthServerInfo(serverUrl,options={}){let resourceMetadata;try{resourceMetadata=await discoverProtectedResourceMetadata(serverUrl,{resourceMetadataUrl:options.resourceMetadataUrl,fetch:options.fetch,signal:options.signal})}catch(error){if(error instanceof TypeError)throw error}if(options.authorizationServerMetadataUrl){let url=options.authorizationServerMetadataUrl,response=await fetchMetadata(url,options.fetch??globalThis.fetch,LATEST_PROTOCOL_VERSION,options.signal);if(!response.ok)throw discard(response),new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`);let metadata=parseAuthorizationServerMetadata(await response.json());return{authorizationServerUrl:metadata.issuer,authorizationServerMetadata:metadata,resourceMetadata}}let authorizationServerUrl=resourceMetadata?.authorization_servers?.[0]??String(new URL("/",serverUrl));return{authorizationServerUrl,authorizationServerMetadata:await discoverAuthorizationServerMetadata(authorizationServerUrl,{fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation,signal:options.signal}),resourceMetadata}}function resourceUrlFromServerUrl(value){let url=new URL(value);return url.hash="",url}function selectResource(serverUrl,metadata){if(!metadata)return;let requested=resourceUrlFromServerUrl(serverUrl),configured=new URL(metadata.resource);if(requested.origin!==configured.origin)throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);let requestedPath=requested.pathname.endsWith("/")?requested.pathname:`${requested.pathname}/`,configuredPath=configured.pathname.endsWith("/")?configured.pathname:`${configured.pathname}/`;if(!requestedPath.startsWith(configuredPath))throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);return metadata.resource}function loopback(hostname){return hostname==="localhost"||hostname==="127.0.0.1"||hostname==="[::1]"||hostname==="::1"}function applicationType(redirectUris){return redirectUris.some(uri=>{if(!URL.canParse(uri))return!1;let url=new URL(uri);return url.protocol!=="http:"&&url.protocol!=="https:"||loopback(url.hostname)})?"native":"web"}function secureEndpoint(value){let url=new URL(value);if(url.protocol!=="https:"&&!loopback(url.hostname))throw new OAuthInsecureEndpointError(url.href);return url}function selectClientAuthMethod(information,supported){let hinted="token_endpoint_auth_method"in information?information.token_endpoint_auth_method:void 0;return hinted&&["client_secret_basic","client_secret_post","none"].includes(hinted)&&(supported.length===0||supported.includes(hinted))?hinted:supported.length===0?information.client_secret?"client_secret_basic":"none":information.client_secret&&supported.includes("client_secret_basic")?"client_secret_basic":information.client_secret&&supported.includes("client_secret_post")?"client_secret_post":supported.includes("none")?"none":information.client_secret?"client_secret_post":"none"}function applyClientAuthentication(method,information,headers,params){if(method==="client_secret_basic"){if(!information.client_secret)throw new Error("client_secret_basic requires a client secret");headers.set("Authorization",`Basic ${Buffer.from(`${information.client_id}:${information.client_secret}`).toString("base64")}`)}else params.set("client_id",information.client_id),method==="client_secret_post"&&information.client_secret&&params.set("client_secret",information.client_secret)}async function pkce(){let bytes=crypto.getRandomValues(new Uint8Array(32)),verifier=Buffer.from(bytes).toString("base64url"),digest=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(verifier));return{verifier,challenge:Buffer.from(digest).toString("base64url")}}async function startAuthorization(authorizationServerUrl,options){let metadata=options.metadata;if(metadata&&!metadata.response_types_supported.includes("code"))throw new Error("Authorization server does not support authorization codes");if(metadata?.code_challenge_methods_supported&&!metadata.code_challenge_methods_supported.includes("S256"))throw new Error("Authorization server does not support PKCE S256");let url=new URL(metadata?.authorization_endpoint??new URL("/authorize",authorizationServerUrl));if(!isHttpUrl(url))throw new Error(`Invalid authorization endpoint ${url.href}`);let{verifier,challenge}=await pkce();return url.searchParams.set("response_type","code"),url.searchParams.set("client_id",options.clientInformation.client_id),url.searchParams.set("code_challenge",challenge),url.searchParams.set("code_challenge_method","S256"),url.searchParams.set("redirect_uri",String(options.redirectUrl)),options.state&&url.searchParams.set("state",options.state),options.scope&&url.searchParams.set("scope",options.scope),options.scope?.split(/\s+/).includes("offline_access")&&url.searchParams.set("prompt","consent"),options.resource&&url.searchParams.set("resource",options.resource),{authorizationUrl:url,codeVerifier:verifier}}async function tokenRequest(authorizationServerUrl,options,params){let url=secureEndpoint(options.metadata?.token_endpoint??new URL("/token",authorizationServerUrl)),headers=new Headers({Accept:"application/json","content-type":"application/x-www-form-urlencoded"});options.resource&&params.set("resource",options.resource),options.addClientAuthentication?await options.addClientAuthentication(headers,params,url,options.metadata):applyClientAuthentication(selectClientAuthMethod(options.clientInformation,options.metadata?.token_endpoint_auth_methods_supported??[]),options.clientInformation,headers,params);let response=await(options.fetch??globalThis.fetch)(url,{method:"POST",headers,body:params,signal:options.signal}),text=await response.text(),value;try{value=JSON.parse(text)}catch{}if(isObject(value)&&typeof value.error=="string")throw new OAuthError(value.error,typeof value.error_description=="string"?value.error_description:value.error,typeof value.error_uri=="string"?value.error_uri:void 0);if(!response.ok)throw new OAuthError("server_error",`HTTP ${response.status}: ${text}`);return parseOAuthTokens(value)}async function registerClient(authorizationServerUrl,options){let endpoint=options.metadata?.registration_endpoint;if(options.metadata&&!endpoint)throw new Error("Authorization server does not support dynamic client registration");let response=await(options.fetch??globalThis.fetch)(new URL(endpoint??new URL("/register",authorizationServerUrl)),{method:"POST",headers:{Accept:"application/json","content-type":"application/json"},body:JSON.stringify({...options.clientMetadata,application_type:options.clientMetadata.application_type??applicationType(options.clientMetadata.redirect_uris),...options.scope?{scope:options.scope}:{}}),signal:options.signal});if(!response.ok)throw new OAuthRegistrationError(response.status,await response.text());return parseClientInformation(await response.json())}async function exchangeAuthorizationCode(authorizationServerUrl,options){return tokenRequest(authorizationServerUrl,options,new URLSearchParams({grant_type:"authorization_code",code:options.code,code_verifier:options.codeVerifier,redirect_uri:String(options.redirectUrl)}))}async function refreshAuthorization(authorizationServerUrl,options){let tokens=await tokenRequest(authorizationServerUrl,options,new URLSearchParams({grant_type:"refresh_token",refresh_token:options.refreshToken}));return{refresh_token:options.refreshToken,...tokens}}function withScope(tokens,scope){return tokens.scope===void 0&&scope?{...tokens,scope}:tokens}function stepUpScope(granted,challenged){if(!challenged)return;let scopes=[granted,challenged].flatMap(scope=>scope?.split(/\s+/).filter(Boolean)??[]);return[...new Set(scopes)].join(" ")}async function runFlow(provider,options,use={}){let metadataUrl=options.authorizationServerMetadataUrl&&secureEndpoint(options.authorizationServerMetadataUrl),cached=metadataUrl?void 0:await provider.discoveryState?.(),discovered=cached?.authorizationServerUrl?{authorizationServerUrl:cached.authorizationServerUrl,authorizationServerMetadata:cached.authorizationServerMetadata??await discoverAuthorizationServerMetadata(cached.authorizationServerUrl,{fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation,signal:options.signal}),resourceMetadata:cached.resourceMetadata}:await discoverOAuthServerInfo(options.serverUrl,{resourceMetadataUrl:options.resourceMetadataUrl,authorizationServerMetadataUrl:metadataUrl,fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation,signal:options.signal});metadataUrl||await provider.saveDiscoveryState?.({...discovered,...options.resourceMetadataUrl?{resourceMetadataUrl:options.resourceMetadataUrl.href}:{}});let metadata=discovered.authorizationServerMetadata,resource=selectResource(options.serverUrl,discovered.resourceMetadata),scope=options.scope||discovered.resourceMetadata?.scopes_supported?.join(" ")||provider.clientMetadata.scope,stored=await provider.clientInformation();use.storedClientId=stored?.client_id;let clientDocument=stored?void 0:provider.clientMetadataDocument?.(metadata);if(clientDocument){let url=new URL(clientDocument.url);if(url.protocol!=="https:"||url.pathname==="/")throw new Error("Invalid OAuth client metadata URL")}let redirectUrl=clientDocument?.redirectUrl??String(provider.redirectUrl);if(options.authorizationCode&&options.authorizationRedirectUrl!==void 0&&redirectUrl!==options.authorizationRedirectUrl)throw new Error(`The code exchange would use the redirect URI ${redirectUrl}, but the authorization request used ${options.authorizationRedirectUrl}`);let client=stored??(clientDocument&&{client_id:clientDocument.url});if(!client){if(options.refreshOnly)return"REDIRECT";if(options.authorizationCode)throw new Error("OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed");if(!provider.saveClientInformation)throw new Error("OAuth client information cannot be persisted");client=await registerClient(discovered.authorizationServerUrl,{metadata,clientMetadata:provider.clientMetadata,scope,fetch:options.fetch,signal:options.signal}),await provider.saveClientInformation(client)}let tokenOptions={metadata,clientInformation:client,resource,addClientAuthentication:provider.addClientAuthentication,fetch:options.fetch,signal:options.signal};if(options.authorizationCode){let iss=options.iss;if((iss!==void 0||metadata?.authorization_response_iss_parameter_supported)&&iss!==metadata?.issuer)throw new OAuthIssuerMismatchError(metadata?.issuer,iss);let tokens=await exchangeAuthorizationCode(discovered.authorizationServerUrl,{...tokenOptions,code:options.authorizationCode,codeVerifier:await provider.codeVerifier(),redirectUrl});return await provider.saveTokens(withScope(tokens,scope)),"AUTHORIZED"}let existing=options.skipRefresh?void 0:await provider.tokens();if(existing?.refresh_token)try{let tokens=await refreshAuthorization(discovered.authorizationServerUrl,{...tokenOptions,refreshToken:existing.refresh_token});return await provider.saveTokens(withScope(tokens,existing.scope)),"AUTHORIZED"}catch(error){if(options.signal?.aborted||error instanceof OAuthInsecureEndpointError||error instanceof OAuthError&&error.code!=="server_error")throw error}if(options.refreshOnly)return"REDIRECT";let state=await provider.state?.(),authorization=await startAuthorization(discovered.authorizationServerUrl,{metadata,clientInformation:client,redirectUrl,scope,state,resource});return await provider.saveCodeVerifier(authorization.codeVerifier),await provider.redirectToAuthorization(authorization.authorizationUrl),"REDIRECT"}async function authorizeMcp(provider,options){let use={};try{return await runFlow(provider,options,use)}catch(error){if(error instanceof OAuthError&&["invalid_client","unauthorized_client"].includes(error.code)){if(options.refreshOnly){if((await provider.clientInformation())?.client_id===use.storedClientId)for(let kind of["client","tokens","discovery"])await provider.invalidateCredentials?.(kind)}else await provider.invalidateCredentials?.("all");return runFlow(provider,options)}if(error instanceof OAuthError&&error.code==="invalid_grant")return await provider.invalidateCredentials?.("tokens"),runFlow(provider,options);throw error}}var REFRESH_SKEW_MS=3e4;function createMcpAuthProvider(options){let{store,redirectUrl}=options,refreshing,refresh=(staleToken,fetch=globalThis.fetch,challenge)=>(refreshing??=store.withRefreshLock(async()=>{let state=await store.load();if(state?.tokens?.access_token!==staleToken)return;if(!state?.tokens?.refresh_token)throw new McpOAuthAuthorizationRequiredError;let client={...options,settings:options.settings()};if(await refreshStoredTokens(client,state,{fetch,challenge,redirectUrl})==="REDIRECT")throw new McpOAuthAuthorizationRequiredError}).finally(()=>{refreshing=void 0}),refreshing);return{token:async()=>{await refreshing?.catch(()=>{});let state=await store.load(),token=state?.tokens?.access_token;return!(state?.tokensExpireAt!==void 0&&state.tokensExpireAt-REFRESH_SKEW_MS<=Date.now())||!state?.tokens?.refresh_token?token:(await refresh(token).catch(()=>{}),(await store.load())?.tokens?.access_token)},onUnauthorized:async context=>{let challenge=parseWwwAuthenticate(context.response.headers.get("www-authenticate"));if(options.onChallenge(challenge),challenge.error==="insufficient_scope")throw new McpOAuthAuthorizationRequiredError;await refresh(context.token,context.fetch,challenge)},settled:async()=>{await refreshing?.catch(()=>{})}}}async function refreshStoredTokens(client,state,options={}){let redirectUrl=[options.redirectUrl,loopbackSettings(client.settings).fixedRedirectUrl,registeredRedirectUrls(state.clientInformation)[0]].filter(url=>url!==void 0).find(url=>client.clientMetadataDocuments?.listsRedirectUrl(url))??DEFAULT_REDIRECT_URL;return authorizeMcp(createOAuthClientProvider(client,redirectUrl),{serverUrl:client.serverUrl,resourceMetadataUrl:options.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:client.settings.authServerMetadataUrl,fetch:timedFetch(options.fetch),refreshOnly:!0})}import{createServer}from"node:http";function plainText(page){return page.ok?"Authorization complete. You may close this window.":page.details?`${page.message}
3
3
 
4
4
  ${page.details}`:page.message}var OAuthCallbackServer=class _OAuthCallbackServer{redirectUrl;server;paths;timeoutMs;renderPage;pending=new Map;constructor(server,redirectUrl,paths,timeoutMs,renderPage2){this.server=server,this.redirectUrl=redirectUrl,this.paths=paths,this.timeoutMs=timeoutMs,this.renderPage=renderPage2}static async listen(options={}){let host=options.host??"127.0.0.1",redirectHost=options.redirectHost??host,path=options.path??"/callback",instance,server=createServer((request,response)=>instance?.handle(request.url??"/",response));await new Promise((resolve2,reject)=>{server.once("error",reject),server.listen(options.port??0,host,()=>{server.off("error",reject),resolve2()})});let address=server.address();if(!address||typeof address=="string")throw new Error("OAuth callback server did not bind to TCP");return instance=new _OAuthCallbackServer(server,`http://${redirectHost.includes(":")?`[${redirectHost}]`:redirectHost}:${address.port}${path}`,[path,...options.extraPaths??[]],options.timeoutMs??5*6e4,options.renderPage),instance}waitForCallback(state,path){if(this.pending.has(state))throw new Error("OAuth state is already pending");return new Promise((resolve2,reject)=>{let timer=setTimeout(()=>{this.pending.delete(state),reject(new Error("OAuth callback timed out"))},this.timeoutMs);this.pending.set(state,{resolve:resolve2,reject,timer,path})})}async close(){for(let pending of this.pending.values())clearTimeout(pending.timer),pending.reject(new Error("OAuth callback server closed"));this.pending.clear();let closed=new Promise((resolve2,reject)=>{this.server.close(error=>error?reject(error):resolve2())});this.server.closeAllConnections(),await closed}reply(response,status,page){this.renderPage?(response.writeHead(status,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),response.end(this.renderPage(page))):response.writeHead(status,{"content-type":"text/plain; charset=utf-8"}).end(plainText(page))}handle(rawUrl,response){let url=new URL(rawUrl,this.redirectUrl);if(!this.paths.includes(url.pathname)){this.reply(response,404,{ok:!1,message:"Not found"});return}let state=url.searchParams.get("state"),pending=state?this.pending.get(state):void 0;if(!state||!pending){this.reply(response,400,{ok:!1,message:"Invalid or expired OAuth state"});return}if(clearTimeout(pending.timer),this.pending.delete(state),pending.path!==void 0&&url.pathname!==pending.path){pending.reject(new Error("The authorization response arrived on another redirect URI")),this.reply(response,400,{ok:!1,message:"Unexpected redirect URI"});return}let error=url.searchParams.get("error");if(error){let description=url.searchParams.get("error_description")??error;pending.reject(new Error(description)),this.reply(response,200,{ok:!1,message:"Authorization failed. You may close this window.",details:description});return}let code=url.searchParams.get("code");if(!code){pending.reject(new Error("OAuth callback did not include an authorization code")),this.reply(response,400,{ok:!1,message:"Missing authorization code"});return}let iss=url.searchParams.get("iss");pending.resolve({code,state,...iss?{iss}:{}}),this.reply(response,200,{ok:!0})}};var McpSignInCancelledError=class extends Error{constructor(){super("Sign-in cancelled"),this.name="McpSignInCancelledError"}};async function startMcpSignIn(options){if(options.signal?.aborted)throw new McpSignInCancelledError;let stepUp=options.challenge?.error==="insufficient_scope";return!stepUp&&await refreshBeforeSignIn(options)==="AUTHORIZED"?{kind:"authorized"}:cancellable(options.signal,()=>startBrowserStep(options,stepUp))}async function refreshBeforeSignIn(options){let{store,settings,challenge,redirectUrl,signal}=options,refreshed=store.withRefreshLock(async()=>{if(signal?.aborted)return"REDIRECT";let state=await store.load();return!state?.tokens?.refresh_token||settings.clientRegistration==="cimd"&&state.clientInformation&&!settings.clientId?"REDIRECT":refreshStoredTokens(options,state,{challenge,redirectUrl})});try{return await untilAborted(signal,refreshed)}catch(error){if(error instanceof McpRefreshLockBusyError)return"REDIRECT";throw error}}function untilAborted(signal,promise){return signal?new Promise((resolve2,reject)=>{let abort=()=>reject(new McpSignInCancelledError);signal.addEventListener("abort",abort,{once:!0}),promise.then(resolve2,reject).finally(()=>signal.removeEventListener("abort",abort))}):promise}async function startBrowserStep(options,stepUp){let{store,settings,redirectUrl,challenge}=options,stored=await store.load();stored&&await store.save(stateForSignIn(stored,options));let authorizationUrl,provider=createOAuthClientProvider(options,redirectUrl,url=>{authorizationUrl=url}),scope=mergeScopes(settings.scope,stepUp?stepUpScope(stored?.tokens?.scope,challenge?.scope):challenge?.scope);if(await authorizeMcp(provider,{...flowOptions(options),scope,skipRefresh:!0}),!authorizationUrl)throw new Error("OAuth flow did not produce an authorization URL");let requestedScope=authorizationUrl.searchParams.get("scope");return{kind:"redirect",authorizationUrl:authorizationUrl.href,redirectUrl:authorizationUrl.searchParams.get("redirect_uri")??redirectUrl,state:await provider.state(),...requestedScope?{scope:requestedScope}:{}}}function stateForSignIn(stored,options){let{settings,redirectUrl}=options,next={...stored};return delete next.oauthState,settings.clientId||(stored.clientInformation?settings.clientRegistration!=="cimd"&&registeredRedirectUrls(stored.clientInformation).includes(redirectUrl):offersClientMetadataDocument(settings,options.clientMetadataDocuments,redirectUrl))||(delete next.clientInformation,delete next.tokens,delete next.tokensExpireAt),next}function mergeScopes(...scopes){let merged=[...new Set(scopes.flatMap(scope=>scope?.split(/\s+/).filter(Boolean)??[]))];return merged.length>0?merged.join(" "):void 0}async function completeMcpSignIn(options){await cancellable(options.signal,async()=>{let{authorization,response}=options;if(response.state!==authorization.state)throw new Error("The authorization response belongs to a different sign-in");if((await options.store.load())?.oauthState!==authorization.state)throw new Error("Another sign-in to this MCP server started since; sign in again");await authorizeMcp(createOAuthClientProvider(options,options.redirectUrl),{...flowOptions(options),scope:authorization.scope,authorizationRedirectUrl:authorization.redirectUrl,authorizationCode:response.code,iss:response.iss})})}function flowOptions(options){return{serverUrl:options.serverUrl,fetch:timedFetch(),signal:options.signal,resourceMetadataUrl:options.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:options.settings.authServerMetadataUrl}}async function cancellable(signal,fn){if(signal?.aborted)throw new McpSignInCancelledError;try{return await fn()}catch(error){throw signal?.aborted?new McpSignInCancelledError:error}}async function listenForLoopbackSignIn(options){let{settings}=options,loopback2=loopbackSettings(settings),registered=registeredRedirectUrls((await options.store.load())?.clientInformation)[0],port=loopback2.port??(registered&&Number(new URL(registered).port)||void 0),offersDocument=offersClientMetadataDocument(settings,options.clientMetadataDocuments,loopback2.url),listenOptions={host:loopback2.host,redirectHost:loopback2.redirectHost,path:loopback2.path,extraPaths:offersDocument?[serverSpecificPath(loopback2.path,options.serverUrl)]:[],renderPage:options.renderPage},callback;try{callback=await OAuthCallbackServer.listen({...listenOptions,port:port??0})}catch(error){if(loopback2.port!==void 0||port===void 0)throw error;callback=await OAuthCallbackServer.listen(listenOptions)}return{callback,redirectUrl:loopback2.fixedRedirectUrl??callback.redirectUrl}}async function waitForLoopbackSignIn(options){let{authorization}=options,controller=new AbortController,signal=options.signal?AbortSignal.any([controller.signal,options.signal]):controller.signal,fromBrowser=options.callback.waitForCallback(authorization.state,new URL(authorization.redirectUrl).pathname),fromUser=options.promptForRedirectUrl?options.promptForRedirectUrl(signal).then(input=>{if(!input?.trim())throw new McpSignInCancelledError;return responseFromRedirectUrl(input,authorization)}):new Promise((_,reject)=>{signal.addEventListener("abort",()=>reject(new McpSignInCancelledError),{once:!0})});try{return await cancellable(options.signal,()=>Promise.race([fromBrowser,fromUser]))}finally{controller.abort(),fromBrowser.catch(()=>{}),fromUser.catch(()=>{})}}function responseFromRedirectUrl(input,authorization){let url;try{url=new URL(input.trim())}catch{throw new Error("Expected the full redirect URL from the browser address bar")}let redirectUrl=new URL(authorization.redirectUrl);if(url.origin!==redirectUrl.origin||url.pathname!==redirectUrl.pathname)throw new Error("The redirect URL does not match this sign-in's redirect URI");let error=url.searchParams.get("error");if(error)throw new Error(url.searchParams.get("error_description")??error);let state=url.searchParams.get("state");if(state!==authorization.state)throw new Error("The redirect URL belongs to a different sign-in");let code=url.searchParams.get("code");if(!code)throw new Error("The redirect URL does not contain an authorization code");let iss=url.searchParams.get("iss");return{code,state,...iss?{iss}:{}}}import{createHash as createHash2}from"node:crypto";import{mkdirSync}from"node:fs";import{join}from"node:path";var LOGO_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#F09082" d="M165.29 165.29H517.36V400H400V282.65H165.29Z"/><path fill="#4D9ABF" d="M165.29 282.65H282.65V400H400V517.36H282.65V634.72H165.29Z"/><path fill="#F1BE58" d="M517.36 400H634.72V634.72H517.36Z"/></svg>';function escapeHtml(value){return value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function renderPage(options){let title=escapeHtml(options.title),heading=escapeHtml(options.heading),message=escapeHtml(options.message),details=options.details?escapeHtml(options.details):void 0;return`<!doctype html>
5
5
  <html lang="en">
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{headersToRecord,providerHeadersToRecord}from"./chunk-UTB4DTYQ.js";import{calculateCost}from"./chunk-QRII7KJY.js";import{getIdentityHeaders}from"./chunk-762GZFUO.js";function httpError(label,response,body){let error=new Error(`${label} returned ${response.status}`);return error.status=response.status,error.headers=response.headers,error.body=body,error}function timeoutError(timeoutMs){let error=new Error(`Request timed out after ${timeoutMs}ms`);return error.name="TimeoutError",error.status=void 0,error.headers=void 0,error.body="",error}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function requiredNumber(label,value,field){if(typeof value!="number"||!Number.isFinite(value))throw new Error(`${label} returned an invalid ${field}`);return value}function requestHeaders(model,apiKey,optionsHeaders,identity){return providerHeadersToRecord(getIdentityHeaders(model,identity),{authorization:`Bearer ${apiKey}`,"content-type":"application/json"},model.headers,optionsHeaders)??{}}async function postClassifierRequest(label,url,model,body,options,noRetryStatuses){if(!options?.apiKey)throw new Error(`No API key for provider: ${model.provider}`);let apiKey=options.apiKey,payload=body,transformed=await options.onPayload?.(payload,model);transformed!==void 0&&(payload=transformed);let requestFetch=options.fetch??globalThis.fetch,{response,json}=await retryProviderRequest(async()=>{let timeoutSignal=options.timeoutMs!==void 0?AbortSignal.timeout(options.timeoutMs):void 0,signal=options.signal&&timeoutSignal?AbortSignal.any([options.signal,timeoutSignal]):options.signal??timeoutSignal;try{let next=await requestFetch(url,{method:"POST",headers:requestHeaders(model,apiKey,options.headers,options.identity),body:JSON.stringify(payload),signal});if(!next.ok)throw httpError(label,next,await next.text());return{response:next,json:await next.json()}}catch(error){throw timeoutSignal?.aborted&&!options.signal?.aborted?timeoutError(options.timeoutMs):error}},{maxRetries:options.maxRetries??2,maxRetryDelayMs:options.maxRetryDelayMs,signal:options.signal,noRetryStatuses});return await options.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),json}function tokenCount(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?value:0}function parseClassifierUsage(value,model){if(!isRecord(value)||value.input_tokens===void 0&&value.output_tokens===void 0)return;let totalInput=tokenCount(value.input_tokens),output=tokenCount(value.output_tokens),details=isRecord(value.input_tokens_details)?value.input_tokens_details:void 0,cacheRead=Math.min(tokenCount(details?.cached_tokens),totalInput),cacheWrite=Math.min(tokenCount(details?.cache_write_tokens),totalInput-cacheRead),usage={input:totalInput-cacheRead-cacheWrite,output,cacheRead,cacheWrite,totalTokens:totalInput+output,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return calculateCost(model,usage),usage}export{isRecord,requiredNumber,postClassifierRequest,parseClassifierUsage};
2
+ import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{headersToRecord,providerHeadersToRecord}from"./chunk-UTB4DTYQ.js";import{calculateCost}from"./chunk-3MKQN3ZR.js";import{getIdentityHeaders}from"./chunk-6L2FT6AE.js";function httpError(label,response,body){let error=new Error(`${label} returned ${response.status}`);return error.status=response.status,error.headers=response.headers,error.body=body,error}function timeoutError(timeoutMs){let error=new Error(`Request timed out after ${timeoutMs}ms`);return error.name="TimeoutError",error.status=void 0,error.headers=void 0,error.body="",error}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function requiredNumber(label,value,field){if(typeof value!="number"||!Number.isFinite(value))throw new Error(`${label} returned an invalid ${field}`);return value}function requestHeaders(model,apiKey,optionsHeaders,identity){return providerHeadersToRecord(getIdentityHeaders(model,identity),{authorization:`Bearer ${apiKey}`,"content-type":"application/json"},model.headers,optionsHeaders)??{}}async function postClassifierRequest(label,url,model,body,options,noRetryStatuses){if(!options?.apiKey)throw new Error(`No API key for provider: ${model.provider}`);let apiKey=options.apiKey,payload=body,transformed=await options.onPayload?.(payload,model);transformed!==void 0&&(payload=transformed);let requestFetch=options.fetch??globalThis.fetch,{response,json}=await retryProviderRequest(async()=>{let timeoutSignal=options.timeoutMs!==void 0?AbortSignal.timeout(options.timeoutMs):void 0,signal=options.signal&&timeoutSignal?AbortSignal.any([options.signal,timeoutSignal]):options.signal??timeoutSignal;try{let next=await requestFetch(url,{method:"POST",headers:requestHeaders(model,apiKey,options.headers,options.identity),body:JSON.stringify(payload),signal});if(!next.ok)throw httpError(label,next,await next.text());return{response:next,json:await next.json()}}catch(error){throw timeoutSignal?.aborted&&!options.signal?.aborted?timeoutError(options.timeoutMs):error}},{maxRetries:options.maxRetries??2,maxRetryDelayMs:options.maxRetryDelayMs,signal:options.signal,noRetryStatuses});return await options.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),json}function tokenCount(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?value:0}function parseClassifierUsage(value,model){if(!isRecord(value)||value.input_tokens===void 0&&value.output_tokens===void 0)return;let totalInput=tokenCount(value.input_tokens),output=tokenCount(value.output_tokens),details=isRecord(value.input_tokens_details)?value.input_tokens_details:void 0,cacheRead=Math.min(tokenCount(details?.cached_tokens),totalInput),cacheWrite=Math.min(tokenCount(details?.cache_write_tokens),totalInput-cacheRead),usage={input:totalInput-cacheRead-cacheWrite,output,cacheRead,cacheWrite,totalTokens:totalInput+output,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return calculateCost(model,usage),usage}export{isRecord,requiredNumber,postClassifierRequest,parseClassifierUsage};
@@ -1,12 +1,12 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{CodeHighlighter,Container,Spacer,Text,getCapabilities,getImageDimensions,hyperlink,imageFallback,keyHint,truncateToWidth}from"./chunk-VJQ6ZYW4.js";import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS,typebox_exports}from"./chunk-4KBADZRL.js";import{sanitizeBinaryOutput}from"./chunk-RJRIMI6M.js";import{getDocsPath,resolvePath,shortenHomePath}from"./chunk-B3FUE2LF.js";import{randomBytes}from"node:crypto";import{createWriteStream}from"node:fs";import{writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";var OUTPUT_FILE_MODE=384;function createOutputFilePath(prefix,extension){return join(tmpdir(),`${prefix}-${randomBytes(8).toString("hex")}${extension}`)}async function writeOutputFile(prefix,extension,data){let path=createOutputFilePath(prefix,extension);return await writeFile(path,data,{mode:OUTPUT_FILE_MODE,flag:"wx"}),path}function createOutputFileStream(prefix,extension){let path=createOutputFilePath(prefix,extension);return{path,stream:createWriteStream(path,{mode:OUTPUT_FILE_MODE,flags:"wx"})}}function createUsageTotals(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0}}function addUsageToTotals(totals,usage){totals.input+=usage.input,totals.output+=usage.output,totals.cacheRead+=usage.cacheRead,totals.cacheWrite+=usage.cacheWrite,totals.cost+=usage.cost.total}function combineUsage(first,second){return{input:first.input+second.input,output:first.output+second.output,cacheRead:first.cacheRead+second.cacheRead,cacheWrite:first.cacheWrite+second.cacheWrite,...first.cacheWrite1h!==void 0||second.cacheWrite1h!==void 0?{cacheWrite1h:(first.cacheWrite1h??0)+(second.cacheWrite1h??0)}:{},...first.reasoning!==void 0||second.reasoning!==void 0?{reasoning:(first.reasoning??0)+(second.reasoning??0)}:{},totalTokens:first.totalTokens+second.totalTokens,cost:{input:first.cost.input+second.cost.input,output:first.cost.output+second.cost.output,cacheRead:first.cost.cacheRead+second.cost.cacheRead,cacheWrite:first.cost.cacheWrite+second.cost.cacheWrite,total:first.cost.total+second.cost.total,totalFromProvider:first.cost.totalFromProvider===!0&&second.cost.totalFromProvider===!0}}}function getUsageCostBreakdown(entries){let totalsByKey=new Map;for(let entry of entries){let key,usage;if(entry.type==="message"&&entry.message.role==="assistant"?(key=`${entry.message.provider}/${entry.message.responseModel??entry.message.model}`,usage=entry.message.usage):entry.type==="usage"?(key=`${entry.provider}/${entry.model}`,usage=entry.usage):entry.type==="message"&&entry.message.role==="toolResult"&&entry.message.usage?(key="Tools/summaries",usage=entry.message.usage):(entry.type==="branch_summary"||entry.type==="compaction")&&entry.usage&&(key="Tools/summaries",usage=entry.usage),!key||!usage)continue;let totals=totalsByKey.get(key);totals||(totals=createUsageTotals(),totalsByKey.set(key,totals)),addUsageToTotals(totals,usage)}return Array.from(totalsByKey,([key,totals])=>({key,cost:totals.cost,tokens:totals.input+totals.output+totals.cacheRead+totals.cacheWrite})).filter(entry=>entry.cost>0||entry.tokens>0).sort((a,b)=>b.cost-a.cost)}function truncateToVisualLines(text,maxVisualLines,width,paddingX=0,keep="end"){if(!text)return{visualLines:[],skippedCount:0};let allVisualLines=new Text(text,paddingX,0).render(width);if(allVisualLines.length<=maxVisualLines)return{visualLines:allVisualLines,skippedCount:0};let truncatedLines=keep==="start"?allVisualLines.slice(0,maxVisualLines):allVisualLines.slice(-maxVisualLines),skippedCount=allVisualLines.length-maxVisualLines;return{visualLines:truncatedLines,skippedCount}}var VisualLinePreview=class{options;cachedWidth;cachedLines;constructor(options){this.options=options}render(width){if(this.cachedLines===void 0||this.cachedWidth!==width){let{text,maxVisualLines,keep,formatHint}=this.options,preview=truncateToVisualLines(text,maxVisualLines,width,0,keep),lines=preview.visualLines;if(preview.skippedCount>0){let hint=truncateToWidth(formatHint(preview.skippedCount),width,"...");this.cachedLines=keep==="start"?[...lines,hint]:[hint,...lines]}else this.cachedLines=lines;this.cachedWidth=width}return this.cachedLines}invalidate(){this.cachedWidth=void 0,this.cachedLines=void 0}};import{pathToFileURL}from"node:url";var ST="(?:\\u0007|\\u001B\\u005C|\\u009C)",OSC_START="\\u001B\\]",CSI_START="(?:(?:\\u001B\\[|\\u009B)[<=>]|[\\u001B\\u009B][[\\]()#;?]*)(?:\\d{1,4}(?:[;:]\\d{0,4})*)?",CSI_FINAL="[\\dA-PR-TZcf-nq-uy=><~]",ansiRegex=new RegExp(`(?:${OSC_START}[\\s\\S]*?${ST})|${CSI_START}${CSI_FINAL}`,"g"),unfinishedAnsiAtEndRegex=new RegExp(`(?:${OSC_START}(?:[^\\u0007\\u009C\\u001B]|\\u001B(?!\\\\))*|${CSI_START})$`),MAX_PENDING_ANSI_LENGTH=256;function splitIncompleteAnsiSuffix(value){if(!value.includes("\x1B")&&!value.includes("\x9B"))return{complete:value,pending:""};let windowStart=Math.max(0,value.length-MAX_PENDING_ANSI_LENGTH),match=unfinishedAnsiAtEndRegex.exec(value.slice(windowStart));if(!match)return{complete:value,pending:""};let splitAt=windowStart+match.index;return{complete:value.slice(0,splitAt),pending:value.slice(splitAt)}}function stripAnsi(value){if(typeof value!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof value}\``);return!value.includes("\x1B")&&!value.includes("\x9B")?value:value.replace(ansiRegex,"")}function shortenPath(path){return typeof path!="string"?"":shortenHomePath(path)}function linkPath(styledText,rawPath,cwd){if(!getCapabilities().hyperlinks)return styledText;let absolutePath=resolvePath(rawPath,cwd);return hyperlink(styledText,pathToFileURL(absolutePath).href)}function str(value){return typeof value=="string"?value:value==null?"":null}function parseLineNumber(value){return typeof value=="string"&&value.trim()!==""&&(value=Number(value)),typeof value=="number"&&Number.isFinite(value)?value:void 0}function formatReadLineRange(offset,limit){if(offset==null&&limit==null)return"";let start=offset==null?1:parseLineNumber(offset);if(start===void 0)return"";if(limit==null)return`:${start}`;let count=parseLineNumber(limit);if(count===void 0)return"";let end=start+count-1;return`:${start}${end?`-${end}`:""}`}function replaceTabs(text){return text.replace(/\t/g," ")}function normalizeDisplayText(text){return text.replace(/\r/g,"")}function getTextOutput(result,showImages){if(!result)return"";let textBlocks=result.content.filter(c=>c.type==="text"),imageBlocks=result.content.filter(c=>c.type==="image"),output=textBlocks.map(c=>sanitizeBinaryOutput(stripAnsi(c.text||"")).replace(/\r/g,"")).join(`
2
+ import{CodeHighlighter,Container,Spacer,Text,getCapabilities,getImageDimensions,hyperlink,imageFallback,keyHint,truncateToWidth}from"./chunk-4NMBWIZG.js";import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS,typebox_exports}from"./chunk-4KBADZRL.js";import{sanitizeBinaryOutput}from"./chunk-GRYHVZSI.js";import{getDocsPath,resolvePath,shortenHomePath}from"./chunk-XAA355T2.js";import{randomBytes}from"node:crypto";import{createWriteStream}from"node:fs";import{writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";var OUTPUT_FILE_MODE=384;function createOutputFilePath(prefix,extension){return join(tmpdir(),`${prefix}-${randomBytes(8).toString("hex")}${extension}`)}async function writeOutputFile(prefix,extension,data){let path=createOutputFilePath(prefix,extension);return await writeFile(path,data,{mode:OUTPUT_FILE_MODE,flag:"wx"}),path}function createOutputFileStream(prefix,extension){let path=createOutputFilePath(prefix,extension);return{path,stream:createWriteStream(path,{mode:OUTPUT_FILE_MODE,flags:"wx"})}}function createUsageTotals(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0}}function addUsageToTotals(totals,usage){totals.input+=usage.input,totals.output+=usage.output,totals.cacheRead+=usage.cacheRead,totals.cacheWrite+=usage.cacheWrite,totals.cost+=usage.cost.total}function combineUsage(first,second){return{input:first.input+second.input,output:first.output+second.output,cacheRead:first.cacheRead+second.cacheRead,cacheWrite:first.cacheWrite+second.cacheWrite,...first.cacheWrite1h!==void 0||second.cacheWrite1h!==void 0?{cacheWrite1h:(first.cacheWrite1h??0)+(second.cacheWrite1h??0)}:{},...first.reasoning!==void 0||second.reasoning!==void 0?{reasoning:(first.reasoning??0)+(second.reasoning??0)}:{},totalTokens:first.totalTokens+second.totalTokens,cost:{input:first.cost.input+second.cost.input,output:first.cost.output+second.cost.output,cacheRead:first.cost.cacheRead+second.cost.cacheRead,cacheWrite:first.cost.cacheWrite+second.cost.cacheWrite,total:first.cost.total+second.cost.total,totalFromProvider:first.cost.totalFromProvider===!0&&second.cost.totalFromProvider===!0}}}function getUsageCostBreakdown(entries){let totalsByKey=new Map;for(let entry of entries){let key,usage;if(entry.type==="message"&&entry.message.role==="assistant"?(key=`${entry.message.provider}/${entry.message.responseModel??entry.message.model}`,usage=entry.message.usage):entry.type==="usage"?(key=`${entry.provider}/${entry.model}`,usage=entry.usage):entry.type==="message"&&entry.message.role==="toolResult"&&entry.message.usage?(key="Tools/summaries",usage=entry.message.usage):(entry.type==="branch_summary"||entry.type==="compaction")&&entry.usage&&(key="Tools/summaries",usage=entry.usage),!key||!usage)continue;let totals=totalsByKey.get(key);totals||(totals=createUsageTotals(),totalsByKey.set(key,totals)),addUsageToTotals(totals,usage)}return Array.from(totalsByKey,([key,totals])=>({key,cost:totals.cost,tokens:totals.input+totals.output+totals.cacheRead+totals.cacheWrite})).filter(entry=>entry.cost>0||entry.tokens>0).sort((a,b)=>b.cost-a.cost)}function truncateToVisualLines(text,maxVisualLines,width,paddingX=0,keep="end"){if(!text)return{visualLines:[],skippedCount:0};let allVisualLines=new Text(text,paddingX,0).render(width);if(allVisualLines.length<=maxVisualLines)return{visualLines:allVisualLines,skippedCount:0};let truncatedLines=keep==="start"?allVisualLines.slice(0,maxVisualLines):allVisualLines.slice(-maxVisualLines),skippedCount=allVisualLines.length-maxVisualLines;return{visualLines:truncatedLines,skippedCount}}var VisualLinePreview=class{options;cachedWidth;cachedLines;constructor(options){this.options=options}render(width){if(this.cachedLines===void 0||this.cachedWidth!==width){let{text,maxVisualLines,keep,formatHint}=this.options,preview=truncateToVisualLines(text,maxVisualLines,width,0,keep),lines=preview.visualLines;if(preview.skippedCount>0){let hint=truncateToWidth(formatHint(preview.skippedCount),width,"...");this.cachedLines=keep==="start"?[...lines,hint]:[hint,...lines]}else this.cachedLines=lines;this.cachedWidth=width}return this.cachedLines}invalidate(){this.cachedWidth=void 0,this.cachedLines=void 0}};import{pathToFileURL}from"node:url";var ST="(?:\\u0007|\\u001B\\u005C|\\u009C)",OSC_START="\\u001B\\]",CSI_START="(?:(?:\\u001B\\[|\\u009B)[<=>]|[\\u001B\\u009B][[\\]()#;?]*)(?:\\d{1,4}(?:[;:]\\d{0,4})*)?",CSI_FINAL="[\\dA-PR-TZcf-nq-uy=><~]",ansiRegex=new RegExp(`(?:${OSC_START}[\\s\\S]*?${ST})|${CSI_START}${CSI_FINAL}`,"g"),unfinishedAnsiAtEndRegex=new RegExp(`(?:${OSC_START}(?:[^\\u0007\\u009C\\u001B]|\\u001B(?!\\\\))*|${CSI_START})$`),MAX_PENDING_ANSI_LENGTH=256;function splitIncompleteAnsiSuffix(value){if(!value.includes("\x1B")&&!value.includes("\x9B"))return{complete:value,pending:""};let windowStart=Math.max(0,value.length-MAX_PENDING_ANSI_LENGTH),match=unfinishedAnsiAtEndRegex.exec(value.slice(windowStart));if(!match)return{complete:value,pending:""};let splitAt=windowStart+match.index;return{complete:value.slice(0,splitAt),pending:value.slice(splitAt)}}function stripAnsi(value){if(typeof value!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof value}\``);return!value.includes("\x1B")&&!value.includes("\x9B")?value:value.replace(ansiRegex,"")}function shortenPath(path){return typeof path!="string"?"":shortenHomePath(path)}function linkPath(styledText,rawPath,cwd){if(!getCapabilities().hyperlinks)return styledText;let absolutePath=resolvePath(rawPath,cwd);return hyperlink(styledText,pathToFileURL(absolutePath).href)}function str(value){return typeof value=="string"?value:value==null?"":null}function parseLineNumber(value){return typeof value=="string"&&value.trim()!==""&&(value=Number(value)),typeof value=="number"&&Number.isFinite(value)?value:void 0}function formatReadLineRange(offset,limit){if(offset==null&&limit==null)return"";let start=offset==null?1:parseLineNumber(offset);if(start===void 0)return"";if(limit==null)return`:${start}`;let count=parseLineNumber(limit);if(count===void 0)return"";let end=start+count-1;return`:${start}${end?`-${end}`:""}`}function replaceTabs(text){return text.replace(/\t/g," ")}function normalizeDisplayText(text){return text.replace(/\r/g,"")}function getTextOutput(result,showImages){if(!result)return"";let textBlocks=result.content.filter(c=>c.type==="text"),imageBlocks=result.content.filter(c=>c.type==="image"),output=textBlocks.map(c=>sanitizeBinaryOutput(stripAnsi(c.text||"")).replace(/\r/g,"")).join(`
3
3
  `),caps=getCapabilities();if(imageBlocks.length>0&&(!caps.images||!showImages)){let imageIndicators=imageBlocks.map(img=>{let mimeType=img.mimeType??"image/unknown",dims=img.data&&img.mimeType?getImageDimensions(img.data,img.mimeType)??void 0:void 0;return imageFallback(mimeType,dims)}).join(`
4
4
  `);output=output?`${output}
5
5
  ${imageIndicators}`:imageIndicators}return output}var COLLAPSED_ARGS_CHARS=100;function formatToolCallWithArgs(title,args,theme,expanded){let header=theme.fg("toolTitle",theme.bold(title));if(args==null)return header;let entries=typeof args=="object"&&!Array.isArray(args)?Object.entries(args):[["args",args]];if(entries.length===0)return header;if(expanded){let lines=entries.map(([key,value])=>{let text=typeof value=="string"?value:JSON.stringify(value,null,2)??String(value);return` ${key}: ${replaceTabs(text).replace(/\r/g,"").split(`
6
6
  `).join(`
7
7
  `)}`});return`${header}
8
8
  ${theme.fg("muted",lines.join(`
9
- `))}`}let pairs=entries.map(([key,value])=>`${key}=${JSON.stringify(value)??String(value)}`).join(" "),preview=pairs.length>COLLAPSED_ARGS_CHARS?`${pairs.slice(0,COLLAPSED_ARGS_CHARS-3)}...`:pairs;return`${header} ${theme.fg("muted",preview)}`}function formatToolDuration(ms){let seconds=ms/1e3;if(seconds<60)return`${seconds.toFixed(1)}s`;let totalSeconds=Math.floor(seconds),minutes=Math.floor(totalSeconds/60),remainder=totalSeconds%60;return minutes<60?`${minutes}m ${remainder}s`:`${Math.floor(minutes/60)}h ${minutes%60}m ${remainder}s`}function startToolTimer(context){let state=context.state;context.executionStarted&&state.startedAt===void 0&&(state.startedAt=Date.now(),state.endedAt=void 0)}function toolTimerText(context,isPartial){let state=context.state;if(state.startedAt!==void 0&&isPartial&&!state.interval&&(state.interval=setInterval(()=>context.invalidate(),1e3)),(!isPartial||context.isError)&&(state.endedAt??=Date.now(),state.interval&&(clearInterval(state.interval),state.interval=void 0)),!isPartial&&context.durationMs!==void 0)return`Took ${formatToolDuration(context.durationMs)}`;if(state.startedAt===void 0)return;let endTime=state.endedAt??Date.now();return`${isPartial?"Elapsed":"Took"} ${formatToolDuration(endTime-state.startedAt)}`}function invalidArgText(theme){return theme.fg("error","[invalid arg]")}function renderToolPath(rawPath,theme,cwd,options){if(rawPath===null)return invalidArgText(theme);let value=rawPath||options?.emptyFallback;return value?linkPath(theme.fg("accent",shortenPath(value)),value,cwd):theme.fg("toolOutput","...")}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()??""}
9
+ `))}`}let pairs=entries.map(([key,value])=>`${key}=${JSON.stringify(value)??String(value)}`).join(" "),preview=pairs.length>COLLAPSED_ARGS_CHARS?`${pairs.slice(0,COLLAPSED_ARGS_CHARS-3)}...`:pairs;return`${header} ${theme.fg("muted",preview)}`}function formatToolDuration(ms){let seconds=ms/1e3;if(seconds<60)return`${seconds.toFixed(1)}s`;let totalSeconds=Math.floor(seconds),minutes=Math.floor(totalSeconds/60),remainder=totalSeconds%60;return minutes<60?`${minutes}m ${remainder}s`:`${Math.floor(minutes/60)}h ${minutes%60}m ${remainder}s`}function startToolTimer(context){let state=context.state;context.executionStarted&&state.startedAt===void 0&&(state.startedAt=Date.now(),state.endedAt=void 0)}function toolTimerText(context,isPartial){let state=context.state;if(state.startedAt!==void 0&&isPartial&&!state.interval&&(state.interval=setInterval(()=>context.invalidate(),1e3)),(!isPartial||context.isError)&&(state.endedAt??=Date.now(),state.interval&&(clearInterval(state.interval),state.interval=void 0)),!isPartial&&context.durationMs!==void 0||state.startedAt===void 0)return;let endTime=state.endedAt??Date.now();return`${isPartial?"Elapsed":"Took"} ${formatToolDuration(endTime-state.startedAt)}`}function invalidArgText(theme){return theme.fg("error","[invalid arg]")}function renderToolPath(rawPath,theme,cwd,options){if(rawPath===null)return invalidArgText(theme);let value=rawPath||options?.emptyFallback;return value?linkPath(theme.fg("accent",shortenPath(value)),value,cwd):theme.fg("toolOutput","...")}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()??""}
10
10
 
11
11
  codemode tool declaration:
12
12
  \`\`\`ts
@@ -30,7 +30,7 @@ Searches over deferred tool metadata with BM25 and exposes matching tools for th
30
30
 
31
31
  Some of the tools, such as tools of MCP servers, may not have been provided to you upfront, and you should use this tool (\`${TOOL_SEARCH_TOOL_NAME}\`) to search for the required tools. For MCP tool discovery, always use \`${TOOL_SEARCH_TOOL_NAME}\`.`;function createToolSearchToolDefinition(options={}){return{name:TOOL_SEARCH_TOOL_NAME,label:TOOL_SEARCH_TOOL_NAME,description:TOOL_SEARCH_DESCRIPTION,promptSnippet:"Search for tools that are not loaded yet and load the matches",parameters:toolSearchSchema,exposure:"model-only",reachesTools:()=>"all",async execute(_toolCallId,{query,limit}){if(query.trim()==="")throw new Error("query must not be empty");let max=limit??DEFAULT_TOOL_SEARCH_LIMIT;if(!Number.isInteger(max)||max<=0)throw new Error("limit must be a positive integer");let tools=options.tools?searchAndLoad(options.tools,query,max):[];return{content:[{type:"text",text:tools.length===0?"No matching tools found.":`Loaded ${tools.length} tool${tools.length===1?"":"s"}. They are available from your next call:
32
32
  ${tools.map(tool=>`- ${tool.name}: ${tool.description.trim().split(/\r?\n/)[0]}`).join(`
33
- `)}`}],details:{loaded:tools.map(tool=>tool.name)}}}}}import{join as join2}from"node:path";var SETTINGS_DEFAULTS={transport:"auto",sessionShareDestination:"auto",steeringMode:"one-at-a-time",followUpMode:"one-at-a-time",compaction:{enabled:!0,reserveTokens:16384,keepRecentTokens:2e4},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,quietStartup:!1,defaultProjectTrust:"ask",collapseChangelog:!1,enableInstallTelemetry:!0,enableAnalytics:!1,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},cacheWarming:"idle",tuiMode:"fullscreen",fullscreenExitOutput:"transcript",fullscreenScrollbar:"auto",fullscreenCopyOnSelect:!0,fullscreenWheelScrollLines:"auto"};function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:definition.prepareArguments,executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-3J63CQJG.js");var CODE_PREVIEW_LINES=10,CALL_PREVIEW_COUNT=8,OUTPUT_PREVIEW_LINES=5,COLLAPSED_ARGS_CHARS2=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(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 args=!expanded&&call.args.length>COLLAPSED_ARGS_CHARS2?`${call.args.slice(0,COLLAPSED_ARGS_CHARS2-3)}...`:call.args,duration=formatDuration(call.durationMs),line=`${statusIcon(call,theme)} ${theme.fg("toolTitle",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+=`
33
+ `)}`}],details:{loaded:tools.map(tool=>tool.name)}}}}}import{join as join2}from"node:path";var SETTINGS_DEFAULTS={transport:"auto",sessionShareDestination:"auto",steeringMode:"one-at-a-time",followUpMode:"one-at-a-time",compaction:{enabled:!0,reserveTokens:16384,keepRecentTokens:2e4},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,quietStartup:!1,defaultProjectTrust:"ask",collapseChangelog:!1,enableInstallTelemetry:!0,enableAnalytics:!1,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},approvalMode:"yolo",sandbox:{mode:"off",network:!1,windows:"unelevated"},memory:{enableManagedAutoMemory:!0,enableManagedAutoDream:!0},goals:{tokenBudget:3e7},experimental:{cron:!0,cronRecurringMaxAgeDays:7},agents:{defaultBackground:!0,maxSubagentDepth:5,maxParallelAgents:10},autoModeClassifierTimeoutMs:1e4,webSearch:{webExtractor:!0,timeoutMs:12e4,maxPerSession:200},cacheWarming:"idle",tuiMode:"fullscreen",fullscreenExitOutput:"transcript",fullscreenScrollbar:"auto",fullscreenCopyOnSelect:!0,fullscreenWheelScrollLines:"auto"};function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:definition.prepareArguments,executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-OEFRHFHI.js");var CODE_PREVIEW_LINES=10,CALL_PREVIEW_COUNT=8,OUTPUT_PREVIEW_LINES=5,COLLAPSED_ARGS_CHARS2=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(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 args=!expanded&&call.args.length>COLLAPSED_ARGS_CHARS2?`${call.args.slice(0,COLLAPSED_ARGS_CHARS2-3)}...`:call.args,duration=formatDuration(call.durationMs),line=`${statusIcon(call,theme)} ${theme.fg("toolTitle",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+=`
34
34
  ${theme.fg("error",call.error.split(`
35
35
  `).join(`
36
36
  `))}`),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.highlight(replaceTabs(code.replace(/\r/g,"").trimEnd()),"javascript").join(`
@@ -52,4 +52,4 @@ ${description}`:""}`)}for(let entry of visible)toolSections.push(entry.section)}
52
52
  `)}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,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(`
53
53
  `)?`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){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()}
54
54
 
55
- 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(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(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"?[]: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(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{SETTINGS_DEFAULTS,splitIncompleteAnsiSuffix,stripAnsi,writeOutputFile,createOutputFileStream,createUsageTotals,addUsageToTotals,combineUsage,getUsageCostBreakdown,wrapToolDefinition,createToolDefinitionFromAgentTool,truncateToVisualLines,VisualLinePreview,shortenPath,str,formatReadLineRange,replaceTabs,normalizeDisplayText,getTextOutput,formatToolCallWithArgs,startToolTimer,toolTimerText,invalidArgText,renderToolPath,toCodemodeIdentifier,renderToolSample,parseCodemodeSource,TOOL_SEARCH_TOOL_NAME,DEFAULT_TOOL_SEARCH_LIMIT,createToolSearchDocument,Bm25Ranker,createToolSearchToolDefinition,CODEMODE_TOOL_NAME,CODEMODE_STORE_ENTRY_TYPE,CODEMODE_DOCS_PATH,toCodemodeDeclaration,getCodemodeCallableTools,createCodemodeToolDefinition};
55
+ 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(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(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"?[]: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(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{SETTINGS_DEFAULTS,splitIncompleteAnsiSuffix,stripAnsi,writeOutputFile,createOutputFileStream,createUsageTotals,addUsageToTotals,combineUsage,getUsageCostBreakdown,wrapToolDefinition,createToolDefinitionFromAgentTool,truncateToVisualLines,VisualLinePreview,shortenPath,str,formatReadLineRange,replaceTabs,normalizeDisplayText,getTextOutput,formatToolCallWithArgs,formatToolDuration,startToolTimer,toolTimerText,invalidArgText,renderToolPath,toCodemodeIdentifier,renderToolSample,parseCodemodeSource,TOOL_SEARCH_TOOL_NAME,DEFAULT_TOOL_SEARCH_LIMIT,createToolSearchDocument,Bm25Ranker,createToolSearchToolDefinition,CODEMODE_TOOL_NAME,CODEMODE_STORE_ENTRY_TYPE,CODEMODE_DOCS_PATH,toCodemodeDeclaration,getCodemodeCallableTools,createCodemodeToolDefinition};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{clampThinkingLevel}from"./chunk-QRII7KJY.js";import{getSystemMessageText}from"./chunk-762GZFUO.js";var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types=typeof schema.type=="string"?[schema.type]:Array.isArray(schema.type)?schema.type:[];return types.includes("object")||types.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.type===void 0&&schema.anyOf===void 0&&schema.enum===void 0)throw new UnsupportedStrictJsonSchemaError("schemas without a type are unsupported");if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items,isUnsupportedKeyword)}let isObjectSchema=schema.type==="object";if(schema.properties!==void 0&&!isObjectSchema)throw new UnsupportedStrictJsonSchemaError("properties require type object");if(!isObjectSchema)return;if(schema.additionalProperties!==void 0&&schema.additionalProperties!==!1)throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");if(schema.properties!==void 0&&!isJsonSchemaObject(schema.properties))throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");if(schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(key=>typeof key!="string")))throw new UnsupportedStrictJsonSchemaError("object required must be a string array");let properties=schema.properties??{},propertyNames=Object.keys(properties),required=new Set(Array.isArray(schema.required)?schema.required:[]);if([...required].some(key=>!propertyNames.includes(key)))throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");for(let[key,property]of Object.entries(properties))makeJsonSchemaNodeStrict(property,isUnsupportedKeyword),!required.has(key)&&!schemaAllowsNull(property)&&(properties[key]={anyOf:[property,{type:"null"}]});schema.required=propertyNames,schema.additionalProperties=!1}function makeStrictJsonSchema(schema,isUnsupportedKeyword){let cloned=structuredClone(schema);if(!isJsonSchemaObject(cloned))throw new UnsupportedStrictJsonSchemaError("root schema must have type object");if(makeJsonSchemaNodeStrict(cloned,isUnsupportedKeyword),cloned.type!=="object")throw new UnsupportedStrictJsonSchemaError("root schema must have type object");return cloned}function prefersJsonSchemaStrictSampling(tool){let config=tool.constrainedSampling;return!!config&&config.type==="json_schema"&&config.strict==="prefer"}function getJsonSchemaToolParameters(tool,strict){return strict===!0?makeStrictJsonSchema(tool.parameters):tool.parameters}function getGrammarToolInput(toolName,arguments_,inputProperty){let input=arguments_[inputProperty];if(typeof input!="string")throw new Error(`Grammar tool call "${toolName}" requires argument "${inputProperty}" to be a string.`);return input}function appendGrammarToolInputJsonDelta(buffer,inputProperty,inputDelta){if(buffer.closed)throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`);if(inputDelta.length!==0)return buffer.input+=inputDelta,grammarToolInputJsonStart(buffer,inputProperty)+JSON.stringify(inputDelta).slice(1,-1)}function closeGrammarToolInputJson(buffer,inputProperty,finalInput){if(buffer.closed){if(finalInput===void 0||finalInput===buffer.input)return;throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`)}if(finalInput!==void 0&&!finalInput.startsWith(buffer.input))throw new Error(`grammar tool input for property "${inputProperty}" changed non-monotonically`);let rest=finalInput===void 0?"":finalInput.slice(buffer.input.length);return finalInput!==void 0&&(buffer.input=finalInput),buffer.closed=!0,`${grammarToolInputJsonStart(buffer,inputProperty)}${JSON.stringify(rest).slice(1,-1)}"}`}function grammarToolInputJsonStart(buffer,inputProperty){return buffer.started?"":(buffer.started=!0,`{${JSON.stringify(inputProperty)}:"`)}function inferGrammarInputProperty(tool){let schema=tool.parameters;if(schema.type!=="object")throw new Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(schema.required)||schema.required.length!==1||typeof schema.required[0]!="string")throw new Error("grammar constrained sampling requires exactly one required string property");let inputProperty=schema.required[0];if(!schema.properties?.[inputProperty])throw new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);if(schema.properties[inputProperty]?.type!=="string")throw new Error(`grammar constrained sampling property ${inputProperty} must have type string`);return inputProperty}function resolveJsonSchemaStrictSampling(tool,supportsStrictMode,isUnsupportedKeyword){let config=tool.constrainedSampling;if(!(!config||config.type!=="json_schema")){if(supportsStrictMode)try{return makeStrictJsonSchema(tool.parameters,isUnsupportedKeyword),!0}catch(error){if(!(error instanceof UnsupportedStrictJsonSchemaError))throw error;if(config.strict!=="require")return;throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`)}if(config.strict==="require")throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools){let config=tool.constrainedSampling;if(!config||config.type!=="grammar"||!supportsOpenAIGrammarTools)return;let larkDefinition=config.variants.openai_lark,regexDefinition=config.variants.openai_regex,hasLarkDefinition=typeof larkDefinition=="string"&&larkDefinition.trim().length>0,hasRegexDefinition=typeof regexDefinition=="string"&&regexDefinition.trim().length>0;if(!hasLarkDefinition&&!hasRegexDefinition)throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:hasLarkDefinition?"lark":"regex",definition:hasLarkDefinition?larkDefinition:regexDefinition,inputProperty:inferGrammarInputProperty(tool)}}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: ${message}.`)}}function createGrammarToolInputProperties(tools,supportsOpenAIGrammarTools){let properties=new Map;for(let tool of tools??[]){let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);grammar&&properties.set(tool.name,grammar.inputProperty)}return properties}var CHARS_PER_TOKEN=3.5,ESTIMATED_IMAGE_CHARS=4800;function calculateContextTokens(usage){return usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function safeJsonStringify(value){try{return JSON.stringify(value)??"undefined"}catch{return"[unserializable]"}}function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars=0;for(let block of content)chars+=block.type==="text"?block.text.length:ESTIMATED_IMAGE_CHARS;return chars}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);for(let block of message.content)block.type==="text"?chars+=block.text.length:block.type==="thinking"?chars+=block.thinking.length:chars+=block.name.length+safeJsonStringify(block.arguments).length;return Math.ceil(chars/CHARS_PER_TOKEN)}function getLastAssistantUsageInfo(messages){let latestPrefixTimestamp=Number.NEGATIVE_INFINITY,usageInfo;for(let i=0;i<messages.length;i++){let message=messages[i];if(message.role==="assistant"){let assistant=message;assistant.timestamp>=latestPrefixTimestamp&&assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens(assistant.usage)>0&&(usageInfo={usage:assistant.usage,index:i})}latestPrefixTimestamp=Math.max(latestPrefixTimestamp,message.timestamp)}return usageInfo}function estimateContextTokens(context){let messages="messages"in context?context.messages:context,usageInfo=getLastAssistantUsageInfo(messages);if(usageInfo){let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=0;for(let i=usageInfo.index+1;i<messages.length;i++)trailingTokens+=estimateMessageTokens(messages[i]);return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}let tokens=0;for(let message of messages)tokens+=estimateMessageTokens(message);return{tokens,usageTokens:0,trailingTokens:tokens,lastUsageIndex:null}}function estimateToolsTokens(tools){return!tools||tools.length===0?0:estimateTextTokens(safeJsonStringify(tools))}var CONTEXT_SAFETY_TOKENS=4096,CONTEXT_SAFETY_RATIO=.15,MIN_OUTPUT_WITH_RATIO_MARGIN=32768,MIN_MAX_TOKENS=1;function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Math.max(MIN_MAX_TOKENS,maxTokens);let input=estimateContextTokens(context).tokens,margin=Math.max(CONTEXT_SAFETY_TOKENS,Math.ceil(input*CONTEXT_SAFETY_RATIO)),room=model.contextWindow-input-margin;return room<MIN_OUTPUT_WITH_RATIO_MARGIN&&(room=Math.min(MIN_OUTPUT_WITH_RATIO_MARGIN,model.contextWindow-input-CONTEXT_SAFETY_TOKENS)),Math.min(maxTokens,Math.max(MIN_MAX_TOKENS,room))}function resolveSamplingParams(model,thinkingLevel,requestParams){let effectiveThinkingLevel=clampThinkingLevel(model,thinkingLevel),thinkingLevelParams=model.samplingParamsByThinkingLevel?.[effectiveThinkingLevel];return model.samplingParams||thinkingLevelParams||requestParams?{...model.samplingParams,...thinkingLevelParams,...requestParams}:void 0}function buildBaseOptions(model,context,options,apiKey){let samplingParams=resolveSamplingParams(model,options?.reasoning??"off",options?.samplingParams);return{temperature:options?.temperature,samplingParams,maxTokens:clampMaxTokensToContext(model,context,options?.maxTokens??model.maxTokens),signal:options?.signal,telemetry:options?.telemetry,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention,sessionId:options?.sessionId,disableContinuation:options?.disableContinuation,headers:options?.headers,identity:options?.identity,onPayload:options?.onPayload,onResponse:options?.onResponse,onProviderStreamEvent:options?.onProviderStreamEvent,timeoutMs:options?.timeoutMs,websocketConnectTimeoutMs:options?.websocketConnectTimeoutMs,maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,metadata:options?.metadata,env:options?.env}}var MIN_ANSWER_TOKENS=1024,DEFAULT_THINKING_BUDGETS={minimal:1024,low:2048,medium:8192,high:16384};function clampReasoning(effort){return effort==="xhigh"||effort==="max"?"high":effort}function thinkingBudgetForLevel(reasoningLevel,customBudgets){let budgets={...DEFAULT_THINKING_BUDGETS,...customBudgets},level=clampReasoning(reasoningLevel);return budgets[level]}function clampThinkingBudgetToAnswerRoom(thinkingBudget,ceiling){return Math.min(thinkingBudget,Math.max(0,ceiling-MIN_ANSWER_TOKENS))}function adjustMaxTokensForThinking(baseMaxTokens,modelMaxTokens,reasoningLevel,customBudgets){let thinkingBudget=thinkingBudgetForLevel(reasoningLevel,customBudgets),maxTokens=baseMaxTokens===void 0?modelMaxTokens:Math.min(baseMaxTokens+thinkingBudget,modelMaxTokens);return maxTokens<=thinkingBudget&&(thinkingBudget=clampThinkingBudgetToAnswerRoom(thinkingBudget,maxTokens)),{maxTokens,thinkingBudget}}var NON_VISION_USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)",NON_VISION_TOOL_IMAGE_PLACEHOLDER="(tool image omitted: model does not support images)",ERROR_TOOL_IMAGE_PLACEHOLDER="(image attached after the tool results)";function splitErrorToolResultImages(msg){if(!msg.isError)return;let images=msg.content.filter(block=>block.type==="image");if(images.length!==0)return{content:replaceImagesWithPlaceholder(msg.content,ERROR_TOOL_IMAGE_PLACEHOLDER),caption:`Images from the error result of tool call ${msg.toolCallId} (${msg.toolName}):`,images}}function replaceImagesWithPlaceholder(content,placeholder){let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.text===placeholder}return result}function downgradeUnsupportedImages(messages,model){return model.input.includes("image")?messages:messages.map(msg=>msg.role==="user"&&Array.isArray(msg.content)?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_USER_IMAGE_PLACEHOLDER)}:msg.role==="toolResult"?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)}:msg)}function transformMessages(messages,model,normalizeToolCallId){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),transformed=downgradeUnsupportedImages(normalizedMessages,model).map(msg=>{if(msg.role==="system"||msg.role==="user")return msg;if(msg.role==="toolResult"){let normalizedId=toolCallIdMap.get(msg.toolCallId);return normalizedId&&normalizedId!==msg.toolCallId?{...msg,toolCallId:normalizedId}:msg}if(msg.role==="assistant"){let assistantMsg=msg,isSameModel=assistantMsg.provider===model.provider&&assistantMsg.api===model.api&&assistantMsg.model===model.id,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking")return isSameModel?block.redacted||block.thinkingSignature?block:!block.thinking||block.thinking.trim()===""?[]:block:[];if(block.type==="text")return isSameModel?block:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall=toolCall;if(!isSameModel&&toolCall.thoughtSignature&&(normalizedToolCall={...toolCall},delete normalizedToolCall.thoughtSignature),!isSameModel&&normalizeToolCallId){let normalizedId=normalizeToolCallId(toolCall.id,model,assistantMsg);normalizedId!==toolCall.id&&(toolCallIdMap.set(toolCall.id,normalizedId),normalizedToolCall={...normalizedToolCall,id:normalizedId})}return normalizedToolCall}return block});return{...assistantMsg,content:transformedContent}}return msg}),result=[],pendingToolCalls=[],existingToolResultIds=new Set,heldSystemMessages=[],closePendingToolCalls=()=>{if(pendingToolCalls.length>0){for(let tc of pendingToolCalls)existingToolResultIds.has(tc.id)||result.push({role:"toolResult",toolCallId:tc.id,toolName:tc.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});pendingToolCalls=[],existingToolResultIds=new Set}result.push(...heldSystemMessages),heldSystemMessages.length=0};for(let i=0;i<transformed.length;i++){let msg=transformed[i];if(msg.role==="assistant"){closePendingToolCalls();let assistantMsg=msg;if(assistantMsg.stopReason==="error"||assistantMsg.stopReason==="aborted")continue;let toolCalls=assistantMsg.content.filter(b=>b.type==="toolCall");toolCalls.length>0&&(pendingToolCalls=toolCalls,existingToolResultIds=new Set),result.push(msg)}else msg.role==="toolResult"?(existingToolResultIds.add(msg.toolCallId),result.push(msg)):msg.role==="system"?pendingToolCalls.length>0?heldSystemMessages.push(msg):result.push(msg):(msg.role==="user"&&closePendingToolCalls(),result.push(msg))}return closePendingToolCalls(),result}export{prefersJsonSchemaStrictSampling,getJsonSchemaToolParameters,getGrammarToolInput,appendGrammarToolInputJsonDelta,closeGrammarToolInputJson,resolveJsonSchemaStrictSampling,resolveGrammarConstrainedSampling,createGrammarToolInputProperties,clampMaxTokensToContext,resolveSamplingParams,buildBaseOptions,thinkingBudgetForLevel,clampThinkingBudgetToAnswerRoom,adjustMaxTokensForThinking,splitErrorToolResultImages,transformMessages};
2
+ import{clampThinkingLevel}from"./chunk-3MKQN3ZR.js";import{getSystemMessageText}from"./chunk-6L2FT6AE.js";var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types=typeof schema.type=="string"?[schema.type]:Array.isArray(schema.type)?schema.type:[];return types.includes("object")||types.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.type===void 0&&schema.anyOf===void 0&&schema.enum===void 0)throw new UnsupportedStrictJsonSchemaError("schemas without a type are unsupported");if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items,isUnsupportedKeyword)}let isObjectSchema=schema.type==="object";if(schema.properties!==void 0&&!isObjectSchema)throw new UnsupportedStrictJsonSchemaError("properties require type object");if(!isObjectSchema)return;if(schema.additionalProperties!==void 0&&schema.additionalProperties!==!1)throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");if(schema.properties!==void 0&&!isJsonSchemaObject(schema.properties))throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");if(schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(key=>typeof key!="string")))throw new UnsupportedStrictJsonSchemaError("object required must be a string array");let properties=schema.properties??{},propertyNames=Object.keys(properties),required=new Set(Array.isArray(schema.required)?schema.required:[]);if([...required].some(key=>!propertyNames.includes(key)))throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");for(let[key,property]of Object.entries(properties))makeJsonSchemaNodeStrict(property,isUnsupportedKeyword),!required.has(key)&&!schemaAllowsNull(property)&&(properties[key]={anyOf:[property,{type:"null"}]});schema.required=propertyNames,schema.additionalProperties=!1}function makeStrictJsonSchema(schema,isUnsupportedKeyword){let cloned=structuredClone(schema);if(!isJsonSchemaObject(cloned))throw new UnsupportedStrictJsonSchemaError("root schema must have type object");if(makeJsonSchemaNodeStrict(cloned,isUnsupportedKeyword),cloned.type!=="object")throw new UnsupportedStrictJsonSchemaError("root schema must have type object");return cloned}function prefersJsonSchemaStrictSampling(tool){let config=tool.constrainedSampling;return!!config&&config.type==="json_schema"&&config.strict==="prefer"}function getJsonSchemaToolParameters(tool,strict){return strict===!0?makeStrictJsonSchema(tool.parameters):tool.parameters}function getGrammarToolInput(toolName,arguments_,inputProperty){let input=arguments_[inputProperty];if(typeof input!="string")throw new Error(`Grammar tool call "${toolName}" requires argument "${inputProperty}" to be a string.`);return input}function appendGrammarToolInputJsonDelta(buffer,inputProperty,inputDelta){if(buffer.closed)throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`);if(inputDelta.length!==0)return buffer.input+=inputDelta,grammarToolInputJsonStart(buffer,inputProperty)+JSON.stringify(inputDelta).slice(1,-1)}function closeGrammarToolInputJson(buffer,inputProperty,finalInput){if(buffer.closed){if(finalInput===void 0||finalInput===buffer.input)return;throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`)}if(finalInput!==void 0&&!finalInput.startsWith(buffer.input))throw new Error(`grammar tool input for property "${inputProperty}" changed non-monotonically`);let rest=finalInput===void 0?"":finalInput.slice(buffer.input.length);return finalInput!==void 0&&(buffer.input=finalInput),buffer.closed=!0,`${grammarToolInputJsonStart(buffer,inputProperty)}${JSON.stringify(rest).slice(1,-1)}"}`}function grammarToolInputJsonStart(buffer,inputProperty){return buffer.started?"":(buffer.started=!0,`{${JSON.stringify(inputProperty)}:"`)}function inferGrammarInputProperty(tool){let schema=tool.parameters;if(schema.type!=="object")throw new Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(schema.required)||schema.required.length!==1||typeof schema.required[0]!="string")throw new Error("grammar constrained sampling requires exactly one required string property");let inputProperty=schema.required[0];if(!schema.properties?.[inputProperty])throw new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);if(schema.properties[inputProperty]?.type!=="string")throw new Error(`grammar constrained sampling property ${inputProperty} must have type string`);return inputProperty}function resolveJsonSchemaStrictSampling(tool,supportsStrictMode,isUnsupportedKeyword){let config=tool.constrainedSampling;if(!(!config||config.type!=="json_schema")){if(supportsStrictMode)try{return makeStrictJsonSchema(tool.parameters,isUnsupportedKeyword),!0}catch(error){if(!(error instanceof UnsupportedStrictJsonSchemaError))throw error;if(config.strict!=="require")return;throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`)}if(config.strict==="require")throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools){let config=tool.constrainedSampling;if(!config||config.type!=="grammar"||!supportsOpenAIGrammarTools)return;let larkDefinition=config.variants.openai_lark,regexDefinition=config.variants.openai_regex,hasLarkDefinition=typeof larkDefinition=="string"&&larkDefinition.trim().length>0,hasRegexDefinition=typeof regexDefinition=="string"&&regexDefinition.trim().length>0;if(!hasLarkDefinition&&!hasRegexDefinition)throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:hasLarkDefinition?"lark":"regex",definition:hasLarkDefinition?larkDefinition:regexDefinition,inputProperty:inferGrammarInputProperty(tool)}}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: ${message}.`)}}function createGrammarToolInputProperties(tools,supportsOpenAIGrammarTools){let properties=new Map;for(let tool of tools??[]){let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);grammar&&properties.set(tool.name,grammar.inputProperty)}return properties}var CHARS_PER_TOKEN=3.5,ESTIMATED_IMAGE_CHARS=4800;function calculateContextTokens(usage){return usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function safeJsonStringify(value){try{return JSON.stringify(value)??"undefined"}catch{return"[unserializable]"}}function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars=0;for(let block of content)chars+=block.type==="text"?block.text.length:ESTIMATED_IMAGE_CHARS;return chars}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);for(let block of message.content)block.type==="text"?chars+=block.text.length:block.type==="thinking"?chars+=block.thinking.length:chars+=block.name.length+safeJsonStringify(block.arguments).length;return Math.ceil(chars/CHARS_PER_TOKEN)}function getLastAssistantUsageInfo(messages){let latestPrefixTimestamp=Number.NEGATIVE_INFINITY,usageInfo;for(let i=0;i<messages.length;i++){let message=messages[i];if(message.role==="assistant"){let assistant=message;assistant.timestamp>=latestPrefixTimestamp&&assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens(assistant.usage)>0&&(usageInfo={usage:assistant.usage,index:i})}latestPrefixTimestamp=Math.max(latestPrefixTimestamp,message.timestamp)}return usageInfo}function estimateContextTokens(context){let messages="messages"in context?context.messages:context,usageInfo=getLastAssistantUsageInfo(messages);if(usageInfo){let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=0;for(let i=usageInfo.index+1;i<messages.length;i++)trailingTokens+=estimateMessageTokens(messages[i]);return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}let tokens=0;for(let message of messages)tokens+=estimateMessageTokens(message);return{tokens,usageTokens:0,trailingTokens:tokens,lastUsageIndex:null}}function estimateToolsTokens(tools){return!tools||tools.length===0?0:estimateTextTokens(safeJsonStringify(tools))}var CONTEXT_SAFETY_TOKENS=4096,CONTEXT_SAFETY_RATIO=.15,MIN_OUTPUT_WITH_RATIO_MARGIN=32768,MIN_MAX_TOKENS=1;function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Math.max(MIN_MAX_TOKENS,maxTokens);let input=estimateContextTokens(context).tokens,margin=Math.max(CONTEXT_SAFETY_TOKENS,Math.ceil(input*CONTEXT_SAFETY_RATIO)),room=model.contextWindow-input-margin;return room<MIN_OUTPUT_WITH_RATIO_MARGIN&&(room=Math.min(MIN_OUTPUT_WITH_RATIO_MARGIN,model.contextWindow-input-CONTEXT_SAFETY_TOKENS)),Math.min(maxTokens,Math.max(MIN_MAX_TOKENS,room))}function resolveSamplingParams(model,thinkingLevel,requestParams){let effectiveThinkingLevel=clampThinkingLevel(model,thinkingLevel),thinkingLevelParams=model.samplingParamsByThinkingLevel?.[effectiveThinkingLevel];return model.samplingParams||thinkingLevelParams||requestParams?{...model.samplingParams,...thinkingLevelParams,...requestParams}:void 0}function buildBaseOptions(model,context,options,apiKey){let samplingParams=resolveSamplingParams(model,options?.reasoning??"off",options?.samplingParams);return{temperature:options?.temperature,samplingParams,maxTokens:clampMaxTokensToContext(model,context,options?.maxTokens??model.maxTokens),signal:options?.signal,telemetry:options?.telemetry,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention,sessionId:options?.sessionId,disableContinuation:options?.disableContinuation,headers:options?.headers,identity:options?.identity,onPayload:options?.onPayload,onResponse:options?.onResponse,onProviderStreamEvent:options?.onProviderStreamEvent,timeoutMs:options?.timeoutMs,websocketConnectTimeoutMs:options?.websocketConnectTimeoutMs,maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,metadata:options?.metadata,env:options?.env}}var MIN_ANSWER_TOKENS=1024,DEFAULT_THINKING_BUDGETS={minimal:1024,low:2048,medium:8192,high:16384};function clampReasoning(effort){return effort==="xhigh"||effort==="max"?"high":effort}function thinkingBudgetForLevel(reasoningLevel,customBudgets){let budgets={...DEFAULT_THINKING_BUDGETS,...customBudgets},level=clampReasoning(reasoningLevel);return budgets[level]}function clampThinkingBudgetToAnswerRoom(thinkingBudget,ceiling){return Math.min(thinkingBudget,Math.max(0,ceiling-MIN_ANSWER_TOKENS))}function adjustMaxTokensForThinking(baseMaxTokens,modelMaxTokens,reasoningLevel,customBudgets){let thinkingBudget=thinkingBudgetForLevel(reasoningLevel,customBudgets),maxTokens=baseMaxTokens===void 0?modelMaxTokens:Math.min(baseMaxTokens+thinkingBudget,modelMaxTokens);return maxTokens<=thinkingBudget&&(thinkingBudget=clampThinkingBudgetToAnswerRoom(thinkingBudget,maxTokens)),{maxTokens,thinkingBudget}}var NON_VISION_USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)",NON_VISION_TOOL_IMAGE_PLACEHOLDER="(tool image omitted: model does not support images)",ERROR_TOOL_IMAGE_PLACEHOLDER="(image attached after the tool results)";function splitErrorToolResultImages(msg){if(!msg.isError)return;let images=msg.content.filter(block=>block.type==="image");if(images.length!==0)return{content:replaceImagesWithPlaceholder(msg.content,ERROR_TOOL_IMAGE_PLACEHOLDER),caption:`Images from the error result of tool call ${msg.toolCallId} (${msg.toolName}):`,images}}function replaceImagesWithPlaceholder(content,placeholder){let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.text===placeholder}return result}function downgradeUnsupportedImages(messages,model){return model.input.includes("image")?messages:messages.map(msg=>msg.role==="user"&&Array.isArray(msg.content)?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_USER_IMAGE_PLACEHOLDER)}:msg.role==="toolResult"?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)}:msg)}function transformMessages(messages,model,normalizeToolCallId){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),transformed=downgradeUnsupportedImages(normalizedMessages,model).map(msg=>{if(msg.role==="system"||msg.role==="user")return msg;if(msg.role==="toolResult"){let normalizedId=toolCallIdMap.get(msg.toolCallId);return normalizedId&&normalizedId!==msg.toolCallId?{...msg,toolCallId:normalizedId}:msg}if(msg.role==="assistant"){let assistantMsg=msg,isSameModel=assistantMsg.provider===model.provider&&assistantMsg.api===model.api&&assistantMsg.model===model.id,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking")return isSameModel?block.redacted||block.thinkingSignature?block:!block.thinking||block.thinking.trim()===""?[]:block:[];if(block.type==="text")return isSameModel?block:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall=toolCall;if(!isSameModel&&toolCall.thoughtSignature&&(normalizedToolCall={...toolCall},delete normalizedToolCall.thoughtSignature),!isSameModel&&normalizeToolCallId){let normalizedId=normalizeToolCallId(toolCall.id,model,assistantMsg);normalizedId!==toolCall.id&&(toolCallIdMap.set(toolCall.id,normalizedId),normalizedToolCall={...normalizedToolCall,id:normalizedId})}return normalizedToolCall}return block});return{...assistantMsg,content:transformedContent}}return msg}),result=[],pendingToolCalls=[],existingToolResultIds=new Set,heldSystemMessages=[],closePendingToolCalls=()=>{if(pendingToolCalls.length>0){for(let tc of pendingToolCalls)existingToolResultIds.has(tc.id)||result.push({role:"toolResult",toolCallId:tc.id,toolName:tc.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});pendingToolCalls=[],existingToolResultIds=new Set}result.push(...heldSystemMessages),heldSystemMessages.length=0};for(let i=0;i<transformed.length;i++){let msg=transformed[i];if(msg.role==="assistant"){closePendingToolCalls();let assistantMsg=msg;if(assistantMsg.stopReason==="error"||assistantMsg.stopReason==="aborted")continue;let toolCalls=assistantMsg.content.filter(b=>b.type==="toolCall");toolCalls.length>0&&(pendingToolCalls=toolCalls,existingToolResultIds=new Set),result.push(msg)}else msg.role==="toolResult"?(existingToolResultIds.add(msg.toolCallId),result.push(msg)):msg.role==="system"?pendingToolCalls.length>0?heldSystemMessages.push(msg):result.push(msg):(msg.role==="user"&&closePendingToolCalls(),result.push(msg))}return closePendingToolCalls(),result}export{prefersJsonSchemaStrictSampling,getJsonSchemaToolParameters,getGrammarToolInput,appendGrammarToolInputJsonDelta,closeGrammarToolInputJson,resolveJsonSchemaStrictSampling,resolveGrammarConstrainedSampling,createGrammarToolInputProperties,clampMaxTokensToContext,resolveSamplingParams,buildBaseOptions,thinkingBudgetForLevel,clampThinkingBudgetToAnswerRoom,adjustMaxTokensForThinking,splitErrorToolResultImages,transformMessages};