@maincode-ai/matilda-code 0.21.12 → 0.21.13-nightly.20261026.e0eae1d8c
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.
- package/bundled/mainy/SKILL.md +0 -2
- package/bundled/mainy/docs/_meta.ts +0 -2
- package/bundled/mainy/docs/configuration/auth.md +5 -10
- package/bundled/mainy/docs/configuration/model-providers.md +31 -217
- package/bundled/mainy/docs/configuration/settings.md +32 -4
- package/bundled/mainy/docs/features/auto-mode.md +1 -1
- package/bundled/mainy/docs/features/channels/_meta.ts +0 -3
- package/bundled/mainy/docs/features/channels/overview.md +8 -16
- package/bundled/mainy/docs/features/commands.md +4 -4
- package/bundled/mainy/docs/features/hooks.md +9 -7
- package/bundled/mainy/docs/features/language.md +2 -29
- package/bundled/mainy/docs/features/sub-agents.md +1 -1
- package/bundled/mainy/docs/features/worktree.md +3 -5
- package/bundled/mainy/docs/integration-github-action.md +3 -3
- package/bundled/mainy/docs/matilda-serve.md +1 -1
- package/bundled/mainy/docs/quickstart.md +2 -2
- package/bundled/mainy/docs/support/troubleshooting.md +3 -10
- package/chunks/agent-4FTU3WN6.js +3 -0
- package/chunks/agent-headless-QJUVHPFC.js +3 -0
- package/chunks/{askUserQuestion-2QI4NSFJ.js → askUserQuestion-QKX4NEFX.js} +1 -1
- package/chunks/{ca-I2HEEIL7.js → ca-C2V7I65K.js} +6 -6
- package/chunks/{chunk-6E766NPX.js → chunk-2ONZZ46N.js} +2 -2
- package/chunks/chunk-36K4HBVM.js +7 -0
- package/chunks/{chunk-EQGA7LH7.js → chunk-3B2HABK7.js} +1 -1
- package/chunks/{chunk-MCQUPLRE.js → chunk-5NMK4Y7C.js} +1 -1
- package/chunks/chunk-5YT4GCK7.js +14 -0
- package/chunks/{chunk-27Q5KW3A.js → chunk-62AFAL4I.js} +10 -10
- package/chunks/chunk-75KP2FVD.js +81 -0
- package/chunks/chunk-7ZODGQO6.js +4 -0
- package/chunks/chunk-BZB7HYRC.js +37 -0
- package/chunks/{chunk-YRQP3SLC.js → chunk-EXNHJQCD.js} +1 -1
- package/chunks/chunk-FCGYRGV4.js +9 -0
- package/chunks/chunk-G4YMVWG4.js +8 -0
- package/chunks/{chunk-6T2GIM76.js → chunk-HDARIAVM.js} +1 -1
- package/chunks/{chunk-YJAKOETP.js → chunk-HM5LCKDB.js} +2 -2
- package/chunks/chunk-IIQ5YERM.js +120 -0
- package/chunks/{chunk-CSJTA7NE.js → chunk-JGJ7BVZN.js} +18 -18
- package/chunks/{chunk-GTVCJCHR.js → chunk-JIKQI4MZ.js} +1 -1
- package/chunks/{chunk-WV3IUPZS.js → chunk-LHDCAN7Z.js} +1 -1
- package/chunks/chunk-LZDHANXA.js +89 -0
- package/chunks/{chunk-PGXQZVLX.js → chunk-NOE4UNQN.js} +1 -1
- package/chunks/chunk-OEZS5R3S.js +207 -0
- package/chunks/{chunk-OOEH6ZSV.js → chunk-PTMCLADZ.js} +1 -1
- package/chunks/{chunk-2HTPVSGT.js → chunk-PYZNGIIR.js} +1 -1
- package/chunks/chunk-QJJTUDDA.js +56 -0
- package/chunks/{chunk-LUNDTQ3G.js → chunk-R34HYLL4.js} +1 -1
- package/chunks/{chunk-QVCGLQCI.js → chunk-RK4LPGBV.js} +3 -3
- package/chunks/{chunk-DE3HKC2W.js → chunk-RYHMPK5G.js} +1 -1
- package/chunks/chunk-SR7ARGUY.js +13 -0
- package/chunks/{chunk-JRECUFB3.js → chunk-SY6JRCN3.js} +636 -654
- package/chunks/chunk-TUKNB5CQ.js +33 -0
- package/chunks/{chunk-VTGICC67.js → chunk-TZ4FRU6B.js} +1 -1
- package/chunks/chunk-U7V7APDV.js +9 -0
- package/chunks/{chunk-CZGZ3KK7.js → chunk-UVWZ44ZW.js} +1 -1
- package/chunks/{chunk-HYVP4472.js → chunk-V6UPUMP3.js} +1 -1
- package/chunks/{chunk-DOOFGSRV.js → chunk-VLDZBRTL.js} +1 -1
- package/chunks/{computer-use-WKDNUTLD.js → computer-use-OXAMR75N.js} +1 -1
- package/chunks/contextCommand-ERLW5VWL.js +3 -0
- package/chunks/{cron-create-F2LXM2OA.js → cron-create-AUDQ6STP.js} +1 -1
- package/chunks/{cron-delete-DE6Q2S2L.js → cron-delete-P5HE3PDD.js} +1 -1
- package/chunks/{cron-list-IAQEJVV7.js → cron-list-NR5FZBK2.js} +1 -1
- package/chunks/{de-AQXFJYZI.js → de-KOUI2CEW.js} +5 -5
- package/chunks/{devtools-5JRKK3E7.js → devtools-G5DWLP2N.js} +1 -1
- package/chunks/dist-XXTQNTKQ.js +42 -0
- package/chunks/dist-ZFZZLIQU.js +3 -0
- package/chunks/{edit-QQNJZ55P.js → edit-REFR5ROS.js} +1 -1
- package/chunks/{en-EJLDYIBM.js → en-RMYRLXC2.js} +4 -4
- package/chunks/{enter-worktree-5X5SAMBJ.js → enter-worktree-WO3DT2G7.js} +1 -1
- package/chunks/{enterPlanMode-HP35SPLN.js → enterPlanMode-PLRHEU5A.js} +1 -1
- package/chunks/{exit-worktree-SRKZBEYF.js → exit-worktree-J5PW6DCV.js} +1 -1
- package/chunks/{exitPlanMode-WSPTGGVN.js → exitPlanMode-KXUPNLCJ.js} +2 -2
- package/chunks/{fr-6TDHK7F2.js → fr-R3QF3LA2.js} +5 -5
- package/chunks/glob-ZVTVRDQO.js +22 -0
- package/chunks/{goal-tools-C6BSBHCF.js → goal-tools-XVKQJL5I.js} +1 -1
- package/chunks/{grep-MVCOBUYW.js → grep-R7CWUNNE.js} +1 -1
- package/chunks/{ja-GGNJR7AR.js → ja-A5OQLXUZ.js} +5 -5
- package/chunks/{keychain-token-storage-KQK6MNOJ.js → keychain-token-storage-IM4UB4P4.js} +1 -1
- package/chunks/{ls-JYJXFSXN.js → ls-DEAFYDVV.js} +1 -1
- package/chunks/{lsp-DYDK6XCS.js → lsp-DL7W47VY.js} +1 -1
- package/chunks/matildaAgentContentGenerator-57EIU5XE.js +8 -0
- package/chunks/mcp-client-X7LEGSP3.js +3 -0
- package/chunks/monitor-KPWTMH3V.js +32 -0
- package/chunks/{multipart-parser-JI75T2O5.js → multipart-parser-FKHYAVGR.js} +1 -1
- package/chunks/notebook-edit-3ZH5M2TC.js +17 -0
- package/chunks/openaiContentGenerator-6PXSD3T7.js +37 -0
- package/chunks/{pt-D6L2QTDM.js → pt-RG3S3KA7.js} +5 -5
- package/chunks/read-file-JNS7WRUP.js +3 -0
- package/chunks/ripGrep-ICJDGIIV.js +3 -0
- package/chunks/{ru-BNJCHDYO.js → ru-5S5HLRT7.js} +5 -5
- package/chunks/scheduler-QC2PPMFP.js +8 -0
- package/chunks/{send-message-P3SMWNEE.js → send-message-V2WYLN5X.js} +1 -1
- package/chunks/{serve-FXH6EBQ6.js → serve-NUVQULZJ.js} +59 -48
- package/chunks/shell-5LNI7URE.js +3 -0
- package/chunks/{skill-HZPFEAPF.js → skill-QFATRHQW.js} +1 -1
- package/chunks/src-6UPZ7TVB.js +3 -0
- package/chunks/src-LZEU4AYF.js +5 -0
- package/chunks/{symbol-search-EAIZPWN7.js → symbol-search-WL6ZHUUN.js} +1 -1
- package/chunks/{syntheticOutput-432LXITX.js → syntheticOutput-3KW6SQAF.js} +1 -1
- package/chunks/task-create-PNW5SN27.js +3 -0
- package/chunks/{task-detach-XMSJ3HBM.js → task-detach-B7PDPFBA.js} +1 -1
- package/chunks/task-list-GGZATGK5.js +9 -0
- package/chunks/{task-stop-NTS62FLG.js → task-stop-UKBBE2KG.js} +1 -1
- package/chunks/{task-update-AR26UFYZ.js → task-update-4RHVUBUV.js} +1 -1
- package/chunks/{team-create-PYXFVIR5.js → team-create-2TJC3X57.js} +1 -1
- package/chunks/team-delete-4UJ7SU65.js +8 -0
- package/chunks/todoWrite-NEBVKOSG.js +3 -0
- package/chunks/{tool-search-RKZDSRYS.js → tool-search-R5GS64YR.js} +1 -1
- package/chunks/{web-fetch-VW3SVDQ6.js → web-fetch-H3XJMAEF.js} +17 -17
- package/chunks/{web-search-XQUIZARL.js → web-search-Q6RWPEIB.js} +1 -1
- package/chunks/{workflow-YXNXDRWZ.js → workflow-3A7KN3E3.js} +2 -2
- package/chunks/write-file-O7Q6SKZC.js +15 -0
- package/cli.js +502 -498
- package/locales/ca.js +1 -28
- package/locales/de.js +1 -28
- package/locales/en.js +1 -30
- package/locales/fr.js +1 -30
- package/locales/ja.js +1 -28
- package/locales/pt.js +1 -28
- package/locales/ru.js +1 -28
- package/package.json +2 -2
- package/sandbox-macos-permissive-closed.sb +0 -1
- package/sandbox-macos-permissive-open.sb +0 -1
- package/sandbox-macos-permissive-proxied.sb +0 -1
- package/sandbox-macos-restrictive-closed.sb +0 -1
- package/sandbox-macos-restrictive-open.sb +0 -1
- package/sandbox-macos-restrictive-proxied.sb +0 -1
- package/bundled/mainy/docs/features/channels/dingtalk.md +0 -134
- package/bundled/mainy/docs/features/channels/feishu.md +0 -186
- package/bundled/mainy/docs/features/channels/weixin.md +0 -106
- package/bundled/mainy/docs/integration-jetbrains.md +0 -81
- package/bundled/mainy/docs/integration-zed.md +0 -72
- package/chunks/agent-WM63A6NK.js +0 -3
- package/chunks/agent-headless-QIUBDKPW.js +0 -3
- package/chunks/anthropicContentGenerator-VKFTAIU3.js +0 -39
- package/chunks/chunk-2MOGYHWM.js +0 -8
- package/chunks/chunk-3IRGBRSP.js +0 -113
- package/chunks/chunk-3YLXGE6T.js +0 -8
- package/chunks/chunk-4F4DA5UI.js +0 -8
- package/chunks/chunk-4J6DC24J.js +0 -59
- package/chunks/chunk-4Q2SNBUH.js +0 -18
- package/chunks/chunk-5C2RJ5RR.js +0 -37
- package/chunks/chunk-6EQMZNIY.js +0 -8
- package/chunks/chunk-6GBNB5Z2.js +0 -3
- package/chunks/chunk-6Z2MV7ZY.js +0 -186
- package/chunks/chunk-BVOCFLC4.js +0 -56
- package/chunks/chunk-FPO57O66.js +0 -39
- package/chunks/chunk-G7R2XEEF.js +0 -7
- package/chunks/chunk-GOJCMVJJ.js +0 -8
- package/chunks/chunk-JCE3JAVC.js +0 -25
- package/chunks/chunk-KHHJYBR5.js +0 -9
- package/chunks/chunk-LJR4RZZ2.js +0 -3
- package/chunks/chunk-MO2HXJG5.js +0 -9
- package/chunks/chunk-O44XK65C.js +0 -8
- package/chunks/chunk-OA56BXPD.js +0 -3
- package/chunks/chunk-PA6532AY.js +0 -6
- package/chunks/chunk-QN6Y6NPA.js +0 -3
- package/chunks/chunk-S3CWEVTS.js +0 -15
- package/chunks/chunk-SDTWBD62.js +0 -8
- package/chunks/chunk-U347OO7S.js +0 -9
- package/chunks/chunk-UIRBHC5X.js +0 -3
- package/chunks/chunk-VI74YQQO.js +0 -8
- package/chunks/chunk-VYZOOSMP.js +0 -30
- package/chunks/chunk-WC2VTVCE.js +0 -27
- package/chunks/chunk-WVY2P6WH.js +0 -26
- package/chunks/chunk-WZ75OGYY.js +0 -14
- package/chunks/chunk-XMZIY7XX.js +0 -13
- package/chunks/chunk-YV3PUOBU.js +0 -65
- package/chunks/contextCommand-DAB3HOHY.js +0 -3
- package/chunks/dist-7UYRLSLE.js +0 -3
- package/chunks/dist-ME6647DQ.js +0 -195
- package/chunks/dist-P6SLWL5V.js +0 -42
- package/chunks/dist-VG3ZDJ2A.js +0 -28
- package/chunks/dist-YTCHM57U.js +0 -23
- package/chunks/fileFromPath-7UCWPD4W.js +0 -3
- package/chunks/geminiContentGenerator-RJ73DQAP.js +0 -8
- package/chunks/glob-QQ6LGKDX.js +0 -22
- package/chunks/matildaAgentContentGenerator-YUYS4336.js +0 -8
- package/chunks/matildaContentGenerator-O4Z2QPCP.js +0 -8
- package/chunks/matildaOAuth2-7COTQQR2.js +0 -3
- package/chunks/mcp-client-RXVQU5VI.js +0 -3
- package/chunks/monitor-77KXDXPR.js +0 -32
- package/chunks/notebook-edit-TKJD2EQZ.js +0 -17
- package/chunks/openaiContentGenerator-2EALAM3U.js +0 -3
- package/chunks/read-file-3KUAH6ND.js +0 -3
- package/chunks/ripGrep-U2PLKXMY.js +0 -3
- package/chunks/scheduler-J7VU2V5Y.js +0 -8
- package/chunks/shell-PXR2AXDD.js +0 -3
- package/chunks/src-RFAEPLY7.js +0 -3
- package/chunks/src-WZTRMETQ.js +0 -5
- package/chunks/task-create-Z3QRCMX4.js +0 -3
- package/chunks/task-list-GXAJW3JP.js +0 -9
- package/chunks/team-delete-OMYVUAQU.js +0 -8
- package/chunks/todoWrite-5NZ7CHTC.js +0 -3
- package/chunks/write-file-XDDLTGSG.js +0 -15
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
# Zed Editor
|
|
2
|
-
|
|
3
|
-
> Zed Editor provides native support for AI coding assistants through the Agent Client Protocol (ACP). This integration allows you to use Matilda Code directly within Zed's interface with real-time code suggestions.
|
|
4
|
-
|
|
5
|
-

