murmur-rag 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +106 -2
  3. package/dist/cdn/anthropic-w7nkjk5e.js +2 -0
  4. package/dist/cdn/browser-t87kf8t0.js +64 -0
  5. package/dist/cdn/chunk-e0j28zmb.js +1 -0
  6. package/dist/cdn/embed-2xm309sb.js +7 -0
  7. package/dist/cdn/embed-4mxwfy19.js +0 -0
  8. package/dist/cdn/embed-59r4jck6.js +6 -0
  9. package/dist/cdn/embed-hn0r8fmg.js +10 -0
  10. package/dist/cdn/embed-n7jskdxd.js +44 -0
  11. package/dist/cdn/embed-q6y6vgv1.js +5 -0
  12. package/dist/cdn/embed-sgjh2kg2.js +83 -0
  13. package/dist/cdn/embed-we24qtes.js +2 -0
  14. package/dist/cdn/google-qha5xyx4.js +14 -0
  15. package/dist/cdn/index-11c9cspb.js +1 -0
  16. package/dist/cdn/index-e5entetm.js +1 -0
  17. package/dist/cdn/index-kk9hgxdc.js +1 -0
  18. package/dist/cdn/index-zrmby2xc.js +9 -0
  19. package/dist/cdn/mistral-16bekg8b.js +3 -0
  20. package/dist/cdn/models.json +1 -0
  21. package/dist/cdn/murmur-5vkc01ns.js +5 -0
  22. package/dist/cdn/murmur.js +204 -0
  23. package/dist/cdn/openai-compatible-za7hc1fv.js +11 -0
  24. package/dist/cdn/openai-dhy4fp4c.js +18 -0
  25. package/dist/cdn/retriever-k9mmdcz5.js +1 -0
  26. package/dist/cli.js +272 -0
  27. package/dist/lib/chunks/chunk-kaeec41p.js +18 -0
  28. package/dist/lib/chunks/index-1zk822m5.js +72 -0
  29. package/dist/lib/chunks/index-6re28wc1.js +46 -0
  30. package/dist/lib/chunks/index-fp1p1byg.js +0 -0
  31. package/dist/lib/chunks/index-fs6gmhz9.js +81 -0
  32. package/dist/lib/chunks/index-v9expxwm.js +1151 -0
  33. package/dist/lib/chunks/index-z8pn9sdj.js +43 -0
  34. package/dist/lib/chunks/murmur-wq1d15n7.js +9 -0
  35. package/dist/lib/chunks/retriever-1rw4z2n6.js +8 -0
  36. package/dist/lib/embed.js +67 -0
  37. package/dist/lib/index.js +45 -0
  38. package/dist/lib/indexer/index.js +108 -0
  39. package/dist/lib/llm/index.js +55 -0
  40. package/dist/lib/rag/index.js +39 -0
  41. package/dist/lib/widget/index.js +22 -0
  42. package/dist/types/core/murmur.d.ts +48 -0
  43. package/dist/types/embed.d.ts +6 -0
  44. package/dist/types/index.d.ts +2 -0
  45. package/dist/types/indexer/extract.d.ts +16 -0
  46. package/dist/types/indexer/files.d.ts +4 -0
  47. package/dist/types/indexer/index.d.ts +33 -0
  48. package/dist/types/llm/index.d.ts +31 -0
  49. package/dist/types/rag/chunk.d.ts +28 -0
  50. package/dist/types/rag/ground.d.ts +12 -0
  51. package/dist/types/rag/index.d.ts +4 -0
  52. package/dist/types/rag/retriever.d.ts +18 -0
  53. package/dist/types/rag/types.d.ts +28 -0
  54. package/dist/types/widget/element.d.ts +54 -0
  55. package/dist/types/widget/i18n.d.ts +48 -0
  56. package/dist/types/widget/icons.d.ts +4 -0
  57. package/dist/types/widget/index.d.ts +13 -0
  58. package/dist/types/widget/markdown.d.ts +8 -0
  59. package/dist/types/widget/session.d.ts +66 -0
  60. package/dist/types/widget/styles.d.ts +6 -0
  61. package/package.json +114 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 maxgfr
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,107 @@
1
- # Temporary Holding Version
1
+ # murmur
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **[Site & live demo](https://maxgfr.github.io/murmur/)** · **[Guide](https://maxgfr.github.io/murmur/guide.html)** · **[Playground](https://maxgfr.github.io/murmur/playground.html)** · [npm](https://www.npmjs.com/package/murmur-rag)
4
+
5
+ An AI chat bubble for any website that answers from the site's own pages, cites them and links to the right heading. One script tag, no backend, the model you pick through [llm-connect](https://github.com/maxgfr/llm-models/tree/main/packages/llm-connect). Works on GitHub Pages.
6
+
7
+ ```html
8
+ <script type="module" src="https://maxgfr.github.io/murmur/cdn/murmur.js"></script>
9
+ ```
10
+
11
+ ## The widget
12
+
13
+ Paste the line before `</body>`. Without options, the bubble answers from the page the visitor is on and each visitor brings their own AI key. The [configurator](https://maxgfr.github.io/murmur/#wire) writes the line for you.
14
+
15
+ | Attribute | |
16
+ | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
17
+ | `data-index` | URL of the index written by `murmur index` (`/murmur-index.json`). Without it, the current page is read |
18
+ | `data-endpoint` | Your OpenAI-compatible proxy (https): visitors chat without a key |
19
+ | `data-provider`, `data-model` | Provider and model preselected for visitors, or the model asked of the proxy |
20
+ | `data-instructions` | Your instructions to the assistant |
21
+ | `data-title`, `data-greeting`, `data-placeholder`, `data-button` | Texts of the panel |
22
+ | `data-lang` | `en` or `fr` (default: the page's `lang`, then the browser's) |
23
+ | `data-position` | `bottom-right` (default) or `bottom-left` |
24
+ | `data-accent`, `data-theme` | Any CSS colour; `auto`, `light` or `dark` |
25
+ | `data-open`, `data-storage-key` | Open on load; prefix of what the widget stores |
26
+
27
+ The widget lives in a Shadow DOM and is restyled through `--murmur-accent`, `--murmur-accent-ink`, `--murmur-font`, `--murmur-radius` and `--murmur-z`. It emits `murmur:state` events (`searching`, `streaming`, `done`, `error`) with the passages found and cited.
28
+
29
+ ## Index your site
30
+
31
+ ```bash
32
+ npx murmur-rag index ./dist --out ./dist/murmur-index.json
33
+ ```
34
+
35
+ Reads every `.html`, `.md` and `.txt` file (or a live `sitemap.xml`), keeps the content of `main` / `article` / `body`, skips navigation, headers, footers, forms, scripts and anything marked `data-murmur-ignore`, and cuts pages into passages under their headings. Options: `--base` (URL prefix), `--root`, `--exclude`, `--max-chunk`.
36
+
37
+ ## AI models and keys
38
+
39
+ A key in a web page is readable by anyone, so murmur never puts one there:
40
+
41
+ - **Your proxy holds the key.** Deploy [`examples/cloudflare-worker`](examples/cloudflare-worker) (about 40 lines): it keeps the key as a secret, allows only your origin, fixes the model and caps answers. Then `data-endpoint="https://murmur-proxy.you.workers.dev/v1"`.
42
+ - **Each visitor brings theirs.** The first question opens the AI settings, built on llm-connect's store: provider and model from the [llm-models](https://github.com/maxgfr/llm-models) catalog, the key encrypted with AES-GCM under a non-extractable browser key and sent only to that provider, or a local Ollama / LM Studio.
43
+
44
+ ## npm package
45
+
46
+ ```bash
47
+ npm install murmur-rag
48
+ ```
49
+
50
+ | Import | |
51
+ | -------------------- | ------------------------------------------------------------------------------------------------------ |
52
+ | `murmur-rag` | `createMurmur({ index \| retriever, model })`: `ask()` streams an answer and its cited passages, no UI |
53
+ | `murmur-rag/rag` | `bm25Retriever`, `buildIndex`, `splitText`, `formatSources`, `citedSources`, the `Retriever` interface |
54
+ | `murmur-rag/indexer` | `indexPages`, `indexDocument`, `extractSections` (Node or browser) |
55
+ | `murmur-rag/llm` | `proxySettings`, `visitorStore`, `resolveSettings` on top of llm-connect |
56
+ | `murmur-rag/widget` | `mountMurmur`, `defineMurmurChat`, `MurmurChat`, `renderMarkdown` |
57
+ | `murmur-rag/embed` | The script-tag entry |
58
+
59
+ ```ts
60
+ import { createMurmur } from "murmur-rag";
61
+ import { anthropic } from "@ai-sdk/anthropic";
62
+
63
+ const murmur = createMurmur({ index, model: anthropic("claude-sonnet-5-5") });
64
+ const answer = await murmur.ask("What does the Pro plan include?");
65
+ for await (const part of answer.textStream) process.stdout.write(part);
66
+ ```
67
+
68
+ Any object with `search(query)` returning passages replaces BM25 (embeddings, a search API…).
69
+
70
+ ## How it works
71
+
72
+ 1. **Index** (build time): pages become passages under their headings, in a static JSON file.
73
+ 2. **Search** (in the visitor's browser): BM25 with [MiniSearch], accents folded, prefix and fuzzy matching, titles and headings boosted.
74
+ 3. **Answer** (at the AI provider): the passages go to the model as quoted data, with instructions to answer only from them, cite them as `[n]`, say when the site does not cover the question and never follow instructions found inside them. The answer is rendered as text with clickable citations.
75
+
76
+ ## Limits
77
+
78
+ - Keyword search, not semantic: plug in your own retriever for embeddings.
79
+ - The index downloads with the first question: fine for hundreds of pages, not tens of thousands.
80
+ - In visitor-key mode the provider must accept browser calls (CORS).
81
+ - Grounding reduces invented answers; it does not end them.
82
+
83
+ ## Privacy
84
+
85
+ No server, no analytics. The question and the matching passages go to the AI provider chosen by you or the visitor, nowhere else. The conversation stays in the tab (`sessionStorage`).
86
+
87
+ ## Development
88
+
89
+ ```bash
90
+ bun install
91
+ bun run dev # build, then serve on http://localhost:4317/murmur/
92
+ bun run test # unit tests
93
+ bun run test:e2e # Playwright, against a fake OpenAI-compatible endpoint
94
+ bun run typecheck && bun run lint
95
+ ```
96
+
97
+ `site/` holds the GitHub Pages site: templates rendered once per language from `site/i18n/<lang>.json` and `site/content/<lang>/` (add a language by adding both). The dev server also serves `examples/host/` (a host page, a proxy-mode page, phone frames) and a fake LLM at `/mock/v1`.
98
+
99
+ ## Credits
100
+
101
+ [llm-connect and llm-models](https://github.com/maxgfr/llm-models), [Vercel AI SDK](https://ai-sdk.dev), [MiniSearch], [linkedom](https://github.com/WebReflection/linkedom), [Sofia Sans](https://github.com/lettersoup/Sofia-Sans) (OFL). Sibling of [ephemeral](https://github.com/maxgfr/ephemeral).
102
+
103
+ ## License
104
+
105
+ MIT
106
+
107
+ [MiniSearch]: https://github.com/lucaong/minisearch
@@ -0,0 +1,2 @@
1
+ import{oe,jt,Be,ft,ht}from"./embed-hn0r8fmg.js";import{Xe}from"./embed-59r4jck6.js";import{v,b,A,Ze,u,e,r,c,w,Re,o,t,B,l,f,ce,y,_n,a,n,F,S,I,d,ie,q,T,ve,le,xe,ot,Le,L,z,de,C,P,ze,j,he,pe,H,ke,it,ge,Q,i,s,x,N,h,g,ne,re,k,_,O,V,E,D,p,_e,M,dt,Y,Ke}from"./embed-sgjh2kg2.js";var Io=i(()=>s(t({type:n("error"),error:t({type:e(),message:e()})}))),ct=E({errorSchema:Io,errorToMessage:(m)=>m.error.message}),Ao=i(()=>s(t({id:e(),type:n("file"),filename:e(),mime_type:e(),size_bytes:r(),created_at:e(),downloadable:c().nullish()}))),Ro=class{get provider(){return this.config.provider}constructor(m){this.config=m,this.specificationVersion="v4"}async uploadFile({data:m,mediaType:R,filename:U,abortSignal:X,headers:me}){let Ne=ve(m),W=new Blob([Ne],{type:R}),ae=new FormData;if(U!=null)ae.append("file",W,U);else ae.append("file",W);let{value:se}=await ne({url:`${this.config.baseURL}/files`,headers:d(await _(this.config.headers),{"anthropic-beta":"files-api-2025-04-14"},me),formData:ae,failedResponseHandler:ct,successfulResponseHandler:p(Ao),abortSignal:X,fetch:this.config.fetch});return{warnings:[],providerReference:{anthropic:se.id},mediaType:se.mime_type??R,filename:se.filename??U,providerMetadata:{anthropic:{filename:se.filename,mimeType:se.mime_type,sizeBytes:se.size_bytes,createdAt:se.created_at,...se.downloadable!=null?{downloadable:se.downloadable}:{}}}}}};function Et(m,R){if(m.type==="web_search_result_location"||m.type==="search_result_location"){let X=m.type==="web_search_result_location"?m.url:m.source;return{source:{type:"source",sourceType:"url",id:X,url:X,title:m.title??void 0,providerMetadata:{anthropic:{...m}}},citedText:m.cited_text}}let U=R[m.document_index];return{source:{type:"source",sourceType:"document",id:m.file_id??String(m.document_index),mediaType:U?.mediaType??"text/plain",title:m.document_title??U?.title??`Document ${m.document_index}`,filename:U?.filename,providerMetadata:{anthropic:{...m}}},citedText:m.cited_text}}var $t=()=>t({type:n("fallback"),from:t({model:e()}),to:t({model:e()})}),Bo=i(()=>s($t())),ao=()=>t({type:e(),category:e().nullish(),explanation:e().nullish(),recommended_model:e().nullish()}),io=()=>t({type:e(),status:t({type:e(),tool_uses:y(e(),t({type:e(),outcome:e().nullish(),explanation:e().nullish()})).nullish()})}),ut=()=>l([t({type:n("code_execution_20250825"),tool_id:e()}),t({type:n("code_execution_20260120"),tool_id:e()}),t({type:n("direct")})]),so=()=>f("type",[t({type:n("web_search_result_location"),cited_text:e(),url:e(),title:e().nullable(),encrypted_index:e()}),t({type:n("page_location"),cited_text:e(),document_index:r(),document_title:e().nullable(),start_page_number:r(),end_page_number:r(),file_id:e().nullish()}),t({type:n("char_location"),cited_text:e(),document_index:r(),document_title:e().nullable(),start_char_index:r(),end_char_index:r(),file_id:e().nullish()}),t({type:n("content_block_location"),cited_text:e(),document_index:r(),document_title:e().nullable(),start_block_index:r(),end_block_index:r(),file_id:e().nullable()}),t({type:n("search_result_location"),cited_text:e(),search_result_index:r(),source:e(),title:e().nullable(),start_block_index:r(),end_block_index:r()})]),lo=()=>l([e(),o(l([e(),t({type:n("text"),text:e(),citations:o(F()).nullable().optional()})]))]),Mt=()=>t({type:e(),path:e(),reason:e()}),St=i(()=>s(t({type:n("message"),id:e().nullish(),model:e().nullish(),content:o(f("type",[t({type:n("text"),text:e(),citations:o(so()).nullable().optional()}),t({type:n("thinking"),thinking:e(),signature:e()}),t({type:n("redacted_thinking"),data:e()}),t({type:n("compaction"),content:e().nullish(),signature:e().nullish()}),t({type:n("tool_use"),id:e(),name:e(),input:w(),caller:ut().optional(),toolset_name:e().nullish()}),t({type:n("server_tool_use"),id:e(),name:e(),input:y(e(),w()).nullish(),caller:ut().optional()}),t({type:n("mcp_tool_use"),id:e(),name:e(),input:w(),server_name:e()}),t({type:n("mcp_tool_result"),tool_use_id:e(),is_error:c(),content:lo()}),t({type:n("web_fetch_tool_result"),tool_use_id:e(),caller:ut().optional(),content:l([t({type:n("web_fetch_result"),url:e(),retrieved_at:e().nullable(),content:t({type:n("document"),title:e().nullable(),citations:t({enabled:c()}).optional(),source:l([t({type:n("base64"),media_type:n("application/pdf"),data:e()}),t({type:n("text"),media_type:n("text/plain"),data:e()})])})}),t({type:n("web_fetch_tool_result_error"),error_code:e()})])}),t({type:n("web_search_tool_result"),tool_use_id:e(),caller:ut().optional(),content:l([o(t({type:n("web_search_result"),url:e(),title:e().nullable(),encrypted_content:e(),page_age:e().nullish()})),t({type:n("web_search_tool_result_error"),error_code:e()})])}),t({type:n("code_execution_tool_result"),tool_use_id:e(),content:l([t({type:n("code_execution_result"),stdout:e(),stderr:e(),return_code:r(),content:o(t({type:n("code_execution_output"),file_id:e()})).optional().default([])}),t({type:n("encrypted_code_execution_result"),encrypted_stdout:e(),stderr:e(),return_code:r(),content:o(t({type:n("code_execution_output"),file_id:e()})).optional().default([])}),t({type:n("code_execution_tool_result_error"),error_code:e()})])}),t({type:n("bash_code_execution_tool_result"),tool_use_id:e(),content:f("type",[t({type:n("bash_code_execution_result"),content:o(t({type:n("bash_code_execution_output"),file_id:e()})),stdout:e(),stderr:e(),return_code:r()}),t({type:n("bash_code_execution_tool_result_error"),error_code:e()})])}),t({type:n("text_editor_code_execution_tool_result"),tool_use_id:e(),content:f("type",[t({type:n("text_editor_code_execution_tool_result_error"),error_code:e()}),t({type:n("text_editor_code_execution_view_result"),content:e(),file_type:e(),num_lines:r().nullable(),start_line:r().nullable(),total_lines:r().nullable()}),t({type:n("text_editor_code_execution_create_result"),is_file_update:c()}),t({type:n("text_editor_code_execution_str_replace_result"),lines:o(e()).nullable(),new_lines:r().nullable(),new_start:r().nullable(),old_lines:r().nullable(),old_start:r().nullable()})])}),t({type:n("tool_search_tool_result"),tool_use_id:e(),content:l([t({type:n("tool_search_tool_search_result"),tool_references:o(t({type:n("tool_reference"),tool_name:e()}))}),t({type:n("tool_search_tool_result_error"),error_code:e()})])}),t({type:n("container_upload"),file_id:e()}),t({type:n("advisor_tool_result"),tool_use_id:e(),content:f("type",[t({type:n("advisor_result"),text:e(),stop_reason:e().nullish()}),t({type:n("advisor_redacted_result"),encrypted_content:e(),stop_reason:e().nullish()}),t({type:n("advisor_tool_result_error"),error_code:e()})])}),$t()])),stop_reason:e().nullish(),stop_sequence:e().nullish(),stop_details:ao().nullish(),input_transformations:o(Mt()).nullish(),safeguard_results:o(io()).nullish(),usage:B({input_tokens:r(),output_tokens:r(),output_tokens_details:t({thinking_tokens:r().nullish()}).nullish(),cache_creation_input_tokens:r().nullish(),cache_read_input_tokens:r().nullish(),iterations:o(t({type:l([n("compaction"),n("message"),n("advisor_message"),n("fallback_message")]),model:e().nullish(),input_tokens:r(),output_tokens:r(),cache_creation_input_tokens:r().nullish(),cache_read_input_tokens:r().nullish()})).nullish()}),container:t({expires_at:e(),id:e(),skills:o(t({type:l([n("anthropic"),n("custom")]),skill_id:e(),version:e()})).nullish()}).nullish(),context_management:t({applied_edits:o(l([t({type:n("clear_tool_uses_20250919"),cleared_tool_uses:r(),cleared_input_tokens:r()}),t({type:n("clear_thinking_20251015"),cleared_thinking_turns:r(),cleared_input_tokens:r()}),t({type:n("compact_20260112")})]))}).nullish()}))),Eo=i(()=>s(f("type",[t({type:n("message_start"),message:t({id:e().nullish(),model:e().nullish(),role:e().nullish(),usage:B({input_tokens:r(),cache_creation_input_tokens:r().nullish(),cache_read_input_tokens:r().nullish()}),content:o(f("type",[t({type:n("tool_use"),id:e(),name:e(),input:w(),caller:ut().optional(),toolset_name:e().nullish()})])).nullish(),stop_reason:e().nullish(),input_transformations:o(Mt()).nullish(),container:t({expires_at:e(),id:e()}).nullish()})}),t({type:n("content_block_start"),index:r(),content_block:f("type",[t({type:n("text"),text:e()}),t({type:n("thinking"),thinking:e()}),t({type:n("tool_use"),id:e(),name:e(),input:y(e(),w()).optional(),caller:ut().optional(),toolset_name:e().nullish()}),t({type:n("redacted_thinking"),data:e()}),t({type:n("compaction"),content:e().nullish(),signature:e().nullish()}),t({type:n("server_tool_use"),id:e(),name:e(),input:y(e(),w()).nullish(),caller:ut().optional()}),t({type:n("mcp_tool_use"),id:e(),name:e(),input:w(),server_name:e()}),t({type:n("mcp_tool_result"),tool_use_id:e(),is_error:c(),content:lo()}),t({type:n("web_fetch_tool_result"),tool_use_id:e(),caller:ut().optional(),content:l([t({type:n("web_fetch_result"),url:e(),retrieved_at:e().nullable(),content:t({type:n("document"),title:e().nullable(),citations:t({enabled:c()}).optional(),source:l([t({type:n("base64"),media_type:n("application/pdf"),data:e()}),t({type:n("text"),media_type:n("text/plain"),data:e()})])})}),t({type:n("web_fetch_tool_result_error"),error_code:e()})])}),t({type:n("web_search_tool_result"),tool_use_id:e(),caller:ut().optional(),content:l([o(t({type:n("web_search_result"),url:e(),title:e().nullable(),encrypted_content:e(),page_age:e().nullish()})),t({type:n("web_search_tool_result_error"),error_code:e()})])}),t({type:n("code_execution_tool_result"),tool_use_id:e(),content:l([t({type:n("code_execution_result"),stdout:e(),stderr:e(),return_code:r(),content:o(t({type:n("code_execution_output"),file_id:e()})).optional().default([])}),t({type:n("encrypted_code_execution_result"),encrypted_stdout:e(),stderr:e(),return_code:r(),content:o(t({type:n("code_execution_output"),file_id:e()})).optional().default([])}),t({type:n("code_execution_tool_result_error"),error_code:e()})])}),t({type:n("bash_code_execution_tool_result"),tool_use_id:e(),content:f("type",[t({type:n("bash_code_execution_result"),content:o(t({type:n("bash_code_execution_output"),file_id:e()})),stdout:e(),stderr:e(),return_code:r()}),t({type:n("bash_code_execution_tool_result_error"),error_code:e()})])}),t({type:n("text_editor_code_execution_tool_result"),tool_use_id:e(),content:f("type",[t({type:n("text_editor_code_execution_tool_result_error"),error_code:e()}),t({type:n("text_editor_code_execution_view_result"),content:e(),file_type:e(),num_lines:r().nullable(),start_line:r().nullable(),total_lines:r().nullable()}),t({type:n("text_editor_code_execution_create_result"),is_file_update:c()}),t({type:n("text_editor_code_execution_str_replace_result"),lines:o(e()).nullable(),new_lines:r().nullable(),new_start:r().nullable(),old_lines:r().nullable(),old_start:r().nullable()})])}),t({type:n("tool_search_tool_result"),tool_use_id:e(),content:l([t({type:n("tool_search_tool_search_result"),tool_references:o(t({type:n("tool_reference"),tool_name:e()}))}),t({type:n("tool_search_tool_result_error"),error_code:e()})])}),t({type:n("advisor_tool_result"),tool_use_id:e(),content:f("type",[t({type:n("advisor_result"),text:e(),stop_reason:e().nullish()}),t({type:n("advisor_redacted_result"),encrypted_content:e(),stop_reason:e().nullish()}),t({type:n("advisor_tool_result_error"),error_code:e()})])}),$t()])}),t({type:n("content_block_delta"),index:r(),delta:f("type",[t({type:n("input_json_delta"),partial_json:e()}),t({type:n("text_delta"),text:e()}),t({type:n("thinking_delta"),thinking:e()}),t({type:n("signature_delta"),signature:e()}),t({type:n("compaction_delta"),content:e().nullish()}),t({type:n("citations_delta"),citation:so()})])}),t({type:n("content_block_stop"),index:r()}),t({type:n("error"),error:t({type:e(),message:e(),code:l([e(),r()]).nullish(),statusCode:r().nullish(),isRetryable:c().nullish(),data:w().nullish()})}),t({type:n("message_delta"),delta:t({stop_reason:e().nullish(),stop_sequence:e().nullish(),stop_details:ao().nullish(),safeguard_results:o(io()).nullish(),container:t({expires_at:e(),id:e(),skills:o(t({type:l([n("anthropic"),n("custom")]),skill_id:e(),version:e()})).nullish()}).nullish()}),usage:B({input_tokens:r().nullish(),output_tokens:r(),output_tokens_details:t({thinking_tokens:r().nullish()}).nullish(),cache_creation_input_tokens:r().nullish(),cache_read_input_tokens:r().nullish(),iterations:o(t({type:l([n("compaction"),n("message"),n("advisor_message"),n("fallback_message")]),model:e().nullish(),input_tokens:r(),output_tokens:r(),cache_creation_input_tokens:r().nullish(),cache_read_input_tokens:r().nullish()})).nullish()}),input_transformations:o(Mt()).nullish(),context_management:t({applied_edits:o(l([t({type:n("clear_tool_uses_20250919"),cleared_tool_uses:r(),cleared_input_tokens:r()}),t({type:n("clear_thinking_20251015"),cleared_thinking_turns:r(),cleared_input_tokens:r()}),t({type:n("compact_20260112")})]))}).nullish()}),t({type:n("message_stop")}),t({type:n("ping")})]))),Mo=i(()=>s(t({signature:e().optional(),redactedData:e().optional()}))),At=i(()=>s(t({containerUpload:c().optional(),citations:t({enabled:c()}).optional(),title:e().optional(),context:e().optional()}))),Uo=i(()=>s(t({clearAt:n("next_user_message").optional(),effort:a(["low","medium","high","xhigh","max"]).optional(),toolChanges:o(f("type",[t({type:n("tool_addition"),toolName:e()}),t({type:n("tool_removal"),toolName:e()})])).optional()}))),Jt=i(()=>s(t({sendReasoning:c().optional(),structuredOutputMode:a(["outputFormat","jsonTool","auto"]).optional(),thinking:l([f("type",[t({type:n("adaptive"),display:a(["omitted","summarized","updates"]).optional(),blockBinding:t({prefixMismatchBehavior:a(["error","drop_block"])}).optional()}),t({type:n("enabled"),budgetTokens:r().optional()}),t({type:n("disabled")}),t({type:n("between_tools")})]),t({type:Re().optional(),blockBinding:t({prefixMismatchBehavior:a(["error","drop_block"])})})]).optional(),disableParallelToolUse:c().optional(),cacheControl:t({type:n("ephemeral"),ttl:l([n("5m"),n("1h")]).optional()}).optional(),metadata:t({userId:e().optional()}).optional(),mcpServers:o(t({type:n("url"),name:e(),url:e(),authorizationToken:e().nullish(),toolConfiguration:t({enabled:c().nullish(),allowedTools:o(e()).nullish()}).nullish()})).optional(),container:t({id:e().optional(),skills:o(f("type",[t({type:n("anthropic"),skillId:e(),version:e().optional()}),t({type:n("custom"),providerReference:y(e(),e()),version:e().optional()})])).optional()}).optional(),toolStreaming:c().optional(),effort:a(["low","medium","high","xhigh","max"]).optional(),taskBudget:t({type:n("tokens"),total:r().int().min(20000),remaining:r().int().min(0).optional()}).optional(),speed:a(["fast","standard"]).optional(),serviceTier:a(["auto","standard_only"]).optional(),inferenceGeo:a(["us","global"]).optional(),fallbacks:l([n("default"),o(t({model:e(),max_tokens:r().int().optional(),thinking:y(e(),w()).optional(),output_config:y(e(),w()).optional(),speed:a(["fast","standard"]).optional()}))]).optional(),anthropicBeta:o(e()).optional(),safeguards:o(t({type:n("dangerous_tool_use"),classifierContext:y(e(),w()).optional()})).optional(),compaction:t({type:n("summarize"),instructions:e().optional()}).optional(),contextManagement:t({edits:o(f("type",[t({type:n("clear_tool_uses_20250919"),trigger:f("type",[t({type:n("input_tokens"),value:r()}),t({type:n("tool_uses"),value:r()})]).optional(),keep:t({type:n("tool_uses"),value:r()}).optional(),clearAtLeast:t({type:n("input_tokens"),value:r()}).optional(),clearToolInputs:c().optional(),excludeTools:o(e()).optional()}),t({type:n("clear_thinking_20251015"),keep:l([n("all"),t({type:n("thinking_turns"),value:r()})]).optional()}),t({type:n("compact_20260112"),trigger:t({type:n("input_tokens"),value:r()}).optional(),pauseAfterCompaction:c().optional(),instructions:e().optional()})]))}).optional()}))),Kt=4;function $o(m,R){let U=m?.[R],X=m?.anthropic;return U?.cacheControl??U?.cache_control??X?.cacheControl??X?.cache_control}var qt=class{constructor(m="anthropic"){this.providerOptionsName=m,this.breakpointCount=0,this.warnings=[]}getCacheControl(m,R){let U=$o(m,this.providerOptionsName);if(!U)return;if(!R.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${R.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>Kt){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${Kt} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return U}getWarnings(){return this.warnings}},qo=i(()=>s(t({model:e(),maxUses:r().optional(),maxTokens:r().int().min(1024).optional(),caching:t({type:n("ephemeral"),ttl:l([n("5m"),n("1h")])}).optional()}))),co=i(()=>s(f("type",[t({type:n("advisor_result"),text:e(),stopReason:e().optional()}),t({type:n("advisor_redacted_result"),encryptedContent:e(),stopReason:e().optional()}),t({type:n("advisor_tool_result_error"),errorCode:e()})]))),Do=i(()=>s(t({}).strict())),Ho=k({id:"anthropic.advisor_20260301",inputSchema:Do,outputSchema:co,supportsDeferredResults:!0}),Po=(m)=>Ho(m),uo=["screenshot","zoom","left_click","right_click","middle_click","double_click","triple_click","left_click_drag","mouse_move","left_mouse_down","left_mouse_up","cursor_position","scroll","type","key","hold_key","wait"],Lo=i(()=>s(t({action:a(uo),coordinate:ce([r().int(),r().int()]).optional(),duration:r().optional(),region:ce([r().int(),r().int(),r().int(),r().int()]).optional(),repeat:r().int().optional(),scroll_amount:r().optional(),scroll_direction:a(["up","down","left","right"]).optional(),start_coordinate:ce([r().int(),r().int()]).optional(),text:e().optional()}))),Fo=i(()=>s(t({configs:_n(a(uo),t({enabled:c().optional(),deferLoading:c().optional()})).optional()}))),Jo=re({id:"anthropic.computer_toolset_20260801",inputSchema:Lo}),Ko=i(()=>s(t({maxCharacters:r().optional()}))),zo=i(()=>s(t({command:a(["view","create","str_replace","insert"]),path:e(),file_text:e().optional(),insert_line:r().int().optional(),new_str:e().optional(),insert_text:e().optional(),old_str:e().optional(),view_range:o(r().int()).optional()}))),Wo=re({id:"anthropic.text_editor_20250728",inputSchema:zo}),Vo=(m={})=>Wo(m),Xo=i(()=>s(t({maxUses:r().optional(),allowedDomains:o(e()).optional(),blockedDomains:o(e()).optional(),userLocation:t({type:n("approximate"),city:e().optional(),region:e().optional(),country:e().optional(),timezone:e().optional()}).optional(),responseInclusion:a(["full","excluded"]).optional()}))),Go=i(()=>s(o(t({url:e(),title:e().nullable(),pageAge:e().nullable(),encryptedContent:e(),type:n("web_search_result")})))),Zo=i(()=>s(t({query:e()}))),Yo=k({id:"anthropic.web_search_20260318",inputSchema:Zo,outputSchema:Go,supportsDeferredResults:!0}),Qo=(m={})=>Yo(m),en=i(()=>s(t({maxUses:r().optional(),allowedDomains:o(e()).optional(),blockedDomains:o(e()).optional(),userLocation:t({type:n("approximate"),city:e().optional(),region:e().optional(),country:e().optional(),timezone:e().optional()}).optional()}))),tn=i(()=>s(o(t({url:e(),title:e().nullable(),pageAge:e().nullable(),encryptedContent:e(),type:n("web_search_result")})))),on=i(()=>s(t({query:e()}))),nn=k({id:"anthropic.web_search_20260209",inputSchema:on,outputSchema:tn,supportsDeferredResults:!0}),rn=(m={})=>nn(m),an=i(()=>s(t({maxUses:r().optional(),allowedDomains:o(e()).optional(),blockedDomains:o(e()).optional(),userLocation:t({type:n("approximate"),city:e().optional(),region:e().optional(),country:e().optional(),timezone:e().optional()}).optional()}))),po=i(()=>s(o(t({url:e(),title:e().nullable(),pageAge:e().nullable(),encryptedContent:e(),type:n("web_search_result")})))),sn=i(()=>s(t({query:e()}))),ln=k({id:"anthropic.web_search_20250305",inputSchema:sn,outputSchema:po,supportsDeferredResults:!0}),cn=(m={})=>ln(m),un=i(()=>s(t({maxUses:r().optional(),allowedDomains:o(e()).optional(),blockedDomains:o(e()).optional(),citations:t({enabled:c()}).optional(),maxContentTokens:r().optional(),useCache:c().optional(),responseInclusion:a(["full","excluded"]).optional()}))),pn=i(()=>s(t({type:n("web_fetch_result"),url:e(),content:t({type:n("document"),title:e().nullable(),citations:t({enabled:c()}).optional(),source:l([t({type:n("base64"),mediaType:n("application/pdf"),data:e()}),t({type:n("text"),mediaType:n("text/plain"),data:e()})])}),retrievedAt:e().nullable()}))),dn=i(()=>s(t({url:e()}))),hn=k({id:"anthropic.web_fetch_20260318",inputSchema:dn,outputSchema:pn,supportsDeferredResults:!0}),mn=(m={})=>hn(m),gn=i(()=>s(t({maxUses:r().optional(),allowedDomains:o(e()).optional(),blockedDomains:o(e()).optional(),citations:t({enabled:c()}).optional(),maxContentTokens:r().optional()}))),fn=i(()=>s(t({type:n("web_fetch_result"),url:e(),content:t({type:n("document"),title:e().nullable(),citations:t({enabled:c()}).optional(),source:l([t({type:n("base64"),mediaType:n("application/pdf"),data:e()}),t({type:n("text"),mediaType:n("text/plain"),data:e()})])}),retrievedAt:e().nullable()}))),yn=i(()=>s(t({url:e()}))),bn=k({id:"anthropic.web_fetch_20260209",inputSchema:yn,outputSchema:fn,supportsDeferredResults:!0}),xn=(m={})=>bn(m),vn=i(()=>s(t({maxUses:r().optional(),allowedDomains:o(e()).optional(),blockedDomains:o(e()).optional(),citations:t({enabled:c()}).optional(),maxContentTokens:r().optional()}))),_o=i(()=>s(t({type:n("web_fetch_result"),url:e(),content:t({type:n("document"),title:e().nullable(),citations:t({enabled:c()}).optional(),source:l([t({type:n("base64"),mediaType:n("application/pdf"),data:e()}),t({type:n("text"),mediaType:n("text/plain"),data:e()})])}),retrievedAt:e().nullable()}))),kn=i(()=>s(t({url:e()}))),wn=k({id:"anthropic.web_fetch_20250910",inputSchema:kn,outputSchema:_o,supportsDeferredResults:!0}),jn=(m={})=>wn(m);async function Tn({tools:m,toolChoice:R,disableParallelToolUse:U,cacheControlValidator:X,supportsStructuredOutput:me,supportsStrictTools:Ne,defaultEagerInputStreaming:W=!1,rejectsForcedToolUse:ae=!1}){m=m?.length?m:void 0;let se=[],fe=new Set,$e=X||new qt;if(m==null)return{tools:void 0,toolChoice:void 0,toolWarnings:se,betas:fe};let Se=[];for(let we of m)switch(we.type){case"function":{let je=$e.getCacheControl(we.providerOptions,{type:"tool definition",canCache:!0}),Me=we.providerOptions?.anthropic,Ve=Me?.eagerInputStreaming??W,Fe=Me?.deferLoading,Pe=Me?.allowedCallers;if(!Ne&&we.strict===!0)se.push({type:"unsupported",feature:"strict",details:`Tool '${we.name}' has strict: ${we.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`});if(Se.push({name:we.name,description:we.description,input_schema:we.inputSchema,cache_control:je,...Ve?{eager_input_streaming:!0}:{},...Ne===!0&&we.strict!=null?{strict:we.strict}:{},...Fe!=null?{defer_loading:Fe}:{},...Pe!=null?{allowed_callers:Pe}:{},...we.inputExamples!=null?{input_examples:we.inputExamples.map((Ae)=>Ae.input)}:{}}),me===!0)fe.add("structured-outputs-2025-11-13");if(we.inputExamples!=null||Pe!=null)fe.add("advanced-tool-use-2025-11-20");break}case"provider":switch(we.id){case"anthropic.code_execution_20250522":fe.add("code-execution-2025-05-22"),Se.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break;case"anthropic.code_execution_20250825":fe.add("code-execution-2025-08-25"),Se.push({type:"code_execution_20250825",name:"code_execution"});break;case"anthropic.code_execution_20260120":Se.push({type:"code_execution_20260120",name:"code_execution"});break;case"anthropic.computer_20250124":fe.add("computer-use-2025-01-24"),Se.push({name:"computer",type:"computer_20250124",display_width_px:we.args.displayWidthPx,display_height_px:we.args.displayHeightPx,display_number:we.args.displayNumber,cache_control:void 0});break;case"anthropic.computer_20251124":fe.add("computer-use-2025-11-24"),Se.push({name:"computer",type:"computer_20251124",display_width_px:we.args.displayWidthPx,display_height_px:we.args.displayHeightPx,display_number:we.args.displayNumber,enable_zoom:we.args.enableZoom,cache_control:void 0});break;case"anthropic.computer_toolset_20260801":{let je=await x({value:we.args,schema:Fo}),Me=je.configs!=null?Object.fromEntries(Object.entries(je.configs).map(([Ve,Fe])=>[Ve,{...Fe?.enabled!=null&&{enabled:Fe.enabled},...Fe?.deferLoading!=null&&{defer_loading:Fe.deferLoading}}])):void 0;Se.push({type:"computer_toolset_20260801",...Me!=null&&{configs:Me},cache_control:void 0});break}case"anthropic.computer_20241022":fe.add("computer-use-2024-10-22"),Se.push({name:"computer",type:"computer_20241022",display_width_px:we.args.displayWidthPx,display_height_px:we.args.displayHeightPx,display_number:we.args.displayNumber,cache_control:void 0});break;case"anthropic.text_editor_20250124":fe.add("computer-use-2025-01-24"),Se.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break;case"anthropic.text_editor_20241022":fe.add("computer-use-2024-10-22"),Se.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break;case"anthropic.text_editor_20250429":fe.add("computer-use-2025-01-24"),Se.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break;case"anthropic.text_editor_20250728":{let je=await x({value:we.args,schema:Ko});Se.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:je.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":fe.add("computer-use-2025-01-24"),Se.push({name:"bash",type:"bash_20250124",cache_control:void 0});break;case"anthropic.bash_20241022":fe.add("computer-use-2024-10-22"),Se.push({name:"bash",type:"bash_20241022",cache_control:void 0});break;case"anthropic.memory_20250818":fe.add("context-management-2025-06-27"),Se.push({name:"memory",type:"memory_20250818"});break;case"anthropic.web_fetch_20250910":{fe.add("web-fetch-2025-09-10");let je=await x({value:we.args,schema:vn});Se.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:je.maxUses,allowed_domains:je.allowedDomains,blocked_domains:je.blockedDomains,citations:je.citations,max_content_tokens:je.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260209":{fe.add("code-execution-web-tools-2026-02-09");let je=await x({value:we.args,schema:gn});Se.push({type:"web_fetch_20260209",name:"web_fetch",max_uses:je.maxUses,allowed_domains:je.allowedDomains,blocked_domains:je.blockedDomains,citations:je.citations,max_content_tokens:je.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260318":{let je=await x({value:we.args,schema:un});Se.push({type:"web_fetch_20260318",name:"web_fetch",max_uses:je.maxUses,allowed_domains:je.allowedDomains,blocked_domains:je.blockedDomains,citations:je.citations,max_content_tokens:je.maxContentTokens,use_cache:je.useCache,response_inclusion:je.responseInclusion,cache_control:void 0});break}case"anthropic.web_search_20250305":{let je=await x({value:we.args,schema:an});Se.push({type:"web_search_20250305",name:"web_search",max_uses:je.maxUses,allowed_domains:je.allowedDomains,blocked_domains:je.blockedDomains,user_location:je.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260209":{fe.add("code-execution-web-tools-2026-02-09");let je=await x({value:we.args,schema:en});Se.push({type:"web_search_20260209",name:"web_search",max_uses:je.maxUses,allowed_domains:je.allowedDomains,blocked_domains:je.blockedDomains,user_location:je.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260318":{let je=await x({value:we.args,schema:Xo});Se.push({type:"web_search_20260318",name:"web_search",max_uses:je.maxUses,allowed_domains:je.allowedDomains,blocked_domains:je.blockedDomains,user_location:je.userLocation,response_inclusion:je.responseInclusion,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":Se.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break;case"anthropic.tool_search_bm25_20251119":Se.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break;case"anthropic.advisor_20260301":{fe.add("advisor-tool-2026-03-01");let je=await x({value:we.args,schema:qo});Se.push({type:"advisor_20260301",name:"advisor",model:je.model,...je.maxUses!==void 0&&{max_uses:je.maxUses},...je.maxTokens!==void 0&&{max_tokens:je.maxTokens},...je.caching!==void 0&&{caching:je.caching}});break}default:se.push({type:"unsupported",feature:`provider-defined tool ${we.id}`})}break;default:se.push({type:"unsupported",feature:`tool ${we}`})}if(R==null)return{tools:Se,toolChoice:U?{type:"auto",disable_parallel_tool_use:U}:void 0,toolWarnings:se,betas:fe};let Ye=R.type;switch(Ye){case"auto":return{tools:Se,toolChoice:{type:"auto",disable_parallel_tool_use:U},toolWarnings:se,betas:fe};case"required":if(ae)return se.push({type:"unsupported",feature:"toolChoice",details:"toolChoice 'required' is not supported with this model or thinking configuration. Using 'auto' instead. Instruct the model to use a tool in the prompt and verify that a tool call was made."}),{tools:Se,toolChoice:{type:"auto",disable_parallel_tool_use:U},toolWarnings:se,betas:fe};return{tools:Se,toolChoice:{type:"any",disable_parallel_tool_use:U},toolWarnings:se,betas:fe};case"none":return{tools:Se,toolChoice:{type:"none"},toolWarnings:se,betas:fe};case"tool":if(ae)return se.push({type:"unsupported",feature:"toolChoice",details:`toolChoice 'tool' is not supported with this model or thinking configuration. Only the '${R.toolName}' tool is sent with 'auto' tool choice. Instruct the model to use the tool in the prompt and verify that a tool call was made.`}),{tools:Se.filter((we)=>("name"in we)&&we.name===R.toolName),toolChoice:{type:"auto",disable_parallel_tool_use:U},toolWarnings:se,betas:fe};return{tools:Se,toolChoice:{type:"tool",name:R.toolName,disable_parallel_tool_use:U},toolWarnings:se,betas:fe};default:throw new u({functionality:`tool choice type: ${Ye}`})}}function Ut({usage:m,rawUsage:R}){let U=m.cache_creation_input_tokens??0,X=m.cache_read_input_tokens??0,me=m.output_tokens_details?.thinking_tokens??void 0,Ne,W,ae=m.iterations?.some((se)=>se.type==="fallback_message");if(m.iterations&&m.iterations.length>0&&!ae){let se=m.iterations.filter((fe)=>fe.type==="compaction"||fe.type==="message");if(se.length>0){let fe=se.reduce(($e,Se)=>({input:$e.input+Se.input_tokens,output:$e.output+Se.output_tokens}),{input:0,output:0});Ne=fe.input,W=fe.output}else Ne=m.input_tokens,W=m.output_tokens}else Ne=m.input_tokens,W=m.output_tokens;return{inputTokens:{total:Ne+U+X,noCache:Ne,cacheRead:X,cacheWrite:U},outputTokens:{total:W,text:me==null?void 0:W-me,reasoning:me},raw:R??m}}var ho=i(()=>s(t({type:n("code_execution_result"),stdout:e(),stderr:e(),return_code:r(),content:o(t({type:n("code_execution_output"),file_id:e()})).optional().default([])}))),Cn=i(()=>s(t({code:e()}))),Sn=k({id:"anthropic.code_execution_20250522",inputSchema:Cn,outputSchema:ho}),Nn=(m={})=>Sn(m),mo=i(()=>s(f("type",[t({type:n("code_execution_result"),stdout:e(),stderr:e(),return_code:r(),content:o(t({type:n("code_execution_output"),file_id:e()})).optional().default([])}),t({type:n("bash_code_execution_result"),content:o(t({type:n("bash_code_execution_output"),file_id:e()})),stdout:e(),stderr:e(),return_code:r()}),t({type:n("bash_code_execution_tool_result_error"),error_code:e()}),t({type:n("text_editor_code_execution_tool_result_error"),error_code:e()}),t({type:n("text_editor_code_execution_view_result"),content:e(),file_type:e(),num_lines:r().nullable(),start_line:r().nullable(),total_lines:r().nullable()}),t({type:n("text_editor_code_execution_create_result"),is_file_update:c()}),t({type:n("text_editor_code_execution_str_replace_result"),lines:o(e()).nullable(),new_lines:r().nullable(),new_start:r().nullable(),old_lines:r().nullable(),old_start:r().nullable()})]))),On=i(()=>s(f("type",[t({type:n("programmatic-tool-call"),code:e()}),t({type:n("bash_code_execution"),command:e()}),f("command",[t({type:n("text_editor_code_execution"),command:n("view"),path:e()}),t({type:n("text_editor_code_execution"),command:n("create"),path:e(),file_text:e().nullish()}),t({type:n("text_editor_code_execution"),command:n("str_replace"),path:e(),old_str:e(),new_str:e()})])]))),In=k({id:"anthropic.code_execution_20250825",inputSchema:On,outputSchema:mo,supportsDeferredResults:!0}),An=(m={})=>Ke(In(m),{type:"provider",prepareProviderOptions:(R)=>{let U=R?.anthropic;return{...R,anthropic:{...U,allowedCallers:[...new Set([...U?.allowedCallers??[],"code_execution_20250825"])]}}}}),go=i(()=>s(f("type",[t({type:n("code_execution_result"),stdout:e(),stderr:e(),return_code:r(),content:o(t({type:n("code_execution_output"),file_id:e()})).optional().default([])}),t({type:n("encrypted_code_execution_result"),encrypted_stdout:e(),stderr:e(),return_code:r(),content:o(t({type:n("code_execution_output"),file_id:e()})).optional().default([])}),t({type:n("bash_code_execution_result"),content:o(t({type:n("bash_code_execution_output"),file_id:e()})),stdout:e(),stderr:e(),return_code:r()}),t({type:n("bash_code_execution_tool_result_error"),error_code:e()}),t({type:n("text_editor_code_execution_tool_result_error"),error_code:e()}),t({type:n("text_editor_code_execution_view_result"),content:e(),file_type:e(),num_lines:r().nullable(),start_line:r().nullable(),total_lines:r().nullable()}),t({type:n("text_editor_code_execution_create_result"),is_file_update:c()}),t({type:n("text_editor_code_execution_str_replace_result"),lines:o(e()).nullable(),new_lines:r().nullable(),new_start:r().nullable(),old_lines:r().nullable(),old_start:r().nullable()})]))),Rn=i(()=>s(f("type",[t({type:n("programmatic-tool-call"),code:e()}),t({type:n("bash_code_execution"),command:e()}),f("command",[t({type:n("text_editor_code_execution"),command:n("view"),path:e()}),t({type:n("text_editor_code_execution"),command:n("create"),path:e(),file_text:e().nullish()}),t({type:n("text_editor_code_execution"),command:n("str_replace"),path:e(),old_str:e(),new_str:e()})])]))),Bn=k({id:"anthropic.code_execution_20260120",inputSchema:Rn,outputSchema:go,supportsDeferredResults:!0}),En=(m={})=>Ke(Bn(m),{type:"provider",prepareProviderOptions:(R)=>{let U=R?.anthropic;return{...R,anthropic:{...U,allowedCallers:[...new Set([...U?.allowedCallers??[],"code_execution_20260120"])]}}}}),fo=i(()=>s(o(t({type:n("tool_reference"),toolName:e()})))),Mn=i(()=>s(t({pattern:e(),limit:r().optional()}))),Un=k({id:"anthropic.tool_search_regex_20251119",inputSchema:Mn,outputSchema:fo,supportsDeferredResults:!0}),$n=(m={})=>Un(m);function qn(m){if(typeof m==="string")return new TextDecoder().decode(q(m));return new TextDecoder().decode(m)}function Rt(m){try{if(typeof m==="string")return Q(m);else if(typeof m==="object"&&m!==null)return m}catch{let R=m?.errorCode;return{errorCode:typeof R==="string"?R:"unavailable"}}return{}}async function Dn({prompt:m,sendReasoning:R,warnings:U,cacheControlValidator:X,toolNameMapping:me,toolsetNames:Ne={},convertMediaPart:W}){let ae=new Set,se=Hn(m),fe=X||new qt,$e=void 0,Se=[],Ye=-1;async function we(Pe){return(await h({provider:"anthropic",providerOptions:Pe,schema:At}))?.citations?.enabled??!1}async function je(Pe){return(await h({provider:"anthropic",providerOptions:Pe,schema:At}))?.containerUpload??!1}async function Me(Pe){let Ae=await h({provider:"anthropic",providerOptions:Pe,schema:At});return{title:Ae?.title,context:Ae?.context}}for(let Pe=0;Pe<se.length;Pe++){let Ae=se[Pe],K=Pe===se.length-1,Ee=Ae.type;switch(Ee){case"system":{let ye=[];for(let{content:De,providerOptions:G}of Ae.messages){let Ce=await h({provider:"anthropic",providerOptions:G,schema:Uo}),Ge=Ce?.toolChanges??[],Z=[];if(De!==""||Ge.length===0&&Ce?.clearAt==null&&Ce?.effort==null)Z.push({type:"text",text:De,cache_control:fe.getCacheControl(G,{type:"system message",canCache:!0})});for(let rt of Ge)Z.push({type:rt.type,tool:{type:"tool_reference",name:me.toProviderToolName(rt.toolName)}});ye.push({content:Z,clearAt:Ce?.clearAt,effort:Ce?.effort,toolChangeCount:Ge.length})}let He=ye.reduce((De,G)=>De+G.toolChangeCount,0),nt=ye.some((De)=>De.clearAt!=null||De.effort!=null);if(Pe===0||$e==null&&He===0&&!nt){if(He>0)U.push({type:"other",message:"tool changes on the initial system message are not supported by Anthropic. Configure the initial tool set via the tools option instead. The tool changes have been ignored."});for(let De of ye)if(De.content.length===0&&De.clearAt==null&&De.effort!=null)Se.push({role:"system",content:[],output_config:{effort:De.effort}}),ae.add("mid-conversation-output-config-2026-07-01");else if(De.clearAt!=null||De.effort!=null)U.push({type:"other",message:"clearAt and effort on this initial system message are not supported by Anthropic. Use a separate effort-only system message with empty content to set effort. These options have been ignored."});$e=ye.flatMap((De)=>De.content.filter((G)=>G.type==="text"))}else{ae.add("mid-conversation-system-2026-04-07");for(let De of ye){if(Se.push({role:"system",content:De.content,...De.clearAt!=null&&{clear_at:De.clearAt},...De.effort!=null&&{output_config:{effort:De.effort}}}),De.toolChangeCount>0)ae.add("mid-conversation-tool-changes-2026-07-01");if(De.clearAt!=null)ae.add("mid-conversation-system-clear-at-2026-08-21");if(De.effort!=null)ae.add("mid-conversation-output-config-2026-07-01")}}break}case"user":{let ye=[];for(let He of Ae.messages){let{role:nt,content:De}=He;switch(nt){case"user":if(De.length>0)Ye=Se.length;for(let G=0;G<De.length;G++){let Ce=De[G],Ge=G===De.length-1,Z=fe.getCacheControl(Ce.providerOptions,{type:"user message part",canCache:!0})??(Ge?fe.getCacheControl(He.providerOptions,{type:"user message",canCache:!0}):void 0);switch(Ce.type){case"text":ye.push({type:"text",text:Ce.text,cache_control:Z});break;case"file":{let rt=await W?.(Ce);if(rt!=null){ye.push({...rt,cache_control:Z});break}switch(Ce.data.type){case"reference":{let Ue=V({reference:Ce.data.reference,provider:"anthropic"});if(ae.add("files-api-2025-04-14"),await je(Ce.providerOptions))ye.push({type:"container_upload",file_id:Ue});else if(z(Ce.mediaType)==="image")ye.push({type:"image",source:{type:"file",file_id:Ue},cache_control:Z});else ye.push({type:"document",source:{type:"file",file_id:Ue},cache_control:Z});break}case"text":{let Ue=await we(Ce.providerOptions),Oe=await Me(Ce.providerOptions);ye.push({type:"document",source:{type:"text",media_type:"text/plain",data:Ce.data.text},title:Oe.title??Ce.filename,...Oe.context&&{context:Oe.context},...Ue&&{citations:{enabled:!0}},cache_control:Z});break}case"url":case"data":{let Ue=z(Ce.mediaType);if(Ue==="image")ye.push({type:"image",source:Ce.data.type==="url"?{type:"url",url:Ce.data.url.toString()}:{type:"base64",media_type:O({part:Ce}),data:T(Ce.data.data)},cache_control:Z});else if(Ue==="application"&&(Ce.data.type==="url"?Ce.mediaType==="application/pdf":O({part:Ce})==="application/pdf")){ae.add("pdfs-2024-09-25");let Oe=await we(Ce.providerOptions),We=await Me(Ce.providerOptions);ye.push({type:"document",source:Ce.data.type==="url"?{type:"url",url:Ce.data.url.toString()}:{type:"base64",media_type:"application/pdf",data:T(Ce.data.data)},title:We.title??Ce.filename,...We.context&&{context:We.context},...Oe&&{citations:{enabled:!0}},cache_control:Z})}else if(Ce.mediaType==="text/plain"){let Oe=await we(Ce.providerOptions),We=await Me(Ce.providerOptions);ye.push({type:"document",source:Ce.data.type==="url"?{type:"url",url:Ce.data.url.toString()}:{type:"text",media_type:"text/plain",data:qn(Ce.data.data)},title:We.title??Ce.filename,...We.context&&{context:We.context},...Oe&&{citations:{enabled:!0}},cache_control:Z})}else throw new u({functionality:`media type: ${Ce.mediaType}`});break}}break}}}break;case"tool":for(let G=0;G<De.length;G++){let Ce=De[G];if(Ce.type==="tool-approval-response")continue;let Ge=Ce.output,Z="providerOptions"in Ge?Ge.providerOptions:Ge.type==="content"?Ge.value.find((te)=>te.providerOptions!=null)?.providerOptions:void 0,rt=G===De.length-1,Ue=fe.getCacheControl(Ce.providerOptions,{type:"tool result part",canCache:!0})??fe.getCacheControl(Z,{type:"tool result output",canCache:!0})??(rt?fe.getCacheControl(He.providerOptions,{type:"tool result message",canCache:!0}):void 0),Oe;switch(Ge.type){case"content":Oe=Ge.value.map((te)=>{switch(te.type){case"text":return{type:"text",text:te.text};case"file":{let ue=z(te.mediaType);if(te.data.type==="reference"){let Qe=V({reference:te.data.reference,provider:"anthropic"});if(ae.add("files-api-2025-04-14"),ue==="image")return{type:"image",source:{type:"file",file_id:Qe}};return{type:"document",source:{type:"file",file_id:Qe}}}if(te.data.type==="url"){if(ue==="image")return{type:"image",source:{type:"url",url:te.data.url.toString()}};return{type:"document",source:{type:"url",url:te.data.url.toString()}}}if(te.data.type==="data"){if(ue==="image")return{type:"image",source:{type:"base64",media_type:O({part:te}),data:T(te.data.data)}};if(O({part:te})==="application/pdf")return ae.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:"application/pdf",data:T(te.data.data)}};U.push({type:"other",message:`unsupported tool content part type: ${te.type} with media type: ${te.mediaType}`});return}U.push({type:"other",message:`unsupported tool content part type: ${te.type} with data type: ${te.data.type}`});return}case"custom":{let ue=te.providerOptions?.anthropic;if(ue?.type==="tool-reference")return{type:"tool_reference",tool_name:ue.toolName};U.push({type:"other",message:"unsupported custom tool content part"});return}default:U.push({type:"other",message:`unsupported tool content part type: ${te.type}`});return}}).filter(ze);break;case"text":case"error-text":Oe=Ge.value;break;case"execution-denied":Oe=Ge.reason??"Tool call execution denied.";break;default:Oe=JSON.stringify(Ge.value)}let We=zt({toolName:Ce.toolName,providerOptions:Ce.providerOptions,toolsetNames:Ne});ye.push({type:"tool_result",tool_use_id:Ce.toolCallId,...We!=null&&{toolset_name:We},content:Oe,is_error:Ge.type==="error-text"||Ge.type==="error-json"?!0:void 0,cache_control:Ue})}break;default:throw Error(`Unsupported role: ${nt}`)}}Se.push({role:"user",content:ye});break}case"assistant":{let ye=[],He=new Set;for(let nt=0;nt<Ae.messages.length;nt++){let De=Ae.messages[nt],G=nt===Ae.messages.length-1,{content:Ce}=De;for(let Ge=0;Ge<Ce.length;Ge++){let Z=Ce[Ge],rt=Ge===Ce.length-1,Ue=fe.getCacheControl(Z.providerOptions,{type:"assistant message part",canCache:!0})??(rt?fe.getCacheControl(De.providerOptions,{type:"assistant message",canCache:!0}):void 0);switch(Z.type){case"text":{let Oe=Z.providerOptions?.anthropic;if(Oe?.type==="compaction"){if(Z.text==="")break;if(typeof Oe.signature==="string")ae.add("compact-2026-09-04");ye.push({type:"compaction",content:Z.text,...typeof Oe.signature==="string"&&{signature:Oe.signature},cache_control:Ue})}else ye.push({type:"text",text:K&&G&&rt?Z.text.trim():Z.text,...Oe?.citations!=null&&{citations:Oe.citations},cache_control:Ue});break}case"reasoning":if(R){let Oe=await h({provider:"anthropic",providerOptions:Z.providerOptions,schema:Mo});if(Oe!=null)if(Oe.signature!=null)fe.getCacheControl(Z.providerOptions,{type:"thinking block",canCache:!1}),ye.push({type:"thinking",thinking:Z.text,signature:Oe.signature});else if(Oe.redactedData!=null)fe.getCacheControl(Z.providerOptions,{type:"redacted thinking block",canCache:!1}),ye.push({type:"redacted_thinking",data:Oe.redactedData});else U.push({type:"other",message:"unsupported reasoning metadata"});else U.push({type:"other",message:"unsupported reasoning metadata"})}else U.push({type:"other",message:"sending reasoning content is disabled for this model"});break;case"custom":{if(Z.kind!=="anthropic.fallback")break;let Oe=await N({value:Z.providerOptions?.anthropic,schema:Bo});if(!Oe.success){U.push({type:"other",message:"anthropic fallback metadata must include from.model and to.model"});break}ae.add("server-side-fallback-2026-06-01"),ye.push({type:"fallback",from:Oe.value.from,to:Oe.value.to});break}case"tool-call":{let Oe=Wt(Z.providerOptions);if(Z.providerExecuted){let te=me.toProviderToolName(Z.toolName);if(Z.providerOptions?.anthropic?.type==="mcp-tool-use"){He.add(Z.toolCallId);let ue=Z.providerOptions?.anthropic?.serverName;if(ue==null||typeof ue!=="string"){U.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}ye.push({type:"mcp_tool_use",id:Z.toolCallId,name:Z.toolName,input:Z.input,server_name:ue,cache_control:Ue})}else if(te==="code_execution"&&Z.input!=null&&typeof Z.input==="object"&&"type"in Z.input&&typeof Z.input.type==="string"&&(Z.input.type==="bash_code_execution"||Z.input.type==="text_editor_code_execution")){let{type:ue,...Qe}=Z.input;ye.push({type:"server_tool_use",id:Z.toolCallId,name:ue,input:Qe,...Oe&&{caller:Oe},cache_control:Ue})}else if(te==="code_execution"&&Z.input!=null&&typeof Z.input==="object"&&"type"in Z.input&&Z.input.type==="programmatic-tool-call"){let{type:ue,...Qe}=Z.input;ye.push({type:"server_tool_use",id:Z.toolCallId,name:"code_execution",input:Qe,...Oe&&{caller:Oe},cache_control:Ue})}else if(te==="code_execution"||te==="web_fetch"||te==="web_search")ye.push({type:"server_tool_use",id:Z.toolCallId,name:te,input:Z.input,...Oe&&{caller:Oe},cache_control:Ue});else if(te==="tool_search_tool_regex"||te==="tool_search_tool_bm25")ye.push({type:"server_tool_use",id:Z.toolCallId,name:te,input:Z.input,...Oe&&{caller:Oe},cache_control:Ue});else if(te==="advisor")ye.push({type:"server_tool_use",id:Z.toolCallId,name:"advisor",input:{},...Oe&&{caller:Oe},cache_control:Ue});else U.push({type:"other",message:`provider executed tool call for tool ${Z.toolName} is not supported`});break}let We=zt({toolName:Z.toolName,providerOptions:Z.providerOptions,toolsetNames:Ne});if(We!=null){let te=Vt(Z.input),{action:ue}=te,Qe=typeof ue==="string";if(!Qe)U.push({type:"other",message:`toolset tool call for tool ${Z.toolName} is missing the action`});ye.push({type:"tool_use",id:Z.toolCallId,name:Qe?ue:We,toolset_name:We,input:te,...Oe&&{caller:Oe},cache_control:Ue});break}ye.push({type:"tool_use",id:Z.toolCallId,name:Z.toolName,input:Vt(Z.input),...Oe&&{caller:Oe},cache_control:Ue});break}case"tool-result":{let Oe=me.toProviderToolName(Z.toolName),We=Wt(Z.providerOptions);if(He.has(Z.toolCallId)){let te=Z.output;if(te.type!=="json"&&te.type!=="error-json"){U.push({type:"other",message:`provider executed tool result output type ${te.type} for tool ${Z.toolName} is not supported`});break}ye.push({type:"mcp_tool_result",tool_use_id:Z.toolCallId,is_error:te.type==="error-json",content:te.value,cache_control:Ue})}else if(Oe==="code_execution"){let te=Z.output;if(te.type==="error-text"||te.type==="error-json"){let ue={};try{if(typeof te.value==="string")ue=Q(te.value);else if(typeof te.value==="object"&&te.value!==null)ue=te.value}catch{}if(ue.type==="code_execution_tool_result_error")ye.push({type:"code_execution_tool_result",tool_use_id:Z.toolCallId,content:{type:"code_execution_tool_result_error",error_code:ue.errorCode??"unknown"},cache_control:Ue});else ye.push({type:"bash_code_execution_tool_result",tool_use_id:Z.toolCallId,cache_control:Ue,content:{type:"bash_code_execution_tool_result_error",error_code:ue.errorCode??"unknown"}});break}if(te.type!=="json"){U.push({type:"other",message:`provider executed tool result output type ${te.type} for tool ${Z.toolName} is not supported`});break}if(te.value==null||typeof te.value!=="object"||!("type"in te.value)||typeof te.value.type!=="string"){U.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${Z.toolName}`});break}if(te.value.type==="code_execution_result"){let ue=await x({value:te.value,schema:ho});ye.push({type:"code_execution_tool_result",tool_use_id:Z.toolCallId,content:{type:ue.type,stdout:ue.stdout,stderr:ue.stderr,return_code:ue.return_code,content:ue.content??[]},cache_control:Ue})}else if(te.value.type==="encrypted_code_execution_result"){let ue=await x({value:te.value,schema:go});if(ue.type==="encrypted_code_execution_result")ye.push({type:"code_execution_tool_result",tool_use_id:Z.toolCallId,content:{type:ue.type,encrypted_stdout:ue.encrypted_stdout,stderr:ue.stderr,return_code:ue.return_code,content:ue.content??[]},cache_control:Ue})}else{let ue=await x({value:te.value,schema:mo});if(ue.type==="code_execution_result")ye.push({type:"code_execution_tool_result",tool_use_id:Z.toolCallId,content:{type:ue.type,stdout:ue.stdout,stderr:ue.stderr,return_code:ue.return_code,content:ue.content??[]},cache_control:Ue});else if(ue.type==="bash_code_execution_result"||ue.type==="bash_code_execution_tool_result_error")ye.push({type:"bash_code_execution_tool_result",tool_use_id:Z.toolCallId,cache_control:Ue,content:ue.type==="bash_code_execution_result"?{type:ue.type,stdout:ue.stdout,stderr:ue.stderr,return_code:ue.return_code,content:ue.content}:ue});else ye.push({type:"text_editor_code_execution_tool_result",tool_use_id:Z.toolCallId,cache_control:Ue,content:ue})}break}if(Oe==="web_fetch"){let te=Z.output;if(te.type==="error-json"){ye.push({type:"web_fetch_tool_result",tool_use_id:Z.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:Rt(te.value).errorCode??"unavailable"},...We&&{caller:We},cache_control:Ue});break}if(te.type!=="json"){U.push({type:"other",message:`provider executed tool result output type ${te.type} for tool ${Z.toolName} is not supported`});break}let ue=await x({value:te.value,schema:_o});ye.push({type:"web_fetch_tool_result",tool_use_id:Z.toolCallId,content:{type:"web_fetch_result",url:ue.url,retrieved_at:ue.retrievedAt,content:{type:"document",title:ue.content.title,citations:ue.content.citations,source:{type:ue.content.source.type,media_type:ue.content.source.mediaType,data:ue.content.source.data}}},...We&&{caller:We},cache_control:Ue});break}if(Oe==="web_search"){let te=Z.output;if(te.type==="error-json"){ye.push({type:"web_search_tool_result",tool_use_id:Z.toolCallId,content:{type:"web_search_tool_result_error",error_code:Rt(te.value).errorCode??"unavailable"},...We&&{caller:We},cache_control:Ue});break}if(te.type!=="json"){U.push({type:"other",message:`provider executed tool result output type ${te.type} for tool ${Z.toolName} is not supported`});break}let ue=await x({value:te.value,schema:po});ye.push({type:"web_search_tool_result",tool_use_id:Z.toolCallId,content:ue.map((Qe)=>({url:Qe.url,title:Qe.title,page_age:Qe.pageAge,encrypted_content:Qe.encryptedContent,type:Qe.type})),...We&&{caller:We},cache_control:Ue});break}if(Oe==="tool_search_tool_regex"||Oe==="tool_search_tool_bm25"){let te=Z.output;if(te.type==="error-json"||te.type==="json"&&te.value!=null&&typeof te.value==="object"&&!Array.isArray(te.value)&&"type"in te.value&&te.value.type==="tool_search_tool_result_error"){ye.push({type:"tool_search_tool_result",tool_use_id:Z.toolCallId,content:{type:"tool_search_tool_result_error",error_code:Rt(te.value).errorCode??"unavailable"},cache_control:Ue});break}if(te.type!=="json"){U.push({type:"other",message:`provider executed tool result output type ${te.type} for tool ${Z.toolName} is not supported`});break}let ue=(await x({value:te.value,schema:fo})).map((Qe)=>({type:"tool_reference",tool_name:Qe.toolName}));ye.push({type:"tool_search_tool_result",tool_use_id:Z.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:ue},cache_control:Ue});break}if(Oe==="advisor"){let te=Z.output;if(te.type!=="json"&&te.type!=="error-json"){U.push({type:"other",message:`provider executed tool result output type ${te.type} for tool ${Z.toolName} is not supported`});break}let ue=await x({value:te.value,schema:co});if(ue.type==="advisor_result")ye.push({type:"advisor_tool_result",tool_use_id:Z.toolCallId,content:{type:"advisor_result",text:ue.text,...ue.stopReason!==void 0&&{stop_reason:ue.stopReason}},cache_control:Ue});else if(ue.type==="advisor_redacted_result")ye.push({type:"advisor_tool_result",tool_use_id:Z.toolCallId,content:{type:"advisor_redacted_result",encrypted_content:ue.encryptedContent,...ue.stopReason!==void 0&&{stop_reason:ue.stopReason}},cache_control:Ue});else ye.push({type:"advisor_tool_result",tool_use_id:Z.toolCallId,content:{type:"advisor_tool_result_error",error_code:ue.errorCode},cache_control:Ue});break}U.push({type:"other",message:`provider executed tool result for tool ${Z.toolName} is not supported`});break}}}}if(ye.length>0)Se.push({role:"assistant",content:Pn(ye)});break}default:throw Error(`content type: ${Ee}`)}}let Ve=new Set;for(let Pe of Se){if(Pe.role!=="assistant")continue;for(let Ae of Pe.content)if(Ae.type==="server_tool_use"&&Ae.name==="code_execution")Ve.add(Ae.id)}let Fe=new Set;for(let Pe=0;Pe<Ye;Pe++){let Ae=Se[Pe];if(Ae.role!=="assistant")continue;for(let K of Ae.content){if(!("caller"in K))continue;let Ee=K.caller;if(Ee==null||Ee.type==="direct"||Ve.has(Ee.tool_id))continue;let ye="id"in K?K.id:K.tool_use_id;if(delete K.caller,!Fe.has(ye))Fe.add(ye),U.push({type:"other",message:`Omitted caller metadata for tool ${ye} because source code execution tool ${Ee.tool_id} is missing from the conversation history.`})}}return{prompt:{system:$e,messages:Se},betas:ae}}function Hn(m){let R=[],U=void 0;for(let X of m){let{role:me}=X;switch(me){case"system":if(U?.type!=="system")U={type:"system",messages:[]},R.push(U);U.messages.push(X);break;case"assistant":if(U?.type!=="assistant")U={type:"assistant",messages:[]},R.push(U);U.messages.push(X);break;case"user":if(U?.type!=="user")U={type:"user",messages:[]},R.push(U);U.messages.push(X);break;case"tool":if(U?.type!=="user")U={type:"user",messages:[]},R.push(U);U.messages.push(X);break;default:throw Error(`Unsupported role: ${me}`)}}return R}function Pn(m){let R=[],U=[];function X(){R.push(...U.filter((me)=>me.type!=="tool_use"),...U.filter((me)=>me.type==="tool_use")),U=[]}for(let me of m)if(me.type==="thinking"||me.type==="redacted_thinking"||me.type==="fallback")X(),R.push(me);else U.push(me);return X(),R}function zt({toolName:m,providerOptions:R,toolsetNames:U}){let X=U[m];if(X!=null)return X;let me=R?.anthropic?.toolsetName;return typeof me==="string"?me:void 0}function Wt(m){let R=m?.anthropic?.caller;if((R?.type==="code_execution_20250825"||R?.type==="code_execution_20260120")&&R.toolId)return{type:R.type,tool_id:R.toolId};return R?.type==="direct"?{type:"direct"}:void 0}function Vt(m){return typeof m==="object"&&m!==null&&!Array.isArray(m)?m:{rawInvalidInput:m}}function Nt({finishReason:m,isJsonResponseFromTool:R}){switch(m){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return R?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";case"compaction":return"other";default:return"other"}}var yo=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),Ln=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties","not"];function Fn(m){return bo(m)}function mt(m){if(typeof m==="boolean"||!j(m))return m;return bo(m)}function bo(m){let R={},U=m;if(m.$ref!=null)return{$ref:m.$ref};if(m.$schema!=null)R.$schema=m.$schema;if(m.$id!=null)R.$id=m.$id;if(m.title!=null)R.title=m.title;if(m.description!=null)R.description=m.description;if(m.default!==void 0)R.default=m.default;if(m.const!==void 0)R.const=m.const;if(m.enum!=null)R.enum=m.enum;if(m.type!=null)R.type=m.type;if(m.anyOf!=null)R.anyOf=m.anyOf.map(mt);else if(m.oneOf!=null)R.anyOf=m.oneOf.map(mt);if(m.allOf!=null)R.allOf=m.allOf.map(mt);if(m.definitions!=null)R.definitions=Object.fromEntries(Object.entries(m.definitions).map(([me,Ne])=>[me,mt(Ne)]));if(U.$defs!=null){let me=R;me.$defs=Object.fromEntries(Object.entries(U.$defs).map(([Ne,W])=>[Ne,mt(W)]))}if(m.type==="object"||m.properties!=null){if(m.properties!=null)R.properties=Object.fromEntries(Object.entries(m.properties).map(([me,Ne])=>[me,mt(Ne)]));if(R.additionalProperties=!1,m.required!=null)R.required=m.required}if(m.items!=null)R.items=Array.isArray(m.items)?m.items.map(mt):mt(m.items);if(typeof m.format==="string"&&yo.has(m.format))R.format=m.format;let X=Jn(m);if(X!=null)R.description=R.description==null?X:`${R.description}
2
+ ${X}`;return R}function Jn(m){let R=Ln.flatMap((U)=>{let X=m[U];if(X==null||X===!1)return[];return`${Kn(U)}: ${zn(X)}`});if(typeof m.format==="string"&&!yo.has(m.format))R.push(`format: ${m.format}`);return R.length===0?void 0:`${R.join("; ")}.`}function Kn(m){return m.replace(/[A-Z]/g,(R)=>` ${R.toLowerCase()}`)}function zn(m){if(typeof m==="string")return m;return JSON.stringify(m)}function Wn(m){let R=Vn(m.type);return xe({message:m.message,type:m.type,code:m.code??void 0,statusCode:m.statusCode??R.statusCode,isRetryable:m.isRetryable??R.isRetryable,data:"data"in m?m.data:m})}function Vn(m){switch(m){case"api_error":return{statusCode:500,isRetryable:!0};case"overloaded_error":return{statusCode:529,isRetryable:!0};case"rate_limit_error":return{statusCode:429,isRetryable:!0};case"request_too_large":return{statusCode:413,isRetryable:!1};case"authentication_error":return{statusCode:401,isRetryable:!1};case"permission_error":return{statusCode:403,isRetryable:!1};case"not_found_error":return{statusCode:404,isRetryable:!1};case"billing_error":case"invalid_request_error":return{statusCode:400,isRetryable:!1};default:return{}}}function Ot(m,R,U){if(m.type==="web_search_result_location")return{type:"source",sourceType:"url",id:U(),url:m.url,title:m.title??void 0,providerMetadata:{anthropic:{citedText:m.cited_text,encryptedIndex:m.encrypted_index}}};if(m.type!=="page_location"&&m.type!=="char_location")return;let X=R[m.document_index];if(!X)return;return{type:"source",sourceType:"document",id:U(),mediaType:X.mediaType,title:m.document_title??X.title,filename:X.filename,providerMetadata:{anthropic:m.type==="page_location"?{citedText:m.cited_text,startPageNumber:m.start_page_number,endPageNumber:m.end_page_number}:{citedText:m.cited_text,startCharIndex:m.start_char_index,endCharIndex:m.end_char_index}}}}function vt(m){return m==null?void 0:{type:m.type,toolId:"tool_id"in m?m.tool_id:void 0}}function st(m){let R=vt(m);return R==null?{}:{providerMetadata:{anthropic:{caller:R}}}}function Xn(m){let R={};for(let U of m??[])if(U.type==="provider"&&U.id==="anthropic.computer_toolset_20260801")R[U.name]="computer";return R}function Xt({memberName:m,input:R}){return{action:m,...typeof R==="object"&&R!==null&&!Array.isArray(R)?R:{}}}function Gt(m){let R=m.indexOf(".");return R===-1?m:m.substring(0,R)}var xo=class m{static[S](R){return M({modelId:R.modelId,config:R.config})}static[I](R){return new m(R.modelId,R.config)}constructor(R,U){this.specificationVersion="v4",this.modelId=R,this.config=U,this.generateId=U.generateId??C}supportsUrl(R){return R.protocol==="https:"}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?.()??{}}static async prepareRequest({modelId:R,config:U,options:{userSuppliedBetas:X,prompt:me,maxOutputTokens:Ne,temperature:W,topP:ae,topK:se,frequencyPenalty:fe,presencePenalty:$e,stopSequences:Se,responseFormat:Ye,seed:we,tools:je,toolChoice:Me,reasoning:Ve,providerOptions:Fe,stream:Pe}}){let Ae=[];if(fe!=null)Ae.push({type:"unsupported",feature:"frequencyPenalty"});if($e!=null)Ae.push({type:"unsupported",feature:"presencePenalty"});if(we!=null)Ae.push({type:"unsupported",feature:"seed"});let K=U.maxTemperature??1,Ee=U.maxTemperature==null?"anthropic":Gt(U.provider);if(W!=null&&W>K)Ae.push({type:"unsupported",feature:"temperature",details:`${W} exceeds ${Ee} maximum of ${K.toFixed(1)}. clamped to ${K.toFixed(1)}`}),W=K;else if(W!=null&&W<0)Ae.push({type:"unsupported",feature:"temperature",details:`${W} is below ${Ee} minimum of 0. clamped to 0`}),W=0;if(Ye?.type==="json"){if(Ye.schema==null)Ae.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."})}let ye=Gt(U.provider),He=await h({provider:"anthropic",providerOptions:Fe,schema:Jt}),nt=ye!=="anthropic"?await h({provider:ye,providerOptions:Fe,schema:Jt}):null,De=nt!=null,G=Object.assign({},He??{},nt??{}),{maxOutputTokens:Ce,supportsStructuredOutput:Ge,supportsAdaptiveThinking:Z,rejectsSamplingParameters:rt,supportsXhighEffort:Ue,rejectsThinkingDisabledAboveHighEffort:Oe,rejectsThinkingDisabled:We,rejectsBudgetThinking:te,rejectsForcedToolUse:ue,supportsBetweenToolsThinking:Qe,isKnownModel:gt}=Gn(R);if(!gt&&Ne==null)Ae.push({type:"compatibility",feature:"maxOutputTokens",details:`The model "${R}" is unknown. The max output tokens have been limited to ${Ce}. Set maxOutputTokens explicitly to override this limit.`});if(rt){if(W!=null)Ae.push({type:"unsupported",feature:"temperature",details:`temperature is not supported by ${R} and will be ignored`}),W=void 0;if(se!=null)Ae.push({type:"unsupported",feature:"topK",details:`topK is not supported by ${R} and will be ignored`}),se=void 0;if(ae!=null)Ae.push({type:"unsupported",feature:"topP",details:`topP is not supported by ${R} and will be ignored`}),ae=void 0}let yt=gt||R.includes("claude-"),bt=(U.supportsNativeStructuredOutput??!0)&&Ge,kt=(U.supportsStrictTools??!0)&&Ge,pt=G?.structuredOutputMode??"auto",et=pt==="outputFormat"||pt==="auto"&&bt;if(!et&&ue&&bt&&Ye?.type==="json"&&Ye.schema!=null)Ae.push({type:"unsupported",feature:"providerOptions.anthropic.structuredOutputMode",details:`structuredOutputMode 'jsonTool' is not supported by ${R} because it rejects forced tool use. Using 'outputFormat' instead.`}),et=!0;let Te=Ye?.type==="json"&&Ye.schema!=null&&!et?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:Ye.schema}:void 0;if(Te!=null&&G?.disableParallelToolUse===!1)Ae.push({type:"unsupported",feature:"providerOptions.anthropic.disableParallelToolUse",details:"`disableParallelToolUse: false` is ignored when using the JSON response tool. Parallel tool use is disabled to ensure a single coherent JSON tool call."});let ee=G?.contextManagement,J=G?.compaction;if(ee!=null&&J!=null)throw new b({argument:"providerOptions",message:"Anthropic provider options `compaction` and `contextManagement` cannot be used together."});let qe=new qt(U.cacheControlProviderOptionsName),be=le({tools:je,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.code_execution_20260120":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.computer_20251124":"computer","anthropic.computer_toolset_20260801":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_search_20260209":"web_search","anthropic.web_search_20260318":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.web_fetch_20260209":"web_fetch","anthropic.web_fetch_20260318":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25","anthropic.advisor_20260301":"advisor"}}),Je=Xn(je),{prompt:_t,betas:tt}=await Dn({prompt:me,sendReasoning:G?.sendReasoning??!0,warnings:Ae,cacheControlValidator:qe,toolNameMapping:be,toolsetNames:Je,convertMediaPart:U.convertMediaPart});if(H(Ve)&&G?.effort==null){let Ie=Zn({reasoning:Ve,modelId:R,supportsAdaptiveThinking:Z,supportsXhighEffort:Ue,rejectsThinkingDisabled:We,supportsBetweenToolsThinking:Qe,maxOutputTokensForModel:Ce,warnings:Ae});if(Ie!=null){if(G.thinking==null)G.thinking=Ie.thinking;if(Ie.effort!=null&&G.thinking?.type!=="disabled")G.effort=Ie.effort}}if(We&&G?.thinking!=null){let Ie=G.thinking;if(Ie.type==="disabled"&&Qe)Ae.push({type:"unsupported",feature:"providerOptions.anthropic.thinking",details:`thinking cannot be disabled for ${R}. Using 'between_tools' thinking, the lowest thinking setting, instead.`}),G.thinking={type:"between_tools"};else if(Ie.type==="disabled")Ae.push({type:"unsupported",feature:"providerOptions.anthropic.thinking",details:`thinking cannot be disabled for ${R}; it always uses adaptive thinking. The thinking setting has been removed. Lower 'effort' to reduce thinking.`}),G.thinking=void 0}if(te&&G?.thinking?.type==="enabled")Ae.push({type:"unsupported",feature:"providerOptions.anthropic.thinking",details:We?`budget-based thinking is not supported by ${R}; it always uses adaptive thinking. Using adaptive thinking instead. Use 'effort' to control how much the model thinks.`:`budget-based thinking is not supported by ${R}. Using adaptive thinking instead. Use 'effort' to control how much the model thinks.`}),G.thinking={type:"adaptive"};if(Oe&&G?.thinking?.type==="disabled"&&(G.effort==="xhigh"||G.effort==="max"))Ae.push({type:"unsupported",feature:"providerOptions.anthropic.effort",details:`effort '${G.effort}' is not supported by ${R} when thinking is disabled. The effort has been lowered to 'high'.`}),G.effort="high";if(G?.thinking?.type==="between_tools"&&(G.effort==="xhigh"||G.effort==="max"))Ae.push({type:"unsupported",feature:"providerOptions.anthropic.effort",details:`effort '${G.effort}' is not supported with 'between_tools' thinking. The effort has been lowered to 'high'.`}),G.effort="high";let at=G?.thinking?.type,Ht=at==="enabled"||at==="adaptive"||at==="between_tools",wt=G?.thinking!=null&&"blockBinding"in G.thinking?G.thinking.blockBinding:void 0,jo=Ht||at==="disabled"||wt!=null,xt=at==="enabled"?G?.thinking?.budgetTokens:void 0,It=at==="adaptive"?G?.thinking?.display:void 0,Pt=Ne??Ce,lt={model:R,max_tokens:Pt,temperature:W,top_k:se,top_p:ae,stop_sequences:Se,...jo&&{thinking:{...at!=null&&{type:at},...xt!=null&&{budget_tokens:xt},...It!=null&&{display:It},...wt!=null&&{block_binding:{prefix_mismatch_behavior:wt.prefixMismatchBehavior}}}},...(G?.effort||G?.taskBudget||et&&Ye?.type==="json"&&Ye.schema!=null)&&{output_config:{...G?.effort&&{effort:G.effort},...G?.taskBudget&&{task_budget:{type:G.taskBudget.type,total:G.taskBudget.total,...G.taskBudget.remaining!=null&&{remaining:G.taskBudget.remaining}}},...et&&Ye?.type==="json"&&Ye.schema!=null&&{format:{type:"json_schema",schema:Fn(Ye.schema)}}}},...G?.speed&&{speed:G.speed},...G?.serviceTier&&{service_tier:G.serviceTier},...G?.inferenceGeo&&{inference_geo:G.inferenceGeo},...G?.fallbacks!=null&&(G.fallbacks==="default"||G.fallbacks.length>0)&&{fallbacks:G.fallbacks},...G?.cacheControl&&{cache_control:G.cacheControl},...G?.metadata?.userId!=null&&{metadata:{user_id:G.metadata.userId}},...G?.mcpServers&&G.mcpServers.length>0&&{mcp_servers:G.mcpServers.map((Ie)=>({type:Ie.type,name:Ie.name,url:Ie.url,authorization_token:Ie.authorizationToken,tool_configuration:Ie.toolConfiguration?{allowed_tools:Ie.toolConfiguration.allowedTools,enabled:Ie.toolConfiguration.enabled}:void 0}))},...G?.container&&{container:G.container.skills&&G.container.skills.length>0?{id:G.container.id,skills:G.container.skills.map((Ie)=>({type:Ie.type,skill_id:Ie.type==="custom"?V({reference:Ie.providerReference,provider:"anthropic"}):Ie.skillId,version:Ie.version}))}:G.container.id},system:_t.system,messages:_t.messages,...G?.safeguards&&G.safeguards.length>0&&{safeguards:G.safeguards.map((Ie)=>({type:Ie.type,...Ie.classifierContext!==void 0&&{classifier_context:Ie.classifierContext}}))},...J&&{compaction:{type:J.type,...J.instructions!==void 0&&{instructions:J.instructions}}},...ee&&{context_management:{edits:ee.edits.map((Ie)=>{let Ft=Ie.type;switch(Ft){case"clear_tool_uses_20250919":return{type:Ie.type,...Ie.trigger!==void 0&&{trigger:Ie.trigger},...Ie.keep!==void 0&&{keep:Ie.keep},...Ie.clearAtLeast!==void 0&&{clear_at_least:Ie.clearAtLeast},...Ie.clearToolInputs!==void 0&&{clear_tool_inputs:Ie.clearToolInputs},...Ie.excludeTools!==void 0&&{exclude_tools:Ie.excludeTools}};case"clear_thinking_20251015":return{type:Ie.type,...Ie.keep!==void 0&&{keep:Ie.keep}};case"compact_20260112":return{type:Ie.type,...Ie.trigger!==void 0&&{trigger:Ie.trigger},...Ie.pauseAfterCompaction!==void 0&&{pause_after_compaction:Ie.pauseAfterCompaction},...Ie.instructions!==void 0&&{instructions:Ie.instructions}};default:Ae.push({type:"other",message:`Unknown context management strategy: ${Ft}`});return}}).filter((Ie)=>Ie!==void 0)}}};if(Ht){if(at==="enabled"&&xt==null)Ae.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),lt.thinking={type:"enabled",budget_tokens:1024},xt=1024;if(lt.temperature!=null&&!U.supportsTemperatureAndTopPWithThinking)lt.temperature=void 0,Ae.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"});if(se!=null)lt.top_k=void 0,Ae.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"});if(ae!=null&&!U.supportsTemperatureAndTopPWithThinking)lt.top_p=void 0,Ae.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"});lt.max_tokens=Pt+(xt??0)}else if(yt&&ae!=null&&W!=null)Ae.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),lt.top_p=void 0;if(gt&&lt.max_tokens>Ce){if(Ne!=null)Ae.push({type:"unsupported",feature:"maxOutputTokens",details:`${lt.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${R} ${Ce} max output tokens. The max output tokens have been limited to ${Ce}.`});lt.max_tokens=Ce}if(G?.mcpServers&&G.mcpServers.length>0)tt.add("mcp-client-2025-04-04");if(G?.safeguards&&G.safeguards.length>0)tt.add("dangerous-tool-use-2026-09-03");if(J)tt.add("compact-2026-09-04");if(ee){if(tt.add("context-management-2025-06-27"),ee.edits.some((Ie)=>Ie.type==="compact_20260112"))tt.add("compact-2026-01-12")}if(G?.container&&G.container.skills&&G.container.skills.length>0){if(tt.add("code-execution-2025-08-25"),tt.add("skills-2025-10-02"),tt.add("files-api-2025-04-14"),!je?.some((Ie)=>Ie.type==="provider"&&(Ie.id==="anthropic.code_execution_20250825"||Ie.id==="anthropic.code_execution_20260120")))Ae.push({type:"other",message:"code execution tool is required when using skills"})}if(G?.taskBudget)tt.add("task-budgets-2026-03-13");if(G?.speed==="fast")tt.add("fast-mode-2026-02-01");if(It==="updates")tt.add("thinking-display-updates-2026-08-18");if(wt!=null)tt.add("thinking-binding-controls-2026-08-01");if(G?.fallbacks==="default")tt.add("server-side-fallback-2026-07-01");else if(G?.fallbacks&&G.fallbacks.length>0)tt.add("server-side-fallback-2026-06-01");let Lt=Pe&&(G?.toolStreaming??!0),{tools:To,toolChoice:Co,toolWarnings:So,betas:No}=await Tn(Te!=null?{tools:[...je??[],Te],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:qe,supportsStructuredOutput:!1,supportsStrictTools:kt,defaultEagerInputStreaming:Lt,rejectsForcedToolUse:ue||at==="enabled"}:{tools:je??[],toolChoice:Me,disableParallelToolUse:G?.disableParallelToolUse,cacheControlValidator:qe,supportsStructuredOutput:bt,supportsStrictTools:kt,defaultEagerInputStreaming:Lt,rejectsForcedToolUse:ue||at==="enabled"}),Oo=qe.getWarnings();return{args:{...lt,tools:To,tool_choice:Co,stream:Pe===!0?!0:void 0},warnings:[...Ae,...So,...Oo],betas:new Set([...tt,...No,...X,...G?.anthropicBeta??[]]),usesJsonResponseTool:Te!=null,toolNameMapping:be,providerOptionsName:ye,usedCustomProviderKey:De}}getArgs(R){return m.prepareRequest({modelId:this.modelId,config:this.config,options:R})}async getHeaders({betas:R,configHeaders:U,headers:X,providerOptions:me}){let Ne=d(U,X,R.size>0?{"anthropic-beta":Array.from(R).join(",")}:{});return this.config.transformRequestHeaders?this.config.transformRequestHeaders(Ne,me):Ne}getBetasFromHeaders(R,U){let X=R?.["anthropic-beta"]??"",me=U?.["anthropic-beta"]??"";return new Set([...X.toLowerCase().split(","),...me.toLowerCase().split(",")].map((Ne)=>Ne.trim()).filter((Ne)=>Ne!==""))}buildRequestUrl(R){return this.config.buildRequestUrl?.(this.config.baseURL,R)??`${this.config.baseURL}/messages`}transformRequestBody(R,U){return this.config.transformRequestBody?.(R,U)??R}extractCitationDocuments(R){let U=(X)=>{if(X.type!=="file")return!1;if(X.mediaType!=="application/pdf"&&X.mediaType!=="text/plain")return!1;return X.providerOptions?.anthropic?.citations?.enabled??!1};return R.filter((X)=>X.role==="user").flatMap((X)=>X.content).filter(U).map((X)=>{let me=X;return{title:me.filename??"Untitled Document",filename:me.filename,mediaType:me.mediaType}})}async doGenerate(R){let U=this.config.headers?await _(this.config.headers):void 0,{args:X,warnings:me,betas:Ne,usesJsonResponseTool:W,toolNameMapping:ae,providerOptionsName:se,usedCustomProviderKey:fe}=await this.getArgs({...R,stream:!1,userSuppliedBetas:this.getBetasFromHeaders(U,R.headers)}),$e=[...this.extractCitationDocuments(R.prompt)],Se=Zt(X.tools),{responseHeaders:Ye,value:we,rawValue:je}=await g({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:Ne,configHeaders:U,headers:R.headers,providerOptions:R.providerOptions}),body:this.transformRequestBody(X,Ne),failedResponseHandler:ct,successfulResponseHandler:p(St),abortSignal:R.abortSignal,fetch:this.config.fetch}),Me=[],Ve={},Fe={},Pe=!1,Ae=we.content.some((K)=>K.type==="web_search_tool_result"&&Array.isArray(K.content)&&K.content.length>0);for(let K of we.content)switch(K.type){case"text":if(!W){let Ee=K.citations??[];if(Me.push({type:"text",text:K.text,...Ee.length>0&&{citations:Ee.map((ye)=>Et(ye,$e))},...Ee.length>0&&{providerMetadata:{anthropic:{citations:Ee}}}}),K.citations)for(let ye of K.citations){if(ye.type==="web_search_result_location"&&Ae)continue;let He=Ot(ye,$e,this.generateId);if(He)Me.push(He)}}break;case"thinking":Me.push({type:"reasoning",text:K.thinking,providerMetadata:{anthropic:{signature:K.signature}}});break;case"redacted_thinking":Me.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:K.data}}});break;case"container_upload":Me.push({type:"custom",kind:"anthropic.container_upload",providerMetadata:{anthropic:{fileId:K.file_id}}});break;case"compaction":if(!K.content)break;Me.push({type:"text",text:K.content,providerMetadata:{anthropic:{type:"compaction",...K.signature!=null&&{signature:K.signature}}}});break;case"tool_use":if(W&&K.name==="json")Pe=!0,Me.push({type:"text",text:JSON.stringify(K.input)});else if(K.toolset_name!=null)Me.push({type:"tool-call",toolCallId:K.id,toolName:ae.toCustomToolName(K.toolset_name),input:JSON.stringify(Xt({memberName:K.name,input:K.input})),providerMetadata:{anthropic:{toolsetName:K.toolset_name,...st(K.caller).providerMetadata?.anthropic}}});else Me.push({type:"tool-call",toolCallId:K.id,toolName:K.name,input:JSON.stringify(K.input),...st(K.caller)});break;case"server_tool_use":if(K.name==="text_editor_code_execution"||K.name==="bash_code_execution")Me.push({type:"tool-call",toolCallId:K.id,toolName:ae.toCustomToolName("code_execution"),input:JSON.stringify({type:K.name,...K.input}),providerExecuted:!0,...Se?{dynamic:!0}:{},...st(K.caller)});else if(K.name==="web_search"||K.name==="code_execution"||K.name==="web_fetch"){let Ee=K.name==="code_execution"&&K.input!=null&&typeof K.input==="object"&&"code"in K.input&&!("type"in K.input)?{type:"programmatic-tool-call",...K.input}:K.input;Me.push({type:"tool-call",toolCallId:K.id,toolName:ae.toCustomToolName(K.name),input:JSON.stringify(Ee),providerExecuted:!0,...Se&&K.name==="code_execution"?{dynamic:!0}:{},...st(K.caller)})}else if(K.name==="tool_search_tool_regex"||K.name==="tool_search_tool_bm25")Fe[K.id]=K.name,Me.push({type:"tool-call",toolCallId:K.id,toolName:ae.toCustomToolName(K.name),input:JSON.stringify(K.input),providerExecuted:!0,...st(K.caller)});else if(K.name==="advisor")Me.push({type:"tool-call",toolCallId:K.id,toolName:ae.toCustomToolName("advisor"),input:JSON.stringify(K.input),providerExecuted:!0,...st(K.caller)});break;case"mcp_tool_use":Ve[K.id]={type:"tool-call",toolCallId:K.id,toolName:K.name,input:JSON.stringify(K.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:K.server_name}}},Me.push(Ve[K.id]);break;case"mcp_tool_result":Me.push({type:"tool-result",toolCallId:K.tool_use_id,toolName:Ve[K.tool_use_id].toolName,isError:K.is_error,result:K.content,dynamic:!0,providerMetadata:Ve[K.tool_use_id].providerMetadata});break;case"web_fetch_tool_result":if(K.content.type==="web_fetch_result")$e.push({title:K.content.content.title??K.content.url,mediaType:K.content.content.source.media_type}),Me.push({type:"tool-result",toolCallId:K.tool_use_id,toolName:ae.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:K.content.url,retrievedAt:K.content.retrieved_at,content:{type:K.content.content.type,title:K.content.content.title,citations:K.content.content.citations,source:{type:K.content.content.source.type,mediaType:K.content.content.source.media_type,data:K.content.content.source.data}}},...st(K.caller)});else if(K.content.type==="web_fetch_tool_result_error")Me.push({type:"tool-result",toolCallId:K.tool_use_id,toolName:ae.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:K.content.error_code},...st(K.caller)});break;case"web_search_tool_result":if(Array.isArray(K.content)){Me.push({type:"tool-result",toolCallId:K.tool_use_id,toolName:ae.toCustomToolName("web_search"),result:K.content.map((Ee)=>({url:Ee.url,...Ee.title!=null?{title:Ee.title}:{},pageAge:Ee.page_age??null,encryptedContent:Ee.encrypted_content,type:Ee.type})),...st(K.caller)});for(let Ee of K.content)Me.push({type:"source",sourceType:"url",id:this.generateId(),url:Ee.url,...Ee.title!=null?{title:Ee.title}:{},providerMetadata:{anthropic:{pageAge:Ee.page_age??null}}})}else Me.push({type:"tool-result",toolCallId:K.tool_use_id,toolName:ae.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:K.content.error_code},...st(K.caller)});break;case"code_execution_tool_result":if(K.content.type==="code_execution_result")Me.push({type:"tool-result",toolCallId:K.tool_use_id,toolName:ae.toCustomToolName("code_execution"),result:{type:K.content.type,stdout:K.content.stdout,stderr:K.content.stderr,return_code:K.content.return_code,content:K.content.content??[]}});else if(K.content.type==="encrypted_code_execution_result")Me.push({type:"tool-result",toolCallId:K.tool_use_id,toolName:ae.toCustomToolName("code_execution"),result:{type:K.content.type,encrypted_stdout:K.content.encrypted_stdout,stderr:K.content.stderr,return_code:K.content.return_code,content:K.content.content??[]}});else if(K.content.type==="code_execution_tool_result_error")Me.push({type:"tool-result",toolCallId:K.tool_use_id,toolName:ae.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:K.content.error_code}});break;case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":Me.push({type:"tool-result",toolCallId:K.tool_use_id,toolName:ae.toCustomToolName("code_execution"),result:K.content});break;case"tool_search_tool_result":{let Ee=Fe[K.tool_use_id];if(Ee==null){let ye=ae.toCustomToolName("tool_search_tool_bm25"),He=ae.toCustomToolName("tool_search_tool_regex");if(ye!=="tool_search_tool_bm25")Ee="tool_search_tool_bm25";else if(He!=="tool_search_tool_regex")Ee="tool_search_tool_regex";else Ee="tool_search_tool_regex"}if(K.content.type==="tool_search_tool_search_result")Me.push({type:"tool-result",toolCallId:K.tool_use_id,toolName:ae.toCustomToolName(Ee),result:K.content.tool_references.map((ye)=>({type:ye.type,toolName:ye.tool_name}))});else Me.push({type:"tool-result",toolCallId:K.tool_use_id,toolName:ae.toCustomToolName(Ee),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:K.content.error_code}});break}case"advisor_tool_result":{let Ee=ae.toCustomToolName("advisor");if(K.content.type==="advisor_result")Me.push({type:"tool-result",toolCallId:K.tool_use_id,toolName:Ee,result:{type:"advisor_result",text:K.content.text,...K.content.stop_reason!=null&&{stopReason:K.content.stop_reason}}});else if(K.content.type==="advisor_redacted_result")Me.push({type:"tool-result",toolCallId:K.tool_use_id,toolName:Ee,result:{type:"advisor_redacted_result",encryptedContent:K.content.encrypted_content,...K.content.stop_reason!=null&&{stopReason:K.content.stop_reason}}});else Me.push({type:"tool-result",toolCallId:K.tool_use_id,toolName:Ee,isError:!0,result:{type:"advisor_tool_result_error",errorCode:K.content.error_code}});break}case"fallback":Me.push({type:"custom",kind:"anthropic.fallback",providerMetadata:{anthropic:{type:"fallback",from:K.from,to:K.to}}})}return{content:Me,finishReason:{unified:Nt({finishReason:we.stop_reason,isJsonResponseFromTool:Pe}),raw:we.stop_reason??void 0},usage:Ut({usage:we.usage}),request:{body:X},response:{id:we.id??void 0,modelId:we.model??void 0,headers:Ye,body:je},warnings:me,providerMetadata:(()=>{let K=Qt(we.stop_details),Ee={usage:we.usage,stopSequence:we.stop_sequence??null,...K!=null?{stopDetails:K}:{},...we.input_transformations!=null?{inputTransformations:we.input_transformations}:{},...we.safeguard_results!=null?{safeguardResults:we.safeguard_results}:{},iterations:we.usage.iterations?we.usage.iterations.map((He)=>({type:He.type,...He.model!=null?{model:He.model}:{},inputTokens:He.input_tokens,outputTokens:He.output_tokens,...He.cache_creation_input_tokens?{cacheCreationInputTokens:He.cache_creation_input_tokens}:{},...He.cache_read_input_tokens?{cacheReadInputTokens:He.cache_read_input_tokens}:{}})):null,container:we.container?{expiresAt:we.container.expires_at,id:we.container.id,skills:we.container.skills?.map((He)=>({type:He.type,skillId:He.skill_id,version:He.version}))??null}:null,contextManagement:Yt(we.context_management)??null},ye={anthropic:Ee};if(fe&&se!=="anthropic")ye[se]=Ee;return ye})()}}async doStream(R){let U=this.config.headers?await _(this.config.headers):void 0,{args:X,warnings:me,betas:Ne,usesJsonResponseTool:W,toolNameMapping:ae,providerOptionsName:se,usedCustomProviderKey:fe}=await this.getArgs({...R,stream:!0,userSuppliedBetas:this.getBetasFromHeaders(U,R.headers)}),$e=[...this.extractCitationDocuments(R.prompt)],Se=Zt(X.tools),Ye=this.buildRequestUrl(!0),{responseHeaders:we,value:je}=await g({url:Ye,headers:await this.getHeaders({betas:Ne,configHeaders:U,headers:R.headers,providerOptions:R.providerOptions}),body:this.transformRequestBody(X,Ne),failedResponseHandler:ct,successfulResponseHandler:D(Eo),abortSignal:R.abortSignal,fetch:this.config.fetch}),Me={unified:"other",raw:void 0},Ve={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,iterations:null},Fe={},Pe={},Ae={},K=null,Ee=void 0,ye=null,He=void 0,nt,De,G=null,Ce=!1,Ge=!1,Z=[],rt=!1,Ue,Oe=!1,We=void 0,te=this.generateId,ue=je.pipeThrough(new TransformStream({start(et){et.enqueue({type:"stream-start",warnings:me})},transform(et,Te){if(Oe)return;if(R.includeRawChunks)Te.enqueue({type:"raw",rawValue:et.rawValue});if(!et.success){Te.enqueue({type:"error",error:et.error});return}let ee=et.value;switch(ee.type){case"ping":return;case"content_block_start":{let J=ee.content_block,qe=J.type;if(qe==="fallback"){Te.enqueue({type:"custom",kind:"anthropic.fallback",providerMetadata:{anthropic:{type:"fallback",from:J.from,to:J.to}}});return}switch(We=qe,qe){case"text":if(W)return;Fe[ee.index]={type:"text",citations:[]},Te.enqueue({type:"text-start",id:String(ee.index)});return;case"thinking":Fe[ee.index]={type:"reasoning"},Te.enqueue({type:"reasoning-start",id:String(ee.index)});return;case"redacted_thinking":Fe[ee.index]={type:"reasoning"},Te.enqueue({type:"reasoning-start",id:String(ee.index),providerMetadata:{anthropic:{redactedData:J.data}}});return;case"compaction":if(Fe[ee.index]={type:"text",citations:[]},Te.enqueue({type:"text-start",id:String(ee.index),providerMetadata:{anthropic:{type:"compaction",...J.signature!=null&&{signature:J.signature}}}}),J.signature!=null&&J.content!=null&&J.content!=="")Te.enqueue({type:"text-delta",id:String(ee.index),delta:J.content});return;case"tool_use":if(W&&J.name==="json")Ce=!0,Fe[ee.index]={type:"text",citations:[]},Te.enqueue({type:"text-start",id:String(ee.index)});else if(J.toolset_name!=null){let be=vt(J.caller),Je=ae.toCustomToolName(J.toolset_name),_t=J.input&&Object.keys(J.input).length>0;Fe[ee.index]={type:"tool-call",toolCallId:J.id,toolName:Je,input:_t?JSON.stringify(J.input):"",firstDelta:!0,toolset:{name:J.toolset_name,memberName:J.name},...be&&{caller:be}},Te.enqueue({type:"tool-input-start",id:J.id,toolName:Je})}else{let be=vt(J.caller),Je=J.input&&Object.keys(J.input).length>0?JSON.stringify(J.input):"";Fe[ee.index]={type:"tool-call",toolCallId:J.id,toolName:J.name,input:Je,firstDelta:Je.length===0,...be&&{caller:be}},Te.enqueue({type:"tool-input-start",id:J.id,toolName:J.name})}return;case"server_tool_use":{let be=vt(J.caller);if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(J.name)){let Je=J.name==="text_editor_code_execution"||J.name==="bash_code_execution"?"code_execution":J.name,_t=J.name==="text_editor_code_execution"||J.name==="bash_code_execution"?J.name:J.name==="code_execution"?"programmatic-tool-call":void 0,tt=ae.toCustomToolName(Je),at=J.input!=null&&typeof J.input==="object"&&Object.keys(J.input).length>0?JSON.stringify(J.input):"";Fe[ee.index]={type:"tool-call",toolCallId:J.id,toolName:tt,input:at,providerExecuted:!0,...Se&&Je==="code_execution"?{dynamic:!0}:{},firstDelta:at.length===0,providerToolName:Je,providerToolInputType:_t,...be&&{caller:be}},Te.enqueue({type:"tool-input-start",id:J.id,toolName:tt,providerExecuted:!0,...Se&&Je==="code_execution"?{dynamic:!0}:{}})}else if(J.name==="tool_search_tool_regex"||J.name==="tool_search_tool_bm25"){Ae[J.id]=J.name;let Je=ae.toCustomToolName(J.name);Fe[ee.index]={type:"tool-call",toolCallId:J.id,toolName:Je,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:J.name,...be&&{caller:be}},Te.enqueue({type:"tool-input-start",id:J.id,toolName:Je,providerExecuted:!0})}else if(J.name==="advisor"){let Je=ae.toCustomToolName("advisor");Fe[ee.index]={type:"tool-call",toolCallId:J.id,toolName:Je,input:"{}",providerExecuted:!0,firstDelta:!0,providerToolName:J.name,...be&&{caller:be}},Te.enqueue({type:"tool-input-start",id:J.id,toolName:Je,providerExecuted:!0})}return}case"web_fetch_tool_result":if(J.content.type==="web_fetch_result")$e.push({title:J.content.content.title??J.content.url,mediaType:J.content.content.source.media_type}),Te.enqueue({type:"tool-result",toolCallId:J.tool_use_id,toolName:ae.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:J.content.url,retrievedAt:J.content.retrieved_at,content:{type:J.content.content.type,title:J.content.content.title,citations:J.content.content.citations,source:{type:J.content.content.source.type,mediaType:J.content.content.source.media_type,data:J.content.content.source.data}}},...st(J.caller)});else if(J.content.type==="web_fetch_tool_result_error")Te.enqueue({type:"tool-result",toolCallId:J.tool_use_id,toolName:ae.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:J.content.error_code},...st(J.caller)});return;case"web_search_tool_result":if(Array.isArray(J.content)){Te.enqueue({type:"tool-result",toolCallId:J.tool_use_id,toolName:ae.toCustomToolName("web_search"),result:J.content.map((be)=>({url:be.url,...be.title!=null?{title:be.title}:{},pageAge:be.page_age??null,encryptedContent:be.encrypted_content,type:be.type})),...st(J.caller)});for(let be of J.content)Ge=!0,Te.enqueue({type:"source",sourceType:"url",id:te(),url:be.url,...be.title!=null?{title:be.title}:{},providerMetadata:{anthropic:{pageAge:be.page_age??null}}})}else Te.enqueue({type:"tool-result",toolCallId:J.tool_use_id,toolName:ae.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:J.content.error_code},...st(J.caller)});return;case"code_execution_tool_result":if(J.content.type==="code_execution_result")Te.enqueue({type:"tool-result",toolCallId:J.tool_use_id,toolName:ae.toCustomToolName("code_execution"),result:{type:J.content.type,stdout:J.content.stdout,stderr:J.content.stderr,return_code:J.content.return_code,content:J.content.content??[]}});else if(J.content.type==="encrypted_code_execution_result")Te.enqueue({type:"tool-result",toolCallId:J.tool_use_id,toolName:ae.toCustomToolName("code_execution"),result:{type:J.content.type,encrypted_stdout:J.content.encrypted_stdout,stderr:J.content.stderr,return_code:J.content.return_code,content:J.content.content??[]}});else if(J.content.type==="code_execution_tool_result_error")Te.enqueue({type:"tool-result",toolCallId:J.tool_use_id,toolName:ae.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:J.content.error_code}});return;case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":Te.enqueue({type:"tool-result",toolCallId:J.tool_use_id,toolName:ae.toCustomToolName("code_execution"),result:J.content});return;case"tool_search_tool_result":{let be=Ae[J.tool_use_id];if(be==null){let Je=ae.toCustomToolName("tool_search_tool_bm25"),_t=ae.toCustomToolName("tool_search_tool_regex");if(Je!=="tool_search_tool_bm25")be="tool_search_tool_bm25";else if(_t!=="tool_search_tool_regex")be="tool_search_tool_regex";else be="tool_search_tool_regex"}if(J.content.type==="tool_search_tool_search_result")Te.enqueue({type:"tool-result",toolCallId:J.tool_use_id,toolName:ae.toCustomToolName(be),result:J.content.tool_references.map((Je)=>({type:Je.type,toolName:Je.tool_name}))});else Te.enqueue({type:"tool-result",toolCallId:J.tool_use_id,toolName:ae.toCustomToolName(be),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:J.content.error_code}});return}case"advisor_tool_result":{let be=ae.toCustomToolName("advisor");if(J.content.type==="advisor_result")Te.enqueue({type:"tool-result",toolCallId:J.tool_use_id,toolName:be,result:{type:"advisor_result",text:J.content.text,...J.content.stop_reason!=null&&{stopReason:J.content.stop_reason}}});else if(J.content.type==="advisor_redacted_result")Te.enqueue({type:"tool-result",toolCallId:J.tool_use_id,toolName:be,result:{type:"advisor_redacted_result",encryptedContent:J.content.encrypted_content,...J.content.stop_reason!=null&&{stopReason:J.content.stop_reason}}});else Te.enqueue({type:"tool-result",toolCallId:J.tool_use_id,toolName:be,isError:!0,result:{type:"advisor_tool_result_error",errorCode:J.content.error_code}});return}case"mcp_tool_use":Pe[J.id]={type:"tool-call",toolCallId:J.id,toolName:J.name,input:JSON.stringify(J.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:J.server_name}}},Te.enqueue(Pe[J.id]);return;case"mcp_tool_result":Te.enqueue({type:"tool-result",toolCallId:J.tool_use_id,toolName:Pe[J.tool_use_id].toolName,isError:J.is_error,result:J.content,dynamic:!0,providerMetadata:Pe[J.tool_use_id].providerMetadata});return;default:throw Error(`Unsupported content block type: ${qe}`)}}case"content_block_stop":if(Fe[ee.index]!=null){let J=Fe[ee.index];switch(J.type){case"text":Te.enqueue({type:"text-end",id:String(ee.index),...J.citations.length>0&&{citations:J.citations.map((qe)=>Et(qe,$e)),providerMetadata:{anthropic:{citations:J.citations}}}});break;case"reasoning":Te.enqueue({type:"reasoning-end",id:String(ee.index)});break;case"tool-call":if(!(W&&J.toolName==="json")){if(J.toolset!=null){let be={};try{be=J.input===""?{}:Q(J.input)}catch{be=void 0}J.input=be===void 0?J.input:JSON.stringify(Xt({memberName:J.toolset.memberName,input:be})),Te.enqueue({type:"tool-input-delta",id:J.toolCallId,delta:J.input})}Te.enqueue({type:"tool-input-end",id:J.toolCallId});let qe=J.input===""?"{}":J.input;if(J.providerToolName==="code_execution")try{let be=Q(qe);if(be!=null&&typeof be==="object"&&"code"in be&&!("type"in be))qe=JSON.stringify({type:"programmatic-tool-call",...be})}catch{}Te.enqueue({type:"tool-call",toolCallId:J.toolCallId,toolName:J.toolName,input:qe,providerExecuted:J.providerExecuted,...Se&&J.providerToolName==="code_execution"?{dynamic:!0}:{},...(J.caller||J.toolset)&&{providerMetadata:{anthropic:{...J.toolset&&{toolsetName:J.toolset.name},...J.caller&&{caller:J.caller}}}}})}}delete Fe[ee.index]}We=void 0;return;case"content_block_delta":{let J=ee.delta.type;switch(J){case"text_delta":if(W)return;Te.enqueue({type:"text-delta",id:String(ee.index),delta:ee.delta.text});return;case"thinking_delta":Te.enqueue({type:"reasoning-delta",id:String(ee.index),delta:ee.delta.thinking});return;case"signature_delta":if(We==="thinking")Te.enqueue({type:"reasoning-delta",id:String(ee.index),delta:"",providerMetadata:{anthropic:{signature:ee.delta.signature}}});return;case"compaction_delta":if(ee.delta.content!=null)Te.enqueue({type:"text-delta",id:String(ee.index),delta:ee.delta.content});return;case"input_json_delta":{let qe=Fe[ee.index],be=ee.delta.partial_json;if(be.length===0)return;if(Ce){if(qe?.type!=="text")return;Te.enqueue({type:"text-delta",id:String(ee.index),delta:be})}else{if(qe?.type!=="tool-call")return;if(qe.toolset!=null){qe.input+=be;return}if(qe.firstDelta&&qe.providerToolInputType!=null)be=`{"type": "${qe.providerToolInputType}",${be.substring(1)}`;Te.enqueue({type:"tool-input-delta",id:qe.toolCallId,delta:be}),qe.input+=be,qe.firstDelta=!1}return}case"citations_delta":{let qe=ee.delta.citation,be=Fe[ee.index];if(be?.type==="text")be.citations.push(qe);if(qe.type==="web_search_result_location")Z.push(qe);else{let Je=Ot(qe,$e,te);if(Je)Te.enqueue(Je)}return}default:throw Error(`Unsupported delta type: ${J}`)}}case"message_start":if(rt){if(Ue===ee.message.id)return;Oe=!0,Te.enqueue({type:"error",error:new A({data:ee,message:`Received message_start for message ${JSON.stringify(ee.message.id)} while message ${JSON.stringify(Ue)} is still open.`})});return}if(rt=!0,Ue=ee.message.id,Ve.input_tokens=ee.message.usage.input_tokens,Ve.cache_read_input_tokens=ee.message.usage.cache_read_input_tokens??0,Ve.cache_creation_input_tokens=ee.message.usage.cache_creation_input_tokens??0,Ee={...ee.message.usage},ee.message.input_transformations!=null)nt=ee.message.input_transformations;if(ee.message.container!=null)G={expiresAt:ee.message.container.expires_at,id:ee.message.container.id,skills:null};if(ee.message.stop_reason!=null)Me={unified:Nt({finishReason:ee.message.stop_reason,isJsonResponseFromTool:Ce}),raw:ee.message.stop_reason};if(Te.enqueue({type:"response-metadata",id:ee.message.id??void 0,modelId:ee.message.model??void 0}),Te.enqueue({type:"custom",kind:"anthropic.message_start",providerMetadata:{anthropic:{id:ee.message.id??null,model:ee.message.model??null,usage:Ee}}}),ee.message.content!=null)for(let J=0;J<ee.message.content.length;J++){let qe=ee.message.content[J];if(qe.type==="tool_use"){let be=vt(qe.caller);Te.enqueue({type:"tool-input-start",id:qe.id,toolName:qe.name});let Je=JSON.stringify(qe.input??{});Te.enqueue({type:"tool-input-delta",id:qe.id,delta:Je}),Te.enqueue({type:"tool-input-end",id:qe.id}),Te.enqueue({type:"tool-call",toolCallId:qe.id,toolName:qe.name,input:Je,...be&&{providerMetadata:{anthropic:{caller:be}}}})}}return;case"message_delta":if(ee.usage.input_tokens!=null&&Ve.input_tokens!==ee.usage.input_tokens)Ve.input_tokens=ee.usage.input_tokens;if(Ve.output_tokens=ee.usage.output_tokens,ee.usage.output_tokens_details!=null)Ve.output_tokens_details=ee.usage.output_tokens_details;if(ee.usage.cache_read_input_tokens!=null)Ve.cache_read_input_tokens=ee.usage.cache_read_input_tokens;if(ee.usage.cache_creation_input_tokens!=null)Ve.cache_creation_input_tokens=ee.usage.cache_creation_input_tokens;if(ee.usage.iterations!=null)Ve.iterations=ee.usage.iterations;if(Me={unified:Nt({finishReason:ee.delta.stop_reason,isJsonResponseFromTool:Ce}),raw:ee.delta.stop_reason??void 0},ye=ee.delta.stop_sequence??null,He=Qt(ee.delta.stop_details),G=ee.delta.container!=null?{expiresAt:ee.delta.container.expires_at,id:ee.delta.container.id,skills:ee.delta.container.skills?.map((J)=>({type:J.type,skillId:J.skill_id,version:J.version}))??null}:null,ee.context_management)K=Yt(ee.context_management);if(ee.input_transformations!=null)nt=ee.input_transformations;if(ee.delta.safeguard_results!=null)De=ee.delta.safeguard_results;Ee={...Ee,...ee.usage};return;case"message_stop":{rt=!1,Ue=void 0;let J={usage:Ee??null,stopSequence:ye,...He!=null?{stopDetails:He}:{},...nt!=null?{inputTransformations:nt}:{},...De!=null?{safeguardResults:De}:{},iterations:Ve.iterations?Ve.iterations.map((be)=>({type:be.type,...be.model!=null?{model:be.model}:{},inputTokens:be.input_tokens,outputTokens:be.output_tokens,...be.cache_creation_input_tokens?{cacheCreationInputTokens:be.cache_creation_input_tokens}:{},...be.cache_read_input_tokens?{cacheReadInputTokens:be.cache_read_input_tokens}:{}})):null,container:G,contextManagement:K},qe={anthropic:J};if(fe&&se!=="anthropic")qe[se]=J;if(!Ge)for(let be of Z){let Je=Ot(be,$e,te);if(Je)Te.enqueue(Je)}Z.length=0,Te.enqueue({type:"finish",finishReason:Me,usage:Ut({usage:Ve,rawUsage:Ee}),providerMetadata:qe});return}case"error":Te.enqueue({type:"error",error:Wn(ee.error)});return;default:throw Error(`Unsupported chunk type: ${ee}`)}}})),Qe=!1,gt=!1,yt,[bt,kt]=ue.pipeThrough(new TransformStream({transform(et,Te){switch(et.type){case"response-metadata":Qe=!1;break;case"finish":Qe=!1,yt=et;break;case"error":gt=!0;break;case"text-delta":case"reasoning-delta":case"tool-input-delta":Qe||=et.delta.length>0;break;case"tool-call":Qe=!0}Te.enqueue(et)},flush(et){if(Qe&&!gt)et.enqueue({type:"finish",finishReason:{unified:"interrupted",raw:void 0},usage:yt?.usage??{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0}},...yt?.providerMetadata!=null?{providerMetadata:yt.providerMetadata}:{}})}})).tee(),pt=bt.getReader();try{await pt.read();let et=await pt.read();if(et.value?.type==="raw")et=await pt.read();if(et.value?.type==="error"){let Te=et.value.error;if(!ot(Te))throw Error("Expected a normalized Anthropic stream error");throw new v({message:Te.message,url:Ye,requestBodyValues:X,statusCode:Te.statusCode??500,responseHeaders:we,responseBody:JSON.stringify(Te.data),isRetryable:Te.isRetryable??!1})}}finally{pt.cancel().catch(()=>{}),pt.releaseLock()}return{stream:kt,request:{body:X},response:{headers:we}}}};function Gn(m){if(m.includes("claude-sonnet-5-5"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!0,rejectsThinkingDisabled:!0,rejectsBudgetThinking:!0,rejectsForcedToolUse:!0,supportsBetweenToolsThinking:!0,isKnownModel:!0};else if(m.includes("claude-opus-5-5"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!0,rejectsThinkingDisabled:!0,rejectsBudgetThinking:!0,rejectsForcedToolUse:!0,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(m.includes("claude-haiku-5-5"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!0,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!0,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(m.includes("claude-opus-5"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!0,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(m.includes("claude-fable-5-1"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!0,rejectsBudgetThinking:!0,rejectsForcedToolUse:!0,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(m.includes("claude-fable-5"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!0,rejectsBudgetThinking:!0,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(m.includes("claude-opus-4-8")||m.includes("claude-opus-4-7")||m.includes("claude-sonnet-5"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(m.includes("claude-sonnet-4-6")||m.includes("claude-opus-4-6"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(m.includes("claude-sonnet-4-5")||m.includes("claude-opus-4-5")||m.includes("claude-haiku-4-5"))return{maxOutputTokens:64000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(m.includes("claude-opus-4-1"))return{maxOutputTokens:32000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(/claude-sonnet-4(?:-|@)/.test(m))return{maxOutputTokens:64000,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(/claude-opus-4(?:-|@)/.test(m))return{maxOutputTokens:32000,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(m.includes("claude-3-haiku"))return{maxOutputTokens:4096,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!0};else if(/claude-(?:instant(?:-|$)|v?2(?=$|[-.:])|3(?=$|[-.]))/.test(m))return{maxOutputTokens:4096,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!1};else if(m.includes("claude-"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,rejectsThinkingDisabledAboveHighEffort:!0,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!1};else return{maxOutputTokens:4096,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,rejectsThinkingDisabledAboveHighEffort:!1,rejectsThinkingDisabled:!1,rejectsBudgetThinking:!1,rejectsForcedToolUse:!1,supportsBetweenToolsThinking:!1,isKnownModel:!1}}function Zt(m){if(!m)return!1;let R=!1,U=!1;for(let X of m){if("type"in X&&(X.type==="web_fetch_20260209"||X.type==="web_fetch_20260318"||X.type==="web_search_20260209"||X.type==="web_search_20260318")){R=!0;continue}if("type"in X&&(X.type==="code_execution_20250522"||X.type==="code_execution_20250825"||X.type==="code_execution_20260120")){U=!0;break}}return R&&!U}function Zn({reasoning:m,modelId:R,supportsAdaptiveThinking:U,supportsXhighEffort:X,rejectsThinkingDisabled:me,supportsBetweenToolsThinking:Ne,maxOutputTokensForModel:W,warnings:ae}){if(!H(m))return;if(m==="none"){if(Ne)return{thinking:{type:"between_tools"}};if(me)return ae.push({type:"compatibility",feature:"reasoning",details:`reasoning 'none' is not supported by ${R}; it always uses adaptive thinking. Using effort 'low' to minimize thinking instead.`}),{effort:"low"};return{thinking:{type:"disabled"}}}if(U)return{thinking:{type:"adaptive",display:"summarized"},effort:ke({reasoning:m,effortMap:{minimal:"low",low:"low",medium:"medium",high:"high",xhigh:X?"xhigh":"max",max:"max"},warnings:ae})};let se=it({reasoning:m,maxOutputTokens:W,maxReasoningBudget:W,warnings:ae});if(se==null)return;return{thinking:{type:"enabled",budgetTokens:se}}}function Yt(m){return m?{appliedEdits:m.applied_edits.map((R)=>{switch(R.type){case"clear_tool_uses_20250919":return{type:R.type,clearedToolUses:R.cleared_tool_uses,clearedInputTokens:R.cleared_input_tokens};case"clear_thinking_20251015":return{type:R.type,clearedThinkingTurns:R.cleared_thinking_turns,clearedInputTokens:R.cleared_input_tokens};case"compact_20260112":return{type:R.type}}}).filter((R)=>R!==void 0)}:null}function Qt(m){if(m==null)return;return{type:m.type,...m.category!=null?{category:m.category}:{},...m.explanation!=null?{explanation:m.explanation}:{},...m.recommended_model!=null?{recommendedModel:m.recommended_model}:{}}}var Yn=/^[A-Za-z0-9_-]{1,64}$/,eo=i(()=>s(t({anthropicBeta:o(e()).optional()}))),vo=()=>t({id:e(),type:n("message_batch"),processing_status:e(),request_counts:t({processing:r(),succeeded:r(),errored:r(),canceled:r(),expired:r()}),created_at:e(),expires_at:e(),archived_at:e().nullish(),cancel_initiated_at:e().nullish(),ended_at:e().nullish(),results_url:e().nullish()}),Bt=i(()=>s(vo())),Qn=i(()=>s(t({data:o(vo()),has_more:c(),last_id:e().nullish()}))),er=new Set(["advisor_tool_result","bash_code_execution_tool_result","code_execution_tool_result","compaction","container_upload","fallback","mcp_tool_result","mcp_tool_use","redacted_thinking","server_tool_use","text","text_editor_code_execution_tool_result","thinking","tool_search_tool_result","tool_use","web_fetch_tool_result","web_search_tool_result"]),tr=i(()=>s(f("type",[t({type:n("succeeded"),message:w()}),t({type:n("errored"),error:t({type:n("error"),error:t({type:e(),message:e()}),request_id:e().nullish()})}),t({type:n("canceled")}),t({type:n("expired")})]))),or=i(()=>s(t({custom_id:e(),result:w()})));function nr(m){for(let R of m){let U=R.type;if(U!=="text")throw new u({functionality:`batch request type: ${U}`,message:`The Anthropic Message Batches API does not support batch requests with type "${U}".`})}}var rr=class{constructor(m){this.options=m,this.specificationVersion="v4",this.provider=m.provider,this.supportedUrls=m.supportedUrls,this.generateId=m.config.generateId??C}async doStartBatch({requests:m,providerOptions:R,headers:U,abortSignal:X,webhookUrl:me}){nr(m),ar(m);let Ne=new Set(await to({provider:this.options.config.provider,providerOptions:R})),W=new Set(Ne),ae=[],se=me==null?[]:[{warning:{type:"unsupported",feature:"webhookUrl",details:"The Anthropic Message Batches API does not support completion webhooks."}}];for(let $e of m){if((await to({provider:this.options.config.provider,providerOptions:$e.options.providerOptions})).length>0)throw new u({functionality:"per-request providerOptions.anthropic.anthropicBeta",message:`Anthropic Message Batches do not support per-request betas (request "${$e.id}"). Set providerOptions.anthropic.anthropicBeta on startBatch instead.`});let Se=await xo.prepareRequest({modelId:$e.modelId,config:this.options.config,options:{...$e.options,stream:!1,userSuppliedBetas:new Set(Ne)}});if(Se.usesJsonResponseTool)throw new u({functionality:"batch responseFormat JSON-tool fallback",message:`Anthropic Message Batches cannot decode the JSON-tool structured-output fallback (request "${$e.id}") because batch results are retrieved independently of the start call. Use a model that supports native output_format structured outputs.`});let Ye=$e.options.tools?.find((je)=>je.type==="provider"&&Se.toolNameMapping.toProviderToolName(je.name)!==je.name);if(Ye!=null)throw new u({functionality:"aliased provider tool names in batches",message:`Anthropic Message Batches cannot restore the custom provider-tool name "${Ye.name}" when results are retrieved independently of the start call (request "${$e.id}"). Use the provider's canonical tool name.`});let we=this.options.config.transformRequestBody?.(Se.args,Se.betas)??Se.args;ir({body:we,requestId:$e.id}),ae.push({custom_id:$e.id,params:we});for(let je of Se.betas)W.add(je);for(let je of Se.warnings)se.push({requestId:$e.id,warning:je})}let{value:fe}=await g({url:this.getBatchUrl(""),headers:await this.getStartBatchHeaders({betas:W,headers:U}),body:{requests:ae},failedResponseHandler:ct,successfulResponseHandler:p(Bt),abortSignal:X,fetch:this.options.config.fetch});return{batchId:fe.id,...Tt(fe),warnings:se}}async doGetBatchStatus(m){return Tt(await this.retrieveBatch(m))}async doCancelBatch(m){return await g({url:this.getBatchUrl(`/${encodeURIComponent(m.batchId)}/cancel`),headers:await this.getBatchHeaders(m.headers),body:{},failedResponseHandler:ct,successfulResponseHandler:p(Bt),abortSignal:m.abortSignal,fetch:this.options.config.fetch}),{}}async doListBatches(m){let R=new URL(this.getBatchUrl(""));if(m.limit!=null)R.searchParams.set("limit",String(m.limit));if(m.cursor!=null)R.searchParams.set("after_id",m.cursor);let{value:U}=await P({url:R.toString(),validateUrl:!1,headers:await this.getBatchHeaders(m.headers),failedResponseHandler:ct,successfulResponseHandler:p(Qn),abortSignal:m.abortSignal,fetch:this.options.config.fetch});return{batches:U.data.map((X)=>({batchId:X.id,...Tt(X)})),...U.has_more&&U.last_id!=null?{nextCursor:U.last_id}:{}}}async doGetBatchResults(m){let R=await this.retrieveBatch(m);if(Tt(R).status==="pending")throw new b({argument:"batchId",message:`Anthropic batch "${m.batchId}" is not complete.`});if(R.archived_at!=null)throw new b({argument:"batchId",message:`Anthropic batch "${m.batchId}" results are no longer available.`});if(R.results_url==null)throw new A({data:R,message:`Anthropic batch "${m.batchId}" completed without batch output.`});let{value:U}=await P({url:R.results_url,validateUrl:!0,credentialedOrigin:this.options.config.baseURL,trustedOrigin:this.options.config.baseURL,headers:await this.getBatchHeaders(m.headers),failedResponseHandler:ct,successfulResponseHandler:_e(or,{maxLineBytes:this.options.maxLineBytes}),abortSignal:m.abortSignal,fetch:this.options.config.fetch});return ie(this.iterateBatchResults(U))}async retrieveBatch(m){let{value:R}=await P({url:this.getBatchUrl(`/${encodeURIComponent(m.batchId)}`),validateUrl:!1,headers:await this.getBatchHeaders(m.headers),failedResponseHandler:ct,successfulResponseHandler:p(Bt),abortSignal:m.abortSignal,fetch:this.options.config.fetch});return R}async*iterateBatchResults(m){for await(let R of m)yield await cr(R,this.generateId)}getBatchUrl(m){return`${this.options.config.baseURL}/messages/batches${m}`}async getStartBatchHeaders({betas:m,headers:R}){return d(Le(await this.getBatchHeaders(R)),{"anthropic-beta":m.size>0?Array.from(m).join(","):void 0})}async getBatchHeaders(m){return d(this.options.config.headers?await _(this.options.config.headers):void 0,m)}};async function to({provider:m,providerOptions:R}){let U=m.split(".")[0],X=await h({provider:"anthropic",providerOptions:R,schema:eo}),me=U!=="anthropic"?await h({provider:U,providerOptions:R,schema:eo}):void 0;return Object.assign({},X??{},me??{}).anthropicBeta??[]}function ar(m){let R=new Set;for(let U of m){if(!Yn.test(U.id))throw new b({argument:"requests",message:`Anthropic batch request ID "${U.id}" must match ^[A-Za-z0-9_-]{1,64}$.`});if(R.has(U.id))throw new b({argument:"requests",message:`Anthropic batch request IDs must be unique; duplicate ID "${U.id}".`});R.add(U.id)}}function ir({body:m,requestId:R}){if(m.speed!=null)throw new u({functionality:"providerOptions.anthropic.speed",message:`Anthropic Message Batches do not support speed (request "${R}").`});if(Array.isArray(m.fallbacks)&&m.fallbacks.some((U)=>U!=null&&typeof U==="object"&&("speed"in U)&&U.speed!=null))throw new u({functionality:"providerOptions.anthropic.fallbacks[].speed",message:`Anthropic Message Batches do not support fallback speed (request "${R}").`})}function Tt(m){let R=lr(m.request_counts);return{status:sr(m.processing_status),rawStatus:m.processing_status,...R!=null?{requestCounts:R}:{},createdAt:m.created_at,expiresAt:m.expires_at,providerMetadata:{anthropic:{archivedAt:m.archived_at??null,cancelInitiatedAt:m.cancel_initiated_at??null,endedAt:m.ended_at??null,requestCounts:m.request_counts,resultsUrl:m.results_url??null}}}}function sr(m){switch(m){case"ended":return"completed";default:return"pending"}}function lr(m){return ge({total:m.processing+m.succeeded+m.errored+m.canceled+m.expired,pending:m.processing,completed:m.succeeded,failed:m.errored+m.canceled+m.expired})}async function cr(m,R){let U=await N({value:m.result,schema:tr});if(!U.success)return oo(m.custom_id);let X=U.value;switch(X.type){case"canceled":return{type:"text",id:m.custom_id,status:"cancelled"};case"expired":return{type:"text",id:m.custom_id,status:"expired"};case"errored":{let me=X.error.request_id;return{type:"text",id:m.custom_id,status:"failed",error:{message:X.error.error.message,type:X.error.error.type},...me!=null?{providerMetadata:{anthropic:{requestId:me}}}:{}}}case"succeeded":{let me=await ur(X.message);if(me==null)return oo(m.custom_id);return{type:"text",id:m.custom_id,status:"succeeded",result:pr(me,R)}}}}function oo(m){return{type:"text",id:m,status:"failed",error:{message:"Anthropic returned an invalid Message batch result.",code:"invalid_response"}}}async function ur(m){let R=await N({value:m,schema:St});if(R.success)return R.value;if(!j(m)||!Array.isArray(m.content))return;let U=[];for(let me of m.content){let Ne=await N({value:{...m,content:[me]},schema:St});if(Ne.success){let[W]=Ne.value.content;if(W!=null)U.push(W)}else if(!j(me)||typeof me.type!=="string"||er.has(me.type))return}let X=await N({value:{...m,content:U},schema:St});return X.success?X.value:void 0}function pr(m,R){let U=[],X={},me={},Ne=m.content.some((W)=>W.type==="web_search_tool_result"&&Array.isArray(W.content)&&W.content.length>0);for(let W of m.content)switch(W.type){case"text":let ae=W.citations;U.push({type:"text",text:W.text,...ae!=null&&ae.length>0&&{citations:ae.map((se)=>Et(se,[]))},...ae!=null&&ae.length>0&&{providerMetadata:{anthropic:{citations:ae}}}});for(let se of W.citations??[])if(se.type==="web_search_result_location"&&!Ne){let fe=Ot(se,[],R);if(fe)U.push(fe)}break;case"thinking":U.push({type:"reasoning",text:W.thinking,providerMetadata:{anthropic:{signature:W.signature}}});break;case"redacted_thinking":U.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:W.data}}});break;case"container_upload":U.push({type:"custom",kind:"anthropic.container_upload",providerMetadata:{anthropic:{fileId:W.file_id}}});break;case"compaction":if(!W.content)break;U.push({type:"text",text:W.content,providerMetadata:{anthropic:{type:"compaction",...W.signature!=null&&{signature:W.signature}}}});break;case"tool_use":U.push({type:"tool-call",toolCallId:W.id,toolName:W.name,input:JSON.stringify(W.input),...Ct(W.caller)});break;case"server_tool_use":{let se=W.name==="bash_code_execution"||W.name==="text_editor_code_execution",fe=se||W.name==="code_execution",$e=se?"code_execution":W.name;if(W.name==="tool_search_tool_bm25"||W.name==="tool_search_tool_regex")me[W.id]=W.name;U.push({type:"tool-call",toolCallId:W.id,toolName:$e,input:JSON.stringify(se?{type:W.name,...W.input}:W.name==="code_execution"&&W.input!=null&&("code"in W.input)&&!("type"in W.input)?{type:"programmatic-tool-call",...W.input}:W.input),providerExecuted:!0,...fe?{dynamic:!0}:{},...Ct(W.caller)});break}case"mcp_tool_use":{let se={type:"tool-call",toolCallId:W.id,toolName:W.name,input:JSON.stringify(W.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{serverName:W.server_name,type:"mcp-tool-use"}}};X[W.id]=se,U.push(se);break}case"mcp_tool_result":{let se=X[W.tool_use_id];U.push({type:"tool-result",toolCallId:W.tool_use_id,toolName:se?.toolName??"mcp",isError:W.is_error,result:W.content,dynamic:!0,...se?.providerMetadata!=null&&{providerMetadata:se.providerMetadata}});break}case"web_fetch_tool_result":U.push({type:"tool-result",toolCallId:W.tool_use_id,toolName:"web_fetch",...W.content.type==="web_fetch_tool_result_error"?{isError:!0,result:{errorCode:W.content.error_code,type:W.content.type}}:{result:{content:{citations:W.content.content.citations,source:{data:W.content.content.source.data,mediaType:W.content.content.source.media_type,type:W.content.content.source.type},title:W.content.content.title,type:W.content.content.type},retrievedAt:W.content.retrieved_at,type:W.content.type,url:W.content.url}},...Ct(W.caller)});break;case"web_search_tool_result":if(U.push({type:"tool-result",toolCallId:W.tool_use_id,toolName:"web_search",...Array.isArray(W.content)?{result:W.content.map((se)=>({encryptedContent:se.encrypted_content,pageAge:se.page_age??null,...se.title!=null?{title:se.title}:{},type:se.type,url:se.url}))}:{isError:!0,result:{errorCode:W.content.error_code,type:W.content.type}},...Ct(W.caller)}),Array.isArray(W.content))for(let se of W.content)U.push({type:"source",sourceType:"url",id:R(),url:se.url,...se.title!=null?{title:se.title}:{},providerMetadata:{anthropic:{pageAge:se.page_age??null}}});break;case"code_execution_tool_result":U.push({type:"tool-result",toolCallId:W.tool_use_id,toolName:"code_execution",...W.content.type==="code_execution_tool_result_error"?{isError:!0,result:{errorCode:W.content.error_code,type:W.content.type}}:{result:W.content}});break;case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":U.push({type:"tool-result",toolCallId:W.tool_use_id,toolName:"code_execution",result:W.content});break;case"tool_search_tool_result":{let se=me[W.tool_use_id]??"tool_search_tool_regex";U.push({type:"tool-result",toolCallId:W.tool_use_id,toolName:se,...W.content.type==="tool_search_tool_result_error"?{isError:!0,result:{errorCode:W.content.error_code,type:W.content.type}}:{result:W.content.tool_references.map((fe)=>({toolName:fe.tool_name,type:fe.type}))}});break}case"advisor_tool_result":if(W.content.type==="advisor_result")U.push({type:"tool-result",toolCallId:W.tool_use_id,toolName:"advisor",result:{type:W.content.type,text:W.content.text,...W.content.stop_reason!=null?{stopReason:W.content.stop_reason}:{}}});else if(W.content.type==="advisor_redacted_result")U.push({type:"tool-result",toolCallId:W.tool_use_id,toolName:"advisor",result:{type:W.content.type,encryptedContent:W.content.encrypted_content,...W.content.stop_reason!=null?{stopReason:W.content.stop_reason}:{}}});else U.push({type:"tool-result",toolCallId:W.tool_use_id,toolName:"advisor",isError:!0,result:{errorCode:W.content.error_code,type:W.content.type}});break;case"fallback":U.push({type:"custom",kind:"anthropic.fallback",providerMetadata:{anthropic:{type:"fallback",from:W.from,to:W.to}}})}return{content:U,finishReason:{unified:Nt({finishReason:m.stop_reason}),raw:m.stop_reason??void 0},usage:Ut({usage:m.usage}),response:{id:m.id??void 0,modelId:m.model??void 0},warnings:[],providerMetadata:{anthropic:dr(m)}}}function Ct(m){return m==null?{}:{providerMetadata:{anthropic:{caller:{type:m.type,toolId:m.tool_id}}}}}function dr(m){let R=hr(m.stop_details);return{usage:m.usage,stopSequence:m.stop_sequence??null,...R!=null?{stopDetails:R}:{},...m.input_transformations!=null?{inputTransformations:m.input_transformations}:{},...m.safeguard_results!=null?{safeguardResults:m.safeguard_results}:{},iterations:m.usage.iterations?m.usage.iterations.map((U)=>({type:U.type,...U.model!=null?{model:U.model}:{},inputTokens:U.input_tokens,outputTokens:U.output_tokens,...U.cache_creation_input_tokens?{cacheCreationInputTokens:U.cache_creation_input_tokens}:{},...U.cache_read_input_tokens?{cacheReadInputTokens:U.cache_read_input_tokens}:{}})):null,container:m.container?{expiresAt:m.container.expires_at,id:m.container.id,skills:m.container.skills?.map((U)=>({type:U.type,skillId:U.skill_id,version:U.version}))??null}:null,contextManagement:_r(m.context_management)}}function _r(m){return m?{appliedEdits:m.applied_edits.map((R)=>{switch(R.type){case"clear_tool_uses_20250919":return{type:R.type,clearedToolUses:R.cleared_tool_uses,clearedInputTokens:R.cleared_input_tokens};case"clear_thinking_20251015":return{type:R.type,clearedThinkingTurns:R.cleared_thinking_turns,clearedInputTokens:R.cleared_input_tokens};case"compact_20260112":return{type:R.type}}})}:null}function hr(m){if(m==null)return;return{type:m.type,...m.category!=null?{category:m.category}:{},...m.explanation!=null?{explanation:m.explanation}:{},...m.recommended_model!=null?{recommendedModel:m.recommended_model}:{}}}var mr=i(()=>s(t({command:e(),restart:c().optional()}))),no=re({id:"anthropic.bash_20241022",inputSchema:mr});function gr(m={}){let{execute:R,...U}=m;if(R===void 0)return no({...U,execute:async({command:X},{abortSignal:me,experimental_sandbox:Ne})=>{if(!Ne)throw Error("Sandbox session is not available");return await Ne.run({command:X,abortSignal:me})}});return no({...U,...R===null?{}:{execute:R}})}var fr=i(()=>s(t({command:e(),restart:c().optional()}))),ro=re({id:"anthropic.bash_20250124",inputSchema:fr});function yr(m={}){let{execute:R,...U}=m;if(R===void 0)return ro({...U,execute:async({command:X},{abortSignal:me,experimental_sandbox:Ne})=>{if(!Ne)throw Error("Sandbox session is not available");return await Ne.run({command:X,abortSignal:me})}});return ro({...U,...R===null?{}:{execute:R}})}var br=i(()=>s(t({action:a(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:o(r().int()).optional(),text:e().optional()}))),xr=re({id:"anthropic.computer_20241022",inputSchema:br}),vr=i(()=>s(t({action:a(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:ce([r().int(),r().int()]).optional(),duration:r().optional(),scroll_amount:r().optional(),scroll_direction:a(["up","down","left","right"]).optional(),start_coordinate:ce([r().int(),r().int()]).optional(),text:e().optional()}))),kr=re({id:"anthropic.computer_20250124",inputSchema:vr}),wr=i(()=>s(t({action:a(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot","zoom"]),coordinate:ce([r().int(),r().int()]).optional(),duration:r().optional(),region:ce([r().int(),r().int(),r().int(),r().int()]).optional(),scroll_amount:r().optional(),scroll_direction:a(["up","down","left","right"]).optional(),start_coordinate:ce([r().int(),r().int()]).optional(),text:e().optional()}))),jr=re({id:"anthropic.computer_20251124",inputSchema:wr}),Tr=i(()=>s(f("command",[t({command:n("view"),path:e(),view_range:ce([r(),r()]).optional()}),t({command:n("create"),path:e(),file_text:e()}),t({command:n("str_replace"),path:e(),old_str:e(),new_str:e()}),t({command:n("insert"),path:e(),insert_line:r(),insert_text:e()}),t({command:n("delete"),path:e()}),t({command:n("rename"),old_path:e(),new_path:e()})]))),Cr=re({id:"anthropic.memory_20250818",inputSchema:Tr}),Sr=i(()=>s(t({command:a(["view","create","str_replace","insert","undo_edit"]),path:e(),file_text:e().optional(),insert_line:r().int().optional(),new_str:e().optional(),insert_text:e().optional(),old_str:e().optional(),view_range:o(r().int()).optional()}))),Nr=re({id:"anthropic.text_editor_20241022",inputSchema:Sr}),Or=i(()=>s(t({command:a(["view","create","str_replace","insert","undo_edit"]),path:e(),file_text:e().optional(),insert_line:r().int().optional(),new_str:e().optional(),insert_text:e().optional(),old_str:e().optional(),view_range:o(r().int()).optional()}))),Ir=re({id:"anthropic.text_editor_20250124",inputSchema:Or}),Ar=i(()=>s(t({command:a(["view","create","str_replace","insert"]),path:e(),file_text:e().optional(),insert_line:r().int().optional(),new_str:e().optional(),insert_text:e().optional(),old_str:e().optional(),view_range:o(r().int()).optional()}))),Rr=re({id:"anthropic.text_editor_20250429",inputSchema:Ar}),Br=i(()=>s(o(t({type:n("tool_reference"),toolName:e()})))),Er=i(()=>s(t({query:e(),limit:r().optional()}))),Mr=k({id:"anthropic.tool_search_bm25_20251119",inputSchema:Er,outputSchema:Br,supportsDeferredResults:!0}),Ur=(m={})=>Mr(m),$r={advisor_20260301:Po,bash_20241022:gr,bash_20250124:yr,codeExecution_20250522:Nn,codeExecution_20250825:An,codeExecution_20260120:En,computer_20241022:xr,computer_20250124:kr,computer_20251124:jr,computerToolset_20260801:Jo,memory_20250818:Cr,textEditor_20241022:Nr,textEditor_20250124:Ir,textEditor_20250429:Rr,textEditor_20250728:Vo,webFetch_20250910:jn,webFetch_20260209:xn,webFetch_20260318:mn,webSearch_20250305:cn,webSearch_20260209:rn,webSearch_20260318:Qo,toolSearchRegex_20251119:$n,toolSearchBm25_20251119:Ur},qr=i(()=>s(t({id:e(),display_title:e().nullish(),name:e().nullish(),description:e().nullish(),latest_version:e().nullish(),source:e(),created_at:e(),updated_at:e()})));i(()=>s(t({data:o(t({version:e()}))})));var Dr=i(()=>s(t({type:e(),skill_id:e(),name:e().nullish(),description:e().nullish()}))),Hr=class{get provider(){return this.config.provider}constructor(m){this.config=m,this.specificationVersion="v4"}async getHeaders(){return d(await _(this.config.headers),{"anthropic-beta":"skills-2025-10-02"})}async fetchVersionMetadata({skillId:m,version:R}){let{value:U}=await P({url:`${this.config.baseURL}/skills/${de(m)}/versions/${de(R)}`,validateUrl:!1,headers:await this.getHeaders(),failedResponseHandler:ct,successfulResponseHandler:p(Dr),fetch:this.config.fetch});return{...U.name!=null?{name:U.name}:{},...U.description!=null?{description:U.description}:{}}}async uploadSkill(m){let R=[],U=new FormData;if(m.displayTitle!=null)U.append("display_title",m.displayTitle);for(let ae of m.files){let se=ve(ae.data);U.append("files[]",new Blob([se]),ae.path)}let{value:X}=await ne({url:`${this.config.baseURL}/skills`,headers:await this.getHeaders(),formData:U,failedResponseHandler:ct,successfulResponseHandler:p(qr),fetch:this.config.fetch}),me=X.latest_version!=null?await this.fetchVersionMetadata({skillId:X.id,version:X.latest_version}):{},Ne=me.name??X.name,W=me.description??X.description;return{providerReference:{anthropic:X.id},...X.display_title!=null?{displayTitle:X.display_title}:{},...Ne!=null?{name:Ne}:{},...W!=null?{description:W}:{},...X.latest_version!=null?{latestVersion:X.latest_version}:{},providerMetadata:{anthropic:{...X.source!=null?{source:X.source}:{},...X.created_at!=null?{createdAt:X.created_at}:{},...X.updated_at!=null?{updatedAt:X.updated_at}:{}}},warnings:R}}},Pr="4.0.90",ko="https://api.anthropic.com",wo=`${ko}/v1`;function Lr(m){let R=Y(dt(m));return R===ko?wo:R}function Dt(m={}){let R=Lr(pe({settingValue:m.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"}))??wo,U=m.name??"anthropic.messages",X={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]};if(m.apiKey&&m.authToken)throw new b({argument:"apiKey/authToken",message:"Both apiKey and authToken were provided. Please use only one authentication method."});let me=async()=>{let $e=m.authToken?{Authorization:`Bearer ${await _(m.authToken)}`}:{"x-api-key":he({apiKey:m.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"})};return L({"anthropic-version":"2023-06-01",...$e,...m.headers},`ai-sdk-anthropic/${Pr}`)},Ne={provider:U,baseURL:R,headers:me,fetch:m.fetch,generateId:m.generateId??C,supportedUrls:()=>X},W=($e)=>new xo($e,Ne),ae=()=>new rr({provider:`${U.replace(/\.messages$/,"")}.batch`,maxLineBytes:m.batchResultDownloads?.maxLineBytes,config:Ne,supportedUrls:X}),se=()=>new Hr({provider:`${U.replace(".messages","")}.skills`,baseURL:R,headers:me,fetch:m.fetch}),fe=function($e){if(new.target)throw Error("The Anthropic model function cannot be called with the new keyword.");return W($e)};return fe.specificationVersion="v4",fe.languageModel=W,fe.chat=W,fe.messages=W,fe.decisionModel=($e)=>new Xe({model:W($e),provider:`${U.replace(/\.messages$/,"")}.decision`}),fe.evaluationModel=fe.decisionModel,fe.experimental_batch=ae,fe.embeddingModel=($e)=>{throw new Ze({modelId:$e,modelType:"embeddingModel"})},fe.textEmbeddingModel=fe.embeddingModel,fe.imageModel=($e)=>{throw new Ze({modelId:$e,modelType:"imageModel"})},fe.files=()=>new Ro({provider:U,baseURL:R,headers:me,fetch:m.fetch}),fe.skills=se,fe.tools=$r,fe}var Xr=Dt();var Fr=(m)=>Dt({apiKey:m.apiKey,...m.baseURL&&{baseURL:ft(m.baseURL)},headers:{...m.headers,...Be(m.baseURL??jt.anthropic)&&{[ht]:"true"}},...m.fetch&&{fetch:m.fetch}})(m.model);function aa(){oe("anthropic",Fr)}export{aa as register};