zen-code 4.10.1 → 4.10.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app.js +157 -2615
- package/dist/chunk-0ddrb30y.js +1 -0
- package/dist/chunk-215an3fz.js +1 -0
- package/dist/chunk-40ht9pe1.js +91 -0
- package/dist/chunk-4wnmk2tj.js +7 -0
- package/dist/chunk-4z0w0ng1.js +2 -0
- package/dist/chunk-57bj89e2.js +1 -0
- package/dist/chunk-5a5mepqj.js +1 -0
- package/dist/chunk-5c3bpcpm.js +1 -0
- package/dist/chunk-7kw7ss8d.js +1 -0
- package/dist/chunk-86m0rmtc.js +1 -0
- package/dist/chunk-8f19qk9r.js +26 -0
- package/dist/chunk-8tbtavry.js +6 -0
- package/dist/chunk-9rayxazs.js +8 -0
- package/dist/chunk-a9gpb2tx.js +2 -0
- package/dist/chunk-a9tw6d68.js +1 -0
- package/dist/chunk-anbtppz1.js +294 -0
- package/dist/chunk-bca8tkkr.js +1 -0
- package/dist/chunk-bdqds8vh.js +1 -0
- package/dist/chunk-bzgznka5.js +3 -0
- package/dist/chunk-c7kd2qrp.js +278 -0
- package/dist/chunk-dvbb3dd1.js +233 -0
- package/dist/chunk-e8kxa5vj.js +140 -0
- package/dist/chunk-ehmmd8qc.js +1 -0
- package/dist/chunk-ejfa95sm.js +1 -0
- package/dist/chunk-f0m4532p.js +54 -0
- package/dist/chunk-f7cps5x1.js +1 -0
- package/dist/chunk-fbemqjck.js +2 -0
- package/dist/chunk-feeqtzv5.js +1 -0
- package/dist/chunk-fzh0v6r0.js +6 -0
- package/dist/chunk-g2zskge5.js +81 -0
- package/dist/chunk-g974hxbz.js +3 -0
- package/dist/chunk-g9911ymn.js +1 -0
- package/dist/chunk-gfhmzpy7.js +176 -0
- package/dist/chunk-gt8c6dne.js +3 -0
- package/dist/chunk-h8fdexm4.js +2 -0
- package/dist/chunk-hnnwbfqk.js +3 -0
- package/dist/chunk-hp2jzn9x.js +166 -0
- package/dist/chunk-hve2a279.js +2 -0
- package/dist/chunk-js4qp900.js +2 -0
- package/dist/chunk-k4q8j7pg.js +2 -0
- package/dist/chunk-m21hvv91.js +2 -0
- package/dist/chunk-mmx0k2yq.js +1 -0
- package/dist/chunk-mnnyjmgw.js +224 -0
- package/dist/chunk-mw7x6xqp.js +1 -0
- package/dist/chunk-n7s6my89.js +112 -0
- package/dist/chunk-n9rpnke9.js +4 -0
- package/dist/chunk-nk62q95g.js +93 -0
- package/dist/chunk-nmzx5nmt.js +1 -0
- package/dist/chunk-nqh1pptf.js +88 -0
- package/dist/chunk-nsw5168d.js +2 -0
- package/dist/chunk-pe8mzxwn.js +16 -0
- package/dist/chunk-pg1ppq4y.js +1 -0
- package/dist/chunk-pzb224c5.js +2 -0
- package/dist/chunk-q1cxrg0x.js +2 -0
- package/dist/chunk-qxebn3jw.js +18 -0
- package/dist/chunk-s1tbdcs8.js +4 -0
- package/dist/chunk-s5cqejr6.js +79 -0
- package/dist/chunk-spa69h7p.js +2 -0
- package/dist/chunk-spx7nn8t.js +6 -0
- package/dist/chunk-swc7se71.js +2 -0
- package/dist/chunk-swyc15ym.js +1 -0
- package/dist/chunk-t2s3s6af.js +1 -0
- package/dist/chunk-t6440ajd.js +5 -0
- package/dist/chunk-tjg2e8v3.js +41 -0
- package/dist/chunk-tjvhqr94.js +1 -0
- package/dist/chunk-vbb3m0vz.js +1 -0
- package/dist/chunk-vdmq9d9x.js +4 -0
- package/dist/chunk-vfxjbdz4.js +2 -0
- package/dist/chunk-vrnj0659.js +213 -0
- package/dist/chunk-wmyc17aa.js +23 -0
- package/dist/chunk-wt3p1w1g.js +1 -0
- package/dist/chunk-y5ry5c7v.js +1 -0
- package/dist/chunk-y8qhrx11.js +2 -0
- package/dist/chunk-yy8p9zph.js +2 -0
- package/dist/chunk-z61m3anh.js +1 -0
- package/dist/chunk-zg54h6gy.js +1 -0
- package/dist/chunk-zr90qp47.js +1 -0
- package/dist/chunk-zsa62xr0.js +2 -0
- package/dist/cli.js +1 -3116
- package/dist/nonInteractive.js +180 -1950
- package/dist/zen-keyboard.js +3 -358
- package/package.json +1 -1
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import{vf as wZ}from"./chunk-yy8p9zph.js";import{Of as FZ,dg as LZ}from"./chunk-mnnyjmgw.js";import{ig as qZ}from"./chunk-f0m4532p.js";import{Ag as C6,Bg as o1,qg as WY,yg as s1}from"./chunk-pe8mzxwn.js";import{Hg as y8,Ig as iY,Jg as f8,Kg as Q7,Lg as L9,Mg as cY,Ng as A9,Og as pY,Pg as E9,Qg as LW,Rg as EW,Sg as xW,Tg as k8,Ug as V9}from"./chunk-hp2jzn9x.js";import{$h as x9,Ai as T9,Ak as hX,Ch as x0,Cj as lY,Ek as KX,Gj as k1,Ih as dY,Jh as OX,Ji as g5,Kh as O0,Ki as BX,Wh as gW,Zj as WX,_h as jX,bi as uW,fi as r,fk as uY,gi as b8,hk as v1,ii as u,ji as l0,ki as O9,oi as D9,qj as tX,rh as vY,ri as t8,si as M9,uj as FW,vj as q9,vk as aX,wj as F9,xi as mY,yj as HX}from"./chunk-nk62q95g.js";import{Gk as y}from"./chunk-nmzx5nmt.js";import{Nk as I1,Xk as R1,bl as Q2,el as C9,fl as I9,gl as J2,pl as G2,tl as N}from"./chunk-tjg2e8v3.js";import{Cl as wG,xl as w6}from"./chunk-hve2a279.js";var OZ=N.object({thought:N.string().describe("Your current thinking step"),nextThoughtNeeded:N.boolean().describe("Whether another thought step is needed"),thoughtNumber:N.number().min(1).describe("Current thought number"),totalThoughts:N.number().min(1).describe("Estimated total thoughts needed"),isRevision:N.boolean().optional().describe("Whether this revises previous thinking"),revisesThought:N.number().min(1).optional().describe("Which thought is being reconsidered"),branchFromThought:N.number().min(1).optional().describe("Branching point thought number"),branchId:N.string().optional().describe("Branch identifier"),needsMoreThoughts:N.boolean().optional().describe("If more thoughts are needed")}),S6=[],ZY={},JK=KX(async(X)=>{try{if(X.thoughtNumber>X.totalThoughts)X.totalThoughts=X.thoughtNumber;if(S6.push(X),X.branchFromThought&&X.branchId){if(!ZY[X.branchId])ZY[X.branchId]=[];ZY[X.branchId].push(X)}return JSON.stringify({thoughtNumber:X.thoughtNumber,totalThoughts:X.totalThoughts,nextThoughtNeeded:X.nextThoughtNeeded,branches:Object.keys(ZY),thoughtHistoryLength:S6.length},null,2)}catch(Y){return JSON.stringify({error:Y instanceof Error?Y.message:String(Y),status:"failed"},null,2)}},{name:"sequential-thinking",description:`A detailed tool for dynamic and reflective problem-solving through thoughts.
|
|
2
|
+
This tool helps analyze problems through a flexible thinking process that can adapt and evolve.
|
|
3
|
+
Each thought can build on, question, or revise previous insights as understanding deepens.
|
|
4
|
+
|
|
5
|
+
When to use this tool:
|
|
6
|
+
- Breaking down complex problems into steps
|
|
7
|
+
- Planning and design with room for revision
|
|
8
|
+
- Analysis that might need course correction
|
|
9
|
+
- Problems where the full scope might not be clear initially
|
|
10
|
+
- Problems that require a multi-step solution
|
|
11
|
+
- Tasks that need to maintain context over multiple steps
|
|
12
|
+
- Situations where irrelevant information needs to be filtered out
|
|
13
|
+
|
|
14
|
+
Key features:
|
|
15
|
+
- You can adjust total_thoughts up or down as you progress
|
|
16
|
+
- You can question or revise previous thoughts
|
|
17
|
+
- You can add more thoughts even after reaching what seemed like the end
|
|
18
|
+
- You can express uncertainty and explore alternative approaches
|
|
19
|
+
- Not every thought needs to build linearly - you can branch or backtrack
|
|
20
|
+
- Generates a solution hypothesis
|
|
21
|
+
- Verifies the hypothesis based on the Chain of Thought steps
|
|
22
|
+
- Repeats the process until satisfied
|
|
23
|
+
- Provides a correct answer`,schema:OZ});var DZ=N.object({url:N.string().url().describe("the url to crawl"),raw:N.boolean().optional().default(!1).describe("return raw html")}),MZ=N.object({query:N.string().describe("the query to search"),engines:N.array(N.enum(["basic","npm","juejin","anthropic","github"])).default(["basic"]).describe("the engines to use"),returnType:N.enum(["json","markdown"]).default("json").describe("the content type to return"),withMetadata:N.boolean().default(!0).describe("whether to include metadata in the search results")}),zK=KX(async({url:X})=>{if(!X)return{status:"error",error:"URL is required"};let Y=await fetch(`${process.env.SEARCH_SERVER_URL||"http://localhost:8123"}/website-to-md/extract`,{method:"POST",body:JSON.stringify({url:X})});if(!Y.ok)throw Error(`HTTP error! status: ${Y.status}`);return await Y.text()},{name:"read_web_page",description:"A powerful web content extraction tool that retrieves and processes raw content from specified URLs, ideal for data collection, content analysis, and research tasks.",schema:N.object(DZ.shape)}),HK=KX(async({query:X,engines:Y})=>{let $=await fetch(`${process.env.SEARCH_SERVER_URL||"http://localhost:8123"}/website-to-md/search`,{method:"POST",body:JSON.stringify({query:X,engines:Y,returnType:"json",withMetadata:!0})});if(!$.ok)throw Error(`HTTP error! status: ${$.status}`);return await $.text()},{name:"web_search",description:"A powerful web search tool that provides comprehensive, real-time results using search engine. Returns relevant web content with customizable parameters for result count, content type, and domain filtering. Ideal for gathering current information, news, and detailed web content analysis.",schema:N.object(MZ.shape)});var OK=(X)=>{return X?.configurable?.thread_id};var I6=WY.Root({...C6.spec,activeAgent:WY});function s8(X,Y){return X.lc_error_code=Y,X.message=`${X.message}
|
|
24
|
+
|
|
25
|
+
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${Y}/
|
|
26
|
+
`,X}function A(X,Y,$,W,Z){if(W==="m")throw TypeError("Private method is not writable");if(W==="a"&&!Z)throw TypeError("Private accessor was defined without a setter");if(typeof Y==="function"?X!==Y||!Z:!Y.has(X))throw TypeError("Cannot write private member to an object whose class did not declare it");return W==="a"?Z.call(X,$):Z?Z.value=$:Y.set(X,$),$}function w(X,Y,$,W){if($==="a"&&!W)throw TypeError("Private accessor was defined without a getter");if(typeof Y==="function"?X!==Y||!W:!Y.has(X))throw TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?W:$==="a"?W.call(X):W?W.value:Y.get(X)}var A$=function(){let{crypto:X}=globalThis;if(X?.randomUUID)return A$=X.randomUUID.bind(X),X.randomUUID();let Y=new Uint8Array(1),$=X?()=>X.getRandomValues(Y)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(W)=>(+W^$()&15>>+W/4).toString(16))};function o8(X){return typeof X==="object"&&X!==null&&(("name"in X)&&X.name==="AbortError"||("message"in X)&&String(X.message).includes("FetchRequestCanceledException"))}var e8=(X)=>{if(X instanceof Error)return X;if(typeof X==="object"&&X!==null){try{if(Object.prototype.toString.call(X)==="[object Error]"){let Y=Error(X.message,X.cause?{cause:X.cause}:{});if(X.stack)Y.stack=X.stack;if(X.cause&&!Y.cause)Y.cause=X.cause;if(X.name)Y.name=X.name;return Y}}catch{}try{return Error(JSON.stringify(X))}catch{}}return Error(X)};class D extends Error{}class n extends D{constructor(X,Y,$,W){super(`${n.makeMessage(X,Y,$)}`);this.status=X,this.headers=W,this.requestID=W?.get("x-request-id"),this.error=Y;let Z=Y;this.code=Z?.code,this.param=Z?.param,this.type=Z?.type}static makeMessage(X,Y,$){let W=Y?.message?typeof Y.message==="string"?Y.message:JSON.stringify(Y.message):Y?JSON.stringify(Y):$;if(X&&W)return`${X} ${W}`;if(X)return`${X} status code (no body)`;if(W)return W;return"(no status code or body)"}static generate(X,Y,$,W){if(!X||!W)return new C0({message:$,cause:e8(Y)});let Z=Y?.error;if(X===400)return new X4(X,Z,$,W);if(X===401)return new Y4(X,Z,$,W);if(X===403)return new $4(X,Z,$,W);if(X===404)return new W4(X,Z,$,W);if(X===409)return new Z4(X,Z,$,W);if(X===422)return new Q4(X,Z,$,W);if(X===429)return new J4(X,Z,$,W);if(X>=500)return new G4(X,Z,$,W);return new n(X,Z,$,W)}}class l extends n{constructor({message:X}={}){super(void 0,void 0,X||"Request was aborted.",void 0)}}class C0 extends n{constructor({message:X,cause:Y}){super(void 0,void 0,X||"Connection error.",void 0);if(Y)this.cause=Y}}class uX extends C0{constructor({message:X}={}){super({message:X??"Request timed out."})}}class X4 extends n{}class Y4 extends n{}class $4 extends n{}class W4 extends n{}class Z4 extends n{}class Q4 extends n{}class J4 extends n{}class G4 extends n{}class K4 extends D{constructor(){super("Could not parse response content as the length limit was reached")}}class V4 extends D{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class dX extends Error{constructor(X){super(X)}}var IZ=/^[a-z][a-z0-9+.-]*:/i,j6=(X)=>{return IZ.test(X)},JX=(X)=>(JX=Array.isArray,JX(X)),P$=JX;function S$(X){if(typeof X!=="object")return{};return X??{}}function _6(X){if(!X)return!0;for(let Y in X)return!1;return!0}function y6(X,Y){return Object.prototype.hasOwnProperty.call(X,Y)}function z4(X){return X!=null&&typeof X==="object"&&!Array.isArray(X)}var k6=(X,Y)=>{if(typeof Y!=="number"||!Number.isInteger(Y))throw new D(`${X} must be an integer`);if(Y<0)throw new D(`${X} must be a positive integer`);return Y};var v6=(X)=>{try{return JSON.parse(X)}catch(Y){return}};var _X=(X)=>new Promise((Y)=>setTimeout(Y,X));var Q0="6.22.0";var g6=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function jZ(){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 _Z=()=>{let X=jZ();if(X==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q0,"X-Stainless-OS":f6(Deno.build.os),"X-Stainless-Arch":b6(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":Q0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(X==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q0,"X-Stainless-OS":f6(globalThis.process.platform??"unknown"),"X-Stainless-Arch":b6(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Y=yZ();if(Y)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Y.browser}`,"X-Stainless-Runtime-Version":Y.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function yZ(){if(typeof navigator>"u"||!navigator)return null;let X=[{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:Y,pattern:$}of X){let W=$.exec(navigator.userAgent);if(W){let Z=W[1]||0,Q=W[2]||0,J=W[3]||0;return{browser:Y,version:`${Z}.${Q}.${J}`}}}return null}var b6=(X)=>{if(X==="x32")return"x32";if(X==="x86_64"||X==="x64")return"x64";if(X==="arm")return"arm";if(X==="aarch64"||X==="arm64")return"arm64";if(X)return`other:${X}`;return"unknown"},f6=(X)=>{if(X=X.toLowerCase(),X.includes("ios"))return"iOS";if(X==="android")return"Android";if(X==="darwin")return"MacOS";if(X==="win32")return"Windows";if(X==="freebsd")return"FreeBSD";if(X==="openbsd")return"OpenBSD";if(X==="linux")return"Linux";if(X)return`Other:${X}`;return"Unknown"},h6,u6=()=>{return h6??(h6=_Z())};function d6(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function R$(...X){let Y=globalThis.ReadableStream;if(typeof Y>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Y(...X)}function QY(X){let Y=Symbol.asyncIterator in X?X[Symbol.asyncIterator]():X[Symbol.iterator]();return R$({start(){},async pull($){let{done:W,value:Z}=await Y.next();if(W)$.close();else $.enqueue(Z)},async cancel(){await Y.return?.()}})}function C$(X){if(X[Symbol.asyncIterator])return X;let Y=X.getReader();return{async next(){try{let $=await Y.read();if($?.done)Y.releaseLock();return $}catch($){throw Y.releaseLock(),$}},async return(){let $=Y.cancel();return Y.releaseLock(),await $,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function m6(X){if(X===null||typeof X!=="object")return;if(X[Symbol.asyncIterator]){await X[Symbol.asyncIterator]().return?.();return}let Y=X.getReader(),$=Y.cancel();Y.releaseLock(),await $}var c6=({headers:X,body:Y})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Y)}};var JY="RFC3986",I$=(X)=>String(X),GY={RFC1738:(X)=>String(X).replace(/%20/g,"+"),RFC3986:I$},j$="RFC1738";var KY=(X,Y)=>(KY=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),KY(X,Y)),yX=(()=>{let X=[];for(let Y=0;Y<256;++Y)X.push("%"+((Y<16?"0":"")+Y.toString(16)).toUpperCase());return X})();var _$=1024,p6=(X,Y,$,W,Z)=>{if(X.length===0)return X;let Q=X;if(typeof X==="symbol")Q=Symbol.prototype.toString.call(X);else if(typeof X!=="string")Q=String(X);if($==="iso-8859-1")return escape(Q).replace(/%u[0-9a-f]{4}/gi,function(G){return"%26%23"+parseInt(G.slice(2),16)+"%3B"});let J="";for(let G=0;G<Q.length;G+=_$){let z=Q.length>=_$?Q.slice(G,G+_$):Q,B=[];for(let H=0;H<z.length;++H){let V=z.charCodeAt(H);if(V===45||V===46||V===95||V===126||V>=48&&V<=57||V>=65&&V<=90||V>=97&&V<=122||Z===j$&&(V===40||V===41)){B[B.length]=z.charAt(H);continue}if(V<128){B[B.length]=yX[V];continue}if(V<2048){B[B.length]=yX[192|V>>6]+yX[128|V&63];continue}if(V<55296||V>=57344){B[B.length]=yX[224|V>>12]+yX[128|V>>6&63]+yX[128|V&63];continue}H+=1,V=65536+((V&1023)<<10|z.charCodeAt(H)&1023),B[B.length]=yX[240|V>>18]+yX[128|V>>12&63]+yX[128|V>>6&63]+yX[128|V&63]}J+=B.join("")}return J};function l6(X){if(!X||typeof X!=="object")return!1;return!!(X.constructor&&X.constructor.isBuffer&&X.constructor.isBuffer(X))}function y$(X,Y){if(JX(X)){let $=[];for(let W=0;W<X.length;W+=1)$.push(Y(X[W]));return $}return Y(X)}var n6={brackets(X){return String(X)+"[]"},comma:"comma",indices(X,Y){return String(X)+"["+Y+"]"},repeat(X){return String(X)}},r6=function(X,Y){Array.prototype.push.apply(X,JX(Y)?Y:[Y])},i6,a={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:p6,encodeValuesOnly:!1,format:JY,formatter:I$,indices:!1,serializeDate(X){return(i6??(i6=Function.prototype.call.bind(Date.prototype.toISOString)))(X)},skipNulls:!1,strictNullHandling:!1};function bZ(X){return typeof X==="string"||typeof X==="number"||typeof X==="boolean"||typeof X==="symbol"||typeof X==="bigint"}var k$={};function a6(X,Y,$,W,Z,Q,J,G,z,B,H,V,K,U,E,I,T,S){let P=X,h=S,f=0,e=!1;while((h=h.get(k$))!==void 0&&!e){let k=h.get(X);if(f+=1,typeof k<"u")if(k===f)throw RangeError("Cyclic object value");else e=!0;if(typeof h.get(k$)>"u")f=0}if(typeof B==="function")P=B(Y,P);else if(P instanceof Date)P=K?.(P);else if($==="comma"&&JX(P))P=y$(P,function(k){if(k instanceof Date)return K?.(k);return k});if(P===null){if(Q)return z&&!I?z(Y,a.encoder,T,"key",U):Y;P=""}if(bZ(P)||l6(P)){if(z){let k=I?Y:z(Y,a.encoder,T,"key",U);return[E?.(k)+"="+E?.(z(P,a.encoder,T,"value",U))]}return[E?.(Y)+"="+E?.(String(P))]}let b=[];if(typeof P>"u")return b;let g;if($==="comma"&&JX(P)){if(I&&z)P=y$(P,z);g=[{value:P.length>0?P.join(",")||null:void 0}]}else if(JX(B))g=B;else{let k=Object.keys(P);g=H?k.sort(H):k}let QX=G?String(Y).replace(/\./g,"%2E"):String(Y),m=W&&JX(P)&&P.length===1?QX+"[]":QX;if(Z&&JX(P)&&P.length===0)return m+"[]";for(let k=0;k<g.length;++k){let TX=g[k],$Y=typeof TX==="object"&&typeof TX.value<"u"?TX.value:P[TX];if(J&&$Y===null)continue;let T$=V&&G?TX.replace(/\./g,"%2E"):TX,xZ=JX(P)?typeof $==="function"?$(m,T$):m:m+(V?"."+T$:"["+T$+"]");S.set(X,f);let P6=new WeakMap;P6.set(k$,S),r6(b,a6($Y,xZ,$,W,Z,Q,J,G,$==="comma"&&I&&JX(P)?null:z,B,H,V,K,U,E,I,T,P6))}return b}function fZ(X=a){if(typeof X.allowEmptyArrays<"u"&&typeof X.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof X.encodeDotInKeys<"u"&&typeof X.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(X.encoder!==null&&typeof X.encoder<"u"&&typeof X.encoder!=="function")throw TypeError("Encoder has to be a function.");let Y=X.charset||a.charset;if(typeof X.charset<"u"&&X.charset!=="utf-8"&&X.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let $=JY;if(typeof X.format<"u"){if(!KY(GY,X.format))throw TypeError("Unknown format option provided.");$=X.format}let W=GY[$],Z=a.filter;if(typeof X.filter==="function"||JX(X.filter))Z=X.filter;let Q;if(X.arrayFormat&&X.arrayFormat in n6)Q=X.arrayFormat;else if("indices"in X)Q=X.indices?"indices":"repeat";else Q=a.arrayFormat;if("commaRoundTrip"in X&&typeof X.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let J=typeof X.allowDots>"u"?!!X.encodeDotInKeys===!0?!0:a.allowDots:!!X.allowDots;return{addQueryPrefix:typeof X.addQueryPrefix==="boolean"?X.addQueryPrefix:a.addQueryPrefix,allowDots:J,allowEmptyArrays:typeof X.allowEmptyArrays==="boolean"?!!X.allowEmptyArrays:a.allowEmptyArrays,arrayFormat:Q,charset:Y,charsetSentinel:typeof X.charsetSentinel==="boolean"?X.charsetSentinel:a.charsetSentinel,commaRoundTrip:!!X.commaRoundTrip,delimiter:typeof X.delimiter>"u"?a.delimiter:X.delimiter,encode:typeof X.encode==="boolean"?X.encode:a.encode,encodeDotInKeys:typeof X.encodeDotInKeys==="boolean"?X.encodeDotInKeys:a.encodeDotInKeys,encoder:typeof X.encoder==="function"?X.encoder:a.encoder,encodeValuesOnly:typeof X.encodeValuesOnly==="boolean"?X.encodeValuesOnly:a.encodeValuesOnly,filter:Z,format:$,formatter:W,serializeDate:typeof X.serializeDate==="function"?X.serializeDate:a.serializeDate,skipNulls:typeof X.skipNulls==="boolean"?X.skipNulls:a.skipNulls,sort:typeof X.sort==="function"?X.sort:null,strictNullHandling:typeof X.strictNullHandling==="boolean"?X.strictNullHandling:a.strictNullHandling}}function v$(X,Y={}){let $=X,W=fZ(Y),Z,Q;if(typeof W.filter==="function")Q=W.filter,$=Q("",$);else if(JX(W.filter))Q=W.filter,Z=Q;let J=[];if(typeof $!=="object"||$===null)return"";let G=n6[W.arrayFormat],z=G==="comma"&&W.commaRoundTrip;if(!Z)Z=Object.keys($);if(W.sort)Z.sort(W.sort);let B=new WeakMap;for(let K=0;K<Z.length;++K){let U=Z[K];if(W.skipNulls&&$[U]===null)continue;r6(J,a6($[U],U,G,z,W.allowEmptyArrays,W.strictNullHandling,W.skipNulls,W.encodeDotInKeys,W.encode?W.encoder:null,W.filter,W.sort,W.allowDots,W.serializeDate,W.format,W.formatter,W.encodeValuesOnly,W.charset,B))}let H=J.join(W.delimiter),V=W.addQueryPrefix===!0?"?":"";if(W.charsetSentinel)if(W.charset==="iso-8859-1")V+="utf8=%26%2310003%3B&";else V+="utf8=%E2%9C%93&";return H.length>0?V+H:""}function o6(X){let Y=0;for(let Z of X)Y+=Z.length;let $=new Uint8Array(Y),W=0;for(let Z of X)$.set(Z,W),W+=Z.length;return $}var t6;function J8(X){let Y;return(t6??(Y=new globalThis.TextEncoder,t6=Y.encode.bind(Y)))(X)}var s6;function b$(X){let Y;return(s6??(Y=new globalThis.TextDecoder,s6=Y.decode.bind(Y)))(X)}var NX,UX;class G8{constructor(){NX.set(this,void 0),UX.set(this,void 0),A(this,NX,new Uint8Array,"f"),A(this,UX,null,"f")}decode(X){if(X==null)return[];let Y=X instanceof ArrayBuffer?new Uint8Array(X):typeof X==="string"?J8(X):X;A(this,NX,o6([w(this,NX,"f"),Y]),"f");let $=[],W;while((W=gZ(w(this,NX,"f"),w(this,UX,"f")))!=null){if(W.carriage&&w(this,UX,"f")==null){A(this,UX,W.index,"f");continue}if(w(this,UX,"f")!=null&&(W.index!==w(this,UX,"f")+1||W.carriage)){$.push(b$(w(this,NX,"f").subarray(0,w(this,UX,"f")-1))),A(this,NX,w(this,NX,"f").subarray(w(this,UX,"f")),"f"),A(this,UX,null,"f");continue}let Z=w(this,UX,"f")!==null?W.preceding-1:W.preceding,Q=b$(w(this,NX,"f").subarray(0,Z));$.push(Q),A(this,NX,w(this,NX,"f").subarray(W.index),"f"),A(this,UX,null,"f")}return $}flush(){if(!w(this,NX,"f").length)return[];return this.decode(`
|
|
27
|
+
`)}}NX=new WeakMap,UX=new WeakMap;G8.NEWLINE_CHARS=new Set([`
|
|
28
|
+
`,"\r"]);G8.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function gZ(X,Y){for(let Z=Y??0;Z<X.length;Z++){if(X[Z]===10)return{preceding:Z,index:Z+1,carriage:!1};if(X[Z]===13)return{preceding:Z,index:Z+1,carriage:!0}}return null}function e6(X){for(let W=0;W<X.length-1;W++){if(X[W]===10&&X[W+1]===10)return W+2;if(X[W]===13&&X[W+1]===13)return W+2;if(X[W]===13&&X[W+1]===10&&W+3<X.length&&X[W+2]===13&&X[W+3]===10)return W+4}return-1}var zY={off:0,error:200,warn:300,info:400,debug:500},f$=(X,Y,$)=>{if(!X)return;if(y6(zY,X))return X;i($).warn(`${Y} was set to ${JSON.stringify(X)}, expected one of ${JSON.stringify(Object.keys(zY))}`);return};function H4(){}function VY(X,Y,$){if(!Y||zY[X]>zY[$])return H4;else return Y[X].bind(Y)}var uZ={error:H4,warn:H4,info:H4,debug:H4},X5=new WeakMap;function i(X){let Y=X.logger,$=X.logLevel??"off";if(!Y)return uZ;let W=X5.get(Y);if(W&&W[0]===$)return W[1];let Z={error:VY("error",Y,$),warn:VY("warn",Y,$),info:VY("info",Y,$),debug:VY("debug",Y,$)};return X5.set(Y,[$,Z]),Z}var mX=(X)=>{if(X.options)X.options={...X.options},delete X.options.headers;if(X.headers)X.headers=Object.fromEntries((X.headers instanceof Headers?[...X.headers]:Object.entries(X.headers)).map(([Y,$])=>[Y,Y.toLowerCase()==="authorization"||Y.toLowerCase()==="cookie"||Y.toLowerCase()==="set-cookie"?"***":$]));if("retryOfRequestLogID"in X){if(X.retryOfRequestLogID)X.retryOf=X.retryOfRequestLogID;delete X.retryOfRequestLogID}return X};var B4;class wX{constructor(X,Y,$){this.iterator=X,B4.set(this,void 0),this.controller=Y,A(this,B4,$,"f")}static fromSSEResponse(X,Y,$){let W=!1,Z=$?i($):console;async function*Q(){if(W)throw new D("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");W=!0;let J=!1;try{for await(let G of dZ(X,Y)){if(J)continue;if(G.data.startsWith("[DONE]")){J=!0;continue}if(G.event===null||!G.event.startsWith("thread.")){let z;try{z=JSON.parse(G.data)}catch(B){throw Z.error("Could not parse message into JSON:",G.data),Z.error("From chunk:",G.raw),B}if(z&&z.error)throw new n(void 0,z.error,void 0,X.headers);yield z}else{let z;try{z=JSON.parse(G.data)}catch(B){throw console.error("Could not parse message into JSON:",G.data),console.error("From chunk:",G.raw),B}if(G.event=="error")throw new n(void 0,z.error,z.message,void 0);yield{event:G.event,data:z}}}J=!0}catch(G){if(o8(G))return;throw G}finally{if(!J)Y.abort()}}return new wX(Q,Y,$)}static fromReadableStream(X,Y,$){let W=!1;async function*Z(){let J=new G8,G=C$(X);for await(let z of G)for(let B of J.decode(z))yield B;for(let z of J.flush())yield z}async function*Q(){if(W)throw new D("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");W=!0;let J=!1;try{for await(let G of Z()){if(J)continue;if(G)yield JSON.parse(G)}J=!0}catch(G){if(o8(G))return;throw G}finally{if(!J)Y.abort()}}return new wX(Q,Y,$)}[(B4=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let X=[],Y=[],$=this.iterator(),W=(Z)=>{return{next:()=>{if(Z.length===0){let Q=$.next();X.push(Q),Y.push(Q)}return Z.shift()}}};return[new wX(()=>W(X),this.controller,w(this,B4,"f")),new wX(()=>W(Y),this.controller,w(this,B4,"f"))]}toReadableStream(){let X=this,Y;return R$({async start(){Y=X[Symbol.asyncIterator]()},async pull($){try{let{value:W,done:Z}=await Y.next();if(Z)return $.close();let Q=J8(JSON.stringify(W)+`
|
|
29
|
+
`);$.enqueue(Q)}catch(W){$.error(W)}},async cancel(){await Y.return?.()}})}}async function*dZ(X,Y){if(!X.body){if(Y.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new D("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 D("Attempted to iterate over a response with no body")}let $=new Y5,W=new G8,Z=C$(X.body);for await(let Q of mZ(Z))for(let J of W.decode(Q)){let G=$.decode(J);if(G)yield G}for(let Q of W.flush()){let J=$.decode(Q);if(J)yield J}}async function*mZ(X){let Y=new Uint8Array;for await(let $ of X){if($==null)continue;let W=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?J8($):$,Z=new Uint8Array(Y.length+W.length);Z.set(Y),Z.set(W,Y.length),Y=Z;let Q;while((Q=e6(Y))!==-1)yield Y.slice(0,Q),Y=Y.slice(Q)}if(Y.length>0)yield Y}class Y5{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(X){if(X.endsWith("\r"))X=X.substring(0,X.length-1);if(!X){if(!this.event&&!this.data.length)return null;let Z={event:this.event,data:this.data.join(`
|
|
30
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],Z}if(this.chunks.push(X),X.startsWith(":"))return null;let[Y,$,W]=cZ(X,":");if(W.startsWith(" "))W=W.substring(1);if(Y==="event")this.event=W;else if(Y==="data")this.data.push(W);return null}}function cZ(X,Y){let $=X.indexOf(Y);if($!==-1)return[X.substring(0,$),Y,X.substring($+Y.length)];return[X,"",""]}async function HY(X,Y){let{response:$,requestLogID:W,retryOfRequestLogID:Z,startTime:Q}=Y,J=await(async()=>{if(Y.options.stream){if(i(X).debug("response",$.status,$.url,$.headers,$.body),Y.options.__streamClass)return Y.options.__streamClass.fromSSEResponse($,Y.controller,X);return wX.fromSSEResponse($,Y.controller,X)}if($.status===204)return null;if(Y.options.__binaryResponse)return $;let z=$.headers.get("content-type")?.split(";")[0]?.trim();if(z?.includes("application/json")||z?.endsWith("+json")){if($.headers.get("content-length")==="0")return;let K=await $.json();return h$(K,$)}return await $.text()})();return i(X).debug(`[${W}] response parsed`,mX({retryOfRequestLogID:Z,url:$.url,status:$.status,body:J,durationMs:Date.now()-Q})),J}function h$(X,Y){if(!X||typeof X!=="object"||Array.isArray(X))return X;return Object.defineProperty(X,"_request_id",{value:Y.headers.get("x-request-id"),enumerable:!1})}var N4;class I0 extends Promise{constructor(X,Y,$=HY){super((W)=>{W(null)});this.responsePromise=Y,this.parseResponse=$,N4.set(this,void 0),A(this,N4,X,"f")}_thenUnwrap(X){return new I0(w(this,N4,"f"),this.responsePromise,async(Y,$)=>h$(X(await this.parseResponse(Y,$),$),$.response))}asResponse(){return this.responsePromise.then((X)=>X.response)}async withResponse(){let[X,Y]=await Promise.all([this.parse(),this.asResponse()]);return{data:X,response:Y,request_id:Y.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then((X)=>this.parseResponse(w(this,N4,"f"),X));return this.parsedPromise}then(X,Y){return this.parse().then(X,Y)}catch(X){return this.parse().catch(X)}finally(X){return this.parse().finally(X)}}N4=new WeakMap;var BY;class NY{constructor(X,Y,$,W){BY.set(this,void 0),A(this,BY,X,"f"),this.options=W,this.response=Y,this.body=$}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let X=this.nextPageRequestOptions();if(!X)throw new D("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await w(this,BY,"f").requestAPIList(this.constructor,X)}async*iterPages(){let X=this;yield X;while(X.hasNextPage())X=await X.getNextPage(),yield X}async*[(BY=new WeakMap,Symbol.asyncIterator)](){for await(let X of this.iterPages())for(let Y of X.getPaginatedItems())yield Y}}class UY extends I0{constructor(X,Y,$){super(X,Y,async(W,Z)=>new $(W,Z.response,await HY(W,Z),Z.options))}async*[Symbol.asyncIterator](){let X=await this;for await(let Y of X)yield Y}}class cX extends NY{constructor(X,Y,$,W){super(X,Y,$,W);this.data=$.data||[],this.object=$.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class _ extends NY{constructor(X,Y,$,W){super(X,Y,$,W);this.data=$.data||[],this.has_more=$.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let X=this.getPaginatedItems(),Y=X[X.length-1]?.id;if(!Y)return null;return{...this.options,query:{...S$(this.options.query),after:Y}}}}class J0 extends NY{constructor(X,Y,$,W){super(X,Y,$,W);this.data=$.data||[],this.has_more=$.has_more||!1,this.last_id=$.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let X=this.last_id;if(!X)return null;return{...this.options,query:{...S$(this.options.query),after:X}}}}var d$=()=>{if(typeof File>"u"){let{process:X}=globalThis,Y=typeof X?.versions?.node==="string"&&parseInt(X.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(Y?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function K8(X,Y,$){return d$(),new File(X,Y??"unknown_file",$)}function U4(X){return(typeof X==="object"&&X!==null&&(("name"in X)&&X.name&&String(X.name)||("url"in X)&&X.url&&String(X.url)||("filename"in X)&&X.filename&&String(X.filename)||("path"in X)&&X.path&&String(X.path))||"").split(/[\\/]/).pop()||void 0}var wY=(X)=>X!=null&&typeof X==="object"&&typeof X[Symbol.asyncIterator]==="function",pX=async(X,Y)=>{if(!g$(X.body))return X;return{...X,body:await W5(X.body,Y)}},AX=async(X,Y)=>{return{...X,body:await W5(X.body,Y)}},$5=new WeakMap;function lZ(X){let Y=typeof X==="function"?X:X.fetch,$=$5.get(Y);if($)return $;let W=(async()=>{try{let Z="Response"in Y?Y.Response:(await Y("data:,")).constructor,Q=new FormData;if(Q.toString()===await new Z(Q).text())return!1;return!0}catch{return!0}})();return $5.set(Y,W),W}var W5=async(X,Y)=>{if(!await lZ(Y))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let $=new FormData;return await Promise.all(Object.entries(X||{}).map(([W,Z])=>u$($,W,Z))),$},Z5=(X)=>X instanceof Blob&&("name"in X),iZ=(X)=>typeof X==="object"&&X!==null&&(X instanceof Response||wY(X)||Z5(X)),g$=(X)=>{if(iZ(X))return!0;if(Array.isArray(X))return X.some(g$);if(X&&typeof X==="object"){for(let Y in X)if(g$(X[Y]))return!0}return!1},u$=async(X,Y,$)=>{if($===void 0)return;if($==null)throw TypeError(`Received null for "${Y}"; to pass null in FormData, you must use the string 'null'`);if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")X.append(Y,String($));else if($ instanceof Response)X.append(Y,K8([await $.blob()],U4($)));else if(wY($))X.append(Y,K8([await new Response(QY($)).blob()],U4($)));else if(Z5($))X.append(Y,$,U4($));else if(Array.isArray($))await Promise.all($.map((W)=>u$(X,Y+"[]",W)));else if(typeof $==="object")await Promise.all(Object.entries($).map(([W,Z])=>u$(X,`${Y}[${W}]`,Z)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${$} instead`)};var Q5=(X)=>X!=null&&typeof X==="object"&&typeof X.size==="number"&&typeof X.type==="string"&&typeof X.text==="function"&&typeof X.slice==="function"&&typeof X.arrayBuffer==="function",nZ=(X)=>X!=null&&typeof X==="object"&&typeof X.name==="string"&&typeof X.lastModified==="number"&&Q5(X),rZ=(X)=>X!=null&&typeof X==="object"&&typeof X.url==="string"&&typeof X.blob==="function";async function w4(X,Y,$){if(d$(),X=await X,nZ(X)){if(X instanceof File)return X;return K8([await X.arrayBuffer()],X.name)}if(rZ(X)){let Z=await X.blob();return Y||(Y=new URL(X.url).pathname.split(/[\\/]/).pop()),K8(await m$(Z),Y,$)}let W=await m$(X);if(Y||(Y=U4(X)),!$?.type){let Z=W.find((Q)=>typeof Q==="object"&&("type"in Q)&&Q.type);if(typeof Z==="string")$={...$,type:Z}}return K8(W,Y,$)}async function m$(X){let Y=[];if(typeof X==="string"||ArrayBuffer.isView(X)||X instanceof ArrayBuffer)Y.push(X);else if(Q5(X))Y.push(X instanceof Blob?X:await X.arrayBuffer());else if(wY(X))for await(let $ of X)Y.push(...await m$($));else{let $=X?.constructor?.name;throw Error(`Unexpected data type: ${typeof X}${$?`; constructor: ${$}`:""}${aZ(X)}`)}return Y}function aZ(X){if(typeof X!=="object"||X===null)return"";return`; props: [${Object.getOwnPropertyNames(X).map(($)=>`"${$}"`).join(", ")}]`}class L{constructor(X){this._client=X}}function G5(X){return X.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var J5=Object.freeze(Object.create(null)),sZ=(X=G5)=>function($,...W){if($.length===1)return $[0];let Z=!1,Q=[],J=$.reduce((H,V,K)=>{if(/[?#]/.test(V))Z=!0;let U=W[K],E=(Z?encodeURIComponent:X)(""+U);if(K!==W.length&&(U==null||typeof U==="object"&&U.toString===Object.getPrototypeOf(Object.getPrototypeOf(U.hasOwnProperty??J5)??J5)?.toString))E=U+"",Q.push({start:H.length+V.length,length:E.length,error:`Value of type ${Object.prototype.toString.call(U).slice(8,-1)} is not a valid path parameter`});return H+V+(K===W.length?"":E)},""),G=J.split(/[?#]/,1)[0],z=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,B;while((B=z.exec(G))!==null)Q.push({start:B.index,length:B[0].length,error:`Value "${B[0]}" can't be safely passed as a path parameter`});if(Q.sort((H,V)=>H.start-V.start),Q.length>0){let H=0,V=Q.reduce((K,U)=>{let E=" ".repeat(U.start-H),I="^".repeat(U.length);return H=U.start+U.length,K+E+I},"");throw new D(`Path parameters result in path with invalid segments:
|
|
31
|
+
${Q.map((K)=>K.error).join(`
|
|
32
|
+
`)}
|
|
33
|
+
${J}
|
|
34
|
+
${V}`)}return J},F=sZ(G5);class V8 extends L{list(X,Y={},$){return this._client.getAPIList(F`/chat/completions/${X}/messages`,_,{query:Y,...$})}}function q4(X){return X!==void 0&&"function"in X&&X.function!==void 0}function K5(X,Y){let $={...X};return Object.defineProperties($,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:Y,enumerable:!1}}),$}function F4(X){return X?.$brand==="auto-parseable-response-format"}function j0(X){return X?.$brand==="auto-parseable-tool"}function V5(X,Y){if(!Y||!c$(Y))return{...X,choices:X.choices.map(($)=>{return H5($.message.tool_calls),{...$,message:{...$.message,parsed:null,...$.message.tool_calls?{tool_calls:$.message.tool_calls}:void 0}}})};return L4(X,Y)}function L4(X,Y){let $=X.choices.map((W)=>{if(W.finish_reason==="length")throw new K4;if(W.finish_reason==="content_filter")throw new V4;return H5(W.message.tool_calls),{...W,message:{...W.message,...W.message.tool_calls?{tool_calls:W.message.tool_calls?.map((Z)=>YQ(Y,Z))??void 0}:void 0,parsed:W.message.content&&!W.message.refusal?XQ(Y,W.message.content):null}}});return{...X,choices:$}}function XQ(X,Y){if(X.response_format?.type!=="json_schema")return null;if(X.response_format?.type==="json_schema"){if("$parseRaw"in X.response_format)return X.response_format.$parseRaw(Y);return JSON.parse(Y)}return null}function YQ(X,Y){let $=X.tools?.find((W)=>q4(W)&&W.function?.name===Y.function.name);return{...Y,function:{...Y.function,parsed_arguments:j0($)?$.$parseRaw(Y.function.arguments):$?.function.strict?JSON.parse(Y.function.arguments):null}}}function z5(X,Y){if(!X||!("tools"in X)||!X.tools)return!1;let $=X.tools?.find((W)=>q4(W)&&W.function?.name===Y.function.name);return q4($)&&(j0($)||$?.function.strict||!1)}function c$(X){if(F4(X.response_format))return!0;return X.tools?.some((Y)=>j0(Y)||Y.type==="function"&&Y.function.strict===!0)??!1}function H5(X){for(let Y of X||[])if(Y.type!=="function")throw new D(`Currently only \`function\` tool calls are supported; Received \`${Y.type}\``)}function B5(X){for(let Y of X??[]){if(Y.type!=="function")throw new D(`Currently only \`function\` tool types support auto-parsing; Received \`${Y.type}\``);if(Y.function.strict!==!0)throw new D(`The \`${Y.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var z8=(X)=>{return X?.role==="assistant"},p$=(X)=>{return X?.role==="tool"};var l$,qY,FY,E4,x4,LY,O4,lX,D4,EY,xY,H8,N5;class _0{constructor(){l$.add(this),this.controller=new AbortController,qY.set(this,void 0),FY.set(this,()=>{}),E4.set(this,()=>{}),x4.set(this,void 0),LY.set(this,()=>{}),O4.set(this,()=>{}),lX.set(this,{}),D4.set(this,!1),EY.set(this,!1),xY.set(this,!1),H8.set(this,!1),A(this,qY,new Promise((X,Y)=>{A(this,FY,X,"f"),A(this,E4,Y,"f")}),"f"),A(this,x4,new Promise((X,Y)=>{A(this,LY,X,"f"),A(this,O4,Y,"f")}),"f"),w(this,qY,"f").catch(()=>{}),w(this,x4,"f").catch(()=>{})}_run(X){setTimeout(()=>{X().then(()=>{this._emitFinal(),this._emit("end")},w(this,l$,"m",N5).bind(this))},0)}_connected(){if(this.ended)return;w(this,FY,"f").call(this),this._emit("connect")}get ended(){return w(this,D4,"f")}get errored(){return w(this,EY,"f")}get aborted(){return w(this,xY,"f")}abort(){this.controller.abort()}on(X,Y){return(w(this,lX,"f")[X]||(w(this,lX,"f")[X]=[])).push({listener:Y}),this}off(X,Y){let $=w(this,lX,"f")[X];if(!$)return this;let W=$.findIndex((Z)=>Z.listener===Y);if(W>=0)$.splice(W,1);return this}once(X,Y){return(w(this,lX,"f")[X]||(w(this,lX,"f")[X]=[])).push({listener:Y,once:!0}),this}emitted(X){return new Promise((Y,$)=>{if(A(this,H8,!0,"f"),X!=="error")this.once("error",$);this.once(X,Y)})}async done(){A(this,H8,!0,"f"),await w(this,x4,"f")}_emit(X,...Y){if(w(this,D4,"f"))return;if(X==="end")A(this,D4,!0,"f"),w(this,LY,"f").call(this);let $=w(this,lX,"f")[X];if($)w(this,lX,"f")[X]=$.filter((W)=>!W.once),$.forEach(({listener:W})=>W(...Y));if(X==="abort"){let W=Y[0];if(!w(this,H8,"f")&&!$?.length)Promise.reject(W);w(this,E4,"f").call(this,W),w(this,O4,"f").call(this,W),this._emit("end");return}if(X==="error"){let W=Y[0];if(!w(this,H8,"f")&&!$?.length)Promise.reject(W);w(this,E4,"f").call(this,W),w(this,O4,"f").call(this,W),this._emit("end")}}_emitFinal(){}}qY=new WeakMap,FY=new WeakMap,E4=new WeakMap,x4=new WeakMap,LY=new WeakMap,O4=new WeakMap,lX=new WeakMap,D4=new WeakMap,EY=new WeakMap,xY=new WeakMap,H8=new WeakMap,l$=new WeakSet,N5=function(Y){if(A(this,EY,!0,"f"),Y instanceof Error&&Y.name==="AbortError")Y=new l;if(Y instanceof l)return A(this,xY,!0,"f"),this._emit("abort",Y);if(Y instanceof D)return this._emit("error",Y);if(Y instanceof Error){let $=new D(Y.message);return $.cause=Y,this._emit("error",$)}return this._emit("error",new D(String(Y)))};function U5(X){return typeof X.parse==="function"}var VX,i$,OY,n$,r$,a$,w5,q5,$Q=10;class M4 extends _0{constructor(){super(...arguments);VX.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(X){this._chatCompletions.push(X),this._emit("chatCompletion",X);let Y=X.choices[0]?.message;if(Y)this._addMessage(Y);return X}_addMessage(X,Y=!0){if(!("content"in X))X.content=null;if(this.messages.push(X),Y){if(this._emit("message",X),p$(X)&&X.content)this._emit("functionToolCallResult",X.content);else if(z8(X)&&X.tool_calls){for(let $ of X.tool_calls)if($.type==="function")this._emit("functionToolCall",$.function)}}}async finalChatCompletion(){await this.done();let X=this._chatCompletions[this._chatCompletions.length-1];if(!X)throw new D("stream ended without producing a ChatCompletion");return X}async finalContent(){return await this.done(),w(this,VX,"m",i$).call(this)}async finalMessage(){return await this.done(),w(this,VX,"m",OY).call(this)}async finalFunctionToolCall(){return await this.done(),w(this,VX,"m",n$).call(this)}async finalFunctionToolCallResult(){return await this.done(),w(this,VX,"m",r$).call(this)}async totalUsage(){return await this.done(),w(this,VX,"m",a$).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let X=this._chatCompletions[this._chatCompletions.length-1];if(X)this._emit("finalChatCompletion",X);let Y=w(this,VX,"m",OY).call(this);if(Y)this._emit("finalMessage",Y);let $=w(this,VX,"m",i$).call(this);if($)this._emit("finalContent",$);let W=w(this,VX,"m",n$).call(this);if(W)this._emit("finalFunctionToolCall",W);let Z=w(this,VX,"m",r$).call(this);if(Z!=null)this._emit("finalFunctionToolCallResult",Z);if(this._chatCompletions.some((Q)=>Q.usage))this._emit("totalUsage",w(this,VX,"m",a$).call(this))}async _createChatCompletion(X,Y,$){let W=$?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}w(this,VX,"m",w5).call(this,Y);let Z=await X.chat.completions.create({...Y,stream:!1},{...$,signal:this.controller.signal});return this._connected(),this._addChatCompletion(L4(Z,Y))}async _runChatCompletion(X,Y,$){for(let W of Y.messages)this._addMessage(W,!1);return await this._createChatCompletion(X,Y,$)}async _runTools(X,Y,$){let{tool_choice:Z="auto",stream:Q,...J}=Y,G=typeof Z!=="string"&&Z.type==="function"&&Z?.function?.name,{maxChatCompletions:z=$Q}=$||{},B=Y.tools.map((K)=>{if(j0(K)){if(!K.$callback)throw new D("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:K.$callback,name:K.function.name,description:K.function.description||"",parameters:K.function.parameters,parse:K.$parseRaw,strict:!0}}}return K}),H={};for(let K of B)if(K.type==="function")H[K.function.name||K.function.function.name]=K.function;let V="tools"in Y?B.map((K)=>K.type==="function"?{type:"function",function:{name:K.function.name||K.function.function.name,parameters:K.function.parameters,description:K.function.description,strict:K.function.strict}}:K):void 0;for(let K of Y.messages)this._addMessage(K,!1);for(let K=0;K<z;++K){let E=(await this._createChatCompletion(X,{...J,tool_choice:Z,tools:V,messages:[...this.messages]},$)).choices[0]?.message;if(!E)throw new D("missing message in ChatCompletion response");if(!E.tool_calls?.length)return;for(let I of E.tool_calls){if(I.type!=="function")continue;let T=I.id,{name:S,arguments:P}=I.function,h=H[S];if(!h){let g=`Invalid tool_call: ${JSON.stringify(S)}. Available options are: ${Object.keys(H).map((QX)=>JSON.stringify(QX)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:T,content:g});continue}else if(G&&G!==S){let g=`Invalid tool_call: ${JSON.stringify(S)}. ${JSON.stringify(G)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:T,content:g});continue}let f;try{f=U5(h)?await h.parse(P):P}catch(g){let QX=g instanceof Error?g.message:String(g);this._addMessage({role:"tool",tool_call_id:T,content:QX});continue}let e=await h.function(f,this),b=w(this,VX,"m",q5).call(this,e);if(this._addMessage({role:"tool",tool_call_id:T,content:b}),G)return}}return}}VX=new WeakSet,i$=function(){return w(this,VX,"m",OY).call(this).content??null},OY=function(){let Y=this.messages.length;while(Y-- >0){let $=this.messages[Y];if(z8($))return{...$,content:$.content??null,refusal:$.refusal??null}}throw new D("stream ended without producing a ChatCompletionMessage with role=assistant")},n$=function(){for(let Y=this.messages.length-1;Y>=0;Y--){let $=this.messages[Y];if(z8($)&&$?.tool_calls?.length)return $.tool_calls.filter((W)=>W.type==="function").at(-1)?.function}return},r$=function(){for(let Y=this.messages.length-1;Y>=0;Y--){let $=this.messages[Y];if(p$($)&&$.content!=null&&typeof $.content==="string"&&this.messages.some((W)=>W.role==="assistant"&&W.tool_calls?.some((Z)=>Z.type==="function"&&Z.id===$.tool_call_id)))return $.content}return},a$=function(){let Y={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:$}of this._chatCompletions)if($)Y.completion_tokens+=$.completion_tokens,Y.prompt_tokens+=$.prompt_tokens,Y.total_tokens+=$.total_tokens;return Y},w5=function(Y){if(Y.n!=null&&Y.n>1)throw new D("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},q5=function(Y){return typeof Y==="string"?Y:Y===void 0?"undefined":JSON.stringify(Y)};class T4 extends M4{static runTools(X,Y,$){let W=new T4,Z={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runTools"}};return W._run(()=>W._runTools(X,Y,Z)),W}_addMessage(X,Y=!0){if(super._addMessage(X,Y),z8(X)&&X.content)this._emit("content",X.content)}}var XX={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class F5 extends Error{}class L5 extends Error{}function WQ(X,Y=XX.ALL){if(typeof X!=="string")throw TypeError(`expecting str, got ${typeof X}`);if(!X.trim())throw Error(`${X} is empty`);return ZQ(X.trim(),Y)}var ZQ=(X,Y)=>{let $=X.length,W=0,Z=(K)=>{throw new F5(`${K} at position ${W}`)},Q=(K)=>{throw new L5(`${K} at position ${W}`)},J=()=>{if(V(),W>=$)Z("Unexpected end of input");if(X[W]==='"')return G();if(X[W]==="{")return z();if(X[W]==="[")return B();if(X.substring(W,W+4)==="null"||XX.NULL&Y&&$-W<4&&"null".startsWith(X.substring(W)))return W+=4,null;if(X.substring(W,W+4)==="true"||XX.BOOL&Y&&$-W<4&&"true".startsWith(X.substring(W)))return W+=4,!0;if(X.substring(W,W+5)==="false"||XX.BOOL&Y&&$-W<5&&"false".startsWith(X.substring(W)))return W+=5,!1;if(X.substring(W,W+8)==="Infinity"||XX.INFINITY&Y&&$-W<8&&"Infinity".startsWith(X.substring(W)))return W+=8,1/0;if(X.substring(W,W+9)==="-Infinity"||XX.MINUS_INFINITY&Y&&1<$-W&&$-W<9&&"-Infinity".startsWith(X.substring(W)))return W+=9,-1/0;if(X.substring(W,W+3)==="NaN"||XX.NAN&Y&&$-W<3&&"NaN".startsWith(X.substring(W)))return W+=3,NaN;return H()},G=()=>{let K=W,U=!1;W++;while(W<$&&(X[W]!=='"'||U&&X[W-1]==="\\"))U=X[W]==="\\"?!U:!1,W++;if(X.charAt(W)=='"')try{return JSON.parse(X.substring(K,++W-Number(U)))}catch(E){Q(String(E))}else if(XX.STR&Y)try{return JSON.parse(X.substring(K,W-Number(U))+'"')}catch(E){return JSON.parse(X.substring(K,X.lastIndexOf("\\"))+'"')}Z("Unterminated string literal")},z=()=>{W++,V();let K={};try{while(X[W]!=="}"){if(V(),W>=$&&XX.OBJ&Y)return K;let U=G();V(),W++;try{let E=J();Object.defineProperty(K,U,{value:E,writable:!0,enumerable:!0,configurable:!0})}catch(E){if(XX.OBJ&Y)return K;else throw E}if(V(),X[W]===",")W++}}catch(U){if(XX.OBJ&Y)return K;else Z("Expected '}' at end of object")}return W++,K},B=()=>{W++;let K=[];try{while(X[W]!=="]")if(K.push(J()),V(),X[W]===",")W++}catch(U){if(XX.ARR&Y)return K;Z("Expected ']' at end of array")}return W++,K},H=()=>{if(W===0){if(X==="-"&&XX.NUM&Y)Z("Not sure what '-' is");try{return JSON.parse(X)}catch(U){if(XX.NUM&Y)try{if(X[X.length-1]===".")return JSON.parse(X.substring(0,X.lastIndexOf(".")));return JSON.parse(X.substring(0,X.lastIndexOf("e")))}catch(E){}Q(String(U))}}let K=W;if(X[W]==="-")W++;while(X[W]&&!",]}".includes(X[W]))W++;if(W==$&&!(XX.NUM&Y))Z("Unterminated number literal");try{return JSON.parse(X.substring(K,W))}catch(U){if(X.substring(K,W)==="-"&&XX.NUM&Y)Z("Not sure what '-' is");try{return JSON.parse(X.substring(K,X.lastIndexOf("e")))}catch(E){Q(String(E))}}},V=()=>{while(W<$&&`
|
|
35
|
+
\r `.includes(X[W]))W++};return J()},t$=(X)=>WQ(X,XX.ALL^XX.NUM);var t,iX,B8,G0,s$,DY,o$,e$,X9,MY,Y9,E5;class K0 extends M4{constructor(X){super();t.add(this),iX.set(this,void 0),B8.set(this,void 0),G0.set(this,void 0),A(this,iX,X,"f"),A(this,B8,[],"f")}get currentChatCompletionSnapshot(){return w(this,G0,"f")}static fromReadableStream(X){let Y=new K0(null);return Y._run(()=>Y._fromReadableStream(X)),Y}static createChatCompletion(X,Y,$){let W=new K0(Y);return W._run(()=>W._runChatCompletion(X,{...Y,stream:!0},{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"stream"}})),W}async _createChatCompletion(X,Y,$){super._createChatCompletion;let W=$?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}w(this,t,"m",s$).call(this);let Z=await X.chat.completions.create({...Y,stream:!0},{...$,signal:this.controller.signal});this._connected();for await(let Q of Z)w(this,t,"m",o$).call(this,Q);if(Z.controller.signal?.aborted)throw new l;return this._addChatCompletion(w(this,t,"m",MY).call(this))}async _fromReadableStream(X,Y){let $=Y?.signal;if($){if($.aborted)this.controller.abort();$.addEventListener("abort",()=>this.controller.abort())}w(this,t,"m",s$).call(this),this._connected();let W=wX.fromReadableStream(X,this.controller),Z;for await(let Q of W){if(Z&&Z!==Q.id)this._addChatCompletion(w(this,t,"m",MY).call(this));w(this,t,"m",o$).call(this,Q),Z=Q.id}if(W.controller.signal?.aborted)throw new l;return this._addChatCompletion(w(this,t,"m",MY).call(this))}[(iX=new WeakMap,B8=new WeakMap,G0=new WeakMap,t=new WeakSet,s$=function(){if(this.ended)return;A(this,G0,void 0,"f")},DY=function(Y){let $=w(this,B8,"f")[Y.index];if($)return $;return $={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},w(this,B8,"f")[Y.index]=$,$},o$=function(Y){if(this.ended)return;let $=w(this,t,"m",E5).call(this,Y);this._emit("chunk",Y,$);for(let W of Y.choices){let Z=$.choices[W.index];if(W.delta.content!=null&&Z.message?.role==="assistant"&&Z.message?.content)this._emit("content",W.delta.content,Z.message.content),this._emit("content.delta",{delta:W.delta.content,snapshot:Z.message.content,parsed:Z.message.parsed});if(W.delta.refusal!=null&&Z.message?.role==="assistant"&&Z.message?.refusal)this._emit("refusal.delta",{delta:W.delta.refusal,snapshot:Z.message.refusal});if(W.logprobs?.content!=null&&Z.message?.role==="assistant")this._emit("logprobs.content.delta",{content:W.logprobs?.content,snapshot:Z.logprobs?.content??[]});if(W.logprobs?.refusal!=null&&Z.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:W.logprobs?.refusal,snapshot:Z.logprobs?.refusal??[]});let Q=w(this,t,"m",DY).call(this,Z);if(Z.finish_reason){if(w(this,t,"m",X9).call(this,Z),Q.current_tool_call_index!=null)w(this,t,"m",e$).call(this,Z,Q.current_tool_call_index)}for(let J of W.delta.tool_calls??[]){if(Q.current_tool_call_index!==J.index){if(w(this,t,"m",X9).call(this,Z),Q.current_tool_call_index!=null)w(this,t,"m",e$).call(this,Z,Q.current_tool_call_index)}Q.current_tool_call_index=J.index}for(let J of W.delta.tool_calls??[]){let G=Z.message.tool_calls?.[J.index];if(!G?.type)continue;if(G?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:G.function?.name,index:J.index,arguments:G.function.arguments,parsed_arguments:G.function.parsed_arguments,arguments_delta:J.function?.arguments??""});else O5(G?.type)}}},e$=function(Y,$){if(w(this,t,"m",DY).call(this,Y).done_tool_calls.has($))return;let Z=Y.message.tool_calls?.[$];if(!Z)throw Error("no tool call snapshot");if(!Z.type)throw Error("tool call snapshot missing `type`");if(Z.type==="function"){let Q=w(this,iX,"f")?.tools?.find((J)=>q4(J)&&J.function.name===Z.function.name);this._emit("tool_calls.function.arguments.done",{name:Z.function.name,index:$,arguments:Z.function.arguments,parsed_arguments:j0(Q)?Q.$parseRaw(Z.function.arguments):Q?.function.strict?JSON.parse(Z.function.arguments):null})}else O5(Z.type)},X9=function(Y){let $=w(this,t,"m",DY).call(this,Y);if(Y.message.content&&!$.content_done){$.content_done=!0;let W=w(this,t,"m",Y9).call(this);this._emit("content.done",{content:Y.message.content,parsed:W?W.$parseRaw(Y.message.content):null})}if(Y.message.refusal&&!$.refusal_done)$.refusal_done=!0,this._emit("refusal.done",{refusal:Y.message.refusal});if(Y.logprobs?.content&&!$.logprobs_content_done)$.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:Y.logprobs.content});if(Y.logprobs?.refusal&&!$.logprobs_refusal_done)$.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:Y.logprobs.refusal})},MY=function(){if(this.ended)throw new D("stream has ended, this shouldn't happen");let Y=w(this,G0,"f");if(!Y)throw new D("request ended without sending any chunks");return A(this,G0,void 0,"f"),A(this,B8,[],"f"),QQ(Y,w(this,iX,"f"))},Y9=function(){let Y=w(this,iX,"f")?.response_format;if(F4(Y))return Y;return null},E5=function(Y){var $,W,Z,Q;let J=w(this,G0,"f"),{choices:G,...z}=Y;if(!J)J=A(this,G0,{...z,choices:[]},"f");else Object.assign(J,z);for(let{delta:B,finish_reason:H,index:V,logprobs:K=null,...U}of Y.choices){let E=J.choices[V];if(!E)E=J.choices[V]={finish_reason:H,index:V,message:{},logprobs:K,...U};if(K)if(!E.logprobs)E.logprobs=Object.assign({},K);else{let{content:e,refusal:b,...g}=K;if(x5(g),Object.assign(E.logprobs,g),e)($=E.logprobs).content??($.content=[]),E.logprobs.content.push(...e);if(b)(W=E.logprobs).refusal??(W.refusal=[]),E.logprobs.refusal.push(...b)}if(H){if(E.finish_reason=H,w(this,iX,"f")&&c$(w(this,iX,"f"))){if(H==="length")throw new K4;if(H==="content_filter")throw new V4}}if(Object.assign(E,U),!B)continue;let{content:I,refusal:T,function_call:S,role:P,tool_calls:h,...f}=B;if(x5(f),Object.assign(E.message,f),T)E.message.refusal=(E.message.refusal||"")+T;if(P)E.message.role=P;if(S)if(!E.message.function_call)E.message.function_call=S;else{if(S.name)E.message.function_call.name=S.name;if(S.arguments)(Z=E.message.function_call).arguments??(Z.arguments=""),E.message.function_call.arguments+=S.arguments}if(I){if(E.message.content=(E.message.content||"")+I,!E.message.refusal&&w(this,t,"m",Y9).call(this))E.message.parsed=t$(E.message.content)}if(h){if(!E.message.tool_calls)E.message.tool_calls=[];for(let{index:e,id:b,type:g,function:QX,...m}of h){let k=(Q=E.message.tool_calls)[e]??(Q[e]={});if(Object.assign(k,m),b)k.id=b;if(g)k.type=g;if(QX)k.function??(k.function={name:QX.name??"",arguments:""});if(QX?.name)k.function.name=QX.name;if(QX?.arguments){if(k.function.arguments+=QX.arguments,z5(w(this,iX,"f"),k))k.function.parsed_arguments=t$(k.function.arguments)}}}}return J},Symbol.asyncIterator)](){let X=[],Y=[],$=!1;return this.on("chunk",(W)=>{let Z=Y.shift();if(Z)Z.resolve(W);else X.push(W)}),this.on("end",()=>{$=!0;for(let W of Y)W.resolve(void 0);Y.length=0}),this.on("abort",(W)=>{$=!0;for(let Z of Y)Z.reject(W);Y.length=0}),this.on("error",(W)=>{$=!0;for(let Z of Y)Z.reject(W);Y.length=0}),{next:async()=>{if(!X.length){if($)return{value:void 0,done:!0};return new Promise((Z,Q)=>Y.push({resolve:Z,reject:Q})).then((Z)=>Z?{value:Z,done:!1}:{value:void 0,done:!0})}return{value:X.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new wX(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function QQ(X,Y){let{id:$,choices:W,created:Z,model:Q,system_fingerprint:J,...G}=X,z={...G,id:$,choices:W.map(({message:B,finish_reason:H,index:V,logprobs:K,...U})=>{if(!H)throw new D(`missing finish_reason for choice ${V}`);let{content:E=null,function_call:I,tool_calls:T,...S}=B,P=B.role;if(!P)throw new D(`missing role for choice ${V}`);if(I){let{arguments:h,name:f}=I;if(h==null)throw new D(`missing function_call.arguments for choice ${V}`);if(!f)throw new D(`missing function_call.name for choice ${V}`);return{...U,message:{content:E,function_call:{arguments:h,name:f},role:P,refusal:B.refusal??null},finish_reason:H,index:V,logprobs:K}}if(T)return{...U,index:V,finish_reason:H,logprobs:K,message:{...S,role:P,content:E,refusal:B.refusal??null,tool_calls:T.map((h,f)=>{let{function:e,type:b,id:g,...QX}=h,{arguments:m,name:k,...TX}=e||{};if(g==null)throw new D(`missing choices[${V}].tool_calls[${f}].id
|
|
36
|
+
${TY(X)}`);if(b==null)throw new D(`missing choices[${V}].tool_calls[${f}].type
|
|
37
|
+
${TY(X)}`);if(k==null)throw new D(`missing choices[${V}].tool_calls[${f}].function.name
|
|
38
|
+
${TY(X)}`);if(m==null)throw new D(`missing choices[${V}].tool_calls[${f}].function.arguments
|
|
39
|
+
${TY(X)}`);return{...QX,id:g,type:b,function:{...TX,name:k,arguments:m}}})}};return{...U,message:{...S,content:E,role:P,refusal:B.refusal??null},finish_reason:H,index:V,logprobs:K}}),created:Z,model:Q,object:"chat.completion",...J?{system_fingerprint:J}:{}};return V5(z,Y)}function TY(X){return JSON.stringify(X)}function x5(X){return}function O5(X){}class N8 extends K0{static fromReadableStream(X){let Y=new N8(null);return Y._run(()=>Y._fromReadableStream(X)),Y}static runTools(X,Y,$){let W=new N8(Y),Z={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runTools"}};return W._run(()=>W._runTools(X,Y,Z)),W}}class V0 extends L{constructor(){super(...arguments);this.messages=new V8(this._client)}create(X,Y){return this._client.post("/chat/completions",{body:X,...Y,stream:X.stream??!1})}retrieve(X,Y){return this._client.get(F`/chat/completions/${X}`,Y)}update(X,Y,$){return this._client.post(F`/chat/completions/${X}`,{body:Y,...$})}list(X={},Y){return this._client.getAPIList("/chat/completions",_,{query:X,...Y})}delete(X,Y){return this._client.delete(F`/chat/completions/${X}`,Y)}parse(X,Y){return B5(X.tools),this._client.chat.completions.create(X,{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(($)=>L4($,X))}runTools(X,Y){if(X.stream)return N8.runTools(this._client,X,Y);return T4.runTools(this._client,X,Y)}stream(X,Y){return K0.createChatCompletion(this._client,X,Y)}}V0.Messages=V8;class y0 extends L{constructor(){super(...arguments);this.completions=new V0(this._client)}}y0.Completions=V0;var D5=Symbol("brand.privateNullableHeaders");function*GQ(X){if(!X)return;if(D5 in X){let{values:W,nulls:Z}=X;yield*W.entries();for(let Q of Z)yield[Q,null];return}let Y=!1,$;if(X instanceof Headers)$=X.entries();else if(P$(X))$=X;else Y=!0,$=Object.entries(X??{});for(let W of $){let Z=W[0];if(typeof Z!=="string")throw TypeError("expected header name to be a string");let Q=P$(W[1])?W[1]:[W[1]],J=!1;for(let G of Q){if(G===void 0)continue;if(Y&&!J)J=!0,yield[Z,null];yield[Z,G]}}}var x=(X)=>{let Y=new Headers,$=new Set;for(let W of X){let Z=new Set;for(let[Q,J]of GQ(W)){let G=Q.toLowerCase();if(!Z.has(G))Y.delete(Q),Z.add(G);if(J===null)Y.delete(Q),$.add(G);else Y.append(Q,J),$.delete(G)}}return{[D5]:!0,values:Y,nulls:$}};class A4 extends L{create(X,Y){return this._client.post("/audio/speech",{body:X,...Y,headers:x([{Accept:"application/octet-stream"},Y?.headers]),__binaryResponse:!0})}}class P4 extends L{create(X,Y){return this._client.post("/audio/transcriptions",AX({body:X,...Y,stream:X.stream??!1,__metadata:{model:X.model}},this._client))}}class S4 extends L{create(X,Y){return this._client.post("/audio/translations",AX({body:X,...Y,__metadata:{model:X.model}},this._client))}}class nX extends L{constructor(){super(...arguments);this.transcriptions=new P4(this._client),this.translations=new S4(this._client),this.speech=new A4(this._client)}}nX.Transcriptions=P4;nX.Translations=S4;nX.Speech=A4;class U8 extends L{create(X,Y){return this._client.post("/batches",{body:X,...Y})}retrieve(X,Y){return this._client.get(F`/batches/${X}`,Y)}list(X={},Y){return this._client.getAPIList("/batches",_,{query:X,...Y})}cancel(X,Y){return this._client.post(F`/batches/${X}/cancel`,Y)}}class R4 extends L{create(X,Y){return this._client.post("/assistants",{body:X,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}retrieve(X,Y){return this._client.get(F`/assistants/${X}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}update(X,Y,$){return this._client.post(F`/assistants/${X}`,{body:Y,...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}list(X={},Y){return this._client.getAPIList("/assistants",_,{query:X,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}delete(X,Y){return this._client.delete(F`/assistants/${X}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}}class C4 extends L{create(X,Y){return this._client.post("/realtime/sessions",{body:X,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}}class I4 extends L{create(X,Y){return this._client.post("/realtime/transcription_sessions",{body:X,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}}class k0 extends L{constructor(){super(...arguments);this.sessions=new C4(this._client),this.transcriptionSessions=new I4(this._client)}}k0.Sessions=C4;k0.TranscriptionSessions=I4;class j4 extends L{create(X,Y){return this._client.post("/chatkit/sessions",{body:X,...Y,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},Y?.headers])})}cancel(X,Y){return this._client.post(F`/chatkit/sessions/${X}/cancel`,{...Y,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},Y?.headers])})}}class _4 extends L{retrieve(X,Y){return this._client.get(F`/chatkit/threads/${X}`,{...Y,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},Y?.headers])})}list(X={},Y){return this._client.getAPIList("/chatkit/threads",J0,{query:X,...Y,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},Y?.headers])})}delete(X,Y){return this._client.delete(F`/chatkit/threads/${X}`,{...Y,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},Y?.headers])})}listItems(X,Y={},$){return this._client.getAPIList(F`/chatkit/threads/${X}/items`,J0,{query:Y,...$,headers:x([{"OpenAI-Beta":"chatkit_beta=v1"},$?.headers])})}}class v0 extends L{constructor(){super(...arguments);this.sessions=new j4(this._client),this.threads=new _4(this._client)}}v0.Sessions=j4;v0.Threads=_4;class y4 extends L{create(X,Y,$){return this._client.post(F`/threads/${X}/messages`,{body:Y,...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}retrieve(X,Y,$){let{thread_id:W}=Y;return this._client.get(F`/threads/${W}/messages/${X}`,{...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}update(X,Y,$){let{thread_id:W,...Z}=Y;return this._client.post(F`/threads/${W}/messages/${X}`,{body:Z,...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}list(X,Y={},$){return this._client.getAPIList(F`/threads/${X}/messages`,_,{query:Y,...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}delete(X,Y,$){let{thread_id:W}=Y;return this._client.delete(F`/threads/${W}/messages/${X}`,{...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}}class k4 extends L{retrieve(X,Y,$){let{thread_id:W,run_id:Z,...Q}=Y;return this._client.get(F`/threads/${W}/runs/${Z}/steps/${X}`,{query:Q,...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}list(X,Y,$){let{thread_id:W,...Z}=Y;return this._client.getAPIList(F`/threads/${W}/runs/${X}/steps`,_,{query:Z,...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}}var M5=(X)=>{if(typeof Buffer<"u"){let Y=Buffer.from(X,"base64");return Array.from(new Float32Array(Y.buffer,Y.byteOffset,Y.length/Float32Array.BYTES_PER_ELEMENT))}else{let Y=atob(X),$=Y.length,W=new Uint8Array($);for(let Z=0;Z<$;Z++)W[Z]=Y.charCodeAt(Z);return Array.from(new Float32Array(W.buffer))}};var z0=(X)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[X]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(X)?.trim();return};var $X,f0,$9,kX,AY,PX,h0,w8,b0,RY,qX,PY,SY,f4,v4,b4,T5,A5,P5,S5,R5,C5,I5;class H0 extends _0{constructor(){super(...arguments);$X.add(this),$9.set(this,[]),kX.set(this,{}),AY.set(this,{}),PX.set(this,void 0),h0.set(this,void 0),w8.set(this,void 0),b0.set(this,void 0),RY.set(this,void 0),qX.set(this,void 0),PY.set(this,void 0),SY.set(this,void 0),f4.set(this,void 0)}[($9=new WeakMap,kX=new WeakMap,AY=new WeakMap,PX=new WeakMap,h0=new WeakMap,w8=new WeakMap,b0=new WeakMap,RY=new WeakMap,qX=new WeakMap,PY=new WeakMap,SY=new WeakMap,f4=new WeakMap,$X=new WeakSet,Symbol.asyncIterator)](){let X=[],Y=[],$=!1;return this.on("event",(W)=>{let Z=Y.shift();if(Z)Z.resolve(W);else X.push(W)}),this.on("end",()=>{$=!0;for(let W of Y)W.resolve(void 0);Y.length=0}),this.on("abort",(W)=>{$=!0;for(let Z of Y)Z.reject(W);Y.length=0}),this.on("error",(W)=>{$=!0;for(let Z of Y)Z.reject(W);Y.length=0}),{next:async()=>{if(!X.length){if($)return{value:void 0,done:!0};return new Promise((Z,Q)=>Y.push({resolve:Z,reject:Q})).then((Z)=>Z?{value:Z,done:!1}:{value:void 0,done:!0})}return{value:X.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream(X){let Y=new f0;return Y._run(()=>Y._fromReadableStream(X)),Y}async _fromReadableStream(X,Y){let $=Y?.signal;if($){if($.aborted)this.controller.abort();$.addEventListener("abort",()=>this.controller.abort())}this._connected();let W=wX.fromReadableStream(X,this.controller);for await(let Z of W)w(this,$X,"m",v4).call(this,Z);if(W.controller.signal?.aborted)throw new l;return this._addRun(w(this,$X,"m",b4).call(this))}toReadableStream(){return new wX(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(X,Y,$,W){let Z=new f0;return Z._run(()=>Z._runToolAssistantStream(X,Y,$,{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}async _createToolAssistantStream(X,Y,$,W){let Z=W?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}let Q={...$,stream:!0},J=await X.submitToolOutputs(Y,Q,{...W,signal:this.controller.signal});this._connected();for await(let G of J)w(this,$X,"m",v4).call(this,G);if(J.controller.signal?.aborted)throw new l;return this._addRun(w(this,$X,"m",b4).call(this))}static createThreadAssistantStream(X,Y,$){let W=new f0;return W._run(()=>W._threadAssistantStream(X,Y,{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"stream"}})),W}static createAssistantStream(X,Y,$,W){let Z=new f0;return Z._run(()=>Z._runAssistantStream(X,Y,$,{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}currentEvent(){return w(this,PY,"f")}currentRun(){return w(this,SY,"f")}currentMessageSnapshot(){return w(this,PX,"f")}currentRunStepSnapshot(){return w(this,f4,"f")}async finalRunSteps(){return await this.done(),Object.values(w(this,kX,"f"))}async finalMessages(){return await this.done(),Object.values(w(this,AY,"f"))}async finalRun(){if(await this.done(),!w(this,h0,"f"))throw Error("Final run was not received.");return w(this,h0,"f")}async _createThreadAssistantStream(X,Y,$){let W=$?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}let Z={...Y,stream:!0},Q=await X.createAndRun(Z,{...$,signal:this.controller.signal});this._connected();for await(let J of Q)w(this,$X,"m",v4).call(this,J);if(Q.controller.signal?.aborted)throw new l;return this._addRun(w(this,$X,"m",b4).call(this))}async _createAssistantStream(X,Y,$,W){let Z=W?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}let Q={...$,stream:!0},J=await X.create(Y,Q,{...W,signal:this.controller.signal});this._connected();for await(let G of J)w(this,$X,"m",v4).call(this,G);if(J.controller.signal?.aborted)throw new l;return this._addRun(w(this,$X,"m",b4).call(this))}static accumulateDelta(X,Y){for(let[$,W]of Object.entries(Y)){if(!X.hasOwnProperty($)){X[$]=W;continue}let Z=X[$];if(Z===null||Z===void 0){X[$]=W;continue}if($==="index"||$==="type"){X[$]=W;continue}if(typeof Z==="string"&&typeof W==="string")Z+=W;else if(typeof Z==="number"&&typeof W==="number")Z+=W;else if(z4(Z)&&z4(W))Z=this.accumulateDelta(Z,W);else if(Array.isArray(Z)&&Array.isArray(W)){if(Z.every((Q)=>typeof Q==="string"||typeof Q==="number")){Z.push(...W);continue}for(let Q of W){if(!z4(Q))throw Error(`Expected array delta entry to be an object but got: ${Q}`);let J=Q.index;if(J==null)throw console.error(Q),Error("Expected array delta entry to have an `index` property");if(typeof J!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${J}`);let G=Z[J];if(G==null)Z.push(Q);else Z[J]=this.accumulateDelta(G,Q)}continue}else throw Error(`Unhandled record type: ${$}, deltaValue: ${W}, accValue: ${Z}`);X[$]=Z}return X}_addRun(X){return X}async _threadAssistantStream(X,Y,$){return await this._createThreadAssistantStream(Y,X,$)}async _runAssistantStream(X,Y,$,W){return await this._createAssistantStream(Y,X,$,W)}async _runToolAssistantStream(X,Y,$,W){return await this._createToolAssistantStream(Y,X,$,W)}}f0=H0,v4=function(Y){if(this.ended)return;switch(A(this,PY,Y,"f"),w(this,$X,"m",P5).call(this,Y),Y.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":w(this,$X,"m",I5).call(this,Y);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":w(this,$X,"m",A5).call(this,Y);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":w(this,$X,"m",T5).call(this,Y);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:xQ(Y)}},b4=function(){if(this.ended)throw new D("stream has ended, this shouldn't happen");if(!w(this,h0,"f"))throw Error("Final run has not been received");return w(this,h0,"f")},T5=function(Y){let[$,W]=w(this,$X,"m",R5).call(this,Y,w(this,PX,"f"));A(this,PX,$,"f"),w(this,AY,"f")[$.id]=$;for(let Z of W){let Q=$.content[Z.index];if(Q?.type=="text")this._emit("textCreated",Q.text)}switch(Y.event){case"thread.message.created":this._emit("messageCreated",Y.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",Y.data.delta,$),Y.data.delta.content)for(let Z of Y.data.delta.content){if(Z.type=="text"&&Z.text){let Q=Z.text,J=$.content[Z.index];if(J&&J.type=="text")this._emit("textDelta",Q,J.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(Z.index!=w(this,w8,"f")){if(w(this,b0,"f"))switch(w(this,b0,"f").type){case"text":this._emit("textDone",w(this,b0,"f").text,w(this,PX,"f"));break;case"image_file":this._emit("imageFileDone",w(this,b0,"f").image_file,w(this,PX,"f"));break}A(this,w8,Z.index,"f")}A(this,b0,$.content[Z.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(w(this,w8,"f")!==void 0){let Z=Y.data.content[w(this,w8,"f")];if(Z)switch(Z.type){case"image_file":this._emit("imageFileDone",Z.image_file,w(this,PX,"f"));break;case"text":this._emit("textDone",Z.text,w(this,PX,"f"));break}}if(w(this,PX,"f"))this._emit("messageDone",Y.data);A(this,PX,void 0,"f")}},A5=function(Y){let $=w(this,$X,"m",S5).call(this,Y);switch(A(this,f4,$,"f"),Y.event){case"thread.run.step.created":this._emit("runStepCreated",Y.data);break;case"thread.run.step.delta":let W=Y.data.delta;if(W.step_details&&W.step_details.type=="tool_calls"&&W.step_details.tool_calls&&$.step_details.type=="tool_calls")for(let Q of W.step_details.tool_calls)if(Q.index==w(this,RY,"f"))this._emit("toolCallDelta",Q,$.step_details.tool_calls[Q.index]);else{if(w(this,qX,"f"))this._emit("toolCallDone",w(this,qX,"f"));if(A(this,RY,Q.index,"f"),A(this,qX,$.step_details.tool_calls[Q.index],"f"),w(this,qX,"f"))this._emit("toolCallCreated",w(this,qX,"f"))}this._emit("runStepDelta",Y.data.delta,$);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(A(this,f4,void 0,"f"),Y.data.step_details.type=="tool_calls"){if(w(this,qX,"f"))this._emit("toolCallDone",w(this,qX,"f")),A(this,qX,void 0,"f")}this._emit("runStepDone",Y.data,$);break;case"thread.run.step.in_progress":break}},P5=function(Y){w(this,$9,"f").push(Y),this._emit("event",Y)},S5=function(Y){switch(Y.event){case"thread.run.step.created":return w(this,kX,"f")[Y.data.id]=Y.data,Y.data;case"thread.run.step.delta":let $=w(this,kX,"f")[Y.data.id];if(!$)throw Error("Received a RunStepDelta before creation of a snapshot");let W=Y.data;if(W.delta){let Z=f0.accumulateDelta($,W.delta);w(this,kX,"f")[Y.data.id]=Z}return w(this,kX,"f")[Y.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":w(this,kX,"f")[Y.data.id]=Y.data;break}if(w(this,kX,"f")[Y.data.id])return w(this,kX,"f")[Y.data.id];throw Error("No snapshot available")},R5=function(Y,$){let W=[];switch(Y.event){case"thread.message.created":return[Y.data,W];case"thread.message.delta":if(!$)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let Z=Y.data;if(Z.delta.content)for(let Q of Z.delta.content)if(Q.index in $.content){let J=$.content[Q.index];$.content[Q.index]=w(this,$X,"m",C5).call(this,Q,J)}else $.content[Q.index]=Q,W.push(Q);return[$,W];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if($)return[$,W];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},C5=function(Y,$){return f0.accumulateDelta($,Y)},I5=function(Y){switch(A(this,SY,Y.data,"f"),Y.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":if(A(this,h0,Y.data,"f"),w(this,qX,"f"))this._emit("toolCallDone",w(this,qX,"f")),A(this,qX,void 0,"f");break;case"thread.run.cancelling":break}};function xQ(X){}class q8 extends L{constructor(){super(...arguments);this.steps=new k4(this._client)}create(X,Y,$){let{include:W,...Z}=Y;return this._client.post(F`/threads/${X}/runs`,{query:{include:W},body:Z,...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers]),stream:Y.stream??!1})}retrieve(X,Y,$){let{thread_id:W}=Y;return this._client.get(F`/threads/${W}/runs/${X}`,{...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}update(X,Y,$){let{thread_id:W,...Z}=Y;return this._client.post(F`/threads/${W}/runs/${X}`,{body:Z,...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}list(X,Y={},$){return this._client.getAPIList(F`/threads/${X}/runs`,_,{query:Y,...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}cancel(X,Y,$){let{thread_id:W}=Y;return this._client.post(F`/threads/${W}/runs/${X}/cancel`,{...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}async createAndPoll(X,Y,$){let W=await this.create(X,Y,$);return await this.poll(W.id,{thread_id:X},$)}createAndStream(X,Y,$){return H0.createAssistantStream(X,this._client.beta.threads.runs,Y,$)}async poll(X,Y,$){let W=x([$?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":$?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:Z,response:Q}=await this.retrieve(X,Y,{...$,headers:{...$?.headers,...W}}).withResponse();switch(Z.status){case"queued":case"in_progress":case"cancelling":let J=5000;if($?.pollIntervalMs)J=$.pollIntervalMs;else{let G=Q.headers.get("openai-poll-after-ms");if(G){let z=parseInt(G);if(!isNaN(z))J=z}}await _X(J);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return Z}}}stream(X,Y,$){return H0.createAssistantStream(X,this._client.beta.threads.runs,Y,$)}submitToolOutputs(X,Y,$){let{thread_id:W,...Z}=Y;return this._client.post(F`/threads/${W}/runs/${X}/submit_tool_outputs`,{body:Z,...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers]),stream:Y.stream??!1})}async submitToolOutputsAndPoll(X,Y,$){let W=await this.submitToolOutputs(X,Y,$);return await this.poll(W.id,Y,$)}submitToolOutputsStream(X,Y,$){return H0.createToolAssistantStream(X,this._client.beta.threads.runs,Y,$)}}q8.Steps=k4;class g0 extends L{constructor(){super(...arguments);this.runs=new q8(this._client),this.messages=new y4(this._client)}create(X={},Y){return this._client.post("/threads",{body:X,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}retrieve(X,Y){return this._client.get(F`/threads/${X}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}update(X,Y,$){return this._client.post(F`/threads/${X}`,{body:Y,...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}delete(X,Y){return this._client.delete(F`/threads/${X}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}createAndRun(X,Y){return this._client.post("/threads/runs",{body:X,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),stream:X.stream??!1})}async createAndRunPoll(X,Y){let $=await this.createAndRun(X,Y);return await this.runs.poll($.id,{thread_id:$.thread_id},Y)}createAndRunStream(X,Y){return H0.createThreadAssistantStream(X,this._client.beta.threads,Y)}}g0.Runs=q8;g0.Messages=y4;class vX extends L{constructor(){super(...arguments);this.realtime=new k0(this._client),this.chatkit=new v0(this._client),this.assistants=new R4(this._client),this.threads=new g0(this._client)}}vX.Realtime=k0;vX.ChatKit=v0;vX.Assistants=R4;vX.Threads=g0;class F8 extends L{create(X,Y){return this._client.post("/completions",{body:X,...Y,stream:X.stream??!1})}}class h4 extends L{retrieve(X,Y,$){let{container_id:W}=Y;return this._client.get(F`/containers/${W}/files/${X}/content`,{...$,headers:x([{Accept:"application/binary"},$?.headers]),__binaryResponse:!0})}}class L8 extends L{constructor(){super(...arguments);this.content=new h4(this._client)}create(X,Y,$){return this._client.post(F`/containers/${X}/files`,pX({body:Y,...$},this._client))}retrieve(X,Y,$){let{container_id:W}=Y;return this._client.get(F`/containers/${W}/files/${X}`,$)}list(X,Y={},$){return this._client.getAPIList(F`/containers/${X}/files`,_,{query:Y,...$})}delete(X,Y,$){let{container_id:W}=Y;return this._client.delete(F`/containers/${W}/files/${X}`,{...$,headers:x([{Accept:"*/*"},$?.headers])})}}L8.Content=h4;class u0 extends L{constructor(){super(...arguments);this.files=new L8(this._client)}create(X,Y){return this._client.post("/containers",{body:X,...Y})}retrieve(X,Y){return this._client.get(F`/containers/${X}`,Y)}list(X={},Y){return this._client.getAPIList("/containers",_,{query:X,...Y})}delete(X,Y){return this._client.delete(F`/containers/${X}`,{...Y,headers:x([{Accept:"*/*"},Y?.headers])})}}u0.Files=L8;class g4 extends L{create(X,Y,$){let{include:W,...Z}=Y;return this._client.post(F`/conversations/${X}/items`,{query:{include:W},body:Z,...$})}retrieve(X,Y,$){let{conversation_id:W,...Z}=Y;return this._client.get(F`/conversations/${W}/items/${X}`,{query:Z,...$})}list(X,Y={},$){return this._client.getAPIList(F`/conversations/${X}/items`,J0,{query:Y,...$})}delete(X,Y,$){let{conversation_id:W}=Y;return this._client.delete(F`/conversations/${W}/items/${X}`,$)}}class d0 extends L{constructor(){super(...arguments);this.items=new g4(this._client)}create(X={},Y){return this._client.post("/conversations",{body:X,...Y})}retrieve(X,Y){return this._client.get(F`/conversations/${X}`,Y)}update(X,Y,$){return this._client.post(F`/conversations/${X}`,{body:Y,...$})}delete(X,Y){return this._client.delete(F`/conversations/${X}`,Y)}}d0.Items=g4;class E8 extends L{create(X,Y){let $=!!X.encoding_format,W=$?X.encoding_format:"base64";if($)i(this._client).debug("embeddings/user defined encoding_format:",X.encoding_format);let Z=this._client.post("/embeddings",{body:{...X,encoding_format:W},...Y});if($)return Z;return i(this._client).debug("embeddings/decoding base64 embeddings from base64"),Z._thenUnwrap((Q)=>{if(Q&&Q.data)Q.data.forEach((J)=>{let G=J.embedding;J.embedding=M5(G)});return Q})}}class u4 extends L{retrieve(X,Y,$){let{eval_id:W,run_id:Z}=Y;return this._client.get(F`/evals/${W}/runs/${Z}/output_items/${X}`,$)}list(X,Y,$){let{eval_id:W,...Z}=Y;return this._client.getAPIList(F`/evals/${W}/runs/${X}/output_items`,_,{query:Z,...$})}}class x8 extends L{constructor(){super(...arguments);this.outputItems=new u4(this._client)}create(X,Y,$){return this._client.post(F`/evals/${X}/runs`,{body:Y,...$})}retrieve(X,Y,$){let{eval_id:W}=Y;return this._client.get(F`/evals/${W}/runs/${X}`,$)}list(X,Y={},$){return this._client.getAPIList(F`/evals/${X}/runs`,_,{query:Y,...$})}delete(X,Y,$){let{eval_id:W}=Y;return this._client.delete(F`/evals/${W}/runs/${X}`,$)}cancel(X,Y,$){let{eval_id:W}=Y;return this._client.post(F`/evals/${W}/runs/${X}`,$)}}x8.OutputItems=u4;class m0 extends L{constructor(){super(...arguments);this.runs=new x8(this._client)}create(X,Y){return this._client.post("/evals",{body:X,...Y})}retrieve(X,Y){return this._client.get(F`/evals/${X}`,Y)}update(X,Y,$){return this._client.post(F`/evals/${X}`,{body:Y,...$})}list(X={},Y){return this._client.getAPIList("/evals",_,{query:X,...Y})}delete(X,Y){return this._client.delete(F`/evals/${X}`,Y)}}m0.Runs=x8;class O8 extends L{create(X,Y){return this._client.post("/files",AX({body:X,...Y},this._client))}retrieve(X,Y){return this._client.get(F`/files/${X}`,Y)}list(X={},Y){return this._client.getAPIList("/files",_,{query:X,...Y})}delete(X,Y){return this._client.delete(F`/files/${X}`,Y)}content(X,Y){return this._client.get(F`/files/${X}/content`,{...Y,headers:x([{Accept:"application/binary"},Y?.headers]),__binaryResponse:!0})}async waitForProcessing(X,{pollInterval:Y=5000,maxWait:$=1800000}={}){let W=new Set(["processed","error","deleted"]),Z=Date.now(),Q=await this.retrieve(X);while(!Q.status||!W.has(Q.status))if(await _X(Y),Q=await this.retrieve(X),Date.now()-Z>$)throw new uX({message:`Giving up on waiting for file ${X} to finish processing after ${$} milliseconds.`});return Q}}class d4 extends L{}class m4 extends L{run(X,Y){return this._client.post("/fine_tuning/alpha/graders/run",{body:X,...Y})}validate(X,Y){return this._client.post("/fine_tuning/alpha/graders/validate",{body:X,...Y})}}class D8 extends L{constructor(){super(...arguments);this.graders=new m4(this._client)}}D8.Graders=m4;class c4 extends L{create(X,Y,$){return this._client.getAPIList(F`/fine_tuning/checkpoints/${X}/permissions`,cX,{body:Y,method:"post",...$})}retrieve(X,Y={},$){return this._client.get(F`/fine_tuning/checkpoints/${X}/permissions`,{query:Y,...$})}delete(X,Y,$){let{fine_tuned_model_checkpoint:W}=Y;return this._client.delete(F`/fine_tuning/checkpoints/${W}/permissions/${X}`,$)}}class M8 extends L{constructor(){super(...arguments);this.permissions=new c4(this._client)}}M8.Permissions=c4;class p4 extends L{list(X,Y={},$){return this._client.getAPIList(F`/fine_tuning/jobs/${X}/checkpoints`,_,{query:Y,...$})}}class T8 extends L{constructor(){super(...arguments);this.checkpoints=new p4(this._client)}create(X,Y){return this._client.post("/fine_tuning/jobs",{body:X,...Y})}retrieve(X,Y){return this._client.get(F`/fine_tuning/jobs/${X}`,Y)}list(X={},Y){return this._client.getAPIList("/fine_tuning/jobs",_,{query:X,...Y})}cancel(X,Y){return this._client.post(F`/fine_tuning/jobs/${X}/cancel`,Y)}listEvents(X,Y={},$){return this._client.getAPIList(F`/fine_tuning/jobs/${X}/events`,_,{query:Y,...$})}pause(X,Y){return this._client.post(F`/fine_tuning/jobs/${X}/pause`,Y)}resume(X,Y){return this._client.post(F`/fine_tuning/jobs/${X}/resume`,Y)}}T8.Checkpoints=p4;class bX extends L{constructor(){super(...arguments);this.methods=new d4(this._client),this.jobs=new T8(this._client),this.checkpoints=new M8(this._client),this.alpha=new D8(this._client)}}bX.Methods=d4;bX.Jobs=T8;bX.Checkpoints=M8;bX.Alpha=D8;class l4 extends L{}class c0 extends L{constructor(){super(...arguments);this.graderModels=new l4(this._client)}}c0.GraderModels=l4;class A8 extends L{createVariation(X,Y){return this._client.post("/images/variations",AX({body:X,...Y},this._client))}edit(X,Y){return this._client.post("/images/edits",AX({body:X,...Y,stream:X.stream??!1},this._client))}generate(X,Y){return this._client.post("/images/generations",{body:X,...Y,stream:X.stream??!1})}}class P8 extends L{retrieve(X,Y){return this._client.get(F`/models/${X}`,Y)}list(X){return this._client.getAPIList("/models",cX,X)}delete(X,Y){return this._client.delete(F`/models/${X}`,Y)}}class S8 extends L{create(X,Y){return this._client.post("/moderations",{body:X,...Y})}}class i4 extends L{accept(X,Y,$){return this._client.post(F`/realtime/calls/${X}/accept`,{body:Y,...$,headers:x([{Accept:"*/*"},$?.headers])})}hangup(X,Y){return this._client.post(F`/realtime/calls/${X}/hangup`,{...Y,headers:x([{Accept:"*/*"},Y?.headers])})}refer(X,Y,$){return this._client.post(F`/realtime/calls/${X}/refer`,{body:Y,...$,headers:x([{Accept:"*/*"},$?.headers])})}reject(X,Y={},$){return this._client.post(F`/realtime/calls/${X}/reject`,{body:Y,...$,headers:x([{Accept:"*/*"},$?.headers])})}}class n4 extends L{create(X,Y){return this._client.post("/realtime/client_secrets",{body:X,...Y})}}class B0 extends L{constructor(){super(...arguments);this.clientSecrets=new n4(this._client),this.calls=new i4(this._client)}}B0.ClientSecrets=n4;B0.Calls=i4;function j5(X,Y){if(!Y||!gQ(Y))return{...X,output_parsed:null,output:X.output.map(($)=>{if($.type==="function_call")return{...$,parsed_arguments:null};if($.type==="message")return{...$,content:$.content.map((W)=>({...W,parsed:null}))};else return $})};return W9(X,Y)}function W9(X,Y){let $=X.output.map((Z)=>{if(Z.type==="function_call")return{...Z,parsed_arguments:mQ(Y,Z)};if(Z.type==="message"){let Q=Z.content.map((J)=>{if(J.type==="output_text")return{...J,parsed:hQ(Y,J.text)};return J});return{...Z,content:Q}}return Z}),W=Object.assign({},X,{output:$});if(!Object.getOwnPropertyDescriptor(X,"output_text"))CY(W);return Object.defineProperty(W,"output_parsed",{enumerable:!0,get(){for(let Z of W.output){if(Z.type!=="message")continue;for(let Q of Z.content)if(Q.type==="output_text"&&Q.parsed!==null)return Q.parsed}return null}}),W}function hQ(X,Y){if(X.text?.format?.type!=="json_schema")return null;if("$parseRaw"in X.text?.format)return(X.text?.format).$parseRaw(Y);return JSON.parse(Y)}function gQ(X){if(F4(X.text?.format))return!0;return!1}function uQ(X){return X?.$brand==="auto-parseable-tool"}function dQ(X,Y){return X.find(($)=>$.type==="function"&&$.name===Y)}function mQ(X,Y){let $=dQ(X.tools??[],Y.name);return{...Y,...Y,parsed_arguments:uQ($)?$.$parseRaw(Y.arguments):$?.strict?JSON.parse(Y.arguments):null}}function CY(X){let Y=[];for(let $ of X.output){if($.type!=="message")continue;for(let W of $.content)if(W.type==="output_text")Y.push(W.text)}X.output_text=Y.join("")}var R8,IY,N0,jY,_5,y5,k5,v5;class _Y extends _0{constructor(X){super();R8.add(this),IY.set(this,void 0),N0.set(this,void 0),jY.set(this,void 0),A(this,IY,X,"f")}static createResponse(X,Y,$){let W=new _Y(Y);return W._run(()=>W._createOrRetrieveResponse(X,Y,{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"stream"}})),W}async _createOrRetrieveResponse(X,Y,$){let W=$?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}w(this,R8,"m",_5).call(this);let Z,Q=null;if("response_id"in Y)Z=await X.responses.retrieve(Y.response_id,{stream:!0},{...$,signal:this.controller.signal,stream:!0}),Q=Y.starting_after??null;else Z=await X.responses.create({...Y,stream:!0},{...$,signal:this.controller.signal});this._connected();for await(let J of Z)w(this,R8,"m",y5).call(this,J,Q);if(Z.controller.signal?.aborted)throw new l;return w(this,R8,"m",k5).call(this)}[(IY=new WeakMap,N0=new WeakMap,jY=new WeakMap,R8=new WeakSet,_5=function(){if(this.ended)return;A(this,N0,void 0,"f")},y5=function(Y,$){if(this.ended)return;let W=(Q,J)=>{if($==null||J.sequence_number>$)this._emit(Q,J)},Z=w(this,R8,"m",v5).call(this,Y);switch(W("event",Y),Y.type){case"response.output_text.delta":{let Q=Z.output[Y.output_index];if(!Q)throw new D(`missing output at index ${Y.output_index}`);if(Q.type==="message"){let J=Q.content[Y.content_index];if(!J)throw new D(`missing content at index ${Y.content_index}`);if(J.type!=="output_text")throw new D(`expected content to be 'output_text', got ${J.type}`);W("response.output_text.delta",{...Y,snapshot:J.text})}break}case"response.function_call_arguments.delta":{let Q=Z.output[Y.output_index];if(!Q)throw new D(`missing output at index ${Y.output_index}`);if(Q.type==="function_call")W("response.function_call_arguments.delta",{...Y,snapshot:Q.arguments});break}default:W(Y.type,Y);break}},k5=function(){if(this.ended)throw new D("stream has ended, this shouldn't happen");let Y=w(this,N0,"f");if(!Y)throw new D("request ended without sending any events");A(this,N0,void 0,"f");let $=cQ(Y,w(this,IY,"f"));return A(this,jY,$,"f"),$},v5=function(Y){let $=w(this,N0,"f");if(!$){if(Y.type!=="response.created")throw new D(`When snapshot hasn't been set yet, expected 'response.created' event, got ${Y.type}`);return $=A(this,N0,Y.response,"f"),$}switch(Y.type){case"response.output_item.added":{$.output.push(Y.item);break}case"response.content_part.added":{let W=$.output[Y.output_index];if(!W)throw new D(`missing output at index ${Y.output_index}`);let Z=W.type,Q=Y.part;if(Z==="message"&&Q.type!=="reasoning_text")W.content.push(Q);else if(Z==="reasoning"&&Q.type==="reasoning_text"){if(!W.content)W.content=[];W.content.push(Q)}break}case"response.output_text.delta":{let W=$.output[Y.output_index];if(!W)throw new D(`missing output at index ${Y.output_index}`);if(W.type==="message"){let Z=W.content[Y.content_index];if(!Z)throw new D(`missing content at index ${Y.content_index}`);if(Z.type!=="output_text")throw new D(`expected content to be 'output_text', got ${Z.type}`);Z.text+=Y.delta}break}case"response.function_call_arguments.delta":{let W=$.output[Y.output_index];if(!W)throw new D(`missing output at index ${Y.output_index}`);if(W.type==="function_call")W.arguments+=Y.delta;break}case"response.reasoning_text.delta":{let W=$.output[Y.output_index];if(!W)throw new D(`missing output at index ${Y.output_index}`);if(W.type==="reasoning"){let Z=W.content?.[Y.content_index];if(!Z)throw new D(`missing content at index ${Y.content_index}`);if(Z.type!=="reasoning_text")throw new D(`expected content to be 'reasoning_text', got ${Z.type}`);Z.text+=Y.delta}break}case"response.completed":{A(this,N0,Y.response,"f");break}}return $},Symbol.asyncIterator)](){let X=[],Y=[],$=!1;return this.on("event",(W)=>{let Z=Y.shift();if(Z)Z.resolve(W);else X.push(W)}),this.on("end",()=>{$=!0;for(let W of Y)W.resolve(void 0);Y.length=0}),this.on("abort",(W)=>{$=!0;for(let Z of Y)Z.reject(W);Y.length=0}),this.on("error",(W)=>{$=!0;for(let Z of Y)Z.reject(W);Y.length=0}),{next:async()=>{if(!X.length){if($)return{value:void 0,done:!0};return new Promise((Z,Q)=>Y.push({resolve:Z,reject:Q})).then((Z)=>Z?{value:Z,done:!1}:{value:void 0,done:!0})}return{value:X.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}async finalResponse(){await this.done();let X=w(this,jY,"f");if(!X)throw new D("stream ended without producing a ChatCompletion");return X}}function cQ(X,Y){return j5(X,Y)}class r4 extends L{list(X,Y={},$){return this._client.getAPIList(F`/responses/${X}/input_items`,_,{query:Y,...$})}}class a4 extends L{count(X={},Y){return this._client.post("/responses/input_tokens",{body:X,...Y})}}class U0 extends L{constructor(){super(...arguments);this.inputItems=new r4(this._client),this.inputTokens=new a4(this._client)}create(X,Y){return this._client.post("/responses",{body:X,...Y,stream:X.stream??!1})._thenUnwrap(($)=>{if("object"in $&&$.object==="response")CY($);return $})}retrieve(X,Y={},$){return this._client.get(F`/responses/${X}`,{query:Y,...$,stream:Y?.stream??!1})._thenUnwrap((W)=>{if("object"in W&&W.object==="response")CY(W);return W})}delete(X,Y){return this._client.delete(F`/responses/${X}`,{...Y,headers:x([{Accept:"*/*"},Y?.headers])})}parse(X,Y){return this._client.responses.create(X,Y)._thenUnwrap(($)=>W9($,X))}stream(X,Y){return _Y.createResponse(this._client,X,Y)}cancel(X,Y){return this._client.post(F`/responses/${X}/cancel`,Y)}compact(X,Y){return this._client.post("/responses/compact",{body:X,...Y})}}U0.InputItems=r4;U0.InputTokens=a4;class t4 extends L{retrieve(X,Y){return this._client.get(F`/skills/${X}/content`,{...Y,headers:x([{Accept:"application/binary"},Y?.headers]),__binaryResponse:!0})}}class s4 extends L{retrieve(X,Y,$){let{skill_id:W}=Y;return this._client.get(F`/skills/${W}/versions/${X}/content`,{...$,headers:x([{Accept:"application/binary"},$?.headers]),__binaryResponse:!0})}}class C8 extends L{constructor(){super(...arguments);this.content=new s4(this._client)}create(X,Y={},$){return this._client.post(F`/skills/${X}/versions`,pX({body:Y,...$},this._client))}retrieve(X,Y,$){let{skill_id:W}=Y;return this._client.get(F`/skills/${W}/versions/${X}`,$)}list(X,Y={},$){return this._client.getAPIList(F`/skills/${X}/versions`,_,{query:Y,...$})}delete(X,Y,$){let{skill_id:W}=Y;return this._client.delete(F`/skills/${W}/versions/${X}`,$)}}C8.Content=s4;class w0 extends L{constructor(){super(...arguments);this.content=new t4(this._client),this.versions=new C8(this._client)}create(X={},Y){return this._client.post("/skills",pX({body:X,...Y},this._client))}retrieve(X,Y){return this._client.get(F`/skills/${X}`,Y)}update(X,Y,$){return this._client.post(F`/skills/${X}`,{body:Y,...$})}list(X={},Y){return this._client.getAPIList("/skills",_,{query:X,...Y})}delete(X,Y){return this._client.delete(F`/skills/${X}`,Y)}}w0.Content=t4;w0.Versions=C8;class o4 extends L{create(X,Y,$){return this._client.post(F`/uploads/${X}/parts`,AX({body:Y,...$},this._client))}}class p0 extends L{constructor(){super(...arguments);this.parts=new o4(this._client)}create(X,Y){return this._client.post("/uploads",{body:X,...Y})}cancel(X,Y){return this._client.post(F`/uploads/${X}/cancel`,Y)}complete(X,Y,$){return this._client.post(F`/uploads/${X}/complete`,{body:Y,...$})}}p0.Parts=o4;var b5=async(X)=>{let Y=await Promise.allSettled(X),$=Y.filter((Z)=>Z.status==="rejected");if($.length){for(let Z of $)console.error(Z.reason);throw Error(`${$.length} promise(s) failed - see the above errors`)}let W=[];for(let Z of Y)if(Z.status==="fulfilled")W.push(Z.value);return W};class e4 extends L{create(X,Y,$){return this._client.post(F`/vector_stores/${X}/file_batches`,{body:Y,...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}retrieve(X,Y,$){let{vector_store_id:W}=Y;return this._client.get(F`/vector_stores/${W}/file_batches/${X}`,{...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}cancel(X,Y,$){let{vector_store_id:W}=Y;return this._client.post(F`/vector_stores/${W}/file_batches/${X}/cancel`,{...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}async createAndPoll(X,Y,$){let W=await this.create(X,Y);return await this.poll(X,W.id,$)}listFiles(X,Y,$){let{vector_store_id:W,...Z}=Y;return this._client.getAPIList(F`/vector_stores/${W}/file_batches/${X}/files`,_,{query:Z,...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}async poll(X,Y,$){let W=x([$?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":$?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:Z,response:Q}=await this.retrieve(Y,{vector_store_id:X},{...$,headers:W}).withResponse();switch(Z.status){case"in_progress":let J=5000;if($?.pollIntervalMs)J=$.pollIntervalMs;else{let G=Q.headers.get("openai-poll-after-ms");if(G){let z=parseInt(G);if(!isNaN(z))J=z}}await _X(J);break;case"failed":case"cancelled":case"completed":return Z}}}async uploadAndPoll(X,{files:Y,fileIds:$=[]},W){if(Y==null||Y.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let Z=W?.maxConcurrency??5,Q=Math.min(Z,Y.length),J=this._client,G=Y.values(),z=[...$];async function B(V){for(let K of V){let U=await J.files.create({file:K,purpose:"assistants"},W);z.push(U.id)}}let H=Array(Q).fill(G).map(B);return await b5(H),await this.createAndPoll(X,{file_ids:z})}}class X7 extends L{create(X,Y,$){return this._client.post(F`/vector_stores/${X}/files`,{body:Y,...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}retrieve(X,Y,$){let{vector_store_id:W}=Y;return this._client.get(F`/vector_stores/${W}/files/${X}`,{...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}update(X,Y,$){let{vector_store_id:W,...Z}=Y;return this._client.post(F`/vector_stores/${W}/files/${X}`,{body:Z,...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}list(X,Y={},$){return this._client.getAPIList(F`/vector_stores/${X}/files`,_,{query:Y,...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}delete(X,Y,$){let{vector_store_id:W}=Y;return this._client.delete(F`/vector_stores/${W}/files/${X}`,{...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}async createAndPoll(X,Y,$){let W=await this.create(X,Y,$);return await this.poll(X,W.id,$)}async poll(X,Y,$){let W=x([$?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":$?.pollIntervalMs?.toString()??void 0}]);while(!0){let Z=await this.retrieve(Y,{vector_store_id:X},{...$,headers:W}).withResponse(),Q=Z.data;switch(Q.status){case"in_progress":let J=5000;if($?.pollIntervalMs)J=$.pollIntervalMs;else{let G=Z.response.headers.get("openai-poll-after-ms");if(G){let z=parseInt(G);if(!isNaN(z))J=z}}await _X(J);break;case"failed":case"completed":return Q}}}async upload(X,Y,$){let W=await this._client.files.create({file:Y,purpose:"assistants"},$);return this.create(X,{file_id:W.id},$)}async uploadAndPoll(X,Y,$){let W=await this.upload(X,Y,$);return await this.poll(X,W.id,$)}content(X,Y,$){let{vector_store_id:W}=Y;return this._client.getAPIList(F`/vector_stores/${W}/files/${X}/content`,cX,{...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}}class q0 extends L{constructor(){super(...arguments);this.files=new X7(this._client),this.fileBatches=new e4(this._client)}create(X,Y){return this._client.post("/vector_stores",{body:X,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}retrieve(X,Y){return this._client.get(F`/vector_stores/${X}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}update(X,Y,$){return this._client.post(F`/vector_stores/${X}`,{body:Y,...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}list(X={},Y){return this._client.getAPIList("/vector_stores",_,{query:X,...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}delete(X,Y){return this._client.delete(F`/vector_stores/${X}`,{...Y,headers:x([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}search(X,Y,$){return this._client.getAPIList(F`/vector_stores/${X}/search`,cX,{body:Y,method:"post",...$,headers:x([{"OpenAI-Beta":"assistants=v2"},$?.headers])})}}q0.Files=X7;q0.FileBatches=e4;class I8 extends L{create(X,Y){return this._client.post("/videos",pX({body:X,...Y},this._client))}retrieve(X,Y){return this._client.get(F`/videos/${X}`,Y)}list(X={},Y){return this._client.getAPIList("/videos",J0,{query:X,...Y})}delete(X,Y){return this._client.delete(F`/videos/${X}`,Y)}downloadContent(X,Y={},$){return this._client.get(F`/videos/${X}/content`,{query:Y,...$,headers:x([{Accept:"application/binary"},$?.headers]),__binaryResponse:!0})}remix(X,Y,$){return this._client.post(F`/videos/${X}/remix`,pX({body:Y,...$},this._client))}}var j8,f5,yY;class _8 extends L{constructor(){super(...arguments);j8.add(this)}async unwrap(X,Y,$=this._client.webhookSecret,W=300){return await this.verifySignature(X,Y,$,W),JSON.parse(X)}async verifySignature(X,Y,$=this._client.webhookSecret,W=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!=="function"||typeof crypto.subtle.verify!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");w(this,j8,"m",f5).call(this,$);let Z=x([Y]).values,Q=w(this,j8,"m",yY).call(this,Z,"webhook-signature"),J=w(this,j8,"m",yY).call(this,Z,"webhook-timestamp"),G=w(this,j8,"m",yY).call(this,Z,"webhook-id"),z=parseInt(J,10);if(isNaN(z))throw new dX("Invalid webhook timestamp format");let B=Math.floor(Date.now()/1000);if(B-z>W)throw new dX("Webhook timestamp is too old");if(z>B+W)throw new dX("Webhook timestamp is too new");let H=Q.split(" ").map((E)=>E.startsWith("v1,")?E.substring(3):E),V=$.startsWith("whsec_")?Buffer.from($.replace("whsec_",""),"base64"):Buffer.from($,"utf-8"),K=G?`${G}.${J}.${X}`:`${J}.${X}`,U=await crypto.subtle.importKey("raw",V,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let E of H)try{let I=Buffer.from(E,"base64");if(await crypto.subtle.verify("HMAC",U,I,new TextEncoder().encode(K)))return}catch{continue}throw new dX("The given webhook signature does not match the expected signature")}}j8=new WeakSet,f5=function(Y){if(typeof Y!=="string"||Y.length===0)throw Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},yY=function(Y,$){if(!Y)throw Error("Headers are required");let W=Y.get($);if(W===null||W===void 0)throw Error(`Missing required header: ${$}`);return W};var Z9,Q9,kY,h5;class R{constructor({baseURL:X=z0("OPENAI_BASE_URL"),apiKey:Y=z0("OPENAI_API_KEY"),organization:$=z0("OPENAI_ORG_ID")??null,project:W=z0("OPENAI_PROJECT_ID")??null,webhookSecret:Z=z0("OPENAI_WEBHOOK_SECRET")??null,...Q}={}){if(Z9.add(this),kY.set(this,void 0),this.completions=new F8(this),this.chat=new y0(this),this.embeddings=new E8(this),this.files=new O8(this),this.images=new A8(this),this.audio=new nX(this),this.moderations=new S8(this),this.models=new P8(this),this.fineTuning=new bX(this),this.graders=new c0(this),this.vectorStores=new q0(this),this.webhooks=new _8(this),this.beta=new vX(this),this.batches=new U8(this),this.uploads=new p0(this),this.responses=new U0(this),this.realtime=new B0(this),this.conversations=new d0(this),this.evals=new m0(this),this.containers=new u0(this),this.skills=new w0(this),this.videos=new I8(this),Y===void 0)throw new D("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let J={apiKey:Y,organization:$,project:W,webhookSecret:Z,...Q,baseURL:X||"https://api.openai.com/v1"};if(!J.dangerouslyAllowBrowser&&g6())throw new D(`It looks like you're running in a browser-like environment.
|
|
40
|
+
|
|
41
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
42
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
43
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
44
|
+
|
|
45
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
46
|
+
|
|
47
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
48
|
+
`);this.baseURL=J.baseURL,this.timeout=J.timeout??Q9.DEFAULT_TIMEOUT,this.logger=J.logger??console;let G="warn";this.logLevel=G,this.logLevel=f$(J.logLevel,"ClientOptions.logLevel",this)??f$(z0("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??G,this.fetchOptions=J.fetchOptions,this.maxRetries=J.maxRetries??2,this.fetch=J.fetch??d6(),A(this,kY,c6,"f"),this._options=J,this.apiKey=typeof Y==="string"?Y:"Missing Key",this.organization=$,this.project=W,this.webhookSecret=Z}withOptions(X){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,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...X})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:X,nulls:Y}){return}async authHeaders(X){return x([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(X){return v$(X,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Q0}`}defaultIdempotencyKey(){return`stainless-node-retry-${A$()}`}makeStatusError(X,Y,$,W){return n.generate(X,Y,$,W)}async _callApiKey(){let X=this._options.apiKey;if(typeof X!=="function")return!1;let Y;try{Y=await X()}catch($){if($ instanceof D)throw $;throw new D(`Failed to get token from 'apiKey' function: ${$.message}`,{cause:$})}if(typeof Y!=="string"||!Y)throw new D(`Expected 'apiKey' function argument to return a string but it returned ${Y}`);return this.apiKey=Y,!0}buildURL(X,Y,$){let W=!w(this,Z9,"m",h5).call(this)&&$||this.baseURL,Z=j6(X)?new URL(X):new URL(W+(W.endsWith("/")&&X.startsWith("/")?X.slice(1):X)),Q=this.defaultQuery();if(!_6(Q))Y={...Q,...Y};if(typeof Y==="object"&&Y&&!Array.isArray(Y))Z.search=this.stringifyQuery(Y);return Z.toString()}async prepareOptions(X){await this._callApiKey()}async prepareRequest(X,{url:Y,options:$}){}get(X,Y){return this.methodRequest("get",X,Y)}post(X,Y){return this.methodRequest("post",X,Y)}patch(X,Y){return this.methodRequest("patch",X,Y)}put(X,Y){return this.methodRequest("put",X,Y)}delete(X,Y){return this.methodRequest("delete",X,Y)}methodRequest(X,Y,$){return this.request(Promise.resolve($).then((W)=>{return{method:X,path:Y,...W}}))}request(X,Y=null){return new I0(this,this.makeRequest(X,Y,void 0))}async makeRequest(X,Y,$){let W=await X,Z=W.maxRetries??this.maxRetries;if(Y==null)Y=Z;await this.prepareOptions(W);let{req:Q,url:J,timeout:G}=await this.buildRequest(W,{retryCount:Z-Y});await this.prepareRequest(Q,{url:J,options:W});let z="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),B=$===void 0?"":`, retryOf: ${$}`,H=Date.now();if(i(this).debug(`[${z}] sending request`,mX({retryOfRequestLogID:$,method:W.method,url:J,options:W,headers:Q.headers})),W.signal?.aborted)throw new l;let V=new AbortController,K=await this.fetchWithTimeout(J,Q,G,V).catch(e8),U=Date.now();if(K instanceof globalThis.Error){let T=`retrying, ${Y} attempts remaining`;if(W.signal?.aborted)throw new l;let S=o8(K)||/timed? ?out/i.test(String(K)+("cause"in K?String(K.cause):""));if(Y)return i(this).info(`[${z}] connection ${S?"timed out":"failed"} - ${T}`),i(this).debug(`[${z}] connection ${S?"timed out":"failed"} (${T})`,mX({retryOfRequestLogID:$,url:J,durationMs:U-H,message:K.message})),this.retryRequest(W,Y,$??z);if(i(this).info(`[${z}] connection ${S?"timed out":"failed"} - error; no more retries left`),i(this).debug(`[${z}] connection ${S?"timed out":"failed"} (error; no more retries left)`,mX({retryOfRequestLogID:$,url:J,durationMs:U-H,message:K.message})),S)throw new uX;throw new C0({cause:K})}let E=[...K.headers.entries()].filter(([T])=>T==="x-request-id").map(([T,S])=>", "+T+": "+JSON.stringify(S)).join(""),I=`[${z}${B}${E}] ${Q.method} ${J} ${K.ok?"succeeded":"failed"} with status ${K.status} in ${U-H}ms`;if(!K.ok){let T=await this.shouldRetry(K);if(Y&&T){let b=`retrying, ${Y} attempts remaining`;return await m6(K.body),i(this).info(`${I} - ${b}`),i(this).debug(`[${z}] response error (${b})`,mX({retryOfRequestLogID:$,url:K.url,status:K.status,headers:K.headers,durationMs:U-H})),this.retryRequest(W,Y,$??z,K.headers)}let S=T?"error; no more retries left":"error; not retryable";i(this).info(`${I} - ${S}`);let P=await K.text().catch((b)=>e8(b).message),h=v6(P),f=h?void 0:P;throw i(this).debug(`[${z}] response error (${S})`,mX({retryOfRequestLogID:$,url:K.url,status:K.status,headers:K.headers,message:f,durationMs:Date.now()-H})),this.makeStatusError(K.status,h,f,K.headers)}return i(this).info(I),i(this).debug(`[${z}] response start`,mX({retryOfRequestLogID:$,url:K.url,status:K.status,headers:K.headers,durationMs:U-H})),{response:K,options:W,controller:V,requestLogID:z,retryOfRequestLogID:$,startTime:H}}getAPIList(X,Y,$){return this.requestAPIList(Y,$&&"then"in $?$.then((W)=>({method:"get",path:X,...W})):{method:"get",path:X,...$})}requestAPIList(X,Y){let $=this.makeRequest(Y,null,void 0);return new UY(this,$,X)}async fetchWithTimeout(X,Y,$,W){let{signal:Z,method:Q,...J}=Y||{},G=this._makeAbort(W);if(Z)Z.addEventListener("abort",G,{once:!0});let z=setTimeout(G,$),B=globalThis.ReadableStream&&J.body instanceof globalThis.ReadableStream||typeof J.body==="object"&&J.body!==null&&Symbol.asyncIterator in J.body,H={signal:W.signal,...B?{duplex:"half"}:{},method:"GET",...J};if(Q)H.method=Q.toUpperCase();try{return await this.fetch.call(void 0,X,H)}finally{clearTimeout(z)}}async shouldRetry(X){let Y=X.headers.get("x-should-retry");if(Y==="true")return!0;if(Y==="false")return!1;if(X.status===408)return!0;if(X.status===409)return!0;if(X.status===429)return!0;if(X.status>=500)return!0;return!1}async retryRequest(X,Y,$,W){let Z,Q=W?.get("retry-after-ms");if(Q){let G=parseFloat(Q);if(!Number.isNaN(G))Z=G}let J=W?.get("retry-after");if(J&&!Z){let G=parseFloat(J);if(!Number.isNaN(G))Z=G*1000;else Z=Date.parse(J)-Date.now()}if(!(Z&&0<=Z&&Z<60000)){let G=X.maxRetries??this.maxRetries;Z=this.calculateDefaultRetryTimeoutMillis(Y,G)}return await _X(Z),this.makeRequest(X,Y-1,$)}calculateDefaultRetryTimeoutMillis(X,Y){let Z=Y-X,Q=Math.min(0.5*Math.pow(2,Z),8),J=1-Math.random()*0.25;return Q*J*1000}async buildRequest(X,{retryCount:Y=0}={}){let $={...X},{method:W,path:Z,query:Q,defaultBaseURL:J}=$,G=this.buildURL(Z,Q,J);if("timeout"in $)k6("timeout",$.timeout);$.timeout=$.timeout??this.timeout;let{bodyHeaders:z,body:B}=this.buildBody({options:$}),H=await this.buildHeaders({options:X,method:W,bodyHeaders:z,retryCount:Y});return{req:{method:W,headers:H,...$.signal&&{signal:$.signal},...globalThis.ReadableStream&&B instanceof globalThis.ReadableStream&&{duplex:"half"},...B&&{body:B},...this.fetchOptions??{},...$.fetchOptions??{}},url:G,timeout:$.timeout}}async buildHeaders({options:X,method:Y,bodyHeaders:$,retryCount:W}){let Z={};if(this.idempotencyHeader&&Y!=="get"){if(!X.idempotencyKey)X.idempotencyKey=this.defaultIdempotencyKey();Z[this.idempotencyHeader]=X.idempotencyKey}let Q=x([Z,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(W),...X.timeout?{"X-Stainless-Timeout":String(Math.trunc(X.timeout/1000))}:{},...u6(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(X),this._options.defaultHeaders,$,X.headers]);return this.validateHeaders(Q),Q.values}_makeAbort(X){return()=>X.abort()}buildBody({options:{body:X,headers:Y}}){if(!X)return{bodyHeaders:void 0,body:void 0};let $=x([Y]);if(ArrayBuffer.isView(X)||X instanceof ArrayBuffer||X instanceof DataView||typeof X==="string"&&$.values.has("content-type")||globalThis.Blob&&X instanceof globalThis.Blob||X instanceof FormData||X instanceof URLSearchParams||globalThis.ReadableStream&&X instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:X};else if(typeof X==="object"&&((Symbol.asyncIterator in X)||(Symbol.iterator in X)&&("next"in X)&&typeof X.next==="function"))return{bodyHeaders:void 0,body:QY(X)};else return w(this,kY,"f").call(this,{body:X,headers:$})}}Q9=R,kY=new WeakMap,Z9=new WeakSet,h5=function(){return this.baseURL!=="https://api.openai.com/v1"};R.OpenAI=Q9;R.DEFAULT_TIMEOUT=600000;R.OpenAIError=D;R.APIError=n;R.APIConnectionError=C0;R.APIConnectionTimeoutError=uX;R.APIUserAbortError=l;R.NotFoundError=W4;R.ConflictError=Z4;R.RateLimitError=J4;R.BadRequestError=X4;R.AuthenticationError=Y4;R.InternalServerError=G4;R.PermissionDeniedError=$4;R.UnprocessableEntityError=Q4;R.InvalidWebhookSignatureError=dX;R.toFile=w4;R.Completions=F8;R.Chat=y0;R.Embeddings=E8;R.Files=O8;R.Images=A8;R.Audio=nX;R.Moderations=S8;R.Models=P8;R.FineTuning=bX;R.Graders=c0;R.VectorStores=q0;R.Webhooks=_8;R.Beta=vX;R.Batches=U8;R.Uploads=p0;R.Responses=U0;R.Realtime=B0;R.Conversations=d0;R.Evals=m0;R.Containers=u0;R.Skills=w0;R.Videos=I8;function eQ(X){if(String(X).includes("context_length_exceeded"))return!0;if("message"in X&&typeof X.message==="string"&&(X.message.includes("Input tokens exceed the configured limit")||X.message.includes("exceeds the context window")))return!0;return!1}function fX(X){if(!X||typeof X!=="object")return X;let Y;if(X.constructor.name===uX.name&&"message"in X&&typeof X.message==="string")Y=Error(X.message),Y.name="TimeoutError";else if(X.constructor.name===l.name&&"message"in X&&typeof X.message==="string")Y=Error(X.message),Y.name="AbortError";else if(eQ(X))Y=vY.fromError(X);else if("status"in X&&X.status===400&&"message"in X&&typeof X.message==="string"&&X.message.includes("tool_calls"))Y=s8(X,"INVALID_TOOL_RESULTS");else if("status"in X&&X.status===401)Y=s8(X,"MODEL_AUTHENTICATION");else if("status"in X&&X.status===429)Y=s8(X,"MODEL_RATE_LIMIT");else if("status"in X&&X.status===404)Y=s8(X,"MODEL_NOT_FOUND");else Y=X;return Y}var G9=(X)=>X();function Y7(X){if(!X)return!1;if(/^o\d/.test(X??""))return!0;if(X.startsWith("gpt-5")&&!X.startsWith("gpt-5-chat"))return!0;return!1}function X3(X){if(X.role!=="system"&&X.role!=="developer"&&X.role!=="assistant"&&X.role!=="user"&&X.role!=="function"&&X.role!=="tool")console.warn(`Unknown message role: ${X.role}`);return X.role}function F0(X){let Y=X._getType();switch(Y){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!l0.isInstance(X))throw Error("Invalid generic chat message");return X3(X);default:throw Error(`Unknown message type: ${Y}`)}}function L0(X){let{azureOpenAIApiDeploymentName:Y,azureOpenAIApiInstanceName:$,azureOpenAIApiKey:W,azureOpenAIBasePath:Z,baseURL:Q,azureADTokenProvider:J,azureOpenAIEndpoint:G}=X;if((W||J)&&Z&&Y)return`${Z}/${Y}`;if((W||J)&&G&&Y)return`${G}/openai/deployments/${Y}`;if(W||J){if(!$)throw Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!Y)throw Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${$}.openai.azure.com/openai/deployments/${Y}`}return Q}function K9(X){return typeof Headers<"u"&&X!==null&&typeof X==="object"&&Object.prototype.toString.call(X)==="[object Headers]"}function u5(X){let Y=G9(()=>{if(K9(X))return X;else if(Array.isArray(X))return new Headers(X);else if(typeof X==="object"&&X!==null&&"values"in X&&K9(X.values))return X.values;else if(typeof X==="object"&&X!==null){let $=Object.entries(X).filter(([,W])=>typeof W==="string").map(([W,Z])=>[W,Z]);return new Headers($)}return new Headers});return Object.fromEntries(Y.entries())}function d5(){let X=g5();if(X==="node"||X==="deno")X=`(${X}/${process.version}; ${process.platform}; ${process.arch})`;return X}function E0(X,Y=!1,$="1.0.0"){let W=u5(X),Z=d5(),Q=`langchainjs${Y?"-azure":""}-openai`;return{...W,"User-Agent":W["User-Agent"]?`${Q}/${$} (${Z})${W["User-Agent"]}`:`${Q}/${$} (${Z})`}}function m5(X,Y){let $;if(hX(X))$=V9(X);else $=X;if(Y?.strict!==void 0)$.function.strict=Y.strict;return $}function Y3(X){return X.anyOf!==void 0&&Array.isArray(X.anyOf)}function c5(X){let Y=["namespace functions {",""];for(let $ of X){if($.description)Y.push(`// ${$.description}`);if(Object.keys($.parameters.properties??{}).length>0)Y.push(`type ${$.name} = (_: {`),Y.push(p5($.parameters,0)),Y.push("}) => any;");else Y.push(`type ${$.name} = () => any;`);Y.push("")}return Y.push("} // namespace functions"),Y.join(`
|
|
49
|
+
`)}function p5(X,Y){let $=[];for(let[W,Z]of Object.entries(X.properties??{})){if(Z.description&&Y<2)$.push(`// ${Z.description}`);if(X.required?.includes(W))$.push(`${W}: ${bY(Z,Y)},`);else $.push(`${W}?: ${bY(Z,Y)},`)}return $.map((W)=>" ".repeat(Y)+W).join(`
|
|
50
|
+
`)}function bY(X,Y){if(Y3(X))return X.anyOf.map(($)=>bY($,Y)).join(" | ");switch(X.type){case"string":if(X.enum)return X.enum.map(($)=>`"${$}"`).join(" | ");return"string";case"number":if(X.enum)return X.enum.map(($)=>`${$}`).join(" | ");return"number";case"integer":if(X.enum)return X.enum.map(($)=>`${$}`).join(" | ");return"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",p5(X,Y+2),"}"].join(`
|
|
51
|
+
`);case"array":if(X.items)return`${bY(X.items,Y)}[]`;return"any[]";default:return""}}function fY(X){return"type"in X&&X.type!=="function"}function l5(X){return typeof X==="object"&&X!==null&&"extras"in X&&typeof X.extras==="object"&&X.extras!==null&&"providerToolDefinition"in X.extras&&typeof X.extras.providerToolDefinition==="object"&&X.extras.providerToolDefinition!==null}function $7(X){return typeof X==="object"&&X!==null&&"metadata"in X&&typeof X.metadata==="object"&&X.metadata!==null&&"customTool"in X.metadata&&typeof X.metadata.customTool==="object"&&X.metadata.customTool!==null}function i5(X){let Y=()=>{if(!X.format)return;if(X.format.type==="grammar")return{type:"grammar",grammar:{definition:X.format.definition,syntax:X.format.syntax}};if(X.format.type==="text")return{type:"text"}};return{type:"custom",custom:{name:X.name,description:X.description,format:Y()}}}var r5=Symbol("Let zodToJsonSchema decide on which parser to use"),n5={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},a5=(X)=>{return typeof X==="string"?{...n5,basePath:["#"],definitions:{},name:X}:{...n5,basePath:["#"],definitions:{},...X}};var W7=(X)=>{return"_def"in X?X._def:X};function t5(X){if(!X)return!0;for(let Y in X)return!1;return!0}var s5=(X)=>{let Y=a5(X),$=Y.name!==void 0?[...Y.basePath,Y.definitionPath,Y.name]:Y.basePath;return{...Y,currentPath:$,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(Y.definitions).map(([W,Z])=>[W7(Z),{def:W7(Z),path:[...Y.basePath,Y.definitionPath,W],jsonSchema:void 0}]))}};function z9(X,Y,$,W){if(!W?.errorMessages)return;if($)X.errorMessage={...X.errorMessage,[Y]:$}}function v(X,Y,$,W,Z){X[Y]=$,z9(X,Y,W,Z)}function o5(){return{}}function e5(X,Y){let $={type:"array"};if(X.type?._def?.typeName!==y.ZodAny)$.items=C(X.type._def,{...Y,currentPath:[...Y.currentPath,"items"]});if(X.minLength)v($,"minItems",X.minLength.value,X.minLength.message,Y);if(X.maxLength)v($,"maxItems",X.maxLength.value,X.maxLength.message,Y);if(X.exactLength)v($,"minItems",X.exactLength.value,X.exactLength.message,Y),v($,"maxItems",X.exactLength.value,X.exactLength.message,Y);return $}function X1(X,Y){let $={type:"integer",format:"int64"};if(!X.checks)return $;for(let W of X.checks)switch(W.kind){case"min":if(Y.target==="jsonSchema7")if(W.inclusive)v($,"minimum",W.value,W.message,Y);else v($,"exclusiveMinimum",W.value,W.message,Y);else{if(!W.inclusive)$.exclusiveMinimum=!0;v($,"minimum",W.value,W.message,Y)}break;case"max":if(Y.target==="jsonSchema7")if(W.inclusive)v($,"maximum",W.value,W.message,Y);else v($,"exclusiveMaximum",W.value,W.message,Y);else{if(!W.inclusive)$.exclusiveMaximum=!0;v($,"maximum",W.value,W.message,Y)}break;case"multipleOf":v($,"multipleOf",W.value,W.message,Y);break}return $}function Y1(){return{type:"boolean"}}function $1(X,Y){return C(X.type._def,Y)}var W1=(X,Y)=>{return C(X.innerType._def,Y)};function H9(X,Y,$){let W=$??Y.dateStrategy;if(Array.isArray(W))return{anyOf:W.map((Z,Q)=>H9(X,Y,Z))};switch(W){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return $3(X,Y)}}var $3=(X,Y)=>{let $={type:"integer",format:"unix-time"};if(Y.target==="openApi3")return $;for(let W of X.checks)switch(W.kind){case"min":v($,"minimum",W.value,W.message,Y);break;case"max":v($,"maximum",W.value,W.message,Y);break}return $};function Z1(X,Y){return{...C(X.innerType._def,Y),default:X.defaultValue()}}function Q1(X,Y,$){return Y.effectStrategy==="input"?C(X.schema._def,Y,$):{}}function J1(X){return{type:"string",enum:[...X.values]}}var W3=(X)=>{if("type"in X&&X.type==="string")return!1;return"allOf"in X};function G1(X,Y){let $=[C(X.left._def,{...Y,currentPath:[...Y.currentPath,"allOf","0"]}),C(X.right._def,{...Y,currentPath:[...Y.currentPath,"allOf","1"]})].filter((Q)=>!!Q),W=Y.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,Z=[];return $.forEach((Q)=>{if(W3(Q)){if(Z.push(...Q.allOf),Q.unevaluatedProperties===void 0)W=void 0}else{let J=Q;if("additionalProperties"in Q&&Q.additionalProperties===!1){let{additionalProperties:G,...z}=Q;J=z}else W=void 0;Z.push(J)}}),Z.length?{allOf:Z,...W}:void 0}function K1(X,Y){let $=typeof X.value;if($!=="bigint"&&$!=="number"&&$!=="boolean"&&$!=="string")return{type:Array.isArray(X.value)?"array":"object"};if(Y.target==="openApi3")return{type:$==="bigint"?"integer":$,enum:[X.value]};return{type:$==="bigint"?"integer":$,const:X.value}}var B9,i0={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(B9===void 0)B9=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return B9},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function hY(X,Y){let $={type:"string"};function W(Z){return Y.patternStrategy==="escape"?Z3(Z):Z}if(X.checks)for(let Z of X.checks)switch(Z.kind){case"min":v($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,Z.value):Z.value,Z.message,Y);break;case"max":v($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,Z.value):Z.value,Z.message,Y);break;case"email":switch(Y.emailStrategy){case"format:email":SX($,"email",Z.message,Y);break;case"format:idn-email":SX($,"idn-email",Z.message,Y);break;case"pattern:zod":RX($,i0.email,Z.message,Y);break}break;case"url":SX($,"uri",Z.message,Y);break;case"uuid":SX($,"uuid",Z.message,Y);break;case"regex":RX($,Z.regex,Z.message,Y);break;case"cuid":RX($,i0.cuid,Z.message,Y);break;case"cuid2":RX($,i0.cuid2,Z.message,Y);break;case"startsWith":RX($,RegExp(`^${W(Z.value)}`),Z.message,Y);break;case"endsWith":RX($,RegExp(`${W(Z.value)}$`),Z.message,Y);break;case"datetime":SX($,"date-time",Z.message,Y);break;case"date":SX($,"date",Z.message,Y);break;case"time":SX($,"time",Z.message,Y);break;case"duration":SX($,"duration",Z.message,Y);break;case"length":v($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,Z.value):Z.value,Z.message,Y),v($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,Z.value):Z.value,Z.message,Y);break;case"includes":{RX($,RegExp(W(Z.value)),Z.message,Y);break}case"ip":{if(Z.version!=="v6")SX($,"ipv4",Z.message,Y);if(Z.version!=="v4")SX($,"ipv6",Z.message,Y);break}case"emoji":RX($,i0.emoji,Z.message,Y);break;case"ulid":{RX($,i0.ulid,Z.message,Y);break}case"base64":{switch(Y.base64Strategy){case"format:binary":{SX($,"binary",Z.message,Y);break}case"contentEncoding:base64":{v($,"contentEncoding","base64",Z.message,Y);break}case"pattern:zod":{RX($,i0.base64,Z.message,Y);break}}break}case"nanoid":RX($,i0.nanoid,Z.message,Y);case"toLowerCase":case"toUpperCase":case"trim":break;default:((Q)=>{})(Z)}return $}var Z3=(X)=>Array.from(X).map((Y)=>/[a-zA-Z0-9]/.test(Y)?Y:`\\${Y}`).join(""),SX=(X,Y,$,W)=>{if(X.format||X.anyOf?.some((Z)=>Z.format)){if(!X.anyOf)X.anyOf=[];if(X.format){if(X.anyOf.push({format:X.format,...X.errorMessage&&W.errorMessages&&{errorMessage:{format:X.errorMessage.format}}}),delete X.format,X.errorMessage){if(delete X.errorMessage.format,Object.keys(X.errorMessage).length===0)delete X.errorMessage}}X.anyOf.push({format:Y,...$&&W.errorMessages&&{errorMessage:{format:$}}})}else v(X,"format",Y,$,W)},RX=(X,Y,$,W)=>{if(X.pattern||X.allOf?.some((Z)=>Z.pattern)){if(!X.allOf)X.allOf=[];if(X.pattern){if(X.allOf.push({pattern:X.pattern,...X.errorMessage&&W.errorMessages&&{errorMessage:{pattern:X.errorMessage.pattern}}}),delete X.pattern,X.errorMessage){if(delete X.errorMessage.pattern,Object.keys(X.errorMessage).length===0)delete X.errorMessage}}X.allOf.push({pattern:V1(Y,W),...$&&W.errorMessages&&{errorMessage:{pattern:$}}})}else v(X,"pattern",V1(Y,W),$,W)},V1=(X,Y)=>{let $=typeof X==="function"?X():X;if(!Y.applyRegexFlags||!$.flags)return $.source;let W={i:$.flags.includes("i"),m:$.flags.includes("m"),s:$.flags.includes("s")},Z=W.i?$.source.toLowerCase():$.source,Q="",J=!1,G=!1,z=!1;for(let B=0;B<Z.length;B++){if(J){Q+=Z[B],J=!1;continue}if(W.i){if(G){if(Z[B].match(/[a-z]/)){if(z)Q+=Z[B],Q+=`${Z[B-2]}-${Z[B]}`.toUpperCase(),z=!1;else if(Z[B+1]==="-"&&Z[B+2]?.match(/[a-z]/))Q+=Z[B],z=!0;else Q+=`${Z[B]}${Z[B].toUpperCase()}`;continue}}else if(Z[B].match(/[a-z]/)){Q+=`[${Z[B]}${Z[B].toUpperCase()}]`;continue}}if(W.m){if(Z[B]==="^"){Q+=`(^|(?<=[\r
|
|
52
|
+
]))`;continue}else if(Z[B]==="$"){Q+=`($|(?=[\r
|
|
53
|
+
]))`;continue}}if(W.s&&Z[B]==="."){Q+=G?`${Z[B]}\r
|
|
54
|
+
`:`[${Z[B]}\r
|
|
55
|
+
]`;continue}if(Q+=Z[B],Z[B]==="\\")J=!0;else if(G&&Z[B]==="]")G=!1;else if(!G&&Z[B]==="[")G=!0}try{let B=new RegExp(Q)}catch{return console.warn(`Could not convert regex pattern at ${Y.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),$.source}return Q};function gY(X,Y){if(Y.target==="openApi3"&&X.keyType?._def.typeName===y.ZodEnum)return{type:"object",required:X.keyType._def.values,properties:X.keyType._def.values.reduce((W,Z)=>({...W,[Z]:C(X.valueType._def,{...Y,currentPath:[...Y.currentPath,"properties",Z]})??{}}),{}),additionalProperties:!1};let $={type:"object",additionalProperties:C(X.valueType._def,{...Y,currentPath:[...Y.currentPath,"additionalProperties"]})??{}};if(Y.target==="openApi3")return $;if(X.keyType?._def.typeName===y.ZodString&&X.keyType._def.checks?.length){let W=Object.entries(hY(X.keyType._def,Y)).reduce((Z,[Q,J])=>Q==="type"?Z:{...Z,[Q]:J},{});return{...$,propertyNames:W}}else if(X.keyType?._def.typeName===y.ZodEnum)return{...$,propertyNames:{enum:X.keyType._def.values}};return $}function z1(X,Y){if(Y.mapStrategy==="record")return gY(X,Y);let $=C(X.keyType._def,{...Y,currentPath:[...Y.currentPath,"items","items","0"]})||{},W=C(X.valueType._def,{...Y,currentPath:[...Y.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[$,W],minItems:2,maxItems:2}}}function H1(X){let Y=X.values,W=Object.keys(X.values).filter((Q)=>{return typeof Y[Y[Q]]!=="number"}).map((Q)=>Y[Q]),Z=Array.from(new Set(W.map((Q)=>typeof Q)));return{type:Z.length===1?Z[0]==="string"?"string":"number":["string","number"],enum:W}}function B1(){return{not:{}}}function N1(X){return X.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Z7={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function w1(X,Y){if(Y.target==="openApi3")return U1(X,Y);let $=X.options instanceof Map?Array.from(X.options.values()):X.options;if($.every((W)=>(W._def.typeName in Z7)&&(!W._def.checks||!W._def.checks.length))){let W=$.reduce((Z,Q)=>{let J=Z7[Q._def.typeName];return J&&!Z.includes(J)?[...Z,J]:Z},[]);return{type:W.length>1?W:W[0]}}else if($.every((W)=>W._def.typeName==="ZodLiteral"&&!W.description)){let W=$.reduce((Z,Q)=>{let J=typeof Q._def.value;switch(J){case"string":case"number":case"boolean":return[...Z,J];case"bigint":return[...Z,"integer"];case"object":if(Q._def.value===null)return[...Z,"null"];case"symbol":case"undefined":case"function":default:return Z}},[]);if(W.length===$.length){let Z=W.filter((Q,J,G)=>G.indexOf(Q)===J);return{type:Z.length>1?Z:Z[0],enum:$.reduce((Q,J)=>{return Q.includes(J._def.value)?Q:[...Q,J._def.value]},[])}}}else if($.every((W)=>W._def.typeName==="ZodEnum"))return{type:"string",enum:$.reduce((W,Z)=>[...W,...Z._def.values.filter((Q)=>!W.includes(Q))],[])};return U1(X,Y)}var U1=(X,Y)=>{let $=(X.options instanceof Map?Array.from(X.options.values()):X.options).map((W,Z)=>C(W._def,{...Y,currentPath:[...Y.currentPath,"anyOf",`${Z}`]})).filter((W)=>!!W&&(!Y.strictUnions||typeof W==="object"&&Object.keys(W).length>0));return $.length?{anyOf:$}:void 0};function q1(X,Y){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(X.innerType._def.typeName)&&(!X.innerType._def.checks||!X.innerType._def.checks.length)){if(Y.target==="openApi3"||Y.nullableStrategy==="property")return{type:Z7[X.innerType._def.typeName],nullable:!0};return{type:[Z7[X.innerType._def.typeName],"null"]}}if(Y.target==="openApi3"){let W=C(X.innerType._def,{...Y,currentPath:[...Y.currentPath]});if(W&&"$ref"in W)return{allOf:[W],nullable:!0};return W&&{...W,nullable:!0}}let $=C(X.innerType._def,{...Y,currentPath:[...Y.currentPath,"anyOf","0"]});return $&&{anyOf:[$,{type:"null"}]}}function F1(X,Y){let $={type:"number"};if(!X.checks)return $;for(let W of X.checks)switch(W.kind){case"int":$.type="integer",z9($,"type",W.message,Y);break;case"min":if(Y.target==="jsonSchema7")if(W.inclusive)v($,"minimum",W.value,W.message,Y);else v($,"exclusiveMinimum",W.value,W.message,Y);else{if(!W.inclusive)$.exclusiveMinimum=!0;v($,"minimum",W.value,W.message,Y)}break;case"max":if(Y.target==="jsonSchema7")if(W.inclusive)v($,"maximum",W.value,W.message,Y);else v($,"exclusiveMaximum",W.value,W.message,Y);else{if(!W.inclusive)$.exclusiveMaximum=!0;v($,"maximum",W.value,W.message,Y)}break;case"multipleOf":v($,"multipleOf",W.value,W.message,Y);break}return $}function Q3(X,Y){if(Y.removeAdditionalStrategy==="strict")return X.catchall._def.typeName==="ZodNever"?X.unknownKeys!=="strict":C(X.catchall._def,{...Y,currentPath:[...Y.currentPath,"additionalProperties"]})??!0;else return X.catchall._def.typeName==="ZodNever"?X.unknownKeys==="passthrough":C(X.catchall._def,{...Y,currentPath:[...Y.currentPath,"additionalProperties"]})??!0}function L1(X,Y){let $={type:"object",...Object.entries(X.shape()).reduce((W,[Z,Q])=>{if(Q===void 0||Q._def===void 0)return W;let J=[...Y.currentPath,"properties",Z],G=C(Q._def,{...Y,currentPath:J,propertyPath:J});if(G===void 0)return W;if(Y.openaiStrictMode&&Q.isOptional()&&!Q.isNullable()&&typeof Q._def?.defaultValue>"u")throw Error(`Zod field at \`${J.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...W.properties,[Z]:G},required:Q.isOptional()&&!Y.openaiStrictMode?W.required:[...W.required,Z]}},{properties:{},required:[]}),additionalProperties:Q3(X,Y)};if(!$.required.length)delete $.required;return $}var E1=(X,Y)=>{if(Y.propertyPath&&Y.currentPath.slice(0,Y.propertyPath.length).toString()===Y.propertyPath.toString())return C(X.innerType._def,{...Y,currentPath:Y.currentPath});let $=C(X.innerType._def,{...Y,currentPath:[...Y.currentPath,"anyOf","1"]});return $?{anyOf:[{not:{}},$]}:{}};var x1=(X,Y)=>{if(Y.pipeStrategy==="input")return C(X.in._def,Y);else if(Y.pipeStrategy==="output")return C(X.out._def,Y);let $=C(X.in._def,{...Y,currentPath:[...Y.currentPath,"allOf","0"]}),W=C(X.out._def,{...Y,currentPath:[...Y.currentPath,"allOf",$?"1":"0"]});return{allOf:[$,W].filter((Z)=>Z!==void 0)}};function O1(X,Y){return C(X.type._def,Y)}function D1(X,Y){let W={type:"array",uniqueItems:!0,items:C(X.valueType._def,{...Y,currentPath:[...Y.currentPath,"items"]})};if(X.minSize)v(W,"minItems",X.minSize.value,X.minSize.message,Y);if(X.maxSize)v(W,"maxItems",X.maxSize.value,X.maxSize.message,Y);return W}function M1(X,Y){if(X.rest)return{type:"array",minItems:X.items.length,items:X.items.map(($,W)=>C($._def,{...Y,currentPath:[...Y.currentPath,"items",`${W}`]})).reduce(($,W)=>W===void 0?$:[...$,W],[]),additionalItems:C(X.rest._def,{...Y,currentPath:[...Y.currentPath,"additionalItems"]})};else return{type:"array",minItems:X.items.length,maxItems:X.items.length,items:X.items.map(($,W)=>C($._def,{...Y,currentPath:[...Y.currentPath,"items",`${W}`]})).reduce(($,W)=>W===void 0?$:[...$,W],[])}}function T1(){return{not:{}}}function A1(){return{}}var P1=(X,Y)=>{return C(X.innerType._def,Y)};function C(X,Y,$=!1){let W=Y.seen.get(X);if(Y.override){let J=Y.override?.(X,Y,W,$);if(J!==r5)return J}if(W&&!$){let J=J3(W,Y);if(J!==void 0){if("$ref"in J)Y.seenRefs.add(J.$ref);return J}}let Z={def:X,path:Y.currentPath,jsonSchema:void 0};Y.seen.set(X,Z);let Q=K3(X,X.typeName,Y,$);if(Q)V3(X,Y,Q);return Z.jsonSchema=Q,Q}var J3=(X,Y)=>{switch(Y.$refStrategy){case"root":return{$ref:X.path.join("/")};case"extract-to-root":let $=X.path.slice(Y.basePath.length+1).join("_");if($!==Y.name&&Y.nameStrategy==="duplicate-ref")Y.definitions[$]=X.def;return{$ref:[...Y.basePath,Y.definitionPath,$].join("/")};case"relative":return{$ref:G3(Y.currentPath,X.path)};case"none":case"seen":{if(X.path.length<Y.currentPath.length&&X.path.every((W,Z)=>Y.currentPath[Z]===W))return console.warn(`Recursive reference detected at ${Y.currentPath.join("/")}! Defaulting to any`),{};return Y.$refStrategy==="seen"?{}:void 0}}},G3=(X,Y)=>{let $=0;for(;$<X.length&&$<Y.length;$++)if(X[$]!==Y[$])break;return[(X.length-$).toString(),...Y.slice($)].join("/")},K3=(X,Y,$,W)=>{switch(Y){case y.ZodString:return hY(X,$);case y.ZodNumber:return F1(X,$);case y.ZodObject:return L1(X,$);case y.ZodBigInt:return X1(X,$);case y.ZodBoolean:return Y1();case y.ZodDate:return H9(X,$);case y.ZodUndefined:return T1();case y.ZodNull:return N1($);case y.ZodArray:return e5(X,$);case y.ZodUnion:case y.ZodDiscriminatedUnion:return w1(X,$);case y.ZodIntersection:return G1(X,$);case y.ZodTuple:return M1(X,$);case y.ZodRecord:return gY(X,$);case y.ZodLiteral:return K1(X,$);case y.ZodEnum:return J1(X);case y.ZodNativeEnum:return H1(X);case y.ZodNullable:return q1(X,$);case y.ZodOptional:return E1(X,$);case y.ZodMap:return z1(X,$);case y.ZodSet:return D1(X,$);case y.ZodLazy:return C(X.getter()._def,$);case y.ZodPromise:return O1(X,$);case y.ZodNaN:case y.ZodNever:return B1();case y.ZodEffects:return Q1(X,$,W);case y.ZodAny:return o5();case y.ZodUnknown:return A1();case y.ZodDefault:return Z1(X,$);case y.ZodBranded:return $1(X,$);case y.ZodReadonly:return P1(X,$);case y.ZodCatch:return W1(X,$);case y.ZodPipeline:return x1(X,$);case y.ZodFunction:case y.ZodVoid:case y.ZodSymbol:return;default:return((Z)=>{return})(Y)}},V3=(X,Y,$)=>{if(X.description){if($.description=X.description,Y.markdownDescription)$.markdownDescription=X.description}return $};var N9=(X,Y)=>{let $=s5(Y),W=typeof Y==="string"?Y:Y?.nameStrategy==="title"?void 0:Y?.name,Z=C(X._def,W===void 0?$:{...$,currentPath:[...$.basePath,$.definitionPath,W]},!1)??{},Q=typeof Y==="object"&&Y.name!==void 0&&Y.nameStrategy==="title"?Y.name:void 0;if(Q!==void 0)Z.title=Q;let J=(()=>{if(t5($.definitions))return;let z={},B=new Set;for(let H=0;H<500;H++){let V=Object.entries($.definitions).filter(([K])=>!B.has(K));if(V.length===0)break;for(let[K,U]of V)z[K]=C(W7(U),{...$,currentPath:[...$.basePath,$.definitionPath,K]},!0)??{},B.add(K)}return z})(),G=W===void 0?J?{...Z,[$.definitionPath]:J}:Z:$.nameStrategy==="duplicate-ref"?{...Z,...J||$.seenRefs.size?{[$.definitionPath]:{...J,...$.seenRefs.size?{[W]:Z}:void 0}}:void 0}:{$ref:[...$.$refStrategy==="relative"?[]:$.basePath,$.definitionPath,W].join("/"),[$.definitionPath]:{...J,[W]:Z}};if($.target==="jsonSchema7")G.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="jsonSchema2019-09")G.$schema="https://json-schema.org/draft/2019-09/schema#";return G};function S1(X){if(X.type!=="object")throw Error(`Root schema must have type: 'object' but got type: ${X.type?`'${X.type}'`:"undefined"}`);let Y=structuredClone(X);return rX(Y,[],Y)}function U9(X){if(typeof X==="boolean")return!1;if(X.type==="null")return!0;for(let Y of X.oneOf??[])if(U9(Y))return!0;for(let Y of X.anyOf??[])if(U9(Y))return!0;return!1}function rX(X,Y,$){if(typeof X==="boolean")throw TypeError(`Expected object schema but got boolean; path=${Y.join("/")}`);if(!n0(X))throw TypeError(`Expected ${JSON.stringify(X)} to be an object; path=${Y.join("/")}`);let W=X.$defs;if(n0(W))for(let[K,U]of Object.entries(W))rX(U,[...Y,"$defs",K],$);let Z=X.definitions;if(n0(Z))for(let[K,U]of Object.entries(Z))rX(U,[...Y,"definitions",K],$);if(X.type==="object"&&!("additionalProperties"in X))X.additionalProperties=!1;let J=X.required??[],G=X.properties;if(n0(G)){for(let[K,U]of Object.entries(G))if(!U9(U)&&!J.includes(K))throw Error(`Zod field at \`${[...Y,"properties",K].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);X.required=Object.keys(G),X.properties=Object.fromEntries(Object.entries(G).map(([K,U])=>[K,rX(U,[...Y,"properties",K],$)]))}let z=X.items;if(n0(z))X.items=rX(z,[...Y,"items"],$);let B=X.anyOf;if(Array.isArray(B))X.anyOf=B.map((K,U)=>rX(K,[...Y,"anyOf",String(U)],$));let H=X.allOf;if(Array.isArray(H))if(H.length===1){let K=rX(H[0],[...Y,"allOf","0"],$);Object.assign(X,K),delete X.allOf}else X.allOf=H.map((K,U)=>rX(K,[...Y,"allOf",String(U)],$));if(X.default===null)delete X.default;let V=X.$ref;if(V&&H3(X,1)){if(typeof V!=="string")throw TypeError(`Received non-string $ref - ${V}; path=${Y.join("/")}`);let K=z3($,V);if(typeof K==="boolean")throw Error(`Expected \`$ref: ${V}\` to resolve to an object schema but got boolean`);if(!n0(K))throw Error(`Expected \`$ref: ${V}\` to resolve to an object but got ${JSON.stringify(K)}`);return Object.assign(X,{...K,...X}),delete X.$ref,rX(X,Y,$)}return X}function z3(X,Y){if(!Y.startsWith("#/"))throw Error(`Unexpected $ref format ${JSON.stringify(Y)}; Does not start with #/`);let $=Y.slice(2).split("/"),W=X;for(let Z of $){if(!n0(W))throw Error(`encountered non-object entry while resolving ${Y} - ${JSON.stringify(W)}`);let Q=W[Z];if(Q===void 0)throw Error(`Key ${Z} not found while resolving ${Y}`);W=Q}return W}function n0(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function H3(X,Y){let $=0;for(let W in X)if($++,$>Y)return!0;return!1}function N3(X,Y){return N9(X,{openaiStrictMode:!0,name:Y.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function U3(X){return S1(R1(X,{target:"draft-7"}))}function w3(X){return"_zod"in X}function w9(X,Y,$){return K5({type:"json_schema",json_schema:{...$,name:Y,strict:!0,schema:w3(X)?U3(X):N3(X,{name:Y})}},(W)=>X.parse(JSON.parse(W)))}var C1=["jsonSchema","functionCalling","jsonMode"];function j1(X,Y){if(typeof Y<"u"&&!C1.includes(Y))throw Error(`Invalid method: ${Y}. Supported methods are: ${C1.join(", ")}`);let $=!X.startsWith("gpt-3")&&!X.startsWith("gpt-4-")&&X!=="gpt-4";if($&&!Y)return"jsonSchema";if(!$&&Y==="jsonSchema")throw Error(`JSON Schema is not supported for model "${X}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return Y??"functionCalling"}function q3(X,Y){let $={...X};return Object.defineProperties($,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:Y,enumerable:!1}}),$}function _1(X,Y,$){if(F9(X))return w9(X,Y,$);if(q9(X))return q3({type:"json_schema",json_schema:{...$,name:Y,strict:!0,schema:WX(X,{cycles:"ref",reused:"ref",override(W){W.jsonSchema.title=Y}})}},(W)=>I1(X,JSON.parse(W)));throw Error("Unsupported schema response format")}var y1={"gpt-4o-2024-11-20":{maxInputTokens:128000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:400000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:400000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:400000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:400000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:200000,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:400000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:400000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:400000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:400000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:400000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:400000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128000,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:200000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:400000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:400000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:200000,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:400000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:400000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128000,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128000,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128000,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};var v8=class extends k8{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(X){let Y=this.invocationParams(X);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:Y.temperature??void 0,ls_max_tokens:Y.max_tokens??void 0,ls_stop:X.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(X){super(X??{});let Y=typeof X?.configuration?.apiKey==="string"||typeof X?.configuration?.apiKey==="function"?X?.configuration?.apiKey:void 0;if(this.apiKey=X?.apiKey??Y??BX("OPENAI_API_KEY"),this.organization=X?.configuration?.organization??BX("OPENAI_ORGANIZATION"),this.model=X?.model??X?.modelName??this.model,this.modelKwargs=X?.modelKwargs??{},this.timeout=X?.timeout,this.temperature=X?.temperature??this.temperature,this.topP=X?.topP??this.topP,this.frequencyPenalty=X?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=X?.presencePenalty??this.presencePenalty,this.logprobs=X?.logprobs,this.topLogprobs=X?.topLogprobs,this.n=X?.n??this.n,this.logitBias=X?.logitBias,this.stop=X?.stopSequences??X?.stop,this.stopSequences=this.stop,this.user=X?.user,this.__includeRawResponse=X?.__includeRawResponse,this.audio=X?.audio,this.modalities=X?.modalities,this.reasoning=X?.reasoning,this.maxTokens=X?.maxCompletionTokens??X?.maxTokens,this.promptCacheKey=X?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=X?.promptCacheRetention??this.promptCacheRetention,this.verbosity=X?.verbosity??this.verbosity,this.disableStreaming=X?.disableStreaming===!0,this.streaming=X?.streaming===!0,this.disableStreaming)this.streaming=!1;if(X?.streaming===!1)this.disableStreaming=!0;if(this.streamUsage=X?.streamUsage??this.streamUsage,this.disableStreaming)this.streamUsage=!1;if(this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...X?.configuration},X?.supportsStrictToolCalling!==void 0)this.supportsStrictToolCalling=X.supportsStrictToolCalling;if(X?.service_tier!==void 0)this.service_tier=X.service_tier;this.zdrEnabled=X?.zdrEnabled??!1}_getReasoningParams(X){if(!Y7(this.model))return;let Y;if(this.reasoning!==void 0)Y={...Y,...this.reasoning};if(X?.reasoning!==void 0)Y={...Y,...X.reasoning};if(X?.reasoningEffort!==void 0&&Y?.effort===void 0)Y={...Y,effort:X.reasoningEffort};return Y}_getResponseFormat(X){if(X&&X.type==="json_schema"&&X.json_schema.schema&&HX(X.json_schema.schema))return _1(X.json_schema.schema,X.json_schema.name,{description:X.json_schema.description});return X}_combineCallOptions(X){return{...this.defaultOptions,...X??{}}}_getClientOptions(X){if(!this.client){let Y=L0({baseURL:this.clientConfig.baseURL}),$={...this.clientConfig,baseURL:Y,timeout:this.timeout,maxRetries:0};if(!$.baseURL)delete $.baseURL;$.defaultHeaders=E0($.defaultHeaders),this.client=new R($)}return{...this.clientConfig,...X}}_convertChatOpenAIToolToCompletionsTool(X,Y){if($7(X))return i5(X.metadata.customTool);if(aX(X)){if(Y?.strict!==void 0)return{...X,function:{...X.function,strict:Y.strict}};return X}return m5(X,Y)}bindTools(X,Y){let $;if(Y?.strict!==void 0)$=Y.strict;else if(this.supportsStrictToolCalling!==void 0)$=this.supportsStrictToolCalling;return this.withConfig({tools:X.map((W)=>{if(fY(W)||$7(W))return W;if(l5(W))return W.extras.providerToolDefinition;return this._convertChatOpenAIToolToCompletionsTool(W,{strict:$})}),...Y})}async stream(X,Y){return super.stream(X,this._combineCallOptions(Y))}async invoke(X,Y){return super.invoke(X,this._combineCallOptions(Y))}_combineLLMOutput(...X){return X.reduce((Y,$)=>{if($&&$.tokenUsage)Y.tokenUsage.completionTokens+=$.tokenUsage.completionTokens??0,Y.tokenUsage.promptTokens+=$.tokenUsage.promptTokens??0,Y.tokenUsage.totalTokens+=$.tokenUsage.totalTokens??0;return Y},{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(X){let Y=0,$=0,W=0;if(this.model==="gpt-3.5-turbo-0301")$=4,W=-1;else $=3,W=1;let Z=await Promise.all(X.map(async(Q)=>{let[J,G]=await Promise.all([this.getNumTokens(Q.content),this.getNumTokens(F0(Q))]),z=Q.name!==void 0?W+await this.getNumTokens(Q.name):0,B=J+$+G+z,H=Q;if(H._getType()==="function")B-=2;if(H.additional_kwargs?.function_call)B+=3;if(H?.additional_kwargs.function_call?.name)B+=await this.getNumTokens(H.additional_kwargs.function_call?.name);if(H.additional_kwargs.function_call?.arguments)try{B+=await this.getNumTokens(JSON.stringify(JSON.parse(H.additional_kwargs.function_call?.arguments)))}catch(V){console.error("Error parsing function arguments",V,JSON.stringify(H.additional_kwargs.function_call)),B+=await this.getNumTokens(H.additional_kwargs.function_call?.arguments)}return Y+=B,B}));return Y+=3,{totalCount:Y,countPerMessage:Z}}async _getNumTokensFromGenerations(X){return(await Promise.all(X.map(async(Y)=>{if(Y.message.additional_kwargs?.function_call)return(await this.getNumTokensFromMessages([Y.message])).countPerMessage[0];else return await this.getNumTokens(Y.message.content)}))).reduce((Y,$)=>Y+$,0)}async _getEstimatedTokenCountFromPrompt(X,Y,$){let W=(await this.getNumTokensFromMessages(X)).totalCount;if(Y&&$!=="auto"){let Z=c5(Y);W+=await this.getNumTokens(Z),W+=9}if(Y&&X.find((Z)=>Z._getType()==="system"))W-=4;if($==="none")W+=1;else if(typeof $==="object")W+=await this.getNumTokens($.name)+4;return W}async moderateContent(X,Y){let $=this._getClientOptions(Y?.options),W={input:X,model:Y?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(W,$)}catch(Z){throw fX(Z)}})}get profile(){return y1[this.model]??{}}_getStructuredOutputMethod(X){let Y={...X};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(Y?.method===void 0)return"jsonSchema"}else if(Y.method==="jsonSchema")console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return Y.method}withStructuredOutput(X,Y){let $,W,{schema:Z,name:Q,includeRaw:J}={...Y,schema:X};if(Y?.strict!==void 0&&Y.method==="jsonMode")throw Error("Argument `strict` is only supported for `method` = 'function_calling'");let G=j1(this.model,Y?.method);if(G==="jsonMode"){if(HX(Z))W=L9.fromZodSchema(Z);else W=new Q7;let V=WX(Z);$=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:Q??"extract",...V}}})}else if(G==="jsonSchema"){let V={name:Q??"extract",description:k1(Z),schema:Z,strict:Y?.strict},K=WX(V.schema);if($=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:V},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:V.name,description:V.description,...K}}}),HX(Z)){let U=L9.fromZodSchema(Z);W=v1.from((E)=>{if("parsed"in E.additional_kwargs)return E.additional_kwargs.parsed;return U})}else W=new Q7}else{let V=Q??"extract";if(HX(Z)){let K=WX(Z);$=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:{name:V,description:K.description,parameters:K}}],tool_choice:{type:"function",function:{name:V}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:V,...K}},...Y?.strict!==void 0?{strict:Y.strict}:{}}),W=new E9({returnSingle:!0,keyName:V,zodSchema:Z})}else{let K;if(typeof Z.name==="string"&&typeof Z.parameters==="object"&&Z.parameters!=null)K=Z,V=Z.name;else V=Z.title??V,K={name:V,description:Z.description??"",parameters:Z};let U=WX(Z);$=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:K}],tool_choice:{type:"function",function:{name:V}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:V,...U}},...Y?.strict!==void 0?{strict:Y.strict}:{}}),W=new E9({returnSingle:!0,keyName:V})}}if(!J)return $.pipe(W);let z=y8.assign({parsed:(V,K)=>W.invoke(V.raw,K)}),B=y8.assign({parsed:()=>null}),H=z.withFallbacks({fallbacks:[B]});return uY.from([{raw:$},H])}};var P3=N.object({type:N.literal("screenshot")}),S3=N.object({type:N.literal("click"),x:N.number(),y:N.number(),button:N.enum(["left","right","wheel","back","forward"]).default("left")}),R3=N.object({type:N.literal("double_click"),x:N.number(),y:N.number(),button:N.enum(["left","right","wheel","back","forward"]).default("left")}),C3=N.object({type:N.literal("drag"),path:N.array(N.object({x:N.number(),y:N.number()}))}),I3=N.object({type:N.literal("keypress"),keys:N.array(N.string())}),j3=N.object({type:N.literal("move"),x:N.number(),y:N.number()}),_3=N.object({type:N.literal("scroll"),x:N.number(),y:N.number(),scroll_x:N.number(),scroll_y:N.number()}),y3=N.object({type:N.literal("type"),text:N.string()}),k3=N.object({type:N.literal("wait"),duration:N.number().optional()}),v3=N.union([P3,S3,R3,C3,I3,j3,_3,y3,k3]),zD=N.object({action:v3});var b3=N.object({type:N.literal("exec"),command:N.array(N.string()),env:N.record(N.string(),N.string()).optional(),working_directory:N.string().optional(),timeout_ms:N.number().optional(),user:N.string().optional()}),UD=N.union([b3]);var LD=N.object({commands:N.array(N.string()).describe("Array of shell commands to execute"),timeout_ms:N.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:N.number().optional().describe("Optional maximum number of characters to return from each command")});var f3=N.object({type:N.literal("create_file"),path:N.string(),diff:N.string()}),h3=N.object({type:N.literal("update_file"),path:N.string(),diff:N.string()}),g3=N.object({type:N.literal("delete_file"),path:N.string()}),DD=N.union([f3,h3,g3]);var dM=N.object({messages:s1(N.custom(),o1).default([])});function e1(X){if(!X)return;else if(X==="any"||X==="required")return"required";else if(X==="auto")return"auto";else if(X==="none")return"none";else if(typeof X==="string")return{type:"function",function:{name:X}};else return X}function X2(X,Y){if(Y&&typeof Y==="object"&&"images"in Y&&Array.isArray(Y.images)){let $=Y.images.filter((W)=>typeof W?.image_url?.url==="string").map((W)=>({type:"image",url:W.image_url.url}));return[{type:"text",text:X},...$]}return X}var i3={providerName:"ChatOpenAI",fromStandardTextBlock(X){return{type:"text",text:X.text}},fromStandardImageBlock(X){if(X.source_type==="url")return{type:"image_url",image_url:{url:X.url,...X.metadata?.detail?{detail:X.metadata.detail}:{}}};if(X.source_type==="base64")return{type:"image_url",image_url:{url:`data:${X.mime_type??""};base64,${X.data}`,...X.metadata?.detail?{detail:X.metadata.detail}:{}}};throw Error(`Image content blocks with source_type ${X.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(X){if(X.source_type==="url"){let Y=OX({dataUrl:X.url});if(!Y)throw Error(`URL audio blocks with source_type ${X.source_type} must be formatted as a data URL for ChatOpenAI`);let $=Y.mime_type||X.mime_type||"",W;try{W=dY($)}catch{throw Error(`Audio blocks with source_type ${X.source_type} must have mime type of audio/wav or audio/mp3`)}if(W.type!=="audio"||W.subtype!=="wav"&&W.subtype!=="mp3")throw Error(`Audio blocks with source_type ${X.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:W.subtype,data:Y.data}}}if(X.source_type==="base64"){let Y;try{Y=dY(X.mime_type??"")}catch{throw Error(`Audio blocks with source_type ${X.source_type} must have mime type of audio/wav or audio/mp3`)}if(Y.type!=="audio"||Y.subtype!=="wav"&&Y.subtype!=="mp3")throw Error(`Audio blocks with source_type ${X.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:Y.subtype,data:X.data}}}throw Error(`Audio content blocks with source_type ${X.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(X){if(X.source_type==="url"){if(!OX({dataUrl:X.url}))throw Error(`URL file blocks with source_type ${X.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:X.url,...X.metadata?.filename||X.metadata?.name?{filename:X.metadata?.filename||X.metadata?.name}:{}}}}if(X.source_type==="base64")return{type:"file",file:{file_data:`data:${X.mime_type??""};base64,${X.data}`,...X.metadata?.filename||X.metadata?.name||X.metadata?.title?{filename:X.metadata?.filename||X.metadata?.name||X.metadata?.title}:{}}};if(X.source_type==="id")return{type:"file",file:{file_id:X.id}};throw Error(`File content blocks with source_type ${X.source_type} are not supported for ChatOpenAI`)}},Y2=({message:X,rawResponse:Y,includeRawResponse:$})=>{let W=X.tool_calls;switch(X.role){case"assistant":{let Z=[],Q=[];for(let B of W??[])try{Z.push(cY(B,{returnId:!0}))}catch(H){Q.push(pY(B,H.message))}let J={function_call:X.function_call,tool_calls:W};if($!==void 0)J.__raw_response=Y;let G={model_provider:"openai",model_name:Y.model,...Y.system_fingerprint?{usage:{...Y.usage},system_fingerprint:Y.system_fingerprint}:{}};if(X.audio)J.audio=X.audio;let z=X2(X.content||"",Y.choices?.[0]?.message);return new r({content:z,tool_calls:Z,invalid_tool_calls:Q,additional_kwargs:J,response_metadata:G,id:Y.id})}default:return new l0(X.content||"",X.role??"unknown")}},$2=({delta:X,rawResponse:Y,includeRawResponse:$,defaultRole:W})=>{let Z=X.role??W,Q=X.content??"",J;if(X.function_call)J={function_call:X.function_call};else if(X.tool_calls)J={tool_calls:X.tool_calls};else J={};if($)J.__raw_response=Y;if(X.audio)J.audio={...X.audio,index:Y.choices[0].index};let G={model_provider:"openai",usage:{...Y.usage}};if(Z==="user")return new M9({content:Q,response_metadata:G});else if(Z==="assistant"){let z=[];if(Array.isArray(X.tool_calls))for(let B of X.tool_calls)z.push({name:B.function?.name,args:B.function?.arguments,id:B.id,index:B.index,type:"tool_call_chunk"});return new u({content:Q,tool_call_chunks:z,additional_kwargs:J,id:Y.id,response_metadata:G})}else if(Z==="system")return new mY({content:Q,response_metadata:G});else if(Z==="developer")return new mY({content:Q,response_metadata:G,additional_kwargs:{__openai_role__:"developer"}});else if(Z==="function")return new D9({content:Q,additional_kwargs:J,name:X.name,response_metadata:G});else if(Z==="tool")return new x9({content:Q,additional_kwargs:J,tool_call_id:X.tool_call_id,response_metadata:G});else return new O9({content:Q,role:Z,response_metadata:G})},n3=(X)=>{if(X.type==="image"){if(X.url)return{type:"image_url",image_url:{url:X.url}};else if(X.data)return{type:"image_url",image_url:{url:`data:${X.mimeType};base64,${X.data}`}}}if(X.type==="audio"){if(X.data){let Y=T9(()=>{let[,$]=X.mimeType.split("/");if($==="wav"||$==="mp3")return $;return"wav"});return{type:"input_audio",input_audio:{data:X.data.toString(),format:Y}}}}if(X.type==="file"){if(X.data)return{type:"file",file:{file_data:X.data.toString()}};if(X.fileId)return{type:"file",file:{file_id:X.fileId}}}return};function W2(X){if(!X)return!1;if(/^o\d/.test(X??""))return!0;if(X.startsWith("gpt-5")&&!X.startsWith("gpt-5-chat"))return!0;return!1}var r3=({message:X,model:Y})=>{let $=F0(X);if($==="system"&&W2(Y))$="developer";if($==="developer")return{role:"developer",content:X.contentBlocks.filter((Z)=>Z.type==="text")};else if($==="system")return{role:"system",content:X.contentBlocks.filter((Z)=>Z.type==="text")};else if($==="assistant")return{role:"assistant",content:X.contentBlocks.filter((Z)=>Z.type==="text")};else if($==="tool"&&jX.isInstance(X))return{role:"tool",tool_call_id:X.tool_call_id,content:X.contentBlocks.filter((Z)=>Z.type==="text")};else if($==="function")return{role:"function",name:X.name??"",content:X.contentBlocks.filter((Z)=>Z.type==="text").join("")};function*W(Z){for(let Q of Z){if(Q.type==="text")yield{type:"text",text:Q.text};let J=n3(Q);if(J)yield J}}return{role:"user",content:Array.from(W(X.contentBlocks))}},S9=({messages:X,model:Y})=>{return X.flatMap(($)=>{if("output_version"in $.response_metadata&&$.response_metadata?.output_version==="v1")return r3({message:$});let W=F0($);if(W==="system"&&W2(Y))W="developer";let Z=typeof $.content==="string"?$.content:$.content.map((J)=>{if(x0(J))return O0(J,i3);return J}),Q={role:W,content:Z};if($.name!=null)Q.name=$.name;if($.additional_kwargs.function_call!=null)Q.function_call=$.additional_kwargs.function_call,Q.content="";if($.additional_kwargs?.reasoning_content&&Y?.includes("deepseek"))Q.reasoning_content=$.additional_kwargs.reasoning_content;if(r.isInstance($)&&!!$.tool_calls?.length)Q.tool_calls=$.tool_calls.map(A9),Q.content="";else{if($.additional_kwargs.tool_calls!=null)Q.tool_calls=$.additional_kwargs.tool_calls;if(jX.isInstance($)&&$.tool_call_id!=null)Q.tool_call_id=$.tool_call_id}if($.additional_kwargs.audio&&typeof $.additional_kwargs.audio==="object"&&"id"in $.additional_kwargs.audio){let J={role:"assistant",audio:{id:$.additional_kwargs.audio.id}};return[Q,J]}return Q})};class J7 extends v8{invocationParams(X,Y){let $;if(X?.strict!==void 0)$=X.strict;else if(this.supportsStrictToolCalling!==void 0)$=this.supportsStrictToolCalling;let W={};if(X?.stream_options!==void 0)W={stream_options:X.stream_options};else if(this.streamUsage&&(this.streaming||Y?.streaming))W={stream_options:{include_usage:!0}};let Z={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:X?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:X?.functions,function_call:X?.function_call,tools:X?.tools?.length?X.tools.map((J)=>this._convertChatOpenAIToolToCompletionsTool(J,{strict:$})):void 0,tool_choice:e1(X?.tool_choice),response_format:this._getResponseFormat(X?.response_format),seed:X?.seed,...W,parallel_tool_calls:X?.parallel_tool_calls,...this.audio||X?.audio?{audio:this.audio||X?.audio}:{},...this.modalities||X?.modalities?{modalities:this.modalities||X?.modalities}:{},...this.modelKwargs,prompt_cache_key:X?.promptCacheKey??this.promptCacheKey,verbosity:X?.verbosity??this.verbosity};if(X?.prediction!==void 0)Z.prediction=X.prediction;if(this.service_tier!==void 0)Z.service_tier=this.service_tier;if(X?.service_tier!==void 0)Z.service_tier=X.service_tier;let Q=this._getReasoningParams(X);if(Q!==void 0&&Q.effort!==void 0)Z.reasoning_effort=Q.effort;if(this.reasoning)Z.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens;else Z.max_tokens=this.maxTokens===-1?void 0:this.maxTokens;return Z}async _generate(X,Y,$){let W={},Z=this.invocationParams(Y),Q=S9({messages:X,model:this.model});if(Z.stream){let J=this._streamResponseChunks(X,Y,$),G={};for await(let U of J){U.message.response_metadata={...U.generationInfo,...U.message.response_metadata};let E=U.generationInfo?.completion??0;if(G[E]===void 0)G[E]=U;else G[E]=G[E].concat(U)}let z=Object.entries(G).sort(([U],[E])=>parseInt(U,10)-parseInt(E,10)).map(([U,E])=>E),{functions:B,function_call:H}=this.invocationParams(Y),V=await this._getEstimatedTokenCountFromPrompt(X,B,H),K=await this._getNumTokensFromGenerations(z);return W.input_tokens=V,W.output_tokens=K,W.total_tokens=V+K,{generations:z,llmOutput:{estimatedTokenUsage:{promptTokens:W.input_tokens,completionTokens:W.output_tokens,totalTokens:W.total_tokens}}}}else{let J=await this.completionWithRetry({...Z,stream:!1,messages:Q},{signal:Y?.signal,...Y?.options}),{completion_tokens:G,prompt_tokens:z,total_tokens:B,prompt_tokens_details:H,completion_tokens_details:V}=J?.usage??{};if(G)W.output_tokens=(W.output_tokens??0)+G;if(z)W.input_tokens=(W.input_tokens??0)+z;if(B)W.total_tokens=(W.total_tokens??0)+B;if(H?.audio_tokens!==null||H?.cached_tokens!==null)W.input_token_details={...H?.audio_tokens!==null&&{audio:H?.audio_tokens},...H?.cached_tokens!==null&&{cache_read:H?.cached_tokens}};if(V?.audio_tokens!==null||V?.reasoning_tokens!==null)W.output_token_details={...V?.audio_tokens!==null&&{audio:V?.audio_tokens},...V?.reasoning_tokens!==null&&{reasoning:V?.reasoning_tokens}};let K=[];for(let U of J?.choices??[]){let E=U.message?.content??"",I=U.message?.reasoning_content??U.message?.reasoning??"",T={text:E,message:this._convertCompletionsMessageToBaseMessage(U.message??{role:"assistant"},J)};if(T.message.additional_kwargs={...T.message.additional_kwargs,reasoning_content:I},T.generationInfo={...U.finish_reason?{finish_reason:U.finish_reason}:{},...U.logprobs?{logprobs:U.logprobs}:{}},b8(T.message))T.message.usage_metadata=W;T.message=new r(Object.fromEntries(Object.entries(T.message).filter(([S])=>!S.startsWith("lc_")))),K.push(T)}return{generations:K,llmOutput:{tokenUsage:{promptTokens:W.input_tokens,completionTokens:W.output_tokens,totalTokens:W.total_tokens}}}}}async*_streamResponseChunks(X,Y,$){let W=S9({messages:X,model:this.model}),Z={...this.invocationParams(Y,{streaming:!0}),messages:W,stream:!0},Q,J=await this.completionWithRetry(Z,Y),G;for await(let z of J){let B=z?.choices?.[0];if(z.usage)G=z.usage;if(!B)continue;let{delta:H}=B;if(!H)continue;let V=this._convertCompletionsDeltaToBaseMessageChunk(H,z,Q),K=H.reasoning_content??H.reasoning??"";if(K)V.additional_kwargs={...V.additional_kwargs,reasoning_content:K};Q=H.role??Q;let U={prompt:Y.promptIndex??0,completion:B.index??0};if(typeof V.content!=="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let E={...U};if(B.finish_reason!=null)E.finish_reason=B.finish_reason,E.system_fingerprint=z.system_fingerprint,E.model_name=z.model,E.service_tier=z.service_tier;if(this.logprobs)E.logprobs=B.logprobs;let I=new tX({message:V,text:V.content,generationInfo:E});yield I,await $?.handleLLMNewToken(I.text??"",U,void 0,void 0,void 0,{chunk:I})}if(G){let z={...G.prompt_tokens_details?.audio_tokens!==null&&{audio:G.prompt_tokens_details?.audio_tokens},...G.prompt_tokens_details?.cached_tokens!==null&&{cache_read:G.prompt_tokens_details?.cached_tokens}},B={...G.completion_tokens_details?.audio_tokens!==null&&{audio:G.completion_tokens_details?.audio_tokens},...G.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:G.completion_tokens_details?.reasoning_tokens}};yield new tX({message:new u({content:"",response_metadata:{usage:{...G}},usage_metadata:{input_tokens:G.prompt_tokens,output_tokens:G.completion_tokens,total_tokens:G.total_tokens,...Object.keys(z).length>0&&{input_token_details:z},...Object.keys(B).length>0&&{output_token_details:B}}}),text:""})}if(Y.signal?.aborted)throw Error("AbortError")}async completionWithRetry(X,Y){let $=this._getClientOptions(Y),W=X.response_format&&X.response_format.type==="json_schema";return this.caller.call(async()=>{try{if(W&&!X.stream)return await this.client.chat.completions.parse(X,$);else return await this.client.chat.completions.create(X,$)}catch(Z){throw fX(Z)}})}_convertCompletionsDeltaToBaseMessageChunk(X,Y,$){return $2({delta:X,rawResponse:Y,includeRawResponse:this.__includeRawResponse,defaultRole:$})}_convertCompletionsMessageToBaseMessage(X,Y){return Y2({message:X,rawResponse:Y,includeRawResponse:this.__includeRawResponse})}}var Z2=class extends iY{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;serializableSchema;constructor(X){super(X);this.keyName=X.keyName,this.returnSingle=X.returnSingle??this.returnSingle,this.zodSchema=X.zodSchema,this.serializableSchema=X.serializableSchema}async _validateResult(X){let Y=X;if(typeof X==="string")try{Y=JSON.parse(X)}catch(W){throw new f8(`Failed to parse. Text: "${JSON.stringify(X,null,2)}". Error: ${JSON.stringify(W.message)}`,X)}else Y=X;if(this.serializableSchema!==void 0){let W=await this.serializableSchema["~standard"].validate(Y);if(W.issues)throw new f8(`Failed to parse. Text: "${JSON.stringify(Y,null,2)}". Error: ${JSON.stringify(W.issues)}`,JSON.stringify(Y,null,2));return W.value}if(this.zodSchema===void 0)return Y;let $=await lY(this.zodSchema,Y);if($.success)return $.data;else throw new f8(`Failed to parse. Text: "${JSON.stringify(X,null,2)}". Error: ${JSON.stringify($.error.issues)}`,JSON.stringify(Y,null,2))}async parseResult(X){let Y=X.flatMap((W)=>{let{message:Z}=W;if(!Array.isArray(Z.content))return[];return R9(Z.content)[0]});if(Y[0]===void 0)throw Error("No parseable tool calls provided to AnthropicToolsOutputParser.");let[$]=Y;return await this._validateResult($.args)}};function R9(X){let Y=[];for(let $ of X)if($.type==="tool_use")Y.push({name:$.name,args:$.input,id:$.id,type:"tool_call"});return Y}function K2(X){if(!X)return;else if(X==="any")return{type:"any"};else if(X==="auto")return{type:"auto"};else if(X==="none")return{type:"none"};else if(typeof X==="string")return{type:"tool",name:X};else return X}var V2=J2({cache_control:G2().optional().nullable(),defer_loading:Q2().optional(),input_examples:I9(C9()).optional(),allowed_callers:I9(C9()).optional()}),j9={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 z2(X){return typeof X==="object"&&X!==null&&"type"in X&&X.type==="thinking"}function H2(X){return typeof X==="object"&&X!==null&&"type"in X&&X.type==="redacted_thinking"}function nY(X){return typeof X==="object"&&X!==null&&"type"in X&&X.type==="compaction"}function B2(X){return typeof X==="object"&&X!==null&&"type"in X&&X.type==="search_result"}function N2(X){if(typeof X!=="object"||X==null)return!1;if(!("type"in X)||X.type!=="image")return!1;if(!("source"in X)||typeof X.source!=="object"||X.source==null)return!1;if(!("type"in X.source))return!1;if(X.source.type==="base64"){if(!("media_type"in X.source))return!1;if(typeof X.source.media_type!=="string")return!1;if(!("data"in X.source))return!1;if(typeof X.source.data!=="string")return!1;return!0}if(X.source.type==="url"){if(!("url"in X.source))return!1;if(typeof X.source.url!=="string")return!1;return!0}return!1}var U2={providerName:"anthropic",fromStandardTextBlock(X){return{type:"text",text:X.text,..."citations"in(X.metadata??{})?{citations:X.metadata.citations}:{},..."cache_control"in(X.metadata??{})?{cache_control:X.metadata.cache_control}:{}}},fromStandardImageBlock(X){if(X.source_type==="url"){let Y=OX({dataUrl:X.url,asTypedArray:!1});if(Y)return{type:"image",source:{type:"base64",data:Y.data,media_type:Y.mime_type},..."cache_control"in(X.metadata??{})?{cache_control:X.metadata.cache_control}:{}};else return{type:"image",source:{type:"url",url:X.url},..."cache_control"in(X.metadata??{})?{cache_control:X.metadata.cache_control}:{}}}else if(X.source_type==="base64")return{type:"image",source:{type:"base64",data:X.data,media_type:X.mime_type??""},..."cache_control"in(X.metadata??{})?{cache_control:X.metadata.cache_control}:{}};else throw Error(`Unsupported image source type: ${X.source_type}`)},fromStandardFileBlock(X){let Y=(X.mime_type??"").split(";")[0];if(X.source_type==="url"){if(Y==="application/pdf"||Y==="")return{type:"document",source:{type:"url",url:X.url},..."cache_control"in(X.metadata??{})?{cache_control:X.metadata.cache_control}:{},..."citations"in(X.metadata??{})?{citations:X.metadata.citations}:{},..."context"in(X.metadata??{})?{context:X.metadata.context}:{},..."title"in(X.metadata??{})?{title:X.metadata.title}:{}};throw Error(`Unsupported file mime type for file url source: ${X.mime_type}`)}else if(X.source_type==="text")if(Y==="text/plain"||Y==="")return{type:"document",source:{type:"text",data:X.text,media_type:X.mime_type??""},..."cache_control"in(X.metadata??{})?{cache_control:X.metadata.cache_control}:{},..."citations"in(X.metadata??{})?{citations:X.metadata.citations}:{},..."context"in(X.metadata??{})?{context:X.metadata.context}:{},..."title"in(X.metadata??{})?{title:X.metadata.title}:{}};else throw Error(`Unsupported file mime type for file text source: ${X.mime_type}`);else if(X.source_type==="base64")if(Y==="application/pdf"||Y==="")return{type:"document",source:{type:"base64",data:X.data,media_type:"application/pdf"},..."cache_control"in(X.metadata??{})?{cache_control:X.metadata.cache_control}:{},..."citations"in(X.metadata??{})?{citations:X.metadata.citations}:{},..."context"in(X.metadata??{})?{context:X.metadata.context}:{},..."title"in(X.metadata??{})?{title:X.metadata.title}:{}};else if(["image/jpeg","image/png","image/gif","image/webp"].includes(Y))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:X.data,media_type:Y}}]},..."cache_control"in(X.metadata??{})?{cache_control:X.metadata.cache_control}:{},..."citations"in(X.metadata??{})?{citations:X.metadata.citations}:{},..."context"in(X.metadata??{})?{context:X.metadata.context}:{},..."title"in(X.metadata??{})?{title:X.metadata.title}:{}};else throw Error(`Unsupported file mime type for file base64 source: ${X.mime_type}`);else throw Error(`Unsupported file source type: ${X.source_type}`)}};var w2=(X)=>X();function a3(X){return typeof X==="object"&&X!==null&&"type"in X&&X.type==="citation"}function t3(X){function*Y(){for(let $ of X)if(a3($)){if($.source==="char")yield{type:"char_location",file_id:$.url??"",start_char_index:$.startIndex??0,end_char_index:$.endIndex??0,document_title:$.title??null,document_index:0,cited_text:$.citedText??""};else if($.source==="page")yield{type:"page_location",file_id:$.url??"",start_page_number:$.startIndex??0,end_page_number:$.endIndex??0,document_title:$.title??null,document_index:0,cited_text:$.citedText??""};else if($.source==="block")yield{type:"content_block_location",file_id:$.url??"",start_block_index:$.startIndex??0,end_block_index:$.endIndex??0,document_title:$.title??null,document_index:0,cited_text:$.citedText??""};else if($.source==="url")yield{type:"web_search_result_location",url:$.url??"",title:$.title??null,encrypted_index:String($.startIndex??0),cited_text:$.citedText??""};else if($.source==="search")yield{type:"search_result_location",title:$.title??null,start_block_index:$.startIndex??0,end_block_index:$.endIndex??0,search_result_index:0,source:$.source??"",cited_text:$.citedText??""}}}return Array.from(Y())}function G7(X){if(typeof X==="string")return X;else return s3(X)}function s3(X){let Y=[];for(let $=0,{length:W}=X;$<W;$++)Y.push(String.fromCharCode(X[$]));return btoa(Y.join(""))}function _9(X){return(X??"").split(";")[0].toLowerCase()}function K7(X,Y){if(X!==void 0&&X!==null&&typeof X==="object"&&Y in X)return X[Y]}function h8(X,Y){let $=K7(Y,"cache_control");if($!==void 0)X.cache_control=$;let W=K7(Y,"citations");if(W!==void 0)X.citations=W;let Z=K7(Y,"context");if(Z!==void 0)X.context=Z;let Q=K7(Y,"title");if(Q!==void 0)X.title=Q;return X}function y9(X,Y){let $=K7(Y,"cache_control");if($!==void 0)X.cache_control=$;return X}function q2(X){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(X)}function F2(X){let Y=[],$=X.response_metadata,W="model_provider"in $&&$?.model_provider==="anthropic";for(let Z of X.contentBlocks)if(Z.type==="text")if(Z.annotations)Y.push({type:"text",text:Z.text,citations:t3(Z.annotations)});else Y.push({type:"text",text:Z.text});else if(Z.type==="tool_call")Y.push({type:"tool_use",id:Z.id??"",name:Z.name,input:Z.args});else if(Z.type==="tool_call_chunk"){let Q=w2(()=>{if(typeof Z.args!=="string")return Z.args;try{return JSON.parse(Z.args)}catch{return{}}});Y.push({type:"tool_use",id:Z.id??"",name:Z.name??"",input:Q})}else if(Z.type==="reasoning"&&W)Y.push({type:"thinking",thinking:Z.reasoning,signature:String(Z.signature)});else if(Z.type==="server_tool_call"&&W){if(Z.name==="web_search")Y.push({type:"server_tool_use",name:Z.name,id:Z.id??"",input:Z.args});else if(Z.name==="code_execution")Y.push({type:"server_tool_use",name:Z.name,id:Z.id??"",input:Z.args})}else if(Z.type==="server_tool_call_result"&&W){if(Z.name==="web_search"&&Array.isArray(Z.output.urls)){let Q=Z.output.urls.map((J)=>({type:"web_search_result",title:"",encrypted_content:"",url:J}));Y.push({type:"web_search_tool_result",tool_use_id:Z.toolCallId??"",content:Q})}else if(Z.name==="code_execution")Y.push({type:"code_execution_tool_result",tool_use_id:Z.toolCallId??"",content:Z.output});else if(Z.name==="mcp_tool_result")Y.push({type:"mcp_tool_result",tool_use_id:Z.toolCallId??"",content:Z.output})}else if(Z.type==="audio")throw Error("Anthropic does not support audio content blocks.");else if(Z.type==="file"){let Q=Z.metadata;if(Z.fileId){Y.push(h8({type:"document",source:{type:"file",file_id:Z.fileId}},Q));continue}if(Z.url){let J=_9(Z.mimeType);if(J==="application/pdf"||J===""){Y.push(h8({type:"document",source:{type:"url",url:Z.url}},Q));continue}}if(Z.data){let J=_9(Z.mimeType);if(J===""||J==="application/pdf")Y.push(h8({type:"document",source:{type:"base64",data:G7(Z.data),media_type:"application/pdf"}},Q));else if(J==="text/plain")Y.push(h8({type:"document",source:{type:"text",data:G7(Z.data),media_type:"text/plain"}},Q));else if(q2(J))Y.push(h8({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:G7(Z.data),media_type:J}}]}},Q));else throw Error(`Unsupported file mime type for Anthropic base64 source: ${J}`);continue}throw Error("File content block must include a fileId, url, or data property.")}else if(Z.type==="image"){let Q=Z.metadata;if(Z.fileId){Y.push(y9({type:"image",source:{type:"file",file_id:Z.fileId}},Q));continue}if(Z.url){Y.push(y9({type:"image",source:{type:"url",url:Z.url}},Q));continue}if(Z.data){let J=_9(Z.mimeType)||"image/png";if(q2(J))Y.push(y9({type:"image",source:{type:"base64",data:G7(Z.data),media_type:J}},Q));continue}throw Error("Image content block must include a fileId, url, or data property.")}else if(Z.type==="video");else if(Z.type==="text-plain"){if(Z.data)Y.push(h8({type:"document",source:{type:"text",data:G7(Z.data),media_type:"text/plain"}},Z.metadata))}else if(Z.type==="non_standard"&&W)Y.push(Z.value);return Y}function k9(X){let Y=OX({dataUrl:X});if(Y)return{type:"base64",media_type:Y.mime_type,data:Y.data};let $;try{$=new URL(X)}catch{throw Error([`Malformed image URL: ${JSON.stringify(X)}. 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(`
|
|
56
|
+
|
|
57
|
+
`))}if($.protocol==="http:"||$.protocol==="https:")return{type:"url",url:X};throw Error([`Invalid image URL protocol: ${JSON.stringify($.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(`
|
|
58
|
+
|
|
59
|
+
`))}function o3(X){let Y=[];for(let $ of X)if($._getType()==="tool")if(typeof $.content==="string"){let W=Y[Y.length-1];if(W?._getType()==="human"&&Array.isArray(W.content)&&"type"in W.content[0]&&W.content[0].type==="tool_result")W.content.push({type:"tool_result",content:$.content,tool_use_id:$.tool_call_id});else Y.push(new t8({content:[{type:"tool_result",content:$.content,tool_use_id:$.tool_call_id}]}))}else Y.push(new t8({content:[{type:"tool_result",...$.content!=null?{content:b9($)}:{},tool_use_id:$.tool_call_id}]}));else Y.push($);return Y}function v9(X){if(X.id===void 0)throw Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:X.id,name:X.name,input:X.args}}function*e3(X,Y){let $=["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"],W=["text","text_delta"];for(let Z of X){if(x0(Z))yield O0(Z,U2);let Q="cache_control"in Z?Z.cache_control:void 0;if(Z.type==="image_url"){let J;if(typeof Z.image_url==="string")J=k9(Z.image_url);else if(typeof Z.image_url==="object"&&Z.image_url!==null&&"url"in Z.image_url&&typeof Z.image_url.url==="string")J=k9(Z.image_url.url);if(J)yield{type:"image",source:J,...Q?{cache_control:Q}:{}}}else if(N2(Z))yield Z;else if(Z.type==="image"){let J;if("url"in Z&&typeof Z.url==="string")J=k9(Z.url);else if("data"in Z&&(typeof Z.data==="string"||Z.data instanceof Uint8Array))J={type:"base64",media_type:"mimeType"in Z&&typeof Z.mimeType==="string"?Z.mimeType:"image/jpeg",data:typeof Z.data==="string"?Z.data:Buffer.from(Z.data).toString("base64")};else if("fileId"in Z&&typeof Z.fileId==="string")J={type:"file",file_id:Z.fileId};if(J)yield{type:"image",source:J,...Q?{cache_control:Q}:{}}}else if(Z.type==="file"){let J;if("url"in Z&&typeof Z.url==="string")J={type:"url",url:Z.url};else if("data"in Z&&(typeof Z.data==="string"||Z.data instanceof Uint8Array))J={type:"base64",media_type:"mimeType"in Z&&typeof Z.mimeType==="string"?Z.mimeType:"application/pdf",data:typeof Z.data==="string"?Z.data:Buffer.from(Z.data).toString("base64")};else if("fileId"in Z&&typeof Z.fileId==="string")J={type:"file",file_id:Z.fileId};if(J)yield{type:"document",source:J,...Q?{cache_control:Q}:{}}}else if(Z.type==="document")yield{...Z,...Q?{cache_control:Q}:{}};else if(z2(Z))yield{type:"thinking",thinking:Z.thinking,signature:Z.signature,...Q?{cache_control:Q}:{}};else if(H2(Z))yield{type:"redacted_thinking",data:Z.data,...Q?{cache_control:Q}:{}};else if(nY(Z))yield{type:"compaction",content:Z.content,...Q?{cache_control:Q}:{}};else if(B2(Z))yield{type:"search_result",title:Z.title,source:Z.source,..."cache_control"in Z&&Z.cache_control?{cache_control:Z.cache_control}:{},..."citations"in Z&&Z.citations?{citations:Z.citations}:{},content:Z.content};else if(W.find((J)=>J===Z.type)&&"text"in Z)yield{type:"text",text:Z.text,...Q?{cache_control:Q}:{},..."citations"in Z&&Z.citations?{citations:Z.citations}:{}};else if($.find((J)=>J===Z.type)){let J={...Z};if(J.type==="input_json_delta")continue;if(J.type==="tool_use"&&typeof J.input==="string"){let G=Y?.find((z)=>z.id===J.id);if(G)J.input=G.args;else J.input=X.filter((z)=>z.index===J.index&&z.type==="input_json_delta"&&typeof z.input==="string").reduce((z,B)=>z+B.input,J.input)}if("index"in J)delete J.index;if("input"in J){if(typeof J.input==="string")try{J.input=JSON.parse(J.input)}catch{J.input={}}}yield{...J,...Q?{cache_control:Q}:{}}}else if(Z.type==="container_upload")yield{...Z,...Q?{cache_control:Q}:{}}}}function b9(X,Y){let{content:$}=X;if(typeof $==="string")return $;else return Array.from(e3($,Y))}function rY(X){let Y=o3(X),$;if(Y.length>0&&Y[0]._getType()==="system")$=X[0].content;return{messages:XJ(($!==void 0?Y.slice(1):Y).map((W)=>{let Z;if(W._getType()==="human")Z="user";else if(W._getType()==="ai")Z="assistant";else if(W._getType()==="tool")Z="user";else if(W._getType()==="system")throw Error("System messages are only permitted as the first passed message.");else throw Error(`Message type "${W.type}" is not supported.`);if(r.isInstance(W)&&W.response_metadata?.output_version==="v1")return{role:Z,content:F2(W)};if(r.isInstance(W)&&!!W.tool_calls?.length)if(typeof W.content==="string")if(W.content==="")return{role:Z,content:W.tool_calls.map(v9)};else return{role:Z,content:[{type:"text",text:W.content},...W.tool_calls.map(v9)]};else{let{content:Q}=W,J=b9(W,W.tool_calls),G=Array.isArray(J)?J:[{type:"text",text:J}],z=W.tool_calls.filter((B)=>!Q.find((H)=>(H.type==="tool_use"||H.type==="input_json_delta"||H.type==="server_tool_use")&&H.id===B.id));return{role:Z,content:[...G,...z.map(v9)]}}else return{role:Z,content:b9(W,r.isInstance(W)?W.tool_calls:void 0)}})),system:$}}function f9(X,Y){if(!X.messages||X.messages.length===0)return X;let $=[...X.messages],W=$.length-1,Z=$[W];if(!Z)return X;if(typeof Z.content==="string")return $[W]={...Z,content:[{type:"text",text:Z.content,cache_control:Y}]},{...X,messages:$};if(Array.isArray(Z.content)&&Z.content.length>0){let Q=[...Z.content],J=Q.length-1;return Q[J]={...Q[J],cache_control:Y},$[W]={...Z,content:Q},{...X,messages:$}}return X}function XJ(X){if(!X||X.length<=1)return X;let Y=[],$=X[0],W=(Q)=>{if(typeof Q==="string")return[{type:"text",text:Q}];return Q},Z=(Q)=>{if(Q.role!=="user")return!1;if(typeof Q.content==="string")return!1;return Array.isArray(Q.content)&&Q.content.every((J)=>J.type==="tool_result")};for(let Q=1;Q<X.length;Q+=1){let J=X[Q];if(Z($)&&Z(J))$={...$,content:[...W($.content),...W(J.content)]};else Y.push($),$=J}return Y.push($),Y}function L2(X,Y){let $={model_provider:"anthropic"};if(X.type==="message_start"){let{content:W,usage:Z,...Q}=X.message,J={};for(let[V,K]of Object.entries(Q))if(K!==void 0&&K!==null)J[V]=K;let{input_tokens:G,output_tokens:z,...B}=Z??{},H=x2(Z);return{chunk:new u({content:Y.coerceContentToString?"":[],additional_kwargs:J,usage_metadata:Y.streamUsage?H:void 0,response_metadata:{...$,usage:{...B}},id:X.message.id})}}else if(X.type==="message_delta"){let W={input_tokens:0,output_tokens:X.usage.output_tokens,total_tokens:X.usage.output_tokens,input_token_details:{cache_creation:X.usage.cache_creation_input_tokens,cache_read:X.usage.cache_read_input_tokens}},Z="context_management"in X.delta?{context_management:X.delta.context_management}:void 0;return{chunk:new u({content:Y.coerceContentToString?"":[],response_metadata:Z,additional_kwargs:{...X.delta},usage_metadata:Y.streamUsage?W:void 0})}}else if(X.type==="content_block_start"&&["tool_use","document","server_tool_use","web_search_tool_result"].includes(X.content_block.type)){let W=X.content_block,Z;if(W.type==="tool_use")Z=[{id:W.id,index:X.index,name:W.name,args:""}];else Z=[];return{chunk:new u({content:Y.coerceContentToString?"":[{index:X.index,...X.content_block,input:W.type==="server_tool_use"||W.type==="tool_use"?"":void 0}],response_metadata:$,additional_kwargs:{},tool_call_chunks:Z})}}else if(X.type==="content_block_delta"&&["text_delta","citations_delta","thinking_delta","signature_delta"].includes(X.delta.type))if(Y.coerceContentToString&&"text"in X.delta)return{chunk:new u({content:X.delta.text})};else{let W=X.delta;if("citation"in W)W.citations=[W.citation],delete W.citation;if(W.type==="thinking_delta"||W.type==="signature_delta")return{chunk:new u({content:[{index:X.index,...W,type:"thinking"}],response_metadata:$})};return{chunk:new u({content:[{index:X.index,...W,type:"text"}],response_metadata:$})}}else if(X.type==="content_block_delta"&&X.delta.type==="input_json_delta")return{chunk:new u({content:Y.coerceContentToString?"":[{index:X.index,input:X.delta.partial_json,type:X.delta.type}],response_metadata:$,additional_kwargs:{},tool_call_chunks:[{index:X.index,args:X.delta.partial_json}]})};else if(X.type==="content_block_start"&&X.content_block.type==="text"){let W=X.content_block?.text;if(W!==void 0)return{chunk:new u({content:Y.coerceContentToString?W:[{index:X.index,...X.content_block}],response_metadata:$,additional_kwargs:{}})}}else if(X.type==="content_block_start"&&X.content_block.type==="redacted_thinking")return{chunk:new u({content:Y.coerceContentToString?"":[{index:X.index,...X.content_block}],response_metadata:$})};else if(X.type==="content_block_start"&&X.content_block.type==="thinking"){let W=X.content_block.thinking;return{chunk:new u({content:Y.coerceContentToString?W:[{index:X.index,...X.content_block}],response_metadata:$})}}else if(X.type==="content_block_start"&&nY(X.content_block))return{chunk:new u({content:Y.coerceContentToString?"":[{index:X.index,...X.content_block}],response_metadata:$})};else if(X.type==="content_block_delta"&&X.delta.type==="compaction_delta")return{chunk:new u({content:Y.coerceContentToString?"":[{index:X.index,...X.delta,type:"compaction"}],response_metadata:$})};return null}function E2(X,Y){let $={...Y,model_provider:"anthropic"},W=Y.usage,Z=W!=null?x2(W):void 0;if(X.length===1&&X[0].type==="text")return[{text:X[0].text,message:new r({content:X[0].text,additional_kwargs:Y,usage_metadata:Z,response_metadata:$,id:Y.id})}];else return[{text:"",message:new r({content:X,additional_kwargs:Y,tool_calls:R9(X),usage_metadata:Z,response_metadata:$,id:Y.id})}]}function x2(X){let Y=X.cache_creation_input_tokens??0,$=X.cache_read_input_tokens??0,W=X.input_tokens+Y+$;return{input_tokens:W,output_tokens:X.output_tokens,total_tokens:W+X.output_tokens,input_token_details:{cache_creation:Y,cache_read:$}}}function aY(X,Y){return X.lc_error_code=Y,X.message=`${X.message}
|
|
60
|
+
|
|
61
|
+
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${Y}/
|
|
62
|
+
`,X}function h9(X){let Y;if(X.status===400&&typeof X.message==="string"&&X.message.includes("prompt is too long"))Y=vY.fromError(X);else if(X.status===400&&X.message.includes("tool"))Y=aY(X,"INVALID_TOOL_RESULTS");else if(X.status===401)Y=aY(X,"MODEL_AUTHENTICATION");else if(X.status===404)Y=aY(X,"MODEL_NOT_FOUND");else if(X.status===429)Y=aY(X,"MODEL_RATE_LIMIT");else Y=X;return Y}var O2={"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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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},"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-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}};function O(X,Y,$,W,Z){if(W==="m")throw TypeError("Private method is not writable");if(W==="a"&&!Z)throw TypeError("Private accessor was defined without a setter");if(typeof Y==="function"?X!==Y||!Z:!Y.has(X))throw TypeError("Cannot write private member to an object whose class did not declare it");return W==="a"?Z.call(X,$):Z?Z.value=$:Y.set(X,$),$}function q(X,Y,$,W){if($==="a"&&!W)throw TypeError("Private accessor was defined without a getter");if(typeof Y==="function"?X!==Y||!W:!Y.has(X))throw TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?W:$==="a"?W.call(X):W?W.value:Y.get(X)}var g9=function(){let{crypto:X}=globalThis;if(X?.randomUUID)return g9=X.randomUUID.bind(X),X.randomUUID();let Y=new Uint8Array(1),$=X?()=>X.getRandomValues(Y)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(W)=>(+W^$()&15>>+W/4).toString(16))};function sX(X){return typeof X==="object"&&X!==null&&(("name"in X)&&X.name==="AbortError"||("message"in X)&&String(X.message).includes("FetchRequestCanceledException"))}var V7=(X)=>{if(X instanceof Error)return X;if(typeof X==="object"&&X!==null){try{if(Object.prototype.toString.call(X)==="[object Error]"){let Y=Error(X.message,X.cause?{cause:X.cause}:{});if(X.stack)Y.stack=X.stack;if(X.cause&&!Y.cause)Y.cause=X.cause;if(X.name)Y.name=X.name;return Y}}catch{}try{return Error(JSON.stringify(X))}catch{}}return Error(X)};class M extends Error{}class s extends M{constructor(X,Y,$,W){super(`${s.makeMessage(X,Y,$)}`);this.status=X,this.headers=W,this.requestID=W?.get("request-id"),this.error=Y}static makeMessage(X,Y,$){let W=Y?.message?typeof Y.message==="string"?Y.message:JSON.stringify(Y.message):Y?JSON.stringify(Y):$;if(X&&W)return`${X} ${W}`;if(X)return`${X} status code (no body)`;if(W)return W;return"(no status code or body)"}static generate(X,Y,$,W){if(!X||!W)return new r0({message:$,cause:V7(Y)});let Z=Y;if(X===400)return new H7(X,Z,$,W);if(X===401)return new B7(X,Z,$,W);if(X===403)return new N7(X,Z,$,W);if(X===404)return new U7(X,Z,$,W);if(X===409)return new w7(X,Z,$,W);if(X===422)return new q7(X,Z,$,W);if(X===429)return new F7(X,Z,$,W);if(X>=500)return new L7(X,Z,$,W);return new s(X,Z,$,W)}}class GX extends s{constructor({message:X}={}){super(void 0,void 0,X||"Request was aborted.",void 0)}}class r0 extends s{constructor({message:X,cause:Y}){super(void 0,void 0,X||"Connection error.",void 0);if(Y)this.cause=Y}}class z7 extends r0{constructor({message:X}={}){super({message:X??"Request timed out."})}}class H7 extends s{}class B7 extends s{}class N7 extends s{}class U7 extends s{}class w7 extends s{}class q7 extends s{}class F7 extends s{}class L7 extends s{}var $J=/^[a-z][a-z0-9+.-]*:/i,D2=(X)=>{return $J.test(X)},u9=(X)=>(u9=Array.isArray,u9(X)),d9=u9;function tY(X){if(typeof X!=="object")return{};return X??{}}function M2(X){if(!X)return!0;for(let Y in X)return!1;return!0}function T2(X,Y){return Object.prototype.hasOwnProperty.call(X,Y)}var A2=(X,Y)=>{if(typeof Y!=="number"||!Number.isInteger(Y))throw new M(`${X} must be an integer`);if(Y<0)throw new M(`${X} must be a positive integer`);return Y};var sY=(X)=>{try{return JSON.parse(X)}catch(Y){return}},zX=(X,Y)=>{let $=X[Y];return delete X[Y],$};var P2=(X)=>new Promise((Y)=>setTimeout(Y,X));var D0="0.74.0";var I2=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function WJ(){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 ZJ=()=>{let X=WJ();if(X==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":D0,"X-Stainless-OS":R2(Deno.build.os),"X-Stainless-Arch":S2(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":D0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(X==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":D0,"X-Stainless-OS":R2(globalThis.process.platform??"unknown"),"X-Stainless-Arch":S2(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Y=QJ();if(Y)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":D0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Y.browser}`,"X-Stainless-Runtime-Version":Y.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":D0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function QJ(){if(typeof navigator>"u"||!navigator)return null;let X=[{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:Y,pattern:$}of X){let W=$.exec(navigator.userAgent);if(W){let Z=W[1]||0,Q=W[2]||0,J=W[3]||0;return{browser:Y,version:`${Z}.${Q}.${J}`}}}return null}var S2=(X)=>{if(X==="x32")return"x32";if(X==="x86_64"||X==="x64")return"x64";if(X==="arm")return"arm";if(X==="aarch64"||X==="arm64")return"arm64";if(X)return`other:${X}`;return"unknown"},R2=(X)=>{if(X=X.toLowerCase(),X.includes("ios"))return"iOS";if(X==="android")return"Android";if(X==="darwin")return"MacOS";if(X==="win32")return"Windows";if(X==="freebsd")return"FreeBSD";if(X==="openbsd")return"OpenBSD";if(X==="linux")return"Linux";if(X)return`Other:${X}`;return"Unknown"},C2,j2=()=>{return C2??(C2=ZJ())};function _2(){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 m9(...X){let Y=globalThis.ReadableStream;if(typeof Y>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Y(...X)}function oY(X){let Y=Symbol.asyncIterator in X?X[Symbol.asyncIterator]():X[Symbol.iterator]();return m9({start(){},async pull($){let{done:W,value:Z}=await Y.next();if(W)$.close();else $.enqueue(Z)},async cancel(){await Y.return?.()}})}function E7(X){if(X[Symbol.asyncIterator])return X;let Y=X.getReader();return{async next(){try{let $=await Y.read();if($?.done)Y.releaseLock();return $}catch($){throw Y.releaseLock(),$}},async return(){let $=Y.cancel();return Y.releaseLock(),await $,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function y2(X){if(X===null||typeof X!=="object")return;if(X[Symbol.asyncIterator]){await X[Symbol.asyncIterator]().return?.();return}let Y=X.getReader(),$=Y.cancel();Y.releaseLock(),await $}var k2=({headers:X,body:Y})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Y)}};function f2(X){let Y=0;for(let Z of X)Y+=Z.length;let $=new Uint8Array(Y),W=0;for(let Z of X)$.set(Z,W),W+=Z.length;return $}var v2;function g8(X){let Y;return(v2??(Y=new globalThis.TextEncoder,v2=Y.encode.bind(Y)))(X)}var b2;function c9(X){let Y;return(b2??(Y=new globalThis.TextDecoder,b2=Y.decode.bind(Y)))(X)}var FX,LX;class M0{constructor(){FX.set(this,void 0),LX.set(this,void 0),O(this,FX,new Uint8Array,"f"),O(this,LX,null,"f")}decode(X){if(X==null)return[];let Y=X instanceof ArrayBuffer?new Uint8Array(X):typeof X==="string"?g8(X):X;O(this,FX,f2([q(this,FX,"f"),Y]),"f");let $=[],W;while((W=KJ(q(this,FX,"f"),q(this,LX,"f")))!=null){if(W.carriage&&q(this,LX,"f")==null){O(this,LX,W.index,"f");continue}if(q(this,LX,"f")!=null&&(W.index!==q(this,LX,"f")+1||W.carriage)){$.push(c9(q(this,FX,"f").subarray(0,q(this,LX,"f")-1))),O(this,FX,q(this,FX,"f").subarray(q(this,LX,"f")),"f"),O(this,LX,null,"f");continue}let Z=q(this,LX,"f")!==null?W.preceding-1:W.preceding,Q=c9(q(this,FX,"f").subarray(0,Z));$.push(Q),O(this,FX,q(this,FX,"f").subarray(W.index),"f"),O(this,LX,null,"f")}return $}flush(){if(!q(this,FX,"f").length)return[];return this.decode(`
|
|
63
|
+
`)}}FX=new WeakMap,LX=new WeakMap;M0.NEWLINE_CHARS=new Set([`
|
|
64
|
+
`,"\r"]);M0.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function KJ(X,Y){for(let Z=Y??0;Z<X.length;Z++){if(X[Z]===10)return{preceding:Z,index:Z+1,carriage:!1};if(X[Z]===13)return{preceding:Z,index:Z+1,carriage:!0}}return null}function h2(X){for(let W=0;W<X.length-1;W++){if(X[W]===10&&X[W+1]===10)return W+2;if(X[W]===13&&X[W+1]===13)return W+2;if(X[W]===13&&X[W+1]===10&&W+3<X.length&&X[W+2]===13&&X[W+3]===10)return W+4}return-1}var X$={off:0,error:200,warn:300,info:400,debug:500},p9=(X,Y,$)=>{if(!X)return;if(T2(X$,X))return X;YX($).warn(`${Y} was set to ${JSON.stringify(X)}, expected one of ${JSON.stringify(Object.keys(X$))}`);return};function x7(){}function eY(X,Y,$){if(!Y||X$[X]>X$[$])return x7;else return Y[X].bind(Y)}var VJ={error:x7,warn:x7,info:x7,debug:x7},g2=new WeakMap;function YX(X){let Y=X.logger,$=X.logLevel??"off";if(!Y)return VJ;let W=g2.get(Y);if(W&&W[0]===$)return W[1];let Z={error:eY("error",Y,$),warn:eY("warn",Y,$),info:eY("info",Y,$),debug:eY("debug",Y,$)};return g2.set(Y,[$,Z]),Z}var oX=(X)=>{if(X.options)X.options={...X.options},delete X.options.headers;if(X.headers)X.headers=Object.fromEntries((X.headers instanceof Headers?[...X.headers]:Object.entries(X.headers)).map(([Y,$])=>[Y,Y.toLowerCase()==="x-api-key"||Y.toLowerCase()==="authorization"||Y.toLowerCase()==="cookie"||Y.toLowerCase()==="set-cookie"?"***":$]));if("retryOfRequestLogID"in X){if(X.retryOfRequestLogID)X.retryOf=X.retryOfRequestLogID;delete X.retryOfRequestLogID}return X};var O7;class EX{constructor(X,Y,$){this.iterator=X,O7.set(this,void 0),this.controller=Y,O(this,O7,$,"f")}static fromSSEResponse(X,Y,$){let W=!1,Z=$?YX($):console;async function*Q(){if(W)throw new M("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");W=!0;let J=!1;try{for await(let G of zJ(X,Y)){if(G.event==="completion")try{yield JSON.parse(G.data)}catch(z){throw Z.error("Could not parse message into JSON:",G.data),Z.error("From chunk:",G.raw),z}if(G.event==="message_start"||G.event==="message_delta"||G.event==="message_stop"||G.event==="content_block_start"||G.event==="content_block_delta"||G.event==="content_block_stop")try{yield JSON.parse(G.data)}catch(z){throw Z.error("Could not parse message into JSON:",G.data),Z.error("From chunk:",G.raw),z}if(G.event==="ping")continue;if(G.event==="error")throw new s(void 0,sY(G.data)??G.data,void 0,X.headers)}J=!0}catch(G){if(sX(G))return;throw G}finally{if(!J)Y.abort()}}return new EX(Q,Y,$)}static fromReadableStream(X,Y,$){let W=!1;async function*Z(){let J=new M0,G=E7(X);for await(let z of G)for(let B of J.decode(z))yield B;for(let z of J.flush())yield z}async function*Q(){if(W)throw new M("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");W=!0;let J=!1;try{for await(let G of Z()){if(J)continue;if(G)yield JSON.parse(G)}J=!0}catch(G){if(sX(G))return;throw G}finally{if(!J)Y.abort()}}return new EX(Q,Y,$)}[(O7=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let X=[],Y=[],$=this.iterator(),W=(Z)=>{return{next:()=>{if(Z.length===0){let Q=$.next();X.push(Q),Y.push(Q)}return Z.shift()}}};return[new EX(()=>W(X),this.controller,q(this,O7,"f")),new EX(()=>W(Y),this.controller,q(this,O7,"f"))]}toReadableStream(){let X=this,Y;return m9({async start(){Y=X[Symbol.asyncIterator]()},async pull($){try{let{value:W,done:Z}=await Y.next();if(Z)return $.close();let Q=g8(JSON.stringify(W)+`
|
|
65
|
+
`);$.enqueue(Q)}catch(W){$.error(W)}},async cancel(){await Y.return?.()}})}}async function*zJ(X,Y){if(!X.body){if(Y.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new M("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new M("Attempted to iterate over a response with no body")}let $=new u2,W=new M0,Z=E7(X.body);for await(let Q of HJ(Z))for(let J of W.decode(Q)){let G=$.decode(J);if(G)yield G}for(let Q of W.flush()){let J=$.decode(Q);if(J)yield J}}async function*HJ(X){let Y=new Uint8Array;for await(let $ of X){if($==null)continue;let W=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?g8($):$,Z=new Uint8Array(Y.length+W.length);Z.set(Y),Z.set(W,Y.length),Y=Z;let Q;while((Q=h2(Y))!==-1)yield Y.slice(0,Q),Y=Y.slice(Q)}if(Y.length>0)yield Y}class u2{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(X){if(X.endsWith("\r"))X=X.substring(0,X.length-1);if(!X){if(!this.event&&!this.data.length)return null;let Z={event:this.event,data:this.data.join(`
|
|
66
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],Z}if(this.chunks.push(X),X.startsWith(":"))return null;let[Y,$,W]=BJ(X,":");if(W.startsWith(" "))W=W.substring(1);if(Y==="event")this.event=W;else if(Y==="data")this.data.push(W);return null}}function BJ(X,Y){let $=X.indexOf(Y);if($!==-1)return[X.substring(0,$),Y,X.substring($+Y.length)];return[X,"",""]}async function Y$(X,Y){let{response:$,requestLogID:W,retryOfRequestLogID:Z,startTime:Q}=Y,J=await(async()=>{if(Y.options.stream){if(YX(X).debug("response",$.status,$.url,$.headers,$.body),Y.options.__streamClass)return Y.options.__streamClass.fromSSEResponse($,Y.controller);return EX.fromSSEResponse($,Y.controller)}if($.status===204)return null;if(Y.options.__binaryResponse)return $;let z=$.headers.get("content-type")?.split(";")[0]?.trim();if(z?.includes("application/json")||z?.endsWith("+json")){if($.headers.get("content-length")==="0")return;let K=await $.json();return l9(K,$)}return await $.text()})();return YX(X).debug(`[${W}] response parsed`,oX({retryOfRequestLogID:Z,url:$.url,status:$.status,body:J,durationMs:Date.now()-Q})),J}function l9(X,Y){if(!X||typeof X!=="object"||Array.isArray(X))return X;return Object.defineProperty(X,"_request_id",{value:Y.headers.get("request-id"),enumerable:!1})}var D7;class a0 extends Promise{constructor(X,Y,$=Y$){super((W)=>{W(null)});this.responsePromise=Y,this.parseResponse=$,D7.set(this,void 0),O(this,D7,X,"f")}_thenUnwrap(X){return new a0(q(this,D7,"f"),this.responsePromise,async(Y,$)=>l9(X(await this.parseResponse(Y,$),$),$.response))}asResponse(){return this.responsePromise.then((X)=>X.response)}async withResponse(){let[X,Y]=await Promise.all([this.parse(),this.asResponse()]);return{data:X,response:Y,request_id:Y.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then((X)=>this.parseResponse(q(this,D7,"f"),X));return this.parsedPromise}then(X,Y){return this.parse().then(X,Y)}catch(X){return this.parse().catch(X)}finally(X){return this.parse().finally(X)}}D7=new WeakMap;var $$;class i9{constructor(X,Y,$,W){$$.set(this,void 0),O(this,$$,X,"f"),this.options=W,this.response=Y,this.body=$}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let X=this.nextPageRequestOptions();if(!X)throw new M("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await q(this,$$,"f").requestAPIList(this.constructor,X)}async*iterPages(){let X=this;yield X;while(X.hasNextPage())X=await X.getNextPage(),yield X}async*[($$=new WeakMap,Symbol.asyncIterator)](){for await(let X of this.iterPages())for(let Y of X.getPaginatedItems())yield Y}}class W$ extends a0{constructor(X,Y,$){super(X,Y,async(W,Z)=>new $(W,Z.response,await Y$(W,Z),Z.options))}async*[Symbol.asyncIterator](){let X=await this;for await(let Y of X)yield Y}}class CX extends i9{constructor(X,Y,$,W){super(X,Y,$,W);this.data=$.data||[],this.has_more=$.has_more||!1,this.first_id=$.first_id||null,this.last_id=$.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 Y=this.first_id;if(!Y)return null;return{...this.options,query:{...tY(this.options.query),before_id:Y}}}let X=this.last_id;if(!X)return null;return{...this.options,query:{...tY(this.options.query),after_id:X}}}}class M7 extends i9{constructor(X,Y,$,W){super(X,Y,$,W);this.data=$.data||[],this.has_more=$.has_more||!1,this.next_page=$.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let X=this.next_page;if(!X)return null;return{...this.options,query:{...tY(this.options.query),page:X}}}}var r9=()=>{if(typeof File>"u"){let{process:X}=globalThis,Y=typeof X?.versions?.node==="string"&&parseInt(X.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(Y?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function t0(X,Y,$){return r9(),new File(X,Y??"unknown_file",$)}function T7(X,Y){let $=typeof X==="object"&&X!==null&&(("name"in X)&&X.name&&String(X.name)||("url"in X)&&X.url&&String(X.url)||("filename"in X)&&X.filename&&String(X.filename)||("path"in X)&&X.path&&String(X.path))||"";return Y?$.split(/[\\/]/).pop()||void 0:$}var a9=(X)=>X!=null&&typeof X==="object"&&typeof X[Symbol.asyncIterator]==="function";var u8=async(X,Y,$=!0)=>{return{...X,body:await wJ(X.body,Y,$)}},d2=new WeakMap;function UJ(X){let Y=typeof X==="function"?X:X.fetch,$=d2.get(Y);if($)return $;let W=(async()=>{try{let Z="Response"in Y?Y.Response:(await Y("data:,")).constructor,Q=new FormData;if(Q.toString()===await new Z(Q).text())return!1;return!0}catch{return!0}})();return d2.set(Y,W),W}var wJ=async(X,Y,$=!0)=>{if(!await UJ(Y))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let W=new FormData;return await Promise.all(Object.entries(X||{}).map(([Z,Q])=>n9(W,Z,Q,$))),W},qJ=(X)=>X instanceof Blob&&("name"in X);var n9=async(X,Y,$,W)=>{if($===void 0)return;if($==null)throw TypeError(`Received null for "${Y}"; to pass null in FormData, you must use the string 'null'`);if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")X.append(Y,String($));else if($ instanceof Response){let Z={},Q=$.headers.get("Content-Type");if(Q)Z={type:Q};X.append(Y,t0([await $.blob()],T7($,W),Z))}else if(a9($))X.append(Y,t0([await new Response(oY($)).blob()],T7($,W)));else if(qJ($))X.append(Y,t0([$],T7($,W),{type:$.type}));else if(Array.isArray($))await Promise.all($.map((Z)=>n9(X,Y+"[]",Z,W)));else if(typeof $==="object")await Promise.all(Object.entries($).map(([Z,Q])=>n9(X,`${Y}[${Z}]`,Q,W)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${$} instead`)};var m2=(X)=>X!=null&&typeof X==="object"&&typeof X.size==="number"&&typeof X.type==="string"&&typeof X.text==="function"&&typeof X.slice==="function"&&typeof X.arrayBuffer==="function",FJ=(X)=>X!=null&&typeof X==="object"&&typeof X.name==="string"&&typeof X.lastModified==="number"&&m2(X),LJ=(X)=>X!=null&&typeof X==="object"&&typeof X.url==="string"&&typeof X.blob==="function";async function Z$(X,Y,$){if(r9(),X=await X,Y||(Y=T7(X,!0)),FJ(X)){if(X instanceof File&&Y==null&&$==null)return X;return t0([await X.arrayBuffer()],Y??X.name,{type:X.type,lastModified:X.lastModified,...$})}if(LJ(X)){let Z=await X.blob();return Y||(Y=new URL(X.url).pathname.split(/[\\/]/).pop()),t0(await t9(Z),Y,$)}let W=await t9(X);if(!$?.type){let Z=W.find((Q)=>typeof Q==="object"&&("type"in Q)&&Q.type);if(typeof Z==="string")$={...$,type:Z}}return t0(W,Y,$)}async function t9(X){let Y=[];if(typeof X==="string"||ArrayBuffer.isView(X)||X instanceof ArrayBuffer)Y.push(X);else if(m2(X))Y.push(X instanceof Blob?X:await X.arrayBuffer());else if(a9(X))for await(let $ of X)Y.push(...await t9($));else{let $=X?.constructor?.name;throw Error(`Unexpected data type: ${typeof X}${$?`; constructor: ${$}`:""}${EJ(X)}`)}return Y}function EJ(X){if(typeof X!=="object"||X===null)return"";return`; props: [${Object.getOwnPropertyNames(X).map(($)=>`"${$}"`).join(", ")}]`}class c{constructor(X){this._client=X}}var c2=Symbol.for("brand.privateNullableHeaders");function*OJ(X){if(!X)return;if(c2 in X){let{values:W,nulls:Z}=X;yield*W.entries();for(let Q of Z)yield[Q,null];return}let Y=!1,$;if(X instanceof Headers)$=X.entries();else if(d9(X))$=X;else Y=!0,$=Object.entries(X??{});for(let W of $){let Z=W[0];if(typeof Z!=="string")throw TypeError("expected header name to be a string");let Q=d9(W[1])?W[1]:[W[1]],J=!1;for(let G of Q){if(G===void 0)continue;if(Y&&!J)J=!0,yield[Z,null];yield[Z,G]}}}var j=(X)=>{let Y=new Headers,$=new Set;for(let W of X){let Z=new Set;for(let[Q,J]of OJ(W)){let G=Q.toLowerCase();if(!Z.has(G))Y.delete(Q),Z.add(G);if(J===null)Y.delete(Q),$.add(G);else Y.append(Q,J),$.delete(G)}}return{[c2]:!0,values:Y,nulls:$}};var A7=Symbol("anthropic.sdk.stainlessHelper");function Q$(X){return typeof X==="object"&&X!==null&&A7 in X}function s9(X,Y){let $=new Set;if(X){for(let W of X)if(Q$(W))$.add(W[A7])}if(Y)for(let W of Y){if(Q$(W))$.add(W[A7]);if(Array.isArray(W.content)){for(let Z of W.content)if(Q$(Z))$.add(Z[A7])}}return Array.from($)}function J$(X,Y){let $=s9(X,Y);if($.length===0)return{};return{"x-stainless-helper":$.join(", ")}}function p2(X){if(Q$(X))return{"x-stainless-helper":X[A7]};return{}}function i2(X){return X.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var l2=Object.freeze(Object.create(null)),DJ=(X=i2)=>function($,...W){if($.length===1)return $[0];let Z=!1,Q=[],J=$.reduce((H,V,K)=>{if(/[?#]/.test(V))Z=!0;let U=W[K],E=(Z?encodeURIComponent:X)(""+U);if(K!==W.length&&(U==null||typeof U==="object"&&U.toString===Object.getPrototypeOf(Object.getPrototypeOf(U.hasOwnProperty??l2)??l2)?.toString))E=U+"",Q.push({start:H.length+V.length,length:E.length,error:`Value of type ${Object.prototype.toString.call(U).slice(8,-1)} is not a valid path parameter`});return H+V+(K===W.length?"":E)},""),G=J.split(/[?#]/,1)[0],z=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,B;while((B=z.exec(G))!==null)Q.push({start:B.index,length:B[0].length,error:`Value "${B[0]}" can't be safely passed as a path parameter`});if(Q.sort((H,V)=>H.start-V.start),Q.length>0){let H=0,V=Q.reduce((K,U)=>{let E=" ".repeat(U.start-H),I="^".repeat(U.length);return H=U.start+U.length,K+E+I},"");throw new M(`Path parameters result in path with invalid segments:
|
|
67
|
+
${Q.map((K)=>K.error).join(`
|
|
68
|
+
`)}
|
|
69
|
+
${J}
|
|
70
|
+
${V}`)}return J},d=DJ(i2);class P7 extends c{list(X={},Y){let{betas:$,...W}=X??{};return this._client.getAPIList("/v1/files",CX,{query:W,...Y,headers:j([{"anthropic-beta":[...$??[],"files-api-2025-04-14"].toString()},Y?.headers])})}delete(X,Y={},$){let{betas:W}=Y??{};return this._client.delete(d`/v1/files/${X}`,{...$,headers:j([{"anthropic-beta":[...W??[],"files-api-2025-04-14"].toString()},$?.headers])})}download(X,Y={},$){let{betas:W}=Y??{};return this._client.get(d`/v1/files/${X}/content`,{...$,headers:j([{"anthropic-beta":[...W??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},$?.headers]),__binaryResponse:!0})}retrieveMetadata(X,Y={},$){let{betas:W}=Y??{};return this._client.get(d`/v1/files/${X}`,{...$,headers:j([{"anthropic-beta":[...W??[],"files-api-2025-04-14"].toString()},$?.headers])})}upload(X,Y){let{betas:$,...W}=X;return this._client.post("/v1/files",u8({body:W,...Y,headers:j([{"anthropic-beta":[...$??[],"files-api-2025-04-14"].toString()},p2(W.file),Y?.headers])},this._client))}}class S7 extends c{retrieve(X,Y={},$){let{betas:W}=Y??{};return this._client.get(d`/v1/models/${X}?beta=true`,{...$,headers:j([{...W?.toString()!=null?{"anthropic-beta":W?.toString()}:void 0},$?.headers])})}list(X={},Y){let{betas:$,...W}=X??{};return this._client.getAPIList("/v1/models?beta=true",CX,{query:W,...Y,headers:j([{...$?.toString()!=null?{"anthropic-beta":$?.toString()}:void 0},Y?.headers])})}}var G$={"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 n2(X){return X?.output_format??X?.output_config?.format}function o9(X,Y,$){let W=n2(Y);if(!Y||!("parse"in(W??{})))return{...X,content:X.content.map((Z)=>{if(Z.type==="text"){let Q=Object.defineProperty({...Z},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(Q,"parsed",{get(){return $.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return Z}),parsed_output:null};return e9(X,Y,$)}function e9(X,Y,$){let W=null,Z=X.content.map((Q)=>{if(Q.type==="text"){let J=AJ(Y,Q.text);if(W===null)W=J;let G=Object.defineProperty({...Q},"parsed_output",{value:J,enumerable:!1});return Object.defineProperty(G,"parsed",{get(){return $.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),J},enumerable:!1})}return Q});return{...X,content:Z,parsed_output:W}}function AJ(X,Y){let $=n2(X);if($?.type!=="json_schema")return null;try{if("parse"in $)return $.parse(Y);return JSON.parse(Y)}catch(W){throw new M(`Failed to parse structured output: ${W}`)}}var PJ=(X)=>{let Y=0,$=[];while(Y<X.length){let W=X[Y];if(W==="\\"){Y++;continue}if(W==="{"){$.push({type:"brace",value:"{"}),Y++;continue}if(W==="}"){$.push({type:"brace",value:"}"}),Y++;continue}if(W==="["){$.push({type:"paren",value:"["}),Y++;continue}if(W==="]"){$.push({type:"paren",value:"]"}),Y++;continue}if(W===":"){$.push({type:"separator",value:":"}),Y++;continue}if(W===","){$.push({type:"delimiter",value:","}),Y++;continue}if(W==='"'){let G="",z=!1;W=X[++Y];while(W!=='"'){if(Y===X.length){z=!0;break}if(W==="\\"){if(Y++,Y===X.length){z=!0;break}G+=W+X[Y],W=X[++Y]}else G+=W,W=X[++Y]}if(W=X[++Y],!z)$.push({type:"string",value:G});continue}if(W&&/\s/.test(W)){Y++;continue}let Q=/[0-9]/;if(W&&Q.test(W)||W==="-"||W==="."){let G="";if(W==="-")G+=W,W=X[++Y];while(W&&Q.test(W)||W===".")G+=W,W=X[++Y];$.push({type:"number",value:G});continue}let J=/[a-z]/i;if(W&&J.test(W)){let G="";while(W&&J.test(W)){if(Y===X.length)break;G+=W,W=X[++Y]}if(G=="true"||G=="false"||G==="null")$.push({type:"name",value:G});else{Y++;continue}continue}Y++}return $},d8=(X)=>{if(X.length===0)return X;let Y=X[X.length-1];switch(Y.type){case"separator":return X=X.slice(0,X.length-1),d8(X);break;case"number":let $=Y.value[Y.value.length-1];if($==="."||$==="-")return X=X.slice(0,X.length-1),d8(X);case"string":let W=X[X.length-2];if(W?.type==="delimiter")return X=X.slice(0,X.length-1),d8(X);else if(W?.type==="brace"&&W.value==="{")return X=X.slice(0,X.length-1),d8(X);break;case"delimiter":return X=X.slice(0,X.length-1),d8(X);break}return X},SJ=(X)=>{let Y=[];if(X.map(($)=>{if($.type==="brace")if($.value==="{")Y.push("}");else Y.splice(Y.lastIndexOf("}"),1);if($.type==="paren")if($.value==="[")Y.push("]");else Y.splice(Y.lastIndexOf("]"),1)}),Y.length>0)Y.reverse().map(($)=>{if($==="}")X.push({type:"brace",value:"}"});else if($==="]")X.push({type:"paren",value:"]"})});return X},RJ=(X)=>{let Y="";return X.map(($)=>{switch($.type){case"string":Y+='"'+$.value+'"';break;default:Y+=$.value;break}}),Y},K$=(X)=>JSON.parse(RJ(SJ(d8(PJ(X)))));var DX,T0,m8,R7,V$,C7,I7,z$,j7,eX,_7,H$,B$,s0,N$,U$,y7,X6,r2,w$,Y6,$6,W6,a2,t2="__json_buf";function s2(X){return X.type==="tool_use"||X.type==="server_tool_use"||X.type==="mcp_tool_use"}class k7{constructor(X,Y){DX.add(this),this.messages=[],this.receivedMessages=[],T0.set(this,void 0),m8.set(this,null),this.controller=new AbortController,R7.set(this,void 0),V$.set(this,()=>{}),C7.set(this,()=>{}),I7.set(this,void 0),z$.set(this,()=>{}),j7.set(this,()=>{}),eX.set(this,{}),_7.set(this,!1),H$.set(this,!1),B$.set(this,!1),s0.set(this,!1),N$.set(this,void 0),U$.set(this,void 0),y7.set(this,void 0),w$.set(this,($)=>{if(O(this,H$,!0,"f"),sX($))$=new GX;if($ instanceof GX)return O(this,B$,!0,"f"),this._emit("abort",$);if($ instanceof M)return this._emit("error",$);if($ instanceof Error){let W=new M($.message);return W.cause=$,this._emit("error",W)}return this._emit("error",new M(String($)))}),O(this,R7,new Promise(($,W)=>{O(this,V$,$,"f"),O(this,C7,W,"f")}),"f"),O(this,I7,new Promise(($,W)=>{O(this,z$,$,"f"),O(this,j7,W,"f")}),"f"),q(this,R7,"f").catch(()=>{}),q(this,I7,"f").catch(()=>{}),O(this,m8,X,"f"),O(this,y7,Y?.logger??console,"f")}get response(){return q(this,N$,"f")}get request_id(){return q(this,U$,"f")}async withResponse(){O(this,s0,!0,"f");let X=await q(this,R7,"f");if(!X)throw Error("Could not resolve a `Response` object");return{data:this,response:X,request_id:X.headers.get("request-id")}}static fromReadableStream(X){let Y=new k7(null);return Y._run(()=>Y._fromReadableStream(X)),Y}static createMessage(X,Y,$,{logger:W}={}){let Z=new k7(Y,{logger:W});for(let Q of Y.messages)Z._addMessageParam(Q);return O(Z,m8,{...Y,stream:!0},"f"),Z._run(()=>Z._createMessage(X,{...Y,stream:!0},{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}_run(X){X().then(()=>{this._emitFinal(),this._emit("end")},q(this,w$,"f"))}_addMessageParam(X){this.messages.push(X)}_addMessage(X,Y=!0){if(this.receivedMessages.push(X),Y)this._emit("message",X)}async _createMessage(X,Y,$){let W=$?.signal,Z;if(W){if(W.aborted)this.controller.abort();Z=this.controller.abort.bind(this.controller),W.addEventListener("abort",Z)}try{q(this,DX,"m",Y6).call(this);let{response:Q,data:J}=await X.create({...Y,stream:!0},{...$,signal:this.controller.signal}).withResponse();this._connected(Q);for await(let G of J)q(this,DX,"m",$6).call(this,G);if(J.controller.signal?.aborted)throw new GX;q(this,DX,"m",W6).call(this)}finally{if(W&&Z)W.removeEventListener("abort",Z)}}_connected(X){if(this.ended)return;O(this,N$,X,"f"),O(this,U$,X?.headers.get("request-id"),"f"),q(this,V$,"f").call(this,X),this._emit("connect")}get ended(){return q(this,_7,"f")}get errored(){return q(this,H$,"f")}get aborted(){return q(this,B$,"f")}abort(){this.controller.abort()}on(X,Y){return(q(this,eX,"f")[X]||(q(this,eX,"f")[X]=[])).push({listener:Y}),this}off(X,Y){let $=q(this,eX,"f")[X];if(!$)return this;let W=$.findIndex((Z)=>Z.listener===Y);if(W>=0)$.splice(W,1);return this}once(X,Y){return(q(this,eX,"f")[X]||(q(this,eX,"f")[X]=[])).push({listener:Y,once:!0}),this}emitted(X){return new Promise((Y,$)=>{if(O(this,s0,!0,"f"),X!=="error")this.once("error",$);this.once(X,Y)})}async done(){O(this,s0,!0,"f"),await q(this,I7,"f")}get currentMessage(){return q(this,T0,"f")}async finalMessage(){return await this.done(),q(this,DX,"m",X6).call(this)}async finalText(){return await this.done(),q(this,DX,"m",r2).call(this)}_emit(X,...Y){if(q(this,_7,"f"))return;if(X==="end")O(this,_7,!0,"f"),q(this,z$,"f").call(this);let $=q(this,eX,"f")[X];if($)q(this,eX,"f")[X]=$.filter((W)=>!W.once),$.forEach(({listener:W})=>W(...Y));if(X==="abort"){let W=Y[0];if(!q(this,s0,"f")&&!$?.length)Promise.reject(W);q(this,C7,"f").call(this,W),q(this,j7,"f").call(this,W),this._emit("end");return}if(X==="error"){let W=Y[0];if(!q(this,s0,"f")&&!$?.length)Promise.reject(W);q(this,C7,"f").call(this,W),q(this,j7,"f").call(this,W),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",q(this,DX,"m",X6).call(this))}async _fromReadableStream(X,Y){let $=Y?.signal,W;if($){if($.aborted)this.controller.abort();W=this.controller.abort.bind(this.controller),$.addEventListener("abort",W)}try{q(this,DX,"m",Y6).call(this),this._connected(null);let Z=EX.fromReadableStream(X,this.controller);for await(let Q of Z)q(this,DX,"m",$6).call(this,Q);if(Z.controller.signal?.aborted)throw new GX;q(this,DX,"m",W6).call(this)}finally{if($&&W)$.removeEventListener("abort",W)}}[(T0=new WeakMap,m8=new WeakMap,R7=new WeakMap,V$=new WeakMap,C7=new WeakMap,I7=new WeakMap,z$=new WeakMap,j7=new WeakMap,eX=new WeakMap,_7=new WeakMap,H$=new WeakMap,B$=new WeakMap,s0=new WeakMap,N$=new WeakMap,U$=new WeakMap,y7=new WeakMap,w$=new WeakMap,DX=new WeakSet,X6=function(){if(this.receivedMessages.length===0)throw new M("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},r2=function(){if(this.receivedMessages.length===0)throw new M("stream ended without producing a Message with role=assistant");let Y=this.receivedMessages.at(-1).content.filter(($)=>$.type==="text").map(($)=>$.text);if(Y.length===0)throw new M("stream ended without producing a content block with type=text");return Y.join(" ")},Y6=function(){if(this.ended)return;O(this,T0,void 0,"f")},$6=function(Y){if(this.ended)return;let $=q(this,DX,"m",a2).call(this,Y);switch(this._emit("streamEvent",Y,$),Y.type){case"content_block_delta":{let W=$.content.at(-1);switch(Y.delta.type){case"text_delta":{if(W.type==="text")this._emit("text",Y.delta.text,W.text||"");break}case"citations_delta":{if(W.type==="text")this._emit("citation",Y.delta.citation,W.citations??[]);break}case"input_json_delta":{if(s2(W)&&W.input)this._emit("inputJson",Y.delta.partial_json,W.input);break}case"thinking_delta":{if(W.type==="thinking")this._emit("thinking",Y.delta.thinking,W.thinking);break}case"signature_delta":{if(W.type==="thinking")this._emit("signature",W.signature);break}case"compaction_delta":{if(W.type==="compaction"&&W.content)this._emit("compaction",W.content);break}default:o2(Y.delta)}break}case"message_stop":{this._addMessageParam($),this._addMessage(o9($,q(this,m8,"f"),{logger:q(this,y7,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",$.content.at(-1));break}case"message_start":{O(this,T0,$,"f");break}case"content_block_start":case"message_delta":break}},W6=function(){if(this.ended)throw new M("stream has ended, this shouldn't happen");let Y=q(this,T0,"f");if(!Y)throw new M("request ended without sending any chunks");return O(this,T0,void 0,"f"),o9(Y,q(this,m8,"f"),{logger:q(this,y7,"f")})},a2=function(Y){let $=q(this,T0,"f");if(Y.type==="message_start"){if($)throw new M(`Unexpected event order, got ${Y.type} before receiving "message_stop"`);return Y.message}if(!$)throw new M(`Unexpected event order, got ${Y.type} before "message_start"`);switch(Y.type){case"message_stop":return $;case"message_delta":if($.container=Y.delta.container,$.stop_reason=Y.delta.stop_reason,$.stop_sequence=Y.delta.stop_sequence,$.usage.output_tokens=Y.usage.output_tokens,$.context_management=Y.context_management,Y.usage.input_tokens!=null)$.usage.input_tokens=Y.usage.input_tokens;if(Y.usage.cache_creation_input_tokens!=null)$.usage.cache_creation_input_tokens=Y.usage.cache_creation_input_tokens;if(Y.usage.cache_read_input_tokens!=null)$.usage.cache_read_input_tokens=Y.usage.cache_read_input_tokens;if(Y.usage.server_tool_use!=null)$.usage.server_tool_use=Y.usage.server_tool_use;if(Y.usage.iterations!=null)$.usage.iterations=Y.usage.iterations;return $;case"content_block_start":return $.content.push(Y.content_block),$;case"content_block_delta":{let W=$.content.at(Y.index);switch(Y.delta.type){case"text_delta":{if(W?.type==="text")$.content[Y.index]={...W,text:(W.text||"")+Y.delta.text};break}case"citations_delta":{if(W?.type==="text")$.content[Y.index]={...W,citations:[...W.citations??[],Y.delta.citation]};break}case"input_json_delta":{if(W&&s2(W)){let Z=W[t2]||"";Z+=Y.delta.partial_json;let Q={...W};if(Object.defineProperty(Q,t2,{value:Z,enumerable:!1,writable:!0}),Z)try{Q.input=K$(Z)}catch(J){let G=new M(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${J}. JSON: ${Z}`);q(this,w$,"f").call(this,G)}$.content[Y.index]=Q}break}case"thinking_delta":{if(W?.type==="thinking")$.content[Y.index]={...W,thinking:W.thinking+Y.delta.thinking};break}case"signature_delta":{if(W?.type==="thinking")$.content[Y.index]={...W,signature:Y.delta.signature};break}case"compaction_delta":{if(W?.type==="compaction")$.content[Y.index]={...W,content:(W.content||"")+Y.delta.content};break}default:o2(Y.delta)}return $}case"content_block_stop":return $}},Symbol.asyncIterator)](){let X=[],Y=[],$=!1;return this.on("streamEvent",(W)=>{let Z=Y.shift();if(Z)Z.resolve(W);else X.push(W)}),this.on("end",()=>{$=!0;for(let W of Y)W.resolve(void 0);Y.length=0}),this.on("abort",(W)=>{$=!0;for(let Z of Y)Z.reject(W);Y.length=0}),this.on("error",(W)=>{$=!0;for(let Z of Y)Z.reject(W);Y.length=0}),{next:async()=>{if(!X.length){if($)return{value:void 0,done:!0};return new Promise((Z,Q)=>Y.push({resolve:Z,reject:Q})).then((Z)=>Z?{value:Z,done:!1}:{value:void 0,done:!0})}return{value:X.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new EX(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function o2(X){}class c8 extends Error{constructor(X){let Y=typeof X==="string"?X:X.map(($)=>{if($.type==="text")return $.text;return`[${$.type}]`}).join(" ");super(Y);this.name="ToolError",this.content=X}}var e2=1e5,XW=`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:
|
|
71
|
+
1. Task Overview
|
|
72
|
+
The user's core request and success criteria
|
|
73
|
+
Any clarifications or constraints they specified
|
|
74
|
+
2. Current State
|
|
75
|
+
What has been completed so far
|
|
76
|
+
Files created, modified, or analyzed (with paths if relevant)
|
|
77
|
+
Key outputs or artifacts produced
|
|
78
|
+
3. Important Discoveries
|
|
79
|
+
Technical constraints or requirements uncovered
|
|
80
|
+
Decisions made and their rationale
|
|
81
|
+
Errors encountered and how they were resolved
|
|
82
|
+
What approaches were tried that didn't work (and why)
|
|
83
|
+
4. Next Steps
|
|
84
|
+
Specific actions needed to complete the task
|
|
85
|
+
Any blockers or open questions to resolve
|
|
86
|
+
Priority order if multiple steps remain
|
|
87
|
+
5. Context to Preserve
|
|
88
|
+
User preferences or style requirements
|
|
89
|
+
Domain-specific details that aren't obvious
|
|
90
|
+
Any promises made to the user
|
|
91
|
+
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.
|
|
92
|
+
Wrap your summary in <summary></summary> tags.`;var v7,p8,o0,o,b7,xX,X0,A0,f7,YW,Z6;function $W(){let X,Y;return{promise:new Promise((W,Z)=>{X=W,Y=Z}),resolve:X,reject:Y}}class h7{constructor(X,Y,$){v7.add(this),this.client=X,p8.set(this,!1),o0.set(this,!1),o.set(this,void 0),b7.set(this,void 0),xX.set(this,void 0),X0.set(this,void 0),A0.set(this,void 0),f7.set(this,0),O(this,o,{params:{...Y,messages:structuredClone(Y.messages)}},"f");let Z=["BetaToolRunner",...s9(Y.tools,Y.messages)].join(", ");O(this,b7,{...$,headers:j([{"x-stainless-helper":Z},$?.headers])},"f"),O(this,A0,$W(),"f")}async*[(p8=new WeakMap,o0=new WeakMap,o=new WeakMap,b7=new WeakMap,xX=new WeakMap,X0=new WeakMap,A0=new WeakMap,f7=new WeakMap,v7=new WeakSet,YW=async function(){let Y=q(this,o,"f").params.compactionControl;if(!Y||!Y.enabled)return!1;let $=0;if(q(this,xX,"f")!==void 0)try{let z=await q(this,xX,"f");$=z.usage.input_tokens+(z.usage.cache_creation_input_tokens??0)+(z.usage.cache_read_input_tokens??0)+z.usage.output_tokens}catch{return!1}let W=Y.contextTokenThreshold??e2;if($<W)return!1;let Z=Y.model??q(this,o,"f").params.model,Q=Y.summaryPrompt??XW,J=q(this,o,"f").params.messages;if(J[J.length-1].role==="assistant"){let z=J[J.length-1];if(Array.isArray(z.content)){let B=z.content.filter((H)=>H.type!=="tool_use");if(B.length===0)J.pop();else z.content=B}}let G=await this.client.beta.messages.create({model:Z,messages:[...J,{role:"user",content:[{type:"text",text:Q}]}],max_tokens:q(this,o,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(G.content[0]?.type!=="text")throw new M("Expected text response for compaction");return q(this,o,"f").params.messages=[{role:"user",content:G.content}],!0},Symbol.asyncIterator)](){var X;if(q(this,p8,"f"))throw new M("Cannot iterate over a consumed stream");O(this,p8,!0,"f"),O(this,o0,!0,"f"),O(this,X0,void 0,"f");try{while(!0){let Y;try{if(q(this,o,"f").params.max_iterations&&q(this,f7,"f")>=q(this,o,"f").params.max_iterations)break;O(this,o0,!1,"f"),O(this,X0,void 0,"f"),O(this,f7,(X=q(this,f7,"f"),X++,X),"f"),O(this,xX,void 0,"f");let{max_iterations:$,compactionControl:W,...Z}=q(this,o,"f").params;if(Z.stream)Y=this.client.beta.messages.stream({...Z},q(this,b7,"f")),O(this,xX,Y.finalMessage(),"f"),q(this,xX,"f").catch(()=>{}),yield Y;else O(this,xX,this.client.beta.messages.create({...Z,stream:!1},q(this,b7,"f")),"f"),yield q(this,xX,"f");if(!await q(this,v7,"m",YW).call(this)){if(!q(this,o0,"f")){let{role:G,content:z}=await q(this,xX,"f");q(this,o,"f").params.messages.push({role:G,content:z})}let J=await q(this,v7,"m",Z6).call(this,q(this,o,"f").params.messages.at(-1));if(J)q(this,o,"f").params.messages.push(J);else if(!q(this,o0,"f"))break}}finally{if(Y)Y.abort()}}if(!q(this,xX,"f"))throw new M("ToolRunner concluded without a message from the server");q(this,A0,"f").resolve(await q(this,xX,"f"))}catch(Y){throw O(this,p8,!1,"f"),q(this,A0,"f").promise.catch(()=>{}),q(this,A0,"f").reject(Y),O(this,A0,$W(),"f"),Y}}setMessagesParams(X){if(typeof X==="function")q(this,o,"f").params=X(q(this,o,"f").params);else q(this,o,"f").params=X;O(this,o0,!0,"f"),O(this,X0,void 0,"f")}async generateToolResponse(){let X=await q(this,xX,"f")??this.params.messages.at(-1);if(!X)return null;return q(this,v7,"m",Z6).call(this,X)}done(){return q(this,A0,"f").promise}async runUntilDone(){if(!q(this,p8,"f"))for await(let X of this);return this.done()}get params(){return q(this,o,"f").params}pushMessages(...X){this.setMessagesParams((Y)=>({...Y,messages:[...Y.messages,...X]}))}then(X,Y){return this.runUntilDone().then(X,Y)}}Z6=async function(Y){if(q(this,X0,"f")!==void 0)return q(this,X0,"f");return O(this,X0,CJ(q(this,o,"f").params,Y),"f"),q(this,X0,"f")};async function CJ(X,Y=X.messages.at(-1)){if(!Y||Y.role!=="assistant"||!Y.content||typeof Y.content==="string")return null;let $=Y.content.filter((Z)=>Z.type==="tool_use");if($.length===0)return null;return{role:"user",content:await Promise.all($.map(async(Z)=>{let Q=X.tools.find((J)=>("name"in J?J.name:J.mcp_server_name)===Z.name);if(!Q||!("run"in Q))return{type:"tool_result",tool_use_id:Z.id,content:`Error: Tool '${Z.name}' not found`,is_error:!0};try{let J=Z.input;if("parse"in Q&&Q.parse)J=Q.parse(J);let G=await Q.run(J);return{type:"tool_result",tool_use_id:Z.id,content:G}}catch(J){return{type:"tool_result",tool_use_id:Z.id,content:J instanceof c8?J.content:`Error: ${J instanceof Error?J.message:String(J)}`,is_error:!0}}}))}}class l8{constructor(X,Y){this.iterator=X,this.controller=Y}async*decoder(){let X=new M0;for await(let Y of this.iterator)for(let $ of X.decode(Y))yield JSON.parse($);for(let Y of X.flush())yield JSON.parse(Y)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(X,Y){if(!X.body){if(Y.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new M("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new M("Attempted to iterate over a response with no body")}return new l8(E7(X.body),Y)}}class g7 extends c{create(X,Y){let{betas:$,...W}=X;return this._client.post("/v1/messages/batches?beta=true",{body:W,...Y,headers:j([{"anthropic-beta":[...$??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}retrieve(X,Y={},$){let{betas:W}=Y??{};return this._client.get(d`/v1/messages/batches/${X}?beta=true`,{...$,headers:j([{"anthropic-beta":[...W??[],"message-batches-2024-09-24"].toString()},$?.headers])})}list(X={},Y){let{betas:$,...W}=X??{};return this._client.getAPIList("/v1/messages/batches?beta=true",CX,{query:W,...Y,headers:j([{"anthropic-beta":[...$??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}delete(X,Y={},$){let{betas:W}=Y??{};return this._client.delete(d`/v1/messages/batches/${X}?beta=true`,{...$,headers:j([{"anthropic-beta":[...W??[],"message-batches-2024-09-24"].toString()},$?.headers])})}cancel(X,Y={},$){let{betas:W}=Y??{};return this._client.post(d`/v1/messages/batches/${X}/cancel?beta=true`,{...$,headers:j([{"anthropic-beta":[...W??[],"message-batches-2024-09-24"].toString()},$?.headers])})}async results(X,Y={},$){let W=await this.retrieve(X);if(!W.results_url)throw new M(`No batch \`results_url\`; Has it finished processing? ${W.processing_status} - ${W.id}`);let{betas:Z}=Y??{};return this._client.get(W.results_url,{...$,headers:j([{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},$?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Q,J)=>l8.fromResponse(J.response,J.controller))}}var WW={"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"},jJ=["claude-opus-4-6"];class P0 extends c{constructor(){super(...arguments);this.batches=new g7(this._client)}create(X,Y){let $=ZW(X),{betas:W,...Z}=$;if(Z.model in WW)console.warn(`The model '${Z.model}' is deprecated and will reach end-of-life on ${WW[Z.model]}
|
|
93
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(Z.model in jJ&&Z.thinking&&Z.thinking.type==="enabled")console.warn(`Using Claude with ${Z.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 Q=this._client._options.timeout;if(!Z.stream&&Q==null){let G=G$[Z.model]??void 0;Q=this._client.calculateNonstreamingTimeout(Z.max_tokens,G)}let J=J$(Z.tools,Z.messages);return this._client.post("/v1/messages?beta=true",{body:Z,timeout:Q??600000,...Y,headers:j([{...W?.toString()!=null?{"anthropic-beta":W?.toString()}:void 0},J,Y?.headers]),stream:$.stream??!1})}parse(X,Y){return Y={...Y,headers:j([{"anthropic-beta":[...X.betas??[],"structured-outputs-2025-12-15"].toString()},Y?.headers])},this.create(X,Y).then(($)=>e9($,X,{logger:this._client.logger??console}))}stream(X,Y){return k7.createMessage(this,X,Y)}countTokens(X,Y){let $=ZW(X),{betas:W,...Z}=$;return this._client.post("/v1/messages/count_tokens?beta=true",{body:Z,...Y,headers:j([{"anthropic-beta":[...W??[],"token-counting-2024-11-01"].toString()},Y?.headers])})}toolRunner(X,Y){return new h7(this._client,X,Y)}}function ZW(X){if(!X.output_format)return X;if(X.output_config?.format)throw new M("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:Y,...$}=X;return{...$,output_config:{...X.output_config,format:Y}}}P0.Batches=g7;P0.BetaToolRunner=h7;P0.ToolError=c8;class u7 extends c{create(X,Y={},$){let{betas:W,...Z}=Y??{};return this._client.post(d`/v1/skills/${X}/versions?beta=true`,u8({body:Z,...$,headers:j([{"anthropic-beta":[...W??[],"skills-2025-10-02"].toString()},$?.headers])},this._client))}retrieve(X,Y,$){let{skill_id:W,betas:Z}=Y;return this._client.get(d`/v1/skills/${W}/versions/${X}?beta=true`,{...$,headers:j([{"anthropic-beta":[...Z??[],"skills-2025-10-02"].toString()},$?.headers])})}list(X,Y={},$){let{betas:W,...Z}=Y??{};return this._client.getAPIList(d`/v1/skills/${X}/versions?beta=true`,M7,{query:Z,...$,headers:j([{"anthropic-beta":[...W??[],"skills-2025-10-02"].toString()},$?.headers])})}delete(X,Y,$){let{skill_id:W,betas:Z}=Y;return this._client.delete(d`/v1/skills/${W}/versions/${X}?beta=true`,{...$,headers:j([{"anthropic-beta":[...Z??[],"skills-2025-10-02"].toString()},$?.headers])})}}class i8 extends c{constructor(){super(...arguments);this.versions=new u7(this._client)}create(X={},Y){let{betas:$,...W}=X??{};return this._client.post("/v1/skills?beta=true",u8({body:W,...Y,headers:j([{"anthropic-beta":[...$??[],"skills-2025-10-02"].toString()},Y?.headers])},this._client,!1))}retrieve(X,Y={},$){let{betas:W}=Y??{};return this._client.get(d`/v1/skills/${X}?beta=true`,{...$,headers:j([{"anthropic-beta":[...W??[],"skills-2025-10-02"].toString()},$?.headers])})}list(X={},Y){let{betas:$,...W}=X??{};return this._client.getAPIList("/v1/skills?beta=true",M7,{query:W,...Y,headers:j([{"anthropic-beta":[...$??[],"skills-2025-10-02"].toString()},Y?.headers])})}delete(X,Y={},$){let{betas:W}=Y??{};return this._client.delete(d`/v1/skills/${X}?beta=true`,{...$,headers:j([{"anthropic-beta":[...W??[],"skills-2025-10-02"].toString()},$?.headers])})}}i8.Versions=u7;class gX extends c{constructor(){super(...arguments);this.models=new S7(this._client),this.messages=new P0(this._client),this.files=new P7(this._client),this.skills=new i8(this._client)}}gX.Models=S7;gX.Messages=P0;gX.Files=P7;gX.Skills=i8;class n8 extends c{create(X,Y){let{betas:$,...W}=X;return this._client.post("/v1/complete",{body:W,timeout:this._client._options.timeout??600000,...Y,headers:j([{...$?.toString()!=null?{"anthropic-beta":$?.toString()}:void 0},Y?.headers]),stream:X.stream??!1})}}function QW(X){return X?.output_config?.format}function Q6(X,Y,$){let W=QW(Y);if(!Y||!("parse"in(W??{})))return{...X,content:X.content.map((Z)=>{if(Z.type==="text")return Object.defineProperty({...Z},"parsed_output",{value:null,enumerable:!1});return Z}),parsed_output:null};return J6(X,Y,$)}function J6(X,Y,$){let W=null,Z=X.content.map((Q)=>{if(Q.type==="text"){let J=vJ(Y,Q.text);if(W===null)W=J;return Object.defineProperty({...Q},"parsed_output",{value:J,enumerable:!1})}return Q});return{...X,content:Z,parsed_output:W}}function vJ(X,Y){let $=QW(X);if($?.type!=="json_schema")return null;try{if("parse"in $)return $.parse(Y);return JSON.parse(Y)}catch(W){throw new M(`Failed to parse structured output: ${W}`)}}var MX,S0,r8,d7,q$,m7,c7,F$,p7,Y0,l7,L$,E$,e0,x$,O$,i7,G6,JW,K6,V6,z6,H6,GW,KW="__json_buf";function VW(X){return X.type==="tool_use"||X.type==="server_tool_use"}class n7{constructor(X,Y){MX.add(this),this.messages=[],this.receivedMessages=[],S0.set(this,void 0),r8.set(this,null),this.controller=new AbortController,d7.set(this,void 0),q$.set(this,()=>{}),m7.set(this,()=>{}),c7.set(this,void 0),F$.set(this,()=>{}),p7.set(this,()=>{}),Y0.set(this,{}),l7.set(this,!1),L$.set(this,!1),E$.set(this,!1),e0.set(this,!1),x$.set(this,void 0),O$.set(this,void 0),i7.set(this,void 0),K6.set(this,($)=>{if(O(this,L$,!0,"f"),sX($))$=new GX;if($ instanceof GX)return O(this,E$,!0,"f"),this._emit("abort",$);if($ instanceof M)return this._emit("error",$);if($ instanceof Error){let W=new M($.message);return W.cause=$,this._emit("error",W)}return this._emit("error",new M(String($)))}),O(this,d7,new Promise(($,W)=>{O(this,q$,$,"f"),O(this,m7,W,"f")}),"f"),O(this,c7,new Promise(($,W)=>{O(this,F$,$,"f"),O(this,p7,W,"f")}),"f"),q(this,d7,"f").catch(()=>{}),q(this,c7,"f").catch(()=>{}),O(this,r8,X,"f"),O(this,i7,Y?.logger??console,"f")}get response(){return q(this,x$,"f")}get request_id(){return q(this,O$,"f")}async withResponse(){O(this,e0,!0,"f");let X=await q(this,d7,"f");if(!X)throw Error("Could not resolve a `Response` object");return{data:this,response:X,request_id:X.headers.get("request-id")}}static fromReadableStream(X){let Y=new n7(null);return Y._run(()=>Y._fromReadableStream(X)),Y}static createMessage(X,Y,$,{logger:W}={}){let Z=new n7(Y,{logger:W});for(let Q of Y.messages)Z._addMessageParam(Q);return O(Z,r8,{...Y,stream:!0},"f"),Z._run(()=>Z._createMessage(X,{...Y,stream:!0},{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"stream"}})),Z}_run(X){X().then(()=>{this._emitFinal(),this._emit("end")},q(this,K6,"f"))}_addMessageParam(X){this.messages.push(X)}_addMessage(X,Y=!0){if(this.receivedMessages.push(X),Y)this._emit("message",X)}async _createMessage(X,Y,$){let W=$?.signal,Z;if(W){if(W.aborted)this.controller.abort();Z=this.controller.abort.bind(this.controller),W.addEventListener("abort",Z)}try{q(this,MX,"m",V6).call(this);let{response:Q,data:J}=await X.create({...Y,stream:!0},{...$,signal:this.controller.signal}).withResponse();this._connected(Q);for await(let G of J)q(this,MX,"m",z6).call(this,G);if(J.controller.signal?.aborted)throw new GX;q(this,MX,"m",H6).call(this)}finally{if(W&&Z)W.removeEventListener("abort",Z)}}_connected(X){if(this.ended)return;O(this,x$,X,"f"),O(this,O$,X?.headers.get("request-id"),"f"),q(this,q$,"f").call(this,X),this._emit("connect")}get ended(){return q(this,l7,"f")}get errored(){return q(this,L$,"f")}get aborted(){return q(this,E$,"f")}abort(){this.controller.abort()}on(X,Y){return(q(this,Y0,"f")[X]||(q(this,Y0,"f")[X]=[])).push({listener:Y}),this}off(X,Y){let $=q(this,Y0,"f")[X];if(!$)return this;let W=$.findIndex((Z)=>Z.listener===Y);if(W>=0)$.splice(W,1);return this}once(X,Y){return(q(this,Y0,"f")[X]||(q(this,Y0,"f")[X]=[])).push({listener:Y,once:!0}),this}emitted(X){return new Promise((Y,$)=>{if(O(this,e0,!0,"f"),X!=="error")this.once("error",$);this.once(X,Y)})}async done(){O(this,e0,!0,"f"),await q(this,c7,"f")}get currentMessage(){return q(this,S0,"f")}async finalMessage(){return await this.done(),q(this,MX,"m",G6).call(this)}async finalText(){return await this.done(),q(this,MX,"m",JW).call(this)}_emit(X,...Y){if(q(this,l7,"f"))return;if(X==="end")O(this,l7,!0,"f"),q(this,F$,"f").call(this);let $=q(this,Y0,"f")[X];if($)q(this,Y0,"f")[X]=$.filter((W)=>!W.once),$.forEach(({listener:W})=>W(...Y));if(X==="abort"){let W=Y[0];if(!q(this,e0,"f")&&!$?.length)Promise.reject(W);q(this,m7,"f").call(this,W),q(this,p7,"f").call(this,W),this._emit("end");return}if(X==="error"){let W=Y[0];if(!q(this,e0,"f")&&!$?.length)Promise.reject(W);q(this,m7,"f").call(this,W),q(this,p7,"f").call(this,W),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",q(this,MX,"m",G6).call(this))}async _fromReadableStream(X,Y){let $=Y?.signal,W;if($){if($.aborted)this.controller.abort();W=this.controller.abort.bind(this.controller),$.addEventListener("abort",W)}try{q(this,MX,"m",V6).call(this),this._connected(null);let Z=EX.fromReadableStream(X,this.controller);for await(let Q of Z)q(this,MX,"m",z6).call(this,Q);if(Z.controller.signal?.aborted)throw new GX;q(this,MX,"m",H6).call(this)}finally{if($&&W)$.removeEventListener("abort",W)}}[(S0=new WeakMap,r8=new WeakMap,d7=new WeakMap,q$=new WeakMap,m7=new WeakMap,c7=new WeakMap,F$=new WeakMap,p7=new WeakMap,Y0=new WeakMap,l7=new WeakMap,L$=new WeakMap,E$=new WeakMap,e0=new WeakMap,x$=new WeakMap,O$=new WeakMap,i7=new WeakMap,K6=new WeakMap,MX=new WeakSet,G6=function(){if(this.receivedMessages.length===0)throw new M("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},JW=function(){if(this.receivedMessages.length===0)throw new M("stream ended without producing a Message with role=assistant");let Y=this.receivedMessages.at(-1).content.filter(($)=>$.type==="text").map(($)=>$.text);if(Y.length===0)throw new M("stream ended without producing a content block with type=text");return Y.join(" ")},V6=function(){if(this.ended)return;O(this,S0,void 0,"f")},z6=function(Y){if(this.ended)return;let $=q(this,MX,"m",GW).call(this,Y);switch(this._emit("streamEvent",Y,$),Y.type){case"content_block_delta":{let W=$.content.at(-1);switch(Y.delta.type){case"text_delta":{if(W.type==="text")this._emit("text",Y.delta.text,W.text||"");break}case"citations_delta":{if(W.type==="text")this._emit("citation",Y.delta.citation,W.citations??[]);break}case"input_json_delta":{if(VW(W)&&W.input)this._emit("inputJson",Y.delta.partial_json,W.input);break}case"thinking_delta":{if(W.type==="thinking")this._emit("thinking",Y.delta.thinking,W.thinking);break}case"signature_delta":{if(W.type==="thinking")this._emit("signature",W.signature);break}default:zW(Y.delta)}break}case"message_stop":{this._addMessageParam($),this._addMessage(Q6($,q(this,r8,"f"),{logger:q(this,i7,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",$.content.at(-1));break}case"message_start":{O(this,S0,$,"f");break}case"content_block_start":case"message_delta":break}},H6=function(){if(this.ended)throw new M("stream has ended, this shouldn't happen");let Y=q(this,S0,"f");if(!Y)throw new M("request ended without sending any chunks");return O(this,S0,void 0,"f"),Q6(Y,q(this,r8,"f"),{logger:q(this,i7,"f")})},GW=function(Y){let $=q(this,S0,"f");if(Y.type==="message_start"){if($)throw new M(`Unexpected event order, got ${Y.type} before receiving "message_stop"`);return Y.message}if(!$)throw new M(`Unexpected event order, got ${Y.type} before "message_start"`);switch(Y.type){case"message_stop":return $;case"message_delta":if($.stop_reason=Y.delta.stop_reason,$.stop_sequence=Y.delta.stop_sequence,$.usage.output_tokens=Y.usage.output_tokens,Y.usage.input_tokens!=null)$.usage.input_tokens=Y.usage.input_tokens;if(Y.usage.cache_creation_input_tokens!=null)$.usage.cache_creation_input_tokens=Y.usage.cache_creation_input_tokens;if(Y.usage.cache_read_input_tokens!=null)$.usage.cache_read_input_tokens=Y.usage.cache_read_input_tokens;if(Y.usage.server_tool_use!=null)$.usage.server_tool_use=Y.usage.server_tool_use;return $;case"content_block_start":return $.content.push({...Y.content_block}),$;case"content_block_delta":{let W=$.content.at(Y.index);switch(Y.delta.type){case"text_delta":{if(W?.type==="text")$.content[Y.index]={...W,text:(W.text||"")+Y.delta.text};break}case"citations_delta":{if(W?.type==="text")$.content[Y.index]={...W,citations:[...W.citations??[],Y.delta.citation]};break}case"input_json_delta":{if(W&&VW(W)){let Z=W[KW]||"";Z+=Y.delta.partial_json;let Q={...W};if(Object.defineProperty(Q,KW,{value:Z,enumerable:!1,writable:!0}),Z)Q.input=K$(Z);$.content[Y.index]=Q}break}case"thinking_delta":{if(W?.type==="thinking")$.content[Y.index]={...W,thinking:W.thinking+Y.delta.thinking};break}case"signature_delta":{if(W?.type==="thinking")$.content[Y.index]={...W,signature:Y.delta.signature};break}default:zW(Y.delta)}return $}case"content_block_stop":return $}},Symbol.asyncIterator)](){let X=[],Y=[],$=!1;return this.on("streamEvent",(W)=>{let Z=Y.shift();if(Z)Z.resolve(W);else X.push(W)}),this.on("end",()=>{$=!0;for(let W of Y)W.resolve(void 0);Y.length=0}),this.on("abort",(W)=>{$=!0;for(let Z of Y)Z.reject(W);Y.length=0}),this.on("error",(W)=>{$=!0;for(let Z of Y)Z.reject(W);Y.length=0}),{next:async()=>{if(!X.length){if($)return{value:void 0,done:!0};return new Promise((Z,Q)=>Y.push({resolve:Z,reject:Q})).then((Z)=>Z?{value:Z,done:!1}:{value:void 0,done:!0})}return{value:X.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new EX(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function zW(X){}class r7 extends c{create(X,Y){return this._client.post("/v1/messages/batches",{body:X,...Y})}retrieve(X,Y){return this._client.get(d`/v1/messages/batches/${X}`,Y)}list(X={},Y){return this._client.getAPIList("/v1/messages/batches",CX,{query:X,...Y})}delete(X,Y){return this._client.delete(d`/v1/messages/batches/${X}`,Y)}cancel(X,Y){return this._client.post(d`/v1/messages/batches/${X}/cancel`,Y)}async results(X,Y){let $=await this.retrieve(X);if(!$.results_url)throw new M(`No batch \`results_url\`; Has it finished processing? ${$.processing_status} - ${$.id}`);return this._client.get($.results_url,{...Y,headers:j([{Accept:"application/binary"},Y?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((W,Z)=>l8.fromResponse(Z.response,Z.controller))}}class X8 extends c{constructor(){super(...arguments);this.batches=new r7(this._client)}create(X,Y){if(X.model in HW)console.warn(`The model '${X.model}' is deprecated and will reach end-of-life on ${HW[X.model]}
|
|
94
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(X.model in fJ&&X.thinking&&X.thinking.type==="enabled")console.warn(`Using Claude with ${X.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 $=this._client._options.timeout;if(!X.stream&&$==null){let Z=G$[X.model]??void 0;$=this._client.calculateNonstreamingTimeout(X.max_tokens,Z)}let W=J$(X.tools,X.messages);return this._client.post("/v1/messages",{body:X,timeout:$??600000,...Y,headers:j([W,Y?.headers]),stream:X.stream??!1})}parse(X,Y){return this.create(X,Y).then(($)=>J6($,X,{logger:this._client.logger??console}))}stream(X,Y){return n7.createMessage(this,X,Y,{logger:this._client.logger??console})}countTokens(X,Y){return this._client.post("/v1/messages/count_tokens",{body:X,...Y})}}var HW={"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"},fJ=["claude-opus-4-6"];X8.Batches=r7;class a8 extends c{retrieve(X,Y={},$){let{betas:W}=Y??{};return this._client.get(d`/v1/models/${X}`,{...$,headers:j([{...W?.toString()!=null?{"anthropic-beta":W?.toString()}:void 0},$?.headers])})}list(X={},Y){let{betas:$,...W}=X??{};return this._client.getAPIList("/v1/models",CX,{query:W,...Y,headers:j([{...$?.toString()!=null?{"anthropic-beta":$?.toString()}:void 0},Y?.headers])})}}var a7=(X)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[X]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(X)?.trim();return};var B6,N6,D$,BW,NW="\\n\\nHuman:",UW="\\n\\nAssistant:";class p{constructor({baseURL:X=a7("ANTHROPIC_BASE_URL"),apiKey:Y=a7("ANTHROPIC_API_KEY")??null,authToken:$=a7("ANTHROPIC_AUTH_TOKEN")??null,...W}={}){B6.add(this),D$.set(this,void 0);let Z={apiKey:Y,authToken:$,...W,baseURL:X||"https://api.anthropic.com"};if(!Z.dangerouslyAllowBrowser&&I2())throw new M(`It looks like you're running in a browser-like environment.
|
|
95
|
+
|
|
96
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
97
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
98
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
99
|
+
|
|
100
|
+
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
101
|
+
`);this.baseURL=Z.baseURL,this.timeout=Z.timeout??N6.DEFAULT_TIMEOUT,this.logger=Z.logger??console;let Q="warn";this.logLevel=Q,this.logLevel=p9(Z.logLevel,"ClientOptions.logLevel",this)??p9(a7("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??Q,this.fetchOptions=Z.fetchOptions,this.maxRetries=Z.maxRetries??2,this.fetch=Z.fetch??_2(),O(this,D$,k2,"f"),this._options=Z,this.apiKey=typeof Y==="string"?Y:null,this.authToken=$}withOptions(X){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,...X})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:X,nulls:Y}){if(X.get("x-api-key")||X.get("authorization"))return;if(this.apiKey&&X.get("x-api-key"))return;if(Y.has("x-api-key"))return;if(this.authToken&&X.get("authorization"))return;if(Y.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(X){return j([await this.apiKeyAuth(X),await this.bearerAuth(X)])}async apiKeyAuth(X){if(this.apiKey==null)return;return j([{"X-Api-Key":this.apiKey}])}async bearerAuth(X){if(this.authToken==null)return;return j([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(X){return Object.entries(X).filter(([Y,$])=>typeof $<"u").map(([Y,$])=>{if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")return`${encodeURIComponent(Y)}=${encodeURIComponent($)}`;if($===null)return`${encodeURIComponent(Y)}=`;throw new M(`Cannot stringify type ${typeof $}; 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 ${D0}`}defaultIdempotencyKey(){return`stainless-node-retry-${g9()}`}makeStatusError(X,Y,$,W){return s.generate(X,Y,$,W)}buildURL(X,Y,$){let W=!q(this,B6,"m",BW).call(this)&&$||this.baseURL,Z=D2(X)?new URL(X):new URL(W+(W.endsWith("/")&&X.startsWith("/")?X.slice(1):X)),Q=this.defaultQuery();if(!M2(Q))Y={...Q,...Y};if(typeof Y==="object"&&Y&&!Array.isArray(Y))Z.search=this.stringifyQuery(Y);return Z.toString()}_calculateNonstreamingTimeout(X){if(3600*X/128000>600)throw new M("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions(X){}async prepareRequest(X,{url:Y,options:$}){}get(X,Y){return this.methodRequest("get",X,Y)}post(X,Y){return this.methodRequest("post",X,Y)}patch(X,Y){return this.methodRequest("patch",X,Y)}put(X,Y){return this.methodRequest("put",X,Y)}delete(X,Y){return this.methodRequest("delete",X,Y)}methodRequest(X,Y,$){return this.request(Promise.resolve($).then((W)=>{return{method:X,path:Y,...W}}))}request(X,Y=null){return new a0(this,this.makeRequest(X,Y,void 0))}async makeRequest(X,Y,$){let W=await X,Z=W.maxRetries??this.maxRetries;if(Y==null)Y=Z;await this.prepareOptions(W);let{req:Q,url:J,timeout:G}=await this.buildRequest(W,{retryCount:Z-Y});await this.prepareRequest(Q,{url:J,options:W});let z="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),B=$===void 0?"":`, retryOf: ${$}`,H=Date.now();if(YX(this).debug(`[${z}] sending request`,oX({retryOfRequestLogID:$,method:W.method,url:J,options:W,headers:Q.headers})),W.signal?.aborted)throw new GX;let V=new AbortController,K=await this.fetchWithTimeout(J,Q,G,V).catch(V7),U=Date.now();if(K instanceof globalThis.Error){let T=`retrying, ${Y} attempts remaining`;if(W.signal?.aborted)throw new GX;let S=sX(K)||/timed? ?out/i.test(String(K)+("cause"in K?String(K.cause):""));if(Y)return YX(this).info(`[${z}] connection ${S?"timed out":"failed"} - ${T}`),YX(this).debug(`[${z}] connection ${S?"timed out":"failed"} (${T})`,oX({retryOfRequestLogID:$,url:J,durationMs:U-H,message:K.message})),this.retryRequest(W,Y,$??z);if(YX(this).info(`[${z}] connection ${S?"timed out":"failed"} - error; no more retries left`),YX(this).debug(`[${z}] connection ${S?"timed out":"failed"} (error; no more retries left)`,oX({retryOfRequestLogID:$,url:J,durationMs:U-H,message:K.message})),S)throw new z7;throw new r0({cause:K})}let E=[...K.headers.entries()].filter(([T])=>T==="request-id").map(([T,S])=>", "+T+": "+JSON.stringify(S)).join(""),I=`[${z}${B}${E}] ${Q.method} ${J} ${K.ok?"succeeded":"failed"} with status ${K.status} in ${U-H}ms`;if(!K.ok){let T=await this.shouldRetry(K);if(Y&&T){let b=`retrying, ${Y} attempts remaining`;return await y2(K.body),YX(this).info(`${I} - ${b}`),YX(this).debug(`[${z}] response error (${b})`,oX({retryOfRequestLogID:$,url:K.url,status:K.status,headers:K.headers,durationMs:U-H})),this.retryRequest(W,Y,$??z,K.headers)}let S=T?"error; no more retries left":"error; not retryable";YX(this).info(`${I} - ${S}`);let P=await K.text().catch((b)=>V7(b).message),h=sY(P),f=h?void 0:P;throw YX(this).debug(`[${z}] response error (${S})`,oX({retryOfRequestLogID:$,url:K.url,status:K.status,headers:K.headers,message:f,durationMs:Date.now()-H})),this.makeStatusError(K.status,h,f,K.headers)}return YX(this).info(I),YX(this).debug(`[${z}] response start`,oX({retryOfRequestLogID:$,url:K.url,status:K.status,headers:K.headers,durationMs:U-H})),{response:K,options:W,controller:V,requestLogID:z,retryOfRequestLogID:$,startTime:H}}getAPIList(X,Y,$){return this.requestAPIList(Y,$&&"then"in $?$.then((W)=>({method:"get",path:X,...W})):{method:"get",path:X,...$})}requestAPIList(X,Y){let $=this.makeRequest(Y,null,void 0);return new W$(this,$,X)}async fetchWithTimeout(X,Y,$,W){let{signal:Z,method:Q,...J}=Y||{},G=this._makeAbort(W);if(Z)Z.addEventListener("abort",G,{once:!0});let z=setTimeout(G,$),B=globalThis.ReadableStream&&J.body instanceof globalThis.ReadableStream||typeof J.body==="object"&&J.body!==null&&Symbol.asyncIterator in J.body,H={signal:W.signal,...B?{duplex:"half"}:{},method:"GET",...J};if(Q)H.method=Q.toUpperCase();try{return await this.fetch.call(void 0,X,H)}finally{clearTimeout(z)}}async shouldRetry(X){let Y=X.headers.get("x-should-retry");if(Y==="true")return!0;if(Y==="false")return!1;if(X.status===408)return!0;if(X.status===409)return!0;if(X.status===429)return!0;if(X.status>=500)return!0;return!1}async retryRequest(X,Y,$,W){let Z,Q=W?.get("retry-after-ms");if(Q){let G=parseFloat(Q);if(!Number.isNaN(G))Z=G}let J=W?.get("retry-after");if(J&&!Z){let G=parseFloat(J);if(!Number.isNaN(G))Z=G*1000;else Z=Date.parse(J)-Date.now()}if(!(Z&&0<=Z&&Z<60000)){let G=X.maxRetries??this.maxRetries;Z=this.calculateDefaultRetryTimeoutMillis(Y,G)}return await P2(Z),this.makeRequest(X,Y-1,$)}calculateDefaultRetryTimeoutMillis(X,Y){let Z=Y-X,Q=Math.min(0.5*Math.pow(2,Z),8),J=1-Math.random()*0.25;return Q*J*1000}calculateNonstreamingTimeout(X,Y){if(3600000*X/128000>600000||Y!=null&&X>Y)throw new M("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest(X,{retryCount:Y=0}={}){let $={...X},{method:W,path:Z,query:Q,defaultBaseURL:J}=$,G=this.buildURL(Z,Q,J);if("timeout"in $)A2("timeout",$.timeout);$.timeout=$.timeout??this.timeout;let{bodyHeaders:z,body:B}=this.buildBody({options:$}),H=await this.buildHeaders({options:X,method:W,bodyHeaders:z,retryCount:Y});return{req:{method:W,headers:H,...$.signal&&{signal:$.signal},...globalThis.ReadableStream&&B instanceof globalThis.ReadableStream&&{duplex:"half"},...B&&{body:B},...this.fetchOptions??{},...$.fetchOptions??{}},url:G,timeout:$.timeout}}async buildHeaders({options:X,method:Y,bodyHeaders:$,retryCount:W}){let Z={};if(this.idempotencyHeader&&Y!=="get"){if(!X.idempotencyKey)X.idempotencyKey=this.defaultIdempotencyKey();Z[this.idempotencyHeader]=X.idempotencyKey}let Q=j([Z,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(W),...X.timeout?{"X-Stainless-Timeout":String(Math.trunc(X.timeout/1000))}:{},...j2(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(X),this._options.defaultHeaders,$,X.headers]);return this.validateHeaders(Q),Q.values}_makeAbort(X){return()=>X.abort()}buildBody({options:{body:X,headers:Y}}){if(!X)return{bodyHeaders:void 0,body:void 0};let $=j([Y]);if(ArrayBuffer.isView(X)||X instanceof ArrayBuffer||X instanceof DataView||typeof X==="string"&&$.values.has("content-type")||globalThis.Blob&&X instanceof globalThis.Blob||X instanceof FormData||X instanceof URLSearchParams||globalThis.ReadableStream&&X instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:X};else if(typeof X==="object"&&((Symbol.asyncIterator in X)||(Symbol.iterator in X)&&("next"in X)&&typeof X.next==="function"))return{bodyHeaders:void 0,body:oY(X)};else return q(this,D$,"f").call(this,{body:X,headers:$})}}N6=p,D$=new WeakMap,B6=new WeakSet,BW=function(){return this.baseURL!=="https://api.anthropic.com"};p.Anthropic=N6;p.HUMAN_PROMPT=NW;p.AI_PROMPT=UW;p.DEFAULT_TIMEOUT=600000;p.AnthropicError=M;p.APIError=s;p.APIConnectionError=r0;p.APIConnectionTimeoutError=z7;p.APIUserAbortError=GX;p.NotFoundError=U7;p.ConflictError=w7;p.RateLimitError=F7;p.BadRequestError=H7;p.AuthenticationError=B7;p.InternalServerError=L7;p.PermissionDeniedError=N7;p.UnprocessableEntityError=q7;p.toFile=Z$;class $0 extends p{constructor(){super(...arguments);this.completions=new n8(this),this.messages=new X8(this),this.models=new a8(this),this.beta=new gX(this)}}$0.Completions=n8;$0.Messages=X8;$0.Models=a8;$0.Beta=gX;var gJ=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]);function uJ(X){return JSON.parse(JSON.stringify(X))}function wW(X){let Y=uJ(X);return Y8(Y)}function Y8(X){let Y={},$=zX(X,"$ref");if($!==void 0)return Y.$ref=$,Y;let W=zX(X,"$defs");if(W!==void 0){let H={};Y.$defs=H;for(let[V,K]of Object.entries(W))H[V]=Y8(K)}let Z=zX(X,"type"),Q=zX(X,"anyOf"),J=zX(X,"oneOf"),G=zX(X,"allOf");if(Array.isArray(Q))Y.anyOf=Q.map((H)=>Y8(H));else if(Array.isArray(J))Y.anyOf=J.map((H)=>Y8(H));else if(Array.isArray(G))Y.allOf=G.map((H)=>Y8(H));else{if(Z===void 0)throw Error("JSON schema must have a type defined if anyOf/oneOf/allOf are not used");Y.type=Z}let z=zX(X,"description");if(z!==void 0)Y.description=z;let B=zX(X,"title");if(B!==void 0)Y.title=B;if(Z==="object"){let H=zX(X,"properties")||{};Y.properties=Object.fromEntries(Object.entries(H).map(([K,U])=>[K,Y8(U)])),zX(X,"additionalProperties"),Y.additionalProperties=!1;let V=zX(X,"required");if(V!==void 0)Y.required=V}else if(Z==="string"){let H=zX(X,"format");if(H!==void 0&&gJ.has(H))Y.format=H;else if(H!==void 0)X.format=H}else if(Z==="array"){let H=zX(X,"items");if(H!==void 0)Y.items=Y8(H);let V=zX(X,"minItems");if(V!==void 0&&(V===0||V===1))Y.minItems=V;else if(V!==void 0)X.minItems=V}if(Object.keys(X).length>0){let H=Y.description;Y.description=(H?H+`
|
|
102
|
+
|
|
103
|
+
`:"")+"{"+Object.entries(X).map(([V,K])=>`${V}: ${JSON.stringify(K)}`).join(", ")+"}"}return Y}var dJ={"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},qW=2048;function mJ(X){if(!X)return qW;return Object.entries(dJ).find(([Y])=>X.startsWith(Y))?.[1]??qW}function cJ(X){return!!(X.tools&&X.tools.length>0)}function pJ(X){for(let Y of X.messages??[]){if(typeof Y.content==="string")continue;for(let $ of Y.content??[])if(typeof $==="object"&&$!=null&&$.type==="document"&&typeof $.citations==="object"&&$.citations?.enabled)return!0}return!1}function lJ(X){return!!(X.thinking&&(X.thinking.type==="enabled"||X.thinking.type==="adaptive"))}function iJ(X){return!!X.context_management?.edits?.some((Y)=>Y.type==="compact_20260112")}function nJ(X){return"input_schema"in X}function rJ(X){return typeof X==="object"&&X!==null&&"type"in X&&(("name"in X)||("mcp_server_name"in X))&&typeof X.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((Y)=>typeof X.type==="string"&&X.type.startsWith(Y))}function aJ(X,Y,...$){return Array.from(new Set([...X??[],...Y??[],...$.flatMap((W)=>Array.from(W))]))}function tJ(X){if(typeof X.content==="string")return X.content;else if(Array.isArray(X.content)&&X.content.length>=1&&"input"in X.content[0])return typeof X.content[0].input==="string"?X.content[0].input:JSON.stringify(X.content[0].input);else if(Array.isArray(X.content)&&X.content.length>=1&&"text"in X.content[0]&&typeof X.content[0].text==="string")return X.content[0].text}var OW=class extends k8{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-sonnet-4-5-20250929";model="claude-sonnet-4-5-20250929";invocationKwargs;stopSequences;streaming=!1;clientOptions;thinking={type:"disabled"};contextManagement;outputConfig;inferenceGeo;batchClient;streamingClient;streamUsage=!0;betas;createClient;constructor(X,Y){let $=typeof X==="string"?{...Y??{},model:X}:X??{};super($??{});if(this._addVersion("@langchain/anthropic","1.3.22"),this.anthropicApiKey=$?.apiKey??$?.anthropicApiKey??BX("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??mJ(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??((W)=>new $0(W))}getLsParams(X){let Y=this.invocationParams(X);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:Y.temperature??void 0,ls_max_tokens:Y.max_tokens??void 0,ls_stop:X.stop}}formatStructuredToolToAnthropic(X){if(!X)return;return X.map((Y)=>{if(hX(Y)&&Y.extras?.providerToolDefinition)return Y.extras.providerToolDefinition;if(rJ(Y))return Y;if(nJ(Y))return Y;if(aX(Y))return{name:Y.function.name,description:Y.function.description,input_schema:Y.function.parameters};if(hX(Y))return{name:Y.name,description:Y.description,input_schema:HX(Y.schema)?WX(Y.schema):Y.schema,...Y.extras?V2.parse(Y.extras):{}};throw Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(Y,null,2)}`)})}bindTools(X,Y){return this.withConfig({tools:this.formatStructuredToolToAnthropic(X),...Y})}invocationParams(X){let Y=K2(X?.tool_choice),$=X?.tools?.reduce((J,G)=>{if(typeof G==="object"&&"type"in G&&G.type in j9){let z=j9[G.type];if(!J.includes(z))return[...J,z]}return J},[]),W=(()=>{let J={...this.outputConfig,...X?.outputConfig};if(X?.outputFormat&&!J.format)J.format=X.outputFormat;return Object.keys(J).length>0?J:void 0})(),Z=this.contextManagement?.edits?.some((J)=>J.type==="compact_20260112")?["compact-2026-01-12"]:[],Q={model:this.model,stop_sequences:X?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(X?.tools),tool_choice:Y,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:X?.container,betas:aJ(this.betas,X?.betas,$??[],Z),output_config:W,inference_geo:X?.inferenceGeo??this.inferenceGeo,mcp_servers:X?.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 if(Q.temperature=this.temperature,Q.top_k=this.topK,this.topP!==void 0)Q.top_p=this.topP;return Q}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(X,Y,$){let W=this.invocationParams(Y),Z=rY(X);if(Y.cache_control)Z=f9(Z,Y.cache_control);let Q={...W,...Z,stream:!0},J=!cJ(Q)&&!pJ(Q)&&!lJ(Q)&&!iJ(Q),G=await this.createStreamWithRetry(Q,{headers:Y.headers,signal:Y.signal});for await(let z of G){if(Y.signal?.aborted){G.controller.abort();return}let B=this.streamUsage??Y.streamUsage,H=L2(z,{streamUsage:B,coerceContentToString:J});if(!H)continue;let{chunk:V}=H,K=tJ(V),U=new tX({message:new u({content:V.content,additional_kwargs:V.additional_kwargs,tool_call_chunks:V.tool_call_chunks,usage_metadata:B?V.usage_metadata:void 0,response_metadata:V.response_metadata,id:V.id}),text:K??""});yield U,await $?.handleLLMNewToken(K??"",void 0,void 0,void 0,void 0,{chunk:U})}}async _generateNonStreaming(X,Y,$,W){let Z=rY(X);if(W)Z=f9(Z,W);let{content:Q,...J}=await this.completionWithRetry({...Y,stream:!1,...Z},$),G=E2(Q,J),{role:z,type:B,...H}=J;return{generations:G,llmOutput:H}}async _generate(X,Y,$){if(Y.signal?.throwIfAborted(),this.stopSequences&&Y.stop)throw Error('"stopSequence" parameter found in input and default params');let W=this.invocationParams(Y);if(W.stream){let Z,Q=this._streamResponseChunks(X,Y,$);for await(let J of Q)if(Z===void 0)Z=J;else Z=Z.concat(J);if(Z===void 0)throw Error("No chunks returned from Anthropic API.");return{generations:[{text:Z.text,message:Z.message}]}}else return this._generateNonStreaming(X,W,{signal:Y.signal,headers:Y.headers},Y.cache_control)}async createStreamWithRetry(X,Y){if(!this.streamingClient){let Q=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...Q,apiKey:this.apiKey,maxRetries:0})}let{betas:$,...W}=X,Z=async()=>{try{if(X?.betas?.length)return await this.streamingClient.beta.messages.create({...W,betas:$,...this.invocationKwargs,stream:!0},Y);return await this.streamingClient.messages.create({...W,...this.invocationKwargs,stream:!0},Y)}catch(Q){throw h9(Q)}};return this.caller.call(Z)}async completionWithRetry(X,Y){if(!this.batchClient){let Q=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...Q,apiKey:this.apiKey,maxRetries:0})}let{betas:$,...W}=X,Z=async()=>{try{if(X?.betas?.length)return await this.batchClient.beta.messages.create({...W,...this.invocationKwargs,betas:$},Y);return await this.batchClient.messages.create({...W,...this.invocationKwargs},Y)}catch(Q){throw h9(Q)}};return this.caller.callWithOptions({signal:Y.signal??void 0},Z)}_llmType(){return"anthropic"}get profile(){return O2[this.model]??{}}withStructuredOutput(X,Y){let $,W,{schema:Z,name:Q,includeRaw:J}={...Y,schema:X},G=Y?.method??"functionCalling";if(G==="jsonMode")console.warn('"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".'),G="jsonSchema";if(G==="jsonSchema"){W=LW(Z);let z=wW(WX(Z));$=this.withConfig({outputVersion:"v0",outputConfig:{format:{type:"json_schema",schema:z}},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:z}})}else if(G==="functionCalling"){let z=Q??"extract",B;if(HX(Z)||FW(Z)){let H=WX(Z);B=[{name:z,description:H.description??"A function available to call.",input_schema:H}]}else if(typeof Z.name==="string"&&typeof Z.description==="string"&&typeof Z.input_schema==="object"&&Z.input_schema!=null)B=[Z],z=Z.name;else B=[{name:z,description:Z.description??"",input_schema:Z}];if(W=EW(Z,z,Z2),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."),$=this.withConfig({outputVersion:"v0",tools:B,ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:WX(Z)}});let V=(K)=>{if(!K.tool_calls||K.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 K};$=$.pipe(V)}else $=this.withConfig({outputVersion:"v0",tools:B,tool_choice:{type:"tool",name:z},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:WX(Z)}})}else throw TypeError(`Unrecognized structured output method '${G}'. Expected 'functionCalling' or 'jsonSchema'`);return xW($,W,J,J?"StructuredOutputRunnable":"ChatAnthropicStructuredOutput")}},U6=class extends OW{};var sJ=N.object({command:N.literal("view"),path:N.string()}),oJ=N.object({command:N.literal("create"),path:N.string(),file_text:N.string()}),eJ=N.object({command:N.literal("str_replace"),path:N.string(),old_str:N.string(),new_str:N.string()}),XG=N.object({command:N.literal("insert"),path:N.string(),insert_line:N.number(),insert_text:N.string()}),YG=N.object({command:N.literal("delete"),path:N.string()}),$G=N.object({command:N.literal("rename"),old_path:N.string(),new_path:N.string()}),WG=N.discriminatedUnion("command",[sJ,oJ,eJ,XG,YG,$G]),ZG=N.object({command:N.literal("view"),path:N.string(),view_range:N.tuple([N.number(),N.number()]).optional()}),QG=N.object({command:N.literal("str_replace"),path:N.string(),old_str:N.string(),new_str:N.string()}),JG=N.object({command:N.literal("create"),path:N.string(),file_text:N.string()}),GG=N.object({command:N.literal("insert"),path:N.string(),insert_line:N.number(),new_str:N.string()}),KG=N.discriminatedUnion("command",[ZG,QG,JG,GG]),IX=N.tuple([N.number(),N.number()]),DW=N.object({action:N.literal("screenshot")}),MW=N.object({action:N.literal("left_click"),coordinate:IX}),TW=N.object({action:N.literal("right_click"),coordinate:IX}),AW=N.object({action:N.literal("middle_click"),coordinate:IX}),PW=N.object({action:N.literal("double_click"),coordinate:IX}),SW=N.object({action:N.literal("triple_click"),coordinate:IX}),RW=N.object({action:N.literal("left_click_drag"),start_coordinate:IX,end_coordinate:IX}),CW=N.object({action:N.literal("left_mouse_down"),coordinate:IX}),IW=N.object({action:N.literal("left_mouse_up"),coordinate:IX}),jW=N.object({action:N.literal("scroll"),coordinate:IX,scroll_direction:N.enum(["up","down","left","right"]),scroll_amount:N.number()}),_W=N.object({action:N.literal("type"),text:N.string()}),yW=N.object({action:N.literal("key"),key:N.string()}),kW=N.object({action:N.literal("mouse_move"),coordinate:IX}),vW=N.object({action:N.literal("hold_key"),key:N.string()}),bW=N.object({action:N.literal("wait"),duration:N.number().optional()}),VG=N.object({action:N.literal("zoom"),region:N.tuple([N.number(),N.number(),N.number(),N.number()])}),zG=N.discriminatedUnion("action",[DW,MW,TW,AW,PW,SW,RW,CW,IW,jW,_W,yW,kW,vW,bW]),HG=N.discriminatedUnion("action",[DW,MW,TW,AW,PW,SW,RW,CW,IW,jW,_W,yW,kW,vW,bW,VG]),BG=N.object({command:N.string().describe("The bash command to run")}),NG=N.object({restart:N.literal(!0).describe("Set to true to restart the bash session")}),UG=N.union([BG,NG]);function W0(X){if(typeof X==="object"&&X!==null){let Y={...X};if("additionalProperties"in Y)delete Y.additionalProperties;if("$schema"in Y)delete Y.$schema;if("strict"in Y)delete Y.strict;for(let $ in Y)if($ in Y){if(Array.isArray(Y[$]))Y[$]=Y[$].map(W0);else if(typeof Y[$]==="object"&&Y[$]!==null)Y[$]=W0(Y[$])}return Y}return X}function t7(X){let{$schema:Y,...$}=W0(HX(X)?WX(X):X);return $}function fW(X){let{$schema:Y,...$}=W0(X);return $}function $8(X,Y,$=[]){if(X==null||typeof X!=="object")return;let W=X;if(Array.isArray(W.enum)){if(W.enum.some((Z)=>Z==="")){let Z=$.length?` at path "${$.join(".")}"`:"",Q=Y?` in tool "${Y}"`:"";throw Error(`Invalid enum: empty string not allowed${Q}${Z}. Gemini API rejects empty strings in enums.`)}}if(W.type==="object"&&W.properties&&typeof W.properties==="object")for(let[Z,Q]of Object.entries(W.properties))$8(Q,Y,[...$,Z]);if(W.items)$8(W.items,Y,[...$,"[]"]);for(let Z of["anyOf","oneOf","allOf"]){let Q=W[Z];if(Array.isArray(Q))Q.forEach((J,G)=>$8(J,Y,[...$,`${Z}[${G}]`]))}if(W.additionalProperties&&typeof W.additionalProperties==="object")$8(W.additionalProperties,Y,[...$,"additionalProperties"])}wG();var q6="__gemini_function_call_thought_signatures__",qG="ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==",FG=(X)=>X();function LG(X){if(l0.isInstance(X))return X.role;return X.type}function EG(X){switch(X){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: ${X}`)}}function xG(X){if("mimeType"in X&&"data"in X)return{inlineData:{mimeType:X.mimeType,data:X.data}};if("mimeType"in X&&"fileUri"in X)return{fileData:{mimeType:X.mimeType,fileUri:X.fileUri}};throw Error("Invalid media content")}function OG(X,Y){return Y.map(($)=>{if(b8($))return $.tool_calls??[];return[]}).flat().find(($)=>{return $.id===X.tool_call_id})?.name}function DG(X){return{providerName:"Google Gemini",fromStandardTextBlock(Y){return{text:Y.text}},fromStandardImageBlock(Y){if(!X)throw Error("This model does not support images");if(Y.source_type==="url"){let $=OX({dataUrl:Y.url});if($)return{inlineData:{mimeType:$.mime_type,data:$.data}};else return{fileData:{mimeType:Y.mime_type??"",fileUri:Y.url}}}if(Y.source_type==="base64")return{inlineData:{mimeType:Y.mime_type??"",data:Y.data}};throw Error(`Unsupported source type: ${Y.source_type}`)},fromStandardAudioBlock(Y){if(!X)throw Error("This model does not support audio");if(Y.source_type==="url"){let $=OX({dataUrl:Y.url});if($)return{inlineData:{mimeType:$.mime_type,data:$.data}};else return{fileData:{mimeType:Y.mime_type??"",fileUri:Y.url}}}if(Y.source_type==="base64")return{inlineData:{mimeType:Y.mime_type??"",data:Y.data}};throw Error(`Unsupported source type: ${Y.source_type}`)},fromStandardFileBlock(Y){if(!X)throw Error("This model does not support files");if(Y.source_type==="text")return{text:Y.text};if(Y.source_type==="url"){let $=OX({dataUrl:Y.url});if($)return{inlineData:{mimeType:$.mime_type,data:$.data}};else return{fileData:{mimeType:Y.mime_type??"",fileUri:Y.url}}}if(Y.source_type==="base64")return{inlineData:{mimeType:Y.mime_type??"",data:Y.data}};throw Error(`Unsupported source type: ${Y.source_type}`)}}}function hW(X,Y){if(x0(X))return O0(X,DG(Y));if(X.type==="text")return{text:X.text};else if(X.type==="executableCode")return{executableCode:X.executableCode};else if(X.type==="codeExecutionResult")return{codeExecutionResult:X.codeExecutionResult};else if(X.type==="image_url"){if(!Y)throw Error("This model does not support images");let $;if(typeof X.image_url==="string")$=X.image_url;else if(typeof X.image_url==="object"&&"url"in X.image_url)$=X.image_url.url;else throw Error("Please provide image as base64 encoded data URL");let[W,Z]=$.split(",");if(!W.startsWith("data:"))throw Error("Please provide image as base64 encoded data URL");let[Q,J]=W.replace(/^data:/,"").split(";");if(J!=="base64")throw Error("Please provide image as base64 encoded data URL");return{inlineData:{data:Z,mimeType:Q}}}else if(X.type==="media")return xG(X);else if(X.type==="tool_use")return{functionCall:{name:X.name,args:X.input}};else if(X.type==="tool_call")return{functionCall:{name:X.name,args:X.args}};else if(X.type?.includes("/")&&X.type.split("/").length===2&&"data"in X&&typeof X.data==="string")return{inlineData:{mimeType:X.type,data:X.data}};else if("functionCall"in X)return;else if("type"in X)throw Error(`Unknown content type ${X.type}`);else throw Error(`Unknown content ${JSON.stringify(X)}`)}function MG(X,Y,$,W){if(uW(X)){let G=X.name??OG(X,$);if(G===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 "${X.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);let z=Array.isArray(X.content)?X.content.map((B)=>hW(B,Y)).filter((B)=>B!==void 0):X.content;if(X.status==="error")return[{functionResponse:{name:G,response:{error:{details:z}}}}];return[{functionResponse:{name:G,response:{result:z}}}]}let Z=[],Q=[];if(typeof X.content==="string"&&X.content)Q.push({text:X.content});if(Array.isArray(X.content))Q.push(...X.content.map((G)=>hW(G,Y)).filter((G)=>G!==void 0));let J=X.additional_kwargs?.[q6];if(b8(X)&&X.tool_calls?.length)Z=X.tool_calls.map((G)=>{let z=FG(()=>{if(G.id){let B=J?.[G.id];if(B)return B}if(W?.includes("gemini-3"))return qG;return""});return{functionCall:{name:G.name,args:G.args},...z?{thoughtSignature:z}:{}}});return[...Q,...Z]}function F6(X,Y,$=!1,W){return X.reduce((Z,Q,J)=>{if(!gW(Q))throw Error("Unsupported message input");let G=LG(Q);if(G==="system"&&J!==0)throw Error("System message should be the first one");let z=EG(G),B=Z.content[Z.content.length];if(!Z.mergeWithPreviousContent&&B&&B.role===z)throw Error("Google Generative AI requires alternate messages between authors");let H=MG(Q,Y,X.slice(0,J),W);if(Z.mergeWithPreviousContent){let U=Z.content[Z.content.length-1];if(!U)throw Error("There was a problem parsing your system message. Please try a prompt without one.");return U.parts.push(...H),{mergeWithPreviousContent:!1,content:Z.content}}let V=z;if(V==="function"||V==="system"&&!$)V="user";let K={role:V,parts:H};return{mergeWithPreviousContent:G==="system"&&!$,content:[...Z.content,K]}},{content:[],mergeWithPreviousContent:!1}).content}function dW(X,Y){if(!X.candidates||X.candidates.length===0||!X.candidates[0])return{generations:[],llmOutput:{filters:X.promptFeedback}};let[$]=X.candidates,{content:W,...Z}=$,Q=W.parts?.reduce((H,V)=>{if("functionCall"in V&&V.functionCall)H.push({...V,id:"id"in V.functionCall&&typeof V.functionCall.id==="string"?V.functionCall.id:w6()});return H},[]),J,G=W?.parts;if(Array.isArray(G)&&G.length===1&&"text"in G[0]&&G[0].text&&!G[0].thought)J=G[0].text;else if(Array.isArray(G)&&G.length>0)J=G.map((H)=>{if(H.thought&&"text"in H&&H.text)return{type:"thinking",thinking:H.text,...H.thoughtSignature?{signature:H.thoughtSignature}:{}};else if("text"in H)return{type:"text",text:H.text};else if("inlineData"in H)return{type:"inlineData",inlineData:H.inlineData};else if("functionCall"in H)return{type:"functionCall",functionCall:H.functionCall};else if("functionResponse"in H)return{type:"functionResponse",functionResponse:H.functionResponse};else if("fileData"in H)return{type:"fileData",fileData:H.fileData};else if("executableCode"in H)return{type:"executableCode",executableCode:H.executableCode};else if("codeExecutionResult"in H)return{type:"codeExecutionResult",codeExecutionResult:H.codeExecutionResult};return H});else J=[];let z=Q?.reduce((H,V)=>{if("thoughtSignature"in V&&typeof V.thoughtSignature==="string")H[V.id]=V.thoughtSignature;return H},{}),B="";if(typeof J==="string")B=J;else if(Array.isArray(J)&&J.length>0)B=J.find((H)=>("text"in H))?.text??B;return{generations:[{text:B,message:new r({content:J??"",tool_calls:Q?.map((H)=>({type:"tool_call",id:H.id,name:H.functionCall.name,args:H.functionCall.args})),additional_kwargs:{...Z,[q6]:z},usage_metadata:Y?.usageMetadata}),generationInfo:Z}],llmOutput:{tokenUsage:{promptTokens:Y?.usageMetadata?.input_tokens,completionTokens:Y?.usageMetadata?.output_tokens,totalTokens:Y?.usageMetadata?.total_tokens}}}}function mW(X,Y){if(!X.candidates||X.candidates.length===0)return null;let[$]=X.candidates,{content:W,...Z}=$,Q=W.parts?.reduce((V,K)=>{if("functionCall"in K&&K.functionCall)V.push({...K,id:"id"in K.functionCall&&typeof K.functionCall.id==="string"?K.functionCall.id:w6()});return V},[]),J,G=W?.parts;if(Array.isArray(G)&&G.every((V)=>("text"in V)&&!V.thought))J=G.map((V)=>V.text).join("");else if(Array.isArray(G))J=G.map((V)=>{if(V.thought&&"text"in V&&V.text)return{type:"thinking",thinking:V.text,...V.thoughtSignature?{signature:V.thoughtSignature}:{}};else if("text"in V)return{type:"text",text:V.text};else if("inlineData"in V)return{type:"inlineData",inlineData:V.inlineData};else if("functionCall"in V)return{type:"functionCall",functionCall:V.functionCall};else if("functionResponse"in V)return{type:"functionResponse",functionResponse:V.functionResponse};else if("fileData"in V)return{type:"fileData",fileData:V.fileData};else if("executableCode"in V)return{type:"executableCode",executableCode:V.executableCode};else if("codeExecutionResult"in V)return{type:"codeExecutionResult",codeExecutionResult:V.codeExecutionResult};return V});else J=[];let z="";if(J&&typeof J==="string")z=J;else if(Array.isArray(J))z=J.find((V)=>("text"in V))?.text??"";let B=[];if(Q)B.push(...Q.map((V)=>({type:"tool_call_chunk",id:V.id,name:V.functionCall.name,args:JSON.stringify(V.functionCall.args)})));let H=Q?.reduce((V,K)=>{if("thoughtSignature"in K&&typeof K.thoughtSignature==="string")V[K.id]=K.thoughtSignature;return V},{});return new tX({text:z,message:new u({content:J||"",name:!W?void 0:W.role,tool_call_chunks:B,additional_kwargs:{[q6]:H},response_metadata:{model_provider:"google-genai"},usage_metadata:Y.usageMetadata}),generationInfo:Z})}function cW(X){if(X.every((Y)=>("functionDeclarations"in Y)&&Array.isArray(Y.functionDeclarations)))return X;return[{functionDeclarations:X.map((Y)=>{if(hX(Y)){let $=t7(Y.schema);if($.type==="object"&&"properties"in $&&Object.keys($.properties).length===0)return{name:Y.name,description:Y.description};return $8($,Y.name),{name:Y.name,description:Y.description,parameters:$}}if(aX(Y)){let $=fW(Y.function.parameters);return $8($,Y.function.name),{name:Y.function.name,description:Y.function.description??"A function available to call.",parameters:$}}return Y})}]}function L6(X,Y){let $={input_tokens:X?.promptTokenCount??0,output_tokens:X?.candidatesTokenCount??0,total_tokens:X?.totalTokenCount??0};if(X?.cachedContentTokenCount)$.input_token_details??={},$.input_token_details.cache_read=X.cachedContentTokenCount;if(Y==="gemini-3-pro-preview"){let W=Math.max(0,X?.promptTokenCount??-200000),Z=Math.max(0,X?.cachedContentTokenCount??-200000);if(W)$.input_token_details={...$.input_token_details,over_200k:W};if(Z)$.input_token_details={...$.input_token_details,cache_read_over_200k:Z}}return $}var E6=class extends iY{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(X){super(X);this.keyName=X.keyName,this.returnSingle=X.returnSingle??this.returnSingle,this.zodSchema=X.zodSchema}async _validateResult(X){if(this.zodSchema===void 0)return X;let Y=await lY(this.zodSchema,X);if(Y.success)return Y.data;else throw new f8(`Failed to parse. Text: "${JSON.stringify(X,null,2)}". Error: ${JSON.stringify(Y.error.issues)}`,JSON.stringify(X,null,2))}async parseResult(X){let Y=X.flatMap((W)=>{let{message:Z}=W;if(!("tool_calls"in Z)||!Array.isArray(Z.tool_calls))return[];return Z.tool_calls});if(Y[0]===void 0)throw Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");let[$]=Y;return await this._validateResult($.args)}};var pW;(function(X){X.STRING="string",X.NUMBER="number",X.INTEGER="integer",X.BOOLEAN="boolean",X.ARRAY="array",X.OBJECT="object"})(pW||(pW={}));var lW;(function(X){X.LANGUAGE_UNSPECIFIED="language_unspecified",X.PYTHON="python"})(lW||(lW={}));var iW;(function(X){X.OUTCOME_UNSPECIFIED="outcome_unspecified",X.OUTCOME_OK="outcome_ok",X.OUTCOME_FAILED="outcome_failed",X.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(iW||(iW={}));var nW=["user","model","function","system"],rW;(function(X){X.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",X.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",X.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",X.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",X.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",X.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(rW||(rW={}));var aW;(function(X){X.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",X.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",X.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",X.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",X.BLOCK_NONE="BLOCK_NONE"})(aW||(aW={}));var tW;(function(X){X.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",X.NEGLIGIBLE="NEGLIGIBLE",X.LOW="LOW",X.MEDIUM="MEDIUM",X.HIGH="HIGH"})(tW||(tW={}));var sW;(function(X){X.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",X.SAFETY="SAFETY",X.OTHER="OTHER"})(sW||(sW={}));var s7;(function(X){X.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",X.STOP="STOP",X.MAX_TOKENS="MAX_TOKENS",X.SAFETY="SAFETY",X.RECITATION="RECITATION",X.LANGUAGE="LANGUAGE",X.BLOCKLIST="BLOCKLIST",X.PROHIBITED_CONTENT="PROHIBITED_CONTENT",X.SPII="SPII",X.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",X.OTHER="OTHER"})(s7||(s7={}));var oW;(function(X){X.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",X.RETRIEVAL_QUERY="RETRIEVAL_QUERY",X.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",X.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",X.CLASSIFICATION="CLASSIFICATION",X.CLUSTERING="CLUSTERING"})(oW||(oW={}));var Z8;(function(X){X.MODE_UNSPECIFIED="MODE_UNSPECIFIED",X.AUTO="AUTO",X.ANY="ANY",X.NONE="NONE"})(Z8||(Z8={}));var eW;(function(X){X.MODE_UNSPECIFIED="MODE_UNSPECIFIED",X.MODE_DYNAMIC="MODE_DYNAMIC"})(eW||(eW={}));class ZX extends Error{constructor(X){super(`[GoogleGenerativeAI Error]: ${X}`)}}class W8 extends ZX{constructor(X,Y){super(X);this.response=Y}}class O6 extends ZX{constructor(X,Y,$,W){super(X);this.status=Y,this.statusText=$,this.errorDetails=W}}class Z0 extends ZX{}class D6 extends ZX{}var TG="https://generativelanguage.googleapis.com",AG="v1beta",PG="0.24.1",SG="genai-js",Q8;(function(X){X.GENERATE_CONTENT="generateContent",X.STREAM_GENERATE_CONTENT="streamGenerateContent",X.COUNT_TOKENS="countTokens",X.EMBED_CONTENT="embedContent",X.BATCH_EMBED_CONTENTS="batchEmbedContents"})(Q8||(Q8={}));class JZ{constructor(X,Y,$,W,Z){this.model=X,this.task=Y,this.apiKey=$,this.stream=W,this.requestOptions=Z}toString(){var X,Y;let $=((X=this.requestOptions)===null||X===void 0?void 0:X.apiVersion)||AG,Z=`${((Y=this.requestOptions)===null||Y===void 0?void 0:Y.baseUrl)||TG}/${$}/${this.model}:${this.task}`;if(this.stream)Z+="?alt=sse";return Z}}function RG(X){let Y=[];if(X===null||X===void 0?void 0:X.apiClient)Y.push(X.apiClient);return Y.push(`${SG}/${PG}`),Y.join(" ")}async function CG(X){var Y;let $=new Headers;$.append("Content-Type","application/json"),$.append("x-goog-api-client",RG(X.requestOptions)),$.append("x-goog-api-key",X.apiKey);let W=(Y=X.requestOptions)===null||Y===void 0?void 0:Y.customHeaders;if(W){if(!(W instanceof Headers))try{W=new Headers(W)}catch(Z){throw new Z0(`unable to convert customHeaders value ${JSON.stringify(W)} to Headers: ${Z.message}`)}for(let[Z,Q]of W.entries()){if(Z==="x-goog-api-key")throw new Z0(`Cannot set reserved header name ${Z}`);else if(Z==="x-goog-api-client")throw new Z0(`Header name ${Z} can only be set using the apiClient field`);$.append(Z,Q)}}return $}async function IG(X,Y,$,W,Z,Q){let J=new JZ(X,Y,$,W,Q);return{url:J.toString(),fetchOptions:Object.assign(Object.assign({},kG(Q)),{method:"POST",headers:await CG(J),body:Z})}}async function XY(X,Y,$,W,Z,Q={},J=fetch){let{url:G,fetchOptions:z}=await IG(X,Y,$,W,Z,Q);return jG(G,z,J)}async function jG(X,Y,$=fetch){let W;try{W=await $(X,Y)}catch(Z){_G(Z,X)}if(!W.ok)await yG(W,X);return W}function _G(X,Y){let $=X;if($.name==="AbortError")$=new D6(`Request aborted when fetching ${Y.toString()}: ${X.message}`),$.stack=X.stack;else if(!(X instanceof O6||X instanceof Z0))$=new ZX(`Error fetching from ${Y.toString()}: ${X.message}`),$.stack=X.stack;throw $}async function yG(X,Y){let $="",W;try{let Z=await X.json();if($=Z.error.message,Z.error.details)$+=` ${JSON.stringify(Z.error.details)}`,W=Z.error.details}catch(Z){}throw new O6(`Error fetching from ${Y.toString()}: [${X.status} ${X.statusText}] ${$}`,X.status,X.statusText,W)}function kG(X){let Y={};if((X===null||X===void 0?void 0:X.signal)!==void 0||(X===null||X===void 0?void 0:X.timeout)>=0){let $=new AbortController;if((X===null||X===void 0?void 0:X.timeout)>=0)setTimeout(()=>$.abort(),X.timeout);if(X===null||X===void 0?void 0:X.signal)X.signal.addEventListener("abort",()=>{$.abort()});Y.signal=$.signal}return Y}function M6(X){return X.text=()=>{if(X.candidates&&X.candidates.length>0){if(X.candidates.length>1)console.warn(`This response had ${X.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`);if(M$(X.candidates[0]))throw new W8(`${R0(X)}`,X);return vG(X)}else if(X.promptFeedback)throw new W8(`Text not available. ${R0(X)}`,X);return""},X.functionCall=()=>{if(X.candidates&&X.candidates.length>0){if(X.candidates.length>1)console.warn(`This response had ${X.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`);if(M$(X.candidates[0]))throw new W8(`${R0(X)}`,X);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),XZ(X)[0]}else if(X.promptFeedback)throw new W8(`Function call not available. ${R0(X)}`,X);return},X.functionCalls=()=>{if(X.candidates&&X.candidates.length>0){if(X.candidates.length>1)console.warn(`This response had ${X.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`);if(M$(X.candidates[0]))throw new W8(`${R0(X)}`,X);return XZ(X)}else if(X.promptFeedback)throw new W8(`Function call not available. ${R0(X)}`,X);return},X}function vG(X){var Y,$,W,Z;let Q=[];if(($=(Y=X.candidates)===null||Y===void 0?void 0:Y[0].content)===null||$===void 0?void 0:$.parts)for(let J of(Z=(W=X.candidates)===null||W===void 0?void 0:W[0].content)===null||Z===void 0?void 0:Z.parts){if(J.text)Q.push(J.text);if(J.executableCode)Q.push("\n```"+J.executableCode.language+`
|
|
104
|
+
`+J.executableCode.code+"\n```\n");if(J.codeExecutionResult)Q.push("\n```\n"+J.codeExecutionResult.output+"\n```\n")}if(Q.length>0)return Q.join("");else return""}function XZ(X){var Y,$,W,Z;let Q=[];if(($=(Y=X.candidates)===null||Y===void 0?void 0:Y[0].content)===null||$===void 0?void 0:$.parts){for(let J of(Z=(W=X.candidates)===null||W===void 0?void 0:W[0].content)===null||Z===void 0?void 0:Z.parts)if(J.functionCall)Q.push(J.functionCall)}if(Q.length>0)return Q;else return}var bG=[s7.RECITATION,s7.SAFETY,s7.LANGUAGE];function M$(X){return!!X.finishReason&&bG.includes(X.finishReason)}function R0(X){var Y,$,W;let Z="";if((!X.candidates||X.candidates.length===0)&&X.promptFeedback){if(Z+="Response was blocked",(Y=X.promptFeedback)===null||Y===void 0?void 0:Y.blockReason)Z+=` due to ${X.promptFeedback.blockReason}`;if(($=X.promptFeedback)===null||$===void 0?void 0:$.blockReasonMessage)Z+=`: ${X.promptFeedback.blockReasonMessage}`}else if((W=X.candidates)===null||W===void 0?void 0:W[0]){let Q=X.candidates[0];if(M$(Q)){if(Z+=`Candidate was blocked due to ${Q.finishReason}`,Q.finishMessage)Z+=`: ${Q.finishMessage}`}}return Z}function o7(X){return this instanceof o7?(this.v=X,this):new o7(X)}function fG(X,Y,$){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var W=$.apply(X,Y||[]),Z,Q=[];return Z={},J("next"),J("throw"),J("return"),Z[Symbol.asyncIterator]=function(){return this},Z;function J(K){if(W[K])Z[K]=function(U){return new Promise(function(E,I){Q.push([K,U,E,I])>1||G(K,U)})}}function G(K,U){try{z(W[K](U))}catch(E){V(Q[0][3],E)}}function z(K){K.value instanceof o7?Promise.resolve(K.value.v).then(B,H):V(Q[0][2],K)}function B(K){G("next",K)}function H(K){G("throw",K)}function V(K,U){if(K(U),Q.shift(),Q.length)G(Q[0][0],Q[0][1])}}var YZ=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function hG(X){let Y=X.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),$=dG(Y),[W,Z]=$.tee();return{stream:uG(W),response:gG(Z)}}async function gG(X){let Y=[],$=X.getReader();while(!0){let{done:W,value:Z}=await $.read();if(W)return M6(mG(Y));Y.push(Z)}}function uG(X){return fG(this,arguments,function*(){let $=X.getReader();while(!0){let{value:W,done:Z}=yield o7($.read());if(Z)break;yield yield o7(M6(W))}})}function dG(X){let Y=X.getReader();return new ReadableStream({start(W){let Z="";return Q();function Q(){return Y.read().then(({value:J,done:G})=>{if(G){if(Z.trim()){W.error(new ZX("Failed to parse stream"));return}W.close();return}Z+=J;let z=Z.match(YZ),B;while(z){try{B=JSON.parse(z[1])}catch(H){W.error(new ZX(`Error parsing JSON response: "${z[1]}"`));return}W.enqueue(B),Z=Z.substring(z[0].length),z=Z.match(YZ)}return Q()}).catch((J)=>{let G=J;if(G.stack=J.stack,G.name==="AbortError")G=new D6("Request aborted when reading from the stream");else G=new ZX("Error reading from the stream");throw G})}}})}function mG(X){let Y=X[X.length-1],$={promptFeedback:Y===null||Y===void 0?void 0:Y.promptFeedback};for(let W of X){if(W.candidates){let Z=0;for(let Q of W.candidates){if(!$.candidates)$.candidates=[];if(!$.candidates[Z])$.candidates[Z]={index:Z};if($.candidates[Z].citationMetadata=Q.citationMetadata,$.candidates[Z].groundingMetadata=Q.groundingMetadata,$.candidates[Z].finishReason=Q.finishReason,$.candidates[Z].finishMessage=Q.finishMessage,$.candidates[Z].safetyRatings=Q.safetyRatings,Q.content&&Q.content.parts){if(!$.candidates[Z].content)$.candidates[Z].content={role:Q.content.role||"user",parts:[]};let J={};for(let G of Q.content.parts){if(G.text)J.text=G.text;if(G.functionCall)J.functionCall=G.functionCall;if(G.executableCode)J.executableCode=G.executableCode;if(G.codeExecutionResult)J.codeExecutionResult=G.codeExecutionResult;if(Object.keys(J).length===0)J.text="";$.candidates[Z].content.parts.push(J)}}}Z++}if(W.usageMetadata)$.usageMetadata=W.usageMetadata}return $}async function GZ(X,Y,$,W){let Z=await XY(Y,Q8.STREAM_GENERATE_CONTENT,X,!0,JSON.stringify($),W);return hG(Z)}async function KZ(X,Y,$,W){let Q=await(await XY(Y,Q8.GENERATE_CONTENT,X,!1,JSON.stringify($),W)).json();return{response:M6(Q)}}function VZ(X){if(X==null)return;else if(typeof X==="string")return{role:"system",parts:[{text:X}]};else if(X.text)return{role:"system",parts:[X]};else if(X.parts)if(!X.role)return{role:"system",parts:X.parts};else return X}function e7(X){let Y=[];if(typeof X==="string")Y=[{text:X}];else for(let $ of X)if(typeof $==="string")Y.push({text:$});else Y.push($);return cG(Y)}function cG(X){let Y={role:"user",parts:[]},$={role:"function",parts:[]},W=!1,Z=!1;for(let Q of X)if("functionResponse"in Q)$.parts.push(Q),Z=!0;else Y.parts.push(Q),W=!0;if(W&&Z)throw new ZX("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!W&&!Z)throw new ZX("No content is provided for sending chat message.");if(W)return Y;return $}function pG(X,Y){var $;let W={model:Y===null||Y===void 0?void 0:Y.model,generationConfig:Y===null||Y===void 0?void 0:Y.generationConfig,safetySettings:Y===null||Y===void 0?void 0:Y.safetySettings,tools:Y===null||Y===void 0?void 0:Y.tools,toolConfig:Y===null||Y===void 0?void 0:Y.toolConfig,systemInstruction:Y===null||Y===void 0?void 0:Y.systemInstruction,cachedContent:($=Y===null||Y===void 0?void 0:Y.cachedContent)===null||$===void 0?void 0:$.name,contents:[]},Z=X.generateContentRequest!=null;if(X.contents){if(Z)throw new Z0("CountTokensRequest must have one of contents or generateContentRequest, not both.");W.contents=X.contents}else if(Z)W=Object.assign(Object.assign({},W),X.generateContentRequest);else{let Q=e7(X);W.contents=[Q]}return{generateContentRequest:W}}function $Z(X){let Y;if(X.contents)Y=X;else Y={contents:[e7(X)]};if(X.systemInstruction)Y.systemInstruction=VZ(X.systemInstruction);return Y}function lG(X){if(typeof X==="string"||Array.isArray(X))return{content:e7(X)};return X}var WZ=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],iG={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function nG(X){let Y=!1;for(let $ of X){let{role:W,parts:Z}=$;if(!Y&&W!=="user")throw new ZX(`First content should be with role 'user', got ${W}`);if(!nW.includes(W))throw new ZX(`Each item should include role field. Got ${W} but valid roles are: ${JSON.stringify(nW)}`);if(!Array.isArray(Z))throw new ZX("Content should have 'parts' property with an array of Parts");if(Z.length===0)throw new ZX("Each Content should have at least one part");let Q={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(let G of Z)for(let z of WZ)if(z in G)Q[z]+=1;let J=iG[W];for(let G of WZ)if(!J.includes(G)&&Q[G]>0)throw new ZX(`Content with role '${W}' can't contain '${G}' part`);Y=!0}}function ZZ(X){var Y;if(X.candidates===void 0||X.candidates.length===0)return!1;let $=(Y=X.candidates[0])===null||Y===void 0?void 0:Y.content;if($===void 0)return!1;if($.parts===void 0||$.parts.length===0)return!1;for(let W of $.parts){if(W===void 0||Object.keys(W).length===0)return!1;if(W.text!==void 0&&W.text==="")return!1}return!0}var QZ="SILENT_ERROR";class zZ{constructor(X,Y,$,W={}){if(this.model=Y,this.params=$,this._requestOptions=W,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=X,$===null||$===void 0?void 0:$.history)nG($.history),this._history=$.history}async getHistory(){return await this._sendPromise,this._history}async sendMessage(X,Y={}){var $,W,Z,Q,J,G;await this._sendPromise;let z=e7(X),B={safetySettings:($=this.params)===null||$===void 0?void 0:$.safetySettings,generationConfig:(W=this.params)===null||W===void 0?void 0:W.generationConfig,tools:(Z=this.params)===null||Z===void 0?void 0:Z.tools,toolConfig:(Q=this.params)===null||Q===void 0?void 0:Q.toolConfig,systemInstruction:(J=this.params)===null||J===void 0?void 0:J.systemInstruction,cachedContent:(G=this.params)===null||G===void 0?void 0:G.cachedContent,contents:[...this._history,z]},H=Object.assign(Object.assign({},this._requestOptions),Y),V;return this._sendPromise=this._sendPromise.then(()=>KZ(this._apiKey,this.model,B,H)).then((K)=>{var U;if(ZZ(K.response)){this._history.push(z);let E=Object.assign({parts:[],role:"model"},(U=K.response.candidates)===null||U===void 0?void 0:U[0].content);this._history.push(E)}else{let E=R0(K.response);if(E)console.warn(`sendMessage() was unsuccessful. ${E}. Inspect response object for details.`)}V=K}).catch((K)=>{throw this._sendPromise=Promise.resolve(),K}),await this._sendPromise,V}async sendMessageStream(X,Y={}){var $,W,Z,Q,J,G;await this._sendPromise;let z=e7(X),B={safetySettings:($=this.params)===null||$===void 0?void 0:$.safetySettings,generationConfig:(W=this.params)===null||W===void 0?void 0:W.generationConfig,tools:(Z=this.params)===null||Z===void 0?void 0:Z.tools,toolConfig:(Q=this.params)===null||Q===void 0?void 0:Q.toolConfig,systemInstruction:(J=this.params)===null||J===void 0?void 0:J.systemInstruction,cachedContent:(G=this.params)===null||G===void 0?void 0:G.cachedContent,contents:[...this._history,z]},H=Object.assign(Object.assign({},this._requestOptions),Y),V=GZ(this._apiKey,this.model,B,H);return this._sendPromise=this._sendPromise.then(()=>V).catch((K)=>{throw Error(QZ)}).then((K)=>K.response).then((K)=>{if(ZZ(K)){this._history.push(z);let U=Object.assign({},K.candidates[0].content);if(!U.role)U.role="model";this._history.push(U)}else{let U=R0(K);if(U)console.warn(`sendMessageStream() was unsuccessful. ${U}. Inspect response object for details.`)}}).catch((K)=>{if(K.message!==QZ)console.error(K)}),V}}async function rG(X,Y,$,W){return(await XY(Y,Q8.COUNT_TOKENS,X,!1,JSON.stringify($),W)).json()}async function aG(X,Y,$,W){return(await XY(Y,Q8.EMBED_CONTENT,X,!1,JSON.stringify($),W)).json()}async function tG(X,Y,$,W){let Z=$.requests.map((J)=>{return Object.assign(Object.assign({},J),{model:Y})});return(await XY(Y,Q8.BATCH_EMBED_CONTENTS,X,!1,JSON.stringify({requests:Z}),W)).json()}class x6{constructor(X,Y,$={}){if(this.apiKey=X,this._requestOptions=$,Y.model.includes("/"))this.model=Y.model;else this.model=`models/${Y.model}`;this.generationConfig=Y.generationConfig||{},this.safetySettings=Y.safetySettings||[],this.tools=Y.tools,this.toolConfig=Y.toolConfig,this.systemInstruction=VZ(Y.systemInstruction),this.cachedContent=Y.cachedContent}async generateContent(X,Y={}){var $;let W=$Z(X),Z=Object.assign(Object.assign({},this._requestOptions),Y);return KZ(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:($=this.cachedContent)===null||$===void 0?void 0:$.name},W),Z)}async generateContentStream(X,Y={}){var $;let W=$Z(X),Z=Object.assign(Object.assign({},this._requestOptions),Y);return GZ(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:($=this.cachedContent)===null||$===void 0?void 0:$.name},W),Z)}startChat(X){var Y;return new zZ(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(Y=this.cachedContent)===null||Y===void 0?void 0:Y.name},X),this._requestOptions)}async countTokens(X,Y={}){let $=pG(X,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),W=Object.assign(Object.assign({},this._requestOptions),Y);return rG(this.apiKey,this.model,$,W)}async embedContent(X,Y={}){let $=lG(X),W=Object.assign(Object.assign({},this._requestOptions),Y);return aG(this.apiKey,this.model,$,W)}async batchEmbedContents(X,Y={}){let $=Object.assign(Object.assign({},this._requestOptions),Y);return tG(this.apiKey,this.model,X,$)}}class YY{constructor(X){this.apiKey=X}getGenerativeModel(X,Y){if(!X.model)throw new ZX("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new x6(this.apiKey,X,Y)}getGenerativeModelFromCachedContent(X,Y,$){if(!X.name)throw new Z0("Cached content must contain a `name` field.");if(!X.model)throw new Z0("Cached content must contain a `model` field.");let W=["model","systemInstruction"];for(let Q of W)if((Y===null||Y===void 0?void 0:Y[Q])&&X[Q]&&(Y===null||Y===void 0?void 0:Y[Q])!==X[Q]){if(Q==="model"){let J=Y.model.startsWith("models/")?Y.model.replace("models/",""):Y.model,G=X.model.startsWith("models/")?X.model.replace("models/",""):X.model;if(J===G)continue}throw new Z0(`Different value for "${Q}" specified in modelParams (${Y[Q]}) and cachedContent (${X[Q]})`)}let Z=Object.assign(Object.assign({},Y),{model:X.model,tools:X.tools,toolConfig:X.toolConfig,systemInstruction:X.systemInstruction,cachedContent:X});return new x6(this.apiKey,Z,$)}}function T6(X,Y){let $=sG(X);return{tools:$,toolConfig:eG($,Y)}}function sG(X){let Y=[],$=[];if(X.forEach((W)=>{if(hX(W)){let[Z]=cW([W]);if(Z.functionDeclarations)Y.push(...Z.functionDeclarations)}else if(aX(W)){let{functionDeclarations:Z}=oG(W);if(Z)Y.push(...Z);else throw Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else $.push(W)}),$.find((W)=>("functionDeclarations"in W)))return $.map((W)=>{if(Y?.length>0&&"functionDeclarations"in W){let Z={functionDeclarations:[...W.functionDeclarations||[],...Y]};return Y=[],Z}return W});return[...$,...Y.length>0?[{functionDeclarations:Y}]:[]]}function oG(X){return{functionDeclarations:[{name:X.function.name,description:X.function.description,parameters:W0(X.function.parameters)}]}}function eG(X,Y){if(!X.length||!Y)return;let{toolChoice:$,allowedFunctionNames:W}=Y,Z={any:Z8.ANY,auto:Z8.AUTO,none:Z8.NONE};if($&&["any","auto","none"].includes($))return{functionCallingConfig:{mode:Z[$]??"MODE_UNSPECIFIED",allowedFunctionNames:W}};if(typeof $==="string"||W)return{functionCallingConfig:{mode:Z8.ANY,allowedFunctionNames:[...W??[],...$&&typeof $==="string"?[$]:[]]}}}var HZ={"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 A6=class extends k8{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(X){super(X);if(this.model=X.model.replace(/^models\//,""),this.maxOutputTokens=X.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw Error("`maxOutputTokens` must be a positive integer");if(this.temperature=X.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=X.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=X.topK??this.topK,this.topK&&this.topK<0)throw Error("`topK` must be a positive integer");if(this.stopSequences=X.stopSequences??this.stopSequences,this.apiKey=X.apiKey??BX("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=X.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0){if(new Set(this.safetySettings.map((Y)=>Y.category)).size!==this.safetySettings.length)throw Error("The categories in `safetySettings` array must be unique")}this.streaming=X.streaming??this.streaming,this.json=X.json,this.thinkingConfig=X.thinkingConfig??this.thinkingConfig,this.client=new YY(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:X.apiVersion,baseUrl:X.baseUrl,customHeaders:X.customHeaders}),this.streamUsage=X.streamUsage??this.streamUsage}useCachedContent(X,Y,$){if(!this.apiKey)return;this.client=new YY(this.apiKey).getGenerativeModelFromCachedContent(X,Y,$)}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(X){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:X.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(X,Y){return this.withConfig({tools:T6(X)?.tools,...Y})}invocationParams(X){let Y=X?.tools?.length?T6(X.tools,{toolChoice:X.tool_choice,allowedFunctionNames:X.allowedFunctionNames}):void 0;if(X?.responseSchema)this.client.generationConfig.responseSchema=X.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{...Y?.tools?{tools:Y.tools}:{},...Y?.toolConfig?{toolConfig:Y.toolConfig}:{}}}async _generate(X,Y,$){Y.signal?.throwIfAborted();let W=F6(X,this._isMultimodalModel,this.useSystemInstruction,this.model),Z=W;if(W[0].role==="system"){let[B]=W;this.client.systemInstruction=B,Z=W.slice(1)}let Q=this.invocationParams(Y);if(this.streaming){let B={},H=this._streamResponseChunks(X,Y,$),V=[];for await(let K of H){let U=K.generationInfo?.completion??0;if(V[U]===void 0)V[U]=K;else V[U]=V[U].concat(K)}return{generations:V.filter((K)=>K!==void 0),llmOutput:{estimatedTokenUsage:B}}}let J=await this.completionWithRetry({...Q,contents:Z}),G;if("usageMetadata"in J.response)G=L6(J.response.usageMetadata,this.model);let z=dW(J.response,{usageMetadata:G});if(z.generations?.length>0)await $?.handleLLMNewToken(z.generations[0]?.text??"");return z}async*_streamResponseChunks(X,Y,$){let W=F6(X,this._isMultimodalModel,this.useSystemInstruction,this.model),Z=W;if(W[0].role==="system"){let[K]=W;this.client.systemInstruction=K,Z=W.slice(1)}let Q={...this.invocationParams(Y),contents:Z},J=await this.caller.callWithOptions({signal:Y?.signal},async()=>{let{stream:K}=await this.client.generateContentStream(Q,{signal:Y?.signal});return K}),G,z=0,B=0,H=0,V=0;for await(let K of J){if(Y.signal?.aborted)return;if("usageMetadata"in K&&K.usageMetadata!==void 0&&this.streamUsage!==!1&&Y.streamUsage!==!1){G=L6(K.usageMetadata,this.model);let E=K.usageMetadata.promptTokenCount??0;G.input_tokens=Math.max(0,E-z),z=E;let I=K.usageMetadata.candidatesTokenCount??0;G.output_tokens=Math.max(0,I-B),B=I;let T=K.usageMetadata.totalTokenCount??0;G.total_tokens=Math.max(0,T-H),H=T}let U=mW(K,{usageMetadata:G,index:V});if(V+=1,!U)continue;yield U,await $?.handleLLMNewToken(U.text??"")}}async completionWithRetry(X,Y){return this.caller.callWithOptions({signal:Y?.signal},async()=>{try{return await this.client.generateContent(X,{signal:Y?.signal})}catch($){if($.message?.includes("400 Bad Request"))$.status=400;throw $}})}get profile(){return HZ[this.model]??{}}withStructuredOutput(X,Y){let $=X,W=Y?.name,Z=Y?.method,Q=Y?.includeRaw;if(Z==="jsonMode")throw Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let J,G;if(Z==="functionCalling"){let V=W??"extract",K;if(HX($)){let U=t7($);K=[{functionDeclarations:[{name:V,description:U.description??"A function available to call.",parameters:U}]}],G=new E6({returnSingle:!0,keyName:V,zodSchema:$})}else{let U;if(typeof $.name==="string"&&typeof $.parameters==="object"&&$.parameters!=null)U=$,U.parameters=W0($.parameters),V=$.name;else U={name:V,description:$.description??"",parameters:W0($)};K=[{functionDeclarations:[U]}],G=new E6({returnSingle:!0,keyName:V})}J=this.bindTools(K).withConfig({allowedFunctionNames:[V]})}else{let V=t7($);J=this.withConfig({responseSchema:V}),G=new Q7}if(!Q)return J.pipe(G).withConfig({runName:"ChatGoogleGenerativeAIStructuredOutput"});let z=y8.assign({parsed:(V,K)=>G.invoke(V.raw,K)}),B=y8.assign({parsed:()=>null}),H=z.withFallbacks({fallbacks:[B]});return uY.from([{raw:J},H]).withConfig({runName:"StructuredOutputRunnable"})}};var BZ=async(X,Y={})=>{let{modelProvider:$,enableThinking:W=!0,streaming:Z=!1}=Y,Q="v1",J;if($==="anthropic")J=new U6({model:X,streamUsage:!0,streaming:Z,maxRetries:1,maxTokens:64000,thinking:W?{budget_tokens:1024,type:"enabled"}:void 0,apiKey:Y.apiKey,anthropicApiUrl:Y.baseURL,metadata:Y.metadata,outputVersion:"v1"});else if($==="gemini"||$==="google")J=new A6({model:X,apiKey:Y.apiKey,baseUrl:Y.baseURL||process.env.GOOGLE_BASE_URL,maxRetries:1,streaming:Z,streamUsage:!0,thinkingConfig:{},metadata:Y.metadata,outputVersion:"v1"});else J=new J7({model:X,configuration:{baseURL:Y.baseURL,apiKey:Y.apiKey},streamUsage:!0,streaming:Z,maxRetries:1,modelKwargs:W?{thinking:{type:"enabled"}}:void 0,metadata:Y.metadata,outputVersion:"v1"});return J};async function NZ(X){return`
|
|
105
|
+
## 环境信息
|
|
106
|
+
工作目录: ${process.cwd()}
|
|
107
|
+
平台: ${process.platform}
|
|
108
|
+
日期: ${new Date().toLocaleDateString()}
|
|
109
|
+
`}var XK=30000;class EZ{agentCache=new Map;modelCache=new Map;providerCache=new Map;providerKeyCache=new Map;get(X,Y){let $=X.get(Y);if($&&Date.now()<$.expiresAt)return $.data;return X.delete(Y),null}set(X,Y,$){X.set(Y,{data:$,expiresAt:Date.now()+XK})}getAgent=(X)=>this.get(this.agentCache,X);setAgent=(X,Y)=>this.set(this.agentCache,X,Y);getModel=(X)=>this.get(this.modelCache,X);setModel=(X,Y)=>this.set(this.modelCache,X,Y);getProvider=(X)=>this.get(this.providerCache,X);setProvider=(X,Y)=>this.set(this.providerCache,X,Y);getProviderKey=(X)=>this.get(this.providerKeyCache,X);setProviderKey=(X,Y)=>this.set(this.providerKeyCache,X,Y);clear(){this.agentCache.clear(),this.modelCache.clear(),this.providerCache.clear(),this.providerKeyCache.clear()}}var UZ=new EZ;async function YK(X,Y,$,W){let{pkg:Z,providerResolver:Q,modelResolver:J,initModel:G,stateSchema:z,enhanceSystemPrompt:B,excludeMiddleware:H=[],yoloMode:V}=$,K=!!W?.parent_id,U=UZ.getAgent(X);if(!U){if(U=await Z.getAgent(X),!U)throw Error(`Agent not found: ${X}`);UZ.setAgent(X,U)}let E=await Z.validateAgent(X);if(!E.valid)throw Error(`Agent validation failed: ${JSON.stringify(E.errors)}`);let I=Y.model_id||U.modelId;if(!I)throw Error(`Agent "${X}" has no model configured and no model_id was provided in state. Please assign a default model to this agent in the settings.`);let T=null;if(J)T=await J.resolve(I);else{let m=await Z.getModel(I);if(m)T={id:m.id,model_name:m.model_name,provider_id:m.provider_id,temperature:m.temperature,enable_thinking:m.enable_thinking,stream_usage:m.stream_usage,max_tokens:m.max_tokens}}if(!T)T={id:I,model_name:I};let S=null;if(Y.provider_id&&Q)S=await Q.resolve(Y.provider_id);else if(T.provider_id&&Q)S=await Q.resolve(T.provider_id);else if(Q)S=await Q.resolveByModel(I);let P={streamUsage:T.stream_usage??!0,enableThinking:T.enable_thinking??Y.enable_thinking??!0,streaming:Y.streaming??!1,metadata:{agent_id:X,model_id:T.id,provider_id:S?.id||Y.provider_id,parent_id:W?.parent_id}};if(S)P.modelProvider=S.type,P.apiKey=S.apiKey,P.baseURL=S.baseUrl,P.temperature=T.temperature??Y.temperature??0.7;else P.modelProvider=Y.provider_type||"openai",P.temperature=Y.temperature??T.temperature??0.7;let h=await G(T.model_name,P),f=await Z.getPromptWithContent(U.systemPromptId);if(!f)throw Error(`Prompt not found: ${U.systemPromptId}`);let e=f.content;if(B)e=await B(e,Y);let b=[];for(let[m,k]of Object.entries(U.middlewares)){if(m==="subagents"&&K)continue;if(H.includes(m))continue;if(!k)continue;if(typeof k==="object"&&"enabled"in k&&!k.enabled)continue;let TX=Z.middlewares.getImplementation(m);if(!TX){console.warn(`Middleware ${m} not found in registry`);continue}let $Y=typeof k==="boolean"?{}:k.customParams||{};b.push(await TX.execute($Y))}let g={ask_user_questions:{allowedDecisions:["respond","approve","reject","edit"]}};if(V)g.terminal={allowedDecisions:["approve","reject","edit"]};if(b.push(LZ({interruptOn:g})),(S?.type||Y.provider_type)==="anthropic"||process.env.MODEL_PROVIDER==="anthropic")b.push(FZ());return qZ({name:K?`subagent_${W.parent_id}`:U.name,model:h,systemPrompt:e,stateSchema:z,middleware:b})}async function pI(X){return(await X.listAgents()).map(($)=>$.id)}async function lI(X,Y,$,W,Z){return YK(X,$,{pkg:Y,stateSchema:wZ,initModel:async(Q,J)=>{return BZ(Q,J)},enhanceSystemPrompt:async(Q,J)=>{return Q+`
|
|
110
|
+
|
|
111
|
+
${await NZ(J)}`},yoloMode:process.env.YOLO_MODE!=="true"},Z)}
|
|
112
|
+
export{OK as mf,R as nf,YY as of,BZ as pf,NZ as qf,YK as rf,pI as sf,lI as tf};
|