@maincode-ai/matilda-code 0.21.13 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (252) hide show
  1. package/chunks/agent-IUINB66G.js +3 -0
  2. package/chunks/agent-headless-YA2RKYEZ.js +3 -0
  3. package/chunks/{askUserQuestion-BNSWGD26.js → askUserQuestion-RZYBOPLR.js} +3 -3
  4. package/chunks/ca-JKEHLTNL.js +23 -0
  5. package/chunks/chunk-225CZWD7.js +89 -0
  6. package/chunks/{chunk-MEV5XQI2.js → chunk-2XSB5XHX.js} +1 -1
  7. package/chunks/chunk-453BANK3.js +8 -0
  8. package/chunks/{chunk-6M5G5FBH.js → chunk-4UGPARBR.js} +1 -1
  9. package/chunks/{chunk-RNKDFE2S.js → chunk-5B2QERWR.js} +1 -1
  10. package/chunks/chunk-5ETLURI6.js +3 -0
  11. package/chunks/chunk-6NXVLJ3X.js +56 -0
  12. package/chunks/{chunk-QZI2ZGZY.js → chunk-7B65UIHB.js} +1 -1
  13. package/chunks/{chunk-27Q5KW3A.js → chunk-7E2YCGHS.js} +13 -13
  14. package/chunks/{chunk-DHDD5YJC.js → chunk-ARAB5QTM.js} +69 -69
  15. package/chunks/chunk-DUB7JMQV.js +13 -0
  16. package/chunks/chunk-G3F3ZCH2.js +9 -0
  17. package/chunks/chunk-GT6MSEK4.js +3 -0
  18. package/chunks/chunk-HEJO7OBH.js +3 -0
  19. package/chunks/{chunk-6T2GIM76.js → chunk-IHWAOFCQ.js} +1 -1
  20. package/chunks/chunk-ILHNCXBC.js +8 -0
  21. package/chunks/chunk-J3ZCE3TA.js +8 -0
  22. package/chunks/{chunk-AOOZREGV.js → chunk-LBQNFSZ2.js} +1 -1
  23. package/chunks/{chunk-5OHGYMKP.js → chunk-LM6OIN4B.js} +1 -1
  24. package/chunks/{chunk-EZDV7A76.js → chunk-LMZBADPW.js} +1 -1
  25. package/chunks/chunk-MGRXOZAG.js +8 -0
  26. package/chunks/chunk-NBLBE7PE.js +2609 -0
  27. package/chunks/chunk-POGNX7U3.js +31 -0
  28. package/chunks/chunk-PQZ6HKKW.js +80 -0
  29. package/chunks/chunk-QXSBPCBA.js +8 -0
  30. package/chunks/chunk-RHSUTILA.js +9 -0
  31. package/chunks/{chunk-P5TG5CON.js → chunk-RPXRN7E6.js} +1 -1
  32. package/chunks/chunk-TUKNB5CQ.js +33 -0
  33. package/chunks/chunk-UM6CLO7D.js +7 -0
  34. package/chunks/chunk-V2VUANFI.js +120 -0
  35. package/chunks/chunk-V4VILMIK.js +14 -0
  36. package/chunks/chunk-ZSGBDQXU.js +11 -0
  37. package/chunks/{computer-use-J4GAM4M6.js → computer-use-PBCWDTJR.js} +1 -1
  38. package/chunks/{cron-create-IDWSZENI.js → cron-create-PHQ43NYA.js} +1 -1
  39. package/chunks/cron-delete-7RCQIU2U.js +3 -0
  40. package/chunks/cron-list-KKNLLMNN.js +5 -0
  41. package/chunks/de-GMGNR5CZ.js +23 -0
  42. package/chunks/{devtools-XRQ4YJ5S.js → devtools-7YNCRYZV.js} +1 -1
  43. package/chunks/{chunk-OOEH6ZSV.js → dist-UWUWLWTO.js} +2 -2
  44. package/chunks/{edit-X2S2ZXRN.js → edit-ELHNQB5E.js} +1 -1
  45. package/chunks/en-3NQMLVKW.js +23 -0
  46. package/chunks/{enter-worktree-TUCGNCLO.js → enter-worktree-UZIBOBV3.js} +1 -1
  47. package/chunks/enterPlanMode-UHY3DZXE.js +18 -0
  48. package/chunks/{exit-worktree-7FLITFZI.js → exit-worktree-HLG4PDMX.js} +1 -1
  49. package/chunks/{exitPlanMode-O5UUJ3GM.js → exitPlanMode-V4HYNH3J.js} +2 -2
  50. package/chunks/fr-WS3EBB36.js +23 -0
  51. package/chunks/{getMachineId-bsd-ZYBNK2JG.js → getMachineId-bsd-ETKQTB6C.js} +1 -1
  52. package/chunks/{getMachineId-darwin-CM2MQGUI.js → getMachineId-darwin-AKNRWOWB.js} +1 -1
  53. package/chunks/{getMachineId-linux-SYE2KMCW.js → getMachineId-linux-2QSD7FTP.js} +1 -1
  54. package/chunks/{getMachineId-unsupported-6IHVG2XO.js → getMachineId-unsupported-UXSV7I24.js} +1 -1
  55. package/chunks/{getMachineId-win-S3J3JSUM.js → getMachineId-win-4MTFXGP3.js} +1 -1
  56. package/chunks/glob-C5CTWXLP.js +22 -0
  57. package/chunks/{goal-tools-YQOA6OKU.js → goal-tools-BGIWEJ3K.js} +3 -3
  58. package/chunks/{grep-VAB2VSXM.js → grep-BEFTGKHW.js} +1 -1
  59. package/chunks/ja-GBCDQ43R.js +23 -0
  60. package/chunks/keychain-token-storage-FEJZYJBB.js +3 -0
  61. package/chunks/ls-XH55NAD3.js +15 -0
  62. package/chunks/{lsp-NGLDRHZU.js → lsp-BKDCR37G.js} +1 -1
  63. package/chunks/mcp-client-GAQG7MCT.js +3 -0
  64. package/chunks/monitor-NSVUUKCM.js +32 -0
  65. package/chunks/{multipart-parser-JI75T2O5.js → multipart-parser-FKHYAVGR.js} +1 -1
  66. package/chunks/notebook-edit-AXKYC64C.js +17 -0
  67. package/chunks/openaiContentGenerator-66YY6CIM.js +47 -0
  68. package/chunks/pt-VID6J2CM.js +23 -0
  69. package/chunks/read-file-YFJMLS7V.js +3 -0
  70. package/chunks/ripGrep-BEHEB23R.js +3 -0
  71. package/chunks/ru-EB6V6EAN.js +23 -0
  72. package/chunks/scheduler-GKQOREMS.js +8 -0
  73. package/chunks/send-message-GJSEMAZB.js +8 -0
  74. package/chunks/shell-J5Q2UEXH.js +3 -0
  75. package/chunks/{skill-ETQM5NI3.js → skill-3RWNSUNE.js} +1 -1
  76. package/chunks/src-LZEU4AYF.js +5 -0
  77. package/chunks/symbol-search-4VM6J5Y4.js +19 -0
  78. package/chunks/{syntheticOutput-WZDPECYS.js → syntheticOutput-O7LEF3AM.js} +1 -1
  79. package/chunks/task-create-N4IRJBTF.js +3 -0
  80. package/chunks/{task-detach-TBAVUOTC.js → task-detach-RGNQUX3H.js} +1 -1
  81. package/chunks/task-list-Z7JUB4QK.js +9 -0
  82. package/chunks/{task-stop-HDSARSJ6.js → task-stop-L2OWK2PJ.js} +1 -1
  83. package/chunks/{task-update-MW2VT2XV.js → task-update-H5AXVXDS.js} +1 -1
  84. package/chunks/{team-create-VMYNLZCC.js → team-create-FWTIQ2FT.js} +2 -2
  85. package/chunks/team-delete-D45ALROH.js +8 -0
  86. package/chunks/todoWrite-LCQOQBI7.js +3 -0
  87. package/chunks/{tool-search-WX6FOE35.js → tool-search-X6UUCSPU.js} +1 -1
  88. package/chunks/{web-fetch-CKYBHGLF.js → web-fetch-244KUWSX.js} +17 -17
  89. package/chunks/web-search-YRZ3BZ3X.js +26 -0
  90. package/chunks/{workflow-WBSRQG3N.js → workflow-EP4AFR24.js} +2 -2
  91. package/chunks/write-file-EXWGRN4Q.js +15 -0
  92. package/cli.js +641 -678
  93. package/examples/starter/README.md +0 -3
  94. package/locales/ca.js +3 -87
  95. package/locales/de.js +3 -91
  96. package/locales/en.js +3 -91
  97. package/locales/fr.js +3 -88
  98. package/locales/ja.js +3 -92
  99. package/locales/pt.js +3 -92
  100. package/locales/ru.js +3 -91
  101. package/package.json +2 -2
  102. package/sandbox-macos-permissive-proxied.sb +1 -1
  103. package/sandbox-macos-restrictive-closed.sb +14 -1
  104. package/sandbox-macos-restrictive-open.sb +14 -1
  105. package/sandbox-macos-restrictive-proxied.sb +15 -2
  106. package/bundled/mainy/SKILL.md +0 -157
  107. package/bundled/mainy/docs/_meta.ts +0 -32
  108. package/bundled/mainy/docs/common-workflow.md +0 -571
  109. package/bundled/mainy/docs/configuration/_meta.ts +0 -7
  110. package/bundled/mainy/docs/configuration/auth.md +0 -82
  111. package/bundled/mainy/docs/configuration/matilda-ignore.md +0 -55
  112. package/bundled/mainy/docs/configuration/model-providers.md +0 -516
  113. package/bundled/mainy/docs/configuration/settings.md +0 -818
  114. package/bundled/mainy/docs/configuration/themes.md +0 -199
  115. package/bundled/mainy/docs/configuration/trusted-folders.md +0 -67
  116. package/bundled/mainy/docs/extension/_meta.ts +0 -9
  117. package/bundled/mainy/docs/extension/extension-releasing.md +0 -204
  118. package/bundled/mainy/docs/extension/getting-started-extensions.md +0 -299
  119. package/bundled/mainy/docs/extension/introduction.md +0 -338
  120. package/bundled/mainy/docs/features/_meta.ts +0 -27
  121. package/bundled/mainy/docs/features/approval-mode.md +0 -388
  122. package/bundled/mainy/docs/features/arena.md +0 -219
  123. package/bundled/mainy/docs/features/auto-mode.md +0 -308
  124. package/bundled/mainy/docs/features/channels/_meta.ts +0 -5
  125. package/bundled/mainy/docs/features/channels/overview.md +0 -328
  126. package/bundled/mainy/docs/features/channels/plugins.md +0 -87
  127. package/bundled/mainy/docs/features/channels/telegram.md +0 -120
  128. package/bundled/mainy/docs/features/code-review.md +0 -291
  129. package/bundled/mainy/docs/features/commands.md +0 -528
  130. package/bundled/mainy/docs/features/dual-output.md +0 -627
  131. package/bundled/mainy/docs/features/followup-suggestions.md +0 -109
  132. package/bundled/mainy/docs/features/headless.md +0 -448
  133. package/bundled/mainy/docs/features/hooks.md +0 -1308
  134. package/bundled/mainy/docs/features/language.md +0 -144
  135. package/bundled/mainy/docs/features/lsp.md +0 -496
  136. package/bundled/mainy/docs/features/markdown-rendering.md +0 -183
  137. package/bundled/mainy/docs/features/mcp.md +0 -423
  138. package/bundled/mainy/docs/features/memory.md +0 -185
  139. package/bundled/mainy/docs/features/sandbox.md +0 -249
  140. package/bundled/mainy/docs/features/scheduled-tasks.md +0 -139
  141. package/bundled/mainy/docs/features/skills.md +0 -347
  142. package/bundled/mainy/docs/features/status-line.md +0 -397
  143. package/bundled/mainy/docs/features/structured-output.md +0 -309
  144. package/bundled/mainy/docs/features/sub-agents.md +0 -737
  145. package/bundled/mainy/docs/features/tips.md +0 -54
  146. package/bundled/mainy/docs/features/token-caching.md +0 -29
  147. package/bundled/mainy/docs/features/tool-use-summaries.md +0 -178
  148. package/bundled/mainy/docs/features/worktree.md +0 -343
  149. package/bundled/mainy/docs/ide-integration/_meta.ts +0 -4
  150. package/bundled/mainy/docs/ide-integration/ide-companion-spec.md +0 -182
  151. package/bundled/mainy/docs/ide-integration/ide-integration.md +0 -144
  152. package/bundled/mainy/docs/integration-github-action.md +0 -241
  153. package/bundled/mainy/docs/integration-jetbrains.md +0 -81
  154. package/bundled/mainy/docs/integration-vscode.md +0 -39
  155. package/bundled/mainy/docs/integration-zed.md +0 -72
  156. package/bundled/mainy/docs/matilda-serve-deploy-local.md +0 -221
  157. package/bundled/mainy/docs/matilda-serve.md +0 -661
  158. package/bundled/mainy/docs/overview.md +0 -64
  159. package/bundled/mainy/docs/quickstart.md +0 -234
  160. package/bundled/mainy/docs/reference/_meta.ts +0 -3
  161. package/bundled/mainy/docs/reference/keyboard-shortcuts.md +0 -91
  162. package/bundled/mainy/docs/support/Uninstall.md +0 -65
  163. package/bundled/mainy/docs/support/_meta.ts +0 -6
  164. package/bundled/mainy/docs/support/tos-privacy.md +0 -94
  165. package/bundled/mainy/docs/support/troubleshooting.md +0 -127
  166. package/chunks/agent-SRAIVZEE.js +0 -3
  167. package/chunks/agent-headless-XRDOZESG.js +0 -3
  168. package/chunks/anthropicContentGenerator-LLDIKDMQ.js +0 -39
  169. package/chunks/ca-NPYL24ME.js +0 -25
  170. package/chunks/chunk-27HUYW23.js +0 -22
  171. package/chunks/chunk-2HTPVSGT.js +0 -3
  172. package/chunks/chunk-3B2HABK7.js +0 -30
  173. package/chunks/chunk-3MTZTNAU.js +0 -101
  174. package/chunks/chunk-3YLXGE6T.js +0 -8
  175. package/chunks/chunk-47XR7IMP.js +0 -8
  176. package/chunks/chunk-4F4DA5UI.js +0 -8
  177. package/chunks/chunk-4Q2SNBUH.js +0 -18
  178. package/chunks/chunk-6EQMZNIY.js +0 -8
  179. package/chunks/chunk-6I6VGTKD.js +0 -8
  180. package/chunks/chunk-DC7LAFZZ.js +0 -8
  181. package/chunks/chunk-DE3HKC2W.js +0 -9
  182. package/chunks/chunk-FWDMPRKU.js +0 -3
  183. package/chunks/chunk-G7R2XEEF.js +0 -7
  184. package/chunks/chunk-GOJCMVJJ.js +0 -8
  185. package/chunks/chunk-GTVCJCHR.js +0 -8
  186. package/chunks/chunk-IJEGHQ7Z.js +0 -32
  187. package/chunks/chunk-JCE3JAVC.js +0 -25
  188. package/chunks/chunk-KHHJYBR5.js +0 -9
  189. package/chunks/chunk-LUNDTQ3G.js +0 -8
  190. package/chunks/chunk-LWARA7JY.js +0 -37
  191. package/chunks/chunk-M53RP3YP.js +0 -31
  192. package/chunks/chunk-MTMU7JYZ.js +0 -11
  193. package/chunks/chunk-O44XK65C.js +0 -8
  194. package/chunks/chunk-OA56BXPD.js +0 -3
  195. package/chunks/chunk-PEKAUGYV.js +0 -2621
  196. package/chunks/chunk-PGUG43HG.js +0 -24
  197. package/chunks/chunk-PGXQZVLX.js +0 -8
  198. package/chunks/chunk-QKYGQLWC.js +0 -8
  199. package/chunks/chunk-QN6Y6NPA.js +0 -3
  200. package/chunks/chunk-RI54U73U.js +0 -56
  201. package/chunks/chunk-RPFSFS7Z.js +0 -39
  202. package/chunks/chunk-SDTWBD62.js +0 -8
  203. package/chunks/chunk-SOEIVSM5.js +0 -113
  204. package/chunks/chunk-SVSY6AWS.js +0 -59
  205. package/chunks/chunk-T2T2UEPY.js +0 -4
  206. package/chunks/chunk-TISQNFB5.js +0 -3
  207. package/chunks/chunk-TWJLOEAI.js +0 -31
  208. package/chunks/chunk-VI74YQQO.js +0 -8
  209. package/chunks/chunk-VYZOOSMP.js +0 -30
  210. package/chunks/chunk-W4QSMIWO.js +0 -9
  211. package/chunks/chunk-WC2VTVCE.js +0 -27
  212. package/chunks/chunk-YV3PUOBU.js +0 -65
  213. package/chunks/chunk-ZX34M2GF.js +0 -14
  214. package/chunks/contextCommand-5F5M7NA4.js +0 -3
  215. package/chunks/cron-delete-NQCDZDUI.js +0 -3
  216. package/chunks/cron-list-Z4XMC3TO.js +0 -5
  217. package/chunks/de-34YZHGC6.js +0 -25
  218. package/chunks/dist-7UYRLSLE.js +0 -3
  219. package/chunks/dist-PH6JW7XD.js +0 -42
  220. package/chunks/en-QLGMD6OS.js +0 -25
  221. package/chunks/enterPlanMode-SQEZAAIR.js +0 -18
  222. package/chunks/fileFromPath-7UCWPD4W.js +0 -3
  223. package/chunks/fr-EDNBQACJ.js +0 -25
  224. package/chunks/geminiContentGenerator-FIZFLPU3.js +0 -8
  225. package/chunks/glob-GSFTYAS2.js +0 -22
  226. package/chunks/ja-LV4RLM3M.js +0 -25
  227. package/chunks/keychain-token-storage-KQK6MNOJ.js +0 -3
  228. package/chunks/ls-IZJ3CKZY.js +0 -15
  229. package/chunks/matildaAgentContentGenerator-QQHPCFJ5.js +0 -8
  230. package/chunks/matildaContentGenerator-W7Z33ONU.js +0 -8
  231. package/chunks/matildaOAuth2-7COTQQR2.js +0 -3
  232. package/chunks/mcp-client-DXUNIEIB.js +0 -3
  233. package/chunks/monitor-4PFIGAGG.js +0 -32
  234. package/chunks/notebook-edit-MWJYAATJ.js +0 -17
  235. package/chunks/openaiContentGenerator-NDVJL6QL.js +0 -3
  236. package/chunks/pt-5SQ4DGL7.js +0 -25
  237. package/chunks/read-file-WPZKPXWA.js +0 -3
  238. package/chunks/ripGrep-7LZDZFTX.js +0 -3
  239. package/chunks/ru-7K24S53N.js +0 -25
  240. package/chunks/scheduler-DK2MVKXX.js +0 -8
  241. package/chunks/send-message-TCPX5UDU.js +0 -8
  242. package/chunks/serve-GSZPJI2O.js +0 -1026
  243. package/chunks/shell-PRS47PDP.js +0 -3
  244. package/chunks/src-UB7DZRYK.js +0 -3
  245. package/chunks/src-WZTRMETQ.js +0 -5
  246. package/chunks/symbol-search-HARHZ5AH.js +0 -19
  247. package/chunks/task-create-XRNIDT4T.js +0 -3
  248. package/chunks/task-list-Z6BDZZID.js +0 -9
  249. package/chunks/team-delete-F7QDC2TE.js +0 -8
  250. package/chunks/todoWrite-SCF5M24M.js +0 -3
  251. package/chunks/web-search-67DFNS5V.js +0 -26
  252. package/chunks/write-file-S5FAX4JJ.js +0 -15
