zen-code 4.9.2 → 4.10.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 (86) hide show
  1. package/dist/app.js +2606 -182
  2. package/dist/cli.js +3116 -1
  3. package/dist/nonInteractive.js +2084 -4
  4. package/dist/zen-keyboard.js +358 -3
  5. package/package.json +37 -37
  6. package/dist/chunk-0pss3s5r.js +0 -88
  7. package/dist/chunk-0sxrk9sx.js +0 -1
  8. package/dist/chunk-0zk0m93z.js +0 -26
  9. package/dist/chunk-178yjjsx.js +0 -1
  10. package/dist/chunk-1p9xzvpt.js +0 -3
  11. package/dist/chunk-2eh0sv3s.js +0 -2
  12. package/dist/chunk-43xrz4wp.js +0 -2
  13. package/dist/chunk-48ce2wt0.js +0 -1
  14. package/dist/chunk-48vkm1yn.js +0 -5
  15. package/dist/chunk-55nx49pj.js +0 -7
  16. package/dist/chunk-578m1dhj.js +0 -2
  17. package/dist/chunk-5dsevrtz.js +0 -91
  18. package/dist/chunk-62zh99t6.js +0 -298
  19. package/dist/chunk-66890qd3.js +0 -2
  20. package/dist/chunk-6nfpdtn6.js +0 -1
  21. package/dist/chunk-738m8242.js +0 -53
  22. package/dist/chunk-8f2zh5h6.js +0 -2
  23. package/dist/chunk-8ty2zfve.js +0 -3
  24. package/dist/chunk-94jawhw7.js +0 -3
  25. package/dist/chunk-98wjxsna.js +0 -79
  26. package/dist/chunk-9b7nj74j.js +0 -1
  27. package/dist/chunk-9k64296h.js +0 -4
  28. package/dist/chunk-9x562s6p.js +0 -1
  29. package/dist/chunk-a90fm6gz.js +0 -278
  30. package/dist/chunk-ac5t2ywn.js +0 -100
  31. package/dist/chunk-ad2hbq42.js +0 -1
  32. package/dist/chunk-afhxxkmv.js +0 -16
  33. package/dist/chunk-b4vvgbav.js +0 -1
  34. package/dist/chunk-b9pcntkv.js +0 -253
  35. package/dist/chunk-c7y5efa0.js +0 -1
  36. package/dist/chunk-cbjnwrt7.js +0 -2
  37. package/dist/chunk-ce53j63y.js +0 -3
  38. package/dist/chunk-dcs1r9as.js +0 -2
  39. package/dist/chunk-dcwnpdtk.js +0 -9
  40. package/dist/chunk-dxec2q4t.js +0 -23
  41. package/dist/chunk-e3tyc24s.js +0 -310
  42. package/dist/chunk-e8hp8d68.js +0 -81
  43. package/dist/chunk-fkrydbn4.js +0 -18
  44. package/dist/chunk-frhhpxxy.js +0 -2
  45. package/dist/chunk-fw3nrwpf.js +0 -1
  46. package/dist/chunk-gyhxdxb4.js +0 -1
  47. package/dist/chunk-h1enhch1.js +0 -2
  48. package/dist/chunk-hcnx1j2z.js +0 -1
  49. package/dist/chunk-hfegb4pr.js +0 -2
  50. package/dist/chunk-hfypkhky.js +0 -2
  51. package/dist/chunk-hmemx3cw.js +0 -2
  52. package/dist/chunk-hra0748z.js +0 -2
  53. package/dist/chunk-hsev32dg.js +0 -4
  54. package/dist/chunk-hyf24r36.js +0 -2
  55. package/dist/chunk-jb4yt88g.js +0 -6
  56. package/dist/chunk-jjcmm167.js +0 -1
  57. package/dist/chunk-jrepjpft.js +0 -2
  58. package/dist/chunk-k38fjqj7.js +0 -140
  59. package/dist/chunk-kym9tb01.js +0 -1
  60. package/dist/chunk-mt1g6g89.js +0 -1
  61. package/dist/chunk-p0vzbr7s.js +0 -585
  62. package/dist/chunk-pndhbee8.js +0 -2
  63. package/dist/chunk-pwrscdkf.js +0 -2
  64. package/dist/chunk-r019959h.js +0 -2
  65. package/dist/chunk-r10bn684.js +0 -1
  66. package/dist/chunk-r3pe49q4.js +0 -8
  67. package/dist/chunk-r4tq44hr.js +0 -1
  68. package/dist/chunk-rjrnaka2.js +0 -1
  69. package/dist/chunk-rt5mpgbg.js +0 -6
  70. package/dist/chunk-rztre6k0.js +0 -1
  71. package/dist/chunk-s77qbhtz.js +0 -3
  72. package/dist/chunk-t7rwtc17.js +0 -1
  73. package/dist/chunk-v8g52kan.js +0 -1
  74. package/dist/chunk-vd6c87cm.js +0 -2
  75. package/dist/chunk-vfwbx331.js +0 -2
  76. package/dist/chunk-vh9zd1v3.js +0 -5
  77. package/dist/chunk-w2hbsa9j.js +0 -86
  78. package/dist/chunk-wabmqprd.js +0 -184
  79. package/dist/chunk-wpy5r9ma.js +0 -40
  80. package/dist/chunk-x552nspp.js +0 -6
  81. package/dist/chunk-x90r4sje.js +0 -1
  82. package/dist/chunk-yndex7hs.js +0 -1
  83. package/dist/chunk-yqwxbcc7.js +0 -31
  84. package/dist/chunk-z8n7y37k.js +0 -1
  85. package/dist/chunk-zr7sx9hd.js +0 -1
  86. package/dist/chunk-zxqmghzf.js +0 -1
