@mcp-use/inspector 0.14.2 → 0.14.3-canary.1

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 (41) hide show
  1. package/dist/cli.js +11 -3
  2. package/dist/server/{chunk-R5QBLPYB.js → chunk-7ILBF6EL.js} +1 -1
  3. package/dist/server/{chunk-OSJXVY3O.js → chunk-F2FWROJ2.js} +2 -2
  4. package/dist/server/{chunk-PUX4EJWH.js → chunk-O7EUTZ5E.js} +1 -1
  5. package/dist/server/{chunk-Z5QIR3IS.js → chunk-SFZ4CU6U.js} +10 -2
  6. package/dist/server/{chunk-GDZFYTRE.js → chunk-W5XB3CR5.js} +10 -2
  7. package/dist/server/{chunk-QCDOO2RF.js → chunk-Z2X4KZ3J.js} +3 -3
  8. package/dist/server/cli.js +5 -5
  9. package/dist/server/index.js +6 -6
  10. package/dist/server/middleware.js +6 -6
  11. package/dist/server/server.js +5 -5
  12. package/dist/server/shared-routes.js +3 -3
  13. package/dist/server/shared-static.js +2 -2
  14. package/dist/server/shared-utils-browser.d.ts.map +1 -1
  15. package/dist/server/shared-utils-browser.js +1 -1
  16. package/dist/server/shared-utils.d.ts.map +1 -1
  17. package/dist/server/shared-utils.js +1 -1
  18. package/dist/server/utils.d.ts.map +1 -1
  19. package/dist/server/utils.js +1 -1
  20. package/dist/web/assets/browser-Bwbzeqra.js +423 -0
  21. package/dist/web/assets/{client-D72CJBab.js → client-C_oXvQls.js} +6 -6
  22. package/dist/web/assets/{display-A5IEINAP-DWRfr5cj.js → display-A5IEINAP-jFT1ZrZv.js} +2 -2
  23. package/dist/web/assets/{embeddings-CVWvogFr.js → embeddings-C2wpTLdB.js} +1 -1
  24. package/dist/web/assets/{index-DdkxcTE2.js → index-5iKuctN5.js} +11 -11
  25. package/dist/web/assets/index-BAVnedrl.js +1783 -0
  26. package/dist/web/assets/index-CF8ue1E2.js +7 -0
  27. package/dist/web/assets/index-CzON1LlU.js +80 -0
  28. package/dist/web/assets/{index-D7_719w8.js → index-D8Ae6d9I.js} +1 -1
  29. package/dist/web/assets/{index-Cv4xpdR-.js → index-DAtu40Ij.js} +1 -1
  30. package/dist/web/assets/{index-CbPoLZEh.js → index-DEZvih5Y.js} +2 -2
  31. package/dist/web/assets/index-DlhqMiEp.css +1 -0
  32. package/dist/web/assets/{index-pQiGNlCj.js → index-YgJNrSvw.js} +6 -6
  33. package/dist/web/assets/{index-BDlTOMS5.js → index-oNOjaFj2.js} +14 -14
  34. package/dist/web/assets/{llms-xXlg9f0z.js → llms-DFXD7LY2.js} +1 -1
  35. package/dist/web/index.html +3 -3
  36. package/package.json +6 -6
  37. package/dist/web/assets/browser-BLnflEDD.js +0 -410
  38. package/dist/web/assets/index-BgQZjv_u.js +0 -40
  39. package/dist/web/assets/index-Bi42MNIH.js +0 -1753
  40. package/dist/web/assets/index-DdrkmeYH.js +0 -80
  41. package/dist/web/assets/index-G80eS8Oh.css +0 -1