|
|
6
|
-
|
|
7
|
-
### Features
|
|
8
|
-
|
|
9
|
-
- **Native agent experience**: Integrated AI assistant panel within Zed's interface
|
|
10
|
-
- **Agent Client Protocol**: Full support for ACP enabling advanced IDE interactions
|
|
11
|
-
- **File management**: @-mention files to add them to the conversation context
|
|
12
|
-
- **Conversation history**: Access to past conversations within Zed
|
|
13
|
-
|
|
14
|
-
### Requirements
|
|
15
|
-
|
|
16
|
-
- Zed Editor (latest version recommended)
|
|
17
|
-
- Matilda Code CLI installed
|
|
18
|
-
|
|
19
|
-
### Installation
|
|
20
|
-
|
|
21
|
-
#### Install from ACP Registry (Recommend)
|
|
22
|
-
|
|
23
|
-
1. Install Matilda Code CLI:
|
|
24
|
-
|
|
25
|
-
```bash
|
|
26
|
-
npm install -g @maincode-ai/matilda-code
|
|
27
|
-
```
|
|
28
|
-
|
|
29
|
-
2. Download and install [Zed Editor](https://zed.dev/)
|
|
30
|
-
|
|
31
|
-
3. In Zed, click the **settings button** in the top right corner, select **"Add agent"**, choose **"Install from Registry"**, find **Matilda Code**, then click **Install**.
|
|
32
|
-
|
|
33
|
-

|
|
34
|
-
|
|
35
|
-

|
|
36
|
-
|
|
37
|
-
#### Manual Install
|
|
38
|
-
|
|
39
|
-
1. Install Matilda Code CLI:
|
|
40
|
-
|
|
41
|
-
```bash
|
|
42
|
-
npm install -g @maincode-ai/matilda-code
|
|
43
|
-
```
|
|
44
|
-
|
|
45
|
-
2. Download and install [Zed Editor](https://zed.dev/)
|
|
46
|
-
|
|
47
|
-
3. In Zed, click the **settings button** in the top right corner, select **"Add agent"**, choose **"Create a custom agent"**, and add the following configuration:
|
|
48
|
-
|
|
49
|
-
```json
|
|
50
|
-
"Matilda Code": {
|
|
51
|
-
"type": "custom",
|
|
52
|
-
"command": "matilda",
|
|
53
|
-
"args": ["--acp"],
|
|
54
|
-
"env": {}
|
|
55
|
-
}
|
|
56
|
-
```
|
|
57
|
-
|
|
58
|
-

|
|
59
|
-
|
|
60
|
-
## Troubleshooting
|
|
61
|
-
|
|
62
|
-
### Agent not appearing
|
|
63
|
-
|
|
64
|
-
- Run `matilda --version` in terminal to verify installation
|
|
65
|
-
- Check that the JSON configuration is valid
|
|
66
|
-
- Restart Zed Editor
|
|
67
|
-
|
|
68
|
-
### Matilda Code not responding
|
|
69
|
-
|
|
70
|
-
- Check your internet connection
|
|
71
|
-
- Verify CLI works by running `matilda` in terminal
|
|
72
|
-
- [File an issue on GitHub](https://github.com/MaincodeHQ/matilda-code/issues) if the problem persists
|
package/chunks/agent-WM63A6NK.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{$g as e,Xg as a,Yg as b,Zg as c,_g as d,ah as f}from"./chunk-JRECUFB3.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-2HTPVSGT.js";import"./chunk-MO2HXJG5.js";import"./chunk-2MOGYHWM.js";import"./chunk-S3CWEVTS.js";import"./chunk-TISQNFB5.js";import"./chunk-47XR7IMP.js";import"./chunk-MTMU7JYZ.js";import"./chunk-QKYGQLWC.js";import"./chunk-WV3IUPZS.js";import"./chunk-RNKDFE2S.js";import"./chunk-BVOCFLC4.js";import"./chunk-MCQUPLRE.js";import"./chunk-CZGZ3KK7.js";import"./chunk-HYVP4472.js";import"./chunk-WC2VTVCE.js";import"./chunk-KHHJYBR5.js";import"./chunk-6EQMZNIY.js";import"./chunk-DOOFGSRV.js";import"./chunk-DE3HKC2W.js";import"./chunk-GTVCJCHR.js";import"./chunk-QVCGLQCI.js";import"./chunk-VI74YQQO.js";import"./chunk-YV3PUOBU.js";import"./chunk-3IRGBRSP.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-3YLXGE6T.js";import"./chunk-JCE3JAVC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-6Z2MV7ZY.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-PGXQZVLX.js";import"./chunk-LUNDTQ3G.js";import"./chunk-YRQP3SLC.js";import"./chunk-6E766NPX.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{vg as a,wg as b,xg as c}from"./chunk-JRECUFB3.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-2HTPVSGT.js";import"./chunk-MO2HXJG5.js";import"./chunk-2MOGYHWM.js";import"./chunk-S3CWEVTS.js";import"./chunk-TISQNFB5.js";import"./chunk-47XR7IMP.js";import"./chunk-MTMU7JYZ.js";import"./chunk-QKYGQLWC.js";import"./chunk-WV3IUPZS.js";import"./chunk-RNKDFE2S.js";import"./chunk-BVOCFLC4.js";import"./chunk-MCQUPLRE.js";import"./chunk-CZGZ3KK7.js";import"./chunk-HYVP4472.js";import"./chunk-WC2VTVCE.js";import"./chunk-KHHJYBR5.js";import"./chunk-6EQMZNIY.js";import"./chunk-DOOFGSRV.js";import"./chunk-DE3HKC2W.js";import"./chunk-GTVCJCHR.js";import"./chunk-QVCGLQCI.js";import"./chunk-VI74YQQO.js";import"./chunk-YV3PUOBU.js";import"./chunk-3IRGBRSP.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-3YLXGE6T.js";import"./chunk-JCE3JAVC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-6Z2MV7ZY.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-PGXQZVLX.js";import"./chunk-LUNDTQ3G.js";import"./chunk-YRQP3SLC.js";import"./chunk-6E766NPX.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 _n,c as wn,d as Sn,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-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{f as kn}from"./chunk-SDTWBD62.js";import{ba as bn}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=Sn(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"?_n(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=bn("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=wn(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"||kn(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
|
-
*/
|
package/chunks/chunk-2MOGYHWM.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{b as X,h as T}from"./chunk-S3CWEVTS.js";import{b as P}from"./chunk-TISQNFB5.js";import{c as g}from"./chunk-LUNDTQ3G.js";import{b as l,ba as $}from"./chunk-27Q5KW3A.js";import{b as _}from"./chunk-GZPNIYVZ.js";import{f as W}from"./chunk-OWGSC52X.js";_();var R=W(X(),1);import*as d from"node:fs/promises";import{constants as B}from"node:fs";import*as b from"node:path";var f=$("AGENTS_TEAM_TASKS"),v=32768,A=16;function C(r){if(!r)return;let e=Buffer.byteLength(JSON.stringify(r),"utf-8");if(e>v)throw new Error(`Task metadata is too large (${e} bytes; max ${v}). Trim the payload or store the bulk content elsewhere.`)}var K={retries:{retries:30,minTimeout:5,maxTimeout:100,factor:2,randomize:!0},stale:5e3,onCompromised:r=>{f.warn("task lock compromised:",r?.message??r)}},j=new Map;function q(r){let e=j.get(r);return e||(e=new P,j.set(r,e)),e}async function h(r,e,t){return q(r).runExclusive(async()=>{let a;try{a=await R.default.lock(r,K)}catch(o){if(l(o)&&o.code==="ENOENT")return t();throw o}try{return await e()}finally{await a()}})}var z="__reciprocal__",L=new Map;function Y(r){let e=L.get(r);return e||(e=new P,L.set(r,e)),e}function G(r){if(!/^[1-9]\d*$/.test(r))throw new Error(`Invalid task ID "${r}". Task IDs must be positive integers.`)}function m(r,e){return G(e),b.join(T(r),`${e}.json`)}var O=new Set;function ie(r){return O.add(r),()=>{O.delete(r)}}function k(r){for(let e of O)try{e(r)}catch(t){f.warn(`task update listener failed: ${t}`)}}async function oe(r,e){C(e.metadata);let t=T(r);await d.mkdir(t,{recursive:!0});let a=15;for(let o=0;o<a;o++){let c=await I(t),s={id:c,subject:e.subject,description:e.description,activeForm:e.activeForm,owner:e.owner,status:"pending",blocks:[],blockedBy:[],metadata:e.metadata},n=b.join(t,`${c}.json`);try{await(await d.open(n,B.O_WRONLY|B.O_CREAT|B.O_EXCL)).close()}catch(i){if(l(i)&&i.code==="EEXIST")continue;throw i}try{await g(n,s)}catch(i){throw await d.unlink(n).catch(()=>{}),i}return k(r),s}throw new Error(`Failed to create task after ${a} attempts (ID contention).`)}async function ce(r,e){let t=m(r,e);try{let a=await d.readFile(t,"utf-8");return JSON.parse(a)}catch(a){if(l(a)&&a.code==="ENOENT")return;throw a}}var p=class extends Error{constructor(t,a,o){super(`Task #${t} is owned by "${o}". Only the leader or the owner can change status / owner / subject / description / blocks.`);this.taskId=t;this.callerName=a;this.actualOwner=o;this.name="TaskOwnershipError"}};async function F(r,e,t,a){let o=m(r,e);return h(o,async()=>{let c;try{c=await d.readFile(o,"utf-8")}catch(n){if(l(n)&&n.code==="ENOENT")return;throw n}let s=JSON.parse(c);if(a?.callerName!==void 0&&a.callerName!==z&&(t.status!==void 0||t.owner!==void 0||t.subject!==void 0||t.description!==void 0||(t.addBlocks?.length??0)>0||(t.addBlockedBy?.length??0)>0)&&s.owner&&s.owner!==a.callerName)throw new p(e,a.callerName,s.owner);if(t.addBlocks?.length){let n=new Set(s.blocks);for(let i of t.addBlocks)n.add(i);s.blocks=Array.from(n)}if(t.addBlockedBy?.length){let n=new Set(s.blockedBy);for(let i of t.addBlockedBy)n.add(i);s.blockedBy=Array.from(n)}if(t.status!==void 0&&(s.status=t.status,t.status==="completed"&&s.blocks.length>0&&await V(r,e,s.blocks)),t.owner!==void 0&&(s.owner=t.owner?t.owner:void 0),t.subject!==void 0&&(s.subject=t.subject),t.description!==void 0&&(s.description=t.description),t.activeForm!==void 0&&(s.activeForm=t.activeForm??void 0),t.metadata!==void 0){s.metadata=s.metadata??{};for(let[n,i]of Object.entries(t.metadata))n==="__proto__"||n==="constructor"||n==="prototype"||(i===null?delete s.metadata[n]:s.metadata[n]=i);Object.keys(s.metadata).length===0&&(s.metadata=void 0),C(s.metadata)}return await g(o,s),k(r),s},()=>{})}async function de(r,e,t){let a=m(r,e),o=await h(a,async()=>{let s;try{let i=await d.readFile(a,"utf-8");s=JSON.parse(i)}catch(i){if(l(i)&&i.code==="ENOENT")return null;throw i}if(t?.callerName!==void 0&&s.owner&&s.owner!==t.callerName)throw new p(e,t.callerName,s.owner);let n=new Set([...s.blocks,...s.blockedBy]);n.delete(e);try{await d.unlink(a)}catch(i){if(l(i)&&i.code==="ENOENT")return null;throw i}return n},()=>null);if(o===null)return!1;let c=await Promise.allSettled(Array.from(o).map(s=>Q(r,s,e)));for(let s of c)s.status==="rejected"&&f.warn(`deleteTask(${e}): edge cleanup failed: ${s.reason}`);return k(r),!0}async function Q(r,e,t){let a=m(r,e);await h(a,async()=>{try{let o=await d.readFile(a,"utf-8"),c=JSON.parse(o),s=c.blocks.length,n=c.blockedBy.length;if(c.blocks=c.blocks.filter(i=>i!==t),c.blockedBy=c.blockedBy.filter(i=>i!==t),c.blocks.length===s&&c.blockedBy.length===n)return;await g(a,c)}catch(o){if(l(o)&&o.code==="ENOENT")return;throw o}},()=>{})}async function x(r,e){let t=T(r),a;try{a=await d.readdir(t)}catch(n){if(l(n)&&n.code==="ENOENT")return[];let i=n instanceof Error?n.message:String(n);throw f.warn(`Failed to list tasks dir ${t}: ${i}`),n instanceof Error?n:new Error(i)}let o=a.filter(n=>n.endsWith(".json")),c=[];for(let n=0;n<o.length;n+=A){let i=o.slice(n,n+A),w=await Promise.all(i.map(async D=>{let y=b.join(t,D),S;try{S=await d.readFile(y,"utf-8")}catch(u){if(l(u)&&u.code==="ENOENT")return;let E=u instanceof Error?u.message:String(u);f.warn(`Failed to read task file ${y}: ${E}`);return}if(S.trim()!=="")try{return JSON.parse(S)}catch(u){let E=u instanceof Error?u.message:String(u);f.warn(`Quarantining corrupt task file ${y}: ${E}`);let J=`${y}.corrupt-${Date.now()}`;try{await d.rename(y,J)}catch(N){let U=N instanceof Error?N.message:String(N);f.warn(`Failed to quarantine ${y}: ${U}`)}return}}));c.push(...w)}let s=c.filter(n=>n!==void 0);return s.sort((n,i)=>Number(n.id)-Number(i.id)),e?s.filter(n=>!(e.status!==void 0&&n.status!==e.status||e.owner!==void 0&&n.owner!==e.owner||e.blockedBy!==void 0&&!n.blockedBy.includes(e.blockedBy))):s}async function le(r){let e=T(r);await d.rm(e,{recursive:!0,force:!0}),k(r)}async function V(r,e,t){let a=await Promise.allSettled(t.map(async o=>{let c=m(r,o);await h(c,async()=>{let s;try{s=await d.readFile(c,"utf-8")}catch(w){if(l(w)&&w.code==="ENOENT")return;throw w}let n=JSON.parse(s),i=n.blockedBy.length;n.blockedBy=n.blockedBy.filter(w=>w!==e),n.blockedBy.length!==i&&await g(c,n)},()=>{})}));for(let o of a)o.status==="rejected"&&f.warn(`unblockDependents(${e}): ${o.reason}`);k(r)}async function ue(r,e,t){await F(r,e,{addBlocks:[t]}),await F(r,t,{addBlockedBy:[e]})}async function fe(r,e,t,a){return a?.checkAgentBusy?Y(t).runExclusive(()=>M(r,e,t,a,!0)):M(r,e,t,a,!1)}async function M(r,e,t,a,o){if(o&&await H(r,t))return;let c=m(r,e);return h(c,async()=>{let s;try{s=await d.readFile(c,"utf-8")}catch(i){if(l(i)&&i.code==="ENOENT")return;throw i}let n=JSON.parse(s);if(n.status==="pending"&&!n.owner)return n.owner=a?.ownerName??t,n.status="in_progress",await g(c,n),k(r),n},()=>{})}async function H(r,e){let t=await x(r,{status:"in_progress"}),a=e.split("@")[0];return t.some(o=>o.owner===e||o.owner===a)}async function Z(r,e,t){let a=m(r,e);return h(a,async()=>{let o;try{o=await d.readFile(a,"utf-8")}catch(s){if(l(s)&&s.code==="ENOENT")return!1;throw s}let c=JSON.parse(o);return c.status!=="in_progress"||c.owner!==t?!1:(c.owner=void 0,c.status="pending",await g(a,c),!0)},()=>!1)}async function we(r,e){let t=e.split("@")[0],o=(await x(r,{status:"in_progress"})).filter(i=>i.owner===e||i.owner===t),c=await Promise.allSettled(o.map(i=>Z(r,i.id,i.owner))),s=c.filter(i=>i.status==="rejected");s.length>0&&f.warn(`unassignTeammateTasks: ${s.length}/${o.length} task(s) failed to unassign for ${e}`);let n=c.filter(i=>i.status==="fulfilled"&&i.value===!0).length;return n>0&&k(r),n}async function ge(r){let e=await x(r),t=new Map;for(let a of e){if(!a.owner)continue;let o=t.get(a.owner)??{inProgress:0,completed:0};a.status==="in_progress"?o.inProgress++:a.status==="completed"&&o.completed++,t.set(a.owner,o)}return t}async function I(r){let e;try{e=await d.readdir(r)}catch{return"1"}let t=0;for(let a of e){if(!a.endsWith(".json"))continue;let o=parseInt(a.replace(".json",""),10);!isNaN(o)&&o>t&&(t=o)}return String(t+1)}export{z as a,G as b,m as c,ie as d,k as e,oe as f,ce as g,p as h,F as i,de as j,x as k,le as l,ue as m,fe as n,Z as o,we as p,ge as q};
|
|
4
|
-
/**
|
|
5
|
-
* @license
|
|
6
|
-
* Copyright 2025 Matilda
|
|
7
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
-
*/
|