@@ -1,53 +0,0 @@
1
- import{rf as oZ}from"./chunk-e3tyc24s.js";import{Ag as P$,Bg as f$,Hg as aZ,Sf as nZ,Tf as R$,Uf as p,Xf as y$,Yf as cZ,sg as rZ,yg as iZ}from"./chunk-p0vzbr7s.js";import{Yg as C$}from"./chunk-afhxxkmv.js";import{$g as b0,ah as B8,gh as g4,hh as g0,ih as aX,jh as A8}from"./chunk-ac5t2ywn.js";import{Kh as v0,Ph as E0,Vh as h0}from"./chunk-dcwnpdtk.js";import{$h as k$,ci as C8,di as R8,ei as b$,ni as v$,ri as U}from"./chunk-cbjnwrt7.js";import{$i as xZ,Ai as u4,Dk as K0,Hi as X0,Hk as h4,Ii as m4,Oj as l,Pj as F$,Rj as j,Uj as C4,fl as Q0,ij as DZ,pj as FZ,tl as E8,xj as k8,zi as t$,zk as L8}from"./chunk-w2hbsa9j.js";import{kq as lZ}from"./chunk-578m1dhj.js";var KW=y$.extend(P$.shape).extend({provider_id:U.string().default("default"),provider_type:U.string().default("openai"),model_id:U.string().default("qwen-plus"),agent_name:U.string().default("Code Agent"),switch_command:U.string().optional(),enable_thinking:U.boolean().default(!0),user_id:U.string().optional(),thread_id:U.string().optional(),cwd:U.string().default(process.cwd())}),_$=R$(f$,C$).build({provider_id:p(()=>"default"),provider_type:p(()=>"openai"),model_id:p(()=>"qwen-plus"),agent_name:p(()=>"Code Agent"),switch_command:p(()=>null),enable_thinking:p(()=>!0),user_id:p(()=>""),thread_id:p(()=>""),cwd:p(()=>process.cwd())});var j8=class extends g4{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor($){super($);this.keyName=$.keyName,this.returnSingle=$.returnSingle??this.returnSingle,this.zodSchema=$.zodSchema}async _validateResult($){let X=$;if(typeof $==="string")try{X=JSON.parse($)}catch(Y){throw new g0(`Failed to parse. Text: "${JSON.stringify($,null,2)}". Error: ${JSON.stringify(Y.message)}`,$)}else X=$;if(this.zodSchema===void 0)return X;let Z=await h4(this.zodSchema,X);if(Z.success)return Z.data;else throw new g0(`Failed to parse. Text: "${JSON.stringify($,null,2)}". Error: ${JSON.stringify(Z.error.issues)}`,JSON.stringify(X,null,2))}async parseResult($){let X=$.flatMap((Y)=>{let{message:W}=Y;if(!Array.isArray(W.content))return[];return S8(W.content)[0]});if(X[0]===void 0)throw Error("No parseable tool calls provided to AnthropicToolsOutputParser.");let[Z]=X;return await this._validateResult(Z.args)}};function S8($){let X=[];for(let Z of $)if(Z.type==="tool_use")X.push({name:Z.name,args:Z.input,id:Z.id,type:"tool_call"});return X}function h$($){if(!$)return;else if($==="any")return{type:"any"};else if($==="auto")return{type:"auto"};else if($==="none")return{type:"none"};else if(typeof $==="string")return{type:"tool",name:$};else return $}var g$=b$({cache_control:v$().optional().nullable(),defer_loading:k$().optional(),input_examples:R8(C8()).optional(),allowed_callers:R8(C8()).optional()}),y8={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 d$($){return typeof $==="object"&&$!==null&&"type"in $&&$.type==="thinking"}function u$($){return typeof $==="object"&&$!==null&&"type"in $&&$.type==="redacted_thinking"}function d4($){return typeof $==="object"&&$!==null&&"type"in $&&$.type==="compaction"}function m$($){return typeof $==="object"&&$!==null&&"type"in $&&$.type==="search_result"}function c$($){if(typeof $!=="object"||$==null)return!1;if(!("type"in $)||$.type!=="image")return!1;if(!("source"in $)||typeof $.source!=="object"||$.source==null)return!1;if(!("type"in $.source))return!1;if($.source.type==="base64"){if(!("media_type"in $.source))return!1;if(typeof $.source.media_type!=="string")return!1;if(!("data"in $.source))return!1;if(typeof $.source.data!=="string")return!1;return!0}if($.source.type==="url"){if(!("url"in $.source))return!1;if(typeof $.source.url!=="string")return!1;return!0}return!1}var p$={providerName:"anthropic",fromStandardTextBlock($){return{type:"text",text:$.text,..."citations"in($.metadata??{})?{citations:$.metadata.citations}:{},..."cache_control"in($.metadata??{})?{cache_control:$.metadata.cache_control}:{}}},fromStandardImageBlock($){if($.source_type==="url"){let X=X0({dataUrl:$.url,asTypedArray:!1});if(X)return{type:"image",source:{type:"base64",data:X.data,media_type:X.mime_type},..."cache_control"in($.metadata??{})?{cache_control:$.metadata.cache_control}:{}};else return{type:"image",source:{type:"url",url:$.url},..."cache_control"in($.metadata??{})?{cache_control:$.metadata.cache_control}:{}}}else if($.source_type==="base64")return{type:"image",source:{type:"base64",data:$.data,media_type:$.mime_type??""},..."cache_control"in($.metadata??{})?{cache_control:$.metadata.cache_control}:{}};else throw Error(`Unsupported image source type: ${$.source_type}`)},fromStandardFileBlock($){let X=($.mime_type??"").split(";")[0];if($.source_type==="url"){if(X==="application/pdf"||X==="")return{type:"document",source:{type:"url",url:$.url},..."cache_control"in($.metadata??{})?{cache_control:$.metadata.cache_control}:{},..."citations"in($.metadata??{})?{citations:$.metadata.citations}:{},..."context"in($.metadata??{})?{context:$.metadata.context}:{},..."title"in($.metadata??{})?{title:$.metadata.title}:{}};throw Error(`Unsupported file mime type for file url source: ${$.mime_type}`)}else if($.source_type==="text")if(X==="text/plain"||X==="")return{type:"document",source:{type:"text",data:$.text,media_type:$.mime_type??""},..."cache_control"in($.metadata??{})?{cache_control:$.metadata.cache_control}:{},..."citations"in($.metadata??{})?{citations:$.metadata.citations}:{},..."context"in($.metadata??{})?{context:$.metadata.context}:{},..."title"in($.metadata??{})?{title:$.metadata.title}:{}};else throw Error(`Unsupported file mime type for file text source: ${$.mime_type}`);else if($.source_type==="base64")if(X==="application/pdf"||X==="")return{type:"document",source:{type:"base64",data:$.data,media_type:"application/pdf"},..."cache_control"in($.metadata??{})?{cache_control:$.metadata.cache_control}:{},..."citations"in($.metadata??{})?{citations:$.metadata.citations}:{},..."context"in($.metadata??{})?{context:$.metadata.context}:{},..."title"in($.metadata??{})?{title:$.metadata.title}:{}};else if(["image/jpeg","image/png","image/gif","image/webp"].includes(X))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:$.data,media_type:X}}]},..."cache_control"in($.metadata??{})?{cache_control:$.metadata.cache_control}:{},..."citations"in($.metadata??{})?{citations:$.metadata.citations}:{},..."context"in($.metadata??{})?{context:$.metadata.context}:{},..."title"in($.metadata??{})?{title:$.metadata.title}:{}};else throw Error(`Unsupported file mime type for file base64 source: ${$.mime_type}`);else throw Error(`Unsupported file source type: ${$.source_type}`)}};var i$=($)=>$();function sZ($){return typeof $==="object"&&$!==null&&"type"in $&&$.type==="citation"}function tZ($){function*X(){for(let Z of $)if(sZ(Z)){if(Z.source==="char")yield{type:"char_location",file_id:Z.url??"",start_char_index:Z.startIndex??0,end_char_index:Z.endIndex??0,document_title:Z.title??null,document_index:0,cited_text:Z.citedText??""};else if(Z.source==="page")yield{type:"page_location",file_id:Z.url??"",start_page_number:Z.startIndex??0,end_page_number:Z.endIndex??0,document_title:Z.title??null,document_index:0,cited_text:Z.citedText??""};else if(Z.source==="block")yield{type:"content_block_location",file_id:Z.url??"",start_block_index:Z.startIndex??0,end_block_index:Z.endIndex??0,document_title:Z.title??null,document_index:0,cited_text:Z.citedText??""};else if(Z.source==="url")yield{type:"web_search_result_location",url:Z.url??"",title:Z.title??null,encrypted_index:String(Z.startIndex??0),cited_text:Z.citedText??""};else if(Z.source==="search")yield{type:"search_result_location",title:Z.title??null,start_block_index:Z.startIndex??0,end_block_index:Z.endIndex??0,search_result_index:0,source:Z.source??"",cited_text:Z.citedText??""}}}return Array.from(X())}function d0($){if(typeof $==="string")return $;else return eZ($)}function eZ($){let X=[];for(let Z=0,{length:Y}=$;Z<Y;Z++)X.push(String.fromCharCode($[Z]));return btoa(X.join(""))}function P8($){return($??"").split(";")[0].toLowerCase()}function u0($,X){if($!==void 0&&$!==null&&typeof $==="object"&&X in $)return $[X]}function I0($,X){let Z=u0(X,"cache_control");if(Z!==void 0)$.cache_control=Z;let Y=u0(X,"citations");if(Y!==void 0)$.citations=Y;let W=u0(X,"context");if(W!==void 0)$.context=W;let J=u0(X,"title");if(J!==void 0)$.title=J;return $}function f8($,X){let Z=u0(X,"cache_control");if(Z!==void 0)$.cache_control=Z;return $}function l$($){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has($)}function n$($){let X=[],Z=$.response_metadata,Y="model_provider"in Z&&Z?.model_provider==="anthropic";for(let W of $.contentBlocks)if(W.type==="text")if(W.annotations)X.push({type:"text",text:W.text,citations:tZ(W.annotations)});else X.push({type:"text",text:W.text});else if(W.type==="tool_call")X.push({type:"tool_use",id:W.id??"",name:W.name,input:W.args});else if(W.type==="tool_call_chunk"){let J=i$(()=>{if(typeof W.args!=="string")return W.args;try{return JSON.parse(W.args)}catch{return{}}});X.push({type:"tool_use",id:W.id??"",name:W.name??"",input:J})}else if(W.type==="reasoning"&&Y)X.push({type:"thinking",thinking:W.reasoning,signature:String(W.signature)});else if(W.type==="server_tool_call"&&Y){if(W.name==="web_search")X.push({type:"server_tool_use",name:W.name,id:W.id??"",input:W.args});else if(W.name==="code_execution")X.push({type:"server_tool_use",name:W.name,id:W.id??"",input:W.args})}else if(W.type==="server_tool_call_result"&&Y){if(W.name==="web_search"&&Array.isArray(W.output.urls)){let J=W.output.urls.map((z)=>({type:"web_search_result",title:"",encrypted_content:"",url:z}));X.push({type:"web_search_tool_result",tool_use_id:W.toolCallId??"",content:J})}else if(W.name==="code_execution")X.push({type:"code_execution_tool_result",tool_use_id:W.toolCallId??"",content:W.output});else if(W.name==="mcp_tool_result")X.push({type:"mcp_tool_result",tool_use_id:W.toolCallId??"",content:W.output})}else if(W.type==="audio")throw Error("Anthropic does not support audio content blocks.");else if(W.type==="file"){let J=W.metadata;if(W.fileId){X.push(I0({type:"document",source:{type:"file",file_id:W.fileId}},J));continue}if(W.url){let z=P8(W.mimeType);if(z==="application/pdf"||z===""){X.push(I0({type:"document",source:{type:"url",url:W.url}},J));continue}}if(W.data){let z=P8(W.mimeType);if(z===""||z==="application/pdf")X.push(I0({type:"document",source:{type:"base64",data:d0(W.data),media_type:"application/pdf"}},J));else if(z==="text/plain")X.push(I0({type:"document",source:{type:"text",data:d0(W.data),media_type:"text/plain"}},J));else if(l$(z))X.push(I0({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:d0(W.data),media_type:z}}]}},J));else throw Error(`Unsupported file mime type for Anthropic base64 source: ${z}`);continue}throw Error("File content block must include a fileId, url, or data property.")}else if(W.type==="image"){let J=W.metadata;if(W.fileId){X.push(f8({type:"image",source:{type:"file",file_id:W.fileId}},J));continue}if(W.url){X.push(f8({type:"image",source:{type:"url",url:W.url}},J));continue}if(W.data){let z=P8(W.mimeType)||"image/png";if(l$(z))X.push(f8({type:"image",source:{type:"base64",data:d0(W.data),media_type:z}},J));continue}throw Error("Image content block must include a fileId, url, or data property.")}else if(W.type==="video");else if(W.type==="text-plain"){if(W.data)X.push(I0({type:"document",source:{type:"text",data:d0(W.data),media_type:"text/plain"}},W.metadata))}else if(W.type==="non_standard"&&Y)X.push(W.value);return X}function _8($){let X=X0({dataUrl:$});if(X)return{type:"base64",media_type:X.mime_type,data:X.data};let Z;try{Z=new URL($)}catch{throw Error([`Malformed image URL: ${JSON.stringify($)}. 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
-
3
- `))}if(Z.protocol==="http:"||Z.protocol==="https:")return{type:"url",url:$};throw Error([`Invalid image URL protocol: ${JSON.stringify(Z.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
-
5
- `))}function $7($){let X=[];for(let Z of $)if(Z._getType()==="tool")if(typeof Z.content==="string"){let Y=X[X.length-1];if(Y?._getType()==="human"&&Array.isArray(Y.content)&&"type"in Y.content[0]&&Y.content[0].type==="tool_result")Y.content.push({type:"tool_result",content:Z.content,tool_use_id:Z.tool_call_id});else X.push(new k8({content:[{type:"tool_result",content:Z.content,tool_use_id:Z.tool_call_id}]}))}else X.push(new k8({content:[{type:"tool_result",...Z.content!=null?{content:b8(Z)}:{},tool_use_id:Z.tool_call_id}]}));else X.push(Z);return X}function r$($){if($.id===void 0)throw Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:$.id,name:$.name,input:$.args}}function*X7($,X){let Z=["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"],Y=["text","text_delta"];for(let W of $){if(u4(W))yield m4(W,p$);let J="cache_control"in W?W.cache_control:void 0;if(W.type==="image_url"){let z;if(typeof W.image_url==="string")z=_8(W.image_url);else if(typeof W.image_url==="object"&&W.image_url!==null&&"url"in W.image_url&&typeof W.image_url.url==="string")z=_8(W.image_url.url);if(z)yield{type:"image",source:z,...J?{cache_control:J}:{}}}else if(c$(W))yield W;else if(W.type==="image"){let z;if("url"in W&&typeof W.url==="string")z=_8(W.url);else if("data"in W&&(typeof W.data==="string"||W.data instanceof Uint8Array))z={type:"base64",media_type:"mimeType"in W&&typeof W.mimeType==="string"?W.mimeType:"image/jpeg",data:typeof W.data==="string"?W.data:Buffer.from(W.data).toString("base64")};else if("fileId"in W&&typeof W.fileId==="string")z={type:"file",file_id:W.fileId};if(z)yield{type:"image",source:z,...J?{cache_control:J}:{}}}else if(W.type==="file"){let z;if("url"in W&&typeof W.url==="string")z={type:"url",url:W.url};else if("data"in W&&(typeof W.data==="string"||W.data instanceof Uint8Array))z={type:"base64",media_type:"mimeType"in W&&typeof W.mimeType==="string"?W.mimeType:"application/pdf",data:typeof W.data==="string"?W.data:Buffer.from(W.data).toString("base64")};else if("fileId"in W&&typeof W.fileId==="string")z={type:"file",file_id:W.fileId};if(z)yield{type:"document",source:z,...J?{cache_control:J}:{}}}else if(W.type==="document")yield{...W,...J?{cache_control:J}:{}};else if(d$(W))yield{type:"thinking",thinking:W.thinking,signature:W.signature,...J?{cache_control:J}:{}};else if(u$(W))yield{type:"redacted_thinking",data:W.data,...J?{cache_control:J}:{}};else if(d4(W))yield{type:"compaction",content:W.content,...J?{cache_control:J}:{}};else if(m$(W))yield{type:"search_result",title:W.title,source:W.source,..."cache_control"in W&&W.cache_control?{cache_control:W.cache_control}:{},..."citations"in W&&W.citations?{citations:W.citations}:{},content:W.content};else if(Y.find((z)=>z===W.type)&&"text"in W)yield{type:"text",text:W.text,...J?{cache_control:J}:{},..."citations"in W&&W.citations?{citations:W.citations}:{}};else if(Z.find((z)=>z===W.type)){let z={...W};if(z.type==="input_json_delta")continue;if(z.type==="tool_use"&&typeof z.input==="string"){let V=X?.find((N)=>N.id===z.id);if(V)z.input=V.args;else z.input=$.filter((N)=>N.index===z.index&&N.type==="input_json_delta"&&typeof N.input==="string").reduce((N,D)=>N+D.input,z.input)}if("index"in z)delete z.index;if("input"in z){if(typeof z.input==="string")try{z.input=JSON.parse(z.input)}catch{z.input={}}}yield{...z,...J?{cache_control:J}:{}}}else if(W.type==="container_upload")yield{...W,...J?{cache_control:J}:{}}}}function b8($,X){let{content:Z}=$;if(typeof Z==="string")return Z;else return Array.from(X7(Z,X))}function c4($){let X=$7($),Z;if(X.length>0&&X[0]._getType()==="system")Z=$[0].content;return{messages:Z7((Z!==void 0?X.slice(1):X).map((Y)=>{let W;if(Y._getType()==="human")W="user";else if(Y._getType()==="ai")W="assistant";else if(Y._getType()==="tool")W="user";else if(Y._getType()==="system")throw Error("System messages are only permitted as the first passed message.");else throw Error(`Message type "${Y.type}" is not supported.`);if(l.isInstance(Y)&&Y.response_metadata?.output_version==="v1")return{role:W,content:n$(Y)};if(l.isInstance(Y)&&!!Y.tool_calls?.length)if(typeof Y.content==="string")if(Y.content==="")return{role:W,content:Y.tool_calls.map(r$)};else return{role:W,content:[{type:"text",text:Y.content},...Y.tool_calls.map(r$)]};else{let{content:J}=Y;if(!Y.tool_calls.every((z)=>J.find((V)=>(V.type==="tool_use"||V.type==="input_json_delta"||V.type==="server_tool_use")&&V.id===z.id)))console.warn('The "tool_calls" field on a message is only respected if content is a string.');return{role:W,content:b8(Y,Y.tool_calls)}}else return{role:W,content:b8(Y,l.isInstance(Y)?Y.tool_calls:void 0)}})),system:Z}}function v8($,X){if(!$.messages||$.messages.length===0)return $;let Z=[...$.messages],Y=Z.length-1,W=Z[Y];if(!W)return $;if(typeof W.content==="string")return Z[Y]={...W,content:[{type:"text",text:W.content,cache_control:X}]},{...$,messages:Z};if(Array.isArray(W.content)&&W.content.length>0){let J=[...W.content],z=J.length-1;return J[z]={...J[z],cache_control:X},Z[Y]={...W,content:J},{...$,messages:Z}}return $}function Z7($){if(!$||$.length<=1)return $;let X=[],Z=$[0],Y=(J)=>{if(typeof J==="string")return[{type:"text",text:J}];return J},W=(J)=>{if(J.role!=="user")return!1;if(typeof J.content==="string")return!1;return Array.isArray(J.content)&&J.content.every((z)=>z.type==="tool_result")};for(let J=1;J<$.length;J+=1){let z=$[J];if(W(Z)&&W(z))Z={...Z,content:[...Y(Z.content),...Y(z.content)]};else X.push(Z),Z=z}return X.push(Z),X}function a$($,X){let Z={model_provider:"anthropic"};if($.type==="message_start"){let{content:Y,usage:W,...J}=$.message,z={};for(let[K,G]of Object.entries(J))if(G!==void 0&&G!==null)z[K]=G;let{input_tokens:V,output_tokens:N,...D}=W??{},w=s$(W);return{chunk:new j({content:X.coerceContentToString?"":[],additional_kwargs:z,usage_metadata:X.streamUsage?w:void 0,response_metadata:{...Z,usage:{...D}},id:$.message.id})}}else if($.type==="message_delta"){let Y={input_tokens:0,output_tokens:$.usage.output_tokens,total_tokens:$.usage.output_tokens,input_token_details:{cache_creation:$.usage.cache_creation_input_tokens,cache_read:$.usage.cache_read_input_tokens}},W="context_management"in $.delta?{context_management:$.delta.context_management}:void 0;return{chunk:new j({content:X.coerceContentToString?"":[],response_metadata:W,additional_kwargs:{...$.delta},usage_metadata:X.streamUsage?Y:void 0})}}else if($.type==="content_block_start"&&["tool_use","document","server_tool_use","web_search_tool_result"].includes($.content_block.type)){let Y=$.content_block,W;if(Y.type==="tool_use")W=[{id:Y.id,index:$.index,name:Y.name,args:""}];else W=[];return{chunk:new j({content:X.coerceContentToString?"":[{index:$.index,...$.content_block,input:Y.type==="server_tool_use"||Y.type==="tool_use"?"":void 0}],response_metadata:Z,additional_kwargs:{},tool_call_chunks:W})}}else if($.type==="content_block_delta"&&["text_delta","citations_delta","thinking_delta","signature_delta"].includes($.delta.type))if(X.coerceContentToString&&"text"in $.delta)return{chunk:new j({content:$.delta.text})};else{let Y=$.delta;if("citation"in Y)Y.citations=[Y.citation],delete Y.citation;if(Y.type==="thinking_delta"||Y.type==="signature_delta")return{chunk:new j({content:[{index:$.index,...Y,type:"thinking"}],response_metadata:Z})};return{chunk:new j({content:[{index:$.index,...Y,type:"text"}],response_metadata:Z})}}else if($.type==="content_block_delta"&&$.delta.type==="input_json_delta")return{chunk:new j({content:X.coerceContentToString?"":[{index:$.index,input:$.delta.partial_json,type:$.delta.type}],response_metadata:Z,additional_kwargs:{},tool_call_chunks:[{index:$.index,args:$.delta.partial_json}]})};else if($.type==="content_block_start"&&$.content_block.type==="text"){let Y=$.content_block?.text;if(Y!==void 0)return{chunk:new j({content:X.coerceContentToString?Y:[{index:$.index,...$.content_block}],response_metadata:Z,additional_kwargs:{}})}}else if($.type==="content_block_start"&&$.content_block.type==="redacted_thinking")return{chunk:new j({content:X.coerceContentToString?"":[{index:$.index,...$.content_block}],response_metadata:Z})};else if($.type==="content_block_start"&&$.content_block.type==="thinking"){let Y=$.content_block.thinking;return{chunk:new j({content:X.coerceContentToString?Y:[{index:$.index,...$.content_block}],response_metadata:Z})}}else if($.type==="content_block_start"&&d4($.content_block))return{chunk:new j({content:X.coerceContentToString?"":[{index:$.index,...$.content_block}],response_metadata:Z})};else if($.type==="content_block_delta"&&$.delta.type==="compaction_delta")return{chunk:new j({content:X.coerceContentToString?"":[{index:$.index,...$.delta,type:"compaction"}],response_metadata:Z})};return null}function o$($,X){let Z={...X,model_provider:"anthropic"},Y=X.usage,W=Y!=null?s$(Y):void 0;if($.length===1&&$[0].type==="text")return[{text:$[0].text,message:new l({content:$[0].text,additional_kwargs:X,usage_metadata:W,response_metadata:Z,id:X.id})}];else return[{text:"",message:new l({content:$,additional_kwargs:X,tool_calls:S8($),usage_metadata:W,response_metadata:Z,id:X.id})}]}function s$($){let X=$.cache_creation_input_tokens??0,Z=$.cache_read_input_tokens??0,Y=$.input_tokens+X+Z;return{input_tokens:Y,output_tokens:$.output_tokens,total_tokens:Y+$.output_tokens,input_token_details:{cache_creation:X,cache_read:Z}}}function p4($,X){return $.lc_error_code=X,$.message=`${$.message}
6
-
7
- Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${X}/
8
- `,$}function h8($){let X;if($.status===400&&typeof $.message==="string"&&$.message.includes("prompt is too long"))X=t$.fromError($);else if($.status===400&&$.message.includes("tool"))X=p4($,"INVALID_TOOL_RESULTS");else if($.status===401)X=p4($,"MODEL_AUTHENTICATION");else if($.status===404)X=p4($,"MODEL_NOT_FOUND");else if($.status===429)X=p4($,"MODEL_RATE_LIMIT");else X=$;return X}var e$={"claude-opus-4-5-20251101":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-haiku-latest":{maxInputTokens:200000,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:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-sonnet-20241022":{maxInputTokens:200000,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-sonnet-20240229":{maxInputTokens:200000,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-opus-4-6":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-6":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-0":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-20250514":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5-20250929":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-0":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-haiku-20241022":{maxInputTokens:200000,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-sonnet-20240620":{maxInputTokens:200000,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-7-sonnet-latest":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-7-sonnet-20250219":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-haiku-20240307":{maxInputTokens:200000,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:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-5":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-opus-20240229":{maxInputTokens:200000,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:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-20250514":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1-20250805":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0}};function H($,X,Z,Y,W){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!W)throw TypeError("Private accessor was defined without a setter");if(typeof X==="function"?$!==X||!W:!X.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?W.call($,Z):W?W.value=Z:X.set($,Z),Z}function Q($,X,Z,Y){if(Z==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof X==="function"?$!==X||!Y:!X.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?Y:Z==="a"?Y.call($):Y?Y.value:X.get($)}var g8=function(){let{crypto:$}=globalThis;if($?.randomUUID)return g8=$.randomUUID.bind($),$.randomUUID();let X=new Uint8Array(1),Z=$?()=>$.getRandomValues(X)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Y)=>(+Y^Z()&15>>+Y/4).toString(16))};function n($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var m0=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let X=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)X.stack=$.stack;if($.cause&&!X.cause)X.cause=$.cause;if($.name)X.name=$.name;return X}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class F extends Error{}class O extends F{constructor($,X,Z,Y){super(`${O.makeMessage($,X,Z)}`);this.status=$,this.headers=Y,this.requestID=Y?.get("request-id"),this.error=X}static makeMessage($,X,Z){let Y=X?.message?typeof X.message==="string"?X.message:JSON.stringify(X.message):X?JSON.stringify(X):Z;if($&&Y)return`${$} ${Y}`;if($)return`${$} status code (no body)`;if(Y)return Y;return"(no status code or body)"}static generate($,X,Z,Y){if(!$||!Y)return new w0({message:Z,cause:m0(X)});let W=X;if($===400)return new p0($,W,Z,Y);if($===401)return new i0($,W,Z,Y);if($===403)return new l0($,W,Z,Y);if($===404)return new n0($,W,Z,Y);if($===409)return new r0($,W,Z,Y);if($===422)return new a0($,W,Z,Y);if($===429)return new o0($,W,Z,Y);if($>=500)return new s0($,W,Z,Y);return new O($,W,Z,Y)}}class y extends O{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class w0 extends O{constructor({message:$,cause:X}){super(void 0,void 0,$||"Connection error.",void 0);if(X)this.cause=X}}class c0 extends w0{constructor({message:$}={}){super({message:$??"Request timed out."})}}class p0 extends O{}class i0 extends O{}class l0 extends O{}class n0 extends O{}class r0 extends O{}class a0 extends O{}class o0 extends O{}class s0 extends O{}var W7=/^[a-z][a-z0-9+.-]*:/i,$X=($)=>{return W7.test($)},d8=($)=>(d8=Array.isArray,d8($)),u8=d8;function i4($){if(typeof $!=="object")return{};return $??{}}function XX($){if(!$)return!0;for(let X in $)return!1;return!0}function ZX($,X){return Object.prototype.hasOwnProperty.call($,X)}var YX=($,X)=>{if(typeof X!=="number"||!Number.isInteger(X))throw new F(`${$} must be an integer`);if(X<0)throw new F(`${$} must be a positive integer`);return X};var l4=($)=>{try{return JSON.parse($)}catch(X){return}},f=($,X)=>{let Z=$[X];return delete $[X],Z};var WX=($)=>new Promise((X)=>setTimeout(X,$));var Z0="0.74.0";var QX=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function J7(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var z7=()=>{let $=J7();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Z0,"X-Stainless-OS":zX(Deno.build.os),"X-Stainless-Arch":JX(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":Z0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if($==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Z0,"X-Stainless-OS":zX(globalThis.process.platform??"unknown"),"X-Stainless-Arch":JX(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let X=V7();if(X)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Z0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${X.browser}`,"X-Stainless-Runtime-Version":X.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Z0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function V7(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:X,pattern:Z}of $){let Y=Z.exec(navigator.userAgent);if(Y){let W=Y[1]||0,J=Y[2]||0,z=Y[3]||0;return{browser:X,version:`${W}.${J}.${z}`}}}return null}var JX=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},zX=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},VX,KX=()=>{return VX??(VX=z7())};function GX(){if(typeof fetch<"u")return fetch;throw 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 m8(...$){let X=globalThis.ReadableStream;if(typeof X>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new X(...$)}function n4($){let X=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return m8({start(){},async pull(Z){let{done:Y,value:W}=await X.next();if(Y)Z.close();else Z.enqueue(W)},async cancel(){await X.return?.()}})}function t0($){if($[Symbol.asyncIterator])return $;let X=$.getReader();return{async next(){try{let Z=await X.read();if(Z?.done)X.releaseLock();return Z}catch(Z){throw X.releaseLock(),Z}},async return(){let Z=X.cancel();return X.releaseLock(),await Z,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function wX($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let X=$.getReader(),Z=X.cancel();X.releaseLock(),await Z}var UX=({headers:$,body:X})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(X)}};function xX($){let X=0;for(let W of $)X+=W.length;let Z=new Uint8Array(X),Y=0;for(let W of $)Z.set(W,Y),Y+=W.length;return Z}var NX;function M0($){let X;return(NX??(X=new globalThis.TextEncoder,NX=X.encode.bind(X)))($)}var HX;function c8($){let X;return(HX??(X=new globalThis.TextDecoder,HX=X.decode.bind(X)))($)}var _,k;class Y0{constructor(){_.set(this,void 0),k.set(this,void 0),H(this,_,new Uint8Array,"f"),H(this,k,null,"f")}decode($){if($==null)return[];let X=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?M0($):$;H(this,_,xX([Q(this,_,"f"),X]),"f");let Z=[],Y;while((Y=G7(Q(this,_,"f"),Q(this,k,"f")))!=null){if(Y.carriage&&Q(this,k,"f")==null){H(this,k,Y.index,"f");continue}if(Q(this,k,"f")!=null&&(Y.index!==Q(this,k,"f")+1||Y.carriage)){Z.push(c8(Q(this,_,"f").subarray(0,Q(this,k,"f")-1))),H(this,_,Q(this,_,"f").subarray(Q(this,k,"f")),"f"),H(this,k,null,"f");continue}let W=Q(this,k,"f")!==null?Y.preceding-1:Y.preceding,J=c8(Q(this,_,"f").subarray(0,W));Z.push(J),H(this,_,Q(this,_,"f").subarray(Y.index),"f"),H(this,k,null,"f")}return Z}flush(){if(!Q(this,_,"f").length)return[];return this.decode(`
9
- `)}}_=new WeakMap,k=new WeakMap;Y0.NEWLINE_CHARS=new Set([`
10
- `,"\r"]);Y0.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function G7($,X){for(let W=X??0;W<$.length;W++){if($[W]===10)return{preceding:W,index:W+1,carriage:!1};if($[W]===13)return{preceding:W,index:W+1,carriage:!0}}return null}function DX($){for(let Y=0;Y<$.length-1;Y++){if($[Y]===10&&$[Y+1]===10)return Y+2;if($[Y]===13&&$[Y+1]===13)return Y+2;if($[Y]===13&&$[Y+1]===10&&Y+3<$.length&&$[Y+2]===13&&$[Y+3]===10)return Y+4}return-1}var a4={off:0,error:200,warn:300,info:400,debug:500},p8=($,X,Z)=>{if(!$)return;if(ZX(a4,$))return $;T(Z).warn(`${X} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(a4))}`);return};function e0(){}function r4($,X,Z){if(!X||a4[$]>a4[Z])return e0;else return X[$].bind(X)}var w7={error:e0,warn:e0,info:e0,debug:e0},FX=new WeakMap;function T($){let X=$.logger,Z=$.logLevel??"off";if(!X)return w7;let Y=FX.get(X);if(Y&&Y[0]===Z)return Y[1];let W={error:r4("error",X,Z),warn:r4("warn",X,Z),info:r4("info",X,Z),debug:r4("debug",X,Z)};return FX.set(X,[Z,W]),W}var r=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([X,Z])=>[X,X.toLowerCase()==="x-api-key"||X.toLowerCase()==="authorization"||X.toLowerCase()==="cookie"||X.toLowerCase()==="set-cookie"?"***":Z]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var $4;class b{constructor($,X,Z){this.iterator=$,$4.set(this,void 0),this.controller=X,H(this,$4,Z,"f")}static fromSSEResponse($,X,Z){let Y=!1,W=Z?T(Z):console;async function*J(){if(Y)throw new F("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Y=!0;let z=!1;try{for await(let V of U7($,X)){if(V.event==="completion")try{yield JSON.parse(V.data)}catch(N){throw W.error("Could not parse message into JSON:",V.data),W.error("From chunk:",V.raw),N}if(V.event==="message_start"||V.event==="message_delta"||V.event==="message_stop"||V.event==="content_block_start"||V.event==="content_block_delta"||V.event==="content_block_stop")try{yield JSON.parse(V.data)}catch(N){throw W.error("Could not parse message into JSON:",V.data),W.error("From chunk:",V.raw),N}if(V.event==="ping")continue;if(V.event==="error")throw new O(void 0,l4(V.data)??V.data,void 0,$.headers)}z=!0}catch(V){if(n(V))return;throw V}finally{if(!z)X.abort()}}return new b(J,X,Z)}static fromReadableStream($,X,Z){let Y=!1;async function*W(){let z=new Y0,V=t0($);for await(let N of V)for(let D of z.decode(N))yield D;for(let N of z.flush())yield N}async function*J(){if(Y)throw new F("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Y=!0;let z=!1;try{for await(let V of W()){if(z)continue;if(V)yield JSON.parse(V)}z=!0}catch(V){if(n(V))return;throw V}finally{if(!z)X.abort()}}return new b(J,X,Z)}[($4=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],X=[],Z=this.iterator(),Y=(W)=>{return{next:()=>{if(W.length===0){let J=Z.next();$.push(J),X.push(J)}return W.shift()}}};return[new b(()=>Y($),this.controller,Q(this,$4,"f")),new b(()=>Y(X),this.controller,Q(this,$4,"f"))]}toReadableStream(){let $=this,X;return m8({async start(){X=$[Symbol.asyncIterator]()},async pull(Z){try{let{value:Y,done:W}=await X.next();if(W)return Z.close();let J=M0(JSON.stringify(Y)+`
11
- `);Z.enqueue(J)}catch(Y){Z.error(Y)}},async cancel(){await X.return?.()}})}}async function*U7($,X){if(!$.body){if(X.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new F("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new F("Attempted to iterate over a response with no body")}let Z=new LX,Y=new Y0,W=t0($.body);for await(let J of N7(W))for(let z of Y.decode(J)){let V=Z.decode(z);if(V)yield V}for(let J of Y.flush()){let z=Z.decode(J);if(z)yield z}}async function*N7($){let X=new Uint8Array;for await(let Z of $){if(Z==null)continue;let Y=Z instanceof ArrayBuffer?new Uint8Array(Z):typeof Z==="string"?M0(Z):Z,W=new Uint8Array(X.length+Y.length);W.set(X),W.set(Y,X.length),X=W;let J;while((J=DX(X))!==-1)yield X.slice(0,J),X=X.slice(J)}if(X.length>0)yield X}class LX{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let W={event:this.event,data:this.data.join(`
12
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],W}if(this.chunks.push($),$.startsWith(":"))return null;let[X,Z,Y]=H7($,":");if(Y.startsWith(" "))Y=Y.substring(1);if(X==="event")this.event=Y;else if(X==="data")this.data.push(Y);return null}}function H7($,X){let Z=$.indexOf(X);if(Z!==-1)return[$.substring(0,Z),X,$.substring(Z+X.length)];return[$,"",""]}async function o4($,X){let{response:Z,requestLogID:Y,retryOfRequestLogID:W,startTime:J}=X,z=await(async()=>{if(X.options.stream){if(T($).debug("response",Z.status,Z.url,Z.headers,Z.body),X.options.__streamClass)return X.options.__streamClass.fromSSEResponse(Z,X.controller);return b.fromSSEResponse(Z,X.controller)}if(Z.status===204)return null;if(X.options.__binaryResponse)return Z;let N=Z.headers.get("content-type")?.split(";")[0]?.trim();if(N?.includes("application/json")||N?.endsWith("+json")){if(Z.headers.get("content-length")==="0")return;let G=await Z.json();return i8(G,Z)}return await Z.text()})();return T($).debug(`[${Y}] response parsed`,r({retryOfRequestLogID:W,url:Z.url,status:Z.status,body:z,durationMs:Date.now()-J})),z}function i8($,X){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:X.headers.get("request-id"),enumerable:!1})}var X4;class U0 extends Promise{constructor($,X,Z=o4){super((Y)=>{Y(null)});this.responsePromise=X,this.parseResponse=Z,X4.set(this,void 0),H(this,X4,$,"f")}_thenUnwrap($){return new U0(Q(this,X4,"f"),this.responsePromise,async(X,Z)=>i8($(await this.parseResponse(X,Z),Z),Z.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,X]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:X,request_id:X.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(Q(this,X4,"f"),$));return this.parsedPromise}then($,X){return this.parse().then($,X)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}X4=new WeakMap;var s4;class l8{constructor($,X,Z,Y){s4.set(this,void 0),H(this,s4,$,"f"),this.options=Y,this.response=X,this.body=Z}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new F("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Q(this,s4,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(s4=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let X of $.getPaginatedItems())yield X}}class t4 extends U0{constructor($,X,Z){super($,X,async(Y,W)=>new Z(Y,W.response,await o4(Y,W),W.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let X of $)yield X}}class u extends l8{constructor($,X,Z,Y){super($,X,Z,Y);this.data=Z.data||[],this.has_more=Z.has_more||!1,this.first_id=Z.first_id||null,this.last_id=Z.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let X=this.first_id;if(!X)return null;return{...this.options,query:{...i4(this.options.query),before_id:X}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...i4(this.options.query),after_id:$}}}}class Z4 extends l8{constructor($,X,Z,Y){super($,X,Z,Y);this.data=Z.data||[],this.has_more=Z.has_more||!1,this.next_page=Z.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.next_page;if(!$)return null;return{...this.options,query:{...i4(this.options.query),page:$}}}}var r8=()=>{if(typeof File>"u"){let{process:$}=globalThis,X=typeof $?.versions?.node==="string"&&parseInt($.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(X?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function N0($,X,Z){return r8(),new File($,X??"unknown_file",Z)}function Y4($,X){let Z=typeof $==="object"&&$!==null&&(("name"in $)&&$.name&&String($.name)||("url"in $)&&$.url&&String($.url)||("filename"in $)&&$.filename&&String($.filename)||("path"in $)&&$.path&&String($.path))||"";return X?Z.split(/[\\/]/).pop()||void 0:Z}var a8=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var T0=async($,X,Z=!0)=>{return{...$,body:await F7($.body,X,Z)}},EX=new WeakMap;function D7($){let X=typeof $==="function"?$:$.fetch,Z=EX.get(X);if(Z)return Z;let Y=(async()=>{try{let W="Response"in X?X.Response:(await X("data:,")).constructor,J=new FormData;if(J.toString()===await new W(J).text())return!1;return!0}catch{return!0}})();return EX.set(X,Y),Y}var F7=async($,X,Z=!0)=>{if(!await D7(X))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let Y=new FormData;return await Promise.all(Object.entries($||{}).map(([W,J])=>n8(Y,W,J,Z))),Y},L7=($)=>$ instanceof Blob&&("name"in $);var n8=async($,X,Z,Y)=>{if(Z===void 0)return;if(Z==null)throw TypeError(`Received null for "${X}"; to pass null in FormData, you must use the string 'null'`);if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")$.append(X,String(Z));else if(Z instanceof Response){let W={},J=Z.headers.get("Content-Type");if(J)W={type:J};$.append(X,N0([await Z.blob()],Y4(Z,Y),W))}else if(a8(Z))$.append(X,N0([await new Response(n4(Z)).blob()],Y4(Z,Y)));else if(L7(Z))$.append(X,N0([Z],Y4(Z,Y),{type:Z.type}));else if(Array.isArray(Z))await Promise.all(Z.map((W)=>n8($,X+"[]",W,Y)));else if(typeof Z==="object")await Promise.all(Object.entries(Z).map(([W,J])=>n8($,`${X}[${W}]`,J,Y)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${Z} instead`)};var BX=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",E7=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&BX($),B7=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function e4($,X,Z){if(r8(),$=await $,X||(X=Y4($,!0)),E7($)){if($ instanceof File&&X==null&&Z==null)return $;return N0([await $.arrayBuffer()],X??$.name,{type:$.type,lastModified:$.lastModified,...Z})}if(B7($)){let W=await $.blob();return X||(X=new URL($.url).pathname.split(/[\\/]/).pop()),N0(await o8(W),X,Z)}let Y=await o8($);if(!Z?.type){let W=Y.find((J)=>typeof J==="object"&&("type"in J)&&J.type);if(typeof W==="string")Z={...Z,type:W}}return N0(Y,X,Z)}async function o8($){let X=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)X.push($);else if(BX($))X.push($ instanceof Blob?$:await $.arrayBuffer());else if(a8($))for await(let Z of $)X.push(...await o8(Z));else{let Z=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${Z?`; constructor: ${Z}`:""}${A7($)}`)}return X}function A7($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Z)=>`"${Z}"`).join(", ")}]`}class A{constructor($){this._client=$}}var AX=Symbol.for("brand.privateNullableHeaders");function*O7($){if(!$)return;if(AX in $){let{values:Y,nulls:W}=$;yield*Y.entries();for(let J of W)yield[J,null];return}let X=!1,Z;if($ instanceof Headers)Z=$.entries();else if(u8($))Z=$;else X=!0,Z=Object.entries($??{});for(let Y of Z){let W=Y[0];if(typeof W!=="string")throw TypeError("expected header name to be a string");let J=u8(Y[1])?Y[1]:[Y[1]],z=!1;for(let V of J){if(V===void 0)continue;if(X&&!z)z=!0,yield[W,null];yield[W,V]}}}var L=($)=>{let X=new Headers,Z=new Set;for(let Y of $){let W=new Set;for(let[J,z]of O7(Y)){let V=J.toLowerCase();if(!W.has(V))X.delete(J),W.add(V);if(z===null)X.delete(J),Z.add(V);else X.append(J,z),Z.delete(V)}}return{[AX]:!0,values:X,nulls:Z}};var W4=Symbol("anthropic.sdk.stainlessHelper");function $8($){return typeof $==="object"&&$!==null&&W4 in $}function s8($,X){let Z=new Set;if($){for(let Y of $)if($8(Y))Z.add(Y[W4])}if(X)for(let Y of X){if($8(Y))Z.add(Y[W4]);if(Array.isArray(Y.content)){for(let W of Y.content)if($8(W))Z.add(W[W4])}}return Array.from(Z)}function X8($,X){let Z=s8($,X);if(Z.length===0)return{};return{"x-stainless-helper":Z.join(", ")}}function qX($){if($8($))return{"x-stainless-helper":$[W4]};return{}}function IX($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var OX=Object.freeze(Object.create(null)),I7=($=IX)=>function(Z,...Y){if(Z.length===1)return Z[0];let W=!1,J=[],z=Z.reduce((w,K,G)=>{if(/[?#]/.test(K))W=!0;let x=Y[G],E=(W?encodeURIComponent:$)(""+x);if(G!==Y.length&&(x==null||typeof x==="object"&&x.toString===Object.getPrototypeOf(Object.getPrototypeOf(x.hasOwnProperty??OX)??OX)?.toString))E=x+"",J.push({start:w.length+K.length,length:E.length,error:`Value of type ${Object.prototype.toString.call(x).slice(8,-1)} is not a valid path parameter`});return w+K+(G===Y.length?"":E)},""),V=z.split(/[?#]/,1)[0],N=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,D;while((D=N.exec(V))!==null)J.push({start:D.index,length:D[0].length,error:`Value "${D[0]}" can't be safely passed as a path parameter`});if(J.sort((w,K)=>w.start-K.start),J.length>0){let w=0,K=J.reduce((G,x)=>{let E=" ".repeat(x.start-w),R="^".repeat(x.length);return w=x.start+x.length,G+E+R},"");throw new F(`Path parameters result in path with invalid segments:
13
- ${J.map((G)=>G.error).join(`
14
- `)}
15
- ${z}
16
- ${K}`)}return z},B=I7(IX);class J4 extends A{list($={},X){let{betas:Z,...Y}=$??{};return this._client.getAPIList("/v1/files",u,{query:Y,...X,headers:L([{"anthropic-beta":[...Z??[],"files-api-2025-04-14"].toString()},X?.headers])})}delete($,X={},Z){let{betas:Y}=X??{};return this._client.delete(B`/v1/files/${$}`,{...Z,headers:L([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},Z?.headers])})}download($,X={},Z){let{betas:Y}=X??{};return this._client.get(B`/v1/files/${$}/content`,{...Z,headers:L([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},Z?.headers]),__binaryResponse:!0})}retrieveMetadata($,X={},Z){let{betas:Y}=X??{};return this._client.get(B`/v1/files/${$}`,{...Z,headers:L([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},Z?.headers])})}upload($,X){let{betas:Z,...Y}=$;return this._client.post("/v1/files",T0({body:Y,...X,headers:L([{"anthropic-beta":[...Z??[],"files-api-2025-04-14"].toString()},qX(Y.file),X?.headers])},this._client))}}class z4 extends A{retrieve($,X={},Z){let{betas:Y}=X??{};return this._client.get(B`/v1/models/${$}?beta=true`,{...Z,headers:L([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}list($={},X){let{betas:Z,...Y}=$??{};return this._client.getAPIList("/v1/models?beta=true",u,{query:Y,...X,headers:L([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},X?.headers])})}}var Z8={"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 MX($){return $?.output_format??$?.output_config?.format}function t8($,X,Z){let Y=MX(X);if(!X||!("parse"in(Y??{})))return{...$,content:$.content.map((W)=>{if(W.type==="text"){let J=Object.defineProperty({...W},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(J,"parsed",{get(){return Z.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return W}),parsed_output:null};return e8($,X,Z)}function e8($,X,Z){let Y=null,W=$.content.map((J)=>{if(J.type==="text"){let z=j7(X,J.text);if(Y===null)Y=z;let V=Object.defineProperty({...J},"parsed_output",{value:z,enumerable:!1});return Object.defineProperty(V,"parsed",{get(){return Z.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),z},enumerable:!1})}return J});return{...$,content:W,parsed_output:Y}}function j7($,X){let Z=MX($);if(Z?.type!=="json_schema")return null;try{if("parse"in Z)return Z.parse(X);return JSON.parse(X)}catch(Y){throw new F(`Failed to parse structured output: ${Y}`)}}var S7=($)=>{let X=0,Z=[];while(X<$.length){let Y=$[X];if(Y==="\\"){X++;continue}if(Y==="{"){Z.push({type:"brace",value:"{"}),X++;continue}if(Y==="}"){Z.push({type:"brace",value:"}"}),X++;continue}if(Y==="["){Z.push({type:"paren",value:"["}),X++;continue}if(Y==="]"){Z.push({type:"paren",value:"]"}),X++;continue}if(Y===":"){Z.push({type:"separator",value:":"}),X++;continue}if(Y===","){Z.push({type:"delimiter",value:","}),X++;continue}if(Y==='"'){let V="",N=!1;Y=$[++X];while(Y!=='"'){if(X===$.length){N=!0;break}if(Y==="\\"){if(X++,X===$.length){N=!0;break}V+=Y+$[X],Y=$[++X]}else V+=Y,Y=$[++X]}if(Y=$[++X],!N)Z.push({type:"string",value:V});continue}if(Y&&/\s/.test(Y)){X++;continue}let J=/[0-9]/;if(Y&&J.test(Y)||Y==="-"||Y==="."){let V="";if(Y==="-")V+=Y,Y=$[++X];while(Y&&J.test(Y)||Y===".")V+=Y,Y=$[++X];Z.push({type:"number",value:V});continue}let z=/[a-z]/i;if(Y&&z.test(Y)){let V="";while(Y&&z.test(Y)){if(X===$.length)break;V+=Y,Y=$[++X]}if(V=="true"||V=="false"||V==="null")Z.push({type:"name",value:V});else{X++;continue}continue}X++}return Z},j0=($)=>{if($.length===0)return $;let X=$[$.length-1];switch(X.type){case"separator":return $=$.slice(0,$.length-1),j0($);break;case"number":let Z=X.value[X.value.length-1];if(Z==="."||Z==="-")return $=$.slice(0,$.length-1),j0($);case"string":let Y=$[$.length-2];if(Y?.type==="delimiter")return $=$.slice(0,$.length-1),j0($);else if(Y?.type==="brace"&&Y.value==="{")return $=$.slice(0,$.length-1),j0($);break;case"delimiter":return $=$.slice(0,$.length-1),j0($);break}return $},C7=($)=>{let X=[];if($.map((Z)=>{if(Z.type==="brace")if(Z.value==="{")X.push("}");else X.splice(X.lastIndexOf("}"),1);if(Z.type==="paren")if(Z.value==="[")X.push("]");else X.splice(X.lastIndexOf("]"),1)}),X.length>0)X.reverse().map((Z)=>{if(Z==="}")$.push({type:"brace",value:"}"});else if(Z==="]")$.push({type:"paren",value:"]"})});return $},R7=($)=>{let X="";return $.map((Z)=>{switch(Z.type){case"string":X+='"'+Z.value+'"';break;default:X+=Z.value;break}}),X},Y8=($)=>JSON.parse(R7(C7(j0(S7($)))));var h,W0,S0,V4,W8,Q4,K4,J8,G4,a,w4,z8,V8,H0,Q8,K8,U4,$$,TX,G8,X$,Z$,Y$,jX,SX="__json_buf";function CX($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class N4{constructor($,X){h.add(this),this.messages=[],this.receivedMessages=[],W0.set(this,void 0),S0.set(this,null),this.controller=new AbortController,V4.set(this,void 0),W8.set(this,()=>{}),Q4.set(this,()=>{}),K4.set(this,void 0),J8.set(this,()=>{}),G4.set(this,()=>{}),a.set(this,{}),w4.set(this,!1),z8.set(this,!1),V8.set(this,!1),H0.set(this,!1),Q8.set(this,void 0),K8.set(this,void 0),U4.set(this,void 0),G8.set(this,(Z)=>{if(H(this,z8,!0,"f"),n(Z))Z=new y;if(Z instanceof y)return H(this,V8,!0,"f"),this._emit("abort",Z);if(Z instanceof F)return this._emit("error",Z);if(Z instanceof Error){let Y=new F(Z.message);return Y.cause=Z,this._emit("error",Y)}return this._emit("error",new F(String(Z)))}),H(this,V4,new Promise((Z,Y)=>{H(this,W8,Z,"f"),H(this,Q4,Y,"f")}),"f"),H(this,K4,new Promise((Z,Y)=>{H(this,J8,Z,"f"),H(this,G4,Y,"f")}),"f"),Q(this,V4,"f").catch(()=>{}),Q(this,K4,"f").catch(()=>{}),H(this,S0,$,"f"),H(this,U4,X?.logger??console,"f")}get response(){return Q(this,Q8,"f")}get request_id(){return Q(this,K8,"f")}async withResponse(){H(this,H0,!0,"f");let $=await Q(this,V4,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let X=new N4(null);return X._run(()=>X._fromReadableStream($)),X}static createMessage($,X,Z,{logger:Y}={}){let W=new N4(X,{logger:Y});for(let J of X.messages)W._addMessageParam(J);return H(W,S0,{...X,stream:!0},"f"),W._run(()=>W._createMessage($,{...X,stream:!0},{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),W}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},Q(this,G8,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,X=!0){if(this.receivedMessages.push($),X)this._emit("message",$)}async _createMessage($,X,Z){let Y=Z?.signal,W;if(Y){if(Y.aborted)this.controller.abort();W=this.controller.abort.bind(this.controller),Y.addEventListener("abort",W)}try{Q(this,h,"m",X$).call(this);let{response:J,data:z}=await $.create({...X,stream:!0},{...Z,signal:this.controller.signal}).withResponse();this._connected(J);for await(let V of z)Q(this,h,"m",Z$).call(this,V);if(z.controller.signal?.aborted)throw new y;Q(this,h,"m",Y$).call(this)}finally{if(Y&&W)Y.removeEventListener("abort",W)}}_connected($){if(this.ended)return;H(this,Q8,$,"f"),H(this,K8,$?.headers.get("request-id"),"f"),Q(this,W8,"f").call(this,$),this._emit("connect")}get ended(){return Q(this,w4,"f")}get errored(){return Q(this,z8,"f")}get aborted(){return Q(this,V8,"f")}abort(){this.controller.abort()}on($,X){return(Q(this,a,"f")[$]||(Q(this,a,"f")[$]=[])).push({listener:X}),this}off($,X){let Z=Q(this,a,"f")[$];if(!Z)return this;let Y=Z.findIndex((W)=>W.listener===X);if(Y>=0)Z.splice(Y,1);return this}once($,X){return(Q(this,a,"f")[$]||(Q(this,a,"f")[$]=[])).push({listener:X,once:!0}),this}emitted($){return new Promise((X,Z)=>{if(H(this,H0,!0,"f"),$!=="error")this.once("error",Z);this.once($,X)})}async done(){H(this,H0,!0,"f"),await Q(this,K4,"f")}get currentMessage(){return Q(this,W0,"f")}async finalMessage(){return await this.done(),Q(this,h,"m",$$).call(this)}async finalText(){return await this.done(),Q(this,h,"m",TX).call(this)}_emit($,...X){if(Q(this,w4,"f"))return;if($==="end")H(this,w4,!0,"f"),Q(this,J8,"f").call(this);let Z=Q(this,a,"f")[$];if(Z)Q(this,a,"f")[$]=Z.filter((Y)=>!Y.once),Z.forEach(({listener:Y})=>Y(...X));if($==="abort"){let Y=X[0];if(!Q(this,H0,"f")&&!Z?.length)Promise.reject(Y);Q(this,Q4,"f").call(this,Y),Q(this,G4,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=X[0];if(!Q(this,H0,"f")&&!Z?.length)Promise.reject(Y);Q(this,Q4,"f").call(this,Y),Q(this,G4,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",Q(this,h,"m",$$).call(this))}async _fromReadableStream($,X){let Z=X?.signal,Y;if(Z){if(Z.aborted)this.controller.abort();Y=this.controller.abort.bind(this.controller),Z.addEventListener("abort",Y)}try{Q(this,h,"m",X$).call(this),this._connected(null);let W=b.fromReadableStream($,this.controller);for await(let J of W)Q(this,h,"m",Z$).call(this,J);if(W.controller.signal?.aborted)throw new y;Q(this,h,"m",Y$).call(this)}finally{if(Z&&Y)Z.removeEventListener("abort",Y)}}[(W0=new WeakMap,S0=new WeakMap,V4=new WeakMap,W8=new WeakMap,Q4=new WeakMap,K4=new WeakMap,J8=new WeakMap,G4=new WeakMap,a=new WeakMap,w4=new WeakMap,z8=new WeakMap,V8=new WeakMap,H0=new WeakMap,Q8=new WeakMap,K8=new WeakMap,U4=new WeakMap,G8=new WeakMap,h=new WeakSet,$$=function(){if(this.receivedMessages.length===0)throw new F("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},TX=function(){if(this.receivedMessages.length===0)throw new F("stream ended without producing a Message with role=assistant");let X=this.receivedMessages.at(-1).content.filter((Z)=>Z.type==="text").map((Z)=>Z.text);if(X.length===0)throw new F("stream ended without producing a content block with type=text");return X.join(" ")},X$=function(){if(this.ended)return;H(this,W0,void 0,"f")},Z$=function(X){if(this.ended)return;let Z=Q(this,h,"m",jX).call(this,X);switch(this._emit("streamEvent",X,Z),X.type){case"content_block_delta":{let Y=Z.content.at(-1);switch(X.delta.type){case"text_delta":{if(Y.type==="text")this._emit("text",X.delta.text,Y.text||"");break}case"citations_delta":{if(Y.type==="text")this._emit("citation",X.delta.citation,Y.citations??[]);break}case"input_json_delta":{if(CX(Y)&&Y.input)this._emit("inputJson",X.delta.partial_json,Y.input);break}case"thinking_delta":{if(Y.type==="thinking")this._emit("thinking",X.delta.thinking,Y.thinking);break}case"signature_delta":{if(Y.type==="thinking")this._emit("signature",Y.signature);break}case"compaction_delta":{if(Y.type==="compaction"&&Y.content)this._emit("compaction",Y.content);break}default:RX(X.delta)}break}case"message_stop":{this._addMessageParam(Z),this._addMessage(t8(Z,Q(this,S0,"f"),{logger:Q(this,U4,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Z.content.at(-1));break}case"message_start":{H(this,W0,Z,"f");break}case"content_block_start":case"message_delta":break}},Y$=function(){if(this.ended)throw new F("stream has ended, this shouldn't happen");let X=Q(this,W0,"f");if(!X)throw new F("request ended without sending any chunks");return H(this,W0,void 0,"f"),t8(X,Q(this,S0,"f"),{logger:Q(this,U4,"f")})},jX=function(X){let Z=Q(this,W0,"f");if(X.type==="message_start"){if(Z)throw new F(`Unexpected event order, got ${X.type} before receiving "message_stop"`);return X.message}if(!Z)throw new F(`Unexpected event order, got ${X.type} before "message_start"`);switch(X.type){case"message_stop":return Z;case"message_delta":if(Z.container=X.delta.container,Z.stop_reason=X.delta.stop_reason,Z.stop_sequence=X.delta.stop_sequence,Z.usage.output_tokens=X.usage.output_tokens,Z.context_management=X.context_management,X.usage.input_tokens!=null)Z.usage.input_tokens=X.usage.input_tokens;if(X.usage.cache_creation_input_tokens!=null)Z.usage.cache_creation_input_tokens=X.usage.cache_creation_input_tokens;if(X.usage.cache_read_input_tokens!=null)Z.usage.cache_read_input_tokens=X.usage.cache_read_input_tokens;if(X.usage.server_tool_use!=null)Z.usage.server_tool_use=X.usage.server_tool_use;if(X.usage.iterations!=null)Z.usage.iterations=X.usage.iterations;return Z;case"content_block_start":return Z.content.push(X.content_block),Z;case"content_block_delta":{let Y=Z.content.at(X.index);switch(X.delta.type){case"text_delta":{if(Y?.type==="text")Z.content[X.index]={...Y,text:(Y.text||"")+X.delta.text};break}case"citations_delta":{if(Y?.type==="text")Z.content[X.index]={...Y,citations:[...Y.citations??[],X.delta.citation]};break}case"input_json_delta":{if(Y&&CX(Y)){let W=Y[SX]||"";W+=X.delta.partial_json;let J={...Y};if(Object.defineProperty(J,SX,{value:W,enumerable:!1,writable:!0}),W)try{J.input=Y8(W)}catch(z){let V=new F(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${z}. JSON: ${W}`);Q(this,G8,"f").call(this,V)}Z.content[X.index]=J}break}case"thinking_delta":{if(Y?.type==="thinking")Z.content[X.index]={...Y,thinking:Y.thinking+X.delta.thinking};break}case"signature_delta":{if(Y?.type==="thinking")Z.content[X.index]={...Y,signature:X.delta.signature};break}case"compaction_delta":{if(Y?.type==="compaction")Z.content[X.index]={...Y,content:(Y.content||"")+X.delta.content};break}default:RX(X.delta)}return Z}case"content_block_stop":return Z}},Symbol.asyncIterator)](){let $=[],X=[],Z=!1;return this.on("streamEvent",(Y)=>{let W=X.shift();if(W)W.resolve(Y);else $.push(Y)}),this.on("end",()=>{Z=!0;for(let Y of X)Y.resolve(void 0);X.length=0}),this.on("abort",(Y)=>{Z=!0;for(let W of X)W.reject(Y);X.length=0}),this.on("error",(Y)=>{Z=!0;for(let W of X)W.reject(Y);X.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((W,J)=>X.push({resolve:W,reject:J})).then((W)=>W?{value:W,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new b(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function RX($){}class C0 extends Error{constructor($){let X=typeof $==="string"?$:$.map((Z)=>{if(Z.type==="text")return Z.text;return`[${Z.type}]`}).join(" ");super(X);this.name="ToolError",this.content=$}}var yX=1e5,PX=`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
- 1. Task Overview
18
- The user's core request and success criteria
19
- Any clarifications or constraints they specified
20
- 2. Current State
21
- What has been completed so far
22
- Files created, modified, or analyzed (with paths if relevant)
23
- Key outputs or artifacts produced
24
- 3. Important Discoveries
25
- Technical constraints or requirements uncovered
26
- Decisions made and their rationale
27
- Errors encountered and how they were resolved
28
- What approaches were tried that didn't work (and why)
29
- 4. Next Steps
30
- Specific actions needed to complete the task
31
- Any blockers or open questions to resolve
32
- Priority order if multiple steps remain
33
- 5. Context to Preserve
34
- User preferences or style requirements
35
- Domain-specific details that aren't obvious
36
- Any promises made to the user
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 H4,R0,x0,I,x4,v,o,J0,D4,fX,W$;function _X(){let $,X;return{promise:new Promise((Y,W)=>{$=Y,X=W}),resolve:$,reject:X}}class F4{constructor($,X,Z){H4.add(this),this.client=$,R0.set(this,!1),x0.set(this,!1),I.set(this,void 0),x4.set(this,void 0),v.set(this,void 0),o.set(this,void 0),J0.set(this,void 0),D4.set(this,0),H(this,I,{params:{...X,messages:structuredClone(X.messages)}},"f");let W=["BetaToolRunner",...s8(X.tools,X.messages)].join(", ");H(this,x4,{...Z,headers:L([{"x-stainless-helper":W},Z?.headers])},"f"),H(this,J0,_X(),"f")}async*[(R0=new WeakMap,x0=new WeakMap,I=new WeakMap,x4=new WeakMap,v=new WeakMap,o=new WeakMap,J0=new WeakMap,D4=new WeakMap,H4=new WeakSet,fX=async function(){let X=Q(this,I,"f").params.compactionControl;if(!X||!X.enabled)return!1;let Z=0;if(Q(this,v,"f")!==void 0)try{let N=await Q(this,v,"f");Z=N.usage.input_tokens+(N.usage.cache_creation_input_tokens??0)+(N.usage.cache_read_input_tokens??0)+N.usage.output_tokens}catch{return!1}let Y=X.contextTokenThreshold??yX;if(Z<Y)return!1;let W=X.model??Q(this,I,"f").params.model,J=X.summaryPrompt??PX,z=Q(this,I,"f").params.messages;if(z[z.length-1].role==="assistant"){let N=z[z.length-1];if(Array.isArray(N.content)){let D=N.content.filter((w)=>w.type!=="tool_use");if(D.length===0)z.pop();else N.content=D}}let V=await this.client.beta.messages.create({model:W,messages:[...z,{role:"user",content:[{type:"text",text:J}]}],max_tokens:Q(this,I,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(V.content[0]?.type!=="text")throw new F("Expected text response for compaction");return Q(this,I,"f").params.messages=[{role:"user",content:V.content}],!0},Symbol.asyncIterator)](){var $;if(Q(this,R0,"f"))throw new F("Cannot iterate over a consumed stream");H(this,R0,!0,"f"),H(this,x0,!0,"f"),H(this,o,void 0,"f");try{while(!0){let X;try{if(Q(this,I,"f").params.max_iterations&&Q(this,D4,"f")>=Q(this,I,"f").params.max_iterations)break;H(this,x0,!1,"f"),H(this,o,void 0,"f"),H(this,D4,($=Q(this,D4,"f"),$++,$),"f"),H(this,v,void 0,"f");let{max_iterations:Z,compactionControl:Y,...W}=Q(this,I,"f").params;if(W.stream)X=this.client.beta.messages.stream({...W},Q(this,x4,"f")),H(this,v,X.finalMessage(),"f"),Q(this,v,"f").catch(()=>{}),yield X;else H(this,v,this.client.beta.messages.create({...W,stream:!1},Q(this,x4,"f")),"f"),yield Q(this,v,"f");if(!await Q(this,H4,"m",fX).call(this)){if(!Q(this,x0,"f")){let{role:V,content:N}=await Q(this,v,"f");Q(this,I,"f").params.messages.push({role:V,content:N})}let z=await Q(this,H4,"m",W$).call(this,Q(this,I,"f").params.messages.at(-1));if(z)Q(this,I,"f").params.messages.push(z);else if(!Q(this,x0,"f"))break}}finally{if(X)X.abort()}}if(!Q(this,v,"f"))throw new F("ToolRunner concluded without a message from the server");Q(this,J0,"f").resolve(await Q(this,v,"f"))}catch(X){throw H(this,R0,!1,"f"),Q(this,J0,"f").promise.catch(()=>{}),Q(this,J0,"f").reject(X),H(this,J0,_X(),"f"),X}}setMessagesParams($){if(typeof $==="function")Q(this,I,"f").params=$(Q(this,I,"f").params);else Q(this,I,"f").params=$;H(this,x0,!0,"f"),H(this,o,void 0,"f")}async generateToolResponse(){let $=await Q(this,v,"f")??this.params.messages.at(-1);if(!$)return null;return Q(this,H4,"m",W$).call(this,$)}done(){return Q(this,J0,"f").promise}async runUntilDone(){if(!Q(this,R0,"f"))for await(let $ of this);return this.done()}get params(){return Q(this,I,"f").params}pushMessages(...$){this.setMessagesParams((X)=>({...X,messages:[...X.messages,...$]}))}then($,X){return this.runUntilDone().then($,X)}}W$=async function(X){if(Q(this,o,"f")!==void 0)return Q(this,o,"f");return H(this,o,y7(Q(this,I,"f").params,X),"f"),Q(this,o,"f")};async function y7($,X=$.messages.at(-1)){if(!X||X.role!=="assistant"||!X.content||typeof X.content==="string")return null;let Z=X.content.filter((W)=>W.type==="tool_use");if(Z.length===0)return null;return{role:"user",content:await Promise.all(Z.map(async(W)=>{let J=$.tools.find((z)=>("name"in z?z.name:z.mcp_server_name)===W.name);if(!J||!("run"in J))return{type:"tool_result",tool_use_id:W.id,content:`Error: Tool '${W.name}' not found`,is_error:!0};try{let z=W.input;if("parse"in J&&J.parse)z=J.parse(z);let V=await J.run(z);return{type:"tool_result",tool_use_id:W.id,content:V}}catch(z){return{type:"tool_result",tool_use_id:W.id,content:z instanceof C0?z.content:`Error: ${z instanceof Error?z.message:String(z)}`,is_error:!0}}}))}}class y0{constructor($,X){this.iterator=$,this.controller=X}async*decoder(){let $=new Y0;for await(let X of this.iterator)for(let Z of $.decode(X))yield JSON.parse(Z);for(let X of $.flush())yield JSON.parse(X)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse($,X){if(!$.body){if(X.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new F("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new F("Attempted to iterate over a response with no body")}return new y0(t0($.body),X)}}class L4 extends A{create($,X){let{betas:Z,...Y}=$;return this._client.post("/v1/messages/batches?beta=true",{body:Y,...X,headers:L([{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString()},X?.headers])})}retrieve($,X={},Z){let{betas:Y}=X??{};return this._client.get(B`/v1/messages/batches/${$}?beta=true`,{...Z,headers:L([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}list($={},X){let{betas:Z,...Y}=$??{};return this._client.getAPIList("/v1/messages/batches?beta=true",u,{query:Y,...X,headers:L([{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString()},X?.headers])})}delete($,X={},Z){let{betas:Y}=X??{};return this._client.delete(B`/v1/messages/batches/${$}?beta=true`,{...Z,headers:L([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}cancel($,X={},Z){let{betas:Y}=X??{};return this._client.post(B`/v1/messages/batches/${$}/cancel?beta=true`,{...Z,headers:L([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}async results($,X={},Z){let Y=await this.retrieve($);if(!Y.results_url)throw new F(`No batch \`results_url\`; Has it finished processing? ${Y.processing_status} - ${Y.id}`);let{betas:W}=X??{};return this._client.get(Y.results_url,{...Z,headers:L([{"anthropic-beta":[...W??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((J,z)=>y0.fromResponse(z.response,z.controller))}}var kX={"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"},f7=["claude-opus-4-6"];class z0 extends A{constructor(){super(...arguments);this.batches=new L4(this._client)}create($,X){let Z=bX($),{betas:Y,...W}=Z;if(W.model in kX)console.warn(`The model '${W.model}' is deprecated and will reach end-of-life on ${kX[W.model]}
39
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(W.model in f7&&W.thinking&&W.thinking.type==="enabled")console.warn(`Using Claude with ${W.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let J=this._client._options.timeout;if(!W.stream&&J==null){let V=Z8[W.model]??void 0;J=this._client.calculateNonstreamingTimeout(W.max_tokens,V)}let z=X8(W.tools,W.messages);return this._client.post("/v1/messages?beta=true",{body:W,timeout:J??600000,...X,headers:L([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},z,X?.headers]),stream:Z.stream??!1})}parse($,X){return X={...X,headers:L([{"anthropic-beta":[...$.betas??[],"structured-outputs-2025-12-15"].toString()},X?.headers])},this.create($,X).then((Z)=>e8(Z,$,{logger:this._client.logger??console}))}stream($,X){return N4.createMessage(this,$,X)}countTokens($,X){let Z=bX($),{betas:Y,...W}=Z;return this._client.post("/v1/messages/count_tokens?beta=true",{body:W,...X,headers:L([{"anthropic-beta":[...Y??[],"token-counting-2024-11-01"].toString()},X?.headers])})}toolRunner($,X){return new F4(this._client,$,X)}}function bX($){if(!$.output_format)return $;if($.output_config?.format)throw new F("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:X,...Z}=$;return{...Z,output_config:{...$.output_config,format:X}}}z0.Batches=L4;z0.BetaToolRunner=F4;z0.ToolError=C0;class E4 extends A{create($,X={},Z){let{betas:Y,...W}=X??{};return this._client.post(B`/v1/skills/${$}/versions?beta=true`,T0({body:W,...Z,headers:L([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])},this._client))}retrieve($,X,Z){let{skill_id:Y,betas:W}=X;return this._client.get(B`/v1/skills/${Y}/versions/${$}?beta=true`,{...Z,headers:L([{"anthropic-beta":[...W??[],"skills-2025-10-02"].toString()},Z?.headers])})}list($,X={},Z){let{betas:Y,...W}=X??{};return this._client.getAPIList(B`/v1/skills/${$}/versions?beta=true`,Z4,{query:W,...Z,headers:L([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])})}delete($,X,Z){let{skill_id:Y,betas:W}=X;return this._client.delete(B`/v1/skills/${Y}/versions/${$}?beta=true`,{...Z,headers:L([{"anthropic-beta":[...W??[],"skills-2025-10-02"].toString()},Z?.headers])})}}class P0 extends A{constructor(){super(...arguments);this.versions=new E4(this._client)}create($={},X){let{betas:Z,...Y}=$??{};return this._client.post("/v1/skills?beta=true",T0({body:Y,...X,headers:L([{"anthropic-beta":[...Z??[],"skills-2025-10-02"].toString()},X?.headers])},this._client,!1))}retrieve($,X={},Z){let{betas:Y}=X??{};return this._client.get(B`/v1/skills/${$}?beta=true`,{...Z,headers:L([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])})}list($={},X){let{betas:Z,...Y}=$??{};return this._client.getAPIList("/v1/skills?beta=true",Z4,{query:Y,...X,headers:L([{"anthropic-beta":[...Z??[],"skills-2025-10-02"].toString()},X?.headers])})}delete($,X={},Z){let{betas:Y}=X??{};return this._client.delete(B`/v1/skills/${$}?beta=true`,{...Z,headers:L([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])})}}P0.Versions=E4;class i extends A{constructor(){super(...arguments);this.models=new z4(this._client),this.messages=new z0(this._client),this.files=new J4(this._client),this.skills=new P0(this._client)}}i.Models=z4;i.Messages=z0;i.Files=J4;i.Skills=P0;class f0 extends A{create($,X){let{betas:Z,...Y}=$;return this._client.post("/v1/complete",{body:Y,timeout:this._client._options.timeout??600000,...X,headers:L([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},X?.headers]),stream:$.stream??!1})}}function vX($){return $?.output_config?.format}function J$($,X,Z){let Y=vX(X);if(!X||!("parse"in(Y??{})))return{...$,content:$.content.map((W)=>{if(W.type==="text")return Object.defineProperty({...W},"parsed_output",{value:null,enumerable:!1});return W}),parsed_output:null};return z$($,X,Z)}function z$($,X,Z){let Y=null,W=$.content.map((J)=>{if(J.type==="text"){let z=v7(X,J.text);if(Y===null)Y=z;return Object.defineProperty({...J},"parsed_output",{value:z,enumerable:!1})}return J});return{...$,content:W,parsed_output:Y}}function v7($,X){let Z=vX($);if(Z?.type!=="json_schema")return null;try{if("parse"in Z)return Z.parse(X);return JSON.parse(X)}catch(Y){throw new F(`Failed to parse structured output: ${Y}`)}}var g,V0,_0,B4,w8,A4,q4,U8,O4,s,I4,N8,H8,D0,x8,D8,M4,V$,hX,Q$,K$,G$,w$,gX,dX="__json_buf";function uX($){return $.type==="tool_use"||$.type==="server_tool_use"}class T4{constructor($,X){g.add(this),this.messages=[],this.receivedMessages=[],V0.set(this,void 0),_0.set(this,null),this.controller=new AbortController,B4.set(this,void 0),w8.set(this,()=>{}),A4.set(this,()=>{}),q4.set(this,void 0),U8.set(this,()=>{}),O4.set(this,()=>{}),s.set(this,{}),I4.set(this,!1),N8.set(this,!1),H8.set(this,!1),D0.set(this,!1),x8.set(this,void 0),D8.set(this,void 0),M4.set(this,void 0),Q$.set(this,(Z)=>{if(H(this,N8,!0,"f"),n(Z))Z=new y;if(Z instanceof y)return H(this,H8,!0,"f"),this._emit("abort",Z);if(Z instanceof F)return this._emit("error",Z);if(Z instanceof Error){let Y=new F(Z.message);return Y.cause=Z,this._emit("error",Y)}return this._emit("error",new F(String(Z)))}),H(this,B4,new Promise((Z,Y)=>{H(this,w8,Z,"f"),H(this,A4,Y,"f")}),"f"),H(this,q4,new Promise((Z,Y)=>{H(this,U8,Z,"f"),H(this,O4,Y,"f")}),"f"),Q(this,B4,"f").catch(()=>{}),Q(this,q4,"f").catch(()=>{}),H(this,_0,$,"f"),H(this,M4,X?.logger??console,"f")}get response(){return Q(this,x8,"f")}get request_id(){return Q(this,D8,"f")}async withResponse(){H(this,D0,!0,"f");let $=await Q(this,B4,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let X=new T4(null);return X._run(()=>X._fromReadableStream($)),X}static createMessage($,X,Z,{logger:Y}={}){let W=new T4(X,{logger:Y});for(let J of X.messages)W._addMessageParam(J);return H(W,_0,{...X,stream:!0},"f"),W._run(()=>W._createMessage($,{...X,stream:!0},{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),W}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},Q(this,Q$,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,X=!0){if(this.receivedMessages.push($),X)this._emit("message",$)}async _createMessage($,X,Z){let Y=Z?.signal,W;if(Y){if(Y.aborted)this.controller.abort();W=this.controller.abort.bind(this.controller),Y.addEventListener("abort",W)}try{Q(this,g,"m",K$).call(this);let{response:J,data:z}=await $.create({...X,stream:!0},{...Z,signal:this.controller.signal}).withResponse();this._connected(J);for await(let V of z)Q(this,g,"m",G$).call(this,V);if(z.controller.signal?.aborted)throw new y;Q(this,g,"m",w$).call(this)}finally{if(Y&&W)Y.removeEventListener("abort",W)}}_connected($){if(this.ended)return;H(this,x8,$,"f"),H(this,D8,$?.headers.get("request-id"),"f"),Q(this,w8,"f").call(this,$),this._emit("connect")}get ended(){return Q(this,I4,"f")}get errored(){return Q(this,N8,"f")}get aborted(){return Q(this,H8,"f")}abort(){this.controller.abort()}on($,X){return(Q(this,s,"f")[$]||(Q(this,s,"f")[$]=[])).push({listener:X}),this}off($,X){let Z=Q(this,s,"f")[$];if(!Z)return this;let Y=Z.findIndex((W)=>W.listener===X);if(Y>=0)Z.splice(Y,1);return this}once($,X){return(Q(this,s,"f")[$]||(Q(this,s,"f")[$]=[])).push({listener:X,once:!0}),this}emitted($){return new Promise((X,Z)=>{if(H(this,D0,!0,"f"),$!=="error")this.once("error",Z);this.once($,X)})}async done(){H(this,D0,!0,"f"),await Q(this,q4,"f")}get currentMessage(){return Q(this,V0,"f")}async finalMessage(){return await this.done(),Q(this,g,"m",V$).call(this)}async finalText(){return await this.done(),Q(this,g,"m",hX).call(this)}_emit($,...X){if(Q(this,I4,"f"))return;if($==="end")H(this,I4,!0,"f"),Q(this,U8,"f").call(this);let Z=Q(this,s,"f")[$];if(Z)Q(this,s,"f")[$]=Z.filter((Y)=>!Y.once),Z.forEach(({listener:Y})=>Y(...X));if($==="abort"){let Y=X[0];if(!Q(this,D0,"f")&&!Z?.length)Promise.reject(Y);Q(this,A4,"f").call(this,Y),Q(this,O4,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=X[0];if(!Q(this,D0,"f")&&!Z?.length)Promise.reject(Y);Q(this,A4,"f").call(this,Y),Q(this,O4,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",Q(this,g,"m",V$).call(this))}async _fromReadableStream($,X){let Z=X?.signal,Y;if(Z){if(Z.aborted)this.controller.abort();Y=this.controller.abort.bind(this.controller),Z.addEventListener("abort",Y)}try{Q(this,g,"m",K$).call(this),this._connected(null);let W=b.fromReadableStream($,this.controller);for await(let J of W)Q(this,g,"m",G$).call(this,J);if(W.controller.signal?.aborted)throw new y;Q(this,g,"m",w$).call(this)}finally{if(Z&&Y)Z.removeEventListener("abort",Y)}}[(V0=new WeakMap,_0=new WeakMap,B4=new WeakMap,w8=new WeakMap,A4=new WeakMap,q4=new WeakMap,U8=new WeakMap,O4=new WeakMap,s=new WeakMap,I4=new WeakMap,N8=new WeakMap,H8=new WeakMap,D0=new WeakMap,x8=new WeakMap,D8=new WeakMap,M4=new WeakMap,Q$=new WeakMap,g=new WeakSet,V$=function(){if(this.receivedMessages.length===0)throw new F("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},hX=function(){if(this.receivedMessages.length===0)throw new F("stream ended without producing a Message with role=assistant");let X=this.receivedMessages.at(-1).content.filter((Z)=>Z.type==="text").map((Z)=>Z.text);if(X.length===0)throw new F("stream ended without producing a content block with type=text");return X.join(" ")},K$=function(){if(this.ended)return;H(this,V0,void 0,"f")},G$=function(X){if(this.ended)return;let Z=Q(this,g,"m",gX).call(this,X);switch(this._emit("streamEvent",X,Z),X.type){case"content_block_delta":{let Y=Z.content.at(-1);switch(X.delta.type){case"text_delta":{if(Y.type==="text")this._emit("text",X.delta.text,Y.text||"");break}case"citations_delta":{if(Y.type==="text")this._emit("citation",X.delta.citation,Y.citations??[]);break}case"input_json_delta":{if(uX(Y)&&Y.input)this._emit("inputJson",X.delta.partial_json,Y.input);break}case"thinking_delta":{if(Y.type==="thinking")this._emit("thinking",X.delta.thinking,Y.thinking);break}case"signature_delta":{if(Y.type==="thinking")this._emit("signature",Y.signature);break}default:mX(X.delta)}break}case"message_stop":{this._addMessageParam(Z),this._addMessage(J$(Z,Q(this,_0,"f"),{logger:Q(this,M4,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Z.content.at(-1));break}case"message_start":{H(this,V0,Z,"f");break}case"content_block_start":case"message_delta":break}},w$=function(){if(this.ended)throw new F("stream has ended, this shouldn't happen");let X=Q(this,V0,"f");if(!X)throw new F("request ended without sending any chunks");return H(this,V0,void 0,"f"),J$(X,Q(this,_0,"f"),{logger:Q(this,M4,"f")})},gX=function(X){let Z=Q(this,V0,"f");if(X.type==="message_start"){if(Z)throw new F(`Unexpected event order, got ${X.type} before receiving "message_stop"`);return X.message}if(!Z)throw new F(`Unexpected event order, got ${X.type} before "message_start"`);switch(X.type){case"message_stop":return Z;case"message_delta":if(Z.stop_reason=X.delta.stop_reason,Z.stop_sequence=X.delta.stop_sequence,Z.usage.output_tokens=X.usage.output_tokens,X.usage.input_tokens!=null)Z.usage.input_tokens=X.usage.input_tokens;if(X.usage.cache_creation_input_tokens!=null)Z.usage.cache_creation_input_tokens=X.usage.cache_creation_input_tokens;if(X.usage.cache_read_input_tokens!=null)Z.usage.cache_read_input_tokens=X.usage.cache_read_input_tokens;if(X.usage.server_tool_use!=null)Z.usage.server_tool_use=X.usage.server_tool_use;return Z;case"content_block_start":return Z.content.push({...X.content_block}),Z;case"content_block_delta":{let Y=Z.content.at(X.index);switch(X.delta.type){case"text_delta":{if(Y?.type==="text")Z.content[X.index]={...Y,text:(Y.text||"")+X.delta.text};break}case"citations_delta":{if(Y?.type==="text")Z.content[X.index]={...Y,citations:[...Y.citations??[],X.delta.citation]};break}case"input_json_delta":{if(Y&&uX(Y)){let W=Y[dX]||"";W+=X.delta.partial_json;let J={...Y};if(Object.defineProperty(J,dX,{value:W,enumerable:!1,writable:!0}),W)J.input=Y8(W);Z.content[X.index]=J}break}case"thinking_delta":{if(Y?.type==="thinking")Z.content[X.index]={...Y,thinking:Y.thinking+X.delta.thinking};break}case"signature_delta":{if(Y?.type==="thinking")Z.content[X.index]={...Y,signature:X.delta.signature};break}default:mX(X.delta)}return Z}case"content_block_stop":return Z}},Symbol.asyncIterator)](){let $=[],X=[],Z=!1;return this.on("streamEvent",(Y)=>{let W=X.shift();if(W)W.resolve(Y);else $.push(Y)}),this.on("end",()=>{Z=!0;for(let Y of X)Y.resolve(void 0);X.length=0}),this.on("abort",(Y)=>{Z=!0;for(let W of X)W.reject(Y);X.length=0}),this.on("error",(Y)=>{Z=!0;for(let W of X)W.reject(Y);X.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((W,J)=>X.push({resolve:W,reject:J})).then((W)=>W?{value:W,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new b(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function mX($){}class j4 extends A{create($,X){return this._client.post("/v1/messages/batches",{body:$,...X})}retrieve($,X){return this._client.get(B`/v1/messages/batches/${$}`,X)}list($={},X){return this._client.getAPIList("/v1/messages/batches",u,{query:$,...X})}delete($,X){return this._client.delete(B`/v1/messages/batches/${$}`,X)}cancel($,X){return this._client.post(B`/v1/messages/batches/${$}/cancel`,X)}async results($,X){let Z=await this.retrieve($);if(!Z.results_url)throw new F(`No batch \`results_url\`; Has it finished processing? ${Z.processing_status} - ${Z.id}`);return this._client.get(Z.results_url,{...X,headers:L([{Accept:"application/binary"},X?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Y,W)=>y0.fromResponse(W.response,W.controller))}}class F0 extends A{constructor(){super(...arguments);this.batches=new j4(this._client)}create($,X){if($.model in cX)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${cX[$.model]}
40
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if($.model in g7&&$.thinking&&$.thinking.type==="enabled")console.warn(`Using Claude with ${$.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let Z=this._client._options.timeout;if(!$.stream&&Z==null){let W=Z8[$.model]??void 0;Z=this._client.calculateNonstreamingTimeout($.max_tokens,W)}let Y=X8($.tools,$.messages);return this._client.post("/v1/messages",{body:$,timeout:Z??600000,...X,headers:L([Y,X?.headers]),stream:$.stream??!1})}parse($,X){return this.create($,X).then((Z)=>z$(Z,$,{logger:this._client.logger??console}))}stream($,X){return T4.createMessage(this,$,X,{logger:this._client.logger??console})}countTokens($,X){return this._client.post("/v1/messages/count_tokens",{body:$,...X})}}var cX={"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","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026"},g7=["claude-opus-4-6"];F0.Batches=j4;class k0 extends A{retrieve($,X={},Z){let{betas:Y}=X??{};return this._client.get(B`/v1/models/${$}`,{...Z,headers:L([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}list($={},X){let{betas:Z,...Y}=$??{};return this._client.getAPIList("/v1/models",u,{query:Y,...X,headers:L([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},X?.headers])})}}var S4=($)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[$]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.($)?.trim();return};var U$,N$,F8,pX,iX="\\n\\nHuman:",lX="\\n\\nAssistant:";class q{constructor({baseURL:$=S4("ANTHROPIC_BASE_URL"),apiKey:X=S4("ANTHROPIC_API_KEY")??null,authToken:Z=S4("ANTHROPIC_AUTH_TOKEN")??null,...Y}={}){U$.add(this),F8.set(this,void 0);let W={apiKey:X,authToken:Z,...Y,baseURL:$||"https://api.anthropic.com"};if(!W.dangerouslyAllowBrowser&&QX())throw new F(`It looks like you're running in a browser-like environment.
41
-
42
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
43
- If you understand the risks and have appropriate mitigations in place,
44
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
45
-
46
- new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
47
- `);this.baseURL=W.baseURL,this.timeout=W.timeout??N$.DEFAULT_TIMEOUT,this.logger=W.logger??console;let J="warn";this.logLevel=J,this.logLevel=p8(W.logLevel,"ClientOptions.logLevel",this)??p8(S4("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??J,this.fetchOptions=W.fetchOptions,this.maxRetries=W.maxRetries??2,this.fetch=W.fetch??GX(),H(this,F8,UX,"f"),this._options=W,this.apiKey=typeof X==="string"?X:null,this.authToken=Z}withOptions($){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,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:X}){if($.get("x-api-key")||$.get("authorization"))return;if(this.apiKey&&$.get("x-api-key"))return;if(X.has("x-api-key"))return;if(this.authToken&&$.get("authorization"))return;if(X.has("authorization"))return;throw 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($){return L([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return L([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return L([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return Object.entries($).filter(([X,Z])=>typeof Z<"u").map(([X,Z])=>{if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")return`${encodeURIComponent(X)}=${encodeURIComponent(Z)}`;if(Z===null)return`${encodeURIComponent(X)}=`;throw new F(`Cannot stringify type ${typeof Z}; 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 ${Z0}`}defaultIdempotencyKey(){return`stainless-node-retry-${g8()}`}makeStatusError($,X,Z,Y){return O.generate($,X,Z,Y)}buildURL($,X,Z){let Y=!Q(this,U$,"m",pX).call(this)&&Z||this.baseURL,W=$X($)?new URL($):new URL(Y+(Y.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),J=this.defaultQuery();if(!XX(J))X={...J,...X};if(typeof X==="object"&&X&&!Array.isArray(X))W.search=this.stringifyQuery(X);return W.toString()}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new F("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 600000}async prepareOptions($){}async prepareRequest($,{url:X,options:Z}){}get($,X){return this.methodRequest("get",$,X)}post($,X){return this.methodRequest("post",$,X)}patch($,X){return this.methodRequest("patch",$,X)}put($,X){return this.methodRequest("put",$,X)}delete($,X){return this.methodRequest("delete",$,X)}methodRequest($,X,Z){return this.request(Promise.resolve(Z).then((Y)=>{return{method:$,path:X,...Y}}))}request($,X=null){return new U0(this,this.makeRequest($,X,void 0))}async makeRequest($,X,Z){let Y=await $,W=Y.maxRetries??this.maxRetries;if(X==null)X=W;await this.prepareOptions(Y);let{req:J,url:z,timeout:V}=await this.buildRequest(Y,{retryCount:W-X});await this.prepareRequest(J,{url:z,options:Y});let N="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),D=Z===void 0?"":`, retryOf: ${Z}`,w=Date.now();if(T(this).debug(`[${N}] sending request`,r({retryOfRequestLogID:Z,method:Y.method,url:z,options:Y,headers:J.headers})),Y.signal?.aborted)throw new y;let K=new AbortController,G=await this.fetchWithTimeout(z,J,V,K).catch(m0),x=Date.now();if(G instanceof globalThis.Error){let M=`retrying, ${X} attempts remaining`;if(Y.signal?.aborted)throw new y;let P=n(G)||/timed? ?out/i.test(String(G)+("cause"in G?String(G.cause):""));if(X)return T(this).info(`[${N}] connection ${P?"timed out":"failed"} - ${M}`),T(this).debug(`[${N}] connection ${P?"timed out":"failed"} (${M})`,r({retryOfRequestLogID:Z,url:z,durationMs:x-w,message:G.message})),this.retryRequest(Y,X,Z??N);if(T(this).info(`[${N}] connection ${P?"timed out":"failed"} - error; no more retries left`),T(this).debug(`[${N}] connection ${P?"timed out":"failed"} (error; no more retries left)`,r({retryOfRequestLogID:Z,url:z,durationMs:x-w,message:G.message})),P)throw new c0;throw new w0({cause:G})}let E=[...G.headers.entries()].filter(([M])=>M==="request-id").map(([M,P])=>", "+M+": "+JSON.stringify(P)).join(""),R=`[${N}${D}${E}] ${J.method} ${z} ${G.ok?"succeeded":"failed"} with status ${G.status} in ${x-w}ms`;if(!G.ok){let M=await this.shouldRetry(G);if(X&&M){let c=`retrying, ${X} attempts remaining`;return await wX(G.body),T(this).info(`${R} - ${c}`),T(this).debug(`[${N}] response error (${c})`,r({retryOfRequestLogID:Z,url:G.url,status:G.status,headers:G.headers,durationMs:x-w})),this.retryRequest(Y,X,Z??N,G.headers)}let P=M?"error; no more retries left":"error; not retryable";T(this).info(`${R} - ${P}`);let d=await G.text().catch((c)=>m0(c).message),b4=l4(d),v4=b4?void 0:d;throw T(this).debug(`[${N}] response error (${P})`,r({retryOfRequestLogID:Z,url:G.url,status:G.status,headers:G.headers,message:v4,durationMs:Date.now()-w})),this.makeStatusError(G.status,b4,v4,G.headers)}return T(this).info(R),T(this).debug(`[${N}] response start`,r({retryOfRequestLogID:Z,url:G.url,status:G.status,headers:G.headers,durationMs:x-w})),{response:G,options:Y,controller:K,requestLogID:N,retryOfRequestLogID:Z,startTime:w}}getAPIList($,X,Z){return this.requestAPIList(X,Z&&"then"in Z?Z.then((Y)=>({method:"get",path:$,...Y})):{method:"get",path:$,...Z})}requestAPIList($,X){let Z=this.makeRequest(X,null,void 0);return new t4(this,Z,$)}async fetchWithTimeout($,X,Z,Y){let{signal:W,method:J,...z}=X||{},V=this._makeAbort(Y);if(W)W.addEventListener("abort",V,{once:!0});let N=setTimeout(V,Z),D=globalThis.ReadableStream&&z.body instanceof globalThis.ReadableStream||typeof z.body==="object"&&z.body!==null&&Symbol.asyncIterator in z.body,w={signal:Y.signal,...D?{duplex:"half"}:{},method:"GET",...z};if(J)w.method=J.toUpperCase();try{return await this.fetch.call(void 0,$,w)}finally{clearTimeout(N)}}async shouldRetry($){let X=$.headers.get("x-should-retry");if(X==="true")return!0;if(X==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,X,Z,Y){let W,J=Y?.get("retry-after-ms");if(J){let V=parseFloat(J);if(!Number.isNaN(V))W=V}let z=Y?.get("retry-after");if(z&&!W){let V=parseFloat(z);if(!Number.isNaN(V))W=V*1000;else W=Date.parse(z)-Date.now()}if(!(W&&0<=W&&W<60000)){let V=$.maxRetries??this.maxRetries;W=this.calculateDefaultRetryTimeoutMillis(X,V)}return await WX(W),this.makeRequest($,X-1,Z)}calculateDefaultRetryTimeoutMillis($,X){let W=X-$,J=Math.min(0.5*Math.pow(2,W),8),z=1-Math.random()*0.25;return J*z*1000}calculateNonstreamingTimeout($,X){if(3600000*$/128000>600000||X!=null&&$>X)throw new F("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 600000}async buildRequest($,{retryCount:X=0}={}){let Z={...$},{method:Y,path:W,query:J,defaultBaseURL:z}=Z,V=this.buildURL(W,J,z);if("timeout"in Z)YX("timeout",Z.timeout);Z.timeout=Z.timeout??this.timeout;let{bodyHeaders:N,body:D}=this.buildBody({options:Z}),w=await this.buildHeaders({options:$,method:Y,bodyHeaders:N,retryCount:X});return{req:{method:Y,headers:w,...Z.signal&&{signal:Z.signal},...globalThis.ReadableStream&&D instanceof globalThis.ReadableStream&&{duplex:"half"},...D&&{body:D},...this.fetchOptions??{},...Z.fetchOptions??{}},url:V,timeout:Z.timeout}}async buildHeaders({options:$,method:X,bodyHeaders:Z,retryCount:Y}){let W={};if(this.idempotencyHeader&&X!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();W[this.idempotencyHeader]=$.idempotencyKey}let J=L([W,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Y),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...KX(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,Z,$.headers]);return this.validateHeaders(J),J.values}_makeAbort($){return()=>$.abort()}buildBody({options:{body:$,headers:X}}){if(!$)return{bodyHeaders:void 0,body:void 0};let Z=L([X]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&Z.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:n4($)};else return Q(this,F8,"f").call(this,{body:$,headers:Z})}}N$=q,F8=new WeakMap,U$=new WeakSet,pX=function(){return this.baseURL!=="https://api.anthropic.com"};q.Anthropic=N$;q.HUMAN_PROMPT=iX;q.AI_PROMPT=lX;q.DEFAULT_TIMEOUT=600000;q.AnthropicError=F;q.APIError=O;q.APIConnectionError=w0;q.APIConnectionTimeoutError=c0;q.APIUserAbortError=y;q.NotFoundError=n0;q.ConflictError=r0;q.RateLimitError=o0;q.BadRequestError=p0;q.AuthenticationError=i0;q.InternalServerError=s0;q.PermissionDeniedError=l0;q.UnprocessableEntityError=a0;q.toFile=e4;class t extends q{constructor(){super(...arguments);this.completions=new f0(this),this.messages=new F0(this),this.models=new k0(this),this.beta=new i(this)}}t.Completions=f0;t.Messages=F0;t.Models=k0;t.Beta=i;var u7=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]);function m7($){return JSON.parse(JSON.stringify($))}function nX($){let X=m7($);return L0(X)}function L0($){let X={},Z=f($,"$ref");if(Z!==void 0)return X.$ref=Z,X;let Y=f($,"$defs");if(Y!==void 0){let w={};X.$defs=w;for(let[K,G]of Object.entries(Y))w[K]=L0(G)}let W=f($,"type"),J=f($,"anyOf"),z=f($,"oneOf"),V=f($,"allOf");if(Array.isArray(J))X.anyOf=J.map((w)=>L0(w));else if(Array.isArray(z))X.anyOf=z.map((w)=>L0(w));else if(Array.isArray(V))X.allOf=V.map((w)=>L0(w));else{if(W===void 0)throw Error("JSON schema must have a type defined if anyOf/oneOf/allOf are not used");X.type=W}let N=f($,"description");if(N!==void 0)X.description=N;let D=f($,"title");if(D!==void 0)X.title=D;if(W==="object"){let w=f($,"properties")||{};X.properties=Object.fromEntries(Object.entries(w).map(([G,x])=>[G,L0(x)])),f($,"additionalProperties"),X.additionalProperties=!1;let K=f($,"required");if(K!==void 0)X.required=K}else if(W==="string"){let w=f($,"format");if(w!==void 0&&u7.has(w))X.format=w;else if(w!==void 0)$.format=w}else if(W==="array"){let w=f($,"items");if(w!==void 0)X.items=L0(w);let K=f($,"minItems");if(K!==void 0&&(K===0||K===1))X.minItems=K;else if(K!==void 0)$.minItems=K}if(Object.keys($).length>0){let w=X.description;X.description=(w?w+`
48
-
49
- `:"")+"{"+Object.entries($).map(([K,G])=>`${K}: ${JSON.stringify(G)}`).join(", ")+"}"}return X}var c7={"claude-opus-4-6":16384,"claude-opus-4-5":16384,"claude-sonnet-4-5":16384,"claude-haiku-4-5":16384,"claude-opus-4-1":16384,"claude-sonnet-4":16384,"claude-opus-4":16384,"claude-3-7-sonnet":8192,"claude-3-5-sonnet":8192,"claude-3-5-haiku":8192,"claude-3-opus":4096,"claude-3-sonnet":4096,"claude-3-haiku":4096},rX=2048;function p7($){if(!$)return rX;return Object.entries(c7).find(([X])=>$.startsWith(X))?.[1]??rX}function i7($){return!!($.tools&&$.tools.length>0)}function l7($){for(let X of $.messages??[]){if(typeof X.content==="string")continue;for(let Z of X.content??[])if(typeof Z==="object"&&Z!=null&&Z.type==="document"&&typeof Z.citations==="object"&&Z.citations?.enabled)return!0}return!1}function n7($){return!!($.thinking&&($.thinking.type==="enabled"||$.thinking.type==="adaptive"))}function r7($){return!!$.context_management?.edits?.some((X)=>X.type==="compact_20260112")}function a7($){return"input_schema"in $}function o7($){return typeof $==="object"&&$!==null&&"type"in $&&(("name"in $)||("mcp_server_name"in $))&&typeof $.type==="string"&&["text_editor_","computer_","bash_","web_search_","web_fetch_","str_replace_editor_","str_replace_based_edit_tool_","code_execution_","memory_","tool_search_","mcp_toolset"].some((X)=>typeof $.type==="string"&&$.type.startsWith(X))}function s7($,X,...Z){return Array.from(new Set([...$??[],...X??[],...Z.flatMap((Y)=>Array.from(Y))]))}function t7($){if(typeof $.content==="string")return $.content;else if(Array.isArray($.content)&&$.content.length>=1&&"input"in $.content[0])return typeof $.content[0].input==="string"?$.content[0].input:JSON.stringify($.content[0].input);else if(Array.isArray($.content)&&$.content.length>=1&&"text"in $.content[0]&&typeof $.content[0].text==="string")return $.content[0].text}var oX=class extends B8{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;outputConfig;inferenceGeo;batchClient;streamingClient;streamUsage=!0;betas;createClient;constructor($){super($??{});if(this.anthropicApiKey=$?.apiKey??$?.anthropicApiKey??C4("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!$?.createClient)throw Error("Anthropic API key not found");this.clientOptions=$?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=$?.anthropicApiUrl,this.modelName=$?.model??$?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=$?.invocationKwargs??{},this.topP=$?.topP??this.topP,this.temperature=$?.temperature??this.temperature,this.topK=$?.topK??this.topK,this.maxTokens=$?.maxTokens??p7(this.model),this.stopSequences=$?.stopSequences??this.stopSequences,this.streaming=$?.streaming??!1,this.streamUsage=$?.streamUsage??this.streamUsage,this.thinking=$?.thinking??this.thinking,this.contextManagement=$?.contextManagement??this.contextManagement,this.outputConfig=$?.outputConfig??this.outputConfig,this.inferenceGeo=$?.inferenceGeo??this.inferenceGeo,this.betas=$?.betas??this.betas,this.createClient=$?.createClient??((X)=>new t(X))}getLsParams($){let X=this.invocationParams($);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:X.temperature??void 0,ls_max_tokens:X.max_tokens??void 0,ls_stop:$.stop}}formatStructuredToolToAnthropic($){if(!$)return;return $.map((X)=>{if(E0(X)&&X.extras?.providerToolDefinition)return X.extras.providerToolDefinition;if(o7(X))return X;if(a7(X))return X;if(v0(X))return{name:X.function.name,description:X.function.description,input_schema:X.function.parameters};if(E0(X))return{name:X.name,description:X.description,input_schema:K0(X.schema)?Q0(X.schema):X.schema,...X.extras?g$.parse(X.extras):{}};throw Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(X,null,2)}`)})}bindTools($,X){return this.withConfig({tools:this.formatStructuredToolToAnthropic($),...X})}invocationParams($){let X=h$($?.tool_choice),Z=$?.tools?.reduce((z,V)=>{if(typeof V==="object"&&"type"in V&&V.type in y8){let N=y8[V.type];if(!z.includes(N))return[...z,N]}return z},[]),Y=(()=>{let z={...this.outputConfig,...$?.outputConfig};if($?.outputFormat&&!z.format)z.format=$.outputFormat;return Object.keys(z).length>0?z:void 0})(),W=this.contextManagement?.edits?.some((z)=>z.type==="compact_20260112")?["compact-2026-01-12"]:[],J={model:this.model,stop_sequences:$?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic($?.tools),tool_choice:X,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:$?.container,betas:s7(this.betas,$?.betas,Z??[],W),output_config:Y,inference_geo:$?.inferenceGeo??this.inferenceGeo,mcp_servers:$?.mcp_servers};if(this.thinking.type==="enabled"||this.thinking.type==="adaptive"){if(this.topP!==void 0&&this.topK!==-1)throw Error("topK is not supported when thinking is enabled");if(this.temperature!==void 0&&this.temperature!==1)throw Error("temperature is not supported when thinking is enabled")}else J.temperature=this.temperature,J.top_k=this.topK,J.top_p=this.topP;return J}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks($,X,Z){let Y=this.invocationParams(X),W=c4($);if(X.cache_control)W=v8(W,X.cache_control);let J={...Y,...W,stream:!0},z=!i7(J)&&!l7(J)&&!n7(J)&&!r7(J),V=await this.createStreamWithRetry(J,{headers:X.headers,signal:X.signal});for await(let N of V){if(X.signal?.aborted){V.controller.abort();return}let D=this.streamUsage??X.streamUsage,w=a$(N,{streamUsage:D,coerceContentToString:z});if(!w)continue;let{chunk:K}=w,G=t7(K),x=new L8({message:new j({content:K.content,additional_kwargs:K.additional_kwargs,tool_call_chunks:K.tool_call_chunks,usage_metadata:D?K.usage_metadata:void 0,response_metadata:K.response_metadata,id:K.id}),text:G??""});yield x,await Z?.handleLLMNewToken(G??"",void 0,void 0,void 0,void 0,{chunk:x})}}async _generateNonStreaming($,X,Z,Y){let W=c4($);if(Y)W=v8(W,Y);let{content:J,...z}=await this.completionWithRetry({...X,stream:!1,...W},Z),V=o$(J,z),{role:N,type:D,...w}=z;return{generations:V,llmOutput:w}}async _generate($,X,Z){if(X.signal?.throwIfAborted(),this.stopSequences&&X.stop)throw Error('"stopSequence" parameter found in input and default params');let Y=this.invocationParams(X);if(Y.stream){let W,J=this._streamResponseChunks($,X,Z);for await(let z of J)if(W===void 0)W=z;else W=W.concat(z);if(W===void 0)throw Error("No chunks returned from Anthropic API.");return{generations:[{text:W.text,message:W.message}]}}else return this._generateNonStreaming($,Y,{signal:X.signal,headers:X.headers},X.cache_control)}async createStreamWithRetry($,X){if(!this.streamingClient){let J=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...J,apiKey:this.apiKey,maxRetries:0})}let{betas:Z,...Y}=$,W=async()=>{try{if($?.betas?.length)return await this.streamingClient.beta.messages.create({...Y,betas:Z,...this.invocationKwargs,stream:!0},X);return await this.streamingClient.messages.create({...Y,...this.invocationKwargs,stream:!0},X)}catch(J){throw h8(J)}};return this.caller.call(W)}async completionWithRetry($,X){if(!this.batchClient){let J=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...J,apiKey:this.apiKey,maxRetries:0})}let{betas:Z,...Y}=$,W=async()=>{try{if($?.betas?.length)return await this.batchClient.beta.messages.create({...Y,...this.invocationKwargs,betas:Z},X);return await this.batchClient.messages.create({...Y,...this.invocationKwargs},X)}catch(J){throw h8(J)}};return this.caller.callWithOptions({signal:X.signal??void 0},W)}_llmType(){return"anthropic"}get profile(){return e$[this.model]??{}}withStructuredOutput($,X){let Z,Y,{schema:W,name:J,includeRaw:z}={...X,schema:$},V=X?.method??"functionCalling";if(V==="jsonMode")console.warn('"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".'),V="jsonSchema";if(V==="jsonSchema"){Y=K0(W)?aX.fromZodSchema(W):new A8;let K=nX(Q0(W));Z=this.withConfig({outputVersion:"v0",outputConfig:{format:{type:"json_schema",schema:K}},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:K}})}else if(V==="functionCalling"){let K=J??"extract",G;if(K0(W)){let x=Q0(W);G=[{name:K,description:x.description??"A function available to call.",input_schema:x}],Y=new j8({returnSingle:!0,keyName:K,zodSchema:W})}else{let x;if(typeof W.name==="string"&&typeof W.description==="string"&&typeof W.input_schema==="object"&&W.input_schema!=null)x=W,K=W.name;else x={name:K,description:W.description??"",input_schema:W};G=[x],Y=new j8({returnSingle:!0,keyName:K})}if(this.thinking?.type==="enabled"||this.thinking?.type==="adaptive"){console.warn("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."),Z=this.withConfig({outputVersion:"v0",tools:G,ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:Q0(W)}});let E=(R)=>{if(!R.tool_calls||R.tool_calls.length===0)throw Error("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.");return R};Z=Z.pipe(E)}else Z=this.withConfig({outputVersion:"v0",tools:G,tool_choice:{type:"tool",name:K},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:Q0(W)}})}else throw TypeError(`Unrecognized structured output method '${V}'. Expected 'functionCalling' or 'jsonSchema'`);if(!z)return Z.pipe(Y).withConfig({runName:"ChatAnthropicStructuredOutput"});let N=b0.assign({parsed:(K,G)=>Y.invoke(K.raw,G)}),D=b0.assign({parsed:()=>null}),w=N.withFallbacks({fallbacks:[D]});return E8.from([{raw:Z},w]).withConfig({runName:"StructuredOutputRunnable"})}},H$=class extends oX{};var e7=U.object({command:U.literal("view"),path:U.string()}),$Y=U.object({command:U.literal("create"),path:U.string(),file_text:U.string()}),XY=U.object({command:U.literal("str_replace"),path:U.string(),old_str:U.string(),new_str:U.string()}),ZY=U.object({command:U.literal("insert"),path:U.string(),insert_line:U.number(),insert_text:U.string()}),YY=U.object({command:U.literal("delete"),path:U.string()}),WY=U.object({command:U.literal("rename"),old_path:U.string(),new_path:U.string()}),JY=U.discriminatedUnion("command",[e7,$Y,XY,ZY,YY,WY]),zY=U.object({command:U.literal("view"),path:U.string(),view_range:U.tuple([U.number(),U.number()]).optional()}),VY=U.object({command:U.literal("str_replace"),path:U.string(),old_str:U.string(),new_str:U.string()}),QY=U.object({command:U.literal("create"),path:U.string(),file_text:U.string()}),KY=U.object({command:U.literal("insert"),path:U.string(),insert_line:U.number(),new_str:U.string()}),GY=U.discriminatedUnion("command",[zY,VY,QY,KY]),m=U.tuple([U.number(),U.number()]),sX=U.object({action:U.literal("screenshot")}),tX=U.object({action:U.literal("left_click"),coordinate:m}),eX=U.object({action:U.literal("right_click"),coordinate:m}),$Z=U.object({action:U.literal("middle_click"),coordinate:m}),XZ=U.object({action:U.literal("double_click"),coordinate:m}),ZZ=U.object({action:U.literal("triple_click"),coordinate:m}),YZ=U.object({action:U.literal("left_click_drag"),start_coordinate:m,end_coordinate:m}),WZ=U.object({action:U.literal("left_mouse_down"),coordinate:m}),JZ=U.object({action:U.literal("left_mouse_up"),coordinate:m}),zZ=U.object({action:U.literal("scroll"),coordinate:m,scroll_direction:U.enum(["up","down","left","right"]),scroll_amount:U.number()}),VZ=U.object({action:U.literal("type"),text:U.string()}),QZ=U.object({action:U.literal("key"),key:U.string()}),KZ=U.object({action:U.literal("mouse_move"),coordinate:m}),GZ=U.object({action:U.literal("hold_key"),key:U.string()}),wZ=U.object({action:U.literal("wait"),duration:U.number().optional()}),wY=U.object({action:U.literal("zoom"),region:U.tuple([U.number(),U.number(),U.number(),U.number()])}),UY=U.discriminatedUnion("action",[sX,tX,eX,$Z,XZ,ZZ,YZ,WZ,JZ,zZ,VZ,QZ,KZ,GZ,wZ]),NY=U.discriminatedUnion("action",[sX,tX,eX,$Z,XZ,ZZ,YZ,WZ,JZ,zZ,VZ,QZ,KZ,GZ,wZ,wY]),HY=U.object({command:U.string().describe("The bash command to run")}),xY=U.object({restart:U.literal(!0).describe("Set to true to restart the bash session")}),DY=U.union([HY,xY]);function e($){if(typeof $==="object"&&$!==null){let X={...$};if("additionalProperties"in X)delete X.additionalProperties;if("$schema"in X)delete X.$schema;if("strict"in X)delete X.strict;for(let Z in X)if(Z in X){if(Array.isArray(X[Z]))X[Z]=X[Z].map(e);else if(typeof X[Z]==="object"&&X[Z]!==null)X[Z]=e(X[Z])}return X}return $}function R4($){let{$schema:X,...Z}=e(K0($)?Q0($):$);return Z}function UZ($){let{$schema:X,...Z}=e($);return Z}function B0($,X,Z=[]){if($==null||typeof $!=="object")return;let Y=$;if(Array.isArray(Y.enum)){if(Y.enum.some((W)=>W==="")){let W=Z.length?` at path "${Z.join(".")}"`:"",J=X?` in tool "${X}"`:"";throw Error(`Invalid enum: empty string not allowed${J}${W}. Gemini API rejects empty strings in enums.`)}}if(Y.type==="object"&&Y.properties&&typeof Y.properties==="object")for(let[W,J]of Object.entries(Y.properties))B0(J,X,[...Z,W]);if(Y.items)B0(Y.items,X,[...Z,"[]"]);for(let W of["anyOf","oneOf","allOf"]){let J=Y[W];if(Array.isArray(J))J.forEach((z,V)=>B0(z,X,[...Z,`${W}[${V}]`]))}if(Y.additionalProperties&&typeof Y.additionalProperties==="object")B0(Y.additionalProperties,X,[...Z,"additionalProperties"])}var S=[];for(let $=0;$<256;++$)S.push(($+256).toString(16).slice(1));function NZ($,X=0){return(S[$[X+0]]+S[$[X+1]]+S[$[X+2]]+S[$[X+3]]+"-"+S[$[X+4]]+S[$[X+5]]+"-"+S[$[X+6]]+S[$[X+7]]+"-"+S[$[X+8]]+S[$[X+9]]+"-"+S[$[X+10]]+S[$[X+11]]+S[$[X+12]]+S[$[X+13]]+S[$[X+14]]+S[$[X+15]]).toLowerCase()}import{randomFillSync as FY}from"crypto";var O8=new Uint8Array(256),q8=O8.length;function x$(){if(q8>O8.length-16)FY(O8),q8=0;return O8.slice(q8,q8+=16)}import{randomUUID as LY}from"crypto";var D$={randomUUID:LY};function EY($,X,Z){if(D$.randomUUID&&!X&&!$)return D$.randomUUID();$=$||{};let Y=$.random??$.rng?.()??x$();if(Y.length<16)throw Error("Random bytes length must be >= 16");if(Y[6]=Y[6]&15|64,Y[8]=Y[8]&63|128,X){if(Z=Z||0,Z<0||Z+16>X.length)throw RangeError(`UUID byte range ${Z}:${Z+15} is out of buffer bounds`);for(let W=0;W<16;++W)X[Z+W]=Y[W];return X}return NZ(Y)}var I8=EY;var L$="__gemini_function_call_thought_signatures__",BY="ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==",AY=($)=>$();function qY($){if(FZ.isInstance($))return $.role;return $.type}function OY($){switch($){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw Error(`Unknown / unsupported author: ${$}`)}}function IY($){if("mimeType"in $&&"data"in $)return{inlineData:{mimeType:$.mimeType,data:$.data}};if("mimeType"in $&&"fileUri"in $)return{fileData:{mimeType:$.mimeType,fileUri:$.fileUri}};throw Error("Invalid media content")}function MY($,X){return X.map((Z)=>{if(F$(Z))return Z.tool_calls??[];return[]}).flat().find((Z)=>{return Z.id===$.tool_call_id})?.name}function TY($){return{providerName:"Google Gemini",fromStandardTextBlock(X){return{text:X.text}},fromStandardImageBlock(X){if(!$)throw Error("This model does not support images");if(X.source_type==="url"){let Z=X0({dataUrl:X.url});if(Z)return{inlineData:{mimeType:Z.mime_type,data:Z.data}};else return{fileData:{mimeType:X.mime_type??"",fileUri:X.url}}}if(X.source_type==="base64")return{inlineData:{mimeType:X.mime_type??"",data:X.data}};throw Error(`Unsupported source type: ${X.source_type}`)},fromStandardAudioBlock(X){if(!$)throw Error("This model does not support audio");if(X.source_type==="url"){let Z=X0({dataUrl:X.url});if(Z)return{inlineData:{mimeType:Z.mime_type,data:Z.data}};else return{fileData:{mimeType:X.mime_type??"",fileUri:X.url}}}if(X.source_type==="base64")return{inlineData:{mimeType:X.mime_type??"",data:X.data}};throw Error(`Unsupported source type: ${X.source_type}`)},fromStandardFileBlock(X){if(!$)throw Error("This model does not support files");if(X.source_type==="text")return{text:X.text};if(X.source_type==="url"){let Z=X0({dataUrl:X.url});if(Z)return{inlineData:{mimeType:Z.mime_type,data:Z.data}};else return{fileData:{mimeType:X.mime_type??"",fileUri:X.url}}}if(X.source_type==="base64")return{inlineData:{mimeType:X.mime_type??"",data:X.data}};throw Error(`Unsupported source type: ${X.source_type}`)}}}function HZ($,X){if(u4($))return m4($,TY(X));if($.type==="text")return{text:$.text};else if($.type==="executableCode")return{executableCode:$.executableCode};else if($.type==="codeExecutionResult")return{codeExecutionResult:$.codeExecutionResult};else if($.type==="image_url"){if(!X)throw Error("This model does not support images");let Z;if(typeof $.image_url==="string")Z=$.image_url;else if(typeof $.image_url==="object"&&"url"in $.image_url)Z=$.image_url.url;else throw Error("Please provide image as base64 encoded data URL");let[Y,W]=Z.split(",");if(!Y.startsWith("data:"))throw Error("Please provide image as base64 encoded data URL");let[J,z]=Y.replace(/^data:/,"").split(";");if(z!=="base64")throw Error("Please provide image as base64 encoded data URL");return{inlineData:{data:W,mimeType:J}}}else if($.type==="media")return IY($);else if($.type==="tool_use")return{functionCall:{name:$.name,args:$.input}};else if($.type==="tool_call")return{functionCall:{name:$.name,args:$.args}};else if($.type?.includes("/")&&$.type.split("/").length===2&&"data"in $&&typeof $.data==="string")return{inlineData:{mimeType:$.type,data:$.data}};else if("functionCall"in $)return;else if("type"in $)throw Error(`Unknown content type ${$.type}`);else throw Error(`Unknown content ${JSON.stringify($)}`)}function jY($,X,Z,Y){if(DZ($)){let V=$.name??MY($,Z);if(V===void 0)throw Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${$.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);let N=Array.isArray($.content)?$.content.map((D)=>HZ(D,X)).filter((D)=>D!==void 0):$.content;if($.status==="error")return[{functionResponse:{name:V,response:{error:{details:N}}}}];return[{functionResponse:{name:V,response:{result:N}}}]}let W=[],J=[];if(typeof $.content==="string"&&$.content)J.push({text:$.content});if(Array.isArray($.content))J.push(...$.content.map((V)=>HZ(V,X)).filter((V)=>V!==void 0));let z=$.additional_kwargs?.[L$];if(F$($)&&$.tool_calls?.length)W=$.tool_calls.map((V)=>{let N=AY(()=>{if(V.id){let D=z?.[V.id];if(D)return D}if(Y?.includes("gemini-3"))return BY;return""});return{functionCall:{name:V.name,args:V.args},...N?{thoughtSignature:N}:{}}});return[...J,...W]}function E$($,X,Z=!1,Y){return $.reduce((W,J,z)=>{if(!xZ(J))throw Error("Unsupported message input");let V=qY(J);if(V==="system"&&z!==0)throw Error("System message should be the first one");let N=OY(V),D=W.content[W.content.length];if(!W.mergeWithPreviousContent&&D&&D.role===N)throw Error("Google Generative AI requires alternate messages between authors");let w=jY(J,X,$.slice(0,z),Y);if(W.mergeWithPreviousContent){let x=W.content[W.content.length-1];if(!x)throw Error("There was a problem parsing your system message. Please try a prompt without one.");return x.parts.push(...w),{mergeWithPreviousContent:!1,content:W.content}}let K=N;if(K==="function"||K==="system"&&!Z)K="user";let G={role:K,parts:w};return{mergeWithPreviousContent:V==="system"&&!Z,content:[...W.content,G]}},{content:[],mergeWithPreviousContent:!1}).content}function LZ($,X){if(!$.candidates||$.candidates.length===0||!$.candidates[0])return{generations:[],llmOutput:{filters:$.promptFeedback}};let[Z]=$.candidates,{content:Y,...W}=Z,J=Y.parts?.reduce((w,K)=>{if("functionCall"in K&&K.functionCall)w.push({...K,id:"id"in K.functionCall&&typeof K.functionCall.id==="string"?K.functionCall.id:I8()});return w},[]),z,V=Y?.parts;if(Array.isArray(V)&&V.length===1&&"text"in V[0]&&V[0].text&&!V[0].thought)z=V[0].text;else if(Array.isArray(V)&&V.length>0)z=V.map((w)=>{if(w.thought&&"text"in w&&w.text)return{type:"thinking",thinking:w.text,...w.thoughtSignature?{signature:w.thoughtSignature}:{}};else if("text"in w)return{type:"text",text:w.text};else if("inlineData"in w)return{type:"inlineData",inlineData:w.inlineData};else if("functionCall"in w)return{type:"functionCall",functionCall:w.functionCall};else if("functionResponse"in w)return{type:"functionResponse",functionResponse:w.functionResponse};else if("fileData"in w)return{type:"fileData",fileData:w.fileData};else if("executableCode"in w)return{type:"executableCode",executableCode:w.executableCode};else if("codeExecutionResult"in w)return{type:"codeExecutionResult",codeExecutionResult:w.codeExecutionResult};return w});else z=[];let N=J?.reduce((w,K)=>{if("thoughtSignature"in K&&typeof K.thoughtSignature==="string")w[K.id]=K.thoughtSignature;return w},{}),D="";if(typeof z==="string")D=z;else if(Array.isArray(z)&&z.length>0)D=z.find((w)=>("text"in w))?.text??D;return{generations:[{text:D,message:new l({content:z??"",tool_calls:J?.map((w)=>({type:"tool_call",id:w.id,name:w.functionCall.name,args:w.functionCall.args})),additional_kwargs:{...W,[L$]:N},usage_metadata:X?.usageMetadata}),generationInfo:W}],llmOutput:{tokenUsage:{promptTokens:X?.usageMetadata?.input_tokens,completionTokens:X?.usageMetadata?.output_tokens,totalTokens:X?.usageMetadata?.total_tokens}}}}function EZ($,X){if(!$.candidates||$.candidates.length===0)return null;let[Z]=$.candidates,{content:Y,...W}=Z,J=Y.parts?.reduce((K,G)=>{if("functionCall"in G&&G.functionCall)K.push({...G,id:"id"in G.functionCall&&typeof G.functionCall.id==="string"?G.functionCall.id:I8()});return K},[]),z,V=Y?.parts;if(Array.isArray(V)&&V.every((K)=>("text"in K)&&!K.thought))z=V.map((K)=>K.text).join("");else if(Array.isArray(V))z=V.map((K)=>{if(K.thought&&"text"in K&&K.text)return{type:"thinking",thinking:K.text,...K.thoughtSignature?{signature:K.thoughtSignature}:{}};else if("text"in K)return{type:"text",text:K.text};else if("inlineData"in K)return{type:"inlineData",inlineData:K.inlineData};else if("functionCall"in K)return{type:"functionCall",functionCall:K.functionCall};else if("functionResponse"in K)return{type:"functionResponse",functionResponse:K.functionResponse};else if("fileData"in K)return{type:"fileData",fileData:K.fileData};else if("executableCode"in K)return{type:"executableCode",executableCode:K.executableCode};else if("codeExecutionResult"in K)return{type:"codeExecutionResult",codeExecutionResult:K.codeExecutionResult};return K});else z=[];let N="";if(z&&typeof z==="string")N=z;else if(Array.isArray(z))N=z.find((K)=>("text"in K))?.text??"";let D=[];if(J)D.push(...J.map((K)=>({type:"tool_call_chunk",id:K.id,name:K.functionCall.name,args:JSON.stringify(K.functionCall.args)})));let w=J?.reduce((K,G)=>{if("thoughtSignature"in G&&typeof G.thoughtSignature==="string")K[G.id]=G.thoughtSignature;return K},{});return new L8({text:N,message:new j({content:z||"",name:!Y?void 0:Y.role,tool_call_chunks:D,additional_kwargs:{[L$]:w},response_metadata:{model_provider:"google-genai"},usage_metadata:X.usageMetadata}),generationInfo:W})}function BZ($){if($.every((X)=>("functionDeclarations"in X)&&Array.isArray(X.functionDeclarations)))return $;return[{functionDeclarations:$.map((X)=>{if(E0(X)){let Z=R4(X.schema);if(Z.type==="object"&&"properties"in Z&&Object.keys(Z.properties).length===0)return{name:X.name,description:X.description};return B0(Z,X.name),{name:X.name,description:X.description,parameters:Z}}if(v0(X)){let Z=UZ(X.function.parameters);return B0(Z,X.function.name),{name:X.function.name,description:X.function.description??"A function available to call.",parameters:Z}}return X})}]}function B$($,X){let Z={input_tokens:$?.promptTokenCount??0,output_tokens:$?.candidatesTokenCount??0,total_tokens:$?.totalTokenCount??0};if($?.cachedContentTokenCount)Z.input_token_details??={},Z.input_token_details.cache_read=$.cachedContentTokenCount;if(X==="gemini-3-pro-preview"){let Y=Math.max(0,$?.promptTokenCount??-200000),W=Math.max(0,$?.cachedContentTokenCount??-200000);if(Y)Z.input_token_details={...Z.input_token_details,over_200k:Y};if(W)Z.input_token_details={...Z.input_token_details,cache_read_over_200k:W}}return Z}var A$=class extends g4{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor($){super($);this.keyName=$.keyName,this.returnSingle=$.returnSingle??this.returnSingle,this.zodSchema=$.zodSchema}async _validateResult($){if(this.zodSchema===void 0)return $;let X=await h4(this.zodSchema,$);if(X.success)return X.data;else throw new g0(`Failed to parse. Text: "${JSON.stringify($,null,2)}". Error: ${JSON.stringify(X.error.issues)}`,JSON.stringify($,null,2))}async parseResult($){let X=$.flatMap((Y)=>{let{message:W}=Y;if(!("tool_calls"in W)||!Array.isArray(W.tool_calls))return[];return W.tool_calls});if(X[0]===void 0)throw Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");let[Z]=X;return await this._validateResult(Z.args)}};var AZ;(function($){$.STRING="string",$.NUMBER="number",$.INTEGER="integer",$.BOOLEAN="boolean",$.ARRAY="array",$.OBJECT="object"})(AZ||(AZ={}));var qZ;(function($){$.LANGUAGE_UNSPECIFIED="language_unspecified",$.PYTHON="python"})(qZ||(qZ={}));var OZ;(function($){$.OUTCOME_UNSPECIFIED="outcome_unspecified",$.OUTCOME_OK="outcome_ok",$.OUTCOME_FAILED="outcome_failed",$.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(OZ||(OZ={}));var IZ=["user","model","function","system"],MZ;(function($){$.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",$.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",$.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",$.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",$.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",$.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(MZ||(MZ={}));var TZ;(function($){$.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",$.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",$.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",$.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",$.BLOCK_NONE="BLOCK_NONE"})(TZ||(TZ={}));var jZ;(function($){$.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",$.NEGLIGIBLE="NEGLIGIBLE",$.LOW="LOW",$.MEDIUM="MEDIUM",$.HIGH="HIGH"})(jZ||(jZ={}));var SZ;(function($){$.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",$.SAFETY="SAFETY",$.OTHER="OTHER"})(SZ||(SZ={}));var y4;(function($){$.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",$.STOP="STOP",$.MAX_TOKENS="MAX_TOKENS",$.SAFETY="SAFETY",$.RECITATION="RECITATION",$.LANGUAGE="LANGUAGE",$.BLOCKLIST="BLOCKLIST",$.PROHIBITED_CONTENT="PROHIBITED_CONTENT",$.SPII="SPII",$.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",$.OTHER="OTHER"})(y4||(y4={}));var CZ;(function($){$.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",$.RETRIEVAL_QUERY="RETRIEVAL_QUERY",$.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",$.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",$.CLASSIFICATION="CLASSIFICATION",$.CLUSTERING="CLUSTERING"})(CZ||(CZ={}));var q0;(function($){$.MODE_UNSPECIFIED="MODE_UNSPECIFIED",$.AUTO="AUTO",$.ANY="ANY",$.NONE="NONE"})(q0||(q0={}));var RZ;(function($){$.MODE_UNSPECIFIED="MODE_UNSPECIFIED",$.MODE_DYNAMIC="MODE_DYNAMIC"})(RZ||(RZ={}));class C extends Error{constructor($){super(`[GoogleGenerativeAI Error]: ${$}`)}}class A0 extends C{constructor($,X){super($);this.response=X}}class O$ extends C{constructor($,X,Z,Y){super($);this.status=X,this.statusText=Z,this.errorDetails=Y}}class $0 extends C{}class I$ extends C{}var SY="https://generativelanguage.googleapis.com",CY="v1beta",RY="0.24.1",yY="genai-js",O0;(function($){$.GENERATE_CONTENT="generateContent",$.STREAM_GENERATE_CONTENT="streamGenerateContent",$.COUNT_TOKENS="countTokens",$.EMBED_CONTENT="embedContent",$.BATCH_EMBED_CONTENTS="batchEmbedContents"})(O0||(O0={}));class vZ{constructor($,X,Z,Y,W){this.model=$,this.task=X,this.apiKey=Z,this.stream=Y,this.requestOptions=W}toString(){var $,X;let Z=(($=this.requestOptions)===null||$===void 0?void 0:$.apiVersion)||CY,W=`${((X=this.requestOptions)===null||X===void 0?void 0:X.baseUrl)||SY}/${Z}/${this.model}:${this.task}`;if(this.stream)W+="?alt=sse";return W}}function PY($){let X=[];if($===null||$===void 0?void 0:$.apiClient)X.push($.apiClient);return X.push(`${yY}/${RY}`),X.join(" ")}async function fY($){var X;let Z=new Headers;Z.append("Content-Type","application/json"),Z.append("x-goog-api-client",PY($.requestOptions)),Z.append("x-goog-api-key",$.apiKey);let Y=(X=$.requestOptions)===null||X===void 0?void 0:X.customHeaders;if(Y){if(!(Y instanceof Headers))try{Y=new Headers(Y)}catch(W){throw new $0(`unable to convert customHeaders value ${JSON.stringify(Y)} to Headers: ${W.message}`)}for(let[W,J]of Y.entries()){if(W==="x-goog-api-key")throw new $0(`Cannot set reserved header name ${W}`);else if(W==="x-goog-api-client")throw new $0(`Header name ${W} can only be set using the apiClient field`);Z.append(W,J)}}return Z}async function _Y($,X,Z,Y,W,J){let z=new vZ($,X,Z,Y,J);return{url:z.toString(),fetchOptions:Object.assign(Object.assign({},hY(J)),{method:"POST",headers:await fY(z),body:W})}}async function _4($,X,Z,Y,W,J={},z=fetch){let{url:V,fetchOptions:N}=await _Y($,X,Z,Y,W,J);return kY(V,N,z)}async function kY($,X,Z=fetch){let Y;try{Y=await Z($,X)}catch(W){bY(W,$)}if(!Y.ok)await vY(Y,$);return Y}function bY($,X){let Z=$;if(Z.name==="AbortError")Z=new I$(`Request aborted when fetching ${X.toString()}: ${$.message}`),Z.stack=$.stack;else if(!($ instanceof O$||$ instanceof $0))Z=new C(`Error fetching from ${X.toString()}: ${$.message}`),Z.stack=$.stack;throw Z}async function vY($,X){let Z="",Y;try{let W=await $.json();if(Z=W.error.message,W.error.details)Z+=` ${JSON.stringify(W.error.details)}`,Y=W.error.details}catch(W){}throw new O$(`Error fetching from ${X.toString()}: [${$.status} ${$.statusText}] ${Z}`,$.status,$.statusText,Y)}function hY($){let X={};if(($===null||$===void 0?void 0:$.signal)!==void 0||($===null||$===void 0?void 0:$.timeout)>=0){let Z=new AbortController;if(($===null||$===void 0?void 0:$.timeout)>=0)setTimeout(()=>Z.abort(),$.timeout);if($===null||$===void 0?void 0:$.signal)$.signal.addEventListener("abort",()=>{Z.abort()});X.signal=Z.signal}return X}function M$($){return $.text=()=>{if($.candidates&&$.candidates.length>0){if($.candidates.length>1)console.warn(`This response had ${$.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`);if(M8($.candidates[0]))throw new A0(`${G0($)}`,$);return gY($)}else if($.promptFeedback)throw new A0(`Text not available. ${G0($)}`,$);return""},$.functionCall=()=>{if($.candidates&&$.candidates.length>0){if($.candidates.length>1)console.warn(`This response had ${$.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`);if(M8($.candidates[0]))throw new A0(`${G0($)}`,$);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),yZ($)[0]}else if($.promptFeedback)throw new A0(`Function call not available. ${G0($)}`,$);return},$.functionCalls=()=>{if($.candidates&&$.candidates.length>0){if($.candidates.length>1)console.warn(`This response had ${$.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`);if(M8($.candidates[0]))throw new A0(`${G0($)}`,$);return yZ($)}else if($.promptFeedback)throw new A0(`Function call not available. ${G0($)}`,$);return},$}function gY($){var X,Z,Y,W;let J=[];if((Z=(X=$.candidates)===null||X===void 0?void 0:X[0].content)===null||Z===void 0?void 0:Z.parts)for(let z of(W=(Y=$.candidates)===null||Y===void 0?void 0:Y[0].content)===null||W===void 0?void 0:W.parts){if(z.text)J.push(z.text);if(z.executableCode)J.push("\n```"+z.executableCode.language+`
50
- `+z.executableCode.code+"\n```\n");if(z.codeExecutionResult)J.push("\n```\n"+z.codeExecutionResult.output+"\n```\n")}if(J.length>0)return J.join("");else return""}function yZ($){var X,Z,Y,W;let J=[];if((Z=(X=$.candidates)===null||X===void 0?void 0:X[0].content)===null||Z===void 0?void 0:Z.parts){for(let z of(W=(Y=$.candidates)===null||Y===void 0?void 0:Y[0].content)===null||W===void 0?void 0:W.parts)if(z.functionCall)J.push(z.functionCall)}if(J.length>0)return J;else return}var dY=[y4.RECITATION,y4.SAFETY,y4.LANGUAGE];function M8($){return!!$.finishReason&&dY.includes($.finishReason)}function G0($){var X,Z,Y;let W="";if((!$.candidates||$.candidates.length===0)&&$.promptFeedback){if(W+="Response was blocked",(X=$.promptFeedback)===null||X===void 0?void 0:X.blockReason)W+=` due to ${$.promptFeedback.blockReason}`;if((Z=$.promptFeedback)===null||Z===void 0?void 0:Z.blockReasonMessage)W+=`: ${$.promptFeedback.blockReasonMessage}`}else if((Y=$.candidates)===null||Y===void 0?void 0:Y[0]){let J=$.candidates[0];if(M8(J)){if(W+=`Candidate was blocked due to ${J.finishReason}`,J.finishMessage)W+=`: ${J.finishMessage}`}}return W}function P4($){return this instanceof P4?(this.v=$,this):new P4($)}function uY($,X,Z){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var Y=Z.apply($,X||[]),W,J=[];return W={},z("next"),z("throw"),z("return"),W[Symbol.asyncIterator]=function(){return this},W;function z(G){if(Y[G])W[G]=function(x){return new Promise(function(E,R){J.push([G,x,E,R])>1||V(G,x)})}}function V(G,x){try{N(Y[G](x))}catch(E){K(J[0][3],E)}}function N(G){G.value instanceof P4?Promise.resolve(G.value.v).then(D,w):K(J[0][2],G)}function D(G){V("next",G)}function w(G){V("throw",G)}function K(G,x){if(G(x),J.shift(),J.length)V(J[0][0],J[0][1])}}var PZ=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function mY($){let X=$.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),Z=iY(X),[Y,W]=Z.tee();return{stream:pY(Y),response:cY(W)}}async function cY($){let X=[],Z=$.getReader();while(!0){let{done:Y,value:W}=await Z.read();if(Y)return M$(lY(X));X.push(W)}}function pY($){return uY(this,arguments,function*(){let Z=$.getReader();while(!0){let{value:Y,done:W}=yield P4(Z.read());if(W)break;yield yield P4(M$(Y))}})}function iY($){let X=$.getReader();return new ReadableStream({start(Y){let W="";return J();function J(){return X.read().then(({value:z,done:V})=>{if(V){if(W.trim()){Y.error(new C("Failed to parse stream"));return}Y.close();return}W+=z;let N=W.match(PZ),D;while(N){try{D=JSON.parse(N[1])}catch(w){Y.error(new C(`Error parsing JSON response: "${N[1]}"`));return}Y.enqueue(D),W=W.substring(N[0].length),N=W.match(PZ)}return J()}).catch((z)=>{let V=z;if(V.stack=z.stack,V.name==="AbortError")V=new I$("Request aborted when reading from the stream");else V=new C("Error reading from the stream");throw V})}}})}function lY($){let X=$[$.length-1],Z={promptFeedback:X===null||X===void 0?void 0:X.promptFeedback};for(let Y of $){if(Y.candidates){let W=0;for(let J of Y.candidates){if(!Z.candidates)Z.candidates=[];if(!Z.candidates[W])Z.candidates[W]={index:W};if(Z.candidates[W].citationMetadata=J.citationMetadata,Z.candidates[W].groundingMetadata=J.groundingMetadata,Z.candidates[W].finishReason=J.finishReason,Z.candidates[W].finishMessage=J.finishMessage,Z.candidates[W].safetyRatings=J.safetyRatings,J.content&&J.content.parts){if(!Z.candidates[W].content)Z.candidates[W].content={role:J.content.role||"user",parts:[]};let z={};for(let V of J.content.parts){if(V.text)z.text=V.text;if(V.functionCall)z.functionCall=V.functionCall;if(V.executableCode)z.executableCode=V.executableCode;if(V.codeExecutionResult)z.codeExecutionResult=V.codeExecutionResult;if(Object.keys(z).length===0)z.text="";Z.candidates[W].content.parts.push(z)}}}W++}if(Y.usageMetadata)Z.usageMetadata=Y.usageMetadata}return Z}async function hZ($,X,Z,Y){let W=await _4(X,O0.STREAM_GENERATE_CONTENT,$,!0,JSON.stringify(Z),Y);return mY(W)}async function gZ($,X,Z,Y){let J=await(await _4(X,O0.GENERATE_CONTENT,$,!1,JSON.stringify(Z),Y)).json();return{response:M$(J)}}function dZ($){if($==null)return;else if(typeof $==="string")return{role:"system",parts:[{text:$}]};else if($.text)return{role:"system",parts:[$]};else if($.parts)if(!$.role)return{role:"system",parts:$.parts};else return $}function f4($){let X=[];if(typeof $==="string")X=[{text:$}];else for(let Z of $)if(typeof Z==="string")X.push({text:Z});else X.push(Z);return nY(X)}function nY($){let X={role:"user",parts:[]},Z={role:"function",parts:[]},Y=!1,W=!1;for(let J of $)if("functionResponse"in J)Z.parts.push(J),W=!0;else X.parts.push(J),Y=!0;if(Y&&W)throw new C("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!Y&&!W)throw new C("No content is provided for sending chat message.");if(Y)return X;return Z}function rY($,X){var Z;let Y={model:X===null||X===void 0?void 0:X.model,generationConfig:X===null||X===void 0?void 0:X.generationConfig,safetySettings:X===null||X===void 0?void 0:X.safetySettings,tools:X===null||X===void 0?void 0:X.tools,toolConfig:X===null||X===void 0?void 0:X.toolConfig,systemInstruction:X===null||X===void 0?void 0:X.systemInstruction,cachedContent:(Z=X===null||X===void 0?void 0:X.cachedContent)===null||Z===void 0?void 0:Z.name,contents:[]},W=$.generateContentRequest!=null;if($.contents){if(W)throw new $0("CountTokensRequest must have one of contents or generateContentRequest, not both.");Y.contents=$.contents}else if(W)Y=Object.assign(Object.assign({},Y),$.generateContentRequest);else{let J=f4($);Y.contents=[J]}return{generateContentRequest:Y}}function fZ($){let X;if($.contents)X=$;else X={contents:[f4($)]};if($.systemInstruction)X.systemInstruction=dZ($.systemInstruction);return X}function aY($){if(typeof $==="string"||Array.isArray($))return{content:f4($)};return $}var _Z=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],oY={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function sY($){let X=!1;for(let Z of $){let{role:Y,parts:W}=Z;if(!X&&Y!=="user")throw new C(`First content should be with role 'user', got ${Y}`);if(!IZ.includes(Y))throw new C(`Each item should include role field. Got ${Y} but valid roles are: ${JSON.stringify(IZ)}`);if(!Array.isArray(W))throw new C("Content should have 'parts' property with an array of Parts");if(W.length===0)throw new C("Each Content should have at least one part");let J={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(let V of W)for(let N of _Z)if(N in V)J[N]+=1;let z=oY[Y];for(let V of _Z)if(!z.includes(V)&&J[V]>0)throw new C(`Content with role '${Y}' can't contain '${V}' part`);X=!0}}function kZ($){var X;if($.candidates===void 0||$.candidates.length===0)return!1;let Z=(X=$.candidates[0])===null||X===void 0?void 0:X.content;if(Z===void 0)return!1;if(Z.parts===void 0||Z.parts.length===0)return!1;for(let Y of Z.parts){if(Y===void 0||Object.keys(Y).length===0)return!1;if(Y.text!==void 0&&Y.text==="")return!1}return!0}var bZ="SILENT_ERROR";class uZ{constructor($,X,Z,Y={}){if(this.model=X,this.params=Z,this._requestOptions=Y,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=$,Z===null||Z===void 0?void 0:Z.history)sY(Z.history),this._history=Z.history}async getHistory(){return await this._sendPromise,this._history}async sendMessage($,X={}){var Z,Y,W,J,z,V;await this._sendPromise;let N=f4($),D={safetySettings:(Z=this.params)===null||Z===void 0?void 0:Z.safetySettings,generationConfig:(Y=this.params)===null||Y===void 0?void 0:Y.generationConfig,tools:(W=this.params)===null||W===void 0?void 0:W.tools,toolConfig:(J=this.params)===null||J===void 0?void 0:J.toolConfig,systemInstruction:(z=this.params)===null||z===void 0?void 0:z.systemInstruction,cachedContent:(V=this.params)===null||V===void 0?void 0:V.cachedContent,contents:[...this._history,N]},w=Object.assign(Object.assign({},this._requestOptions),X),K;return this._sendPromise=this._sendPromise.then(()=>gZ(this._apiKey,this.model,D,w)).then((G)=>{var x;if(kZ(G.response)){this._history.push(N);let E=Object.assign({parts:[],role:"model"},(x=G.response.candidates)===null||x===void 0?void 0:x[0].content);this._history.push(E)}else{let E=G0(G.response);if(E)console.warn(`sendMessage() was unsuccessful. ${E}. Inspect response object for details.`)}K=G}).catch((G)=>{throw this._sendPromise=Promise.resolve(),G}),await this._sendPromise,K}async sendMessageStream($,X={}){var Z,Y,W,J,z,V;await this._sendPromise;let N=f4($),D={safetySettings:(Z=this.params)===null||Z===void 0?void 0:Z.safetySettings,generationConfig:(Y=this.params)===null||Y===void 0?void 0:Y.generationConfig,tools:(W=this.params)===null||W===void 0?void 0:W.tools,toolConfig:(J=this.params)===null||J===void 0?void 0:J.toolConfig,systemInstruction:(z=this.params)===null||z===void 0?void 0:z.systemInstruction,cachedContent:(V=this.params)===null||V===void 0?void 0:V.cachedContent,contents:[...this._history,N]},w=Object.assign(Object.assign({},this._requestOptions),X),K=hZ(this._apiKey,this.model,D,w);return this._sendPromise=this._sendPromise.then(()=>K).catch((G)=>{throw Error(bZ)}).then((G)=>G.response).then((G)=>{if(kZ(G)){this._history.push(N);let x=Object.assign({},G.candidates[0].content);if(!x.role)x.role="model";this._history.push(x)}else{let x=G0(G);if(x)console.warn(`sendMessageStream() was unsuccessful. ${x}. Inspect response object for details.`)}}).catch((G)=>{if(G.message!==bZ)console.error(G)}),K}}async function tY($,X,Z,Y){return(await _4(X,O0.COUNT_TOKENS,$,!1,JSON.stringify(Z),Y)).json()}async function eY($,X,Z,Y){return(await _4(X,O0.EMBED_CONTENT,$,!1,JSON.stringify(Z),Y)).json()}async function $W($,X,Z,Y){let W=Z.requests.map((z)=>{return Object.assign(Object.assign({},z),{model:X})});return(await _4(X,O0.BATCH_EMBED_CONTENTS,$,!1,JSON.stringify({requests:W}),Y)).json()}class q${constructor($,X,Z={}){if(this.apiKey=$,this._requestOptions=Z,X.model.includes("/"))this.model=X.model;else this.model=`models/${X.model}`;this.generationConfig=X.generationConfig||{},this.safetySettings=X.safetySettings||[],this.tools=X.tools,this.toolConfig=X.toolConfig,this.systemInstruction=dZ(X.systemInstruction),this.cachedContent=X.cachedContent}async generateContent($,X={}){var Z;let Y=fZ($),W=Object.assign(Object.assign({},this._requestOptions),X);return gZ(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(Z=this.cachedContent)===null||Z===void 0?void 0:Z.name},Y),W)}async generateContentStream($,X={}){var Z;let Y=fZ($),W=Object.assign(Object.assign({},this._requestOptions),X);return hZ(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(Z=this.cachedContent)===null||Z===void 0?void 0:Z.name},Y),W)}startChat($){var X;return new uZ(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(X=this.cachedContent)===null||X===void 0?void 0:X.name},$),this._requestOptions)}async countTokens($,X={}){let Z=rY($,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),Y=Object.assign(Object.assign({},this._requestOptions),X);return tY(this.apiKey,this.model,Z,Y)}async embedContent($,X={}){let Z=aY($),Y=Object.assign(Object.assign({},this._requestOptions),X);return eY(this.apiKey,this.model,Z,Y)}async batchEmbedContents($,X={}){let Z=Object.assign(Object.assign({},this._requestOptions),X);return $W(this.apiKey,this.model,$,Z)}}class k4{constructor($){this.apiKey=$}getGenerativeModel($,X){if(!$.model)throw new C("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new q$(this.apiKey,$,X)}getGenerativeModelFromCachedContent($,X,Z){if(!$.name)throw new $0("Cached content must contain a `name` field.");if(!$.model)throw new $0("Cached content must contain a `model` field.");let Y=["model","systemInstruction"];for(let J of Y)if((X===null||X===void 0?void 0:X[J])&&$[J]&&(X===null||X===void 0?void 0:X[J])!==$[J]){if(J==="model"){let z=X.model.startsWith("models/")?X.model.replace("models/",""):X.model,V=$.model.startsWith("models/")?$.model.replace("models/",""):$.model;if(z===V)continue}throw new $0(`Different value for "${J}" specified in modelParams (${X[J]}) and cachedContent (${$[J]})`)}let W=Object.assign(Object.assign({},X),{model:$.model,tools:$.tools,toolConfig:$.toolConfig,systemInstruction:$.systemInstruction,cachedContent:$});return new q$(this.apiKey,W,Z)}}function T$($,X){let Z=XW($);return{tools:Z,toolConfig:YW(Z,X)}}function XW($){let X=[],Z=[];if($.forEach((Y)=>{if(E0(Y)){let[W]=BZ([Y]);if(W.functionDeclarations)X.push(...W.functionDeclarations)}else if(v0(Y)){let{functionDeclarations:W}=ZW(Y);if(W)X.push(...W);else throw Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else Z.push(Y)}),Z.find((Y)=>("functionDeclarations"in Y)))return Z.map((Y)=>{if(X?.length>0&&"functionDeclarations"in Y){let W={functionDeclarations:[...Y.functionDeclarations||[],...X]};return X=[],W}return Y});return[...Z,...X.length>0?[{functionDeclarations:X}]:[]]}function ZW($){return{functionDeclarations:[{name:$.function.name,description:$.function.description,parameters:e($.function.parameters)}]}}function YW($,X){if(!$.length||!X)return;let{toolChoice:Z,allowedFunctionNames:Y}=X,W={any:q0.ANY,auto:q0.AUTO,none:q0.NONE};if(Z&&["any","auto","none"].includes(Z))return{functionCallingConfig:{mode:W[Z]??"MODE_UNSPECIFIED",allowedFunctionNames:Y}};if(typeof Z==="string"||Y)return{functionCallingConfig:{mode:q0.ANY,allowedFunctionNames:[...Y??[],...Z&&typeof Z==="string"?[Z]:[]]}}}var mZ={"gemini-embedding-001":{maxInputTokens:2048,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-lite-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-06-05":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-04-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-05-06":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-05-20":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash":{maxInputTokens:128000,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-3-flash-preview":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash-preview-native-audio":{maxInputTokens:131072,imageInputs:!1,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-tts":{maxInputTokens:8000,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16000,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-flash-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-lite-preview-06-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-image":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-pro-preview-tts":{maxInputTokens:8000,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16000,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-image-preview":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-1.5-flash-8b":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-3-pro-preview":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:64000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.0-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-flash":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-flash-lite-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.0-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-pro":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1}};var j$=class extends B8{static lc_name(){return"ChatGoogleGenerativeAI"}lc_serializable=!0;get lc_secrets(){return{apiKey:"GOOGLE_API_KEY"}}lc_namespace=["langchain","chat_models","google_genai"];get lc_aliases(){return{apiKey:"google_api_key"}}model;temperature;maxOutputTokens;topP;topK;stopSequences=[];safetySettings;apiKey;streaming=!1;json;streamUsage=!0;convertSystemMessageToHumanContent;thinkingConfig;client;get _isMultimodalModel(){return this.model.includes("vision")||this.model.startsWith("gemini-1.5")||this.model.startsWith("gemini-2")||this.model.startsWith("gemma-3-")&&!this.model.startsWith("gemma-3-1b")||this.model.startsWith("gemini-3")}constructor($){super($);if(this.model=$.model.replace(/^models\//,""),this.maxOutputTokens=$.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw Error("`maxOutputTokens` must be a positive integer");if(this.temperature=$.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=$.topP??this.topP,this.topP&&this.topP<0)throw Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw Error("`topP` must be below 1.");if(this.topK=$.topK??this.topK,this.topK&&this.topK<0)throw Error("`topK` must be a positive integer");if(this.stopSequences=$.stopSequences??this.stopSequences,this.apiKey=$.apiKey??C4("GOOGLE_API_KEY"),!this.apiKey)throw Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=$.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0){if(new Set(this.safetySettings.map((X)=>X.category)).size!==this.safetySettings.length)throw Error("The categories in `safetySettings` array must be unique")}this.streaming=$.streaming??this.streaming,this.json=$.json,this.thinkingConfig=$.thinkingConfig??this.thinkingConfig,this.client=new k4(this.apiKey).getGenerativeModel({model:this.model,safetySettings:this.safetySettings,generationConfig:{stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...this.json?{responseMimeType:"application/json"}:{},...this.thinkingConfig?{thinkingConfig:this.thinkingConfig}:{}}},{apiVersion:$.apiVersion,baseUrl:$.baseUrl,customHeaders:$.customHeaders}),this.streamUsage=$.streamUsage??this.streamUsage}useCachedContent($,X,Z){if(!this.apiKey)return;this.client=new k4(this.apiKey).getGenerativeModelFromCachedContent($,X,Z)}get useSystemInstruction(){return typeof this.convertSystemMessageToHumanContent==="boolean"?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){if(this.model==="gemini-1.0-pro-001")return!1;else if(this.model.startsWith("gemini-pro-vision"))return!1;else if(this.model.startsWith("gemini-1.0-pro-vision"))return!1;else if(this.model==="gemini-pro")return!1;return!0}getLsParams($){return{ls_provider:"google_genai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:this.client.generationConfig.temperature,ls_max_tokens:this.client.generationConfig.maxOutputTokens,ls_stop:$.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools($,X){return this.withConfig({tools:T$($)?.tools,...X})}invocationParams($){let X=$?.tools?.length?T$($.tools,{toolChoice:$.tool_choice,allowedFunctionNames:$.allowedFunctionNames}):void 0;if($?.responseSchema)this.client.generationConfig.responseSchema=$.responseSchema,this.client.generationConfig.responseMimeType="application/json";else this.client.generationConfig.responseSchema=void 0,this.client.generationConfig.responseMimeType=this.json?"application/json":void 0;return{...X?.tools?{tools:X.tools}:{},...X?.toolConfig?{toolConfig:X.toolConfig}:{}}}async _generate($,X,Z){X.signal?.throwIfAborted();let Y=E$($,this._isMultimodalModel,this.useSystemInstruction,this.model),W=Y;if(Y[0].role==="system"){let[D]=Y;this.client.systemInstruction=D,W=Y.slice(1)}let J=this.invocationParams(X);if(this.streaming){let D={},w=this._streamResponseChunks($,X,Z),K=[];for await(let G of w){let x=G.generationInfo?.completion??0;if(K[x]===void 0)K[x]=G;else K[x]=K[x].concat(G)}return{generations:K.filter((G)=>G!==void 0),llmOutput:{estimatedTokenUsage:D}}}let z=await this.completionWithRetry({...J,contents:W}),V;if("usageMetadata"in z.response)V=B$(z.response.usageMetadata,this.model);let N=LZ(z.response,{usageMetadata:V});if(N.generations?.length>0)await Z?.handleLLMNewToken(N.generations[0]?.text??"");return N}async*_streamResponseChunks($,X,Z){let Y=E$($,this._isMultimodalModel,this.useSystemInstruction,this.model),W=Y;if(Y[0].role==="system"){let[G]=Y;this.client.systemInstruction=G,W=Y.slice(1)}let J={...this.invocationParams(X),contents:W},z=await this.caller.callWithOptions({signal:X?.signal},async()=>{let{stream:G}=await this.client.generateContentStream(J,{signal:X?.signal});return G}),V,N=0,D=0,w=0,K=0;for await(let G of z){if(X.signal?.aborted)return;if("usageMetadata"in G&&G.usageMetadata!==void 0&&this.streamUsage!==!1&&X.streamUsage!==!1){V=B$(G.usageMetadata,this.model);let E=G.usageMetadata.promptTokenCount??0;V.input_tokens=Math.max(0,E-N),N=E;let R=G.usageMetadata.candidatesTokenCount??0;V.output_tokens=Math.max(0,R-D),D=R;let M=G.usageMetadata.totalTokenCount??0;V.total_tokens=Math.max(0,M-w),w=M}let x=EZ(G,{usageMetadata:V,index:K});if(K+=1,!x)continue;yield x,await Z?.handleLLMNewToken(x.text??"")}}async completionWithRetry($,X){return this.caller.callWithOptions({signal:X?.signal},async()=>{try{return await this.client.generateContent($,{signal:X?.signal})}catch(Z){if(Z.message?.includes("400 Bad Request"))Z.status=400;throw Z}})}get profile(){return mZ[this.model]??{}}withStructuredOutput($,X){let Z=$,Y=X?.name,W=X?.method,J=X?.includeRaw;if(W==="jsonMode")throw Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let z,V;if(W==="functionCalling"){let K=Y??"extract",G;if(K0(Z)){let x=R4(Z);G=[{functionDeclarations:[{name:K,description:x.description??"A function available to call.",parameters:x}]}],V=new A$({returnSingle:!0,keyName:K,zodSchema:Z})}else{let x;if(typeof Z.name==="string"&&typeof Z.parameters==="object"&&Z.parameters!=null)x=Z,x.parameters=e(Z.parameters),K=Z.name;else x={name:K,description:Z.description??"",parameters:e(Z)};G=[{functionDeclarations:[x]}],V=new A$({returnSingle:!0,keyName:K})}z=this.bindTools(G).withConfig({allowedFunctionNames:[K]})}else{let K=R4(Z);z=this.withConfig({responseSchema:K}),V=new A8}if(!J)return z.pipe(V).withConfig({runName:"ChatGoogleGenerativeAIStructuredOutput"});let N=b0.assign({parsed:(K,G)=>V.invoke(K.raw,G)}),D=b0.assign({parsed:()=>null}),w=N.withFallbacks({fallbacks:[D]});return E8.from([{raw:z},w]).withConfig({runName:"StructuredOutputRunnable"})}};var pZ=async($,X={})=>{let{modelProvider:Z,enableThinking:Y=!0}=X,W="v1",J;if(Z==="anthropic")J=new H$({model:$,streamUsage:!0,streaming:!0,maxRetries:1,maxTokens:64000,thinking:Y?{budget_tokens:1024,type:"enabled"}:void 0,apiKey:X.apiKey,anthropicApiUrl:X.baseURL,metadata:X.metadata,outputVersion:"v1"});else if(Z==="gemini"||Z==="google")J=new j$({model:$,apiKey:X.apiKey,baseUrl:X.baseURL||process.env.GOOGLE_BASE_URL,maxRetries:1,streaming:!0,streamUsage:!0,thinkingConfig:{},metadata:X.metadata,outputVersion:"v1"});else J=new cZ({model:$,configuration:{baseURL:X.baseURL,apiKey:X.apiKey},streamUsage:!0,maxRetries:1,modelKwargs:Y?{thinking:{type:"enabled"}}:void 0,metadata:X.metadata,outputVersion:"v1"});return J};class T8 extends iZ{constructor($){super({configProvider:async()=>T8.loadConfigFromStore(),cache:$})}static async loadConfigFromStore(){try{let $=new lZ;await $.initialize();let X=await $.getConfig();if(!X.mcp_config||Object.keys(X.mcp_config).length===0)return null;return{servers:X.mcp_config}}catch($){return console.error("Failed to load MCP config from store:",$),null}}}var WW={ask_user_questions:{allowedDecisions:["respond","approve","reject","edit"]}};async function XQ($,X,Z,Y,W){let J=!!W?.parent_id,z=await X.getAgent($);if(!z)throw Error(`Agent not found: ${$}`);let V=await X.validateAgent($);if(!V.valid)throw Error(`Agent validation failed: ${JSON.stringify(V.errors)}`);let N=await pZ(Z.model_id,{modelProvider:Z.provider_type,streamUsage:!0,enableThinking:Z.enable_thinking,metadata:{parent_id:W?.parent_id}}),D=[],w=X.tools;for(let[M,P]of Object.entries(z.tools)){let d=w.getImplementation(M);if(!d){console.warn(`Tool ${M} not found in registry`);continue}if(!d.name||!P)continue;let b4=h0(async(v4,S$)=>{let c=await d.execute(v4,S$);if(c&&typeof c==="object"&&"content"in c)return c.content;return c},{name:d.name,description:d.description,schema:d.paramsSchema});D.push(b4)}let K=[];for(let[M,P]of Object.entries(z.middleware)){if(M==="subagents"&&J)continue;let d=X.middlewares.getImplementation(M);if(!P)continue;K.push(await d.execute(P.customParams||{}))}let G=new T8;K.push(G);let x={...WW};if(process.env.YOLO_MODE!=="true")Object.assign(x,{terminal:{allowedDecisions:["approve","reject","edit"]}});if(K.push(aZ({interruptOn:x})),process.env.MODEL_PROVIDER==="anthropic")K.push(rZ());let E=await X.getPromptWithContent(z.systemPromptId);if(!E)throw Error(`Prompt not found: ${z.systemPromptId}`);let R=E.content+`
51
-
52
- ${await oZ(Z)}`;return nZ({name:J?`subagent_${W.parent_id}`:z.name,model:N,systemPrompt:R,tools:D,stateSchema:_$,middleware:K})}async function ZQ($){return(await $.listAgents()).map((Z)=>Z.id)}
53
- export{KW as jf,_$ as kf,I8 as lf,k4 as mf,pZ as nf,XQ as of,ZQ as pf};
@@ -1,2 +0,0 @@
1
- import{qq as L}from"./chunk-dcs1r9as.js";var N=L((O,D)=>{var I=[0,4129,8258,12387,16516,20645,24774,28903,33032,37161,41290,45419,49548,53677,57806,61935,4657,528,12915,8786,21173,17044,29431,25302,37689,33560,45947,41818,54205,50076,62463,58334,9314,13379,1056,5121,25830,29895,17572,21637,42346,46411,34088,38153,58862,62927,50604,54669,13907,9842,5649,1584,30423,26358,22165,18100,46939,42874,38681,34616,63455,59390,55197,51132,18628,22757,26758,30887,2112,6241,10242,14371,51660,55789,59790,63919,35144,39273,43274,47403,23285,19156,31415,27286,6769,2640,14899,10770,56317,52188,64447,60318,39801,35672,47931,43802,27814,31879,19684,23749,11298,15363,3168,7233,60846,64911,52716,56781,44330,48395,36200,40265,32407,28342,24277,20212,15891,11826,7761,3696,65439,61374,57309,53244,48923,44858,40793,36728,37256,33193,45514,41451,53516,49453,61774,57711,4224,161,12482,8419,20484,16421,28742,24679,33721,37784,41979,46042,49981,54044,58239,62302,689,4752,8947,13010,16949,21012,25207,29270,46570,42443,38312,34185,62830,58703,54572,50445,13538,9411,5280,1153,29798,25671,21540,17413,42971,47098,34713,38840,59231,63358,50973,55100,9939,14066,1681,5808,26199,30326,17941,22068,55628,51565,63758,59695,39368,35305,47498,43435,22596,18533,30726,26663,6336,2273,14466,10403,52093,56156,60223,64286,35833,39896,43963,48026,19061,23124,27191,31254,2801,6864,10931,14994,64814,60687,56684,52557,48554,44427,40424,36297,31782,27655,23652,19525,15522,11395,7392,3265,61215,65342,53085,57212,44955,49082,36825,40952,28183,32310,20053,24180,11923,16050,3793,7920],M=function(x){var j,z=0,q=0,w=[],B=x.length;for(;z<B;z++)if(j=x.charCodeAt(z),j<128)w[q++]=j;else if(j<2048)w[q++]=j>>6|192,w[q++]=j&63|128;else if((j&64512)===55296&&z+1<x.length&&(x.charCodeAt(z+1)&64512)===56320)j=65536+((j&1023)<<10)+(x.charCodeAt(++z)&1023),w[q++]=j>>18|240,w[q++]=j>>12&63|128,w[q++]=j>>6&63|128,w[q++]=j&63|128;else w[q++]=j>>12|224,w[q++]=j>>6&63|128,w[q++]=j&63|128;return w},J=D.exports=function(x){var j,z=0,q=-1,w=0,B=0,G=typeof x==="string"?M(x):x,K=G.length;while(z<K){if(j=G[z++],q===-1){if(j===123)q=z}else if(j!==125)B=I[(j^B>>8)&255]^B<<8;else if(z-1!==q)return B&16383;w=I[(j^w>>8)&255]^w<<8}return w&16383};D.exports.generateMulti=function(x){var j=1,z=x.length,q=J(x[0]);while(j<z)if(J(x[j++])!==q)return-1;return q}});
2
- export{N as g};
@@ -1,3 +0,0 @@
1
- import{h as v,i as Z}from"./chunk-r3pe49q4.js";import{Ae as Q,Be as G,Je as M,Ke as F,Oe as O,ye as k}from"./chunk-a90fm6gz.js";import"./chunk-wabmqprd.js";import"./chunk-x552nspp.js";import"./chunk-43xrz4wp.js";import"./chunk-dcwnpdtk.js";import"./chunk-cbjnwrt7.js";import"./chunk-w2hbsa9j.js";import"./chunk-rztre6k0.js";import"./chunk-wpy5r9ma.js";import"./chunk-frhhpxxy.js";import"./chunk-h1enhch1.js";import"./chunk-hyf24r36.js";import"./chunk-1p9xzvpt.js";import"./chunk-hra0748z.js";import{pq as Y}from"./chunk-dcs1r9as.js";var N=Y(k(),1);var y=Y(k(),1);var J=Y(F(),1),h=({pid:z,onClose:A})=>{let[H,R]=y.useState({stdout:"",stderr:""});M((W,X)=>{if(X.escape)A()}),y.useEffect(()=>{let W=()=>{let _=Z.getProcessOutput(z);if(_)R(_)};W();let X=setInterval(W,500);return()=>clearInterval(X)},[z]);let $=I(H.stdout,20),U=I(H.stderr,20);return J.jsxDEV(Q,{flexDirection:"column",padding:1,children:[J.jsxDEV(Q,{justifyContent:"space-between",marginBottom:1,children:[J.jsxDEV(G,{bold:!0,color:"cyan",children:["进程 [",z,"] 输出"]},void 0,!0,void 0,this),J.jsxDEV(G,{dimColor:!0,children:"按 ESC 返回"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J.jsxDEV(Q,{flexDirection:"column",marginBottom:1,children:[J.jsxDEV(G,{color:"green",bold:!0,children:"STDOUT:"},void 0,!1,void 0,this),J.jsxDEV(Q,{borderStyle:"single",borderColor:"green",paddingX:1,children:J.jsxDEV(G,{children:$||"(空)"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J.jsxDEV(Q,{flexDirection:"column",children:[J.jsxDEV(G,{color:"red",bold:!0,children:"STDERR:"},void 0,!1,void 0,this),J.jsxDEV(Q,{borderStyle:"single",borderColor:"red",paddingX:1,children:J.jsxDEV(G,{children:U||"(空)"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};function I(z,A){let H=z.split(`
2
- `);if(H.length<=A)return z;return`...${H.slice(-A).join(`
3
- `)}`}var g=h;var w=Y(F(),1),T=({onClose:z})=>{let[A,H]=N.useState([]),[R,$]=N.useState(null);N.useEffect(()=>{let q=async()=>{let b=await Z.getProcessList();H(b)};q();let K=setInterval(q,1000);return()=>clearInterval(K)},[]);let U=N.useCallback(async()=>{let q=await Z.getProcessList();H(q)},[]),W=N.useCallback((q,K,b)=>{let C=q.status==="running"?"\uD83D\uDFE2":"\uD83D\uDD34",B=f(q.duration);return w.jsxDEV(Q,{flexDirection:"column",children:[w.jsxDEV(Q,{children:[w.jsxDEV(G,{color:"cyan",children:[C," [",q.pid,"]"]},void 0,!0,void 0,this),w.jsxDEV(G,{children:[" ",P(q.command,40)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),w.jsxDEV(Q,{paddingLeft:3,children:[w.jsxDEV(G,{dimColor:!0,children:["⏱ ",B]},void 0,!0,void 0,this),w.jsxDEV(G,{dimColor:!0,children:[" | CPU: ",q.cpu.toFixed(1),"%"]},void 0,!0,void 0,this),w.jsxDEV(G,{dimColor:!0,children:[" | MEM: ",(q.memory/1024/1024).toFixed(1),"MB"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},[]),X=N.useCallback((q)=>{Z.killProcess(q.pid)},[]),_=N.useCallback((q)=>{$(q.pid)},[]),L=N.useCallback((q)=>{return w.jsxDEV(G,{dimColor:!0,children:["运行中: ",q.filter((K)=>K.status==="running").length," | 总计: ",q.length," | Enter 查看输出 | Backspace/Delete 关闭进程"]},void 0,!0,void 0,this)},[]),S=N.useMemo(()=>({id:"processes",title:"进程管理器",icon:"⚙️",dataSource:()=>Promise.resolve(A),searchable:!0,searchFields:["command"],renderItem:W,onSelect:_,onDelete:X,itemHeight:2,statusInfo:L,keyMap:{r:()=>{U()}}}),[A,W,_,X,L,U]);return w.jsxDEV(w.Fragment,{children:R!==null?w.jsxDEV(v,{name:"ProcessOutputPanel",fallback:null,children:w.jsxDEV(g,{pid:R,onClose:()=>$(null)},void 0,!1,void 0,this)},void 0,!1,void 0,this):w.jsxDEV(O,{config:S,onClose:z},void 0,!1,void 0,this)},void 0,!1,void 0,this)};function f(z){let A=Math.floor(z/1000),H=Math.floor(A/60),R=Math.floor(H/60);if(R>0)return`${R}h ${H%60}m`;if(H>0)return`${H}m ${A%60}s`;return`${A}s`}function P(z,A){return z.length>A?z.slice(0,A-3)+"...":z}var n=T;export{n as default};
@@ -1,3 +0,0 @@
1
- import{writeFileSync as B,readFileSync as C,existsSync as u,mkdirSync as G}from"node:fs";import{join as H,dirname as J}from"node:path";import{randomUUID as K}from"node:crypto";class z{errors=[];filePath;maxEntries;isLoaded=!1;constructor(b){this.filePath=b?.filePath||H(process.cwd(),".zen-code","errors.json"),this.maxEntries=b?.maxEntries||500,this.ensureDirectory()}ensureDirectory(){let b=J(this.filePath);if(!u(b))G(b,{recursive:!0})}loadFromFile(){if(this.isLoaded)return;try{if(u(this.filePath)){let b=C(this.filePath,"utf-8"),q=JSON.parse(b);if(Array.isArray(q))this.errors=q}}catch(b){this.errors=[]}this.isLoaded=!0}saveToFile(){try{let b=JSON.stringify(this.errors,null,2);B(this.filePath,b,"utf-8")}catch(b){process.stderr.write(`[ErrorStore] Failed to save errors: ${b}
2
- `)}}addError(b){this.loadFromFile();let q={...b,id:K(),timestamp:new Date().toISOString()};if(this.errors.unshift(q),this.errors.length>this.maxEntries)this.errors=this.errors.slice(0,this.maxEntries);return this.saveToFile(),q}getErrors(){return this.loadFromFile(),[...this.errors]}getRecentErrors(b=100){return this.loadFromFile(),this.errors.slice(0,b)}clearAll(){this.errors=[],this.saveToFile()}deleteError(b){this.loadFromFile();let q=this.errors.findIndex((A)=>A.id===b);if(q!==-1)return this.errors.splice(q,1),this.saveToFile(),!0;return!1}getStats(){return this.loadFromFile(),{total:this.errors.length,errors:this.errors.filter((b)=>b.level==="error").length,warnings:this.errors.filter((b)=>b.level==="warning").length}}}var O=new z;
3
- export{O as hq};