@@ -1,19 +1,19 @@
1
- import{g as wn,O as Ut,h as bn,c as $t,f as xn,S as kn,J as Sn,R as Bt}from"./index-pQiGNlCj.js";import{r as Tn,K as xs,t as Lt,ah as jt,I as Mn,J as On,E as N,B as qt,L as vn,y as ie,i as at,D as In,M as Rn}from"./index-DdrkmeYH.js";import{o as y,i as Wt,j as An,k as Cn,u as Dt,s as b,m as w,n as E,q as Ze,t as Mt,v as Pn,w as En}from"./index-Bi42MNIH.js";import"./index-CbPoLZEh.js";var Ft=class extends wn{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(n){throw new Ut(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const s=await Tn(this.zodSchema,e);if(s.success)return s.data;throw new Ut(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(s.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(r=>{const{message:a}=r;return Array.isArray(a.content)?ks(a.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[s]=e;return await this._validateResult(s.args)}};function ks(t){const e=[];for(const s of t)s.type==="tool_use"&&e.push({name:s.name,args:s.input,id:s.id,type:"tool_call"});return e}function Nn(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}const Un=y({cache_control:Cn().optional().nullable(),defer_loading:An().optional(),input_examples:Wt(Dt()).optional(),allowed_callers:Wt(Dt()).optional()}),Ht={tool_search_tool_regex_20251119:"advanced-tool-use-2025-11-20",tool_search_tool_bm25_20251119:"advanced-tool-use-2025-11-20",memory_20250818:"context-management-2025-06-27",web_fetch_20250910:"web-fetch-2025-09-10",code_execution_20250825:"code-execution-2025-08-25",computer_20251124:"computer-use-2025-11-24",computer_20250124:"computer-use-2025-01-24",mcp_toolset:"mcp-client-2025-11-20"};function $n(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Bn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function Ln(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function jn(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const qn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=xs({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Wn=t=>t();function Dn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Fn(t){function*e(){for(const s of t)Dn(s)&&(s.source==="char"?yield{type:"char_location",file_id:s.url??"",start_char_index:s.startIndex??0,end_char_index:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="page"?yield{type:"page_location",file_id:s.url??"",start_page_number:s.startIndex??0,end_page_number:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="block"?yield{type:"content_block_location",file_id:s.url??"",start_block_index:s.startIndex??0,end_block_index:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="url"?yield{type:"web_search_result_location",url:s.url??"",title:s.title??null,encrypted_index:String(s.startIndex??0),cited_text:s.citedText??""}:s.source==="search"&&(yield{type:"search_result_location",title:s.title??null,start_block_index:s.startIndex??0,end_block_index:s.endIndex??0,search_result_index:0,source:s.source??"",cited_text:s.citedText??""}))}return Array.from(e())}function oe(t){return typeof t=="string"?t:Hn(t)}function Hn(t){const e=[];for(let s=0,{length:n}=t;s<n;s++)e.push(String.fromCharCode(t[s]));return btoa(e.join(""))}function it(t){return(t??"").split(";")[0].toLowerCase()}function Se(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function Z(t,e){const s=Se(e,"cache_control");s!==void 0&&(t.cache_control=s);const n=Se(e,"citations");n!==void 0&&(t.citations=n);const r=Se(e,"context");r!==void 0&&(t.context=r);const a=Se(e,"title");return a!==void 0&&(t.title=a),t}function ot(t,e){const s=Se(e,"cache_control");return s!==void 0&&(t.cache_control=s),t}function Jt(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function Jn(t){const e=[],s=t.response_metadata,n="model_provider"in s&&s?.model_provider==="anthropic";for(const r of t.contentBlocks)if(r.type==="text")r.annotations?e.push({type:"text",text:r.text,citations:Fn(r.annotations)}):e.push({type:"text",text:r.text});else if(r.type==="tool_call")e.push({type:"tool_use",id:r.id??"",name:r.name,input:r.args});else if(r.type==="tool_call_chunk"){const a=Wn(()=>{if(typeof r.args!="string")return r.args;try{return JSON.parse(r.args)}catch{return{}}});e.push({type:"tool_use",id:r.id??"",name:r.name??"",input:a})}else if(r.type==="reasoning"&&n)e.push({type:"thinking",thinking:r.reasoning,signature:String(r.signature)});else if(r.type==="server_tool_call"&&n)r.name==="web_search"?e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args}):r.name==="code_execution"&&e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args});else if(r.type==="server_tool_call_result"&&n)if(r.name==="web_search"&&Array.isArray(r.output.urls)){const a=r.output.urls.map(i=>({type:"web_search_result",title:"",encrypted_content:"",url:i}));e.push({type:"web_search_tool_result",tool_use_id:r.toolCallId??"",content:a})}else r.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:r.toolCallId??"",content:r.output}):r.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:r.toolCallId??"",content:r.output});else{if(r.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(r.type==="file"){const a=r.metadata;if(r.fileId){e.push(Z({type:"document",source:{type:"file",file_id:r.fileId}},a));continue}if(r.url){const i=it(r.mimeType);if(i==="application/pdf"||i===""){e.push(Z({type:"document",source:{type:"url",url:r.url}},a));continue}}if(r.data){const i=it(r.mimeType);if(i===""||i==="application/pdf")e.push(Z({type:"document",source:{type:"base64",data:oe(r.data),media_type:"application/pdf"}},a));else if(i==="text/plain")e.push(Z({type:"document",source:{type:"text",data:oe(r.data),media_type:"text/plain"}},a));else if(Jt(i))e.push(Z({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:oe(r.data),media_type:i}}]}},a));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${i}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(r.type==="image"){const a=r.metadata;if(r.fileId){e.push(ot({type:"image",source:{type:"file",file_id:r.fileId}},a));continue}if(r.url){e.push(ot({type:"image",source:{type:"url",url:r.url}},a));continue}if(r.data){const i=it(r.mimeType)||"image/png";Jt(i)&&e.push(ot({type:"image",source:{type:"base64",data:oe(r.data),media_type:i}},a));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else r.type==="video"||(r.type==="text-plain"?r.data&&e.push(Z({type:"document",source:{type:"text",data:oe(r.data),media_type:"text/plain"}},r.metadata)):r.type==="non_standard"&&n&&e.push(r.value))}return e}function Kt(t){const e=xs({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let s;try{s=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
1
+ import{g as wn,O as Ut,h as bn,c as $t,f as xn,S as Sn,J as kn,R as Bt}from"./index-YgJNrSvw.js";import{r as Tn,K as xs,t as Lt,ah as jt,I as Mn,J as On,E as N,B as qt,L as vn,y as ie,i as at,D as In,M as An}from"./index-CzON1LlU.js";import{bw as y,bx as Dt,by as Rn,bz as Cn,bA as Wt,bB as b,bC as w,bD as E,bE as Ze,bF as Mt,bG as Pn,bH as En}from"./index-BAVnedrl.js";import"./index-DEZvih5Y.js";var Ft=class extends wn{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(n){throw new Ut(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const s=await Tn(this.zodSchema,e);if(s.success)return s.data;throw new Ut(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(s.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(r=>{const{message:a}=r;return Array.isArray(a.content)?Ss(a.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[s]=e;return await this._validateResult(s.args)}};function Ss(t){const e=[];for(const s of t)s.type==="tool_use"&&e.push({name:s.name,args:s.input,id:s.id,type:"tool_call"});return e}function Nn(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}const Un=y({cache_control:Cn().optional().nullable(),defer_loading:Rn().optional(),input_examples:Dt(Wt()).optional(),allowed_callers:Dt(Wt()).optional()}),Ht={tool_search_tool_regex_20251119:"advanced-tool-use-2025-11-20",tool_search_tool_bm25_20251119:"advanced-tool-use-2025-11-20",memory_20250818:"context-management-2025-06-27",web_fetch_20250910:"web-fetch-2025-09-10",code_execution_20250825:"code-execution-2025-08-25",computer_20251124:"computer-use-2025-11-24",computer_20250124:"computer-use-2025-01-24",mcp_toolset:"mcp-client-2025-11-20"};function $n(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Bn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function Ln(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function jn(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const qn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=xs({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Dn=t=>t();function Wn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Fn(t){function*e(){for(const s of t)Wn(s)&&(s.source==="char"?yield{type:"char_location",file_id:s.url??"",start_char_index:s.startIndex??0,end_char_index:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="page"?yield{type:"page_location",file_id:s.url??"",start_page_number:s.startIndex??0,end_page_number:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="block"?yield{type:"content_block_location",file_id:s.url??"",start_block_index:s.startIndex??0,end_block_index:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="url"?yield{type:"web_search_result_location",url:s.url??"",title:s.title??null,encrypted_index:String(s.startIndex??0),cited_text:s.citedText??""}:s.source==="search"&&(yield{type:"search_result_location",title:s.title??null,start_block_index:s.startIndex??0,end_block_index:s.endIndex??0,search_result_index:0,source:s.source??"",cited_text:s.citedText??""}))}return Array.from(e())}function oe(t){return typeof t=="string"?t:Hn(t)}function Hn(t){const e=[];for(let s=0,{length:n}=t;s<n;s++)e.push(String.fromCharCode(t[s]));return btoa(e.join(""))}function it(t){return(t??"").split(";")[0].toLowerCase()}function ke(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function Z(t,e){const s=ke(e,"cache_control");s!==void 0&&(t.cache_control=s);const n=ke(e,"citations");n!==void 0&&(t.citations=n);const r=ke(e,"context");r!==void 0&&(t.context=r);const a=ke(e,"title");return a!==void 0&&(t.title=a),t}function ot(t,e){const s=ke(e,"cache_control");return s!==void 0&&(t.cache_control=s),t}function Jt(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function Jn(t){const e=[],s=t.response_metadata,n="model_provider"in s&&s?.model_provider==="anthropic";for(const r of t.contentBlocks)if(r.type==="text")r.annotations?e.push({type:"text",text:r.text,citations:Fn(r.annotations)}):e.push({type:"text",text:r.text});else if(r.type==="tool_call")e.push({type:"tool_use",id:r.id??"",name:r.name,input:r.args});else if(r.type==="tool_call_chunk"){const a=Dn(()=>{if(typeof r.args!="string")return r.args;try{return JSON.parse(r.args)}catch{return{}}});e.push({type:"tool_use",id:r.id??"",name:r.name??"",input:a})}else if(r.type==="reasoning"&&n)e.push({type:"thinking",thinking:r.reasoning,signature:String(r.signature)});else if(r.type==="server_tool_call"&&n)r.name==="web_search"?e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args}):r.name==="code_execution"&&e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args});else if(r.type==="server_tool_call_result"&&n)if(r.name==="web_search"&&Array.isArray(r.output.urls)){const a=r.output.urls.map(i=>({type:"web_search_result",title:"",encrypted_content:"",url:i}));e.push({type:"web_search_tool_result",tool_use_id:r.toolCallId??"",content:a})}else r.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:r.toolCallId??"",content:r.output}):r.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:r.toolCallId??"",content:r.output});else{if(r.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(r.type==="file"){const a=r.metadata;if(r.fileId){e.push(Z({type:"document",source:{type:"file",file_id:r.fileId}},a));continue}if(r.url){const i=it(r.mimeType);if(i==="application/pdf"||i===""){e.push(Z({type:"document",source:{type:"url",url:r.url}},a));continue}}if(r.data){const i=it(r.mimeType);if(i===""||i==="application/pdf")e.push(Z({type:"document",source:{type:"base64",data:oe(r.data),media_type:"application/pdf"}},a));else if(i==="text/plain")e.push(Z({type:"document",source:{type:"text",data:oe(r.data),media_type:"text/plain"}},a));else if(Jt(i))e.push(Z({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:oe(r.data),media_type:i}}]}},a));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${i}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(r.type==="image"){const a=r.metadata;if(r.fileId){e.push(ot({type:"image",source:{type:"file",file_id:r.fileId}},a));continue}if(r.url){e.push(ot({type:"image",source:{type:"url",url:r.url}},a));continue}if(r.data){const i=it(r.mimeType)||"image/png";Jt(i)&&e.push(ot({type:"image",source:{type:"base64",data:oe(r.data),media_type:i}},a));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else r.type==="video"||(r.type==="text-plain"?r.data&&e.push(Z({type:"document",source:{type:"text",data:oe(r.data),media_type:"text/plain"}},r.metadata)):r.type==="non_standard"&&n&&e.push(r.value))}return e}function Kt(t){const e=xs({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let s;try{s=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
2
2
 
3
3
  `))}if(s.protocol==="http:"||s.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(s.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
4
4
 
5
- `))}function Kn(t){const e=[];for(const s of t)if(s._getType()==="tool")if(typeof s.content=="string"){const n=e[e.length-1];n?._getType()==="human"&&Array.isArray(n.content)&&"type"in n.content[0]&&n.content[0].type==="tool_result"?n.content.push({type:"tool_result",content:s.content,tool_use_id:s.tool_call_id}):e.push(new jt({content:[{type:"tool_result",content:s.content,tool_use_id:s.tool_call_id}]}))}else e.push(new jt({content:[{type:"tool_result",...s.content!=null?{content:_t(s)}:{},tool_use_id:s.tool_call_id}]}));else e.push(s);return e}function Xt(t){if(t.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:t.id,name:t.name,input:t.args}}function*Xn(t){const e=["bash_code_execution_tool_result","input_json_delta","server_tool_use","text_editor_code_execution_tool_result","tool_result","tool_use","web_search_result","web_search_tool_result"],s=["text","text_delta"];for(const n of t){Mn(n)&&(yield On(n,qn));const r="cache_control"in n?n.cache_control:void 0;if(n.type==="image_url"){let a;typeof n.image_url=="string"?a=Kt(n.image_url):typeof n.image_url=="object"&&n.image_url!==null&&"url"in n.image_url&&typeof n.image_url.url=="string"&&(a=Kt(n.image_url.url)),a&&(yield{type:"image",source:a,...r?{cache_control:r}:{}})}else{if(jn(n))return n;if(n.type==="document")yield{...n,...r?{cache_control:r}:{}};else if($n(n))yield{type:"thinking",thinking:n.thinking,signature:n.signature,...r?{cache_control:r}:{}};else if(Bn(n))yield{type:"redacted_thinking",data:n.data,...r?{cache_control:r}:{}};else if(Ln(n))yield{type:"search_result",title:n.title,source:n.source,..."cache_control"in n&&n.cache_control?{cache_control:n.cache_control}:{},..."citations"in n&&n.citations?{citations:n.citations}:{},content:n.content};else if(s.find(a=>a===n.type)&&"text"in n)yield{type:"text",text:n.text,...r?{cache_control:r}:{},..."citations"in n&&n.citations?{citations:n.citations}:{}};else if(e.find(a=>a===n.type)){const a={...n};if("index"in a&&delete a.index,a.type==="input_json_delta"&&(a.type="tool_use"),"input"in a&&typeof a.input=="string")try{a.input=JSON.parse(a.input)}catch{a.input={}}yield{...a,...r?{cache_control:r}:{}}}else n.type==="container_upload"&&(yield{...n,...r?{cache_control:r}:{}})}}}function _t(t){const{content:e}=t;return typeof e=="string"?e:Array.from(Xn(e))}function zt(t){const e=Kn(t);let s;e.length>0&&e[0]._getType()==="system"&&(s=t[0].content);const r=(s!==void 0?e.slice(1):e).map(a=>{let i;if(a._getType()==="human")i="user";else if(a._getType()==="ai")i="assistant";else if(a._getType()==="tool")i="user";else throw a._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${a.type}" is not supported.`);if(Lt(a)&&a.response_metadata?.output_version==="v1")return{role:i,content:Jn(a)};if(Lt(a)&&a.tool_calls?.length){if(typeof a.content=="string")return a.content===""?{role:i,content:a.tool_calls.map(Xt)}:{role:i,content:[{type:"text",text:a.content},...a.tool_calls.map(Xt)]};{const{content:u}=a;return!a.tool_calls.every(h=>u.find(p=>(p.type==="tool_use"||p.type==="input_json_delta"||p.type==="server_tool_use")&&p.id===h.id))&&console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:i,content:_t(a)}}}else return{role:i,content:_t(a)}});return{messages:zn(r),system:s}}function zn(t){if(!t||t.length<=1)return t;const e=[];let s=t[0];const n=a=>typeof a=="string"?[{type:"text",text:a}]:a,r=a=>a.role!=="user"||typeof a.content=="string"?!1:Array.isArray(a.content)&&a.content.every(i=>i.type==="tool_result");for(let a=1;a<t.length;a+=1){const i=t[a];r(s)&&r(i)?s={...s,content:[...n(s.content),...n(i.content)]}:(e.push(s),s=i)}return e.push(s),e}function Vn(t,e){const s={model_provider:"anthropic"};if(t.type==="message_start"){const{content:n,usage:r,...a}=t.message,i={};for(const[_,d]of Object.entries(a))d!=null&&(i[_]=d);const{input_tokens:u,output_tokens:c,...h}=r??{},p=u+h.cache_creation_input_tokens+h.cache_read_input_tokens,f={input_tokens:p,output_tokens:c,total_tokens:p+c,input_token_details:{cache_creation:h.cache_creation_input_tokens,cache_read:h.cache_read_input_tokens}};return{chunk:new N({content:e.coerceContentToString?"":[],additional_kwargs:i,usage_metadata:e.streamUsage?f:void 0,response_metadata:{...s,usage:{...h}},id:t.message.id})}}else if(t.type==="message_delta"){const n={input_tokens:0,output_tokens:t.usage.output_tokens,total_tokens:t.usage.output_tokens,input_token_details:{cache_creation:t.usage.cache_creation_input_tokens,cache_read:t.usage.cache_read_input_tokens}},r="context_management"in t.delta?{context_management:t.delta.context_management}:void 0;return{chunk:new N({content:e.coerceContentToString?"":[],response_metadata:r,additional_kwargs:{...t.delta},usage_metadata:e.streamUsage?n:void 0})}}else if(t.type==="content_block_start"&&["tool_use","document","server_tool_use","web_search_tool_result"].includes(t.content_block.type)){const n=t.content_block;let r;return n.type==="tool_use"?r=[{id:n.id,index:t.index,name:n.name,args:""}]:r=[],{chunk:new N({content:e.coerceContentToString?"":[{index:t.index,...t.content_block,input:n.type==="server_tool_use"||n.type==="tool_use"?"":void 0}],response_metadata:s,additional_kwargs:{},tool_call_chunks:r})}}else if(t.type==="content_block_delta"&&["text_delta","citations_delta","thinking_delta","signature_delta"].includes(t.delta.type)){if(e.coerceContentToString&&"text"in t.delta)return{chunk:new N({content:t.delta.text})};{const n=t.delta;return"citation"in n&&(n.citations=[n.citation],delete n.citation),n.type==="thinking_delta"||n.type==="signature_delta"?{chunk:new N({content:[{index:t.index,...n,type:"thinking"}],response_metadata:s})}:{chunk:new N({content:[{index:t.index,...n,type:"text"}],response_metadata:s})}}}else{if(t.type==="content_block_delta"&&t.delta.type==="input_json_delta")return{chunk:new N({content:e.coerceContentToString?"":[{index:t.index,input:t.delta.partial_json,type:t.delta.type}],response_metadata:s,additional_kwargs:{},tool_call_chunks:[{index:t.index,args:t.delta.partial_json}]})};if(t.type==="content_block_start"&&t.content_block.type==="text"){const n=t.content_block?.text;if(n!==void 0)return{chunk:new N({content:e.coerceContentToString?n:[{index:t.index,...t.content_block}],response_metadata:s,additional_kwargs:{}})}}else{if(t.type==="content_block_start"&&t.content_block.type==="redacted_thinking")return{chunk:new N({content:e.coerceContentToString?"":[{index:t.index,...t.content_block}],response_metadata:s})};if(t.type==="content_block_start"&&t.content_block.type==="thinking"){const n=t.content_block.thinking;return{chunk:new N({content:e.coerceContentToString?n:[{index:t.index,...t.content_block}],response_metadata:s})}}}}return null}function Qn(t,e){const s={...e,model_provider:"anthropic"},n=e.usage,r=n!=null?{input_tokens:n.input_tokens??0,output_tokens:n.output_tokens??0,total_tokens:(n.input_tokens??0)+(n.output_tokens??0),input_token_details:{cache_creation:n.cache_creation_input_tokens,cache_read:n.cache_read_input_tokens}}:void 0;if(t.length===1&&t[0].type==="text")return[{text:t[0].text,message:new qt({content:t[0].text,additional_kwargs:e,usage_metadata:r,response_metadata:s,id:e.id})}];{const a=ks(t);return[{text:"",message:new qt({content:t,additional_kwargs:e,tool_calls:a,usage_metadata:r,response_metadata:s,id:e.id})}]}}function Ce(t,e){return t.lc_error_code=e,t.message=`${t.message}
5
+ `))}function Kn(t){const e=[];for(const s of t)if(s._getType()==="tool")if(typeof s.content=="string"){const n=e[e.length-1];n?._getType()==="human"&&Array.isArray(n.content)&&"type"in n.content[0]&&n.content[0].type==="tool_result"?n.content.push({type:"tool_result",content:s.content,tool_use_id:s.tool_call_id}):e.push(new jt({content:[{type:"tool_result",content:s.content,tool_use_id:s.tool_call_id}]}))}else e.push(new jt({content:[{type:"tool_result",...s.content!=null?{content:_t(s)}:{},tool_use_id:s.tool_call_id}]}));else e.push(s);return e}function Xt(t){if(t.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:t.id,name:t.name,input:t.args}}function*Xn(t){const e=["bash_code_execution_tool_result","input_json_delta","server_tool_use","text_editor_code_execution_tool_result","tool_result","tool_use","web_search_result","web_search_tool_result"],s=["text","text_delta"];for(const n of t){Mn(n)&&(yield On(n,qn));const r="cache_control"in n?n.cache_control:void 0;if(n.type==="image_url"){let a;typeof n.image_url=="string"?a=Kt(n.image_url):typeof n.image_url=="object"&&n.image_url!==null&&"url"in n.image_url&&typeof n.image_url.url=="string"&&(a=Kt(n.image_url.url)),a&&(yield{type:"image",source:a,...r?{cache_control:r}:{}})}else{if(jn(n))return n;if(n.type==="document")yield{...n,...r?{cache_control:r}:{}};else if($n(n))yield{type:"thinking",thinking:n.thinking,signature:n.signature,...r?{cache_control:r}:{}};else if(Bn(n))yield{type:"redacted_thinking",data:n.data,...r?{cache_control:r}:{}};else if(Ln(n))yield{type:"search_result",title:n.title,source:n.source,..."cache_control"in n&&n.cache_control?{cache_control:n.cache_control}:{},..."citations"in n&&n.citations?{citations:n.citations}:{},content:n.content};else if(s.find(a=>a===n.type)&&"text"in n)yield{type:"text",text:n.text,...r?{cache_control:r}:{},..."citations"in n&&n.citations?{citations:n.citations}:{}};else if(e.find(a=>a===n.type)){const a={...n};if("index"in a&&delete a.index,a.type==="input_json_delta"&&(a.type="tool_use"),"input"in a&&typeof a.input=="string")try{a.input=JSON.parse(a.input)}catch{a.input={}}yield{...a,...r?{cache_control:r}:{}}}else n.type==="container_upload"&&(yield{...n,...r?{cache_control:r}:{}})}}}function _t(t){const{content:e}=t;return typeof e=="string"?e:Array.from(Xn(e))}function zt(t){const e=Kn(t);let s;e.length>0&&e[0]._getType()==="system"&&(s=t[0].content);const r=(s!==void 0?e.slice(1):e).map(a=>{let i;if(a._getType()==="human")i="user";else if(a._getType()==="ai")i="assistant";else if(a._getType()==="tool")i="user";else throw a._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${a.type}" is not supported.`);if(Lt(a)&&a.response_metadata?.output_version==="v1")return{role:i,content:Jn(a)};if(Lt(a)&&a.tool_calls?.length){if(typeof a.content=="string")return a.content===""?{role:i,content:a.tool_calls.map(Xt)}:{role:i,content:[{type:"text",text:a.content},...a.tool_calls.map(Xt)]};{const{content:u}=a;return!a.tool_calls.every(h=>u.find(p=>(p.type==="tool_use"||p.type==="input_json_delta"||p.type==="server_tool_use")&&p.id===h.id))&&console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:i,content:_t(a)}}}else return{role:i,content:_t(a)}});return{messages:zn(r),system:s}}function zn(t){if(!t||t.length<=1)return t;const e=[];let s=t[0];const n=a=>typeof a=="string"?[{type:"text",text:a}]:a,r=a=>a.role!=="user"||typeof a.content=="string"?!1:Array.isArray(a.content)&&a.content.every(i=>i.type==="tool_result");for(let a=1;a<t.length;a+=1){const i=t[a];r(s)&&r(i)?s={...s,content:[...n(s.content),...n(i.content)]}:(e.push(s),s=i)}return e.push(s),e}function Vn(t,e){const s={model_provider:"anthropic"};if(t.type==="message_start"){const{content:n,usage:r,...a}=t.message,i={};for(const[_,d]of Object.entries(a))d!=null&&(i[_]=d);const{input_tokens:u,output_tokens:c,...h}=r??{},p=u+h.cache_creation_input_tokens+h.cache_read_input_tokens,f={input_tokens:p,output_tokens:c,total_tokens:p+c,input_token_details:{cache_creation:h.cache_creation_input_tokens,cache_read:h.cache_read_input_tokens}};return{chunk:new N({content:e.coerceContentToString?"":[],additional_kwargs:i,usage_metadata:e.streamUsage?f:void 0,response_metadata:{...s,usage:{...h}},id:t.message.id})}}else if(t.type==="message_delta"){const n={input_tokens:0,output_tokens:t.usage.output_tokens,total_tokens:t.usage.output_tokens,input_token_details:{cache_creation:t.usage.cache_creation_input_tokens,cache_read:t.usage.cache_read_input_tokens}},r="context_management"in t.delta?{context_management:t.delta.context_management}:void 0;return{chunk:new N({content:e.coerceContentToString?"":[],response_metadata:r,additional_kwargs:{...t.delta},usage_metadata:e.streamUsage?n:void 0})}}else if(t.type==="content_block_start"&&["tool_use","document","server_tool_use","web_search_tool_result"].includes(t.content_block.type)){const n=t.content_block;let r;return n.type==="tool_use"?r=[{id:n.id,index:t.index,name:n.name,args:""}]:r=[],{chunk:new N({content:e.coerceContentToString?"":[{index:t.index,...t.content_block,input:n.type==="server_tool_use"||n.type==="tool_use"?"":void 0}],response_metadata:s,additional_kwargs:{},tool_call_chunks:r})}}else if(t.type==="content_block_delta"&&["text_delta","citations_delta","thinking_delta","signature_delta"].includes(t.delta.type)){if(e.coerceContentToString&&"text"in t.delta)return{chunk:new N({content:t.delta.text})};{const n=t.delta;return"citation"in n&&(n.citations=[n.citation],delete n.citation),n.type==="thinking_delta"||n.type==="signature_delta"?{chunk:new N({content:[{index:t.index,...n,type:"thinking"}],response_metadata:s})}:{chunk:new N({content:[{index:t.index,...n,type:"text"}],response_metadata:s})}}}else{if(t.type==="content_block_delta"&&t.delta.type==="input_json_delta")return{chunk:new N({content:e.coerceContentToString?"":[{index:t.index,input:t.delta.partial_json,type:t.delta.type}],response_metadata:s,additional_kwargs:{},tool_call_chunks:[{index:t.index,args:t.delta.partial_json}]})};if(t.type==="content_block_start"&&t.content_block.type==="text"){const n=t.content_block?.text;if(n!==void 0)return{chunk:new N({content:e.coerceContentToString?n:[{index:t.index,...t.content_block}],response_metadata:s,additional_kwargs:{}})}}else{if(t.type==="content_block_start"&&t.content_block.type==="redacted_thinking")return{chunk:new N({content:e.coerceContentToString?"":[{index:t.index,...t.content_block}],response_metadata:s})};if(t.type==="content_block_start"&&t.content_block.type==="thinking"){const n=t.content_block.thinking;return{chunk:new N({content:e.coerceContentToString?n:[{index:t.index,...t.content_block}],response_metadata:s})}}}}return null}function Qn(t,e){const s={...e,model_provider:"anthropic"},n=e.usage,r=n!=null?{input_tokens:n.input_tokens??0,output_tokens:n.output_tokens??0,total_tokens:(n.input_tokens??0)+(n.output_tokens??0),input_token_details:{cache_creation:n.cache_creation_input_tokens,cache_read:n.cache_read_input_tokens}}:void 0;if(t.length===1&&t[0].type==="text")return[{text:t[0].text,message:new qt({content:t[0].text,additional_kwargs:e,usage_metadata:r,response_metadata:s,id:e.id})}];{const a=Ss(t);return[{text:"",message:new qt({content:t,additional_kwargs:e,tool_calls:a,usage_metadata:r,response_metadata:s,id:e.id})}]}}function Ce(t,e){return t.lc_error_code=e,t.message=`${t.message}
6
6
 
7
7
  Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
8
- `,t}function Vt(t){let e;return t.status===400&&t.message.includes("tool")?e=Ce(t,"INVALID_TOOL_RESULTS"):t.status===401?e=Ce(t,"MODEL_AUTHENTICATION"):t.status===404?e=Ce(t,"MODEL_NOT_FOUND"):t.status===429?e=Ce(t,"MODEL_RATE_LIMIT"):e=t,e}const Yn={"claude-opus-4-0":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-sonnet-20241022":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-sonnet-20240620":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-haiku-latest":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-opus-20240229":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5-20250929":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-20250514":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-20250514":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-haiku-20241022":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-haiku-20240307":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-7-sonnet-20250219":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-7-sonnet-latest":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-0":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1-20250805":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-sonnet-20240229":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5-20251001":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0}};var Gn=Yn;function l(t,e,s,n,r){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,s),s}function o(t,e,s,n){if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return s==="m"?n:s==="a"?n.call(t):n?n.value:e.get(t)}let Ss=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return Ss=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),s=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^s()&15>>+n/4).toString(16))};function Oe(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const yt=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class m extends Error{}class T extends m{constructor(e,s,n,r){super(`${T.makeMessage(e,s,n)}`),this.status=e,this.headers=r,this.requestID=r?.get("request-id"),this.error=s}static makeMessage(e,s,n){const r=s?.message?typeof s.message=="string"?s.message:JSON.stringify(s.message):s?JSON.stringify(s):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,s,n,r){if(!e||!r)return new et({message:n,cause:yt(s)});const a=s;return e===400?new Ms(e,a,n,r):e===401?new Os(e,a,n,r):e===403?new vs(e,a,n,r):e===404?new Is(e,a,n,r):e===409?new Rs(e,a,n,r):e===422?new As(e,a,n,r):e===429?new Cs(e,a,n,r):e>=500?new Ps(e,a,n,r):new T(e,a,n,r)}}class U extends T{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class et extends T{constructor({message:e,cause:s}){super(void 0,void 0,e||"Connection error.",void 0),s&&(this.cause=s)}}class Ts extends et{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ms extends T{}class Os extends T{}class vs extends T{}class Is extends T{}class Rs extends T{}class As extends T{}class Cs extends T{}class Ps extends T{}const Zn=/^[a-z][a-z0-9+.-]*:/i,er=t=>Zn.test(t);let wt=t=>(wt=Array.isArray,wt(t)),Qt=wt;function bt(t){return typeof t!="object"?{}:t??{}}function tr(t){if(!t)return!0;for(const e in t)return!1;return!0}function sr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}const nr=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new m(`${t} must be an integer`);if(e<0)throw new m(`${t} must be a positive integer`);return e},Es=t=>{try{return JSON.parse(t)}catch{return}},O=(t,e)=>{const s=t[e];return delete t[e],s},rr=t=>new Promise(e=>setTimeout(e,t)),se="0.71.2",ar=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function ir(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const or=()=>{const t=ir();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":Gt(Deno.build.os),"X-Stainless-Arch":Yt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":Gt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Yt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=ur();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ur(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:s}of t){const n=s.exec(navigator.userAgent);if(n){const r=n[1]||0,a=n[2]||0,i=n[3]||0;return{browser:e,version:`${r}.${a}.${i}`}}}return null}const Yt=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Gt=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let Zt;const cr=()=>Zt??(Zt=or());function lr(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ns(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Us(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Ns({start(){},async pull(s){const{done:n,value:r}=await e.next();n?s.close():s.enqueue(r)},async cancel(){await e.return?.()}})}function Ot(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const s=await e.read();return s?.done&&e.releaseLock(),s}catch(s){throw e.releaseLock(),s}},async return(){const s=e.cancel();return e.releaseLock(),await s,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function dr(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}const e=t.getReader(),s=e.cancel();e.releaseLock(),await s}const hr=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function pr(t){let e=0;for(const r of t)e+=r.length;const s=new Uint8Array(e);let n=0;for(const r of t)s.set(r,n),n+=r.length;return s}let es;function vt(t){let e;return(es??(e=new globalThis.TextEncoder,es=e.encode.bind(e)))(t)}let ts;function ss(t){let e;return(ts??(e=new globalThis.TextDecoder,ts=e.decode.bind(e)))(t)}var R,A;class ve{constructor(){R.set(this,void 0),A.set(this,void 0),l(this,R,new Uint8Array),l(this,A,null)}decode(e){if(e==null)return[];const s=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?vt(e):e;l(this,R,pr([o(this,R,"f"),s]));const n=[];let r;for(;(r=fr(o(this,R,"f"),o(this,A,"f")))!=null;){if(r.carriage&&o(this,A,"f")==null){l(this,A,r.index);continue}if(o(this,A,"f")!=null&&(r.index!==o(this,A,"f")+1||r.carriage)){n.push(ss(o(this,R,"f").subarray(0,o(this,A,"f")-1))),l(this,R,o(this,R,"f").subarray(o(this,A,"f"))),l(this,A,null);continue}const a=o(this,A,"f")!==null?r.preceding-1:r.preceding,i=ss(o(this,R,"f").subarray(0,a));n.push(i),l(this,R,o(this,R,"f").subarray(r.index)),l(this,A,null)}return n}flush(){return o(this,R,"f").length?this.decode(`
9
- `):[]}}R=new WeakMap,A=new WeakMap;ve.NEWLINE_CHARS=new Set([`
8
+ `,t}function Vt(t){let e;return t.status===400&&t.message.includes("tool")?e=Ce(t,"INVALID_TOOL_RESULTS"):t.status===401?e=Ce(t,"MODEL_AUTHENTICATION"):t.status===404?e=Ce(t,"MODEL_NOT_FOUND"):t.status===429?e=Ce(t,"MODEL_RATE_LIMIT"):e=t,e}const Yn={"claude-opus-4-0":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-sonnet-20241022":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-sonnet-20240620":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-haiku-latest":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-opus-20240229":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5-20250929":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-20250514":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-20250514":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-haiku-20241022":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-haiku-20240307":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-7-sonnet-20250219":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-7-sonnet-latest":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-0":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1-20250805":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-sonnet-20240229":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5-20251001":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0}};var Gn=Yn;function l(t,e,s,n,r){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,s),s}function o(t,e,s,n){if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return s==="m"?n:s==="a"?n.call(t):n?n.value:e.get(t)}let ks=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return ks=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),s=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^s()&15>>+n/4).toString(16))};function Oe(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const yt=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class m extends Error{}class T extends m{constructor(e,s,n,r){super(`${T.makeMessage(e,s,n)}`),this.status=e,this.headers=r,this.requestID=r?.get("request-id"),this.error=s}static makeMessage(e,s,n){const r=s?.message?typeof s.message=="string"?s.message:JSON.stringify(s.message):s?JSON.stringify(s):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,s,n,r){if(!e||!r)return new et({message:n,cause:yt(s)});const a=s;return e===400?new Ms(e,a,n,r):e===401?new Os(e,a,n,r):e===403?new vs(e,a,n,r):e===404?new Is(e,a,n,r):e===409?new As(e,a,n,r):e===422?new Rs(e,a,n,r):e===429?new Cs(e,a,n,r):e>=500?new Ps(e,a,n,r):new T(e,a,n,r)}}class U extends T{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class et extends T{constructor({message:e,cause:s}){super(void 0,void 0,e||"Connection error.",void 0),s&&(this.cause=s)}}class Ts extends et{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ms extends T{}class Os extends T{}class vs extends T{}class Is extends T{}class As extends T{}class Rs extends T{}class Cs extends T{}class Ps extends T{}const Zn=/^[a-z][a-z0-9+.-]*:/i,er=t=>Zn.test(t);let wt=t=>(wt=Array.isArray,wt(t)),Qt=wt;function bt(t){return typeof t!="object"?{}:t??{}}function tr(t){if(!t)return!0;for(const e in t)return!1;return!0}function sr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}const nr=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new m(`${t} must be an integer`);if(e<0)throw new m(`${t} must be a positive integer`);return e},Es=t=>{try{return JSON.parse(t)}catch{return}},O=(t,e)=>{const s=t[e];return delete t[e],s},rr=t=>new Promise(e=>setTimeout(e,t)),se="0.71.2",ar=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function ir(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const or=()=>{const t=ir();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":Gt(Deno.build.os),"X-Stainless-Arch":Yt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":Gt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Yt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=ur();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ur(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:s}of t){const n=s.exec(navigator.userAgent);if(n){const r=n[1]||0,a=n[2]||0,i=n[3]||0;return{browser:e,version:`${r}.${a}.${i}`}}}return null}const Yt=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Gt=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let Zt;const cr=()=>Zt??(Zt=or());function lr(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ns(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Us(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Ns({start(){},async pull(s){const{done:n,value:r}=await e.next();n?s.close():s.enqueue(r)},async cancel(){await e.return?.()}})}function Ot(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const s=await e.read();return s?.done&&e.releaseLock(),s}catch(s){throw e.releaseLock(),s}},async return(){const s=e.cancel();return e.releaseLock(),await s,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function dr(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}const e=t.getReader(),s=e.cancel();e.releaseLock(),await s}const hr=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function pr(t){let e=0;for(const r of t)e+=r.length;const s=new Uint8Array(e);let n=0;for(const r of t)s.set(r,n),n+=r.length;return s}let es;function vt(t){let e;return(es??(e=new globalThis.TextEncoder,es=e.encode.bind(e)))(t)}let ts;function ss(t){let e;return(ts??(e=new globalThis.TextDecoder,ts=e.decode.bind(e)))(t)}var A,R;class ve{constructor(){A.set(this,void 0),R.set(this,void 0),l(this,A,new Uint8Array),l(this,R,null)}decode(e){if(e==null)return[];const s=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?vt(e):e;l(this,A,pr([o(this,A,"f"),s]));const n=[];let r;for(;(r=fr(o(this,A,"f"),o(this,R,"f")))!=null;){if(r.carriage&&o(this,R,"f")==null){l(this,R,r.index);continue}if(o(this,R,"f")!=null&&(r.index!==o(this,R,"f")+1||r.carriage)){n.push(ss(o(this,A,"f").subarray(0,o(this,R,"f")-1))),l(this,A,o(this,A,"f").subarray(o(this,R,"f"))),l(this,R,null);continue}const a=o(this,R,"f")!==null?r.preceding-1:r.preceding,i=ss(o(this,A,"f").subarray(0,a));n.push(i),l(this,A,o(this,A,"f").subarray(r.index)),l(this,R,null)}return n}flush(){return o(this,A,"f").length?this.decode(`
9
+ `):[]}}A=new WeakMap,R=new WeakMap;ve.NEWLINE_CHARS=new Set([`
10
10
  `,"\r"]);ve.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function fr(t,e){for(let r=e??0;r<t.length;r++){if(t[r]===10)return{preceding:r,index:r+1,carriage:!1};if(t[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function mr(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}const Qe={off:0,error:200,warn:300,info:400,debug:500},ns=(t,e,s)=>{if(t){if(sr(Qe,t))return t;M(s).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Qe))}`)}};function Te(){}function Pe(t,e,s){return!e||Qe[t]>Qe[s]?Te:e[t].bind(e)}const gr={error:Te,warn:Te,info:Te,debug:Te};let rs=new WeakMap;function M(t){const e=t.logger,s=t.logLevel??"off";if(!e)return gr;const n=rs.get(e);if(n&&n[0]===s)return n[1];const r={error:Pe("error",e,s),warn:Pe("warn",e,s),info:Pe("info",e,s),debug:Pe("debug",e,s)};return rs.set(e,[s,r]),r}const Y=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,s])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":s]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var ue;class j{constructor(e,s,n){this.iterator=e,ue.set(this,void 0),this.controller=s,l(this,ue,n)}static fromSSEResponse(e,s,n){let r=!1;const a=n?M(n):console;async function*i(){if(r)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let u=!1;try{for await(const c of _r(e,s)){if(c.event==="completion")try{yield JSON.parse(c.data)}catch(h){throw a.error("Could not parse message into JSON:",c.data),a.error("From chunk:",c.raw),h}if(c.event==="message_start"||c.event==="message_delta"||c.event==="message_stop"||c.event==="content_block_start"||c.event==="content_block_delta"||c.event==="content_block_stop")try{yield JSON.parse(c.data)}catch(h){throw a.error("Could not parse message into JSON:",c.data),a.error("From chunk:",c.raw),h}if(c.event!=="ping"&&c.event==="error")throw new T(void 0,Es(c.data)??c.data,void 0,e.headers)}u=!0}catch(c){if(Oe(c))return;throw c}finally{u||s.abort()}}return new j(i,s,n)}static fromReadableStream(e,s,n){let r=!1;async function*a(){const u=new ve,c=Ot(e);for await(const h of c)for(const p of u.decode(h))yield p;for(const h of u.flush())yield h}async function*i(){if(r)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let u=!1;try{for await(const c of a())u||c&&(yield JSON.parse(c));u=!0}catch(c){if(Oe(c))return;throw c}finally{u||s.abort()}}return new j(i,s,n)}[(ue=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],s=[],n=this.iterator(),r=a=>({next:()=>{if(a.length===0){const i=n.next();e.push(i),s.push(i)}return a.shift()}});return[new j(()=>r(e),this.controller,o(this,ue,"f")),new j(()=>r(s),this.controller,o(this,ue,"f"))]}toReadableStream(){const e=this;let s;return Ns({async start(){s=e[Symbol.asyncIterator]()},async pull(n){try{const{value:r,done:a}=await s.next();if(a)return n.close();const i=vt(JSON.stringify(r)+`
11
11
  `);n.enqueue(i)}catch(r){n.error(r)}},async cancel(){await s.return?.()}})}}async function*_r(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new m("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new m("Attempted to iterate over a response with no body");const s=new wr,n=new ve,r=Ot(t.body);for await(const a of yr(r))for(const i of n.decode(a)){const u=s.decode(i);u&&(yield u)}for(const a of n.flush()){const i=s.decode(a);i&&(yield i)}}async function*yr(t){let e=new Uint8Array;for await(const s of t){if(s==null)continue;const n=s instanceof ArrayBuffer?new Uint8Array(s):typeof s=="string"?vt(s):s;let r=new Uint8Array(e.length+n.length);r.set(e),r.set(n,e.length),e=r;let a;for(;(a=mr(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class wr{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const a={event:this.event,data:this.data.join(`
12
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[s,n,r]=br(e,":");return r.startsWith(" ")&&(r=r.substring(1)),s==="event"?this.event=r:s==="data"&&this.data.push(r),null}}function br(t,e){const s=t.indexOf(e);return s!==-1?[t.substring(0,s),e,t.substring(s+e.length)]:[t,"",""]}async function $s(t,e){const{response:s,requestLogID:n,retryOfRequestLogID:r,startTime:a}=e,i=await(async()=>{if(e.options.stream)return M(t).debug("response",s.status,s.url,s.headers,s.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(s,e.controller):j.fromSSEResponse(s,e.controller);if(s.status===204)return null;if(e.options.__binaryResponse)return s;const c=s.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){const f=await s.json();return Bs(f,s)}return await s.text()})();return M(t).debug(`[${n}] response parsed`,Y({retryOfRequestLogID:r,url:s.url,status:s.status,body:i,durationMs:Date.now()-a})),i}function Bs(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var Me;class tt extends Promise{constructor(e,s,n=$s){super(r=>{r(null)}),this.responsePromise=s,this.parseResponse=n,Me.set(this,void 0),l(this,Me,e)}_thenUnwrap(e){return new tt(o(this,Me,"f"),this.responsePromise,async(s,n)=>Bs(e(await this.parseResponse(s,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,s]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:s,request_id:s.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(o(this,Me,"f"),e))),this.parsedPromise}then(e,s){return this.parse().then(e,s)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Me=new WeakMap;var Ee;class Ls{constructor(e,s,n,r){Ee.set(this,void 0),l(this,Ee,e),this.options=r,this.response=s,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new m("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await o(this,Ee,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ee=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const s of e.getPaginatedItems())yield s}}class xr extends tt{constructor(e,s,n){super(e,s,async(r,a)=>new n(r,a.response,await $s(r,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const s of e)yield s}}class Ie extends Ls{constructor(e,s,n,r){super(e,s,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){const s=this.first_id;return s?{...this.options,query:{...bt(this.options.query),before_id:s}}:null}const e=this.last_id;return e?{...this.options,query:{...bt(this.options.query),after_id:e}}:null}}class js extends Ls{constructor(e,s,n,r){super(e,s,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.next_page=n.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.next_page;return e?{...this.options,query:{...bt(this.options.query),page:e}}:null}}const qs=()=>{if(typeof File>"u"){const{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function re(t,e,s){return qs(),new File(t,e??"unknown_file",s)}function ze(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}const Ws=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",It=async(t,e)=>({...t,body:await Sr(t.body,e)}),as=new WeakMap;function kr(t){const e=typeof t=="function"?t:t.fetch,s=as.get(e);if(s)return s;const n=(async()=>{try{const r="Response"in e?e.Response:(await e("data:,")).constructor,a=new FormData;return a.toString()!==await new r(a).text()}catch{return!0}})();return as.set(e,n),n}const Sr=async(t,e)=>{if(!await kr(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const s=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,r])=>xt(s,n,r))),s},Tr=t=>t instanceof Blob&&"name"in t,xt=async(t,e,s)=>{if(s!==void 0){if(s==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")t.append(e,String(s));else if(s instanceof Response){let n={};const r=s.headers.get("Content-Type");r&&(n={type:r}),t.append(e,re([await s.blob()],ze(s),n))}else if(Ws(s))t.append(e,re([await new Response(Us(s)).blob()],ze(s)));else if(Tr(s))t.append(e,re([s],ze(s),{type:s.type}));else if(Array.isArray(s))await Promise.all(s.map(n=>xt(t,e+"[]",n)));else if(typeof s=="object")await Promise.all(Object.entries(s).map(([n,r])=>xt(t,`${e}[${n}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`)}},Ds=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",Mr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Ds(t),Or=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function vr(t,e,s){if(qs(),t=await t,e||(e=ze(t)),Mr(t))return t instanceof File&&e==null&&s==null?t:re([await t.arrayBuffer()],e??t.name,{type:t.type,lastModified:t.lastModified,...s});if(Or(t)){const r=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),re(await kt(r),e,s)}const n=await kt(t);if(!s?.type){const r=n.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof r=="string"&&(s={...s,type:r})}return re(n,e,s)}async function kt(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Ds(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Ws(t))for await(const s of t)e.push(...await kt(s));else{const s=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${s?`; constructor: ${s}`:""}${Ir(t)}`)}return e}function Ir(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(s=>`"${s}"`).join(", ")}]`}class B{constructor(e){this._client=e}}const Fs=Symbol.for("brand.privateNullableHeaders");function*Rr(t){if(!t)return;if(Fs in t){const{values:n,nulls:r}=t;yield*n.entries();for(const a of r)yield[a,null];return}let e=!1,s;t instanceof Headers?s=t.entries():Qt(t)?s=t:(e=!0,s=Object.entries(t??{}));for(let n of s){const r=n[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const a=Qt(n[1])?n[1]:[n[1]];let i=!1;for(const u of a)u!==void 0&&(e&&!i&&(i=!0,yield[r,null]),yield[r,u])}}const g=t=>{const e=new Headers,s=new Set;for(const n of t){const r=new Set;for(const[a,i]of Rr(n)){const u=a.toLowerCase();r.has(u)||(e.delete(a),r.add(u)),i===null?(e.delete(a),s.add(u)):(e.append(a,i),s.delete(u))}}return{[Fs]:!0,values:e,nulls:s}};function Hs(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const is=Object.freeze(Object.create(null)),Ar=(t=Hs)=>function(s,...n){if(s.length===1)return s[0];let r=!1;const a=[],i=s.reduce((p,f,_)=>{/[?#]/.test(f)&&(r=!0);const d=n[_];let v=(r?encodeURIComponent:t)(""+d);return _!==n.length&&(d==null||typeof d=="object"&&d.toString===Object.getPrototypeOf(Object.getPrototypeOf(d.hasOwnProperty??is)??is)?.toString)&&(v=d+"",a.push({start:p.length+f.length,length:v.length,error:`Value of type ${Object.prototype.toString.call(d).slice(8,-1)} is not a valid path parameter`})),p+f+(_===n.length?"":v)},""),u=i.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let h;for(;(h=c.exec(u))!==null;)a.push({start:h.index,length:h[0].length,error:`Value "${h[0]}" can't be safely passed as a path parameter`});if(a.sort((p,f)=>p.start-f.start),a.length>0){let p=0;const f=a.reduce((_,d)=>{const v=" ".repeat(d.start-p),X="^".repeat(d.length);return p=d.start+d.length,_+v+X},"");throw new m(`Path parameters result in path with invalid segments:
12
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[s,n,r]=br(e,":");return r.startsWith(" ")&&(r=r.substring(1)),s==="event"?this.event=r:s==="data"&&this.data.push(r),null}}function br(t,e){const s=t.indexOf(e);return s!==-1?[t.substring(0,s),e,t.substring(s+e.length)]:[t,"",""]}async function $s(t,e){const{response:s,requestLogID:n,retryOfRequestLogID:r,startTime:a}=e,i=await(async()=>{if(e.options.stream)return M(t).debug("response",s.status,s.url,s.headers,s.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(s,e.controller):j.fromSSEResponse(s,e.controller);if(s.status===204)return null;if(e.options.__binaryResponse)return s;const c=s.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){const f=await s.json();return Bs(f,s)}return await s.text()})();return M(t).debug(`[${n}] response parsed`,Y({retryOfRequestLogID:r,url:s.url,status:s.status,body:i,durationMs:Date.now()-a})),i}function Bs(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var Me;class tt extends Promise{constructor(e,s,n=$s){super(r=>{r(null)}),this.responsePromise=s,this.parseResponse=n,Me.set(this,void 0),l(this,Me,e)}_thenUnwrap(e){return new tt(o(this,Me,"f"),this.responsePromise,async(s,n)=>Bs(e(await this.parseResponse(s,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,s]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:s,request_id:s.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(o(this,Me,"f"),e))),this.parsedPromise}then(e,s){return this.parse().then(e,s)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Me=new WeakMap;var Ee;class Ls{constructor(e,s,n,r){Ee.set(this,void 0),l(this,Ee,e),this.options=r,this.response=s,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new m("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await o(this,Ee,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ee=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const s of e.getPaginatedItems())yield s}}class xr extends tt{constructor(e,s,n){super(e,s,async(r,a)=>new n(r,a.response,await $s(r,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const s of e)yield s}}class Ie extends Ls{constructor(e,s,n,r){super(e,s,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){const s=this.first_id;return s?{...this.options,query:{...bt(this.options.query),before_id:s}}:null}const e=this.last_id;return e?{...this.options,query:{...bt(this.options.query),after_id:e}}:null}}class js extends Ls{constructor(e,s,n,r){super(e,s,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.next_page=n.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.next_page;return e?{...this.options,query:{...bt(this.options.query),page:e}}:null}}const qs=()=>{if(typeof File>"u"){const{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function re(t,e,s){return qs(),new File(t,e??"unknown_file",s)}function ze(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}const Ds=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",It=async(t,e)=>({...t,body:await kr(t.body,e)}),as=new WeakMap;function Sr(t){const e=typeof t=="function"?t:t.fetch,s=as.get(e);if(s)return s;const n=(async()=>{try{const r="Response"in e?e.Response:(await e("data:,")).constructor,a=new FormData;return a.toString()!==await new r(a).text()}catch{return!0}})();return as.set(e,n),n}const kr=async(t,e)=>{if(!await Sr(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const s=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,r])=>xt(s,n,r))),s},Tr=t=>t instanceof Blob&&"name"in t,xt=async(t,e,s)=>{if(s!==void 0){if(s==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")t.append(e,String(s));else if(s instanceof Response){let n={};const r=s.headers.get("Content-Type");r&&(n={type:r}),t.append(e,re([await s.blob()],ze(s),n))}else if(Ds(s))t.append(e,re([await new Response(Us(s)).blob()],ze(s)));else if(Tr(s))t.append(e,re([s],ze(s),{type:s.type}));else if(Array.isArray(s))await Promise.all(s.map(n=>xt(t,e+"[]",n)));else if(typeof s=="object")await Promise.all(Object.entries(s).map(([n,r])=>xt(t,`${e}[${n}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`)}},Ws=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",Mr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Ws(t),Or=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function vr(t,e,s){if(qs(),t=await t,e||(e=ze(t)),Mr(t))return t instanceof File&&e==null&&s==null?t:re([await t.arrayBuffer()],e??t.name,{type:t.type,lastModified:t.lastModified,...s});if(Or(t)){const r=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),re(await St(r),e,s)}const n=await St(t);if(!s?.type){const r=n.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof r=="string"&&(s={...s,type:r})}return re(n,e,s)}async function St(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Ws(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Ds(t))for await(const s of t)e.push(...await St(s));else{const s=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${s?`; constructor: ${s}`:""}${Ir(t)}`)}return e}function Ir(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(s=>`"${s}"`).join(", ")}]`}class B{constructor(e){this._client=e}}const Fs=Symbol.for("brand.privateNullableHeaders");function*Ar(t){if(!t)return;if(Fs in t){const{values:n,nulls:r}=t;yield*n.entries();for(const a of r)yield[a,null];return}let e=!1,s;t instanceof Headers?s=t.entries():Qt(t)?s=t:(e=!0,s=Object.entries(t??{}));for(let n of s){const r=n[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const a=Qt(n[1])?n[1]:[n[1]];let i=!1;for(const u of a)u!==void 0&&(e&&!i&&(i=!0,yield[r,null]),yield[r,u])}}const g=t=>{const e=new Headers,s=new Set;for(const n of t){const r=new Set;for(const[a,i]of Ar(n)){const u=a.toLowerCase();r.has(u)||(e.delete(a),r.add(u)),i===null?(e.delete(a),s.add(u)):(e.append(a,i),s.delete(u))}}return{[Fs]:!0,values:e,nulls:s}};function Hs(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const is=Object.freeze(Object.create(null)),Rr=(t=Hs)=>function(s,...n){if(s.length===1)return s[0];let r=!1;const a=[],i=s.reduce((p,f,_)=>{/[?#]/.test(f)&&(r=!0);const d=n[_];let v=(r?encodeURIComponent:t)(""+d);return _!==n.length&&(d==null||typeof d=="object"&&d.toString===Object.getPrototypeOf(Object.getPrototypeOf(d.hasOwnProperty??is)??is)?.toString)&&(v=d+"",a.push({start:p.length+f.length,length:v.length,error:`Value of type ${Object.prototype.toString.call(d).slice(8,-1)} is not a valid path parameter`})),p+f+(_===n.length?"":v)},""),u=i.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let h;for(;(h=c.exec(u))!==null;)a.push({start:h.index,length:h[0].length,error:`Value "${h[0]}" can't be safely passed as a path parameter`});if(a.sort((p,f)=>p.start-f.start),a.length>0){let p=0;const f=a.reduce((_,d)=>{const v=" ".repeat(d.start-p),X="^".repeat(d.length);return p=d.start+d.length,_+v+X},"");throw new m(`Path parameters result in path with invalid segments:
13
13
  ${a.map(_=>_.error).join(`
14
14
  `)}
15
15
  ${i}
16
- ${f}`)}return i},S=Ar(Hs);class Js extends B{list(e={},s){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/files",Ie,{query:r,...s,headers:g([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},s?.headers])})}delete(e,s={},n){const{betas:r}=s??{};return this._client.delete(S`/v1/files/${e}`,{...n,headers:g([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,s={},n){const{betas:r}=s??{};return this._client.get(S`/v1/files/${e}/content`,{...n,headers:g([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,s={},n){const{betas:r}=s??{};return this._client.get(S`/v1/files/${e}`,{...n,headers:g([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}upload(e,s){const{betas:n,...r}=e;return this._client.post("/v1/files",It({body:r,...s,headers:g([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},s?.headers])},this._client))}}let Ks=class extends B{retrieve(e,s={},n){const{betas:r}=s??{};return this._client.get(S`/v1/models/${e}?beta=true`,{...n,headers:g([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}list(e={},s){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/models?beta=true",Ie,{query:r,...s,headers:g([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}};const Xs={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function os(t,e,s){return!e||!("parse"in(e.output_format??{}))?{...t,content:t.content.map(n=>{if(n.type==="text"){const r=Object.defineProperty({...n},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(r,"parsed",{get(){return s.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return n}),parsed_output:null}:zs(t,e,s)}function zs(t,e,s){let n=null;const r=t.content.map(a=>{if(a.type==="text"){const i=Cr(e,a.text);n===null&&(n=i);const u=Object.defineProperty({...a},"parsed_output",{value:i,enumerable:!1});return Object.defineProperty(u,"parsed",{get(){return s.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),i},enumerable:!1})}return a});return{...t,content:r,parsed_output:n}}function Cr(t,e){if(t.output_format?.type!=="json_schema")return null;try{return"parse"in t.output_format?t.output_format.parse(e):JSON.parse(e)}catch(s){throw new m(`Failed to parse structured output: ${s}`)}}const Pr=t=>{let e=0,s=[];for(;e<t.length;){let n=t[e];if(n==="\\"){e++;continue}if(n==="{"){s.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){s.push({type:"brace",value:"}"}),e++;continue}if(n==="["){s.push({type:"paren",value:"["}),e++;continue}if(n==="]"){s.push({type:"paren",value:"]"}),e++;continue}if(n===":"){s.push({type:"separator",value:":"}),e++;continue}if(n===","){s.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let u="",c=!1;for(n=t[++e];n!=='"';){if(e===t.length){c=!0;break}if(n==="\\"){if(e++,e===t.length){c=!0;break}u+=n+t[e],n=t[++e]}else u+=n,n=t[++e]}n=t[++e],c||s.push({type:"string",value:u});continue}if(n&&/\s/.test(n)){e++;continue}let a=/[0-9]/;if(n&&a.test(n)||n==="-"||n==="."){let u="";for(n==="-"&&(u+=n,n=t[++e]);n&&a.test(n)||n===".";)u+=n,n=t[++e];s.push({type:"number",value:u});continue}let i=/[a-z]/i;if(n&&i.test(n)){let u="";for(;n&&i.test(n)&&e!==t.length;)u+=n,n=t[++e];if(u=="true"||u=="false"||u==="null")s.push({type:"name",value:u});else{e++;continue}continue}e++}return s},ne=t=>{if(t.length===0)return t;let e=t[t.length-1];switch(e.type){case"separator":return t=t.slice(0,t.length-1),ne(t);case"number":let s=e.value[e.value.length-1];if(s==="."||s==="-")return t=t.slice(0,t.length-1),ne(t);case"string":let n=t[t.length-2];if(n?.type==="delimiter")return t=t.slice(0,t.length-1),ne(t);if(n?.type==="brace"&&n.value==="{")return t=t.slice(0,t.length-1),ne(t);break;case"delimiter":return t=t.slice(0,t.length-1),ne(t)}return t},Er=t=>{let e=[];return t.map(s=>{s.type==="brace"&&(s.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),s.type==="paren"&&(s.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(s=>{s==="}"?t.push({type:"brace",value:"}"}):s==="]"&&t.push({type:"paren",value:"]"})}),t},Nr=t=>{let e="";return t.map(s=>{switch(s.type){case"string":e+='"'+s.value+'"';break;default:e+=s.value;break}}),e},Vs=t=>JSON.parse(Nr(Er(ne(Pr(t)))));var C,H,ee,ce,Ne,le,de,Ue,he,W,pe,$e,Be,z,Le,je,fe,ut,us,qe,ct,lt,dt,cs;const ls="__json_buf";function ds(t){return t.type==="tool_use"||t.type==="server_tool_use"||t.type==="mcp_tool_use"}class Ye{constructor(e,s){C.add(this),this.messages=[],this.receivedMessages=[],H.set(this,void 0),ee.set(this,null),this.controller=new AbortController,ce.set(this,void 0),Ne.set(this,()=>{}),le.set(this,()=>{}),de.set(this,void 0),Ue.set(this,()=>{}),he.set(this,()=>{}),W.set(this,{}),pe.set(this,!1),$e.set(this,!1),Be.set(this,!1),z.set(this,!1),Le.set(this,void 0),je.set(this,void 0),fe.set(this,void 0),qe.set(this,n=>{if(l(this,$e,!0),Oe(n)&&(n=new U),n instanceof U)return l(this,Be,!0),this._emit("abort",n);if(n instanceof m)return this._emit("error",n);if(n instanceof Error){const r=new m(n.message);return r.cause=n,this._emit("error",r)}return this._emit("error",new m(String(n)))}),l(this,ce,new Promise((n,r)=>{l(this,Ne,n,"f"),l(this,le,r,"f")})),l(this,de,new Promise((n,r)=>{l(this,Ue,n,"f"),l(this,he,r,"f")})),o(this,ce,"f").catch(()=>{}),o(this,de,"f").catch(()=>{}),l(this,ee,e),l(this,fe,s?.logger??console)}get response(){return o(this,Le,"f")}get request_id(){return o(this,je,"f")}async withResponse(){l(this,z,!0);const e=await o(this,ce,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const s=new Ye(null);return s._run(()=>s._fromReadableStream(e)),s}static createMessage(e,s,n,{logger:r}={}){const a=new Ye(s,{logger:r});for(const i of s.messages)a._addMessageParam(i);return l(a,ee,{...s,stream:!0}),a._run(()=>a._createMessage(e,{...s,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},o(this,qe,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,s=!0){this.receivedMessages.push(e),s&&this._emit("message",e)}async _createMessage(e,s,n){const r=n?.signal;let a;r&&(r.aborted&&this.controller.abort(),a=this.controller.abort.bind(this.controller),r.addEventListener("abort",a));try{o(this,C,"m",ct).call(this);const{response:i,data:u}=await e.create({...s,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(i);for await(const c of u)o(this,C,"m",lt).call(this,c);if(u.controller.signal?.aborted)throw new U;o(this,C,"m",dt).call(this)}finally{r&&a&&r.removeEventListener("abort",a)}}_connected(e){this.ended||(l(this,Le,e),l(this,je,e?.headers.get("request-id")),o(this,Ne,"f").call(this,e),this._emit("connect"))}get ended(){return o(this,pe,"f")}get errored(){return o(this,$e,"f")}get aborted(){return o(this,Be,"f")}abort(){this.controller.abort()}on(e,s){return(o(this,W,"f")[e]||(o(this,W,"f")[e]=[])).push({listener:s}),this}off(e,s){const n=o(this,W,"f")[e];if(!n)return this;const r=n.findIndex(a=>a.listener===s);return r>=0&&n.splice(r,1),this}once(e,s){return(o(this,W,"f")[e]||(o(this,W,"f")[e]=[])).push({listener:s,once:!0}),this}emitted(e){return new Promise((s,n)=>{l(this,z,!0),e!=="error"&&this.once("error",n),this.once(e,s)})}async done(){l(this,z,!0),await o(this,de,"f")}get currentMessage(){return o(this,H,"f")}async finalMessage(){return await this.done(),o(this,C,"m",ut).call(this)}async finalText(){return await this.done(),o(this,C,"m",us).call(this)}_emit(e,...s){if(o(this,pe,"f"))return;e==="end"&&(l(this,pe,!0),o(this,Ue,"f").call(this));const n=o(this,W,"f")[e];if(n&&(o(this,W,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...s))),e==="abort"){const r=s[0];!o(this,z,"f")&&!n?.length&&Promise.reject(r),o(this,le,"f").call(this,r),o(this,he,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=s[0];!o(this,z,"f")&&!n?.length&&Promise.reject(r),o(this,le,"f").call(this,r),o(this,he,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",o(this,C,"m",ut).call(this))}async _fromReadableStream(e,s){const n=s?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{o(this,C,"m",ct).call(this),this._connected(null);const a=j.fromReadableStream(e,this.controller);for await(const i of a)o(this,C,"m",lt).call(this,i);if(a.controller.signal?.aborted)throw new U;o(this,C,"m",dt).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(H=new WeakMap,ee=new WeakMap,ce=new WeakMap,Ne=new WeakMap,le=new WeakMap,de=new WeakMap,Ue=new WeakMap,he=new WeakMap,W=new WeakMap,pe=new WeakMap,$e=new WeakMap,Be=new WeakMap,z=new WeakMap,Le=new WeakMap,je=new WeakMap,fe=new WeakMap,qe=new WeakMap,C=new WeakSet,ut=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},us=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");const s=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(s.length===0)throw new m("stream ended without producing a content block with type=text");return s.join(" ")},ct=function(){this.ended||l(this,H,void 0)},lt=function(s){if(this.ended)return;const n=o(this,C,"m",cs).call(this,s);switch(this._emit("streamEvent",s,n),s.type){case"content_block_delta":{const r=n.content.at(-1);switch(s.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",s.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",s.delta.citation,r.citations??[]);break}case"input_json_delta":{ds(r)&&r.input&&this._emit("inputJson",s.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",s.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}default:s.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(os(n,o(this,ee,"f"),{logger:o(this,fe,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{l(this,H,n);break}}},dt=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");const s=o(this,H,"f");if(!s)throw new m("request ended without sending any chunks");return l(this,H,void 0),os(s,o(this,ee,"f"),{logger:o(this,fe,"f")})},cs=function(s){let n=o(this,H,"f");if(s.type==="message_start"){if(n)throw new m(`Unexpected event order, got ${s.type} before receiving "message_stop"`);return s.message}if(!n)throw new m(`Unexpected event order, got ${s.type} before "message_start"`);switch(s.type){case"message_stop":return n;case"message_delta":return n.container=s.delta.container,n.stop_reason=s.delta.stop_reason,n.stop_sequence=s.delta.stop_sequence,n.usage.output_tokens=s.usage.output_tokens,n.context_management=s.context_management,s.usage.input_tokens!=null&&(n.usage.input_tokens=s.usage.input_tokens),s.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=s.usage.cache_creation_input_tokens),s.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=s.usage.cache_read_input_tokens),s.usage.server_tool_use!=null&&(n.usage.server_tool_use=s.usage.server_tool_use),n;case"content_block_start":return n.content.push(s.content_block),n;case"content_block_delta":{const r=n.content.at(s.index);switch(s.delta.type){case"text_delta":{r?.type==="text"&&(n.content[s.index]={...r,text:(r.text||"")+s.delta.text});break}case"citations_delta":{r?.type==="text"&&(n.content[s.index]={...r,citations:[...r.citations??[],s.delta.citation]});break}case"input_json_delta":{if(r&&ds(r)){let a=r[ls]||"";a+=s.delta.partial_json;const i={...r};if(Object.defineProperty(i,ls,{value:a,enumerable:!1,writable:!0}),a)try{i.input=Vs(a)}catch(u){const c=new m(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${u}. JSON: ${a}`);o(this,qe,"f").call(this,c)}n.content[s.index]=i}break}case"thinking_delta":{r?.type==="thinking"&&(n.content[s.index]={...r,thinking:r.thinking+s.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(n.content[s.index]={...r,signature:s.delta.signature});break}default:s.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){const e=[],s=[];let n=!1;return this.on("streamEvent",r=>{const a=s.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of s)r.resolve(void 0);s.length=0}),this.on("abort",r=>{n=!0;for(const a of s)a.reject(r);s.length=0}),this.on("error",r=>{n=!0;for(const a of s)a.reject(r);s.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>s.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new j(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}const Ur=1e5,$r=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
16
+ ${f}`)}return i},k=Rr(Hs);class Js extends B{list(e={},s){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/files",Ie,{query:r,...s,headers:g([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},s?.headers])})}delete(e,s={},n){const{betas:r}=s??{};return this._client.delete(k`/v1/files/${e}`,{...n,headers:g([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,s={},n){const{betas:r}=s??{};return this._client.get(k`/v1/files/${e}/content`,{...n,headers:g([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,s={},n){const{betas:r}=s??{};return this._client.get(k`/v1/files/${e}`,{...n,headers:g([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}upload(e,s){const{betas:n,...r}=e;return this._client.post("/v1/files",It({body:r,...s,headers:g([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},s?.headers])},this._client))}}let Ks=class extends B{retrieve(e,s={},n){const{betas:r}=s??{};return this._client.get(k`/v1/models/${e}?beta=true`,{...n,headers:g([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}list(e={},s){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/models?beta=true",Ie,{query:r,...s,headers:g([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}};const Xs={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function os(t,e,s){return!e||!("parse"in(e.output_format??{}))?{...t,content:t.content.map(n=>{if(n.type==="text"){const r=Object.defineProperty({...n},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(r,"parsed",{get(){return s.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return n}),parsed_output:null}:zs(t,e,s)}function zs(t,e,s){let n=null;const r=t.content.map(a=>{if(a.type==="text"){const i=Cr(e,a.text);n===null&&(n=i);const u=Object.defineProperty({...a},"parsed_output",{value:i,enumerable:!1});return Object.defineProperty(u,"parsed",{get(){return s.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),i},enumerable:!1})}return a});return{...t,content:r,parsed_output:n}}function Cr(t,e){if(t.output_format?.type!=="json_schema")return null;try{return"parse"in t.output_format?t.output_format.parse(e):JSON.parse(e)}catch(s){throw new m(`Failed to parse structured output: ${s}`)}}const Pr=t=>{let e=0,s=[];for(;e<t.length;){let n=t[e];if(n==="\\"){e++;continue}if(n==="{"){s.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){s.push({type:"brace",value:"}"}),e++;continue}if(n==="["){s.push({type:"paren",value:"["}),e++;continue}if(n==="]"){s.push({type:"paren",value:"]"}),e++;continue}if(n===":"){s.push({type:"separator",value:":"}),e++;continue}if(n===","){s.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let u="",c=!1;for(n=t[++e];n!=='"';){if(e===t.length){c=!0;break}if(n==="\\"){if(e++,e===t.length){c=!0;break}u+=n+t[e],n=t[++e]}else u+=n,n=t[++e]}n=t[++e],c||s.push({type:"string",value:u});continue}if(n&&/\s/.test(n)){e++;continue}let a=/[0-9]/;if(n&&a.test(n)||n==="-"||n==="."){let u="";for(n==="-"&&(u+=n,n=t[++e]);n&&a.test(n)||n===".";)u+=n,n=t[++e];s.push({type:"number",value:u});continue}let i=/[a-z]/i;if(n&&i.test(n)){let u="";for(;n&&i.test(n)&&e!==t.length;)u+=n,n=t[++e];if(u=="true"||u=="false"||u==="null")s.push({type:"name",value:u});else{e++;continue}continue}e++}return s},ne=t=>{if(t.length===0)return t;let e=t[t.length-1];switch(e.type){case"separator":return t=t.slice(0,t.length-1),ne(t);case"number":let s=e.value[e.value.length-1];if(s==="."||s==="-")return t=t.slice(0,t.length-1),ne(t);case"string":let n=t[t.length-2];if(n?.type==="delimiter")return t=t.slice(0,t.length-1),ne(t);if(n?.type==="brace"&&n.value==="{")return t=t.slice(0,t.length-1),ne(t);break;case"delimiter":return t=t.slice(0,t.length-1),ne(t)}return t},Er=t=>{let e=[];return t.map(s=>{s.type==="brace"&&(s.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),s.type==="paren"&&(s.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(s=>{s==="}"?t.push({type:"brace",value:"}"}):s==="]"&&t.push({type:"paren",value:"]"})}),t},Nr=t=>{let e="";return t.map(s=>{switch(s.type){case"string":e+='"'+s.value+'"';break;default:e+=s.value;break}}),e},Vs=t=>JSON.parse(Nr(Er(ne(Pr(t)))));var C,H,ee,ce,Ne,le,de,Ue,he,D,pe,$e,Be,z,Le,je,fe,ut,us,qe,ct,lt,dt,cs;const ls="__json_buf";function ds(t){return t.type==="tool_use"||t.type==="server_tool_use"||t.type==="mcp_tool_use"}class Ye{constructor(e,s){C.add(this),this.messages=[],this.receivedMessages=[],H.set(this,void 0),ee.set(this,null),this.controller=new AbortController,ce.set(this,void 0),Ne.set(this,()=>{}),le.set(this,()=>{}),de.set(this,void 0),Ue.set(this,()=>{}),he.set(this,()=>{}),D.set(this,{}),pe.set(this,!1),$e.set(this,!1),Be.set(this,!1),z.set(this,!1),Le.set(this,void 0),je.set(this,void 0),fe.set(this,void 0),qe.set(this,n=>{if(l(this,$e,!0),Oe(n)&&(n=new U),n instanceof U)return l(this,Be,!0),this._emit("abort",n);if(n instanceof m)return this._emit("error",n);if(n instanceof Error){const r=new m(n.message);return r.cause=n,this._emit("error",r)}return this._emit("error",new m(String(n)))}),l(this,ce,new Promise((n,r)=>{l(this,Ne,n,"f"),l(this,le,r,"f")})),l(this,de,new Promise((n,r)=>{l(this,Ue,n,"f"),l(this,he,r,"f")})),o(this,ce,"f").catch(()=>{}),o(this,de,"f").catch(()=>{}),l(this,ee,e),l(this,fe,s?.logger??console)}get response(){return o(this,Le,"f")}get request_id(){return o(this,je,"f")}async withResponse(){l(this,z,!0);const e=await o(this,ce,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const s=new Ye(null);return s._run(()=>s._fromReadableStream(e)),s}static createMessage(e,s,n,{logger:r}={}){const a=new Ye(s,{logger:r});for(const i of s.messages)a._addMessageParam(i);return l(a,ee,{...s,stream:!0}),a._run(()=>a._createMessage(e,{...s,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},o(this,qe,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,s=!0){this.receivedMessages.push(e),s&&this._emit("message",e)}async _createMessage(e,s,n){const r=n?.signal;let a;r&&(r.aborted&&this.controller.abort(),a=this.controller.abort.bind(this.controller),r.addEventListener("abort",a));try{o(this,C,"m",ct).call(this);const{response:i,data:u}=await e.create({...s,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(i);for await(const c of u)o(this,C,"m",lt).call(this,c);if(u.controller.signal?.aborted)throw new U;o(this,C,"m",dt).call(this)}finally{r&&a&&r.removeEventListener("abort",a)}}_connected(e){this.ended||(l(this,Le,e),l(this,je,e?.headers.get("request-id")),o(this,Ne,"f").call(this,e),this._emit("connect"))}get ended(){return o(this,pe,"f")}get errored(){return o(this,$e,"f")}get aborted(){return o(this,Be,"f")}abort(){this.controller.abort()}on(e,s){return(o(this,D,"f")[e]||(o(this,D,"f")[e]=[])).push({listener:s}),this}off(e,s){const n=o(this,D,"f")[e];if(!n)return this;const r=n.findIndex(a=>a.listener===s);return r>=0&&n.splice(r,1),this}once(e,s){return(o(this,D,"f")[e]||(o(this,D,"f")[e]=[])).push({listener:s,once:!0}),this}emitted(e){return new Promise((s,n)=>{l(this,z,!0),e!=="error"&&this.once("error",n),this.once(e,s)})}async done(){l(this,z,!0),await o(this,de,"f")}get currentMessage(){return o(this,H,"f")}async finalMessage(){return await this.done(),o(this,C,"m",ut).call(this)}async finalText(){return await this.done(),o(this,C,"m",us).call(this)}_emit(e,...s){if(o(this,pe,"f"))return;e==="end"&&(l(this,pe,!0),o(this,Ue,"f").call(this));const n=o(this,D,"f")[e];if(n&&(o(this,D,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...s))),e==="abort"){const r=s[0];!o(this,z,"f")&&!n?.length&&Promise.reject(r),o(this,le,"f").call(this,r),o(this,he,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=s[0];!o(this,z,"f")&&!n?.length&&Promise.reject(r),o(this,le,"f").call(this,r),o(this,he,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",o(this,C,"m",ut).call(this))}async _fromReadableStream(e,s){const n=s?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{o(this,C,"m",ct).call(this),this._connected(null);const a=j.fromReadableStream(e,this.controller);for await(const i of a)o(this,C,"m",lt).call(this,i);if(a.controller.signal?.aborted)throw new U;o(this,C,"m",dt).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(H=new WeakMap,ee=new WeakMap,ce=new WeakMap,Ne=new WeakMap,le=new WeakMap,de=new WeakMap,Ue=new WeakMap,he=new WeakMap,D=new WeakMap,pe=new WeakMap,$e=new WeakMap,Be=new WeakMap,z=new WeakMap,Le=new WeakMap,je=new WeakMap,fe=new WeakMap,qe=new WeakMap,C=new WeakSet,ut=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},us=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");const s=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(s.length===0)throw new m("stream ended without producing a content block with type=text");return s.join(" ")},ct=function(){this.ended||l(this,H,void 0)},lt=function(s){if(this.ended)return;const n=o(this,C,"m",cs).call(this,s);switch(this._emit("streamEvent",s,n),s.type){case"content_block_delta":{const r=n.content.at(-1);switch(s.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",s.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",s.delta.citation,r.citations??[]);break}case"input_json_delta":{ds(r)&&r.input&&this._emit("inputJson",s.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",s.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}default:s.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(os(n,o(this,ee,"f"),{logger:o(this,fe,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{l(this,H,n);break}}},dt=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");const s=o(this,H,"f");if(!s)throw new m("request ended without sending any chunks");return l(this,H,void 0),os(s,o(this,ee,"f"),{logger:o(this,fe,"f")})},cs=function(s){let n=o(this,H,"f");if(s.type==="message_start"){if(n)throw new m(`Unexpected event order, got ${s.type} before receiving "message_stop"`);return s.message}if(!n)throw new m(`Unexpected event order, got ${s.type} before "message_start"`);switch(s.type){case"message_stop":return n;case"message_delta":return n.container=s.delta.container,n.stop_reason=s.delta.stop_reason,n.stop_sequence=s.delta.stop_sequence,n.usage.output_tokens=s.usage.output_tokens,n.context_management=s.context_management,s.usage.input_tokens!=null&&(n.usage.input_tokens=s.usage.input_tokens),s.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=s.usage.cache_creation_input_tokens),s.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=s.usage.cache_read_input_tokens),s.usage.server_tool_use!=null&&(n.usage.server_tool_use=s.usage.server_tool_use),n;case"content_block_start":return n.content.push(s.content_block),n;case"content_block_delta":{const r=n.content.at(s.index);switch(s.delta.type){case"text_delta":{r?.type==="text"&&(n.content[s.index]={...r,text:(r.text||"")+s.delta.text});break}case"citations_delta":{r?.type==="text"&&(n.content[s.index]={...r,citations:[...r.citations??[],s.delta.citation]});break}case"input_json_delta":{if(r&&ds(r)){let a=r[ls]||"";a+=s.delta.partial_json;const i={...r};if(Object.defineProperty(i,ls,{value:a,enumerable:!1,writable:!0}),a)try{i.input=Vs(a)}catch(u){const c=new m(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${u}. JSON: ${a}`);o(this,qe,"f").call(this,c)}n.content[s.index]=i}break}case"thinking_delta":{r?.type==="thinking"&&(n.content[s.index]={...r,thinking:r.thinking+s.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(n.content[s.index]={...r,signature:s.delta.signature});break}default:s.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){const e=[],s=[];let n=!1;return this.on("streamEvent",r=>{const a=s.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of s)r.resolve(void 0);s.length=0}),this.on("abort",r=>{n=!0;for(const a of s)a.reject(r);s.length=0}),this.on("error",r=>{n=!0;for(const a of s)a.reject(r);s.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>s.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new j(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}const Ur=1e5,$r=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
17
17
  1. Task Overview
18
18
  The user's core request and success criteria
19
19
  Any clarifications or constraints they specified
@@ -35,15 +35,15 @@ User preferences or style requirements
35
35
  Domain-specific details that aren't obvious
36
36
  Any promises made to the user
37
37
  Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
38
- Wrap your summary in <summary></summary> tags.`;var me,te,V,k,ge,I,F,J,_e,hs,St;function ps(){let t,e;return{promise:new Promise((n,r)=>{t=n,e=r}),resolve:t,reject:e}}class Qs{constructor(e,s,n){me.add(this),this.client=e,te.set(this,!1),V.set(this,!1),k.set(this,void 0),ge.set(this,void 0),I.set(this,void 0),F.set(this,void 0),J.set(this,void 0),_e.set(this,0),l(this,k,{params:{...s,messages:structuredClone(s.messages)}}),l(this,ge,{...n,headers:g([{"x-stainless-helper":"BetaToolRunner"},n?.headers])}),l(this,J,ps())}async*[(te=new WeakMap,V=new WeakMap,k=new WeakMap,ge=new WeakMap,I=new WeakMap,F=new WeakMap,J=new WeakMap,_e=new WeakMap,me=new WeakSet,hs=async function(){const s=o(this,k,"f").params.compactionControl;if(!s||!s.enabled)return!1;let n=0;if(o(this,I,"f")!==void 0)try{const h=await o(this,I,"f");n=h.usage.input_tokens+(h.usage.cache_creation_input_tokens??0)+(h.usage.cache_read_input_tokens??0)+h.usage.output_tokens}catch{return!1}const r=s.contextTokenThreshold??Ur;if(n<r)return!1;const a=s.model??o(this,k,"f").params.model,i=s.summaryPrompt??$r,u=o(this,k,"f").params.messages;if(u[u.length-1].role==="assistant"){const h=u[u.length-1];if(Array.isArray(h.content)){const p=h.content.filter(f=>f.type!=="tool_use");p.length===0?u.pop():h.content=p}}const c=await this.client.beta.messages.create({model:a,messages:[...u,{role:"user",content:[{type:"text",text:i}]}],max_tokens:o(this,k,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(c.content[0]?.type!=="text")throw new m("Expected text response for compaction");return o(this,k,"f").params.messages=[{role:"user",content:c.content}],!0},Symbol.asyncIterator)](){var e;if(o(this,te,"f"))throw new m("Cannot iterate over a consumed stream");l(this,te,!0),l(this,V,!0),l(this,F,void 0);try{for(;;){let s;try{if(o(this,k,"f").params.max_iterations&&o(this,_e,"f")>=o(this,k,"f").params.max_iterations)break;l(this,V,!1,"f"),l(this,F,void 0,"f"),l(this,_e,(e=o(this,_e,"f"),e++,e),"f"),l(this,I,void 0,"f");const{max_iterations:n,compactionControl:r,...a}=o(this,k,"f").params;if(a.stream?(s=this.client.beta.messages.stream({...a},o(this,ge,"f")),l(this,I,s.finalMessage(),"f"),o(this,I,"f").catch(()=>{}),yield s):(l(this,I,this.client.beta.messages.create({...a,stream:!1},o(this,ge,"f")),"f"),yield o(this,I,"f")),!await o(this,me,"m",hs).call(this)){if(!o(this,V,"f")){const{role:c,content:h}=await o(this,I,"f");o(this,k,"f").params.messages.push({role:c,content:h})}const u=await o(this,me,"m",St).call(this,o(this,k,"f").params.messages.at(-1));if(u)o(this,k,"f").params.messages.push(u);else if(!o(this,V,"f"))break}}finally{s&&s.abort()}}if(!o(this,I,"f"))throw new m("ToolRunner concluded without a message from the server");o(this,J,"f").resolve(await o(this,I,"f"))}catch(s){throw l(this,te,!1),o(this,J,"f").promise.catch(()=>{}),o(this,J,"f").reject(s),l(this,J,ps()),s}}setMessagesParams(e){typeof e=="function"?o(this,k,"f").params=e(o(this,k,"f").params):o(this,k,"f").params=e,l(this,V,!0),l(this,F,void 0)}async generateToolResponse(){const e=await o(this,I,"f")??this.params.messages.at(-1);return e?o(this,me,"m",St).call(this,e):null}done(){return o(this,J,"f").promise}async runUntilDone(){if(!o(this,te,"f"))for await(const e of this);return this.done()}get params(){return o(this,k,"f").params}pushMessages(...e){this.setMessagesParams(s=>({...s,messages:[...s.messages,...e]}))}then(e,s){return this.runUntilDone().then(e,s)}}St=async function(e){return o(this,F,"f")!==void 0?o(this,F,"f"):(l(this,F,Br(o(this,k,"f").params,e)),o(this,F,"f"))};async function Br(t,e=t.messages.at(-1)){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;const s=e.content.filter(r=>r.type==="tool_use");return s.length===0?null:{role:"user",content:await Promise.all(s.map(async r=>{const a=t.tools.find(i=>("name"in i?i.name:i.mcp_server_name)===r.name);if(!a||!("run"in a))return{type:"tool_result",tool_use_id:r.id,content:`Error: Tool '${r.name}' not found`,is_error:!0};try{let i=r.input;"parse"in a&&a.parse&&(i=a.parse(i));const u=await a.run(i);return{type:"tool_result",tool_use_id:r.id,content:u}}catch(i){return{type:"tool_result",tool_use_id:r.id,content:`Error: ${i instanceof Error?i.message:String(i)}`,is_error:!0}}}))}}class st{constructor(e,s){this.iterator=e,this.controller=s}async*decoder(){const e=new ve;for await(const s of this.iterator)for(const n of e.decode(s))yield JSON.parse(n);for(const s of e.flush())yield JSON.parse(s)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,s){if(!e.body)throw s.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new m("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new m("Attempted to iterate over a response with no body");return new st(Ot(e.body),s)}}let Ys=class extends B{create(e,s){const{betas:n,...r}=e;return this._client.post("/v1/messages/batches?beta=true",{body:r,...s,headers:g([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},s?.headers])})}retrieve(e,s={},n){const{betas:r}=s??{};return this._client.get(S`/v1/messages/batches/${e}?beta=true`,{...n,headers:g([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}list(e={},s){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",Ie,{query:r,...s,headers:g([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},s?.headers])})}delete(e,s={},n){const{betas:r}=s??{};return this._client.delete(S`/v1/messages/batches/${e}?beta=true`,{...n,headers:g([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,s={},n){const{betas:r}=s??{};return this._client.post(S`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:g([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}async results(e,s={},n){const r=await this.retrieve(e);if(!r.results_url)throw new m(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);const{betas:a}=s??{};return this._client.get(r.results_url,{...n,headers:g([{"anthropic-beta":[...a??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((i,u)=>st.fromResponse(u.response,u.controller))}};const fs={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"};let nt=class extends B{constructor(){super(...arguments),this.batches=new Ys(this._client)}create(e,s){const{betas:n,...r}=e;r.model in fs&&console.warn(`The model '${r.model}' is deprecated and will reach end-of-life on ${fs[r.model]}
39
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let a=this._client._options.timeout;if(!r.stream&&a==null){const i=Xs[r.model]??void 0;a=this._client.calculateNonstreamingTimeout(r.max_tokens,i)}return this._client.post("/v1/messages?beta=true",{body:r,timeout:a??6e5,...s,headers:g([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},s?.headers]),stream:e.stream??!1})}parse(e,s){return s={...s,headers:g([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-11-13"].toString()},s?.headers])},this.create(e,s).then(n=>zs(n,e,{logger:this._client.logger??console}))}stream(e,s){return Ye.createMessage(this,e,s)}countTokens(e,s){const{betas:n,...r}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:r,...s,headers:g([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},s?.headers])})}toolRunner(e,s){return new Qs(this._client,e,s)}};nt.Batches=Ys;nt.BetaToolRunner=Qs;class Gs extends B{create(e,s={},n){const{betas:r,...a}=s??{};return this._client.post(S`/v1/skills/${e}/versions?beta=true`,It({body:a,...n,headers:g([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n?.headers])},this._client))}retrieve(e,s,n){const{skill_id:r,betas:a}=s;return this._client.get(S`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:g([{"anthropic-beta":[...a??[],"skills-2025-10-02"].toString()},n?.headers])})}list(e,s={},n){const{betas:r,...a}=s??{};return this._client.getAPIList(S`/v1/skills/${e}/versions?beta=true`,js,{query:a,...n,headers:g([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n?.headers])})}delete(e,s,n){const{skill_id:r,betas:a}=s;return this._client.delete(S`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:g([{"anthropic-beta":[...a??[],"skills-2025-10-02"].toString()},n?.headers])})}}class Rt extends B{constructor(){super(...arguments),this.versions=new Gs(this._client)}create(e={},s){const{betas:n,...r}=e??{};return this._client.post("/v1/skills?beta=true",It({body:r,...s,headers:g([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},s?.headers])},this._client))}retrieve(e,s={},n){const{betas:r}=s??{};return this._client.get(S`/v1/skills/${e}?beta=true`,{...n,headers:g([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n?.headers])})}list(e={},s){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/skills?beta=true",js,{query:r,...s,headers:g([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},s?.headers])})}delete(e,s={},n){const{betas:r}=s??{};return this._client.delete(S`/v1/skills/${e}?beta=true`,{...n,headers:g([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n?.headers])})}}Rt.Versions=Gs;class ae extends B{constructor(){super(...arguments),this.models=new Ks(this._client),this.messages=new nt(this._client),this.files=new Js(this._client),this.skills=new Rt(this._client)}}ae.Models=Ks;ae.Messages=nt;ae.Files=Js;ae.Skills=Rt;class Zs extends B{create(e,s){const{betas:n,...r}=e;return this._client.post("/v1/complete",{body:r,timeout:this._client._options.timeout??6e5,...s,headers:g([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},s?.headers]),stream:e.stream??!1})}}var P,K,ye,We,we,be,De,xe,D,ke,Fe,He,Q,Je,Ke,ht,ms,pt,ft,mt,gt,gs;const _s="__json_buf";function ys(t){return t.type==="tool_use"||t.type==="server_tool_use"}class Ge{constructor(){P.add(this),this.messages=[],this.receivedMessages=[],K.set(this,void 0),this.controller=new AbortController,ye.set(this,void 0),We.set(this,()=>{}),we.set(this,()=>{}),be.set(this,void 0),De.set(this,()=>{}),xe.set(this,()=>{}),D.set(this,{}),ke.set(this,!1),Fe.set(this,!1),He.set(this,!1),Q.set(this,!1),Je.set(this,void 0),Ke.set(this,void 0),pt.set(this,e=>{if(l(this,Fe,!0),Oe(e)&&(e=new U),e instanceof U)return l(this,He,!0),this._emit("abort",e);if(e instanceof m)return this._emit("error",e);if(e instanceof Error){const s=new m(e.message);return s.cause=e,this._emit("error",s)}return this._emit("error",new m(String(e)))}),l(this,ye,new Promise((e,s)=>{l(this,We,e,"f"),l(this,we,s,"f")})),l(this,be,new Promise((e,s)=>{l(this,De,e,"f"),l(this,xe,s,"f")})),o(this,ye,"f").catch(()=>{}),o(this,be,"f").catch(()=>{})}get response(){return o(this,Je,"f")}get request_id(){return o(this,Ke,"f")}async withResponse(){l(this,Q,!0);const e=await o(this,ye,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const s=new Ge;return s._run(()=>s._fromReadableStream(e)),s}static createMessage(e,s,n){const r=new Ge;for(const a of s.messages)r._addMessageParam(a);return r._run(()=>r._createMessage(e,{...s,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},o(this,pt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,s=!0){this.receivedMessages.push(e),s&&this._emit("message",e)}async _createMessage(e,s,n){const r=n?.signal;let a;r&&(r.aborted&&this.controller.abort(),a=this.controller.abort.bind(this.controller),r.addEventListener("abort",a));try{o(this,P,"m",ft).call(this);const{response:i,data:u}=await e.create({...s,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(i);for await(const c of u)o(this,P,"m",mt).call(this,c);if(u.controller.signal?.aborted)throw new U;o(this,P,"m",gt).call(this)}finally{r&&a&&r.removeEventListener("abort",a)}}_connected(e){this.ended||(l(this,Je,e),l(this,Ke,e?.headers.get("request-id")),o(this,We,"f").call(this,e),this._emit("connect"))}get ended(){return o(this,ke,"f")}get errored(){return o(this,Fe,"f")}get aborted(){return o(this,He,"f")}abort(){this.controller.abort()}on(e,s){return(o(this,D,"f")[e]||(o(this,D,"f")[e]=[])).push({listener:s}),this}off(e,s){const n=o(this,D,"f")[e];if(!n)return this;const r=n.findIndex(a=>a.listener===s);return r>=0&&n.splice(r,1),this}once(e,s){return(o(this,D,"f")[e]||(o(this,D,"f")[e]=[])).push({listener:s,once:!0}),this}emitted(e){return new Promise((s,n)=>{l(this,Q,!0),e!=="error"&&this.once("error",n),this.once(e,s)})}async done(){l(this,Q,!0),await o(this,be,"f")}get currentMessage(){return o(this,K,"f")}async finalMessage(){return await this.done(),o(this,P,"m",ht).call(this)}async finalText(){return await this.done(),o(this,P,"m",ms).call(this)}_emit(e,...s){if(o(this,ke,"f"))return;e==="end"&&(l(this,ke,!0),o(this,De,"f").call(this));const n=o(this,D,"f")[e];if(n&&(o(this,D,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...s))),e==="abort"){const r=s[0];!o(this,Q,"f")&&!n?.length&&Promise.reject(r),o(this,we,"f").call(this,r),o(this,xe,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=s[0];!o(this,Q,"f")&&!n?.length&&Promise.reject(r),o(this,we,"f").call(this,r),o(this,xe,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",o(this,P,"m",ht).call(this))}async _fromReadableStream(e,s){const n=s?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{o(this,P,"m",ft).call(this),this._connected(null);const a=j.fromReadableStream(e,this.controller);for await(const i of a)o(this,P,"m",mt).call(this,i);if(a.controller.signal?.aborted)throw new U;o(this,P,"m",gt).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(K=new WeakMap,ye=new WeakMap,We=new WeakMap,we=new WeakMap,be=new WeakMap,De=new WeakMap,xe=new WeakMap,D=new WeakMap,ke=new WeakMap,Fe=new WeakMap,He=new WeakMap,Q=new WeakMap,Je=new WeakMap,Ke=new WeakMap,pt=new WeakMap,P=new WeakSet,ht=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},ms=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");const s=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(s.length===0)throw new m("stream ended without producing a content block with type=text");return s.join(" ")},ft=function(){this.ended||l(this,K,void 0)},mt=function(s){if(this.ended)return;const n=o(this,P,"m",gs).call(this,s);switch(this._emit("streamEvent",s,n),s.type){case"content_block_delta":{const r=n.content.at(-1);switch(s.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",s.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",s.delta.citation,r.citations??[]);break}case"input_json_delta":{ys(r)&&r.input&&this._emit("inputJson",s.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",s.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}default:s.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{l(this,K,n);break}}},gt=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");const s=o(this,K,"f");if(!s)throw new m("request ended without sending any chunks");return l(this,K,void 0),s},gs=function(s){let n=o(this,K,"f");if(s.type==="message_start"){if(n)throw new m(`Unexpected event order, got ${s.type} before receiving "message_stop"`);return s.message}if(!n)throw new m(`Unexpected event order, got ${s.type} before "message_start"`);switch(s.type){case"message_stop":return n;case"message_delta":return n.stop_reason=s.delta.stop_reason,n.stop_sequence=s.delta.stop_sequence,n.usage.output_tokens=s.usage.output_tokens,s.usage.input_tokens!=null&&(n.usage.input_tokens=s.usage.input_tokens),s.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=s.usage.cache_creation_input_tokens),s.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=s.usage.cache_read_input_tokens),s.usage.server_tool_use!=null&&(n.usage.server_tool_use=s.usage.server_tool_use),n;case"content_block_start":return n.content.push({...s.content_block}),n;case"content_block_delta":{const r=n.content.at(s.index);switch(s.delta.type){case"text_delta":{r?.type==="text"&&(n.content[s.index]={...r,text:(r.text||"")+s.delta.text});break}case"citations_delta":{r?.type==="text"&&(n.content[s.index]={...r,citations:[...r.citations??[],s.delta.citation]});break}case"input_json_delta":{if(r&&ys(r)){let a=r[_s]||"";a+=s.delta.partial_json;const i={...r};Object.defineProperty(i,_s,{value:a,enumerable:!1,writable:!0}),a&&(i.input=Vs(a)),n.content[s.index]=i}break}case"thinking_delta":{r?.type==="thinking"&&(n.content[s.index]={...r,thinking:r.thinking+s.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(n.content[s.index]={...r,signature:s.delta.signature});break}default:s.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){const e=[],s=[];let n=!1;return this.on("streamEvent",r=>{const a=s.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of s)r.resolve(void 0);s.length=0}),this.on("abort",r=>{n=!0;for(const a of s)a.reject(r);s.length=0}),this.on("error",r=>{n=!0;for(const a of s)a.reject(r);s.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>s.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new j(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class en extends B{create(e,s){return this._client.post("/v1/messages/batches",{body:e,...s})}retrieve(e,s){return this._client.get(S`/v1/messages/batches/${e}`,s)}list(e={},s){return this._client.getAPIList("/v1/messages/batches",Ie,{query:e,...s})}delete(e,s){return this._client.delete(S`/v1/messages/batches/${e}`,s)}cancel(e,s){return this._client.post(S`/v1/messages/batches/${e}/cancel`,s)}async results(e,s){const n=await this.retrieve(e);if(!n.results_url)throw new m(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...s,headers:g([{Accept:"application/binary"},s?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((r,a)=>st.fromResponse(a.response,a.controller))}}class At extends B{constructor(){super(...arguments),this.batches=new en(this._client)}create(e,s){e.model in ws&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${ws[e.model]}
40
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let n=this._client._options.timeout;if(!e.stream&&n==null){const r=Xs[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,r)}return this._client.post("/v1/messages",{body:e,timeout:n??6e5,...s,stream:e.stream??!1})}stream(e,s){return Ge.createMessage(this,e,s)}countTokens(e,s){return this._client.post("/v1/messages/count_tokens",{body:e,...s})}}const ws={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"};At.Batches=en;class tn extends B{retrieve(e,s={},n){const{betas:r}=s??{};return this._client.get(S`/v1/models/${e}`,{...n,headers:g([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}list(e={},s){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/models",Ie,{query:r,...s,headers:g([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}}var Lr={};const Xe=t=>{if(typeof globalThis.process<"u")return Lr?.[t]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()};var Tt,Ct,Ve,sn;const jr="\\n\\nHuman:",qr="\\n\\nAssistant:";class x{constructor({baseURL:e=Xe("ANTHROPIC_BASE_URL"),apiKey:s=Xe("ANTHROPIC_API_KEY")??null,authToken:n=Xe("ANTHROPIC_AUTH_TOKEN")??null,...r}={}){Tt.add(this),Ve.set(this,void 0);const a={apiKey:s,authToken:n,...r,baseURL:e||"https://api.anthropic.com"};if(!a.dangerouslyAllowBrowser&&ar())throw new m(`It looks like you're running in a browser-like environment.
38
+ Wrap your summary in <summary></summary> tags.`;var me,te,V,S,ge,I,F,J,_e,hs,kt;function ps(){let t,e;return{promise:new Promise((n,r)=>{t=n,e=r}),resolve:t,reject:e}}class Qs{constructor(e,s,n){me.add(this),this.client=e,te.set(this,!1),V.set(this,!1),S.set(this,void 0),ge.set(this,void 0),I.set(this,void 0),F.set(this,void 0),J.set(this,void 0),_e.set(this,0),l(this,S,{params:{...s,messages:structuredClone(s.messages)}}),l(this,ge,{...n,headers:g([{"x-stainless-helper":"BetaToolRunner"},n?.headers])}),l(this,J,ps())}async*[(te=new WeakMap,V=new WeakMap,S=new WeakMap,ge=new WeakMap,I=new WeakMap,F=new WeakMap,J=new WeakMap,_e=new WeakMap,me=new WeakSet,hs=async function(){const s=o(this,S,"f").params.compactionControl;if(!s||!s.enabled)return!1;let n=0;if(o(this,I,"f")!==void 0)try{const h=await o(this,I,"f");n=h.usage.input_tokens+(h.usage.cache_creation_input_tokens??0)+(h.usage.cache_read_input_tokens??0)+h.usage.output_tokens}catch{return!1}const r=s.contextTokenThreshold??Ur;if(n<r)return!1;const a=s.model??o(this,S,"f").params.model,i=s.summaryPrompt??$r,u=o(this,S,"f").params.messages;if(u[u.length-1].role==="assistant"){const h=u[u.length-1];if(Array.isArray(h.content)){const p=h.content.filter(f=>f.type!=="tool_use");p.length===0?u.pop():h.content=p}}const c=await this.client.beta.messages.create({model:a,messages:[...u,{role:"user",content:[{type:"text",text:i}]}],max_tokens:o(this,S,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(c.content[0]?.type!=="text")throw new m("Expected text response for compaction");return o(this,S,"f").params.messages=[{role:"user",content:c.content}],!0},Symbol.asyncIterator)](){var e;if(o(this,te,"f"))throw new m("Cannot iterate over a consumed stream");l(this,te,!0),l(this,V,!0),l(this,F,void 0);try{for(;;){let s;try{if(o(this,S,"f").params.max_iterations&&o(this,_e,"f")>=o(this,S,"f").params.max_iterations)break;l(this,V,!1,"f"),l(this,F,void 0,"f"),l(this,_e,(e=o(this,_e,"f"),e++,e),"f"),l(this,I,void 0,"f");const{max_iterations:n,compactionControl:r,...a}=o(this,S,"f").params;if(a.stream?(s=this.client.beta.messages.stream({...a},o(this,ge,"f")),l(this,I,s.finalMessage(),"f"),o(this,I,"f").catch(()=>{}),yield s):(l(this,I,this.client.beta.messages.create({...a,stream:!1},o(this,ge,"f")),"f"),yield o(this,I,"f")),!await o(this,me,"m",hs).call(this)){if(!o(this,V,"f")){const{role:c,content:h}=await o(this,I,"f");o(this,S,"f").params.messages.push({role:c,content:h})}const u=await o(this,me,"m",kt).call(this,o(this,S,"f").params.messages.at(-1));if(u)o(this,S,"f").params.messages.push(u);else if(!o(this,V,"f"))break}}finally{s&&s.abort()}}if(!o(this,I,"f"))throw new m("ToolRunner concluded without a message from the server");o(this,J,"f").resolve(await o(this,I,"f"))}catch(s){throw l(this,te,!1),o(this,J,"f").promise.catch(()=>{}),o(this,J,"f").reject(s),l(this,J,ps()),s}}setMessagesParams(e){typeof e=="function"?o(this,S,"f").params=e(o(this,S,"f").params):o(this,S,"f").params=e,l(this,V,!0),l(this,F,void 0)}async generateToolResponse(){const e=await o(this,I,"f")??this.params.messages.at(-1);return e?o(this,me,"m",kt).call(this,e):null}done(){return o(this,J,"f").promise}async runUntilDone(){if(!o(this,te,"f"))for await(const e of this);return this.done()}get params(){return o(this,S,"f").params}pushMessages(...e){this.setMessagesParams(s=>({...s,messages:[...s.messages,...e]}))}then(e,s){return this.runUntilDone().then(e,s)}}kt=async function(e){return o(this,F,"f")!==void 0?o(this,F,"f"):(l(this,F,Br(o(this,S,"f").params,e)),o(this,F,"f"))};async function Br(t,e=t.messages.at(-1)){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;const s=e.content.filter(r=>r.type==="tool_use");return s.length===0?null:{role:"user",content:await Promise.all(s.map(async r=>{const a=t.tools.find(i=>("name"in i?i.name:i.mcp_server_name)===r.name);if(!a||!("run"in a))return{type:"tool_result",tool_use_id:r.id,content:`Error: Tool '${r.name}' not found`,is_error:!0};try{let i=r.input;"parse"in a&&a.parse&&(i=a.parse(i));const u=await a.run(i);return{type:"tool_result",tool_use_id:r.id,content:u}}catch(i){return{type:"tool_result",tool_use_id:r.id,content:`Error: ${i instanceof Error?i.message:String(i)}`,is_error:!0}}}))}}class st{constructor(e,s){this.iterator=e,this.controller=s}async*decoder(){const e=new ve;for await(const s of this.iterator)for(const n of e.decode(s))yield JSON.parse(n);for(const s of e.flush())yield JSON.parse(s)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,s){if(!e.body)throw s.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new m("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new m("Attempted to iterate over a response with no body");return new st(Ot(e.body),s)}}let Ys=class extends B{create(e,s){const{betas:n,...r}=e;return this._client.post("/v1/messages/batches?beta=true",{body:r,...s,headers:g([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},s?.headers])})}retrieve(e,s={},n){const{betas:r}=s??{};return this._client.get(k`/v1/messages/batches/${e}?beta=true`,{...n,headers:g([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}list(e={},s){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",Ie,{query:r,...s,headers:g([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},s?.headers])})}delete(e,s={},n){const{betas:r}=s??{};return this._client.delete(k`/v1/messages/batches/${e}?beta=true`,{...n,headers:g([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,s={},n){const{betas:r}=s??{};return this._client.post(k`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:g([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}async results(e,s={},n){const r=await this.retrieve(e);if(!r.results_url)throw new m(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);const{betas:a}=s??{};return this._client.get(r.results_url,{...n,headers:g([{"anthropic-beta":[...a??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((i,u)=>st.fromResponse(u.response,u.controller))}};const fs={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"};let nt=class extends B{constructor(){super(...arguments),this.batches=new Ys(this._client)}create(e,s){const{betas:n,...r}=e;r.model in fs&&console.warn(`The model '${r.model}' is deprecated and will reach end-of-life on ${fs[r.model]}
39
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let a=this._client._options.timeout;if(!r.stream&&a==null){const i=Xs[r.model]??void 0;a=this._client.calculateNonstreamingTimeout(r.max_tokens,i)}return this._client.post("/v1/messages?beta=true",{body:r,timeout:a??6e5,...s,headers:g([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},s?.headers]),stream:e.stream??!1})}parse(e,s){return s={...s,headers:g([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-11-13"].toString()},s?.headers])},this.create(e,s).then(n=>zs(n,e,{logger:this._client.logger??console}))}stream(e,s){return Ye.createMessage(this,e,s)}countTokens(e,s){const{betas:n,...r}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:r,...s,headers:g([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},s?.headers])})}toolRunner(e,s){return new Qs(this._client,e,s)}};nt.Batches=Ys;nt.BetaToolRunner=Qs;class Gs extends B{create(e,s={},n){const{betas:r,...a}=s??{};return this._client.post(k`/v1/skills/${e}/versions?beta=true`,It({body:a,...n,headers:g([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n?.headers])},this._client))}retrieve(e,s,n){const{skill_id:r,betas:a}=s;return this._client.get(k`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:g([{"anthropic-beta":[...a??[],"skills-2025-10-02"].toString()},n?.headers])})}list(e,s={},n){const{betas:r,...a}=s??{};return this._client.getAPIList(k`/v1/skills/${e}/versions?beta=true`,js,{query:a,...n,headers:g([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n?.headers])})}delete(e,s,n){const{skill_id:r,betas:a}=s;return this._client.delete(k`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:g([{"anthropic-beta":[...a??[],"skills-2025-10-02"].toString()},n?.headers])})}}class At extends B{constructor(){super(...arguments),this.versions=new Gs(this._client)}create(e={},s){const{betas:n,...r}=e??{};return this._client.post("/v1/skills?beta=true",It({body:r,...s,headers:g([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},s?.headers])},this._client))}retrieve(e,s={},n){const{betas:r}=s??{};return this._client.get(k`/v1/skills/${e}?beta=true`,{...n,headers:g([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n?.headers])})}list(e={},s){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/skills?beta=true",js,{query:r,...s,headers:g([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},s?.headers])})}delete(e,s={},n){const{betas:r}=s??{};return this._client.delete(k`/v1/skills/${e}?beta=true`,{...n,headers:g([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n?.headers])})}}At.Versions=Gs;class ae extends B{constructor(){super(...arguments),this.models=new Ks(this._client),this.messages=new nt(this._client),this.files=new Js(this._client),this.skills=new At(this._client)}}ae.Models=Ks;ae.Messages=nt;ae.Files=Js;ae.Skills=At;class Zs extends B{create(e,s){const{betas:n,...r}=e;return this._client.post("/v1/complete",{body:r,timeout:this._client._options.timeout??6e5,...s,headers:g([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},s?.headers]),stream:e.stream??!1})}}var P,K,ye,De,we,be,We,xe,W,Se,Fe,He,Q,Je,Ke,ht,ms,pt,ft,mt,gt,gs;const _s="__json_buf";function ys(t){return t.type==="tool_use"||t.type==="server_tool_use"}class Ge{constructor(){P.add(this),this.messages=[],this.receivedMessages=[],K.set(this,void 0),this.controller=new AbortController,ye.set(this,void 0),De.set(this,()=>{}),we.set(this,()=>{}),be.set(this,void 0),We.set(this,()=>{}),xe.set(this,()=>{}),W.set(this,{}),Se.set(this,!1),Fe.set(this,!1),He.set(this,!1),Q.set(this,!1),Je.set(this,void 0),Ke.set(this,void 0),pt.set(this,e=>{if(l(this,Fe,!0),Oe(e)&&(e=new U),e instanceof U)return l(this,He,!0),this._emit("abort",e);if(e instanceof m)return this._emit("error",e);if(e instanceof Error){const s=new m(e.message);return s.cause=e,this._emit("error",s)}return this._emit("error",new m(String(e)))}),l(this,ye,new Promise((e,s)=>{l(this,De,e,"f"),l(this,we,s,"f")})),l(this,be,new Promise((e,s)=>{l(this,We,e,"f"),l(this,xe,s,"f")})),o(this,ye,"f").catch(()=>{}),o(this,be,"f").catch(()=>{})}get response(){return o(this,Je,"f")}get request_id(){return o(this,Ke,"f")}async withResponse(){l(this,Q,!0);const e=await o(this,ye,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const s=new Ge;return s._run(()=>s._fromReadableStream(e)),s}static createMessage(e,s,n){const r=new Ge;for(const a of s.messages)r._addMessageParam(a);return r._run(()=>r._createMessage(e,{...s,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},o(this,pt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,s=!0){this.receivedMessages.push(e),s&&this._emit("message",e)}async _createMessage(e,s,n){const r=n?.signal;let a;r&&(r.aborted&&this.controller.abort(),a=this.controller.abort.bind(this.controller),r.addEventListener("abort",a));try{o(this,P,"m",ft).call(this);const{response:i,data:u}=await e.create({...s,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(i);for await(const c of u)o(this,P,"m",mt).call(this,c);if(u.controller.signal?.aborted)throw new U;o(this,P,"m",gt).call(this)}finally{r&&a&&r.removeEventListener("abort",a)}}_connected(e){this.ended||(l(this,Je,e),l(this,Ke,e?.headers.get("request-id")),o(this,De,"f").call(this,e),this._emit("connect"))}get ended(){return o(this,Se,"f")}get errored(){return o(this,Fe,"f")}get aborted(){return o(this,He,"f")}abort(){this.controller.abort()}on(e,s){return(o(this,W,"f")[e]||(o(this,W,"f")[e]=[])).push({listener:s}),this}off(e,s){const n=o(this,W,"f")[e];if(!n)return this;const r=n.findIndex(a=>a.listener===s);return r>=0&&n.splice(r,1),this}once(e,s){return(o(this,W,"f")[e]||(o(this,W,"f")[e]=[])).push({listener:s,once:!0}),this}emitted(e){return new Promise((s,n)=>{l(this,Q,!0),e!=="error"&&this.once("error",n),this.once(e,s)})}async done(){l(this,Q,!0),await o(this,be,"f")}get currentMessage(){return o(this,K,"f")}async finalMessage(){return await this.done(),o(this,P,"m",ht).call(this)}async finalText(){return await this.done(),o(this,P,"m",ms).call(this)}_emit(e,...s){if(o(this,Se,"f"))return;e==="end"&&(l(this,Se,!0),o(this,We,"f").call(this));const n=o(this,W,"f")[e];if(n&&(o(this,W,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...s))),e==="abort"){const r=s[0];!o(this,Q,"f")&&!n?.length&&Promise.reject(r),o(this,we,"f").call(this,r),o(this,xe,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=s[0];!o(this,Q,"f")&&!n?.length&&Promise.reject(r),o(this,we,"f").call(this,r),o(this,xe,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",o(this,P,"m",ht).call(this))}async _fromReadableStream(e,s){const n=s?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{o(this,P,"m",ft).call(this),this._connected(null);const a=j.fromReadableStream(e,this.controller);for await(const i of a)o(this,P,"m",mt).call(this,i);if(a.controller.signal?.aborted)throw new U;o(this,P,"m",gt).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(K=new WeakMap,ye=new WeakMap,De=new WeakMap,we=new WeakMap,be=new WeakMap,We=new WeakMap,xe=new WeakMap,W=new WeakMap,Se=new WeakMap,Fe=new WeakMap,He=new WeakMap,Q=new WeakMap,Je=new WeakMap,Ke=new WeakMap,pt=new WeakMap,P=new WeakSet,ht=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},ms=function(){if(this.receivedMessages.length===0)throw new m("stream ended without producing a Message with role=assistant");const s=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(s.length===0)throw new m("stream ended without producing a content block with type=text");return s.join(" ")},ft=function(){this.ended||l(this,K,void 0)},mt=function(s){if(this.ended)return;const n=o(this,P,"m",gs).call(this,s);switch(this._emit("streamEvent",s,n),s.type){case"content_block_delta":{const r=n.content.at(-1);switch(s.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",s.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",s.delta.citation,r.citations??[]);break}case"input_json_delta":{ys(r)&&r.input&&this._emit("inputJson",s.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",s.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}default:s.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{l(this,K,n);break}}},gt=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");const s=o(this,K,"f");if(!s)throw new m("request ended without sending any chunks");return l(this,K,void 0),s},gs=function(s){let n=o(this,K,"f");if(s.type==="message_start"){if(n)throw new m(`Unexpected event order, got ${s.type} before receiving "message_stop"`);return s.message}if(!n)throw new m(`Unexpected event order, got ${s.type} before "message_start"`);switch(s.type){case"message_stop":return n;case"message_delta":return n.stop_reason=s.delta.stop_reason,n.stop_sequence=s.delta.stop_sequence,n.usage.output_tokens=s.usage.output_tokens,s.usage.input_tokens!=null&&(n.usage.input_tokens=s.usage.input_tokens),s.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=s.usage.cache_creation_input_tokens),s.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=s.usage.cache_read_input_tokens),s.usage.server_tool_use!=null&&(n.usage.server_tool_use=s.usage.server_tool_use),n;case"content_block_start":return n.content.push({...s.content_block}),n;case"content_block_delta":{const r=n.content.at(s.index);switch(s.delta.type){case"text_delta":{r?.type==="text"&&(n.content[s.index]={...r,text:(r.text||"")+s.delta.text});break}case"citations_delta":{r?.type==="text"&&(n.content[s.index]={...r,citations:[...r.citations??[],s.delta.citation]});break}case"input_json_delta":{if(r&&ys(r)){let a=r[_s]||"";a+=s.delta.partial_json;const i={...r};Object.defineProperty(i,_s,{value:a,enumerable:!1,writable:!0}),a&&(i.input=Vs(a)),n.content[s.index]=i}break}case"thinking_delta":{r?.type==="thinking"&&(n.content[s.index]={...r,thinking:r.thinking+s.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(n.content[s.index]={...r,signature:s.delta.signature});break}default:s.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){const e=[],s=[];let n=!1;return this.on("streamEvent",r=>{const a=s.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of s)r.resolve(void 0);s.length=0}),this.on("abort",r=>{n=!0;for(const a of s)a.reject(r);s.length=0}),this.on("error",r=>{n=!0;for(const a of s)a.reject(r);s.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>s.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new j(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class en extends B{create(e,s){return this._client.post("/v1/messages/batches",{body:e,...s})}retrieve(e,s){return this._client.get(k`/v1/messages/batches/${e}`,s)}list(e={},s){return this._client.getAPIList("/v1/messages/batches",Ie,{query:e,...s})}delete(e,s){return this._client.delete(k`/v1/messages/batches/${e}`,s)}cancel(e,s){return this._client.post(k`/v1/messages/batches/${e}/cancel`,s)}async results(e,s){const n=await this.retrieve(e);if(!n.results_url)throw new m(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...s,headers:g([{Accept:"application/binary"},s?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((r,a)=>st.fromResponse(a.response,a.controller))}}class Rt extends B{constructor(){super(...arguments),this.batches=new en(this._client)}create(e,s){e.model in ws&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${ws[e.model]}
40
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let n=this._client._options.timeout;if(!e.stream&&n==null){const r=Xs[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,r)}return this._client.post("/v1/messages",{body:e,timeout:n??6e5,...s,stream:e.stream??!1})}stream(e,s){return Ge.createMessage(this,e,s)}countTokens(e,s){return this._client.post("/v1/messages/count_tokens",{body:e,...s})}}const ws={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"};Rt.Batches=en;class tn extends B{retrieve(e,s={},n){const{betas:r}=s??{};return this._client.get(k`/v1/models/${e}`,{...n,headers:g([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}list(e={},s){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/models",Ie,{query:r,...s,headers:g([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},s?.headers])})}}var Lr={};const Xe=t=>{if(typeof globalThis.process<"u")return Lr?.[t]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()};var Tt,Ct,Ve,sn;const jr="\\n\\nHuman:",qr="\\n\\nAssistant:";class x{constructor({baseURL:e=Xe("ANTHROPIC_BASE_URL"),apiKey:s=Xe("ANTHROPIC_API_KEY")??null,authToken:n=Xe("ANTHROPIC_AUTH_TOKEN")??null,...r}={}){Tt.add(this),Ve.set(this,void 0);const a={apiKey:s,authToken:n,...r,baseURL:e||"https://api.anthropic.com"};if(!a.dangerouslyAllowBrowser&&ar())throw new m(`It looks like you're running in a browser-like environment.
41
41
 
42
42
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
43
43
  If you understand the risks and have appropriate mitigations in place,
44
44
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
45
45
 
46
46
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
47
- `);this.baseURL=a.baseURL,this.timeout=a.timeout??Ct.DEFAULT_TIMEOUT,this.logger=a.logger??console;const i="warn";this.logLevel=i,this.logLevel=ns(a.logLevel,"ClientOptions.logLevel",this)??ns(Xe("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??i,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??lr(),l(this,Ve,hr),this._options=a,this.apiKey=typeof s=="string"?s:null,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:s}){if(!(e.get("x-api-key")||e.get("authorization"))&&!(this.apiKey&&e.get("x-api-key"))&&!s.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!s.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return g([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return g([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return g([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([s,n])=>typeof n<"u").map(([s,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(s)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(s)}=`;throw new m(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${se}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ss()}`}makeStatusError(e,s,n,r){return T.generate(e,s,n,r)}buildURL(e,s,n){const r=!o(this,Tt,"m",sn).call(this)&&n||this.baseURL,a=er(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return tr(i)||(s={...i,...s}),typeof s=="object"&&s&&!Array.isArray(s)&&(a.search=this.stringifyQuery(s)),a.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new m("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:s,options:n}){}get(e,s){return this.methodRequest("get",e,s)}post(e,s){return this.methodRequest("post",e,s)}patch(e,s){return this.methodRequest("patch",e,s)}put(e,s){return this.methodRequest("put",e,s)}delete(e,s){return this.methodRequest("delete",e,s)}methodRequest(e,s,n){return this.request(Promise.resolve(n).then(r=>({method:e,path:s,...r})))}request(e,s=null){return new tt(this,this.makeRequest(e,s,void 0))}async makeRequest(e,s,n){const r=await e,a=r.maxRetries??this.maxRetries;s==null&&(s=a),await this.prepareOptions(r);const{req:i,url:u,timeout:c}=await this.buildRequest(r,{retryCount:a-s});await this.prepareRequest(i,{url:u,options:r});const h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),p=n===void 0?"":`, retryOf: ${n}`,f=Date.now();if(M(this).debug(`[${h}] sending request`,Y({retryOfRequestLogID:n,method:r.method,url:u,options:r,headers:i.headers})),r.signal?.aborted)throw new U;const _=new AbortController,d=await this.fetchWithTimeout(u,i,c,_).catch(yt),v=Date.now();if(d instanceof globalThis.Error){const q=`retrying, ${s} attempts remaining`;if(r.signal?.aborted)throw new U;const L=Oe(d)||/timed? ?out/i.test(String(d)+("cause"in d?String(d.cause):""));if(s)return M(this).info(`[${h}] connection ${L?"timed out":"failed"} - ${q}`),M(this).debug(`[${h}] connection ${L?"timed out":"failed"} (${q})`,Y({retryOfRequestLogID:n,url:u,durationMs:v-f,message:d.message})),this.retryRequest(r,s,n??h);throw M(this).info(`[${h}] connection ${L?"timed out":"failed"} - error; no more retries left`),M(this).debug(`[${h}] connection ${L?"timed out":"failed"} (error; no more retries left)`,Y({retryOfRequestLogID:n,url:u,durationMs:v-f,message:d.message})),L?new Ts:new et({cause:d})}const X=[...d.headers.entries()].filter(([q])=>q==="request-id").map(([q,L])=>", "+q+": "+JSON.stringify(L)).join(""),rt=`[${h}${p}${X}] ${i.method} ${u} ${d.ok?"succeeded":"failed"} with status ${d.status} in ${v-f}ms`;if(!d.ok){const q=await this.shouldRetry(d);if(s&&q){const Ae=`retrying, ${s} attempts remaining`;return await dr(d.body),M(this).info(`${rt} - ${Ae}`),M(this).debug(`[${h}] response error (${Ae})`,Y({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:v-f})),this.retryRequest(r,s,n??h,d.headers)}const L=q?"error; no more retries left":"error; not retryable";M(this).info(`${rt} - ${L}`);const Pt=await d.text().catch(Ae=>yt(Ae).message),Et=Es(Pt),Nt=Et?void 0:Pt;throw M(this).debug(`[${h}] response error (${L})`,Y({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,message:Nt,durationMs:Date.now()-f})),this.makeStatusError(d.status,Et,Nt,d.headers)}return M(this).info(rt),M(this).debug(`[${h}] response start`,Y({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:v-f})),{response:d,options:r,controller:_,requestLogID:h,retryOfRequestLogID:n,startTime:f}}getAPIList(e,s,n){return this.requestAPIList(s,{method:"get",path:e,...n})}requestAPIList(e,s){const n=this.makeRequest(s,null,void 0);return new xr(this,n,e)}async fetchWithTimeout(e,s,n,r){const{signal:a,method:i,...u}=s||{};a&&a.addEventListener("abort",()=>r.abort());const c=setTimeout(()=>r.abort(),n),h=globalThis.ReadableStream&&u.body instanceof globalThis.ReadableStream||typeof u.body=="object"&&u.body!==null&&Symbol.asyncIterator in u.body,p={signal:r.signal,...h?{duplex:"half"}:{},method:"GET",...u};i&&(p.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,p)}finally{clearTimeout(c)}}async shouldRetry(e){const s=e.headers.get("x-should-retry");return s==="true"?!0:s==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,s,n,r){let a;const i=r?.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(a=c)}const u=r?.get("retry-after");if(u&&!a){const c=parseFloat(u);Number.isNaN(c)?a=Date.parse(u)-Date.now():a=c*1e3}if(!(a&&0<=a&&a<60*1e3)){const c=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(s,c)}return await rr(a),this.makeRequest(e,s-1,n)}calculateDefaultRetryTimeoutMillis(e,s){const a=s-e,i=Math.min(.5*Math.pow(2,a),8),u=1-Math.random()*.25;return i*u*1e3}calculateNonstreamingTimeout(e,s){if(36e5*e/128e3>6e5||s!=null&&e>s)throw new m("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:s=0}={}){const n={...e},{method:r,path:a,query:i,defaultBaseURL:u}=n,c=this.buildURL(a,i,u);"timeout"in n&&nr("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:h,body:p}=this.buildBody({options:n}),f=await this.buildHeaders({options:e,method:r,bodyHeaders:h,retryCount:s});return{req:{method:r,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&p instanceof globalThis.ReadableStream&&{duplex:"half"},...p&&{body:p},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:s,bodyHeaders:n,retryCount:r}){let a={};this.idempotencyHeader&&s!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const i=g([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...cr(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:s}}){if(!e)return{bodyHeaders:void 0,body:void 0};const n=g([s]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Us(e)}:o(this,Ve,"f").call(this,{body:e,headers:n})}}Ct=x,Ve=new WeakMap,Tt=new WeakSet,sn=function(){return this.baseURL!=="https://api.anthropic.com"};x.Anthropic=Ct;x.HUMAN_PROMPT=jr;x.AI_PROMPT=qr;x.DEFAULT_TIMEOUT=6e5;x.AnthropicError=m;x.APIError=T;x.APIConnectionError=et;x.APIConnectionTimeoutError=Ts;x.APIUserAbortError=U;x.NotFoundError=Is;x.ConflictError=Rs;x.RateLimitError=Cs;x.BadRequestError=Ms;x.AuthenticationError=Os;x.InternalServerError=Ps;x.PermissionDeniedError=vs;x.UnprocessableEntityError=As;x.toFile=vr;class Re extends x{constructor(){super(...arguments),this.completions=new Zs(this),this.messages=new At(this),this.models=new tn(this),this.beta=new ae(this)}}Re.Completions=Zs;Re.Messages=At;Re.Models=tn;Re.Beta=ae;const Wr=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]);function Dr(t){return JSON.parse(JSON.stringify(t))}function Fr(t){const e=Dr(t);return G(e)}function G(t){const e={},s=O(t,"$ref");if(s!==void 0)return e.$ref=s,e;const n=O(t,"$defs");if(n!==void 0){const p={};e.$defs=p;for(const[f,_]of Object.entries(n))p[f]=G(_)}const r=O(t,"type"),a=O(t,"anyOf"),i=O(t,"oneOf"),u=O(t,"allOf");if(Array.isArray(a))e.anyOf=a.map(p=>G(p));else if(Array.isArray(i))e.anyOf=i.map(p=>G(p));else if(Array.isArray(u))e.allOf=u.map(p=>G(p));else{if(r===void 0)throw new Error("JSON schema must have a type defined if anyOf/oneOf/allOf are not used");e.type=r}const c=O(t,"description");c!==void 0&&(e.description=c);const h=O(t,"title");if(h!==void 0&&(e.title=h),r==="object"){const p=O(t,"properties")||{};e.properties=Object.fromEntries(Object.entries(p).map(([_,d])=>[_,G(d)])),O(t,"additionalProperties"),e.additionalProperties=!1;const f=O(t,"required");f!==void 0&&(e.required=f)}else if(r==="string"){const p=O(t,"format");p!==void 0&&Wr.has(p)?e.format=p:p!==void 0&&(t.format=p)}else if(r==="array"){const p=O(t,"items");p!==void 0&&(e.items=G(p));const f=O(t,"minItems");f!==void 0&&(f===0||f===1)?e.minItems=f:f!==void 0&&(t.minItems=f)}if(Object.keys(t).length>0){const p=e.description;e.description=(p?p+`
47
+ `);this.baseURL=a.baseURL,this.timeout=a.timeout??Ct.DEFAULT_TIMEOUT,this.logger=a.logger??console;const i="warn";this.logLevel=i,this.logLevel=ns(a.logLevel,"ClientOptions.logLevel",this)??ns(Xe("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??i,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??lr(),l(this,Ve,hr),this._options=a,this.apiKey=typeof s=="string"?s:null,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:s}){if(!(e.get("x-api-key")||e.get("authorization"))&&!(this.apiKey&&e.get("x-api-key"))&&!s.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!s.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return g([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return g([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return g([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([s,n])=>typeof n<"u").map(([s,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(s)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(s)}=`;throw new m(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${se}`}defaultIdempotencyKey(){return`stainless-node-retry-${ks()}`}makeStatusError(e,s,n,r){return T.generate(e,s,n,r)}buildURL(e,s,n){const r=!o(this,Tt,"m",sn).call(this)&&n||this.baseURL,a=er(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return tr(i)||(s={...i,...s}),typeof s=="object"&&s&&!Array.isArray(s)&&(a.search=this.stringifyQuery(s)),a.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new m("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:s,options:n}){}get(e,s){return this.methodRequest("get",e,s)}post(e,s){return this.methodRequest("post",e,s)}patch(e,s){return this.methodRequest("patch",e,s)}put(e,s){return this.methodRequest("put",e,s)}delete(e,s){return this.methodRequest("delete",e,s)}methodRequest(e,s,n){return this.request(Promise.resolve(n).then(r=>({method:e,path:s,...r})))}request(e,s=null){return new tt(this,this.makeRequest(e,s,void 0))}async makeRequest(e,s,n){const r=await e,a=r.maxRetries??this.maxRetries;s==null&&(s=a),await this.prepareOptions(r);const{req:i,url:u,timeout:c}=await this.buildRequest(r,{retryCount:a-s});await this.prepareRequest(i,{url:u,options:r});const h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),p=n===void 0?"":`, retryOf: ${n}`,f=Date.now();if(M(this).debug(`[${h}] sending request`,Y({retryOfRequestLogID:n,method:r.method,url:u,options:r,headers:i.headers})),r.signal?.aborted)throw new U;const _=new AbortController,d=await this.fetchWithTimeout(u,i,c,_).catch(yt),v=Date.now();if(d instanceof globalThis.Error){const q=`retrying, ${s} attempts remaining`;if(r.signal?.aborted)throw new U;const L=Oe(d)||/timed? ?out/i.test(String(d)+("cause"in d?String(d.cause):""));if(s)return M(this).info(`[${h}] connection ${L?"timed out":"failed"} - ${q}`),M(this).debug(`[${h}] connection ${L?"timed out":"failed"} (${q})`,Y({retryOfRequestLogID:n,url:u,durationMs:v-f,message:d.message})),this.retryRequest(r,s,n??h);throw M(this).info(`[${h}] connection ${L?"timed out":"failed"} - error; no more retries left`),M(this).debug(`[${h}] connection ${L?"timed out":"failed"} (error; no more retries left)`,Y({retryOfRequestLogID:n,url:u,durationMs:v-f,message:d.message})),L?new Ts:new et({cause:d})}const X=[...d.headers.entries()].filter(([q])=>q==="request-id").map(([q,L])=>", "+q+": "+JSON.stringify(L)).join(""),rt=`[${h}${p}${X}] ${i.method} ${u} ${d.ok?"succeeded":"failed"} with status ${d.status} in ${v-f}ms`;if(!d.ok){const q=await this.shouldRetry(d);if(s&&q){const Re=`retrying, ${s} attempts remaining`;return await dr(d.body),M(this).info(`${rt} - ${Re}`),M(this).debug(`[${h}] response error (${Re})`,Y({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:v-f})),this.retryRequest(r,s,n??h,d.headers)}const L=q?"error; no more retries left":"error; not retryable";M(this).info(`${rt} - ${L}`);const Pt=await d.text().catch(Re=>yt(Re).message),Et=Es(Pt),Nt=Et?void 0:Pt;throw M(this).debug(`[${h}] response error (${L})`,Y({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,message:Nt,durationMs:Date.now()-f})),this.makeStatusError(d.status,Et,Nt,d.headers)}return M(this).info(rt),M(this).debug(`[${h}] response start`,Y({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:v-f})),{response:d,options:r,controller:_,requestLogID:h,retryOfRequestLogID:n,startTime:f}}getAPIList(e,s,n){return this.requestAPIList(s,{method:"get",path:e,...n})}requestAPIList(e,s){const n=this.makeRequest(s,null,void 0);return new xr(this,n,e)}async fetchWithTimeout(e,s,n,r){const{signal:a,method:i,...u}=s||{};a&&a.addEventListener("abort",()=>r.abort());const c=setTimeout(()=>r.abort(),n),h=globalThis.ReadableStream&&u.body instanceof globalThis.ReadableStream||typeof u.body=="object"&&u.body!==null&&Symbol.asyncIterator in u.body,p={signal:r.signal,...h?{duplex:"half"}:{},method:"GET",...u};i&&(p.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,p)}finally{clearTimeout(c)}}async shouldRetry(e){const s=e.headers.get("x-should-retry");return s==="true"?!0:s==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,s,n,r){let a;const i=r?.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(a=c)}const u=r?.get("retry-after");if(u&&!a){const c=parseFloat(u);Number.isNaN(c)?a=Date.parse(u)-Date.now():a=c*1e3}if(!(a&&0<=a&&a<60*1e3)){const c=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(s,c)}return await rr(a),this.makeRequest(e,s-1,n)}calculateDefaultRetryTimeoutMillis(e,s){const a=s-e,i=Math.min(.5*Math.pow(2,a),8),u=1-Math.random()*.25;return i*u*1e3}calculateNonstreamingTimeout(e,s){if(36e5*e/128e3>6e5||s!=null&&e>s)throw new m("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:s=0}={}){const n={...e},{method:r,path:a,query:i,defaultBaseURL:u}=n,c=this.buildURL(a,i,u);"timeout"in n&&nr("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:h,body:p}=this.buildBody({options:n}),f=await this.buildHeaders({options:e,method:r,bodyHeaders:h,retryCount:s});return{req:{method:r,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&p instanceof globalThis.ReadableStream&&{duplex:"half"},...p&&{body:p},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:s,bodyHeaders:n,retryCount:r}){let a={};this.idempotencyHeader&&s!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const i=g([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...cr(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:s}}){if(!e)return{bodyHeaders:void 0,body:void 0};const n=g([s]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Us(e)}:o(this,Ve,"f").call(this,{body:e,headers:n})}}Ct=x,Ve=new WeakMap,Tt=new WeakSet,sn=function(){return this.baseURL!=="https://api.anthropic.com"};x.Anthropic=Ct;x.HUMAN_PROMPT=jr;x.AI_PROMPT=qr;x.DEFAULT_TIMEOUT=6e5;x.AnthropicError=m;x.APIError=T;x.APIConnectionError=et;x.APIConnectionTimeoutError=Ts;x.APIUserAbortError=U;x.NotFoundError=Is;x.ConflictError=As;x.RateLimitError=Cs;x.BadRequestError=Ms;x.AuthenticationError=Os;x.InternalServerError=Ps;x.PermissionDeniedError=vs;x.UnprocessableEntityError=Rs;x.toFile=vr;class Ae extends x{constructor(){super(...arguments),this.completions=new Zs(this),this.messages=new Rt(this),this.models=new tn(this),this.beta=new ae(this)}}Ae.Completions=Zs;Ae.Messages=Rt;Ae.Models=tn;Ae.Beta=ae;const Dr=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]);function Wr(t){return JSON.parse(JSON.stringify(t))}function Fr(t){const e=Wr(t);return G(e)}function G(t){const e={},s=O(t,"$ref");if(s!==void 0)return e.$ref=s,e;const n=O(t,"$defs");if(n!==void 0){const p={};e.$defs=p;for(const[f,_]of Object.entries(n))p[f]=G(_)}const r=O(t,"type"),a=O(t,"anyOf"),i=O(t,"oneOf"),u=O(t,"allOf");if(Array.isArray(a))e.anyOf=a.map(p=>G(p));else if(Array.isArray(i))e.anyOf=i.map(p=>G(p));else if(Array.isArray(u))e.allOf=u.map(p=>G(p));else{if(r===void 0)throw new Error("JSON schema must have a type defined if anyOf/oneOf/allOf are not used");e.type=r}const c=O(t,"description");c!==void 0&&(e.description=c);const h=O(t,"title");if(h!==void 0&&(e.title=h),r==="object"){const p=O(t,"properties")||{};e.properties=Object.fromEntries(Object.entries(p).map(([_,d])=>[_,G(d)])),O(t,"additionalProperties"),e.additionalProperties=!1;const f=O(t,"required");f!==void 0&&(e.required=f)}else if(r==="string"){const p=O(t,"format");p!==void 0&&Dr.has(p)?e.format=p:p!==void 0&&(t.format=p)}else if(r==="array"){const p=O(t,"items");p!==void 0&&(e.items=G(p));const f=O(t,"minItems");f!==void 0&&(f===0||f===1)?e.minItems=f:f!==void 0&&(t.minItems=f)}if(Object.keys(t).length>0){const p=e.description;e.description=(p?p+`
48
48
 
49
- `:"")+"{"+Object.entries(t).map(([f,_])=>`${f}: ${JSON.stringify(_)}`).join(", ")+"}"}return e}const Hr={"claude-opus-4-1":8192,"claude-opus-4":8192,"claude-sonnet-4":8192,"claude-sonnet-3-7-sonnet":8192,"claude-3-5-sonnet":4096,"claude-3-5-haiku":4096,"claude-3-haiku":2048},bs=2048;function Jr(t){return t?Object.entries(Hr).find(([s])=>t.startsWith(s))?.[1]??bs:bs}function Kr(t){return!!(t.tools&&t.tools.length>0)}function Xr(t){for(const e of t.messages??[])if(typeof e.content!="string"){for(const s of e.content??[])if(typeof s=="object"&&s!=null&&s.type==="document"&&typeof s.citations=="object"&&s.citations?.enabled)return!0}return!1}function zr(t){return!!(t.thinking&&t.thinking.type==="enabled")}function Vr(t){return"input_schema"in t}function Qr(t){const e=["text_editor_","computer_","bash_","web_search_","web_fetch_","str_replace_editor_","str_replace_based_edit_tool_","code_execution_","memory_","tool_search_","mcp_toolset"];return typeof t=="object"&&t!==null&&"type"in t&&("name"in t||"mcp_server_name"in t)&&typeof t.type=="string"&&e.some(s=>typeof t.type=="string"&&t.type.startsWith(s))}function Yr(t,e,...s){return Array.from(new Set([...t??[],...e??[],...s.flatMap(n=>Array.from(n))]))}function Gr(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0]&&typeof t.content[0].text=="string")return t.content[0].text}var Zr=class extends bn{static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}lc_serializable=!0;anthropicApiKey;apiKey;apiUrl;temperature;topK;topP;maxTokens;modelName="claude-3-5-sonnet-latest";model="claude-3-5-sonnet-latest";invocationKwargs;stopSequences;streaming=!1;clientOptions;thinking={type:"disabled"};contextManagement;batchClient;streamingClient;streamUsage=!0;betas;createClient;constructor(t){if(super(t??{}),this.anthropicApiKey=t?.apiKey??t?.anthropicApiKey??vn("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!t?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=t?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=t?.anthropicApiUrl,this.modelName=t?.model??t?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=t?.invocationKwargs??{},this.topP=t?.topP??this.topP,this.temperature=t?.temperature??this.temperature,this.topK=t?.topK??this.topK,this.maxTokens=t?.maxTokens??Jr(this.model),this.stopSequences=t?.stopSequences??this.stopSequences,this.streaming=t?.streaming??!1,this.streamUsage=t?.streamUsage??this.streamUsage,this.thinking=t?.thinking??this.thinking,this.contextManagement=t?.contextManagement??this.contextManagement,this.betas=t?.betas??this.betas,this.createClient=t?.createClient??(e=>new Re(e))}getLsParams(t){const e=this.invocationParams(t);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}formatStructuredToolToAnthropic(t){if(!(!t||!t.length))return t.map(e=>{if($t(e)&&e.extras?.providerToolDefinition)return e.extras.providerToolDefinition;if(Qr(e)||Vr(e))return e;if(xn(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if($t(e))return{name:e.name,description:e.description,input_schema:at(e.schema)?ie(e.schema):e.schema,...e.extras?Un.parse(e.extras):{}};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)})}bindTools(t,e){return this.withConfig({tools:this.formatStructuredToolToAnthropic(t),...e})}invocationParams(t){const e=Nn(t?.tool_choice),s=t?.tools?.reduce((r,a)=>{if(typeof a=="object"&&"type"in a&&a.type in Ht){const i=Ht[a.type];if(!r.includes(i))return[...r,i]}return r},[]),n={model:this.model,stop_sequences:t?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(t?.tools),tool_choice:e,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:t?.container,betas:Yr(this.betas,t?.betas,s??[]),output_format:t?.output_format,mcp_servers:t?.mcp_servers};if(this.thinking.type==="enabled"){if(this.topP!==void 0&&this.topK!==-1)throw new Error("topK is not supported when thinking is enabled");if(this.temperature!==void 0&&this.temperature!==1)throw new Error("temperature is not supported when thinking is enabled")}else n.temperature=this.temperature,n.top_k=this.topK,n.top_p=this.topP;return n}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(t,e,s){const n=this.invocationParams(e),r=zt(t),a={...n,...r,stream:!0},i=!Kr(a)&&!Xr(a)&&!zr(a),u=await this.createStreamWithRetry(a,{headers:e.headers});for await(const c of u){if(e.signal?.aborted)throw u.controller.abort(),new Error("AbortError: User aborted the request.");const h=this.streamUsage??e.streamUsage,p=Vn(c,{streamUsage:h,coerceContentToString:i});if(!p)continue;const{chunk:f}=p,_=Gr(f),d=new In({message:new N({content:f.content,additional_kwargs:f.additional_kwargs,tool_call_chunks:f.tool_call_chunks,usage_metadata:h?f.usage_metadata:void 0,response_metadata:f.response_metadata,id:f.id}),text:_??""});yield d,await s?.handleLLMNewToken(_??"",void 0,void 0,void 0,void 0,{chunk:d})}}async _generateNonStreaming(t,e,s){const n=await this.completionWithRetry({...e,stream:!1,...zt(t)},s),{content:r,...a}=n,i=Qn(r,a),{role:u,type:c,...h}=a;return{generations:i,llmOutput:h}}async _generate(t,e,s){if(this.stopSequences&&e.stop)throw new Error('"stopSequence" parameter found in input and default params');const n=this.invocationParams(e);if(n.stream){let r;const a=this._streamResponseChunks(t,e,s);for await(const i of a)r===void 0?r=i:r=r.concat(i);if(r===void 0)throw new Error("No chunks returned from Anthropic API.");return{generations:[{text:r.text,message:r.message}]}}else return this._generateNonStreaming(t,n,{signal:e.signal,headers:e.headers})}async createStreamWithRetry(t,e){if(!this.streamingClient){const a=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...a,apiKey:this.apiKey,maxRetries:0})}const{betas:s,...n}=t,r=async()=>{try{return t?.betas?.length?await this.streamingClient.beta.messages.create({...n,betas:s,...this.invocationKwargs,stream:!0},e):await this.streamingClient.messages.create({...n,...this.invocationKwargs,stream:!0},e)}catch(a){throw Vt(a)}};return this.caller.call(r)}async completionWithRetry(t,e){if(!this.batchClient){const a=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...a,apiKey:this.apiKey,maxRetries:0})}const{betas:s,...n}=t,r=async()=>{try{return t?.betas?.length?await this.batchClient.beta.messages.create({...n,...this.invocationKwargs,betas:s},e):await this.batchClient.messages.create({...n,...this.invocationKwargs},e)}catch(a){throw Vt(a)}};return this.caller.callWithOptions({signal:e.signal??void 0},r)}_llmType(){return"anthropic"}get profile(){return Gn[this.model]??{}}withStructuredOutput(t,e){let s,n;const{schema:r,name:a,includeRaw:i}={...e,schema:t};let u=e?.method??"functionCalling";if(u==="jsonMode"&&(console.warn('"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".'),u="jsonSchema"),u==="jsonSchema"){n=at(r)?kn.fromZodSchema(r):new Sn;const f=Fr(ie(r));s=this.withConfig({outputVersion:"v0",output_format:{type:"json_schema",schema:f},betas:["structured-outputs-2025-11-13"],ls_structured_output_format:{kwargs:{method:"json_schema"},schema:f}})}else if(u==="functionCalling"){let f=a??"extract",_;if(at(r)){const d=ie(r);_=[{name:f,description:d.description??"A function available to call.",input_schema:d}],n=new Ft({returnSingle:!0,keyName:f,zodSchema:r})}else{let d;typeof r.name=="string"&&typeof r.description=="string"&&typeof r.input_schema=="object"&&r.input_schema!=null?(d=r,f=r.name):d={name:f,description:r.description??"",input_schema:r},_=[d],n=new Ft({returnSingle:!0,keyName:f})}if(this.thinking?.type==="enabled"){const d="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(d),s=this.withConfig({outputVersion:"v0",tools:_,ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:ie(r)}});const v=X=>{if(!X.tool_calls||X.tool_calls.length===0)throw new Error(d);return X};s=s.pipe(v)}else s=this.withConfig({outputVersion:"v0",tools:_,tool_choice:{type:"tool",name:f},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:ie(r)}})}else throw new TypeError(`Unrecognized structured output method '${u}'. Expected 'functionCalling' or 'jsonSchema'`);if(!i)return s.pipe(n).withConfig({runName:"ChatAnthropicStructuredOutput"});const c=Bt.assign({parsed:(f,_)=>n.invoke(f.raw,_)}),h=Bt.assign({parsed:()=>null}),p=c.withFallbacks({fallbacks:[h]});return Rn.from([{raw:s},p]).withConfig({runName:"StructuredOutputRunnable"})}},xa=class extends Zr{};const ea=y({command:w("view"),path:b()}),ta=y({command:w("create"),path:b(),file_text:b()}),sa=y({command:w("str_replace"),path:b(),old_str:b(),new_str:b()}),na=y({command:w("insert"),path:b(),insert_line:E(),insert_text:b()}),ra=y({command:w("delete"),path:b()}),aa=y({command:w("rename"),old_path:b(),new_path:b()});Ze("command",[ea,ta,sa,na,ra,aa]);const ia=y({command:w("view"),path:b(),view_range:Mt([E(),E()]).optional()}),oa=y({command:w("str_replace"),path:b(),old_str:b(),new_str:b()}),ua=y({command:w("create"),path:b(),file_text:b()}),ca=y({command:w("insert"),path:b(),insert_line:E(),new_str:b()});Ze("command",[ia,oa,ua,ca]);const $=Mt([E(),E()]),nn=y({action:w("screenshot")}),rn=y({action:w("left_click"),coordinate:$}),an=y({action:w("right_click"),coordinate:$}),on=y({action:w("middle_click"),coordinate:$}),un=y({action:w("double_click"),coordinate:$}),cn=y({action:w("triple_click"),coordinate:$}),ln=y({action:w("left_click_drag"),start_coordinate:$,end_coordinate:$}),dn=y({action:w("left_mouse_down"),coordinate:$}),hn=y({action:w("left_mouse_up"),coordinate:$}),pn=y({action:w("scroll"),coordinate:$,scroll_direction:Pn(["up","down","left","right"]),scroll_amount:E()}),fn=y({action:w("type"),text:b()}),mn=y({action:w("key"),key:b()}),gn=y({action:w("mouse_move"),coordinate:$}),_n=y({action:w("hold_key"),key:b()}),yn=y({action:w("wait"),duration:E().optional()}),la=y({action:w("zoom"),region:Mt([E(),E(),E(),E()])});Ze("action",[nn,rn,an,on,un,cn,ln,dn,hn,pn,fn,mn,gn,_n,yn]);Ze("action",[nn,rn,an,on,un,cn,ln,dn,hn,pn,fn,mn,gn,_n,yn,la]);const da=y({command:b().describe("The bash command to run")}),ha=y({restart:w(!0).describe("Set to true to restart the bash session")});En([da,ha]);export{xa as ChatAnthropic,Zr as ChatAnthropicMessages};
49
+ `:"")+"{"+Object.entries(t).map(([f,_])=>`${f}: ${JSON.stringify(_)}`).join(", ")+"}"}return e}const Hr={"claude-opus-4-1":8192,"claude-opus-4":8192,"claude-sonnet-4":8192,"claude-sonnet-3-7-sonnet":8192,"claude-3-5-sonnet":4096,"claude-3-5-haiku":4096,"claude-3-haiku":2048},bs=2048;function Jr(t){return t?Object.entries(Hr).find(([s])=>t.startsWith(s))?.[1]??bs:bs}function Kr(t){return!!(t.tools&&t.tools.length>0)}function Xr(t){for(const e of t.messages??[])if(typeof e.content!="string"){for(const s of e.content??[])if(typeof s=="object"&&s!=null&&s.type==="document"&&typeof s.citations=="object"&&s.citations?.enabled)return!0}return!1}function zr(t){return!!(t.thinking&&t.thinking.type==="enabled")}function Vr(t){return"input_schema"in t}function Qr(t){const e=["text_editor_","computer_","bash_","web_search_","web_fetch_","str_replace_editor_","str_replace_based_edit_tool_","code_execution_","memory_","tool_search_","mcp_toolset"];return typeof t=="object"&&t!==null&&"type"in t&&("name"in t||"mcp_server_name"in t)&&typeof t.type=="string"&&e.some(s=>typeof t.type=="string"&&t.type.startsWith(s))}function Yr(t,e,...s){return Array.from(new Set([...t??[],...e??[],...s.flatMap(n=>Array.from(n))]))}function Gr(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0]&&typeof t.content[0].text=="string")return t.content[0].text}var Zr=class extends bn{static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}lc_serializable=!0;anthropicApiKey;apiKey;apiUrl;temperature;topK;topP;maxTokens;modelName="claude-3-5-sonnet-latest";model="claude-3-5-sonnet-latest";invocationKwargs;stopSequences;streaming=!1;clientOptions;thinking={type:"disabled"};contextManagement;batchClient;streamingClient;streamUsage=!0;betas;createClient;constructor(t){if(super(t??{}),this.anthropicApiKey=t?.apiKey??t?.anthropicApiKey??vn("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!t?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=t?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=t?.anthropicApiUrl,this.modelName=t?.model??t?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=t?.invocationKwargs??{},this.topP=t?.topP??this.topP,this.temperature=t?.temperature??this.temperature,this.topK=t?.topK??this.topK,this.maxTokens=t?.maxTokens??Jr(this.model),this.stopSequences=t?.stopSequences??this.stopSequences,this.streaming=t?.streaming??!1,this.streamUsage=t?.streamUsage??this.streamUsage,this.thinking=t?.thinking??this.thinking,this.contextManagement=t?.contextManagement??this.contextManagement,this.betas=t?.betas??this.betas,this.createClient=t?.createClient??(e=>new Ae(e))}getLsParams(t){const e=this.invocationParams(t);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}formatStructuredToolToAnthropic(t){if(!(!t||!t.length))return t.map(e=>{if($t(e)&&e.extras?.providerToolDefinition)return e.extras.providerToolDefinition;if(Qr(e)||Vr(e))return e;if(xn(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if($t(e))return{name:e.name,description:e.description,input_schema:at(e.schema)?ie(e.schema):e.schema,...e.extras?Un.parse(e.extras):{}};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)})}bindTools(t,e){return this.withConfig({tools:this.formatStructuredToolToAnthropic(t),...e})}invocationParams(t){const e=Nn(t?.tool_choice),s=t?.tools?.reduce((r,a)=>{if(typeof a=="object"&&"type"in a&&a.type in Ht){const i=Ht[a.type];if(!r.includes(i))return[...r,i]}return r},[]),n={model:this.model,stop_sequences:t?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(t?.tools),tool_choice:e,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:t?.container,betas:Yr(this.betas,t?.betas,s??[]),output_format:t?.output_format,mcp_servers:t?.mcp_servers};if(this.thinking.type==="enabled"){if(this.topP!==void 0&&this.topK!==-1)throw new Error("topK is not supported when thinking is enabled");if(this.temperature!==void 0&&this.temperature!==1)throw new Error("temperature is not supported when thinking is enabled")}else n.temperature=this.temperature,n.top_k=this.topK,n.top_p=this.topP;return n}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(t,e,s){const n=this.invocationParams(e),r=zt(t),a={...n,...r,stream:!0},i=!Kr(a)&&!Xr(a)&&!zr(a),u=await this.createStreamWithRetry(a,{headers:e.headers});for await(const c of u){if(e.signal?.aborted)throw u.controller.abort(),new Error("AbortError: User aborted the request.");const h=this.streamUsage??e.streamUsage,p=Vn(c,{streamUsage:h,coerceContentToString:i});if(!p)continue;const{chunk:f}=p,_=Gr(f),d=new In({message:new N({content:f.content,additional_kwargs:f.additional_kwargs,tool_call_chunks:f.tool_call_chunks,usage_metadata:h?f.usage_metadata:void 0,response_metadata:f.response_metadata,id:f.id}),text:_??""});yield d,await s?.handleLLMNewToken(_??"",void 0,void 0,void 0,void 0,{chunk:d})}}async _generateNonStreaming(t,e,s){const n=await this.completionWithRetry({...e,stream:!1,...zt(t)},s),{content:r,...a}=n,i=Qn(r,a),{role:u,type:c,...h}=a;return{generations:i,llmOutput:h}}async _generate(t,e,s){if(this.stopSequences&&e.stop)throw new Error('"stopSequence" parameter found in input and default params');const n=this.invocationParams(e);if(n.stream){let r;const a=this._streamResponseChunks(t,e,s);for await(const i of a)r===void 0?r=i:r=r.concat(i);if(r===void 0)throw new Error("No chunks returned from Anthropic API.");return{generations:[{text:r.text,message:r.message}]}}else return this._generateNonStreaming(t,n,{signal:e.signal,headers:e.headers})}async createStreamWithRetry(t,e){if(!this.streamingClient){const a=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...a,apiKey:this.apiKey,maxRetries:0})}const{betas:s,...n}=t,r=async()=>{try{return t?.betas?.length?await this.streamingClient.beta.messages.create({...n,betas:s,...this.invocationKwargs,stream:!0},e):await this.streamingClient.messages.create({...n,...this.invocationKwargs,stream:!0},e)}catch(a){throw Vt(a)}};return this.caller.call(r)}async completionWithRetry(t,e){if(!this.batchClient){const a=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...a,apiKey:this.apiKey,maxRetries:0})}const{betas:s,...n}=t,r=async()=>{try{return t?.betas?.length?await this.batchClient.beta.messages.create({...n,...this.invocationKwargs,betas:s},e):await this.batchClient.messages.create({...n,...this.invocationKwargs},e)}catch(a){throw Vt(a)}};return this.caller.callWithOptions({signal:e.signal??void 0},r)}_llmType(){return"anthropic"}get profile(){return Gn[this.model]??{}}withStructuredOutput(t,e){let s,n;const{schema:r,name:a,includeRaw:i}={...e,schema:t};let u=e?.method??"functionCalling";if(u==="jsonMode"&&(console.warn('"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".'),u="jsonSchema"),u==="jsonSchema"){n=at(r)?Sn.fromZodSchema(r):new kn;const f=Fr(ie(r));s=this.withConfig({outputVersion:"v0",output_format:{type:"json_schema",schema:f},betas:["structured-outputs-2025-11-13"],ls_structured_output_format:{kwargs:{method:"json_schema"},schema:f}})}else if(u==="functionCalling"){let f=a??"extract",_;if(at(r)){const d=ie(r);_=[{name:f,description:d.description??"A function available to call.",input_schema:d}],n=new Ft({returnSingle:!0,keyName:f,zodSchema:r})}else{let d;typeof r.name=="string"&&typeof r.description=="string"&&typeof r.input_schema=="object"&&r.input_schema!=null?(d=r,f=r.name):d={name:f,description:r.description??"",input_schema:r},_=[d],n=new Ft({returnSingle:!0,keyName:f})}if(this.thinking?.type==="enabled"){const d="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(d),s=this.withConfig({outputVersion:"v0",tools:_,ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:ie(r)}});const v=X=>{if(!X.tool_calls||X.tool_calls.length===0)throw new Error(d);return X};s=s.pipe(v)}else s=this.withConfig({outputVersion:"v0",tools:_,tool_choice:{type:"tool",name:f},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:ie(r)}})}else throw new TypeError(`Unrecognized structured output method '${u}'. Expected 'functionCalling' or 'jsonSchema'`);if(!i)return s.pipe(n).withConfig({runName:"ChatAnthropicStructuredOutput"});const c=Bt.assign({parsed:(f,_)=>n.invoke(f.raw,_)}),h=Bt.assign({parsed:()=>null}),p=c.withFallbacks({fallbacks:[h]});return An.from([{raw:s},p]).withConfig({runName:"StructuredOutputRunnable"})}},xa=class extends Zr{};const ea=y({command:w("view"),path:b()}),ta=y({command:w("create"),path:b(),file_text:b()}),sa=y({command:w("str_replace"),path:b(),old_str:b(),new_str:b()}),na=y({command:w("insert"),path:b(),insert_line:E(),insert_text:b()}),ra=y({command:w("delete"),path:b()}),aa=y({command:w("rename"),old_path:b(),new_path:b()});Ze("command",[ea,ta,sa,na,ra,aa]);const ia=y({command:w("view"),path:b(),view_range:Mt([E(),E()]).optional()}),oa=y({command:w("str_replace"),path:b(),old_str:b(),new_str:b()}),ua=y({command:w("create"),path:b(),file_text:b()}),ca=y({command:w("insert"),path:b(),insert_line:E(),new_str:b()});Ze("command",[ia,oa,ua,ca]);const $=Mt([E(),E()]),nn=y({action:w("screenshot")}),rn=y({action:w("left_click"),coordinate:$}),an=y({action:w("right_click"),coordinate:$}),on=y({action:w("middle_click"),coordinate:$}),un=y({action:w("double_click"),coordinate:$}),cn=y({action:w("triple_click"),coordinate:$}),ln=y({action:w("left_click_drag"),start_coordinate:$,end_coordinate:$}),dn=y({action:w("left_mouse_down"),coordinate:$}),hn=y({action:w("left_mouse_up"),coordinate:$}),pn=y({action:w("scroll"),coordinate:$,scroll_direction:Pn(["up","down","left","right"]),scroll_amount:E()}),fn=y({action:w("type"),text:b()}),mn=y({action:w("key"),key:b()}),gn=y({action:w("mouse_move"),coordinate:$}),_n=y({action:w("hold_key"),key:b()}),yn=y({action:w("wait"),duration:E().optional()}),la=y({action:w("zoom"),region:Mt([E(),E(),E(),E()])});Ze("action",[nn,rn,an,on,un,cn,ln,dn,hn,pn,fn,mn,gn,_n,yn]);Ze("action",[nn,rn,an,on,un,cn,ln,dn,hn,pn,fn,mn,gn,_n,yn,la]);const da=y({command:b().describe("The bash command to run")}),ha=y({restart:w(!0).describe("Set to true to restart the bash session")});En([da,ha]);export{xa as ChatAnthropic,Zr as ChatAnthropicMessages};