@@ -1,127 +0,0 @@
1
- # Troubleshooting
2
-
3
- This guide provides solutions to common issues and debugging tips, including topics on:
4
-
5
- - Authentication or login errors
6
- - Frequently asked questions (FAQs)
7
- - Debugging tips
8
- - Existing GitHub Issues similar to yours or creating new Issues
9
-
10
- ## Authentication or login errors
11
-
12
- - **Error: `Matilda OAuth free tier was discontinued on 2026-04-15`**
13
- - **Cause:** Matilda OAuth is no longer available as of April 15, 2026.
14
- - **Solution:** Switch to a different authentication method. Run `matilda` → `/auth` and choose one of:
15
-
16
- - **Error: `UNABLE_TO_GET_ISSUER_CERT_LOCALLY`, `UNABLE_TO_VERIFY_LEAF_SIGNATURE`, or `unable to get local issuer certificate`**
17
- - **Cause:** You may be on a corporate network with a firewall that intercepts and inspects SSL/TLS traffic. This often requires a custom root CA certificate to be trusted by Node.js.
18
- - **Solution:** Set the `NODE_EXTRA_CA_CERTS` environment variable to the absolute path of your corporate root CA certificate file.
19
- - Example: `export NODE_EXTRA_CA_CERTS=/path/to/your/corporate-ca.crt`
20
-
21
- - **Error: `Device authorization flow failed: fetch failed`**
22
- - **Cause:** Node.js could not reach Matilda OAuth endpoints (often a proxy or SSL/TLS trust issue). When available, Matilda Code will also print the underlying error cause (for example: `UNABLE_TO_VERIFY_LEAF_SIGNATURE`). Note: this error is specific to the legacy Matilda OAuth flow.
23
- - **Solution:**
24
- - If you are still using Matilda OAuth, switch to a Matilda account or API token via `/auth`.
25
- - If you are behind a proxy, set it via `matilda --proxy <url>` (or the `proxy` setting in `settings.json`).
26
- - If your network uses a corporate TLS inspection CA, set `NODE_EXTRA_CA_CERTS` as described above.
27
-
28
- - **Issue: Unable to display UI after authentication failure**
29
- - **Cause:** If authentication fails after selecting an authentication type, the `security.auth.selectedType` setting may be persisted in `settings.json`. On restart, the CLI may get stuck trying to authenticate with the failed auth type and fail to display the UI.
30
- - **Solution:** Clear the `security.auth.selectedType` configuration item in your `settings.json` file:
31
- - Open `~/.matilda/settings.json` (or `./.matilda/settings.json` for project-specific settings)
32
- - Remove the `security.auth.selectedType` field
33
- - Restart the CLI to allow it to prompt for authentication again
34
-
35
- ## Frequently asked questions (FAQs)
36
-
37
- - **Q: How do I update Matilda Code to the latest version?**
38
- - A: If you installed Matilda Code with the standalone installer, rerun the standalone install command. If you installed it globally via `npm`, update it using the command `npm install -g @maincode-ai/matilda-code@latest`. If you compiled it from source, pull the latest changes from the repository, and then rebuild using the command `npm run build`.
39
-
40
- - **Q: Where are the Matilda Code configuration or settings files stored?**
41
- - A: The Matilda Code configuration is stored in two `settings.json` files:
42
- 1. In your home directory: `~/.matilda/settings.json`.
43
- 2. In your project's root directory: `./.matilda/settings.json`.
44
-
45
- Refer to [Matilda Code Configuration](../configuration/settings) for more details.
46
-
47
- - **Q: Why don't I see cached token counts in my stats output?**
48
-
49
- ## Common error messages and solutions
50
-
51
- - **Error: `EADDRINUSE` (Address already in use) when starting an MCP server.**
52
- - **Cause:** Another process is already using the port that the MCP server is trying to bind to.
53
- - **Solution:**
54
- Either stop the other process that is using the port or configure the MCP server to use a different port.
55
-
56
- - **Error: Command not found (when attempting to run Matilda Code with `matilda`).**
57
- - **Cause:** The CLI is not correctly installed or it is not in your system's `PATH`.
58
- - **Solution:**
59
- The update depends on how you installed Matilda Code:
60
- - If you installed `matilda` with the standalone installer, rerun the standalone install command and then open a new terminal.
61
- - If you installed `matilda` globally, check that your `npm` global binary directory is in your `PATH`. You can update using the command `npm install -g @maincode-ai/matilda-code@latest`.
62
- - If you are running `matilda` from source, ensure you are using the correct command to invoke it (e.g. `node packages/cli/dist/index.js ...`). To update, pull the latest changes from the repository, and then rebuild using the command `npm run build`.
63
-
64
- - **Error: `MODULE_NOT_FOUND` or import errors.**
65
- - **Cause:** Dependencies are not installed correctly, or the project hasn't been built.
66
- - **Solution:**
67
- 1. Run `npm install` to ensure all dependencies are present.
68
- 2. Run `npm run build` to compile the project.
69
- 3. Verify that the build completed successfully with `npm run start`.
70
-
71
- - **Error: "Operation not permitted", "Permission denied", or similar.**
72
- - **Cause:** When sandboxing is enabled, Matilda Code may attempt operations that are restricted by your sandbox configuration, such as writing outside the project directory or system temp directory.
73
- - **Solution:** Refer to the [Configuration: Sandboxing](../features/sandbox) documentation for more information, including how to customize your sandbox configuration.
74
-
75
- - **Matilda Code is not running in interactive mode in "CI" environments**
76
- - **Issue:** Matilda Code does not enter interactive mode (no prompt appears) if an environment variable starting with `CI_` (e.g. `CI_TOKEN`) is set. This is because the `is-in-ci` package, used by the underlying UI framework, detects these variables and assumes a non-interactive CI environment.
77
- - **Cause:** The `is-in-ci` package checks for the presence of `CI`, `CONTINUOUS_INTEGRATION`, or any environment variable with a `CI_` prefix. When any of these are found, it signals that the environment is non-interactive, which prevents the CLI from starting in its interactive mode.
78
- - **Solution:** If the `CI_` prefixed variable is not needed for the CLI to function, you can temporarily unset it for the command. e.g. `env -u CI_TOKEN matilda`
79
-
80
- - **DEBUG mode not working from project .env file**
81
- - **Issue:** Setting `DEBUG=true` in a project's `.env` file doesn't enable debug mode for the CLI.
82
- - **Cause:** The `DEBUG` and `DEBUG_MODE` variables are automatically excluded from project `.env` files to prevent interference with the CLI behavior.
83
- - **Solution:** Use a `.matilda/.env` file instead, or configure the `advanced.excludedEnvVars` setting in your `settings.json` to exclude fewer variables.
84
-
85
- ## IDE Companion not connecting
86
-
87
- - Ensure VS Code has a single workspace folder open.
88
- - Restart the integrated terminal after installing the extension so it inherits:
89
- - `MATILDA_CODE_IDE_WORKSPACE_PATH`
90
- - `MATILDA_CODE_IDE_SERVER_PORT`
91
- - If running in a container, verify `host.docker.internal` resolves. Otherwise, map the host appropriately.
92
- - Reinstall the companion with `/ide install` and use “Matilda Code: Run” in the Command Palette to verify it launches.
93
-
94
- ## Exit Codes
95
-
96
- The Matilda Code uses specific exit codes to indicate the reason for termination. This is especially useful for scripting and automation.
97
-
98
- | Exit Code | Error Type | Description |
99
- | --------- | -------------------------- | --------------------------------------------------------------------------------------------------- |
100
- | 41 | `FatalAuthenticationError` | An error occurred during the authentication process. |
101
- | 42 | `FatalInputError` | Invalid or missing input was provided to the CLI. (non-interactive mode only) |
102
- | 44 | `FatalSandboxError` | An error occurred with the sandboxing environment (e.g. Docker, Podman, or Seatbelt). |
103
- | 52 | `FatalConfigError` | A configuration file (`settings.json`) is invalid or contains errors. |
104
- | 53 | `FatalTurnLimitedError` | The maximum number of conversational turns for the session was reached. (non-interactive mode only) |
105
-
106
- ## Debugging Tips
107
-
108
- - **CLI debugging:**
109
- - Use the `--verbose` flag (if available) with CLI commands for more detailed output.
110
- - Check the CLI logs, often found in a user-specific configuration or cache directory.
111
-
112
- - **Core debugging:**
113
- - Check the server console output for error messages or stack traces.
114
- - Increase log verbosity if configurable.
115
- - Use Node.js debugging tools (e.g. `node --inspect`) if you need to step through server-side code.
116
-
117
- - **Tool issues:**
118
- - If a specific tool is failing, try to isolate the issue by running the simplest possible version of the command or operation the tool performs.
119
- - For `run_shell_command`, check that the command works directly in your shell first.
120
- - For _file system tools_, verify that paths are correct and check the permissions.
121
-
122
- - **Pre-flight checks:**
123
- - Always run `npm run preflight` before committing code. This can catch many common issues related to formatting, linting, and type errors.
124
-
125
- ## Existing GitHub Issues similar to yours or creating new Issues
126
-
127
- If you encounter an issue that was not covered here in this _Troubleshooting guide_, consider searching the Matilda Code [Issue tracker on GitHub](https://github.com/MaincodeHQ/matilda-code/issues). If you can't find an issue similar to yours, consider creating a new GitHub Issue with a detailed description. Pull requests are also welcome!
@@ -1,3 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{Pg as a,Qg as b,Rg as c,Sg as d,Tg as e,Ug as f}from"./chunk-PEKAUGYV.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-2HTPVSGT.js";import"./chunk-W4QSMIWO.js";import"./chunk-6I6VGTKD.js";import"./chunk-ZX34M2GF.js";import"./chunk-47XR7IMP.js";import"./chunk-MTMU7JYZ.js";import"./chunk-QKYGQLWC.js";import"./chunk-EZDV7A76.js";import"./chunk-RNKDFE2S.js";import"./chunk-RI54U73U.js";import"./chunk-6M5G5FBH.js";import"./chunk-QZI2ZGZY.js";import"./chunk-V6UPUMP3.js";import"./chunk-WC2VTVCE.js";import"./chunk-KHHJYBR5.js";import"./chunk-6EQMZNIY.js";import"./chunk-P5TG5CON.js";import"./chunk-DE3HKC2W.js";import"./chunk-GTVCJCHR.js";import"./chunk-IJEGHQ7Z.js";import"./chunk-PGUG43HG.js";import"./chunk-7ZODGQO6.js";import"./chunk-TISQNFB5.js";import"./chunk-VI74YQQO.js";import"./chunk-YV3PUOBU.js";import"./chunk-SOEIVSM5.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-3YLXGE6T.js";import"./chunk-JCE3JAVC.js";import"./chunk-SVSY6AWS.js";import"./chunk-AOOZREGV.js";import"./chunk-SDTWBD62.js";import"./chunk-DHDD5YJC.js";import"./chunk-PGXQZVLX.js";import"./chunk-LUNDTQ3G.js";import"./chunk-5OHGYMKP.js";import"./chunk-TWJLOEAI.js";import"./chunk-27Q5KW3A.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{f as AgentTool,b as TOOL_REGISTRY_REBUILT,e as createApprovalModeOverride,c as hasRebuiltToolRegistry,d as rebuildToolRegistryOnOverride,a as resolveSubagentApprovalMode};
@@ -1,3 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{ng as a,og as b,pg as c}from"./chunk-PEKAUGYV.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-2HTPVSGT.js";import"./chunk-W4QSMIWO.js";import"./chunk-6I6VGTKD.js";import"./chunk-ZX34M2GF.js";import"./chunk-47XR7IMP.js";import"./chunk-MTMU7JYZ.js";import"./chunk-QKYGQLWC.js";import"./chunk-EZDV7A76.js";import"./chunk-RNKDFE2S.js";import"./chunk-RI54U73U.js";import"./chunk-6M5G5FBH.js";import"./chunk-QZI2ZGZY.js";import"./chunk-V6UPUMP3.js";import"./chunk-WC2VTVCE.js";import"./chunk-KHHJYBR5.js";import"./chunk-6EQMZNIY.js";import"./chunk-P5TG5CON.js";import"./chunk-DE3HKC2W.js";import"./chunk-GTVCJCHR.js";import"./chunk-IJEGHQ7Z.js";import"./chunk-PGUG43HG.js";import"./chunk-7ZODGQO6.js";import"./chunk-TISQNFB5.js";import"./chunk-VI74YQQO.js";import"./chunk-YV3PUOBU.js";import"./chunk-SOEIVSM5.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-3YLXGE6T.js";import"./chunk-JCE3JAVC.js";import"./chunk-SVSY6AWS.js";import"./chunk-AOOZREGV.js";import"./chunk-SDTWBD62.js";import"./chunk-DHDD5YJC.js";import"./chunk-PGXQZVLX.js";import"./chunk-LUNDTQ3G.js";import"./chunk-5OHGYMKP.js";import"./chunk-TWJLOEAI.js";import"./chunk-27Q5KW3A.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{c as AgentHeadless,a as ContextState,b as templateString};
@@ -1,39 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{a as xr,b as Tr}from"./chunk-QN6Y6NPA.js";import{a as M,b as rt,c as Se,d as Pn}from"./chunk-4Q2SNBUH.js";import{a as En}from"./chunk-GOJCMVJJ.js";import{c as An,f as we}from"./chunk-YV3PUOBU.js";import{b as wn,c as Sn,d as kn,g as nt,o as Cn,t as xn,v as Tn}from"./chunk-JCE3JAVC.js";import{b as ee,e as tt}from"./chunk-SVSY6AWS.js";import"./chunk-AOOZREGV.js";import{f as bn}from"./chunk-SDTWBD62.js";import{ba as _n}from"./chunk-27Q5KW3A.js";import{a as Cr}from"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as c}from"./chunk-GZPNIYVZ.js";import{a as et,d as _e,f as jt}from"./chunk-OWGSC52X.js";var jn=_e((oo,Ln)=>{"use strict";c();var Or=et("util"),Br=Cr();Ln.exports=function(r){if(typeof r=="number")return r;var e=Br(r);if(e===void 0){var t=new Error(Or.format("humanize-ms(%j) result undefined",r));console.warn(t.stack)}return e}});var ct=_e((ao,qn)=>{"use strict";c();qn.exports={CURRENT_ID:Symbol("agentkeepalive#currentId"),CREATE_ID:Symbol("agentkeepalive#createId"),INIT_SOCKET:Symbol("agentkeepalive#initSocket"),CREATE_HTTPS_CONNECTION:Symbol("agentkeepalive#createHttpsConnection"),SOCKET_CREATED_TIME:Symbol("agentkeepalive#socketCreatedTime"),SOCKET_NAME:Symbol("agentkeepalive#socketName"),SOCKET_REQUEST_COUNT:Symbol("agentkeepalive#socketRequestCount"),SOCKET_REQUEST_FINISHED_COUNT:Symbol("agentkeepalive#socketRequestFinishedCount")}});var Kt=_e((uo,$n)=>{"use strict";c();var Lr=et("http").Agent,$t=jn(),P=et("util").debuglog("agentkeepalive"),{INIT_SOCKET:Dn,CURRENT_ID:ut,CREATE_ID:Nn,SOCKET_CREATED_TIME:Un,SOCKET_NAME:R,SOCKET_REQUEST_COUNT:v,SOCKET_REQUEST_FINISHED_COUNT:j}=ct(),Ht=1,Gt=parseInt(process.version.split(".",1)[0].substring(1));Gt>=11&&Gt<=12?Ht=2:Gt>=13&&(Ht=3);function ke(r){console.log("[agentkeepalive:deprecated] %s",r)}var Jt=class extends Lr{constructor(e){e=e||{},e.keepAlive=e.keepAlive!==!1,e.freeSocketTimeout===void 0&&(e.freeSocketTimeout=4e3),e.keepAliveTimeout&&(ke("options.keepAliveTimeout is deprecated, please use options.freeSocketTimeout instead"),e.freeSocketTimeout=e.keepAliveTimeout,delete e.keepAliveTimeout),e.freeSocketKeepAliveTimeout&&(ke("options.freeSocketKeepAliveTimeout is deprecated, please use options.freeSocketTimeout instead"),e.freeSocketTimeout=e.freeSocketKeepAliveTimeout,delete e.freeSocketKeepAliveTimeout),e.timeout===void 0&&(e.timeout=Math.max(e.freeSocketTimeout*2,8e3)),e.timeout=$t(e.timeout),e.freeSocketTimeout=$t(e.freeSocketTimeout),e.socketActiveTTL=e.socketActiveTTL?$t(e.socketActiveTTL):0,super(e),this[ut]=0,this.createSocketCount=0,this.createSocketCountLastCheck=0,this.createSocketErrorCount=0,this.createSocketErrorCountLastCheck=0,this.closeSocketCount=0,this.closeSocketCountLastCheck=0,this.errorSocketCount=0,this.errorSocketCountLastCheck=0,this.requestCount=0,this.requestCountLastCheck=0,this.timeoutSocketCount=0,this.timeoutSocketCountLastCheck=0,this.on("free",t=>{let n=this.calcSocketTimeout(t);n>0&&t.timeout!==n&&t.setTimeout(n)})}get freeSocketKeepAliveTimeout(){return ke("agent.freeSocketKeepAliveTimeout is deprecated, please use agent.options.freeSocketTimeout instead"),this.options.freeSocketTimeout}get timeout(){return ke("agent.timeout is deprecated, please use agent.options.timeout instead"),this.options.timeout}get socketActiveTTL(){return ke("agent.socketActiveTTL is deprecated, please use agent.options.socketActiveTTL instead"),this.options.socketActiveTTL}calcSocketTimeout(e){let t=this.options.freeSocketTimeout,n=this.options.socketActiveTTL;if(n){let s=Date.now()-e[Un],o=n-s;if(o<=0)return o;t&&o<t&&(t=o)}if(t)return e.freeSocketTimeout||e.freeSocketKeepAliveTimeout||t}keepSocketAlive(e){let t=super.keepSocketAlive(e);if(!t)return t;let n=this.calcSocketTimeout(e);return typeof n>"u"?!0:n<=0?(P("%s(requests: %s, finished: %s) free but need to destroy by TTL, request count %s, diff is %s",e[R],e[v],e[j],n),!1):(e.timeout!==n&&e.setTimeout(n),!0)}reuseSocket(...e){super.reuseSocket(...e);let t=e[0],n=e[1];n.reusedSocket=!0;let s=this.options.timeout;Ce(t)!==s&&(t.setTimeout(s),P("%s reset timeout to %sms",t[R],s)),t[v]++,P("%s(requests: %s, finished: %s) reuse on addRequest, timeout %sms",t[R],t[v],t[j],Ce(t))}[Nn](){let e=this[ut]++;return this[ut]===Number.MAX_SAFE_INTEGER&&(this[ut]=0),e}[Dn](e,t){t.timeout&&(Ce(e)||e.setTimeout(t.timeout)),this.options.keepAlive&&e.setNoDelay(!0),this.createSocketCount++,this.options.socketActiveTTL&&(e[Un]=Date.now()),e[R]=`sock[${this[Nn]()}#${t._agentKey}]`.split("-----BEGIN",1)[0],e[v]=1,e[j]=0,jr(this,e,t)}createConnection(e,t){let n=!1,s=(i,a)=>{if(!n){if(n=!0,i)return this.createSocketErrorCount++,t(i);this[Dn](a,e),t(i,a)}},o=super.createConnection(e,s);return o&&s(null,o),o}get statusChanged(){let e=this.createSocketCount!==this.createSocketCountLastCheck||this.createSocketErrorCount!==this.createSocketErrorCountLastCheck||this.closeSocketCount!==this.closeSocketCountLastCheck||this.errorSocketCount!==this.errorSocketCountLastCheck||this.timeoutSocketCount!==this.timeoutSocketCountLastCheck||this.requestCount!==this.requestCountLastCheck;return e&&(this.createSocketCountLastCheck=this.createSocketCount,this.createSocketErrorCountLastCheck=this.createSocketErrorCount,this.closeSocketCountLastCheck=this.closeSocketCount,this.errorSocketCountLastCheck=this.errorSocketCount,this.timeoutSocketCountLastCheck=this.timeoutSocketCount,this.requestCountLastCheck=this.requestCount),e}getCurrentStatus(){return{createSocketCount:this.createSocketCount,createSocketErrorCount:this.createSocketErrorCount,closeSocketCount:this.closeSocketCount,errorSocketCount:this.errorSocketCount,timeoutSocketCount:this.timeoutSocketCount,requestCount:this.requestCount,freeSockets:Wt(this.freeSockets),sockets:Wt(this.sockets),requests:Wt(this.requests)}}};function Ce(r){return r.timeout||r._idleTimeout}function jr(r,e,t){P("%s create, timeout %sms",e[R],Ce(e));function n(){if(!e._httpMessage&&e[v]===1)return;e[j]++,r.requestCount++,P("%s(requests: %s, finished: %s) free",e[R],e[v],e[j]);let u=r.getName(t);e.writable&&r.requests[u]&&r.requests[u].length&&(e[v]++,P("%s(requests: %s, finished: %s) will be reuse on agent free event",e[R],e[v],e[j]))}e.on("free",n);function s(u){P("%s(requests: %s, finished: %s) close, isError: %s",e[R],e[v],e[j],u),r.closeSocketCount++}e.on("close",s);function o(){let u=e.listeners("timeout").length,l=Ce(e),y=e._httpMessage,g=y&&y.listeners("timeout").length||0;P("%s(requests: %s, finished: %s) timeout after %sms, listeners %s, defaultTimeoutListenerCount %s, hasHttpRequest %s, HttpRequest timeoutListenerCount %s",e[R],e[v],e[j],l,u,Ht,!!y,g),P.enabled&&P("timeout listeners: %s",e.listeners("timeout").map(_=>_.name).join(", ")),r.timeoutSocketCount++;let h=r.getName(t);if(r.freeSockets[h]&&r.freeSockets[h].indexOf(e)!==-1)e.destroy(),r.removeSocket(e,t),P("%s is free, destroy quietly",e[R]);else if(g===0){let _=new Error("Socket timeout");_.code="ERR_SOCKET_TIMEOUT",_.timeout=l,e.destroy(_),r.removeSocket(e,t),P("%s destroy with timeout error",e[R])}}e.on("timeout",o);function i(u){let l=e.listeners("error").length;P("%s(requests: %s, finished: %s) error: %s, listenerCount: %s",e[R],e[v],e[j],u,l),r.errorSocketCount++,l===1&&(P("%s emit uncaught error event",e[R]),e.removeListener("error",i),e.emit("error",u))}e.on("error",i);function a(){P("%s(requests: %s, finished: %s) agentRemove",e[R],e[v],e[j]),e.removeListener("close",s),e.removeListener("error",i),e.removeListener("free",n),e.removeListener("timeout",o),e.removeListener("agentRemove",a)}e.on("agentRemove",a)}$n.exports=Jt;function Wt(r){let e={};for(let t in r)e[t]=r[t].length;return e}});var Hn=_e((fo,Wn)=>{"use strict";c();var Xt=et("https").Agent,qr=Kt(),{INIT_SOCKET:Dr,CREATE_HTTPS_CONNECTION:Gn}=ct(),xe=class extends qr{constructor(e){super(e),this.defaultPort=443,this.protocol="https:",this.maxCachedSessions=this.options.maxCachedSessions,this.maxCachedSessions===void 0&&(this.maxCachedSessions=100),this._sessionCache={map:{},list:[]}}createConnection(e,t){let n=this[Gn](e,t);return this[Dr](n,e),n}};xe.prototype[Gn]=Xt.prototype.createConnection;["getName","_getSession","_cacheSession","_evictSession"].forEach(function(r){typeof Xt.prototype[r]=="function"&&(xe.prototype[r]=Xt.prototype[r])});Wn.exports=xe});var Kn=_e((po,Te)=>{"use strict";c();var Jn=Kt();Te.exports=Jn;Te.exports.HttpAgent=Jn;Te.exports.HttpsAgent=Hn();Te.exports.constants=ct()});c();c();c();c();c();var te="0.36.3";c();c();c();var Rn=!1,ne,qt,Ar,Er,Pr,Mn,Rr,st,Dt,vn,Nt,ot,In;function Fn(r,e={auto:!1}){if(Rn)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${r.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(ne)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${r.kind}'\` after \`import '@anthropic-ai/sdk/shims/${ne}'\``);Rn=e.auto,ne=r.kind,qt=r.fetch,Ar=r.Request,Er=r.Response,Pr=r.Headers,Mn=r.FormData,Rr=r.Blob,st=r.File,Dt=r.ReadableStream,vn=r.getMultipartRequestOptions,Nt=r.getDefaultAgent,ot=r.fileFromPath,In=r.isFsReadStream}c();var X=jt(xr(),1);c();c();import{inspect as Ir}from"util";c();var On=r=>r instanceof rt;c();import{deprecate as vr}from"util";var Bn=vr(()=>{},'Constructor "entries" argument is not spec-compliant and will be removed in next major release.');var B=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},it,L,Ut,at=class{constructor(e){it.add(this),L.set(this,new Map),e&&(Bn(),e.forEach(({name:t,value:n,fileName:s})=>this.append(t,n,s)))}static[(L=new WeakMap,it=new WeakSet,Symbol.hasInstance)](e){return!!(e&&M(e.constructor)&&e[Symbol.toStringTag]==="FormData"&&M(e.append)&&M(e.set)&&M(e.get)&&M(e.getAll)&&M(e.has)&&M(e.delete)&&M(e.entries)&&M(e.values)&&M(e.keys)&&M(e[Symbol.iterator])&&M(e.forEach))}append(e,t,n){B(this,it,"m",Ut).call(this,{name:e,fileName:n,append:!0,rawValue:t,argsLength:arguments.length})}set(e,t,n){B(this,it,"m",Ut).call(this,{name:e,fileName:n,append:!1,rawValue:t,argsLength:arguments.length})}get(e){let t=B(this,L,"f").get(String(e));return t?t[0]:null}getAll(e){let t=B(this,L,"f").get(String(e));return t?t.slice():[]}has(e){return B(this,L,"f").has(String(e))}delete(e){B(this,L,"f").delete(String(e))}*keys(){for(let e of B(this,L,"f").keys())yield e}*entries(){for(let e of this.keys()){let t=this.getAll(e);for(let n of t)yield[e,n]}}*values(){for(let[,e]of this)yield e}[(Ut=function({name:t,rawValue:n,append:s,fileName:o,argsLength:i}){let a=s?"append":"set";if(i<2)throw new TypeError(`Failed to execute '${a}' on 'FormData': 2 arguments required, but only ${i} present.`);t=String(t);let u;if(Pn(n))u=o===void 0?n:new Se([n],o,{type:n.type,lastModified:n.lastModified});else if(On(n))u=new Se([n],o===void 0?"blob":o,{type:n.type});else{if(o)throw new TypeError(`Failed to execute '${a}' on 'FormData': parameter 2 is not of type 'Blob'.`);u=String(n)}let l=B(this,L,"f").get(t);if(!l)return void B(this,L,"f").set(t,[u]);if(!s)return void B(this,L,"f").set(t,[u]);l.push(u)},Symbol.iterator)](){return this.entries()}forEach(e,t){for(let[n,s]of this)e.call(t,s,n,this)}get[Symbol.toStringTag](){return"FormData"}[Ir.custom](){return this[Symbol.toStringTag]}};var Zt=jt(Kn(),1),Yn=jt(Tr(),1);import{ReadStream as Kr}from"node:fs";c();c();c();var Xn="abcdefghijklmnopqrstuvwxyz0123456789";function Nr(){let r=16,e="";for(;r--;)e+=Xn[Math.random()*Xn.length<<0];return e}var zn=Nr;c();var Ur=r=>Object.prototype.toString.call(r).slice(8,-1).toLowerCase();function $r(r){if(Ur(r)!=="object")return!1;let e=Object.getPrototypeOf(r);return e==null?!0:(e.constructor&&e.constructor.toString())===Object.toString()}var zt=$r;c();var Gr=r=>String(r).replace(/\r|\n/g,(e,t,n)=>e==="\r"&&n[t+1]!==`
4
- `||e===`
5
- `&&n[t-1]!=="\r"?`\r
6
- `:e),Vt=Gr;c();var Wr=r=>String(r).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22"),Qt=Wr;c();c();var Hr=r=>typeof r=="function",U=Hr;var re=r=>!!(r&&typeof r=="object"&&U(r.constructor)&&r[Symbol.toStringTag]==="File"&&U(r.stream)&&r.name!=null&&r.size!=null&&r.lastModified!=null);c();var Vn=r=>!!(r&&U(r.constructor)&&r[Symbol.toStringTag]==="FormData"&&U(r.append)&&U(r.getAll)&&U(r.entries)&&U(r[Symbol.iterator]));var Ae=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},w=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},lt,K,Ee,ft,Pe,se,Re,Me,ht,Yt,Jr={enableAdditionalHeaders:!1},dt=class{constructor(e,t,n){if(lt.add(this),K.set(this,`\r
7
- `),Ee.set(this,void 0),ft.set(this,void 0),Pe.set(this,"-".repeat(2)),se.set(this,new TextEncoder),Re.set(this,void 0),Me.set(this,void 0),ht.set(this,void 0),!Vn(e))throw new TypeError("Expected first argument to be a FormData instance.");let s;if(zt(t)?n=t:s=t,s||(s=zn()),typeof s!="string")throw new TypeError("Expected boundary argument to be a string.");if(n&&!zt(n))throw new TypeError("Expected options argument to be an object.");Ae(this,Me,e,"f"),Ae(this,ht,{...Jr,...n},"f"),Ae(this,Ee,w(this,se,"f").encode(w(this,K,"f")),"f"),Ae(this,ft,w(this,Ee,"f").byteLength,"f"),this.boundary=`form-data-boundary-${s}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,Ae(this,Re,w(this,se,"f").encode(`${w(this,Pe,"f")}${this.boundary}${w(this,Pe,"f")}${w(this,K,"f").repeat(2)}`),"f"),this.contentLength=String(this.getContentLength()),this.headers=Object.freeze({"Content-Type":this.contentType,"Content-Length":this.contentLength}),Object.defineProperties(this,{boundary:{writable:!1,configurable:!1},contentType:{writable:!1,configurable:!1},contentLength:{writable:!1,configurable:!1},headers:{writable:!1,configurable:!1}})}getContentLength(){let e=0;for(let[t,n]of w(this,Me,"f")){let s=re(n)?n:w(this,se,"f").encode(Vt(n));e+=w(this,lt,"m",Yt).call(this,t,s).byteLength,e+=re(s)?s.size:s.byteLength,e+=w(this,ft,"f")}return e+w(this,Re,"f").byteLength}*values(){for(let[e,t]of w(this,Me,"f").entries()){let n=re(t)?t:w(this,se,"f").encode(Vt(t));yield w(this,lt,"m",Yt).call(this,e,n),yield n,yield w(this,Ee,"f")}yield w(this,Re,"f")}async*encode(){for(let e of this.values())re(e)?yield*e.stream():yield e}[(K=new WeakMap,Ee=new WeakMap,ft=new WeakMap,Pe=new WeakMap,se=new WeakMap,Re=new WeakMap,Me=new WeakMap,ht=new WeakMap,lt=new WeakSet,Yt=function(t,n){let s="";return s+=`${w(this,Pe,"f")}${this.boundary}${w(this,K,"f")}`,s+=`Content-Disposition: form-data; name="${Qt(t)}"`,re(n)&&(s+=`; filename="${Qt(n.name)}"${w(this,K,"f")}`,s+=`Content-Type: ${n.type||"application/octet-stream"}`),w(this,ht,"f").enableAdditionalHeaders===!0&&(s+=`${w(this,K,"f")}Content-Length: ${re(n)?n.size:n.byteLength}`),w(this,se,"f").encode(`${s}${w(this,K,"f").repeat(2)}`)},Symbol.iterator)](){return this.values()}[Symbol.asyncIterator](){return this.encode()}};c();c();import{Readable as Xr}from"node:stream";c();var pt=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};import{ReadableStream as zr}from"node:stream/web";var Qn=!1;async function Vr(r,...e){let{fileFromPath:t}=await import("./fileFromPath-7UCWPD4W.js");return Qn||(console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(r)}) instead`),Qn=!0),await t(r,...e)}var Qr=new Zt.default({keepAlive:!0,timeout:5*60*1e3}),Yr=new Zt.default.HttpsAgent({keepAlive:!0,timeout:5*60*1e3});async function Zr(r,e){let t=new dt(r),n=Xr.from(t),s=new pt(n),o={...e.headers,...t.headers,"Content-Length":t.contentLength};return{...e,body:s,headers:o}}function Zn(){return typeof AbortController>"u"&&(globalThis.AbortController=Yn.AbortController),{kind:"node",fetch:X.default,Request:X.Request,Response:X.Response,Headers:X.Headers,FormData:at,Blob:rt,File:Se,ReadableStream:zr,getMultipartRequestOptions:Zr,getDefaultAgent:r=>r.startsWith("https")?Yr:Qr,fileFromPath:Vr,isFsReadStream:r=>r instanceof Kr}}ne||Fn(Zn(),{auto:!0});c();var f=class extends Error{},C=class r extends f{constructor(e,t,n,s){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.request_id=s?.["request-id"],this.error=t}static makeMessage(e,t,n){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new z({message:n,cause:mt(t)});let o=t;return e===400?new ve(e,o,n,s):e===401?new Ie(e,o,n,s):e===403?new Fe(e,o,n,s):e===404?new Oe(e,o,n,s):e===409?new Be(e,o,n,s):e===422?new Le(e,o,n,s):e===429?new je(e,o,n,s):e>=500?new qe(e,o,n,s):new r(e,o,n,s)}},T=class extends C{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},z=class extends C{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},le=class extends z{constructor({message:e}={}){super({message:e??"Request timed out."})}},ve=class extends C{},Ie=class extends C{},Fe=class extends C{},Oe=class extends C{},Be=class extends C{},Le=class extends C{},je=class extends C{},qe=class extends C{};c();var $=class r{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let t=this.decodeText(e);if(this.trailingCR&&(t="\r"+t,this.trailingCR=!1),t.endsWith("\r")&&(this.trailingCR=!0,t=t.slice(0,-1)),!t)return[];let n=r.NEWLINE_CHARS.has(t[t.length-1]||""),s=t.split(r.NEWLINE_REGEXP);return n&&s.pop(),s.length===1&&!n?(this.buffer.push(s[0]),[]):(this.buffer.length>0&&(s=[this.buffer.join("")+s[0],...s.slice(1)],this.buffer=[]),n||(this.buffer=[s.pop()||""]),s)}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new f(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new f(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new f("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}};$.NEWLINE_CHARS=new Set([`
8
- `,"\r"]);$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;c();function De(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var q=class r{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;async function*s(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let o=!1;try{for await(let i of ts(e,t)){if(i.event==="completion")try{yield JSON.parse(i.data)}catch(a){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),a}if(i.event==="message_start"||i.event==="message_delta"||i.event==="message_stop"||i.event==="content_block_start"||i.event==="content_block_delta"||i.event==="content_block_stop")try{yield JSON.parse(i.data)}catch(a){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),a}if(i.event!=="ping"&&i.event==="error")throw C.generate(void 0,`SSE Error: ${i.data}`,i.data,tn(e.headers))}o=!0}catch(i){if(i instanceof Error&&i.name==="AbortError")return;throw i}finally{o||t.abort()}}return new r(s,t)}static fromReadableStream(e,t){let n=!1;async function*s(){let i=new $,a=De(e);for await(let u of a)for(let l of i.decode(u))yield l;for(let u of i.flush())yield u}async function*o(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(let a of s())i||a&&(yield JSON.parse(a));i=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{i||t.abort()}}return new r(o,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),s=o=>({next:()=>{if(o.length===0){let i=n.next();e.push(i),t.push(i)}return o.shift()}});return[new r(()=>s(e),this.controller),new r(()=>s(t),this.controller)]}toReadableStream(){let e=this,t,n=new TextEncoder;return new Dt({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{let{value:o,done:i}=await t.next();if(i)return s.close();let a=n.encode(JSON.stringify(o)+`
9
- `);s.enqueue(a)}catch(o){s.error(o)}},async cancel(){await t.return?.()}})}};async function*ts(r,e){if(!r.body)throw e.abort(),new f("Attempted to iterate over a response with no body");let t=new en,n=new $,s=De(r.body);for await(let o of ns(s))for(let i of n.decode(o)){let a=t.decode(i);a&&(yield a)}for(let o of n.flush()){let i=t.decode(o);i&&(yield i)}}async function*ns(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t,s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let o;for(;(o=rs(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}function rs(r){for(let n=0;n<r.length-2;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}var en=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
10
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=ss(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function ss(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}c();var os=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",is=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Ne(r),Ne=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function";async function er(r,e,t){if(r=await r,is(r))return r;if(os(r)){let s=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");let o=Ne(s)?[await s.arrayBuffer()]:[s];return new st(o,e,t)}let n=await as(r);if(e||(e=us(r)??"unknown_file"),!t?.type){let s=n[0]?.type;typeof s=="string"&&(t={...t,type:s})}return new st(n,e,t)}async function as(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(Ne(r))e.push(await r.arrayBuffer());else if(ls(r))for await(let t of r)e.push(t);else throw new Error(`Unexpected data type: ${typeof r}; constructor: ${r?.constructor?.name}; props: ${cs(r)}`);return e}function cs(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function us(r){return nn(r.name)||nn(r.filename)||nn(r.path)?.split(/[\\/]/).pop()}var nn=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},ls=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",rn=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody";var hs=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},ds=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},gt;async function ir(r){let{response:e}=r;if(r.options.stream)return fe("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):q.fromSSEResponse(e,r.controller);if(e.status===204)return null;if(r.options.__binaryResponse)return e;let t=e.headers.get("content-type");if(t?.includes("application/json")||t?.includes("application/vnd.api+json")){let o=await e.json();return fe("response",e.status,e.url,e.headers,o),ar(o,e)}let s=await e.text();return fe("response",e.status,e.url,e.headers,s),s}function ar(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var yt=class r extends Promise{constructor(e,t=ir){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new r(this.responsePromise,async t=>ar(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}},bt=class{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:o}){this.baseURL=e,this.maxRetries=sn("maxRetries",t),this.timeout=sn("timeout",n),this.httpAgent=s,this.fetch=o??qt}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...ys(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${ks()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(async s=>{let o=s&&Ne(s?.body)?new DataView(await s.body.arrayBuffer()):s?.body instanceof DataView?s.body:s?.body instanceof ArrayBuffer?new DataView(s.body):s&&ArrayBuffer.isView(s?.body)?new DataView(s.body.buffer):s?.body;return{method:e,path:t,...s,body:o}}))}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){let{method:n,path:s,query:o,headers:i={}}=e,a=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:rn(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,u=this.calculateContentLength(a),l=this.buildURL(s,o);"timeout"in e&&sn("timeout",e.timeout);let y=e.timeout??this.timeout,g=e.httpAgent??this.httpAgent??Nt(l),h=y+1e3;typeof g?.options?.timeout=="number"&&h>(g.options.timeout??0)&&(g.options.timeout=h),this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let _=this.buildHeaders({options:e,headers:i,contentLength:u,retryCount:t});return{req:{method:n,...a&&{body:a},headers:_,...g&&{agent:g},signal:e.signal??null},url:l,timeout:y}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:s}){let o={};n&&(o["content-length"]=n);let i=this.defaultHeaders(e);return sr(o,i),sr(o,t),rn(e.body)&&ne!=="node"&&delete o["content-type"],or(i,"x-stainless-retry-count")===void 0&&or(t,"x-stainless-retry-count")===void 0&&(o["x-stainless-retry-count"]=String(s)),this.validateHeaders(o,t),o}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,n,s){return C.generate(e,t,n,s)}request(e,t=null){return new yt(this.makeRequest(e,t))}async makeRequest(e,t){let n=await e,s=n.maxRetries??this.maxRetries;t==null&&(t=s),await this.prepareOptions(n);let{req:o,url:i,timeout:a}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(o,{url:i,options:n}),fe("request",i,n,o.headers),n.signal?.aborted)throw new T;let u=new AbortController,l=await this.fetchWithTimeout(i,o,a,u).catch(mt);if(l instanceof Error){if(n.signal?.aborted)throw new T;if(t)return this.retryRequest(n,t);throw l.name==="AbortError"?new le:new z({cause:l})}let y=tn(l.headers);if(!l.ok){if(t&&this.shouldRetry(l)){let m=`retrying, ${t} attempts remaining`;return fe(`response (error; ${m})`,l.status,i,y),this.retryRequest(n,t,y)}let g=await l.text().catch(m=>mt(m).message),h=bs(g),_=h?void 0:g;throw fe(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,l.status,i,y,_),this.makeStatusError(l.status,h,_,y)}return{response:l,options:n,controller:u}}requestAPIList(e,t){let n=this.makeRequest(t,null);return new on(this,n,e)}buildURL(e,t){let n=ws(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return Ue(s)||(t={...s,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new f(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,n,s){let{signal:o,...i}=t||{};o&&o.addEventListener("abort",()=>s.abort());let a=setTimeout(()=>s.abort(),n),u={signal:s.signal,...i};return u.method&&(u.method=u.method.toUpperCase()),this.fetch.call(void 0,e,u).finally(()=>{clearTimeout(a)})}shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n){let s,o=n?.["retry-after-ms"];if(o){let a=parseFloat(o);Number.isNaN(a)||(s=a)}let i=n?.["retry-after"];if(i&&!s){let a=parseFloat(i);Number.isNaN(a)?s=Date.parse(i)-Date.now():s=a*1e3}if(!(s&&0<=s&&s<60*1e3)){let a=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,a)}return await Ss(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${te}`}},_t=class{constructor(e,t,n,s){gt.set(this,void 0),hs(this,gt,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new f("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){let n=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(let[s,o]of n)e.url.searchParams.set(s,o);t.query=void 0,t.path=e.url.toString()}return await ds(this,gt,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(gt=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},on=class extends yt{constructor(e,t,n){super(t,async s=>new n(e,s.response,await ir(s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},tn=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){let n=t.toString();return e[n.toLowerCase()]||e[n]}}),ps={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},I=r=>typeof r=="object"&&r!==null&&!Ue(r)&&Object.keys(r).every(e=>cr(ps,e)),ms=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":te,"X-Stainless-OS":nr(Deno.build.os),"X-Stainless-Arch":tr(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":te,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":te,"X-Stainless-OS":nr(process.platform),"X-Stainless-Arch":tr(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let r=gs();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":te,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${r.browser}`,"X-Stainless-Runtime-Version":r.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":te,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function gs(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,i=n[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}var tr=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",nr=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),rr,ys=()=>rr??(rr=ms()),bs=r=>{try{return JSON.parse(r)}catch{return}},_s=/^[a-z][a-z0-9+.-]*:/i,ws=r=>_s.test(r),Ss=r=>new Promise(e=>setTimeout(e,r)),sn=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new f(`${r} must be an integer`);if(e<0)throw new f(`${r} must be a positive integer`);return e},mt=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null)try{return new Error(JSON.stringify(r))}catch{}return new Error(String(r))};var wt=r=>{if(typeof process<"u")return process.env?.[r]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(r)?.trim()};function Ue(r){if(!r)return!0;for(let e in r)return!1;return!0}function cr(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function sr(r,e){for(let t in e){if(!cr(e,t))continue;let n=t.toLowerCase();if(!n)continue;let s=e[t];s===null?delete r[n]:s!==void 0&&(r[n]=s)}}function fe(r,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Anthropic:DEBUG:${r}`,...e)}var ks=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),ur=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",Cs=r=>typeof r?.get=="function";var or=(r,e)=>{let t=e.toLowerCase();if(Cs(r)){let n=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(s,o,i)=>o+i.toUpperCase());for(let s of[e,t,e.toUpperCase(),n]){let o=r.get(s);if(o)return o}}for(let[n,s]of Object.entries(r))if(n.toLowerCase()===t)return Array.isArray(s)?(s.length<=1||console.warn(`Received ${s.length} entries for the ${e} header, using the first entry.`),s[0]):s};c();var D=class extends _t{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}nextPageParams(){let e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;let t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){if(this.options.query?.before_id){let t=this.first_id;return t?{params:{before_id:t}}:null}let e=this.last_id;return e?{params:{after_id:e}}:null}};c();c();c();var x=class{constructor(e){this._client=e}};c();var oe=class extends x{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return I(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",he,{query:e,...t})}},he=class extends D{};oe.BetaModelInfosPage=he;c();c();c();var de=class r{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new $;for await(let t of this.iterator)for(let n of e.decode(t))yield JSON.parse(n);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),new f("Attempted to iterate over a response with no body");return new r(De(e.body),t)}};var ie=class extends x{create(e,t){let{betas:n,...s}=e;return this._client.post("/v1/messages/batches?beta=true",{body:s,...t,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},n){if(I(t))return this.retrieve(e,{},t);let{betas:s}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...n,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}list(e={},t){if(I(e))return this.list({},e);let{betas:n,...s}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",pe,{query:s,...t,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},n){if(I(t))return this.delete(e,{},t);let{betas:s}=t;return this._client.delete(`/v1/messages/batches/${e}?beta=true`,{...n,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}cancel(e,t={},n){if(I(t))return this.cancel(e,{},t);let{betas:s}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}async results(e,t={},n){if(I(t))return this.results(e,{},t);let s=await this.retrieve(e);if(!s.results_url)throw new f(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);let{betas:o}=t;return this._client.get(s.results_url,{...n,headers:{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...n?.headers},__binaryResponse:!0})._thenUnwrap((i,a)=>de.fromResponse(a.response,a.controller))}},pe=class extends D{};ie.BetaMessageBatchesPage=pe;c();c();var Es=r=>{let e=0,t=[];for(;e<r.length;){let n=r[e];if(n==="\\"){e++;continue}if(n==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(n==="["){t.push({type:"paren",value:"["}),e++;continue}if(n==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(n===":"){t.push({type:"separator",value:":"}),e++;continue}if(n===","){t.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let a="",u=!1;for(n=r[++e];n!=='"';){if(e===r.length){u=!0;break}if(n==="\\"){if(e++,e===r.length){u=!0;break}a+=n+r[e],n=r[++e]}else a+=n,n=r[++e]}n=r[++e],u||t.push({type:"string",value:a});continue}if(n&&/\s/.test(n)){e++;continue}let o=/[0-9]/;if(n&&o.test(n)||n==="-"||n==="."){let a="";for(n==="-"&&(a+=n,n=r[++e]);n&&o.test(n)||n===".";)a+=n,n=r[++e];t.push({type:"number",value:a});continue}let i=/[a-z]/i;if(n&&i.test(n)){let a="";for(;n&&i.test(n)&&e!==r.length;)a+=n,n=r[++e];if(a=="true"||a=="false"||a==="null")t.push({type:"name",value:a});else{e++;continue}continue}e++}return t},me=r=>{if(r.length===0)return r;let e=r[r.length-1];switch(e.type){case"separator":return r=r.slice(0,r.length-1),me(r);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return r=r.slice(0,r.length-1),me(r);case"string":let n=r[r.length-2];if(n?.type==="delimiter")return r=r.slice(0,r.length-1),me(r);if(n?.type==="brace"&&n.value==="{")return r=r.slice(0,r.length-1),me(r);break;case"delimiter":return r=r.slice(0,r.length-1),me(r);break}return r},Ps=r=>{let e=[];return r.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?r.push({type:"brace",value:"}"}):t==="]"&&r.push({type:"paren",value:"]"})}),r},Rs=r=>{let e="";return r.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},St=r=>JSON.parse(Rs(Ps(me(Es(r)))));var A=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},d=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},F,V,$e,kt,Ge,We,Ct,He,G,Je,xt,Tt,ge,At,Et,an,lr,cn,un,ln,fn,fr,hr="__json_buf",Pt=class r{constructor(){F.add(this),this.messages=[],this.receivedMessages=[],V.set(this,void 0),this.controller=new AbortController,$e.set(this,void 0),kt.set(this,()=>{}),Ge.set(this,()=>{}),We.set(this,void 0),Ct.set(this,()=>{}),He.set(this,()=>{}),G.set(this,{}),Je.set(this,!1),xt.set(this,!1),Tt.set(this,!1),ge.set(this,!1),At.set(this,void 0),Et.set(this,void 0),cn.set(this,e=>{if(A(this,xt,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new T),e instanceof T)return A(this,Tt,!0,"f"),this._emit("abort",e);if(e instanceof f)return this._emit("error",e);if(e instanceof Error){let t=new f(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new f(String(e)))}),A(this,$e,new Promise((e,t)=>{A(this,kt,e,"f"),A(this,Ge,t,"f")}),"f"),A(this,We,new Promise((e,t)=>{A(this,Ct,e,"f"),A(this,He,t,"f")}),"f"),d(this,$e,"f").catch(()=>{}),d(this,We,"f").catch(()=>{})}get response(){return d(this,At,"f")}get request_id(){return d(this,Et,"f")}async withResponse(){let e=await d(this,$e,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){let s=new r;for(let o of t.messages)s._addMessageParam(o);return s._run(()=>s._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},d(this,cn,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),d(this,F,"m",un).call(this);let{response:o,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(let a of i)d(this,F,"m",ln).call(this,a);if(i.controller.signal?.aborted)throw new T;d(this,F,"m",fn).call(this)}_connected(e){this.ended||(A(this,At,e,"f"),A(this,Et,e?.headers.get("request-id"),"f"),d(this,kt,"f").call(this,e),this._emit("connect"))}get ended(){return d(this,Je,"f")}get errored(){return d(this,xt,"f")}get aborted(){return d(this,Tt,"f")}abort(){this.controller.abort()}on(e,t){return(d(this,G,"f")[e]||(d(this,G,"f")[e]=[])).push({listener:t}),this}off(e,t){let n=d(this,G,"f")[e];if(!n)return this;let s=n.findIndex(o=>o.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(d(this,G,"f")[e]||(d(this,G,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{A(this,ge,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){A(this,ge,!0,"f"),await d(this,We,"f")}get currentMessage(){return d(this,V,"f")}async finalMessage(){return await this.done(),d(this,F,"m",an).call(this)}async finalText(){return await this.done(),d(this,F,"m",lr).call(this)}_emit(e,...t){if(d(this,Je,"f"))return;e==="end"&&(A(this,Je,!0,"f"),d(this,Ct,"f").call(this));let n=d(this,G,"f")[e];if(n&&(d(this,G,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!d(this,ge,"f")&&!n?.length&&Promise.reject(s),d(this,Ge,"f").call(this,s),d(this,He,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!d(this,ge,"f")&&!n?.length&&Promise.reject(s),d(this,Ge,"f").call(this,s),d(this,He,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",d(this,F,"m",an).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),d(this,F,"m",un).call(this),this._connected(null);let s=q.fromReadableStream(e,this.controller);for await(let o of s)d(this,F,"m",ln).call(this,o);if(s.controller.signal?.aborted)throw new T;d(this,F,"m",fn).call(this)}[(V=new WeakMap,$e=new WeakMap,kt=new WeakMap,Ge=new WeakMap,We=new WeakMap,Ct=new WeakMap,He=new WeakMap,G=new WeakMap,Je=new WeakMap,xt=new WeakMap,Tt=new WeakMap,ge=new WeakMap,At=new WeakMap,Et=new WeakMap,cn=new WeakMap,F=new WeakSet,an=function(){if(this.receivedMessages.length===0)throw new f("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},lr=function(){if(this.receivedMessages.length===0)throw new f("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new f("stream ended without producing a content block with type=text");return t.join(" ")},un=function(){this.ended||A(this,V,void 0,"f")},ln=function(t){if(this.ended)return;let n=d(this,F,"m",fr).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{let s=n.content.at(-1);switch(t.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{s.type==="tool_use"&&s.input&&this._emit("inputJson",t.delta.partial_json,s.input);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{A(this,V,n,"f");break}case"content_block_start":case"message_delta":break}},fn=function(){if(this.ended)throw new f("stream has ended, this shouldn't happen");let t=d(this,V,"f");if(!t)throw new f("request ended without sending any chunks");return A(this,V,void 0,"f"),t},fr=function(t){let n=d(this,V,"f");if(t.type==="message_start"){if(n)throw new f(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new f(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,n;case"content_block_start":return n.content.push(t.content_block),n;case"content_block_delta":{let s=n.content.at(t.index);switch(t.delta.type){case"text_delta":{s?.type==="text"&&(s.text+=t.delta.text);break}case"citations_delta":{s?.type==="text"&&(s.citations??(s.citations=[]),s.citations.push(t.delta.citation));break}case"input_json_delta":{if(s?.type==="tool_use"){let o=s[hr]||"";o+=t.delta.partial_json,Object.defineProperty(s,hr,{value:o,enumerable:!1,writable:!0}),o&&(s.input=St(o))}break}default:t.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("streamEvent",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new q(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var dr={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"},Q=class extends x{constructor(){super(...arguments),this.batches=new ie(this._client)}create(e,t){let{betas:n,...s}=e;return s.model in dr&&console.warn(`The model '${s.model}' is deprecated and will reach end-of-life on ${dr[s.model]}
11
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:s,timeout:this._client._options.timeout??6e5,...t,headers:{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}stream(e,t){return Pt.createMessage(this,e,t)}countTokens(e,t){let{betas:n,...s}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:s,...t,headers:{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString(),...t?.headers}})}};Q.Batches=ie;Q.BetaMessageBatchesPage=pe;var N=class extends x{constructor(){super(...arguments),this.models=new oe(this._client),this.messages=new Q(this._client)}};N.Models=oe;N.BetaModelInfosPage=he;N.Messages=Q;c();var ae=class extends x{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}};c();c();var ce=class extends x{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/v1/messages/batches/${e}`,t)}list(e={},t){return I(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",ye,{query:e,...t})}delete(e,t){return this._client.delete(`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let n=await this.retrieve(e);if(!n.results_url)throw new f(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})._thenUnwrap((s,o)=>de.fromResponse(o.response,o.controller))}},ye=class extends D{};ce.MessageBatchesPage=ye;c();var E=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},p=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},O,Y,Ke,Rt,Xe,ze,Mt,Ve,W,Qe,vt,It,be,Ft,Ot,hn,pr,dn,pn,mn,gn,mr,gr="__json_buf",Bt=class r{constructor(){O.add(this),this.messages=[],this.receivedMessages=[],Y.set(this,void 0),this.controller=new AbortController,Ke.set(this,void 0),Rt.set(this,()=>{}),Xe.set(this,()=>{}),ze.set(this,void 0),Mt.set(this,()=>{}),Ve.set(this,()=>{}),W.set(this,{}),Qe.set(this,!1),vt.set(this,!1),It.set(this,!1),be.set(this,!1),Ft.set(this,void 0),Ot.set(this,void 0),dn.set(this,e=>{if(E(this,vt,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new T),e instanceof T)return E(this,It,!0,"f"),this._emit("abort",e);if(e instanceof f)return this._emit("error",e);if(e instanceof Error){let t=new f(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new f(String(e)))}),E(this,Ke,new Promise((e,t)=>{E(this,Rt,e,"f"),E(this,Xe,t,"f")}),"f"),E(this,ze,new Promise((e,t)=>{E(this,Mt,e,"f"),E(this,Ve,t,"f")}),"f"),p(this,Ke,"f").catch(()=>{}),p(this,ze,"f").catch(()=>{})}get response(){return p(this,Ft,"f")}get request_id(){return p(this,Ot,"f")}async withResponse(){let e=await p(this,Ke,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){let s=new r;for(let o of t.messages)s._addMessageParam(o);return s._run(()=>s._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},p(this,dn,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),p(this,O,"m",pn).call(this);let{response:o,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(let a of i)p(this,O,"m",mn).call(this,a);if(i.controller.signal?.aborted)throw new T;p(this,O,"m",gn).call(this)}_connected(e){this.ended||(E(this,Ft,e,"f"),E(this,Ot,e?.headers.get("request-id"),"f"),p(this,Rt,"f").call(this,e),this._emit("connect"))}get ended(){return p(this,Qe,"f")}get errored(){return p(this,vt,"f")}get aborted(){return p(this,It,"f")}abort(){this.controller.abort()}on(e,t){return(p(this,W,"f")[e]||(p(this,W,"f")[e]=[])).push({listener:t}),this}off(e,t){let n=p(this,W,"f")[e];if(!n)return this;let s=n.findIndex(o=>o.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(p(this,W,"f")[e]||(p(this,W,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{E(this,be,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){E(this,be,!0,"f"),await p(this,ze,"f")}get currentMessage(){return p(this,Y,"f")}async finalMessage(){return await this.done(),p(this,O,"m",hn).call(this)}async finalText(){return await this.done(),p(this,O,"m",pr).call(this)}_emit(e,...t){if(p(this,Qe,"f"))return;e==="end"&&(E(this,Qe,!0,"f"),p(this,Mt,"f").call(this));let n=p(this,W,"f")[e];if(n&&(p(this,W,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!p(this,be,"f")&&!n?.length&&Promise.reject(s),p(this,Xe,"f").call(this,s),p(this,Ve,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!p(this,be,"f")&&!n?.length&&Promise.reject(s),p(this,Xe,"f").call(this,s),p(this,Ve,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",p(this,O,"m",hn).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),p(this,O,"m",pn).call(this),this._connected(null);let s=q.fromReadableStream(e,this.controller);for await(let o of s)p(this,O,"m",mn).call(this,o);if(s.controller.signal?.aborted)throw new T;p(this,O,"m",gn).call(this)}[(Y=new WeakMap,Ke=new WeakMap,Rt=new WeakMap,Xe=new WeakMap,ze=new WeakMap,Mt=new WeakMap,Ve=new WeakMap,W=new WeakMap,Qe=new WeakMap,vt=new WeakMap,It=new WeakMap,be=new WeakMap,Ft=new WeakMap,Ot=new WeakMap,dn=new WeakMap,O=new WeakSet,hn=function(){if(this.receivedMessages.length===0)throw new f("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},pr=function(){if(this.receivedMessages.length===0)throw new f("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new f("stream ended without producing a content block with type=text");return t.join(" ")},pn=function(){this.ended||E(this,Y,void 0,"f")},mn=function(t){if(this.ended)return;let n=p(this,O,"m",mr).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{let s=n.content.at(-1);switch(t.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{s.type==="tool_use"&&s.input&&this._emit("inputJson",t.delta.partial_json,s.input);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{E(this,Y,n,"f");break}case"content_block_start":case"message_delta":break}},gn=function(){if(this.ended)throw new f("stream has ended, this shouldn't happen");let t=p(this,Y,"f");if(!t)throw new f("request ended without sending any chunks");return E(this,Y,void 0,"f"),t},mr=function(t){let n=p(this,Y,"f");if(t.type==="message_start"){if(n)throw new f(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new f(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,n;case"content_block_start":return n.content.push(t.content_block),n;case"content_block_delta":{let s=n.content.at(t.index);switch(t.delta.type){case"text_delta":{s?.type==="text"&&(s.text+=t.delta.text);break}case"citations_delta":{s?.type==="text"&&(s.citations??(s.citations=[]),s.citations.push(t.delta.citation));break}case"input_json_delta":{if(s?.type==="tool_use"){let o=s[gr]||"";o+=t.delta.partial_json,Object.defineProperty(s,gr,{value:o,enumerable:!1,writable:!0}),o&&(s.input=St(o))}break}default:t.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("streamEvent",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new q(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var H=class extends x{constructor(){super(...arguments),this.batches=new ce(this._client)}create(e,t){return e.model in yr&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${yr[e.model]}
12
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}stream(e,t){return Bt.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}},yr={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};H.Batches=ce;H.MessageBatchesPage=ye;c();var Z=class extends x{retrieve(e,t){return this._client.get(`/v1/models/${e}`,t)}list(e={},t){return I(e)?this.list({},e):this._client.getAPIList("/v1/models",ue,{query:e,...t})}},ue=class extends D{};Z.ModelInfosPage=ue;var br,b=class extends bt{constructor({baseURL:e=wt("ANTHROPIC_BASE_URL"),apiKey:t=wt("ANTHROPIC_API_KEY")??null,authToken:n=wt("ANTHROPIC_AUTH_TOKEN")??null,...s}={}){let o={apiKey:t,authToken:n,...s,baseURL:e||"https://api.anthropic.com"};if(!o.dangerouslyAllowBrowser&&ur())throw new f(`It looks like you're running in a browser-like environment.
13
-
14
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
15
- If you understand the risks and have appropriate mitigations in place,
16
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
17
-
18
- new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
19
- `);super({baseURL:o.baseURL,timeout:o.timeout??6e5,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new ae(this),this.messages=new H(this),this.models=new Z(this),this.beta=new N(this),this._options=o,this.apiKey=t,this.authToken=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(e,t){if(!(this.apiKey&&e["x-api-key"])&&t["x-api-key"]!==null&&!(this.authToken&&e.authorization)&&t.authorization!==null)throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders(e){let t=this.apiKeyAuth(e),n=this.bearerAuth(e);return t!=null&&!Ue(t)?t:n!=null&&!Ue(n)?n:{}}apiKeyAuth(e){return this.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){return this.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};br=b;b.Anthropic=br;b.HUMAN_PROMPT=`
20
-
21
- Human:`;b.AI_PROMPT=`
22
-
23
- Assistant:`;b.DEFAULT_TIMEOUT=6e5;b.AnthropicError=f;b.APIError=C;b.APIConnectionError=z;b.APIConnectionTimeoutError=le;b.APIUserAbortError=T;b.NotFoundError=Oe;b.ConflictError=Be;b.RateLimitError=je;b.BadRequestError=ve;b.AuthenticationError=Ie;b.InternalServerError=qe;b.PermissionDeniedError=Fe;b.UnprocessableEntityError=Le;b.toFile=er;b.fileFromPath=ot;b.Completions=ae;b.Messages=H;b.Models=Z;b.ModelInfosPage=ue;b.Beta=N;var{HUMAN_PROMPT:Xa,AI_PROMPT:za}=b,_r=b;c();c();function Ye(r){let{inputTokens:e,cacheReadTokens:t,cacheCreationTokens:n,outputTokens:s}=r,i=n===0&&t>0&&e>=t?e:e+t+n;return{promptTokenCount:i,candidatesTokenCount:s,totalTokenCount:i+s,cachedContentTokenCount:t}}var Lt=class{model;schemaCompliance;enableCacheControl;constructor(e,t="auto",n=!0){this.model=e,this.schemaCompliance=t,this.enableCacheControl=n}convertGeminiRequestToAnthropic(e,t={}){let n=[],s=this.extractTextFromContentUnion(e.config?.systemInstruction);this.processContents(e.contents,n),t.stripAssistantThinking&&this.stripThinkingFromAssistantMessages(n),t.normalizeAssistantThinkingSignature&&this.fillMissingThinkingSignatures(n),t.injectThinkingOnToolUseTurns&&this.injectEmptyThinkingOnToolUseTurns(n);let o=t.enableCacheControl??this.enableCacheControl,i=t.useGlobalCacheScope??!1,a=o?this.buildSystemWithCacheControl(s,i):s;return o&&this.addCacheControlToMessages(n),{system:a,messages:n}}async convertGeminiToolsToAnthropic(e,t={}){let n=[];for(let i of e){let a;if("tool"in i?a=await i.tool():a=i,!!a.functionDeclarations)for(let u of a.functionDeclarations){if(!u.name||!u.description)continue;let l;u.parametersJsonSchema?l={...u.parametersJsonSchema}:u.parameters&&(l=u.parameters),l||(l={type:"object",properties:{}}),l=kn(l,this.schemaCompliance),typeof l.type!="string"&&(l.type="object"),n.push({name:u.name,description:u.description,input_schema:l})}}let s=t.enableCacheControl??this.enableCacheControl,o=t.useGlobalCacheScope??!1;if(s&&n.length>0){let i=n.length-1;n[i]={...n[i],cache_control:o?{type:"ephemeral",scope:"global"}:{type:"ephemeral"}}}return n}convertAnthropicResponseToGemini(e){let t=new tt,n=[];for(let i of e.content||[]){let a=String(i.type||"");if(a==="text"){let u=typeof i.text=="string"?i.text:"";u&&n.push({text:u})}else if(a==="tool_use"){let u=i,l=this.safeInputToArgs(u.input);if(l===null)continue;n.push({functionCall:{id:typeof u.id=="string"?u.id:void 0,name:typeof u.name=="string"?u.name:void 0,args:l}})}else if(a==="thinking"){let u=typeof i.thinking=="string"?i.thinking:"",l=typeof i.signature=="string"?i.signature:"";if(u||l){let y={text:u,thought:!0,thoughtSignature:l};n.push(y)}}else a==="redacted_thinking"&&n.push({text:"",thought:!0})}let s={content:{parts:n,role:"model"},index:0,safetyRatings:[]},o=this.mapAnthropicFinishReasonToGemini(e.stop_reason);return o&&(s.finishReason=o),t.candidates=[s],t.responseId=e.id,t.createTime=Date.now().toString(),t.modelVersion=e.model||this.model,t.promptFeedback={safetyRatings:[]},e.usage&&(t.usageMetadata=Ye({inputTokens:e.usage.input_tokens||0,cacheReadTokens:e.usage.cache_read_input_tokens||0,cacheCreationTokens:e.usage.cache_creation_input_tokens||0,outputTokens:e.usage.output_tokens||0})),t}processContents(e,t){if(Array.isArray(e))for(let n of e)this.processContent(n,t);else e&&this.processContent(e,t)}processContent(e,t){if(typeof e=="string"){t.push({role:"user",content:[{type:"text",text:e}]});return}if(!this.isContentObject(e))return;let n=e.parts||[],s=e.role==="model"?"assistant":"user",o=[],i=0;for(let a of n){if(typeof a=="string"){o.push({type:"text",text:a});continue}if("text"in a&&"thought"in a&&a.thought&&s==="assistant"){let l={type:"thinking",thinking:a.text||""};"thoughtSignature"in a&&typeof a.thoughtSignature=="string"&&(l.signature=a.thoughtSignature),o.push(l)}"text"in a&&a.text&&!("thought"in a&&a.thought)&&o.push({type:"text",text:a.text});let u=this.createMediaBlockFromPart(a);if(u&&o.push(u),"functionCall"in a&&a.functionCall&&s==="assistant"&&(o.push({type:"tool_use",id:a.functionCall.id||`tool_${i}`,name:a.functionCall.name||"",input:a.functionCall.args||{}}),i+=1),a.functionResponse){let l=this.createToolResultBlock(a.functionResponse);l&&s==="user"&&o.push(l)}}o.length>0&&t.push({role:s,content:o})}createToolResultBlock(e){let t=this.extractFunctionResponseContent(e.response),n=[];for(let o of e.parts||[]){let i=this.createMediaBlockFromPart(o);i&&n.push(i)}let s;if(n.length>0){let o=[];t&&o.push({type:"text",text:t}),o.push(...n),s=o}else s=t;return{type:"tool_result",tool_use_id:e.id||"",content:s}}createMediaBlockFromPart(e){if(e.inlineData?.mimeType&&e.inlineData?.data){if(this.isSupportedAnthropicImageMimeType(e.inlineData.mimeType))return{type:"image",source:{type:"base64",media_type:e.inlineData.mimeType,data:e.inlineData.data}};if(e.inlineData.mimeType==="application/pdf")return{type:"document",source:{type:"base64",media_type:"application/pdf",data:e.inlineData.data}};let t=e.inlineData.displayName?` (${e.inlineData.displayName})`:"";return{type:"text",text:`Unsupported inline media type: ${e.inlineData.mimeType}${t}.`}}if(e.fileData?.mimeType&&e.fileData?.fileUri){let t=e.fileData.displayName?` (${e.fileData.displayName})`:"",n=e.fileData.fileUri;return this.isSupportedAnthropicImageMimeType(e.fileData.mimeType)?{type:"image",source:{type:"url",url:n}}:e.fileData.mimeType==="application/pdf"?{type:"document",source:{type:"url",url:n}}:{type:"text",text:`Unsupported file media type: ${e.fileData.mimeType}${t}.`}}return null}isSupportedAnthropicImageMimeType(e){return e==="image/jpeg"||e==="image/png"||e==="image/gif"||e==="image/webp"}extractTextFromContentUnion(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>this.extractTextFromContentUnion(t)).filter(Boolean).join(`
24
- `):typeof e=="object"&&e!==null&&"parts"in e&&e.parts?.map(n=>typeof n=="string"?n:"text"in n&&n.text||"").filter(Boolean).join(`
25
- `)||""}extractFunctionResponseContent(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="object"){let t=e,n=t.output;if(typeof n=="string")return n;let s=t.error;if(typeof s=="string")return s}try{return JSON.stringify(e)??String(e)}catch{return String(e)}}safeInputToArgs(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:typeof e=="string"?wn(e):e==null?{}:null}mapAnthropicFinishReasonToGemini(e){return e?{end_turn:ee.STOP,stop_sequence:ee.STOP,tool_use:ee.STOP,max_tokens:ee.MAX_TOKENS,content_filter:ee.SAFETY}[e]||ee.FINISH_REASON_UNSPECIFIED:void 0}isContentObject(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&Array.isArray(e.parts)}buildSystemWithCacheControl(e,t){return e&&[{type:"text",text:e,cache_control:t?{type:"ephemeral",scope:"global"}:{type:"ephemeral"}}]}stripThinkingFromAssistantMessages(e){for(let t of e){if(t.role!=="assistant"||!Array.isArray(t.content))continue;let n=t.content.filter(s=>{let o=s.type;return o!=="thinking"&&o!=="redacted_thinking"});n.length!==0&&n.length!==t.content.length&&(t.content=n)}}fillMissingThinkingSignatures(e){for(let t of e){if(t.role!=="assistant"||!Array.isArray(t.content))continue;let n=!1,s=t.content.map(o=>{let i=o;return i.type==="thinking"&&typeof i.signature!="string"?(n=!0,{...o,signature:""}):o});n&&(t.content=s)}}injectEmptyThinkingOnToolUseTurns(e){for(let t of e){if(t.role!=="assistant"||!Array.isArray(t.content))continue;let n=t.content;if(!n.some(a=>a.type==="tool_use")||n.some(a=>{let u=a.type;return u==="thinking"||u==="redacted_thinking"}))continue;let i={type:"thinking",thinking:"",signature:""};t.content=[i,...n]}}addCacheControlToMessages(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user"){let s=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}];if(s.length>0){let o=s[s.length-1];if(typeof o=="object"&&"type"in o){let i=o.type,a=i==="text"&&(!("text"in o)||!o.text);(i==="text"||i==="tool_result")&&!a&&(o.cache_control={type:"ephemeral"})}n.content=s}break}}}};var yn=_n("ANTHROPIC");function kr(r){let e=r.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t==="api.deepseek.com"||t.endsWith(".api.deepseek.com")}catch{return!1}}function Os(r){return kr(r)?!0:(r.model??"").toLowerCase().includes("deepseek")}function Bs(r){let e=r.baseUrl?.trim();if(e)return e;let t=process.env.ANTHROPIC_BASE_URL?.trim();return t||"https://api.anthropic.com"}function wr(r){try{let e=new URL(Bs(r)).hostname.toLowerCase();return e==="api.anthropic.com"||e.endsWith(".anthropic.com")}catch{return!1}}function Sr(r,e){for(let t of r){if(e.jsonEscape){e.jsonEscape=!1;continue}if(t==="\\"&&e.inJsonString){e.jsonEscape=!0;continue}if(t==='"'){e.inJsonString=!e.inJsonString;continue}e.inJsonString||(t==="{"||t==="["?e.jsonDepth+=1:(t==="}"||t==="]")&&e.jsonDepth>0&&(e.jsonDepth-=1))}}function Ls(r){return r.jsonDepth>0||r.inJsonString}function js(r){let e=r.trim();if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{let t=Sn(e);if(t&&t!==e)try{let n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}return}}var Ze=class{constructor(e,t){this.contentGeneratorConfig=e;this.cliConfig=t;let n=!wr(e),s=this.buildHeaders(n),o=e.baseUrl,i=An("anthropic",this.cliConfig.getProxy());this.client=new _r({...n?{authToken:e.apiKey,apiKey:null}:{apiKey:e.apiKey,authToken:null},baseURL:o,timeout:e.timeout||6e5,maxRetries:e.maxRetries,defaultHeaders:s,...i}),this.converter=new Lt(e.model,e.schemaCompliance,e.enableCacheControl)}client;converter;effortClampWarned=!1;async generateContent(e){let t;try{let n=await this.buildRequest(e);nt.recordAnthropicWireRequest(n);let s=this.buildPerRequestHeaders(n);t=await this.client.messages.create(n,{signal:e.config?.abortSignal,...s?{headers:s}:{}})}catch(n){throw we(n)}return this.converter.convertAnthropicResponseToGemini(t)}async generateContentStream(e){let t=await this.buildRequest(e),n=this.buildPerRequestHeaders(t),s={...t,stream:!0};nt.recordAnthropicWireRequest(s);let o;try{o=await this.client.messages.create(s,{signal:e.config?.abortSignal,...n?{headers:n}:{}})}catch(i){throw we(i)}return this.processStreamWithEmptyFallback(this.redactStreamErrors(o),t,e.config?.abortSignal,n)}async countTokens(e){try{return{totalTokens:(await new En().calculateTokens(e)).totalTokens}}catch(t){yn.warn("Failed to calculate tokens with tokenizer, falling back to simple method:",t);let n=JSON.stringify(e.contents);return{totalTokens:Math.ceil(n.length/4)}}}async embedContent(e){throw new Error("Anthropic does not support embeddings.")}useSummarizedThinking(){return!1}buildHeaders(e){let t=this.cliConfig.getCliVersion()||"unknown",n=e?`claude-cli/${t} (external, cli)`:`MatildaCode/${t} (${process.platform}; ${process.arch})`,{customHeaders:s}=this.contentGeneratorConfig,o={"User-Agent":n};if(e&&(o["x-app"]="cli"),s)for(let[i,a]of Object.entries(s))i.toLowerCase()==="anthropic-beta"||bn(i)||(o[i]=a);return o}buildPerRequestHeaders(e){let t=[];for(let s of this.collectCustomBetaFlags())t.push(s);return e.thinking&&t.push("interleaved-thinking-2025-05-14"),e.output_config&&t.push("effort-2025-11-24"),this.hasGlobalCacheScopeOnWire(e)&&t.push("prompt-caching-scope-2026-01-05"),t.length===0?void 0:{"anthropic-beta":Array.from(new Set(t)).join(",")}}useGlobalCacheScope(){return this.contentGeneratorConfig.enableCacheControl!==!1&&wr(this.contentGeneratorConfig)}hasGlobalCacheScopeOnWire(e){let t=n=>{if(!n||typeof n!="object")return!1;let s=n.cache_control;return!s||typeof s!="object"?!1:s.scope==="global"};if(Array.isArray(e.system)){for(let n of e.system)if(t(n))return!0}if(Array.isArray(e.tools)){for(let n of e.tools)if(t(n))return!0}return!1}collectCustomBetaFlags(){let e=this.contentGeneratorConfig.customHeaders;if(!e)return[];let t=[];for(let[n,s]of Object.entries(e))if(n.toLowerCase()==="anthropic-beta"&&!(typeof s!="string"||!s))for(let o of s.split(",")){let i=o.trim();i&&t.push(i)}return t}async buildRequest(e){let t=this.buildSamplingParameters(e),n=this.resolveEffectiveEffort(e),s=this.buildThinkingConfig(e,n),o=this.buildOutputConfig(e,n),i=Os(this.contentGeneratorConfig),a=i&&!!s,u=i&&!s,l=this.contentGeneratorConfig.enableCacheControl!==!1,y=this.useGlobalCacheScope(),g=e.config?.tools?await this.converter.convertGeminiToolsToAnthropic(e.config.tools,{enableCacheControl:l,useGlobalCacheScope:y}):void 0,h=y&&!!g&&g.length>0,_=y&&!h,{system:S,messages:k}=this.converter.convertGeminiRequestToAnthropic(e,{normalizeAssistantThinkingSignature:a,injectThinkingOnToolUseTurns:a,stripAssistantThinking:u,enableCacheControl:l,useGlobalCacheScope:_});return{model:this.contentGeneratorConfig.model,system:S,messages:k,tools:g,...t,...s?{thinking:s}:{},...o?{output_config:o}:{}}}buildSamplingParameters(e){let t=this.contentGeneratorConfig.samplingParams,n=e.config||{},s=(y,g)=>{let h=t?.[y],_=g?n[g]:void 0;return h!==void 0?h:_},o=s("max_tokens","maxOutputTokens"),i=this.contentGeneratorConfig.model,a=Tn(i,"output"),u=xn(i),l;if(o!=null)l=u?Math.min(o,a):o;else{let y=process.env.MATILDA_CODE_MAX_OUTPUT_TOKENS,g=y?parseInt(y,10):NaN;!isNaN(g)&&g>0?l=u?Math.min(g,a):g:l=Math.min(a,8e3)}return{max_tokens:l,temperature:s("temperature","temperature")??1,top_p:s("top_p","topP"),top_k:s("top_k","topK")}}resolveEffectiveEffort(e){if(e.config?.thinkingConfig?.includeThoughts===!1)return;let t=this.contentGeneratorConfig.reasoning;if(t===!1||t===void 0)return;let n=t.effort;if(n!==void 0)return n==="max"&&!kr(this.contentGeneratorConfig)?(this.effortClampWarned||(yn.warn("reasoning.effort='max' is a DeepSeek extension; clamping to 'high' for non-DeepSeek anthropic provider to avoid HTTP 400."),this.effortClampWarned=!0),"high"):n}modelSupportsAdaptiveThinking(){let t=(this.contentGeneratorConfig.model||"").toLowerCase().match(/claude-(?:opus|sonnet|haiku)-(\d+)-(\d+)/);if(!t)return!1;let n=Number.parseInt(t[1],10),s=Number.parseInt(t[2],10);return n>4||n===4&&s>=6}buildThinkingConfig(e,t){if(e.config?.thinkingConfig?.includeThoughts===!1)return;let n=this.contentGeneratorConfig.reasoning;return n===!1?void 0:n?.budget_tokens!==void 0?{type:"enabled",budget_tokens:n.budget_tokens}:this.modelSupportsAdaptiveThinking()?{type:"adaptive"}:{type:"enabled",budget_tokens:t==="low"?16e3:t==="max"?128e3:t==="high"?64e3:32e3}}buildOutputConfig(e,t){if(t!==void 0)return{effort:t}}async*redactStreamErrors(e){try{for await(let t of e)yield t}catch(t){throw we(t)}}async*processStream(e){let t,n=this.contentGeneratorConfig.model,s=0,o=0,i=0,a=0,u,l=!1,y=new Map,g=[];for await(let h of e)switch(h.type){case"message_start":{t=h.message.id??t,n=h.message.model??n,s=h.message.usage?.cache_read_input_tokens??s,o=h.message.usage?.cache_creation_input_tokens??o,i=h.message.usage?.input_tokens??i;break}case"content_block_start":{let _=h.index??0,S=String(h.content_block.type||"text"),k=S==="tool_use"&&"input"in h.content_block?JSON.stringify(h.content_block.input):"",m={type:S,id:"id"in h.content_block?h.content_block.id:void 0,name:"name"in h.content_block?h.content_block.name:void 0,inputJson:k!=="{}"?k:"",signature:S==="thinking"&&"signature"in h.content_block&&typeof h.content_block.signature=="string"?h.content_block.signature:"",jsonDepth:0,inJsonString:!1,jsonEscape:!1};m.inputJson&&Sr(m.inputJson,m),y.set(_,m);break}case"content_block_delta":{let _=h.index??0,S=h.delta.type||"",k=y.get(_);if(S==="text_delta"){let m="text"in h.delta?h.delta.text:"";if(m){let J=this.buildGeminiChunk({text:m},t,n);g.push(J),yield J}}else if(S==="thinking_delta"){let m=h.delta.thinking||"";if(m){let J=this.buildGeminiChunk({text:m,thought:!0},t,n);g.push(J),yield J}}else if(S==="signature_delta"&&k){let m=h.delta.signature||"";if(m){k.signature+=m;let J=this.buildGeminiChunk({thought:!0,thoughtSignature:m},t,n);g.push(J),yield J}}else if(S==="input_json_delta"&&k){let m=h.delta.partial_json||"";m&&(k.inputJson+=m,Sr(m,k))}break}case"content_block_stop":{let _=h.index??0,S=y.get(_);if(S?.type==="tool_use")if(Ls(S))l=!0;else{let k=js(S.inputJson);if(k!==void 0){let m=this.buildGeminiChunk({functionCall:{id:S.id,name:S.name,args:k}},t,n);g.push(m),yield m}}y.delete(_);break}case"message_delta":{let _=h.delta.stop_reason;_&&(u=_),l&&u!=="max_tokens"&&(u="max_tokens");let S=h.usage,k=S&&typeof S=="object"?S:void 0;if(h.usage?.output_tokens!==void 0&&(a=h.usage.output_tokens),k?.input_tokens!==void 0){let m=k.input_tokens;typeof m=="number"&&(i=m)}if(k?.cache_read_input_tokens!==void 0){let m=k.cache_read_input_tokens;typeof m=="number"&&(s=m)}if(k?.cache_creation_input_tokens!==void 0){let m=k.cache_creation_input_tokens;typeof m=="number"&&(o=m)}if(u||h.usage){let m=this.buildGeminiChunk(void 0,t,n,u,Ye({inputTokens:i,cacheReadTokens:s,cacheCreationTokens:o,outputTokens:a}));g.push(m),yield m}break}case"message_stop":{if(l&&u!=="max_tokens"&&(u="max_tokens"),i||a){let _=this.buildGeminiChunk(void 0,t,n,u,Ye({inputTokens:i,cacheReadTokens:s,cacheCreationTokens:o,outputTokens:a}));g.push(_),yield _}break}default:break}}async*processStreamWithEmptyFallback(e,t,n,s){let o=!1,i=!1;for await(let u of this.processStream(e)){let l=u.candidates??[];i||=l.some(y=>y.finishReason!==void 0),o||=l.some(y=>y.content?.parts?.some(g=>g.text||g.thought||g.thoughtSignature||g.functionCall)),yield u}if(o||i)return;yn.warn("Anthropic stream ended without assistant payload or finish reason; probing once with a non-streaming request to surface provider errors.");let a;try{nt.recordAnthropicWireRequest(t),a=await this.client.messages.create(t,{signal:n,...s?{headers:s}:{}}),yield this.converter.convertAnthropicResponseToGemini(a)}catch(u){throw we(u)}}buildGeminiChunk(e,t,n,s,o){let i=new tt;i.responseId=t,i.createTime=Date.now().toString(),i.modelVersion=n||this.contentGeneratorConfig.model,i.promptFeedback={safetyRatings:[]};let a=e?[e]:[],u=s!==void 0?this.converter.mapAnthropicFinishReasonToGemini(s):void 0;return i.candidates=[{content:{parts:a,role:"model"},index:0,safetyRatings:[],...u?{finishReason:u}:{}}],o&&(i.usageMetadata=o),i}};function Sc(r,e){return new Ze(r,e)}export{Ze as AnthropicContentGenerator,Sc as createAnthropicContentGenerator};
26
- /**
27
- * @license
28
- * Copyright 2025 Matilda
29
- * SPDX-License-Identifier: Apache-2.0
30
- */
31
- /*! Bundled license information:
32
-
33
- humanize-ms/index.js:
34
- (*!
35
- * humanize-ms - index.js
36
- * Copyright(c) 2014 dead_horse <dead_horse@qq.com>
37
- * MIT Licensed
38
- *)
39
- */