gitnexus 1.6.12-rc.21 → 1.6.12-rc.22
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.
|
@@ -182,18 +182,18 @@ Here are the output tags:
|
|
|
182
182
|
`)}var dM=C({EventStreamContentType:()=>fM,convertEventStreamToIterableReadableDataStream:()=>vM,getBytes:()=>pM,getLines:()=>mM,getMessages:()=>hM}),fM=`text/event-stream`;async function pM(e,t){if(e instanceof ReadableStream){let n=e.getReader();for(;;){let e=await n.read();if(e.done){t(new Uint8Array,!0);break}t(e.value)}}else try{for await(let n of e)t(new Uint8Array(n));t(new Uint8Array,!0)}catch(e){throw Error([`Parsing event source stream failed.`,`Ensure your implementation of fetch returns a web or Node readable stream.`,`Error: ${e.message}`].join(`
|
|
183
183
|
`))}}function mM(e){let t,n,r,i=!1;return function(a,o){if(o){e(a,0,!0);return}t===void 0?(t=a,n=0,r=-1):t=gM(t,a);let s=t.length,c=0;for(;n<s;){i&&=(t[n]===10&&(c=++n),!1);let a=-1;for(;n<s&&a===-1;++n)switch(t[n]){case 58:r===-1&&(r=n-c);break;case 13:i=!0;case 10:a=n;break}if(a===-1)break;e(t.subarray(c,a),r),c=n,r=-1}c===s?t=void 0:c!==0&&(t=t.subarray(c),n-=c)}}function hM(e,t,n){let r=_M(),i=new TextDecoder;return function(a,o,s){if(s){yM(r)||(e?.(r),r=_M());return}if(a.length===0)e?.(r),r=_M();else if(o>0){let e=i.decode(a.subarray(0,o)),s=o+(a[o+1]===32?2:1),c=i.decode(a.subarray(s));switch(e){case`data`:r.data=r.data?r.data+`
|
|
184
184
|
`+c:c;break;case`event`:r.event=c;break;case`id`:t?.(r.id=c);break;case`retry`:{let e=parseInt(c,10);Number.isNaN(e)||n?.(r.retry=e);break}}}}}function gM(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function _M(){return{data:``,event:``,id:``,retry:void 0}}function vM(e,t){let n=new ReadableStream({async start(n){let r=hM(e=>{if(e.event===`error`)throw Error(e.data??`Unspecified event streaming error.`);e.event===`metadata`?t?.(e):e.data&&n.enqueue(e.data)});await pM(e,mM((e,t,i)=>{r(e,t,i),i&&n.close()}))}});return Fu.fromReadableStream(n)}function yM(e){return e.data===``&&e.event===``&&e.id===``&&e.retry===void 0}var bM=C({}),xM=C({convertToOpenAIFunction:()=>SM,convertToOpenAITool:()=>CM,isLangChainTool:()=>eA,isRunnableToolLike:()=>Qk,isStructuredTool:()=>Zk,isStructuredToolParams:()=>$k});function SM(e,t){let n=typeof t==`number`?void 0:t;return{name:e.name,description:e.description,parameters:Rx(e.schema),...n?.strict===void 0?{}:{strict:n.strict}}}function CM(e,t){let n=typeof t==`number`?void 0:t,r;return r=eA(e)?{type:`function`,function:SM(e)}:e,n?.strict!==void 0&&(r.function.strict=n.strict),r}var wM=C({DEFAULT_LANGSMITH_GATEWAY:()=>OM,resolveLangSmithGatewayConfig:()=>MM}),TM=`LANGSMITH_GATEWAY`,EM=`LANGSMITH_GATEWAY_API_KEY`,DM=`LANGSMITH_API_KEY`,OM=`https://gateway.smith.langchain.com`,kM=[`true`,`1`,`yes`],AM=[`false`,`0`,`no`];function jM(e){let t=ui(TM);if(!(!t||AM.includes(t.toLowerCase())))return`${kM.includes(t.toLowerCase())?OM:t.replace(/\/+$/,``)}/${e}`}function MM({baseURL:e,providerPath:t}){if(e!==void 0)return{baseURL:e};let n=jM(t);return n===void 0?{}:{baseURL:n,apiKey:ui(EM)||ui(DM)}}function NM(e,t){let n=0,r=0,i=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],i+=t[a]*t[a];return n/(Math.sqrt(r)*Math.sqrt(i))}function PM(e,t){let n=0;for(let r=0;r<e.length;r++)n+=e[r]*t[r];return n}function FM(e,t){let n=0;for(let r=0;r<e.length;r++)n+=(e[r]-t[r])*(e[r]-t[r]);return n}function IM(e,t){return Math.sqrt(FM(e,t))}var LM=C({cosineSimilarity:()=>BM,euclideanDistance:()=>HM,innerProduct:()=>VM,matrixFunc:()=>RM,maximalMarginalRelevance:()=>UM,normalize:()=>zM});function RM(e,t,n){if(e.length===0||e[0].length===0||t.length===0||t[0].length===0)return[[]];if(e[0].length!==t[0].length)throw Error(`Number of columns in X and Y must be the same. X has shape ${[e.length,e[0].length]} and Y has shape ${[t.length,t[0].length]}.`);return e.map(e=>t.map(t=>n(e,t)).map(e=>Number.isNaN(e)?0:e))}function zM(e,t=!1){let n=GM(e);return e.map(e=>e.map(e=>t?1-e/n:e/n))}function BM(e,t){return RM(e,t,NM)}function VM(e,t){return RM(e,t,PM)}function HM(e,t){return RM(e,t,IM)}function UM(e,t,n=.5,r=4){if(Math.min(r,t.length)<=0)return[];let i=BM(Array.isArray(e[0])?e:[e],t)[0],a=WM(i).maxIndex,o=[t[a]],s=[a];for(;s.length<Math.min(r,t.length);){let e=-1/0,r=-1,a=BM(t,o);i.forEach((t,i)=>{if(s.includes(i))return;let o=Math.max(...a[i]),c=n*t-(1-n)*o;c>e&&(e=c,r=i)}),o.push(t[r]),s.push(r)}return s}function WM(e){if(e.length===0)return{maxIndex:-1,maxValue:NaN};let t=e[0],n=0;for(let r=1;r<e.length;r+=1)e[r]>t&&(n=r,t=e[r]);return{maxIndex:n,maxValue:t}}function GM(e){return e.reduce((e,t)=>Math.max(e,WM(t).maxValue),0)}var KM=C({isCloudMetadata:()=>oN,isLocalhost:()=>sN,isPrivateIp:()=>aN,isSafeUrl:()=>lN,isSameOrigin:()=>uN,validateSafeUrl:()=>cN}),qM=[`10.0.0.0/8`,`172.16.0.0/12`,`192.168.0.0/16`,`127.0.0.0/8`,`169.254.0.0/16`,`0.0.0.0/8`,`::1/128`,`fc00::/7`,`fe80::/10`,`ff00::/8`],JM=[`169.254.169.254`,`169.254.170.2`,`100.100.100.200`],YM=[`metadata.google.internal`,`metadata`,`instance-data`],XM=[`localhost`,`localhost.localdomain`],ZM=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function QM(e){return ZM.test(e)}function $M(e){return nN(e)!==null}function eN(e){return QM(e)||$M(e)}function tN(e){if(QM(e))return e.split(`.`).map(e=>parseInt(e,10));if($M(e)){let t=nN(e);if(!t)return null;let n=t.split(`:`),r=[];for(let e of n)r.push(parseInt(e,16));return r}return null}function nN(e){if(!e||typeof e!=`string`||!e.includes(`:`)||!/^[0-9a-fA-F:]+$/.test(e))return null;let t=e;if(t.includes(`::`)){let e=t.split(`::`);if(e.length>2)return null;let[n,r]=e,i=n?n.split(`:`):[],a=r?r.split(`:`):[],o=8-(i.length+a.length);if(o<0)return null;let s=Array(o).fill(`0`);t=[...i,...s,...a].filter(e=>e!==``).join(`:`)}let n=t.split(`:`);if(n.length!==8)return null;for(let e of n)if(e.length===0||e.length>4||!/^[0-9a-fA-F]+$/.test(e))return null;return n.map(e=>e.padStart(4,`0`).toLowerCase()).join(`:`)}function rN(e){let[t,n]=e.split(`/`);if(!t||!n)return null;let r=tN(t);if(!r)return null;let i=parseInt(n,10);if(isNaN(i))return null;let a=$M(t);return a&&i>128||!a&&i>32?null:{addr:r,prefixLen:i,isIpv6:a}}function iN(e,t){let n=tN(e);if(!n)return!1;let r=rN(t);if(!r)return!1;let i=$M(e);if(i!==r.isIpv6)return!1;let{addr:a,prefixLen:o}=r;if(i)for(let e=0;e<Math.ceil(o/16);e++){let t=65535<<16-Math.min(16,o-e*16)&65535;if((n[e]&t)!==(a[e]&t))return!1}else for(let e=0;e<Math.ceil(o/8);e++){let t=255<<8-Math.min(8,o-e*8)&255;if((n[e]&t)!==(a[e]&t))return!1}return!0}function aN(e){if(!eN(e))return!1;for(let t of qM)if(iN(e,t))return!0;return!1}function oN(e,t){if(JM.includes(t||``))return!0;let n=e.toLowerCase();return!!YM.includes(n)}function sN(e,t){if(t&&(t===`127.0.0.1`||t===`::1`||t===`0.0.0.0`||t.startsWith(`127.`)))return!0;let n=e.toLowerCase();return!!XM.includes(n)}function cN(e,t){let n=t?.allowPrivate??!1,r=t?.allowHttp??!1;try{let t;try{t=new URL(e)}catch{throw Error(`Invalid URL: ${e}`)}let i=t.hostname;if(!i)throw Error(`URL missing hostname.`);if(oN(i))throw Error(`URL points to cloud metadata endpoint: ${i}`);if(sN(i)){if(!n)throw Error(`URL points to localhost: ${i}`);return e}let a=t.protocol;if(a!==`http:`&&a!==`https:`)throw Error(`Invalid URL scheme: ${a}. Only http and https are allowed.`);if(a===`http:`&&!r)throw Error(`HTTP scheme not allowed. Use HTTPS or set allowHttp: true.`);if(eN(i)){let t=i;if(sN(i,t)){if(!n)throw Error(`URL points to localhost: ${i}`);return e}if(oN(i,t))throw Error(`URL resolves to cloud metadata IP: ${t} (${i})`);if(aN(t)&&!n)throw Error(`URL resolves to private IP: ${t} (${i}). Set allowPrivate: true to allow.`);return e}return e}catch(e){throw e&&typeof e==`object`&&`message`in e?e:Error(`URL validation failed: ${e}`)}}function lN(e,t){try{return cN(e,t),!0}catch{return!1}}function uN(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}var dN=C({SaveableVectorStore:()=>mN,VectorStore:()=>pN,VectorStoreRetriever:()=>fN}),fN=class extends WO{static lc_name(){return`VectorStoreRetriever`}get lc_namespace(){return[`langchain_core`,`vectorstores`]}vectorStore;k=4;searchType=`similarity`;searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType===`mmr`&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if(this.searchType===`mmr`){if(typeof this.vectorStore.maxMarginalRelevanceSearch!=`function`)throw Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild(`vectorstore`))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild(`vectorstore`))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},pN=class extends Ke{lc_namespace=[`langchain`,`vectorstores`,this._vectorstoreType()];embeddings;constructor(e,t){super(t),this.embeddings=e}async delete(e){throw Error(`Not implemented.`)}async similaritySearch(e,t=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)).map(e=>e[0])}async similaritySearchWithScore(e,t=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)}static fromTexts(e,t,n,r){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}static fromDocuments(e,t,n){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}asRetriever(e,t,n,r,i,a){if(typeof e==`number`)return new fN({vectorStore:this,k:e,filter:t,tags:[...r??[],this._vectorstoreType()],metadata:i,verbose:a,callbacks:n});{let t={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType===`mmr`?new fN({...t,searchKwargs:e.searchKwargs}):new fN({...t})}}},mN=class extends pN{static load(e,t){throw Error(`Not implemented`)}},hN=class extends iD{_combineLLMOutput(){return[]}_llmType(){return`fake`}async _generate(e,t,n){if(t?.stop?.length)return{generations:[{message:new An(t.stop[0]),text:t.stop[0]}]};let r=e.map(e=>typeof e.content==`string`?e.content:JSON.stringify(e.content,null,2)).join(`
|
|
185
|
-
`);return await n?.handleLLMNewToken(r),{generations:[{message:new An(r),text:r}],llmOutput:{}}}},gN=class e extends iD{sleep=50;responses=[];chunks=[];toolStyle=`openai`;thrownErrorString;tools=[];constructor({sleep:e=50,responses:t=[],chunks:n=[],toolStyle:r=`openai`,thrownErrorString:i,...a}){super(a),this.sleep=e,this.responses=t,this.chunks=n,this.toolStyle=r,this.thrownErrorString=i}_llmType(){return`fake`}bindTools(t){let n=[...this.tools,...t],r=n.map(e=>{switch(this.toolStyle){case`openai`:return{type:`function`,function:{name:e.name,description:e.description,parameters:Rx(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:Rx(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:Rx(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:Rx(e.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle===`google`?[{functionDeclarations:r}]:r,a=new e({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return a.tools=n,a.withConfig({tools:i})}async _generate(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);return{generations:[{text:``,message:new An({content:this.responses?.[0]?.content??e[0].content??``,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);if(this.chunks?.length){for(let e of this.chunks){let r=new xd({message:new Nn({content:e.content,tool_calls:e.tool_calls,additional_kwargs:e.additional_kwargs??{}}),text:e.content?.toString()??``});if(t.signal?.aborted)break;yield r,await n?.handleLLMNewToken(e.content,void 0,void 0,void 0,void 0,{chunk:r})}return}let r=this.responses?.[0]??new An(typeof e[0].content==`string`?e[0].content:``),i=typeof r.content==`string`?r.content:``;for(let e of i){await new Promise(e=>setTimeout(e,this.sleep));let r=new xd({message:new Nn({content:e}),text:e});if(t.signal?.aborted)break;yield r,await n?.handleLLMNewToken(e,void 0,void 0,void 0,void 0,{chunk:r})}}},_N=class e extends iD{static lc_name(){return`FakeListChatModel`}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle=`openai`;constructor(e){super(e);let{responses:t,sleep:n,emitCustomEvent:r,generationInfo:i}=e;this.responses=t,this.sleep=n,this.emitCustomEvent=r??this.emitCustomEvent,this.generationInfo=i}_combineLLMOutput(){return[]}_llmType(){return`fake-list`}async _generate(e,t,n){if(await this._sleepIfRequested(),t?.thrownErrorString)throw Error(t.thrownErrorString);if(this.emitCustomEvent&&await n?.handleCustomEvent(`some_test_event`,{someval:!0}),t?.stop?.length)return{generations:[this._formatGeneration(t.stop[0])]};{let e=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(e)],llmOutput:{}}}}_formatGeneration(e){return{message:new An(e),text:e}}async*_streamResponseChunks(e,t,n){let r=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await n?.handleCustomEvent(`some_test_event`,{someval:!0});let i=[...r];for(let e=0;e<i.length;e++){let r=i[e],a=e===i.length-1;if(await this._sleepIfRequested(),t?.thrownErrorString)throw Error(t.thrownErrorString);let o=this._createResponseChunk(r,a?this.generationInfo:void 0);if(t.signal?.aborted)break;yield o,n?.handleLLMNewToken(r)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(e=>{setTimeout(()=>e(),this.sleep)})}_createResponseChunk(e,t){return new xd({message:new Nn({content:e}),text:e,generationInfo:t})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(t){let n=[...this.tools,...t],r=n.map(e=>{switch(this.toolStyle){case`openai`:return{type:`function`,function:{name:e.name,description:e.description,parameters:Rx(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:Rx(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:Rx(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:Rx(e.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle===`google`?[{functionDeclarations:r}]:r,a=new e({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return a.tools=n,a.toolStyle=this.toolStyle,a.i=this.i,a.withConfig({tools:i})}withStructuredOutput(e,t){return lS.from(async e=>{let t=await this.invoke(e);if(t.tool_calls?.[0]?.args)return t.tool_calls[0].args;if(typeof t.content==`string`)return JSON.parse(t.content);throw Error(`No structured output found`)})}},vN=class extends $w{vectorSize;constructor(e){super(e??{}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map(e=>this.embedQuery(e)))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,``);let n=t.length%this.vectorSize,r=n===0?0:this.vectorSize-n,i=t.length+r;t=t.padEnd(i,` `);let a=t.length/this.vectorSize,o=[];for(let e=0;e<t.length;e+=a)o.push(t.slice(e,e+a));return o.map(e=>{let t=0;for(let n=0;n<e.length;n+=1)t+=e===` `?0:e.charCodeAt(n);return t%26/26})}},yN=class extends $w{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}},bN=class extends gD{response;thrownErrorString;constructor(e){super(e),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return`fake`}async _call(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);let r=this.response??e;return await n?.handleLLMNewToken(r),r}},xN=class extends gD{sleep=50;responses;thrownErrorString;constructor(e){super(e),this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return`fake`}async _call(e){if(this.thrownErrorString)throw Error(this.thrownErrorString);let t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);let r=this.responses?.[0];this.responses=this.responses?.slice(1);for(let t of r??e)await new Promise(e=>setTimeout(e,this.sleep)),yield{text:t,generationInfo:{}},await n?.handleLLMNewToken(t)}},SN=class extends Bw{lc_namespace=[`langchain_core`,`message`,`fake`];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new Hn(e))}async addAIMessage(e){this.messages.push(new An(e))}async clear(){this.messages=[]}},CN=class extends Vw{lc_namespace=[`langchain_core`,`message`,`fake`];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},wN=class extends wl{name=`fake_tracer`;runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}},TN=class extends XT{lc_namespace=[`tests`,`fake`];getFormatInstructions(){return``}async parse(e){return e.split(`,`).map(e=>e.trim())}},EN=class extends WO{lc_namespace=[`test`,`fake`];output=[new Uw({pageContent:`foo`}),new Uw({pageContent:`bar`})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}},DN=class extends tS{lc_namespace=[`tests`,`fake`];returnOptions;constructor(e){super(e),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}},ON=class extends qj{name;description;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,t){return JSON.stringify(e)}},kN=class extends wl{runPromiseResolver;runPromise;name=`single_run_extractor`;constructor(){super(),this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}},AN=class e extends pN{memoryVectors=[];similarity;_vectorstoreType(){return`memory`}constructor(e,{similarity:t,...n}={}){super(e,n),this.similarity=t??NM}async addDocuments(e){let t=e.map(({pageContent:e})=>e);return this.addVectors(await this.embeddings.embedDocuments(t),e)}async addVectors(e,t){let n=e.map((e,n)=>({content:t[n].pageContent,embedding:e,metadata:t[n].metadata}));this.memoryVectors=this.memoryVectors.concat(n)}async similaritySearchVectorWithScore(e,t,n){let r=this.memoryVectors.filter(e=>!n||n(new Uw({metadata:e.metadata,pageContent:e.content})));return r.map((t,n)=>({similarity:this.similarity(e,t.embedding),index:n})).sort((e,t)=>e.similarity>t.similarity?-1:0).slice(0,t).map(e=>[new Uw({metadata:r[e.index].metadata,pageContent:r[e.index].content}),e.similarity])}static async fromTexts(t,n,r,i){let a=[];for(let e=0;e<t.length;e+=1){let r=Array.isArray(n)?n[e]:n,i=new Uw({pageContent:t[e],metadata:r});a.push(i)}return e.fromDocuments(a,r,i)}static async fromDocuments(e,t,n){let r=new this(t,n);return await r.addDocuments(e),r}static async fromExistingIndex(e,t){return new this(e,t)}},jN=C({FakeChatMessageHistory:()=>SN,FakeChatModel:()=>hN,FakeEmbeddings:()=>yN,FakeLLM:()=>bN,FakeListChatMessageHistory:()=>CN,FakeListChatModel:()=>_N,FakeRetriever:()=>EN,FakeRunnable:()=>DN,FakeSplitIntoListParser:()=>TN,FakeStreamingChatModel:()=>gN,FakeStreamingLLM:()=>xN,FakeTool:()=>ON,FakeTracer:()=>wN,FakeVectorStore:()=>AN,SingleRunExtractor:()=>kN,SyntheticEmbeddings:()=>vN,asAsyncIterable:()=>Wk,openAIReasoningTextChunks:()=>qk,openAITextOnlyChunks:()=>Kk,openAITextOnlyChunksWithUsage:()=>Gk,openAIToolCallChunks:()=>Jk,sseResponseFromOpenAIChunks:()=>Yk,streamMatchers:()=>Tk}),MN=C({agents:()=>ww,caches:()=>Mw,callbacks__base:()=>di,callbacks__manager:()=>ou,callbacks__promises:()=>tu,chat_history:()=>zw,document_loaders__base:()=>qw,document_loaders__langsmith:()=>Yw,documents:()=>Kw,embeddings:()=>Qw,errors:()=>fe,example_selectors:()=>lT,index:()=>Cw,indexing:()=>vT,language_models__base:()=>zT,language_models__chat_models:()=>nD,language_models__compat:()=>UE,language_models__event:()=>pD,language_models__llms:()=>mD,language_models__openai_completions_stream:()=>oD,language_models__profile:()=>_D,language_models__stream:()=>kE,language_models__structured_output:()=>TE,load__serializable:()=>He,memory:()=>vD,messages:()=>IS,messages__tool:()=>Jt,output_parsers:()=>vE,output_parsers__openai_functions:()=>DD,output_parsers__openai_tools:()=>OD,outputs:()=>vd,prompt_values:()=>yT,prompts:()=>BO,retrievers:()=>UO,retrievers__document_compressors:()=>VO,runnables:()=>RS,runnables__graph:()=>Bx,singletons:()=>Cu,stores:()=>GO,structured_query:()=>fk,testing:()=>Xk,tools:()=>Kj,tracers__base:()=>yl,tracers__console:()=>Tl,tracers__log_stream:()=>ud,tracers__run_collector:()=>nM,tracers__tracer_langchain:()=>Vl,types__stream:()=>iM,utils__async_caller:()=>Id,utils__chunk_array:()=>aM,utils__context:()=>sM,utils__env:()=>ti,utils__event_source_parse:()=>dM,utils__format:()=>bM,utils__function_calling:()=>xM,utils__gateway:()=>wM,utils__hash:()=>jw,utils__json_patch:()=>JT,utils__json_schema:()=>Ix,utils__math:()=>LM,utils__ssrf:()=>KM,utils__standard_schema:()=>Jb,utils__stream:()=>Pu,utils__testing:()=>jN,utils__tiktoken:()=>PT,utils__types:()=>yE,utils__uuid:()=>Ur,vectorstores:()=>dN}),NN=50;function PN(e){let t={};for(let n=e;n&&n.prototype;n=Object.getPrototypeOf(n))Object.assign(t,Reflect.get(n.prototype,`lc_aliases`));return Object.entries(t).reduce((e,[t,n])=>(e[n]=t,e),{})}async function FN(e){let{optionalImportsMap:t,optionalImportEntrypoints:n,importMap:r,secretsMap:i,secretsFromEnv:a,path:o,depth:s,maxDepth:c}=this,l=o.join(`.`);if(s>c)throw Error(`Maximum recursion depth (${c}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return Promise.all(e.map((e,t)=>FN.call({...this,path:[...o,`${t}`],depth:s+1},e)));let u=e;if(Le(u))return Ve(u);if(`lc`in u&&`type`in u&&`id`in u&&u.lc===1&&u.type===`secret`){let[e]=u.id;if(e in i)return i[e];if(a){let t=ui(e);if(t)return t}throw Error(`Missing secret "${e}" at ${l}`)}if(`lc`in u&&`type`in u&&`id`in u&&u.lc===1&&u.type===`not_implemented`){let e=JSON.stringify(u);throw Error(`Trying to load an object that doesn't implement serialization: ${l} -> ${e}`)}if(`lc`in u&&`type`in u&&`id`in u&&`kwargs`in u&&u.lc===1&&u.type===`constructor`){let e=u,i=JSON.stringify(e),[a,...c]=e.id.slice().reverse(),d=c.reverse(),f={langchain_core:MN,langchain:r},p=null,m=[d.join(`/`)];d[0]===`langchain_community`&&m.push([`langchain`,...d.slice(1)].join(`/`));let h=m.find(e=>e in t);if(Sw.concat(n).includes(d.join(`/`))||h)if(h!==void 0)p=await t[h];else throw Error(`Missing key "${d.join(`/`)}" for ${l} in load(optionalImportsMap={})`);else{let e;if(d[0]===`langchain`||d[0]===`langchain_core`)e=f[d[0]],d.shift();else throw Error(`Invalid namespace: ${l} -> ${i}`);if(d.length===0)throw Error(`Invalid namespace: ${l} -> ${i}`);let t;do{if(t=d.join(`__`),t in e)break;d.pop()}while(d.length>0);t in e&&(p=e[t])}if(typeof p!=`object`||!p)throw Error(`Invalid namespace: ${l} -> ${i}`);let g=p[a]??Object.values(p).find(e=>typeof e==`function`&&Ge(e)===a);if(typeof g!=`function`)throw Error(`Invalid identifer: ${l} -> ${i}`);let _=new g(Ne(await FN.call({...this,path:[...o,`kwargs`],depth:s+1},e.kwargs),Me,PN(g)));return Object.defineProperty(_.constructor,"name",{value:a}),_}let d={};for(let[e,t]of Object.entries(u))d[e]=await FN.call({...this,path:[...o,e],depth:s+1},t);return d}async function IN(e,t){let n=JSON.parse(e),r={optionalImportsMap:t?.optionalImportsMap??{},optionalImportEntrypoints:t?.optionalImportEntrypoints??[],secretsMap:t?.secretsMap??{},secretsFromEnv:t?.secretsFromEnv??!1,importMap:t?.importMap??{},path:[`$`],depth:0,maxDepth:t?.maxDepth??NN};return FN.call(r,n)}function LN(e){return e!==null&&e.lc===1&&e.type===`constructor`&&Array.isArray(e.id)}async function RN(e){if(e&&typeof e==`object`){if(Array.isArray(e))return await Promise.all(e.map(e=>RN(e)));{let t={};for(let[n,r]of Object.entries(e))t[n]=await RN(r);if(t.lc===2&&t.type===`undefined`)return;if(t.lc===2&&t.type===`delta_snapshot`)return new dw(t.value);if(t.lc===2&&t.type===`constructor`&&Array.isArray(t.id))try{let e=t.id[t.id.length-1],n;switch(e){case`Set`:n=Set;break;case`Map`:n=Map;break;case`RegExp`:n=RegExp;break;case`Error`:n=Error;break;case`Uint8Array`:n=Uint8Array;break;default:return t}return t.method?n[t.method](...t.args||[]):new n(...t.args||[])}catch{return t}else if(LN(t))return IN(JSON.stringify(t));return t}}return e}function zN(e,t,n,r){return{lc:2,type:`constructor`,id:[e.name],method:t??null,args:n??[],kwargs:r??{}}}function BN(e){return e===void 0?{lc:2,type:`undefined`}:e instanceof dw?{lc:2,type:`delta_snapshot`,value:e.value}:e instanceof Set||e instanceof Map?zN(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?zN(RegExp,void 0,[e.source,e.flags]):e instanceof Error?zN(e.constructor,void 0,[e.message]):e?.lg_name===`Send`?{node:e.node,args:e.args,...e.timeout===void 0?{}:{timeout:e.timeout}}:e instanceof Uint8Array?zN(Uint8Array,`from`,[Array.from(e)]):e}var VN=class{_dumps(e){return new TextEncoder().encode(vw(e,(e,t)=>BN(t)))}async dumpsTyped(e){return e instanceof Uint8Array?[`bytes`,e]:[`json`,this._dumps(e)]}async _loads(e){return RN(JSON.parse(e))}async loadsTyped(e,t){if(e===`bytes`)return typeof t==`string`?new TextEncoder().encode(t):t;if(e===`json`)return this._loads(typeof t==`string`?t:new TextDecoder().decode(t));throw Error(`Unknown serialization type: ${e}`)}};function HN(e){if(typeof e!=`object`||!e)return e;let t=Array.isArray(e)?[]:{};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=HN(e[n]));return t}function UN(){return{v:4,id:aw(0),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function WN(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values??{}},channel_versions:{...e.channel_versions??{}},versions_seen:HN(e.versions_seen??{})}}function GN(e,t){return typeof e==`number`&&typeof t==`number`?Math.sign(e-t):String(e).localeCompare(String(t))}function KN(...e){return e.reduce((e,t,n)=>n===0?t:GN(e,t)>=0?e:t)}var qN={[sw]:-1,[cw]:-2,[lw]:-3,[uw]:-4},JN=new Set([`thread_id`,`checkpoint_id`,`checkpoint_ns`,`checkpoint_map`,`langgraph_step`,`langgraph_node`,`langgraph_triggers`,`langgraph_path`,`langgraph_checkpoint_ns`]),YN=class extends Error{constructor(e){super(e),this.name=`InvalidNamespaceError`}};function XN(e){if(e.length===0)throw new YN(`Namespace cannot be empty.`);for(let t of e){if(typeof t!=`string`)throw new YN(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes(`.`))throw new YN(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(t===``)throw new YN(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if(e[0]===`langgraph`)throw new YN(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var ZN=class{async get(e,t){return(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){let{filter:n,limit:r=10,offset:i=0,query:a}=t;return(await this.batch([{namespacePrefix:e,filter:n,limit:r,offset:i,query:a}]))[0]}async put(e,t,n,r){XN(e),await this.batch([{namespace:e,key:t,value:n,index:r}])}async delete(e,t){await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){let{prefix:t,suffix:n,maxDepth:r,limit:i=100,offset:a=0}=e,o=[];return t&&o.push({matchType:`prefix`,path:t}),n&&o.push({matchType:`suffix`,path:n}),(await this.batch([{matchConditions:o.length?o:void 0,maxDepth:r,limit:i,offset:a}]))[0]}start(){}stop(){}},QN=e=>`lg_name`in e&&e.lg_name===`AsyncBatchedStore`?e.store:e,$N=class extends ZN{lg_name=`AsyncBatchedStore`;store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=QN(e)}get isRunning(){return this.running}async batch(e){throw Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){let{filter:n,limit:r=10,offset:i=0,query:a}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:n,limit:r,offset:i,query:a})}async put(e,t,n){return this.enqueueOperation({namespace:e,key:t,value:n})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((t,n)=>{let r=this.nextKey;this.nextKey+=1,this.queue.set(r,{operation:e,resolve:t,reject:n})})}async processBatchQueue(){for(;this.running;){if(await new Promise(e=>{setTimeout(e,0)}),this.queue.size===0)continue;let e=new Map(this.queue);this.queue.clear();try{let t=Array.from(e.values()).map(({operation:e})=>e),n=await this.store.batch(t);e.forEach(({resolve:t},r)=>{t(n[Array.from(e.keys()).indexOf(r)])})}catch(t){e.forEach(({reject:e})=>{e(t)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:`[LangGraphStore]`}}},eP=class{serde=new VN;constructor(e){this.serde=e||this.serde}},tP=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function nP(e){return e!=null&&e.lc_graph_name===`DeltaChannel`}function rP(e){return e!=null&&e.lg_is_channel===!0}var iP=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===$C.unminifiable_name)return!1;throw e}}equals(e){return this===e}},aP=Symbol.for(`LG_IS_ONLY_BASE_CHANNEL`);function oP(e){if(e[aP]===!0)return e;let t={};for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let r=e[n];rP(r)&&(t[n]=r)}return Object.assign(t,{[aP]:!0}),t}function sP(e,t){let n=oP(e),r={};for(let e in n){if(!Object.prototype.hasOwnProperty.call(n,e))continue;let i=t.channel_values[e];r[e]=n[e].fromCheckpoint(i)}return Object.assign(r,{[aP]:!0}),r}function cP(e,t){if(!tP.test(t))throw TypeError(`Invalid task id for exit delta: ${t}`);let n=t.toLowerCase().split(`-`);return`${String(e).padStart(8,`0`)}-${n[1]}-${n[2]}-${n[3]}-${n[4]}`}function lP(e,t){let n=new Set,r=qS();for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let a=e[i];if(!nP(a)||!a.isAvailable())continue;let[o,s]=t[i]??[0,0];(o>=a.snapshotFrequency||s>=r)&&n.add(i)}return n}function uP(e,t,n,r){let i=r?.channelsToSnapshot??new Set,{updatedChannels:a,getNextVersion:o}=r??{},s,c=e.channel_versions;if(t===void 0)s=e.channel_values;else{s={},c={...e.channel_versions};for(let e in t){if(!Object.prototype.hasOwnProperty.call(t,e))continue;let n=t[e];if(i.has(e)){o!==void 0&&(a===void 0||!a.has(e))&&(c[e]=o(c[e])),s[e]=new dw(n.get());continue}if(!nP(n))try{s[e]=n.checkpoint()}catch(e){if(e.name!==$C.unminifiable_name)throw e}}}return{v:4,id:r?.id??aw(n),ts:new Date().toISOString(),channel_values:s,channel_versions:c,versions_seen:e.versions_seen}}async function dP(e,t,n){let r=sP(e,t),{saver:i,config:a}=n??{},o=oP(e),s=[];for(let e in o)Object.prototype.hasOwnProperty.call(o,e)&&nP(o[e])&&!Object.prototype.hasOwnProperty.call(t.channel_values,e)&&s.push(e);if(s.length===0||i===void 0||a===void 0)return r;let c=await i.getDeltaChannelHistory({config:a,channels:s});for(let e of s){let t=c[e];if(t===void 0)continue;let n=o[e].fromCheckpoint(t.seed);n.replayWrites(t.writes),r[e]=n}return r}var fP=class e extends iP{lc_graph_name=`LastValue`;value=[];constructor(e){super(),this.initialValueFactory=e,e&&(this.value=[e()])}fromCheckpoint(t){let n=new e(this.initialValueFactory);return t!==void 0&&(n.value=[t]),n}update(e){if(e.length===0)return!1;if(e.length!==1)throw new ew(`LastValue can only receive one value per step.`,{lc_error_code:`INVALID_CONCURRENT_GRAPH_UPDATE`});return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new $C;return this.value[0]}checkpoint(){if(this.value.length===0)throw new $C;return this.value[0]}isAvailable(){return this.value.length!==0}},pP=class e extends iP{lc_graph_name=`LastValueAfterFinish`;value=[];finished=!1;fromCheckpoint(t){let n=new e;if(t!==void 0){let[e,r]=t;n.value=[e],n.finished=r}return n}update(e){return e.length===0?!1:(this.finished=!1,this.value=[e[e.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new $C;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}},mP=e=>e!=null&&e.lc_graph_name===`BinaryOperatorAggregate`,hP=class e extends iP{lc_graph_name=`BinaryOperatorAggregate`;value;operator;initialValueFactory;constructor(e,t){super(),this.operator=e,this.initialValueFactory=t,this.value=t?.()}fromCheckpoint(t){let n=new e(this.operator,this.initialValueFactory);return t!==void 0&&(n.value=t),n}update(e){let t=e;if(!t.length)return!1;if(this.value===void 0){let e=t[0],[n,r]=jC(e);n?this.value=r:this.value=e,t=t.slice(1)}let n=!1;for(let e of t)if(MC(e)){if(n)throw new ew(`Can receive only one Overwrite value per step.`);let[,t]=jC(e);this.value=t,n=!0;continue}else!n&&this.value!==void 0&&(this.value=this.operator(this.value,e));return!0}get(){if(this.value===void 0)throw new $C;return this.value}checkpoint(){if(this.value===void 0)throw new $C;return this.value}isAvailable(){return this.value!==void 0}equals(e){return this===e?!0:mP(e)?this.operator===e.operator:!1}},gP=class{lc_graph_name=`AnnotationRoot`;spec;constructor(e){this.spec=e}static isInstance(e){return typeof e==`object`&&!!e&&`lc_graph_name`in e&&e.lc_graph_name===`AnnotationRoot`}},_P=function(e){return e?vP(e):new fP};_P.Root=e=>new gP(e);function vP(e){return typeof e==`object`&&e&&`reducer`in e&&e.reducer?new hP(e.reducer,e.default):typeof e==`object`&&e&&`value`in e&&e.value?new hP(e.value,e.default):new fP}var yP=[`tags`,`metadata`,`callbacks`,`configurable`],bP=[`tags`,`metadata`,`callbacks`,`runName`,`maxConcurrency`,`recursionLimit`,`configurable`,`runId`,`outputKeys`,`streamMode`,`store`,`writer`,`interrupt`,`context`,`interruptBefore`,`interruptAfter`,`checkpointDuring`,`durability`,`signal`,`heartbeat`,`executionInfo`,`serverInfo`,`control`],xP=25,SP=new Set([`thread_id`,`checkpoint_id`,`checkpoint_ns`,`task_id`,`run_id`,`assistant_id`,`graph_id`]);function CP(e,t){if(!e)return t;let n=t??{};for(let t of SP){if(t in n)continue;let r=e[t];r!==void 0&&(n[t]=r)}return n}function wP(e){if(e==null||e.length===0)return;let t=e.filter(e=>!e.startsWith(`seq:step`));return t.length>0?t:void 0}function TP(e,t){if(t===void 0)return e;if(e===void 0)return Array.isArray(t)?[...t]:t.copy();if(Array.isArray(t)){if(Array.isArray(e))return e.concat(t);let n=e.copy();for(let e of t)n.addHandler(vu(e),!0);return n}if(Array.isArray(e)){let n=t.copy();for(let t of e)n.addHandler(vu(t),!0);return n}return new _u(t._parentRunId,{handlers:e.handlers.concat(t.handlers),inheritableHandlers:e.inheritableHandlers.concat(t.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(t.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(t.inheritableTags))),metadata:{...e.metadata,...t.metadata},inheritableMetadata:{...e.inheritableMetadata,...t.inheritableMetadata}})}function EP(e){let t;for(let n=e.length-1;n>=0;--n)if(e[n]!==void 0){t=e[n];break}let n=t?.configurable?.thread_id!==void 0,r=e.some(e=>e?.configurable?.[XS]!==void 0),i=Su.getRunnableConfig()?.configurable?.[XS]!==void 0;return n&&!r&&!i}function DP(...e){let t={tags:[],metadata:{},callbacks:void 0,recursionLimit:xP,configurable:{}},n=EP(e),r=Su.getRunnableConfig();if(r!==void 0){for(let[e,i]of Object.entries(r))if(i!==void 0){if(e===`configurable`&&n)continue;if(yP.includes(e)){let n;n=Array.isArray(i)?[...i]:typeof i==`object`?e===`callbacks`&&`copy`in i&&typeof i.copy==`function`?i.copy():{...i}:i,t[e]=n}else t[e]=i}}for(let n of e)if(n!==void 0)for(let[e,r]of Object.entries(n))r===void 0||!bP.includes(e)||(e===`configurable`?t.configurable={...t.configurable,...r}:e===`metadata`?t.metadata={...t.metadata,...r}:e===`tags`?t.tags=[...t.tags??[],...r]:e===`callbacks`?t.callbacks=TP(t.callbacks,r):t[e]=r);return t.metadata=CP(t.configurable,t.metadata)??{},t}function OP(){return Su.getRunnableConfig()}function kP(e){return e.split(`|`).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(`:`)[0]).join(`|`)}function AP(e){let t=e.split(`|`);for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join(`|`)}var jP=class extends tS{lc_namespace=[`langgraph`];func;tags;config;trace=!0;recurse=!0;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,t,n){return new Promise((r,i)=>{let a=Au(t,{callbacks:n?.getChild()});Su.runWithConfig(a,async()=>{try{r(await this.func(e,a))}catch(e){i(e)}})})}async invoke(e,t){let n,r=DP(t),i=Ou(this.config,r);return n=this.trace?await this._callWithConfig(this._tracedInvoke,e,i):await Su.runWithConfig(i,async()=>this.func(e,i)),tS.isRunnable(n)&&this.recurse?await Su.runWithConfig(i,async()=>n.invoke(e,i)):n}};function*MP(e,t){if(t===void 0)yield*e;else for(let n of e)yield[t,n]}async function NP(e){let t=[];for await(let n of await e)t.push(n);return t}function PP(e){let t=[];for(let n of e)t.push(n);return t}function FP(e,t){return e?`configurable`in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function IP(e){return typeof e==`object`&&e?.[Symbol.for(`LG_SKIP_WRITE`)]!==void 0}var LP={[Symbol.for(`LG_PASSTHROUGH`)]:!0};function RP(e){return typeof e==`object`&&e?.[Symbol.for(`LG_PASSTHROUGH`)]!==void 0}var zP=Symbol(`IS_WRITER`),BP=class e extends jP{writes;constructor(e,t){let n=`ChannelWrite<${e.map(e=>kC(e)?e.node:`channel`in e?e.channel:`...`).join(`,`)}>`;super({writes:e,name:n,tags:t,trace:!1,func:async(e,t)=>this._write(e,t??{})}),this.writes=e}async _write(t,n){let r=this.writes.map(e=>HP(e)&&RP(e.value)?{mapper:e.mapper,value:t}:VP(e)&&RP(e.value)?{channel:e.channel,value:t,skipNone:e.skipNone,mapper:e.mapper}:e);return await e.doWrite(n,r),t}static async doWrite(e,t){for(let e of t){if(VP(e)){if(e.channel===`__pregel_tasks`)throw new ew(`Cannot write to the reserved channel TASKS`);if(RP(e.value))throw new ew(`PASSTHROUGH value must be replaced`)}if(HP(e)&&RP(e.value))throw new ew(`PASSTHROUGH value must be replaced`)}let n=[];for(let r of t)if(kC(r))n.push([bC,r]);else if(HP(r)){let t=await r.mapper.invoke(r.value,e);t!=null&&t.length>0&&n.push(...t)}else if(VP(r)){let t=r.mapper===void 0?r.value:await r.mapper.invoke(r.value,e);if(IP(t)||r.skipNone&&t===void 0)continue;n.push([r.channel,t])}else throw Error(`Invalid write entry: ${JSON.stringify(r)}`);let r=e.configurable?.[JS];r(n)}static isWriter(t){return t instanceof e||zP in t&&!!t[zP]}static registerWriter(e){return Object.defineProperty(e,zP,{value:!0})}};function VP(e){return e!==void 0&&typeof e.channel==`string`}function HP(e){return e!==void 0&&!VP(e)&&tS.isRunnable(e.mapper)}var UP=class e extends jP{lc_graph_name=`ChannelRead`;channel;fresh=!1;mapper;constructor(t,n,r=!1){super({trace:!1,func:(t,n)=>e.doRead(n,this.channel,this.fresh,this.mapper)}),this.fresh=r,this.mapper=n,this.channel=t,this.name=Array.isArray(t)?`ChannelRead<${t.join(`,`)}>`:`ChannelRead<${t}>`}static doRead(e,t,n,r){let i=e.configurable?.[XS];if(!i)throw Error(`Runnable is not configured with a read function. Make sure to call in the context of a Pregel process`);return r?r(i(t,n)):i(t,n)}},WP=new _S,GP=class e extends nS{lc_graph_name=`PregelNode`;channels;triggers=[];mapper;writers=[];bound=WP;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;timeout;subgraphs;ends;isErrorHandler;errorHandlerNode;constructor(e){let{channels:t,triggers:n,mapper:r,writers:i,bound:a,kwargs:o,metadata:s,retryPolicy:c,cachePolicy:l,timeout:u,tags:d,subgraphs:f,ends:p,isErrorHandler:m,errorHandlerNode:h}=e,g=[...e.config?.tags?e.config.tags:[],...d??[]];super({...e,bound:e.bound??WP,config:{...e.config?e.config:{},tags:g}}),this.channels=t,this.triggers=n,this.mapper=r,this.writers=i??this.writers,this.bound=a??this.bound,this.kwargs=o??this.kwargs,this.metadata=s??this.metadata,this.tags=g,this.retryPolicy=c,this.cachePolicy=l,this.timeout=u,this.subgraphs=f,this.ends=p,this.isErrorHandler=m,this.errorHandlerNode=h}getWriters(){let e=[...this.writers];for(;e.length>1&&e[e.length-1]instanceof BP&&e[e.length-2]instanceof BP;){let t=e.slice(-2),n=t[0].writes.concat(t[1].writes);e[e.length-2]=new BP(n,t[0].config?.tags),e.pop()}return e}getNode(){let e=this.getWriters();if(!(this.bound===WP&&e.length===0))return this.bound===WP&&e.length===1?e[0]:this.bound===WP?new aS({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new aS({first:this.bound,middle:e.slice(0,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):this.bound}join(t){if(!Array.isArray(t))throw Error(`channels must be a list`);if(typeof this.channels!=`object`)throw Error(`all channels must be named when using .join()`);return new e({channels:{...this.channels,...Object.fromEntries(t.map(e=>[e,e]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout})}pipe(t){return BP.isWriter(t)?new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,t],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout}):this.bound===WP?new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:fS(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout}):new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout})}};function KP(e){let t=typeof e[VS];if(t===`number`)return 0;if(t===`string`)return``;for(let t in e){if(!Object.prototype.hasOwnProperty.call(e,t))continue;let n=typeof e[t];if(n===`number`)return 0;if(n===`string`)return``;break}}function qP(e,t){if(Object.keys(e).length>0){let n=KP(t);return Object.fromEntries(Object.entries(t).filter(([t,r])=>r>(e[t]??n)))}else return t}function JP(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e==`object`?e:{[t]:e}}function YP(e,t){return e===null?{configurable:t}:e?.configurable===void 0?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function XP(e,t){let n=t?.parents??{};return Object.keys(n).length>0?YP(e,{[uC]:{...n,[e.configurable?.checkpoint_ns??``]:e.configurable?.checkpoint_id}}):e}function ZP(...e){let t=[...new Set(e.filter(Boolean))];if(t.length===0)return{signal:void 0,dispose:void 0};if(t.length===1)return{signal:t[0],dispose:void 0};let n=new AbortController,r=()=>{let e=t.find(e=>e.aborted)?.reason;n.abort(e),t.forEach(e=>e.removeEventListener(`abort`,r))};t.forEach(e=>e.addEventListener(`abort`,r,{once:!0}));let i=t.find(e=>e.aborted);return i&&n.abort(i.reason),{signal:n.signal,dispose:()=>{t.forEach(e=>e.removeEventListener(`abort`,r))}}}function QP(e){return`steps`in e&&Array.isArray(e.steps)}function $P(e){return`lg_is_pregel`in e&&e.lg_is_pregel===!0}function eF(e){let t=[e];for(let e of t)if($P(e))return e;else QP(e)&&t.push(...e.steps)}var tF=class e extends iP{lc_graph_name=`EphemeralValue`;guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(t){let n=new e(this.guard);return t!==void 0&&(n.value=[t]),n}update(e){if(e.length===0){let e=this.value.length>0;return this.value=[],e}if(e.length!==1&&this.guard)throw new ew(`EphemeralValue can only receive one value per step.`);return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new $C;return this.value[0]}checkpoint(){if(this.value.length===0)throw new $C;return this.value[0]}isAvailable(){return this.value.length!==0}},nF=class{#e=void 0;requestDrain(e=`shutdown`){this.#e=e}get drainRequested(){return this.#e!==void 0}get drainReason(){return this.#e}},H=e=>BigInt(e),rF=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),iF=H(`0x9E3779B1`),aF=H(`0x85EBCA77`),oF=H(`0xC2B2AE3D`),sF=H(`0x9E3779B185EBCA87`),cF=H(`0xC2B2AE3D27D4EB4F`),lF=H(`0x165667B19E3779F9`),uF=H(`0x85EBCA77C2B2AE63`),dF=H(`0x27D4EB2F165667C5`),fF=H(`0x165667919E3779F9`),pF=H(`0x9FB21C651E98DF25`),mF=(e=>{let t=e.length;if(t%2!=0)throw Error(`String should have an even number of characters`);let n=t/2,r=new Uint8Array(n),i=0,a=0;for(;a<n;){let t=e.slice(i,i+=2);r[a]=Number.parseInt(t,16),a+=1}return rF(r)})(`b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e`),hF=(H(1)<<H(128))-H(1),gF=(H(1)<<H(64))-H(1),_F=(H(1)<<H(32))-H(1),vF=64,yF=vF/8,bF=8,xF=4;function SF(e){if(!e)throw Error(`Assert failed`)}function CF(e){let t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function wF(e){let t=e;return t=(t&H(65535))<<H(16)|(t&H(4294901760))>>H(16),t=(t&H(16711935))<<H(8)|(t&H(4278255360))>>H(8),t}function TF(e,t){return(e&_F)*(t&_F)&gF}function EF(e,t){return(e<<t|e>>H(32)-t)&_F}function DF(e,t,n){for(let r=0;r<yF;r+=1){let i=t.getBigUint64(r*8,!0),a=i^n.getBigUint64(r*8,!0);e[r^1]+=i,e[r]+=TF(a,a>>H(32))}return e}function OF(e,t,n,r){for(let i=0;i<r;i+=1)DF(e,rF(t,i*vF),rF(n,i*8));return e}function kF(e,t){for(let n=0;n<yF;n+=1){let r=t.getBigUint64(n*8,!0),i=e[n];i=BF(i,H(47)),i^=r,i*=iF,e[n]=i&gF}return e}function AF(e,t){return PF(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(bF,!0))}function jF(e,t,n){let r=n;return r+=AF(e.slice(0),rF(t,0*xF)),r+=AF(e.slice(2),rF(t,4*xF)),r+=AF(e.slice(4),rF(t,8*xF)),r+=AF(e.slice(6),rF(t,12*xF)),LF(r&gF)}function MF(e,t,n,r,i){let a=e,o=Math.floor((n.byteLength-vF)/8),s=vF*o,c=Math.floor((t.byteLength-1)/s);for(let e=0;e<c;e+=1)a=OF(a,rF(t,e*s),n,o),a=i(a,rF(n,n.byteLength-vF));{let e=Math.floor((t.byteLength-1-s*c)/vF);a=OF(a,rF(t,c*s),n,e),a=r(a,rF(t,t.byteLength-vF),rF(n,n.byteLength-vF-7))}return a}function NF(e,t){let n=new BigUint64Array([oF,sF,cF,lF,uF,aF,dF,iF]);SF(e.byteLength>128),n=MF(n,e,t,DF,kF),SF(n.length*8==64);{let r=jF(n,rF(t,11),H(e.byteLength)*sF&gF);return jF(n,rF(t,t.byteLength-vF-11),~(H(e.byteLength)*cF)&gF)<<H(64)|r}}function PF(e,t){let n=e*t&hF;return n&gF^n>>H(64)}function FF(e,t,n){return PF((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+n)&gF,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-n)&gF)}function IF(e,t,n,r,i){let a=e&gF,o=e>>H(64)&gF;return a+=FF(t,r,i),a^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),a&=gF,o+=FF(n,rF(r,16),i),o^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),o&=gF,o<<H(64)|a}function LF(e){let t=e;return t^=t>>H(37),t*=fF,t&=gF,t^=t>>H(32),t}function RF(e){let t=e;return t^=t>>H(33),t*=cF,t&=gF,t^=t>>H(29),t*=lF,t&=gF,t^=t>>H(32),t}function zF(e,t,n){let r=e.byteLength;SF(r>0&&r<=3);let i=H(e.getUint8(r-1))|H(r<<8)|H(e.getUint8(0)<<16)|H(e.getUint8(r>>1)<<24),a=(i^(H(t.getUint32(0,!0))^H(t.getUint32(4,!0)))+n)&gF,o=(H(t.getUint32(8,!0))^H(t.getUint32(12,!0)))-n;return(RF((EF(wF(i),H(13))^o)&gF)&gF)<<H(64)|RF(a)}function BF(e,t){return e^e>>t}function VF(e,t,n){let r=e.byteLength;SF(r>=4&&r<=8);{let i=e.getUint32(0,!0),a=e.getUint32(r-4,!0),o=((H(i)|H(a)<<H(32))^(t.getBigUint64(16,!0)^t.getBigUint64(24,!0))+n&gF)*(sF+(H(r)<<H(2)))&hF;return o+=(o&gF)<<H(65),o&=hF,o^=o>>H(67),BF(BF(o&gF,H(35))*pF&gF,H(28))|LF(o>>H(64))<<H(64)}}function HF(e,t,n){let r=e.byteLength;SF(r>=9&&r<=16);{let i=(t.getBigUint64(32,!0)^t.getBigUint64(40,!0))+n&gF,a=(t.getBigUint64(48,!0)^t.getBigUint64(56,!0))-n&gF,o=e.getBigUint64(0,!0),s=e.getBigUint64(r-8,!0),c=(o^s^i)*sF,l=(c&gF)+(H(r-1)<<H(54));c=c&(hF^gF)|l,s^=a,c+=s+(s&_F)*(aF-H(1))<<H(64),c&=hF,c^=CF(c>>H(64));let u=(c&gF)*cF;return u+=(c>>H(64))*cF<<H(64),u&=hF,LF(u&gF)|LF(u>>H(64))<<H(64)}}function UF(e,t){let n=e.byteLength;return SF(n<=16),n>8?HF(e,mF,t):n>=4?VF(e,mF,t):n>0?zF(e,mF,t):RF(t^mF.getBigUint64(64,!0)^mF.getBigUint64(72,!0))|RF(t^mF.getBigUint64(80,!0)^mF.getBigUint64(88,!0))<<H(64)}function WF(e){return~e+H(1)&gF}function GF(e,t,n){let r=H(e.byteLength)*sF&gF,i=H(e.byteLength-1)/H(32);for(;i>=0;){let a=Number(i);r=IF(r,rF(e,16*a),rF(e,e.byteLength-16*(a+1)),rF(t,32*a),n),i-=H(1)}let a=r+(r>>H(64))&gF;a=LF(a);let o=(r&gF)*sF+(r>>H(64))*uF+(H(e.byteLength)-n&gF)*cF;return o&=gF,o=WF(LF(o)),a|o<<H(64)}function KF(e,t,n){let r=H(e.byteLength)*sF&gF;for(let i=32;i<160;i+=32)r=IF(r,rF(e,i-32),rF(e,i-16),rF(t,i-32),n);r=LF(r&gF)|LF(r>>H(64))<<H(64);for(let i=160;i<=e.byteLength;i+=32)r=IF(r,rF(e,i-32),rF(e,i-16),rF(t,3+i-160),n);r=IF(r,rF(e,e.byteLength-16),rF(e,e.byteLength-32),rF(t,103),WF(n));let i=r+(r>>H(64))&gF;i=LF(i);let a=(r&gF)*sF+(r>>H(64))*uF+(H(e.byteLength)-n&gF)*cF;return a&=gF,a=WF(LF(a)),i|a<<H(64)}function qF(e,t=H(0)){let n=new TextEncoder,r=rF(typeof e==`string`?n.encode(e):e),i=r.byteLength;return(e=>e.toString(16).padStart(32,`0`))(i<=16?UF(r,t):i<=128?GF(r,mF,t):i<=240?KF(r,mF,t):NF(r,mF))}function JF(e){return/^[0-9a-f]{32}$/.test(e)}function YF(e,t,n=!0,r=!1){try{return e[t].get()}catch(e){if(e.name===$C.unminifiable_name){if(r)return e;if(n)return null}throw e}}function XF(e,t,n=!0){if(Array.isArray(t)){let r={};for(let i of t)try{r[i]=YF(e,i,!n)}catch(e){if(e.name===$C.unminifiable_name)continue}return r}else return YF(e,t)}function*ZF(e,t){if(e.graph===PC.PARENT)throw new ew(`There is no parent graph.`);if(e.goto){let t;t=Array.isArray(e.goto)?e.goto:[e.goto];for(let e of t)if(kC(e))yield[CC,bC,e];else if(typeof e==`string`)yield[CC,`branch:to:${e}`,`__start__`];else throw Error(`In Command.send, expected Send or string, got ${typeof e}`)}if(e.resume)if(typeof e.resume==`object`&&Object.keys(e.resume).length&&Object.keys(e.resume).every(JF))for(let[n,r]of Object.entries(e.resume)){let e=t.filter(e=>e[0]===n&&e[1]===`__resume__`).map(e=>e[2]).slice(0,1)??[];e.push(r),yield[n,mC,e]}else yield[CC,mC,e.resume];if(e.update){if(typeof e.update!=`object`||!e.update)throw Error(`Expected cmd.update to be a dict mapping channel names to update values`);if(Array.isArray(e.update))for(let[t,n]of e.update)yield[CC,t,n];else for(let[t,n]of Object.entries(e.update))yield[CC,t,n]}}function*QF(e,t){if(t!=null)if(Array.isArray(e)&&typeof t==`object`&&!Array.isArray(t))for(let n in t)e.includes(n)&&(yield[n,t[n]]);else if(Array.isArray(e))throw Error(`Input chunk must be an object when "inputChannels" is an array`);else yield[e,t]}function*$F(e,t,n){Array.isArray(e)?(t===!0||t.find(([t,n])=>e.includes(t)))&&(yield XF(n,e)):(t===!0||t.some(([t,n])=>t===e))&&(yield YF(n,e))}function*eI(e,t,n){let r=t.filter(([e,t])=>(e.config===void 0||!e.config.tags?.includes(`langsmith:hidden`))&&t[0][0]!==`__error__`&&t[0][0]!==`__interrupt__`);if(!r.length)return;let i;i=r.some(([e])=>e.writes.some(([e,t])=>e===`__return__`))?r.flatMap(([e])=>e.writes.filter(([e,t])=>e===gC).map(([t,n])=>[e.name,n])):Array.isArray(e)?r.flatMap(([t])=>{let{writes:n}=t,r={};for(let[t]of n)e.includes(t)&&(r[t]=(r[t]||0)+1);return Object.values(r).some(e=>e>1)?n.filter(([t])=>e.includes(t)).map(([e,n])=>[t.name,{[e]:n}]):[[t.name,Object.fromEntries(n.filter(([t])=>e.includes(t)))]]}):r.flatMap(([t])=>t.writes.filter(([t,n])=>t===e).map(([e,n])=>[t.name,n]));let a={};for(let[e,t]of i)e in a||(a[e]=[]),a[e].push(t);let o={};for(let e in a)if(a[e].length===1){let[t]=a[e];o[e]=t}else o[e]=a[e];n&&(o.__metadata__={cached:n}),yield o}var tI=class{func;name;input;retry;cache;timeout;callbacks;__lg_type=`call`;constructor({func:e,name:t,input:n,retry:r,cache:i,timeout:a,callbacks:o}){this.func=e,this.name=t,this.input=n,this.retry=r,this.cache=i,this.timeout=a,this.callbacks=o}};function nI(e){return typeof e==`object`&&!!e&&`__lg_type`in e&&e.__lg_type===`call`}function rI(e,t){return new aS({name:e,first:new jP({func:e=>t(...e),name:e,trace:!1,recurse:!1}),last:new BP([{channel:gC,value:LP}],[vC])})}var iI=e=>e===void 0?1:e+1;function aI(e,t){if(t==null)return!1;for(let n of e)if(t[n])return!0;return!1}function oI(e){let t;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t=t==null?e[n]:KN(t,e[n]));return t}function sI(e,t,n){let r=KP(e.channel_versions),i=e.versions_seen.__interrupt__??{},a=!1;if((e.channel_versions.__start__??r)>(i.__start__??r))a=!0;else for(let t in e.channel_versions)if(Object.prototype.hasOwnProperty.call(e.channel_versions,t)&&e.channel_versions[t]>(i[t]??r)){a=!0;break}let o=n.some(e=>t===`*`?!e.config?.tags?.includes(vC):t.includes(e.name));return a&&o}function cI(e,t,n,r,i=!1){let a=new Set;if(Array.isArray(r))a=new Set(r.filter(e=>n.writes.some(([t,n])=>t===e)));else{for(let[e]of n.writes)if(e===r){a=new Set([e]);break}a||=new Set}let o;if(i&&a.size>0){let i=Object.fromEntries(Object.entries(t).filter(([e,t])=>a.has(e))),s=new Set;for(let e in i){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let t=i[e];nP(t)&&t.isAvailable()&&s.add(e)}let c=uP(e,i,-1,{channelsToSnapshot:s}),l=sP(i,c);fI(WN(c),l,[n],void 0,void 0),o=XF({...t,...l},r)}else o=XF(t,r);return o}function lI(e,t,n){for(let[e,r]of n)if([`__pregel_push`,`__pregel_tasks`].includes(e)&&r!=null){if(!kC(r))throw new ew(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(r)}`);if(!(r.node in t))throw new ew(`Invalid node name "${r.node}" in Send packet`)}e(n)}var uI=new Set([hC,xC,mC,pC,gC,WS,GS]),dI=new Set(wC);function fI(e,t,n,r,i){let a=new Map;for(let e of n)a.set(e,e.path?.slice(0,3)||[]);n.sort((e,t)=>{let n=a.get(e),r=a.get(t);for(let e=0;e<Math.min(n.length,r.length);e+=1){if(n[e]<r[e])return-1;if(n[e]>r[e])return 1}return n.length-r.length});let o=oP(t),s=!1,c=new Set;for(let t of n){t.triggers.length>0&&(s=!0),e.versions_seen[t.name]??={};for(let n of t.triggers)n in e.channel_versions&&(e.versions_seen[t.name][n]=e.channel_versions[n]),dI.has(n)||c.add(n)}let l=oI(e.channel_versions),u=!1;for(let t of c)t in o&&o[t].consume()&&r!==void 0&&(e.channel_versions[t]=r(l),u=!0);let d={},f={};for(let e of n){let t=e.id??``;for(let[n,r]of e.writes)uI.has(n)||n in o&&(d[n]??=[],d[n].push(r),f[n]??=[],f[n].push(t))}for(let[e,t]of Object.entries(d)){if(t.length<2||o[e]?.lc_graph_name!==`DeltaChannel`)continue;let n=f[e],r=t.map((e,t)=>({val:e,taskId:n[t]}));r.sort((e,t)=>e.taskId<t.taskId?-1:+(e.taskId>t.taskId)),d[e]=r.map(e=>e.val)}l!=null&&r!=null&&(l=u?r(l):l);let p=new Set;for(let[t,n]of Object.entries(d))if(t in o){let i=o[t],a;try{a=i.update(n)}catch(e){if(e.name===ew.unminifiable_name){let r=new ew(`Invalid update for channel "${t}" with values ${JSON.stringify(n)}: ${e.message}`);throw r.lc_error_code=e.lc_error_code,r}else throw e}a&&r!==void 0&&(e.channel_versions[t]=r(l),i.isAvailable()&&p.add(t))}if(s)for(let t in o){if(!Object.prototype.hasOwnProperty.call(o,t))continue;let n=o[t];n.isAvailable()&&!p.has(t)&&n.update([])&&r!==void 0&&(e.channel_versions[t]=r(l),n.isAvailable()&&p.add(t))}if(s&&!aI(p,i))for(let t in o){if(!Object.prototype.hasOwnProperty.call(o,t))continue;let n=o[t];n.finish()&&r!==void 0&&(e.channel_versions[t]=r(l),n.isAvailable()&&p.add(t))}return p}function*pI(e,t,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){let e=new Set;for(let t of n.updatedChannels){let r=n.triggerToNodes[t];for(let t of r??[])e.add(t)}yield*[...e].sort();return}if(!(()=>{for(let t in e.channel_versions)if(e.channel_versions[t]!==null)return!1;return!0})())for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(yield e)}function mI(e){let t,n=new Map,r=new Set;if(e)for(let[i,a,o]of e){if(i===`00000000-0000-0000-0000-000000000000`&&a===`__resume__`&&t===void 0&&(t=o),a===`__resume__`&&i!==`00000000-0000-0000-0000-000000000000`){let e=n.get(i);e||(e=[],n.set(i,e)),e.push(o)}a!==`__error__`&&r.add(i)}return{nullResume:t,resumeByTaskId:n,successfulWriteTaskIds:r}}function hI(e,t,n,r,i,a,o){let s={},c=o.pendingWritesIndex?o:{...o,pendingWritesIndex:mI(t)},l=r[bC];if(l?.isAvailable()){let o=l.get().length;for(let l=0;l<o;l+=1){let o=gI([xC,l],e,t,n,r,i,a,c);o!==void 0&&(s[o.id]=o)}}for(let o of pI(e,n,c)){let l=gI([SC,o],e,t,n,r,i,a,c);l!==void 0&&(s[l.id]=l)}return s}function gI(e,t,n,r,i,a,o,s){let{step:c,checkpointer:l,manager:u}=s,d=a.configurable??{},f=d.checkpoint_ns??``;if(e[0]===`__pregel_push`&&nI(e[e.length-1])){let p=e[e.length-1],m=rI(p.name,p.func),h=[xC],g=f===``?p.name:`${f}|${p.name}`,_=ow(JSON.stringify([g,c.toString(),p.name,xC,e[1],e[2]]),t.id),v=`${g}:${_}`,y=[...e.slice(0,3),!0],b={langgraph_step:c,langgraph_node:p.name,langgraph_triggers:h,langgraph_path:y,langgraph_checkpoint_ns:v,checkpoint_ns:v};if(o){let e=[],o={checkpointId:t.id,checkpointNs:v,taskId:_,threadId:d.thread_id,runId:a.runId==null?void 0:String(a.runId),nodeAttempt:1};return{name:p.name,input:p.input,proc:m,writes:e,config:{...Au(Ou(a,{metadata:b,store:s.store??a.store}),{runName:p.name,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[$S]:_,[JS]:t=>lI(t=>e.push(...t),r,t),[XS]:(n,r=!1)=>cI(t,i,{name:p.name,writes:e,triggers:h,path:y},n,r),[ZS]:l??d.__pregel_checkpointer,[uC]:{...d[uC],[f]:t.id},[rC]:bI({pendingWrites:n??[],taskId:_,currentTaskInput:p.input,resumeMap:a.configurable?.[nC],namespaceHash:qF(v),pendingWritesIndex:s.pendingWritesIndex}),[iC]:t.channel_values[_C],checkpoint_id:void 0,checkpoint_ns:v}}),executionInfo:o},triggers:h,retry_policy:p.retry,cache_key:p.cache?{key:qF((p.cache.keyFunc??JSON.stringify)([p.input])),ns:[KS,p.name??`__dynamic__`],ttl:p.cache.ttl}:void 0,id:_,path:y,writers:[],timeout:p.timeout}}else return{id:_,name:p.name,interrupts:[],path:y}}else if(e[0]===`__pregel_push`){let p=typeof e[1]==`number`?e[1]:parseInt(e[1],10);if(!i.__pregel_tasks?.isAvailable())return;let m=i[bC].get();if(p<0||p>=m.length)return;let h=DC(m[p])&&!kC(m[p])?new OC(m[p].node,m[p].args,m[p].timeout===void 0?void 0:{timeout:m[p].timeout}):m[p];if(!DC(h)){console.warn(`Ignoring invalid packet ${JSON.stringify(h)} in pending sends.`);return}if(!(h.node in r)){console.warn(`Ignoring unknown node name ${h.node} in pending sends.`);return}let g=[xC],_=f===``?h.node:`${f}|${h.node}`,v=ow(JSON.stringify([_,c.toString(),h.node,xC,p.toString()]),t.id),y=`${_}:${v}`,b={langgraph_step:c,langgraph_node:h.node,langgraph_triggers:g,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:y,checkpoint_ns:y};if(o){let o=r[h.node],p=o.getNode();if(p!==void 0){o.metadata!==void 0&&(b={...b,...o.metadata});let m=[],_={checkpointId:t.id,checkpointNs:y,taskId:v,threadId:d.thread_id,runId:a.runId==null?void 0:String(a.runId),nodeAttempt:1};return{name:h.node,input:h.args,proc:p,subgraphs:o.subgraphs,writes:m,config:{...Au(Ou(a,{metadata:b,tags:o.tags,store:s.store??a.store}),{runName:h.node,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[$S]:v,[JS]:e=>lI(e=>m.push(...e),r,e),[XS]:(n,r=!1)=>cI(t,i,{name:h.node,writes:m,triggers:g,path:e},n,r),[ZS]:l??d.__pregel_checkpointer,[uC]:{...d[uC],[f]:t.id},[rC]:bI({pendingWrites:n??[],taskId:v,currentTaskInput:h.args,resumeMap:a.configurable?.[nC],namespaceHash:qF(y),pendingWritesIndex:s.pendingWritesIndex}),[iC]:t.channel_values[_C],checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:_},triggers:g,retry_policy:o.retryPolicy,cache_key:o.cachePolicy?{key:qF((o.cachePolicy.keyFunc??JSON.stringify)([h.args])),ns:[KS,o.name??`__dynamic__`,h.node],ttl:o.cachePolicy.ttl}:void 0,id:v,path:e,writers:o.getWriters(),timeout:h.timeout??o.timeout}}}else return{id:v,name:h.node,interrupts:[],path:e}}else if(e[0]===`__pregel_pull`){let p=e[1].toString(),m=r[p];if(m===void 0)return;if(n?.length){let e=f===``?p:`${f}|${p}`,r=ow(JSON.stringify([e,c.toString(),p,SC,p]),t.id);if(s.pendingWritesIndex?s.pendingWritesIndex.successfulWriteTaskIds.has(r):n.some(e=>e[0]===r&&e[1]!==`__error__`))return}let h=KP(t.channel_versions);if(h===void 0)return;let g=t.versions_seen[p]??{},_=m.triggers.find(e=>i[e].isAvailable()?(t.channel_versions[e]??h)>(g[e]??h):!1);if(_!==void 0){let h=vI(m,i,o);if(h===void 0)return;let g=f===``?p:`${f}|${p}`,v=ow(JSON.stringify([g,c.toString(),p,SC,[_]]),t.id),y=`${g}:${v}`,b={langgraph_step:c,langgraph_node:p,langgraph_triggers:[_],langgraph_path:e,langgraph_checkpoint_ns:y,checkpoint_ns:y};if(o){let o=m.getNode();if(o!==void 0){m.metadata!==void 0&&(b={...b,...m.metadata});let g=[],ee={checkpointId:t.id,checkpointNs:y,taskId:v,threadId:d.thread_id,runId:a.runId==null?void 0:String(a.runId),nodeAttempt:1};return{name:p,input:h,proc:o,subgraphs:m.subgraphs,writes:g,config:{...Au(Ou(a,{metadata:b,tags:m.tags,store:s.store??a.store}),{runName:p,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[$S]:v,[JS]:e=>lI(e=>{g.push(...e)},r,e),[XS]:(n,r=!1)=>cI(t,i,{name:p,writes:g,triggers:[_],path:e},n,r),[ZS]:l??d.__pregel_checkpointer,[uC]:{...d[uC],[f]:t.id},[rC]:bI({pendingWrites:n??[],taskId:v,currentTaskInput:h,resumeMap:a.configurable?.[nC],namespaceHash:qF(y),pendingWritesIndex:s.pendingWritesIndex}),[iC]:t.channel_values[_C],checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:ee},triggers:[_],retry_policy:m.retryPolicy,cache_key:m.cachePolicy?{key:qF((m.cachePolicy.keyFunc??JSON.stringify)([h])),ns:[KS,m.name??`__dynamic__`,p],ttl:m.cachePolicy.ttl}:void 0,id:v,path:e,writers:m.getWriters(),timeout:m.timeout}}}else return{id:v,name:p,interrupts:[],path:e}}}}function _I(e,t,n,r,i,a,o,s,c){let{step:l,checkpointer:u,manager:d}=c,f=a[t];if(f===void 0)return;let p=f.getNode();if(p===void 0)return;let m=s.configurable??{},h=m.checkpoint_ns??``,g=[xC],_=h===``?t:`${h}|${t}`,v=ow(JSON.stringify([_,l.toString(),t,xC,`node_error_handler`,e.id]),r.id),y=`${_}:${v}`,b=[xC,String(e.name),t,!1],ee={langgraph_step:l,langgraph_node:t,langgraph_triggers:g,langgraph_path:b,langgraph_checkpoint_ns:y,checkpoint_ns:y};f.metadata!==void 0&&(ee={...ee,...f.metadata});let te=[],ne={checkpointId:r.id,checkpointNs:y,taskId:v,threadId:m.thread_id,runId:s.runId==null?void 0:String(s.runId),nodeAttempt:1};return{name:t,input:e.input,proc:p,subgraphs:f.subgraphs,writes:te,config:{...Au(Ou(s,{metadata:ee,tags:f.tags,store:c.store??s.store}),{runName:t,callbacks:d?.getChild(`graph:step:${l}`),configurable:{[$S]:v,[JS]:e=>lI(e=>te.push(...e),a,e),[XS]:(e,n=!1)=>cI(r,o,{name:t,writes:te,triggers:g,path:b},e,n),[ZS]:u??m.__pregel_checkpointer,[uC]:{...m[uC],[h]:r.id},[rC]:bI({pendingWrites:i??[],taskId:v,currentTaskInput:e.input,resumeMap:s.configurable?.[nC],namespaceHash:qF(y)}),[iC]:r.channel_values[_C],[lC]:new KC(String(e.name),n),checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:ne},triggers:g,retry_policy:f.retryPolicy,cache_key:void 0,id:v,path:b,writers:f.getWriters()}}function vI(e,t,n){let r;if(typeof e.channels==`object`&&!Array.isArray(e.channels)){r={};for(let[n,i]of Object.entries(e.channels))if(e.triggers.includes(i))try{r[n]=YF(t,i,!1)}catch(e){if(e.name===$C.unminifiable_name)return;throw e}else if(i in t)try{r[n]=YF(t,i,!1)}catch(e){if(e.name===$C.unminifiable_name)continue;throw e}}else if(Array.isArray(e.channels)){let n=!1;for(let i of e.channels)try{r=YF(t,i,!1),n=!0;break}catch(e){if(e.name===$C.unminifiable_name)continue;throw e}if(!n)return}else throw Error(`Invalid channels type, expected list or dict, got ${e.channels}`);return n&&e.mapper!==void 0&&(r=e.mapper(r)),r}function yI(e,t){if(typeof e.args!=`object`||e.args===null)return e;let n={};for(let[r,i]of Object.entries(e.args)){let e=t[r];(!e||e.lc_graph_name!==`UntrackedValue`)&&(n[r]=i)}return new OC(e.node,n)}function bI({pendingWrites:e,taskId:t,currentTaskInput:n,resumeMap:r,namespaceHash:i,pendingWritesIndex:a}){let o=a?a.nullResume:e.find(([e,t])=>e===`00000000-0000-0000-0000-000000000000`&&t===`__resume__`)?.[2],s={callCounter:0,interruptCounter:-1,resume:(()=>{let n=a?(a.resumeByTaskId.get(t)??[]).flat():e.filter(([e,n])=>e===t&&n===`__resume__`).flatMap(([e,t,n])=>n);if(r!=null&&i in r){let e=r[i];n.push(e)}return n})(),nullResume:o,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(s.nullResume)return delete s.nullResume,e.splice(e.findIndex(([e,t])=>e===`00000000-0000-0000-0000-000000000000`&&t===`__resume__`),1),o}};return s}var xI={blue:{start:`\x1B[34m`,end:`\x1B[0m`},green:{start:`\x1B[32m`,end:`\x1B[0m`},yellow:{start:`\x1B[33;1m`,end:`\x1B[0m`}},SI=(e,t)=>`${e.start}${t}${e.end}`;function CI(e){if(e==null)return;let t={};if(e.metadata!=null)for(let[n,r]of Object.entries(e.metadata))JN.has(n)||(t[n]=r);let n=wP(e.tags);return n!=null&&(t.tags=n),Object.keys(t).length>0?t:void 0}function*wI(e){for(let{id:t,name:n,input:r,config:i,triggers:a,writes:o}of e){if(i?.tags?.includes(`langsmith:hidden`))continue;let e={id:t,name:n,input:r,triggers:a,interrupts:o.filter(([e,n])=>e===t&&n===`__interrupt__`).map(([,e])=>e)},s=CI(i);s!=null&&(e.metadata=s),yield e}}function TI(e){return typeof e!=`object`||!e?!1:`$writes`in e&&Array.isArray(e.$writes)}function EI(e){let t={};for(let[n,r]of e){let e=String(n);if(e in t){let n=TI(t[e])?t[e].$writes:[t[e]];n.push(r),t[e]={$writes:n}}else t[e]=r}return t}function*DI(e,t){for(let[{id:n,name:r,config:i},a]of e)i?.tags?.includes(`langsmith:hidden`)||(yield{id:n,name:r,result:EI(a.filter(([e])=>Array.isArray(t)?t.includes(e):e===t)),interrupts:a.filter(e=>e[0]===pC).map(e=>e[1])})}function*OI(e,t,n,r,i,a,o,s){function c(e){let t={};return e.callbacks!=null&&(t.callbacks=e.callbacks),e.configurable!=null&&(t.configurable=e.configurable),e.maxConcurrency!=null&&(t.max_concurrency=e.maxConcurrency),e.metadata!=null&&(t.metadata=e.metadata),e.recursionLimit!=null&&(t.recursion_limit=e.recursionLimit),e.runId!=null&&(t.run_id=e.runId),e.runName!=null&&(t.run_name=e.runName),e.tags!=null&&(t.tags=e.tags),t}let l=e.configurable?.checkpoint_ns,u={};for(let t of i){if(!(t.subgraphs?.length?t.subgraphs:[t.proc]).find(eF))continue;let n=`${t.name}:${t.id}`;l&&(n=`${l}|${n}`),u[t.id]={configurable:{thread_id:e.configurable?.thread_id,checkpoint_ns:n}}}yield{config:c(e),values:XF(t,n),metadata:r,next:i.map(e=>e.name),tasks:kI(i,a,u,s),parentConfig:o?c(o):void 0}}function kI(e,t,n,r){return e.map(e=>{let i=t.find(([t,n])=>t===e.id&&n===`__error__`)?.[2],a=t.filter(([t,n])=>t===e.id&&n===`__interrupt__`).map(([,,e])=>e),o=(()=>{if(i||a.length||!t.length)return;let n=t.findIndex(([t,n])=>t===e.id&&n===`__return__`);if(n>=0)return t[n][2];if(typeof r==`string`)return t.find(([t,n])=>t===e.id&&n===r)?.[2];if(Array.isArray(r)){let n=t.filter(([t,n])=>t===e.id&&r.includes(n)).map(([,e,t])=>[e,t]);return n.length?EI(n):void 0}})();if(i)return{id:e.id,name:e.name,path:e.path,error:i,interrupts:a,result:o};let s=n?.[e.id];return{id:e.id,name:e.name,path:e.path,interrupts:a,...s===void 0?{}:{state:s},result:o}})}function AI(e,t,n){console.log([`${SI(xI.blue,`[${e}:checkpoint]`)}`,`\x1b[1m State at the end of step ${e}:\x1b[0m\n`,JSON.stringify(XF(t,n),null,2)].join(``))}function jI(e,t){let n=t.length;console.log([`${SI(xI.blue,`[${e}:tasks]`)}`,`\x1b[1m Starting step ${e} with ${n} task${n===1?``:`s`}:\x1b[0m\n`,t.map(e=>`- ${SI(xI.green,String(e.name))} -> ${JSON.stringify(e.input,null,2)}`).join(`
|
|
186
|
-
`)].join(``))}function
|
|
187
|
-
`)].join(``))}var NI=[`values`,`updates`,`messages`,`tools`,`custom`,`tasks`];function PI(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&(`source`in t||typeof t.step==`number`)&&!(`values`in t)&&!(`config`in t)}function FI(e){if(!Array.isArray(e)||e.length!==2)return{data:e};let[t,n]=e;if(typeof n!=`object`||!n)return{data:e};let r=n,i=typeof r.langgraph_node==`string`?r.langgraph_node:void 0,a=typeof r.run_id==`string`?r.run_id:void 0;return{data:a!=null&&typeof t==`object`&&t?{...t,run_id:a}:t,node:i}}function II({namespace:e,mode:t,payload:n,seq:r}){let i=Date.now(),a={type:`event`};switch(t){case`messages`:{let{data:t,node:o}=FI(n);return[{...a,seq:r,method:`messages`,params:{namespace:e,timestamp:i,...o?{node:o}:{},data:t}}]}case`tools`:return[{...a,seq:r,method:`tools`,params:{namespace:e,timestamp:i,data:LI(n)}}];case`checkpoints`:return PI(n)?[{...a,seq:r,method:`checkpoints`,params:{namespace:e,timestamp:i,data:n}}]:[];case`values`:return[{...a,seq:r,method:`values`,params:{namespace:e,timestamp:i,data:n}}];case`updates`:{let t=RI(n);return[{...a,seq:r,method:`updates`,params:{namespace:e,timestamp:i,...typeof t.node==`string`?{node:t.node}:{},data:t}}]}case`custom`:{let t=typeof n==`object`&&n&&!Array.isArray(n)&&`name`in n?n:{payload:n};return[{...a,seq:r,method:`custom`,params:{namespace:e,timestamp:i,data:t}}]}case`tasks`:return[{...a,seq:r,method:`tasks`,params:{namespace:e,timestamp:i,data:n}}];default:return[]}}function LI(e){if(typeof e!=`object`||!e)return{event:`tool-error`,tool_call_id:``,message:`Unexpected tools payload shape`};let t=e,n=String(t.toolCallId??``);switch(t.event){case`on_tool_start`:return{event:`tool-started`,tool_call_id:n,tool_name:String(t.name??`unknown`),input:t.input};case`on_tool_event`:return{event:`tool-output-delta`,tool_call_id:n,delta:typeof t.data==`string`?t.data:JSON.stringify(t.data??``)};case`on_tool_end`:return{event:`tool-finished`,tool_call_id:n,output:t.output};case`on_tool_error`:{let e=t.error;return{event:`tool-error`,tool_call_id:n,message:typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`?e.message:String(e??`unknown error`)}}default:return{event:`tool-error`,tool_call_id:``,message:`Unknown tool event: ${String(t.event)}`}}}function RI(e){if(typeof e!=`object`||!e)return{values:{}};let t=Object.entries(e);if(t.length===0)return{values:{}};let[n,r]=t[0];return{node:n,values:typeof r==`object`&&r?r:{value:r}}}var zI=class extends Fu{_abortController;_innerReader;constructor(e,t){let n=e.getReader(),r=t??new AbortController;super({start(e){return t();function t(){return n.read().then(({done:n,value:r})=>{if(n){e.close();return}return e.enqueue(r),t()})}}}),this._abortController=r,this._innerReader=n}async cancel(e){this._abortController.abort(e),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},BI=class extends Fu{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(e){let t,n=new Promise(e=>{t=e});super({start:e=>{t(e)}}),n.then(e=>{this.controller=e}),this.passthroughFn=e.passthroughFn,this.modes=e.modes}push(e){this._closed||!this.controller||(this.passthroughFn?.(e),this.controller.enqueue(e))}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(e){try{this.controller?.error(e)}finally{this._closed=!0}}},VI=class extends hi{name=`StreamToolsHandler`;awaitHandlers=!0;streamFn;runs={};constructor(e){super(),this.streamFn=e}handleToolStart(e,t,n,r,i,a,o,s){if(!a||i&&i.includes(`langsmith:hidden`))return;let c=a.langgraph_checkpoint_ns?.split(`|`)??[],l={ns:c,toolCallId:s,toolName:o??`unknown`,input:t};this.runs[n]=l,this.streamFn([c,`tools`,{event:`on_tool_start`,toolCallId:l.toolCallId,name:l.toolName,input:t}])}handleToolEvent(e,t){let n=this.runs[t];n&&this.streamFn([n.ns,`tools`,{event:`on_tool_event`,toolCallId:n.toolCallId,name:n.toolName,data:e}])}handleToolEnd(e,t){let n=this.runs[t];delete this.runs[t],n&&this.streamFn([n.ns,`tools`,{event:`on_tool_end`,toolCallId:n.toolCallId,name:n.toolName,output:e}])}handleToolError(e,t){let n=this.runs[t];delete this.runs[t],n&&this.streamFn([n.ns,`tools`,{event:`on_tool_error`,toolCallId:n.toolCallId,name:n.toolName,error:e}])}};function HI(e){return JSON.stringify(e,function(e,t){let n=this[e];if(typeof n==`object`&&n&&`toDict`in n&&typeof n.toDict==`function`){let{type:e,data:t}=n.toDict();return{...t,type:e}}return t})}function UI(e){return e instanceof Error?{error:e.name,message:e.message}:{error:`Error`,message:JSON.stringify(e)}}function WI(e){return typeof e!=`object`||!e?!1:`configurable`in e&&typeof e.configurable==`object`&&e.configurable!=null}function GI(e){return!WI(e)||!e.configurable.thread_id?null:{thread_id:e.configurable.thread_id,checkpoint_ns:e.configurable.checkpoint_ns||``,checkpoint_id:e.configurable.checkpoint_id||null,checkpoint_map:e.configurable.checkpoint_map||null}}function KI(e){if(WI(e)){let t=Object.fromEntries(Object.entries(e.configurable).filter(([e])=>!e.startsWith(`__`))),n={...e,configurable:t};return delete n.callbacks,n}return e}function qI(e){let t={...e,checkpoint:GI(e.config),parent_checkpoint:GI(e.parentConfig),config:KI(e.config),parent_config:KI(e.parentConfig),tasks:e.tasks.map(e=>{if(WI(e.state)){let t=GI(e.state);if(t!=null){let n={...e,checkpoint:t};return delete n.state,n}}return e})};return delete t.parentConfig,t}function JI(e){let t=new TextEncoder;return new ReadableStream({async start(n){let r=e=>{n.enqueue(t.encode(`event: ${e.event}\ndata: ${HI(e.data)}\n\n`))};try{for await(let t of e){let[e,n,i]=t,a=i;if(n===`debug`){let e=i;e.type===`checkpoint`&&(a={...e,payload:qI(e.payload)})}n===`checkpoints`&&(a=qI(i)),r({event:e?.length?`${n}|${e.join(`|`)}`:n,data:a})}}catch(e){r({event:`error`,data:UI(e)})}n.close()}})}function YI(...e){return new BI({passthroughFn:t=>{let n=t[1]===`checkpoints`&&PI(t[2]);for(let r of e)(r.modes.has(t[1])||n)&&r.push(t)},modes:new Set(e.flatMap(e=>Array.from(e.modes)))})}var XI=class{checkpointId;#e=new Set;constructor(e){this.checkpointId=e}#t(e){let t=e.includes(`:`)?e.slice(0,e.lastIndexOf(`:`)):e;return this.#e.has(t)?!1:(this.#e.add(t),!0)}async getCheckpoint(e,t,n){if(this.#t(e)){let e=[];for await(let r of t.list(n,{before:{configurable:{checkpoint_id:this.checkpointId}},limit:1}))e.push(r);return e.length>0?e[0]:void 0}return await t.getTuple(n)??void 0}},ZI=Symbol.for(`INPUT_DONE`),QI=Symbol.for(`INPUT_RESUMING`),$I=25;function eL(e){if(!(typeof e!=`object`||!e)){if(Mt.isInstance(e)){let t=e;t.id??(t.id=Yr(),t.lc_kwargs!=null&&(t.lc_kwargs.id=t.id));return}if(Array.isArray(e)){for(let t of e)eL(t);return}}}function tL(e){return e===void 0||e===``?[]:e.split(`|`)}function nL(e){if(!e)return[];let t=``;for(let n of Object.keys(e))n!==``&&n.length>t.length&&(t=n);return tL(t)}var rL=class extends eP{cache;queue=Promise.resolve();constructor(e){super(),this.cache=e}async get(e){return this.enqueueOperation(`get`,e)}async set(e){return this.enqueueOperation(`set`,e)}async clear(e){return this.enqueueOperation(`clear`,e)}async stop(){await this.queue}enqueueOperation(e,...t){let n=this.queue.then(()=>this.cache[e](...t));return this.queue=n.then(()=>void 0,()=>void 0),n}},iL=class e{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;_exitDeltaWrites;_deltaChannelsWithOverwrite=new Set;_hasPersistedParent=!1;_initialCheckpointConfig;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status=`pending`;control;tasks={};stream;checkpointerPromises=new Set;isNested;resumeAtHead;_checkpointerChainedPromise=Promise.resolve();_trackCheckpointerPromise(e){let t=e.then(e=>(this.checkpointerPromises.delete(t),e),e=>{throw e});this.checkpointerPromises.add(t)}async _awaitCheckpointerPromises(){await Promise.all([...this.checkpointerPromises])}store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let e=!1;if(`__start__`in this.checkpoint.channel_versions)e=!0;else for(let t in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,t)){e=!0;break}let t=this.config.configurable?.__pregel_resuming!==void 0&&this.config.configurable?.__pregel_resuming,n=this.input===null||this.input===void 0,r=FC(this.input)&&this.input.resume!=null,i=this.input===QI,a=!this.isNested&&this.config.metadata?.run_id!==void 0&&this.checkpointMetadata?.run_id!==void 0&&this.config.metadata.run_id===this.checkpointMetadata?.run_id;return e&&(t||n||r||i||a)}get isReplaying(){return!this.skipDoneTasks}constructor(e){this.input=e.input,this.checkpointer=e.checkpointer,this.checkpointer===void 0?this.checkpointerGetNextVersion=iI:this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer),this.checkpoint=e.checkpoint,this.checkpointMetadata=e.checkpointMetadata,this.checkpointPreviousVersions=e.checkpointPreviousVersions,this.channels=e.channels,this.checkpointPendingWrites=e.checkpointPendingWrites,this.step=e.step,this.stop=e.stop,this.config=e.config,this.checkpointConfig=e.checkpointConfig,this.isNested=e.isNested,this.resumeAtHead=e.resumeAtHead,this.manager=e.manager,this.outputKeys=e.outputKeys,this.streamKeys=e.streamKeys,this.nodes=e.nodes,this.skipDoneTasks=e.skipDoneTasks,this.store=e.store,this.cache=e.cache?new rL(e.cache):void 0,this.stream=e.stream,this.checkpointNamespace=e.checkpointNamespace,this.prevCheckpointConfig=e.prevCheckpointConfig,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.durability=e.durability,this.debug=e.debug,this.triggerToNodes=e.triggerToNodes,this.control=this.config.control,this._exitDeltaWrites=this.durability===`exit`&&this.checkpointer!=null?[]:void 0,this._hasPersistedParent=e.hasPersistedParent??!1,this._initialCheckpointConfig=e.checkpointConfig,this.checkpointIdSaved=e.checkpoint.id}static async initialize(t){let{config:n,stream:r}=t;r!==void 0&&n.configurable?.__pregel_stream!==void 0&&(r=YI(r,n.configurable[eC]));let i=!n.configurable||!(`checkpoint_id`in n.configurable),a=n.configurable?.[rC];n.configurable&&a&&(a.subgraphCounter>0&&(n=YP(n,{[sC]:[n.configurable[sC],a.subgraphCounter.toString()].join(`|`)})),a.subgraphCounter+=1);let o=n.configurable?.checkpoint_id,s=XS in(n.configurable??{});!s&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==``&&(n=YP(n,{checkpoint_ns:``,checkpoint_id:void 0}));let c=n;n.configurable?.checkpoint_id===void 0&&n.configurable?.checkpoint_map!==void 0&&n.configurable?.checkpoint_map?.[n.configurable?.checkpoint_ns]&&(c=YP(n,{checkpoint_id:n.configurable[uC][n.configurable?.checkpoint_ns]}));let l=tL(n.configurable?.checkpoint_ns),u;t.checkpointer?c.configurable?.checkpoint_id?u=await t.checkpointer.getTuple(c):n.configurable?.__pregel_replay_state?(u=await n.configurable[dC].getCheckpoint(n.configurable?.checkpoint_ns??``,t.checkpointer,c),n.configurable&&delete n.configurable[QS]):u=await t.checkpointer.getTuple(c):u=void 0;let d=u!==void 0;u||={config:n,checkpoint:UN(),metadata:{source:`input`,step:-2,parents:{}},pendingWrites:[]},c={...n,...u.config,configurable:{checkpoint_ns:``,...n.configurable,...u.config.configurable}};let f=u.parentConfig,p=WN(u.checkpoint),m={...u.metadata},h=u.pendingWrites??[],g=n.configurable?.checkpoint_ns,_=n.configurable?.[uC];typeof g==`string`&&g!==``&&typeof _==`object`&&_&&g in _&&h.length>0&&(h=h.filter(([,e])=>e!==mC));let v=!1,y=c.configurable?.thread_id,b=c.configurable?.checkpoint_ns??``;t.checkpointer&&o&&typeof y==`string`&&(v=(await t.checkpointer.getTuple({configurable:{thread_id:y,checkpoint_ns:b}}))?.config.configurable?.checkpoint_id===o&&m.source!==`update`&&m.source!==`fork`);let ee=await dP(t.channelSpecs,p,{saver:t.checkpointer,config:c}),te=(m.step??0)+1,ne=te+(n.recursionLimit??$I)+1,x={...p.channel_versions},re=t.store?new $N(t.store):void 0;return re&&await re.start(),new e({input:t.input,config:n,checkpointer:t.checkpointer,checkpoint:p,checkpointMetadata:m,checkpointConfig:c,prevCheckpointConfig:f,checkpointNamespace:l,channels:ee,isNested:s,resumeAtHead:v,manager:t.manager,skipDoneTasks:i,step:te,stop:ne,checkpointPreviousVersions:x,checkpointPendingWrites:h,outputKeys:t.outputKeys??[],streamKeys:t.streamKeys??[],nodes:t.nodes,stream:r,store:re,cache:t.cache,interruptAfter:t.interruptAfter,interruptBefore:t.interruptBefore,durability:t.durability,debug:t.debug,triggerToNodes:t.triggerToNodes,hasPersistedParent:d})}_checkpointerPutAfterPrevious(e){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(e.config,e.checkpoint,e.metadata,e.newVersions)),this._trackCheckpointerPromise(this._checkpointerChainedPromise)}putWrites(e,t){let n=t;if(n.length===0)return;n.every(([e])=>e in qN)&&(n=Array.from(new Map(n.map(e=>[e[0],e])).values()));let r=!1;for(let e in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,e)&&this.channels[e].lc_graph_name===`UntrackedValue`){r=!0;break}let i=n;r&&(i=n.filter(([e])=>{let t=this.channels[e];return!t||t.lc_graph_name!==`UntrackedValue`}).map(([e,t])=>e===`__pregel_tasks`&&kC(t)?[e,yI(t,this.channels)]:[e,t])),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(t=>t[0]!==e);for(let[t,n]of i)this.checkpointPendingWrites.push([e,t,n]);for(let[e,t]of i){let n=this.channels[e];n!=null&&nP(n)&&eL(t)}let a=YP(this.checkpointConfig,{[sC]:this.config.configurable?.checkpoint_ns??``,[oC]:this.checkpoint.id});if(this.durability!==`exit`&&this.checkpointer!=null&&this._trackCheckpointerPromise(this.checkpointer.putWrites(a,i,e)),this.tasks&&this._outputWrites(e,n),!t.length||!this.cache||!this.tasks)return;let o=this.tasks[e];o==null||o.cache_key==null||t[0][0]===`__error__`||t[0][0]===`__interrupt__`||this.cache.set([{key:[o.cache_key.ns,o.cache_key.key],value:o.writes,ttl:o.cache_key.ttl}])}_outputWrites(e,t,n=!1){let r=this.tasks[e];if(r!==void 0){if(r.config!==void 0&&(r.config.tags??[]).includes(`langsmith:hidden`))return;if(t.length>0)if(t[0][0]===`__interrupt__`){if(r.path?.[0]===`__pregel_push`&&r.path?.[r.path.length-1]===!0)return;let e=t.filter(e=>e[0]===pC).flatMap(e=>e[1]);this._emit([[`updates`,{[pC]:e}],[`values`,{[pC]:e}]])}else t[0][0]!==`__error__`&&this._emit(PP(MP(eI(this.outputKeys,[[r,t]],n),`updates`)));n||this._emit(PP(MP(DI([[r,t]],this.streamKeys),`tasks`)))}}async _matchCachedWrites(){if(!this.cache)return[];let e=[],t=([e,t])=>`ns:${e.join(`,`)}|key:${t}`,n=[],r={};for(let e of Object.values(this.tasks))e.cache_key!=null&&!e.writes.length&&(n.push([e.cache_key.ns,e.cache_key.key]),r[t([e.cache_key.ns,e.cache_key.key])]=e);if(n.length===0)return[];let i=await this.cache.get(n);for(let{key:n,value:a}of i){let i=r[t(n)];i!=null&&(i.writes.push(...a),e.push({task:i,result:a}))}return e}async tick(e){this.store&&!this.store.isRunning&&await this.store?.start();let{inputKeys:t=[]}=e;if(this.status!==`pending`)throw Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![ZI,QI].includes(this.input))await this._first(t);else if(this.toInterrupt.length>0)throw this.status=`interrupt_before`,new WC;else if(Object.values(this.tasks).every(e=>e.writes.length>0)){let e=Object.values(this.tasks),t=e.flatMap(e=>e.writes);this.updatedChannels=fI(this.checkpoint,this.channels,e,this.checkpointerGetNextVersion,this.triggerToNodes);for(let[e,n]of t){let t=this.channels[e];t!=null&&nP(t)&&MC(n)&&this._deltaChannelsWithOverwrite.add(e)}let n=await NP(MP($F(this.outputKeys,t,this.channels),`values`));if(this._exitDeltaWrites!==void 0)for(let[e,t,n]of this.checkpointPendingWrites){let r=this.channels[t];r!=null&&nP(r)&&this._exitDeltaWrites.push([this.step,e,t,n])}if(this.checkpointPendingWrites=[],await this._putCheckpoint({source:`loop`}),this.durability===`sync`&&await this._awaitCheckpointerPromises(),this._emitValuesWithCheckpointMeta(n),sI(this.checkpoint,this.interruptAfter,e))throw this.status=`interrupt_after`,new WC;this.config.configurable?.__pregel_resuming!==void 0&&delete this.config.configurable?.[QS]}else return!1;if(this.step>this.stop)return this.status=`out_of_steps`,!1;this.tasks=hI(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step,checkpointer:this.checkpointer,isResuming:this.isResuming,manager:this.manager,store:this.store,stream:this.stream,triggerToNodes:this.triggerToNodes,updatedChannels:this.updatedChannels});let n=Object.values(this.tasks);if(this.checkpointer&&(this.stream.modes.has(`checkpoints`)||this.stream.modes.has(`debug`))&&this._emit(await NP(MP(OI(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,n,this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),`checkpoints`))),n.length===0)return this.status=`done`,!1;if(this.control!=null&&this.control.drainRequested)return this.status=`draining`,!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(let[e,t,r]of this.checkpointPendingWrites){if(t===`__error__`||t===`__error_source_node__`||t===`__interrupt__`||t===`__resume__`)continue;let i=n.find(t=>t.id===e);i&&i.writes.push([t,r])}this._resumeErrorHandlersIfApplicable(),n=Object.values(this.tasks);for(let e of n)e.writes.length>0&&this._outputWrites(e.id,e.writes,!0)}if(n.every(e=>e.writes.length>0))return this.tick({inputKeys:t});if(sI(this.checkpoint,this.interruptBefore,n))throw this.status=`interrupt_before`,new WC;if(this.stream.modes.has(`tasks`)||this.stream.modes.has(`debug`)){let e=await NP(MP(wI(n),`tasks`));this._emit(e)}return!0}async finishAndHandleError(e){this.durability===`exit`&&(!this.isNested||e!==void 0||this.checkpointNamespace.every(e=>!e.includes(`:`)))&&(await this._putExitDeltaWrites(),this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());let t=this._suppressInterrupt(e);return(t||e===void 0)&&(this.output=XF(this.channels,this.outputKeys)),t&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(e=>e.writes.length>0)&&(this.updatedChannels=fI(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emitValuesWithCheckpointMeta(PP(MP($F(this.outputKeys,Object.values(this.tasks).flatMap(e=>e.writes),this.channels),`values`)))),XC(e)&&!e.interrupts.length&&this._emit([[`updates`,{[pC]:[]}],[`values`,{[pC]:[]}]],this.#e())),t}async acceptPush(e,t,n){if(this.interruptAfter?.length>0&&sI(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}let r=gI([xC,e.path??[],t,e.id,n],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,e.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!r)return;if(this.interruptBefore?.length>0&&sI(this.checkpoint,this.interruptBefore,[r])){this.toInterrupt.push(r);return}(this.stream.modes.has(`tasks`)||this.stream.modes.has(`debug`))&&this._emit(PP(MP(wI([r]),`tasks`))),this.debug&&jI(this.step,[r]),this.tasks[r.id]=r,this.skipDoneTasks&&this._matchWrites({[r.id]:r});let i=await this._matchCachedWrites();for(let{task:e}of i)this._outputWrites(e.id,e.writes,!0);return r}getErrorHandlerNode(e){return this.nodes[e]?.errorHandlerNode}isErrorHandlerNode(e){return this.nodes[e]?.isErrorHandler===!0}scheduleErrorHandler(e,t){let n=this.getErrorHandlerNode(String(e.name));if(!n)return;let r=_I(e,n,t,this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,e.config??this.config,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(r!==void 0)return this.tasks[r.id]=r,this._emit(PP(MP(wI([r]),`tasks`))),this.debug&&jI(this.step,[r]),r}_resumeErrorHandlersIfApplicable(){let e=new Map;for(let[t,n]of this.checkpointPendingWrites){if(n!==`__error_source_node__`)continue;let r=this.checkpointPendingWrites.find(([e,n])=>e===t&&n===`__error__`);if(r===void 0)continue;let i=r[2],a=Error(i?.message??String(i));i?.name&&(a.name=i.name),e.set(t,a)}for(let[t,n]of e){let e=this.tasks[t];e!==void 0&&this.getErrorHandlerNode(String(e.name))&&(e.writes.length===0&&e.writes.push([WS,{message:n.message,name:n.name}]),this.scheduleErrorHandler(e,n))}}_suppressInterrupt(e){return XC(e)&&!this.isNested}async _first(e){let{configurable:t}=this.config,n=t?.[rC];if(n&&n.nullResume!==void 0&&this.putWrites(CC,[[mC,n.nullResume]]),FC(this.input)){let e=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume==`object`&&Object.keys(this.input.resume).every(JF)&&(this.config.configurable??={},this.config.configurable[nC]=this.input.resume),e&&this.checkpointer==null)throw Error(`Cannot use Command(resume=...) without checkpointer`);let t={};for(let[e,n,r]of ZF(this.input,this.checkpointPendingWrites))t[e]??=[],t[e].push([n,r]);if(Object.keys(t).length===0)throw new QC(`Received empty Command input`);for(let[e,n]of Object.entries(t))this.putWrites(e,n)}let r=(this.checkpointPendingWrites??[]).filter(e=>e[0]===CC).map(e=>e.slice(1));r.length>0&&fI(this.checkpoint,this.channels,[{name:US,writes:r,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);let i=FC(this.input),a=i&&r.length>0,o=this.isReplaying&&(this.isNested&&t?.checkpoint_ns!==void 0&&t?.checkpoint_ns!==``&&t?.checkpoint_map!==void 0&&t.checkpoint_ns in t.checkpoint_map||!(i&&this.input.resume!=null||t?.__pregel_resuming===!0||this.resumeAtHead));o&&(this.checkpointPendingWrites=this.checkpointPendingWrites.filter(e=>e[1]!==mC));let s=this.isResuming;if(s||a){let e={...this.checkpoint.versions_seen[pC]};for(let t in this.channels)Object.prototype.hasOwnProperty.call(this.channels,t)&&this.checkpoint.channel_versions[t]!==void 0&&(e[t]=this.checkpoint.channel_versions[t]);this.checkpoint.versions_seen[pC]=e,o&&this.checkpointMetadata.source!==`update`&&this.checkpointMetadata.source!==`fork`&&(this.checkpointPendingWrites=this.checkpointPendingWrites.filter(e=>e[1]!==pC),await this._putCheckpoint({source:`fork`}));let t=await NP(MP($F(this.outputKeys,!0,this.channels),`values`));s?this.input=QI:a&&(await this._putCheckpoint({source:`input`}),this.input=ZI),this._emitValuesWithCheckpointMeta(t)}else{let t=await NP(QF(e,this.input));if(t.length>0){let e=hI(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=fI(this.checkpoint,this.channels,Object.values(e).concat([{name:US,writes:t,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes);let n=t.filter(([e])=>{let t=this.channels[e];return t!=null&&nP(t)});for(let[e,t]of n)MC(t)&&this._deltaChannelsWithOverwrite.add(e);if(n.length>0)if(this._exitDeltaWrites!==void 0)for(let[e,t]of n)this._exitDeltaWrites.push([this.step,CC,e,t]);else this.checkpointer!=null&&this.putWrites(CC,n);await this._putCheckpoint({source:`input`}),this.input=ZI}else if(`__pregel_resuming`in(this.config.configurable??{}))this.input=ZI;else throw new QC(`Received no input writes for ${JSON.stringify(e,null,2)}`)}if(!this.isNested){let e;if(o){let t=this.checkpoint.id;(this.checkpointMetadata.source===`update`||this.checkpointMetadata.source===`fork`)&&this.prevCheckpointConfig&&(t=this.prevCheckpointConfig.configurable?.checkpoint_id??t),e=new XI(t)}this.config=YP(this.config,{[QS]:this.isResuming,[dC]:e})}}#e(){let e=this.checkpointNamespace;if(!(e.length===0||e.length===1&&e[0]===``)||this.config.configurable?.__pregel_stream===void 0)return e;let t=nL(this.config.configurable?.[uC]);return t.length>0?t:e}_emit(e,t=this.checkpointNamespace){for(let[n,r]of e)if(this.stream.modes.has(n)&&this.stream.push([t,n,r]),(n===`checkpoints`||n===`tasks`)&&this.stream.modes.has(`debug`)){let e=n===`checkpoints`?this.step-1:this.step,i=new Date().toISOString(),a=n===`checkpoints`?`checkpoint`:typeof r==`object`&&r&&`result`in r?`task_result`:`task`;this.stream.push([t,`debug`,{step:e,type:a,timestamp:i,payload:r}])}}_currentCheckpointMeta(){if(!this.checkpointMetadata||!this.checkpoint?.id)return;let e=this.prevCheckpointConfig?.configurable?.checkpoint_id;return{checkpoint:{id:this.checkpoint.id,...e?{parent_id:e}:{},step:this.checkpointMetadata.step,source:this.checkpointMetadata.source}}}_emitValuesWithCheckpointMeta(e){let t=this._currentCheckpointMeta();for(let[n,r]of e)n===`values`&&t?.checkpoint!=null&&!this.stream.modes.has(`checkpoints`)&&this.stream.push([this.checkpointNamespace,`checkpoints`,t.checkpoint]),this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,r])}_putCheckpoint(e){let t=this.checkpointMetadata===e,n=this.checkpointer!=null&&(this.durability!==`exit`||t),r=e=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=YP(this.checkpointConfig,{[sC]:this.config.configurable?.checkpoint_ns??``});let t={...this.checkpoint.channel_versions},n=qP(this.checkpointPreviousVersions,t);this.checkpointPreviousVersions=t,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:WN(e),metadata:{...this.checkpointMetadata},newVersions:n}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}},i;if(t)i={...this.checkpointMetadata.counters_since_delta_snapshot??{}};else{let t=this.checkpointMetadata.counters_since_delta_snapshot??{};i={};let n=this.updatedChannels??new Set;for(let e in this.channels){if(!Object.prototype.hasOwnProperty.call(this.channels,e)||!nP(this.channels[e]))continue;let[r,a]=t[e]??[0,0];i[e]=[n.has(e)?r+1:r,a+1]}this.checkpointMetadata={...e,step:this.step,parents:this.config.configurable?.checkpoint_map??{}}}let a=n?lP(this.channels,i):new Set;if(n)for(let e of this._deltaChannelsWithOverwrite)a.add(e);this.checkpoint=uP(this.checkpoint,n?this.channels:void 0,this.step,{id:t?this.checkpoint.id:void 0,channelsToSnapshot:a,updatedChannels:this.updatedChannels,getNextVersion:n?e=>this.checkpointerGetNextVersion(e):void 0});for(let e of a)i[e]=[0,0],this._deltaChannelsWithOverwrite.delete(e);let o={};for(let e in i){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let[t,n]=i[e];(t!==0||n!==0)&&(o[e]=[t,n])}Object.keys(o).length>0?this.checkpointMetadata.counters_since_delta_snapshot=o:delete this.checkpointMetadata.counters_since_delta_snapshot,n&&r(this.checkpoint),t||(this.step+=1)}async _putExitDeltaWrites(){if(this._exitDeltaWrites===void 0||this._exitDeltaWrites.length===0||this.checkpointer==null||this._initialCheckpointConfig===void 0)return;let e=this.checkpointMetadata.counters_since_delta_snapshot??{},t=lP(this.channels,e);for(let e of this._deltaChannelsWithOverwrite)t.add(e);let n=this._exitDeltaWrites.filter(([,,e])=>!t.has(e));if(n.length===0)return;let r;if(this._hasPersistedParent)r=this._initialCheckpointConfig;else{let e=UN();e.id=this.checkpointIdSaved??e.id,e.ts=new Date().toISOString();let t=YP(this._initialCheckpointConfig,{[oC]:void 0});r=YP(this._initialCheckpointConfig,{[oC]:e.id}),this._trackCheckpointerPromise(this.checkpointer.put(t,e,{source:`loop`,step:-2,parents:{}},{})),this.checkpointConfig=r}let i=YP(r,{[sC]:this.config.configurable?.checkpoint_ns??``,[oC]:r.configurable?.[oC]}),a=new Map,o=[];for(let[e,t,r,i]of n){let n=`${e}\u0000${t}`,s=a.get(n);s===void 0&&(s=[],a.set(n,s),o.push({key:n,step:e,tid:t})),s.push([r,i])}for(let{key:e,step:t,tid:n}of o){let r=cP(t,n);this._trackCheckpointerPromise(this.checkpointer.putWrites(i,a.get(e),r))}}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;let e=YP(this.checkpointConfig,{[sC]:this.config.configurable?.checkpoint_ns??``,[oC]:this.checkpoint.id}),t={};for(let[e,n,r]of this.checkpointPendingWrites)t[e]??=[],t[e].push([n,r]);for(let[n,r]of Object.entries(t))this._trackCheckpointerPromise(this.checkpointer.putWrites(e,r,n))}_matchWrites(e){for(let[t,n,r]of this.checkpointPendingWrites){if(n===`__error__`||n===`__interrupt__`||n===`__resume__`)continue;let i=Object.values(e).find(e=>e.id===t);i&&i.writes.push([n,r])}for(let t of Object.values(e))t.writes.length>0&&this._outputWrites(t.id,t.writes,!0)}};function aL(e){return Kt(e?.message)}function oL(e,t,n){if(!e)return;let r=e.langgraph_checkpoint_ns,i=e.checkpoint_ns,a=r??i;if(a)return[a.split(`|`),{tags:t,name:n,...e}]}var sL=class extends hi{name=`StreamMessagesHandler`;streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(e){super(),this.streamFn=e}_emit(e,t,n,r=!1){if(r&&t.id!==void 0&&this.seen[t.id]!==void 0)return;let i=t.id;n!=null&&($t(t)?i??=`run-${n}-tool-${t.tool_call_id}`:((i==null||i===`run-${n}`)&&(i=this.stableMessageIdMap[n]??i??`run-${n}`),this.stableMessageIdMap[n]??=i)),i!==t.id&&(t.id=i,t.lc_kwargs.id=i),t.id!=null&&(this.seen[t.id]=t),this.streamFn([e[0],`messages`,[t,e[1]]])}handleChatModelStart(e,t,n,r,i,a,o,s){o&&(!a||!a.includes(`langsmith:nostream`)&&!a.includes(`nostream`))&&(this.metadatas[n]=oL(o,a,s))}handleLLMNewToken(e,t,n,r,i,a){let o=a?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(aL(o)?this._emit(this.metadatas[n],o.message,n):this._emit(this.metadatas[n],new Nn({content:e}),n))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){let n=e.generations?.[0]?.[0];Kt(n?.message)&&this._emit(this.metadatas[t],n?.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,n,r,i,a,o,s){if(a!==void 0&&s===a.langgraph_node&&(i===void 0||!i.includes(`langsmith:hidden`))&&(this.metadatas[n]=oL(a,i,s),typeof t==`object`)){for(let e of Object.values(t))if((Kt(e)||qt(e))&&e.id!==void 0)this.seen[e.id]=e;else if(Array.isArray(e))for(let t of e)(Kt(t)||qt(t))&&t.id!==void 0&&(this.seen[t.id]=t)}}handleChainEnd(e,t){let n=this.metadatas[t];if(delete this.metadatas[t],n!==void 0){if(Kt(e))this._emit(n,e,t,!0);else if(Array.isArray(e))for(let r of e)Kt(r)&&this._emit(n,r,t,!0);else if(typeof e==`object`&&e){for(let r of Object.values(e))if(Kt(r))this._emit(n,r,t,!0);else if(Array.isArray(r))for(let e of r)Kt(e)&&this._emit(n,e,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}};function cL(e){if(`response_metadata`in e&&typeof e.response_metadata==`object`&&e.response_metadata!=null)return e.response_metadata}function lL(e){if(`usage_metadata`in e&&typeof e.usage_metadata==`object`&&e.usage_metadata!=null)return e.usage_metadata}function uL(e){switch(e.type){case`text`:return{type:`text`,text:``};case`reasoning`:return{type:`reasoning`,reasoning:``};case`tool_call`:case`tool_call_chunk`:return{type:`tool_call_chunk`,...e.id==null?{}:{id:e.id},...e.name==null?{}:{name:e.name},args:``};default:return e}}function dL(e){switch(e.type){case`text`:{let t=typeof e.text==`string`?e.text:``;return t.length>0?{event:`content-block-delta`,index:typeof e.index==`number`?e.index:0,delta:{type:`text-delta`,text:t}}:void 0}case`reasoning`:{let t=typeof e.reasoning==`string`?e.reasoning:``;return t.length>0?{event:`content-block-delta`,index:typeof e.index==`number`?e.index:0,delta:{type:`reasoning-delta`,reasoning:t}}:void 0}case`tool_call_chunk`:return{event:`content-block-delta`,index:typeof e.index==`number`?e.index:0,delta:{type:`block-delta`,fields:{...e,type:`tool_call_chunk`}}};default:return}}var fL=class extends hi{name=`StreamProtocolMessagesHandler`;streamFn;metadatas={};seen={};streamedRunIds=new Set;stableMessageIdMap={};lc_prefer_chat_model_stream_events=!0;awaitHandlers=!0;constructor(e){super(),this.streamFn=e}normalizeMessageId(e,t){let n=e.id;return t!=null&&(Xt.isInstance(e)?n??=`run-${t}-tool-${e.tool_call_id}`:((n==null||n===`run-${t}`)&&(n=this.stableMessageIdMap[t]??n??`run-${t}`),this.stableMessageIdMap[t]??=n)),n!==e.id&&(e.id=n,e.lc_kwargs.id=n),e.id!=null&&(this.seen[e.id]=e),e.id}emit(e,t,n){let r=n==null?e[1]:{...e[1],run_id:n};this.streamFn([e[0],`messages`,[t,r]])}emitFinalMessage(e,t,n,r=!1){let i=t.id??(n==null?void 0:this.stableMessageIdMap[n]);if(r&&i!=null&&this.seen[i]!==void 0)return;let a=this.normalizeMessageId(t,n),o=t.type===`human`?`human`:t.type===`system`?`system`:t.type===`tool`?`tool`:`ai`,s=o===`tool`&&Xt.isInstance(t)?t.tool_call_id:void 0;this.emit(e,{event:`message-start`,...a==null?{}:{id:a},...o===`ai`?{}:{role:o},...typeof s==`string`?{tool_call_id:s}:{}},n),(Array.isArray(t.content)?t.content:typeof t.content==`string`&&t.content.length>0?[{type:`text`,text:t.content}]:[]).forEach((t,r)=>{let i=typeof t.index==`number`?t.index:r;this.emit(e,{event:`content-block-start`,index:i,content:uL(t)},n);let a=dL({...t,index:i});a!=null&&this.emit(e,a,n),this.emit(e,{event:`content-block-finish`,index:i,content:t},n)}),this.emit(e,{event:`message-finish`,...lL(t)==null?{}:{usage:lL(t)},...cL(t)==null?{}:{responseMetadata:cL(t)}},n)}handleChatModelStart(e,t,n,r,i,a,o,s){o&&(!a||!a.includes(`langsmith:nostream`)&&!a.includes(`nostream`))&&(this.metadatas[n]=[o.langgraph_checkpoint_ns.split(`|`),{tags:a,name:s,...o}])}handleLLMNewToken(){}handleChatModelStreamEvent(e,t){let n=this.metadatas[t];if(n===void 0)return;let r=e;if(e.event===`message-start`){this.streamedRunIds.add(t);let n=e.id??`run-${t}`;this.seen[n]=!0,this.stableMessageIdMap[t]??=n,e.id??(r={...e,id:n})}this.emit(n,r,t)}handleLLMEnd(e,t){let n=this.metadatas[t];if(n===void 0)return;let r=e.generations?.[0]?.[0],i=Mt.isInstance(r?.message)?r.message:void 0;if(i!=null)if(this.streamedRunIds.has(t)){let e=this.normalizeMessageId(i,t);e!=null&&(this.seen[e]=i)}else this.emitFinalMessage(n,i,t,!0);this.streamedRunIds.delete(t),delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleLLMError(e,t){this.streamedRunIds.delete(t),delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleChainStart(e,t,n,r,i,a,o,s){if(a!==void 0&&s===a.langgraph_node&&(i===void 0||!i.includes(`langsmith:hidden`))&&(this.metadatas[n]=[a.langgraph_checkpoint_ns.split(`|`),{tags:i,name:s,...a}],typeof t==`object`)){for(let e of Object.values(t))if((Mt.isInstance(e)||Wt.isInstance(e))&&e.id!==void 0)this.seen[e.id]=e;else if(Array.isArray(e))for(let t of e)(Mt.isInstance(t)||Wt.isInstance(t))&&t.id!==void 0&&(this.seen[t.id]=t)}}handleChainEnd(e,t){let n=this.metadatas[t];if(delete this.metadatas[t],n===void 0)return;let r=e=>{Mt.isInstance(e)&&!Xt.isInstance(e)&&this.emitFinalMessage(n,e,t,!0)};if(Mt.isInstance(e))r(e);else if(Array.isArray(e))for(let t of e)r(t);else if(typeof e==`object`&&e)for(let t of Object.values(e))if(Array.isArray(t))for(let e of t)r(e);else r(t);delete this.stableMessageIdMap[t]}handleChainError(e,t){delete this.metadatas[t],delete this.stableMessageIdMap[t]}},pL=class{active=!0;lastProgress=Date.now();refreshOn;constructor(e){this.refreshOn=e}touch(){this.lastProgress=Date.now()}autoTouch(){this.refreshOn===`auto`&&(this.lastProgress=Date.now())}close(){this.active=!1}},mL=class extends hi{name=`IdleProgressCallbackHandler`;awaitHandlers=!1;#e;constructor(e){super(),this.#e=e}#t=()=>{this.#e.autoTouch()};handleLLMStart=this.#t;handleChatModelStart=this.#t;handleLLMNewToken=this.#t;handleLLMEnd=this.#t;handleLLMError=this.#t;handleChainStart=this.#t;handleChainEnd=this.#t;handleChainError=this.#t;handleToolStart=this.#t;handleToolEnd=this.#t;handleToolError=this.#t;handleText=this.#t;handleRetrieverStart=this.#t;handleRetrieverEnd=this.#t;handleRetrieverError=this.#t;handleCustomEvent=this.#t};function hL(e,t,n,r){let i=e.configurable??{},a={},o=i[JS];typeof o==`function`&&(a[JS]=e=>{if(t.active)return e&&e.length&&t.autoTouch(),o(e)});let s=i[YS];typeof s==`function`&&(a[YS]=(...e)=>{if(!t.active)throw Error(`Node "${r}" attempt was cancelled after its timeout fired`);return t.autoTouch(),s(...e)});let c={...Object.keys(a).length>0?YP(e,a):e};if(c.heartbeat=()=>{n.idleTimeout!==void 0&&t.touch()},typeof c.writer==`function`){let e=c.writer;c.writer=(n=>{if(t.active)return t.autoTouch(),e(n)})}if((n.refreshOn??`auto`)===`auto`&&n.idleTimeout!==void 0){let e=new mL(t),n=c.callbacks;if(n===void 0)c.callbacks=[e];else if(Array.isArray(n))c.callbacks=[...n,e];else{let t=n.copy();t.addHandler(e,!0),c.callbacks=t}}return c}async function gL(e,t,n,r){let i=new pL(n.refreshOn??`auto`),a=new AbortController,{signal:o,dispose:s}=ZP(t.signal,a.signal),c=hL({...t,signal:o},i,n,String(e.name)),l=Date.now(),u=r(c).then(e=>({type:`ok`,value:e}),e=>({type:`err`,error:e})),d,f,p=()=>{d!==void 0&&clearTimeout(d),f!==void 0&&clearTimeout(f)},m=new Promise(e=>{if(n.runTimeout!==void 0&&(d=setTimeout(()=>e({type:`timeout`,kind:`run`}),n.runTimeout)),n.idleTimeout!==void 0){let t=n.idleTimeout,r=()=>{let n=i.lastProgress+t-Date.now();n<=0?e({type:`timeout`,kind:`idle`}):f=setTimeout(r,n)};f=setTimeout(r,t)}}),h;try{h=await Promise.race([u,m])}finally{p()}if(h.type!==`timeout`){let e=Date.now();n.runTimeout!==void 0&&e-l>=n.runTimeout?h={type:`timeout`,kind:`run`}:n.idleTimeout!==void 0&&e-i.lastProgress>=n.idleTimeout&&(h={type:`timeout`,kind:`idle`})}if(h.type===`ok`)return s?.(),h.value;if(h.type===`err`)throw s?.(),h.error;let g=Date.now()-l;throw i.close(),e.writes.splice(0,e.writes.length),a.abort(),s?.(),new ZC({node:String(e.name),elapsed:g,kind:h.kind,runTimeout:n.runTimeout,idleTimeout:n.idleTimeout})}var _L=[400,401,402,403,404,405,406,407,409],vL=e=>{if(e.message.startsWith(`Cancel`)||e.message.startsWith(`AbortError`)||e.name===`AbortError`||e.name===`GraphValueError`||e?.code===`ECONNABORTED`)return!1;let t=e?.response?.status??e?.status;return!(t&&_L.includes(+t)||e?.error?.code===`insufficient_quota`)};async function yL(e,t,n,r){let i=e.retry_policy??t,a=0,o,s,c=e.config??{};n&&(c=YP(c,n)),c={...c,signal:r};let l=Date.now();for(c.executionInfo!=null&&(c.executionInfo={...c.executionInfo,nodeFirstAttemptTime:l});!r?.aborted;){e.writes.splice(0,e.writes.length),o=void 0;try{s=e.timeout===void 0?await e.proc.invoke(e.input,c):await gL(e,c,e.timeout,t=>e.proc.invoke(e.input,t));break}catch(t){if(o=t,o.pregelTaskId=e.id,JC(o)){let t=c?.configurable?.checkpoint_ns,n=o.command;if(n.graph===t){for(let t of e.writers)await t.invoke(n,c);o=void 0;break}else if(n.graph===PC.PARENT){let e=AP(t);o.command=new PC({...o.command,graph:e})}}if(YC(o)||i===void 0||(a+=1,a>=(i.maxAttempts??3))||!(i.retryOn??vL)(o))break;let n=i.initialInterval??500,r=Math.min(i.maxInterval??128e3,n*(i.backoffFactor??2)**(a-1)),s=i.jitter??!0?r+Math.random()*1e3:r;await new Promise(e=>setTimeout(e,s));let u=o.name??o.constructor.unminifiable_name??o.constructor.name;(i?.logWarning??!0)&&console.log(`Retrying task "${String(e.name)}" after ${s.toFixed(2)}ms (attempt ${a}) after ${u}: ${o}`),c=YP(c,{[QS]:!0}),c.executionInfo!=null&&(c.executionInfo={...c.executionInfo,nodeAttempt:a+1,nodeFirstAttemptTime:l})}}return{task:e,result:s,error:o,signalAborted:r?.aborted}}var bL=Symbol.for(`promiseAdded`);function xL(){let e={next:()=>void 0,wait:Promise.resolve(bL)};function t(n){e.next=()=>{e.wait=new Promise(t),n(bL)}}return e.wait=new Promise(t),e}var SL=class{nodeFinished;loop;handledExceptions=new WeakSet;constructor({loop:e,nodeFinished:t}){this.loop=e,this.nodeFinished=t}async tick(e={}){let{timeout:t,retryPolicy:n,onStepWrite:r,maxConcurrency:i}=e,a=new Set,o,s=new AbortController,c=s.signal,l=t?AbortSignal.timeout(t):void 0,u=Object.values(this.loop.tasks),d=u.filter(e=>e.writes.length===0),{signals:f,disposeCombinedSignal:p}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:l,signal:e.signal}),m=this._executeTasksWithRetry(d,{signals:f,retryPolicy:n,maxConcurrency:i});for await(let{task:e,error:t,signalAborted:n}of m)this._commit(e,t),!(t!==void 0&&this.handledExceptions.has(t))&&(XC(t)||YC(t)&&!XC(o)?o=t:t&&(a.size===0||!n)&&(s.abort(),a.add(t)));if(p?.(),r?.(this.loop.step,u.map(e=>e.writes).flat()),a.size===1)throw Array.from(a)[0];if(a.size>1)throw AggregateError(Array.from(a),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(XC(o)||UC(o)||YC(o)&&this.loop.isNested)throw o}_initializeAbortSignals({exceptionSignal:e,stepTimeoutSignal:t,signal:n}){let r=this.loop.config.configurable?.__pregel_abort_signals??{},i=r.externalAbortSignal??n,a=t??r.timeoutAbortSignal,{signal:o,dispose:s}=ZP(i,a,e),c={externalAbortSignal:i,timeoutAbortSignal:a,composedAbortSignal:o};return this.loop.config=YP(this.loop.config,{[fC]:c}),{signals:c,disposeCombinedSignal:s}}async*_executeTasksWithRetry(e,t){let{retryPolicy:n,maxConcurrency:r,signals:i}=t??{},a=xL(),o={},s={executingTasksMap:o,barrier:a,retryPolicy:n,scheduleTask:async(e,t,n)=>this.loop.acceptPush(e,t,n)};if(i?.composedAbortSignal?.aborted)throw Error(`Abort`);let c=0,l,u=ZP(i?.externalAbortSignal,i?.timeoutAbortSignal),d=u.signal?new Promise((e,t)=>{l=()=>t(Error(`Abort`)),u.signal?.addEventListener(`abort`,l,{once:!0})}):void 0;for(;(c===0||Object.keys(o).length>0)&&e.length;){for(;Object.values(o).length<(r??e.length)&&c<e.length;c+=1){let t=e[c];o[t.id]=yL(t,n,{[YS]:CL?.bind(s,this,t)},i?.composedAbortSignal).catch(e=>({task:t,error:e,signalAborted:i?.composedAbortSignal?.aborted}))}let t=await Promise.race([...Object.values(o),...d?[d]:[],a.wait]);if(t===bL)continue;let f=t,{task:p,error:m}=f;if(m!==void 0&&!YC(m)&&!this.loop.isErrorHandlerNode(String(p.name))&&this.loop.getErrorHandlerNode(String(p.name))!==void 0){let e=this.loop.scheduleErrorHandler(p,m);e!==void 0&&(o[e.id]=yL(e,n,{[YS]:CL?.bind(s,this,e)},i?.composedAbortSignal).catch(t=>({task:e,error:t,signalAborted:i?.composedAbortSignal?.aborted})),a.next())}yield f,l!=null&&(u.signal?.removeEventListener(`abort`,l),u.dispose?.()),delete o[t.task.id]}}_shouldRouteToErrorHandler(e){let t=String(e.name);return!this.loop.isErrorHandlerNode(t)&&this.loop.getErrorHandlerNode(t)!==void 0}_commit(e,t){if(t!==void 0)if(XC(t)){if(t.interrupts.length){let n=t.interrupts.map(e=>[pC,e]),r=e.writes.filter(e=>e[0]===mC);r.length&&n.push(...r),this.loop.putWrites(e.id,n)}}else UC(t)?e.writes.length&&this.loop.putWrites(e.id,e.writes):YC(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):(e.writes.push([WS,{message:t.message,name:t.name}]),this._shouldRouteToErrorHandler(e)&&(e.writes.push([GS,String(e.name)]),this.handledExceptions.add(t)),this.loop.putWrites(e.id,e.writes));else this.nodeFinished&&(e.config?.tags==null||!e.config.tags.includes(`langsmith:hidden`))&&this.nodeFinished(String(e.name)),e.writes.length===0&&e.writes.push([hC,null]),this.loop.putWrites(e.id,e.writes)}};async function CL(e,t,n,r,i,a={}){let o=t.config?.configurable?.[rC];if(!o)throw Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);let s=o.callCounter;o.callCounter+=1;let c=new tI({func:n,name:r,input:i,cache:a.cache,retry:a.retry,timeout:a.timeout,callbacks:a.callbacks}),l=await this.scheduleTask(t,s,c);if(!l)return;let u=this.executingTasksMap[l.id];if(u!==void 0)return u;if(l.writes.length>0){let e=l.writes.filter(([e])=>e===gC),t=l.writes.filter(([e])=>e===WS);if(e.length>0){if(e.length===1)return Promise.resolve(e[0][1]);throw Error(`BUG: multiple returns found for task ${l.name}__${l.id}`)}if(t.length>0){if(t.length===1){let e=t[0][1],n=e instanceof Error?e:Error(String(e));return Promise.reject(n)}throw Error(`BUG: multiple errors found for task ${l.name}__${l.id}`)}return}else{let t=yL(l,a.retry,{[YS]:CL.bind(this,e,l)});return this.executingTasksMap[l.id]=t,this.barrier.next(),t.then(({result:e,error:t})=>t?Promise.reject(t):e)}}var wL=Symbol.for(`langgraph.stream_channel`),TL=class e{[wL]=!0;channelName;#e=[];#t=[];#n=!1;#r;#i;constructor(e){this.channelName=e}static local(){return new e}static remote(t){return new e(t)}static isInstance(e){return typeof e==`object`&&!!e&&wL in e&&e[wL]===!0}push(e){this.#e.push(e),this.#a(),this.#i?.(e)}iterate(e=0){let t=e;return{next:async()=>{for(;;){if(t<this.#e.length)return{value:this.#e[t++],done:!1};if(this.#n){if(this.#r)throw this.#r;return{value:void 0,done:!0}}await new Promise(e=>this.#t.push(e))}}}}toAsyncIterable(e=0){return{[Symbol.asyncIterator]:()=>this.iterate(e)}}toEventStream(e={}){let t=new TextEncoder,n=this.iterate(e.startAt),r=e.event??this.channelName,i=e.serialize??(e=>JSON.stringify(e)??`null`);return new ReadableStream({async pull(e){try{let a=await n.next();if(a.done){e.close();return}let o=[];r!=null&&o.push(`event: ${r}`);for(let e of i(a.value).split(/\r\n|\r|\n/))o.push(`data: ${e}`);e.enqueue(t.encode(`${o.join(`
|
|
188
|
-
`)}\n\n`))}catch(t){e.error(t)}},async cancel(){await n.return?.()}})}get(e){if(e<0||e>=this.#e.length)throw RangeError(`StreamChannel index ${e} out of bounds (size=${this.#e.length})`);return this.#e[e]}get size(){return this.#e.length}get done(){return this.#n}close(){this.#n=!0,this.#a()}fail(e){this.#r=e,this.#n=!0,this.#a()}_wire(e){this.#i=e}_close(){this.close()}_fail(e){this.fail(e)}[Symbol.asyncIterator](){return this.iterate()}#a(){let e=this.#t.splice(0);for(let t of e)t()}};function EL(e){return TL.isInstance(e)}var DL=`custom:`;function OL(e){return`${DL}${e}`}function kL(e){return e!=null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}var AL=Symbol(`resolveValues`),jL=Symbol(`rejectValues`),ML=class{_events=TL.local();_discoveries=TL.local();#e=0;#t=!1;#n;#r=!1;#i=[];#a=[];#o=[];#s=new Map;#c=new Map;#l=[];#u=[];register(e,t){this.#s.set(PL(e),t)}addTransformer(e){let t=this._events.size;this.#a.push(e),e.onRegister&&e.onRegister({push:(e,t)=>this.push(e,t)});for(let n=0;n<t;n+=1)e.process(this._events.get(n));this.#t&&(this.#n===void 0?e.finalize?.():e.fail?.(this.#n))}wireChannels(e){for(let[t,n]of Object.entries(e)){if(EL(n)){if(this.#o.push(n),typeof n.channelName!=`string`)continue;let e=OL(n.channelName);n._wire(t=>{this._events.push({type:`event`,seq:this.#e++,method:e,params:{namespace:this.#i,timestamp:Date.now(),data:t}})});continue}kL(n)&&this.#u.push({name:t,promise:Promise.resolve(n)})}}push(e,t){t.method===`values`&&this.#c.set(PL(e),t.params.data);let n=this.#i;this.#i=e;let r=!0;for(let e of this.#a)e.process(t)||(r=!1);this.#i=n,r&&this._events.push({...t,seq:this.#e++})}close(){this.#t=!0;for(let[e,t]of this.#c.entries()){let n=e?e.split(`\0`):[];this.#s.get(PL(n))?.[AL](t)}let e=[];for(let t of this.#a){let n=t.finalize?.();n!=null&&typeof n.then==`function`&&e.push(n)}for(let e of this.#o)e._close();let t=this.#u;t.length===0&&e.length===0?(this._events.close(),this._discoveries.close()):Promise.allSettled([...e,...t.map(async({name:e,promise:t})=>{try{let n=await t;this._events.done||this._events.push({type:`event`,seq:this.#e++,method:`custom`,params:{namespace:[],timestamp:Date.now(),data:{name:e,payload:n}}})}catch{}})]).then(()=>{this._events.close(),this._discoveries.close()});for(let e of this.#s.values())e[AL](void 0)}fail(e){this.#t=!0,this.#n=e;for(let t of this.#a)t.fail?.(e);for(let t of this.#o)t._fail(e);this._events.fail(e),this._discoveries.fail(e);for(let t of this.#s.values())t[jL](e)}markInterrupted(e){this.#r=!0,this.#l.push(...e)}get interrupted(){return this.#r}get interrupts(){return this.#l}subscribeEvents(e,t=0){let n=this._events.iterate(t);return{async next(){for(;;){let t=await n.next();if(t.done||FL(t.value.params.namespace,e))return t}}}}};async function NL(e,t){let n=0;try{for await(let r of e){let[e,i,a]=r;if(i===`values`&&NC(a)){let e=a[pC];t.markInterrupted(e.map(e=>({interruptId:e.id??``,payload:e.value})))}let o=II({namespace:e,mode:i,payload:a,seq:n});n+=o.length;for(let n of o)t.push(e,n)}}catch(e){t.fail(e);return}t.close()}function PL(e){return e.join(`\0`)}function FL(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n+=1)if(e[n]!==t[n])return!1;return!0}function IL(e,t,n=0){return{[Symbol.asyncIterator](){let r=e.iterate(n);return{async next(){for(;;){let e=await r.next();if(e.done)return{value:void 0,done:!0};if(FL(e.value.namespace,t))return{value:e.value,done:!1}}}}}}}var LL=`root`;function RL(e){if(e.length===0)return LL;let t=e[e.length-1],n=t.indexOf(`:`);return n===-1?t:t.slice(0,n)}function zL(e){if(e instanceof Error)return e.message;if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function BL(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function VL(e){if(!BL(e)||e.event!==`started`)return;let t=e.cause;if(BL(t)&&typeof t.type==`string`)return t}function HL(e){if(BL(e)&&`result`in e&&typeof e.name==`string`&&typeof e.id==`string`&&!e.name.startsWith(`__`))return{name:e.name,id:e.id}}function UL(e={}){let t=e.rootGraphName??LL,n=e.initialStatus??`running`,r=e.emitRootOnRegister??!0,i=e.getGraphName??RL,a=e.serializeError??zL,o=e.getTerminalStatusOverride,s=TL.local(),c=new Map,l=new Map,u=new Map,d=new Map,f=new Set,p=[],m,h=0,g=!1,_=e=>{if(e.length===0)return t;let n=u.get(PL(e));return typeof n==`string`&&n.length>0?n:i(e)},v=(e,t)=>{let n=PL(e);if(u.has(n))return;let r=(BL(t)&&BL(t.metadata)?t.metadata:void 0)?.lc_agent_name;u.set(n,typeof r==`string`?r:void 0)},y=e=>{if(!BL(e))return;let t=e.id;if(typeof t!=`string`)return;let n=e.input,r;if(BL(n)&&BL(n.tool_call)){let e=n.tool_call.id;typeof e==`string`&&(r=e)}else if(Array.isArray(n)){for(let e of n)if(BL(e)&&typeof e.id==`string`){r=e.id;break}}r!=null&&d.set(t,r)},b=e=>{if(e.length===0)return;let t=u.get(PL(e));if(typeof t!=`string`||t.length===0)return;let n=e[e.length-1],r=n.indexOf(`:`);if(r===-1)return;let i=n.slice(r+1);if(i.length===0)return;let a=d.get(i);if(!(typeof a!=`string`||a.length===0))return{type:`toolCall`,tool_call_id:a}},ee=e=>l.get(PL(e))??b(e),te=(e,t,n)=>{let i=PL(e),a=c.get(i),o=a?.graphName??_(e);if(a!=null&&a.status===t&&a.graphName===o&&n?.error==null)return;a==null?(a={namespace:e,graphName:o,status:t},c.set(i,a)):a.status=t;let l={event:t,graph_name:o,...n?.cause==null?{}:{cause:n.cause},...n?.error==null?{}:{error:n.error}},u=Date.now();if(s.push({namespace:e,timestamp:u,...l}),!(e.length===0&&!r)&&m!=null){h+=1;try{m.push(e,{type:`event`,seq:0,method:`lifecycle`,params:{namespace:e,timestamp:u,data:l}})}finally{--h}}},ne=e=>{let t=PL(e),n=c.get(t);return n??(n={namespace:e,graphName:_(e),status:void 0},c.set(t,n)),n},x=()=>{if(p.length===0)return;let e=p.splice(0,p.length);for(let t of e){let e=PL(t.namespace),n=c.get(e);n==null||n.status!==`started`||te(t.namespace,`completed`)}},re=e=>{let t=PL(e.namespace),n=c.get(t);n==null||n.status!==`started`||p.some(e=>PL(e.namespace)===t)||p.push(e)},ie=(e,t)=>{for(let n=p.length-1;n>=0;--n){let r=p[n];r.source.type===`node`&&r.source.node===t&&PL(r.source.parent)===PL(e)&&p.splice(n,1)}},ae=e=>{for(let t=1;t<=e.length;t+=1){let n=e.slice(0,t),r=PL(n);if(c.has(r))continue;ne(n);let i=ee(n);te(n,`started`,i==null?void 0:{cause:i})}},oe=()=>f.size>0?`interrupted`:`completed`,se=e=>{for(let t of c.values())t.namespace.length!==0&&t.status===`started`&&te(t.namespace,e);te([],e),s.close()},ce=async()=>{if(o==null)return oe();try{return await o()??oe()}catch{return oe()}},le=(e,t)=>{let n=`${t}:`;for(let r of c.values()){if(r.namespace.length!==e.length+1||r.status!==`started`||!FL(r.namespace,e))continue;let i=r.namespace[r.namespace.length-1];if(i===t||i.startsWith(n))return r.namespace}},S=(e,t)=>{let n=[...e,`${t.name}:${t.id}`];return c.get(PL(n))?.status===`started`?n:void 0};return{__native:!0,init(){return{_lifecycleLog:s,lifecycle:IL(s,[],0)}},onRegister(e){m=e,ne([]),r&&te([],n)},process(e){let t=e.params.namespace;if(h>0)return!0;let n=e.method===`tasks`?HL(e.params.data):void 0;if(n==null?e.method===`tasks`&&(v(t,e.params.data),y(e.params.data)):ie(t,n.name),x(),e.method===`lifecycle`){let n=VL(e.params.data);return n!=null&&l.set(PL(t),n),ae(t),!1}if(ae(t),e.method===`input`&&BL(e.params.data)&&e.params.data.event===`requested`){let t=e.params.data.id;typeof t==`string`&&f.add(t)}if(n!=null){let e=S(t,n);e!=null&&re({namespace:e,source:{type:`task`}})}if(e.method===`updates`){let n=e.params.node;if(typeof n==`string`&&!n.startsWith(`__`)){let e=le(t,n);e!=null&&re({namespace:e,source:{type:`node`,parent:t,node:n}})}}return!0},finalize(){if(!g){if(g=!0,x(),o==null){se(oe());return}return ce().then(se).catch(e=>{s.fail(e)})}},fail(e){if(g)return;g=!0;let t=a(e);for(let e of c.values())e.namespace.length!==0&&e.status===`started`&&te(e.namespace,`failed`);te([],`failed`,{error:t}),s.fail(e)}}}function WL(e){let t=e;return typeof t.run_id==`string`?`run:${t.run_id}`:e.event===`message-start`&&typeof t.id==`string`?`message:${t.id}`:`__default__`}function GL(e,t){let n=TL.local(),r=new Map,i=new Set;return{init:()=>({messages:n.toAsyncIterable()}),process(a){if(a.method!==`messages`||!FL(a.params.namespace,e)||a.params.namespace.length!==e.length+1||t!==void 0&&a.params.node!==t)return!0;let o=a.params.data;switch(o.event){case`message-start`:{let e=WL(o);if(o.role===`tool`){i.add(e);break}let t=TL.local(),s=Object.assign(new HE(t.toAsyncIterable()),{namespace:a.params.namespace,node:a.params.node});r.set(e,{source:t,stream:s}),t.push(o),n.push(s);break}case`content-block-start`:case`content-block-delta`:case`content-block-finish`:if(i.has(WL(o)))break;r.get(WL(o))?.source.push(o);break;case`message-finish`:{let e=WL(o);if(i.delete(e))break;let t=r.get(e);t&&(t.source.push(o),t.source.close(),r.delete(e));break}case`error`:if(i.has(WL(o)))break;r.get(WL(o))?.source.push(o);break}return!0},finalize(){for(let[e,t]of r)t.source.push({event:`message-finish`}),t.source.close(),r.delete(e);i.clear(),n.close()},fail(e){for(let[t,n]of r)n.source.fail(e),r.delete(t);i.clear(),n.fail(e)}}}function KL(e,t,n=0){let r=t.length+1;return{[Symbol.asyncIterator](){let i=e.iterate(n);return{async next(){for(;;){let e=await i.next();if(e.done)return{value:void 0,done:!0};let{ns:n,stream:a}=e.value;if(n.length===r&&FL(n,t))return{value:a,done:!1}}}}}}}function qL(e,t){let{createStream:n}=t,r=new Set;return{__native:!0,init(){return{_discoveries:e._discoveries,subgraphs:KL(e._discoveries,[],0)}},process(t){let i=t.params.namespace;if(i.length===0)return!0;let a=i.slice(0,1),o=PL(a);if(r.has(o))return!0;r.add(o);let s=n(a,e._discoveries.size,e._events.size);return e.register(a,s),e._discoveries.push({ns:a,stream:s}),!0}}}function JL(e){let t=TL.local();return{init:()=>({_valuesLog:t}),process(n){return n.method!==`values`||n.params.namespace.length!==e.length||!FL(n.params.namespace,e)||t.push(n.params.data),!0},finalize(){t.close()},fail(e){t.fail(e)}}}function YL(e){return`__native`in e&&e.__native===!0}var XL=Symbol(`setValuesLog`),ZL=Symbol(`setMessagesIterable`),QL=Symbol(`setLifecycleIterable`),$L=Symbol(`setSubgraphsIterable`),eR={[Symbol.asyncIterator](){return{next:()=>Promise.resolve({value:void 0,done:!0})}}},tR=class{path;extensions;_mux;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e,t,n=0,r=0,i,a){this.path=e,this._mux=t,this.#t=n,this.#e=r,this.extensions=i??{},this.#n=a??new AbortController,this.#a=new Promise((e,t)=>{this.#r=e,this.#i=t}),this.#a.catch(()=>{})}[Symbol.asyncIterator](){return this._mux.subscribeEvents(this.path,this.#e)}get subgraphs(){return this.#l?this.#l:KL(this._mux._discoveries,this.path,this.#t)}get values(){let e=this.#o,t=this.#a,n=this._mux,r=this.#e,i=this.path,a=e?e.toAsyncIterable():{[Symbol.asyncIterator]:()=>{let e=n.subscribeEvents(i,r);return{async next(){for(;;){let t=await e.next();if(t.done)return{value:void 0,done:!0};if(t.value.method===`values`&&t.value.params.namespace.length===i.length)return{value:t.value.params.data,done:!1}}}}}};return{[Symbol.asyncIterator]:()=>a[Symbol.asyncIterator](),then:t.then.bind(t)}}get messages(){if(this.#s)return this.#s;let e=GL(this.path),t=e.init();return this._mux.addTransformer(e),this.#s=t.messages,this.#s}get lifecycle(){return this.#c??eR}messagesFrom(e){let t=GL(this.path,e),n=t.init();return this._mux.addTransformer(t),n.messages}get output(){return this.#a}get interrupted(){return this._mux.interrupted}get interrupts(){return this._mux.interrupts}abort(e){this.#n.abort(e)}get signal(){return this.#n.signal}[AL](e){this.#r?.(e),this.#r=void 0}[jL](e){this.#i?.(e),this.#i=void 0}[XL](e){this.#o=e}[ZL](e){this.#s=e}[QL](e){this.#c=e}[$L](e){this.#l=e}},nR=class extends tR{name;index;constructor(e,t,n=0,r=0,i,a){super(e,t,n,r,i,a);let o=e[e.length-1]??``,s=o.lastIndexOf(`:`);if(s>=0){this.name=o.slice(0,s);let e=o.slice(s+1);this.index=/^\d+$/.test(e)?Number(e):0}else this.name=o,this.index=0}};function rR(e,t=[],n){let{abortController:r}=n instanceof AbortController?{abortController:n}:n??{},i=new ML,a=UL(),o=a.init(),s=o._lifecycleLog,c=qL(i,{createStream:(e,t,n)=>{let r=new nR(e,i,t,n);return r[$L](KL(i._discoveries,e,t)),r[QL](IL(s,e,s.size)),r}}),l=c.init();i.addTransformer(c),i.addTransformer(a);let u=JL([]),d=GL([]);i.addTransformer(u),i.addTransformer(d);let f={},p=[];for(let e of t){let t=e();i.addTransformer(t);let n=t.init();YL(t)?p.push(n):Object.assign(f,n),typeof n==`object`&&n&&!YL(t)&&i.wireChannels(n)}let m=new tR([],i,0,0,f,r);for(let e of p)Object.assign(m,e);let h=u.init();m[XL](h._valuesLog);let g=d.init();return m[ZL](g.messages),m[QL](o.lifecycle),m[$L](l.subgraphs),i.register([],m),NL(e,i).catch(e=>{}),m}var iR=class extends Error{constructor(e){super(e),this.name=`GraphValidationError`}};function aR({nodes:e,channels:t,inputChannels:n,outputChannels:r,streamChannels:i,interruptAfterNodes:a,interruptBeforeNodes:o}){if(!t)throw new iR(`Channels not provided`);let s=new Set,c=new Set;for(let[t,n]of Object.entries(e)){if(t===`__interrupt__`)throw new iR(`"Node name ${pC} is reserved"`);if(n.constructor===GP)n.triggers.forEach(e=>s.add(e));else throw new iR(`Invalid node type ${typeof n}, expected PregelNode`)}for(let e of s)if(!(e in t))throw new iR(`Subscribed channel '${String(e)}' not in channels`);if(!Array.isArray(n)){if(!s.has(n))throw new iR(`Input channel ${String(n)} is not subscribed to by any node`)}else if(n.every(e=>!s.has(e)))throw new iR(`None of the input channels ${n} are subscribed to by any node`);Array.isArray(r)?r.forEach(e=>c.add(e)):c.add(r),i&&!Array.isArray(i)?c.add(i):Array.isArray(i)&&i.forEach(e=>c.add(e));for(let e of c)if(!(e in t))throw new iR(`Output channel '${String(e)}' not in channels`);if(a&&a!==`*`){for(let t of a)if(!(t in e))throw new iR(`Node ${String(t)} not in nodes`)}if(o&&o!==`*`){for(let t of o)if(!(t in e))throw new iR(`Node ${String(t)} not in nodes`)}}function oR(e,t){if(Array.isArray(e)){for(let n of e)if(!(n in t))throw Error(`Key ${String(n)} not found in channels`)}else if(!(e in t))throw Error(`Key ${String(e)} not found in channels`)}function sR(e){return Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1])}var cR=class e extends iP{lc_graph_name=`Topic`;unique=!1;accumulate=!1;seen;values;constructor(e){super(),this.unique=e?.unique??this.unique,this.accumulate=e?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(t){let n=new e({unique:this.unique,accumulate:this.accumulate});return t===void 0?n:sR(t)?(n.seen=new Set(t[0]),n.values=[...t[1]],n):(n.values=[...t],this.unique&&(n.seen=new Set(n.values)),n)}update(e){let t=!1;this.accumulate||(t=this.values.length>0,this.values=[]);let n=e.flat();if(n.length>0)if(this.unique)for(let e of n)this.seen.has(e)||(t=!0,this.seen.add(e),this.values.push(e));else t=!0,this.values.push(...n);return t}get(){if(this.values.length===0)throw new $C;return this.values}checkpoint(){return this.unique?[[...this.seen],[...this.values]]:[...this.values]}isAvailable(){return this.values.length!==0}};function lR(e){let t=Su.getRunnableConfig();if(!t)throw Error(`Called interrupt() outside the context of a graph.`);let n=t.configurable;if(!n)throw Error(`No configurable found in config`);if(!n.__pregel_checkpointer)throw new VC(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=n[rC];r.interruptCounter+=1;let i=r.interruptCounter;if(r.resume.length>0&&i<r.resume.length)return n[JS]?.([[mC,r.resume]]),r.resume[i];if(r.nullResume!==void 0){if(r.resume.length!==i)throw Error(`Resume length mismatch: ${r.resume.length} !== ${i}`);let e=r.consumeNullResume();return r.resume.push(e),n[JS]?.([[mC,r.resume]]),e}let a=n[sC]?.split(`|`);throw new WC([{id:a?qF(a.join(`|`)):void 0,value:e}])}function uR(e){let t=new TextEncoder;return new ReadableStream({async start(n){try{for await(let r of e){let e=r.params.namespace,i=e.length?`${r.method}|${e.join(`|`)}`:r.method;n.enqueue(t.encode(`event: ${i}\ndata: ${JSON.stringify(r.params.data??{})}\n\n`))}}catch(e){n.enqueue(t.encode(`event: error\ndata: ${JSON.stringify({message:String(e)})}\n\n`))}finally{n.close()}}})}var dR=class{static subscribeTo(e,t){let{key:n,tags:r}={key:void 0,tags:void 0,...t??{}};if(Array.isArray(e)&&n!==void 0)throw Error(`Can't specify a key when subscribing to multiple channels`);let i;return i=typeof e==`string`?n?{[n]:e}:[e]:Object.fromEntries(e.map(e=>[e,e])),new GP({channels:i,triggers:Array.isArray(e)?e:[e],tags:r})}static writeTo(e,t){let n=[];for(let t of e)n.push({channel:t,value:LP,skipNone:!1});for(let[e,r]of Object.entries(t??{}))tS.isRunnable(r)||typeof r==`function`?n.push({channel:e,value:LP,skipNone:!0,mapper:fS(r)}):n.push({channel:e,value:r,skipNone:!1});return new BP(n)}},fR=class extends tS{lc_namespace=[`langgraph`,`pregel`];invoke(e,t){throw Error(`Not implemented`)}withConfig(e){return super.withConfig(e)}stream(e,t){return super.stream(e,t)}},pR=class extends fR{static lc_name(){return`LangGraph`}lc_namespace=[`langgraph`,`pregel`];lg_is_pregel=!0;nodes;channels;inputChannels;outputChannels;autoValidate=!0;streamMode=[`values`];streamChannels;interruptAfter;interruptBefore;stepTimeout;debug=!1;checkpointer;retryPolicy;config;store;cache;userInterrupt;streamTransformers;triggerToNodes={};constructor(e){super(e);let{streamMode:t}=e;if(t!=null&&!Array.isArray(t)&&(t=[t]),this.nodes=e.nodes,this.channels=e.channels,`__pregel_tasks`in this.channels&&`lc_graph_name`in this.channels.__pregel_tasks&&this.channels.__pregel_tasks.lc_graph_name!==`Topic`)throw Error(`Channel '${bC}' is reserved and cannot be used in the graph.`);this.channels[bC]=new cR({accumulate:!1}),this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.cache=e.cache,this.name=e.name,this.triggerToNodes=e.triggerToNodes??this.triggerToNodes,this.userInterrupt=e.userInterrupt,this.streamTransformers=e.streamTransformers??[],this.autoValidate&&this.validate()}withConfig(e){let{streamTransformers:t,...n}=e,r=Ou(this.config,n),i=[...this.streamTransformers,...t??[]];return new this.constructor({...this,config:r,streamTransformers:i})}validate(){aR({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(let[e,t]of Object.entries(this.nodes))for(let n of t.triggers)this.triggerToNodes[n]??=[],this.triggerToNodes[n].push(e);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(e){return this.getGraph(e)}*getSubgraphs(e,t){for(let[n,r]of Object.entries(this.nodes)){if(e!==void 0&&!e.startsWith(n))continue;let i=r.subgraphs?.length?r.subgraphs:[r.bound];for(let r of i){let i=eF(r);if(i!==void 0){if(n===e){yield[n,i];return}if(e===void 0&&(yield[n,i]),t){let r=e;e!==void 0&&(r=e.slice(n.length+1));for(let[e,a]of i.getSubgraphs(r,t))yield[`${n}|${e}`,a]}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}async _prepareStateSnapshot({config:e,saved:t,subgraphCheckpointer:n,applyPendingWrites:r=!1}){if(t===void 0)return{values:{},next:[],config:e,tasks:[]};let i=await dP(this.channels,t.checkpoint,{saver:typeof this.checkpointer==`object`?this.checkpointer:void 0,config:t.config??e});if(t.pendingWrites?.length){let e=t.pendingWrites.filter(([e,t])=>e===CC).map(([e,t,n])=>[String(t),n]);e.length>0&&fI(t.checkpoint,i,[{name:US,writes:e,triggers:[]}],void 0,this.triggerToNodes)}let a=Object.values(hI(t.checkpoint,t.pendingWrites,this.nodes,i,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),o=await NP(this.getSubgraphsAsync()),s=t.config.configurable?.checkpoint_ns??``,c={};for(let e of a){let r=o.find(([t])=>t===e.name);if(!r)continue;let i=`${String(e.name)}:${e.id}`;if(s&&(i=`${s}|${i}`),n===void 0){let n={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:i}};c[e.id]=n}else{let a={configurable:{[ZS]:n,thread_id:t.config.configurable?.thread_id,checkpoint_ns:i}},o=r[1];c[e.id]=await o.getState(a,{subgraphs:!0})}}if(r&&t.pendingWrites?.length){let e=Object.fromEntries(a.map(e=>[e.id,e]));for(let[n,r,i]of t.pendingWrites)[`__error__`,`__interrupt__`,`__scheduled__`].includes(r)||n in e&&e[n].writes.push([String(r),i]);let n=a.filter(e=>e.writes.length>0);n.length>0&&fI(t.checkpoint,i,n,void 0,this.triggerToNodes)}let l=t?.metadata;l&&t?.config?.configurable?.thread_id&&(l={...l,thread_id:t.config.configurable.thread_id});let u=a.filter(e=>e.writes.length===0).map(e=>e.name);return{values:XF(i,this.streamChannelsAsIs),next:u,tasks:kI(a,t?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:l,config:XP(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new VC(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_read===void 0&&e.configurable?.__pregel_checkpointer===void 0){let i=kP(r);for await(let[r,a]of this.getSubgraphsAsync(i,!0))if(r===i)return await a.getState(FP(e,{[ZS]:n}),{subgraphs:t?.subgraphs})}let i=Ou(this.config,e),a=await n.getTuple(e);return await this._prepareStateSnapshot({config:i,saved:a,subgraphCheckpointer:t?.subgraphs?n:void 0,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new VC(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_checkpointer===void 0){let i=kP(r);for await(let[r,a]of this.getSubgraphsAsync(i,!0))if(r===i){yield*a.getStateHistory(FP(e,{[ZS]:n}),t);return}}let i=Ou(this.config,e,{configurable:{checkpoint_ns:r}});for await(let e of n.list(i,t))yield this._prepareStateSnapshot({config:e.config,saved:e})}async bulkUpdateState(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new VC(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});if(t.length===0)throw Error(`No supersteps provided`);if(t.some(e=>e.updates.length===0))throw Error(`No updates provided`);let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_checkpointer===void 0){let i=kP(r);for await(let[,r]of this.getSubgraphsAsync(i,!0))return await r.bulkUpdateState(FP(e,{[ZS]:n}),t);throw Error(`Subgraph "${i}" not found`)}let i=async(e,t)=>{let r=this.config?Ou(this.config,e):e,a=await n.getTuple(r),o=a===void 0?UN():WN(a.checkpoint),s={...a?.checkpoint.channel_versions},c=a?.metadata?.step??-1,l=FP(r,{checkpoint_ns:r.configurable?.checkpoint_ns??``}),u=r.metadata??{};a?.config.configurable&&(l=FP(r,a.config.configurable),u={...a.metadata,...u});let{values:d,asNode:f}=t[0];if(d==null&&f===void 0){if(t.length>1)throw new ew(`Cannot create empty checkpoint with multiple updates`);return XP(await n.put(l,uP(o,void 0,c),{source:`update`,step:c+1,parents:a?.metadata?.parents??{}},{}),a?a.metadata:void 0)}let p=await dP(this.channels,o,{saver:n,config:a?.config??l});if(d===null&&f===`__end__`){if(t.length>1)throw new ew(`Cannot apply multiple updates when clearing state`);if(a){let e=hI(o,a.pendingWrites||[],this.nodes,p,a.config,!0,{step:(a.metadata?.step??-1)+1,checkpointer:n,store:this.store}),t=(a.pendingWrites||[]).filter(e=>e[0]===CC).map(e=>e.slice(1));t.length>0&&fI(o,p,[{name:US,writes:t,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(let[t,n,r]of a.pendingWrites||[])[`__error__`,`__interrupt__`,`__scheduled__`].includes(n)||t in e&&e[t].writes.push([n,r]);fI(o,p,Object.values(e),n.getNextVersion.bind(n),this.triggerToNodes)}return XP(await n.put(l,uP(o,p,c),{...u,source:`update`,step:c+1,parents:a?.metadata?.parents??{}},qP(s,o.channel_versions)),a?a.metadata:void 0)}if(f===`__copy__`){if(t.length>1)throw new ew(`Cannot copy checkpoint with multiple updates`);if(a==null)throw new ew(`Cannot copy a non-existent checkpoint`);let e=e=>!Array.isArray(e)||e.length===0?!1:e.every(e=>Array.isArray(e)&&e.length===2),r=uP(o,void 0,c),s=await n.put(a.parentConfig??FP(a.config,{checkpoint_id:void 0}),r,{source:`fork`,step:c+1,parents:a.metadata?.parents??{}},{});if(e(d)){let e=hI(r,a.pendingWrites,this.nodes,p,s,!1,{step:c+2}),t=Object.values(e).reduce((e,{name:t,id:n})=>(e[t]??=[],e[t].push({id:n}),e),{}),n=d.reduce((e,n)=>{let[r,i]=n;e[i]??=[];let a=e[i].length,o=t[i]?.[a]?.id;return e[i].push({values:r,asNode:i,taskId:o}),e},{});return i(XP(s,a.metadata),Object.values(n).flat())}return XP(s,a.metadata)}if(f===`__input__`){if(t.length>1)throw new ew(`Cannot apply multiple updates when updating as input`);let e=await NP(QF(this.inputChannels,d));if(e.length===0)throw new ew(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);fI(o,p,[{name:US,writes:e,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let r=a?.metadata?.step==null?-1:a.metadata.step+1,i=await n.put(l,uP(o,p,r),{source:`input`,step:r,parents:a?.metadata?.parents??{}},qP(s,o.channel_versions));return await n.putWrites(i,e,ow(US,o.id)),XP(i,a?a.metadata:void 0)}if(r.configurable?.checkpoint_id===void 0&&a?.pendingWrites!==void 0&&a.pendingWrites.length>0){let e=hI(o,a.pendingWrites,this.nodes,p,a.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(a.metadata?.step??-1)+1}),t=(a.pendingWrites??[]).filter(e=>e[0]===CC).map(e=>e.slice(1));t.length>0&&fI(a.checkpoint,p,[{name:US,writes:t,triggers:[]}],void 0,this.triggerToNodes);for(let[t,n,r]of a.pendingWrites)[`__error__`,`__interrupt__`,`__scheduled__`].includes(n)||e[t]===void 0||e[t].writes.push([n,r]);let n=Object.values(e).filter(e=>e.writes.length>0);n.length>0&&fI(o,p,n,void 0,this.triggerToNodes)}let m=Object.values(o.versions_seen).map(e=>Object.values(e)).flat().find(e=>!!e),h=[];if(t.length===1){let{values:e,asNode:n,taskId:r}=t[0];if(n===void 0&&Object.keys(this.nodes).length===1)[n]=Object.keys(this.nodes);else if(n===void 0&&m===void 0)typeof this.inputChannels==`string`&&this.nodes[this.inputChannels]!==void 0&&(n=this.inputChannels);else if(n===void 0){let e=Object.entries(o.versions_seen).map(([e,t])=>Object.values(t).map(t=>[t,e])).flat().filter(([e,t])=>t!==pC).sort(([e],[t])=>GN(e,t));e&&(e.length===1?n=e[0][1]:e[e.length-1][0]!==e[e.length-2][0]&&(n=e[e.length-1][1]))}if(n===void 0)throw new ew(`Ambiguous update, specify "asNode"`);h.push({values:e,asNode:n,taskId:r})}else for(let{asNode:e,values:n,taskId:r}of t){if(e==null)throw new ew(`"asNode" is required when applying multiple updates`);h.push({values:n,asNode:e,taskId:r})}let g=[];for(let{asNode:e,values:t,taskId:n}of h){if(this.nodes[e]===void 0)throw new ew(`Node "${e.toString()}" does not exist`);let r=this.nodes[e].getWriters();if(!r.length)throw new ew(`No writers found for node "${e.toString()}"`);g.push({name:e,input:t,proc:r.length>1?aS.from(r,{omitSequenceTags:!0}):r[0],writes:[],triggers:[pC],id:n??ow(`__interrupt__`,o.id),writers:[]})}for(let e of g)await e.proc.invoke(e.input,Au({...r,store:r?.store??this.store},{runName:r.runName??`${this.getName()}UpdateState`,configurable:{[JS]:t=>e.writes.push(...t),[XS]:(t,n=!1)=>cI(o,p,e,t,n)}}));for(let e of g){let t=e.writes.filter(e=>e[0]!==xC);a!==void 0&&t.length>0&&await n.putWrites(l,t,e.id)}fI(o,p,g,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let _=qP(s,o.channel_versions),v=await n.put(l,uP(o,p,c+1),{source:`update`,step:c+1,parents:a?.metadata?.parents??{}},_);for(let e of g){let t=e.writes.filter(e=>e[0]===xC);t.length>0&&await n.putWrites(v,t,e.id)}return XP(v,a?a.metadata:void 0)},a=e;for(let{updates:e}of t)a=await i(a,e);return a}async updateState(e,t,n){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:n}]}])}_defaults(e){let{debug:t,streamMode:n,inputKeys:r,outputKeys:i,interruptAfter:a,interruptBefore:o,...s}=e,c=!0,l=t===void 0?this.debug:t,u=i;u===void 0?u=this.streamChannelsAsIs:oR(u,this.channels);let d=r;d===void 0?d=this.inputChannels:oR(d,this.channels);let f=o??this.interruptBefore??[],p=a??this.interruptAfter??[],m;n===void 0?(m=e.configurable?.__pregel_task_id===void 0?this.streamMode:[`values`],c=!0):(m=Array.isArray(n)?n:[n],c=typeof n==`string`);let h;if(this.checkpointer===!1)h=void 0;else if(e!==void 0&&e.configurable?.__pregel_checkpointer!==void 0)h=e.configurable[ZS];else if(this.checkpointer===!0)throw Error(`checkpointer: true cannot be used for root graphs.`);else h=this.checkpointer;let g=e.store??this.store,_=e.cache??this.cache;if(e.durability!=null&&e.checkpointDuring!=null)throw Error("Cannot use both `durability` and `checkpointDuring` at the same time.");let v=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?`exit`:`async`})(),y=e.durability??v??e?.configurable?.__pregel_durability??`async`;return[l,m,d,u,s,f,p,h,g,c,_,y]}async stream(e,t){let n=new AbortController,r=OP()?.configurable;r?.__pregel_read!==void 0&&t?.configurable?.__pregel_read===void 0&&(t={...t,configurable:{...r,...t?.configurable}});let i={recursionLimit:this.config?.recursionLimit,...t,signal:ZP(t?.signal,n.signal).signal},a=await super.stream(e,i);return new zI(t?.encoding===`text/event-stream`?JI(a):a,n)}async#e(e,t){let{version:n,encoding:r,transformers:i,...a}=t,o={recursionLimit:this.config?.recursionLimit,...a,configurable:{...this.config?.configurable,...a?.configurable},version:n,streamMode:NI,subgraphs:!0,encoding:void 0},s=this.stream(e,o),c=rR({[Symbol.asyncIterator]:async function*(){let e=await s;for await(let t of e)yield t}},[...this.streamTransformers??[],...i??[]]);if(r===`text/event-stream`){let e=new AbortController;return e.signal.addEventListener(`abort`,()=>c.abort(e.signal.reason),{once:!0}),new zI(uR(c),e)}return c}streamEvents(e,t,n){if(t.version===`v3`)return this.#e(e,t);let r=new AbortController,i={recursionLimit:this.config?.recursionLimit,...t,signal:ZP(t?.signal,r.signal).signal};return new zI(super.streamEvents(e,i,n),r)}async _validateInput(e){return e}async _validateContext(e){return e}async*_streamIterator(e,t){let n=`version`in(t??{})?void 0:t?.encoding??void 0,r=t?.subgraphs,i=t?.version===`v3`,a=DP(this.config,t);if(a.recursionLimit===void 0||a.recursionLimit<1)throw Error(`Passed "recursionLimit" must be at least 1.`);if(this.checkpointer!==void 0&&this.checkpointer!==!1&&a.configurable===void 0)throw Error(`Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"`);let o=await this._validateInput(e),{runId:s,...c}=a,[l,u,,d,f,p,m,h,g,_,v,y]=this._defaults(c);f.metadata={ls_integration:`langgraph`,...f.metadata},f.context===void 0?f.configurable=await this._validateContext(f.configurable):f.context=await this._validateContext(f.context);let b=new BI({modes:new Set(u)});if(this.checkpointer===!0){f.configurable??={};let e=f.configurable.checkpoint_ns??``;f.configurable[sC]=e.split(`|`).map(e=>e.split(`:`)[0]).join(`|`)}if(u.includes(`messages`)){let e=i?new fL(e=>b.push(e)):new sL(e=>b.push(e)),{callbacks:t}=f;if(t===void 0)f.callbacks=[e];else if(Array.isArray(t))f.callbacks=t.concat(e);else{let n=t.copy();n.addHandler(e,!0),f.callbacks=n}}if(u.includes(`tools`)){let e=new VI(e=>b.push(e)),{callbacks:t}=f;if(t===void 0)f.callbacks=[e];else if(Array.isArray(t))f.callbacks=t.concat(e);else{let n=t.copy();n.addHandler(e,!0),f.callbacks=n}}f.writer??=e=>{if(!u.includes(`custom`))return;let t=(OP()?.configurable?.[sC])?.split(`|`).slice(0,-1);b.push([t??[],`custom`,e])},f.interrupt??=this.userInterrupt??lR,f.serverInfo??=mR(f),f.control??=new nF;let ee={tracerInheritableMetadata:_R(f)},te=await(await _u._configureSync(f?.callbacks,void 0,f?.tags,void 0,f?.metadata,void 0,ee))?.handleChainStart(this.toJSON(),JP(e,`input`),s,void 0,void 0,void 0,f?.runName??this.getName()),ne=oP(this.channels),x,re,ie=(async()=>{try{x=await iL.initialize({input:o,config:f,checkpointer:h,nodes:this.nodes,channelSpecs:ne,outputKeys:d,streamKeys:this.streamChannelsAsIs,store:g,cache:v,stream:b,interruptAfter:m,interruptBefore:p,manager:te,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:y});let e=new SL({loop:x,nodeFinished:f.configurable?.[cC]});t?.subgraphs&&(x.config.configurable={...x.config.configurable,[eC]:x.stream}),await this._runLoop({loop:x,runner:e,debug:l,config:f}),y===`sync`&&await Promise.all(x?.checkpointerPromises??[])}catch(e){re=e}finally{try{x&&(await x.store?.stop(),await x.cache?.stop()),await Promise.all(x?.checkpointerPromises??[])}catch(e){re??=e}re?(await new Promise(e=>{queueMicrotask(e)}),b.error(re)):b.close()}})();try{for await(let e of b){if(e===void 0)throw Error(`Data structure error.`);let[a,o,s]=e,c=`version`in(t??{});if(u.includes(o)||o===`checkpoints`&&PI(s)&&(i||c&&r&&u.includes(`values`))){if(n===`text/event-stream`){r?yield[a,o,s]:yield[null,o,s];continue}r&&!_?yield[a,o,s]:_?r?yield[a,s]:yield s:yield[o,s]}}}catch(e){throw await te?.handleChainError(re),e}finally{await ie}await te?.handleChainEnd(x?.output??{},s,void 0,void 0,void 0)}async invoke(e,t){let n=t?.streamMode??`values`,r={...t,outputKeys:t?.outputKeys??this.outputChannels,streamMode:n,encoding:void 0},i=[],a=await this.stream(e,r),o=[],s;for await(let e of a)n===`values`?NC(e)?o.push(e[pC]):s=e:i.push(e);if(n===`values`){if(o.length>0){let e=o.flat(1);if(s==null)return{[pC]:e};if(typeof s==`object`)return{...s,[pC]:e}}return s}return i}async _runLoop(e){let{loop:t,runner:n,debug:r,config:i}=e,a;try{for(;await t.tick({inputKeys:this.inputChannels});){for(let{task:e}of await t._matchCachedWrites())t._outputWrites(e.id,e.writes,!0);r&&AI(t.checkpointMetadata.step,t.channels,this.streamChannelsList),r&&jI(t.step,Object.values(t.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(e,t)=>{r&&MI(e,t,this.streamChannelsList)},maxConcurrency:i.maxConcurrency,signal:i.signal})}if(t.status===`draining`)throw t.control==null?Error(`Draining status requires run control`):new HC(t.control.drainReason??`shutdown`);if(t.status===`out_of_steps`)throw new BC([`Recursion limit of ${i.recursionLimit} reached`,`without hitting a stop condition. You can increase the`,`limit by setting the "recursionLimit" config key.`].join(` `),{lc_error_code:`GRAPH_RECURSION_LIMIT`})}catch(e){if(a=e,!await t.finishAndHandleError(a))throw e}finally{a===void 0&&await t.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}};function mR(e){let t=e.metadata??{},n=e.configurable??{},r=n.assistant_id??t.assistant_id,i=n.graph_id??t.graph_id,a=n.langgraph_auth_user,o;if(typeof a==`object`&&a&&`identity`in a&&(o=a),r!=null||i!=null||o!=null)return{assistantId:r==null?``:String(r),graphId:i==null?``:String(i),user:o}}var hR=new Set([`key`,`token`,`secret`,`password`,`auth`]);function gR(e,t){let n=e.toLowerCase(),r=!1;for(let e of hR)if(n.includes(e)){r=!0;break}return e.startsWith(`__`)||!(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)||r}function _R(e){let t=e.configurable;if(!t)return;let n={};for(let[e,r]of Object.entries(t))gR(e,r)||(n[e]=r);return Object.keys(n).length>0?n:void 0}var vR=class{path;ends;constructor(e){tS.isRunnable(e.path)?this.path=e.path:this.path=fS(e.path),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((e,t)=>(e[t]=t,e),{}):e.pathMap}run(e,t){return BP.registerWriter(new jP({name:`<branch_run>`,trace:!1,func:async(n,r)=>{try{return await this._route(n,r,e,t)}catch(e){throw e.name===GC.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
|
|
189
|
-
NodeInterrupt should only be thrown inside a node, not in edge conditions.`),e}}}))}async _route(e,t,n,r){let i=await this.path.invoke(r?r(t):e,t);Array.isArray(i)||(i=[i]);let a;if(a=this.ends?i.map(e=>kC(e)?e:this.ends[e]):i,a.some(e=>!e))throw Error(`Branch condition returned unknown or null destination`);if(a.filter(kC).some(e=>e.node===`__end__`))throw new ew(`Cannot send a packet to the END node`);return await n(a,t)??e}},
|
|
190
|
-
`),{lc_error_code:`UNREACHABLE_NODE`});for(let e of n)if(e!==`__end__`&&!(e in this.nodes))throw Error(`Found edge ending at unknown node \`${e}\``);if(e){for(let t of e)if(!(t in this.nodes))throw Error(`Interrupt node \`${t}\` is not present`)}this.compiled=!0}},bR=class extends pR{builder;constructor({builder:e,...t}){super(t),this.builder=e}withConfig(e){return super.withConfig(e)}attachNode(e,t){this.channels[e]=new tF,this.nodes[e]=new GP({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new BP([{channel:e,value:LP}],[vC])),this.streamChannels.push(e)}attachEdge(e,t){if(t===`__end__`){if(e===`__start__`)throw Error(`Cannot have an edge from START to END`);this.nodes[e].writers.push(new BP([{channel:HS,value:LP}],[vC]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,n){e===`__start__`&&!this.nodes.__start__&&(this.nodes[VS]=dR.subscribeTo(VS,{tags:[vC]})),this.nodes[e].pipe(n.run(n=>new BP(n.map(n=>kC(n)?n:{channel:n===`__end__`?HS:`branch:${e}:${t}:${n}`,value:LP}),[vC])));let r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(let n of r)if(n!==`__end__`){let r=`branch:${e}:${t}:${n}`;this.channels[r]=new tF,this.nodes[n].triggers.push(r),this.nodes[n].channels.push(r)}}async getGraphAsync(e){let t=e?.xray,n=new Ux,r={[VS]:n.addNode({schema:ej()},VS)},i={},a={};t&&(a=Object.fromEntries((await NP(this.getSubgraphsAsync())).filter(e=>xR(e[1]))));let o=[];function s(e,t,a,s=!1){if(t===`__end__`&&i.__end__===void 0&&(i[HS]=n.addNode({schema:ej()},HS)),r[e]!==void 0){if(i[t]===void 0)throw Error(`End node ${t} not found!`);return o.push({src:e,dest:t,conditional:s}),n.addEdge(r[e],i[t],a===t?void 0:a,s)}}for(let[o,s]of Object.entries(this.builder.nodes)){let c=SR(o),l=s.runnable,u=s.metadata??{};if(this.interruptBefore?.includes(o)&&this.interruptAfter?.includes(o)?u.__interrupt=`before,after`:this.interruptBefore?.includes(o)?u.__interrupt=`before`:this.interruptAfter?.includes(o)&&(u.__interrupt=`after`),t){let s=typeof t==`number`?t-1:t,d=a[o]===void 0?l.getGraph(e):await a[o].getGraphAsync({...e,xray:s});if(d.trimFirstNode(),d.trimLastNode(),Object.keys(d.nodes).length>1){let[e,t]=n.extend(d,c);if(e===void 0)throw Error(`Could not extend subgraph "${o}" due to missing entrypoint.`);function a(e){return e?e.lc_runnable:!1}function s(e,t){if(e!==void 0&&!$r(e))return e;if(a(t))try{let e=t.getName();return e=e.startsWith(`Runnable`)?e.slice(8):e,e}catch{return t.getName()}else return t.name??`UnknownSchema`}t!==void 0&&(r[c]={name:s(t.id,t.data),...t}),i[c]={name:s(e.id,e.data),...e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}let c=[...this.builder.allEdges].sort(([e],[t])=>e<t?-1:+(t>e));for(let[e,t]of c)s(SR(e),SR(t));for(let[e,t]of Object.entries(this.builder.branches)){let n={...Object.fromEntries(Object.keys(this.builder.nodes).filter(t=>t!==e).map(e=>[SR(e),SR(e)])),[HS]:HS};for(let r of Object.values(t)){let t;t=r.ends===void 0?n:r.ends;for(let[n,r]of Object.entries(t))s(SR(e),SR(r),n,!0)}}for(let[e,t]of Object.entries(this.builder.nodes))if(t.ends!==void 0)for(let n of t.ends)s(SR(e),SR(n),void 0,!0);return CR(this.builder.nodes,o,s),n}getGraph(e){let t=e?.xray,n=new Ux,r={[VS]:n.addNode({schema:ej()},VS)},i={},a={};t&&(a=Object.fromEntries(PP(this.getSubgraphs()).filter(e=>xR(e[1]))));let o=[];function s(e,t,a,s=!1){if(t===`__end__`&&i.__end__===void 0&&(i[HS]=n.addNode({schema:ej()},HS)),r[e]!==void 0){if(i[t]===void 0)throw Error(`End node ${t} not found!`);return o.push({src:e,dest:t,conditional:s}),n.addEdge(r[e],i[t],a===t?void 0:a,s)}}for(let[o,s]of Object.entries(this.builder.nodes)){let c=SR(o),l=s.runnable,u=s.metadata??{};if(this.interruptBefore?.includes(o)&&this.interruptAfter?.includes(o)?u.__interrupt=`before,after`:this.interruptBefore?.includes(o)?u.__interrupt=`before`:this.interruptAfter?.includes(o)&&(u.__interrupt=`after`),t){let s=typeof t==`number`?t-1:t,d=a[o]===void 0?l.getGraph(e):a[o].getGraph({...e,xray:s});if(d.trimFirstNode(),d.trimLastNode(),Object.keys(d.nodes).length>1){let[e,t]=n.extend(d,c);if(e===void 0)throw Error(`Could not extend subgraph "${o}" due to missing entrypoint.`);function a(e){return e?e.lc_runnable:!1}function s(e,t){if(e!==void 0&&!$r(e))return e;if(a(t))try{let e=t.getName();return e=e.startsWith(`Runnable`)?e.slice(8):e,e}catch{return t.getName()}else return t.name??`UnknownSchema`}t!==void 0&&(r[c]={name:s(t.id,t.data),...t}),i[c]={name:s(e.id,e.data),...e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}let c=[...this.builder.allEdges].sort(([e],[t])=>e<t?-1:+(t>e));for(let[e,t]of c)s(SR(e),SR(t));for(let[e,t]of Object.entries(this.builder.branches)){let n={...Object.fromEntries(Object.keys(this.builder.nodes).filter(t=>t!==e).map(e=>[SR(e),SR(e)])),[HS]:HS};for(let r of Object.values(t)){let t;t=r.ends===void 0?n:r.ends;for(let[n,r]of Object.entries(t))s(SR(e),SR(r),n,!0)}}for(let[e,t]of Object.entries(this.builder.nodes))if(t.ends!==void 0)for(let n of t.ends)s(SR(e),SR(n),void 0,!0);return CR(this.builder.nodes,o,s),n}};function xR(e){return typeof e.attachNode==`function`&&typeof e.attachEdge==`function`}function SR(e){return e===`subgraph`?`"${e}"`:e}function CR(e,t,n){let r=new Set(t.map(e=>e.src)),i=[...new Set(t.filter(e=>!e.conditional&&e.dest!==`__end__`).map(e=>e.dest))].sort();for(let t of i){if(r.has(t))continue;let i=Object.keys(e).find(e=>SR(e)===t);i!==void 0&&e[i]?.isErrorHandler||n(t,HS)}}var wR=(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e)),TR=class e extends iP{lc_graph_name=`NamedBarrierValue`;names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(t){let n=new e(this.names);return t!==void 0&&(n.seen=new Set(t)),n}update(e){let t=!1;for(let n of e)if(this.names.has(n))this.seen.has(n)||(this.seen.add(n),t=!0);else throw new ew(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return t}get(){if(!wR(this.names,this.seen))throw new $C}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&wR(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&wR(this.names,this.seen)}},ER=class e extends iP{lc_graph_name=`NamedBarrierValueAfterFinish`;names;seen;finished;constructor(e){super(),this.names=e,this.seen=new Set,this.finished=!1}fromCheckpoint(t){let n=new e(this.names);if(t!==void 0){let[e,r]=t;n.seen=new Set(e),n.finished=r}return n}update(e){let t=!1;for(let n of e)if(this.names.has(n)&&!this.seen.has(n))this.seen.add(n),t=!0;else if(!this.names.has(n))throw new ew(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return t}get(){if(!this.finished||!wR(this.names,this.seen))throw new $C}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&wR(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&wR(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&wR(this.names,this.seen)}};function DR(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`validate`in e[`~standard`]}function OR(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`jsonSchema`in e[`~standard`]}function kR(e){if(OR(e))try{return e[`~standard`].jsonSchema.input({target:`draft-07`})}catch{return}}function AR(e){if(e!=null&&DR(e))try{let t=e[`~standard`].validate(void 0);if(t&&typeof t==`object`&&!(`then`in t&&typeof t.then==`function`)){let e=t;if(!e.issues){let t=e.value;return()=>t}}}catch{}}var jR=e=>e!=null&&e.lc_graph_name===`DeltaChannel`,MR=class e extends iP{lc_graph_name=`DeltaChannel`;value;reducer;snapshotFrequency;initialValueFactory;constructor(e,t){super();let n=t?.snapshotFrequency??1e3;if(!Number.isInteger(n)||n<=0)throw Error(`snapshotFrequency must be a positive integer, got ${n}`);this.reducer=e,this.snapshotFrequency=n,this.initialValueFactory=t?.initialValueFactory??(()=>[]),this.value=void 0}fromCheckpoint(t){let n=new e(this.reducer,{snapshotFrequency:this.snapshotFrequency,initialValueFactory:this.initialValueFactory});return t===void 0?n.value=this.initialValueFactory():fw(t)?n.value=t.value:n.value=t,n}replayWrites(e){let t=e.map(e=>e[2]);if(t.length===0)return;let n=this.value,r=0;for(let e=0;e<t.length;e+=1){let[i,a]=jC(t[e]);i&&(n=a??this.initialValueFactory(),r=e+1)}let i=t.slice(r);this.value=i.length>0?this.reducer(n,i):n}update(e){if(e.length===0)return!1;let t,n=!1;for(let r of e)if(MC(r)){if(n)throw new ew(`Can receive only one Overwrite value per step.`);n=!0,[,t]=jC(r)}if(n)return this.value=t??this.initialValueFactory(),!0;let r=this.value===void 0?this.initialValueFactory():this.value;return this.value=this.reducer(r,e),!0}get(){if(this.value===void 0)throw new $C;return this.value}checkpoint(){}isAvailable(){return this.value!==void 0}equals(e){return this===e?!0:!jR(e)||this.snapshotFrequency!==e.snapshotFrequency?!1:this.reducer===e.reducer}},NR=Symbol.for(`langgraph.channel.missing`),PR=class e extends iP{lc_graph_name=`UntrackedValue`;guard;_value=NR;initialValueFactory;constructor(e){super(),this.guard=e?.guard??!0,this.initialValueFactory=e?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new e({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(e){if(e.length===0)return!1;if(e.length!==1&&this.guard)throw new ew(`UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.`,{lc_error_code:`INVALID_CONCURRENT_GRAPH_UPDATE`});return this._value=e[e.length-1],!0}get(){if(this._value===NR)throw new $C;return this._value}checkpoint(){}isAvailable(){return this._value!==NR}},FR=Symbol.for(`langgraph.state.reduced_value`),IR=class{[FR]=!0;valueSchema;inputSchema;reducer;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.jsonSchemaExtra=t.jsonSchemaExtra,this.valueSchema=e,this.inputSchema=`inputSchema`in t?t.inputSchema:e,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e==`object`&&!!e&&FR in e&&e[FR]===!0}},LR=Symbol.for(`langgraph.state.untracked_value`),RR=class{[LR]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e==`object`&&!!e&&LR in e}},zR=Symbol.for(`langgraph.state.delta_value`),BR=class{[zR]=!0;valueSchema;inputSchema;reducer;snapshotFrequency;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.valueSchema=e,this.inputSchema=`inputSchema`in t?t.inputSchema:e,this.snapshotFrequency=t.snapshotFrequency,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e==`object`&&!!e&&zR in e&&e[zR]===!0}},VR=Symbol.for(`langgraph.state.state_schema`),HR=class{[VR]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,n]of Object.entries(this.fields))if(BR.isInstance(n)){let r=AR(n.valueSchema);e[t]=new MR(n.reducer,{snapshotFrequency:n.snapshotFrequency,initialValueFactory:r})}else if(IR.isInstance(n)){let r=AR(n.valueSchema);e[t]=new hP(n.reducer,r)}else if(RR.isInstance(n)){let r=n.schema?AR(n.schema):void 0;e[t]=new PR({guard:n.guard,initialValueFactory:r})}else if(DR(n))e[t]=new fP(AR(n));else throw Error(`Invalid state field "${t}": must be a schema, ReducedValue, DeltaValue, UntrackedValue, or ManagedValue`);return e}getJsonSchema(){let e={},t=[];for(let[n,r]of Object.entries(this.fields)){let i;if(BR.isInstance(r)||IR.isInstance(r)?(i=kR(r.valueSchema),r.jsonSchemaExtra&&(i={...i??{},...r.jsonSchemaExtra})):RR.isInstance(r)?i=r.schema?kR(r.schema):void 0:DR(r)&&(i=kR(r)),i){e[n]=i;let a=!1;a=BR.isInstance(r)||IR.isInstance(r)?AR(r.valueSchema)!==void 0:RR.isInstance(r)?r.schema?AR(r.schema)!==void 0:!1:AR(r)!==void 0,a||t.push(n)}}return{type:`object`,properties:e,required:t.length>0?t:void 0}}getInputJsonSchema(){let e={};for(let[t,n]of Object.entries(this.fields)){let r;BR.isInstance(n)||IR.isInstance(n)?(r=kR(n.inputSchema),n.jsonSchemaExtra&&(r={...r??{},...n.jsonSchemaExtra})):RR.isInstance(n)?r=n.schema?kR(n.schema):void 0:DR(n)&&(r=kR(n)),r&&(e[t]=r)}return{type:`object`,properties:e}}getChannelKeys(){return Object.entries(this.fields).map(([e])=>e)}getAllKeys(){return Object.keys(this.fields)}async validateInput(e){if(typeof e!=`object`||!e)return e;let t={};for(let[n,r]of Object.entries(e)){let e=this.fields[n];if(e===void 0){t[n]=r;continue}let i;if(BR.isInstance(e)||IR.isInstance(e)){let[a,o]=jC(r);if(a){i=e.valueSchema;let r=await i[`~standard`].validate(o);if(r.issues)throw Error(`Validation failed for field "${n}": ${JSON.stringify(r.issues)}`);t[n]={[AC]:r.value};continue}i=e.inputSchema}else RR.isInstance(e)?i=e.schema:DR(e)&&(i=e);if(i){let e=await i[`~standard`].validate(r);if(e.issues)throw Error(`Validation failed for field "${n}": ${JSON.stringify(e.issues)}`);t[n]=e.value}else t[n]=r}return t}static isInstance(e){return typeof e==`object`&&!!e&&VR in e&&e[VR]===!0}};function UR(e,t){let n=Array.isArray(e)?e:[e],r=Array.isArray(t)?t:[t],i=n.map(nr),a=r.map(nr);for(let e of i)(e.id===null||e.id===void 0)&&(e.id=Yr(),e.lc_kwargs.id=e.id);let o;for(let e=0;e<a.length;e+=1){let t=a[e];(t.id===null||t.id===void 0)&&(t.id=Yr(),t.lc_kwargs.id=t.id),Kn.isInstance(t)&&t.id===`__remove_all__`&&(o=e)}if(o!=null)return a.slice(o+1);let s=[...i],c=new Map(s.map((e,t)=>[e.id,t])),l=new Set;for(let e of a){let t=c.get(e.id);if(t!==void 0)Kn.isInstance(e)?l.add(e.id):(l.delete(e.id),s[t]=e);else{if(Kn.isInstance(e))throw Error(`Attempting to delete a message with an ID that doesn't exist ('${e.id}')`);c.set(e.id,s.length),s.push(e)}}return s.filter(e=>!l.has(e.id))}function WR(e,t){let n=[];for(let e of t)Array.isArray(e)?n.push(...e):n.push(e);let r=e.length>0&&Mt.isInstance(e[0])?e:e.map(nr),i=n.map(nr),a=new Map;for(let e=0;e<r.length;e+=1){let t=r[e].id;t!=null&&a.set(t,e)}let o=[...r];for(let e of i){let t=e.id;Kn.isInstance(e)&&t===`__remove_all__`?(o.length=0,a.clear()):t==null?o.push(e):Kn.isInstance(e)?a.has(t)&&(o[a.get(t)]=null,a.delete(t)):a.has(t)?o[a.get(t)]=e:(a.set(t,o.length),o.push(e))}return o.filter(e=>e!==null)}var GR=Uj().default(()=>[]),KR=Uj();new IR(GR,{inputSchema:KR,reducer:UR,jsonSchemaExtra:{langgraph_type:`messages`,description:`A list of chat messages`}}),new BR(GR,{inputSchema:KR,reducer:WR,jsonSchemaExtra:{langgraph_type:`messages`,description:`A list of chat messages`}});var qR=new class{_map=new Map;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){let n=this.get(e);this._map.set(e,t(n))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){let t={},n=X_(e);for(let[e,r]of Object.entries(n)){let n=this.get(r);n?.reducer?t[e]=new hP(n.reducer.fn,n.default):t[e]=new fP(n?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).filter(([,e])=>e===!0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}:${t}`).join(`|`),r=this._extensionCache.get(n)??new Map;if(r.has(e))return r.get(e);let i=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let n=Object.entries(X_(e)).map(([e,n])=>{let r=this.get(n),i=t.withReducerSchema?r?.reducer?.schema??n:n;if(t.withJsonSchemaExtrasAsDescription&&r?.jsonSchemaExtra){let e=V_(i)??V_(n),t=JSON.stringify({...r.jsonSchemaExtra,description:e});i=i.describe(`lg:${t}`)}return[e,i]});i=Z_(e,Object.fromEntries(n)),j_(i)&&(i._def.unknownKeys=`strip`)}return t.asPartial&&(i=Q_(i)),r.set(e,i),this._extensionCache.set(n,r),i}};function JR(e){return e!=null&&!!(HR.isInstance(e)||Y_(e)||typeof e==`object`&&`lc_graph_name`in e&&e.lc_graph_name===`AnnotationRoot`||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(e=>typeof e==`function`||rP(e)))}function YR(e){if(typeof e!=`object`||!e)return!1;let t=e,n=`state`in t&&JR(t.state),r=`stateSchema`in t&&JR(t.stateSchema),i=`input`in t&&JR(t.input);return!(!n&&!r&&!i||`input`in t&&t.input!=null&&!JR(t.input)||`output`in t&&t.output!=null&&!JR(t.output))}var XR=`__root__`,ZR=`__default_error_handler__`,QR=Symbol.for(`langgraph.state.partial`),$R=class extends yR{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=qR;_configSchema;_configRuntimeSchema;_interrupt;_writer;_nodeDefaults={};constructor(e,t){super();let n=this._normalizeToStateGraphInit(e,t),r=n.state??n.stateSchema??n.input;if(!r)throw new nw;let i=this._getChannelsFromSchema(r);this._schemaDefinition=i,(HR.isInstance(r)||Y_(r))&&(this._schemaRuntimeDefinition=r),n.input&&(HR.isInstance(n.input)||Y_(n.input))?this._inputRuntimeDefinition=n.input:this._inputRuntimeDefinition=QR,n.output&&(HR.isInstance(n.output)||Y_(n.output))?this._outputRuntimeDefinition=n.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let a=n.input?this._getChannelsFromSchema(n.input):i,o=n.output?this._getChannelsFromSchema(n.output):i;this._inputDefinition=a,this._outputDefinition=o,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),n.context&&Y_(n.context)&&(this._configRuntimeSchema=n.context),this._interrupt=n.interrupt,this._writer=n.writer}setNodeDefaults(e){return e.retryPolicy!==void 0&&(this._nodeDefaults.retryPolicy=e.retryPolicy),e.cachePolicy!==void 0&&(this._nodeDefaults.cachePolicy=typeof e.cachePolicy==`boolean`?e.cachePolicy?{}:void 0:e.cachePolicy),e.timeout!==void 0&&(this._nodeDefaults.timeout=BS(e.timeout)),e.errorHandler!==void 0&&(this._nodeDefaults.errorHandler=e.errorHandler),this}_createDefaultErrorHandlerSpec(){let e=this._nodeDefaults.errorHandler;if(e!==void 0)return{runnable:new jP({func:(t,n)=>{let r=n?.configurable?.[lC];return e(t,r,n)},name:ZR,trace:!1}),metadata:void 0,input:this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0}}_normalizeToStateGraphInit(e,t){if(YR(e)){if(Y_(t)||gP.isInstance(t))return{...e,context:t};let n=t;return{...e,input:e.input??n?.input,output:e.output??n?.output,context:e.context??n?.context,interrupt:e.interrupt??n?.interrupt,writer:e.writer??n?.writer,nodes:e.nodes??n?.nodes}}if(JR(e)){if(Y_(t)||gP.isInstance(t))return{state:e,context:t};let n=t;return{state:e,input:n?.input,output:n?.output,context:n?.context,interrupt:n?.interrupt,writer:n?.writer,nodes:n?.nodes}}if(nz(e))return{state:ez(e.channels)};throw new nw}_getChannelsFromSchema(e){if(HR.isInstance(e))return e.getChannels();if(Y_(e))return this._metaRegistry.getChannelsForSchema(e);if(typeof e==`object`&&`lc_graph_name`in e&&e.lc_graph_name===`AnnotationRoot`)return e.spec;if(typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0)return e;throw new nw(`Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.`)}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(e=>[e,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(let[t,n]of Object.entries(e)){let e;if(e=typeof n==`function`?n():n,this.channels[t]!==void 0){if(!this.channels[t].equals(e)&&e.lc_graph_name!==`LastValue`)throw Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=e}}}addNode(...e){function t(e){return e.length>=1&&typeof e[0]!=`string`}let n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([e,t])=>[e,t]):[[e[0],e[1],e[2]]];if(n.length===0)throw Error("No nodes provided in `addNode`");for(let[e,t,r]of n){if(e in this.channels)throw Error(`${e} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(let t of[`|`,`:`])if(e.includes(t))throw Error(`"${t}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`),e in this.nodes)throw Error(`Node \`${e}\` already present.`);if(e===`__end__`||e===`__start__`)throw Error(`Node \`${e}\` is reserved.`);let n=this._schemaDefinition;r?.input!==void 0&&(n=this._getChannelsFromSchema(r.input)),this._addSchema(n);let i;i=tS.isRunnable(t)?t:typeof t==`function`?new jP({func:t,name:e,trace:!1}):fS(t);let a=r?.cachePolicy,o;a!==void 0&&(o=typeof a==`boolean`?a?{}:!1:a);let s;if(r?.errorHandler!==void 0){if(s=`__error_handler__${e}`,s in this.nodes)throw Error(`Cannot add error handler to node \`${e}\`: the reserved name \`${s}\` is already in use. StateGraph registers \`__error_handler__<nodeName>\` when you pass \`errorHandler\` in addNode options. Remove or rename the existing node with that name (for example, you may have added it manually).`);let t=r.errorHandler,i={runnable:new jP({func:(e,n)=>{let r=n?.configurable?.[lC];return t(e,r,n)},name:s,trace:!1}),metadata:void 0,input:n??this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0};this.nodes[s]=i}let c={runnable:i,retryPolicy:r?.retryPolicy,cachePolicy:o,timeout:BS(r?.timeout),metadata:r?.metadata,input:n??this._schemaDefinition,subgraphs:$P(i)?[i]:r?.subgraphs,ends:r?.ends,defer:r?.defer,errorHandlerNode:s};this.nodes[e]=c}return this}addEdge(e,t){if(typeof e==`string`)return super.addEdge(e,t);this.compiled&&console.warn(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`);for(let t of e){if(t===`__end__`)throw Error(`END cannot be a start node`);if(!Object.keys(this.nodes).some(e=>e===t))throw Error(`Need to add a node named "${t}" first`)}if(t===`__end__`)throw Error(`END cannot be an end node`);if(!Object.keys(this.nodes).some(e=>e===t))throw Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){let t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw Error(`Sequence requires at least one node.`);let n;for(let[e,r,i]of t){if(e in this.nodes)throw Error(`Node names must be unique: node with the name "${e}" already exists.`);let t=e;this.addNode(e,r,i),n!=null&&this.addEdge(n,t),n=t}return this}compile({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:i,name:a,description:o,transformers:s}={}){let c=this._createDefaultErrorHandlerSpec();if(c!==void 0){if(ZR in this.nodes)throw Error(`Cannot apply a default error handler: the reserved node name \`${ZR}\` is already in use. setNodeDefaults({ errorHandler }) registers a node with that name; rename the conflicting node.`);this.nodes[ZR]=c}try{return this._compileResolved({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:i,name:a,description:o,transformers:s,defaultErrorHandlerNode:c===void 0?void 0:ZR})}finally{c!==void 0&&delete this.nodes[ZR]}}_compileResolved({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:i,name:a,description:o,transformers:s,defaultErrorHandlerNode:c}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(i)?i:[]]);let l=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),u=l.length===1&&l[0]===XR?XR:l,d=Object.keys(this.channels),f=d.length===1&&d[0]===XR?XR:d,p=this._interrupt,m=new tz({builder:this,checkpointer:e,interruptAfter:i,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[VS]:new tF},inputChannels:VS,outputChannels:u,streamChannels:f,streamMode:`updates`,store:t,cache:n,name:a,description:o,userInterrupt:p,streamTransformers:s});m.attachNode(VS);let h=this._nodeDefaults,g=h.retryPolicy!==void 0||h.cachePolicy!==void 0||h.timeout!==void 0||c!==void 0;for(let[e,t]of Object.entries(this.nodes)){let n=t.isErrorHandler===!0,r=g?{...t,retryPolicy:t.retryPolicy??h.retryPolicy,cachePolicy:n||t.cachePolicy===!1?void 0:t.cachePolicy??h.cachePolicy,timeout:t.timeout??h.timeout,errorHandlerNode:!n&&c!==void 0&&t.errorHandlerNode===void 0?c:t.errorHandlerNode}:t;m.attachNode(e,r)}m.attachBranch(VS,yC,iz(),{withReader:!1});for(let[e]of Object.entries(this.nodes))m.attachBranch(e,yC,iz(),{withReader:!1});for(let[e,t]of this.edges)m.attachEdge(e,t);for(let[e,t]of this.waitingEdges)m.attachEdge(e,t);for(let[e,t]of Object.entries(this.branches))for(let[n,r]of Object.entries(t))m.attachBranch(e,n,r);return m.validate()}};function ez(e){let t={};for(let[n,r]of Object.entries(e))t[n]=vP(r);return t}var tz=class extends bR{description;_metaRegistry=qR;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let n;n=e===`__start__`?Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([e])=>e):Object.keys(this.builder.channels);function r(e){if(FC(e))return e.graph===PC.PARENT?null:e._updateAsTuples();if(Array.isArray(e)&&e.length>0&&e.some(e=>FC(e))){let t=[];for(let n of e)if(FC(n)){if(n.graph===PC.PARENT)continue;t.push(...n._updateAsTuples())}else t.push([XR,n]);return t}else if(e!=null)return[[XR,e]];return null}let i=e,a=async e=>{if(e==null||e.length===0)return e;let t=this.builder._schemaRuntimeDefinition;if(HR.isInstance(t)){let n=new Set(t.getChannelKeys());return Promise.all(e.map(async([e,r])=>{if(!n.has(e))return[e,r];let i=await t.validateInput({[e]:r});return[e,Object.prototype.hasOwnProperty.call(i,e)?i[e]:r]}))}if(Y_(t)){let n=new Set(Object.keys(X_(t)));if(e.filter(([e])=>n.has(e)).length===0)return e;let r=Q_(this._metaRegistry.getExtendedChannelSchemas(t,{withReducerSchema:!0})),i=Q_(t);return e.map(([e,t])=>{if(!n.has(e))return[e,t];let[a,o]=jC(t);if(a){let n=B_(i,{[e]:o});return[e,Object.prototype.hasOwnProperty.call(n,e)?{[AC]:n[e]}:t]}let s=B_(r,{[e]:t});return[e,Object.prototype.hasOwnProperty.call(s,e)?s[e]:t]})}return e};async function o(e){if(!e)return null;if(FC(e))return e.graph===PC.PARENT?null:a(e._updateAsTuples().filter(([e])=>n.includes(e)));if(Array.isArray(e)&&e.length>0&&e.some(FC)){let t=[];for(let r of e)if(FC(r)){if(r.graph===PC.PARENT)continue;t.push(...r._updateAsTuples().filter(([e])=>n.includes(e)))}else{let e=await o(r);e&&t.push(...e??[])}return a(t)}else if(typeof e==`object`&&!Array.isArray(e))return a(Object.entries(e).filter(([e])=>n.includes(e)));else{let t=Array.isArray(e)?`array`:typeof e;throw new ew(`Expected node "${i.toString()}" to return an object or an array containing at least one Command object, received ${t}`,{lc_error_code:`INVALID_GRAPH_NODE_RETURN_VALUE`})}}let s=[{value:LP,mapper:new jP({func:n.length&&n[0]===XR?r:o,trace:!1,recurse:!1})}];if(e===`__start__`)this.nodes[e]=new GP({tags:[vC],triggers:[VS],channels:[VS],writers:[new BP(s,[vC])]});else{let n=t?.input??this.builder._schemaDefinition,r=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(n)).map(e=>[e,e])),i=Object.keys(r).length===1&&XR in r,a=`branch:to:${e}`;this.channels[a]=t?.defer?new pP:new tF(!1);let o=t?.cachePolicy,c=o===!1?void 0:o;this.nodes[e]=new GP({triggers:[a],channels:i?Object.keys(r):r,writers:[new BP(s,[vC])],mapper:i?void 0:e=>Object.fromEntries(Object.entries(e).filter(([e])=>e in r)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:c,timeout:t?.timeout,subgraphs:t?.subgraphs,ends:t?.ends,isErrorHandler:t?.isErrorHandler,errorHandlerNode:t?.errorHandlerNode})}}attachEdge(e,t){if(t!==`__end__`){if(typeof e==`string`)this.nodes[e].writers.push(new BP([{channel:`branch:to:${t}`,value:null}],[vC]));else if(Array.isArray(e)){let n=`join:${e.join(`+`)}:${t}`;this.channels[n]=this.builder.nodes[t].defer?new ER(new Set(e)):new TR(new Set(e)),this.nodes[t].triggers.push(n);for(let t of e)this.nodes[t].writers.push(new BP([{channel:n,value:t}],[vC]))}}}attachBranch(e,t,n,r={withReader:!0}){this.nodes[e].writers.push(n.run(async(t,n)=>{let r=t.filter(e=>e!==HS);if(!r.length)return;let i=r.map(t=>kC(t)?t:{channel:t===`__end__`?t:`branch:to:${t}`,value:e});await BP.doWrite({...n,tags:(n.tags??[]).concat([vC])},i)},r.withReader?e=>UP.doRead(e,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;let t=this.builder._inputRuntimeDefinition,n=this.builder._schemaRuntimeDefinition;if(HR.isInstance(t)){if(FC(e)){let n=e;return e.update&&(n.update=await t.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),n}return await t.validateInput(e)}if(t===QR&&HR.isInstance(n)){if(FC(e)){let t=e;return e.update&&(t.update=await n.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),t}return await n.validateInput(e)}let r=(()=>{let e=e=>{if(e!=null)return this._metaRegistry.getExtendedChannelSchemas(e,{withReducerSchema:!0})};if(Y_(t))return e(t);if(t===QR)return Y_(n)?Q_(e(n)):void 0})();if(FC(e)){let t=e;if(e.update&&r!=null){let n=Array.isArray(e.update)?Object.fromEntries(e.update):e.update,i=B_(r,n);t.update=Object.fromEntries(Object.keys(n).map(e=>[e,i[e]]))}return t}return r==null?e:B_(r,e)}isInterrupted(e){return NC(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return Y_(t)&&B_(t,e),e}};function nz(e){return typeof e==`object`&&!!e&&e.channels!==void 0}function rz(e){if(kC(e))return[e];let t=[];FC(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(FC));let n=[];for(let e of t){if(e.graph===PC.PARENT)throw new qC(e);kC(e.goto)||typeof e.goto==`string`?n.push(e.goto):Array.isArray(e.goto)&&n.push(...e.goto)}return n}function iz(){return new vR({path:new jP({func:rz,tags:[vC],trace:!1,recurse:!1,name:`<control_branch>`})})}var az=e=>Array.isArray(e)&&e.every(Kt),oz=e=>typeof e==`object`&&!!e&&`messages`in e&&az(e.messages),sz=e=>typeof e==`object`&&!!e&&`lg_tool_call`in e,cz=class extends jP{tools;handleToolErrors=!0;trace=!1;constructor(e,t){let{name:n,tags:r,handleToolErrors:i}=t??{};super({name:n,tags:r,func:(e,t)=>this.run(e,t)}),this.tools=e,this.handleToolErrors=i??this.handleToolErrors}async runTool(e,t,n){let r=this.tools.find(t=>t.name===e.name);try{if(r===void 0)throw Error(`Tool "${e.name}" not found.`);let i={...e,type:`tool_call`},a={...t,state:n,toolCallId:e.id??``,config:t,context:t.context,store:t.store??null,writer:t.writer??t.configurable?.writer??null},o=await r.invoke(i,a);return Kt(o)&&o.getType()===`tool`||FC(o)?o:new Xt({status:`success`,name:r.name,content:typeof o==`string`?o:JSON.stringify(o),tool_call_id:e.id})}catch(t){if(!this.handleToolErrors||XC(t))throw t;return new Xt({status:`error`,content:`Error: ${t.message}\n Please fix your mistakes.`,name:e.name,tool_call_id:e.id??``})}}async run(e,t){let n;if(sz(e)){let{lg_tool_call:r,...i}=e;n=[await this.runTool(r,t,i)]}else{let r;if(az(e))r=e;else if(oz(e))r=e.messages;else throw Error(`ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.`);let i=new Set(r.filter(e=>e.getType()===`tool`).map(e=>e.tool_call_id)),a;for(let e=r.length-1;e>=0;--e){let t=r[e];if(jn(t)){a=t;break}}if(a==null||!jn(a))throw Error(`ToolNode only accepts AIMessages as input.`);n=await Promise.all(a.tool_calls?.filter(e=>e.id==null||!i.has(e.id)).map(n=>this.runTool(n,t,e))??[])}if(!n.some(FC))return Array.isArray(e)?n:{messages:n};let r=[],i=null;for(let t of n)FC(t)?t.graph===PC.PARENT&&Array.isArray(t.goto)&&t.goto.every(e=>kC(e))?i?i.goto.push(...t.goto):i=new PC({graph:PC.PARENT,goto:t.goto}):r.push(t):r.push(Array.isArray(e)?[t]:{messages:[t]});return i&&r.push(i),r}},lz=/<name>(.*?)<\/name>/s,uz=/<content>(.*?)<\/content>/s;function dz(e){if(!(Kt(e)&&(jn(e)||qt(e)&&Mn(e)))||!e.name)return e;let{name:t}=e;if(typeof e.content==`string`)return new An({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:`<name>${t}</name><content>${e.content}</content>`,name:void 0});let n=[],r=0;for(let i of e.content)typeof i==`string`?(r+=1,n.push(`<name>${t}</name><content>${i}</content>`)):typeof i==`object`&&`type`in i&&i.type===`text`?(r+=1,n.push({...i,text:`<name>${t}</name><content>${i.text}</content>`})):n.push(i);return r||n.unshift({type:`text`,text:`<name>${t}</name><content></content>`}),new An({...e.lc_kwargs,content:n,name:void 0})}function fz(e){if(!jn(e)||!e.content)return e;let t=[],n;if(Array.isArray(e.content))t=e.content.filter(e=>{if(e.type===`text`&&typeof e.text==`string`){let t=e.text.match(lz),r=e.text.match(uz);return t&&(!r||r[1]===``)?(n=t[1],!1):!0}return!0}).map(e=>{if(e.type===`text`&&typeof e.text==`string`){let t=e.text.match(lz),r=e.text.match(uz);return!t||!r?e:(n=t[1],{...e,text:r[1]})}return e});else{let r=e.content,i=r.match(lz),a=r.match(uz);if(!i||!a)return e;n=i[1],t=a[1]}return new An({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:n})}function pz(e,t){let n,r;if(t===`inline`)n=dz,r=fz;else throw Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);function i(e){return e.map(n)}return aS.from([lS.from(i),e,lS.from(r)])}function mz(e){if(typeof e==`string`||Kt(e)&&e._getType()===`system`)return e;if(typeof e==`function`)return async t=>e(t.messages);if(tS.isRunnable(e))return lS.from(e=>e.messages).pipe(e);throw Error(`Unexpected type for messageModifier: ${typeof e}`)}var hz=`prompt`;function gz(e){let t;if(e==null)t=lS.from(e=>e.messages).withConfig({runName:hz});else if(typeof e==`string`){let n=new qn(e);t=lS.from(e=>[n,...e.messages??[]]).withConfig({runName:hz})}else if(Kt(e)&&e._getType()===`system`)t=lS.from(t=>[e,...t.messages]).withConfig({runName:hz});else if(typeof e==`function`)t=lS.from(e).withConfig({runName:hz});else if(tS.isRunnable(e))t=e;else throw Error(`Got unexpected type for 'prompt': ${typeof e}`);return t}function _z(e){return tS.isRunnable(e)}function vz(e,t,n){if([e,t,n].filter(e=>e!=null).length>1)throw Error(`Expected only one of prompt, stateModifier, or messageModifier, got multiple values`);let r=e;return t==null?n!=null&&(r=mz(n)):r=t,gz(r)}function yz(e){return`invoke`in e&&typeof e.invoke==`function`&&`_modelType`in e}function bz(e){return`_queuedMethodOperations`in e&&`_model`in e&&typeof e._model==`function`}function xz(e){return yz(e)?`bindTools`in e&&typeof e.bindTools==`function`:!1}async function Sz(e,t){let n=e;if(aS.isRunnableSequence(n)&&(n=n.steps.find(e=>nS.isRunnableBinding(e)||yz(e)||bz(e))||n),bz(n)&&(n=await n._model()),!nS.isRunnableBinding(n))return!0;let r=n.kwargs!=null&&typeof n.kwargs==`object`&&`tools`in n.kwargs&&Array.isArray(n.kwargs.tools)?n.kwargs.tools??null:n.config!=null&&typeof n.config==`object`&&`tools`in n.config&&Array.isArray(n.config.tools)?n.config.tools??null:null;if(r!=null&&r.length===1&&`functionDeclarations`in r[0]&&(r=r[0].functionDeclarations),r==null)return!0;if(t.length!==r.length)throw Error(`Number of tools in the model.bindTools() and tools passed to createReactAgent must match`);let i=new Set(t.flatMap(e=>_z(e)?e.name:[])),a=new Set;for(let e of r){let t;if(`type`in e&&e.type===`function`)t=e.function.name;else if(`name`in e)t=e.name;else if(`toolSpec`in e&&`name`in e.toolSpec)t=e.toolSpec.name;else continue;t&&a.add(t)}let o=[...i].filter(e=>!a.has(e));if(o.length>0)throw Error(`Missing tools '${o}' in the model.bindTools().Tools in the model.bindTools() must match the tools passed to createReactAgent.`);return!1}var Cz=(e,t)=>{if(xz(e))return e.bindTools(t);if(nS.isRunnableBinding(e)&&xz(e.bound)){let n=e.bound.bindTools(t);return nS.isRunnableBinding(n)?new nS({bound:n.bound,config:{...e.config,...n.config},kwargs:{...e.kwargs,...n.kwargs},configFactories:n.configFactories??e.configFactories}):new nS({bound:n,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};async function wz(e,t){let n=Cz(e,t);if(n)return n;if(bz(e)){let n=Cz(await e._model(),t);if(n)return n}if(aS.isRunnableSequence(e)){let n=e.steps.findIndex(e=>nS.isRunnableBinding(e)||yz(e)||bz(e));if(n>=0){let r=Cz(e.steps[n],t);if(r){let t=e.steps.slice();return t.splice(n,1,r),aS.from(t)}}}throw Error(`llm ${e} must define bindTools method.`)}async function Tz(e){let t=e;if(aS.isRunnableSequence(t)&&(t=t.steps.find(e=>nS.isRunnableBinding(e)||yz(e)||bz(e))||t),bz(t)&&(t=await t._model()),nS.isRunnableBinding(t)&&(t=t.bound),!yz(t))throw Error(`Expected \`llm\` to be a ChatModel or RunnableBinding (e.g. llm.bind_tools(...)) with invoke() and generate() methods, got ${t.constructor.name}`);return t}var Ez=()=>_P.Root({messages:_P({reducer:UR,default:()=>[]}),structuredResponse:_P}),Dz=_P.Root({llmInputMessages:_P({reducer:(e,t)=>UR([],t),default:()=>[]})});function Oz(e){let{llm:t,tools:n,messageModifier:r,stateModifier:i,prompt:a,stateSchema:o,contextSchema:s,checkpointSaver:c,checkpointer:l,interruptBefore:u,interruptAfter:d,store:f,responseFormat:p,preModelHook:m,postModelHook:h,name:g,description:_,version:v=`v1`,includeAgentName:y}=e,b,ee;Array.isArray(n)?(b=n,ee=new cz(b.filter(_z))):(b=n.tools,ee=n);let te=null,ne=async e=>{if(te)return te;let t;t=await Sz(e,b)?await wz(e,b):e;let n=vz(a,i,r),o=y===`inline`?pz(t,y):t;return te=n.pipe(o),te},x=async(e,t,n)=>{let o=await e(t,n);return vz(a,i,r).pipe(y===`inline`?pz(o,y):o)},re=new Set(b.filter(_z).filter(e=>`returnDirect`in e&&e.returnDirect).map(e=>e.name));function ie(e){let{messages:t,llmInputMessages:n,...r}=e;return n!=null&&n.length>0?{messages:n,...r}:{messages:t,...r}}let ae=async(e,n)=>{if(p==null)throw Error(`Attempted to generate structured output with no passed response schema. Please contact us for help.`);let r=[...e.messages],i,a=typeof t==`function`?await t(e,n):await Tz(t);if(!yz(a))throw Error(`Expected \`llm\` to be a ChatModel with .withStructuredOutput() method, got ${a.constructor.name}`);if(typeof p==`object`&&`schema`in p){let{prompt:e,schema:t,...n}=p;i=a.withStructuredOutput(t,n),e!=null&&r.unshift(new qn({content:e}))}else i=a.withStructuredOutput(p);let o=await i.invoke(r,n);if(o==null)throw Error("Failed to parse structured response against the provided `responseFormat` schema: the structured-output parser returned null/undefined, which usually means the model output did not satisfy the schema.");return{structuredResponse:o}},oe=async(e,n)=>{let r=await(typeof t==`function`?await x(t,e,n):await ne(t)).invoke(ie(e),n);return r.name=g,r.lc_kwargs.name=g,{messages:[r]}},se=new $R(o??Ez(),s).addNode(`tools`,ee);if(!(`messages`in se._schemaDefinition))throw Error("Missing required `messages` key in state schema.");let ce=se,le=e=>Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null)),S=`agent`,C;return m==null?S=`agent`:(ce.addNode(`pre_model_hook`,m).addEdge(`pre_model_hook`,`agent`),S=`pre_model_hook`,C=_P.Root({...se._schemaDefinition,...Dz.spec})),ce.addNode(`agent`,oe,{input:C}).addEdge(VS,S),h!=null&&ce.addNode(`post_model_hook`,h).addEdge(`agent`,`post_model_hook`).addConditionalEdges(`post_model_hook`,e=>{let{messages:t}=e,n=new Set(t.filter($t).map(e=>e.tool_call_id)),r;for(let e=t.length-1;e>=0;--e){let n=t[e];if(jn(n)){r=n;break}}let i=r?.tool_calls?.filter(e=>e.id==null||!n.has(e.id))??[],a=t[t.length-1];return i.length>0?v===`v2`?i.map(t=>new OC(`tools`,{...e,lg_tool_call:t})):`tools`:a&&$t(a)?S:p==null?HS:`generate_structured_response`},le({tools:`tools`,[S]:S,generate_structured_response:p==null?null:`generate_structured_response`,[HS]:p==null?HS:null})),p!==void 0&&se.addNode(`generate_structured_response`,ae).addEdge(`generate_structured_response`,HS),h??ce.addConditionalEdges(`agent`,e=>{let{messages:t}=e,n=t[t.length-1];return!jn(n)||!n.tool_calls?.length?p==null?HS:`generate_structured_response`:v===`v2`?n.tool_calls.map(t=>new OC(`tools`,{...e,lg_tool_call:t})):`tools`},le({tools:`tools`,generate_structured_response:p==null?null:`generate_structured_response`,[HS]:p==null?HS:null})),re.size>0?ce.addConditionalEdges(`tools`,e=>{let t=e;for(let e=t.messages.length-1;e>=0;--e){let n=t.messages[e];if(!$t(n))break;if(n.name!==void 0&&re.has(n.name))return HS}return S},le({[S]:S,[HS]:HS})):ce.addEdge(`tools`,S),ce.compile({checkpointer:l??c,interruptBefore:u,interruptAfter:d,store:f,name:g,description:_})}function kz(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}function U(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function W(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var Az=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Az=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function jz(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var Mz=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},G=class extends Error{},Nz=class e extends G{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new Fz({message:r,cause:Mz(n)});let a=n?.error;return t===400?new Lz(t,a,r,i):t===401?new Rz(t,a,r,i):t===403?new zz(t,a,r,i):t===404?new Bz(t,a,r,i):t===409?new Vz(t,a,r,i):t===422?new Hz(t,a,r,i):t===429?new Uz(t,a,r,i):t>=500?new Wz(t,a,r,i):new e(t,a,r,i)}},Pz=class extends Nz{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},Fz=class extends Nz{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},Iz=class extends Fz{constructor({message:e}={}){super({message:e??`Request timed out.`})}},Lz=class extends Nz{},Rz=class extends Nz{},zz=class extends Nz{},Bz=class extends Nz{},Vz=class extends Nz{},Hz=class extends Nz{},Uz=class extends Nz{},Wz=class extends Nz{},Gz=class extends G{constructor(){super(`Could not parse response content as the length limit was reached`)}},Kz=class extends G{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},qz=class extends Error{constructor(e){super(e)}},Jz=class extends Nz{constructor(e,t,n){let r=`OAuth2 authentication error`,i;if(t&&typeof t==`object`){let e=t;i=e.error;let n=e.error_description;n&&typeof n==`string`?r=n:i&&(r=i)}super(e,t,r,n),this.error_code=i}},Yz=class extends G{constructor(e,t,n){super(e),this.provider=t,this.cause=n}},Xz=/^[a-z][a-z0-9+.-]*:/i,Zz=e=>Xz.test(e),Qz=e=>(Qz=Array.isArray,Qz(e)),$z=Qz;function eB(e){return typeof e==`object`?e??{}:{}}function tB(e){if(!e)return!0;for(let t in e)return!1;return!0}function nB(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function rB(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var iB=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new G(`${e} must be an integer`);if(t<0)throw new G(`${e} must be a positive integer`);return t},aB=e=>{try{return JSON.parse(e)}catch{return}},oB=e=>new Promise(t=>setTimeout(t,e)),sB=`6.45.0`,cB=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function lB(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var uB=()=>{let e=lB();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":sB,"X-Stainless-OS":pB(Deno.build.os),"X-Stainless-Arch":fB(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":sB,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":sB,"X-Stainless-OS":pB(globalThis.process.platform??`unknown`),"X-Stainless-Arch":fB(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=dB();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":sB,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":sB,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function dB(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{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/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var fB=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,pB=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),mB,hB=()=>mB??=uB();function gB(){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 _B(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function vB(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return _B({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function yB(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function bB(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var xB=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),SB=`RFC3986`,CB=e=>String(e),wB={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:CB},TB=(e,t)=>(TB=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),TB(e,t)),EB=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),DB=1024,OB=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=DB){let t=a.length>=DB?a.slice(e,e+DB):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=EB[r];continue}if(r<2048){n[n.length]=EB[192|r>>6]+EB[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=EB[224|r>>12]+EB[128|r>>6&63]+EB[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=EB[240|r>>18]+EB[128|r>>12&63]+EB[128|r>>6&63]+EB[128|r&63]}o+=n.join(``)}return o};function kB(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function AB(e,t){if(Qz(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var jB={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},MB=function(e,t){Array.prototype.push.apply(e,Qz(t)?t:[t])},NB,PB={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:OB,encodeValuesOnly:!1,format:SB,formatter:CB,indices:!1,serializeDate(e){return(NB??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function FB(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var IB={};function LB(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,ee=!1;for(;(y=y.get(IB))!==void 0&&!ee;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);ee=!0}y.get(IB)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&Qz(v)&&(v=AB(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,PB.encoder,g,`key`,p):t;v=``}if(FB(v)||kB(v)){if(c){let e=h?t:c(t,PB.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,PB.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let te=[];if(v===void 0)return te;let ne;if(n===`comma`&&Qz(v))h&&c&&(v=AB(v,c)),ne=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(Qz(l))ne=l;else{let e=Object.keys(v);ne=u?e.sort(u):e}let x=s?String(t).replace(/\./g,`%2E`):String(t),re=r&&Qz(v)&&v.length===1?x+`[]`:x;if(i&&Qz(v)&&v.length===0)return re+`[]`;for(let t=0;t<ne.length;++t){let y=ne[t],ee=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&ee===null)continue;let x=d&&s?y.replace(/\./g,`%2E`):y,ie=Qz(v)?typeof n==`function`?n(re,x):re:re+(d?`.`+x:`[`+x+`]`);_.set(e,b);let ae=new WeakMap;ae.set(IB,_),MB(te,LB(ee,ie,n,r,i,a,o,s,n===`comma`&&h&&Qz(v)?null:c,l,u,d,f,p,m,h,g,ae))}return te}function RB(e=PB){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||PB.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=SB;if(e.format!==void 0){if(!TB(wB,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=wB[n],i=PB.filter;(typeof e.filter==`function`||Qz(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in jB?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:PB.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:PB.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:PB.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:PB.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:PB.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?PB.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:PB.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:PB.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:PB.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:PB.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:PB.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:PB.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:PB.strictNullHandling}}function zB(e,t={}){let n=e,r=RB(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):Qz(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=jB[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||MB(o,LB(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function BB(e){return zB(e,{arrayFormat:`brackets`})}function VB(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var HB;function UB(e){let t;return(HB??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var WB;function GB(e){let t;return(WB??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var KB,qB,JB=class{constructor(){KB.set(this,void 0),qB.set(this,void 0),U(this,KB,new Uint8Array,`f`),U(this,qB,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?UB(e):e;U(this,KB,VB([W(this,KB,`f`),t]),`f`);let n=[],r;for(;(r=YB(W(this,KB,`f`),W(this,qB,`f`)))!=null;){if(r.carriage&&W(this,qB,`f`)==null){U(this,qB,r.index,`f`);continue}if(W(this,qB,`f`)!=null&&(r.index!==W(this,qB,`f`)+1||r.carriage)){n.push(GB(W(this,KB,`f`).subarray(0,W(this,qB,`f`)-1))),U(this,KB,W(this,KB,`f`).subarray(W(this,qB,`f`)),`f`),U(this,qB,null,`f`);continue}let e=W(this,qB,`f`)===null?r.preceding:r.preceding-1,t=GB(W(this,KB,`f`).subarray(0,e));n.push(t),U(this,KB,W(this,KB,`f`).subarray(r.index),`f`),U(this,qB,null,`f`)}return n}flush(){return W(this,KB,`f`).length?this.decode(`
|
|
191
|
-
`):[]}};
|
|
192
|
-
`,`\r`]),
|
|
193
|
-
`);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*
|
|
194
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=uV(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function uV(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function dV(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return rV(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):oV.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:fV(await n.json(),n):await n.text()})();return rV(e).debug(`[${r}] response parsed`,iV({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function fV(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`x-request-id`),enumerable:!1})}var pV,mV=class e extends Promise{constructor(e,t,n=dV){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,pV.set(this,void 0),U(this,pV,e,`f`)}_thenUnwrap(t){return new e(W(this,pV,`f`),this.responsePromise,async(e,n)=>fV(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(W(this,pV,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};pV=new WeakMap;var hV,gV=class{constructor(e,t,n,r){hV.set(this,void 0),U(this,hV,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new G("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await W(this,hV,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(hV=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},_V=class extends mV{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await dV(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},vV=class extends gV{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},yV=class extends gV{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...eB(this.options.query),after:t}}:null}},bV=class extends gV{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...eB(this.options.query),after:e}}:null}},xV=class extends gV{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...eB(this.options.query),after:e}}:null}},SV={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},CV=`urn:ietf:params:oauth:grant-type:token-exchange`,wV=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??gB()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e={grant_type:CV,subject_token:await this.config.provider.getToken(),subject_token_type:SV[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(e.client_id=this.config.clientId);let t=await this.fetch(this.tokenExchangeUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.text(),n;try{n=JSON.parse(e)}catch{}throw t.status===400||t.status===401||t.status===403?new Jz(t.status,n,t.headers):Nz.generate(t.status,n,`Token exchange failed with status ${t.status}`,t.headers)}let n=await t.json();if(typeof n!=`object`||!n||!(`access_token`in n)||typeof n.access_token!=`string`||n.access_token.trim().length===0)throw new G(`Token exchange response missing 'access_token' field`);let r=n.access_token,i=n.expires_in??3600,a=Date.now()+i*1e3;return this.cachedToken={token:r,expiresAt:a},r}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let t=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-t}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}},TV=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function EV(e,t,n){return TV(),new File(e,t??`unknown_file`,n)}function DV(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}var OV=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,kV=async(e,t)=>IV(e.body)?{...e,body:await NV(e.body,t)}:e,AV=async(e,t)=>({...e,body:await NV(e.body,t)}),jV=new WeakMap;function MV(e){let t=typeof e==`function`?e:e.fetch,n=jV.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return jV.set(t,r),r}var NV=async(e,t)=>{if(!await MV(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>LV(n,e,t))),n},PV=e=>e instanceof Blob&&`name`in e,FV=e=>typeof e==`object`&&!!e&&(e instanceof Response||OV(e)||PV(e)),IV=e=>{if(FV(e))return!0;if(Array.isArray(e))return e.some(IV);if(e&&typeof e==`object`){for(let t in e)if(IV(e[t]))return!0}return!1},LV=async(e,t,n)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response)e.append(t,EV([await n.blob()],DV(n)));else if(OV(n))e.append(t,EV([await new Response(vB(n)).blob()],DV(n)));else if(PV(n))e.append(t,n,DV(n));else if(Array.isArray(n))await Promise.all(n.map(n=>LV(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>LV(e,`${t}[${n}]`,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},RV=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,zV=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&RV(e),BV=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function VV(e,t,n){if(TV(),e=await e,zV(e))return e instanceof File?e:EV([await e.arrayBuffer()],e.name);if(BV(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),EV(await HV(r),t,n)}let r=await HV(e);if(t||=DV(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return EV(r,t,n)}async function HV(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(RV(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(OV(e))for await(let n of e)t.push(...await HV(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${UV(e)}`)}return t}function UV(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var K=class{constructor(e){this._client=e}};function WV(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var GV=Object.freeze(Object.create(null)),q=((e=WV)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??GV)??GV)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new G(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
|
|
195
|
-
`)}\n${a}\n${t}`)}return a})(WV),KV=class extends K{list(e,t={},n){return this._client.getAPIList(q`/chat/completions/${e}/messages`,yV,{query:t,...n,__security:{bearerAuth:!0}})}};function qV(e){return e!==void 0&&`function`in e&&e.function!==void 0}function JV(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:`auto-parseable-response-format`,enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function YV(e){return e?.$brand===`auto-parseable-response-format`}function XV(e){return e?.$brand===`auto-parseable-tool`}function ZV(e,t){return!t||!nH(t)?{...e,choices:e.choices.map(e=>(rH(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:QV(e,t)}function QV(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new Gz;if(e.finish_reason===`content_filter`)throw new Kz;return rH(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>eH(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?$V(t,e.message.content):null}}});return{...e,choices:n}}function $V(e,t){return e.response_format?.type===`json_schema`&&e.response_format?.type===`json_schema`?`$parseRaw`in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function eH(e,t){let n=e.tools?.find(e=>qV(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:XV(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function tH(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>qV(e)&&e.function?.name===t.function.name);return qV(n)&&(XV(n)||n?.function.strict||!1)}function nH(e){return YV(e.response_format)?!0:e.tools?.some(e=>XV(e)||e.type===`function`&&e.function.strict===!0)??!1}function rH(e){for(let t of e||[])if(t.type!==`function`)throw new G(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function iH(e){for(let t of e??[]){if(t.type!==`function`)throw new G(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new G(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var aH=e=>e?.role===`assistant`,oH=e=>e?.role===`tool`,sH,cH,lH,uH,dH,fH,pH,mH,hH,gH,_H,vH,yH,bH,xH,SH=class{constructor(){sH.add(this),this.controller=new AbortController,cH.set(this,void 0),lH.set(this,()=>{}),uH.set(this,()=>{}),dH.set(this,void 0),fH.set(this,()=>{}),pH.set(this,()=>{}),mH.set(this,{}),hH.set(this,[]),gH.set(this,!1),_H.set(this,!1),vH.set(this,!1),yH.set(this,!1),U(this,cH,new Promise((e,t)=>{U(this,lH,e,`f`),U(this,uH,t,`f`)}),`f`),U(this,dH,new Promise((e,t)=>{U(this,fH,e,`f`),U(this,pH,t,`f`)}),`f`),W(this,cH,`f`).catch(()=>{}),W(this,dH,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},W(this,sH,`m`,xH).bind(this))},0)}_connected(){this.ended||(W(this,lH,`f`).call(this),this._emit(`connect`))}get ended(){return W(this,gH,`f`)}get errored(){return W(this,_H,`f`)}get aborted(){return W(this,vH,`f`)}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let t=()=>this.controller.abort();e.addEventListener(`abort`,t,{once:!0}),W(this,hH,`f`).push({signal:e,listener:t})}on(e,t){return(W(this,mH,`f`)[e]||(W(this,mH,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=W(this,mH,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(W(this,mH,`f`)[e]||(W(this,mH,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{U(this,yH,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){U(this,yH,!0,`f`),await W(this,dH,`f`)}_emit(e,...t){if(W(this,gH,`f`))return;e===`end`&&(W(this,sH,`m`,bH).call(this),U(this,gH,!0,`f`),W(this,fH,`f`).call(this));let n=W(this,mH,`f`)[e];if(n&&(W(this,mH,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!W(this,yH,`f`)&&!n?.length&&Promise.reject(e),W(this,uH,`f`).call(this,e),W(this,pH,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!W(this,yH,`f`)&&!n?.length&&Promise.reject(e),W(this,uH,`f`).call(this,e),W(this,pH,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};cH=new WeakMap,lH=new WeakMap,uH=new WeakMap,dH=new WeakMap,fH=new WeakMap,pH=new WeakMap,mH=new WeakMap,hH=new WeakMap,gH=new WeakMap,_H=new WeakMap,vH=new WeakMap,yH=new WeakMap,sH=new WeakSet,bH=function(){for(let{signal:e,listener:t}of W(this,hH,`f`).splice(0))e.removeEventListener(`abort`,t)},xH=function(e){if(U(this,_H,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=new Pz),e instanceof Pz)return U(this,vH,!0,`f`),this._emit(`abort`,e);if(e instanceof G)return this._emit(`error`,e);if(e instanceof Error){let t=new G(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new G(String(e)))};function CH(e){return typeof e.parse==`function`}var wH,TH,EH,DH,OH,kH,AH,jH,MH=10,NH=class extends SH{constructor(){super(...arguments),wH.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),oH(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(aH(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new G(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),W(this,wH,`m`,TH).call(this)}async finalMessage(){return await this.done(),W(this,wH,`m`,EH).call(this)}async finalFunctionToolCall(){return await this.done(),W(this,wH,`m`,DH).call(this)}async finalFunctionToolCallResult(){return await this.done(),W(this,wH,`m`,OH).call(this)}async totalUsage(){return await this.done(),W(this,wH,`m`,kH).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=W(this,wH,`m`,EH).call(this);t&&this._emit(`finalMessage`,t);let n=W(this,wH,`m`,TH).call(this);n&&this._emit(`finalContent`,n);let r=W(this,wH,`m`,DH).call(this);r&&this._emit(`finalFunctionToolCall`,r);let i=W(this,wH,`m`,OH).call(this);i!=null&&this._emit(`finalFunctionToolCallResult`,i),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,W(this,wH,`m`,kH).call(this))}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),W(this,wH,`m`,AH).call(this,t);let r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(QV(r,t))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n,r){let i=`tool`,{tool_choice:a=`auto`,stream:o,...s}=t,c=typeof a!=`string`&&a.type===`function`&&a?.function?.name,{maxChatCompletions:l=MH,afterCompletion:u}=r||{},d=t.tools.map(e=>{if(XV(e)){if(!e.$callback)throw new G("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),f={};for(let e of d)e.type===`function`&&(f[e.function.name||e.function.function.name]=e.function);let p=`tools`in t?d.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of t.messages)this._addMessage(e,!1);let m=async e=>{if(e.type!==`function`)return{message:void 0,functionCalled:!1};let t=e.id,{name:r,arguments:a}=e.function,o=f[r];if(!o){let e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(f).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;return{message:{role:i,tool_call_id:t,content:e},functionCalled:!1}}if(c&&c!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(c)} requested. Please try again`;return{message:{role:i,tool_call_id:t,content:e},functionCalled:!1}}let s;if(CH(o)){let e;try{e=await o.parse(a)}catch(e){let n=e instanceof Error?e.message:String(e);return{message:{role:i,tool_call_id:t,content:n},functionCalled:!1}}s=await o.function(e,n)}else s=await o.function(a,n);let l=W(this,wH,`m`,jH).call(this,s);return{message:{role:i,tool_call_id:t,content:l},functionCalled:!0}};for(let i=0;i<l;++i){let i=await this._createChatCompletion(e,{...s,tool_choice:a,tools:p,messages:[...this.messages]},r),o=i.choices[0]?.message;if(!o)throw new G(`missing message in ChatCompletion response`);if(!o.tool_calls?.length){await u?.(i,n);return}if(c||t.parallel_tool_calls===!1)for(let e of o.tool_calls){let t=await m(e);if(t.message&&this._addMessage(t.message),c&&t.functionCalled){await u?.(i,n);return}}else{let e=await Promise.allSettled(o.tool_calls.map(m));for(let t of e)if(t.status===`rejected`)throw t.reason;for(let t of e)t.status===`fulfilled`&&t.value.message&&this._addMessage(t.value.message)}await u?.(i,n)}}};wH=new WeakSet,TH=function(){return W(this,wH,`m`,EH).call(this).content??null},EH=function(){let e=this.messages.length;for(;e-->0;){let t=this.messages[e];if(aH(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new G(`stream ended without producing a ChatCompletionMessage with role=assistant`)},DH=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(aH(t)&&t?.tool_calls?.length)for(let e=t.tool_calls.length-1;e>=0;e--){let n=t.tool_calls[e];if(n?.type===`function`)return n.function}}},OH=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(oH(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},kH=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},AH=function(e){if(e.n!=null&&e.n>1)throw new G(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},jH=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var PH=class e extends NH{static runTools(t,n,r){let i=new e,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),aH(e)&&e.content&&this._emit(`content`,e.content)}},FH={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},IH=class extends Error{},LH=class extends Error{};function RH(e,t=FH.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return zH(e.trim(),t)}var zH=(e,t)=>{let n=e.length,r=0,i=e=>{throw new IH(`${e} at position ${r}`)},a=e=>{throw new LH(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||FH.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||FH.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||FH.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||FH.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||FH.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||FH.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`&&!s,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(FH.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&FH.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(FH.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(FH.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(FH.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&FH.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(FH.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r==n&&!(FH.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&FH.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
|
|
196
|
-
\r `.includes(e[r]);)r++};return o()},BH=e=>RH(e,FH.ALL^FH.NUM),VH,HH,UH,WH,GH,KH,qH,JH,YH,XH,ZH,QH,$H=class e extends NH{constructor(e){super(),VH.add(this),HH.set(this,void 0),UH.set(this,void 0),WH.set(this,void 0),U(this,HH,e,`f`),U(this,UH,[],`f`)}get currentChatCompletionSnapshot(){return W(this,WH,`f`)}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){let i=new e(n);return i._run(()=>i._runChatCompletion(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createChatCompletion(e,t,n){super._createChatCompletion,this._listenForAbort(n?.signal),W(this,VH,`m`,GH).call(this);let r=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let e of r)W(this,VH,`m`,qH).call(this,e);if(r.controller.signal?.aborted)throw new Pz;return this._addChatCompletion(W(this,VH,`m`,XH).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),W(this,VH,`m`,GH).call(this),this._connected();let n=oV.fromReadableStream(e,this.controller),r;for await(let e of n)r&&r!==e.id&&this._addChatCompletion(W(this,VH,`m`,XH).call(this)),W(this,VH,`m`,qH).call(this,e),r=e.id;if(n.controller.signal?.aborted)throw new Pz;return this._addChatCompletion(W(this,VH,`m`,XH).call(this))}[(HH=new WeakMap,UH=new WeakMap,WH=new WeakMap,VH=new WeakSet,GH=function(){this.ended||U(this,WH,void 0,`f`)},KH=function(e){let t=W(this,UH,`f`)[e.index];return t||(t={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,UH,`f`)[e.index]=t,t)},qH=function(e){if(this.ended)return;let t=W(this,VH,`m`,QH).call(this,e);this._emit(`chunk`,e,t);for(let n of e.choices){let e=t.choices[n.index];n.delta.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,n.delta.content,e.message.content),this._emit(`content.delta`,{delta:n.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),n.delta.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:n.delta.refusal,snapshot:e.message.refusal}),n.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),n.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let r=W(this,VH,`m`,KH).call(this,e);e.finish_reason&&(W(this,VH,`m`,YH).call(this,e),r.current_tool_call_index!=null&&W(this,VH,`m`,JH).call(this,e,r.current_tool_call_index));for(let t of n.delta.tool_calls??[])r.current_tool_call_index!==t.index&&(W(this,VH,`m`,YH).call(this,e),r.current_tool_call_index!=null&&W(this,VH,`m`,JH).call(this,e,r.current_tool_call_index)),r.current_tool_call_index=t.index;for(let t of n.delta.tool_calls??[]){let n=e.message.tool_calls?.[t.index];n?.type&&(n?.type===`function`?this._emit(`tool_calls.function.arguments.delta`,{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??``}):n?.type)}}},JH=function(e,t){if(W(this,VH,`m`,KH).call(this,e).done_tool_calls.has(t))return;let n=e.message.tool_calls?.[t];if(!n)throw Error(`no tool call snapshot`);if(!n.type)throw Error("tool call snapshot missing `type`");if(n.type===`function`){let e=W(this,HH,`f`)?.tools?.find(e=>qV(e)&&e.function.name===n.function.name);this._emit(`tool_calls.function.arguments.done`,{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:XV(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},YH=function(e){let t=W(this,VH,`m`,KH).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;let n=W(this,VH,`m`,ZH).call(this);this._emit(`content.done`,{content:e.message.content,parsed:n?n.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit(`refusal.done`,{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},XH=function(){if(this.ended)throw new G(`stream has ended, this shouldn't happen`);let e=W(this,WH,`f`);if(!e)throw new G(`request ended without sending any chunks`);return U(this,WH,void 0,`f`),U(this,UH,[],`f`),eU(e,W(this,HH,`f`))},ZH=function(){let e=W(this,HH,`f`)?.response_format;return YV(e)?e:null},QH=function(e){var t,n,r,i;let a=W(this,WH,`f`),{choices:o,...s}=e;a?Object.assign(a,s):a=U(this,WH,{...s,choices:[]},`f`);for(let{delta:o,finish_reason:s,index:c,logprobs:l=null,...u}of e.choices){let e=a.choices[c];if(e||=a.choices[c]={finish_reason:s,index:c,message:{},logprobs:l,...u},l)if(!e.logprobs)e.logprobs=Object.assign({},l);else{let{content:r,refusal:i,...a}=l;Object.assign(e.logprobs,a),r&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...r)),i&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...i))}if(s&&(e.finish_reason=s,W(this,HH,`f`)&&nH(W(this,HH,`f`)))){if(s===`length`)throw new Gz;if(s===`content_filter`)throw new Kz}if(Object.assign(e,u),!o)continue;let{content:d,refusal:f,function_call:p,role:m,tool_calls:h,...g}=o;if(Object.assign(e.message,g),f&&(e.message.refusal=(e.message.refusal||``)+f),m&&(e.message.role=m),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((r=e.message.function_call).arguments??(r.arguments=``),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),d&&(e.message.content=(e.message.content||``)+d,!e.message.refusal&&W(this,VH,`m`,ZH).call(this)&&(e.message.parsed=e.message.content.trim()?BH(e.message.content):null)),h){e.message.tool_calls||(e.message.tool_calls=[]);for(let{index:t,id:n,type:r,function:a,...o}of h){let s=(i=e.message.tool_calls)[t]??(i[t]={});Object.assign(s,o),n&&(s.id=n),r&&(s.type=r),a&&(s.function??={name:a.name??``,arguments:``}),a?.name&&(s.function.name=a.name),a?.arguments&&(s.function.arguments+=a.arguments,tH(W(this,HH,`f`),s)&&(s.function.parsed_arguments=BH(s.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`chunk`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new oV(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function eU(e,t){let{id:n,choices:r,created:i,model:a,system_fingerprint:o,...s}=e;return ZV({...s,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:i,...a})=>{if(!n)throw new G(`missing finish_reason for choice ${r}`);let{content:o=null,function_call:s,tool_calls:c,...l}=t,u=t.role;if(!u)throw new G(`missing role for choice ${r}`);if(s){let{arguments:e,name:c}=s;if(e==null)throw new G(`missing function_call.arguments for choice ${r}`);if(!c)throw new G(`missing function_call.name for choice ${r}`);return{...a,message:{content:o,function_call:{arguments:e,name:c},role:u,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}return c?{...a,index:r,finish_reason:n,logprobs:i,message:{...l,role:u,content:o,refusal:t.refusal??null,tool_calls:c.map((t,n)=>{let{function:i,type:a,id:o,...s}=t,{arguments:c,name:l,...u}=i||{};if(o==null)throw new G(`missing choices[${r}].tool_calls[${n}].id\n${tU(e)}`);if(a==null)throw new G(`missing choices[${r}].tool_calls[${n}].type\n${tU(e)}`);if(l==null)throw new G(`missing choices[${r}].tool_calls[${n}].function.name\n${tU(e)}`);if(c==null)throw new G(`missing choices[${r}].tool_calls[${n}].function.arguments\n${tU(e)}`);return{...s,id:o,type:a,function:{...u,name:l,arguments:c}}})}}:{...a,message:{...l,content:o,role:u,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}),created:i,model:a,object:`chat.completion`,...o?{system_fingerprint:o}:{}},t)}function tU(e){return JSON.stringify(e)}var nU=class e extends $H{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){let i=new e(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}},rU=class extends K{constructor(){super(...arguments),this.messages=new KV(this._client)}create(e,t){return this._client.post(`/chat/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(q`/chat/completions/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chat/completions`,yV,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return iH(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>QV(t,e))}runTools(e,t){return e.stream?nU.runTools(this._client,e,t):PH.runTools(this._client,e,t)}stream(e,t){return $H.createChatCompletion(this._client,e,t)}};rU.Messages=KV;var iU=class extends K{constructor(){super(...arguments),this.completions=new rU(this._client)}};iU.Completions=rU;var aU=class extends K{create(e,t){return this._client.post(`/organization/admin_api_keys`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(q`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/admin_api_keys`,yV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(q`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},oU=class extends K{list(e={},t){return this._client.getAPIList(`/organization/audit_logs`,bV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},sU=class extends K{create(e,t){return this._client.post(`/organization/certificates`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(q`/organization/certificates/${e}`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/certificates/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/certificates`,bV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(q`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList(`/organization/certificates/activate`,vV,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList(`/organization/certificates/deactivate`,vV,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}},cU=class extends K{retrieve(e){return this._client.get(`/organization/data_retention`,{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post(`/organization/data_retention`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}},lU=class extends K{create(e,t){return this._client.post(`/organization/invites`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(q`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/invites`,bV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(q`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},uU=class extends K{create(e,t){return this._client.post(`/organization/roles`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(q`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/roles/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/roles`,xV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(q`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},dU=class extends K{create(e,t){return this._client.post(`/organization/spend_alerts`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(q`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/spend_alerts/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/spend_alerts`,bV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(q`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},fU=class extends K{audioSpeeches(e,t){return this._client.get(`/organization/usage/audio_speeches`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get(`/organization/usage/audio_transcriptions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get(`/organization/usage/code_interpreter_sessions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get(`/organization/usage/completions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get(`/organization/costs`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get(`/organization/usage/embeddings`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get(`/organization/usage/file_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get(`/organization/usage/images`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get(`/organization/usage/moderations`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get(`/organization/usage/vector_stores`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get(`/organization/usage/web_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},pU=class extends K{create(e,t,n){return this._client.post(q`/organization/groups/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(q`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/organization/groups/${e}/roles`,xV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(q`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},mU=class extends K{create(e,t,n){return this._client.post(q`/organization/groups/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(q`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/organization/groups/${e}/users`,xV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(q`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},hU=class extends K{constructor(){super(...arguments),this.users=new mU(this._client),this.roles=new pU(this._client)}create(e,t){return this._client.post(`/organization/groups`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(q`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/groups/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/groups`,xV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(q`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};hU.Users=mU,hU.Roles=pU;var gU=class extends K{retrieve(e,t,n){let{project_id:r}=t;return this._client.get(q`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/organization/projects/${e}/api_keys`,bV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(q`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},_U=class extends K{list(e,t={},n){return this._client.getAPIList(q`/organization/projects/${e}/certificates`,bV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(q`/organization/projects/${e}/certificates/activate`,vV,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(q`/organization/projects/${e}/certificates/deactivate`,vV,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}},vU=class extends K{retrieve(e,t){return this._client.get(q`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/projects/${e}/data_retention`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},yU=class extends K{retrieve(e,t){return this._client.get(q`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},bU=class extends K{retrieve(e,t){return this._client.get(q`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/projects/${e}/model_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(q`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}},xU=class extends K{listRateLimits(e,t={},n){return this._client.getAPIList(q`/organization/projects/${e}/rate_limits`,bV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:r,...i}=t;return this._client.post(q`/organization/projects/${r}/rate_limits/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},SU=class extends K{create(e,t,n){return this._client.post(q`/projects/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(q`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(q`/projects/${r}/roles/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/projects/${e}/roles`,xV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(q`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},CU=class extends K{create(e,t,n){return this._client.post(q`/organization/projects/${e}/service_accounts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(q`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(q`/organization/projects/${r}/service_accounts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/organization/projects/${e}/service_accounts`,bV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(q`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},wU=class extends K{create(e,t,n){return this._client.post(q`/organization/projects/${e}/spend_alerts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(q`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(q`/organization/projects/${r}/spend_alerts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/organization/projects/${e}/spend_alerts`,bV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(q`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},TU=class extends K{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(q`/projects/${r}/groups/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,group_id:i}=t;return this._client.get(q`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(q`/projects/${r}/groups/${e}/roles`,xV,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,group_id:i}=t;return this._client.delete(q`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},EU=class extends K{constructor(){super(...arguments),this.roles=new TU(this._client)}create(e,t,n){return this._client.post(q`/organization/projects/${e}/groups`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,...i}=t;return this._client.get(q`/organization/projects/${r}/groups/${e}`,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/organization/projects/${e}/groups`,xV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(q`/organization/projects/${r}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};EU.Roles=TU;var DU=class extends K{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(q`/projects/${r}/users/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,user_id:i}=t;return this._client.get(q`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(q`/projects/${r}/users/${e}/roles`,xV,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,user_id:i}=t;return this._client.delete(q`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},OU=class extends K{constructor(){super(...arguments),this.roles=new DU(this._client)}create(e,t,n){return this._client.post(q`/organization/projects/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(q`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(q`/organization/projects/${r}/users/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/organization/projects/${e}/users`,bV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(q`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};OU.Roles=DU;var kU=class extends K{constructor(){super(...arguments),this.users=new OU(this._client),this.serviceAccounts=new CU(this._client),this.apiKeys=new gU(this._client),this.rateLimits=new xU(this._client),this.modelPermissions=new bU(this._client),this.hostedToolPermissions=new yU(this._client),this.groups=new EU(this._client),this.roles=new SU(this._client),this.dataRetention=new vU(this._client),this.spendAlerts=new wU(this._client),this.certificates=new _U(this._client)}create(e,t){return this._client.post(`/organization/projects`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(q`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/projects/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/projects`,bV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(q`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};kU.Users=OU,kU.ServiceAccounts=CU,kU.APIKeys=gU,kU.RateLimits=xU,kU.ModelPermissions=bU,kU.HostedToolPermissions=yU,kU.Groups=EU,kU.Roles=SU,kU.DataRetention=vU,kU.SpendAlerts=wU,kU.Certificates=_U;var AU=class extends K{create(e,t,n){return this._client.post(q`/organization/users/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{user_id:r}=t;return this._client.get(q`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/organization/users/${e}/roles`,xV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:r}=t;return this._client.delete(q`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},jU=class extends K{constructor(){super(...arguments),this.roles=new AU(this._client)}retrieve(e,t){return this._client.get(q`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/users/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/users`,bV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(q`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};jU.Roles=AU;var MU=class extends K{constructor(){super(...arguments),this.auditLogs=new oU(this._client),this.adminAPIKeys=new aU(this._client),this.usage=new fU(this._client),this.invites=new lU(this._client),this.users=new jU(this._client),this.groups=new hU(this._client),this.roles=new uU(this._client),this.dataRetention=new cU(this._client),this.spendAlerts=new dU(this._client),this.certificates=new sU(this._client),this.projects=new kU(this._client)}};MU.AuditLogs=oU,MU.AdminAPIKeys=aU,MU.Usage=fU,MU.Invites=lU,MU.Users=jU,MU.Groups=hU,MU.Roles=uU,MU.DataRetention=cU,MU.SpendAlerts=dU,MU.Certificates=sU,MU.Projects=kU;var NU=class extends K{constructor(){super(...arguments),this.organization=new MU(this._client)}};NU.Organization=MU;var PU=Symbol(`brand.privateNullableHeaders`);function*FU(e){if(!e)return;if(PU in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():$z(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=$z(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var J=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of FU(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[PU]:!0,values:t,nulls:n}},IU=class extends K{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:J([{Accept:`application/octet-stream`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},LU=class extends K{create(e,t){return this._client.post(`/audio/transcriptions`,AV({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},RU=class extends K{create(e,t){return this._client.post(`/audio/translations`,AV({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},zU=class extends K{constructor(){super(...arguments),this.transcriptions=new LU(this._client),this.translations=new RU(this._client),this.speech=new IU(this._client)}};zU.Transcriptions=LU,zU.Translations=RU,zU.Speech=IU;var BU=class extends K{create(e,t){return this._client.post(`/batches`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/batches`,yV,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(q`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}},VU=class extends K{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/assistants/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(q`/assistants/${e}`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/assistants`,yV,{query:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/assistants/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},HU=class extends K{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},UU=class extends K{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},WU=class extends K{constructor(){super(...arguments),this.sessions=new HU(this._client),this.transcriptionSessions=new UU(this._client)}};WU.Sessions=HU,WU.TranscriptionSessions=UU;var GU=class extends K{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(q`/chatkit/sessions/${e}/cancel`,{...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}},KU=class extends K{retrieve(e,t){return this._client.get(q`/chatkit/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,bV,{query:e,...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/chatkit/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(q`/chatkit/threads/${e}/items`,bV,{query:t,...n,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers]),__security:{bearerAuth:!0}})}},qU=class extends K{constructor(){super(...arguments),this.sessions=new GU(this._client),this.threads=new KU(this._client)}};qU.Sessions=GU,qU.Threads=KU;var JU=class extends K{create(e,t,n){return this._client.post(q`/threads/${e}/messages`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(q`/threads/${r}/messages/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(q`/threads/${r}/messages/${e}`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/threads/${e}/messages`,yV,{query:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(q`/threads/${r}/messages/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},YU=class extends K{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(q`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(q`/threads/${r}/runs/${e}/steps`,yV,{query:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},XU=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},ZU=e=>{if(globalThis.process!==void 0)return{}[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0},QU,$U,eW,tW,nW,rW,iW,aW,oW,sW,cW,lW,uW,dW,fW,pW,mW,hW,gW,_W,vW,yW,bW,xW=class extends SH{constructor(){super(...arguments),QU.add(this),eW.set(this,[]),tW.set(this,{}),nW.set(this,{}),rW.set(this,void 0),iW.set(this,void 0),aW.set(this,void 0),oW.set(this,void 0),sW.set(this,void 0),cW.set(this,void 0),lW.set(this,void 0),uW.set(this,void 0),dW.set(this,void 0)}[(eW=new WeakMap,tW=new WeakMap,nW=new WeakMap,rW=new WeakMap,iW=new WeakMap,aW=new WeakMap,oW=new WeakMap,sW=new WeakMap,cW=new WeakMap,lW=new WeakMap,uW=new WeakMap,dW=new WeakMap,QU=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new $U;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let n=oV.fromReadableStream(e,this.controller);for await(let e of n)W(this,QU,`m`,fW).call(this,e);if(n.controller.signal?.aborted)throw new Pz;return this._addRun(W(this,QU,`m`,pW).call(this))}toReadableStream(){return new oV(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new $U;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},a=await e.submitToolOutputs(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)W(this,QU,`m`,fW).call(this,e);if(a.controller.signal?.aborted)throw new Pz;return this._addRun(W(this,QU,`m`,pW).call(this))}static createThreadAssistantStream(e,t,n){let r=new $U;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":`stream`}})),r}static createAssistantStream(e,t,n,r){let i=new $U;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return W(this,lW,`f`)}currentRun(){return W(this,uW,`f`)}currentMessageSnapshot(){return W(this,rW,`f`)}currentRunStepSnapshot(){return W(this,dW,`f`)}async finalRunSteps(){return await this.done(),Object.values(W(this,tW,`f`))}async finalMessages(){return await this.done(),Object.values(W(this,nW,`f`))}async finalRun(){if(await this.done(),!W(this,iW,`f`))throw Error(`Final run was not received.`);return W(this,iW,`f`)}async _createThreadAssistantStream(e,t,n){this._listenForAbort(n?.signal);let r={...t,stream:!0},i=await e.createAndRun(r,{...n,signal:this.controller.signal});this._connected();for await(let e of i)W(this,QU,`m`,fW).call(this,e);if(i.controller.signal?.aborted)throw new Pz;return this._addRun(W(this,QU,`m`,pW).call(this))}async _createAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},a=await e.create(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)W(this,QU,`m`,fW).call(this,e);if(a.controller.signal?.aborted)throw new Pz;return this._addRun(W(this,QU,`m`,pW).call(this))}static accumulateDelta(e,t){for(let[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(t==null){e[n]=r;continue}if(n===`index`||n===`type`){e[n]=r;continue}if(typeof t==`string`&&typeof r==`string`)t+=r;else if(typeof t==`number`&&typeof r==`number`)t+=r;else if(rB(t)&&rB(r))t=this.accumulateDelta(t,r);else if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>typeof e==`string`||typeof e==`number`)){t.push(...r);continue}for(let e of r){if(!rB(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let n=e.index;if(n==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof n!=`number`)throw Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let r=t[n];r==null?t.push(e):t[n]=this.accumulateDelta(r,e)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`);e[n]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};$U=xW,fW=function(e){if(!this.ended)switch(U(this,lW,e,`f`),W(this,QU,`m`,gW).call(this,e),e.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,QU,`m`,bW).call(this,e);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,QU,`m`,hW).call(this,e);break;case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:W(this,QU,`m`,mW).call(this,e);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},pW=function(){if(this.ended)throw new G(`stream has ended, this shouldn't happen`);if(!W(this,iW,`f`))throw Error(`Final run has not been received`);return W(this,iW,`f`)},mW=function(e){let[t,n]=W(this,QU,`m`,vW).call(this,e,W(this,rW,`f`));U(this,rW,t,`f`),W(this,nW,`f`)[t.id]=t;for(let e of n){let n=t.content[e.index];n?.type==`text`&&this._emit(`textCreated`,n.text)}switch(e.event){case`thread.message.created`:this._emit(`messageCreated`,e.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(this._emit(`messageDelta`,e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type==`text`&&n.text){let e=n.text,r=t.content[n.index];if(r&&r.type==`text`)this._emit(`textDelta`,e,r.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(n.index!=W(this,aW,`f`)){if(W(this,oW,`f`))switch(W(this,oW,`f`).type){case`text`:this._emit(`textDone`,W(this,oW,`f`).text,W(this,rW,`f`));break;case`image_file`:this._emit(`imageFileDone`,W(this,oW,`f`).image_file,W(this,rW,`f`));break}U(this,aW,n.index,`f`)}U(this,oW,t.content[n.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(W(this,aW,`f`)!==void 0){let t=e.data.content[W(this,aW,`f`)];if(t)switch(t.type){case`image_file`:this._emit(`imageFileDone`,t.image_file,W(this,rW,`f`));break;case`text`:this._emit(`textDone`,t.text,W(this,rW,`f`));break}}W(this,rW,`f`)&&this._emit(`messageDone`,e.data),U(this,rW,void 0,`f`)}},hW=function(e){let t=W(this,QU,`m`,_W).call(this,e);switch(U(this,dW,t,`f`),e.event){case`thread.run.step.created`:this._emit(`runStepCreated`,e.data);break;case`thread.run.step.delta`:let n=e.data.delta;if(n.step_details&&n.step_details.type==`tool_calls`&&n.step_details.tool_calls&&t.step_details.type==`tool_calls`)for(let e of n.step_details.tool_calls)e.index==W(this,sW,`f`)?this._emit(`toolCallDelta`,e,t.step_details.tool_calls[e.index]):(W(this,cW,`f`)&&this._emit(`toolCallDone`,W(this,cW,`f`)),U(this,sW,e.index,`f`),U(this,cW,t.step_details.tool_calls[e.index],`f`),W(this,cW,`f`)&&this._emit(`toolCallCreated`,W(this,cW,`f`)));this._emit(`runStepDelta`,e.data.delta,t);break;case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:U(this,dW,void 0,`f`),e.data.step_details.type==`tool_calls`&&W(this,cW,`f`)&&(this._emit(`toolCallDone`,W(this,cW,`f`)),U(this,cW,void 0,`f`)),this._emit(`runStepDone`,e.data,t);break;case`thread.run.step.in_progress`:break}},gW=function(e){W(this,eW,`f`).push(e),this._emit(`event`,e)},_W=function(e){switch(e.event){case`thread.run.step.created`:return W(this,tW,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let t=W(this,tW,`f`)[e.data.id];if(!t)throw Error(`Received a RunStepDelta before creation of a snapshot`);let n=e.data;if(n.delta){let r=$U.accumulateDelta(t,n.delta);W(this,tW,`f`)[e.data.id]=r}return W(this,tW,`f`)[e.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,tW,`f`)[e.data.id]=e.data;break}if(W(this,tW,`f`)[e.data.id])return W(this,tW,`f`)[e.data.id];throw Error(`No snapshot available`)},vW=function(e,t){let n=[];switch(e.event){case`thread.message.created`:return[e.data,n];case`thread.message.delta`:if(!t)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let r=e.data;if(r.delta.content)for(let e of r.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=W(this,QU,`m`,yW).call(this,e,n)}else t.content[e.index]=e,n.push(e);return[t,n];case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(t)return[t,n];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},yW=function(e,t){return $U.accumulateDelta(t,e)},bW=function(e){switch(U(this,uW,e.data,`f`),e.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`:U(this,iW,e.data,`f`),W(this,cW,`f`)&&(this._emit(`toolCallDone`,W(this,cW,`f`)),U(this,cW,void 0,`f`));break;case`thread.run.cancelling`:break}};var SW=class extends K{constructor(){super(...arguments),this.steps=new YU(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(q`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(q`/threads/${r}/runs/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(q`/threads/${r}/runs/${e}`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/threads/${e}/runs`,yV,{query:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(q`/threads/${r}/runs/${e}/cancel`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return xW.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=J([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(i.status){case`queued`:case`in_progress`:case`cancelling`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await oB(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return xW.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(q`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return xW.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};SW.Steps=YU;var CW=class extends K{constructor(){super(...arguments),this.runs=new SW(this._client),this.messages=new JU(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(q`/threads/${e}`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return xW.createThreadAssistantStream(e,this._client.beta.threads,t)}};CW.Runs=SW,CW.Messages=JU;var wW=class extends K{constructor(){super(...arguments),this.realtime=new WU(this._client),this.chatkit=new qU(this._client),this.assistants=new VU(this._client),this.threads=new CW(this._client)}};wW.Realtime=WU,wW.ChatKit=qU,wW.Assistants=VU,wW.Threads=CW;var TW=class extends K{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},EW=class extends K{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(q`/containers/${r}/files/${e}/content`,{...n,headers:J([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},DW=class extends K{constructor(){super(...arguments),this.content=new EW(this._client)}create(e,t,n){return this._client.post(q`/containers/${e}/files`,kV({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(q`/containers/${r}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/containers/${e}/files`,yV,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(q`/containers/${r}/files/${e}`,{...n,headers:J([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}};DW.Content=EW;var OW=class extends K{constructor(){super(...arguments),this.files=new DW(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/containers`,yV,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/containers/${e}`,{...t,headers:J([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}};OW.Files=DW;var kW=class extends K{create(e,t,n){let{include:r,...i}=t;return this._client.post(q`/conversations/${e}/items`,{query:{include:r},body:i,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(q`/conversations/${r}/items/${e}`,{query:i,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/conversations/${e}/items`,bV,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(q`/conversations/${r}/items/${e}`,{...n,__security:{bearerAuth:!0}})}},AW=class extends K{constructor(){super(...arguments),this.items=new kW(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(q`/conversations/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};AW.Items=kW;var jW=class extends K{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&rV(this._client).debug(`embeddings/user defined encoding_format:`,e.encoding_format);let i=this._client.post(`/embeddings`,{body:{...e,encoding_format:r},...t,__security:{bearerAuth:!0}});return n?i:(rV(this._client).debug(`embeddings/decoding base64 embeddings from base64`),i._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=XU(t)}),e)))}},MW=class extends K{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(q`/evals/${r}/runs/${i}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(q`/evals/${r}/runs/${e}/output_items`,yV,{query:i,...n,__security:{bearerAuth:!0}})}},NW=class extends K{constructor(){super(...arguments),this.outputItems=new MW(this._client)}create(e,t,n){return this._client.post(q`/evals/${e}/runs`,{body:t,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(q`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/evals/${e}/runs`,yV,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(q`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(q`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};NW.OutputItems=MW;var PW=class extends K{constructor(){super(...arguments),this.runs=new NW(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(q`/evals/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/evals`,yV,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};PW.Runs=NW;var FW=class extends K{create(e,t){return this._client.post(`/files`,AV({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(q`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/files`,yV,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(q`/files/${e}/content`,{...t,headers:J([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await oB(t),a=await this.retrieve(e),Date.now()-i>n)throw new Iz({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},IW=class extends K{},LW=class extends K{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t,__security:{bearerAuth:!0}})}},RW=class extends K{constructor(){super(...arguments),this.graders=new LW(this._client)}};RW.Graders=LW;var zW=class extends K{create(e,t,n){return this._client.getAPIList(q`/fine_tuning/checkpoints/${e}/permissions`,vV,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(q`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/fine_tuning/checkpoints/${e}/permissions`,bV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(q`/fine_tuning/checkpoints/${r}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},BW=class extends K{constructor(){super(...arguments),this.permissions=new zW(this._client)}};BW.Permissions=zW;var VW=class extends K{list(e,t={},n){return this._client.getAPIList(q`/fine_tuning/jobs/${e}/checkpoints`,yV,{query:t,...n,__security:{bearerAuth:!0}})}},HW=class extends K{constructor(){super(...arguments),this.checkpoints=new VW(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,yV,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(q`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},n){return this._client.getAPIList(q`/fine_tuning/jobs/${e}/events`,yV,{query:t,...n,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(q`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(q`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};HW.Checkpoints=VW;var UW=class extends K{constructor(){super(...arguments),this.methods=new IW(this._client),this.jobs=new HW(this._client),this.checkpoints=new BW(this._client),this.alpha=new RW(this._client)}};UW.Methods=IW,UW.Jobs=HW,UW.Checkpoints=BW,UW.Alpha=RW;var WW=class extends K{},GW=class extends K{constructor(){super(...arguments),this.graderModels=new WW(this._client)}};GW.GraderModels=WW;var KW=class extends K{createVariation(e,t){return this._client.post(`/images/variations`,AV({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post(`/images/edits`,AV({body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},qW=class extends K{retrieve(e,t){return this._client.get(q`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList(`/models`,vV,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/models/${e}`,{...t,__security:{bearerAuth:!0}})}},JW=class extends K{create(e,t){return this._client.post(`/moderations`,{body:e,...t,__security:{bearerAuth:!0}})}},YW=class extends K{accept(e,t,n){return this._client.post(q`/realtime/calls/${e}/accept`,{body:t,...n,headers:J([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(q`/realtime/calls/${e}/hangup`,{...t,headers:J([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(q`/realtime/calls/${e}/refer`,{body:t,...n,headers:J([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(q`/realtime/calls/${e}/reject`,{body:t,...n,headers:J([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}},XW=class extends K{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t,__security:{bearerAuth:!0}})}},ZW=class extends K{constructor(){super(...arguments),this.clientSecrets=new XW(this._client),this.calls=new YW(this._client)}};ZW.ClientSecrets=XW,ZW.Calls=YW;function QW(e,t){if(!t||!tG(t)){let t={...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)};return aG(e,t)&&oG(t),t}return $W(e,t)}function $W(e,t){let n=!e.status||e.status===`completed`,r=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:n?iG(t,e):null};if(e.type===`message`){let r=e.content.map(e=>e.type===`output_text`?{...e,parsed:n?eG(t,e.text):null}:e);return{...e,content:r}}return e}),i=Object.assign({},e,{output:r});return aG(e,i)&&oG(i),Object.defineProperty(i,"output_parsed",{enumerable:!0,get(){for(let e of i.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),i}function eG(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function tG(e){return!!YV(e.text?.format)}function nG(e){return e?.$brand===`auto-parseable-tool`}function rG(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function iG(e,t){let n=rG(e.tools??[],t.name);return{...t,...t,parsed_arguments:nG(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function aG(e,t){return!Object.getOwnPropertyDescriptor(e,`output_text`)||t.output_text==null}function oG(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}function sG(e,t){if(!t){if(e.type!==`response.created`)throw new G(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return cG(e.response)}switch(e.type){case`response.output_item.added`:t.output.push(structuredClone(e.item)),e.item.type===`message`&&oG(t);break;case`response.output_item.done`:lG(t,e.output_index),t.output[e.output_index]=structuredClone(e.item),e.item.type===`message`&&oG(t);break;case`response.content_part.added`:{let n=lG(t,e.output_index),r=n.type,i=e.part;r===`message`&&i.type!==`reasoning_text`?(n.content.push(structuredClone(i)),i.type===`output_text`&&oG(t)):r===`reasoning`&&i.type===`reasoning_text`&&(n.content||=[],n.content.push(structuredClone(i)));break}case`response.content_part.done`:{let n=lG(t,e.output_index),r=e.part;if(n.type===`message`&&r.type!==`reasoning_text`)uG(n.content,e.content_index),n.content[e.content_index]=structuredClone(r),r.type===`output_text`&&oG(t);else if(n.type===`reasoning`&&r.type===`reasoning_text`){let t=n.content;if(!t)throw new G(`missing content at index ${e.content_index}`);uG(t,e.content_index),t[e.content_index]=structuredClone(r)}break}case`response.output_text.delta`:{let n=lG(t,e.output_index);if(n.type===`message`){let r=uG(n.content,e.content_index);if(r.type!==`output_text`)throw new G(`expected content to be 'output_text', got ${r.type}`);r.text+=e.delta,t.output_text+=e.delta}break}case`response.output_text.done`:{let n=lG(t,e.output_index);if(n.type===`message`){let r=uG(n.content,e.content_index);if(r.type!==`output_text`)throw new G(`expected content to be 'output_text', got ${r.type}`);r.text=e.text,oG(t)}break}case`response.output_text.annotation.added`:{let n=lG(t,e.output_index);if(n.type===`message`){let t=uG(n.content,e.content_index);if(t.type!==`output_text`)throw new G(`expected content to be 'output_text', got ${t.type}`);t.annotations[e.annotation_index]=structuredClone(e.annotation)}break}case`response.refusal.delta`:{let n=lG(t,e.output_index);if(n.type===`message`){let t=uG(n.content,e.content_index);if(t.type!==`refusal`)throw new G(`expected content to be 'refusal', got ${t.type}`);t.refusal+=e.delta}break}case`response.refusal.done`:{let n=lG(t,e.output_index);if(n.type===`message`){let t=uG(n.content,e.content_index);if(t.type!==`refusal`)throw new G(`expected content to be 'refusal', got ${t.type}`);t.refusal=e.refusal}break}case`response.function_call_arguments.delta`:{let n=lG(t,e.output_index);n.type===`function_call`&&(n.arguments+=e.delta);break}case`response.function_call_arguments.done`:{let n=lG(t,e.output_index);n.type===`function_call`&&(n.arguments=e.arguments);break}case`response.reasoning_text.delta`:{let n=lG(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new G(`missing content at index ${e.content_index}`);let t=uG(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new G(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case`response.reasoning_text.done`:{let n=lG(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new G(`missing content at index ${e.content_index}`);let t=uG(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new G(`expected content to be 'reasoning_text', got ${t.type}`);t.text=e.text}break}case`response.reasoning_summary_part.added`:{let n=lG(t,e.output_index);n.type===`reasoning`&&n.summary.push(structuredClone(e.part));break}case`response.reasoning_summary_part.done`:{let n=lG(t,e.output_index);n.type===`reasoning`&&(uG(n.summary,e.summary_index),n.summary[e.summary_index]=structuredClone(e.part));break}case`response.reasoning_summary_text.delta`:{let n=lG(t,e.output_index);if(n.type===`reasoning`){let t=uG(n.summary,e.summary_index);t.text+=e.delta}break}case`response.reasoning_summary_text.done`:{let n=lG(t,e.output_index);if(n.type===`reasoning`){let t=uG(n.summary,e.summary_index);t.text=e.text}break}case`response.custom_tool_call_input.delta`:{let n=lG(t,e.output_index);n.type===`custom_tool_call`&&(n.input+=e.delta);break}case`response.custom_tool_call_input.done`:{let n=lG(t,e.output_index);n.type===`custom_tool_call`&&(n.input=e.input);break}case`response.mcp_call_arguments.delta`:{let n=lG(t,e.output_index);n.type===`mcp_call`&&(n.arguments+=e.delta);break}case`response.mcp_call_arguments.done`:{let n=lG(t,e.output_index);n.type===`mcp_call`&&(n.arguments=e.arguments);break}case`response.code_interpreter_call_code.delta`:{let n=lG(t,e.output_index);n.type===`code_interpreter_call`&&(n.code=(n.code??``)+e.delta);break}case`response.code_interpreter_call_code.done`:{let n=lG(t,e.output_index);n.type===`code_interpreter_call`&&(n.code=e.code);break}case`response.code_interpreter_call.in_progress`:{let n=lG(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`in_progress`);break}case`response.code_interpreter_call.interpreting`:{let n=lG(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`interpreting`);break}case`response.code_interpreter_call.completed`:{let n=lG(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`completed`);break}case`response.file_search_call.in_progress`:{let n=lG(t,e.output_index);n.type===`file_search_call`&&(n.status=`in_progress`);break}case`response.file_search_call.searching`:{let n=lG(t,e.output_index);n.type===`file_search_call`&&(n.status=`searching`);break}case`response.file_search_call.completed`:{let n=lG(t,e.output_index);n.type===`file_search_call`&&(n.status=`completed`);break}case`response.web_search_call.in_progress`:{let n=lG(t,e.output_index);n.type===`web_search_call`&&(n.status=`in_progress`);break}case`response.web_search_call.searching`:{let n=lG(t,e.output_index);n.type===`web_search_call`&&(n.status=`searching`);break}case`response.web_search_call.completed`:{let n=lG(t,e.output_index);n.type===`web_search_call`&&(n.status=`completed`);break}case`response.image_generation_call.in_progress`:{let n=lG(t,e.output_index);n.type===`image_generation_call`&&(n.status=`in_progress`);break}case`response.image_generation_call.generating`:{let n=lG(t,e.output_index);n.type===`image_generation_call`&&(n.status=`generating`);break}case`response.image_generation_call.completed`:{let n=lG(t,e.output_index);n.type===`image_generation_call`&&(n.status=`completed`);break}case`response.mcp_call.in_progress`:{let n=lG(t,e.output_index);n.type===`mcp_call`&&(n.status=`in_progress`);break}case`response.mcp_call.completed`:{let n=lG(t,e.output_index);n.type===`mcp_call`&&(n.status=`completed`);break}case`response.mcp_call.failed`:{let n=lG(t,e.output_index);n.type===`mcp_call`&&(n.status=`failed`);break}case`response.created`:case`response.queued`:case`response.in_progress`:case`response.completed`:case`response.failed`:case`response.incomplete`:t=cG(e.response);break;case`response.audio.delta`:case`response.audio.done`:case`response.audio.transcript.delta`:case`response.audio.transcript.done`:case`response.image_generation_call.partial_image`:case`response.mcp_list_tools.in_progress`:case`response.mcp_list_tools.completed`:case`response.mcp_list_tools.failed`:case`error`:break;default:dG(e)}return t}function cG(e){let t=structuredClone(e);return(!Object.getOwnPropertyDescriptor(t,`output_text`)||t.output_text==null)&&oG(t),t}function lG(e,t){let n=e.output[t];if(!n)throw new G(`missing output at index ${t}`);return n}function uG(e,t){let n=e[t];if(!n)throw new G(`missing content at index ${t}`);return n}function dG(e){throw new G(`Unhandled response stream event: ${JSON.stringify(e)}`)}var fG,pG,mG,hG,gG,_G,vG,yG=class e extends SH{constructor(e){super(),fG.add(this),pG.set(this,void 0),mG.set(this,void 0),hG.set(this,void 0),U(this,pG,e,`f`)}static createResponse(t,n,r){let i=new e(n);return i._run(()=>i._createOrRetrieveResponse(t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createOrRetrieveResponse(e,t,n){this._listenForAbort(n?.signal),W(this,fG,`m`,gG).call(this);let r,i=null;`response_id`in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let e of r)W(this,fG,`m`,_G).call(this,e,i);if(r.controller.signal?.aborted)throw new Pz;return W(this,fG,`m`,vG).call(this)}[(pG=new WeakMap,mG=new WeakMap,hG=new WeakMap,fG=new WeakSet,gG=function(){this.ended||U(this,mG,void 0,`f`)},_G=function(e,t){if(this.ended)return;let n=(e,n)=>{(t==null||n.sequence_number>t)&&this._emit(e,n)},r=sG(e,W(this,mG,`f`));switch(U(this,mG,r,`f`),n(`event`,e),e.type){case`response.output_text.delta`:{let t=r.output[e.output_index];if(!t)throw new G(`missing output at index ${e.output_index}`);if(t.type===`message`){let r=t.content[e.content_index];if(!r)throw new G(`missing content at index ${e.content_index}`);if(r.type!==`output_text`)throw new G(`expected content to be 'output_text', got ${r.type}`);n(`response.output_text.delta`,{...e,snapshot:r.text})}break}case`response.function_call_arguments.delta`:{let t=r.output[e.output_index];if(!t)throw new G(`missing output at index ${e.output_index}`);t.type===`function_call`&&n(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:n(e.type,e);break}},vG=function(){if(this.ended)throw new G(`stream has ended, this shouldn't happen`);let e=W(this,mG,`f`);if(!e)throw new G(`request ended without sending any events`);U(this,mG,void 0,`f`);let t=bG(e,W(this,pG,`f`));return U(this,hG,t,`f`),t},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=W(this,hG,`f`);if(!e)throw new G(`stream ended without producing a ChatCompletion`);return e}};function bG(e,t){return QW(e,t)}var xG=class extends K{list(e,t={},n){return this._client.getAPIList(q`/responses/${e}/input_items`,yV,{query:t,...n,__security:{bearerAuth:!0}})}},SG=class extends K{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t,__security:{bearerAuth:!0}})}},CG=class extends K{constructor(){super(...arguments),this.inputItems=new xG(this._client),this.inputTokens=new SG(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&oG(e),e))}retrieve(e,t={},n){return this._client.get(q`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&oG(e),e))}delete(e,t){return this._client.delete(q`/responses/${e}`,{...t,headers:J([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>$W(t,e))}stream(e,t){return yG.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(q`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t,__security:{bearerAuth:!0}})}};CG.InputItems=xG,CG.InputTokens=SG;var wG=class extends K{retrieve(e,t){return this._client.get(q`/skills/${e}/content`,{...t,headers:J([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},TG=class extends K{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(q`/skills/${r}/versions/${e}/content`,{...n,headers:J([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},EG=class extends K{constructor(){super(...arguments),this.content=new TG(this._client)}create(e,t={},n){return this._client.post(q`/skills/${e}/versions`,kV({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(q`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/skills/${e}/versions`,yV,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(q`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};EG.Content=TG;var DG=class extends K{constructor(){super(...arguments),this.content=new wG(this._client),this.versions=new EG(this._client)}create(e={},t){return this._client.post(`/skills`,kV({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(q`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(q`/skills/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/skills`,yV,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};DG.Content=wG,DG.Versions=EG;var OG=class extends K{create(e,t,n){return this._client.post(q`/uploads/${e}/parts`,AV({body:t,...n,__security:{bearerAuth:!0}},this._client))}},kG=class extends K{constructor(){super(...arguments),this.parts=new OG(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(q`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,n){return this._client.post(q`/uploads/${e}/complete`,{body:t,...n,__security:{bearerAuth:!0}})}};kG.Parts=OG;var AG=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n)console.error(e.reason);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r},jG=class extends K{create(e,t,n){return this._client.post(q`/vector_stores/${e}/file_batches`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(q`/vector_stores/${r}/file_batches/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(q`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(q`/vector_stores/${r}/file_batches/${e}/files`,yV,{query:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){let r=J([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await oB(e);break;case`failed`:case`cancelled`:case`completed`:return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=r?.maxConcurrency??5,a=Math.min(i,t.length),o=this._client,s=t.values(),c=[...n];async function l(e){for(let t of e){let e=await o.files.create({file:t,purpose:`assistants`},r);c.push(e.id)}}return await AG(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}},MG=class extends K{create(e,t,n){return this._client.post(q`/vector_stores/${e}/files`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(q`/vector_stores/${r}/files/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(q`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/vector_stores/${e}/files`,yV,{query:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(q`/vector_stores/${r}/files/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){let r=J([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),a=i.data;switch(a.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=i.response.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await oB(e);break;case`failed`:case`completed`:return a}}}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(q`/vector_stores/${r}/files/${e}/content`,vV,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},NG=class extends K{constructor(){super(...arguments),this.files=new MG(this._client),this.fileBatches=new jG(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/vector_stores/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(q`/vector_stores/${e}`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/vector_stores`,yV,{query:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/vector_stores/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(q`/vector_stores/${e}/search`,vV,{body:t,method:`post`,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}};NG.Files=MG,NG.FileBatches=jG;var PG=class extends K{create(e,t){return this._client.post(`/videos`,AV({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(q`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/videos`,bV,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post(`/videos/characters`,AV({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(q`/videos/${e}/content`,{query:t,...n,headers:J([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,AV({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,AV({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(q`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,n){return this._client.post(q`/videos/${e}/remix`,kV({body:t,...n,__security:{bearerAuth:!0}},this._client))}},FG,IG,LG,RG=class extends K{constructor(){super(...arguments),FG.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,r=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,FG,`m`,IG).call(this,n);let i=J([t]).values,a=W(this,FG,`m`,LG).call(this,i,`webhook-signature`),o=W(this,FG,`m`,LG).call(this,i,`webhook-timestamp`),s=W(this,FG,`m`,LG).call(this,i,`webhook-id`),c=parseInt(o,10);if(isNaN(c))throw new qz(`Invalid webhook timestamp format`);let l=Math.floor(Date.now()/1e3);if(l-c>r)throw new qz(`Webhook timestamp is too old`);if(c>l+r)throw new qz(`Webhook timestamp is too new`);let u=a.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),d=n.startsWith(`whsec_`)?Buffer.from(n.replace(`whsec_`,``),`base64`):Buffer.from(n,`utf-8`),f=s?`${s}.${o}.${e}`:`${o}.${e}`,p=await crypto.subtle.importKey(`raw`,d,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of u)try{let t=Buffer.from(e,`base64`);if(await crypto.subtle.verify(`HMAC`,p,t,new TextEncoder().encode(f)))return}catch{continue}throw new qz(`The given webhook signature does not match the expected signature`)}};FG=new WeakSet,IG=function(e){if(typeof e!=`string`||e.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`)},LG=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n};var zG=Symbol.for(`openai.node.providerDefinitions.v1`),BG=globalThis,VG=BG[zG],HG=VG??new WeakMap;VG||Object.defineProperty(BG,zG,{value:HG});function UG(e){let t=HG.get(e);if(!t)throw Error(`Invalid provider. Providers must be created with createProvider().`);return t.configure()}var WG,GG,KG,qG,JG=`workload-identity-auth`,Y=class{constructor(e={}){WG.add(this),KG.set(this,void 0),this.completions=new TW(this),this.chat=new iU(this),this.embeddings=new jW(this),this.files=new FW(this),this.images=new KW(this),this.audio=new zU(this),this.moderations=new JW(this),this.models=new qW(this),this.fineTuning=new UW(this),this.graders=new GW(this),this.vectorStores=new NG(this),this.webhooks=new RG(this),this.beta=new wW(this),this.batches=new BU(this),this.uploads=new kG(this),this.admin=new NU(this),this.responses=new CG(this),this.realtime=new ZW(this),this.conversations=new AW(this),this.evals=new PW(this),this.containers=new OW(this),this.skills=new DG(this),this.videos=new PG(this);let t=e.provider;if(t){let t=[`apiKey`,`adminAPIKey`,`workloadIdentity`,`baseURL`].filter(t=>e[t]!=null);if(t.length)throw new G(`The \`provider\` option cannot be used with ${t.map(e=>`\`${e}\``).join(`, `)}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:n=t?null:ZU(`OPENAI_BASE_URL`),apiKey:r=t?null:ZU(`OPENAI_API_KEY`)??null,adminAPIKey:i=t?null:ZU(`OPENAI_ADMIN_KEY`)??null,organization:a=t?null:ZU(`OPENAI_ORG_ID`)??null,project:o=t?null:ZU(`OPENAI_PROJECT_ID`)??null,webhookSecret:s=ZU(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:c,...l}=e,u=t?UG(t):void 0,d={apiKey:r,adminAPIKey:i,organization:a,project:o,webhookSecret:s,workloadIdentity:c,provider:t,...l,baseURL:u?.baseURL??(n||`https://api.openai.com/v1`)};if(r&&c)throw new G("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!u&&!r&&!i&&!c)throw new G("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!d.dangerouslyAllowBrowser&&cB())throw new G(`It looks like you're running in a browser-like environment.
|
|
185
|
+
`);return await n?.handleLLMNewToken(r),{generations:[{message:new An(r),text:r}],llmOutput:{}}}},gN=class e extends iD{sleep=50;responses=[];chunks=[];toolStyle=`openai`;thrownErrorString;tools=[];constructor({sleep:e=50,responses:t=[],chunks:n=[],toolStyle:r=`openai`,thrownErrorString:i,...a}){super(a),this.sleep=e,this.responses=t,this.chunks=n,this.toolStyle=r,this.thrownErrorString=i}_llmType(){return`fake`}bindTools(t){let n=[...this.tools,...t],r=n.map(e=>{switch(this.toolStyle){case`openai`:return{type:`function`,function:{name:e.name,description:e.description,parameters:Rx(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:Rx(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:Rx(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:Rx(e.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle===`google`?[{functionDeclarations:r}]:r,a=new e({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return a.tools=n,a.withConfig({tools:i})}async _generate(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);return{generations:[{text:``,message:new An({content:this.responses?.[0]?.content??e[0].content??``,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);if(this.chunks?.length){for(let e of this.chunks){let r=new xd({message:new Nn({content:e.content,tool_calls:e.tool_calls,additional_kwargs:e.additional_kwargs??{}}),text:e.content?.toString()??``});if(t.signal?.aborted)break;yield r,await n?.handleLLMNewToken(e.content,void 0,void 0,void 0,void 0,{chunk:r})}return}let r=this.responses?.[0]??new An(typeof e[0].content==`string`?e[0].content:``),i=typeof r.content==`string`?r.content:``;for(let e of i){await new Promise(e=>setTimeout(e,this.sleep));let r=new xd({message:new Nn({content:e}),text:e});if(t.signal?.aborted)break;yield r,await n?.handleLLMNewToken(e,void 0,void 0,void 0,void 0,{chunk:r})}}},_N=class e extends iD{static lc_name(){return`FakeListChatModel`}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle=`openai`;constructor(e){super(e);let{responses:t,sleep:n,emitCustomEvent:r,generationInfo:i}=e;this.responses=t,this.sleep=n,this.emitCustomEvent=r??this.emitCustomEvent,this.generationInfo=i}_combineLLMOutput(){return[]}_llmType(){return`fake-list`}async _generate(e,t,n){if(await this._sleepIfRequested(),t?.thrownErrorString)throw Error(t.thrownErrorString);if(this.emitCustomEvent&&await n?.handleCustomEvent(`some_test_event`,{someval:!0}),t?.stop?.length)return{generations:[this._formatGeneration(t.stop[0])]};{let e=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(e)],llmOutput:{}}}}_formatGeneration(e){return{message:new An(e),text:e}}async*_streamResponseChunks(e,t,n){let r=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await n?.handleCustomEvent(`some_test_event`,{someval:!0});let i=[...r];for(let e=0;e<i.length;e++){let r=i[e],a=e===i.length-1;if(await this._sleepIfRequested(),t?.thrownErrorString)throw Error(t.thrownErrorString);let o=this._createResponseChunk(r,a?this.generationInfo:void 0);if(t.signal?.aborted)break;yield o,n?.handleLLMNewToken(r)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(e=>{setTimeout(()=>e(),this.sleep)})}_createResponseChunk(e,t){return new xd({message:new Nn({content:e}),text:e,generationInfo:t})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(t){let n=[...this.tools,...t],r=n.map(e=>{switch(this.toolStyle){case`openai`:return{type:`function`,function:{name:e.name,description:e.description,parameters:Rx(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:Rx(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:Rx(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:Rx(e.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle===`google`?[{functionDeclarations:r}]:r,a=new e({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return a.tools=n,a.toolStyle=this.toolStyle,a.i=this.i,a.withConfig({tools:i})}withStructuredOutput(e,t){return lS.from(async e=>{let t=await this.invoke(e);if(t.tool_calls?.[0]?.args)return t.tool_calls[0].args;if(typeof t.content==`string`)return JSON.parse(t.content);throw Error(`No structured output found`)})}},vN=class extends $w{vectorSize;constructor(e){super(e??{}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map(e=>this.embedQuery(e)))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,``);let n=t.length%this.vectorSize,r=n===0?0:this.vectorSize-n,i=t.length+r;t=t.padEnd(i,` `);let a=t.length/this.vectorSize,o=[];for(let e=0;e<t.length;e+=a)o.push(t.slice(e,e+a));return o.map(e=>{let t=0;for(let n=0;n<e.length;n+=1)t+=e===` `?0:e.charCodeAt(n);return t%26/26})}},yN=class extends $w{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}},bN=class extends gD{response;thrownErrorString;constructor(e){super(e),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return`fake`}async _call(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);let r=this.response??e;return await n?.handleLLMNewToken(r),r}},xN=class extends gD{sleep=50;responses;thrownErrorString;constructor(e){super(e),this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return`fake`}async _call(e){if(this.thrownErrorString)throw Error(this.thrownErrorString);let t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);let r=this.responses?.[0];this.responses=this.responses?.slice(1);for(let t of r??e)await new Promise(e=>setTimeout(e,this.sleep)),yield{text:t,generationInfo:{}},await n?.handleLLMNewToken(t)}},SN=class extends Bw{lc_namespace=[`langchain_core`,`message`,`fake`];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new Hn(e))}async addAIMessage(e){this.messages.push(new An(e))}async clear(){this.messages=[]}},CN=class extends Vw{lc_namespace=[`langchain_core`,`message`,`fake`];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},wN=class extends wl{name=`fake_tracer`;runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}},TN=class extends XT{lc_namespace=[`tests`,`fake`];getFormatInstructions(){return``}async parse(e){return e.split(`,`).map(e=>e.trim())}},EN=class extends WO{lc_namespace=[`test`,`fake`];output=[new Uw({pageContent:`foo`}),new Uw({pageContent:`bar`})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}},DN=class extends tS{lc_namespace=[`tests`,`fake`];returnOptions;constructor(e){super(e),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}},ON=class extends qj{name;description;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,t){return JSON.stringify(e)}},kN=class extends wl{runPromiseResolver;runPromise;name=`single_run_extractor`;constructor(){super(),this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}},AN=class e extends pN{memoryVectors=[];similarity;_vectorstoreType(){return`memory`}constructor(e,{similarity:t,...n}={}){super(e,n),this.similarity=t??NM}async addDocuments(e){let t=e.map(({pageContent:e})=>e);return this.addVectors(await this.embeddings.embedDocuments(t),e)}async addVectors(e,t){let n=e.map((e,n)=>({content:t[n].pageContent,embedding:e,metadata:t[n].metadata}));this.memoryVectors=this.memoryVectors.concat(n)}async similaritySearchVectorWithScore(e,t,n){let r=this.memoryVectors.filter(e=>!n||n(new Uw({metadata:e.metadata,pageContent:e.content})));return r.map((t,n)=>({similarity:this.similarity(e,t.embedding),index:n})).sort((e,t)=>e.similarity>t.similarity?-1:0).slice(0,t).map(e=>[new Uw({metadata:r[e.index].metadata,pageContent:r[e.index].content}),e.similarity])}static async fromTexts(t,n,r,i){let a=[];for(let e=0;e<t.length;e+=1){let r=Array.isArray(n)?n[e]:n,i=new Uw({pageContent:t[e],metadata:r});a.push(i)}return e.fromDocuments(a,r,i)}static async fromDocuments(e,t,n){let r=new this(t,n);return await r.addDocuments(e),r}static async fromExistingIndex(e,t){return new this(e,t)}},jN=C({FakeChatMessageHistory:()=>SN,FakeChatModel:()=>hN,FakeEmbeddings:()=>yN,FakeLLM:()=>bN,FakeListChatMessageHistory:()=>CN,FakeListChatModel:()=>_N,FakeRetriever:()=>EN,FakeRunnable:()=>DN,FakeSplitIntoListParser:()=>TN,FakeStreamingChatModel:()=>gN,FakeStreamingLLM:()=>xN,FakeTool:()=>ON,FakeTracer:()=>wN,FakeVectorStore:()=>AN,SingleRunExtractor:()=>kN,SyntheticEmbeddings:()=>vN,asAsyncIterable:()=>Wk,openAIReasoningTextChunks:()=>qk,openAITextOnlyChunks:()=>Kk,openAITextOnlyChunksWithUsage:()=>Gk,openAIToolCallChunks:()=>Jk,sseResponseFromOpenAIChunks:()=>Yk,streamMatchers:()=>Tk}),MN=C({agents:()=>ww,caches:()=>Mw,callbacks__base:()=>di,callbacks__manager:()=>ou,callbacks__promises:()=>tu,chat_history:()=>zw,document_loaders__base:()=>qw,document_loaders__langsmith:()=>Yw,documents:()=>Kw,embeddings:()=>Qw,errors:()=>fe,example_selectors:()=>lT,index:()=>Cw,indexing:()=>vT,language_models__base:()=>zT,language_models__chat_models:()=>nD,language_models__compat:()=>UE,language_models__event:()=>pD,language_models__llms:()=>mD,language_models__openai_completions_stream:()=>oD,language_models__profile:()=>_D,language_models__stream:()=>kE,language_models__structured_output:()=>TE,load__serializable:()=>He,memory:()=>vD,messages:()=>IS,messages__tool:()=>Jt,output_parsers:()=>vE,output_parsers__openai_functions:()=>DD,output_parsers__openai_tools:()=>OD,outputs:()=>vd,prompt_values:()=>yT,prompts:()=>BO,retrievers:()=>UO,retrievers__document_compressors:()=>VO,runnables:()=>RS,runnables__graph:()=>Bx,singletons:()=>Cu,stores:()=>GO,structured_query:()=>fk,testing:()=>Xk,tools:()=>Kj,tracers__base:()=>yl,tracers__console:()=>Tl,tracers__log_stream:()=>ud,tracers__run_collector:()=>nM,tracers__tracer_langchain:()=>Vl,types__stream:()=>iM,utils__async_caller:()=>Id,utils__chunk_array:()=>aM,utils__context:()=>sM,utils__env:()=>ti,utils__event_source_parse:()=>dM,utils__format:()=>bM,utils__function_calling:()=>xM,utils__gateway:()=>wM,utils__hash:()=>jw,utils__json_patch:()=>JT,utils__json_schema:()=>Ix,utils__math:()=>LM,utils__ssrf:()=>KM,utils__standard_schema:()=>Jb,utils__stream:()=>Pu,utils__testing:()=>jN,utils__tiktoken:()=>PT,utils__types:()=>yE,utils__uuid:()=>Ur,vectorstores:()=>dN}),NN=50;function PN(e){let t={};for(let n=e;n&&n.prototype;n=Object.getPrototypeOf(n))Object.assign(t,Reflect.get(n.prototype,`lc_aliases`));return Object.entries(t).reduce((e,[t,n])=>(e[n]=t,e),{})}async function FN(e){let{optionalImportsMap:t,optionalImportEntrypoints:n,importMap:r,secretsMap:i,secretsFromEnv:a,path:o,depth:s,maxDepth:c}=this,l=o.join(`.`);if(s>c)throw Error(`Maximum recursion depth (${c}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return Promise.all(e.map((e,t)=>FN.call({...this,path:[...o,`${t}`],depth:s+1},e)));let u=e;if(Le(u))return Ve(u);if(`lc`in u&&`type`in u&&`id`in u&&u.lc===1&&u.type===`secret`){let[e]=u.id;if(e in i)return i[e];if(a){let t=ui(e);if(t)return t}throw Error(`Missing secret "${e}" at ${l}`)}if(`lc`in u&&`type`in u&&`id`in u&&u.lc===1&&u.type===`not_implemented`){let e=JSON.stringify(u);throw Error(`Trying to load an object that doesn't implement serialization: ${l} -> ${e}`)}if(`lc`in u&&`type`in u&&`id`in u&&`kwargs`in u&&u.lc===1&&u.type===`constructor`){let e=u,i=JSON.stringify(e),[a,...c]=e.id.slice().reverse(),d=c.reverse(),f={langchain_core:MN,langchain:r},p=null,m=[d.join(`/`)];d[0]===`langchain_community`&&m.push([`langchain`,...d.slice(1)].join(`/`));let h=m.find(e=>e in t);if(Sw.concat(n).includes(d.join(`/`))||h)if(h!==void 0)p=await t[h];else throw Error(`Missing key "${d.join(`/`)}" for ${l} in load(optionalImportsMap={})`);else{let e;if(d[0]===`langchain`||d[0]===`langchain_core`)e=f[d[0]],d.shift();else throw Error(`Invalid namespace: ${l} -> ${i}`);if(d.length===0)throw Error(`Invalid namespace: ${l} -> ${i}`);let t;do{if(t=d.join(`__`),t in e)break;d.pop()}while(d.length>0);t in e&&(p=e[t])}if(typeof p!=`object`||!p)throw Error(`Invalid namespace: ${l} -> ${i}`);let g=p[a]??Object.values(p).find(e=>typeof e==`function`&&Ge(e)===a);if(typeof g!=`function`)throw Error(`Invalid identifer: ${l} -> ${i}`);let _=new g(Ne(await FN.call({...this,path:[...o,`kwargs`],depth:s+1},e.kwargs),Me,PN(g)));return Object.defineProperty(_.constructor,"name",{value:a}),_}let d={};for(let[e,t]of Object.entries(u))d[e]=await FN.call({...this,path:[...o,e],depth:s+1},t);return d}async function IN(e,t){let n=JSON.parse(e),r={optionalImportsMap:t?.optionalImportsMap??{},optionalImportEntrypoints:t?.optionalImportEntrypoints??[],secretsMap:t?.secretsMap??{},secretsFromEnv:t?.secretsFromEnv??!1,importMap:t?.importMap??{},path:[`$`],depth:0,maxDepth:t?.maxDepth??NN};return FN.call(r,n)}function LN(e){return e!==null&&e.lc===1&&e.type===`constructor`&&Array.isArray(e.id)}function RN(e){return e.lc===2&&e.type===`undefined`}function zN(e){return e.lc===2&&e.type===`delta_snapshot`&&Object.prototype.hasOwnProperty.call(e,`value`)}function BN(e){return e.lc===2&&e.type===`constructor`}function VN(e,t){return Array.isArray(e.id)&&e.id.length===1&&e.id[0]===t}function HN(e){return e.method===void 0||e.method===null}function UN(e){return Array.isArray(e.args)&&e.args.length===1&&Array.isArray(e.args[0])}function WN(e){return e.every(e=>typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=255)}function GN(e){if(VN(e,`Set`)&&HN(e))return UN(e)?new Set(e.args[0]):void 0;if(VN(e,`Map`)&&HN(e))return!UN(e)||!e.args[0].every(e=>Array.isArray(e)&&e.length===2)?void 0:new Map(e.args[0]);if(VN(e,`RegExp`)&&HN(e)){if(!Array.isArray(e.args)||e.args.length!==2||typeof e.args[0]!=`string`||typeof e.args[1]!=`string`)return;try{return new RegExp(e.args[0],e.args[1])}catch{return}}if(VN(e,`Error`)&&HN(e))return!Array.isArray(e.args)||e.args.length!==1||typeof e.args[0]!=`string`?void 0:Error(e.args[0]);if(VN(e,`Uint8Array`)&&(HN(e)||e.method===`from`))return!UN(e)||!WN(e.args[0])?void 0:new Uint8Array(e.args[0])}async function KN(e){if(e&&typeof e==`object`){if(Array.isArray(e))return await Promise.all(e.map(e=>KN(e)));{let t={};for(let[n,r]of Object.entries(e))t[n]=await KN(r);return RN(t)?void 0:zN(t)?new dw(t.value):BN(t)?GN(t)??t:LN(t)?IN(JSON.stringify(t)):t}}return e}function qN(e,t,n,r){return{lc:2,type:`constructor`,id:[e.name],method:t??null,args:n??[],kwargs:r??{}}}function JN(e){return e===void 0?{lc:2,type:`undefined`}:e instanceof dw?{lc:2,type:`delta_snapshot`,value:e.value}:e instanceof Set||e instanceof Map?qN(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?qN(RegExp,void 0,[e.source,e.flags]):e instanceof Error?qN(Error,void 0,[e.message]):e?.lg_name===`Send`?{node:e.node,args:e.args,...e.timeout===void 0?{}:{timeout:e.timeout}}:e instanceof Uint8Array?qN(Uint8Array,`from`,[Array.from(e)]):e}var YN=class{_dumps(e){return new TextEncoder().encode(vw(e,(e,t)=>JN(t)))}async dumpsTyped(e){return e instanceof Uint8Array?[`bytes`,e]:[`json`,this._dumps(e)]}async _loads(e){return KN(JSON.parse(e))}async loadsTyped(e,t){if(e===`bytes`)return typeof t==`string`?new TextEncoder().encode(t):t;if(e===`json`)return this._loads(typeof t==`string`?t:new TextDecoder().decode(t));throw Error(`Unknown serialization type: ${e}`)}};function XN(e){if(typeof e!=`object`||!e)return e;let t=Array.isArray(e)?[]:{};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=XN(e[n]));return t}function ZN(){return{v:4,id:aw(0),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function QN(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values??{}},channel_versions:{...e.channel_versions??{}},versions_seen:XN(e.versions_seen??{})}}function $N(e,t){return typeof e==`number`&&typeof t==`number`?Math.sign(e-t):String(e).localeCompare(String(t))}function eP(...e){return e.reduce((e,t,n)=>n===0?t:$N(e,t)>=0?e:t)}var tP={[sw]:-1,[cw]:-2,[lw]:-3,[uw]:-4},nP=new Set([`thread_id`,`checkpoint_id`,`checkpoint_ns`,`checkpoint_map`,`langgraph_step`,`langgraph_node`,`langgraph_triggers`,`langgraph_path`,`langgraph_checkpoint_ns`]),rP=class extends Error{constructor(e){super(e),this.name=`InvalidNamespaceError`}};function iP(e){if(e.length===0)throw new rP(`Namespace cannot be empty.`);for(let t of e){if(typeof t!=`string`)throw new rP(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes(`.`))throw new rP(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(t===``)throw new rP(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if(e[0]===`langgraph`)throw new rP(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var aP=class{async get(e,t){return(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){let{filter:n,limit:r=10,offset:i=0,query:a}=t;return(await this.batch([{namespacePrefix:e,filter:n,limit:r,offset:i,query:a}]))[0]}async put(e,t,n,r){iP(e),await this.batch([{namespace:e,key:t,value:n,index:r}])}async delete(e,t){await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){let{prefix:t,suffix:n,maxDepth:r,limit:i=100,offset:a=0}=e,o=[];return t&&o.push({matchType:`prefix`,path:t}),n&&o.push({matchType:`suffix`,path:n}),(await this.batch([{matchConditions:o.length?o:void 0,maxDepth:r,limit:i,offset:a}]))[0]}start(){}stop(){}},oP=e=>`lg_name`in e&&e.lg_name===`AsyncBatchedStore`?e.store:e,sP=class extends aP{lg_name=`AsyncBatchedStore`;store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=oP(e)}get isRunning(){return this.running}async batch(e){throw Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){let{filter:n,limit:r=10,offset:i=0,query:a}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:n,limit:r,offset:i,query:a})}async put(e,t,n){return this.enqueueOperation({namespace:e,key:t,value:n})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((t,n)=>{let r=this.nextKey;this.nextKey+=1,this.queue.set(r,{operation:e,resolve:t,reject:n})})}async processBatchQueue(){for(;this.running;){if(await new Promise(e=>{setTimeout(e,0)}),this.queue.size===0)continue;let e=new Map(this.queue);this.queue.clear();try{let t=Array.from(e.values()).map(({operation:e})=>e),n=await this.store.batch(t);e.forEach(({resolve:t},r)=>{t(n[Array.from(e.keys()).indexOf(r)])})}catch(t){e.forEach(({reject:e})=>{e(t)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:`[LangGraphStore]`}}},cP=class{serde=new YN;constructor(e){this.serde=e||this.serde}},lP=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function uP(e){return e!=null&&e.lc_graph_name===`DeltaChannel`}function dP(e){return e!=null&&e.lg_is_channel===!0}var fP=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===$C.unminifiable_name)return!1;throw e}}equals(e){return this===e}},pP=Symbol.for(`LG_IS_ONLY_BASE_CHANNEL`);function mP(e){if(e[pP]===!0)return e;let t={};for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let r=e[n];dP(r)&&(t[n]=r)}return Object.assign(t,{[pP]:!0}),t}function hP(e,t){let n=mP(e),r={};for(let e in n){if(!Object.prototype.hasOwnProperty.call(n,e))continue;let i=t.channel_values[e];r[e]=n[e].fromCheckpoint(i)}return Object.assign(r,{[pP]:!0}),r}function gP(e,t){if(!lP.test(t))throw TypeError(`Invalid task id for exit delta: ${t}`);let n=t.toLowerCase().split(`-`);return`${String(e).padStart(8,`0`)}-${n[1]}-${n[2]}-${n[3]}-${n[4]}`}function _P(e,t){let n=new Set,r=qS();for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let a=e[i];if(!uP(a)||!a.isAvailable())continue;let[o,s]=t[i]??[0,0];(o>=a.snapshotFrequency||s>=r)&&n.add(i)}return n}function vP(e,t,n,r){let i=r?.channelsToSnapshot??new Set,{updatedChannels:a,getNextVersion:o}=r??{},s,c=e.channel_versions;if(t===void 0)s=e.channel_values;else{s={},c={...e.channel_versions};for(let e in t){if(!Object.prototype.hasOwnProperty.call(t,e))continue;let n=t[e];if(i.has(e)){o!==void 0&&(a===void 0||!a.has(e))&&(c[e]=o(c[e])),s[e]=new dw(n.get());continue}if(!uP(n))try{s[e]=n.checkpoint()}catch(e){if(e.name!==$C.unminifiable_name)throw e}}}return{v:4,id:r?.id??aw(n),ts:new Date().toISOString(),channel_values:s,channel_versions:c,versions_seen:e.versions_seen}}async function yP(e,t,n){let r=hP(e,t),{saver:i,config:a}=n??{},o=mP(e),s=[];for(let e in o)Object.prototype.hasOwnProperty.call(o,e)&&uP(o[e])&&!Object.prototype.hasOwnProperty.call(t.channel_values,e)&&s.push(e);if(s.length===0||i===void 0||a===void 0)return r;let c=await i.getDeltaChannelHistory({config:a,channels:s});for(let e of s){let t=c[e];if(t===void 0)continue;let n=o[e].fromCheckpoint(t.seed);n.replayWrites(t.writes),r[e]=n}return r}var bP=class e extends fP{lc_graph_name=`LastValue`;value=[];constructor(e){super(),this.initialValueFactory=e,e&&(this.value=[e()])}fromCheckpoint(t){let n=new e(this.initialValueFactory);return t!==void 0&&(n.value=[t]),n}update(e){if(e.length===0)return!1;if(e.length!==1)throw new ew(`LastValue can only receive one value per step.`,{lc_error_code:`INVALID_CONCURRENT_GRAPH_UPDATE`});return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new $C;return this.value[0]}checkpoint(){if(this.value.length===0)throw new $C;return this.value[0]}isAvailable(){return this.value.length!==0}},xP=class e extends fP{lc_graph_name=`LastValueAfterFinish`;value=[];finished=!1;fromCheckpoint(t){let n=new e;if(t!==void 0){let[e,r]=t;n.value=[e],n.finished=r}return n}update(e){return e.length===0?!1:(this.finished=!1,this.value=[e[e.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new $C;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}},SP=e=>e!=null&&e.lc_graph_name===`BinaryOperatorAggregate`,CP=class e extends fP{lc_graph_name=`BinaryOperatorAggregate`;value;operator;initialValueFactory;constructor(e,t){super(),this.operator=e,this.initialValueFactory=t,this.value=t?.()}fromCheckpoint(t){let n=new e(this.operator,this.initialValueFactory);return t!==void 0&&(n.value=t),n}update(e){let t=e;if(!t.length)return!1;if(this.value===void 0){let e=t[0],[n,r]=jC(e);n?this.value=r:this.value=e,t=t.slice(1)}let n=!1;for(let e of t)if(MC(e)){if(n)throw new ew(`Can receive only one Overwrite value per step.`);let[,t]=jC(e);this.value=t,n=!0;continue}else!n&&this.value!==void 0&&(this.value=this.operator(this.value,e));return!0}get(){if(this.value===void 0)throw new $C;return this.value}checkpoint(){if(this.value===void 0)throw new $C;return this.value}isAvailable(){return this.value!==void 0}equals(e){return this===e?!0:SP(e)?this.operator===e.operator:!1}},wP=class{lc_graph_name=`AnnotationRoot`;spec;constructor(e){this.spec=e}static isInstance(e){return typeof e==`object`&&!!e&&`lc_graph_name`in e&&e.lc_graph_name===`AnnotationRoot`}},TP=function(e){return e?EP(e):new bP};TP.Root=e=>new wP(e);function EP(e){return typeof e==`object`&&e&&`reducer`in e&&e.reducer?new CP(e.reducer,e.default):typeof e==`object`&&e&&`value`in e&&e.value?new CP(e.value,e.default):new bP}var DP=[`tags`,`metadata`,`callbacks`,`configurable`],OP=[`tags`,`metadata`,`callbacks`,`runName`,`maxConcurrency`,`recursionLimit`,`configurable`,`runId`,`outputKeys`,`streamMode`,`store`,`writer`,`interrupt`,`context`,`interruptBefore`,`interruptAfter`,`checkpointDuring`,`durability`,`signal`,`heartbeat`,`executionInfo`,`serverInfo`,`control`],kP=25,AP=new Set([`thread_id`,`checkpoint_id`,`checkpoint_ns`,`task_id`,`run_id`,`assistant_id`,`graph_id`]);function jP(e,t){if(!e)return t;let n=t??{};for(let t of AP){if(t in n)continue;let r=e[t];r!==void 0&&(n[t]=r)}return n}function MP(e){if(e==null||e.length===0)return;let t=e.filter(e=>!e.startsWith(`seq:step`));return t.length>0?t:void 0}function NP(e,t){if(t===void 0)return e;if(e===void 0)return Array.isArray(t)?[...t]:t.copy();if(Array.isArray(t)){if(Array.isArray(e))return e.concat(t);let n=e.copy();for(let e of t)n.addHandler(vu(e),!0);return n}if(Array.isArray(e)){let n=t.copy();for(let t of e)n.addHandler(vu(t),!0);return n}let n=e=>e.filter((t,n)=>e.findIndex(e=>e===t||e.name===`StreamMessagesHandler`&&t.name===`StreamMessagesHandler`)===n);return new _u(t._parentRunId,{handlers:n(e.handlers.concat(t.handlers)),inheritableHandlers:n(e.inheritableHandlers.concat(t.inheritableHandlers)),tags:Array.from(new Set(e.tags.concat(t.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(t.inheritableTags))),metadata:{...e.metadata,...t.metadata},inheritableMetadata:{...e.inheritableMetadata,...t.inheritableMetadata}})}function PP(e){let t;for(let n=e.length-1;n>=0;--n)if(e[n]!==void 0){t=e[n];break}let n=t?.configurable?.thread_id!==void 0,r=e.some(e=>e?.configurable?.[XS]!==void 0),i=Su.getRunnableConfig()?.configurable?.[XS]!==void 0;return n&&!r&&!i}function FP(...e){let t={tags:[],metadata:{},callbacks:void 0,recursionLimit:kP,configurable:{}},n=PP(e),r=Su.getRunnableConfig();if(r!==void 0){for(let[e,i]of Object.entries(r))if(i!==void 0){if(e===`configurable`&&n)continue;if(DP.includes(e)){let n;n=Array.isArray(i)?[...i]:typeof i==`object`?e===`callbacks`&&`copy`in i&&typeof i.copy==`function`?i.copy():{...i}:i,t[e]=n}else t[e]=i}}for(let n of e)if(n!==void 0)for(let[e,r]of Object.entries(n))r===void 0||!OP.includes(e)||(e===`configurable`?t.configurable={...t.configurable,...r}:e===`metadata`?t.metadata={...t.metadata,...r}:e===`tags`?t.tags=[...t.tags??[],...r]:e===`callbacks`?t.callbacks=NP(t.callbacks,r):t[e]=r);return t.metadata=jP(t.configurable,t.metadata)??{},t}function IP(){return Su.getRunnableConfig()}function LP(e){return e.split(`|`).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(`:`)[0]).join(`|`)}function RP(e){let t=e.split(`|`);for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join(`|`)}var zP=class extends tS{lc_namespace=[`langgraph`];func;tags;config;trace=!0;recurse=!0;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,t,n){return new Promise((r,i)=>{let a=Au(t,{callbacks:n?.getChild()});Su.runWithConfig(a,async()=>{try{r(await this.func(e,a))}catch(e){i(e)}})})}async invoke(e,t){let n,r=FP(t),i=Ou(this.config,r);return n=this.trace?await this._callWithConfig(this._tracedInvoke,e,i):await Su.runWithConfig(i,async()=>this.func(e,i)),tS.isRunnable(n)&&this.recurse?await Su.runWithConfig(i,async()=>n.invoke(e,i)):n}};function*BP(e,t){if(t===void 0)yield*e;else for(let n of e)yield[t,n]}async function VP(e){let t=[];for await(let n of await e)t.push(n);return t}function HP(e){let t=[];for(let n of e)t.push(n);return t}function UP(e,t){return e?`configurable`in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function WP(e){return typeof e==`object`&&e?.[Symbol.for(`LG_SKIP_WRITE`)]!==void 0}var GP={[Symbol.for(`LG_PASSTHROUGH`)]:!0};function KP(e){return typeof e==`object`&&e?.[Symbol.for(`LG_PASSTHROUGH`)]!==void 0}var qP=Symbol(`IS_WRITER`),JP=class e extends zP{writes;constructor(e,t){let n=`ChannelWrite<${e.map(e=>kC(e)?e.node:`channel`in e?e.channel:`...`).join(`,`)}>`;super({writes:e,name:n,tags:t,trace:!1,func:async(e,t)=>this._write(e,t??{})}),this.writes=e}async _write(t,n){let r=this.writes.map(e=>XP(e)&&KP(e.value)?{mapper:e.mapper,value:t}:YP(e)&&KP(e.value)?{channel:e.channel,value:t,skipNone:e.skipNone,mapper:e.mapper}:e);return await e.doWrite(n,r),t}static async doWrite(e,t){for(let e of t){if(YP(e)){if(e.channel===`__pregel_tasks`)throw new ew(`Cannot write to the reserved channel TASKS`);if(KP(e.value))throw new ew(`PASSTHROUGH value must be replaced`)}if(XP(e)&&KP(e.value))throw new ew(`PASSTHROUGH value must be replaced`)}let n=[];for(let r of t)if(kC(r))n.push([bC,r]);else if(XP(r)){let t=await r.mapper.invoke(r.value,e);t!=null&&t.length>0&&n.push(...t)}else if(YP(r)){let t=r.mapper===void 0?r.value:await r.mapper.invoke(r.value,e);if(WP(t)||r.skipNone&&t===void 0)continue;n.push([r.channel,t])}else throw Error(`Invalid write entry: ${JSON.stringify(r)}`);let r=e.configurable?.[JS];r(n)}static isWriter(t){return t instanceof e||qP in t&&!!t[qP]}static registerWriter(e){return Object.defineProperty(e,qP,{value:!0})}};function YP(e){return e!==void 0&&typeof e.channel==`string`}function XP(e){return e!==void 0&&!YP(e)&&tS.isRunnable(e.mapper)}var ZP=class e extends zP{lc_graph_name=`ChannelRead`;channel;fresh=!1;mapper;constructor(t,n,r=!1){super({trace:!1,func:(t,n)=>e.doRead(n,this.channel,this.fresh,this.mapper)}),this.fresh=r,this.mapper=n,this.channel=t,this.name=Array.isArray(t)?`ChannelRead<${t.join(`,`)}>`:`ChannelRead<${t}>`}static doRead(e,t,n,r){let i=e.configurable?.[XS];if(!i)throw Error(`Runnable is not configured with a read function. Make sure to call in the context of a Pregel process`);return r?r(i(t,n)):i(t,n)}},QP=new _S,$P=class e extends nS{lc_graph_name=`PregelNode`;channels;triggers=[];mapper;writers=[];bound=QP;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;timeout;subgraphs;ends;isErrorHandler;errorHandlerNode;constructor(e){let{channels:t,triggers:n,mapper:r,writers:i,bound:a,kwargs:o,metadata:s,retryPolicy:c,cachePolicy:l,timeout:u,tags:d,subgraphs:f,ends:p,isErrorHandler:m,errorHandlerNode:h}=e,g=[...e.config?.tags?e.config.tags:[],...d??[]];super({...e,bound:e.bound??QP,config:{...e.config?e.config:{},tags:g}}),this.channels=t,this.triggers=n,this.mapper=r,this.writers=i??this.writers,this.bound=a??this.bound,this.kwargs=o??this.kwargs,this.metadata=s??this.metadata,this.tags=g,this.retryPolicy=c,this.cachePolicy=l,this.timeout=u,this.subgraphs=f,this.ends=p,this.isErrorHandler=m,this.errorHandlerNode=h}getWriters(){let e=[...this.writers];for(;e.length>1&&e[e.length-1]instanceof JP&&e[e.length-2]instanceof JP;){let t=e.slice(-2),n=t[0].writes.concat(t[1].writes);e[e.length-2]=new JP(n,t[0].config?.tags),e.pop()}return e}getNode(){let e=this.getWriters();if(!(this.bound===QP&&e.length===0))return this.bound===QP&&e.length===1?e[0]:this.bound===QP?new aS({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new aS({first:this.bound,middle:e.slice(0,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):this.bound}join(t){if(!Array.isArray(t))throw Error(`channels must be a list`);if(typeof this.channels!=`object`)throw Error(`all channels must be named when using .join()`);return new e({channels:{...this.channels,...Object.fromEntries(t.map(e=>[e,e]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout})}pipe(t){return JP.isWriter(t)?new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,t],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout}):this.bound===QP?new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:fS(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout}):new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout})}};function eF(e){let t=typeof e[VS];if(t===`number`)return 0;if(t===`string`)return``;for(let t in e){if(!Object.prototype.hasOwnProperty.call(e,t))continue;let n=typeof e[t];if(n===`number`)return 0;if(n===`string`)return``;break}}function tF(e,t){if(Object.keys(e).length>0){let n=eF(t);return Object.fromEntries(Object.entries(t).filter(([t,r])=>r>(e[t]??n)))}else return t}function nF(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e==`object`?e:{[t]:e}}function rF(e,t){return e===null?{configurable:t}:e?.configurable===void 0?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function iF(e,t){let n=t?.parents??{};return Object.keys(n).length>0?rF(e,{[uC]:{...n,[e.configurable?.checkpoint_ns??``]:e.configurable?.checkpoint_id}}):e}function aF(...e){let t=[...new Set(e.filter(Boolean))];if(t.length===0)return{signal:void 0,dispose:void 0};if(t.length===1)return{signal:t[0],dispose:void 0};let n=new AbortController,r=()=>{let e=t.find(e=>e.aborted)?.reason;n.abort(e),t.forEach(e=>e.removeEventListener(`abort`,r))};t.forEach(e=>e.addEventListener(`abort`,r,{once:!0}));let i=t.find(e=>e.aborted);return i&&n.abort(i.reason),{signal:n.signal,dispose:()=>{t.forEach(e=>e.removeEventListener(`abort`,r))}}}function oF(e){return`steps`in e&&Array.isArray(e.steps)}function sF(e){return`lg_is_pregel`in e&&e.lg_is_pregel===!0}function cF(e){let t=[e];for(let e of t)if(sF(e))return e;else oF(e)&&t.push(...e.steps)}var lF=class e extends fP{lc_graph_name=`EphemeralValue`;guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(t){let n=new e(this.guard);return t!==void 0&&(n.value=[t]),n}update(e){if(e.length===0){let e=this.value.length>0;return this.value=[],e}if(e.length!==1&&this.guard)throw new ew(`EphemeralValue can only receive one value per step.`);return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new $C;return this.value[0]}checkpoint(){if(this.value.length===0)throw new $C;return this.value[0]}isAvailable(){return this.value.length!==0}},uF=class{#e=void 0;requestDrain(e=`shutdown`){this.#e=e}get drainRequested(){return this.#e!==void 0}get drainReason(){return this.#e}},H=e=>BigInt(e),dF=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),fF=H(`0x9E3779B1`),pF=H(`0x85EBCA77`),mF=H(`0xC2B2AE3D`),hF=H(`0x9E3779B185EBCA87`),gF=H(`0xC2B2AE3D27D4EB4F`),_F=H(`0x165667B19E3779F9`),vF=H(`0x85EBCA77C2B2AE63`),yF=H(`0x27D4EB2F165667C5`),bF=H(`0x165667919E3779F9`),xF=H(`0x9FB21C651E98DF25`),SF=(e=>{let t=e.length;if(t%2!=0)throw Error(`String should have an even number of characters`);let n=t/2,r=new Uint8Array(n),i=0,a=0;for(;a<n;){let t=e.slice(i,i+=2);r[a]=Number.parseInt(t,16),a+=1}return dF(r)})(`b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e`),CF=(H(1)<<H(128))-H(1),wF=(H(1)<<H(64))-H(1),TF=(H(1)<<H(32))-H(1),EF=64,DF=EF/8,OF=8,kF=4;function AF(e){if(!e)throw Error(`Assert failed`)}function jF(e){let t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function MF(e){let t=e;return t=(t&H(65535))<<H(16)|(t&H(4294901760))>>H(16),t=(t&H(16711935))<<H(8)|(t&H(4278255360))>>H(8),t}function NF(e,t){return(e&TF)*(t&TF)&wF}function PF(e,t){return(e<<t|e>>H(32)-t)&TF}function FF(e,t,n){for(let r=0;r<DF;r+=1){let i=t.getBigUint64(r*8,!0),a=i^n.getBigUint64(r*8,!0);e[r^1]+=i,e[r]+=NF(a,a>>H(32))}return e}function IF(e,t,n,r){for(let i=0;i<r;i+=1)FF(e,dF(t,i*EF),dF(n,i*8));return e}function LF(e,t){for(let n=0;n<DF;n+=1){let r=t.getBigUint64(n*8,!0),i=e[n];i=JF(i,H(47)),i^=r,i*=fF,e[n]=i&wF}return e}function RF(e,t){return HF(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(OF,!0))}function zF(e,t,n){let r=n;return r+=RF(e.slice(0),dF(t,0*kF)),r+=RF(e.slice(2),dF(t,4*kF)),r+=RF(e.slice(4),dF(t,8*kF)),r+=RF(e.slice(6),dF(t,12*kF)),GF(r&wF)}function BF(e,t,n,r,i){let a=e,o=Math.floor((n.byteLength-EF)/8),s=EF*o,c=Math.floor((t.byteLength-1)/s);for(let e=0;e<c;e+=1)a=IF(a,dF(t,e*s),n,o),a=i(a,dF(n,n.byteLength-EF));{let e=Math.floor((t.byteLength-1-s*c)/EF);a=IF(a,dF(t,c*s),n,e),a=r(a,dF(t,t.byteLength-EF),dF(n,n.byteLength-EF-7))}return a}function VF(e,t){let n=new BigUint64Array([mF,hF,gF,_F,vF,pF,yF,fF]);AF(e.byteLength>128),n=BF(n,e,t,FF,LF),AF(n.length*8==64);{let r=zF(n,dF(t,11),H(e.byteLength)*hF&wF);return zF(n,dF(t,t.byteLength-EF-11),~(H(e.byteLength)*gF)&wF)<<H(64)|r}}function HF(e,t){let n=e*t&CF;return n&wF^n>>H(64)}function UF(e,t,n){return HF((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+n)&wF,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-n)&wF)}function WF(e,t,n,r,i){let a=e&wF,o=e>>H(64)&wF;return a+=UF(t,r,i),a^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),a&=wF,o+=UF(n,dF(r,16),i),o^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),o&=wF,o<<H(64)|a}function GF(e){let t=e;return t^=t>>H(37),t*=bF,t&=wF,t^=t>>H(32),t}function KF(e){let t=e;return t^=t>>H(33),t*=gF,t&=wF,t^=t>>H(29),t*=_F,t&=wF,t^=t>>H(32),t}function qF(e,t,n){let r=e.byteLength;AF(r>0&&r<=3);let i=H(e.getUint8(r-1))|H(r<<8)|H(e.getUint8(0)<<16)|H(e.getUint8(r>>1)<<24),a=(i^(H(t.getUint32(0,!0))^H(t.getUint32(4,!0)))+n)&wF,o=(H(t.getUint32(8,!0))^H(t.getUint32(12,!0)))-n;return(KF((PF(MF(i),H(13))^o)&wF)&wF)<<H(64)|KF(a)}function JF(e,t){return e^e>>t}function YF(e,t,n){let r=e.byteLength;AF(r>=4&&r<=8);{let i=e.getUint32(0,!0),a=e.getUint32(r-4,!0),o=((H(i)|H(a)<<H(32))^(t.getBigUint64(16,!0)^t.getBigUint64(24,!0))+n&wF)*(hF+(H(r)<<H(2)))&CF;return o+=(o&wF)<<H(65),o&=CF,o^=o>>H(67),JF(JF(o&wF,H(35))*xF&wF,H(28))|GF(o>>H(64))<<H(64)}}function XF(e,t,n){let r=e.byteLength;AF(r>=9&&r<=16);{let i=(t.getBigUint64(32,!0)^t.getBigUint64(40,!0))+n&wF,a=(t.getBigUint64(48,!0)^t.getBigUint64(56,!0))-n&wF,o=e.getBigUint64(0,!0),s=e.getBigUint64(r-8,!0),c=(o^s^i)*hF,l=(c&wF)+(H(r-1)<<H(54));c=c&(CF^wF)|l,s^=a,c+=s+(s&TF)*(pF-H(1))<<H(64),c&=CF,c^=jF(c>>H(64));let u=(c&wF)*gF;return u+=(c>>H(64))*gF<<H(64),u&=CF,GF(u&wF)|GF(u>>H(64))<<H(64)}}function ZF(e,t){let n=e.byteLength;return AF(n<=16),n>8?XF(e,SF,t):n>=4?YF(e,SF,t):n>0?qF(e,SF,t):KF(t^SF.getBigUint64(64,!0)^SF.getBigUint64(72,!0))|KF(t^SF.getBigUint64(80,!0)^SF.getBigUint64(88,!0))<<H(64)}function QF(e){return~e+H(1)&wF}function $F(e,t,n){let r=H(e.byteLength)*hF&wF,i=H(e.byteLength-1)/H(32);for(;i>=0;){let a=Number(i);r=WF(r,dF(e,16*a),dF(e,e.byteLength-16*(a+1)),dF(t,32*a),n),i-=H(1)}let a=r+(r>>H(64))&wF;a=GF(a);let o=(r&wF)*hF+(r>>H(64))*vF+(H(e.byteLength)-n&wF)*gF;return o&=wF,o=QF(GF(o)),a|o<<H(64)}function eI(e,t,n){let r=H(e.byteLength)*hF&wF;for(let i=32;i<160;i+=32)r=WF(r,dF(e,i-32),dF(e,i-16),dF(t,i-32),n);r=GF(r&wF)|GF(r>>H(64))<<H(64);for(let i=160;i<=e.byteLength;i+=32)r=WF(r,dF(e,i-32),dF(e,i-16),dF(t,3+i-160),n);r=WF(r,dF(e,e.byteLength-16),dF(e,e.byteLength-32),dF(t,103),QF(n));let i=r+(r>>H(64))&wF;i=GF(i);let a=(r&wF)*hF+(r>>H(64))*vF+(H(e.byteLength)-n&wF)*gF;return a&=wF,a=QF(GF(a)),i|a<<H(64)}function tI(e,t=H(0)){let n=new TextEncoder,r=dF(typeof e==`string`?n.encode(e):e),i=r.byteLength;return(e=>e.toString(16).padStart(32,`0`))(i<=16?ZF(r,t):i<=128?$F(r,SF,t):i<=240?eI(r,SF,t):VF(r,SF))}function nI(e){return/^[0-9a-f]{32}$/.test(e)}function rI(e,t,n=!0,r=!1){try{return e[t].get()}catch(e){if(e.name===$C.unminifiable_name){if(r)return e;if(n)return null}throw e}}function iI(e,t,n=!0){if(Array.isArray(t)){let r={};for(let i of t)try{r[i]=rI(e,i,!n)}catch(e){if(e.name===$C.unminifiable_name)continue}return r}else return rI(e,t)}function*aI(e,t){if(e.graph===PC.PARENT)throw new ew(`There is no parent graph.`);if(e.goto){let t;t=Array.isArray(e.goto)?e.goto:[e.goto];for(let e of t)if(kC(e))yield[CC,bC,e];else if(typeof e==`string`)yield[CC,`branch:to:${e}`,`__start__`];else throw Error(`In Command.send, expected Send or string, got ${typeof e}`)}if(e.resume)if(typeof e.resume==`object`&&Object.keys(e.resume).length&&Object.keys(e.resume).every(nI))for(let[n,r]of Object.entries(e.resume)){let e=t.filter(e=>e[0]===n&&e[1]===`__resume__`).map(e=>e[2]).slice(0,1)??[];e.push(r),yield[n,mC,e]}else yield[CC,mC,e.resume];if(e.update){if(typeof e.update!=`object`||!e.update)throw Error(`Expected cmd.update to be a dict mapping channel names to update values`);if(Array.isArray(e.update))for(let[t,n]of e.update)yield[CC,t,n];else for(let[t,n]of Object.entries(e.update))yield[CC,t,n]}}function*oI(e,t){if(t!=null)if(Array.isArray(e)&&typeof t==`object`&&!Array.isArray(t))for(let n in t)e.includes(n)&&(yield[n,t[n]]);else if(Array.isArray(e))throw Error(`Input chunk must be an object when "inputChannels" is an array`);else yield[e,t]}function*sI(e,t,n){Array.isArray(e)?(t===!0||t.find(([t,n])=>e.includes(t)))&&(yield iI(n,e)):(t===!0||t.some(([t,n])=>t===e))&&(yield rI(n,e))}function*cI(e,t,n){let r=t.filter(([e,t])=>(e.config===void 0||!e.config.tags?.includes(`langsmith:hidden`))&&t[0][0]!==`__error__`&&t[0][0]!==`__interrupt__`);if(!r.length)return;let i;i=r.some(([e])=>e.writes.some(([e,t])=>e===`__return__`))?r.flatMap(([e])=>e.writes.filter(([e,t])=>e===gC).map(([t,n])=>[e.name,n])):Array.isArray(e)?r.flatMap(([t])=>{let{writes:n}=t,r={};for(let[t]of n)e.includes(t)&&(r[t]=(r[t]||0)+1);return Object.values(r).some(e=>e>1)?n.filter(([t])=>e.includes(t)).map(([e,n])=>[t.name,{[e]:n}]):[[t.name,Object.fromEntries(n.filter(([t])=>e.includes(t)))]]}):r.flatMap(([t])=>t.writes.filter(([t,n])=>t===e).map(([e,n])=>[t.name,n]));let a={};for(let[e,t]of i)e in a||(a[e]=[]),a[e].push(t);let o={};for(let e in a)if(a[e].length===1){let[t]=a[e];o[e]=t}else o[e]=a[e];n&&(o.__metadata__={cached:n}),yield o}var lI=class{func;name;input;retry;cache;timeout;callbacks;__lg_type=`call`;constructor({func:e,name:t,input:n,retry:r,cache:i,timeout:a,callbacks:o}){this.func=e,this.name=t,this.input=n,this.retry=r,this.cache=i,this.timeout=a,this.callbacks=o}};function uI(e){return typeof e==`object`&&!!e&&`__lg_type`in e&&e.__lg_type===`call`}function dI(e,t){return new aS({name:e,first:new zP({func:e=>t(...e),name:e,trace:!1,recurse:!1}),last:new JP([{channel:gC,value:GP}],[vC])})}var fI=e=>e===void 0?1:e+1;function pI(e,t){if(t==null)return!1;for(let n of e)if(t[n])return!0;return!1}function mI(e){let t;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t=t==null?e[n]:eP(t,e[n]));return t}function hI(e,t,n){let r=eF(e.channel_versions),i=e.versions_seen.__interrupt__??{},a=!1;if((e.channel_versions.__start__??r)>(i.__start__??r))a=!0;else for(let t in e.channel_versions)if(Object.prototype.hasOwnProperty.call(e.channel_versions,t)&&e.channel_versions[t]>(i[t]??r)){a=!0;break}let o=n.some(e=>t===`*`?!e.config?.tags?.includes(vC):t.includes(e.name));return a&&o}function gI(e,t,n,r,i=!1){let a=new Set;if(Array.isArray(r))a=new Set(r.filter(e=>n.writes.some(([t,n])=>t===e)));else{for(let[e]of n.writes)if(e===r){a=new Set([e]);break}a||=new Set}let o;if(i&&a.size>0){let i=Object.fromEntries(Object.entries(t).filter(([e,t])=>a.has(e))),s=new Set;for(let e in i){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let t=i[e];uP(t)&&t.isAvailable()&&s.add(e)}let c=vP(e,i,-1,{channelsToSnapshot:s}),l=hP(i,c);bI(QN(c),l,[n],void 0,void 0),o=iI({...t,...l},r)}else o=iI(t,r);return o}function _I(e,t,n){for(let[e,r]of n)if([`__pregel_push`,`__pregel_tasks`].includes(e)&&r!=null){if(!kC(r))throw new ew(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(r)}`);if(!(r.node in t))throw new ew(`Invalid node name "${r.node}" in Send packet`)}e(n)}var vI=new Set([hC,xC,mC,pC,gC,WS,GS]),yI=new Set(wC);function bI(e,t,n,r,i){let a=new Map;for(let e of n)a.set(e,e.path?.slice(0,3)||[]);n.sort((e,t)=>{let n=a.get(e),r=a.get(t);for(let e=0;e<Math.min(n.length,r.length);e+=1){if(n[e]<r[e])return-1;if(n[e]>r[e])return 1}return n.length-r.length});let o=mP(t),s=!1,c=new Set;for(let t of n){t.triggers.length>0&&(s=!0),e.versions_seen[t.name]??={};for(let n of t.triggers)n in e.channel_versions&&(e.versions_seen[t.name][n]=e.channel_versions[n]),yI.has(n)||c.add(n)}let l=mI(e.channel_versions),u=!1;for(let t of c)t in o&&o[t].consume()&&r!==void 0&&(e.channel_versions[t]=r(l),u=!0);let d={},f={};for(let e of n){let t=e.id??``;for(let[n,r]of e.writes)vI.has(n)||n in o&&(d[n]??=[],d[n].push(r),f[n]??=[],f[n].push(t))}for(let[e,t]of Object.entries(d)){if(t.length<2||o[e]?.lc_graph_name!==`DeltaChannel`)continue;let n=f[e],r=t.map((e,t)=>({val:e,taskId:n[t]}));r.sort((e,t)=>e.taskId<t.taskId?-1:+(e.taskId>t.taskId)),d[e]=r.map(e=>e.val)}l!=null&&r!=null&&(l=u?r(l):l);let p=new Set;for(let[t,n]of Object.entries(d))if(t in o){let i=o[t],a;try{a=i.update(n)}catch(e){if(e.name===ew.unminifiable_name){let r=new ew(`Invalid update for channel "${t}" with values ${JSON.stringify(n)}: ${e.message}`);throw r.lc_error_code=e.lc_error_code,r}else throw e}a&&r!==void 0&&(e.channel_versions[t]=r(l),i.isAvailable()&&p.add(t))}if(s)for(let t in o){if(!Object.prototype.hasOwnProperty.call(o,t))continue;let n=o[t];n.isAvailable()&&!p.has(t)&&n.update([])&&r!==void 0&&(e.channel_versions[t]=r(l),n.isAvailable()&&p.add(t))}if(s&&!pI(p,i))for(let t in o){if(!Object.prototype.hasOwnProperty.call(o,t))continue;let n=o[t];n.finish()&&r!==void 0&&(e.channel_versions[t]=r(l),n.isAvailable()&&p.add(t))}return p}function*xI(e,t,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){let e=new Set;for(let t of n.updatedChannels){let r=n.triggerToNodes[t];for(let t of r??[])e.add(t)}yield*[...e].sort();return}if(!(()=>{for(let t in e.channel_versions)if(e.channel_versions[t]!==null)return!1;return!0})())for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(yield e)}function SI(e){let t,n=new Map,r=new Set;if(e)for(let[i,a,o]of e){if(i===`00000000-0000-0000-0000-000000000000`&&a===`__resume__`&&t===void 0&&(t=o),a===`__resume__`&&i!==`00000000-0000-0000-0000-000000000000`){let e=n.get(i);e||(e=[],n.set(i,e)),e.push(o)}a!==`__error__`&&r.add(i)}return{nullResume:t,resumeByTaskId:n,successfulWriteTaskIds:r}}function CI(e,t,n,r,i,a,o){let s={},c=o.pendingWritesIndex?o:{...o,pendingWritesIndex:SI(t)},l=r[bC];if(l?.isAvailable()){let o=l.get().length;for(let l=0;l<o;l+=1){let o=wI([xC,l],e,t,n,r,i,a,c);o!==void 0&&(s[o.id]=o)}}for(let o of xI(e,n,c)){let l=wI([SC,o],e,t,n,r,i,a,c);l!==void 0&&(s[l.id]=l)}return s}function wI(e,t,n,r,i,a,o,s){let{step:c,checkpointer:l,manager:u}=s,d=a.configurable??{},f=d.checkpoint_ns??``;if(e[0]===`__pregel_push`&&uI(e[e.length-1])){let p=e[e.length-1],m=dI(p.name,p.func),h=[xC],g=f===``?p.name:`${f}|${p.name}`,_=ow(JSON.stringify([g,c.toString(),p.name,xC,e[1],e[2]]),t.id),v=`${g}:${_}`,y=[...e.slice(0,3),!0],b={langgraph_step:c,langgraph_node:p.name,langgraph_triggers:h,langgraph_path:y,langgraph_checkpoint_ns:v,checkpoint_ns:v};if(o){let e=[],o={checkpointId:t.id,checkpointNs:v,taskId:_,threadId:d.thread_id,runId:a.runId==null?void 0:String(a.runId),nodeAttempt:1};return{name:p.name,input:p.input,proc:m,writes:e,config:{...Au(Ou(a,{metadata:b,store:s.store??a.store}),{runName:p.name,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[$S]:_,[JS]:t=>_I(t=>e.push(...t),r,t),[XS]:(n,r=!1)=>gI(t,i,{name:p.name,writes:e,triggers:h,path:y},n,r),[ZS]:l??d.__pregel_checkpointer,[uC]:{...d[uC],[f]:t.id},[rC]:OI({pendingWrites:n??[],taskId:_,currentTaskInput:p.input,resumeMap:a.configurable?.[nC],namespaceHash:tI(v),pendingWritesIndex:s.pendingWritesIndex}),[iC]:t.channel_values[_C],checkpoint_id:void 0,checkpoint_ns:v}}),executionInfo:o},triggers:h,retry_policy:p.retry,cache_key:p.cache?{key:tI((p.cache.keyFunc??JSON.stringify)([p.input])),ns:[KS,p.name??`__dynamic__`],ttl:p.cache.ttl}:void 0,id:_,path:y,writers:[],timeout:p.timeout}}else return{id:_,name:p.name,interrupts:[],path:y}}else if(e[0]===`__pregel_push`){let p=typeof e[1]==`number`?e[1]:parseInt(e[1],10);if(!i.__pregel_tasks?.isAvailable())return;let m=i[bC].get();if(p<0||p>=m.length)return;let h=DC(m[p])&&!kC(m[p])?new OC(m[p].node,m[p].args,m[p].timeout===void 0?void 0:{timeout:m[p].timeout}):m[p];if(!DC(h)){console.warn(`Ignoring invalid packet ${JSON.stringify(h)} in pending sends.`);return}if(!(h.node in r)){console.warn(`Ignoring unknown node name ${h.node} in pending sends.`);return}let g=[xC],_=f===``?h.node:`${f}|${h.node}`,v=ow(JSON.stringify([_,c.toString(),h.node,xC,p.toString()]),t.id),y=`${_}:${v}`,b={langgraph_step:c,langgraph_node:h.node,langgraph_triggers:g,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:y,checkpoint_ns:y};if(o){let o=r[h.node],p=o.getNode();if(p!==void 0){o.metadata!==void 0&&(b={...b,...o.metadata});let m=[],_={checkpointId:t.id,checkpointNs:y,taskId:v,threadId:d.thread_id,runId:a.runId==null?void 0:String(a.runId),nodeAttempt:1};return{name:h.node,input:h.args,proc:p,subgraphs:o.subgraphs,writes:m,config:{...Au(Ou(a,{metadata:b,tags:o.tags,store:s.store??a.store}),{runName:h.node,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[$S]:v,[JS]:e=>_I(e=>m.push(...e),r,e),[XS]:(n,r=!1)=>gI(t,i,{name:h.node,writes:m,triggers:g,path:e},n,r),[ZS]:l??d.__pregel_checkpointer,[uC]:{...d[uC],[f]:t.id},[rC]:OI({pendingWrites:n??[],taskId:v,currentTaskInput:h.args,resumeMap:a.configurable?.[nC],namespaceHash:tI(y),pendingWritesIndex:s.pendingWritesIndex}),[iC]:t.channel_values[_C],checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:_},triggers:g,retry_policy:o.retryPolicy,cache_key:o.cachePolicy?{key:tI((o.cachePolicy.keyFunc??JSON.stringify)([h.args])),ns:[KS,o.name??`__dynamic__`,h.node],ttl:o.cachePolicy.ttl}:void 0,id:v,path:e,writers:o.getWriters(),timeout:h.timeout??o.timeout}}}else return{id:v,name:h.node,interrupts:[],path:e}}else if(e[0]===`__pregel_pull`){let p=e[1].toString(),m=r[p];if(m===void 0)return;if(n?.length){let e=f===``?p:`${f}|${p}`,r=ow(JSON.stringify([e,c.toString(),p,SC,p]),t.id);if(s.pendingWritesIndex?s.pendingWritesIndex.successfulWriteTaskIds.has(r):n.some(e=>e[0]===r&&e[1]!==`__error__`))return}let h=eF(t.channel_versions);if(h===void 0)return;let g=t.versions_seen[p]??{},_=m.triggers.find(e=>i[e].isAvailable()?(t.channel_versions[e]??h)>(g[e]??h):!1);if(_!==void 0){let h=EI(m,i,o);if(h===void 0)return;let g=f===``?p:`${f}|${p}`,v=ow(JSON.stringify([g,c.toString(),p,SC,[_]]),t.id),y=`${g}:${v}`,b={langgraph_step:c,langgraph_node:p,langgraph_triggers:[_],langgraph_path:e,langgraph_checkpoint_ns:y,checkpoint_ns:y};if(o){let o=m.getNode();if(o!==void 0){m.metadata!==void 0&&(b={...b,...m.metadata});let g=[],ee={checkpointId:t.id,checkpointNs:y,taskId:v,threadId:d.thread_id,runId:a.runId==null?void 0:String(a.runId),nodeAttempt:1};return{name:p,input:h,proc:o,subgraphs:m.subgraphs,writes:g,config:{...Au(Ou(a,{metadata:b,tags:m.tags,store:s.store??a.store}),{runName:p,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[$S]:v,[JS]:e=>_I(e=>{g.push(...e)},r,e),[XS]:(n,r=!1)=>gI(t,i,{name:p,writes:g,triggers:[_],path:e},n,r),[ZS]:l??d.__pregel_checkpointer,[uC]:{...d[uC],[f]:t.id},[rC]:OI({pendingWrites:n??[],taskId:v,currentTaskInput:h,resumeMap:a.configurable?.[nC],namespaceHash:tI(y),pendingWritesIndex:s.pendingWritesIndex}),[iC]:t.channel_values[_C],checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:ee},triggers:[_],retry_policy:m.retryPolicy,cache_key:m.cachePolicy?{key:tI((m.cachePolicy.keyFunc??JSON.stringify)([h])),ns:[KS,m.name??`__dynamic__`,p],ttl:m.cachePolicy.ttl}:void 0,id:v,path:e,writers:m.getWriters(),timeout:m.timeout}}}else return{id:v,name:p,interrupts:[],path:e}}}}function TI(e,t,n,r,i,a,o,s,c){let{step:l,checkpointer:u,manager:d}=c,f=a[t];if(f===void 0)return;let p=f.getNode();if(p===void 0)return;let m=s.configurable??{},h=m.checkpoint_ns??``,g=[xC],_=h===``?t:`${h}|${t}`,v=ow(JSON.stringify([_,l.toString(),t,xC,`node_error_handler`,e.id]),r.id),y=`${_}:${v}`,b=[xC,String(e.name),t,!1],ee={langgraph_step:l,langgraph_node:t,langgraph_triggers:g,langgraph_path:b,langgraph_checkpoint_ns:y,checkpoint_ns:y};f.metadata!==void 0&&(ee={...ee,...f.metadata});let te=[],ne={checkpointId:r.id,checkpointNs:y,taskId:v,threadId:m.thread_id,runId:s.runId==null?void 0:String(s.runId),nodeAttempt:1};return{name:t,input:e.input,proc:p,subgraphs:f.subgraphs,writes:te,config:{...Au(Ou(s,{metadata:ee,tags:f.tags,store:c.store??s.store}),{runName:t,callbacks:d?.getChild(`graph:step:${l}`),configurable:{[$S]:v,[JS]:e=>_I(e=>te.push(...e),a,e),[XS]:(e,n=!1)=>gI(r,o,{name:t,writes:te,triggers:g,path:b},e,n),[ZS]:u??m.__pregel_checkpointer,[uC]:{...m[uC],[h]:r.id},[rC]:OI({pendingWrites:i??[],taskId:v,currentTaskInput:e.input,resumeMap:s.configurable?.[nC],namespaceHash:tI(y)}),[iC]:r.channel_values[_C],[lC]:new KC(String(e.name),n),checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:ne},triggers:g,retry_policy:f.retryPolicy,cache_key:void 0,id:v,path:b,writers:f.getWriters()}}function EI(e,t,n){let r;if(typeof e.channels==`object`&&!Array.isArray(e.channels)){r={};for(let[n,i]of Object.entries(e.channels))if(e.triggers.includes(i))try{r[n]=rI(t,i,!1)}catch(e){if(e.name===$C.unminifiable_name)return;throw e}else if(i in t)try{r[n]=rI(t,i,!1)}catch(e){if(e.name===$C.unminifiable_name)continue;throw e}}else if(Array.isArray(e.channels)){let n=!1;for(let i of e.channels)try{r=rI(t,i,!1),n=!0;break}catch(e){if(e.name===$C.unminifiable_name)continue;throw e}if(!n)return}else throw Error(`Invalid channels type, expected list or dict, got ${e.channels}`);return n&&e.mapper!==void 0&&(r=e.mapper(r)),r}function DI(e,t){if(typeof e.args!=`object`||e.args===null)return e;let n={};for(let[r,i]of Object.entries(e.args)){let e=t[r];(!e||e.lc_graph_name!==`UntrackedValue`)&&(n[r]=i)}return new OC(e.node,n)}function OI({pendingWrites:e,taskId:t,currentTaskInput:n,resumeMap:r,namespaceHash:i,pendingWritesIndex:a}){let o=a?a.nullResume:e.find(([e,t])=>e===`00000000-0000-0000-0000-000000000000`&&t===`__resume__`)?.[2],s={callCounter:0,interruptCounter:-1,resume:(()=>{let n=a?(a.resumeByTaskId.get(t)??[]).flat():e.filter(([e,n])=>e===t&&n===`__resume__`).flatMap(([e,t,n])=>n);if(r!=null&&i in r){let e=r[i];n.push(e)}return n})(),nullResume:o,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(s.nullResume)return delete s.nullResume,e.splice(e.findIndex(([e,t])=>e===`00000000-0000-0000-0000-000000000000`&&t===`__resume__`),1),o}};return s}var kI={blue:{start:`\x1B[34m`,end:`\x1B[0m`},green:{start:`\x1B[32m`,end:`\x1B[0m`},yellow:{start:`\x1B[33;1m`,end:`\x1B[0m`}},AI=(e,t)=>`${e.start}${t}${e.end}`;function jI(e){if(e==null)return;let t={};if(e.metadata!=null)for(let[n,r]of Object.entries(e.metadata))nP.has(n)||(t[n]=r);let n=MP(e.tags);return n!=null&&(t.tags=n),Object.keys(t).length>0?t:void 0}function*MI(e){for(let{id:t,name:n,input:r,config:i,triggers:a,writes:o}of e){if(i?.tags?.includes(`langsmith:hidden`))continue;let e={id:t,name:n,input:r,triggers:a,interrupts:o.filter(([e,n])=>e===t&&n===`__interrupt__`).map(([,e])=>e)},s=jI(i);s!=null&&(e.metadata=s),yield e}}function NI(e){return typeof e!=`object`||!e?!1:`$writes`in e&&Array.isArray(e.$writes)}function PI(e){let t={};for(let[n,r]of e){let e=String(n);if(e in t){let n=NI(t[e])?t[e].$writes:[t[e]];n.push(r),t[e]={$writes:n}}else t[e]=r}return t}function*FI(e,t){for(let[{id:n,name:r,config:i},a]of e)i?.tags?.includes(`langsmith:hidden`)||(yield{id:n,name:r,result:PI(a.filter(([e])=>Array.isArray(t)?t.includes(e):e===t)),interrupts:a.filter(e=>e[0]===pC).map(e=>e[1])})}function*II(e,t,n,r,i,a,o,s){function c(e){let t={};return e.callbacks!=null&&(t.callbacks=e.callbacks),e.configurable!=null&&(t.configurable=e.configurable),e.maxConcurrency!=null&&(t.max_concurrency=e.maxConcurrency),e.metadata!=null&&(t.metadata=e.metadata),e.recursionLimit!=null&&(t.recursion_limit=e.recursionLimit),e.runId!=null&&(t.run_id=e.runId),e.runName!=null&&(t.run_name=e.runName),e.tags!=null&&(t.tags=e.tags),t}let l=e.configurable?.checkpoint_ns,u={};for(let t of i){if(!(t.subgraphs?.length?t.subgraphs:[t.proc]).find(cF))continue;let n=`${t.name}:${t.id}`;l&&(n=`${l}|${n}`),u[t.id]={configurable:{thread_id:e.configurable?.thread_id,checkpoint_ns:n}}}yield{config:c(e),values:iI(t,n),metadata:r,next:i.map(e=>e.name),tasks:LI(i,a,u,s),parentConfig:o?c(o):void 0}}function LI(e,t,n,r){return e.map(e=>{let i=t.find(([t,n])=>t===e.id&&n===`__error__`)?.[2],a=t.filter(([t,n])=>t===e.id&&n===`__interrupt__`).map(([,,e])=>e),o=(()=>{if(i||a.length||!t.length)return;let n=t.findIndex(([t,n])=>t===e.id&&n===`__return__`);if(n>=0)return t[n][2];if(typeof r==`string`)return t.find(([t,n])=>t===e.id&&n===r)?.[2];if(Array.isArray(r)){let n=t.filter(([t,n])=>t===e.id&&r.includes(n)).map(([,e,t])=>[e,t]);return n.length?PI(n):void 0}})();if(i)return{id:e.id,name:e.name,path:e.path,error:i,interrupts:a,result:o};let s=n?.[e.id];return{id:e.id,name:e.name,path:e.path,interrupts:a,...s===void 0?{}:{state:s},result:o}})}function RI(e,t,n){console.log([`${AI(kI.blue,`[${e}:checkpoint]`)}`,`\x1b[1m State at the end of step ${e}:\x1b[0m\n`,JSON.stringify(iI(t,n),null,2)].join(``))}function zI(e,t){let n=t.length;console.log([`${AI(kI.blue,`[${e}:tasks]`)}`,`\x1b[1m Starting step ${e} with ${n} task${n===1?``:`s`}:\x1b[0m\n`,t.map(e=>`- ${AI(kI.green,String(e.name))} -> ${JSON.stringify(e.input,null,2)}`).join(`
|
|
186
|
+
`)].join(``))}function BI(e,t,n){let r={};for(let[e,i]of t)n.includes(e)&&(r[e]||(r[e]=[]),r[e].push(i));console.log([`${AI(kI.blue,`[${e}:writes]`)}`,`\x1b[1m Finished step ${e} with writes to ${Object.keys(r).length} channel${Object.keys(r).length===1?``:`s`}:\x1b[0m\n`,Object.entries(r).map(([e,t])=>`- ${AI(kI.yellow,e)} -> ${t.map(e=>JSON.stringify(e)).join(`, `)}`).join(`
|
|
187
|
+
`)].join(``))}var VI=[`values`,`updates`,`messages`,`tools`,`custom`,`tasks`];function HI(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&(`source`in t||typeof t.step==`number`)&&!(`values`in t)&&!(`config`in t)}function UI(e){if(!Array.isArray(e)||e.length!==2)return{data:e};let[t,n]=e;if(typeof n!=`object`||!n)return{data:e};let r=n,i=typeof r.langgraph_node==`string`?r.langgraph_node:void 0,a=typeof r.run_id==`string`?r.run_id:void 0;return{data:a!=null&&typeof t==`object`&&t?{...t,run_id:a}:t,node:i}}function WI({namespace:e,mode:t,payload:n,seq:r}){let i=Date.now(),a={type:`event`};switch(t){case`messages`:{let{data:t,node:o}=UI(n);return[{...a,seq:r,method:`messages`,params:{namespace:e,timestamp:i,...o?{node:o}:{},data:t}}]}case`tools`:return[{...a,seq:r,method:`tools`,params:{namespace:e,timestamp:i,data:GI(n)}}];case`checkpoints`:return HI(n)?[{...a,seq:r,method:`checkpoints`,params:{namespace:e,timestamp:i,data:n}}]:[];case`values`:return[{...a,seq:r,method:`values`,params:{namespace:e,timestamp:i,data:n}}];case`updates`:{let t=KI(n);return[{...a,seq:r,method:`updates`,params:{namespace:e,timestamp:i,...typeof t.node==`string`?{node:t.node}:{},data:t}}]}case`custom`:{let t=typeof n==`object`&&n&&!Array.isArray(n)&&`name`in n?n:{payload:n};return[{...a,seq:r,method:`custom`,params:{namespace:e,timestamp:i,data:t}}]}case`tasks`:return[{...a,seq:r,method:`tasks`,params:{namespace:e,timestamp:i,data:n}}];default:return[]}}function GI(e){if(typeof e!=`object`||!e)return{event:`tool-error`,tool_call_id:``,message:`Unexpected tools payload shape`};let t=e,n=String(t.toolCallId??``);switch(t.event){case`on_tool_start`:return{event:`tool-started`,tool_call_id:n,tool_name:String(t.name??`unknown`),input:t.input};case`on_tool_event`:return{event:`tool-output-delta`,tool_call_id:n,delta:typeof t.data==`string`?t.data:JSON.stringify(t.data??``)};case`on_tool_end`:return{event:`tool-finished`,tool_call_id:n,output:t.output};case`on_tool_error`:{let e=t.error;return{event:`tool-error`,tool_call_id:n,message:typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`?e.message:String(e??`unknown error`)}}default:return{event:`tool-error`,tool_call_id:``,message:`Unknown tool event: ${String(t.event)}`}}}function KI(e){if(typeof e!=`object`||!e)return{values:{}};let t=Object.entries(e);if(t.length===0)return{values:{}};let[n,r]=t[0];return{node:n,values:typeof r==`object`&&r?r:{value:r}}}var qI=class extends Fu{_abortController;_innerReader;constructor(e,t){let n=e.getReader(),r=t??new AbortController;super({start(e){return t();function t(){return n.read().then(({done:n,value:r})=>{if(n){e.close();return}return e.enqueue(r),t()})}}}),this._abortController=r,this._innerReader=n}async cancel(e){this._abortController.abort(e),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},JI=class extends Fu{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(e){let t,n=new Promise(e=>{t=e});super({start:e=>{t(e)}}),n.then(e=>{this.controller=e}),this.passthroughFn=e.passthroughFn,this.modes=e.modes}push(e){this._closed||!this.controller||(this.passthroughFn?.(e),this.controller.enqueue(e))}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(e){try{this.controller?.error(e)}finally{this._closed=!0}}},YI=class extends hi{name=`StreamToolsHandler`;awaitHandlers=!0;streamFn;runs={};constructor(e){super(),this.streamFn=e}handleToolStart(e,t,n,r,i,a,o,s){if(!a||i&&i.includes(`langsmith:hidden`))return;let c=a.langgraph_checkpoint_ns?.split(`|`)??[],l={ns:c,toolCallId:s,toolName:o??`unknown`,input:t};this.runs[n]=l,this.streamFn([c,`tools`,{event:`on_tool_start`,toolCallId:l.toolCallId,name:l.toolName,input:t}])}handleToolEvent(e,t){let n=this.runs[t];n&&this.streamFn([n.ns,`tools`,{event:`on_tool_event`,toolCallId:n.toolCallId,name:n.toolName,data:e}])}handleToolEnd(e,t){let n=this.runs[t];delete this.runs[t],n&&this.streamFn([n.ns,`tools`,{event:`on_tool_end`,toolCallId:n.toolCallId,name:n.toolName,output:e}])}handleToolError(e,t){let n=this.runs[t];delete this.runs[t],n&&this.streamFn([n.ns,`tools`,{event:`on_tool_error`,toolCallId:n.toolCallId,name:n.toolName,error:e}])}};function XI(e){return JSON.stringify(e,function(e,t){let n=this[e];if(typeof n==`object`&&n&&`toDict`in n&&typeof n.toDict==`function`){let{type:e,data:t}=n.toDict();return{...t,type:e}}return t})}function ZI(e){return e instanceof Error?{error:e.name,message:e.message}:{error:`Error`,message:JSON.stringify(e)}}function QI(e){return typeof e!=`object`||!e?!1:`configurable`in e&&typeof e.configurable==`object`&&e.configurable!=null}function $I(e){return!QI(e)||!e.configurable.thread_id?null:{thread_id:e.configurable.thread_id,checkpoint_ns:e.configurable.checkpoint_ns||``,checkpoint_id:e.configurable.checkpoint_id||null,checkpoint_map:e.configurable.checkpoint_map||null}}function eL(e){if(QI(e)){let t=Object.fromEntries(Object.entries(e.configurable).filter(([e])=>!e.startsWith(`__`))),n={...e,configurable:t};return delete n.callbacks,n}return e}function tL(e){let t={...e,checkpoint:$I(e.config),parent_checkpoint:$I(e.parentConfig),config:eL(e.config),parent_config:eL(e.parentConfig),tasks:e.tasks.map(e=>{if(QI(e.state)){let t=$I(e.state);if(t!=null){let n={...e,checkpoint:t};return delete n.state,n}}return e})};return delete t.parentConfig,t}function nL(e){let t=new TextEncoder;return new ReadableStream({async start(n){let r=e=>{n.enqueue(t.encode(`event: ${e.event}\ndata: ${XI(e.data)}\n\n`))};try{for await(let t of e){let[e,n,i]=t,a=i;if(n===`debug`){let e=i;e.type===`checkpoint`&&(a={...e,payload:tL(e.payload)})}n===`checkpoints`&&(a=tL(i)),r({event:e?.length?`${n}|${e.join(`|`)}`:n,data:a})}}catch(e){r({event:`error`,data:ZI(e)})}n.close()}})}function rL(...e){return new JI({passthroughFn:t=>{let n=t[1]===`checkpoints`&&HI(t[2]);for(let r of e)(r.modes.has(t[1])||n)&&r.push(t)},modes:new Set(e.flatMap(e=>Array.from(e.modes)))})}var iL=class{checkpointId;#e=new Set;constructor(e){this.checkpointId=e}#t(e){let t=e.includes(`:`)?e.slice(0,e.lastIndexOf(`:`)):e;return this.#e.has(t)?!1:(this.#e.add(t),!0)}async getCheckpoint(e,t,n){if(this.#t(e)){let e=[];for await(let r of t.list(n,{before:{configurable:{checkpoint_id:this.checkpointId}},limit:1}))e.push(r);return e.length>0?e[0]:void 0}return await t.getTuple(n)??void 0}},aL=Symbol.for(`INPUT_DONE`),oL=Symbol.for(`INPUT_RESUMING`),sL=25;function cL(e){if(!(typeof e!=`object`||!e)){if(Mt.isInstance(e)){let t=e;t.id??(t.id=Yr(),t.lc_kwargs!=null&&(t.lc_kwargs.id=t.id));return}if(Array.isArray(e)){for(let t of e)cL(t);return}}}function lL(e){return e===void 0||e===``?[]:e.split(`|`)}function uL(e){if(!e)return[];let t=``;for(let n of Object.keys(e))n!==``&&n.length>t.length&&(t=n);return lL(t)}var dL=class extends cP{cache;queue=Promise.resolve();constructor(e){super(),this.cache=e}async get(e){return this.enqueueOperation(`get`,e)}async set(e){return this.enqueueOperation(`set`,e)}async clear(e){return this.enqueueOperation(`clear`,e)}async stop(){await this.queue}enqueueOperation(e,...t){let n=this.queue.then(()=>this.cache[e](...t));return this.queue=n.then(()=>void 0,()=>void 0),n}},fL=class e{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;_exitDeltaWrites;_deltaChannelsWithOverwrite=new Set;_hasPersistedParent=!1;_initialCheckpointConfig;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status=`pending`;control;tasks={};stream;checkpointerPromises=new Set;isNested;resumeAtHead;_checkpointerChainedPromise=Promise.resolve();_trackCheckpointerPromise(e){let t=e.then(e=>(this.checkpointerPromises.delete(t),e),e=>{throw e});this.checkpointerPromises.add(t)}async _awaitCheckpointerPromises(){await Promise.all([...this.checkpointerPromises])}store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let e=!1;if(`__start__`in this.checkpoint.channel_versions)e=!0;else for(let t in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,t)){e=!0;break}let t=this.config.configurable?.__pregel_resuming!==void 0&&this.config.configurable?.__pregel_resuming,n=this.input===null||this.input===void 0,r=FC(this.input)&&this.input.resume!=null,i=this.input===oL,a=!this.isNested&&this.config.metadata?.run_id!==void 0&&this.checkpointMetadata?.run_id!==void 0&&this.config.metadata.run_id===this.checkpointMetadata?.run_id;return e&&(t||n||r||i||a)}get isReplaying(){return!this.skipDoneTasks}constructor(e){this.input=e.input,this.checkpointer=e.checkpointer,this.checkpointer===void 0?this.checkpointerGetNextVersion=fI:this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer),this.checkpoint=e.checkpoint,this.checkpointMetadata=e.checkpointMetadata,this.checkpointPreviousVersions=e.checkpointPreviousVersions,this.channels=e.channels,this.checkpointPendingWrites=e.checkpointPendingWrites,this.step=e.step,this.stop=e.stop,this.config=e.config,this.checkpointConfig=e.checkpointConfig,this.isNested=e.isNested,this.resumeAtHead=e.resumeAtHead,this.manager=e.manager,this.outputKeys=e.outputKeys,this.streamKeys=e.streamKeys,this.nodes=e.nodes,this.skipDoneTasks=e.skipDoneTasks,this.store=e.store,this.cache=e.cache?new dL(e.cache):void 0,this.stream=e.stream,this.checkpointNamespace=e.checkpointNamespace,this.prevCheckpointConfig=e.prevCheckpointConfig,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.durability=e.durability,this.debug=e.debug,this.triggerToNodes=e.triggerToNodes,this.control=this.config.control,this._exitDeltaWrites=this.durability===`exit`&&this.checkpointer!=null?[]:void 0,this._hasPersistedParent=e.hasPersistedParent??!1,this._initialCheckpointConfig=e.checkpointConfig,this.checkpointIdSaved=e.checkpoint.id}static async initialize(t){let{config:n,stream:r}=t;r!==void 0&&n.configurable?.__pregel_stream!==void 0&&(r=rL(r,n.configurable[eC]));let i=!n.configurable||!(`checkpoint_id`in n.configurable),a=n.configurable?.[rC];n.configurable&&a&&(a.subgraphCounter>0&&(n=rF(n,{[sC]:[n.configurable[sC],a.subgraphCounter.toString()].join(`|`)})),a.subgraphCounter+=1);let o=n.configurable?.checkpoint_id,s=XS in(n.configurable??{});!s&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==``&&(n=rF(n,{checkpoint_ns:``,checkpoint_id:void 0}));let c=n;n.configurable?.checkpoint_id===void 0&&n.configurable?.checkpoint_map!==void 0&&n.configurable?.checkpoint_map?.[n.configurable?.checkpoint_ns]&&(c=rF(n,{checkpoint_id:n.configurable[uC][n.configurable?.checkpoint_ns]}));let l=lL(n.configurable?.checkpoint_ns),u;t.checkpointer?c.configurable?.checkpoint_id?u=await t.checkpointer.getTuple(c):n.configurable?.__pregel_replay_state?(u=await n.configurable[dC].getCheckpoint(n.configurable?.checkpoint_ns??``,t.checkpointer,c),n.configurable&&delete n.configurable[QS]):u=await t.checkpointer.getTuple(c):u=void 0;let d=u!==void 0;u||={config:n,checkpoint:ZN(),metadata:{source:`input`,step:-2,parents:{}},pendingWrites:[]},c={...n,...u.config,configurable:{checkpoint_ns:``,...n.configurable,...u.config.configurable}};let f=u.parentConfig,p=QN(u.checkpoint),m={...u.metadata},h=u.pendingWrites??[],g=n.configurable?.checkpoint_ns,_=n.configurable?.[uC];typeof g==`string`&&g!==``&&typeof _==`object`&&_&&g in _&&h.length>0&&(h=h.filter(([,e])=>e!==mC));let v=!1,y=c.configurable?.thread_id,b=c.configurable?.checkpoint_ns??``;t.checkpointer&&o&&typeof y==`string`&&(v=(await t.checkpointer.getTuple({configurable:{thread_id:y,checkpoint_ns:b}}))?.config.configurable?.checkpoint_id===o&&m.source!==`update`&&m.source!==`fork`);let ee=await yP(t.channelSpecs,p,{saver:t.checkpointer,config:c}),te=(m.step??0)+1,ne=te+(n.recursionLimit??sL)+1,x={...p.channel_versions},re=t.store?new sP(t.store):void 0;return re&&await re.start(),new e({input:t.input,config:n,checkpointer:t.checkpointer,checkpoint:p,checkpointMetadata:m,checkpointConfig:c,prevCheckpointConfig:f,checkpointNamespace:l,channels:ee,isNested:s,resumeAtHead:v,manager:t.manager,skipDoneTasks:i,step:te,stop:ne,checkpointPreviousVersions:x,checkpointPendingWrites:h,outputKeys:t.outputKeys??[],streamKeys:t.streamKeys??[],nodes:t.nodes,stream:r,store:re,cache:t.cache,interruptAfter:t.interruptAfter,interruptBefore:t.interruptBefore,durability:t.durability,debug:t.debug,triggerToNodes:t.triggerToNodes,hasPersistedParent:d})}_checkpointerPutAfterPrevious(e){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(e.config,e.checkpoint,e.metadata,e.newVersions)),this._trackCheckpointerPromise(this._checkpointerChainedPromise)}putWrites(e,t){let n=t;if(n.length===0)return;n.every(([e])=>e in tP)&&(n=Array.from(new Map(n.map(e=>[e[0],e])).values()));let r=!1;for(let e in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,e)&&this.channels[e].lc_graph_name===`UntrackedValue`){r=!0;break}let i=n;r&&(i=n.filter(([e])=>{let t=this.channels[e];return!t||t.lc_graph_name!==`UntrackedValue`}).map(([e,t])=>e===`__pregel_tasks`&&kC(t)?[e,DI(t,this.channels)]:[e,t])),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(t=>t[0]!==e);for(let[t,n]of i)this.checkpointPendingWrites.push([e,t,n]);for(let[e,t]of i){let n=this.channels[e];n!=null&&uP(n)&&cL(t)}let a=rF(this.checkpointConfig,{[sC]:this.config.configurable?.checkpoint_ns??``,[oC]:this.checkpoint.id});if(this.durability!==`exit`&&this.checkpointer!=null&&this._trackCheckpointerPromise(this.checkpointer.putWrites(a,i,e)),this.tasks&&this._outputWrites(e,n),!t.length||!this.cache||!this.tasks)return;let o=this.tasks[e];o==null||o.cache_key==null||t[0][0]===`__error__`||t[0][0]===`__interrupt__`||this.cache.set([{key:[o.cache_key.ns,o.cache_key.key],value:o.writes,ttl:o.cache_key.ttl}])}_outputWrites(e,t,n=!1){let r=this.tasks[e];if(r!==void 0){if(r.config!==void 0&&(r.config.tags??[]).includes(`langsmith:hidden`))return;if(t.length>0)if(t[0][0]===`__interrupt__`){if(r.path?.[0]===`__pregel_push`&&r.path?.[r.path.length-1]===!0)return;let e=t.filter(e=>e[0]===pC).flatMap(e=>e[1]);this._emit([[`updates`,{[pC]:e}],[`values`,{[pC]:e}]])}else t[0][0]!==`__error__`&&this._emit(HP(BP(cI(this.outputKeys,[[r,t]],n),`updates`)));n||this._emit(HP(BP(FI([[r,t]],this.streamKeys),`tasks`)))}}async _matchCachedWrites(){if(!this.cache)return[];let e=[],t=([e,t])=>`ns:${e.join(`,`)}|key:${t}`,n=[],r={};for(let e of Object.values(this.tasks))e.cache_key!=null&&!e.writes.length&&(n.push([e.cache_key.ns,e.cache_key.key]),r[t([e.cache_key.ns,e.cache_key.key])]=e);if(n.length===0)return[];let i=await this.cache.get(n);for(let{key:n,value:a}of i){let i=r[t(n)];i!=null&&(i.writes.push(...a),e.push({task:i,result:a}))}return e}async tick(e){this.store&&!this.store.isRunning&&await this.store?.start();let{inputKeys:t=[]}=e;if(this.status!==`pending`)throw Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![aL,oL].includes(this.input))await this._first(t);else if(this.toInterrupt.length>0)throw this.status=`interrupt_before`,new WC;else if(Object.values(this.tasks).every(e=>e.writes.length>0)){let e=Object.values(this.tasks),t=e.flatMap(e=>e.writes);this.updatedChannels=bI(this.checkpoint,this.channels,e,this.checkpointerGetNextVersion,this.triggerToNodes);for(let[e,n]of t){let t=this.channels[e];t!=null&&uP(t)&&MC(n)&&this._deltaChannelsWithOverwrite.add(e)}let n=await VP(BP(sI(this.outputKeys,t,this.channels),`values`));if(this._exitDeltaWrites!==void 0)for(let[e,t,n]of this.checkpointPendingWrites){let r=this.channels[t];r!=null&&uP(r)&&this._exitDeltaWrites.push([this.step,e,t,n])}if(this.checkpointPendingWrites=[],await this._putCheckpoint({source:`loop`}),this.durability===`sync`&&await this._awaitCheckpointerPromises(),this._emitValuesWithCheckpointMeta(n),hI(this.checkpoint,this.interruptAfter,e))throw this.status=`interrupt_after`,new WC;this.config.configurable?.__pregel_resuming!==void 0&&delete this.config.configurable?.[QS]}else return!1;if(this.step>this.stop)return this.status=`out_of_steps`,!1;this.tasks=CI(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step,checkpointer:this.checkpointer,isResuming:this.isResuming,manager:this.manager,store:this.store,stream:this.stream,triggerToNodes:this.triggerToNodes,updatedChannels:this.updatedChannels});let n=Object.values(this.tasks);if(this.checkpointer&&(this.stream.modes.has(`checkpoints`)||this.stream.modes.has(`debug`))&&this._emit(await VP(BP(II(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,n,this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),`checkpoints`))),n.length===0)return this.status=`done`,!1;if(this.control!=null&&this.control.drainRequested)return this.status=`draining`,!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(let[e,t,r]of this.checkpointPendingWrites){if(t===`__error__`||t===`__error_source_node__`||t===`__interrupt__`||t===`__resume__`)continue;let i=n.find(t=>t.id===e);i&&i.writes.push([t,r])}this._resumeErrorHandlersIfApplicable(),n=Object.values(this.tasks);for(let e of n)e.writes.length>0&&this._outputWrites(e.id,e.writes,!0)}if(n.every(e=>e.writes.length>0))return this.tick({inputKeys:t});if(hI(this.checkpoint,this.interruptBefore,n))throw this.status=`interrupt_before`,new WC;if(this.stream.modes.has(`tasks`)||this.stream.modes.has(`debug`)){let e=await VP(BP(MI(n),`tasks`));this._emit(e)}return!0}async finishAndHandleError(e){this.durability===`exit`&&(!this.isNested||e!==void 0||this.checkpointNamespace.every(e=>!e.includes(`:`)))&&(await this._putExitDeltaWrites(),this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());let t=this._suppressInterrupt(e);return(t||e===void 0)&&(this.output=iI(this.channels,this.outputKeys)),t&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(e=>e.writes.length>0)&&(this.updatedChannels=bI(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emitValuesWithCheckpointMeta(HP(BP(sI(this.outputKeys,Object.values(this.tasks).flatMap(e=>e.writes),this.channels),`values`)))),XC(e)&&!e.interrupts.length&&this._emit([[`updates`,{[pC]:[]}],[`values`,{[pC]:[]}]],this.#e())),t}async acceptPush(e,t,n){if(this.interruptAfter?.length>0&&hI(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}let r=wI([xC,e.path??[],t,e.id,n],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,e.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!r)return;if(this.interruptBefore?.length>0&&hI(this.checkpoint,this.interruptBefore,[r])){this.toInterrupt.push(r);return}(this.stream.modes.has(`tasks`)||this.stream.modes.has(`debug`))&&this._emit(HP(BP(MI([r]),`tasks`))),this.debug&&zI(this.step,[r]),this.tasks[r.id]=r,this.skipDoneTasks&&this._matchWrites({[r.id]:r});let i=await this._matchCachedWrites();for(let{task:e}of i)this._outputWrites(e.id,e.writes,!0);return r}getErrorHandlerNode(e){return this.nodes[e]?.errorHandlerNode}isErrorHandlerNode(e){return this.nodes[e]?.isErrorHandler===!0}scheduleErrorHandler(e,t){let n=this.getErrorHandlerNode(String(e.name));if(!n)return;let r=TI(e,n,t,this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,e.config??this.config,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(r!==void 0)return this.tasks[r.id]=r,this._emit(HP(BP(MI([r]),`tasks`))),this.debug&&zI(this.step,[r]),r}_resumeErrorHandlersIfApplicable(){let e=new Map;for(let[t,n]of this.checkpointPendingWrites){if(n!==`__error_source_node__`)continue;let r=this.checkpointPendingWrites.find(([e,n])=>e===t&&n===`__error__`);if(r===void 0)continue;let i=r[2],a=Error(i?.message??String(i));i?.name&&(a.name=i.name),e.set(t,a)}for(let[t,n]of e){let e=this.tasks[t];e!==void 0&&this.getErrorHandlerNode(String(e.name))&&(e.writes.length===0&&e.writes.push([WS,{message:n.message,name:n.name}]),this.scheduleErrorHandler(e,n))}}_suppressInterrupt(e){return XC(e)&&!this.isNested}async _first(e){let{configurable:t}=this.config,n=t?.[rC];if(n&&n.nullResume!==void 0&&this.putWrites(CC,[[mC,n.nullResume]]),FC(this.input)){let e=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume==`object`&&Object.keys(this.input.resume).every(nI)&&(this.config.configurable??={},this.config.configurable[nC]=this.input.resume),e&&this.checkpointer==null)throw Error(`Cannot use Command(resume=...) without checkpointer`);let t={};for(let[e,n,r]of aI(this.input,this.checkpointPendingWrites))t[e]??=[],t[e].push([n,r]);if(Object.keys(t).length===0)throw new QC(`Received empty Command input`);for(let[e,n]of Object.entries(t))this.putWrites(e,n)}let r=(this.checkpointPendingWrites??[]).filter(e=>e[0]===CC).map(e=>e.slice(1));r.length>0&&bI(this.checkpoint,this.channels,[{name:US,writes:r,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);let i=FC(this.input),a=i&&r.length>0,o=this.isReplaying&&(this.isNested&&t?.checkpoint_ns!==void 0&&t?.checkpoint_ns!==``&&t?.checkpoint_map!==void 0&&t.checkpoint_ns in t.checkpoint_map||!(i&&this.input.resume!=null||t?.__pregel_resuming===!0||this.resumeAtHead));o&&(this.checkpointPendingWrites=this.checkpointPendingWrites.filter(e=>e[1]!==mC));let s=this.isResuming;if(s||a){let e={...this.checkpoint.versions_seen[pC]};for(let t in this.channels)Object.prototype.hasOwnProperty.call(this.channels,t)&&this.checkpoint.channel_versions[t]!==void 0&&(e[t]=this.checkpoint.channel_versions[t]);this.checkpoint.versions_seen[pC]=e,o&&this.checkpointMetadata.source!==`update`&&this.checkpointMetadata.source!==`fork`&&(this.checkpointPendingWrites=this.checkpointPendingWrites.filter(e=>e[1]!==pC),await this._putCheckpoint({source:`fork`}));let t=await VP(BP(sI(this.outputKeys,!0,this.channels),`values`));s?this.input=oL:a&&(await this._putCheckpoint({source:`input`}),this.input=aL),this._emitValuesWithCheckpointMeta(t)}else{let t=await VP(oI(e,this.input));if(t.length>0){let e=CI(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=bI(this.checkpoint,this.channels,Object.values(e).concat([{name:US,writes:t,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes);let n=t.filter(([e])=>{let t=this.channels[e];return t!=null&&uP(t)});for(let[e,t]of n)MC(t)&&this._deltaChannelsWithOverwrite.add(e);if(n.length>0)if(this._exitDeltaWrites!==void 0)for(let[e,t]of n)this._exitDeltaWrites.push([this.step,CC,e,t]);else this.checkpointer!=null&&this.putWrites(CC,n);await this._putCheckpoint({source:`input`}),this.input=aL}else if(`__pregel_resuming`in(this.config.configurable??{}))this.input=aL;else throw new QC(`Received no input writes for ${JSON.stringify(e,null,2)}`)}if(!this.isNested){let e;if(o){let t=this.checkpoint.id;(this.checkpointMetadata.source===`update`||this.checkpointMetadata.source===`fork`)&&this.prevCheckpointConfig&&(t=this.prevCheckpointConfig.configurable?.checkpoint_id??t),e=new iL(t)}this.config=rF(this.config,{[QS]:this.isResuming,[dC]:e})}}#e(){let e=this.checkpointNamespace;if(!(e.length===0||e.length===1&&e[0]===``)||this.config.configurable?.__pregel_stream===void 0)return e;let t=uL(this.config.configurable?.[uC]);return t.length>0?t:e}_emit(e,t=this.checkpointNamespace){for(let[n,r]of e)if(this.stream.modes.has(n)&&this.stream.push([t,n,r]),(n===`checkpoints`||n===`tasks`)&&this.stream.modes.has(`debug`)){let e=n===`checkpoints`?this.step-1:this.step,i=new Date().toISOString(),a=n===`checkpoints`?`checkpoint`:typeof r==`object`&&r&&`result`in r?`task_result`:`task`;this.stream.push([t,`debug`,{step:e,type:a,timestamp:i,payload:r}])}}_currentCheckpointMeta(){if(!this.checkpointMetadata||!this.checkpoint?.id)return;let e=this.prevCheckpointConfig?.configurable?.checkpoint_id;return{checkpoint:{id:this.checkpoint.id,...e?{parent_id:e}:{},step:this.checkpointMetadata.step,source:this.checkpointMetadata.source}}}_emitValuesWithCheckpointMeta(e){let t=this._currentCheckpointMeta();for(let[n,r]of e)n===`values`&&t?.checkpoint!=null&&!this.stream.modes.has(`checkpoints`)&&this.stream.push([this.checkpointNamespace,`checkpoints`,t.checkpoint]),this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,r])}_putCheckpoint(e){let t=this.checkpointMetadata===e,n=this.checkpointer!=null&&(this.durability!==`exit`||t),r=e=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=rF(this.checkpointConfig,{[sC]:this.config.configurable?.checkpoint_ns??``});let t={...this.checkpoint.channel_versions},n=tF(this.checkpointPreviousVersions,t);this.checkpointPreviousVersions=t,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:QN(e),metadata:{...this.checkpointMetadata},newVersions:n}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}},i;if(t)i={...this.checkpointMetadata.counters_since_delta_snapshot??{}};else{let t=this.checkpointMetadata.counters_since_delta_snapshot??{};i={};let n=this.updatedChannels??new Set;for(let e in this.channels){if(!Object.prototype.hasOwnProperty.call(this.channels,e)||!uP(this.channels[e]))continue;let[r,a]=t[e]??[0,0];i[e]=[n.has(e)?r+1:r,a+1]}this.checkpointMetadata={...e,step:this.step,parents:this.config.configurable?.checkpoint_map??{}}}let a=n?_P(this.channels,i):new Set;if(n)for(let e of this._deltaChannelsWithOverwrite)a.add(e);this.checkpoint=vP(this.checkpoint,n?this.channels:void 0,this.step,{id:t?this.checkpoint.id:void 0,channelsToSnapshot:a,updatedChannels:this.updatedChannels,getNextVersion:n?e=>this.checkpointerGetNextVersion(e):void 0});for(let e of a)i[e]=[0,0],this._deltaChannelsWithOverwrite.delete(e);let o={};for(let e in i){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let[t,n]=i[e];(t!==0||n!==0)&&(o[e]=[t,n])}Object.keys(o).length>0?this.checkpointMetadata.counters_since_delta_snapshot=o:delete this.checkpointMetadata.counters_since_delta_snapshot,n&&r(this.checkpoint),t||(this.step+=1)}async _putExitDeltaWrites(){if(this._exitDeltaWrites===void 0||this._exitDeltaWrites.length===0||this.checkpointer==null||this._initialCheckpointConfig===void 0)return;let e=this.checkpointMetadata.counters_since_delta_snapshot??{},t=_P(this.channels,e);for(let e of this._deltaChannelsWithOverwrite)t.add(e);let n=this._exitDeltaWrites.filter(([,,e])=>!t.has(e));if(n.length===0)return;let r;if(this._hasPersistedParent)r=this._initialCheckpointConfig;else{let e=ZN();e.id=this.checkpointIdSaved??e.id,e.ts=new Date().toISOString();let t=rF(this._initialCheckpointConfig,{[oC]:void 0});r=rF(this._initialCheckpointConfig,{[oC]:e.id}),this._trackCheckpointerPromise(this.checkpointer.put(t,e,{source:`loop`,step:-2,parents:{}},{})),this.checkpointConfig=r}let i=rF(r,{[sC]:this.config.configurable?.checkpoint_ns??``,[oC]:r.configurable?.[oC]}),a=new Map,o=[];for(let[e,t,r,i]of n){let n=`${e}\u0000${t}`,s=a.get(n);s===void 0&&(s=[],a.set(n,s),o.push({key:n,step:e,tid:t})),s.push([r,i])}for(let{key:e,step:t,tid:n}of o){let r=gP(t,n);this._trackCheckpointerPromise(this.checkpointer.putWrites(i,a.get(e),r))}}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;let e=rF(this.checkpointConfig,{[sC]:this.config.configurable?.checkpoint_ns??``,[oC]:this.checkpoint.id}),t={};for(let[e,n,r]of this.checkpointPendingWrites)t[e]??=[],t[e].push([n,r]);for(let[n,r]of Object.entries(t))this._trackCheckpointerPromise(this.checkpointer.putWrites(e,r,n))}_matchWrites(e){for(let[t,n,r]of this.checkpointPendingWrites){if(n===`__error__`||n===`__interrupt__`||n===`__resume__`)continue;let i=Object.values(e).find(e=>e.id===t);i&&i.writes.push([n,r])}for(let t of Object.values(e))t.writes.length>0&&this._outputWrites(t.id,t.writes,!0)}};function pL(e){return Kt(e?.message)}function mL(e,t,n){if(!e)return;let r=e.langgraph_checkpoint_ns,i=e.checkpoint_ns,a=r??i;if(a)return[a.split(`|`),{tags:t,name:n,...e}]}var hL=class extends hi{name=`StreamMessagesHandler`;streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(e){super(),this.streamFn=e}_emit(e,t,n,r=!1){if(r&&t.id!==void 0&&this.seen[t.id]!==void 0)return;let i=t.id;n!=null&&($t(t)?i??=`run-${n}-tool-${t.tool_call_id}`:((i==null||i===`run-${n}`)&&(i=this.stableMessageIdMap[n]??i??`run-${n}`),this.stableMessageIdMap[n]??=i)),i!==t.id&&(t.id=i,t.lc_kwargs.id=i),t.id!=null&&(this.seen[t.id]=t),this.streamFn([e[0],`messages`,[t,e[1]]])}handleChatModelStart(e,t,n,r,i,a,o,s){o&&(!a||!a.includes(`langsmith:nostream`)&&!a.includes(`nostream`))&&(this.metadatas[n]=mL(o,a,s))}handleLLMNewToken(e,t,n,r,i,a){let o=a?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(pL(o)?this._emit(this.metadatas[n],o.message,n):this._emit(this.metadatas[n],new Nn({content:e}),n))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){let n=e.generations?.[0]?.[0];Kt(n?.message)&&this._emit(this.metadatas[t],n?.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,n,r,i,a,o,s){if(a!==void 0&&s===a.langgraph_node&&(i===void 0||!i.includes(`langsmith:hidden`))&&(this.metadatas[n]=mL(a,i,s),typeof t==`object`)){for(let e of Object.values(t))if((Kt(e)||qt(e))&&e.id!==void 0)this.seen[e.id]=e;else if(Array.isArray(e))for(let t of e)(Kt(t)||qt(t))&&t.id!==void 0&&(this.seen[t.id]=t)}}handleChainEnd(e,t){let n=this.metadatas[t];if(delete this.metadatas[t],n!==void 0){if(Kt(e))this._emit(n,e,t,!0);else if(Array.isArray(e))for(let r of e)Kt(r)&&this._emit(n,r,t,!0);else if(typeof e==`object`&&e){for(let r of Object.values(e))if(Kt(r))this._emit(n,r,t,!0);else if(Array.isArray(r))for(let e of r)Kt(e)&&this._emit(n,e,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}};function gL(e){if(`response_metadata`in e&&typeof e.response_metadata==`object`&&e.response_metadata!=null)return e.response_metadata}function _L(e){if(`usage_metadata`in e&&typeof e.usage_metadata==`object`&&e.usage_metadata!=null)return e.usage_metadata}function vL(e){switch(e.type){case`text`:return{type:`text`,text:``};case`reasoning`:return{type:`reasoning`,reasoning:``};case`tool_call`:case`tool_call_chunk`:return{type:`tool_call_chunk`,...e.id==null?{}:{id:e.id},...e.name==null?{}:{name:e.name},args:``};default:return e}}function yL(e){switch(e.type){case`text`:{let t=typeof e.text==`string`?e.text:``;return t.length>0?{event:`content-block-delta`,index:typeof e.index==`number`?e.index:0,delta:{type:`text-delta`,text:t}}:void 0}case`reasoning`:{let t=typeof e.reasoning==`string`?e.reasoning:``;return t.length>0?{event:`content-block-delta`,index:typeof e.index==`number`?e.index:0,delta:{type:`reasoning-delta`,reasoning:t}}:void 0}case`tool_call_chunk`:return{event:`content-block-delta`,index:typeof e.index==`number`?e.index:0,delta:{type:`block-delta`,fields:{...e,type:`tool_call_chunk`}}};default:return}}var bL=class extends hi{name=`StreamProtocolMessagesHandler`;streamFn;metadatas={};seen={};streamedRunIds=new Set;stableMessageIdMap={};lc_prefer_chat_model_stream_events=!0;awaitHandlers=!0;constructor(e){super(),this.streamFn=e}normalizeMessageId(e,t){let n=e.id;return t!=null&&(Xt.isInstance(e)?n??=`run-${t}-tool-${e.tool_call_id}`:((n==null||n===`run-${t}`)&&(n=this.stableMessageIdMap[t]??n??`run-${t}`),this.stableMessageIdMap[t]??=n)),n!==e.id&&(e.id=n,e.lc_kwargs.id=n),e.id!=null&&(this.seen[e.id]=e),e.id}emit(e,t,n){let r=n==null?e[1]:{...e[1],run_id:n};this.streamFn([e[0],`messages`,[t,r]])}emitFinalMessage(e,t,n,r=!1){let i=t.id??(n==null?void 0:this.stableMessageIdMap[n]);if(r&&i!=null&&this.seen[i]!==void 0)return;let a=this.normalizeMessageId(t,n),o=t.type===`human`?`human`:t.type===`system`?`system`:t.type===`tool`?`tool`:`ai`,s=o===`tool`&&Xt.isInstance(t)?t.tool_call_id:void 0;this.emit(e,{event:`message-start`,...a==null?{}:{id:a},...o===`ai`?{}:{role:o},...typeof s==`string`?{tool_call_id:s}:{}},n),(Array.isArray(t.content)?t.content:typeof t.content==`string`&&t.content.length>0?[{type:`text`,text:t.content}]:[]).forEach((t,r)=>{let i=typeof t.index==`number`?t.index:r;this.emit(e,{event:`content-block-start`,index:i,content:vL(t)},n);let a=yL({...t,index:i});a!=null&&this.emit(e,a,n),this.emit(e,{event:`content-block-finish`,index:i,content:t},n)}),this.emit(e,{event:`message-finish`,..._L(t)==null?{}:{usage:_L(t)},...gL(t)==null?{}:{responseMetadata:gL(t)}},n)}handleChatModelStart(e,t,n,r,i,a,o,s){o&&(!a||!a.includes(`langsmith:nostream`)&&!a.includes(`nostream`))&&(this.metadatas[n]=[o.langgraph_checkpoint_ns.split(`|`),{tags:a,name:s,...o}])}handleLLMNewToken(){}handleChatModelStreamEvent(e,t){let n=this.metadatas[t];if(n===void 0)return;let r=e;if(e.event===`message-start`){this.streamedRunIds.add(t);let n=e.id??`run-${t}`;this.seen[n]=!0,this.stableMessageIdMap[t]??=n,e.id??(r={...e,id:n})}this.emit(n,r,t)}handleLLMEnd(e,t){let n=this.metadatas[t];if(n===void 0)return;let r=e.generations?.[0]?.[0],i=Mt.isInstance(r?.message)?r.message:void 0;if(i!=null)if(this.streamedRunIds.has(t)){let e=this.normalizeMessageId(i,t);e!=null&&(this.seen[e]=i)}else this.emitFinalMessage(n,i,t,!0);this.streamedRunIds.delete(t),delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleLLMError(e,t){this.streamedRunIds.delete(t),delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleChainStart(e,t,n,r,i,a,o,s){if(a!==void 0&&s===a.langgraph_node&&(i===void 0||!i.includes(`langsmith:hidden`))&&(this.metadatas[n]=[a.langgraph_checkpoint_ns.split(`|`),{tags:i,name:s,...a}],typeof t==`object`)){for(let e of Object.values(t))if((Mt.isInstance(e)||Wt.isInstance(e))&&e.id!==void 0)this.seen[e.id]=e;else if(Array.isArray(e))for(let t of e)(Mt.isInstance(t)||Wt.isInstance(t))&&t.id!==void 0&&(this.seen[t.id]=t)}}handleChainEnd(e,t){let n=this.metadatas[t];if(delete this.metadatas[t],n===void 0)return;let r=e=>{Mt.isInstance(e)&&!Xt.isInstance(e)&&this.emitFinalMessage(n,e,t,!0)};if(Mt.isInstance(e))r(e);else if(Array.isArray(e))for(let t of e)r(t);else if(typeof e==`object`&&e)for(let t of Object.values(e))if(Array.isArray(t))for(let e of t)r(e);else r(t);delete this.stableMessageIdMap[t]}handleChainError(e,t){delete this.metadatas[t],delete this.stableMessageIdMap[t]}},xL=class{active=!0;lastProgress=Date.now();refreshOn;constructor(e){this.refreshOn=e}touch(){this.lastProgress=Date.now()}autoTouch(){this.refreshOn===`auto`&&(this.lastProgress=Date.now())}close(){this.active=!1}},SL=class extends hi{name=`IdleProgressCallbackHandler`;awaitHandlers=!1;#e;constructor(e){super(),this.#e=e}#t=()=>{this.#e.autoTouch()};handleLLMStart=this.#t;handleChatModelStart=this.#t;handleLLMNewToken=this.#t;handleLLMEnd=this.#t;handleLLMError=this.#t;handleChainStart=this.#t;handleChainEnd=this.#t;handleChainError=this.#t;handleToolStart=this.#t;handleToolEnd=this.#t;handleToolError=this.#t;handleText=this.#t;handleRetrieverStart=this.#t;handleRetrieverEnd=this.#t;handleRetrieverError=this.#t;handleCustomEvent=this.#t};function CL(e,t,n,r){let i=e.configurable??{},a={},o=i[JS];typeof o==`function`&&(a[JS]=e=>{if(t.active)return e&&e.length&&t.autoTouch(),o(e)});let s=i[YS];typeof s==`function`&&(a[YS]=(...e)=>{if(!t.active)throw Error(`Node "${r}" attempt was cancelled after its timeout fired`);return t.autoTouch(),s(...e)});let c={...Object.keys(a).length>0?rF(e,a):e};if(c.heartbeat=()=>{n.idleTimeout!==void 0&&t.touch()},typeof c.writer==`function`){let e=c.writer;c.writer=(n=>{if(t.active)return t.autoTouch(),e(n)})}if((n.refreshOn??`auto`)===`auto`&&n.idleTimeout!==void 0){let e=new SL(t),n=c.callbacks;if(n===void 0)c.callbacks=[e];else if(Array.isArray(n))c.callbacks=[...n,e];else{let t=n.copy();t.addHandler(e,!0),c.callbacks=t}}return c}async function wL(e,t,n,r){let i=new xL(n.refreshOn??`auto`),a=new AbortController,{signal:o,dispose:s}=aF(t.signal,a.signal),c=CL({...t,signal:o},i,n,String(e.name)),l=Date.now(),u=r(c).then(e=>({type:`ok`,value:e}),e=>({type:`err`,error:e})),d,f,p=()=>{d!==void 0&&clearTimeout(d),f!==void 0&&clearTimeout(f)},m=new Promise(e=>{if(n.runTimeout!==void 0&&(d=setTimeout(()=>e({type:`timeout`,kind:`run`}),n.runTimeout)),n.idleTimeout!==void 0){let t=n.idleTimeout,r=()=>{let n=i.lastProgress+t-Date.now();n<=0?e({type:`timeout`,kind:`idle`}):f=setTimeout(r,n)};f=setTimeout(r,t)}}),h;try{h=await Promise.race([u,m])}finally{p()}if(h.type!==`timeout`){let e=Date.now();n.runTimeout!==void 0&&e-l>=n.runTimeout?h={type:`timeout`,kind:`run`}:n.idleTimeout!==void 0&&e-i.lastProgress>=n.idleTimeout&&(h={type:`timeout`,kind:`idle`})}if(h.type===`ok`)return s?.(),h.value;if(h.type===`err`)throw s?.(),h.error;let g=Date.now()-l;throw i.close(),e.writes.splice(0,e.writes.length),a.abort(),s?.(),new ZC({node:String(e.name),elapsed:g,kind:h.kind,runTimeout:n.runTimeout,idleTimeout:n.idleTimeout})}var TL=[400,401,402,403,404,405,406,407,409],EL=e=>{if(e.message.startsWith(`Cancel`)||e.message.startsWith(`AbortError`)||e.name===`AbortError`||e.name===`GraphValueError`||e?.code===`ECONNABORTED`)return!1;let t=e?.response?.status??e?.status;return!(t&&TL.includes(+t)||e?.error?.code===`insufficient_quota`)};async function DL(e,t,n,r){let i=e.retry_policy??t,a=0,o,s,c=e.config??{};n&&(c=rF(c,n)),c={...c,signal:r};let l=Date.now();for(c.executionInfo!=null&&(c.executionInfo={...c.executionInfo,nodeFirstAttemptTime:l});!r?.aborted;){e.writes.splice(0,e.writes.length),o=void 0;try{s=e.timeout===void 0?await e.proc.invoke(e.input,c):await wL(e,c,e.timeout,t=>e.proc.invoke(e.input,t));break}catch(t){if(o=t,o.pregelTaskId=e.id,JC(o)){let t=c?.configurable?.checkpoint_ns,n=o.command;if(n.graph===t){for(let t of e.writers)await t.invoke(n,c);o=void 0;break}else if(n.graph===PC.PARENT){let e=RP(t);o.command=new PC({...o.command,graph:e})}}if(YC(o)||i===void 0||(a+=1,a>=(i.maxAttempts??3))||!(i.retryOn??EL)(o))break;let n=i.initialInterval??500,r=Math.min(i.maxInterval??128e3,n*(i.backoffFactor??2)**(a-1)),s=i.jitter??!0?r+Math.random()*1e3:r;await new Promise(e=>setTimeout(e,s));let u=o.name??o.constructor.unminifiable_name??o.constructor.name;(i?.logWarning??!0)&&console.log(`Retrying task "${String(e.name)}" after ${s.toFixed(2)}ms (attempt ${a}) after ${u}: ${o}`),c=rF(c,{[QS]:!0}),c.executionInfo!=null&&(c.executionInfo={...c.executionInfo,nodeAttempt:a+1,nodeFirstAttemptTime:l})}}return{task:e,result:s,error:o,signalAborted:r?.aborted}}var OL=Symbol.for(`promiseAdded`);function kL(){let e={next:()=>void 0,wait:Promise.resolve(OL)};function t(n){e.next=()=>{e.wait=new Promise(t),n(OL)}}return e.wait=new Promise(t),e}var AL=class{nodeFinished;loop;handledExceptions=new WeakSet;constructor({loop:e,nodeFinished:t}){this.loop=e,this.nodeFinished=t}async tick(e={}){let{timeout:t,retryPolicy:n,onStepWrite:r,maxConcurrency:i}=e,a=new Set,o,s=new AbortController,c=s.signal,l=t?AbortSignal.timeout(t):void 0,u=Object.values(this.loop.tasks),d=u.filter(e=>e.writes.length===0),{signals:f,disposeCombinedSignal:p}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:l,signal:e.signal}),m=this._executeTasksWithRetry(d,{signals:f,retryPolicy:n,maxConcurrency:i});for await(let{task:e,error:t,signalAborted:n}of m)this._commit(e,t),!(t!==void 0&&this.handledExceptions.has(t))&&(XC(t)||YC(t)&&!XC(o)?o=t:t&&(a.size===0||!n)&&(s.abort(),a.add(t)));if(p?.(),r?.(this.loop.step,u.map(e=>e.writes).flat()),a.size===1)throw Array.from(a)[0];if(a.size>1)throw AggregateError(Array.from(a),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(XC(o)||UC(o)||YC(o)&&this.loop.isNested)throw o}_initializeAbortSignals({exceptionSignal:e,stepTimeoutSignal:t,signal:n}){let r=this.loop.config.configurable?.__pregel_abort_signals??{},i=r.externalAbortSignal??n,a=t??r.timeoutAbortSignal,{signal:o,dispose:s}=aF(i,a,e),c={externalAbortSignal:i,timeoutAbortSignal:a,composedAbortSignal:o};return this.loop.config=rF(this.loop.config,{[fC]:c}),{signals:c,disposeCombinedSignal:s}}async*_executeTasksWithRetry(e,t){let{retryPolicy:n,maxConcurrency:r,signals:i}=t??{},a=kL(),o={},s={executingTasksMap:o,barrier:a,retryPolicy:n,scheduleTask:async(e,t,n)=>this.loop.acceptPush(e,t,n)};if(i?.composedAbortSignal?.aborted)throw Error(`Abort`);let c=0,l,u=aF(i?.externalAbortSignal,i?.timeoutAbortSignal),d=u.signal?new Promise((e,t)=>{l=()=>t(Error(`Abort`)),u.signal?.addEventListener(`abort`,l,{once:!0})}):void 0;for(;(c===0||Object.keys(o).length>0)&&e.length;){for(;Object.values(o).length<(r??e.length)&&c<e.length;c+=1){let t=e[c];o[t.id]=DL(t,n,{[YS]:jL?.bind(s,this,t)},i?.composedAbortSignal).catch(e=>({task:t,error:e,signalAborted:i?.composedAbortSignal?.aborted}))}let t=await Promise.race([...Object.values(o),...d?[d]:[],a.wait]);if(t===OL)continue;let f=t,{task:p,error:m}=f;if(m!==void 0&&!YC(m)&&!this.loop.isErrorHandlerNode(String(p.name))&&this.loop.getErrorHandlerNode(String(p.name))!==void 0){let e=this.loop.scheduleErrorHandler(p,m);e!==void 0&&(o[e.id]=DL(e,n,{[YS]:jL?.bind(s,this,e)},i?.composedAbortSignal).catch(t=>({task:e,error:t,signalAborted:i?.composedAbortSignal?.aborted})),a.next())}yield f,l!=null&&(u.signal?.removeEventListener(`abort`,l),u.dispose?.()),delete o[t.task.id]}}_shouldRouteToErrorHandler(e){let t=String(e.name);return!this.loop.isErrorHandlerNode(t)&&this.loop.getErrorHandlerNode(t)!==void 0}_commit(e,t){if(t!==void 0)if(XC(t)){if(t.interrupts.length){let n=t.interrupts.map(e=>[pC,e]),r=e.writes.filter(e=>e[0]===mC);r.length&&n.push(...r),this.loop.putWrites(e.id,n)}}else UC(t)?e.writes.length&&this.loop.putWrites(e.id,e.writes):YC(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):(e.writes.push([WS,{message:t.message,name:t.name}]),this._shouldRouteToErrorHandler(e)&&(e.writes.push([GS,String(e.name)]),this.handledExceptions.add(t)),this.loop.putWrites(e.id,e.writes));else this.nodeFinished&&(e.config?.tags==null||!e.config.tags.includes(`langsmith:hidden`))&&this.nodeFinished(String(e.name)),e.writes.length===0&&e.writes.push([hC,null]),this.loop.putWrites(e.id,e.writes)}};async function jL(e,t,n,r,i,a={}){let o=t.config?.configurable?.[rC];if(!o)throw Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);let s=o.callCounter;o.callCounter+=1;let c=new lI({func:n,name:r,input:i,cache:a.cache,retry:a.retry,timeout:a.timeout,callbacks:a.callbacks}),l=await this.scheduleTask(t,s,c);if(!l)return;let u=this.executingTasksMap[l.id];if(u!==void 0)return u;if(l.writes.length>0){let e=l.writes.filter(([e])=>e===gC),t=l.writes.filter(([e])=>e===WS);if(e.length>0){if(e.length===1)return Promise.resolve(e[0][1]);throw Error(`BUG: multiple returns found for task ${l.name}__${l.id}`)}if(t.length>0){if(t.length===1){let e=t[0][1],n=e instanceof Error?e:Error(String(e));return Promise.reject(n)}throw Error(`BUG: multiple errors found for task ${l.name}__${l.id}`)}return}else{let t=DL(l,a.retry,{[YS]:jL.bind(this,e,l)});return this.executingTasksMap[l.id]=t,this.barrier.next(),t.then(({result:e,error:t})=>t?Promise.reject(t):e)}}var ML=Symbol.for(`langgraph.stream_channel`),NL=class e{[ML]=!0;channelName;#e=[];#t=[];#n=!1;#r;#i;constructor(e){this.channelName=e}static local(){return new e}static remote(t){return new e(t)}static isInstance(e){return typeof e==`object`&&!!e&&ML in e&&e[ML]===!0}push(e){this.#e.push(e),this.#a(),this.#i?.(e)}iterate(e=0){let t=e;return{next:async()=>{for(;;){if(t<this.#e.length)return{value:this.#e[t++],done:!1};if(this.#n){if(this.#r)throw this.#r;return{value:void 0,done:!0}}await new Promise(e=>this.#t.push(e))}}}}toAsyncIterable(e=0){return{[Symbol.asyncIterator]:()=>this.iterate(e)}}toEventStream(e={}){let t=new TextEncoder,n=this.iterate(e.startAt),r=e.event??this.channelName,i=e.serialize??(e=>JSON.stringify(e)??`null`);return new ReadableStream({async pull(e){try{let a=await n.next();if(a.done){e.close();return}let o=[];r!=null&&o.push(`event: ${r}`);for(let e of i(a.value).split(/\r\n|\r|\n/))o.push(`data: ${e}`);e.enqueue(t.encode(`${o.join(`
|
|
188
|
+
`)}\n\n`))}catch(t){e.error(t)}},async cancel(){await n.return?.()}})}get(e){if(e<0||e>=this.#e.length)throw RangeError(`StreamChannel index ${e} out of bounds (size=${this.#e.length})`);return this.#e[e]}get size(){return this.#e.length}get done(){return this.#n}close(){this.#n=!0,this.#a()}fail(e){this.#r=e,this.#n=!0,this.#a()}_wire(e){this.#i=e}_close(){this.close()}_fail(e){this.fail(e)}[Symbol.asyncIterator](){return this.iterate()}#a(){let e=this.#t.splice(0);for(let t of e)t()}};function PL(e){return NL.isInstance(e)}var FL=`custom:`;function IL(e){return`${FL}${e}`}function LL(e){return e!=null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}var RL=Symbol(`resolveValues`),zL=Symbol(`rejectValues`),BL=class{_events=NL.local();_discoveries=NL.local();#e=0;#t=!1;#n;#r=!1;#i=[];#a=[];#o=[];#s=new Map;#c=new Map;#l=[];#u=[];register(e,t){this.#s.set(HL(e),t)}addTransformer(e){let t=this._events.size;this.#a.push(e),e.onRegister&&e.onRegister({push:(e,t)=>this.push(e,t)});for(let n=0;n<t;n+=1)e.process(this._events.get(n));this.#t&&(this.#n===void 0?e.finalize?.():e.fail?.(this.#n))}wireChannels(e){for(let[t,n]of Object.entries(e)){if(PL(n)){if(this.#o.push(n),typeof n.channelName!=`string`)continue;let e=IL(n.channelName);n._wire(t=>{this._events.push({type:`event`,seq:this.#e++,method:e,params:{namespace:this.#i,timestamp:Date.now(),data:t}})});continue}LL(n)&&this.#u.push({name:t,promise:Promise.resolve(n)})}}push(e,t){t.method===`values`&&this.#c.set(HL(e),t.params.data);let n=this.#i;this.#i=e;let r=!0;for(let e of this.#a)e.process(t)||(r=!1);this.#i=n,r&&this._events.push({...t,seq:this.#e++})}close(){this.#t=!0;for(let[e,t]of this.#c.entries()){let n=e?e.split(`\0`):[];this.#s.get(HL(n))?.[RL](t)}let e=[];for(let t of this.#a){let n=t.finalize?.();n!=null&&typeof n.then==`function`&&e.push(n)}for(let e of this.#o)e._close();let t=this.#u;t.length===0&&e.length===0?(this._events.close(),this._discoveries.close()):Promise.allSettled([...e,...t.map(async({name:e,promise:t})=>{try{let n=await t;this._events.done||this._events.push({type:`event`,seq:this.#e++,method:`custom`,params:{namespace:[],timestamp:Date.now(),data:{name:e,payload:n}}})}catch{}})]).then(()=>{this._events.close(),this._discoveries.close()});for(let e of this.#s.values())e[RL](void 0)}fail(e){this.#t=!0,this.#n=e;for(let t of this.#a)t.fail?.(e);for(let t of this.#o)t._fail(e);this._events.fail(e),this._discoveries.fail(e);for(let t of this.#s.values())t[zL](e)}markInterrupted(e){this.#r=!0,this.#l.push(...e)}get interrupted(){return this.#r}get interrupts(){return this.#l}subscribeEvents(e,t=0){let n=this._events.iterate(t);return{async next(){for(;;){let t=await n.next();if(t.done||UL(t.value.params.namespace,e))return t}}}}};async function VL(e,t){let n=0;try{for await(let r of e){let[e,i,a]=r;if(i===`values`&&NC(a)){let e=a[pC];t.markInterrupted(e.map(e=>({interruptId:e.id??``,payload:e.value})))}let o=WI({namespace:e,mode:i,payload:a,seq:n});n+=o.length;for(let n of o)t.push(e,n)}}catch(e){t.fail(e);return}t.close()}function HL(e){return e.join(`\0`)}function UL(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n+=1)if(e[n]!==t[n])return!1;return!0}function WL(e,t,n=0){return{[Symbol.asyncIterator](){let r=e.iterate(n);return{async next(){for(;;){let e=await r.next();if(e.done)return{value:void 0,done:!0};if(UL(e.value.namespace,t))return{value:e.value,done:!1}}}}}}}var GL=`root`;function KL(e){if(e.length===0)return GL;let t=e[e.length-1],n=t.indexOf(`:`);return n===-1?t:t.slice(0,n)}function qL(e){if(e instanceof Error)return e.message;if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function JL(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function YL(e){if(!JL(e)||e.event!==`started`)return;let t=e.cause;if(JL(t)&&typeof t.type==`string`)return t}function XL(e){if(JL(e)&&`result`in e&&typeof e.name==`string`&&typeof e.id==`string`&&!e.name.startsWith(`__`))return{name:e.name,id:e.id}}function ZL(e={}){let t=e.rootGraphName??GL,n=e.initialStatus??`running`,r=e.emitRootOnRegister??!0,i=e.getGraphName??KL,a=e.serializeError??qL,o=e.getTerminalStatusOverride,s=NL.local(),c=new Map,l=new Map,u=new Map,d=new Map,f=new Set,p=[],m,h=0,g=!1,_=e=>{if(e.length===0)return t;let n=u.get(HL(e));return typeof n==`string`&&n.length>0?n:i(e)},v=(e,t)=>{let n=HL(e);if(u.has(n))return;let r=(JL(t)&&JL(t.metadata)?t.metadata:void 0)?.lc_agent_name;u.set(n,typeof r==`string`?r:void 0)},y=e=>{if(!JL(e))return;let t=e.id;if(typeof t!=`string`)return;let n=e.input,r;if(JL(n)&&JL(n.tool_call)){let e=n.tool_call.id;typeof e==`string`&&(r=e)}else if(Array.isArray(n)){for(let e of n)if(JL(e)&&typeof e.id==`string`){r=e.id;break}}r!=null&&d.set(t,r)},b=e=>{if(e.length===0)return;let t=u.get(HL(e));if(typeof t!=`string`||t.length===0)return;let n=e[e.length-1],r=n.indexOf(`:`);if(r===-1)return;let i=n.slice(r+1);if(i.length===0)return;let a=d.get(i);if(!(typeof a!=`string`||a.length===0))return{type:`toolCall`,tool_call_id:a}},ee=e=>l.get(HL(e))??b(e),te=(e,t,n)=>{let i=HL(e),a=c.get(i),o=a?.graphName??_(e);if(a!=null&&a.status===t&&a.graphName===o&&n?.error==null)return;a==null?(a={namespace:e,graphName:o,status:t},c.set(i,a)):a.status=t;let l={event:t,graph_name:o,...n?.cause==null?{}:{cause:n.cause},...n?.error==null?{}:{error:n.error}},u=Date.now();if(s.push({namespace:e,timestamp:u,...l}),!(e.length===0&&!r)&&m!=null){h+=1;try{m.push(e,{type:`event`,seq:0,method:`lifecycle`,params:{namespace:e,timestamp:u,data:l}})}finally{--h}}},ne=e=>{let t=HL(e),n=c.get(t);return n??(n={namespace:e,graphName:_(e),status:void 0},c.set(t,n)),n},x=()=>{if(p.length===0)return;let e=p.splice(0,p.length);for(let t of e){let e=HL(t.namespace),n=c.get(e);n==null||n.status!==`started`||te(t.namespace,`completed`)}},re=e=>{let t=HL(e.namespace),n=c.get(t);n==null||n.status!==`started`||p.some(e=>HL(e.namespace)===t)||p.push(e)},ie=(e,t)=>{for(let n=p.length-1;n>=0;--n){let r=p[n];r.source.type===`node`&&r.source.node===t&&HL(r.source.parent)===HL(e)&&p.splice(n,1)}},ae=e=>{for(let t=1;t<=e.length;t+=1){let n=e.slice(0,t),r=HL(n);if(c.has(r))continue;ne(n);let i=ee(n);te(n,`started`,i==null?void 0:{cause:i})}},oe=()=>f.size>0?`interrupted`:`completed`,se=e=>{for(let t of c.values())t.namespace.length!==0&&t.status===`started`&&te(t.namespace,e);te([],e),s.close()},ce=async()=>{if(o==null)return oe();try{return await o()??oe()}catch{return oe()}},le=(e,t)=>{let n=`${t}:`;for(let r of c.values()){if(r.namespace.length!==e.length+1||r.status!==`started`||!UL(r.namespace,e))continue;let i=r.namespace[r.namespace.length-1];if(i===t||i.startsWith(n))return r.namespace}},S=(e,t)=>{let n=[...e,`${t.name}:${t.id}`];return c.get(HL(n))?.status===`started`?n:void 0};return{__native:!0,init(){return{_lifecycleLog:s,lifecycle:WL(s,[],0)}},onRegister(e){m=e,ne([]),r&&te([],n)},process(e){let t=e.params.namespace;if(h>0)return!0;let n=e.method===`tasks`?XL(e.params.data):void 0;if(n==null?e.method===`tasks`&&(v(t,e.params.data),y(e.params.data)):ie(t,n.name),x(),e.method===`lifecycle`){let n=YL(e.params.data);return n!=null&&l.set(HL(t),n),ae(t),!1}if(ae(t),e.method===`input`&&JL(e.params.data)&&e.params.data.event===`requested`){let t=e.params.data.id;typeof t==`string`&&f.add(t)}if(n!=null){let e=S(t,n);e!=null&&re({namespace:e,source:{type:`task`}})}if(e.method===`updates`){let n=e.params.node;if(typeof n==`string`&&!n.startsWith(`__`)){let e=le(t,n);e!=null&&re({namespace:e,source:{type:`node`,parent:t,node:n}})}}return!0},finalize(){if(!g){if(g=!0,x(),o==null){se(oe());return}return ce().then(se).catch(e=>{s.fail(e)})}},fail(e){if(g)return;g=!0;let t=a(e);for(let e of c.values())e.namespace.length!==0&&e.status===`started`&&te(e.namespace,`failed`);te([],`failed`,{error:t}),s.fail(e)}}}function QL(e){let t=e;return typeof t.run_id==`string`?`run:${t.run_id}`:e.event===`message-start`&&typeof t.id==`string`?`message:${t.id}`:`__default__`}function $L(e,t){let n=NL.local(),r=new Map,i=new Set;return{init:()=>({messages:n.toAsyncIterable()}),process(a){if(a.method!==`messages`||!UL(a.params.namespace,e)||a.params.namespace.length!==e.length+1||t!==void 0&&a.params.node!==t)return!0;let o=a.params.data;switch(o.event){case`message-start`:{let e=QL(o);if(o.role===`tool`){i.add(e);break}let t=NL.local(),s=Object.assign(new HE(t.toAsyncIterable()),{namespace:a.params.namespace,node:a.params.node});r.set(e,{source:t,stream:s}),t.push(o),n.push(s);break}case`content-block-start`:case`content-block-delta`:case`content-block-finish`:if(i.has(QL(o)))break;r.get(QL(o))?.source.push(o);break;case`message-finish`:{let e=QL(o);if(i.delete(e))break;let t=r.get(e);t&&(t.source.push(o),t.source.close(),r.delete(e));break}case`error`:if(i.has(QL(o)))break;r.get(QL(o))?.source.push(o);break}return!0},finalize(){for(let[e,t]of r)t.source.push({event:`message-finish`}),t.source.close(),r.delete(e);i.clear(),n.close()},fail(e){for(let[t,n]of r)n.source.fail(e),r.delete(t);i.clear(),n.fail(e)}}}function eR(e,t,n=0){let r=t.length+1;return{[Symbol.asyncIterator](){let i=e.iterate(n);return{async next(){for(;;){let e=await i.next();if(e.done)return{value:void 0,done:!0};let{ns:n,stream:a}=e.value;if(n.length===r&&UL(n,t))return{value:a,done:!1}}}}}}}function tR(e,t){let{createStream:n}=t,r=new Set;return{__native:!0,init(){return{_discoveries:e._discoveries,subgraphs:eR(e._discoveries,[],0)}},process(t){let i=t.params.namespace;if(i.length===0)return!0;let a=i.slice(0,1),o=HL(a);if(r.has(o))return!0;r.add(o);let s=n(a,e._discoveries.size,e._events.size);return e.register(a,s),e._discoveries.push({ns:a,stream:s}),!0}}}function nR(e){let t=NL.local();return{init:()=>({_valuesLog:t}),process(n){return n.method!==`values`||n.params.namespace.length!==e.length||!UL(n.params.namespace,e)||t.push(n.params.data),!0},finalize(){t.close()},fail(e){t.fail(e)}}}function rR(e){return`__native`in e&&e.__native===!0}var iR=Symbol(`setValuesLog`),aR=Symbol(`setMessagesIterable`),oR=Symbol(`setLifecycleIterable`),sR=Symbol(`setSubgraphsIterable`),cR={[Symbol.asyncIterator](){return{next:()=>Promise.resolve({value:void 0,done:!0})}}},lR=class{path;extensions;_mux;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e,t,n=0,r=0,i,a){this.path=e,this._mux=t,this.#t=n,this.#e=r,this.extensions=i??{},this.#n=a??new AbortController,this.#a=new Promise((e,t)=>{this.#r=e,this.#i=t}),this.#a.catch(()=>{})}[Symbol.asyncIterator](){return this._mux.subscribeEvents(this.path,this.#e)}get subgraphs(){return this.#l?this.#l:eR(this._mux._discoveries,this.path,this.#t)}get values(){let e=this.#o,t=this.#a,n=this._mux,r=this.#e,i=this.path,a=e?e.toAsyncIterable():{[Symbol.asyncIterator]:()=>{let e=n.subscribeEvents(i,r);return{async next(){for(;;){let t=await e.next();if(t.done)return{value:void 0,done:!0};if(t.value.method===`values`&&t.value.params.namespace.length===i.length)return{value:t.value.params.data,done:!1}}}}}};return{[Symbol.asyncIterator]:()=>a[Symbol.asyncIterator](),then:t.then.bind(t)}}get messages(){if(this.#s)return this.#s;let e=$L(this.path),t=e.init();return this._mux.addTransformer(e),this.#s=t.messages,this.#s}get lifecycle(){return this.#c??cR}messagesFrom(e){let t=$L(this.path,e),n=t.init();return this._mux.addTransformer(t),n.messages}get output(){return this.#a}get interrupted(){return this._mux.interrupted}get interrupts(){return this._mux.interrupts}abort(e){this.#n.abort(e)}get signal(){return this.#n.signal}[RL](e){this.#r?.(e),this.#r=void 0}[zL](e){this.#i?.(e),this.#i=void 0}[iR](e){this.#o=e}[aR](e){this.#s=e}[oR](e){this.#c=e}[sR](e){this.#l=e}},uR=class extends lR{name;index;constructor(e,t,n=0,r=0,i,a){super(e,t,n,r,i,a);let o=e[e.length-1]??``,s=o.lastIndexOf(`:`);if(s>=0){this.name=o.slice(0,s);let e=o.slice(s+1);this.index=/^\d+$/.test(e)?Number(e):0}else this.name=o,this.index=0}};function dR(e,t=[],n){let{abortController:r}=n instanceof AbortController?{abortController:n}:n??{},i=new BL,a=ZL(),o=a.init(),s=o._lifecycleLog,c=tR(i,{createStream:(e,t,n)=>{let r=new uR(e,i,t,n);return r[sR](eR(i._discoveries,e,t)),r[oR](WL(s,e,s.size)),r}}),l=c.init();i.addTransformer(c),i.addTransformer(a);let u=nR([]),d=$L([]);i.addTransformer(u),i.addTransformer(d);let f={},p=[];for(let e of t){let t=e();i.addTransformer(t);let n=t.init();rR(t)?p.push(n):Object.assign(f,n),typeof n==`object`&&n&&!rR(t)&&i.wireChannels(n)}let m=new lR([],i,0,0,f,r);for(let e of p)Object.assign(m,e);let h=u.init();m[iR](h._valuesLog);let g=d.init();return m[aR](g.messages),m[oR](o.lifecycle),m[sR](l.subgraphs),i.register([],m),VL(e,i).catch(e=>{}),m}var fR=class extends Error{constructor(e){super(e),this.name=`GraphValidationError`}};function pR({nodes:e,channels:t,inputChannels:n,outputChannels:r,streamChannels:i,interruptAfterNodes:a,interruptBeforeNodes:o}){if(!t)throw new fR(`Channels not provided`);let s=new Set,c=new Set;for(let[t,n]of Object.entries(e)){if(t===`__interrupt__`)throw new fR(`"Node name ${pC} is reserved"`);if(n.constructor===$P)n.triggers.forEach(e=>s.add(e));else throw new fR(`Invalid node type ${typeof n}, expected PregelNode`)}for(let e of s)if(!(e in t))throw new fR(`Subscribed channel '${String(e)}' not in channels`);if(!Array.isArray(n)){if(!s.has(n))throw new fR(`Input channel ${String(n)} is not subscribed to by any node`)}else if(n.every(e=>!s.has(e)))throw new fR(`None of the input channels ${n} are subscribed to by any node`);Array.isArray(r)?r.forEach(e=>c.add(e)):c.add(r),i&&!Array.isArray(i)?c.add(i):Array.isArray(i)&&i.forEach(e=>c.add(e));for(let e of c)if(!(e in t))throw new fR(`Output channel '${String(e)}' not in channels`);if(a&&a!==`*`){for(let t of a)if(!(t in e))throw new fR(`Node ${String(t)} not in nodes`)}if(o&&o!==`*`){for(let t of o)if(!(t in e))throw new fR(`Node ${String(t)} not in nodes`)}}function mR(e,t){if(Array.isArray(e)){for(let n of e)if(!(n in t))throw Error(`Key ${String(n)} not found in channels`)}else if(!(e in t))throw Error(`Key ${String(e)} not found in channels`)}function hR(e){return Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1])}var gR=class e extends fP{lc_graph_name=`Topic`;unique=!1;accumulate=!1;seen;values;constructor(e){super(),this.unique=e?.unique??this.unique,this.accumulate=e?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(t){let n=new e({unique:this.unique,accumulate:this.accumulate});return t===void 0?n:hR(t)?(n.seen=new Set(t[0]),n.values=[...t[1]],n):(n.values=[...t],this.unique&&(n.seen=new Set(n.values)),n)}update(e){let t=!1;this.accumulate||(t=this.values.length>0,this.values=[]);let n=e.flat();if(n.length>0)if(this.unique)for(let e of n)this.seen.has(e)||(t=!0,this.seen.add(e),this.values.push(e));else t=!0,this.values.push(...n);return t}get(){if(this.values.length===0)throw new $C;return this.values}checkpoint(){return this.unique?[[...this.seen],[...this.values]]:[...this.values]}isAvailable(){return this.values.length!==0}};function _R(e){let t=Su.getRunnableConfig();if(!t)throw Error(`Called interrupt() outside the context of a graph.`);let n=t.configurable;if(!n)throw Error(`No configurable found in config`);if(!n.__pregel_checkpointer)throw new VC(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=n[rC];r.interruptCounter+=1;let i=r.interruptCounter;if(r.resume.length>0&&i<r.resume.length)return n[JS]?.([[mC,r.resume]]),r.resume[i];if(r.nullResume!==void 0){if(r.resume.length!==i)throw Error(`Resume length mismatch: ${r.resume.length} !== ${i}`);let e=r.consumeNullResume();return r.resume.push(e),n[JS]?.([[mC,r.resume]]),e}let a=n[sC]?.split(`|`);throw new WC([{id:a?tI(a.join(`|`)):void 0,value:e}])}function vR(e){let t=new TextEncoder;return new ReadableStream({async start(n){try{for await(let r of e){let e=r.params.namespace,i=e.length?`${r.method}|${e.join(`|`)}`:r.method;n.enqueue(t.encode(`event: ${i}\ndata: ${JSON.stringify(r.params.data??{})}\n\n`))}}catch(e){n.enqueue(t.encode(`event: error\ndata: ${JSON.stringify({message:String(e)})}\n\n`))}finally{n.close()}}})}var yR=class{static subscribeTo(e,t){let{key:n,tags:r}={key:void 0,tags:void 0,...t??{}};if(Array.isArray(e)&&n!==void 0)throw Error(`Can't specify a key when subscribing to multiple channels`);let i;return i=typeof e==`string`?n?{[n]:e}:[e]:Object.fromEntries(e.map(e=>[e,e])),new $P({channels:i,triggers:Array.isArray(e)?e:[e],tags:r})}static writeTo(e,t){let n=[];for(let t of e)n.push({channel:t,value:GP,skipNone:!1});for(let[e,r]of Object.entries(t??{}))tS.isRunnable(r)||typeof r==`function`?n.push({channel:e,value:GP,skipNone:!0,mapper:fS(r)}):n.push({channel:e,value:r,skipNone:!1});return new JP(n)}},bR=class extends tS{lc_namespace=[`langgraph`,`pregel`];invoke(e,t){throw Error(`Not implemented`)}withConfig(e){return super.withConfig(e)}stream(e,t){return super.stream(e,t)}},xR=class extends bR{static lc_name(){return`LangGraph`}lc_namespace=[`langgraph`,`pregel`];lg_is_pregel=!0;nodes;channels;inputChannels;outputChannels;autoValidate=!0;streamMode=[`values`];streamChannels;interruptAfter;interruptBefore;stepTimeout;debug=!1;checkpointer;retryPolicy;config;store;cache;userInterrupt;streamTransformers;triggerToNodes={};constructor(e){super(e);let{streamMode:t}=e;if(t!=null&&!Array.isArray(t)&&(t=[t]),this.nodes=e.nodes,this.channels=e.channels,`__pregel_tasks`in this.channels&&`lc_graph_name`in this.channels.__pregel_tasks&&this.channels.__pregel_tasks.lc_graph_name!==`Topic`)throw Error(`Channel '${bC}' is reserved and cannot be used in the graph.`);this.channels[bC]=new gR({accumulate:!1}),this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.cache=e.cache,this.name=e.name,this.triggerToNodes=e.triggerToNodes??this.triggerToNodes,this.userInterrupt=e.userInterrupt,this.streamTransformers=e.streamTransformers??[],this.autoValidate&&this.validate()}withConfig(e){let{streamTransformers:t,...n}=e,r=Ou(this.config,n),i=[...this.streamTransformers,...t??[]];return new this.constructor({...this,config:r,streamTransformers:i})}validate(){pR({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(let[e,t]of Object.entries(this.nodes))for(let n of t.triggers)this.triggerToNodes[n]??=[],this.triggerToNodes[n].push(e);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(e){return this.getGraph(e)}*getSubgraphs(e,t){for(let[n,r]of Object.entries(this.nodes)){if(e!==void 0&&!e.startsWith(n))continue;let i=r.subgraphs?.length?r.subgraphs:[r.bound];for(let r of i){let i=cF(r);if(i!==void 0){if(n===e){yield[n,i];return}if(e===void 0&&(yield[n,i]),t){let r=e;e!==void 0&&(r=e.slice(n.length+1));for(let[e,a]of i.getSubgraphs(r,t))yield[`${n}|${e}`,a]}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}async _prepareStateSnapshot({config:e,saved:t,subgraphCheckpointer:n,applyPendingWrites:r=!1}){if(t===void 0)return{values:{},next:[],config:e,tasks:[]};let i=await yP(this.channels,t.checkpoint,{saver:typeof this.checkpointer==`object`?this.checkpointer:void 0,config:t.config??e});if(t.pendingWrites?.length){let e=t.pendingWrites.filter(([e,t])=>e===CC).map(([e,t,n])=>[String(t),n]);e.length>0&&bI(t.checkpoint,i,[{name:US,writes:e,triggers:[]}],void 0,this.triggerToNodes)}let a=Object.values(CI(t.checkpoint,t.pendingWrites,this.nodes,i,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),o=await VP(this.getSubgraphsAsync()),s=t.config.configurable?.checkpoint_ns??``,c={};for(let e of a){let r=o.find(([t])=>t===e.name);if(!r)continue;let i=`${String(e.name)}:${e.id}`;if(s&&(i=`${s}|${i}`),n===void 0){let n={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:i}};c[e.id]=n}else{let a={configurable:{[ZS]:n,thread_id:t.config.configurable?.thread_id,checkpoint_ns:i}},o=r[1];c[e.id]=await o.getState(a,{subgraphs:!0})}}if(r&&t.pendingWrites?.length){let e=Object.fromEntries(a.map(e=>[e.id,e]));for(let[n,r,i]of t.pendingWrites)[`__error__`,`__interrupt__`,`__scheduled__`].includes(r)||n in e&&e[n].writes.push([String(r),i]);let n=a.filter(e=>e.writes.length>0);n.length>0&&bI(t.checkpoint,i,n,void 0,this.triggerToNodes)}let l=t?.metadata;l&&t?.config?.configurable?.thread_id&&(l={...l,thread_id:t.config.configurable.thread_id});let u=a.filter(e=>e.writes.length===0).map(e=>e.name);return{values:iI(i,this.streamChannelsAsIs),next:u,tasks:LI(a,t?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:l,config:iF(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new VC(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_read===void 0&&e.configurable?.__pregel_checkpointer===void 0){let i=LP(r);for await(let[r,a]of this.getSubgraphsAsync(i,!0))if(r===i)return await a.getState(UP(e,{[ZS]:n}),{subgraphs:t?.subgraphs})}let i=Ou(this.config,e),a=await n.getTuple(e);return await this._prepareStateSnapshot({config:i,saved:a,subgraphCheckpointer:t?.subgraphs?n:void 0,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new VC(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_checkpointer===void 0){let i=LP(r);for await(let[r,a]of this.getSubgraphsAsync(i,!0))if(r===i){yield*a.getStateHistory(UP(e,{[ZS]:n}),t);return}}let i=Ou(this.config,e,{configurable:{checkpoint_ns:r}});for await(let e of n.list(i,t))yield this._prepareStateSnapshot({config:e.config,saved:e})}async bulkUpdateState(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new VC(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});if(t.length===0)throw Error(`No supersteps provided`);if(t.some(e=>e.updates.length===0))throw Error(`No updates provided`);let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_checkpointer===void 0){let i=LP(r);for await(let[,r]of this.getSubgraphsAsync(i,!0))return await r.bulkUpdateState(UP(e,{[ZS]:n}),t);throw Error(`Subgraph "${i}" not found`)}let i=async(e,t)=>{let r=this.config?Ou(this.config,e):e,a=await n.getTuple(r),o=a===void 0?ZN():QN(a.checkpoint),s={...a?.checkpoint.channel_versions},c=a?.metadata?.step??-1,l=UP(r,{checkpoint_ns:r.configurable?.checkpoint_ns??``}),u=r.metadata??{};a?.config.configurable&&(l=UP(r,a.config.configurable),u={...a.metadata,...u});let{values:d,asNode:f}=t[0];if(d==null&&f===void 0){if(t.length>1)throw new ew(`Cannot create empty checkpoint with multiple updates`);return iF(await n.put(l,vP(o,void 0,c),{source:`update`,step:c+1,parents:a?.metadata?.parents??{}},{}),a?a.metadata:void 0)}let p=await yP(this.channels,o,{saver:n,config:a?.config??l});if(d===null&&f===`__end__`){if(t.length>1)throw new ew(`Cannot apply multiple updates when clearing state`);if(a){let e=CI(o,a.pendingWrites||[],this.nodes,p,a.config,!0,{step:(a.metadata?.step??-1)+1,checkpointer:n,store:this.store}),t=(a.pendingWrites||[]).filter(e=>e[0]===CC).map(e=>e.slice(1));t.length>0&&bI(o,p,[{name:US,writes:t,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(let[t,n,r]of a.pendingWrites||[])[`__error__`,`__interrupt__`,`__scheduled__`].includes(n)||t in e&&e[t].writes.push([n,r]);bI(o,p,Object.values(e),n.getNextVersion.bind(n),this.triggerToNodes)}return iF(await n.put(l,vP(o,p,c),{...u,source:`update`,step:c+1,parents:a?.metadata?.parents??{}},tF(s,o.channel_versions)),a?a.metadata:void 0)}if(f===`__copy__`){if(t.length>1)throw new ew(`Cannot copy checkpoint with multiple updates`);if(a==null)throw new ew(`Cannot copy a non-existent checkpoint`);let e=e=>!Array.isArray(e)||e.length===0?!1:e.every(e=>Array.isArray(e)&&e.length===2),r=vP(o,void 0,c),s=await n.put(a.parentConfig??UP(a.config,{checkpoint_id:void 0}),r,{source:`fork`,step:c+1,parents:a.metadata?.parents??{}},{});if(e(d)){let e=CI(r,a.pendingWrites,this.nodes,p,s,!1,{step:c+2}),t=Object.values(e).reduce((e,{name:t,id:n})=>(e[t]??=[],e[t].push({id:n}),e),{}),n=d.reduce((e,n)=>{let[r,i]=n;e[i]??=[];let a=e[i].length,o=t[i]?.[a]?.id;return e[i].push({values:r,asNode:i,taskId:o}),e},{});return i(iF(s,a.metadata),Object.values(n).flat())}return iF(s,a.metadata)}if(f===`__input__`){if(t.length>1)throw new ew(`Cannot apply multiple updates when updating as input`);let e=await VP(oI(this.inputChannels,d));if(e.length===0)throw new ew(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);bI(o,p,[{name:US,writes:e,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let r=a?.metadata?.step==null?-1:a.metadata.step+1,i=await n.put(l,vP(o,p,r),{source:`input`,step:r,parents:a?.metadata?.parents??{}},tF(s,o.channel_versions));return await n.putWrites(i,e,ow(US,o.id)),iF(i,a?a.metadata:void 0)}if(r.configurable?.checkpoint_id===void 0&&a?.pendingWrites!==void 0&&a.pendingWrites.length>0){let e=CI(o,a.pendingWrites,this.nodes,p,a.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(a.metadata?.step??-1)+1}),t=(a.pendingWrites??[]).filter(e=>e[0]===CC).map(e=>e.slice(1));t.length>0&&bI(a.checkpoint,p,[{name:US,writes:t,triggers:[]}],void 0,this.triggerToNodes);for(let[t,n,r]of a.pendingWrites)[`__error__`,`__interrupt__`,`__scheduled__`].includes(n)||e[t]===void 0||e[t].writes.push([n,r]);let n=Object.values(e).filter(e=>e.writes.length>0);n.length>0&&bI(o,p,n,void 0,this.triggerToNodes)}let m=Object.values(o.versions_seen).map(e=>Object.values(e)).flat().find(e=>!!e),h=[];if(t.length===1){let{values:e,asNode:n,taskId:r}=t[0];if(n===void 0&&Object.keys(this.nodes).length===1)[n]=Object.keys(this.nodes);else if(n===void 0&&m===void 0)typeof this.inputChannels==`string`&&this.nodes[this.inputChannels]!==void 0&&(n=this.inputChannels);else if(n===void 0){let e=Object.entries(o.versions_seen).map(([e,t])=>Object.values(t).map(t=>[t,e])).flat().filter(([e,t])=>t!==pC).sort(([e],[t])=>$N(e,t));e&&(e.length===1?n=e[0][1]:e[e.length-1][0]!==e[e.length-2][0]&&(n=e[e.length-1][1]))}if(n===void 0)throw new ew(`Ambiguous update, specify "asNode"`);h.push({values:e,asNode:n,taskId:r})}else for(let{asNode:e,values:n,taskId:r}of t){if(e==null)throw new ew(`"asNode" is required when applying multiple updates`);h.push({values:n,asNode:e,taskId:r})}let g=[];for(let{asNode:e,values:t,taskId:n}of h){if(this.nodes[e]===void 0)throw new ew(`Node "${e.toString()}" does not exist`);let r=this.nodes[e].getWriters();if(!r.length)throw new ew(`No writers found for node "${e.toString()}"`);g.push({name:e,input:t,proc:r.length>1?aS.from(r,{omitSequenceTags:!0}):r[0],writes:[],triggers:[pC],id:n??ow(`__interrupt__`,o.id),writers:[]})}for(let e of g)await e.proc.invoke(e.input,Au({...r,store:r?.store??this.store},{runName:r.runName??`${this.getName()}UpdateState`,configurable:{[JS]:t=>e.writes.push(...t),[XS]:(t,n=!1)=>gI(o,p,e,t,n)}}));for(let e of g){let t=e.writes.filter(e=>e[0]!==xC);a!==void 0&&t.length>0&&await n.putWrites(l,t,e.id)}bI(o,p,g,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let _=tF(s,o.channel_versions),v=await n.put(l,vP(o,p,c+1),{source:`update`,step:c+1,parents:a?.metadata?.parents??{}},_);for(let e of g){let t=e.writes.filter(e=>e[0]===xC);t.length>0&&await n.putWrites(v,t,e.id)}return iF(v,a?a.metadata:void 0)},a=e;for(let{updates:e}of t)a=await i(a,e);return a}async updateState(e,t,n){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:n}]}])}_defaults(e){let{debug:t,streamMode:n,inputKeys:r,outputKeys:i,interruptAfter:a,interruptBefore:o,...s}=e,c=!0,l=t===void 0?this.debug:t,u=i;u===void 0?u=this.streamChannelsAsIs:mR(u,this.channels);let d=r;d===void 0?d=this.inputChannels:mR(d,this.channels);let f=o??this.interruptBefore??[],p=a??this.interruptAfter??[],m;n===void 0?(m=e.configurable?.__pregel_task_id===void 0?this.streamMode:[`values`],c=!0):(m=Array.isArray(n)?n:[n],c=typeof n==`string`);let h;if(this.checkpointer===!1)h=void 0;else if(e!==void 0&&e.configurable?.__pregel_checkpointer!==void 0)h=e.configurable[ZS];else if(this.checkpointer===!0)throw Error(`checkpointer: true cannot be used for root graphs.`);else h=this.checkpointer;let g=e.store??this.store,_=e.cache??this.cache;if(e.durability!=null&&e.checkpointDuring!=null)throw Error("Cannot use both `durability` and `checkpointDuring` at the same time.");let v=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?`exit`:`async`})(),y=e.durability??v??e?.configurable?.__pregel_durability??`async`;return[l,m,d,u,s,f,p,h,g,c,_,y]}async stream(e,t){let n=new AbortController,r=IP()?.configurable;r?.__pregel_read!==void 0&&t?.configurable?.__pregel_read===void 0&&(t={...t,configurable:{...r,...t?.configurable}});let i={recursionLimit:this.config?.recursionLimit,...t,signal:aF(t?.signal,n.signal).signal},a=await super.stream(e,i);return new qI(t?.encoding===`text/event-stream`?nL(a):a,n)}async#e(e,t){let{version:n,encoding:r,transformers:i,...a}=t,o={recursionLimit:this.config?.recursionLimit,...a,configurable:{...this.config?.configurable,...a?.configurable},version:n,streamMode:VI,subgraphs:!0,encoding:void 0},s=this.stream(e,o),c=dR({[Symbol.asyncIterator]:async function*(){let e=await s;for await(let t of e)yield t}},[...this.streamTransformers??[],...i??[]]);if(r===`text/event-stream`){let e=new AbortController;return e.signal.addEventListener(`abort`,()=>c.abort(e.signal.reason),{once:!0}),new qI(vR(c),e)}return c}streamEvents(e,t,n){if(t.version===`v3`)return this.#e(e,t);let r=new AbortController,i={recursionLimit:this.config?.recursionLimit,...t,signal:aF(t?.signal,r.signal).signal};return new qI(super.streamEvents(e,i,n),r)}async _validateInput(e){return e}async _validateContext(e){return e}async*_streamIterator(e,t){let n=`version`in(t??{})?void 0:t?.encoding??void 0,r=t?.subgraphs,i=t?.version===`v3`,a=FP(this.config,t);if(a.recursionLimit===void 0||a.recursionLimit<1)throw Error(`Passed "recursionLimit" must be at least 1.`);if(this.checkpointer!==void 0&&this.checkpointer!==!1&&a.configurable===void 0)throw Error(`Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"`);let o=await this._validateInput(e),{runId:s,...c}=a,[l,u,,d,f,p,m,h,g,_,v,y]=this._defaults(c);f.metadata={ls_integration:`langgraph`,...f.metadata},f.context===void 0?f.configurable=await this._validateContext(f.configurable):f.context=await this._validateContext(f.context);let b=new JI({modes:new Set(u)});if(this.checkpointer===!0){f.configurable??={};let e=f.configurable.checkpoint_ns??``;f.configurable[sC]=e.split(`|`).map(e=>e.split(`:`)[0]).join(`|`)}if(u.includes(`messages`)){let e=i?new bL(e=>b.push(e)):new hL(e=>b.push(e)),{callbacks:t}=f;if(t===void 0)f.callbacks=[e];else if(Array.isArray(t))f.callbacks=t.concat(e);else{let n=t.copy();n.addHandler(e,!0),f.callbacks=n}}if(u.includes(`tools`)){let e=new YI(e=>b.push(e)),{callbacks:t}=f;if(t===void 0)f.callbacks=[e];else if(Array.isArray(t))f.callbacks=t.concat(e);else{let n=t.copy();n.addHandler(e,!0),f.callbacks=n}}f.writer??=e=>{if(!u.includes(`custom`))return;let t=(IP()?.configurable?.[sC])?.split(`|`).slice(0,-1);b.push([t??[],`custom`,e])},f.interrupt??=this.userInterrupt??_R,f.serverInfo??=SR(f),f.control??=new uF;let ee={tracerInheritableMetadata:TR(f)},te=await(await _u._configureSync(f?.callbacks,void 0,f?.tags,void 0,f?.metadata,void 0,ee))?.handleChainStart(this.toJSON(),nF(e,`input`),s,void 0,void 0,void 0,f?.runName??this.getName()),ne=mP(this.channels),x,re,ie=(async()=>{try{x=await fL.initialize({input:o,config:f,checkpointer:h,nodes:this.nodes,channelSpecs:ne,outputKeys:d,streamKeys:this.streamChannelsAsIs,store:g,cache:v,stream:b,interruptAfter:m,interruptBefore:p,manager:te,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:y});let e=new AL({loop:x,nodeFinished:f.configurable?.[cC]});t?.subgraphs&&(x.config.configurable={...x.config.configurable,[eC]:x.stream}),await this._runLoop({loop:x,runner:e,debug:l,config:f}),y===`sync`&&await Promise.all(x?.checkpointerPromises??[])}catch(e){re=e}finally{try{x&&(await x.store?.stop(),await x.cache?.stop()),await Promise.all(x?.checkpointerPromises??[])}catch(e){re??=e}re?(await new Promise(e=>{queueMicrotask(e)}),b.error(re)):b.close()}})();try{for await(let e of b){if(e===void 0)throw Error(`Data structure error.`);let[a,o,s]=e,c=`version`in(t??{});if(u.includes(o)||o===`checkpoints`&&HI(s)&&(i||c&&r&&u.includes(`values`))){if(n===`text/event-stream`){r?yield[a,o,s]:yield[null,o,s];continue}r&&!_?yield[a,o,s]:_?r?yield[a,s]:yield s:yield[o,s]}}}catch(e){throw await te?.handleChainError(re),e}finally{await ie}await te?.handleChainEnd(x?.output??{},s,void 0,void 0,void 0)}async invoke(e,t){let n=t?.streamMode??`values`,r={...t,outputKeys:t?.outputKeys??this.outputChannels,streamMode:n,encoding:void 0},i=[],a=await this.stream(e,r),o=[],s;for await(let e of a)n===`values`?NC(e)?o.push(e[pC]):s=e:i.push(e);if(n===`values`){if(o.length>0){let e=o.flat(1);if(s==null)return{[pC]:e};if(typeof s==`object`)return{...s,[pC]:e}}return s}return i}async _runLoop(e){let{loop:t,runner:n,debug:r,config:i}=e,a;try{for(;await t.tick({inputKeys:this.inputChannels});){for(let{task:e}of await t._matchCachedWrites())t._outputWrites(e.id,e.writes,!0);r&&RI(t.checkpointMetadata.step,t.channels,this.streamChannelsList),r&&zI(t.step,Object.values(t.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(e,t)=>{r&&BI(e,t,this.streamChannelsList)},maxConcurrency:i.maxConcurrency,signal:i.signal})}if(t.status===`draining`)throw t.control==null?Error(`Draining status requires run control`):new HC(t.control.drainReason??`shutdown`);if(t.status===`out_of_steps`)throw new BC([`Recursion limit of ${i.recursionLimit} reached`,`without hitting a stop condition. You can increase the`,`limit by setting the "recursionLimit" config key.`].join(` `),{lc_error_code:`GRAPH_RECURSION_LIMIT`})}catch(e){if(a=e,!await t.finishAndHandleError(a))throw e}finally{a===void 0&&await t.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}};function SR(e){let t=e.metadata??{},n=e.configurable??{},r=n.assistant_id??t.assistant_id,i=n.graph_id??t.graph_id,a=n.langgraph_auth_user,o;if(typeof a==`object`&&a&&`identity`in a&&(o=a),r!=null||i!=null||o!=null)return{assistantId:r==null?``:String(r),graphId:i==null?``:String(i),user:o}}var CR=new Set([`key`,`token`,`secret`,`password`,`auth`]);function wR(e,t){let n=e.toLowerCase(),r=!1;for(let e of CR)if(n.includes(e)){r=!0;break}return e.startsWith(`__`)||!(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)||r}function TR(e){let t=e.configurable;if(!t)return;let n=e.context,r={};for(let[e,i]of Object.entries(t)){if(n!=null&&Object.prototype.hasOwnProperty.call(n,e)&&Object.is(n[e],i)){e.startsWith(`__`)||(r[e]=void 0);continue}wR(e,i)||(r[e]=i)}return Object.keys(r).length>0?r:void 0}var ER=class{path;ends;constructor(e){tS.isRunnable(e.path)?this.path=e.path:this.path=fS(e.path),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((e,t)=>(e[t]=t,e),{}):e.pathMap}run(e,t){return JP.registerWriter(new zP({name:`<branch_run>`,trace:!1,func:async(n,r)=>{try{return await this._route(n,r,e,t)}catch(e){throw e.name===GC.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
|
|
189
|
+
NodeInterrupt should only be thrown inside a node, not in edge conditions.`),e}}}))}async _route(e,t,n,r){let i=await this.path.invoke(r?r(t):e,t);Array.isArray(i)||(i=[i]);let a;if(a=this.ends?i.map(e=>kC(e)?e:this.ends[e]):i,a.some(e=>!e))throw Error(`Branch condition returned unknown or null destination`);if(a.filter(kC).some(e=>e.node===`__end__`))throw new ew(`Cannot send a packet to the END node`);return await n(a,t)??e}},DR=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(e){this.compiled&&console.warn(e)}get allEdges(){return this.edges}addNode(...e){function t(e){return e.length>=1&&typeof e[0]!=`string`}let n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]):[[e[0],e[1],e[2]]];if(n.length===0)throw Error("No nodes provided in `addNode`");for(let[e,t,r]of n){for(let t of[`|`,`:`])if(e.includes(t))throw Error(`"${t}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`),e in this.nodes)throw Error(`Node \`${e}\` already present.`);if(e===`__end__`)throw Error(`Node \`${e}\` is reserved.`);let n=fS(t);this.nodes[e]={runnable:n,metadata:r?.metadata,subgraphs:sF(n)?[n]:r?.subgraphs,ends:r?.ends}}return this}addEdge(e,t){if(this.warnIfCompiled(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`),e===`__end__`)throw Error(`END cannot be a start node`);if(t===`__start__`)throw Error(`START cannot be an end node`);if(Array.from(this.edges).some(([t])=>t===e)&&!(`channels`in this))throw Error(`Already found path for ${e}. For multiple edges, use StateGraph.`);return this.edges.add([e,t]),this}addConditionalEdges(e,t,n){let r=typeof e==`object`?e:{source:e,path:t,pathMap:n};this.warnIfCompiled(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`),tS.isRunnable(r.path)||(r.path=fS(r.path));let i=r.path.getName()===`RunnableLambda`?`condition`:r.path.getName();if(this.branches[r.source]&&this.branches[r.source][i])throw Error(`Condition \`${i}\` already present for node \`${e}\``);return this.branches[r.source]??={},this.branches[r.source][i]=new ER(r),this}setEntryPoint(e){return this.warnIfCompiled(`Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph.`),this.addEdge(VS,e)}setFinishPoint(e){return this.warnIfCompiled(`Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph.`),this.addEdge(e,HS)}compile({checkpointer:e,interruptBefore:t,interruptAfter:n,name:r,transformers:i}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(n)?n:[]]);let a=new OR({builder:this,checkpointer:e,interruptAfter:n,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[VS]:new lF,[HS]:new lF},inputChannels:VS,outputChannels:HS,streamChannels:[],streamMode:`values`,name:r,streamTransformers:i});for(let[e,t]of Object.entries(this.nodes))a.attachNode(e,t);for(let[e,t]of this.edges)a.attachEdge(e,t);for(let[e,t]of Object.entries(this.branches))for(let[n,r]of Object.entries(t))a.attachBranch(e,n,r);return a.validate()}validate(e){let t=new Set([...this.allEdges].map(([e,t])=>e));for(let[e]of Object.entries(this.branches))t.add(e);for(let e of t)if(e!==`__start__`&&!(e in this.nodes))throw Error(`Found edge starting at unknown node \`${e}\``);let n=new Set([...this.allEdges].map(([e,t])=>t));for(let[e,t]of Object.entries(this.branches))for(let r of Object.values(t))if(r.ends!=null)for(let e of Object.values(r.ends))n.add(e);else{n.add(HS);for(let t of Object.keys(this.nodes))t!==e&&n.add(t)}for(let e of Object.values(this.nodes))for(let t of e.ends??[])n.add(t);if(Object.values(this.nodes).some(e=>e.isErrorHandler))for(let e of Object.keys(this.nodes))n.add(e);for(let e of Object.keys(this.nodes))if(!this.nodes[e].isErrorHandler&&!n.has(e))throw new tw([`Node \`${e}\` is not reachable.`,``,`If you are returning Command objects from your node,`,`make sure you are passing names of potential destination nodes as an "ends" array`,`into ".addNode(..., { ends: ["node1", "node2"] })".`].join(`
|
|
190
|
+
`),{lc_error_code:`UNREACHABLE_NODE`});for(let e of n)if(e!==`__end__`&&!(e in this.nodes))throw Error(`Found edge ending at unknown node \`${e}\``);if(e){for(let t of e)if(!(t in this.nodes))throw Error(`Interrupt node \`${t}\` is not present`)}this.compiled=!0}},OR=class extends xR{builder;constructor({builder:e,...t}){super(t),this.builder=e}withConfig(e){return super.withConfig(e)}attachNode(e,t){this.channels[e]=new lF,this.nodes[e]=new $P({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new JP([{channel:e,value:GP}],[vC])),this.streamChannels.push(e)}attachEdge(e,t){if(t===`__end__`){if(e===`__start__`)throw Error(`Cannot have an edge from START to END`);this.nodes[e].writers.push(new JP([{channel:HS,value:GP}],[vC]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,n){e===`__start__`&&!this.nodes.__start__&&(this.nodes[VS]=yR.subscribeTo(VS,{tags:[vC]})),this.nodes[e].pipe(n.run(n=>new JP(n.map(n=>kC(n)?n:{channel:n===`__end__`?HS:`branch:${e}:${t}:${n}`,value:GP}),[vC])));let r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(let n of r)if(n!==`__end__`){let r=`branch:${e}:${t}:${n}`;this.channels[r]=new lF,this.nodes[n].triggers.push(r),this.nodes[n].channels.push(r)}}async getGraphAsync(e){let t=e?.xray,n=new Ux,r={[VS]:n.addNode({schema:ej()},VS)},i={},a={};t&&(a=Object.fromEntries((await VP(this.getSubgraphsAsync())).filter(e=>kR(e[1]))));let o=[];function s(e,t,a,s=!1){if(t===`__end__`&&i.__end__===void 0&&(i[HS]=n.addNode({schema:ej()},HS)),r[e]!==void 0){if(i[t]===void 0)throw Error(`End node ${t} not found!`);return o.push({src:e,dest:t,conditional:s}),n.addEdge(r[e],i[t],a===t?void 0:a,s)}}for(let[o,s]of Object.entries(this.builder.nodes)){let c=AR(o),l=s.runnable,u=s.metadata??{};if(this.interruptBefore?.includes(o)&&this.interruptAfter?.includes(o)?u.__interrupt=`before,after`:this.interruptBefore?.includes(o)?u.__interrupt=`before`:this.interruptAfter?.includes(o)&&(u.__interrupt=`after`),t){let s=typeof t==`number`?t-1:t,d=a[o]===void 0?l.getGraph(e):await a[o].getGraphAsync({...e,xray:s});if(d.trimFirstNode(),d.trimLastNode(),Object.keys(d.nodes).length>1){let[e,t]=n.extend(d,c);if(e===void 0)throw Error(`Could not extend subgraph "${o}" due to missing entrypoint.`);function a(e){return e?e.lc_runnable:!1}function s(e,t){if(e!==void 0&&!$r(e))return e;if(a(t))try{let e=t.getName();return e=e.startsWith(`Runnable`)?e.slice(8):e,e}catch{return t.getName()}else return t.name??`UnknownSchema`}t!==void 0&&(r[c]={name:s(t.id,t.data),...t}),i[c]={name:s(e.id,e.data),...e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}let c=[...this.builder.allEdges].sort(([e],[t])=>e<t?-1:+(t>e));for(let[e,t]of c)s(AR(e),AR(t));for(let[e,t]of Object.entries(this.builder.branches)){let n={...Object.fromEntries(Object.keys(this.builder.nodes).filter(t=>t!==e).map(e=>[AR(e),AR(e)])),[HS]:HS};for(let r of Object.values(t)){let t;t=r.ends===void 0?n:r.ends;for(let[n,r]of Object.entries(t))s(AR(e),AR(r),n,!0)}}for(let[e,t]of Object.entries(this.builder.nodes))if(t.ends!==void 0)for(let n of t.ends)s(AR(e),AR(n),void 0,!0);return jR(this.builder.nodes,o,s),n}getGraph(e){let t=e?.xray,n=new Ux,r={[VS]:n.addNode({schema:ej()},VS)},i={},a={};t&&(a=Object.fromEntries(HP(this.getSubgraphs()).filter(e=>kR(e[1]))));let o=[];function s(e,t,a,s=!1){if(t===`__end__`&&i.__end__===void 0&&(i[HS]=n.addNode({schema:ej()},HS)),r[e]!==void 0){if(i[t]===void 0)throw Error(`End node ${t} not found!`);return o.push({src:e,dest:t,conditional:s}),n.addEdge(r[e],i[t],a===t?void 0:a,s)}}for(let[o,s]of Object.entries(this.builder.nodes)){let c=AR(o),l=s.runnable,u=s.metadata??{};if(this.interruptBefore?.includes(o)&&this.interruptAfter?.includes(o)?u.__interrupt=`before,after`:this.interruptBefore?.includes(o)?u.__interrupt=`before`:this.interruptAfter?.includes(o)&&(u.__interrupt=`after`),t){let s=typeof t==`number`?t-1:t,d=a[o]===void 0?l.getGraph(e):a[o].getGraph({...e,xray:s});if(d.trimFirstNode(),d.trimLastNode(),Object.keys(d.nodes).length>1){let[e,t]=n.extend(d,c);if(e===void 0)throw Error(`Could not extend subgraph "${o}" due to missing entrypoint.`);function a(e){return e?e.lc_runnable:!1}function s(e,t){if(e!==void 0&&!$r(e))return e;if(a(t))try{let e=t.getName();return e=e.startsWith(`Runnable`)?e.slice(8):e,e}catch{return t.getName()}else return t.name??`UnknownSchema`}t!==void 0&&(r[c]={name:s(t.id,t.data),...t}),i[c]={name:s(e.id,e.data),...e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}let c=[...this.builder.allEdges].sort(([e],[t])=>e<t?-1:+(t>e));for(let[e,t]of c)s(AR(e),AR(t));for(let[e,t]of Object.entries(this.builder.branches)){let n={...Object.fromEntries(Object.keys(this.builder.nodes).filter(t=>t!==e).map(e=>[AR(e),AR(e)])),[HS]:HS};for(let r of Object.values(t)){let t;t=r.ends===void 0?n:r.ends;for(let[n,r]of Object.entries(t))s(AR(e),AR(r),n,!0)}}for(let[e,t]of Object.entries(this.builder.nodes))if(t.ends!==void 0)for(let n of t.ends)s(AR(e),AR(n),void 0,!0);return jR(this.builder.nodes,o,s),n}};function kR(e){return typeof e.attachNode==`function`&&typeof e.attachEdge==`function`}function AR(e){return e===`subgraph`?`"${e}"`:e}function jR(e,t,n){let r=new Set(t.map(e=>e.src)),i=[...new Set(t.filter(e=>!e.conditional&&e.dest!==`__end__`).map(e=>e.dest))].sort();for(let t of i){if(r.has(t))continue;let i=Object.keys(e).find(e=>AR(e)===t);i!==void 0&&e[i]?.isErrorHandler||n(t,HS)}}var MR=(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e)),NR=class e extends fP{lc_graph_name=`NamedBarrierValue`;names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(t){let n=new e(this.names);return t!==void 0&&(n.seen=new Set(t)),n}update(e){let t=!1;for(let n of e)if(this.names.has(n))this.seen.has(n)||(this.seen.add(n),t=!0);else throw new ew(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return t}get(){if(!MR(this.names,this.seen))throw new $C}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&MR(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&MR(this.names,this.seen)}},PR=class e extends fP{lc_graph_name=`NamedBarrierValueAfterFinish`;names;seen;finished;constructor(e){super(),this.names=e,this.seen=new Set,this.finished=!1}fromCheckpoint(t){let n=new e(this.names);if(t!==void 0){let[e,r]=t;n.seen=new Set(e),n.finished=r}return n}update(e){let t=!1;for(let n of e)if(this.names.has(n)&&!this.seen.has(n))this.seen.add(n),t=!0;else if(!this.names.has(n))throw new ew(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return t}get(){if(!this.finished||!MR(this.names,this.seen))throw new $C}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&MR(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&MR(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&MR(this.names,this.seen)}};function FR(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`validate`in e[`~standard`]}function IR(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`jsonSchema`in e[`~standard`]}function LR(e){if(IR(e))try{return e[`~standard`].jsonSchema.input({target:`draft-07`})}catch{return}}function RR(e){if(e!=null&&FR(e))try{let t=e[`~standard`].validate(void 0);if(t&&typeof t==`object`&&!(`then`in t&&typeof t.then==`function`)){let e=t;if(!e.issues){let t=e.value;return()=>t}}}catch{}}var zR=e=>e!=null&&e.lc_graph_name===`DeltaChannel`,BR=class e extends fP{lc_graph_name=`DeltaChannel`;value;reducer;snapshotFrequency;initialValueFactory;constructor(e,t){super();let n=t?.snapshotFrequency??1e3;if(!Number.isInteger(n)||n<=0)throw Error(`snapshotFrequency must be a positive integer, got ${n}`);this.reducer=e,this.snapshotFrequency=n,this.initialValueFactory=t?.initialValueFactory??(()=>[]),this.value=void 0}fromCheckpoint(t){let n=new e(this.reducer,{snapshotFrequency:this.snapshotFrequency,initialValueFactory:this.initialValueFactory});return t===void 0?n.value=this.initialValueFactory():fw(t)?n.value=t.value:n.value=t,n}replayWrites(e){let t=e.map(e=>e[2]);if(t.length===0)return;let n=this.value,r=0;for(let e=0;e<t.length;e+=1){let[i,a]=jC(t[e]);i&&(n=a??this.initialValueFactory(),r=e+1)}let i=t.slice(r);this.value=i.length>0?this.reducer(n,i):n}update(e){if(e.length===0)return!1;let t,n=!1;for(let r of e)if(MC(r)){if(n)throw new ew(`Can receive only one Overwrite value per step.`);n=!0,[,t]=jC(r)}if(n)return this.value=t??this.initialValueFactory(),!0;let r=this.value===void 0?this.initialValueFactory():this.value;return this.value=this.reducer(r,e),!0}get(){if(this.value===void 0)throw new $C;return this.value}checkpoint(){}isAvailable(){return this.value!==void 0}equals(e){return this===e?!0:!zR(e)||this.snapshotFrequency!==e.snapshotFrequency?!1:this.reducer===e.reducer}},VR=Symbol.for(`langgraph.channel.missing`),HR=class e extends fP{lc_graph_name=`UntrackedValue`;guard;_value=VR;initialValueFactory;constructor(e){super(),this.guard=e?.guard??!0,this.initialValueFactory=e?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new e({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(e){if(e.length===0)return!1;if(e.length!==1&&this.guard)throw new ew(`UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.`,{lc_error_code:`INVALID_CONCURRENT_GRAPH_UPDATE`});return this._value=e[e.length-1],!0}get(){if(this._value===VR)throw new $C;return this._value}checkpoint(){}isAvailable(){return this._value!==VR}},UR=Symbol.for(`langgraph.state.reduced_value`),WR=class{[UR]=!0;valueSchema;inputSchema;reducer;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.jsonSchemaExtra=t.jsonSchemaExtra,this.valueSchema=e,this.inputSchema=`inputSchema`in t?t.inputSchema:e,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e==`object`&&!!e&&UR in e&&e[UR]===!0}},GR=Symbol.for(`langgraph.state.untracked_value`),KR=class{[GR]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e==`object`&&!!e&&GR in e}},qR=Symbol.for(`langgraph.state.delta_value`),JR=class{[qR]=!0;valueSchema;inputSchema;reducer;snapshotFrequency;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.valueSchema=e,this.inputSchema=`inputSchema`in t?t.inputSchema:e,this.snapshotFrequency=t.snapshotFrequency,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e==`object`&&!!e&&qR in e&&e[qR]===!0}},YR=Symbol.for(`langgraph.state.state_schema`),XR=class{[YR]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,n]of Object.entries(this.fields))if(JR.isInstance(n)){let r=RR(n.valueSchema);e[t]=new BR(n.reducer,{snapshotFrequency:n.snapshotFrequency,initialValueFactory:r})}else if(WR.isInstance(n)){let r=RR(n.valueSchema);e[t]=new CP(n.reducer,r)}else if(KR.isInstance(n)){let r=n.schema?RR(n.schema):void 0;e[t]=new HR({guard:n.guard,initialValueFactory:r})}else if(FR(n))e[t]=new bP(RR(n));else throw Error(`Invalid state field "${t}": must be a schema, ReducedValue, DeltaValue, UntrackedValue, or ManagedValue`);return e}getJsonSchema(){let e={},t=[];for(let[n,r]of Object.entries(this.fields)){let i;if(JR.isInstance(r)||WR.isInstance(r)?(i=LR(r.valueSchema),r.jsonSchemaExtra&&(i={...i??{},...r.jsonSchemaExtra})):KR.isInstance(r)?i=r.schema?LR(r.schema):void 0:FR(r)&&(i=LR(r)),i){e[n]=i;let a=!1;a=JR.isInstance(r)||WR.isInstance(r)?RR(r.valueSchema)!==void 0:KR.isInstance(r)?r.schema?RR(r.schema)!==void 0:!1:RR(r)!==void 0,a||t.push(n)}}return{type:`object`,properties:e,required:t.length>0?t:void 0}}getInputJsonSchema(){let e={};for(let[t,n]of Object.entries(this.fields)){let r;JR.isInstance(n)||WR.isInstance(n)?(r=LR(n.inputSchema),n.jsonSchemaExtra&&(r={...r??{},...n.jsonSchemaExtra})):KR.isInstance(n)?r=n.schema?LR(n.schema):void 0:FR(n)&&(r=LR(n)),r&&(e[t]=r)}return{type:`object`,properties:e}}getChannelKeys(){return Object.entries(this.fields).map(([e])=>e)}getAllKeys(){return Object.keys(this.fields)}async validateInput(e){if(typeof e!=`object`||!e)return e;let t={};for(let[n,r]of Object.entries(e)){let e=this.fields[n];if(e===void 0){t[n]=r;continue}let i;if(JR.isInstance(e)||WR.isInstance(e)){let[a,o]=jC(r);if(a){i=e.valueSchema;let r=await i[`~standard`].validate(o);if(r.issues)throw Error(`Validation failed for field "${n}": ${JSON.stringify(r.issues)}`);t[n]={[AC]:r.value};continue}i=e.inputSchema}else KR.isInstance(e)?i=e.schema:FR(e)&&(i=e);if(i){let e=await i[`~standard`].validate(r);if(e.issues)throw Error(`Validation failed for field "${n}": ${JSON.stringify(e.issues)}`);t[n]=e.value}else t[n]=r}return t}static isInstance(e){return typeof e==`object`&&!!e&&YR in e&&e[YR]===!0}};function ZR(e,t){let n=Array.isArray(e)?e:[e],r=Array.isArray(t)?t:[t],i=n.map(nr),a=r.map(nr);for(let e of i)(e.id===null||e.id===void 0)&&(e.id=Yr(),e.lc_kwargs.id=e.id);let o;for(let e=0;e<a.length;e+=1){let t=a[e];(t.id===null||t.id===void 0)&&(t.id=Yr(),t.lc_kwargs.id=t.id),Kn.isInstance(t)&&t.id===`__remove_all__`&&(o=e)}if(o!=null)return a.slice(o+1);let s=[...i],c=new Map(s.map((e,t)=>[e.id,t])),l=new Set;for(let e of a){let t=c.get(e.id);if(t!==void 0)Kn.isInstance(e)?l.add(e.id):(l.delete(e.id),s[t]=e);else{if(Kn.isInstance(e))throw Error(`Attempting to delete a message with an ID that doesn't exist ('${e.id}')`);c.set(e.id,s.length),s.push(e)}}return s.filter(e=>!l.has(e.id))}function QR(e,t){let n=[];for(let e of t)Array.isArray(e)?n.push(...e):n.push(e);let r=e.length>0&&Mt.isInstance(e[0])?e:e.map(nr),i=n.map(nr),a=new Map;for(let e=0;e<r.length;e+=1){let t=r[e].id;t!=null&&a.set(t,e)}let o=[...r];for(let e of i){let t=e.id;Kn.isInstance(e)&&t===`__remove_all__`?(o.length=0,a.clear()):t==null?o.push(e):Kn.isInstance(e)?a.has(t)&&(o[a.get(t)]=null,a.delete(t)):a.has(t)?o[a.get(t)]=e:(a.set(t,o.length),o.push(e))}return o.filter(e=>e!==null)}var $R=Uj().default(()=>[]),ez=Uj();new WR($R,{inputSchema:ez,reducer:ZR,jsonSchemaExtra:{langgraph_type:`messages`,description:`A list of chat messages`}}),new JR($R,{inputSchema:ez,reducer:QR,jsonSchemaExtra:{langgraph_type:`messages`,description:`A list of chat messages`}});var tz=new class{_map=new Map;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){let n=this.get(e);this._map.set(e,t(n))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){let t={},n=X_(e);for(let[e,r]of Object.entries(n)){let n=this.get(r);n?.reducer?t[e]=new CP(n.reducer.fn,n.default):t[e]=new bP(n?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).filter(([,e])=>e===!0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}:${t}`).join(`|`),r=this._extensionCache.get(n)??new Map;if(r.has(e))return r.get(e);let i=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let n=Object.entries(X_(e)).map(([e,n])=>{let r=this.get(n),i=t.withReducerSchema?r?.reducer?.schema??n:n;if(t.withJsonSchemaExtrasAsDescription&&r?.jsonSchemaExtra){let e=V_(i)??V_(n),t=JSON.stringify({...r.jsonSchemaExtra,description:e});i=i.describe(`lg:${t}`)}return[e,i]});i=Z_(e,Object.fromEntries(n)),j_(i)&&(i._def.unknownKeys=`strip`)}return t.asPartial&&(i=Q_(i)),r.set(e,i),this._extensionCache.set(n,r),i}};function nz(e){return e!=null&&!!(XR.isInstance(e)||Y_(e)||typeof e==`object`&&`lc_graph_name`in e&&e.lc_graph_name===`AnnotationRoot`||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(e=>typeof e==`function`||dP(e)))}function rz(e){if(typeof e!=`object`||!e)return!1;let t=e,n=`state`in t&&nz(t.state),r=`stateSchema`in t&&nz(t.stateSchema),i=`input`in t&&nz(t.input);return!(!n&&!r&&!i||`input`in t&&t.input!=null&&!nz(t.input)||`output`in t&&t.output!=null&&!nz(t.output))}var iz=`__root__`,az=`__default_error_handler__`,oz=Symbol.for(`langgraph.state.partial`),sz=class extends DR{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=tz;_configSchema;_configRuntimeSchema;_interrupt;_writer;_nodeDefaults={};constructor(e,t){super();let n=this._normalizeToStateGraphInit(e,t),r=n.state??n.stateSchema??n.input;if(!r)throw new nw;let i=this._getChannelsFromSchema(r);this._schemaDefinition=i,(XR.isInstance(r)||Y_(r))&&(this._schemaRuntimeDefinition=r),n.input&&(XR.isInstance(n.input)||Y_(n.input))?this._inputRuntimeDefinition=n.input:this._inputRuntimeDefinition=oz,n.output&&(XR.isInstance(n.output)||Y_(n.output))?this._outputRuntimeDefinition=n.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let a=n.input?this._getChannelsFromSchema(n.input):i,o=n.output?this._getChannelsFromSchema(n.output):i;this._inputDefinition=a,this._outputDefinition=o,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),n.context&&Y_(n.context)&&(this._configRuntimeSchema=n.context),this._interrupt=n.interrupt,this._writer=n.writer}setNodeDefaults(e){return e.retryPolicy!==void 0&&(this._nodeDefaults.retryPolicy=e.retryPolicy),e.cachePolicy!==void 0&&(this._nodeDefaults.cachePolicy=typeof e.cachePolicy==`boolean`?e.cachePolicy?{}:void 0:e.cachePolicy),e.timeout!==void 0&&(this._nodeDefaults.timeout=BS(e.timeout)),e.errorHandler!==void 0&&(this._nodeDefaults.errorHandler=e.errorHandler),this}_createDefaultErrorHandlerSpec(){let e=this._nodeDefaults.errorHandler;if(e!==void 0)return{runnable:new zP({func:(t,n)=>{let r=n?.configurable?.[lC];return e(t,r,n)},name:az,trace:!1}),metadata:void 0,input:this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0}}_normalizeToStateGraphInit(e,t){if(rz(e)){if(Y_(t)||wP.isInstance(t))return{...e,context:t};let n=t;return{...e,input:e.input??n?.input,output:e.output??n?.output,context:e.context??n?.context,interrupt:e.interrupt??n?.interrupt,writer:e.writer??n?.writer,nodes:e.nodes??n?.nodes}}if(nz(e)){if(Y_(t)||wP.isInstance(t))return{state:e,context:t};let n=t;return{state:e,input:n?.input,output:n?.output,context:n?.context,interrupt:n?.interrupt,writer:n?.writer,nodes:n?.nodes}}if(uz(e))return{state:cz(e.channels)};throw new nw}_getChannelsFromSchema(e){if(XR.isInstance(e))return e.getChannels();if(Y_(e))return this._metaRegistry.getChannelsForSchema(e);if(typeof e==`object`&&`lc_graph_name`in e&&e.lc_graph_name===`AnnotationRoot`)return e.spec;if(typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0)return e;throw new nw(`Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.`)}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(e=>[e,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(let[t,n]of Object.entries(e)){let e;if(e=typeof n==`function`?n():n,this.channels[t]!==void 0){if(!this.channels[t].equals(e)&&e.lc_graph_name!==`LastValue`)throw Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=e}}}addNode(...e){function t(e){return e.length>=1&&typeof e[0]!=`string`}let n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([e,t])=>[e,t]):[[e[0],e[1],e[2]]];if(n.length===0)throw Error("No nodes provided in `addNode`");for(let[e,t,r]of n){if(e in this.channels)throw Error(`${e} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(let t of[`|`,`:`])if(e.includes(t))throw Error(`"${t}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`),e in this.nodes)throw Error(`Node \`${e}\` already present.`);if(e===`__end__`||e===`__start__`)throw Error(`Node \`${e}\` is reserved.`);let n=this._schemaDefinition;r?.input!==void 0&&(n=this._getChannelsFromSchema(r.input)),this._addSchema(n);let i;i=tS.isRunnable(t)?t:typeof t==`function`?new zP({func:t,name:e,trace:!1}):fS(t);let a=r?.cachePolicy,o;a!==void 0&&(o=typeof a==`boolean`?a?{}:!1:a);let s;if(r?.errorHandler!==void 0){if(s=`__error_handler__${e}`,s in this.nodes)throw Error(`Cannot add error handler to node \`${e}\`: the reserved name \`${s}\` is already in use. StateGraph registers \`__error_handler__<nodeName>\` when you pass \`errorHandler\` in addNode options. Remove or rename the existing node with that name (for example, you may have added it manually).`);let t=r.errorHandler,i={runnable:new zP({func:(e,n)=>{let r=n?.configurable?.[lC];return t(e,r,n)},name:s,trace:!1}),metadata:void 0,input:n??this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0};this.nodes[s]=i}let c={runnable:i,retryPolicy:r?.retryPolicy,cachePolicy:o,timeout:BS(r?.timeout),metadata:r?.metadata,input:n??this._schemaDefinition,subgraphs:sF(i)?[i]:r?.subgraphs,ends:r?.ends,defer:r?.defer,errorHandlerNode:s};this.nodes[e]=c}return this}addEdge(e,t){if(typeof e==`string`)return super.addEdge(e,t);this.compiled&&console.warn(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`);for(let t of e){if(t===`__end__`)throw Error(`END cannot be a start node`);if(!Object.keys(this.nodes).some(e=>e===t))throw Error(`Need to add a node named "${t}" first`)}if(t===`__end__`)throw Error(`END cannot be an end node`);if(!Object.keys(this.nodes).some(e=>e===t))throw Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){let t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw Error(`Sequence requires at least one node.`);let n;for(let[e,r,i]of t){if(e in this.nodes)throw Error(`Node names must be unique: node with the name "${e}" already exists.`);let t=e;this.addNode(e,r,i),n!=null&&this.addEdge(n,t),n=t}return this}compile({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:i,name:a,description:o,transformers:s}={}){let c=this._createDefaultErrorHandlerSpec();if(c!==void 0){if(az in this.nodes)throw Error(`Cannot apply a default error handler: the reserved node name \`${az}\` is already in use. setNodeDefaults({ errorHandler }) registers a node with that name; rename the conflicting node.`);this.nodes[az]=c}try{return this._compileResolved({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:i,name:a,description:o,transformers:s,defaultErrorHandlerNode:c===void 0?void 0:az})}finally{c!==void 0&&delete this.nodes[az]}}_compileResolved({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:i,name:a,description:o,transformers:s,defaultErrorHandlerNode:c}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(i)?i:[]]);let l=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),u=l.length===1&&l[0]===iz?iz:l,d=Object.keys(this.channels),f=d.length===1&&d[0]===iz?iz:d,p=this._interrupt,m=new lz({builder:this,checkpointer:e,interruptAfter:i,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[VS]:new lF},inputChannels:VS,outputChannels:u,streamChannels:f,streamMode:`updates`,store:t,cache:n,name:a,description:o,userInterrupt:p,streamTransformers:s});m.attachNode(VS);let h=this._nodeDefaults,g=h.retryPolicy!==void 0||h.cachePolicy!==void 0||h.timeout!==void 0||c!==void 0;for(let[e,t]of Object.entries(this.nodes)){let n=t.isErrorHandler===!0,r=g?{...t,retryPolicy:t.retryPolicy??h.retryPolicy,cachePolicy:n||t.cachePolicy===!1?void 0:t.cachePolicy??h.cachePolicy,timeout:t.timeout??h.timeout,errorHandlerNode:!n&&c!==void 0&&t.errorHandlerNode===void 0?c:t.errorHandlerNode}:t;m.attachNode(e,r)}m.attachBranch(VS,yC,fz(),{withReader:!1});for(let[e]of Object.entries(this.nodes))m.attachBranch(e,yC,fz(),{withReader:!1});for(let[e,t]of this.edges)m.attachEdge(e,t);for(let[e,t]of this.waitingEdges)m.attachEdge(e,t);for(let[e,t]of Object.entries(this.branches))for(let[n,r]of Object.entries(t))m.attachBranch(e,n,r);return m.validate()}};function cz(e){let t={};for(let[n,r]of Object.entries(e))t[n]=EP(r);return t}var lz=class extends OR{description;_metaRegistry=tz;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let n;n=e===`__start__`?Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([e])=>e):Object.keys(this.builder.channels);function r(e){if(FC(e))return e.graph===PC.PARENT?null:e._updateAsTuples();if(Array.isArray(e)&&e.length>0&&e.some(e=>FC(e))){let t=[];for(let n of e)if(FC(n)){if(n.graph===PC.PARENT)continue;t.push(...n._updateAsTuples())}else t.push([iz,n]);return t}else if(e!=null)return[[iz,e]];return null}let i=e,a=async e=>{if(e==null||e.length===0)return e;let t=this.builder._schemaRuntimeDefinition;if(XR.isInstance(t)){let n=new Set(t.getChannelKeys());return Promise.all(e.map(async([e,r])=>{if(!n.has(e))return[e,r];let i=await t.validateInput({[e]:r});return[e,Object.prototype.hasOwnProperty.call(i,e)?i[e]:r]}))}if(Y_(t)){let n=new Set(Object.keys(X_(t)));if(e.filter(([e])=>n.has(e)).length===0)return e;let r=Q_(this._metaRegistry.getExtendedChannelSchemas(t,{withReducerSchema:!0})),i=Q_(t);return e.map(([e,t])=>{if(!n.has(e))return[e,t];let[a,o]=jC(t);if(a){let n=B_(i,{[e]:o});return[e,Object.prototype.hasOwnProperty.call(n,e)?{[AC]:n[e]}:t]}let s=B_(r,{[e]:t});return[e,Object.prototype.hasOwnProperty.call(s,e)?s[e]:t]})}return e};async function o(e){if(!e)return null;if(FC(e))return e.graph===PC.PARENT?null:a(e._updateAsTuples().filter(([e])=>n.includes(e)));if(Array.isArray(e)&&e.length>0&&e.some(FC)){let t=[];for(let r of e)if(FC(r)){if(r.graph===PC.PARENT)continue;t.push(...r._updateAsTuples().filter(([e])=>n.includes(e)))}else{let e=await o(r);e&&t.push(...e??[])}return a(t)}else if(typeof e==`object`&&!Array.isArray(e))return a(Object.entries(e).filter(([e])=>n.includes(e)));else{let t=Array.isArray(e)?`array`:typeof e;throw new ew(`Expected node "${i.toString()}" to return an object or an array containing at least one Command object, received ${t}`,{lc_error_code:`INVALID_GRAPH_NODE_RETURN_VALUE`})}}let s=[{value:GP,mapper:new zP({func:n.length&&n[0]===iz?r:o,trace:!1,recurse:!1})}];if(e===`__start__`)this.nodes[e]=new $P({tags:[vC],triggers:[VS],channels:[VS],writers:[new JP(s,[vC])]});else{let n=t?.input??this.builder._schemaDefinition,r=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(n)).map(e=>[e,e])),i=Object.keys(r).length===1&&iz in r,a=`branch:to:${e}`;this.channels[a]=t?.defer?new xP:new lF(!1);let o=t?.cachePolicy,c=o===!1?void 0:o;this.nodes[e]=new $P({triggers:[a],channels:i?Object.keys(r):r,writers:[new JP(s,[vC])],mapper:i?void 0:e=>Object.fromEntries(Object.entries(e).filter(([e])=>e in r)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:c,timeout:t?.timeout,subgraphs:t?.subgraphs,ends:t?.ends,isErrorHandler:t?.isErrorHandler,errorHandlerNode:t?.errorHandlerNode})}}attachEdge(e,t){if(t!==`__end__`){if(typeof e==`string`)this.nodes[e].writers.push(new JP([{channel:`branch:to:${t}`,value:null}],[vC]));else if(Array.isArray(e)){let n=`join:${e.join(`+`)}:${t}`;this.channels[n]=this.builder.nodes[t].defer?new PR(new Set(e)):new NR(new Set(e)),this.nodes[t].triggers.push(n);for(let t of e)this.nodes[t].writers.push(new JP([{channel:n,value:t}],[vC]))}}}attachBranch(e,t,n,r={withReader:!0}){this.nodes[e].writers.push(n.run(async(t,n)=>{let r=t.filter(e=>e!==HS);if(!r.length)return;let i=r.map(t=>kC(t)?t:{channel:t===`__end__`?t:`branch:to:${t}`,value:e});await JP.doWrite({...n,tags:(n.tags??[]).concat([vC])},i)},r.withReader?e=>ZP.doRead(e,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;let t=this.builder._inputRuntimeDefinition,n=this.builder._schemaRuntimeDefinition;if(XR.isInstance(t)){if(FC(e)){let n=e;return e.update&&(n.update=await t.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),n}return await t.validateInput(e)}if(t===oz&&XR.isInstance(n)){if(FC(e)){let t=e;return e.update&&(t.update=await n.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),t}return await n.validateInput(e)}let r=(()=>{let e=e=>{if(e!=null)return this._metaRegistry.getExtendedChannelSchemas(e,{withReducerSchema:!0})};if(Y_(t))return e(t);if(t===oz)return Y_(n)?Q_(e(n)):void 0})();if(FC(e)){let t=e;if(e.update&&r!=null){let n=Array.isArray(e.update)?Object.fromEntries(e.update):e.update,i=B_(r,n);t.update=Object.fromEntries(Object.keys(n).map(e=>[e,i[e]]))}return t}return r==null?e:B_(r,e)}isInterrupted(e){return NC(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return Y_(t)&&B_(t,e),e}};function uz(e){return typeof e==`object`&&!!e&&e.channels!==void 0}function dz(e){if(kC(e))return[e];let t=[];FC(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(FC));let n=[];for(let e of t){if(e.graph===PC.PARENT)throw new qC(e);kC(e.goto)||typeof e.goto==`string`?n.push(e.goto):Array.isArray(e.goto)&&n.push(...e.goto)}return n}function fz(){return new ER({path:new zP({func:dz,tags:[vC],trace:!1,recurse:!1,name:`<control_branch>`})})}var pz=e=>Array.isArray(e)&&e.every(Kt),mz=e=>typeof e==`object`&&!!e&&`messages`in e&&pz(e.messages),hz=e=>typeof e==`object`&&!!e&&`lg_tool_call`in e,gz=class extends zP{tools;handleToolErrors=!0;trace=!1;constructor(e,t){let{name:n,tags:r,handleToolErrors:i}=t??{};super({name:n,tags:r,func:(e,t)=>this.run(e,t)}),this.tools=e,this.handleToolErrors=i??this.handleToolErrors}async runTool(e,t,n){let r=this.tools.find(t=>t.name===e.name);try{if(r===void 0)throw Error(`Tool "${e.name}" not found.`);let i={...e,type:`tool_call`},a={...t,state:n,toolCallId:e.id??``,config:t,context:t.context,store:t.store??null,writer:t.writer??t.configurable?.writer??null},o=await r.invoke(i,a);return Kt(o)&&o.getType()===`tool`||FC(o)?o:new Xt({status:`success`,name:r.name,content:typeof o==`string`?o:JSON.stringify(o),tool_call_id:e.id})}catch(t){if(!this.handleToolErrors||XC(t))throw t;return new Xt({status:`error`,content:`Error: ${t.message}\n Please fix your mistakes.`,name:e.name,tool_call_id:e.id??``})}}async run(e,t){let n;if(hz(e)){let{lg_tool_call:r,...i}=e;n=[await this.runTool(r,t,i)]}else{let r;if(pz(e))r=e;else if(mz(e))r=e.messages;else throw Error(`ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.`);let i=new Set(r.filter(e=>e.getType()===`tool`).map(e=>e.tool_call_id)),a;for(let e=r.length-1;e>=0;--e){let t=r[e];if(jn(t)){a=t;break}}if(a==null||!jn(a))throw Error(`ToolNode only accepts AIMessages as input.`);n=await Promise.all(a.tool_calls?.filter(e=>e.id==null||!i.has(e.id)).map(n=>this.runTool(n,t,e))??[])}if(!n.some(FC))return Array.isArray(e)?n:{messages:n};let r=[],i=null;for(let t of n)FC(t)?t.graph===PC.PARENT&&Array.isArray(t.goto)&&t.goto.every(e=>kC(e))?i?i.goto.push(...t.goto):i=new PC({graph:PC.PARENT,goto:t.goto}):r.push(t):r.push(Array.isArray(e)?[t]:{messages:[t]});return i&&r.push(i),r}},_z=/<name>(.*?)<\/name>/s,vz=/<content>(.*?)<\/content>/s;function yz(e){if(!(Kt(e)&&(jn(e)||qt(e)&&Mn(e)))||!e.name)return e;let{name:t}=e;if(typeof e.content==`string`)return new An({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:`<name>${t}</name><content>${e.content}</content>`,name:void 0});let n=[],r=0;for(let i of e.content)typeof i==`string`?(r+=1,n.push(`<name>${t}</name><content>${i}</content>`)):typeof i==`object`&&`type`in i&&i.type===`text`?(r+=1,n.push({...i,text:`<name>${t}</name><content>${i.text}</content>`})):n.push(i);return r||n.unshift({type:`text`,text:`<name>${t}</name><content></content>`}),new An({...e.lc_kwargs,content:n,name:void 0})}function bz(e){if(!jn(e)||!e.content)return e;let t=[],n;if(Array.isArray(e.content))t=e.content.filter(e=>{if(e.type===`text`&&typeof e.text==`string`){let t=e.text.match(_z),r=e.text.match(vz);return t&&(!r||r[1]===``)?(n=t[1],!1):!0}return!0}).map(e=>{if(e.type===`text`&&typeof e.text==`string`){let t=e.text.match(_z),r=e.text.match(vz);return!t||!r?e:(n=t[1],{...e,text:r[1]})}return e});else{let r=e.content,i=r.match(_z),a=r.match(vz);if(!i||!a)return e;n=i[1],t=a[1]}return new An({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:n})}function xz(e,t){let n,r;if(t===`inline`)n=yz,r=bz;else throw Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);function i(e){return e.map(n)}return aS.from([lS.from(i),e,lS.from(r)])}function Sz(e){if(typeof e==`string`||Kt(e)&&e._getType()===`system`)return e;if(typeof e==`function`)return async t=>e(t.messages);if(tS.isRunnable(e))return lS.from(e=>e.messages).pipe(e);throw Error(`Unexpected type for messageModifier: ${typeof e}`)}var Cz=`prompt`;function wz(e){let t;if(e==null)t=lS.from(e=>e.messages).withConfig({runName:Cz});else if(typeof e==`string`){let n=new qn(e);t=lS.from(e=>[n,...e.messages??[]]).withConfig({runName:Cz})}else if(Kt(e)&&e._getType()===`system`)t=lS.from(t=>[e,...t.messages]).withConfig({runName:Cz});else if(typeof e==`function`)t=lS.from(e).withConfig({runName:Cz});else if(tS.isRunnable(e))t=e;else throw Error(`Got unexpected type for 'prompt': ${typeof e}`);return t}function Tz(e){return tS.isRunnable(e)}function Ez(e,t,n){if([e,t,n].filter(e=>e!=null).length>1)throw Error(`Expected only one of prompt, stateModifier, or messageModifier, got multiple values`);let r=e;return t==null?n!=null&&(r=Sz(n)):r=t,wz(r)}function Dz(e){return`invoke`in e&&typeof e.invoke==`function`&&`_modelType`in e}function Oz(e){return`_queuedMethodOperations`in e&&`_model`in e&&typeof e._model==`function`}function kz(e){return Dz(e)?`bindTools`in e&&typeof e.bindTools==`function`:!1}async function Az(e,t){let n=e;if(aS.isRunnableSequence(n)&&(n=n.steps.find(e=>nS.isRunnableBinding(e)||Dz(e)||Oz(e))||n),Oz(n)&&(n=await n._model()),!nS.isRunnableBinding(n))return!0;let r=n.kwargs!=null&&typeof n.kwargs==`object`&&`tools`in n.kwargs&&Array.isArray(n.kwargs.tools)?n.kwargs.tools??null:n.config!=null&&typeof n.config==`object`&&`tools`in n.config&&Array.isArray(n.config.tools)?n.config.tools??null:null;if(r!=null&&r.length===1&&`functionDeclarations`in r[0]&&(r=r[0].functionDeclarations),r==null)return!0;if(t.length!==r.length)throw Error(`Number of tools in the model.bindTools() and tools passed to createReactAgent must match`);let i=new Set(t.flatMap(e=>Tz(e)?e.name:[])),a=new Set;for(let e of r){let t;if(`type`in e&&e.type===`function`)t=e.function.name;else if(`name`in e)t=e.name;else if(`toolSpec`in e&&`name`in e.toolSpec)t=e.toolSpec.name;else continue;t&&a.add(t)}let o=[...i].filter(e=>!a.has(e));if(o.length>0)throw Error(`Missing tools '${o}' in the model.bindTools().Tools in the model.bindTools() must match the tools passed to createReactAgent.`);return!1}var jz=(e,t)=>{if(kz(e))return e.bindTools(t);if(nS.isRunnableBinding(e)&&kz(e.bound)){let n=e.bound.bindTools(t);return nS.isRunnableBinding(n)?new nS({bound:n.bound,config:{...e.config,...n.config},kwargs:{...e.kwargs,...n.kwargs},configFactories:n.configFactories??e.configFactories}):new nS({bound:n,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};async function Mz(e,t){let n=jz(e,t);if(n)return n;if(Oz(e)){let n=jz(await e._model(),t);if(n)return n}if(aS.isRunnableSequence(e)){let n=e.steps.findIndex(e=>nS.isRunnableBinding(e)||Dz(e)||Oz(e));if(n>=0){let r=jz(e.steps[n],t);if(r){let t=e.steps.slice();return t.splice(n,1,r),aS.from(t)}}}throw Error(`llm ${e} must define bindTools method.`)}async function Nz(e){let t=e;if(aS.isRunnableSequence(t)&&(t=t.steps.find(e=>nS.isRunnableBinding(e)||Dz(e)||Oz(e))||t),Oz(t)&&(t=await t._model()),nS.isRunnableBinding(t)&&(t=t.bound),!Dz(t))throw Error(`Expected \`llm\` to be a ChatModel or RunnableBinding (e.g. llm.bind_tools(...)) with invoke() and generate() methods, got ${t.constructor.name}`);return t}var Pz=()=>TP.Root({messages:TP({reducer:ZR,default:()=>[]}),structuredResponse:TP}),Fz=TP.Root({llmInputMessages:TP({reducer:(e,t)=>ZR([],t),default:()=>[]})});function Iz(e){let{llm:t,tools:n,messageModifier:r,stateModifier:i,prompt:a,stateSchema:o,contextSchema:s,checkpointSaver:c,checkpointer:l,interruptBefore:u,interruptAfter:d,store:f,responseFormat:p,preModelHook:m,postModelHook:h,name:g,description:_,version:v=`v1`,includeAgentName:y}=e,b,ee;Array.isArray(n)?(b=n,ee=new gz(b.filter(Tz))):(b=n.tools,ee=n);let te=null,ne=async e=>{if(te)return te;let t;t=await Az(e,b)?await Mz(e,b):e;let n=Ez(a,i,r),o=y===`inline`?xz(t,y):t;return te=n.pipe(o),te},x=async(e,t,n)=>{let o=await e(t,n);return Ez(a,i,r).pipe(y===`inline`?xz(o,y):o)},re=new Set(b.filter(Tz).filter(e=>`returnDirect`in e&&e.returnDirect).map(e=>e.name));function ie(e){let{messages:t,llmInputMessages:n,...r}=e;return n!=null&&n.length>0?{messages:n,...r}:{messages:t,...r}}let ae=async(e,n)=>{if(p==null)throw Error(`Attempted to generate structured output with no passed response schema. Please contact us for help.`);let r=[...e.messages],i,a=typeof t==`function`?await t(e,n):await Nz(t);if(!Dz(a))throw Error(`Expected \`llm\` to be a ChatModel with .withStructuredOutput() method, got ${a.constructor.name}`);if(typeof p==`object`&&`schema`in p){let{prompt:e,schema:t,...n}=p;i=a.withStructuredOutput(t,n),e!=null&&r.unshift(new qn({content:e}))}else i=a.withStructuredOutput(p);let o=await i.invoke(r,n);if(o==null)throw Error("Failed to parse structured response against the provided `responseFormat` schema: the structured-output parser returned null/undefined, which usually means the model output did not satisfy the schema.");return{structuredResponse:o}},oe=async(e,n)=>{let r=await(typeof t==`function`?await x(t,e,n):await ne(t)).invoke(ie(e),n);return r.name=g,r.lc_kwargs.name=g,{messages:[r]}},se=new sz(o??Pz(),s).addNode(`tools`,ee);if(!(`messages`in se._schemaDefinition))throw Error("Missing required `messages` key in state schema.");let ce=se,le=e=>Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null)),S=`agent`,C;return m==null?S=`agent`:(ce.addNode(`pre_model_hook`,m).addEdge(`pre_model_hook`,`agent`),S=`pre_model_hook`,C=TP.Root({...se._schemaDefinition,...Fz.spec})),ce.addNode(`agent`,oe,{input:C}).addEdge(VS,S),h!=null&&ce.addNode(`post_model_hook`,h).addEdge(`agent`,`post_model_hook`).addConditionalEdges(`post_model_hook`,e=>{let{messages:t}=e,n=new Set(t.filter($t).map(e=>e.tool_call_id)),r;for(let e=t.length-1;e>=0;--e){let n=t[e];if(jn(n)){r=n;break}}let i=r?.tool_calls?.filter(e=>e.id==null||!n.has(e.id))??[],a=t[t.length-1];return i.length>0?v===`v2`?i.map(t=>new OC(`tools`,{...e,lg_tool_call:t})):`tools`:a&&$t(a)?S:p==null?HS:`generate_structured_response`},le({tools:`tools`,[S]:S,generate_structured_response:p==null?null:`generate_structured_response`,[HS]:p==null?HS:null})),p!==void 0&&se.addNode(`generate_structured_response`,ae).addEdge(`generate_structured_response`,HS),h??ce.addConditionalEdges(`agent`,e=>{let{messages:t}=e,n=t[t.length-1];return!jn(n)||!n.tool_calls?.length?p==null?HS:`generate_structured_response`:v===`v2`?n.tool_calls.map(t=>new OC(`tools`,{...e,lg_tool_call:t})):`tools`},le({tools:`tools`,generate_structured_response:p==null?null:`generate_structured_response`,[HS]:p==null?HS:null})),re.size>0?ce.addConditionalEdges(`tools`,e=>{let t=e;for(let e=t.messages.length-1;e>=0;--e){let n=t.messages[e];if(!$t(n))break;if(n.name!==void 0&&re.has(n.name))return HS}return S},le({[S]:S,[HS]:HS})):ce.addEdge(`tools`,S),ce.compile({checkpointer:l??c,interruptBefore:u,interruptAfter:d,store:f,name:g,description:_})}function Lz(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}function U(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function W(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var Rz=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Rz=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function zz(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var Bz=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},G=class extends Error{},Vz=class e extends G{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new Uz({message:r,cause:Bz(n)});let a=n?.error;return t===400?new Gz(t,a,r,i):t===401?new Kz(t,a,r,i):t===403?new qz(t,a,r,i):t===404?new Jz(t,a,r,i):t===409?new Yz(t,a,r,i):t===422?new Xz(t,a,r,i):t===429?new Zz(t,a,r,i):t>=500?new Qz(t,a,r,i):new e(t,a,r,i)}},Hz=class extends Vz{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},Uz=class extends Vz{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},Wz=class extends Uz{constructor({message:e}={}){super({message:e??`Request timed out.`})}},Gz=class extends Vz{},Kz=class extends Vz{},qz=class extends Vz{},Jz=class extends Vz{},Yz=class extends Vz{},Xz=class extends Vz{},Zz=class extends Vz{},Qz=class extends Vz{},$z=class extends G{constructor(){super(`Could not parse response content as the length limit was reached`)}},eB=class extends G{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},tB=class extends Error{constructor(e){super(e)}},nB=class extends Vz{constructor(e,t,n){let r=`OAuth2 authentication error`,i;if(t&&typeof t==`object`){let e=t;i=e.error;let n=e.error_description;n&&typeof n==`string`?r=n:i&&(r=i)}super(e,t,r,n),this.error_code=i}},rB=class extends G{constructor(e,t,n){super(e),this.provider=t,this.cause=n}},iB=/^[a-z][a-z0-9+.-]*:/i,aB=e=>iB.test(e),oB=e=>(oB=Array.isArray,oB(e)),sB=oB;function cB(e){return typeof e==`object`?e??{}:{}}function lB(e){if(!e)return!0;for(let t in e)return!1;return!0}function uB(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function dB(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var fB=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new G(`${e} must be an integer`);if(t<0)throw new G(`${e} must be a positive integer`);return t},pB=e=>{try{return JSON.parse(e)}catch{return}},mB=e=>new Promise(t=>setTimeout(t,e)),hB=`6.45.0`,gB=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function _B(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var vB=()=>{let e=_B();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":hB,"X-Stainless-OS":xB(Deno.build.os),"X-Stainless-Arch":bB(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":hB,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":hB,"X-Stainless-OS":xB(globalThis.process.platform??`unknown`),"X-Stainless-Arch":bB(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=yB();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":hB,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":hB,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function yB(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{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/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var bB=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,xB=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),SB,CB=()=>SB??=vB();function wB(){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 TB(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function EB(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return TB({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function DB(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function OB(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var kB=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),AB=`RFC3986`,jB=e=>String(e),MB={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:jB},NB=(e,t)=>(NB=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),NB(e,t)),PB=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),FB=1024,IB=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=FB){let t=a.length>=FB?a.slice(e,e+FB):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=PB[r];continue}if(r<2048){n[n.length]=PB[192|r>>6]+PB[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=PB[224|r>>12]+PB[128|r>>6&63]+PB[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=PB[240|r>>18]+PB[128|r>>12&63]+PB[128|r>>6&63]+PB[128|r&63]}o+=n.join(``)}return o};function LB(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function RB(e,t){if(oB(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var zB={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},BB=function(e,t){Array.prototype.push.apply(e,oB(t)?t:[t])},VB,HB={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:IB,encodeValuesOnly:!1,format:AB,formatter:jB,indices:!1,serializeDate(e){return(VB??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function UB(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var WB={};function GB(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,ee=!1;for(;(y=y.get(WB))!==void 0&&!ee;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);ee=!0}y.get(WB)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&oB(v)&&(v=RB(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,HB.encoder,g,`key`,p):t;v=``}if(UB(v)||LB(v)){if(c){let e=h?t:c(t,HB.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,HB.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let te=[];if(v===void 0)return te;let ne;if(n===`comma`&&oB(v))h&&c&&(v=RB(v,c)),ne=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(oB(l))ne=l;else{let e=Object.keys(v);ne=u?e.sort(u):e}let x=s?String(t).replace(/\./g,`%2E`):String(t),re=r&&oB(v)&&v.length===1?x+`[]`:x;if(i&&oB(v)&&v.length===0)return re+`[]`;for(let t=0;t<ne.length;++t){let y=ne[t],ee=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&ee===null)continue;let x=d&&s?y.replace(/\./g,`%2E`):y,ie=oB(v)?typeof n==`function`?n(re,x):re:re+(d?`.`+x:`[`+x+`]`);_.set(e,b);let ae=new WeakMap;ae.set(WB,_),BB(te,GB(ee,ie,n,r,i,a,o,s,n===`comma`&&h&&oB(v)?null:c,l,u,d,f,p,m,h,g,ae))}return te}function KB(e=HB){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||HB.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=AB;if(e.format!==void 0){if(!NB(MB,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=MB[n],i=HB.filter;(typeof e.filter==`function`||oB(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in zB?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:HB.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:HB.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:HB.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:HB.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:HB.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?HB.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:HB.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:HB.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:HB.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:HB.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:HB.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:HB.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:HB.strictNullHandling}}function qB(e,t={}){let n=e,r=KB(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):oB(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=zB[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||BB(o,GB(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function JB(e){return qB(e,{arrayFormat:`brackets`})}function YB(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var XB;function ZB(e){let t;return(XB??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var QB;function $B(e){let t;return(QB??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var eV,tV,nV=class{constructor(){eV.set(this,void 0),tV.set(this,void 0),U(this,eV,new Uint8Array,`f`),U(this,tV,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?ZB(e):e;U(this,eV,YB([W(this,eV,`f`),t]),`f`);let n=[],r;for(;(r=rV(W(this,eV,`f`),W(this,tV,`f`)))!=null;){if(r.carriage&&W(this,tV,`f`)==null){U(this,tV,r.index,`f`);continue}if(W(this,tV,`f`)!=null&&(r.index!==W(this,tV,`f`)+1||r.carriage)){n.push($B(W(this,eV,`f`).subarray(0,W(this,tV,`f`)-1))),U(this,eV,W(this,eV,`f`).subarray(W(this,tV,`f`)),`f`),U(this,tV,null,`f`);continue}let e=W(this,tV,`f`)===null?r.preceding:r.preceding-1,t=$B(W(this,eV,`f`).subarray(0,e));n.push(t),U(this,eV,W(this,eV,`f`).subarray(r.index),`f`),U(this,tV,null,`f`)}return n}flush(){return W(this,eV,`f`).length?this.decode(`
|
|
191
|
+
`):[]}};eV=new WeakMap,tV=new WeakMap,nV.NEWLINE_CHARS=new Set([`
|
|
192
|
+
`,`\r`]),nV.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function rV(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function iV(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}var aV={off:0,error:200,warn:300,info:400,debug:500},oV=(e,t,n)=>{if(e){if(uB(aV,e))return e;dV(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(aV))}`)}};function sV(){}function cV(e,t,n){return!t||aV[e]>aV[n]?sV:t[e].bind(t)}var lV={error:sV,warn:sV,info:sV,debug:sV},uV=new WeakMap;function dV(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return lV;let r=uV.get(t);if(r&&r[0]===n)return r[1];let i={error:cV(`error`,t,n),warn:cV(`warn`,t,n),info:cV(`info`,t,n),debug:cV(`debug`,t,n)};return uV.set(t,[n,i]),i}var fV=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`api-key`||e.toLowerCase()===`x-api-key`||e.toLowerCase()===`x-amz-security-token`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),pV,mV=class e{constructor(e,t,n){this.iterator=e,pV.set(this,void 0),this.controller=t,U(this,pV,n,`f`)}static fromSSEResponse(t,n,r,i){let a=!1,o=r?dV(r):console;async function*s(){if(a)throw new G("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let e=!1;try{for await(let r of hV(t,n))if(!e){if(r.data.startsWith(`[DONE]`)){e=!0;continue}if(r.event===null||!r.event.startsWith(`thread.`)){let e;try{e=JSON.parse(r.data)}catch(e){throw o.error(`Could not parse message into JSON:`,r.data),o.error(`From chunk:`,r.raw),e}if(e&&e.error)throw new Vz(void 0,e.error,void 0,t.headers);yield i?{event:r.event,data:e}:e}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error(`Could not parse message into JSON:`,r.data),console.error(`From chunk:`,r.raw),e}if(r.event==`error`)throw new Vz(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}e=!0}catch(e){if(zz(e))return;throw e}finally{e||n.abort()}}return new e(s,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new nV,n=DB(t);for await(let t of n)for(let n of e.decode(t))yield n;for(let t of e.flush())yield t}async function*o(){if(i)throw new G("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(zz(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(pV=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,W(this,pV,`f`)),new e(()=>i(n),this.controller,W(this,pV,`f`))]}toReadableStream(){let e=this,t;return TB({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=ZB(JSON.stringify(n)+`
|
|
193
|
+
`);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*hV(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new G(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new G(`Attempted to iterate over a response with no body`);let n=new _V,r=new nV,i=DB(e.body);for await(let e of gV(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*gV(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?ZB(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=iV(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var _V=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
|
|
194
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=vV(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function vV(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function yV(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return dV(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):mV.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:bV(await n.json(),n):await n.text()})();return dV(e).debug(`[${r}] response parsed`,fV({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function bV(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`x-request-id`),enumerable:!1})}var xV,SV=class e extends Promise{constructor(e,t,n=yV){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,xV.set(this,void 0),U(this,xV,e,`f`)}_thenUnwrap(t){return new e(W(this,xV,`f`),this.responsePromise,async(e,n)=>bV(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(W(this,xV,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};xV=new WeakMap;var CV,wV=class{constructor(e,t,n,r){CV.set(this,void 0),U(this,CV,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new G("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await W(this,CV,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(CV=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},TV=class extends SV{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await yV(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},EV=class extends wV{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},DV=class extends wV{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...cB(this.options.query),after:t}}:null}},OV=class extends wV{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...cB(this.options.query),after:e}}:null}},kV=class extends wV{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...cB(this.options.query),after:e}}:null}},AV={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},jV=`urn:ietf:params:oauth:grant-type:token-exchange`,MV=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??wB()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e={grant_type:jV,subject_token:await this.config.provider.getToken(),subject_token_type:AV[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(e.client_id=this.config.clientId);let t=await this.fetch(this.tokenExchangeUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.text(),n;try{n=JSON.parse(e)}catch{}throw t.status===400||t.status===401||t.status===403?new nB(t.status,n,t.headers):Vz.generate(t.status,n,`Token exchange failed with status ${t.status}`,t.headers)}let n=await t.json();if(typeof n!=`object`||!n||!(`access_token`in n)||typeof n.access_token!=`string`||n.access_token.trim().length===0)throw new G(`Token exchange response missing 'access_token' field`);let r=n.access_token,i=n.expires_in??3600,a=Date.now()+i*1e3;return this.cachedToken={token:r,expiresAt:a},r}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let t=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-t}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}},NV=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function PV(e,t,n){return NV(),new File(e,t??`unknown_file`,n)}function FV(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}var IV=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,LV=async(e,t)=>WV(e.body)?{...e,body:await VV(e.body,t)}:e,RV=async(e,t)=>({...e,body:await VV(e.body,t)}),zV=new WeakMap;function BV(e){let t=typeof e==`function`?e:e.fetch,n=zV.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return zV.set(t,r),r}var VV=async(e,t)=>{if(!await BV(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>GV(n,e,t))),n},HV=e=>e instanceof Blob&&`name`in e,UV=e=>typeof e==`object`&&!!e&&(e instanceof Response||IV(e)||HV(e)),WV=e=>{if(UV(e))return!0;if(Array.isArray(e))return e.some(WV);if(e&&typeof e==`object`){for(let t in e)if(WV(e[t]))return!0}return!1},GV=async(e,t,n)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response)e.append(t,PV([await n.blob()],FV(n)));else if(IV(n))e.append(t,PV([await new Response(EB(n)).blob()],FV(n)));else if(HV(n))e.append(t,n,FV(n));else if(Array.isArray(n))await Promise.all(n.map(n=>GV(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>GV(e,`${t}[${n}]`,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},KV=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,qV=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&KV(e),JV=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function YV(e,t,n){if(NV(),e=await e,qV(e))return e instanceof File?e:PV([await e.arrayBuffer()],e.name);if(JV(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),PV(await XV(r),t,n)}let r=await XV(e);if(t||=FV(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return PV(r,t,n)}async function XV(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(KV(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(IV(e))for await(let n of e)t.push(...await XV(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${ZV(e)}`)}return t}function ZV(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var K=class{constructor(e){this._client=e}};function QV(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var $V=Object.freeze(Object.create(null)),q=((e=QV)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??$V)??$V)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new G(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
|
|
195
|
+
`)}\n${a}\n${t}`)}return a})(QV),eH=class extends K{list(e,t={},n){return this._client.getAPIList(q`/chat/completions/${e}/messages`,DV,{query:t,...n,__security:{bearerAuth:!0}})}};function tH(e){return e!==void 0&&`function`in e&&e.function!==void 0}function nH(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:`auto-parseable-response-format`,enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function rH(e){return e?.$brand===`auto-parseable-response-format`}function iH(e){return e?.$brand===`auto-parseable-tool`}function aH(e,t){return!t||!uH(t)?{...e,choices:e.choices.map(e=>(dH(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:oH(e,t)}function oH(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new $z;if(e.finish_reason===`content_filter`)throw new eB;return dH(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>cH(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?sH(t,e.message.content):null}}});return{...e,choices:n}}function sH(e,t){return e.response_format?.type===`json_schema`&&e.response_format?.type===`json_schema`?`$parseRaw`in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function cH(e,t){let n=e.tools?.find(e=>tH(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:iH(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function lH(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>tH(e)&&e.function?.name===t.function.name);return tH(n)&&(iH(n)||n?.function.strict||!1)}function uH(e){return rH(e.response_format)?!0:e.tools?.some(e=>iH(e)||e.type===`function`&&e.function.strict===!0)??!1}function dH(e){for(let t of e||[])if(t.type!==`function`)throw new G(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function fH(e){for(let t of e??[]){if(t.type!==`function`)throw new G(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new G(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var pH=e=>e?.role===`assistant`,mH=e=>e?.role===`tool`,hH,gH,_H,vH,yH,bH,xH,SH,CH,wH,TH,EH,DH,OH,kH,AH=class{constructor(){hH.add(this),this.controller=new AbortController,gH.set(this,void 0),_H.set(this,()=>{}),vH.set(this,()=>{}),yH.set(this,void 0),bH.set(this,()=>{}),xH.set(this,()=>{}),SH.set(this,{}),CH.set(this,[]),wH.set(this,!1),TH.set(this,!1),EH.set(this,!1),DH.set(this,!1),U(this,gH,new Promise((e,t)=>{U(this,_H,e,`f`),U(this,vH,t,`f`)}),`f`),U(this,yH,new Promise((e,t)=>{U(this,bH,e,`f`),U(this,xH,t,`f`)}),`f`),W(this,gH,`f`).catch(()=>{}),W(this,yH,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},W(this,hH,`m`,kH).bind(this))},0)}_connected(){this.ended||(W(this,_H,`f`).call(this),this._emit(`connect`))}get ended(){return W(this,wH,`f`)}get errored(){return W(this,TH,`f`)}get aborted(){return W(this,EH,`f`)}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let t=()=>this.controller.abort();e.addEventListener(`abort`,t,{once:!0}),W(this,CH,`f`).push({signal:e,listener:t})}on(e,t){return(W(this,SH,`f`)[e]||(W(this,SH,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=W(this,SH,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(W(this,SH,`f`)[e]||(W(this,SH,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{U(this,DH,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){U(this,DH,!0,`f`),await W(this,yH,`f`)}_emit(e,...t){if(W(this,wH,`f`))return;e===`end`&&(W(this,hH,`m`,OH).call(this),U(this,wH,!0,`f`),W(this,bH,`f`).call(this));let n=W(this,SH,`f`)[e];if(n&&(W(this,SH,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!W(this,DH,`f`)&&!n?.length&&Promise.reject(e),W(this,vH,`f`).call(this,e),W(this,xH,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!W(this,DH,`f`)&&!n?.length&&Promise.reject(e),W(this,vH,`f`).call(this,e),W(this,xH,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};gH=new WeakMap,_H=new WeakMap,vH=new WeakMap,yH=new WeakMap,bH=new WeakMap,xH=new WeakMap,SH=new WeakMap,CH=new WeakMap,wH=new WeakMap,TH=new WeakMap,EH=new WeakMap,DH=new WeakMap,hH=new WeakSet,OH=function(){for(let{signal:e,listener:t}of W(this,CH,`f`).splice(0))e.removeEventListener(`abort`,t)},kH=function(e){if(U(this,TH,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=new Hz),e instanceof Hz)return U(this,EH,!0,`f`),this._emit(`abort`,e);if(e instanceof G)return this._emit(`error`,e);if(e instanceof Error){let t=new G(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new G(String(e)))};function jH(e){return typeof e.parse==`function`}var MH,NH,PH,FH,IH,LH,RH,zH,BH=10,VH=class extends AH{constructor(){super(...arguments),MH.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),mH(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(pH(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new G(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),W(this,MH,`m`,NH).call(this)}async finalMessage(){return await this.done(),W(this,MH,`m`,PH).call(this)}async finalFunctionToolCall(){return await this.done(),W(this,MH,`m`,FH).call(this)}async finalFunctionToolCallResult(){return await this.done(),W(this,MH,`m`,IH).call(this)}async totalUsage(){return await this.done(),W(this,MH,`m`,LH).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=W(this,MH,`m`,PH).call(this);t&&this._emit(`finalMessage`,t);let n=W(this,MH,`m`,NH).call(this);n&&this._emit(`finalContent`,n);let r=W(this,MH,`m`,FH).call(this);r&&this._emit(`finalFunctionToolCall`,r);let i=W(this,MH,`m`,IH).call(this);i!=null&&this._emit(`finalFunctionToolCallResult`,i),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,W(this,MH,`m`,LH).call(this))}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),W(this,MH,`m`,RH).call(this,t);let r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(oH(r,t))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n,r){let i=`tool`,{tool_choice:a=`auto`,stream:o,...s}=t,c=typeof a!=`string`&&a.type===`function`&&a?.function?.name,{maxChatCompletions:l=BH,afterCompletion:u}=r||{},d=t.tools.map(e=>{if(iH(e)){if(!e.$callback)throw new G("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),f={};for(let e of d)e.type===`function`&&(f[e.function.name||e.function.function.name]=e.function);let p=`tools`in t?d.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of t.messages)this._addMessage(e,!1);let m=async e=>{if(e.type!==`function`)return{message:void 0,functionCalled:!1};let t=e.id,{name:r,arguments:a}=e.function,o=f[r];if(!o){let e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(f).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;return{message:{role:i,tool_call_id:t,content:e},functionCalled:!1}}if(c&&c!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(c)} requested. Please try again`;return{message:{role:i,tool_call_id:t,content:e},functionCalled:!1}}let s;if(jH(o)){let e;try{e=await o.parse(a)}catch(e){let n=e instanceof Error?e.message:String(e);return{message:{role:i,tool_call_id:t,content:n},functionCalled:!1}}s=await o.function(e,n)}else s=await o.function(a,n);let l=W(this,MH,`m`,zH).call(this,s);return{message:{role:i,tool_call_id:t,content:l},functionCalled:!0}};for(let i=0;i<l;++i){let i=await this._createChatCompletion(e,{...s,tool_choice:a,tools:p,messages:[...this.messages]},r),o=i.choices[0]?.message;if(!o)throw new G(`missing message in ChatCompletion response`);if(!o.tool_calls?.length){await u?.(i,n);return}if(c||t.parallel_tool_calls===!1)for(let e of o.tool_calls){let t=await m(e);if(t.message&&this._addMessage(t.message),c&&t.functionCalled){await u?.(i,n);return}}else{let e=await Promise.allSettled(o.tool_calls.map(m));for(let t of e)if(t.status===`rejected`)throw t.reason;for(let t of e)t.status===`fulfilled`&&t.value.message&&this._addMessage(t.value.message)}await u?.(i,n)}}};MH=new WeakSet,NH=function(){return W(this,MH,`m`,PH).call(this).content??null},PH=function(){let e=this.messages.length;for(;e-->0;){let t=this.messages[e];if(pH(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new G(`stream ended without producing a ChatCompletionMessage with role=assistant`)},FH=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(pH(t)&&t?.tool_calls?.length)for(let e=t.tool_calls.length-1;e>=0;e--){let n=t.tool_calls[e];if(n?.type===`function`)return n.function}}},IH=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(mH(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},LH=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},RH=function(e){if(e.n!=null&&e.n>1)throw new G(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},zH=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var HH=class e extends VH{static runTools(t,n,r){let i=new e,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),pH(e)&&e.content&&this._emit(`content`,e.content)}},UH={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},WH=class extends Error{},GH=class extends Error{};function KH(e,t=UH.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return qH(e.trim(),t)}var qH=(e,t)=>{let n=e.length,r=0,i=e=>{throw new WH(`${e} at position ${r}`)},a=e=>{throw new GH(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||UH.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||UH.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||UH.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||UH.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||UH.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||UH.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`&&!s,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(UH.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&UH.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(UH.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(UH.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(UH.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&UH.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(UH.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r==n&&!(UH.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&UH.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
|
|
196
|
+
\r `.includes(e[r]);)r++};return o()},JH=e=>KH(e,UH.ALL^UH.NUM),YH,XH,ZH,QH,$H,eU,tU,nU,rU,iU,aU,oU,sU=class e extends VH{constructor(e){super(),YH.add(this),XH.set(this,void 0),ZH.set(this,void 0),QH.set(this,void 0),U(this,XH,e,`f`),U(this,ZH,[],`f`)}get currentChatCompletionSnapshot(){return W(this,QH,`f`)}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){let i=new e(n);return i._run(()=>i._runChatCompletion(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createChatCompletion(e,t,n){super._createChatCompletion,this._listenForAbort(n?.signal),W(this,YH,`m`,$H).call(this);let r=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let e of r)W(this,YH,`m`,tU).call(this,e);if(r.controller.signal?.aborted)throw new Hz;return this._addChatCompletion(W(this,YH,`m`,iU).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),W(this,YH,`m`,$H).call(this),this._connected();let n=mV.fromReadableStream(e,this.controller),r;for await(let e of n)r&&r!==e.id&&this._addChatCompletion(W(this,YH,`m`,iU).call(this)),W(this,YH,`m`,tU).call(this,e),r=e.id;if(n.controller.signal?.aborted)throw new Hz;return this._addChatCompletion(W(this,YH,`m`,iU).call(this))}[(XH=new WeakMap,ZH=new WeakMap,QH=new WeakMap,YH=new WeakSet,$H=function(){this.ended||U(this,QH,void 0,`f`)},eU=function(e){let t=W(this,ZH,`f`)[e.index];return t||(t={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,ZH,`f`)[e.index]=t,t)},tU=function(e){if(this.ended)return;let t=W(this,YH,`m`,oU).call(this,e);this._emit(`chunk`,e,t);for(let n of e.choices){let e=t.choices[n.index];n.delta.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,n.delta.content,e.message.content),this._emit(`content.delta`,{delta:n.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),n.delta.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:n.delta.refusal,snapshot:e.message.refusal}),n.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),n.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let r=W(this,YH,`m`,eU).call(this,e);e.finish_reason&&(W(this,YH,`m`,rU).call(this,e),r.current_tool_call_index!=null&&W(this,YH,`m`,nU).call(this,e,r.current_tool_call_index));for(let t of n.delta.tool_calls??[])r.current_tool_call_index!==t.index&&(W(this,YH,`m`,rU).call(this,e),r.current_tool_call_index!=null&&W(this,YH,`m`,nU).call(this,e,r.current_tool_call_index)),r.current_tool_call_index=t.index;for(let t of n.delta.tool_calls??[]){let n=e.message.tool_calls?.[t.index];n?.type&&(n?.type===`function`?this._emit(`tool_calls.function.arguments.delta`,{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??``}):n?.type)}}},nU=function(e,t){if(W(this,YH,`m`,eU).call(this,e).done_tool_calls.has(t))return;let n=e.message.tool_calls?.[t];if(!n)throw Error(`no tool call snapshot`);if(!n.type)throw Error("tool call snapshot missing `type`");if(n.type===`function`){let e=W(this,XH,`f`)?.tools?.find(e=>tH(e)&&e.function.name===n.function.name);this._emit(`tool_calls.function.arguments.done`,{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:iH(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},rU=function(e){let t=W(this,YH,`m`,eU).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;let n=W(this,YH,`m`,aU).call(this);this._emit(`content.done`,{content:e.message.content,parsed:n?n.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit(`refusal.done`,{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},iU=function(){if(this.ended)throw new G(`stream has ended, this shouldn't happen`);let e=W(this,QH,`f`);if(!e)throw new G(`request ended without sending any chunks`);return U(this,QH,void 0,`f`),U(this,ZH,[],`f`),cU(e,W(this,XH,`f`))},aU=function(){let e=W(this,XH,`f`)?.response_format;return rH(e)?e:null},oU=function(e){var t,n,r,i;let a=W(this,QH,`f`),{choices:o,...s}=e;a?Object.assign(a,s):a=U(this,QH,{...s,choices:[]},`f`);for(let{delta:o,finish_reason:s,index:c,logprobs:l=null,...u}of e.choices){let e=a.choices[c];if(e||=a.choices[c]={finish_reason:s,index:c,message:{},logprobs:l,...u},l)if(!e.logprobs)e.logprobs=Object.assign({},l);else{let{content:r,refusal:i,...a}=l;Object.assign(e.logprobs,a),r&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...r)),i&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...i))}if(s&&(e.finish_reason=s,W(this,XH,`f`)&&uH(W(this,XH,`f`)))){if(s===`length`)throw new $z;if(s===`content_filter`)throw new eB}if(Object.assign(e,u),!o)continue;let{content:d,refusal:f,function_call:p,role:m,tool_calls:h,...g}=o;if(Object.assign(e.message,g),f&&(e.message.refusal=(e.message.refusal||``)+f),m&&(e.message.role=m),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((r=e.message.function_call).arguments??(r.arguments=``),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),d&&(e.message.content=(e.message.content||``)+d,!e.message.refusal&&W(this,YH,`m`,aU).call(this)&&(e.message.parsed=e.message.content.trim()?JH(e.message.content):null)),h){e.message.tool_calls||(e.message.tool_calls=[]);for(let{index:t,id:n,type:r,function:a,...o}of h){let s=(i=e.message.tool_calls)[t]??(i[t]={});Object.assign(s,o),n&&(s.id=n),r&&(s.type=r),a&&(s.function??={name:a.name??``,arguments:``}),a?.name&&(s.function.name=a.name),a?.arguments&&(s.function.arguments+=a.arguments,lH(W(this,XH,`f`),s)&&(s.function.parsed_arguments=JH(s.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`chunk`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new mV(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function cU(e,t){let{id:n,choices:r,created:i,model:a,system_fingerprint:o,...s}=e;return aH({...s,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:i,...a})=>{if(!n)throw new G(`missing finish_reason for choice ${r}`);let{content:o=null,function_call:s,tool_calls:c,...l}=t,u=t.role;if(!u)throw new G(`missing role for choice ${r}`);if(s){let{arguments:e,name:c}=s;if(e==null)throw new G(`missing function_call.arguments for choice ${r}`);if(!c)throw new G(`missing function_call.name for choice ${r}`);return{...a,message:{content:o,function_call:{arguments:e,name:c},role:u,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}return c?{...a,index:r,finish_reason:n,logprobs:i,message:{...l,role:u,content:o,refusal:t.refusal??null,tool_calls:c.map((t,n)=>{let{function:i,type:a,id:o,...s}=t,{arguments:c,name:l,...u}=i||{};if(o==null)throw new G(`missing choices[${r}].tool_calls[${n}].id\n${lU(e)}`);if(a==null)throw new G(`missing choices[${r}].tool_calls[${n}].type\n${lU(e)}`);if(l==null)throw new G(`missing choices[${r}].tool_calls[${n}].function.name\n${lU(e)}`);if(c==null)throw new G(`missing choices[${r}].tool_calls[${n}].function.arguments\n${lU(e)}`);return{...s,id:o,type:a,function:{...u,name:l,arguments:c}}})}}:{...a,message:{...l,content:o,role:u,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}),created:i,model:a,object:`chat.completion`,...o?{system_fingerprint:o}:{}},t)}function lU(e){return JSON.stringify(e)}var uU=class e extends sU{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){let i=new e(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}},dU=class extends K{constructor(){super(...arguments),this.messages=new eH(this._client)}create(e,t){return this._client.post(`/chat/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(q`/chat/completions/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chat/completions`,DV,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return fH(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>oH(t,e))}runTools(e,t){return e.stream?uU.runTools(this._client,e,t):HH.runTools(this._client,e,t)}stream(e,t){return sU.createChatCompletion(this._client,e,t)}};dU.Messages=eH;var fU=class extends K{constructor(){super(...arguments),this.completions=new dU(this._client)}};fU.Completions=dU;var pU=class extends K{create(e,t){return this._client.post(`/organization/admin_api_keys`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(q`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/admin_api_keys`,DV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(q`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},mU=class extends K{list(e={},t){return this._client.getAPIList(`/organization/audit_logs`,OV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},hU=class extends K{create(e,t){return this._client.post(`/organization/certificates`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(q`/organization/certificates/${e}`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/certificates/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/certificates`,OV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(q`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList(`/organization/certificates/activate`,EV,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList(`/organization/certificates/deactivate`,EV,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}},gU=class extends K{retrieve(e){return this._client.get(`/organization/data_retention`,{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post(`/organization/data_retention`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}},_U=class extends K{create(e,t){return this._client.post(`/organization/invites`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(q`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/invites`,OV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(q`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},vU=class extends K{create(e,t){return this._client.post(`/organization/roles`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(q`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/roles/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/roles`,kV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(q`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},yU=class extends K{create(e,t){return this._client.post(`/organization/spend_alerts`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(q`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/spend_alerts/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/spend_alerts`,OV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(q`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},bU=class extends K{audioSpeeches(e,t){return this._client.get(`/organization/usage/audio_speeches`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get(`/organization/usage/audio_transcriptions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get(`/organization/usage/code_interpreter_sessions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get(`/organization/usage/completions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get(`/organization/costs`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get(`/organization/usage/embeddings`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get(`/organization/usage/file_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get(`/organization/usage/images`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get(`/organization/usage/moderations`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get(`/organization/usage/vector_stores`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get(`/organization/usage/web_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},xU=class extends K{create(e,t,n){return this._client.post(q`/organization/groups/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(q`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/organization/groups/${e}/roles`,kV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(q`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},SU=class extends K{create(e,t,n){return this._client.post(q`/organization/groups/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(q`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/organization/groups/${e}/users`,kV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(q`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},CU=class extends K{constructor(){super(...arguments),this.users=new SU(this._client),this.roles=new xU(this._client)}create(e,t){return this._client.post(`/organization/groups`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(q`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/groups/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/groups`,kV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(q`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};CU.Users=SU,CU.Roles=xU;var wU=class extends K{retrieve(e,t,n){let{project_id:r}=t;return this._client.get(q`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/organization/projects/${e}/api_keys`,OV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(q`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},TU=class extends K{list(e,t={},n){return this._client.getAPIList(q`/organization/projects/${e}/certificates`,OV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(q`/organization/projects/${e}/certificates/activate`,EV,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(q`/organization/projects/${e}/certificates/deactivate`,EV,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}},EU=class extends K{retrieve(e,t){return this._client.get(q`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/projects/${e}/data_retention`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},DU=class extends K{retrieve(e,t){return this._client.get(q`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},OU=class extends K{retrieve(e,t){return this._client.get(q`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/projects/${e}/model_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(q`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}},kU=class extends K{listRateLimits(e,t={},n){return this._client.getAPIList(q`/organization/projects/${e}/rate_limits`,OV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:r,...i}=t;return this._client.post(q`/organization/projects/${r}/rate_limits/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},AU=class extends K{create(e,t,n){return this._client.post(q`/projects/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(q`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(q`/projects/${r}/roles/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/projects/${e}/roles`,kV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(q`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},jU=class extends K{create(e,t,n){return this._client.post(q`/organization/projects/${e}/service_accounts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(q`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(q`/organization/projects/${r}/service_accounts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/organization/projects/${e}/service_accounts`,OV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(q`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},MU=class extends K{create(e,t,n){return this._client.post(q`/organization/projects/${e}/spend_alerts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(q`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(q`/organization/projects/${r}/spend_alerts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/organization/projects/${e}/spend_alerts`,OV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(q`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},NU=class extends K{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(q`/projects/${r}/groups/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,group_id:i}=t;return this._client.get(q`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(q`/projects/${r}/groups/${e}/roles`,kV,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,group_id:i}=t;return this._client.delete(q`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},PU=class extends K{constructor(){super(...arguments),this.roles=new NU(this._client)}create(e,t,n){return this._client.post(q`/organization/projects/${e}/groups`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,...i}=t;return this._client.get(q`/organization/projects/${r}/groups/${e}`,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/organization/projects/${e}/groups`,kV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(q`/organization/projects/${r}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};PU.Roles=NU;var FU=class extends K{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(q`/projects/${r}/users/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,user_id:i}=t;return this._client.get(q`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(q`/projects/${r}/users/${e}/roles`,kV,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,user_id:i}=t;return this._client.delete(q`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},IU=class extends K{constructor(){super(...arguments),this.roles=new FU(this._client)}create(e,t,n){return this._client.post(q`/organization/projects/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(q`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(q`/organization/projects/${r}/users/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/organization/projects/${e}/users`,OV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(q`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};IU.Roles=FU;var LU=class extends K{constructor(){super(...arguments),this.users=new IU(this._client),this.serviceAccounts=new jU(this._client),this.apiKeys=new wU(this._client),this.rateLimits=new kU(this._client),this.modelPermissions=new OU(this._client),this.hostedToolPermissions=new DU(this._client),this.groups=new PU(this._client),this.roles=new AU(this._client),this.dataRetention=new EU(this._client),this.spendAlerts=new MU(this._client),this.certificates=new TU(this._client)}create(e,t){return this._client.post(`/organization/projects`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(q`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/projects/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/projects`,OV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(q`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};LU.Users=IU,LU.ServiceAccounts=jU,LU.APIKeys=wU,LU.RateLimits=kU,LU.ModelPermissions=OU,LU.HostedToolPermissions=DU,LU.Groups=PU,LU.Roles=AU,LU.DataRetention=EU,LU.SpendAlerts=MU,LU.Certificates=TU;var RU=class extends K{create(e,t,n){return this._client.post(q`/organization/users/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{user_id:r}=t;return this._client.get(q`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/organization/users/${e}/roles`,kV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:r}=t;return this._client.delete(q`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},zU=class extends K{constructor(){super(...arguments),this.roles=new RU(this._client)}retrieve(e,t){return this._client.get(q`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(q`/organization/users/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/users`,OV,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(q`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};zU.Roles=RU;var BU=class extends K{constructor(){super(...arguments),this.auditLogs=new mU(this._client),this.adminAPIKeys=new pU(this._client),this.usage=new bU(this._client),this.invites=new _U(this._client),this.users=new zU(this._client),this.groups=new CU(this._client),this.roles=new vU(this._client),this.dataRetention=new gU(this._client),this.spendAlerts=new yU(this._client),this.certificates=new hU(this._client),this.projects=new LU(this._client)}};BU.AuditLogs=mU,BU.AdminAPIKeys=pU,BU.Usage=bU,BU.Invites=_U,BU.Users=zU,BU.Groups=CU,BU.Roles=vU,BU.DataRetention=gU,BU.SpendAlerts=yU,BU.Certificates=hU,BU.Projects=LU;var VU=class extends K{constructor(){super(...arguments),this.organization=new BU(this._client)}};VU.Organization=BU;var HU=Symbol(`brand.privateNullableHeaders`);function*UU(e){if(!e)return;if(HU in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():sB(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=sB(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var J=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of UU(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[HU]:!0,values:t,nulls:n}},WU=class extends K{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:J([{Accept:`application/octet-stream`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},GU=class extends K{create(e,t){return this._client.post(`/audio/transcriptions`,RV({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},KU=class extends K{create(e,t){return this._client.post(`/audio/translations`,RV({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},qU=class extends K{constructor(){super(...arguments),this.transcriptions=new GU(this._client),this.translations=new KU(this._client),this.speech=new WU(this._client)}};qU.Transcriptions=GU,qU.Translations=KU,qU.Speech=WU;var JU=class extends K{create(e,t){return this._client.post(`/batches`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/batches`,DV,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(q`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}},YU=class extends K{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/assistants/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(q`/assistants/${e}`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/assistants`,DV,{query:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/assistants/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},XU=class extends K{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},ZU=class extends K{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},QU=class extends K{constructor(){super(...arguments),this.sessions=new XU(this._client),this.transcriptionSessions=new ZU(this._client)}};QU.Sessions=XU,QU.TranscriptionSessions=ZU;var $U=class extends K{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(q`/chatkit/sessions/${e}/cancel`,{...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}},eW=class extends K{retrieve(e,t){return this._client.get(q`/chatkit/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,OV,{query:e,...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/chatkit/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(q`/chatkit/threads/${e}/items`,OV,{query:t,...n,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers]),__security:{bearerAuth:!0}})}},tW=class extends K{constructor(){super(...arguments),this.sessions=new $U(this._client),this.threads=new eW(this._client)}};tW.Sessions=$U,tW.Threads=eW;var nW=class extends K{create(e,t,n){return this._client.post(q`/threads/${e}/messages`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(q`/threads/${r}/messages/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(q`/threads/${r}/messages/${e}`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/threads/${e}/messages`,DV,{query:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(q`/threads/${r}/messages/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},rW=class extends K{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(q`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(q`/threads/${r}/runs/${e}/steps`,DV,{query:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},iW=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},aW=e=>{if(globalThis.process!==void 0)return{}[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0},oW,sW,cW,lW,uW,dW,fW,pW,mW,hW,gW,_W,vW,yW,bW,xW,SW,CW,wW,TW,EW,DW,OW,kW=class extends AH{constructor(){super(...arguments),oW.add(this),cW.set(this,[]),lW.set(this,{}),uW.set(this,{}),dW.set(this,void 0),fW.set(this,void 0),pW.set(this,void 0),mW.set(this,void 0),hW.set(this,void 0),gW.set(this,void 0),_W.set(this,void 0),vW.set(this,void 0),yW.set(this,void 0)}[(cW=new WeakMap,lW=new WeakMap,uW=new WeakMap,dW=new WeakMap,fW=new WeakMap,pW=new WeakMap,mW=new WeakMap,hW=new WeakMap,gW=new WeakMap,_W=new WeakMap,vW=new WeakMap,yW=new WeakMap,oW=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new sW;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let n=mV.fromReadableStream(e,this.controller);for await(let e of n)W(this,oW,`m`,bW).call(this,e);if(n.controller.signal?.aborted)throw new Hz;return this._addRun(W(this,oW,`m`,xW).call(this))}toReadableStream(){return new mV(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new sW;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},a=await e.submitToolOutputs(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)W(this,oW,`m`,bW).call(this,e);if(a.controller.signal?.aborted)throw new Hz;return this._addRun(W(this,oW,`m`,xW).call(this))}static createThreadAssistantStream(e,t,n){let r=new sW;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":`stream`}})),r}static createAssistantStream(e,t,n,r){let i=new sW;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return W(this,_W,`f`)}currentRun(){return W(this,vW,`f`)}currentMessageSnapshot(){return W(this,dW,`f`)}currentRunStepSnapshot(){return W(this,yW,`f`)}async finalRunSteps(){return await this.done(),Object.values(W(this,lW,`f`))}async finalMessages(){return await this.done(),Object.values(W(this,uW,`f`))}async finalRun(){if(await this.done(),!W(this,fW,`f`))throw Error(`Final run was not received.`);return W(this,fW,`f`)}async _createThreadAssistantStream(e,t,n){this._listenForAbort(n?.signal);let r={...t,stream:!0},i=await e.createAndRun(r,{...n,signal:this.controller.signal});this._connected();for await(let e of i)W(this,oW,`m`,bW).call(this,e);if(i.controller.signal?.aborted)throw new Hz;return this._addRun(W(this,oW,`m`,xW).call(this))}async _createAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},a=await e.create(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)W(this,oW,`m`,bW).call(this,e);if(a.controller.signal?.aborted)throw new Hz;return this._addRun(W(this,oW,`m`,xW).call(this))}static accumulateDelta(e,t){for(let[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(t==null){e[n]=r;continue}if(n===`index`||n===`type`){e[n]=r;continue}if(typeof t==`string`&&typeof r==`string`)t+=r;else if(typeof t==`number`&&typeof r==`number`)t+=r;else if(dB(t)&&dB(r))t=this.accumulateDelta(t,r);else if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>typeof e==`string`||typeof e==`number`)){t.push(...r);continue}for(let e of r){if(!dB(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let n=e.index;if(n==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof n!=`number`)throw Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let r=t[n];r==null?t.push(e):t[n]=this.accumulateDelta(r,e)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`);e[n]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};sW=kW,bW=function(e){if(!this.ended)switch(U(this,_W,e,`f`),W(this,oW,`m`,wW).call(this,e),e.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,oW,`m`,OW).call(this,e);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,oW,`m`,CW).call(this,e);break;case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:W(this,oW,`m`,SW).call(this,e);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},xW=function(){if(this.ended)throw new G(`stream has ended, this shouldn't happen`);if(!W(this,fW,`f`))throw Error(`Final run has not been received`);return W(this,fW,`f`)},SW=function(e){let[t,n]=W(this,oW,`m`,EW).call(this,e,W(this,dW,`f`));U(this,dW,t,`f`),W(this,uW,`f`)[t.id]=t;for(let e of n){let n=t.content[e.index];n?.type==`text`&&this._emit(`textCreated`,n.text)}switch(e.event){case`thread.message.created`:this._emit(`messageCreated`,e.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(this._emit(`messageDelta`,e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type==`text`&&n.text){let e=n.text,r=t.content[n.index];if(r&&r.type==`text`)this._emit(`textDelta`,e,r.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(n.index!=W(this,pW,`f`)){if(W(this,mW,`f`))switch(W(this,mW,`f`).type){case`text`:this._emit(`textDone`,W(this,mW,`f`).text,W(this,dW,`f`));break;case`image_file`:this._emit(`imageFileDone`,W(this,mW,`f`).image_file,W(this,dW,`f`));break}U(this,pW,n.index,`f`)}U(this,mW,t.content[n.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(W(this,pW,`f`)!==void 0){let t=e.data.content[W(this,pW,`f`)];if(t)switch(t.type){case`image_file`:this._emit(`imageFileDone`,t.image_file,W(this,dW,`f`));break;case`text`:this._emit(`textDone`,t.text,W(this,dW,`f`));break}}W(this,dW,`f`)&&this._emit(`messageDone`,e.data),U(this,dW,void 0,`f`)}},CW=function(e){let t=W(this,oW,`m`,TW).call(this,e);switch(U(this,yW,t,`f`),e.event){case`thread.run.step.created`:this._emit(`runStepCreated`,e.data);break;case`thread.run.step.delta`:let n=e.data.delta;if(n.step_details&&n.step_details.type==`tool_calls`&&n.step_details.tool_calls&&t.step_details.type==`tool_calls`)for(let e of n.step_details.tool_calls)e.index==W(this,hW,`f`)?this._emit(`toolCallDelta`,e,t.step_details.tool_calls[e.index]):(W(this,gW,`f`)&&this._emit(`toolCallDone`,W(this,gW,`f`)),U(this,hW,e.index,`f`),U(this,gW,t.step_details.tool_calls[e.index],`f`),W(this,gW,`f`)&&this._emit(`toolCallCreated`,W(this,gW,`f`)));this._emit(`runStepDelta`,e.data.delta,t);break;case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:U(this,yW,void 0,`f`),e.data.step_details.type==`tool_calls`&&W(this,gW,`f`)&&(this._emit(`toolCallDone`,W(this,gW,`f`)),U(this,gW,void 0,`f`)),this._emit(`runStepDone`,e.data,t);break;case`thread.run.step.in_progress`:break}},wW=function(e){W(this,cW,`f`).push(e),this._emit(`event`,e)},TW=function(e){switch(e.event){case`thread.run.step.created`:return W(this,lW,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let t=W(this,lW,`f`)[e.data.id];if(!t)throw Error(`Received a RunStepDelta before creation of a snapshot`);let n=e.data;if(n.delta){let r=sW.accumulateDelta(t,n.delta);W(this,lW,`f`)[e.data.id]=r}return W(this,lW,`f`)[e.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,lW,`f`)[e.data.id]=e.data;break}if(W(this,lW,`f`)[e.data.id])return W(this,lW,`f`)[e.data.id];throw Error(`No snapshot available`)},EW=function(e,t){let n=[];switch(e.event){case`thread.message.created`:return[e.data,n];case`thread.message.delta`:if(!t)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let r=e.data;if(r.delta.content)for(let e of r.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=W(this,oW,`m`,DW).call(this,e,n)}else t.content[e.index]=e,n.push(e);return[t,n];case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(t)return[t,n];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},DW=function(e,t){return sW.accumulateDelta(t,e)},OW=function(e){switch(U(this,vW,e.data,`f`),e.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`:U(this,fW,e.data,`f`),W(this,gW,`f`)&&(this._emit(`toolCallDone`,W(this,gW,`f`)),U(this,gW,void 0,`f`));break;case`thread.run.cancelling`:break}};var AW=class extends K{constructor(){super(...arguments),this.steps=new rW(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(q`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(q`/threads/${r}/runs/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(q`/threads/${r}/runs/${e}`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/threads/${e}/runs`,DV,{query:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(q`/threads/${r}/runs/${e}/cancel`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return kW.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=J([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(i.status){case`queued`:case`in_progress`:case`cancelling`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await mB(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return kW.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(q`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return kW.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};AW.Steps=rW;var jW=class extends K{constructor(){super(...arguments),this.runs=new AW(this._client),this.messages=new nW(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(q`/threads/${e}`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return kW.createThreadAssistantStream(e,this._client.beta.threads,t)}};jW.Runs=AW,jW.Messages=nW;var MW=class extends K{constructor(){super(...arguments),this.realtime=new QU(this._client),this.chatkit=new tW(this._client),this.assistants=new YU(this._client),this.threads=new jW(this._client)}};MW.Realtime=QU,MW.ChatKit=tW,MW.Assistants=YU,MW.Threads=jW;var NW=class extends K{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},PW=class extends K{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(q`/containers/${r}/files/${e}/content`,{...n,headers:J([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},FW=class extends K{constructor(){super(...arguments),this.content=new PW(this._client)}create(e,t,n){return this._client.post(q`/containers/${e}/files`,LV({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(q`/containers/${r}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/containers/${e}/files`,DV,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(q`/containers/${r}/files/${e}`,{...n,headers:J([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}};FW.Content=PW;var IW=class extends K{constructor(){super(...arguments),this.files=new FW(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/containers`,DV,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/containers/${e}`,{...t,headers:J([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}};IW.Files=FW;var LW=class extends K{create(e,t,n){let{include:r,...i}=t;return this._client.post(q`/conversations/${e}/items`,{query:{include:r},body:i,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(q`/conversations/${r}/items/${e}`,{query:i,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/conversations/${e}/items`,OV,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(q`/conversations/${r}/items/${e}`,{...n,__security:{bearerAuth:!0}})}},RW=class extends K{constructor(){super(...arguments),this.items=new LW(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(q`/conversations/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};RW.Items=LW;var zW=class extends K{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&dV(this._client).debug(`embeddings/user defined encoding_format:`,e.encoding_format);let i=this._client.post(`/embeddings`,{body:{...e,encoding_format:r},...t,__security:{bearerAuth:!0}});return n?i:(dV(this._client).debug(`embeddings/decoding base64 embeddings from base64`),i._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=iW(t)}),e)))}},BW=class extends K{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(q`/evals/${r}/runs/${i}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(q`/evals/${r}/runs/${e}/output_items`,DV,{query:i,...n,__security:{bearerAuth:!0}})}},VW=class extends K{constructor(){super(...arguments),this.outputItems=new BW(this._client)}create(e,t,n){return this._client.post(q`/evals/${e}/runs`,{body:t,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(q`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/evals/${e}/runs`,DV,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(q`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(q`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};VW.OutputItems=BW;var HW=class extends K{constructor(){super(...arguments),this.runs=new VW(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(q`/evals/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/evals`,DV,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};HW.Runs=VW;var UW=class extends K{create(e,t){return this._client.post(`/files`,RV({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(q`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/files`,DV,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(q`/files/${e}/content`,{...t,headers:J([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await mB(t),a=await this.retrieve(e),Date.now()-i>n)throw new Wz({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},WW=class extends K{},GW=class extends K{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t,__security:{bearerAuth:!0}})}},KW=class extends K{constructor(){super(...arguments),this.graders=new GW(this._client)}};KW.Graders=GW;var qW=class extends K{create(e,t,n){return this._client.getAPIList(q`/fine_tuning/checkpoints/${e}/permissions`,EV,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(q`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/fine_tuning/checkpoints/${e}/permissions`,OV,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(q`/fine_tuning/checkpoints/${r}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},JW=class extends K{constructor(){super(...arguments),this.permissions=new qW(this._client)}};JW.Permissions=qW;var YW=class extends K{list(e,t={},n){return this._client.getAPIList(q`/fine_tuning/jobs/${e}/checkpoints`,DV,{query:t,...n,__security:{bearerAuth:!0}})}},XW=class extends K{constructor(){super(...arguments),this.checkpoints=new YW(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,DV,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(q`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},n){return this._client.getAPIList(q`/fine_tuning/jobs/${e}/events`,DV,{query:t,...n,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(q`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(q`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};XW.Checkpoints=YW;var ZW=class extends K{constructor(){super(...arguments),this.methods=new WW(this._client),this.jobs=new XW(this._client),this.checkpoints=new JW(this._client),this.alpha=new KW(this._client)}};ZW.Methods=WW,ZW.Jobs=XW,ZW.Checkpoints=JW,ZW.Alpha=KW;var QW=class extends K{},$W=class extends K{constructor(){super(...arguments),this.graderModels=new QW(this._client)}};$W.GraderModels=QW;var eG=class extends K{createVariation(e,t){return this._client.post(`/images/variations`,RV({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post(`/images/edits`,RV({body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},tG=class extends K{retrieve(e,t){return this._client.get(q`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList(`/models`,EV,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/models/${e}`,{...t,__security:{bearerAuth:!0}})}},nG=class extends K{create(e,t){return this._client.post(`/moderations`,{body:e,...t,__security:{bearerAuth:!0}})}},rG=class extends K{accept(e,t,n){return this._client.post(q`/realtime/calls/${e}/accept`,{body:t,...n,headers:J([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(q`/realtime/calls/${e}/hangup`,{...t,headers:J([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(q`/realtime/calls/${e}/refer`,{body:t,...n,headers:J([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(q`/realtime/calls/${e}/reject`,{body:t,...n,headers:J([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}},iG=class extends K{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t,__security:{bearerAuth:!0}})}},aG=class extends K{constructor(){super(...arguments),this.clientSecrets=new iG(this._client),this.calls=new rG(this._client)}};aG.ClientSecrets=iG,aG.Calls=rG;function oG(e,t){if(!t||!lG(t)){let t={...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)};return pG(e,t)&&mG(t),t}return sG(e,t)}function sG(e,t){let n=!e.status||e.status===`completed`,r=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:n?fG(t,e):null};if(e.type===`message`){let r=e.content.map(e=>e.type===`output_text`?{...e,parsed:n?cG(t,e.text):null}:e);return{...e,content:r}}return e}),i=Object.assign({},e,{output:r});return pG(e,i)&&mG(i),Object.defineProperty(i,"output_parsed",{enumerable:!0,get(){for(let e of i.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),i}function cG(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function lG(e){return!!rH(e.text?.format)}function uG(e){return e?.$brand===`auto-parseable-tool`}function dG(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function fG(e,t){let n=dG(e.tools??[],t.name);return{...t,...t,parsed_arguments:uG(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function pG(e,t){return!Object.getOwnPropertyDescriptor(e,`output_text`)||t.output_text==null}function mG(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}function hG(e,t){if(!t){if(e.type!==`response.created`)throw new G(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return gG(e.response)}switch(e.type){case`response.output_item.added`:t.output.push(structuredClone(e.item)),e.item.type===`message`&&mG(t);break;case`response.output_item.done`:_G(t,e.output_index),t.output[e.output_index]=structuredClone(e.item),e.item.type===`message`&&mG(t);break;case`response.content_part.added`:{let n=_G(t,e.output_index),r=n.type,i=e.part;r===`message`&&i.type!==`reasoning_text`?(n.content.push(structuredClone(i)),i.type===`output_text`&&mG(t)):r===`reasoning`&&i.type===`reasoning_text`&&(n.content||=[],n.content.push(structuredClone(i)));break}case`response.content_part.done`:{let n=_G(t,e.output_index),r=e.part;if(n.type===`message`&&r.type!==`reasoning_text`)vG(n.content,e.content_index),n.content[e.content_index]=structuredClone(r),r.type===`output_text`&&mG(t);else if(n.type===`reasoning`&&r.type===`reasoning_text`){let t=n.content;if(!t)throw new G(`missing content at index ${e.content_index}`);vG(t,e.content_index),t[e.content_index]=structuredClone(r)}break}case`response.output_text.delta`:{let n=_G(t,e.output_index);if(n.type===`message`){let r=vG(n.content,e.content_index);if(r.type!==`output_text`)throw new G(`expected content to be 'output_text', got ${r.type}`);r.text+=e.delta,t.output_text+=e.delta}break}case`response.output_text.done`:{let n=_G(t,e.output_index);if(n.type===`message`){let r=vG(n.content,e.content_index);if(r.type!==`output_text`)throw new G(`expected content to be 'output_text', got ${r.type}`);r.text=e.text,mG(t)}break}case`response.output_text.annotation.added`:{let n=_G(t,e.output_index);if(n.type===`message`){let t=vG(n.content,e.content_index);if(t.type!==`output_text`)throw new G(`expected content to be 'output_text', got ${t.type}`);t.annotations[e.annotation_index]=structuredClone(e.annotation)}break}case`response.refusal.delta`:{let n=_G(t,e.output_index);if(n.type===`message`){let t=vG(n.content,e.content_index);if(t.type!==`refusal`)throw new G(`expected content to be 'refusal', got ${t.type}`);t.refusal+=e.delta}break}case`response.refusal.done`:{let n=_G(t,e.output_index);if(n.type===`message`){let t=vG(n.content,e.content_index);if(t.type!==`refusal`)throw new G(`expected content to be 'refusal', got ${t.type}`);t.refusal=e.refusal}break}case`response.function_call_arguments.delta`:{let n=_G(t,e.output_index);n.type===`function_call`&&(n.arguments+=e.delta);break}case`response.function_call_arguments.done`:{let n=_G(t,e.output_index);n.type===`function_call`&&(n.arguments=e.arguments);break}case`response.reasoning_text.delta`:{let n=_G(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new G(`missing content at index ${e.content_index}`);let t=vG(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new G(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case`response.reasoning_text.done`:{let n=_G(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new G(`missing content at index ${e.content_index}`);let t=vG(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new G(`expected content to be 'reasoning_text', got ${t.type}`);t.text=e.text}break}case`response.reasoning_summary_part.added`:{let n=_G(t,e.output_index);n.type===`reasoning`&&n.summary.push(structuredClone(e.part));break}case`response.reasoning_summary_part.done`:{let n=_G(t,e.output_index);n.type===`reasoning`&&(vG(n.summary,e.summary_index),n.summary[e.summary_index]=structuredClone(e.part));break}case`response.reasoning_summary_text.delta`:{let n=_G(t,e.output_index);if(n.type===`reasoning`){let t=vG(n.summary,e.summary_index);t.text+=e.delta}break}case`response.reasoning_summary_text.done`:{let n=_G(t,e.output_index);if(n.type===`reasoning`){let t=vG(n.summary,e.summary_index);t.text=e.text}break}case`response.custom_tool_call_input.delta`:{let n=_G(t,e.output_index);n.type===`custom_tool_call`&&(n.input+=e.delta);break}case`response.custom_tool_call_input.done`:{let n=_G(t,e.output_index);n.type===`custom_tool_call`&&(n.input=e.input);break}case`response.mcp_call_arguments.delta`:{let n=_G(t,e.output_index);n.type===`mcp_call`&&(n.arguments+=e.delta);break}case`response.mcp_call_arguments.done`:{let n=_G(t,e.output_index);n.type===`mcp_call`&&(n.arguments=e.arguments);break}case`response.code_interpreter_call_code.delta`:{let n=_G(t,e.output_index);n.type===`code_interpreter_call`&&(n.code=(n.code??``)+e.delta);break}case`response.code_interpreter_call_code.done`:{let n=_G(t,e.output_index);n.type===`code_interpreter_call`&&(n.code=e.code);break}case`response.code_interpreter_call.in_progress`:{let n=_G(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`in_progress`);break}case`response.code_interpreter_call.interpreting`:{let n=_G(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`interpreting`);break}case`response.code_interpreter_call.completed`:{let n=_G(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`completed`);break}case`response.file_search_call.in_progress`:{let n=_G(t,e.output_index);n.type===`file_search_call`&&(n.status=`in_progress`);break}case`response.file_search_call.searching`:{let n=_G(t,e.output_index);n.type===`file_search_call`&&(n.status=`searching`);break}case`response.file_search_call.completed`:{let n=_G(t,e.output_index);n.type===`file_search_call`&&(n.status=`completed`);break}case`response.web_search_call.in_progress`:{let n=_G(t,e.output_index);n.type===`web_search_call`&&(n.status=`in_progress`);break}case`response.web_search_call.searching`:{let n=_G(t,e.output_index);n.type===`web_search_call`&&(n.status=`searching`);break}case`response.web_search_call.completed`:{let n=_G(t,e.output_index);n.type===`web_search_call`&&(n.status=`completed`);break}case`response.image_generation_call.in_progress`:{let n=_G(t,e.output_index);n.type===`image_generation_call`&&(n.status=`in_progress`);break}case`response.image_generation_call.generating`:{let n=_G(t,e.output_index);n.type===`image_generation_call`&&(n.status=`generating`);break}case`response.image_generation_call.completed`:{let n=_G(t,e.output_index);n.type===`image_generation_call`&&(n.status=`completed`);break}case`response.mcp_call.in_progress`:{let n=_G(t,e.output_index);n.type===`mcp_call`&&(n.status=`in_progress`);break}case`response.mcp_call.completed`:{let n=_G(t,e.output_index);n.type===`mcp_call`&&(n.status=`completed`);break}case`response.mcp_call.failed`:{let n=_G(t,e.output_index);n.type===`mcp_call`&&(n.status=`failed`);break}case`response.created`:case`response.queued`:case`response.in_progress`:case`response.completed`:case`response.failed`:case`response.incomplete`:t=gG(e.response);break;case`response.audio.delta`:case`response.audio.done`:case`response.audio.transcript.delta`:case`response.audio.transcript.done`:case`response.image_generation_call.partial_image`:case`response.mcp_list_tools.in_progress`:case`response.mcp_list_tools.completed`:case`response.mcp_list_tools.failed`:case`error`:break;default:yG(e)}return t}function gG(e){let t=structuredClone(e);return(!Object.getOwnPropertyDescriptor(t,`output_text`)||t.output_text==null)&&mG(t),t}function _G(e,t){let n=e.output[t];if(!n)throw new G(`missing output at index ${t}`);return n}function vG(e,t){let n=e[t];if(!n)throw new G(`missing content at index ${t}`);return n}function yG(e){throw new G(`Unhandled response stream event: ${JSON.stringify(e)}`)}var bG,xG,SG,CG,wG,TG,EG,DG=class e extends AH{constructor(e){super(),bG.add(this),xG.set(this,void 0),SG.set(this,void 0),CG.set(this,void 0),U(this,xG,e,`f`)}static createResponse(t,n,r){let i=new e(n);return i._run(()=>i._createOrRetrieveResponse(t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createOrRetrieveResponse(e,t,n){this._listenForAbort(n?.signal),W(this,bG,`m`,wG).call(this);let r,i=null;`response_id`in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let e of r)W(this,bG,`m`,TG).call(this,e,i);if(r.controller.signal?.aborted)throw new Hz;return W(this,bG,`m`,EG).call(this)}[(xG=new WeakMap,SG=new WeakMap,CG=new WeakMap,bG=new WeakSet,wG=function(){this.ended||U(this,SG,void 0,`f`)},TG=function(e,t){if(this.ended)return;let n=(e,n)=>{(t==null||n.sequence_number>t)&&this._emit(e,n)},r=hG(e,W(this,SG,`f`));switch(U(this,SG,r,`f`),n(`event`,e),e.type){case`response.output_text.delta`:{let t=r.output[e.output_index];if(!t)throw new G(`missing output at index ${e.output_index}`);if(t.type===`message`){let r=t.content[e.content_index];if(!r)throw new G(`missing content at index ${e.content_index}`);if(r.type!==`output_text`)throw new G(`expected content to be 'output_text', got ${r.type}`);n(`response.output_text.delta`,{...e,snapshot:r.text})}break}case`response.function_call_arguments.delta`:{let t=r.output[e.output_index];if(!t)throw new G(`missing output at index ${e.output_index}`);t.type===`function_call`&&n(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:n(e.type,e);break}},EG=function(){if(this.ended)throw new G(`stream has ended, this shouldn't happen`);let e=W(this,SG,`f`);if(!e)throw new G(`request ended without sending any events`);U(this,SG,void 0,`f`);let t=OG(e,W(this,xG,`f`));return U(this,CG,t,`f`),t},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=W(this,CG,`f`);if(!e)throw new G(`stream ended without producing a ChatCompletion`);return e}};function OG(e,t){return oG(e,t)}var kG=class extends K{list(e,t={},n){return this._client.getAPIList(q`/responses/${e}/input_items`,DV,{query:t,...n,__security:{bearerAuth:!0}})}},AG=class extends K{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t,__security:{bearerAuth:!0}})}},jG=class extends K{constructor(){super(...arguments),this.inputItems=new kG(this._client),this.inputTokens=new AG(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&mG(e),e))}retrieve(e,t={},n){return this._client.get(q`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&mG(e),e))}delete(e,t){return this._client.delete(q`/responses/${e}`,{...t,headers:J([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>sG(t,e))}stream(e,t){return DG.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(q`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t,__security:{bearerAuth:!0}})}};jG.InputItems=kG,jG.InputTokens=AG;var MG=class extends K{retrieve(e,t){return this._client.get(q`/skills/${e}/content`,{...t,headers:J([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},NG=class extends K{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(q`/skills/${r}/versions/${e}/content`,{...n,headers:J([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},PG=class extends K{constructor(){super(...arguments),this.content=new NG(this._client)}create(e,t={},n){return this._client.post(q`/skills/${e}/versions`,LV({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(q`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/skills/${e}/versions`,DV,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(q`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};PG.Content=NG;var FG=class extends K{constructor(){super(...arguments),this.content=new MG(this._client),this.versions=new PG(this._client)}create(e={},t){return this._client.post(`/skills`,LV({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(q`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(q`/skills/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/skills`,DV,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};FG.Content=MG,FG.Versions=PG;var IG=class extends K{create(e,t,n){return this._client.post(q`/uploads/${e}/parts`,RV({body:t,...n,__security:{bearerAuth:!0}},this._client))}},LG=class extends K{constructor(){super(...arguments),this.parts=new IG(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(q`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,n){return this._client.post(q`/uploads/${e}/complete`,{body:t,...n,__security:{bearerAuth:!0}})}};LG.Parts=IG;var RG=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n)console.error(e.reason);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r},zG=class extends K{create(e,t,n){return this._client.post(q`/vector_stores/${e}/file_batches`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(q`/vector_stores/${r}/file_batches/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(q`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(q`/vector_stores/${r}/file_batches/${e}/files`,DV,{query:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){let r=J([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await mB(e);break;case`failed`:case`cancelled`:case`completed`:return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=r?.maxConcurrency??5,a=Math.min(i,t.length),o=this._client,s=t.values(),c=[...n];async function l(e){for(let t of e){let e=await o.files.create({file:t,purpose:`assistants`},r);c.push(e.id)}}return await RG(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}},BG=class extends K{create(e,t,n){return this._client.post(q`/vector_stores/${e}/files`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(q`/vector_stores/${r}/files/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(q`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(q`/vector_stores/${e}/files`,DV,{query:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(q`/vector_stores/${r}/files/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){let r=J([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),a=i.data;switch(a.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=i.response.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await mB(e);break;case`failed`:case`completed`:return a}}}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(q`/vector_stores/${r}/files/${e}/content`,EV,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},VG=class extends K{constructor(){super(...arguments),this.files=new BG(this._client),this.fileBatches=new zG(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(q`/vector_stores/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(q`/vector_stores/${e}`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/vector_stores`,DV,{query:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/vector_stores/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(q`/vector_stores/${e}/search`,EV,{body:t,method:`post`,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}};VG.Files=BG,VG.FileBatches=zG;var HG=class extends K{create(e,t){return this._client.post(`/videos`,RV({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(q`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/videos`,OV,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(q`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post(`/videos/characters`,RV({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(q`/videos/${e}/content`,{query:t,...n,headers:J([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,RV({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,RV({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(q`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,n){return this._client.post(q`/videos/${e}/remix`,LV({body:t,...n,__security:{bearerAuth:!0}},this._client))}},UG,WG,GG,KG=class extends K{constructor(){super(...arguments),UG.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,r=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,UG,`m`,WG).call(this,n);let i=J([t]).values,a=W(this,UG,`m`,GG).call(this,i,`webhook-signature`),o=W(this,UG,`m`,GG).call(this,i,`webhook-timestamp`),s=W(this,UG,`m`,GG).call(this,i,`webhook-id`),c=parseInt(o,10);if(isNaN(c))throw new tB(`Invalid webhook timestamp format`);let l=Math.floor(Date.now()/1e3);if(l-c>r)throw new tB(`Webhook timestamp is too old`);if(c>l+r)throw new tB(`Webhook timestamp is too new`);let u=a.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),d=n.startsWith(`whsec_`)?Buffer.from(n.replace(`whsec_`,``),`base64`):Buffer.from(n,`utf-8`),f=s?`${s}.${o}.${e}`:`${o}.${e}`,p=await crypto.subtle.importKey(`raw`,d,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of u)try{let t=Buffer.from(e,`base64`);if(await crypto.subtle.verify(`HMAC`,p,t,new TextEncoder().encode(f)))return}catch{continue}throw new tB(`The given webhook signature does not match the expected signature`)}};UG=new WeakSet,WG=function(e){if(typeof e!=`string`||e.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`)},GG=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n};var qG=Symbol.for(`openai.node.providerDefinitions.v1`),JG=globalThis,YG=JG[qG],XG=YG??new WeakMap;YG||Object.defineProperty(JG,qG,{value:XG});function ZG(e){let t=XG.get(e);if(!t)throw Error(`Invalid provider. Providers must be created with createProvider().`);return t.configure()}var QG,$G,eK,tK,nK=`workload-identity-auth`,Y=class{constructor(e={}){QG.add(this),eK.set(this,void 0),this.completions=new NW(this),this.chat=new fU(this),this.embeddings=new zW(this),this.files=new UW(this),this.images=new eG(this),this.audio=new qU(this),this.moderations=new nG(this),this.models=new tG(this),this.fineTuning=new ZW(this),this.graders=new $W(this),this.vectorStores=new VG(this),this.webhooks=new KG(this),this.beta=new MW(this),this.batches=new JU(this),this.uploads=new LG(this),this.admin=new VU(this),this.responses=new jG(this),this.realtime=new aG(this),this.conversations=new RW(this),this.evals=new HW(this),this.containers=new IW(this),this.skills=new FG(this),this.videos=new HG(this);let t=e.provider;if(t){let t=[`apiKey`,`adminAPIKey`,`workloadIdentity`,`baseURL`].filter(t=>e[t]!=null);if(t.length)throw new G(`The \`provider\` option cannot be used with ${t.map(e=>`\`${e}\``).join(`, `)}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:n=t?null:aW(`OPENAI_BASE_URL`),apiKey:r=t?null:aW(`OPENAI_API_KEY`)??null,adminAPIKey:i=t?null:aW(`OPENAI_ADMIN_KEY`)??null,organization:a=t?null:aW(`OPENAI_ORG_ID`)??null,project:o=t?null:aW(`OPENAI_PROJECT_ID`)??null,webhookSecret:s=aW(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:c,...l}=e,u=t?ZG(t):void 0,d={apiKey:r,adminAPIKey:i,organization:a,project:o,webhookSecret:s,workloadIdentity:c,provider:t,...l,baseURL:u?.baseURL??(n||`https://api.openai.com/v1`)};if(r&&c)throw new G("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!u&&!r&&!i&&!c)throw new G("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!d.dangerouslyAllowBrowser&&gB())throw new G(`It looks like you're running in a browser-like environment.
|
|
197
197
|
|
|
198
198
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
199
199
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -202,23 +202,23 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
202
202
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
203
203
|
|
|
204
204
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
205
|
-
`);this.baseURL=d.baseURL,this.timeout=d.timeout
|
|
206
|
-
`)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}d.defaultHeaders=J([e,d.defaultHeaders])}this._options=d,this._provider=u,c&&(this._workloadIdentityAuth=new wV(c,this.fetch)),this.apiKey=typeof r==`string`?r:null,this.adminAPIKey=i,this.organization=a,this.project=o,this.webhookSecret=s}withOptions(e){let t=this._options.provider,n=e.provider??t,r={...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._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return n&&(delete r.apiKey,delete r.adminAPIKey,delete r.workloadIdentity,delete r.baseURL,n!==t&&(delete r.organization,delete r.project,delete r.defaultHeaders)),new this.constructor({...r,...e,provider:n})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get(`authorization`)||e.get(`api-key`))&&!(t.has(`authorization`)||t.has(`api-key`))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw Error(`Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted`)}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return J([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return J([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return J([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return J([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return BB(e)}getUserAgent(){return`${this.constructor.name}/JS ${sB}`}defaultIdempotencyKey(){return`stainless-node-retry-${Az()}`}makeStatusError(e,t,n,r){return Nz.generate(e,t,n,r)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!=`function`)return!1;let t;try{t=await e()}catch(e){throw e instanceof G?e:new G(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new G(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){let r=!W(this,WG,`m`,qG).call(this)&&n||this.baseURL,i=Zz(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!tB(a)||!tB(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){this._provider||(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new mV(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r}),await this._provider?.prepareRequest?.(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(rV(this).debug(`[${c}] sending request`,iV({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new Pz;let d=r.__security??{bearerAuth:!0},f=new AbortController,p=await this.fetchWithAuth(o,a,s,f,d).catch(Mz),m=Date.now();if(p instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new Pz;let i=jz(p)||/timed? ?out/i.test(String(p)+(`cause`in p?String(p.cause):``));if(t)return rV(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),rV(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,iV({retryOfRequestLogID:n,url:o,durationMs:m-u,message:p.message})),this.retryRequest(r,t,n??c);throw rV(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),rV(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,iV({retryOfRequestLogID:n,url:o,durationMs:m-u,message:p.message})),p instanceof Jz||p instanceof Yz?p:i?new Iz:new Fz({message:YG(p),cause:p})}let h=`[${c}${l}${[...p.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${p.ok?`succeeded`:`failed`} with status ${p.status} in ${m-u}ms`;if(!p.ok){if(p.status===401&&this._workloadIdentityAuth&&d.bearerAuth&&!r.__metadata?.hasStreamingBody&&!r.__metadata?.workloadIdentityTokenRefreshed)return await bB(p.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...r,__metadata:{...r.__metadata,workloadIdentityTokenRefreshed:!0}},t,n??c);let e=await this.shouldRetry(p);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await bB(p.body),rV(this).info(`${h} - ${e}`),rV(this).debug(`[${c}] response error (${e})`,iV({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-u})),this.retryRequest(r,t,n??c,p.headers)}let i=e?`error; no more retries left`:`error; not retryable`;rV(this).info(`${h} - ${i}`);let a=await p.text().catch(e=>Mz(e).message),o=aB(a),s=o?void 0:a;throw rV(this).debug(`[${c}] response error (${i})`,iV({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(p.status,o,s,p.headers)}return rV(this).info(h),rV(this).debug(`[${c}] response start`,iV({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-u})),{response:p,options:r,controller:f,requestLogID:c,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new _V(this,n,e)}async fetchWithAuth(e,t,n,r,i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&i.bearerAuth){let e=t.headers,n=e.get(`Authorization`);if(!n||n===`Bearer ${JG}`){let t=await this._workloadIdentityAuth.getToken();e.set(`Authorization`,`Bearer ${t}`)}}return await this.fetchWithTimeout(e,t,n,r)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await oB(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&iB(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l,isStreamingBody:u}=this.buildBody({options:n});return u&&(e.__metadata={...e.__metadata,hasStreamingBody:!0}),{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=J([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...hB(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this._provider||this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t===void 0&&`body`in e?{...W(this,KG,`f`).call(this,{body:t,headers:J([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let r=J([n]),i=globalThis.ReadableStream!==void 0&&t instanceof globalThis.ReadableStream,a=!i&&(typeof t==`string`||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||globalThis.Blob!==void 0&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t==`string`&&r.values.has(`content-type`)||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||i?{bodyHeaders:void 0,body:t,isStreamingBody:!a}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:vB(t),isStreamingBody:!0}:typeof t==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(t),isStreamingBody:!1}:{...W(this,KG,`f`).call(this,{body:t,headers:r}),isStreamingBody:!1}}};GG=Y,KG=new WeakMap,WG=new WeakSet,qG=function(){return this._provider!==void 0||this.baseURL!==`https://api.openai.com/v1`},Y.OpenAI=GG,Y.DEFAULT_TIMEOUT=6e5,Y.OpenAIError=G,Y.APIError=Nz,Y.APIConnectionError=Fz,Y.APIConnectionTimeoutError=Iz,Y.APIUserAbortError=Pz,Y.NotFoundError=Bz,Y.ConflictError=Vz,Y.RateLimitError=Uz,Y.BadRequestError=Lz,Y.AuthenticationError=Rz,Y.InternalServerError=Wz,Y.PermissionDeniedError=zz,Y.UnprocessableEntityError=Hz,Y.InvalidWebhookSignatureError=qz,Y.toFile=VV,Y.Completions=TW,Y.Chat=iU,Y.Embeddings=jW,Y.Files=FW,Y.Images=KW,Y.Audio=zU,Y.Moderations=JW,Y.Models=qW,Y.FineTuning=UW,Y.Graders=GW,Y.VectorStores=NG,Y.Webhooks=RG,Y.Beta=wW,Y.Batches=BU,Y.Uploads=kG,Y.Admin=NU,Y.Responses=CG,Y.Realtime=ZW,Y.Conversations=AW,Y.Evals=PW,Y.Containers=OW,Y.Skills=DG,Y.Videos=PG;function YG(e){if(XG(e))return`Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });`}function XG(e){let t=e;for(let e=0;e<8&&t&&typeof t==`object`;e++){let e=t;if(e.code===`UND_ERR_INVALID_ARG`&&typeof e.message==`string`&&e.message.includes(`invalid onRequestStart method`))return!0;t=e.cause}return!1}var ZG=class extends Y{constructor({baseURL:e=ZU(`OPENAI_BASE_URL`),apiKey:t=ZU(`AZURE_OPENAI_API_KEY`),apiVersion:n=ZU(`OPENAI_API_VERSION`),endpoint:r,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:o,...s}={}){if(!n)throw new G(`The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).`);if(typeof a==`function`&&(o=!0),!a&&!t)throw new G("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&t)throw new G("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(s.defaultQuery={...s.defaultQuery,"api-version":n},!e){if(r||={}.AZURE_OPENAI_ENDPOINT,!r)throw new G("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${r}/openai`}else if(r)throw new G(`baseURL and endpoint are mutually exclusive`);super({apiKey:a??t,baseURL:e,...s,...o===void 0?{}:{dangerouslyAllowBrowser:o}}),this.apiVersion=``,this.apiVersion=n,this.deploymentName=i}async buildRequest(e,t={}){if(QG.has(e.path)&&e.method===`post`&&e.body!==void 0){if(!rB(e.body))throw Error(`Expected request body to be an object`);let t=this.deploymentName||e.body.model||e.__metadata?.model;t!==void 0&&!this.baseURL.includes(`/deployments`)&&(e.path=`/deployments/${t}${e.path}`)}return super.buildRequest(e,t)}async authHeaders(e,t){let n=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return n.bearerAuth&&typeof this._options.apiKey==`string`?J([{"api-key":this.apiKey}]):super.authHeaders(e,n)}},QG=new Set([`/completions`,`/chat/completions`,`/embeddings`,`/audio/transcriptions`,`/audio/translations`,`/audio/speech`,`/images/generations`,`/batches`,`/images/edits`]);function $G(e){return!!(String(e).includes(`context_length_exceeded`)||`message`in e&&typeof e.message==`string`&&(e.message.includes(`Input tokens exceed the configured limit`)||e.message.includes(`exceeds the context window`)||e.message.includes(`maximum context length`)))}function eK(e){if(!e||typeof e!=`object`)return e;let t;return e.constructor.name===Iz.name&&`message`in e&&typeof e.message==`string`?(t=Error(e.message),t.name=`TimeoutError`):e.constructor.name===Pz.name&&`message`in e&&typeof e.message==`string`?(t=Error(e.message),t.name=`AbortError`):t=$G(e)?be.fromError(e):`status`in e&&e.status===400&&`message`in e&&typeof e.message==`string`&&e.message.includes(`tool_calls`)?kz(e,`INVALID_TOOL_RESULTS`):`status`in e&&e.status===401?kz(e,`MODEL_AUTHENTICATION`):`status`in e&&e.status===429?kz(e,`MODEL_RATE_LIMIT`):`status`in e&&e.status===404?kz(e,`MODEL_NOT_FOUND`):e,t}var tK=e=>e();function nK(e){return e?!!(/^o\d/.test(e??``)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)):!1}function rK(e){return e.role!==`system`&&e.role!==`developer`&&e.role!==`assistant`&&e.role!==`user`&&e.role!==`function`&&e.role!==`tool`&&console.warn(`Unknown message role: ${e.role}`),e.role}function iK(e){return e.metadata?.filename??e.metadata?.name??e.metadata?.title}var aK=`LC_AUTOGENERATED`;function oK(e){return(e.metadata?.filename??e.metadata?.name??e.metadata?.title)||(console.warn(`OpenAI may require a filename for file uploads. Specify a filename in the content block metadata, e.g.: { type: 'file', mimeType: '...', data: '...', metadata: { filename: 'my-file.pdf' } }. Using placeholder filename 'LC_AUTOGENERATED'.`),aK)}function sK(e){let t=e._getType();switch(t){case`system`:return`system`;case`ai`:return`assistant`;case`human`:return`user`;case`function`:return`function`;case`tool`:return`tool`;case`generic`:if(!Pn.isInstance(e))throw Error(`Invalid generic chat message`);return rK(e);default:throw Error(`Unknown message type: ${t}`)}}function cK(e){return!!(e.includes(`gpt-5.2-pro`)||e.includes(`gpt-5.4-pro`)||e.includes(`gpt-5.5-pro`)||e.includes(`codex`))}function lK(e){let{azureOpenAIApiDeploymentName:t,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:r,azureOpenAIBasePath:i,baseURL:a,azureADTokenProvider:o,azureOpenAIEndpoint:s}=e;if((r||o)&&i&&t)return`${i}/${t}`;if((r||o)&&s&&t)return`${s}/openai/deployments/${t}`;if(r||o){if(!n)throw Error(`azureOpenAIApiInstanceName is required when using azureOpenAIApiKey`);if(!t)throw Error(`azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey`);return`https://${n}.openai.azure.com/openai/deployments/${t}`}return a}function uK(e){return typeof Headers<`u`&&typeof e==`object`&&!!e&&Object.prototype.toString.call(e)===`[object Headers]`}function dK(e){let t=tK(()=>{if(uK(e))return e;if(Array.isArray(e))return new Headers(e);if(typeof e==`object`&&e&&`values`in e&&uK(e.values))return e.values;if(typeof e==`object`&&e){let t=Object.entries(e).filter(([,e])=>typeof e==`string`).map(([e,t])=>[e,t]);return new Headers(t)}return new Headers});return Object.fromEntries(t.entries())}function fK(){let e=si();return(e===`node`||e===`deno`)&&(e=`(${e}/${process.version}; ${process.platform}; ${process.arch})`),e}function pK(e,t=!1,n=`1.0.0`){let r=dK(e),i=fK(),a=`langchainjs${t?`-azure`:``}-openai`;return{...r,"User-Agent":r[`User-Agent`]?`${a}/${n} (${i})${r[`User-Agent`]}`:`${a}/${n} (${i})`}}function mK(e,t){let n;return n=eA(e)?CM(e):e,t?.strict!==void 0&&(n.function.strict=t.strict),n}function hK(e){return e.anyOf!==void 0&&Array.isArray(e.anyOf)}function gK(e){let t=[`namespace functions {`,``];for(let n of e)n.description&&t.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(t.push(`type ${n.name} = (_: {`),t.push(_K(n.parameters,0)),t.push(`}) => any;`)):t.push(`type ${n.name} = () => any;`),t.push(``);return t.push(`} // namespace functions`),t.join(`
|
|
207
|
-
`)}function
|
|
208
|
-
`)}function
|
|
209
|
-
`);case`array`:return e.items?`${vK(e.items,t)}[]`:`any[]`;default:return``}}function yK(e){if(e)return e===`any`||e===`required`?`required`:e===`auto`?`auto`:e===`none`?`none`:typeof e==`string`?{type:`function`,function:{name:e}}:e}function bK(e){return`type`in e&&e.type!==`function`}function xK(e){return typeof e==`object`&&!!e&&`extras`in e&&typeof e.extras==`object`&&e.extras!==null&&`providerToolDefinition`in e.extras&&typeof e.extras.providerToolDefinition==`object`&&e.extras.providerToolDefinition!==null}function SK(e){return typeof e==`object`&&!!e&&`type`in e&&e.type!==`function`}function CK(e){return typeof e==`object`&&!!e&&`metadata`in e&&typeof e.metadata==`object`&&e.metadata!==null&&`customTool`in e.metadata&&typeof e.metadata.customTool==`object`&&e.metadata.customTool!==null}function wK(e){return`type`in e&&e.type===`custom`&&`custom`in e&&typeof e.custom==`object`&&e.custom!==null}function TK(e){if(e.type===`custom_tool_call`)return{...e,type:`tool_call`,call_id:e.id,id:e.call_id,name:e.name,isCustomTool:!0,args:{input:e.input}}}function EK(e){if(e.type===`computer_call`)return{...e,type:`tool_call`,call_id:e.id,id:e.call_id,name:`computer_use`,isComputerTool:!0,args:{action:e.action}}}function DK(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_call`&&`isComputerTool`in e&&e.isComputerTool===!0}function OK(e,t){return typeof e!=`object`||!e||!(`type`in e)||e.type!==`tool_call`?!1:!!(`isCustomTool`in e&&e.isCustomTool===!0||t&&`id`in e&&typeof e.id==`string`&&e.id in t)}function kK(e){return{type:`custom`,name:e.custom.name,description:e.custom.description,format:(()=>{if(e.custom.format){if(e.custom.format.type===`grammar`)return{type:`grammar`,definition:e.custom.format.grammar.definition,syntax:e.custom.format.grammar.syntax};if(e.custom.format.type===`text`)return{type:`text`}}})()}}function AK(e){return{type:`custom`,custom:{name:e.name,description:e.description,format:(()=>{if(e.format){if(e.format.type===`grammar`)return{type:`grammar`,grammar:{definition:e.format.definition,syntax:e.format.syntax}};if(e.format.type===`text`)return{type:`text`}}})()}}}var jK=Symbol(`Let zodToJsonSchema decide on which parser to use`),MK={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`},NK=e=>typeof e==`string`?{...MK,basePath:[`#`],definitions:{},name:e}:{...MK,basePath:[`#`],definitions:{},...e},PK=e=>`_def`in e?e._def:e;function FK(e){if(!e)return!0;for(let t in e)return!1;return!0}var IK=e=>{let t=NK(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[PK(n),{def:PK(n),path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function LK(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function RK(e,t,n,r,i){e[t]=n,LK(e,t,r,i)}function zK(){return{}}function BK(e,t){let n={type:`array`};return e.type?._def?.typeName!==R.ZodAny&&(n.items=Eq(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&RK(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&RK(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(RK(n,`minItems`,e.exactLength.value,e.exactLength.message,t),RK(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function VK(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?RK(n,`minimum`,r.value,r.message,t):RK(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),RK(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?RK(n,`maximum`,r.value,r.message,t):RK(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),RK(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:RK(n,`multipleOf`,r.value,r.message,t);break}return n}function HK(){return{type:`boolean`}}function UK(e,t,n){return Eq(e.type._def,t,n)}var WK=(e,t,n)=>Eq(e.innerType._def,t,n);function GK(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>GK(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return KK(e,t)}}var KK=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:RK(n,`minimum`,r.value,r.message,t);break;case`max`:RK(n,`maximum`,r.value,r.message,t);break}return n};function qK(e,t,n){return{...Eq(e.innerType._def,t,n),default:e.defaultValue()}}function JK(e,t,n){return t.effectStrategy===`input`?Eq(e.schema._def,t,n):{}}function YK(e){return{type:`string`,enum:[...e.values]}}var XK=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function ZK(e,t){let n=[Eq(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),Eq(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(XK(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function QK(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var $K,eq={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:()=>($K===void 0&&($K=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),$K),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 tq(e,t){let n={type:`string`};function r(e){return t.patternStrategy===`escape`?nq(e):e}if(e.checks)for(let i of e.checks)switch(i.kind){case`min`:RK(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t);break;case`max`:RK(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:rq(n,`email`,i.message,t);break;case`format:idn-email`:rq(n,`idn-email`,i.message,t);break;case`pattern:zod`:iq(n,eq.email,i.message,t);break}break;case`url`:rq(n,`uri`,i.message,t);break;case`uuid`:rq(n,`uuid`,i.message,t);break;case`regex`:iq(n,i.regex,i.message,t);break;case`cuid`:iq(n,eq.cuid,i.message,t);break;case`cuid2`:iq(n,eq.cuid2,i.message,t);break;case`startsWith`:iq(n,RegExp(`^${r(i.value)}`),i.message,t);break;case`endsWith`:iq(n,RegExp(`${r(i.value)}$`),i.message,t);break;case`datetime`:rq(n,`date-time`,i.message,t);break;case`date`:rq(n,`date`,i.message,t);break;case`time`:rq(n,`time`,i.message,t);break;case`duration`:rq(n,`duration`,i.message,t);break;case`length`:RK(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t),RK(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case`includes`:iq(n,RegExp(r(i.value)),i.message,t);break;case`ip`:i.version!==`v6`&&rq(n,`ipv4`,i.message,t),i.version!==`v4`&&rq(n,`ipv6`,i.message,t);break;case`emoji`:iq(n,eq.emoji,i.message,t);break;case`ulid`:iq(n,eq.ulid,i.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:rq(n,`binary`,i.message,t);break;case`contentEncoding:base64`:RK(n,`contentEncoding`,`base64`,i.message,t);break;case`pattern:zod`:iq(n,eq.base64,i.message,t);break}break;case`nanoid`:iq(n,eq.nanoid,i.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:}return n}var nq=e=>Array.from(e).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(``),rq=(e,t,n,r)=>{e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):RK(e,`format`,t,n,r)},iq=(e,t,n,r)=>{e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:aq(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):RK(e,`pattern`,aq(t,r),n,r)},aq=(e,t)=>{let n=typeof e==`function`?e():e;if(!t.applyRegexFlags||!n.flags)return n.source;let r={i:n.flags.includes(`i`),m:n.flags.includes(`m`),s:n.flags.includes(`s`)},i=r.i?n.source.toLowerCase():n.source,a=``,o=!1,s=!1,c=!1;for(let e=0;e<i.length;e++){if(o){a+=i[e],o=!1;continue}if(r.i){if(s){if(i[e].match(/[a-z]/)){c?(a+=i[e],a+=`${i[e-2]}-${i[e]}`.toUpperCase(),c=!1):i[e+1]===`-`&&i[e+2]?.match(/[a-z]/)?(a+=i[e],c=!0):a+=`${i[e]}${i[e].toUpperCase()}`;continue}}else if(i[e].match(/[a-z]/)){a+=`[${i[e]}${i[e].toUpperCase()}]`;continue}}if(r.m){if(i[e]===`^`){a+=`(^|(?<=[\r
|
|
205
|
+
`);this.baseURL=d.baseURL,this.timeout=d.timeout??$G.DEFAULT_TIMEOUT,this.logger=d.logger??console;let f=`warn`;this.logLevel=f,this.logLevel=oV(d.logLevel,`ClientOptions.logLevel`,this)??oV(aW(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??f,this.fetchOptions=d.fetchOptions,this.maxRetries=d.maxRetries??2,this.fetch=d.fetch??wB(),U(this,eK,kB,`f`);let p=t?void 0:aW(`OPENAI_CUSTOM_HEADERS`);if(p){let e={};for(let t of p.split(`
|
|
206
|
+
`)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}d.defaultHeaders=J([e,d.defaultHeaders])}this._options=d,this._provider=u,c&&(this._workloadIdentityAuth=new MV(c,this.fetch)),this.apiKey=typeof r==`string`?r:null,this.adminAPIKey=i,this.organization=a,this.project=o,this.webhookSecret=s}withOptions(e){let t=this._options.provider,n=e.provider??t,r={...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._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return n&&(delete r.apiKey,delete r.adminAPIKey,delete r.workloadIdentity,delete r.baseURL,n!==t&&(delete r.organization,delete r.project,delete r.defaultHeaders)),new this.constructor({...r,...e,provider:n})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get(`authorization`)||e.get(`api-key`))&&!(t.has(`authorization`)||t.has(`api-key`))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw Error(`Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted`)}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return J([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return J([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return J([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return J([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return JB(e)}getUserAgent(){return`${this.constructor.name}/JS ${hB}`}defaultIdempotencyKey(){return`stainless-node-retry-${Rz()}`}makeStatusError(e,t,n,r){return Vz.generate(e,t,n,r)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!=`function`)return!1;let t;try{t=await e()}catch(e){throw e instanceof G?e:new G(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new G(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){let r=!W(this,QG,`m`,tK).call(this)&&n||this.baseURL,i=aB(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!lB(a)||!lB(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){this._provider||(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new SV(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r}),await this._provider?.prepareRequest?.(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(dV(this).debug(`[${c}] sending request`,fV({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new Hz;let d=r.__security??{bearerAuth:!0},f=new AbortController,p=await this.fetchWithAuth(o,a,s,f,d).catch(Bz),m=Date.now();if(p instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new Hz;let i=zz(p)||/timed? ?out/i.test(String(p)+(`cause`in p?String(p.cause):``));if(t)return dV(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),dV(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,fV({retryOfRequestLogID:n,url:o,durationMs:m-u,message:p.message})),this.retryRequest(r,t,n??c);throw dV(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),dV(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,fV({retryOfRequestLogID:n,url:o,durationMs:m-u,message:p.message})),p instanceof nB||p instanceof rB?p:i?new Wz:new Uz({message:rK(p),cause:p})}let h=`[${c}${l}${[...p.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${p.ok?`succeeded`:`failed`} with status ${p.status} in ${m-u}ms`;if(!p.ok){if(p.status===401&&this._workloadIdentityAuth&&d.bearerAuth&&!r.__metadata?.hasStreamingBody&&!r.__metadata?.workloadIdentityTokenRefreshed)return await OB(p.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...r,__metadata:{...r.__metadata,workloadIdentityTokenRefreshed:!0}},t,n??c);let e=await this.shouldRetry(p);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await OB(p.body),dV(this).info(`${h} - ${e}`),dV(this).debug(`[${c}] response error (${e})`,fV({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-u})),this.retryRequest(r,t,n??c,p.headers)}let i=e?`error; no more retries left`:`error; not retryable`;dV(this).info(`${h} - ${i}`);let a=await p.text().catch(e=>Bz(e).message),o=pB(a),s=o?void 0:a;throw dV(this).debug(`[${c}] response error (${i})`,fV({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(p.status,o,s,p.headers)}return dV(this).info(h),dV(this).debug(`[${c}] response start`,fV({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-u})),{response:p,options:r,controller:f,requestLogID:c,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new TV(this,n,e)}async fetchWithAuth(e,t,n,r,i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&i.bearerAuth){let e=t.headers,n=e.get(`Authorization`);if(!n||n===`Bearer ${nK}`){let t=await this._workloadIdentityAuth.getToken();e.set(`Authorization`,`Bearer ${t}`)}}return await this.fetchWithTimeout(e,t,n,r)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await mB(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&fB(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l,isStreamingBody:u}=this.buildBody({options:n});return u&&(e.__metadata={...e.__metadata,hasStreamingBody:!0}),{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=J([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...CB(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this._provider||this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t===void 0&&`body`in e?{...W(this,eK,`f`).call(this,{body:t,headers:J([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let r=J([n]),i=globalThis.ReadableStream!==void 0&&t instanceof globalThis.ReadableStream,a=!i&&(typeof t==`string`||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||globalThis.Blob!==void 0&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t==`string`&&r.values.has(`content-type`)||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||i?{bodyHeaders:void 0,body:t,isStreamingBody:!a}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:EB(t),isStreamingBody:!0}:typeof t==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(t),isStreamingBody:!1}:{...W(this,eK,`f`).call(this,{body:t,headers:r}),isStreamingBody:!1}}};$G=Y,eK=new WeakMap,QG=new WeakSet,tK=function(){return this._provider!==void 0||this.baseURL!==`https://api.openai.com/v1`},Y.OpenAI=$G,Y.DEFAULT_TIMEOUT=6e5,Y.OpenAIError=G,Y.APIError=Vz,Y.APIConnectionError=Uz,Y.APIConnectionTimeoutError=Wz,Y.APIUserAbortError=Hz,Y.NotFoundError=Jz,Y.ConflictError=Yz,Y.RateLimitError=Zz,Y.BadRequestError=Gz,Y.AuthenticationError=Kz,Y.InternalServerError=Qz,Y.PermissionDeniedError=qz,Y.UnprocessableEntityError=Xz,Y.InvalidWebhookSignatureError=tB,Y.toFile=YV,Y.Completions=NW,Y.Chat=fU,Y.Embeddings=zW,Y.Files=UW,Y.Images=eG,Y.Audio=qU,Y.Moderations=nG,Y.Models=tG,Y.FineTuning=ZW,Y.Graders=$W,Y.VectorStores=VG,Y.Webhooks=KG,Y.Beta=MW,Y.Batches=JU,Y.Uploads=LG,Y.Admin=VU,Y.Responses=jG,Y.Realtime=aG,Y.Conversations=RW,Y.Evals=HW,Y.Containers=IW,Y.Skills=FG,Y.Videos=HG;function rK(e){if(iK(e))return`Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });`}function iK(e){let t=e;for(let e=0;e<8&&t&&typeof t==`object`;e++){let e=t;if(e.code===`UND_ERR_INVALID_ARG`&&typeof e.message==`string`&&e.message.includes(`invalid onRequestStart method`))return!0;t=e.cause}return!1}var aK=class extends Y{constructor({baseURL:e=aW(`OPENAI_BASE_URL`),apiKey:t=aW(`AZURE_OPENAI_API_KEY`),apiVersion:n=aW(`OPENAI_API_VERSION`),endpoint:r,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:o,...s}={}){if(!n)throw new G(`The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).`);if(typeof a==`function`&&(o=!0),!a&&!t)throw new G("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&t)throw new G("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(s.defaultQuery={...s.defaultQuery,"api-version":n},!e){if(r||={}.AZURE_OPENAI_ENDPOINT,!r)throw new G("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${r}/openai`}else if(r)throw new G(`baseURL and endpoint are mutually exclusive`);super({apiKey:a??t,baseURL:e,...s,...o===void 0?{}:{dangerouslyAllowBrowser:o}}),this.apiVersion=``,this.apiVersion=n,this.deploymentName=i}async buildRequest(e,t={}){if(oK.has(e.path)&&e.method===`post`&&e.body!==void 0){if(!dB(e.body))throw Error(`Expected request body to be an object`);let t=this.deploymentName||e.body.model||e.__metadata?.model;t!==void 0&&!this.baseURL.includes(`/deployments`)&&(e.path=`/deployments/${t}${e.path}`)}return super.buildRequest(e,t)}async authHeaders(e,t){let n=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return n.bearerAuth&&typeof this._options.apiKey==`string`?J([{"api-key":this.apiKey}]):super.authHeaders(e,n)}},oK=new Set([`/completions`,`/chat/completions`,`/embeddings`,`/audio/transcriptions`,`/audio/translations`,`/audio/speech`,`/images/generations`,`/batches`,`/images/edits`]);function sK(e){return!!(String(e).includes(`context_length_exceeded`)||`message`in e&&typeof e.message==`string`&&(e.message.includes(`Input tokens exceed the configured limit`)||e.message.includes(`exceeds the context window`)||e.message.includes(`maximum context length`)))}function cK(e){if(!e||typeof e!=`object`)return e;let t;return e.constructor.name===Wz.name&&`message`in e&&typeof e.message==`string`?(t=Error(e.message),t.name=`TimeoutError`):e.constructor.name===Hz.name&&`message`in e&&typeof e.message==`string`?(t=Error(e.message),t.name=`AbortError`):t=sK(e)?be.fromError(e):`status`in e&&e.status===400&&`message`in e&&typeof e.message==`string`&&e.message.includes(`tool_calls`)?Lz(e,`INVALID_TOOL_RESULTS`):`status`in e&&e.status===401?Lz(e,`MODEL_AUTHENTICATION`):`status`in e&&e.status===429?Lz(e,`MODEL_RATE_LIMIT`):`status`in e&&e.status===404?Lz(e,`MODEL_NOT_FOUND`):e,t}var lK=e=>e();function uK(e){return e?!!(/^o\d/.test(e??``)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)):!1}function dK(e){return e.role!==`system`&&e.role!==`developer`&&e.role!==`assistant`&&e.role!==`user`&&e.role!==`function`&&e.role!==`tool`&&console.warn(`Unknown message role: ${e.role}`),e.role}function fK(e){return e.metadata?.filename??e.metadata?.name??e.metadata?.title}var pK=`LC_AUTOGENERATED`;function mK(e){return(e.metadata?.filename??e.metadata?.name??e.metadata?.title)||(console.warn(`OpenAI may require a filename for file uploads. Specify a filename in the content block metadata, e.g.: { type: 'file', mimeType: '...', data: '...', metadata: { filename: 'my-file.pdf' } }. Using placeholder filename 'LC_AUTOGENERATED'.`),pK)}function hK(e){let t=e._getType();switch(t){case`system`:return`system`;case`ai`:return`assistant`;case`human`:return`user`;case`function`:return`function`;case`tool`:return`tool`;case`generic`:if(!Pn.isInstance(e))throw Error(`Invalid generic chat message`);return dK(e);default:throw Error(`Unknown message type: ${t}`)}}function gK(e){return!!(e.includes(`gpt-5.2-pro`)||e.includes(`gpt-5.4-pro`)||e.includes(`gpt-5.5-pro`)||e.includes(`codex`))}function _K(e){let{azureOpenAIApiDeploymentName:t,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:r,azureOpenAIBasePath:i,baseURL:a,azureADTokenProvider:o,azureOpenAIEndpoint:s}=e;if((r||o)&&i&&t)return`${i}/${t}`;if((r||o)&&s&&t)return`${s}/openai/deployments/${t}`;if(r||o){if(!n)throw Error(`azureOpenAIApiInstanceName is required when using azureOpenAIApiKey`);if(!t)throw Error(`azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey`);return`https://${n}.openai.azure.com/openai/deployments/${t}`}return a}function vK(e){return typeof Headers<`u`&&typeof e==`object`&&!!e&&Object.prototype.toString.call(e)===`[object Headers]`}function yK(e){let t=lK(()=>{if(vK(e))return e;if(Array.isArray(e))return new Headers(e);if(typeof e==`object`&&e&&`values`in e&&vK(e.values))return e.values;if(typeof e==`object`&&e){let t=Object.entries(e).filter(([,e])=>typeof e==`string`).map(([e,t])=>[e,t]);return new Headers(t)}return new Headers});return Object.fromEntries(t.entries())}function bK(){let e=si();return(e===`node`||e===`deno`)&&(e=`(${e}/${process.version}; ${process.platform}; ${process.arch})`),e}function xK(e,t=!1,n=`1.0.0`){let r=yK(e),i=bK(),a=`langchainjs${t?`-azure`:``}-openai`;return{...r,"User-Agent":r[`User-Agent`]?`${a}/${n} (${i})${r[`User-Agent`]}`:`${a}/${n} (${i})`}}function SK(e,t){let n;return n=eA(e)?CM(e):e,t?.strict!==void 0&&(n.function.strict=t.strict),n}function CK(e){return e.anyOf!==void 0&&Array.isArray(e.anyOf)}function wK(e){let t=[`namespace functions {`,``];for(let n of e)n.description&&t.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(t.push(`type ${n.name} = (_: {`),t.push(TK(n.parameters,0)),t.push(`}) => any;`)):t.push(`type ${n.name} = () => any;`),t.push(``);return t.push(`} // namespace functions`),t.join(`
|
|
207
|
+
`)}function TK(e,t){let n=[];for(let[r,i]of Object.entries(e.properties??{}))i.description&&t<2&&n.push(`// ${i.description}`),e.required?.includes(r)?n.push(`${r}: ${EK(i,t)},`):n.push(`${r}?: ${EK(i,t)},`);return n.map(e=>` `.repeat(t)+e).join(`
|
|
208
|
+
`)}function EK(e,t){if(CK(e))return e.anyOf.map(e=>EK(e,t)).join(` | `);switch(e.type){case`string`:return e.enum?e.enum.map(e=>`"${e}"`).join(` | `):`string`;case`number`:return e.enum?e.enum.map(e=>`${e}`).join(` | `):`number`;case`integer`:return e.enum?e.enum.map(e=>`${e}`).join(` | `):`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`object`:return[`{`,TK(e,t+2),`}`].join(`
|
|
209
|
+
`);case`array`:return e.items?`${EK(e.items,t)}[]`:`any[]`;default:return``}}function DK(e){if(e)return e===`any`||e===`required`?`required`:e===`auto`?`auto`:e===`none`?`none`:typeof e==`string`?{type:`function`,function:{name:e}}:e}function OK(e){return`type`in e&&e.type!==`function`}function kK(e){return typeof e==`object`&&!!e&&`extras`in e&&typeof e.extras==`object`&&e.extras!==null&&`providerToolDefinition`in e.extras&&typeof e.extras.providerToolDefinition==`object`&&e.extras.providerToolDefinition!==null}function AK(e){return typeof e==`object`&&!!e&&`type`in e&&e.type!==`function`}function jK(e){return typeof e==`object`&&!!e&&`metadata`in e&&typeof e.metadata==`object`&&e.metadata!==null&&`customTool`in e.metadata&&typeof e.metadata.customTool==`object`&&e.metadata.customTool!==null}function MK(e){return`type`in e&&e.type===`custom`&&`custom`in e&&typeof e.custom==`object`&&e.custom!==null}function NK(e){if(e.type===`custom_tool_call`)return{...e,type:`tool_call`,call_id:e.id,id:e.call_id,name:e.name,isCustomTool:!0,args:{input:e.input}}}function PK(e){if(e.type===`computer_call`)return{...e,type:`tool_call`,call_id:e.id,id:e.call_id,name:`computer_use`,isComputerTool:!0,args:{action:e.action}}}function FK(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_call`&&`isComputerTool`in e&&e.isComputerTool===!0}function IK(e,t){return typeof e!=`object`||!e||!(`type`in e)||e.type!==`tool_call`?!1:!!(`isCustomTool`in e&&e.isCustomTool===!0||t&&`id`in e&&typeof e.id==`string`&&e.id in t)}function LK(e){return{type:`custom`,name:e.custom.name,description:e.custom.description,format:(()=>{if(e.custom.format){if(e.custom.format.type===`grammar`)return{type:`grammar`,definition:e.custom.format.grammar.definition,syntax:e.custom.format.grammar.syntax};if(e.custom.format.type===`text`)return{type:`text`}}})()}}function RK(e){return{type:`custom`,custom:{name:e.name,description:e.description,format:(()=>{if(e.format){if(e.format.type===`grammar`)return{type:`grammar`,grammar:{definition:e.format.definition,syntax:e.format.syntax}};if(e.format.type===`text`)return{type:`text`}}})()}}}var zK=Symbol(`Let zodToJsonSchema decide on which parser to use`),BK={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`},VK=e=>typeof e==`string`?{...BK,basePath:[`#`],definitions:{},name:e}:{...BK,basePath:[`#`],definitions:{},...e},HK=e=>`_def`in e?e._def:e;function UK(e){if(!e)return!0;for(let t in e)return!1;return!0}var WK=e=>{let t=VK(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[HK(n),{def:HK(n),path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function GK(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function KK(e,t,n,r,i){e[t]=n,GK(e,t,r,i)}function qK(){return{}}function JK(e,t){let n={type:`array`};return e.type?._def?.typeName!==R.ZodAny&&(n.items=Pq(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&KK(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&KK(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(KK(n,`minItems`,e.exactLength.value,e.exactLength.message,t),KK(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function YK(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?KK(n,`minimum`,r.value,r.message,t):KK(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),KK(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?KK(n,`maximum`,r.value,r.message,t):KK(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),KK(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:KK(n,`multipleOf`,r.value,r.message,t);break}return n}function XK(){return{type:`boolean`}}function ZK(e,t,n){return Pq(e.type._def,t,n)}var QK=(e,t,n)=>Pq(e.innerType._def,t,n);function $K(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>$K(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return eq(e,t)}}var eq=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:KK(n,`minimum`,r.value,r.message,t);break;case`max`:KK(n,`maximum`,r.value,r.message,t);break}return n};function tq(e,t,n){return{...Pq(e.innerType._def,t,n),default:e.defaultValue()}}function nq(e,t,n){return t.effectStrategy===`input`?Pq(e.schema._def,t,n):{}}function rq(e){return{type:`string`,enum:[...e.values]}}var iq=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function aq(e,t){let n=[Pq(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),Pq(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(iq(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function oq(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var sq,cq={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:()=>(sq===void 0&&(sq=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),sq),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 lq(e,t){let n={type:`string`};function r(e){return t.patternStrategy===`escape`?uq(e):e}if(e.checks)for(let i of e.checks)switch(i.kind){case`min`:KK(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t);break;case`max`:KK(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:dq(n,`email`,i.message,t);break;case`format:idn-email`:dq(n,`idn-email`,i.message,t);break;case`pattern:zod`:fq(n,cq.email,i.message,t);break}break;case`url`:dq(n,`uri`,i.message,t);break;case`uuid`:dq(n,`uuid`,i.message,t);break;case`regex`:fq(n,i.regex,i.message,t);break;case`cuid`:fq(n,cq.cuid,i.message,t);break;case`cuid2`:fq(n,cq.cuid2,i.message,t);break;case`startsWith`:fq(n,RegExp(`^${r(i.value)}`),i.message,t);break;case`endsWith`:fq(n,RegExp(`${r(i.value)}$`),i.message,t);break;case`datetime`:dq(n,`date-time`,i.message,t);break;case`date`:dq(n,`date`,i.message,t);break;case`time`:dq(n,`time`,i.message,t);break;case`duration`:dq(n,`duration`,i.message,t);break;case`length`:KK(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t),KK(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case`includes`:fq(n,RegExp(r(i.value)),i.message,t);break;case`ip`:i.version!==`v6`&&dq(n,`ipv4`,i.message,t),i.version!==`v4`&&dq(n,`ipv6`,i.message,t);break;case`emoji`:fq(n,cq.emoji,i.message,t);break;case`ulid`:fq(n,cq.ulid,i.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:dq(n,`binary`,i.message,t);break;case`contentEncoding:base64`:KK(n,`contentEncoding`,`base64`,i.message,t);break;case`pattern:zod`:fq(n,cq.base64,i.message,t);break}break;case`nanoid`:fq(n,cq.nanoid,i.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:}return n}var uq=e=>Array.from(e).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(``),dq=(e,t,n,r)=>{e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):KK(e,`format`,t,n,r)},fq=(e,t,n,r)=>{e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:pq(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):KK(e,`pattern`,pq(t,r),n,r)},pq=(e,t)=>{let n=typeof e==`function`?e():e;if(!t.applyRegexFlags||!n.flags)return n.source;let r={i:n.flags.includes(`i`),m:n.flags.includes(`m`),s:n.flags.includes(`s`)},i=r.i?n.source.toLowerCase():n.source,a=``,o=!1,s=!1,c=!1;for(let e=0;e<i.length;e++){if(o){a+=i[e],o=!1;continue}if(r.i){if(s){if(i[e].match(/[a-z]/)){c?(a+=i[e],a+=`${i[e-2]}-${i[e]}`.toUpperCase(),c=!1):i[e+1]===`-`&&i[e+2]?.match(/[a-z]/)?(a+=i[e],c=!0):a+=`${i[e]}${i[e].toUpperCase()}`;continue}}else if(i[e].match(/[a-z]/)){a+=`[${i[e]}${i[e].toUpperCase()}]`;continue}}if(r.m){if(i[e]===`^`){a+=`(^|(?<=[\r
|
|
210
210
|
]))`;continue}else if(i[e]===`$`){a+=`($|(?=[\r
|
|
211
|
-
]))`;continue}}if(r.s&&i[e]===`.`){a+=s?`${i[e]}\r\n`:`[${i[e]}\r\n]`;continue}a+=i[e],i[e]===`\\`?o=!0:s&&i[e]===`]`?s=!1:!s&&i[e]===`[`&&(s=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return a};function oq(e,t){if(t.target===`openApi3`&&e.keyType?._def.typeName===R.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:Eq(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??{}}),{}),additionalProperties:!1};let n={type:`object`,additionalProperties:Eq(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??{}};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===R.ZodString&&e.keyType._def.checks?.length){let r=Object.entries(tq(e.keyType._def,t)).reduce((e,[t,n])=>t===`type`?e:{...e,[t]:n},{});return{...n,propertyNames:r}}else if(e.keyType?._def.typeName===R.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};return n}function sq(e,t){return t.mapStrategy===`record`?oq(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[Eq(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||{},Eq(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||{}],minItems:2,maxItems:2}}}function cq(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function lq(){return{not:{}}}function uq(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var dq={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function fq(e,t){if(t.target===`openApi3`)return pq(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in dq&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=dq[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return pq(e,t)}var pq=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>Eq(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function mq(e,t,n){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`||t.nullableStrategy===`property`?{type:dq[e.innerType._def.typeName],nullable:!0}:{type:[dq[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let r=Eq(e.innerType._def,{...t,currentPath:[...t.currentPath]},n);return r&&`$ref`in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let r=Eq(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return r&&{anyOf:[r,{type:`null`}]}}function hq(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,LK(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?RK(n,`minimum`,r.value,r.message,t):RK(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),RK(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?RK(n,`maximum`,r.value,r.message,t):RK(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),RK(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:RK(n,`multipleOf`,r.value,r.message,t);break}return n}function gq(e,t){return t.removeAdditionalStrategy===`strict`?e.catchall._def.typeName===`ZodNever`?e.unknownKeys!==`strict`:Eq(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0:e.catchall._def.typeName===`ZodNever`?e.unknownKeys===`passthrough`:Eq(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0}function _q(e,t){let n={type:`object`,...Object.entries(e.shape()).reduce((e,[n,r])=>{if(r===void 0||r._def===void 0)return e;let i=[...t.currentPath,`properties`,n],a=Eq(r._def,{...t,currentPath:i,propertyPath:i});if(a===void 0)return e;if(t.openaiStrictMode&&r.isOptional()&&!r.isNullable()&&r._def?.defaultValue===void 0)throw Error(`Zod field at \`${i.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:{...e.properties,[n]:a},required:r.isOptional()&&!t.openaiStrictMode?e.required:[...e.required,n]}},{properties:{},required:[]}),additionalProperties:gq(e,t)};return n.required.length||delete n.required,n}var vq=(e,t,n)=>{if(t.propertyPath&&t.currentPath.slice(0,t.propertyPath.length).toString()===t.propertyPath.toString())return Eq(e.innerType._def,{...t,currentPath:t.currentPath},n);let r=Eq(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]},n);return r?{anyOf:[{not:{}},r]}:{}},yq=(e,t,n)=>{if(t.pipeStrategy===`input`)return Eq(e.in._def,t,n);if(t.pipeStrategy===`output`)return Eq(e.out._def,t,n);let r=Eq(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[r,Eq(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,r?`1`:`0`]})].filter(e=>e!==void 0)}};function bq(e,t,n){return Eq(e.type._def,t,n)}function xq(e,t){let n={type:`array`,uniqueItems:!0,items:Eq(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&RK(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&RK(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function Sq(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>Eq(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:Eq(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>Eq(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Cq(){return{not:{}}}function wq(){return{}}var Tq=(e,t,n)=>Eq(e.innerType._def,t,n);function Eq(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==jK)return i}if(r&&!n){let e=Dq(r,t);if(e!==void 0)return`$ref`in e&&t.seenRefs.add(e.$ref),e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);try{let r=jq(e,e.typeName,t,n);return r&&Mq(e,t,r),i.jsonSchema=r,r}finally{n&&r&&t.seen.set(e,r)}}var Dq=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`extract-to-root`:let n=e.path.slice(t.basePath.length+1).map((e,t)=>t===0?e:kq(e)).join(`_`);return n!==t.name&&t.nameStrategy===`duplicate-ref`&&(t.definitions[n]=e.def),{$ref:[...t.basePath,t.definitionPath,n].join(`/`)};case`relative`:return{$ref:Aq(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),{}):t.$refStrategy===`seen`?{}:void 0}},Oq=`_x_`,kq=e=>{if(/^[A-Za-z0-9_-]*$/.test(e)&&!e.startsWith(Oq))return e;let t=Oq;for(let n=0;n<e.length;n++)t+=e.charCodeAt(n).toString(16).padStart(4,`0`);return t},Aq=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)},jq=(e,t,n,r)=>{switch(t){case R.ZodString:return tq(e,n);case R.ZodNumber:return hq(e,n);case R.ZodObject:return _q(e,n);case R.ZodBigInt:return VK(e,n);case R.ZodBoolean:return HK();case R.ZodDate:return GK(e,n);case R.ZodUndefined:return Cq();case R.ZodNull:return uq(n);case R.ZodArray:return BK(e,n);case R.ZodUnion:case R.ZodDiscriminatedUnion:return fq(e,n);case R.ZodIntersection:return ZK(e,n);case R.ZodTuple:return Sq(e,n);case R.ZodRecord:return oq(e,n);case R.ZodLiteral:return QK(e,n);case R.ZodEnum:return YK(e);case R.ZodNativeEnum:return cq(e);case R.ZodNullable:return mq(e,n,r);case R.ZodOptional:return vq(e,n,r);case R.ZodMap:return sq(e,n);case R.ZodSet:return xq(e,n);case R.ZodLazy:return Eq(e.getter()._def,n,r);case R.ZodPromise:return bq(e,n,r);case R.ZodNaN:case R.ZodNever:return lq();case R.ZodEffects:return JK(e,n,r);case R.ZodAny:return zK();case R.ZodUnknown:return wq();case R.ZodDefault:return qK(e,n,r);case R.ZodBranded:return UK(e,n,r);case R.ZodReadonly:return Tq(e,n,r);case R.ZodCatch:return WK(e,n,r);case R.ZodPipeline:return yq(e,n,r);case R.ZodFunction:case R.ZodVoid:case R.ZodSymbol:return;default:return(e=>void 0)(t)}},Mq=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Nq=(e,t)=>{let n=IK(t),r=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,i=Eq(e._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??{},a=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;a!==void 0&&(i.title=a);let o=(()=>{if(FK(n.definitions))return;let e={},t=new Set;for(let r=0;r<500;r++){let r=Object.entries(n.definitions).filter(([e])=>!t.has(e));if(r.length===0)break;for(let[i,a]of r)e[i]=Eq(PK(a),{...n,currentPath:[...n.basePath,n.definitionPath,i]},!0)??{},t.add(i)}return e})(),s=r===void 0?o?{...i,[n.definitionPath]:o}:i:n.nameStrategy===`duplicate-ref`?{...i,...o||n.seenRefs.size?{[n.definitionPath]:{...o,...n.seenRefs.size?{[r]:i}:void 0}}:void 0}:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,r].join(`/`),[n.definitionPath]:{...o,[r]:i}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:n.target===`jsonSchema2019-09`&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),s};function Pq(e){if(e.type!==`object`)throw Error(`Root schema must have type: 'object' but got type: ${e.type?`'${e.type}'`:`undefined`}`);let t=structuredClone(e);return Iq(t,[],t)}function Fq(e){if(typeof e==`boolean`)return!1;if(e.type===`null`)return!0;for(let t of e.oneOf??[])if(Fq(t))return!0;for(let t of e.anyOf??[])if(Fq(t))return!0;return!1}function Iq(e,t,n){if(typeof e==`boolean`)throw TypeError(`Expected object schema but got boolean; path=${t.join(`/`)}`);if(!Rq(e))throw TypeError(`Expected ${JSON.stringify(e)} to be an object; path=${t.join(`/`)}`);let r=e.$defs;if(Rq(r))for(let[e,i]of Object.entries(r))Iq(i,[...t,`$defs`,e],n);let i=e.definitions;if(Rq(i))for(let[e,r]of Object.entries(i))Iq(r,[...t,`definitions`,e],n);e.type===`object`&&!(`additionalProperties`in e)&&(e.additionalProperties=!1);let a=e.required??[],o=e.properties;if(Rq(o)){for(let[e,n]of Object.entries(o))if(!Fq(n)&&!a.includes(e))throw Error(`Zod field at \`${[...t,`properties`,e].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`);e.required=Object.keys(o),e.properties=Object.fromEntries(Object.entries(o).map(([e,r])=>[e,Iq(r,[...t,`properties`,e],n)]))}let s=e.items;Rq(s)&&(e.items=Iq(s,[...t,`items`],n));let c=e.anyOf;Array.isArray(c)&&(e.anyOf=c.map((e,r)=>Iq(e,[...t,`anyOf`,String(r)],n)));let l=e.allOf;if(Array.isArray(l))if(l.length===1){let r=Iq(l[0],[...t,`allOf`,`0`],n);Object.assign(e,r),delete e.allOf}else e.allOf=l.map((e,r)=>Iq(e,[...t,`allOf`,String(r)],n));e.default===null&&delete e.default;let u=e.$ref;if(u&&zq(e,1)){if(typeof u!=`string`)throw TypeError(`Received non-string $ref - ${u}; path=${t.join(`/`)}`);let r=Lq(n,u);if(typeof r==`boolean`)throw Error(`Expected \`$ref: ${u}\` to resolve to an object schema but got boolean`);if(!Rq(r))throw Error(`Expected \`$ref: ${u}\` to resolve to an object but got ${JSON.stringify(r)}`);return Object.assign(e,{...r,...e}),delete e.$ref,Iq(e,t,n)}return e}function Lq(e,t){if(!t.startsWith(`#/`))throw Error(`Unexpected $ref format ${JSON.stringify(t)}; Does not start with #/`);let n=t.slice(2).split(`/`),r=e;for(let e of n){if(!Rq(r))throw Error(`encountered non-object entry while resolving ${t} - ${JSON.stringify(r)}`);let n=r[e];if(n===void 0)throw Error(`Key ${e} not found while resolving ${t}`);r=n}return r}function Rq(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zq(e,t){let n=0;for(let r in e)if(n++,n>t)return!0;return!1}function Bq(e,t){return Nq(e,{openaiStrictMode:!0,name:t.name,nameStrategy:`duplicate-ref`,$refStrategy:`extract-to-root`,nullableStrategy:`property`})}function Vq(e){return Pq(k_(e,{target:`draft-7`,override:({zodSchema:e,jsonSchema:t})=>{let n=e._zod.def;if(n.type===`union`&&`discriminator`in n&&Array.isArray(t.oneOf)){if(t.anyOf!==void 0)throw Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");t.anyOf=t.oneOf,delete t.oneOf}}}))}function Hq(e){return`_zod`in e}function Uq(e,t,n){return JV({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:Hq(e)?Vq(e):Bq(e,{name:t})}},t=>e.parse(JSON.parse(t)))}var Wq=[`jsonSchema`,`functionCalling`,`jsonMode`];function Gq(e,t){if(t!==void 0&&!Wq.includes(t))throw Error(`Invalid method: ${t}. Supported methods are: ${Wq.join(`, `)}`);let n=!e.startsWith(`gpt-3`)&&!e.startsWith(`gpt-4-`)&&e!==`gpt-4`;if(n&&!t)return`jsonSchema`;if(!n&&t===`jsonSchema`)throw Error(`JSON Schema is not supported for model "${e}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return t??`functionCalling`}function Kq(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:`auto-parseable-response-format`,enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function qq(e,t,n){if(j_(e))return Uq(e,t,n);if(A_(e))return Kq({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:Rx(e,{cycles:`ref`,reused:`ref`,override(e){e.jsonSchema.title=t}})}},t=>$f(e,JSON.parse(t)));throw Error(`Unsupported schema response format`)}function Jq(e,t){if(t&&typeof t==`object`&&`images`in t&&Array.isArray(t.images)){let n=t.images.filter(e=>typeof e?.image_url?.url==`string`).map(e=>({type:`image`,url:e.image_url.url}));return[{type:`text`,text:e},...n]}return e}var Yq={"gpt-4o-2024-11-20":{maxInputTokens:128e3,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,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:128e3,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:128e3,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,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:2e5,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,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:2e5,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:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,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:2e5,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:128e3,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,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},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,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},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,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:128e3,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,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:128e3,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,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:128e3,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}};function Xq(e,t){return typeof e==`string`?{model:e,...t??{}}:e??t}var Zq=class extends iD{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`.split(`.`)}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`openai`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(e){super(e??{});let t=typeof e?.configuration?.apiKey==`string`||typeof e?.configuration?.apiKey==`function`?e?.configuration?.apiKey:void 0;this.apiKey=e?.apiKey??t??ui(`OPENAI_API_KEY`),this.organization=e?.configuration?.organization??ui(`OPENAI_ORGANIZATION`),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoning=e?.reasoning,this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.promptCacheKey=e?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=e?.promptCacheRetention??this.promptCacheRetention,this.verbosity=e?.verbosity??this.verbosity,this.disableStreaming=e?.disableStreaming===!0,this.streaming=e?.streaming===!0,this.disableStreaming&&(this.streaming=!1),e?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},e?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),e?.service_tier!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1,this._addVersion(`@langchain/openai`,`1.5.3`)}_getReasoningParams(e){if(!nK(this.model))return;let t;return this.reasoning!==void 0&&(t={...t,...this.reasoning}),e?.reasoning!==void 0&&(t={...t,...e.reasoning}),e?.reasoningEffort!==void 0&&t?.effort===void 0&&(t={...t,effort:e.reasoningEffort}),t}_getResponseFormat(e){return e&&e.type===`json_schema`&&e.json_schema.schema&&N_(e.json_schema.schema)?qq(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){let e=lK({baseURL:this.clientConfig.baseURL}),t={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};t.baseURL||delete t.baseURL,t.defaultHeaders=pK(t.defaultHeaders),this.client=new Y(t)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return CK(e)?AK(e.metadata.customTool):UT(e)?t?.strict===void 0?e:{...e,function:{...e.function,strict:t.strict}}:mK(e,t)}bindTools(e,t){let n;return t?.strict===void 0?this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling):n=t.strict,this.withConfig({tools:e.map(e=>{if(bK(e)||CK(e))return e;if(xK(e))return e.extras.providerToolDefinition;let t=this._convertChatOpenAIToolToCompletionsTool(e,{strict:n});return eA(e)&&e.extras?.defer_loading===!0?{...t,defer_loading:!0}:t}),...t})}async stream(e,t){return super.stream(e,this._combineCallOptions(t))}async invoke(e,t){return super.invoke(e,this._combineCallOptions(t))}_combineLLMOutput(...e){return e.reduce((e,t)=>(t&&t.tokenUsage&&(e.tokenUsage.completionTokens+=t.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=t.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=t.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=0,n=0,r=0;this.model===`gpt-3.5-turbo-0301`?(n=4,r=-1):(n=3,r=1);let i=await Promise.all(e.map(async e=>{let[i,a]=await Promise.all([this.getNumTokens(e.content),this.getNumTokens(sK(e))]),o=e.name===void 0?0:r+await this.getNumTokens(e.name),s=i+n+a+o,c=e;if(c._getType()===`function`&&(s-=2),c.additional_kwargs?.function_call&&(s+=3),c?.additional_kwargs.function_call?.name&&(s+=await this.getNumTokens(c.additional_kwargs.function_call?.name)),c.additional_kwargs.function_call?.arguments)try{s+=await this.getNumTokens(JSON.stringify(JSON.parse(c.additional_kwargs.function_call?.arguments)))}catch(e){console.error(`Error parsing function arguments`,e,JSON.stringify(c.additional_kwargs.function_call)),s+=await this.getNumTokens(c.additional_kwargs.function_call?.arguments)}return t+=s,s}));return t+=3,{totalCount:t,countPerMessage:i}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,t)=>e+t,0)}async _getEstimatedTokenCountFromPrompt(e,t,n){let r=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&n!==`auto`){let e=gK(t);r+=await this.getNumTokens(e),r+=9}return t&&e.find(e=>e._getType()===`system`)&&(r-=4),n===`none`?r+=1:typeof n==`object`&&(r+=await this.getNumTokens(n.name)+4),r}async moderateContent(e,t){let n=this._getClientOptions(t?.options),r={input:e,model:t?.model??`omni-moderation-latest`};return this.caller.call(async()=>{try{return await this.client.moderations.create(r,n)}catch(e){throw eK(e)}})}get profile(){return Yq[this.model]??{}}_getStructuredOutputMethod(e){let t={...e};if(!this.model.startsWith(`gpt-3`)&&!this.model.startsWith(`gpt-4-`)&&this.model!==`gpt-4`){if(t?.method===void 0)return`jsonSchema`}else t.method===`jsonSchema`&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return t.method}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e};if(t?.strict!==void 0&&t.method===`jsonMode`)throw Error("Argument `strict` is only supported for `method` = 'function_calling'");let s=Gq(this.model,t?.method);if(s===`jsonMode`){r=EE(i);let e=Rx(i);n=this.withConfig({outputVersion:`v0`,response_format:{type:`json_object`},ls_structured_output_format:{kwargs:{method:`json_mode`},schema:{title:a??`extract`,...e}}})}else if(s===`jsonSchema`){let e=Rx(i),o={name:a??`extract`,description:V_(e),schema:N_(i)?i:e,strict:t?.strict};if(n=this.withConfig({outputVersion:`v0`,response_format:{type:`json_schema`,json_schema:o},ls_structured_output_format:{kwargs:{method:`json_schema`},schema:{title:o.name,description:o.description,...e}}}),N_(i)||Zb(i)){let e=EE(i);r=lS.from(async t=>`parsed`in t.additional_kwargs?t.additional_kwargs.parsed:e.invoke(t.content))}else r=new sE}else{let e=a??`extract`,o=Rx(i),s;N_(i)||Zb(i)?s={name:e,description:o.description,parameters:o}:typeof i.name==`string`&&typeof i.parameters==`object`&&i.parameters!=null?(s=i,e=i.name):(e=i.title??e,s={name:e,description:i.description??``,parameters:i}),n=this.withConfig({outputVersion:`v0`,tools:[{type:`function`,function:s}],tool_choice:{type:`function`,function:{name:e}},ls_structured_output_format:{kwargs:{method:`function_calling`},schema:{title:e,...o}},...t?.strict===void 0?{}:{strict:t.strict}}),r=DE(i,e)}return OE(n,r,o)}},Qq={providerName:`ChatOpenAI`,fromStandardTextBlock(e){return{type:`text`,text:e.text}},fromStandardImageBlock(e){if(e.source_type===`url`)return{type:`image_url`,image_url:{url:e.url,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};if(e.source_type===`base64`)return{type:`image_url`,image_url:{url:`data:${e.mime_type??``};base64,${e.data}`,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};throw Error(`Image content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(e){if(e.source_type===`url`){let t=et({dataUrl:e.url});if(!t)throw Error(`URL audio blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);let n=t.mime_type||e.mime_type||``,r;try{r=$e(n)}catch{throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(r.type!==`audio`||r.subtype!==`wav`&&r.subtype!==`mp3`)throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:`input_audio`,input_audio:{format:r.subtype,data:t.data}}}if(e.source_type===`base64`){let t;try{t=$e(e.mime_type??``)}catch{throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(t.type!==`audio`||t.subtype!==`wav`&&t.subtype!==`mp3`)throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:`input_audio`,input_audio:{format:t.subtype,data:e.data}}}throw Error(`Audio content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(e){if(e.source_type===`url`){let t=et({dataUrl:e.url}),n=oK(e);if(!t)throw Error(`URL file blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:`file`,file:{file_data:e.url,filename:n}}}if(e.source_type===`base64`){let t=oK(e);return{type:`file`,file:{file_data:`data:${e.mime_type??``};base64,${e.data}`,filename:t}}}if(e.source_type===`id`)return{type:`file`,file:{file_id:e.id}};throw Error(`File content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)}},$q=({message:e,rawResponse:t,includeRawResponse:n})=>{let r=e.tool_calls,i=e.reasoning_content;switch(e.role){case`assistant`:{let a=[],o=[];for(let e of r??[])try{a.push(bE(e,{returnId:!0}))}catch(t){o.push(SE(e,t.message))}let s={function_call:e.function_call,tool_calls:r};n!==void 0&&(s.__raw_response=t),i!==void 0&&(s.reasoning_content=i);let c={model_provider:`openai`,model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};return e.audio&&(s.audio=e.audio),new An({content:Jq(e.content||``,t.choices?.[0]?.message),tool_calls:a,invalid_tool_calls:o,additional_kwargs:s,response_metadata:c,id:t.id})}default:return new Pn(e.content||``,e.role??`unknown`)}},eJ=({delta:e,rawResponse:t,includeRawResponse:n,defaultRole:r})=>{let i=e.role??r,a=e.content??``,o;o=e.function_call?{function_call:e.function_call}:e.tool_calls?{tool_calls:e.tool_calls}:{},n&&(o.__raw_response=t),e.reasoning_content!==void 0&&(o.reasoning_content=e.reasoning_content),e.audio&&(o.audio={...e.audio,index:t.choices[0].index});let s={model_provider:`openai`,usage:{...t.usage}};if(i===`user`)return new Un({content:a,response_metadata:s});if(i===`assistant`){let n=[];if(Array.isArray(e.tool_calls))for(let t of e.tool_calls)n.push({name:t.function?.name,args:t.function?.arguments,id:t.id,index:t.index,type:`tool_call_chunk`});return new Nn({content:a,tool_call_chunks:n,additional_kwargs:o,id:t.id,response_metadata:s})}else if(i===`system`)return new Jn({content:a,response_metadata:s});else if(i===`developer`)return new Jn({content:a,response_metadata:s,additional_kwargs:{__openai_role__:`developer`}});else if(i===`function`)return new zn({content:a,additional_kwargs:o,name:e.name,response_metadata:s});else if(i===`tool`)return new Zt({content:a,additional_kwargs:o,tool_call_id:e.tool_call_id,response_metadata:s});else return new Fn({content:a,role:i,response_metadata:s})},tJ=e=>{if(e.type===`image`){if(e.url)return{type:`image_url`,image_url:{url:e.url}};if(e.data)return{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}}if(e.type===`audio`&&e.data){let t=Qn(()=>{let[,t]=e.mimeType.split(`/`);return t===`wav`||t===`mp3`?t:`wav`});return{type:`input_audio`,input_audio:{data:e.data.toString(),format:t}}}if(e.type===`file`){if(e.data){let t=oK(e);return{type:`file`,file:{file_data:`data:${e.mimeType};base64,${e.data}`,filename:t}}}if(e.fileId)return{type:`file`,file:{file_id:e.fileId}}}},nJ=({message:e,model:t})=>{let n=sK(e);if(n===`system`&&nK(t)&&(n=`developer`),n===`developer`)return{role:`developer`,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`system`)return{role:`system`,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`assistant`){let t={role:`assistant`,content:e.contentBlocks.filter(e=>e.type===`text`)};return An.isInstance(e)&&e.tool_calls?.length?t.tool_calls=e.tool_calls.map(xE):e.additional_kwargs.tool_calls!=null&&(t.tool_calls=e.additional_kwargs.tool_calls),t}else if(n===`tool`&&Xt.isInstance(e))return{role:`tool`,tool_call_id:e.tool_call_id,content:e.contentBlocks.filter(e=>e.type===`text`)};else if(n===`function`)return{role:`function`,name:e.name??``,content:e.contentBlocks.filter(e=>e.type===`text`).join(``)};function*r(e){for(let t of e){t.type===`text`&&(yield{type:`text`,text:t.text});let e=tJ(t);e&&(yield e)}}return{role:`user`,content:Array.from(r(e.contentBlocks))}},rJ=({messages:e,model:t})=>e.flatMap(e=>{if(`output_version`in e.response_metadata&&e.response_metadata?.output_version===`v1`)return nJ({message:e});let n=sK(e);n===`system`&&nK(t)&&(n=`developer`);let r=typeof e.content==`string`?e.content:e.content.flatMap(e=>qe(e)?tt(e,Qq):typeof e==`object`&&e&&`type`in e&&e.type===`tool_use`?[]:e),i={role:n,content:r};return e.name!=null&&(i.name=e.name),e.additional_kwargs.function_call!=null&&(i.function_call=e.additional_kwargs.function_call),An.isInstance(e)&&e.tool_calls?.length?i.tool_calls=e.tool_calls.map(xE):(e.additional_kwargs.tool_calls!=null&&(i.tool_calls=e.additional_kwargs.tool_calls),Xt.isInstance(e)&&e.tool_call_id!=null&&(i.tool_call_id=e.tool_call_id)),e.additional_kwargs.audio&&typeof e.additional_kwargs.audio==`object`&&`id`in e.additional_kwargs.audio?[i,{role:`assistant`,audio:{id:e.additional_kwargs.audio.id}}]:i}),iJ=class extends Zq{constructor(e,t){super(Xq(e,t))}invocationParams(e,t){let n;e?.strict===void 0?this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling):n=e.strict,!(this.streaming||t?.streaming)&&e?.response_format?.type===`json_schema`&&n!==!1&&(n=!0);let r={};e?.stream_options===void 0?this.streamUsage&&(this.streaming||t?.streaming)&&(r={stream_options:{include_usage:!0}}):r={stream_options:e.stream_options};let i={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:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map(e=>this._convertChatOpenAIToolToCompletionsTool(e,{strict:n})):void 0,tool_choice:yK(e?.tool_choice),response_format:this._getResponseFormat(e?.response_format),seed:e?.seed,...r,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,verbosity:e?.verbosity??this.verbosity};e?.prediction!==void 0&&(i.prediction=e.prediction),this.service_tier!==void 0&&(i.service_tier=this.service_tier),e?.service_tier!==void 0&&(i.service_tier=e.service_tier);let a=this._getReasoningParams(e);return a!==void 0&&a.effort!==void 0&&(i.reasoning_effort=a.effort),nK(i.model)?i.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:i.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,i}async _generate(e,t,n){t.signal?.throwIfAborted();let r={},i=this.invocationParams(t),a=rJ({messages:e,model:this.model});if(i.stream){let i=this._streamResponseChunks(e,t,n),a={};for await(let e of i){e.message.response_metadata={...e.generationInfo,...e.message.response_metadata};let t=e.generationInfo?.completion??0;a[t]===void 0?a[t]=e:a[t]=a[t].concat(e)}let o=Object.entries(a).sort(([e],[t])=>parseInt(e,10)-parseInt(t,10)).map(([e,t])=>t),{functions:s,function_call:c}=this.invocationParams(t),l=await this._getEstimatedTokenCountFromPrompt(e,s,c),u=await this._getNumTokensFromGenerations(o);return r.input_tokens=l,r.output_tokens=u,r.total_tokens=l+u,{generations:o,llmOutput:{estimatedTokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}else{let e=await this.completionWithRetry({...i,stream:!1,messages:a},{signal:t?.signal,...t?.options}),{completion_tokens:n,prompt_tokens:o,total_tokens:s,prompt_tokens_details:c,completion_tokens_details:l}=e?.usage??{};n&&(r.output_tokens=(r.output_tokens??0)+n),o&&(r.input_tokens=(r.input_tokens??0)+o),s&&(r.total_tokens=(r.total_tokens??0)+s),(c?.audio_tokens!==null||c?.cached_tokens!==null)&&(r.input_token_details={...c?.audio_tokens!==null&&{audio:c?.audio_tokens},...c?.cached_tokens!==null&&{cache_read:c?.cached_tokens}}),(l?.audio_tokens!==null||l?.reasoning_tokens!==null)&&(r.output_token_details={...l?.audio_tokens!==null&&{audio:l?.audio_tokens},...l?.reasoning_tokens!==null&&{reasoning:l?.reasoning_tokens}});let u=[];for(let t of e?.choices??[]){let n={text:t.message?.content??``,message:this._convertCompletionsMessageToBaseMessage(t.message??{role:`assistant`},e)};n.generationInfo={...t.finish_reason?{finish_reason:t.finish_reason}:{},...t.logprobs?{logprobs:t.logprobs}:{}},jn(n.message)&&(n.message.usage_metadata=r),n.message=new An(Object.fromEntries(Object.entries(n.message).filter(([e])=>!e.startsWith(`lc_`)))),u.push(n)}return{generations:u,llmOutput:{tokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}}async*_streamChatModelEvents(e,t,n){let r=rJ({messages:e,model:this.model}),i={...this.invocationParams(t,{streaming:!0}),messages:r,stream:!0},a=await this.completionWithRetry(i,t),o=this.streamUsage??t.streamUsage;yield*sD(async function*(e,t){for await(let n of e){if(t?.aborted)return;yield n}}(a,t.signal),{streamUsage:o??!0,provider:this.streamEventProvider})}get streamEventProvider(){return`openai`}async*_streamResponseChunks(e,t,n){let r=rJ({messages:e,model:this.model}),i={...this.invocationParams(t,{streaming:!0}),messages:r,stream:!0},a,o=await this.completionWithRetry(i,t),s;for await(let e of o){if(t.signal?.aborted)return;let r=e?.choices?.[0];if(e.usage&&(s=e.usage),!r)continue;let{delta:i}=r;if(!i)continue;let o=this._convertCompletionsDeltaToBaseMessageChunk(i,e,a);a=i.role??a;let c={prompt:t.promptIndex??0,completion:r.index??0};if(typeof o.content!=`string`){console.log(`[WARNING]: Received non-string content from OpenAI. This is currently not supported.`);continue}let l={...c};r.finish_reason!=null&&(l.finish_reason=r.finish_reason,l.system_fingerprint=e.system_fingerprint,l.model_name=e.model,l.service_tier=e.service_tier),this.logprobs&&(l.logprobs=r.logprobs);let u=new xd({message:o,text:o.content,generationInfo:l});yield u,await n?.handleLLMNewToken(u.text??``,c,void 0,void 0,void 0,{chunk:u})}if(s){let e={...s.prompt_tokens_details?.audio_tokens!==null&&{audio:s.prompt_tokens_details?.audio_tokens},...s.prompt_tokens_details?.cached_tokens!==null&&{cache_read:s.prompt_tokens_details?.cached_tokens}},t={...s.completion_tokens_details?.audio_tokens!==null&&{audio:s.completion_tokens_details?.audio_tokens},...s.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:s.completion_tokens_details?.reasoning_tokens}},r=new xd({message:new Nn({content:``,response_metadata:{usage:{...s}},usage_metadata:{input_tokens:s.prompt_tokens,output_tokens:s.completion_tokens,total_tokens:s.total_tokens,...Object.keys(e).length>0&&{input_token_details:e},...Object.keys(t).length>0&&{output_token_details:t}}}),text:``});yield r,await n?.handleLLMNewToken(r.text??``,{prompt:0,completion:0},void 0,void 0,void 0,{chunk:r})}if(t.signal?.aborted)throw Error(`AbortError`)}async completionWithRetry(e,t){let n=this._getClientOptions(t),r=e.response_format&&e.response_format.type===`json_schema`;return this.caller.call(async()=>{try{return r&&!e.stream?await this.client.chat.completions.parse(e,n):await this.client.chat.completions.create(e,n)}catch(e){throw eK(e)}})}_convertCompletionsDeltaToBaseMessageChunk(e,t,n){return eJ({delta:e,rawResponse:t,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(e,t){return $q({message:e,rawResponse:t,includeRawResponse:this.__includeRawResponse})}},aJ={openAIApiKey:`openai_api_key`,openAIApiVersion:`openai_api_version`,openAIBasePath:`openai_api_base`,deploymentName:`deployment_name`,azureOpenAIEndpoint:`azure_endpoint`,azureOpenAIApiVersion:`openai_api_version`,azureOpenAIBasePath:`openai_api_base`,azureOpenAIApiDeploymentName:`deployment_name`},oJ={azureOpenAIApiKey:`AZURE_OPENAI_API_KEY`},sJ=[`azureOpenAIApiKey`,`azureOpenAIApiVersion`,`azureOpenAIBasePath`,`azureOpenAIEndpoint`,`azureOpenAIApiInstanceName`,`azureOpenAIApiDeploymentName`,`deploymentName`,`openAIApiKey`,`openAIApiVersion`];function cJ(e,t){return typeof e==`string`?{model:e,deploymentName:e,azureOpenAIApiDeploymentName:e,...t??{}}:e??t}function lJ(e){if(this.azureOpenAIApiKey=e?.azureOpenAIApiKey??(typeof e?.openAIApiKey==`string`?e?.openAIApiKey:void 0)??(typeof e?.apiKey==`string`?e?.apiKey:void 0)??ui(`AZURE_OPENAI_API_KEY`),this.azureOpenAIApiInstanceName=e?.azureOpenAIApiInstanceName??ui(`AZURE_OPENAI_API_INSTANCE_NAME`),this.azureOpenAIApiDeploymentName=e?.azureOpenAIApiDeploymentName??e?.deploymentName??ui(`AZURE_OPENAI_API_DEPLOYMENT_NAME`),this.azureOpenAIApiVersion=e?.azureOpenAIApiVersion??e?.openAIApiVersion??ui(`AZURE_OPENAI_API_VERSION`),this.azureOpenAIBasePath=e?.azureOpenAIBasePath??ui(`AZURE_OPENAI_BASE_PATH`),this.azureOpenAIEndpoint=e?.azureOpenAIEndpoint??ui(`AZURE_OPENAI_ENDPOINT`),this.azureADTokenProvider=e?.azureADTokenProvider,!this.azureOpenAIApiKey&&!this.apiKey&&!this.azureADTokenProvider)throw Error(`Azure OpenAI API key or Token Provider not found`)}function uJ(e){if(!this.client){let e={azureOpenAIApiDeploymentName:this.azureOpenAIApiDeploymentName,azureOpenAIApiInstanceName:this.azureOpenAIApiInstanceName,azureOpenAIApiKey:this.azureOpenAIApiKey,azureOpenAIBasePath:this.azureOpenAIBasePath,azureADTokenProvider:this.azureADTokenProvider,baseURL:this.clientConfig.baseURL,azureOpenAIEndpoint:this.azureOpenAIEndpoint},t=lK(e),{apiKey:n,...r}=this.clientConfig,i={...r,baseURL:t,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(i.apiKey=e.azureOpenAIApiKey),i.baseURL||delete i.baseURL,i.defaultHeaders=pK(i.defaultHeaders,!0,`2.0.0`),this.client=new ZG({apiVersion:this.azureOpenAIApiVersion,azureADTokenProvider:this.azureADTokenProvider,deployment:this.azureOpenAIApiDeploymentName,...i})}let t={...this.clientConfig,...e};return this.azureOpenAIApiKey&&(t.headers={"api-key":this.azureOpenAIApiKey,...t.headers},t.query={"api-version":this.azureOpenAIApiVersion,...t.query}),t}function dJ(e){let t=e;function n(e){return typeof e==`object`&&!!e}if(n(t)&&n(t.kwargs)){if(delete t.kwargs.azure_openai_base_path,delete t.kwargs.azure_openai_api_deployment_name,delete t.kwargs.azure_openai_api_key,delete t.kwargs.azure_openai_api_version,delete t.kwargs.azure_open_ai_base_path,!t.kwargs.azure_endpoint&&this.azureOpenAIEndpoint&&(t.kwargs.azure_endpoint=this.azureOpenAIEndpoint),!t.kwargs.azure_endpoint&&this.azureOpenAIBasePath){let e=this.azureOpenAIBasePath.split(`/openai/deployments/`);if(e.length===2&&e[0].startsWith(`http`)){let[n]=e;t.kwargs.azure_endpoint=n}}if(!t.kwargs.azure_endpoint&&this.azureOpenAIApiInstanceName&&(t.kwargs.azure_endpoint=`https://${this.azureOpenAIApiInstanceName}.openai.azure.com/`),!t.kwargs.deployment_name&&this.azureOpenAIApiDeploymentName&&(t.kwargs.deployment_name=this.azureOpenAIApiDeploymentName),!t.kwargs.deployment_name&&this.azureOpenAIBasePath){let e=this.azureOpenAIBasePath.split(`/openai/deployments/`);if(e.length===2){let[,n]=e;t.kwargs.deployment_name=n}}t.kwargs.azure_endpoint&&t.kwargs.deployment_name&&t.kwargs.openai_api_base&&delete t.kwargs.openai_api_base,t.kwargs.azure_openai_api_instance_name&&t.kwargs.azure_endpoint&&delete t.kwargs.azure_openai_api_instance_name}return t}var fJ=class extends iJ{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,...aJ}}get lc_secrets(){return{...super.lc_secrets,...oJ}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...sJ]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=cJ(e,t);super(n),lJ.call(this,n)}_getClientOptions(e){return uJ.call(this,e)}toJSON(){return dJ.call(this,super.toJSON())}},pJ=`__openai_function_call_ids__`,mJ=`__openai_custom_tool_call_ids__`;function hJ(e){return e.type===`url_citation`?{type:`citation`,source:`url_citation`,url:e.url,title:e.title,startIndex:e.start_index,endIndex:e.end_index}:e.type===`file_citation`?{type:`citation`,source:`file_citation`,title:e.filename,startIndex:e.index,file_id:e.file_id}:e.type===`container_file_citation`?{type:`citation`,source:`container_file_citation`,title:e.filename,startIndex:e.start_index,endIndex:e.end_index,file_id:e.file_id,container_id:e.container_id}:e.type===`file_path`?{type:`citation`,source:`file_path`,startIndex:e.index,file_id:e.file_id}:{type:`non_standard`,value:e}}function gJ(e){if(e.type===`url_citation`||e.type===`file_citation`||e.type===`container_file_citation`||e.type===`file_path`)return e;if(e.type===`citation`){let t=e;if(t.source===`url_citation`)return{type:`url_citation`,url:t.url??``,title:t.title??``,start_index:t.startIndex??0,end_index:t.endIndex??0};if(t.source===`file_citation`)return{type:`file_citation`,file_id:t.file_id??``,filename:t.title??``,index:t.startIndex??0};if(t.source===`container_file_citation`)return{type:`container_file_citation`,file_id:t.file_id??``,filename:t.title??``,container_id:t.container_id??``,start_index:t.startIndex??0,end_index:t.endIndex??0};if(t.source===`file_path`)return{type:`file_path`,file_id:t.file_id??``,index:t.startIndex??0}}return e.type===`non_standard`?e.value:e}var _J=e=>{let t={...e?.input_tokens_details?.cached_tokens!=null&&{cache_read:e?.input_tokens_details?.cached_tokens}},n={...e?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:e?.output_tokens_details?.reasoning_tokens}};return{input_tokens:e?.input_tokens??0,output_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,input_token_details:t,output_token_details:n}},vJ=e=>{if(e.error){let t=Error(e.error.message);throw t.name=e.error.code,t}let t=[],n=[],r=[],i=e.output.map(e=>{if(e.type===`function_call`&&`parsed_arguments`in e){let t={...e};return delete t.parsed_arguments,t}return e}),a={model_provider:`openai`,model:e.model,created_at:e.created_at,id:e.id,incomplete_details:e.incomplete_details,metadata:e.metadata,object:e.object,output:i,status:e.status,user:e.user,service_tier:e.service_tier,model_name:e.model},o={};for(let i of e.output)if(i.type===`message`)t.push(...i.content.flatMap(e=>e.type===`output_text`?(`parsed`in e&&e.parsed!=null&&(o.parsed=e.parsed),{type:`text`,text:e.text,annotations:e.annotations.map(hJ),...i.phase===null?{}:{phase:i.phase}}):e.type===`refusal`?(o.refusal=e.refusal,[]):e));else if(i.type===`function_call`){let e={function:{name:i.name,arguments:i.arguments},id:i.call_id};try{n.push(bE(e,{returnId:!0}))}catch(t){let n;typeof t==`object`&&t&&`message`in t&&typeof t.message==`string`&&(n=t.message),r.push(SE(e,n))}o[pJ]??={},i.id&&(o[pJ][i.call_id]=i.id)}else if(i.type===`reasoning`){o.reasoning=i;let e=i.summary?.map(e=>e.text).filter(Boolean).join(``);e&&t.push({type:`reasoning`,reasoning:e})}else if(i.type===`custom_tool_call`){let e=TK(i);e?(n.push(e),o[mJ]??={},i.id&&i.call_id&&(o[mJ][i.call_id]=i.id)):r.push(SE(i,`Malformed custom tool call`))}else if(i.type===`computer_call`){let e=EK(i);e?n.push(e):r.push(SE(i,`Malformed computer call`))}else i.type===`image_generation_call`?(i.result&&t.push({type:`image`,mimeType:`image/png`,data:i.result,id:i.id,metadata:{status:i.status}}),o.tool_outputs??=[],o.tool_outputs.push(i)):(o.tool_outputs??=[],o.tool_outputs.push(i));return new An({id:e.id,content:t,tool_calls:n,invalid_tool_calls:r,usage_metadata:_J(e.usage),additional_kwargs:o,response_metadata:a})},yJ=e=>{let t=(e.summary.length>1?e.summary.reduce((e,t)=>{let n=e[e.length-1];return n.index===t.index?n.text+=t.text:e.push(t),e},[{...e.summary[0]}]):e.summary).map(e=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==`index`)));return{...e,summary:t}},bJ=e=>{let t=[],n={},r,i=[],a={model_provider:`openai`},o={},s;if(e.type===`response.output_text.delta`)t.push({type:`text`,text:e.delta,index:e.content_index});else if(e.type===`response.output_text.annotation.added`)t.push({type:`text`,text:``,annotations:[hJ(e.annotation)],index:e.content_index});else if(e.type===`response.output_item.added`&&e.item.type===`message`){let n=`phase`in e.item?e.item.phase:void 0;n&&t.push({type:`text`,text:``,phase:n,index:0})}else if(e.type===`response.output_item.added`&&e.item.type===`function_call`)i.push({type:`tool_call_chunk`,name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),o[pJ]={[e.item.call_id]:e.item.id};else if(e.type===`response.output_item.added`&&e.item.type===`custom_tool_call`)i.push({type:`tool_call_chunk`,isCustomTool:!0,name:e.item.name,args:e.item.input,id:e.item.call_id,index:e.output_index}),o[mJ]={[e.item.call_id]:e.item.id};else if(e.type===`response.output_item.done`&&e.item.type===`computer_call`)i.push({type:`tool_call_chunk`,name:`computer_use`,args:JSON.stringify({action:e.item.action}),id:e.item.call_id,index:e.output_index}),o.tool_outputs=[e.item];else if(e.type===`response.output_item.done`&&e.item.type===`image_generation_call`)e.item.result&&t.push({type:`image`,mimeType:`image/png`,data:e.item.result,id:e.item.id,metadata:{status:e.item.status}}),o.tool_outputs=[e.item];else if(e.type===`response.output_item.done`&&[`web_search_call`,`file_search_call`,`code_interpreter_call`,`shell_call`,`local_shell_call`,`mcp_call`,`mcp_list_tools`,`mcp_approval_request`,`custom_tool_call`,`tool_search_call`,`tool_search_output`].includes(e.item.type))o.tool_outputs=[e.item];else if(e.type===`response.created`)s=e.response.id,a.id=e.response.id,a.model_name=e.response.model,a.model=e.response.model;else if(e.type===`response.completed`||e.type===`response.incomplete`){s=e.response.id;let t=vJ(e.response);if(r=_J(e.response.usage),e.response.text?.format?.type===`json_schema`&&t.text)try{o.parsed??=JSON.parse(t.text)}catch{}for(let[n,r]of Object.entries(e.response))n!==`id`&&(n===`output`?a[n]=t.response_metadata.output:a[n]=r)}else if(e.type===`response.function_call_arguments.delta`||e.type===`response.custom_tool_call_input.delta`)i.push({type:`tool_call_chunk`,args:e.delta,index:e.output_index,...e.type===`response.custom_tool_call_input.delta`?{isCustomTool:!0}:{}});else if(e.type===`response.web_search_call.in_progress`||e.type===`response.web_search_call.searching`||e.type===`response.web_search_call.completed`||e.type===`response.file_search_call.in_progress`||e.type===`response.file_search_call.searching`||e.type===`response.file_search_call.completed`||e.type===`response.image_generation_call.in_progress`||e.type===`response.image_generation_call.generating`||e.type===`response.image_generation_call.completed`){let[,t,r]=e.type.match(/^response\.(.*)\.([^.]+)$/)??[``,``,``];n={tool_outputs:{id:e.item_id,type:t,status:r}}}else if(e.type===`response.refusal.done`)o.refusal=e.refusal;else if(e.type===`response.output_item.added`&&`item`in e&&e.item.type===`reasoning`){let n=e.item.summary?e.item.summary.map((e,t)=>({...e,index:t})):void 0;o.reasoning={id:e.item.id,type:e.item.type,...n?{summary:n}:{}};let r=e.item.summary?.map(e=>e.text).filter(Boolean).join(``);r&&t.push({type:`reasoning`,reasoning:r})}else if(e.type===`response.reasoning_summary_part.added`)o.reasoning={type:`reasoning`,summary:[{...e.part,index:e.summary_index}]},e.part.text&&t.push({type:`reasoning`,reasoning:e.part.text,index:e.summary_index});else if(e.type===`response.reasoning_summary_text.delta`)o.reasoning={type:`reasoning`,summary:[{text:e.delta,type:`summary_text`,index:e.summary_index}]},e.delta&&t.push({type:`reasoning`,reasoning:e.delta,index:e.summary_index});else if(e.type===`response.image_generation_call.partial_image`)return null;else return null;return new xd({text:t.map(e=>e.text).join(``),message:new Nn({id:s,content:t,tool_call_chunks:i,usage_metadata:r,additional_kwargs:o,response_metadata:a}),generationInfo:n})},xJ=e=>{let t=An.isInstance(e)&&e.response_metadata?.model_provider===`openai`;function*n(){let n=tK(()=>{try{let t=sK(e);return t===`system`||t===`developer`||t===`assistant`||t===`user`?t:`assistant`}catch{return`assistant`}}),r,i=new Set,a=new Set,o=new Map,s=new Map;function*c(){if(!r)return;let e=r.content;(typeof e==`string`&&e.length>0||Array.isArray(e)&&e.length>0)&&(yield r),r=void 0}let l=(e,t)=>{r||={type:`message`,role:n,content:[],...t?{phase:t}:{}},typeof r.content==`string`?r.content=r.content.length>0?[{type:`input_text`,text:r.content},...e]:[...e]:r.content.push(...e)},u=e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e??{})}catch{return`{}`}},d=e=>{let t=tK(()=>{let t=e.metadata?.detail;return t===`low`||t===`high`||t===`auto`?t:`auto`});if(e.fileId)return{type:`input_image`,detail:t,file_id:e.fileId};if(e.url)return{type:`input_image`,detail:t,image_url:e.url};if(e.data){let n=typeof e.data==`string`?e.data:Buffer.from(e.data).toString(`base64`);return{type:`input_image`,detail:t,image_url:`data:${e.mimeType??`image/png`};base64,${n}`}}},f=e=>{if(e.fileId){let t=iK(e);return{type:`input_file`,file_id:e.fileId,...t?{filename:t}:{}}}if(e.url){let t=iK(e);return{...t?{filename:t}:{},type:`input_file`,file_url:e.url}}if(e.data){let t=oK(e),n=typeof e.data==`string`?e.data:Buffer.from(e.data).toString(`base64`);return{type:`input_file`,file_data:`data:${e.mimeType??`application/octet-stream`};base64,${n}`,filename:t}}},p=e=>{let t=tK(()=>{if(Array.isArray(e.summary)){let t=e.summary?.map(e=>e?.text).filter(e=>typeof e==`string`)??[];if(t.length>0)return t}return e.reasoning?[e.reasoning]:[]}),n=t.length>0?t.map(e=>({type:`summary_text`,text:e})):[{type:`summary_text`,text:``}];return{type:`reasoning`,...e.id?{id:e.id}:{},summary:n}},m=e=>({type:`function_call`,name:e.name??``,call_id:e.id??``,arguments:u(e.args)}),h=e=>{let t=u(e.output),n=e.status===`success`?`completed`:e.status===`error`?`incomplete`:void 0;return{type:`function_call_output`,call_id:e.toolCallId??``,output:t,...n?{status:n}:{}}};for(let n of e.contentBlocks)if(n.type===`text`){let e=tK(()=>{if(`extras`in n&&typeof n.extras==`object`&&n.extras!==null&&`phase`in n.extras)return n.extras.phase});l([{type:`input_text`,text:n.text}],e)}else if(n.type!==`invalid_tool_call`){if(n.type===`reasoning`)yield*c(),yield p(n);else if(n.type===`tool_call`){yield*c();let e=n.id??``;e&&(i.add(e),o.delete(e)),yield m(n)}else if(n.type===`tool_call_chunk`){if(n.id){let e=o.get(n.id)??{name:n.name,args:[]};n.name&&(e.name=n.name),n.args&&e.args.push(n.args),o.set(n.id,e)}}else if(n.type===`server_tool_call`){yield*c();let e=n.id??``;e&&(a.add(e),s.delete(e)),yield m(n)}else if(n.type===`server_tool_call_chunk`){if(n.id){let e=s.get(n.id)??{name:n.name,args:[]};n.name&&(e.name=n.name),n.args&&e.args.push(n.args),s.set(n.id,e)}}else if(n.type===`server_tool_call_result`)yield*c(),yield h(n);else if(n.type!==`audio`)if(n.type===`file`){let e=f(n);e&&l([e])}else if(n.type===`image`){let e=d(n);e&&l([e])}else if(n.type===`video`){let e=f(n);e&&l([e])}else n.type===`text-plain`?n.text&&l([{type:`input_text`,text:n.text}]):n.type===`non_standard`&&t&&(yield*c(),yield n.value)}yield*c();for(let[e,t]of o){if(!e||i.has(e))continue;let n=t.args.join(``);!t.name&&!n||(yield{type:`function_call`,call_id:e,name:t.name??``,arguments:n})}for(let[e,t]of s){if(!e||a.has(e))continue;let n=t.args.join(``);!t.name&&!n||(yield{type:`function_call`,call_id:e,name:t.name??``,arguments:n})}}return Array.from(n())},SJ=({messages:e,zdrEnabled:t,model:n})=>e.flatMap(e=>{let r=e.response_metadata;if(r?.output_version===`v1`)return xJ(e);let i=e.additional_kwargs,a=sK(e);if(a===`system`&&nK(n)&&(a=`developer`),a===`function`)throw Error(`Function messages are not supported in Responses API`);if(a===`tool`){let t=e;if(i?.type===`computer_call_output`)return{type:`computer_call_output`,output:(()=>{if(typeof t.content==`string`)return{type:`input_image`,image_url:t.content};if(Array.isArray(t.content)){let e=t.content.find(e=>e.type===`input_image`);if(e)return e;let n=t.content.find(e=>e.type===`computer_screenshot`);if(n)return n;let r=t.content.find(e=>e.type===`image_url`);if(r)return{type:`input_image`,image_url:typeof r.image_url==`string`?r.image_url:r.image_url.url}}throw Error(`Invalid computer call output`)})(),call_id:t.tool_call_id};if(t.additional_kwargs?.customTool)return{type:`custom_tool_call_output`,call_id:t.tool_call_id,output:t.content};let n=Array.isArray(t.content)&&t.content.every(e=>typeof e==`object`&&!!e&&`type`in e&&(e.type===`input_file`||e.type===`input_image`||e.type===`input_text`));return{type:`function_call_output`,call_id:t.tool_call_id,id:t.id?.startsWith(`fc_`)?t.id:void 0,output:n||typeof t.content==`string`?t.content:JSON.stringify(t.content)}}if(a===`assistant`){if(!t&&r?.output!=null&&Array.isArray(r?.output)&&r?.output.length>0&&r?.output.every(e=>`type`in e))return r?.output;let n=[],a=i?.reasoning,o=!!a?.encrypted_content;if(a&&(!t||o)){let e=yJ(a);n.push(e)}let{content:s}=e;if(i?.refusal&&(typeof s==`string`&&(s=[{type:`output_text`,text:s,annotations:[]}]),s=[...s,{type:`refusal`,refusal:i.refusal}]),typeof s==`string`||s.length>0){let r={type:`message`,role:`assistant`,...e.id&&!t&&e.id.startsWith(`msg_`)?{id:e.id}:{},content:tK(()=>typeof s==`string`?s:s.flatMap(e=>{if(e.type===`text`){let t=e;return{type:`output_text`,text:t.text,annotations:(t.annotations??[]).map(gJ)}}return e.type===`output_text`||e.type===`refusal`?e:[]})),phase:tK(()=>{if(Array.isArray(s))return s.find(e=>`phase`in e&&typeof e.phase==`string`)?.phase})};n.push(r)}let c=i?.[pJ],l=i?.[mJ];An.isInstance(e)&&e.tool_calls?.length?n.push(...e.tool_calls.map(e=>OK(e,l)?{type:`custom_tool_call`,id:`call_id`in e&&typeof e.call_id==`string`?e.call_id:l?.[e.id??``]??``,call_id:e.id??``,input:e.args.input,name:e.name}:DK(e)?{type:`computer_call`,id:e.call_id,call_id:e.id??``,action:e.args.action}:{type:`function_call`,name:e.name,arguments:JSON.stringify(e.args),call_id:e.id,...t?{}:{id:c?.[e.id]}})):i?.tool_calls&&n.push(...i.tool_calls.map(e=>({type:`function_call`,name:e.function.name,call_id:e.id,arguments:e.function.arguments,...t?{}:{id:c?.[e.id]}})));let u=r?.output?.length?r?.output:i.tool_outputs,d=[`computer_call`,`mcp_call`,`code_interpreter_call`,`image_generation_call`,`shell_call`,`local_shell_call`];if(u!=null){let e=u?.filter(e=>d.includes(e.type));e.length>0&&n.push(...e)}return n}if(a===`user`||a===`system`||a===`developer`){if(typeof e.content==`string`)return{type:`message`,role:a,content:e.content};let t=[],n=e.content.flatMap(e=>{if(e.type===`mcp_approval_response`&&t.push({type:`mcp_approval_response`,approval_request_id:e.approval_request_id,approve:e.approve}),qe(e)){if(e.type===`file`){let t=iK(e);if(e.source_type===`url`)return{type:`input_file`,file_url:e.url,...t?{filename:t}:{}};if(e.source_type===`id`)return{type:`input_file`,file_id:e.id,...t?{filename:t}:{}};if(e.source_type===`base64`)return{type:`input_file`,file_data:`data:${e.mime_type??``};base64,${e.data}`,filename:oK(e)}}return tt(e,Qq)}return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`image_url`?{type:`input_image`,image_url:tK(()=>{if(typeof e.image_url==`string`)return e.image_url;if(typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url)return e.image_url.url}),detail:tK(()=>{if(typeof e.image_url==`string`)return`auto`;if(typeof e.image_url==`object`&&e.image_url!==null&&`detail`in e.image_url)return e.image_url.detail})}:e.type===`input_text`||e.type===`input_image`||e.type===`input_file`?e:[]});return n.length>0&&t.push({type:`message`,role:a,content:n}),t}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]});async function*CJ(e,t={}){let n=t.streamUsage??!0,r=t.provider??`openai`,i=new Map,a=new Map,o=0,s=!1,c,l,u,d,f=new Set,p=(e,t)=>{let n=a.get(e);if(n!==void 0)return{index:n,isNew:!1};let r=o++;return a.set(e,r),i.set(r,{...t}),{index:r,isNew:!0}},m=function*(){s||(s=!0,yield{event:`message-start`,id:c})},h=function*(e){if(f.has(e))return;let t=i.get(e);t&&(f.add(e),yield{event:`content-block-finish`,index:e,content:$E(t)})};for await(let t of e){if(t.type===`response.created`){c=t.response.id,yield*m(),yield{event:`provider`,provider:r,name:`response.created`,payload:{model:t.response.model,id:t.response.id}};continue}if(t.type===`response.output_text.delta`){yield*m();let{index:e,isNew:n}=p(`text:${t.output_index}:${t.content_index}`,{type:`text`,text:``});n&&(yield{event:`content-block-start`,index:e,content:{type:`text`,text:``}});let r=i.get(e);r.text=(r.text??``)+t.delta,yield{event:`content-block-delta`,index:e,delta:{type:`text-delta`,text:t.delta}};continue}if(t.type===`response.reasoning_summary_text.delta`){yield*m();let{index:e,isNew:n}=p(`reasoning:${t.output_index}:${t.summary_index}`,{type:`reasoning`,reasoning:``});n&&(yield{event:`content-block-start`,index:e,content:{type:`reasoning`,reasoning:``}});let r=i.get(e);r.reasoning=(r.reasoning??``)+t.delta,yield{event:`content-block-delta`,index:e,delta:{type:`reasoning-delta`,reasoning:t.delta}};continue}if(t.type===`response.output_item.added`&&(t.item.type===`function_call`||t.item.type===`custom_tool_call`)){yield*m();let e=`tool:${t.output_index}`,n=t.item.type===`custom_tool_call`,r=t.item.type===`function_call`?t.item.arguments??``:t.item.input??``,{index:a,isNew:o}=p(e,{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:r,index:t.output_index,...n?{isCustomTool:!0}:{}});if(o&&(yield{event:`content-block-start`,index:a,content:{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:r,index:t.output_index}}),r){let e=i.get(a);yield{event:`content-block-delta`,index:a,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,...e.id==null?{}:{id:e.id},...e.name==null?{}:{name:e.name},args:e.args}}}}continue}if(t.type===`response.function_call_arguments.delta`||t.type===`response.custom_tool_call_input.delta`){yield*m();let{index:e,isNew:n}=p(`tool:${t.output_index}`,{type:`tool_call_chunk`,args:``,index:t.output_index,...t.type===`response.custom_tool_call_input.delta`?{isCustomTool:!0}:{}});n&&(yield{event:`content-block-start`,index:e,content:{type:`tool_call_chunk`,args:``,index:t.output_index}});let r=i.get(e);r.args=(r.args??``)+t.delta,yield{event:`content-block-delta`,index:e,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,...r.id==null?{}:{id:r.id},...r.name==null?{}:{name:r.name},args:r.args}}};continue}if(t.type===`response.output_item.done`&&(t.item.type===`function_call`||t.item.type===`custom_tool_call`)){yield*m();let e=`tool:${t.output_index}`,n=t.item.type===`function_call`?t.item.arguments??``:t.item.input??``,{index:r,isNew:a}=p(e,{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:n,index:t.output_index});if(a)yield{event:`content-block-start`,index:r,content:{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:n,index:t.output_index}};else{let e=i.get(r);e.args=n,e.id=t.item.call_id,e.name=t.item.name}yield*h(r);continue}if(t.type===`response.completed`||t.type===`response.incomplete`){yield*m(),c=t.response.id,u=wJ(t.response.status,t.type),d={model_provider:r,id:t.response.id,model:t.response.model,status:t.response.status},n&&t.response.usage&&(l=_J(t.response.usage),yield{event:`usage`,usage:l});continue}t.type!==`response.image_generation_call.partial_image`&&(yield*m(),yield{event:`provider`,provider:r,name:t.type,payload:t})}s||(yield{event:`message-start`});for(let[e]of i)f.has(e)||(yield*h(e));yield{event:`message-finish`,reason:u,...l?{usage:l}:{},...d?{responseMetadata:d}:{}}}function wJ(e,t){return t===`response.incomplete`?`length`:e===`completed`?`stop`:e===`incomplete`?`length`:`stop`}var TJ=class extends Zq{constructor(e,t){super(Xq(e,t))}invocationParams(e){let t;e?.strict!==void 0&&(t=e.strict),t===void 0&&this.supportsStrictToolCalling!==void 0&&(t=this.supportsStrictToolCalling);let n={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?this._reduceChatOpenAITools(e.tools,{stream:this.streaming,strict:t}):void 0,tool_choice:SK(e?.tool_choice)?e?.tool_choice:(()=>{let t=yK(e?.tool_choice);if(typeof t==`object`&&`type`in t){if(t.type===`function`)return{type:`function`,name:t.function.name};if(t.type===`allowed_tools`)return{type:`allowed_tools`,mode:t.allowed_tools.mode,tools:t.allowed_tools.tools};if(t.type===`custom`)return{type:`custom`,name:t.custom.name}}})(),text:(()=>{if(e?.text)return e.text;let t=this._getResponseFormat(e?.response_format);return t?.type===`json_schema`?t.json_schema.schema==null?void 0:{format:{type:`json_schema`,schema:t.json_schema.schema,description:t.json_schema.description,name:t.json_schema.name,strict:t.json_schema.strict},verbosity:e?.verbosity}:{format:t,verbosity:e?.verbosity}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},r=this._getReasoningParams(e);return r!==void 0&&(n.reasoning=r),n}async _generate(e,t,n){t.signal?.throwIfAborted();let r=this.invocationParams(t);if(r.stream){let r=this._streamResponseChunks(e,t,n),i;for await(let e of r)e.message.response_metadata={...e.generationInfo,...e.message.response_metadata},i=i?.concat(e)??e;return{generations:i?[i]:[],llmOutput:{estimatedTokenUsage:i?.message?.usage_metadata}}}else{let n=await this.completionWithRetry({input:SJ({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...r,stream:!1},{signal:t?.signal,...t?.options});return{generations:[{text:n.output_text,message:vJ(n)}],llmOutput:{id:n.id,estimatedTokenUsage:n.usage?{promptTokens:n.usage.input_tokens,completionTokens:n.usage.output_tokens,totalTokens:n.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(e,t,n){let r=await this.completionWithRetry({...this.invocationParams(t),input:SJ({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},t),i=this.streamUsage??t.streamUsage;yield*CJ(async function*(e,t){for await(let n of e){if(t?.aborted)return;yield n}}(r,t.signal),{streamUsage:i??!0,provider:this.streamEventProvider})}get streamEventProvider(){return`openai`}async*_streamResponseChunks(e,t,n){let r=await this.completionWithRetry({...this.invocationParams(t),input:SJ({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},t);try{for await(let e of r){if(t.signal?.aborted)return;let r=bJ(e);r!=null&&(yield r,await n?.handleLLMNewToken(r.text||``,{prompt:t.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:r}))}}catch(e){throw eK(e)}}async completionWithRetry(e,t){return this.caller.call(async()=>{let n=this._getClientOptions(t);try{return e.text?.format?.type===`json_schema`&&!e.stream?await this.client.responses.parse(e,n):await this.client.responses.create(e,n)}catch(e){throw eK(e)}})}_reduceChatOpenAITools(e,t){let n=[];for(let r of e)if(bK(r))r.type===`image_generation`&&t?.stream&&(r.partial_images=1),n.push(r);else if(CK(r)){let e=r.metadata.customTool;n.push({type:`custom`,name:e.name,description:e.description,format:e.format})}else if(UT(r)){let e={};for(let[t,n]of Object.entries(r))t!==`type`&&t!==`function`&&(e[t]=n);n.push({type:`function`,name:r.function.name,parameters:r.function.parameters,description:r.function.description,strict:t?.strict??null,...e})}else wK(r)&&n.push(kK(r));return n}},EJ=class extends TJ{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,...aJ}}get lc_secrets(){return{...super.lc_secrets,...oJ}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...sJ]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=cJ(e,t);super(n),lJ.call(this,n)}_getClientOptions(e){return uJ.call(this,e)}toJSON(){return dJ.call(this,super.toJSON())}},DJ=class e extends Zq{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,`useResponsesApi`]}get callKeys(){return[...super.callKeys,`useResponsesApi`]}fields;constructor(e,t){let n=Xq(e,t);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new TJ(n),this.completions=n?.completions??new iJ(n)}_useResponsesApi(e){let t=e?.tools?.some(bK),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,r=e?.tools?.some(wK)||e?.tools?.some(CK);return this.useResponsesApi||t||n||r||cK(this.model)}getLsParams(e){let t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(t):this.completions.getLsParams(t)}invocationParams(e){let t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(t):this.completions.invocationParams(t)}async _generate(e,t,n){return this._useResponsesApi(t)?this.responses._generate(e,t,n):this.completions._generate(e,t,n)}async*_streamChatModelEvents(e,t,n){if(this._useResponsesApi(t)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(t),n);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(t),n)}async*_streamResponseChunks(e,t,n){if(this._useResponsesApi(t)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(t),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(t),n)}withConfig(t){let n=new e(this.fields);return n.defaultOptions={...this.defaultOptions,...t},n}},OJ=class extends DJ{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,...aJ}}get lc_secrets(){return{...super.lc_secrets,...oJ}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...sJ]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=cJ(e,t);super({...n,completions:new fJ(n),responses:new EJ(n)}),lJ.call(this,n)}_getStructuredOutputMethod(e){let t={...e};return this.model.startsWith(`gpt-4o`)&&t?.method===void 0?`functionCalling`:super._getStructuredOutputMethod(t)}toJSON(){return dJ.call(this,super.toJSON())}};V({action:lj([V({type:xj(`screenshot`)}),V({type:xj(`click`),x:JA(),y:JA(),button:yj([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),V({type:xj(`double_click`),x:JA(),y:JA(),button:yj([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),V({type:xj(`drag`),path:oj(V({x:JA(),y:JA()}))}),V({type:xj(`keypress`),keys:oj(B())}),V({type:xj(`move`),x:JA(),y:JA()}),V({type:xj(`scroll`),x:JA(),y:JA(),scroll_x:JA(),scroll_y:JA()}),V({type:xj(`type`),text:B()}),V({type:xj(`wait`),duration:JA().optional()})])}),lj([V({type:xj(`exec`),command:oj(B()),env:_j(B(),B()).optional(),working_directory:B().optional(),timeout_ms:JA().optional(),user:B().optional()})]),V({commands:oj(B()).describe(`Array of shell commands to execute`),timeout_ms:JA().optional().describe(`Optional timeout in milliseconds for the commands`),max_output_length:JA().optional().describe(`Optional maximum number of characters to return from each command`)}),lj([V({type:xj(`create_file`),path:B(),diff:B()}),V({type:xj(`update_file`),path:B(),diff:B()}),V({type:xj(`delete_file`),path:B()})]);function kJ(e){if(typeof e==`object`&&e){let t={...e};`additionalProperties`in t&&delete t.additionalProperties,`$schema`in t&&delete t.$schema,`strict`in t&&delete t.strict;for(let e in t)e in t&&(Array.isArray(t[e])?t[e]=t[e].map(kJ):typeof t[e]==`object`&&t[e]!==null&&(t[e]=kJ(t[e])));return t}return e}function AJ(e){let{$schema:t,...n}=kJ(N_(e)||Zb(e)?Rx(e):e);return n}function jJ(e){let{$schema:t,...n}=kJ(e);return n}function MJ(e,t,n=[]){if(typeof e!=`object`||!e)return;let r=e;if(Array.isArray(r.enum)&&r.enum.some(e=>e===``)){let e=n.length?` at path "${n.join(`.`)}"`:``,r=t?` in tool "${t}"`:``;throw Error(`Invalid enum: empty string not allowed${r}${e}. Gemini API rejects empty strings in enums.`)}if(r.type===`object`&&r.properties&&typeof r.properties==`object`)for(let[e,i]of Object.entries(r.properties))MJ(i,t,[...n,e]);r.items&&MJ(r.items,t,[...n,`[]`]);for(let e of[`anyOf`,`oneOf`,`allOf`]){let i=r[e];Array.isArray(i)&&i.forEach((r,i)=>MJ(r,t,[...n,`${e}[${i}]`]))}r.additionalProperties&&typeof r.additionalProperties==`object`&&MJ(r.additionalProperties,t,[...n,`additionalProperties`])}var NJ=`__gemini_function_call_thought_signatures__`,PJ=`ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==`,FJ=e=>e();function IJ(e){return Pn.isInstance(e)?e.role:e.type}function LJ(e){switch(e){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: ${e}`)}}function RJ(e){if(`mimeType`in e&&`data`in e)return{inlineData:{mimeType:e.mimeType,data:e.data}};if(`mimeType`in e&&`fileUri`in e)return{fileData:{mimeType:e.mimeType,fileUri:e.fileUri}};throw Error(`Invalid media content`)}function zJ(e,t){return t.map(e=>jn(e)?e.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function BJ(e,t){if(`data`in e&&e.data!==void 0){let n=e.data instanceof Uint8Array?btoa(String.fromCharCode(...e.data)):e.data;return{inlineData:{mimeType:e.mimeType||t,data:n}}}if(`url`in e&&e.url!==void 0){let n=et({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mimeType||t,fileUri:e.url}}}throw`fileId`in e&&e.fileId!==void 0?Error(`ContentBlock.Multimodal fileId is not supported by Google Generative AI. Use a URL or base64 data instead.`):Error(`Invalid multimodal content block: must have "data", "url", or "fileId" property. Received: ${JSON.stringify(e)}`)}function VJ(e){return{providerName:`Google Gemini`,fromStandardTextBlock(e){return{text:e.text}},fromStandardImageBlock(t){if(!e)throw Error(`This model does not support images`);if(t.source_type===`url`){let e=et({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)},fromStandardAudioBlock(t){if(!e)throw Error(`This model does not support audio`);if(t.source_type===`url`){let e=et({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)},fromStandardFileBlock(t){if(!e)throw Error(`This model does not support files`);if(t.source_type===`text`)return{text:t.text};if(t.source_type===`url`){let e=et({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)}}}function HJ(e,t){if(qe(e))return tt(e,VJ(t));if(e.type===`text`)return{text:e.text};if(e.type===`executableCode`)return{executableCode:e.executableCode};if(e.type===`codeExecutionResult`)return{codeExecutionResult:e.codeExecutionResult};if(e.type===`image_url`){if(!t)throw Error(`This model does not support images`);let n;if(typeof e.image_url==`string`)n=e.image_url;else if(typeof e.image_url==`object`&&`url`in e.image_url)n=e.image_url.url;else throw Error(`Please provide image as base64 encoded data URL`);let[r,i]=n.split(`,`);if(!r.startsWith(`data:`))throw Error(`Please provide image as base64 encoded data URL`);let[a,o]=r.replace(/^data:/,``).split(`;`);if(o!==`base64`)throw Error(`Please provide image as base64 encoded data URL`);return{inlineData:{data:i,mimeType:a}}}else if(e.type===`media`)return RJ(e);else if(e.type===`image`)return BJ(e,`image/png`);else if(e.type===`video`)return BJ(e,`video/mp4`);else if(e.type===`audio`)return BJ(e,`audio/mpeg`);else if(e.type===`file`)return BJ(e,`application/octet-stream`);else if(e.type===`text-plain`)return`text`in e&&typeof e.text==`string`?{text:e.text}:BJ(e,`text/plain`);else if(e.type===`tool_use`)return{functionCall:{name:e.name,args:e.input}};else if(e.type===`tool_call`)return{functionCall:{name:e.name,args:e.args}};else if(e.type?.includes(`/`)&&e.type.split(`/`).length===2&&`data`in e&&typeof e.data==`string`)return{inlineData:{mimeType:e.type,data:e.data}};else if(e.type===`thinking`){let t=e;return{text:t.thinking,thought:!0,...t.signature?{thoughtSignature:t.signature}:{}}}else if(`functionCall`in e)return;else if(`type`in e)throw Error(`Unknown content type ${e.type}`);else throw Error(`Unknown content ${JSON.stringify(e)}`)}function UJ(e,t,n,r){if($t(e)){let r=e.name??zJ(e,n);if(r===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 "${e.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);let i=Array.isArray(e.content)?e.content.map(e=>HJ(e,t)).filter(e=>e!==void 0):e.content;return e.status===`error`?[{functionResponse:{name:r,response:{error:{details:i}}}}]:[{functionResponse:{name:r,response:{result:i}}}]}let i=[],a=[];typeof e.content==`string`&&e.content&&a.push({text:e.content}),Array.isArray(e.content)&&a.push(...e.content.map(e=>HJ(e,t)).filter(e=>e!==void 0));let o=e.additional_kwargs?.[NJ];return jn(e)&&e.tool_calls?.length&&(i=e.tool_calls.map(e=>{let t=FJ(()=>{if(e.id){let t=o?.[e.id];if(t)return t}return r?.includes(`gemini-3`)?PJ:``});return{functionCall:{name:e.name,args:e.args},...t?{thoughtSignature:t}:{}}})),[...a,...i]}function WJ(e,t,n=!1,r){return e.reduce((i,a,o)=>{if(!Kt(a))throw Error(`Unsupported message input`);let s=IJ(a);if(s===`system`&&o!==0)throw Error(`System message should be the first one`);let c=LJ(s),l=i.content[i.content.length];if(!i.mergeWithPreviousContent&&l&&l.role===c)throw Error(`Google Generative AI requires alternate messages between authors`);let u=UJ(a,t,e.slice(0,o),r);if(i.mergeWithPreviousContent){let e=i.content[i.content.length-1];if(!e)throw Error(`There was a problem parsing your system message. Please try a prompt without one.`);return e.parts.push(...u),{mergeWithPreviousContent:!1,content:i.content}}let d=c;(d===`function`||d===`system`&&!n)&&(d=`user`);let f={role:d,parts:u};return{mergeWithPreviousContent:s===`system`&&!n,content:[...i.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function GJ(e,t){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};let[n]=e.candidates,{content:r,...i}=n,a=r?.parts?.reduce((e,t)=>(`functionCall`in t&&t.functionCall&&e.push({...t,id:`id`in t.functionCall&&typeof t.functionCall.id==`string`?t.functionCall.id:Yr()}),e),[]),o,s=r?.parts;o=Array.isArray(s)&&s.length===1&&`text`in s[0]&&s[0].text&&!s[0].thought?s[0].text:Array.isArray(s)&&s.length>0?s.map(e=>e.thought&&`text`in e&&e.text?{type:`thinking`,thinking:e.text,...e.thoughtSignature?{signature:e.thoughtSignature}:{}}:`text`in e?{type:`text`,text:e.text}:`inlineData`in e?{type:`inlineData`,inlineData:e.inlineData}:`functionCall`in e?{type:`functionCall`,functionCall:e.functionCall}:`functionResponse`in e?{type:`functionResponse`,functionResponse:e.functionResponse}:`fileData`in e?{type:`fileData`,fileData:e.fileData}:`executableCode`in e?{type:`executableCode`,executableCode:e.executableCode}:`codeExecutionResult`in e?{type:`codeExecutionResult`,codeExecutionResult:e.codeExecutionResult}:e):[];let c=a?.reduce((e,t)=>(`thoughtSignature`in t&&typeof t.thoughtSignature==`string`&&(e[t.id]=t.thoughtSignature),e),{}),l=``;return typeof o==`string`?l=o:Array.isArray(o)&&o.length>0&&(l=o.find(e=>`text`in e)?.text??l),{generations:[{text:l,message:new An({content:o??``,tool_calls:a?.map(e=>({type:`tool_call`,id:e.id,name:e.functionCall.name,args:e.functionCall.args})),additional_kwargs:{...i,[NJ]:c},usage_metadata:t?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:t?.usageMetadata?.input_tokens,completionTokens:t?.usageMetadata?.output_tokens,totalTokens:t?.usageMetadata?.total_tokens}}}}function KJ(e,t){if(!e.candidates||e.candidates.length===0)return null;let[n]=e.candidates,{content:r,...i}=n,a=r.parts?.reduce((e,t)=>(`functionCall`in t&&t.functionCall&&e.push({...t,id:`id`in t.functionCall&&typeof t.functionCall.id==`string`?t.functionCall.id:Yr()}),e),[]),o,s=r?.parts;o=Array.isArray(s)&&s.every(e=>`text`in e&&!e.thought)?s.map(e=>e.text).join(``):Array.isArray(s)?s.map(e=>e.thought&&`text`in e&&e.text?{type:`thinking`,thinking:e.text,...e.thoughtSignature?{signature:e.thoughtSignature}:{}}:`text`in e?{type:`text`,text:e.text}:`inlineData`in e?{type:`inlineData`,inlineData:e.inlineData}:`functionCall`in e?{type:`functionCall`,functionCall:e.functionCall}:`functionResponse`in e?{type:`functionResponse`,functionResponse:e.functionResponse}:`fileData`in e?{type:`fileData`,fileData:e.fileData}:`executableCode`in e?{type:`executableCode`,executableCode:e.executableCode}:`codeExecutionResult`in e?{type:`codeExecutionResult`,codeExecutionResult:e.codeExecutionResult}:e):[];let c=``;o&&typeof o==`string`?c=o:Array.isArray(o)&&(c=o.find(e=>`text`in e)?.text??``);let l=[];a&&l.push(...a.map(e=>({type:`tool_call_chunk`,id:e.id,name:e.functionCall.name,args:JSON.stringify(e.functionCall.args)})));let u=a?.reduce((e,t)=>(`thoughtSignature`in t&&typeof t.thoughtSignature==`string`&&(e[t.id]=t.thoughtSignature),e),{});return new xd({text:c,message:new Nn({content:o||``,name:r?r.role:void 0,tool_call_chunks:l,additional_kwargs:{[NJ]:u},response_metadata:{model_provider:`google-genai`},usage_metadata:t.usageMetadata}),generationInfo:i})}function qJ(e){return e.every(e=>`functionDeclarations`in e&&Array.isArray(e.functionDeclarations))?e:[{functionDeclarations:e.map(e=>{if(eA(e)){let t=AJ(e.schema);return t.type===`object`&&`properties`in t&&Object.keys(t.properties).length===0?{name:e.name,description:e.description}:(MJ(t,e.name),{name:e.name,description:e.description,parameters:t})}if(UT(e)){let t=jJ(e.function.parameters);return MJ(t,e.function.name),{name:e.function.name,description:e.function.description??`A function available to call.`,parameters:t}}return e})}]}function JJ(e,t){let n={input_tokens:e?.promptTokenCount??0,output_tokens:e?.candidatesTokenCount??0,total_tokens:e?.totalTokenCount??0};if(e?.cachedContentTokenCount&&(n.input_token_details??={},n.input_token_details.cache_read=e.cachedContentTokenCount),t===`gemini-3-pro-preview`){let t=Math.max(0,e?.promptTokenCount??-2e5),r=Math.max(0,e?.cachedContentTokenCount??-2e5);t&&(n.input_token_details={...n.input_token_details,over_200k:t}),r&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:r})}return n}async function*YJ(e,t={}){let n=t.streamUsage??!0,r=new Map,i=new Map,a=0,o=!1,s,c=`stop`,l=(e,t)=>{let n=i.get(e);if(n!==void 0)return{index:n,isNew:!1};let o=a++;return i.set(e,o),r.set(o,{...t}),{index:o,isNew:!0}};for await(let i of e){o||(o=!0,yield{event:`message-start`}),n&&`usageMetadata`in i&&i.usageMetadata&&(s=JJ(i.usageMetadata,t.model??``),yield{event:`usage`,usage:s});let e=i.candidates?.[0];e?.finishReason&&(c=XJ(e.finishReason));let a=e?.content?.parts;if(!a)continue;let u=0;for(let e of a)if(`text`in e&&e.text)if(`thought`in e&&e.thought){let{index:t,isNew:n}=l(`reasoning`,{type:`reasoning`,reasoning:``});n&&(yield{event:`content-block-start`,index:t,content:{type:`reasoning`,reasoning:``}});let i=r.get(t);i.reasoning=(i.reasoning??``)+e.text,yield{event:`content-block-delta`,index:t,delta:{type:`reasoning-delta`,reasoning:e.text}}}else{let{index:t,isNew:n}=l(`text`,{type:`text`,text:``});n&&(yield{event:`content-block-start`,index:t,content:{type:`text`,text:``}});let i=r.get(t);i.text=(i.text??``)+e.text,yield{event:`content-block-delta`,index:t,delta:{type:`text-delta`,text:e.text}}}else if(`functionCall`in e&&e.functionCall){let t=`tool:${u}`,n=JSON.stringify(e.functionCall.args??{}),{index:i,isNew:a}=l(t,{type:`tool_call_chunk`,name:e.functionCall.name,args:``,index:u});a&&(yield{event:`content-block-start`,index:i,content:{type:`tool_call_chunk`,name:e.functionCall.name,args:``,index:u}});let o=r.get(i);o.args=n,yield{event:`content-block-delta`,index:i,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,name:o.name,args:o.args}}},u+=1}}for(let[e,t]of r)yield{event:`content-block-finish`,index:e,content:$E(t)};yield{event:`message-finish`,reason:c,...s?{usage:s}:{},responseMetadata:{model_provider:`google-genai`}}}function XJ(e){switch(e.toLowerCase()){case`max_tokens`:case`max-token`:case`max_token`:return`length`;case`safety`:case`recitation`:case`language`:case`blocklist`:case`prohibited_content`:case`prohibited-content`:case`spii`:case`image_safety`:case`image-safety`:case`image_prohibited_content`:case`image-prohibited-content`:case`image_recitation`:case`image-recitation`:return`content_filter`;default:return`stop`}}var ZJ=class extends YT{static lc_name(){return`GoogleGenerativeAIToolsOutputParser`}lc_namespace=[`langchain`,`google_genai`,`output_parsers`];returnId=!1;keyName;returnSingle=!1;zodSchema;serializableSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}async _validateResult(e){if(this.serializableSchema!==void 0){let t=await this.serializableSchema[`~standard`].validate(e);if(t.issues)throw new ZT(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.issues)}`,JSON.stringify(e,null,2));return t.value}if(this.zodSchema===void 0)return e;let t=await L_(this.zodSchema,e);if(t.success)return t.data;throw new ZT(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){let t=e.flatMap(e=>{let{message:t}=e;return!(`tool_calls`in t)||!Array.isArray(t.tool_calls)?[]:t.tool_calls});if(t[0]===void 0)throw Error(`No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.`);let[n]=t;return await this._validateResult(n.args)}},QJ;(function(e){e.STRING=`string`,e.NUMBER=`number`,e.INTEGER=`integer`,e.BOOLEAN=`boolean`,e.ARRAY=`array`,e.OBJECT=`object`})(QJ||={});var $J;(function(e){e.LANGUAGE_UNSPECIFIED=`language_unspecified`,e.PYTHON=`python`})($J||={});var eY;(function(e){e.OUTCOME_UNSPECIFIED=`outcome_unspecified`,e.OUTCOME_OK=`outcome_ok`,e.OUTCOME_FAILED=`outcome_failed`,e.OUTCOME_DEADLINE_EXCEEDED=`outcome_deadline_exceeded`})(eY||={});var tY=[`user`,`model`,`function`,`system`],nY;(function(e){e.HARM_CATEGORY_UNSPECIFIED=`HARM_CATEGORY_UNSPECIFIED`,e.HARM_CATEGORY_HATE_SPEECH=`HARM_CATEGORY_HATE_SPEECH`,e.HARM_CATEGORY_SEXUALLY_EXPLICIT=`HARM_CATEGORY_SEXUALLY_EXPLICIT`,e.HARM_CATEGORY_HARASSMENT=`HARM_CATEGORY_HARASSMENT`,e.HARM_CATEGORY_DANGEROUS_CONTENT=`HARM_CATEGORY_DANGEROUS_CONTENT`,e.HARM_CATEGORY_CIVIC_INTEGRITY=`HARM_CATEGORY_CIVIC_INTEGRITY`})(nY||={});var rY;(function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED=`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,e.BLOCK_LOW_AND_ABOVE=`BLOCK_LOW_AND_ABOVE`,e.BLOCK_MEDIUM_AND_ABOVE=`BLOCK_MEDIUM_AND_ABOVE`,e.BLOCK_ONLY_HIGH=`BLOCK_ONLY_HIGH`,e.BLOCK_NONE=`BLOCK_NONE`})(rY||={});var iY;(function(e){e.HARM_PROBABILITY_UNSPECIFIED=`HARM_PROBABILITY_UNSPECIFIED`,e.NEGLIGIBLE=`NEGLIGIBLE`,e.LOW=`LOW`,e.MEDIUM=`MEDIUM`,e.HIGH=`HIGH`})(iY||={});var aY;(function(e){e.BLOCKED_REASON_UNSPECIFIED=`BLOCKED_REASON_UNSPECIFIED`,e.SAFETY=`SAFETY`,e.OTHER=`OTHER`})(aY||={});var oY;(function(e){e.FINISH_REASON_UNSPECIFIED=`FINISH_REASON_UNSPECIFIED`,e.STOP=`STOP`,e.MAX_TOKENS=`MAX_TOKENS`,e.SAFETY=`SAFETY`,e.RECITATION=`RECITATION`,e.LANGUAGE=`LANGUAGE`,e.BLOCKLIST=`BLOCKLIST`,e.PROHIBITED_CONTENT=`PROHIBITED_CONTENT`,e.SPII=`SPII`,e.MALFORMED_FUNCTION_CALL=`MALFORMED_FUNCTION_CALL`,e.OTHER=`OTHER`})(oY||={});var sY;(function(e){e.TASK_TYPE_UNSPECIFIED=`TASK_TYPE_UNSPECIFIED`,e.RETRIEVAL_QUERY=`RETRIEVAL_QUERY`,e.RETRIEVAL_DOCUMENT=`RETRIEVAL_DOCUMENT`,e.SEMANTIC_SIMILARITY=`SEMANTIC_SIMILARITY`,e.CLASSIFICATION=`CLASSIFICATION`,e.CLUSTERING=`CLUSTERING`})(sY||={});var cY;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.AUTO=`AUTO`,e.ANY=`ANY`,e.NONE=`NONE`})(cY||={});var lY;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.MODE_DYNAMIC=`MODE_DYNAMIC`})(lY||={});var uY=class extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}},dY=class extends uY{constructor(e,t){super(e),this.response=t}},fY=class extends uY{constructor(e,t,n,r){super(e),this.status=t,this.statusText=n,this.errorDetails=r}},pY=class extends uY{},mY=class extends uY{},hY=`https://generativelanguage.googleapis.com`,gY=`v1beta`,_Y=`0.24.1`,vY=`genai-js`,yY;(function(e){e.GENERATE_CONTENT=`generateContent`,e.STREAM_GENERATE_CONTENT=`streamGenerateContent`,e.COUNT_TOKENS=`countTokens`,e.EMBED_CONTENT=`embedContent`,e.BATCH_EMBED_CONTENTS=`batchEmbedContents`})(yY||={});var bY=class{constructor(e,t,n,r,i){this.model=e,this.task=t,this.apiKey=n,this.stream=r,this.requestOptions=i}toString(){let e=this.requestOptions?.apiVersion||gY,t=`${this.requestOptions?.baseUrl||hY}/${e}/${this.model}:${this.task}`;return this.stream&&(t+=`?alt=sse`),t}};function xY(e){let t=[];return e?.apiClient&&t.push(e.apiClient),t.push(`${vY}/${_Y}`),t.join(` `)}async function SY(e){let t=new Headers;t.append(`Content-Type`,`application/json`),t.append(`x-goog-api-client`,xY(e.requestOptions)),t.append(`x-goog-api-key`,e.apiKey);let n=e.requestOptions?.customHeaders;if(n){if(!(n instanceof Headers))try{n=new Headers(n)}catch(e){throw new pY(`unable to convert customHeaders value ${JSON.stringify(n)} to Headers: ${e.message}`)}for(let[e,r]of n.entries()){if(e===`x-goog-api-key`)throw new pY(`Cannot set reserved header name ${e}`);if(e===`x-goog-api-client`)throw new pY(`Header name ${e} can only be set using the apiClient field`);t.append(e,r)}}return t}async function CY(e,t,n,r,i,a){let o=new bY(e,t,n,r,a);return{url:o.toString(),fetchOptions:Object.assign(Object.assign({},OY(a)),{method:`POST`,headers:await SY(o),body:i})}}async function wY(e,t,n,r,i,a={},o=fetch){let{url:s,fetchOptions:c}=await CY(e,t,n,r,i,a);return TY(s,c,o)}async function TY(e,t,n=fetch){let r;try{r=await n(e,t)}catch(t){EY(t,e)}return r.ok||await DY(r,e),r}function EY(e,t){let n=e;throw n.name===`AbortError`?(n=new mY(`Request aborted when fetching ${t.toString()}: ${e.message}`),n.stack=e.stack):e instanceof fY||e instanceof pY||(n=new uY(`Error fetching from ${t.toString()}: ${e.message}`),n.stack=e.stack),n}async function DY(e,t){let n=``,r;try{let t=await e.json();n=t.error.message,t.error.details&&(n+=` ${JSON.stringify(t.error.details)}`,r=t.error.details)}catch{}throw new fY(`Error fetching from ${t.toString()}: [${e.status} ${e.statusText}] ${n}`,e.status,e.statusText,r)}function OY(e){let t={};if(e?.signal!==void 0||e?.timeout>=0){let n=new AbortController;e?.timeout>=0&&setTimeout(()=>n.abort(),e.timeout),e?.signal&&e.signal.addEventListener(`abort`,()=>{n.abort()}),t.signal=n.signal}return t}function kY(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),NY(e.candidates[0]))throw new dY(`${PY(e)}`,e);return AY(e)}else if(e.promptFeedback)throw new dY(`Text not available. ${PY(e)}`,e);return``},e.functionCall=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),NY(e.candidates[0]))throw new dY(`${PY(e)}`,e);return console.warn(`response.functionCall() is deprecated. Use response.functionCalls() instead.`),jY(e)[0]}else if(e.promptFeedback)throw new dY(`Function call not available. ${PY(e)}`,e)},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),NY(e.candidates[0]))throw new dY(`${PY(e)}`,e);return jY(e)}else if(e.promptFeedback)throw new dY(`Function call not available. ${PY(e)}`,e)},e}function AY(e){let t=[];if(e.candidates?.[0].content?.parts)for(let n of e.candidates?.[0].content?.parts)n.text&&t.push(n.text),n.executableCode&&t.push("\n```"+n.executableCode.language+`
|
|
212
|
-
`+n.executableCode.code+"\n```\n"),n.codeExecutionResult&&t.push("\n```\n"+n.codeExecutionResult.output+"\n```\n");return t.length>0?t.join(``):``}function jY(e){let t=[];if(e.candidates?.[0].content?.parts)for(let n of e.candidates?.[0].content?.parts)n.functionCall&&t.push(n.functionCall);if(t.length>0)return t}var MY=[oY.RECITATION,oY.SAFETY,oY.LANGUAGE];function NY(e){return!!e.finishReason&&MY.includes(e.finishReason)}function PY(e){let t=``;if((!e.candidates||e.candidates.length===0)&&e.promptFeedback)t+=`Response was blocked`,e.promptFeedback?.blockReason&&(t+=` due to ${e.promptFeedback.blockReason}`),e.promptFeedback?.blockReasonMessage&&(t+=`: ${e.promptFeedback.blockReasonMessage}`);else if(e.candidates?.[0]){let n=e.candidates[0];NY(n)&&(t+=`Candidate was blocked due to ${n.finishReason}`,n.finishMessage&&(t+=`: ${n.finishMessage}`))}return t}function FY(e){return this instanceof FY?(this.v=e,this):new FY(e)}function IY(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i={},o(`next`),o(`throw`),o(`return`),i[Symbol.asyncIterator]=function(){return this},i;function o(e){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||s(e,t)})})}function s(e,t){try{c(r[e](t))}catch(e){d(a[0][3],e)}}function c(e){e.value instanceof FY?Promise.resolve(e.value.v).then(l,u):d(a[0][2],e)}function l(e){s(`next`,e)}function u(e){s(`throw`,e)}function d(e,t){e(t),a.shift(),a.length&&s(a[0][0],a[0][1])}}var LY=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function RY(e){let[t,n]=VY(e.body.pipeThrough(new TextDecoderStream(`utf8`,{fatal:!0}))).tee();return{stream:BY(t),response:zY(n)}}async function zY(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)return kY(HY(t));t.push(r)}}function BY(e){return IY(this,arguments,function*(){let t=e.getReader();for(;;){let{value:e,done:n}=yield FY(t.read());if(n)break;yield yield FY(kY(e))}})}function VY(e){let t=e.getReader();return new ReadableStream({start(e){let n=``;return r();function r(){return t.read().then(({value:t,done:i})=>{if(i){if(n.trim()){e.error(new uY(`Failed to parse stream`));return}e.close();return}n+=t;let a=n.match(LY),o;for(;a;){try{o=JSON.parse(a[1])}catch{e.error(new uY(`Error parsing JSON response: "${a[1]}"`));return}e.enqueue(o),n=n.substring(a[0].length),a=n.match(LY)}return r()}).catch(e=>{let t=e;throw t.stack=e.stack,t=t.name===`AbortError`?new mY(`Request aborted when reading from the stream`):new uY(`Error reading from the stream`),t})}}})}function HY(e){let t={promptFeedback:e[e.length-1]?.promptFeedback};for(let n of e){if(n.candidates){let e=0;for(let r of n.candidates)if(t.candidates||=[],t.candidates[e]||(t.candidates[e]={index:e}),t.candidates[e].citationMetadata=r.citationMetadata,t.candidates[e].groundingMetadata=r.groundingMetadata,t.candidates[e].finishReason=r.finishReason,t.candidates[e].finishMessage=r.finishMessage,t.candidates[e].safetyRatings=r.safetyRatings,r.content&&r.content.parts){t.candidates[e].content||(t.candidates[e].content={role:r.content.role||`user`,parts:[]});let n={};for(let i of r.content.parts)i.text&&(n.text=i.text),i.functionCall&&(n.functionCall=i.functionCall),i.executableCode&&(n.executableCode=i.executableCode),i.codeExecutionResult&&(n.codeExecutionResult=i.codeExecutionResult),Object.keys(n).length===0&&(n.text=``),t.candidates[e].content.parts.push(n)}e++}n.usageMetadata&&(t.usageMetadata=n.usageMetadata)}return t}async function UY(e,t,n,r){return RY(await wY(t,yY.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(n),r))}async function WY(e,t,n,r){return{response:kY(await(await wY(t,yY.GENERATE_CONTENT,e,!1,JSON.stringify(n),r)).json())}}function GY(e){if(e!=null){if(typeof e==`string`)return{role:`system`,parts:[{text:e}]};if(e.text)return{role:`system`,parts:[e]};if(e.parts)return e.role?e:{role:`system`,parts:e.parts}}}function KY(e){let t=[];if(typeof e==`string`)t=[{text:e}];else for(let n of e)typeof n==`string`?t.push({text:n}):t.push(n);return qY(t)}function qY(e){let t={role:`user`,parts:[]},n={role:`function`,parts:[]},r=!1,i=!1;for(let a of e)`functionResponse`in a?(n.parts.push(a),i=!0):(t.parts.push(a),r=!0);if(r&&i)throw new uY(`Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.`);if(!r&&!i)throw new uY(`No content is provided for sending chat message.`);return r?t:n}function JY(e,t){let n={model:t?.model,generationConfig:t?.generationConfig,safetySettings:t?.safetySettings,tools:t?.tools,toolConfig:t?.toolConfig,systemInstruction:t?.systemInstruction,cachedContent:t?.cachedContent?.name,contents:[]},r=e.generateContentRequest!=null;if(e.contents){if(r)throw new pY(`CountTokensRequest must have one of contents or generateContentRequest, not both.`);n.contents=e.contents}else if(r)n=Object.assign(Object.assign({},n),e.generateContentRequest);else{let t=KY(e);n.contents=[t]}return{generateContentRequest:n}}function YY(e){let t;return t=e.contents?e:{contents:[KY(e)]},e.systemInstruction&&(t.systemInstruction=GY(e.systemInstruction)),t}function XY(e){return typeof e==`string`||Array.isArray(e)?{content:KY(e)}:e}var ZY=[`text`,`inlineData`,`functionCall`,`functionResponse`,`executableCode`,`codeExecutionResult`],QY={user:[`text`,`inlineData`],function:[`functionResponse`],model:[`text`,`functionCall`,`executableCode`,`codeExecutionResult`],system:[`text`]};function $Y(e){let t=!1;for(let n of e){let{role:e,parts:r}=n;if(!t&&e!==`user`)throw new uY(`First content should be with role 'user', got ${e}`);if(!tY.includes(e))throw new uY(`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(tY)}`);if(!Array.isArray(r))throw new uY(`Content should have 'parts' property with an array of Parts`);if(r.length===0)throw new uY(`Each Content should have at least one part`);let i={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(let e of r)for(let t of ZY)t in e&&(i[t]+=1);let a=QY[e];for(let t of ZY)if(!a.includes(t)&&i[t]>0)throw new uY(`Content with role '${e}' can't contain '${t}' part`);t=!0}}function eX(e){if(e.candidates===void 0||e.candidates.length===0)return!1;let t=e.candidates[0]?.content;if(t===void 0||t.parts===void 0||t.parts.length===0)return!1;for(let e of t.parts)if(e===void 0||Object.keys(e).length===0||e.text!==void 0&&e.text===``)return!1;return!0}var tX=`SILENT_ERROR`,nX=class{constructor(e,t,n,r={}){this.model=t,this.params=n,this._requestOptions=r,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,n?.history&&($Y(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,t={}){await this._sendPromise;let n=KY(e),r={safetySettings:this.params?.safetySettings,generationConfig:this.params?.generationConfig,tools:this.params?.tools,toolConfig:this.params?.toolConfig,systemInstruction:this.params?.systemInstruction,cachedContent:this.params?.cachedContent,contents:[...this._history,n]},i=Object.assign(Object.assign({},this._requestOptions),t),a;return this._sendPromise=this._sendPromise.then(()=>WY(this._apiKey,this.model,r,i)).then(e=>{if(eX(e.response)){this._history.push(n);let t=Object.assign({parts:[],role:`model`},e.response.candidates?.[0].content);this._history.push(t)}else{let t=PY(e.response);t&&console.warn(`sendMessage() was unsuccessful. ${t}. Inspect response object for details.`)}a=e}).catch(e=>{throw this._sendPromise=Promise.resolve(),e}),await this._sendPromise,a}async sendMessageStream(e,t={}){await this._sendPromise;let n=KY(e),r={safetySettings:this.params?.safetySettings,generationConfig:this.params?.generationConfig,tools:this.params?.tools,toolConfig:this.params?.toolConfig,systemInstruction:this.params?.systemInstruction,cachedContent:this.params?.cachedContent,contents:[...this._history,n]},i=Object.assign(Object.assign({},this._requestOptions),t),a=UY(this._apiKey,this.model,r,i);return this._sendPromise=this._sendPromise.then(()=>a).catch(e=>{throw Error(tX)}).then(e=>e.response).then(e=>{if(eX(e)){this._history.push(n);let t=Object.assign({},e.candidates[0].content);t.role||=`model`,this._history.push(t)}else{let t=PY(e);t&&console.warn(`sendMessageStream() was unsuccessful. ${t}. Inspect response object for details.`)}}).catch(e=>{e.message!==tX&&console.error(e)}),a}};async function rX(e,t,n,r){return(await wY(t,yY.COUNT_TOKENS,e,!1,JSON.stringify(n),r)).json()}async function iX(e,t,n,r){return(await wY(t,yY.EMBED_CONTENT,e,!1,JSON.stringify(n),r)).json()}async function aX(e,t,n,r){let i=n.requests.map(e=>Object.assign(Object.assign({},e),{model:t}));return(await wY(t,yY.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:i}),r)).json()}var oX=class{constructor(e,t,n={}){this.apiKey=e,this._requestOptions=n,t.model.includes(`/`)?this.model=t.model:this.model=`models/${t.model}`,this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=GY(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(e,t={}){let n=YY(e),r=Object.assign(Object.assign({},this._requestOptions),t);return WY(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},n),r)}async generateContentStream(e,t={}){let n=YY(e),r=Object.assign(Object.assign({},this._requestOptions),t);return UY(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},n),r)}startChat(e){return new nX(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},e),this._requestOptions)}async countTokens(e,t={}){let n=JY(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),r=Object.assign(Object.assign({},this._requestOptions),t);return rX(this.apiKey,this.model,n,r)}async embedContent(e,t={}){let n=XY(e),r=Object.assign(Object.assign({},this._requestOptions),t);return iX(this.apiKey,this.model,n,r)}async batchEmbedContents(e,t={}){let n=Object.assign(Object.assign({},this._requestOptions),t);return aX(this.apiKey,this.model,e,n)}},sX=class{constructor(e){this.apiKey=e}getGenerativeModel(e,t){if(!e.model)throw new uY(`Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })`);return new oX(this.apiKey,e,t)}getGenerativeModelFromCachedContent(e,t,n){if(!e.name)throw new pY("Cached content must contain a `name` field.");if(!e.model)throw new pY("Cached content must contain a `model` field.");for(let n of[`model`,`systemInstruction`])if(t?.[n]&&e[n]&&t?.[n]!==e[n]){if(n===`model`&&(t.model.startsWith(`models/`)?t.model.replace(`models/`,``):t.model)===(e.model.startsWith(`models/`)?e.model.replace(`models/`,``):e.model))continue;throw new pY(`Different value for "${n}" specified in modelParams (${t[n]}) and cachedContent (${e[n]})`)}let r=Object.assign(Object.assign({},t),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new oX(this.apiKey,r,n)}};function cX(e,t){let n=lX(e);return{tools:n,toolConfig:dX(n,t)}}function lX(e){let t=[],n=[];return e.forEach(e=>{if(eA(e)){let[n]=qJ([e]);n.functionDeclarations&&t.push(...n.functionDeclarations)}else if(UT(e)){let{functionDeclarations:n}=uX(e);if(n)t.push(...n);else throw Error(`Failed to convert OpenAI structured tool to GenerativeAI tool`)}else n.push(e)}),n.find(e=>`functionDeclarations`in e)?n.map(e=>{if(t?.length>0&&`functionDeclarations`in e){let n={functionDeclarations:[...e.functionDeclarations||[],...t]};return t=[],n}return e}):[...n,...t.length>0?[{functionDeclarations:t}]:[]]}function uX(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:kJ(e.function.parameters)}]}}function dX(e,t){if(!e.length||!t)return;let{toolChoice:n,allowedFunctionNames:r}=t,i={any:cY.ANY,auto:cY.AUTO,none:cY.NONE};if(n&&[`any`,`auto`,`none`].includes(n))return{functionCallingConfig:{mode:i[n]??`MODE_UNSPECIFIED`,allowedFunctionNames:r}};if(typeof n==`string`||r)return{functionCallingConfig:{mode:cY.ANY,allowedFunctionNames:[...r??[],...n&&typeof n==`string`?[n]:[]]}}}var fX={"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:128e3,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8e3,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:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,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:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,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:64e3,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}},pX=class extends iD{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(e,t){let n=typeof e==`string`?{...t??{},model:e}:e;if(super(n),this._addVersion(`@langchain/google-genai`,`2.2.0`),this.model=n.model.replace(/^models\//,``),this.maxOutputTokens=n.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw Error("`maxOutputTokens` must be a positive integer");if(this.temperature=n.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=n.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=n.topK??this.topK,this.topK&&this.topK<0)throw Error("`topK` must be a positive integer");if(this.stopSequences=n.stopSequences??this.stopSequences,this.apiKey=n.apiKey??ui(`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=n.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(e=>e.category)).size!==this.safetySettings.length)throw Error("The categories in `safetySettings` array must be unique");this.streaming=n.streaming??this.streaming,this.json=n.json,this.thinkingConfig=n.thinkingConfig??this.thinkingConfig,this.client=new sX(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:n.apiVersion,baseUrl:n.baseUrl,customHeaders:n.customHeaders}),this.streamUsage=n.streamUsage??this.streamUsage}useCachedContent(e,t,n){this.apiKey&&(this.client=new sX(this.apiKey).getGenerativeModelFromCachedContent(e,t,n))}get useSystemInstruction(){return typeof this.convertSystemMessageToHumanContent==`boolean`?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return this.model!==`gemini-1.0-pro-001`&&!this.model.startsWith(`gemini-pro-vision`)&&!this.model.startsWith(`gemini-1.0-pro-vision`)&&this.model!==`gemini-pro`}getLsParams(e){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:e.stop}}_combineLLMOutput(){return[]}_llmType(){return`googlegenerativeai`}bindTools(e,t){return this.withConfig({tools:cX(e)?.tools,...t})}invocationParams(e){let t=e?.tools?.length?cX(e.tools,{toolChoice:e.tool_choice,allowedFunctionNames:e.allowedFunctionNames}):void 0;return{...t?.tools?{tools:t.tools}:{},...t?.toolConfig?{toolConfig:t.toolConfig}:{},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}:{},...e?.responseSchema?{responseSchema:e.responseSchema,responseMimeType:`application/json`}:{}}}}_buildGenerateContentRequest(e,t){let n=WJ(e,this._isMultimodalModel,this.useSystemInstruction,this.model),r=n,i;return n[0]?.role===`system`&&([i,...r]=n),{...this.invocationParams(t),...i?{systemInstruction:i}:{},contents:r}}async _generate(e,t,n){if(t.signal?.throwIfAborted(),this.streaming){let r={},i=this._streamResponseChunks(e,t,n),a=[];for await(let e of i){let t=e.generationInfo?.completion??0;a[t]===void 0?a[t]=e:a[t]=a[t].concat(e)}return{generations:a.filter(e=>e!==void 0),llmOutput:{estimatedTokenUsage:r}}}let r=await this.completionWithRetry(this._buildGenerateContentRequest(e,t)),i;`usageMetadata`in r.response&&(i=JJ(r.response.usageMetadata,this.model));let a=GJ(r.response,{usageMetadata:i});return a.generations?.length>0&&await n?.handleLLMNewToken(a.generations[0]?.text??``),a}async*_streamChatModelEvents(e,t,n){let r=this._buildGenerateContentRequest(e,t),i=await this.caller.callWithOptions({signal:t?.signal},async()=>{let{stream:e}=await this.client.generateContentStream(r,{signal:t?.signal});return e}),a=this.streamUsage!==!1&&t.streamUsage!==!1;yield*YJ(async function*(e,t){for await(let n of e){if(t?.aborted)return;yield n}}(i,t.signal),{streamUsage:a,model:this.model})}async*_streamResponseChunks(e,t,n){let r=this._buildGenerateContentRequest(e,t),i=await this.caller.callWithOptions({signal:t?.signal},async()=>{let{stream:e}=await this.client.generateContentStream(r,{signal:t?.signal});return e}),a,o=0,s=0,c=0,l=0;for await(let e of i){if(t.signal?.aborted)return;if(`usageMetadata`in e&&e.usageMetadata!==void 0&&this.streamUsage!==!1&&t.streamUsage!==!1){a=JJ(e.usageMetadata,this.model);let t=e.usageMetadata.promptTokenCount??0;a.input_tokens=Math.max(0,t-o),o=t;let n=e.usageMetadata.candidatesTokenCount??0;a.output_tokens=Math.max(0,n-s),s=n;let r=e.usageMetadata.totalTokenCount??0;a.total_tokens=Math.max(0,r-c),c=r}let r=KJ(e,{usageMetadata:a,index:l});l+=1,r&&(yield r,await n?.handleLLMNewToken(r.text??``))}}async completionWithRetry(e,t){return this.caller.callWithOptions({signal:t?.signal},async()=>{try{return await this.client.generateContent(e,{signal:t?.signal})}catch(e){throw e.message?.includes(`400 Bad Request`)&&(e.status=400),e}})}get profile(){return fX[this.model]??{}}withStructuredOutput(e,t){let n=e,r=t?.name,i=t?.method,a=t?.includeRaw;if(i===`jsonMode`)throw Error(`ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.`);let o,s;if(i===`functionCalling`){let e=r??`extract`,t;if(N_(n)||Zb(n)){let r=AJ(n);t={name:e,description:r.description??`A function available to call.`,parameters:r}}else typeof n.name==`string`&&typeof n.parameters==`object`&&n.parameters!=null?(t=n,t.parameters=kJ(n.parameters),e=n.name):t={name:e,description:n.description??``,parameters:kJ(n)};let i=[{functionDeclarations:[t]}];o=this.bindTools(i).withConfig({allowedFunctionNames:[e]}),s=DE(n,e,ZJ)}else{let e=AJ(n);o=this.withConfig({responseSchema:e}),s=EE(n)}return OE(o,s,a,a?`StructuredOutputRunnable`:`ChatGoogleGenerativeAIStructuredOutput`)}},mX=class extends YT{static lc_name(){return`AnthropicToolsOutputParser`}lc_namespace=[`langchain`,`anthropic`,`output_parsers`];returnId=!1;keyName;returnSingle=!1;zodSchema;serializableSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}async _validateResult(e){let t=e;if(typeof e==`string`)try{t=JSON.parse(e)}catch(t){throw new ZT(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.message)}`,e)}else t=e;if(this.serializableSchema!==void 0){let e=await this.serializableSchema[`~standard`].validate(t);if(e.issues)throw new ZT(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(e.issues)}`,JSON.stringify(t,null,2));return e.value}if(this.zodSchema===void 0)return t;let n=await L_(this.zodSchema,t);if(n.success)return n.data;throw new ZT(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(e){let t=e.flatMap(e=>{let{message:t}=e;return Array.isArray(t.content)?hX(t.content)[0]:[]});if(t[0]===void 0)throw Error(`No parseable tool calls provided to AnthropicToolsOutputParser.`);let[n]=t;return await this._validateResult(n.args)}};function hX(e){let t=[];for(let n of e)n.type===`tool_use`&&t.push({name:n.name,args:n.input,id:n.id,type:`tool_call`});return t}var gX=[`oneOf`,`anyOf`,`allOf`];function _X(e){return typeof e.input_schema!=`object`||e.input_schema===null?[]:gX.filter(t=>Object.prototype.hasOwnProperty.call(e.input_schema,t))}function vX(e){if(e)return e===`any`||e===`required`?{type:`any`}:e===`auto`?{type:`auto`}:e===`none`?{type:`none`}:typeof e==`string`?{type:`tool`,name:e}:e}var yX=V({cache_control:Uj().optional().nullable(),defer_loading:QA().optional(),input_examples:oj(nj()).optional(),allowed_callers:oj(nj()).optional(),strict:QA().optional()}),bX={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 xX(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`thinking`}function SX(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`redacted_thinking`}function CX(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`compaction`}function wX(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`search_result`}function TX(e){return typeof e!=`object`||!e||!(`type`in e)||e.type!==`image`||!(`source`in e)||typeof e.source!=`object`||e.source==null||!(`type`in e.source)?!1:e.source.type===`base64`?!(!(`media_type`in e.source)||typeof e.source.media_type!=`string`||!(`data`in e.source)||typeof e.source.data!=`string`):e.source.type===`url`&&!(!(`url`in e.source)||typeof e.source.url!=`string`)}var EX={providerName:`anthropic`,fromStandardTextBlock(e){return{type:`text`,text:e.text,...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}},fromStandardImageBlock(e){if(e.source_type===`url`){let t=et({dataUrl:e.url,asTypedArray:!1});return t?{type:`image`,source:{type:`base64`,data:t.data,media_type:t.mime_type},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}:{type:`image`,source:{type:`url`,url:e.url},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}}else if(e.source_type===`base64`)return{type:`image`,source:{type:`base64`,data:e.data,media_type:e.mime_type??``},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}};else throw Error(`Unsupported image source type: ${e.source_type}`)},fromStandardFileBlock(e){let t=(e.mime_type??``).split(`;`)[0];if(e.source_type===`url`){if(t===`application/pdf`||t===``)return{type:`document`,source:{type:`url`,url:e.url},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file url source: ${e.mime_type}`)}else if(e.source_type===`text`){if(t===`text/plain`||t===``)return{type:`document`,source:{type:`text`,data:e.text,media_type:e.mime_type??``},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file text source: ${e.mime_type}`)}else if(e.source_type===`base64`){if(t===`application/pdf`||t===``)return{type:`document`,source:{type:`base64`,data:e.data,media_type:`application/pdf`},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};if([`image/jpeg`,`image/png`,`image/gif`,`image/webp`].includes(t))return{type:`document`,source:{type:`content`,content:[{type:`image`,source:{type:`base64`,data:e.data,media_type:t}}]},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file base64 source: ${e.mime_type}`)}else throw Error(`Unsupported file source type: ${e.source_type}`)}},DX=e=>e();function OX(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`citation`}function kX(e){function*t(){for(let t of e)OX(t)&&(t.source===`char`?yield{type:`char_location`,file_id:t.url??``,start_char_index:t.startIndex??0,end_char_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`page`?yield{type:`page_location`,file_id:t.url??``,start_page_number:t.startIndex??0,end_page_number:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`block`?yield{type:`content_block_location`,file_id:t.url??``,start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`url`?yield{type:`web_search_result_location`,url:t.url??``,title:t.title??null,encrypted_index:String(t.startIndex??0),cited_text:t.citedText??``}:t.source===`search`&&(yield{type:`search_result_location`,title:t.title??null,start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,search_result_index:0,source:t.source??``,cited_text:t.citedText??``}))}return Array.from(t())}function AX(e){return typeof e==`string`?e:jX(e)}function jX(e){let t=[];for(let n=0,{length:r}=e;n<r;n++)t.push(String.fromCharCode(e[n]));return btoa(t.join(``))}function MX(e){return(e??``).split(`;`)[0].toLowerCase()}function NX(e,t){if(typeof e==`object`&&e&&t in e)return e[t]}function PX(e,t){let n=NX(t,`cache_control`);n!==void 0&&(e.cache_control=n);let r=NX(t,`citations`);r!==void 0&&(e.citations=r);let i=NX(t,`context`);i!==void 0&&(e.context=i);let a=NX(t,`title`);return a!==void 0&&(e.title=a),e}function FX(e,t){let n=NX(t,`cache_control`);return n!==void 0&&(e.cache_control=n),e}function IX(e){return new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]).has(e)}function LX(e){let t=[],n=e.response_metadata,r=`model_provider`in n&&n?.model_provider===`anthropic`;for(let n of e.contentBlocks)if(n.type===`text`)n.annotations?t.push({type:`text`,text:n.text,citations:kX(n.annotations)}):t.push({type:`text`,text:n.text});else if(n.type===`tool_call`)t.push({type:`tool_use`,id:n.id??``,name:n.name,input:n.args});else if(n.type===`tool_call_chunk`){let e=DX(()=>{if(typeof n.args!=`string`)return n.args;try{return JSON.parse(n.args)}catch{return{}}});t.push({type:`tool_use`,id:n.id??``,name:n.name??``,input:e})}else if(n.type===`reasoning`&&r)t.push({type:`thinking`,thinking:n.reasoning,signature:String(n.signature)});else if(n.type===`server_tool_call`&&r)(n.name===`web_search`||n.name===`code_execution`)&&t.push({type:`server_tool_use`,name:n.name,id:n.id??``,input:n.args});else if(n.type===`server_tool_call_result`&&r)if(n.name===`web_search`&&Array.isArray(n.output.urls)){let e=n.output.urls.map(e=>({type:`web_search_result`,title:``,encrypted_content:``,url:e}));t.push({type:`web_search_tool_result`,tool_use_id:n.toolCallId??``,content:e})}else n.name===`code_execution`?t.push({type:`code_execution_tool_result`,tool_use_id:n.toolCallId??``,content:n.output}):n.name===`mcp_tool_result`&&t.push({type:`mcp_tool_result`,tool_use_id:n.toolCallId??``,content:n.output});else if(n.type===`audio`)throw Error(`Anthropic does not support audio content blocks.`);else if(n.type===`file`){let e=n.metadata;if(n.fileId){t.push(PX({type:`document`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){let r=MX(n.mimeType);if(r===`application/pdf`||r===``){t.push(PX({type:`document`,source:{type:`url`,url:n.url}},e));continue}}if(n.data){let r=MX(n.mimeType);if(r===``||r===`application/pdf`)t.push(PX({type:`document`,source:{type:`base64`,data:AX(n.data),media_type:`application/pdf`}},e));else if(r===`text/plain`)t.push(PX({type:`document`,source:{type:`text`,data:AX(n.data),media_type:`text/plain`}},e));else if(IX(r))t.push(PX({type:`document`,source:{type:`content`,content:[{type:`image`,source:{type:`base64`,data:AX(n.data),media_type:r}}]}},e));else throw Error(`Unsupported file mime type for Anthropic base64 source: ${r}`);continue}throw Error(`File content block must include a fileId, url, or data property.`)}else if(n.type===`image`){let e=n.metadata;if(n.fileId){t.push(FX({type:`image`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){t.push(FX({type:`image`,source:{type:`url`,url:n.url}},e));continue}if(n.data){let r=MX(n.mimeType)||`image/png`;IX(r)&&t.push(FX({type:`image`,source:{type:`base64`,data:AX(n.data),media_type:r}},e));continue}throw Error(`Image content block must include a fileId, url, or data property.`)}else n.type===`video`||(n.type===`text-plain`?n.data&&t.push(PX({type:`document`,source:{type:`text`,data:AX(n.data),media_type:`text/plain`}},n.metadata)):n.type===`non_standard`&&r&&t.push(n.value));return t}function RX(e){let t=et({dataUrl:e});if(t)return{type:`base64`,media_type:t.mime_type,data:t.data};let n;try{n=new URL(e)}catch{throw Error([`Malformed image URL: ${JSON.stringify(e)}. 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(`
|
|
211
|
+
]))`;continue}}if(r.s&&i[e]===`.`){a+=s?`${i[e]}\r\n`:`[${i[e]}\r\n]`;continue}a+=i[e],i[e]===`\\`?o=!0:s&&i[e]===`]`?s=!1:!s&&i[e]===`[`&&(s=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return a};function mq(e,t){if(t.target===`openApi3`&&e.keyType?._def.typeName===R.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:Pq(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??{}}),{}),additionalProperties:!1};let n={type:`object`,additionalProperties:Pq(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??{}};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===R.ZodString&&e.keyType._def.checks?.length){let r=Object.entries(lq(e.keyType._def,t)).reduce((e,[t,n])=>t===`type`?e:{...e,[t]:n},{});return{...n,propertyNames:r}}else if(e.keyType?._def.typeName===R.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};return n}function hq(e,t){return t.mapStrategy===`record`?mq(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[Pq(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||{},Pq(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||{}],minItems:2,maxItems:2}}}function gq(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function _q(){return{not:{}}}function vq(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var yq={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function bq(e,t){if(t.target===`openApi3`)return xq(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in yq&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=yq[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return xq(e,t)}var xq=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>Pq(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Sq(e,t,n){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`||t.nullableStrategy===`property`?{type:yq[e.innerType._def.typeName],nullable:!0}:{type:[yq[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let r=Pq(e.innerType._def,{...t,currentPath:[...t.currentPath]},n);return r&&`$ref`in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let r=Pq(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return r&&{anyOf:[r,{type:`null`}]}}function Cq(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,GK(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?KK(n,`minimum`,r.value,r.message,t):KK(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),KK(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?KK(n,`maximum`,r.value,r.message,t):KK(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),KK(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:KK(n,`multipleOf`,r.value,r.message,t);break}return n}function wq(e,t){return t.removeAdditionalStrategy===`strict`?e.catchall._def.typeName===`ZodNever`?e.unknownKeys!==`strict`:Pq(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0:e.catchall._def.typeName===`ZodNever`?e.unknownKeys===`passthrough`:Pq(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0}function Tq(e,t){let n={type:`object`,...Object.entries(e.shape()).reduce((e,[n,r])=>{if(r===void 0||r._def===void 0)return e;let i=[...t.currentPath,`properties`,n],a=Pq(r._def,{...t,currentPath:i,propertyPath:i});if(a===void 0)return e;if(t.openaiStrictMode&&r.isOptional()&&!r.isNullable()&&r._def?.defaultValue===void 0)throw Error(`Zod field at \`${i.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:{...e.properties,[n]:a},required:r.isOptional()&&!t.openaiStrictMode?e.required:[...e.required,n]}},{properties:{},required:[]}),additionalProperties:wq(e,t)};return n.required.length||delete n.required,n}var Eq=(e,t,n)=>{if(t.propertyPath&&t.currentPath.slice(0,t.propertyPath.length).toString()===t.propertyPath.toString())return Pq(e.innerType._def,{...t,currentPath:t.currentPath},n);let r=Pq(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]},n);return r?{anyOf:[{not:{}},r]}:{}},Dq=(e,t,n)=>{if(t.pipeStrategy===`input`)return Pq(e.in._def,t,n);if(t.pipeStrategy===`output`)return Pq(e.out._def,t,n);let r=Pq(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[r,Pq(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,r?`1`:`0`]})].filter(e=>e!==void 0)}};function Oq(e,t,n){return Pq(e.type._def,t,n)}function kq(e,t){let n={type:`array`,uniqueItems:!0,items:Pq(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&KK(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&KK(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function Aq(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>Pq(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:Pq(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>Pq(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function jq(){return{not:{}}}function Mq(){return{}}var Nq=(e,t,n)=>Pq(e.innerType._def,t,n);function Pq(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==zK)return i}if(r&&!n){let e=Fq(r,t);if(e!==void 0)return`$ref`in e&&t.seenRefs.add(e.$ref),e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);try{let r=zq(e,e.typeName,t,n);return r&&Bq(e,t,r),i.jsonSchema=r,r}finally{n&&r&&t.seen.set(e,r)}}var Fq=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`extract-to-root`:let n=e.path.slice(t.basePath.length+1).map((e,t)=>t===0?e:Lq(e)).join(`_`);return n!==t.name&&t.nameStrategy===`duplicate-ref`&&(t.definitions[n]=e.def),{$ref:[...t.basePath,t.definitionPath,n].join(`/`)};case`relative`:return{$ref:Rq(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),{}):t.$refStrategy===`seen`?{}:void 0}},Iq=`_x_`,Lq=e=>{if(/^[A-Za-z0-9_-]*$/.test(e)&&!e.startsWith(Iq))return e;let t=Iq;for(let n=0;n<e.length;n++)t+=e.charCodeAt(n).toString(16).padStart(4,`0`);return t},Rq=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)},zq=(e,t,n,r)=>{switch(t){case R.ZodString:return lq(e,n);case R.ZodNumber:return Cq(e,n);case R.ZodObject:return Tq(e,n);case R.ZodBigInt:return YK(e,n);case R.ZodBoolean:return XK();case R.ZodDate:return $K(e,n);case R.ZodUndefined:return jq();case R.ZodNull:return vq(n);case R.ZodArray:return JK(e,n);case R.ZodUnion:case R.ZodDiscriminatedUnion:return bq(e,n);case R.ZodIntersection:return aq(e,n);case R.ZodTuple:return Aq(e,n);case R.ZodRecord:return mq(e,n);case R.ZodLiteral:return oq(e,n);case R.ZodEnum:return rq(e);case R.ZodNativeEnum:return gq(e);case R.ZodNullable:return Sq(e,n,r);case R.ZodOptional:return Eq(e,n,r);case R.ZodMap:return hq(e,n);case R.ZodSet:return kq(e,n);case R.ZodLazy:return Pq(e.getter()._def,n,r);case R.ZodPromise:return Oq(e,n,r);case R.ZodNaN:case R.ZodNever:return _q();case R.ZodEffects:return nq(e,n,r);case R.ZodAny:return qK();case R.ZodUnknown:return Mq();case R.ZodDefault:return tq(e,n,r);case R.ZodBranded:return ZK(e,n,r);case R.ZodReadonly:return Nq(e,n,r);case R.ZodCatch:return QK(e,n,r);case R.ZodPipeline:return Dq(e,n,r);case R.ZodFunction:case R.ZodVoid:case R.ZodSymbol:return;default:return(e=>void 0)(t)}},Bq=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Vq=(e,t)=>{let n=WK(t),r=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,i=Pq(e._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??{},a=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;a!==void 0&&(i.title=a);let o=(()=>{if(UK(n.definitions))return;let e={},t=new Set;for(let r=0;r<500;r++){let r=Object.entries(n.definitions).filter(([e])=>!t.has(e));if(r.length===0)break;for(let[i,a]of r)e[i]=Pq(HK(a),{...n,currentPath:[...n.basePath,n.definitionPath,i]},!0)??{},t.add(i)}return e})(),s=r===void 0?o?{...i,[n.definitionPath]:o}:i:n.nameStrategy===`duplicate-ref`?{...i,...o||n.seenRefs.size?{[n.definitionPath]:{...o,...n.seenRefs.size?{[r]:i}:void 0}}:void 0}:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,r].join(`/`),[n.definitionPath]:{...o,[r]:i}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:n.target===`jsonSchema2019-09`&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),s};function Hq(e){if(e.type!==`object`)throw Error(`Root schema must have type: 'object' but got type: ${e.type?`'${e.type}'`:`undefined`}`);let t=structuredClone(e);return Wq(t,[],t)}function Uq(e){if(typeof e==`boolean`)return!1;if(e.type===`null`)return!0;for(let t of e.oneOf??[])if(Uq(t))return!0;for(let t of e.anyOf??[])if(Uq(t))return!0;return!1}function Wq(e,t,n){if(typeof e==`boolean`)throw TypeError(`Expected object schema but got boolean; path=${t.join(`/`)}`);if(!Kq(e))throw TypeError(`Expected ${JSON.stringify(e)} to be an object; path=${t.join(`/`)}`);let r=e.$defs;if(Kq(r))for(let[e,i]of Object.entries(r))Wq(i,[...t,`$defs`,e],n);let i=e.definitions;if(Kq(i))for(let[e,r]of Object.entries(i))Wq(r,[...t,`definitions`,e],n);e.type===`object`&&!(`additionalProperties`in e)&&(e.additionalProperties=!1);let a=e.required??[],o=e.properties;if(Kq(o)){for(let[e,n]of Object.entries(o))if(!Uq(n)&&!a.includes(e))throw Error(`Zod field at \`${[...t,`properties`,e].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`);e.required=Object.keys(o),e.properties=Object.fromEntries(Object.entries(o).map(([e,r])=>[e,Wq(r,[...t,`properties`,e],n)]))}let s=e.items;Kq(s)&&(e.items=Wq(s,[...t,`items`],n));let c=e.anyOf;Array.isArray(c)&&(e.anyOf=c.map((e,r)=>Wq(e,[...t,`anyOf`,String(r)],n)));let l=e.allOf;if(Array.isArray(l))if(l.length===1){let r=Wq(l[0],[...t,`allOf`,`0`],n);Object.assign(e,r),delete e.allOf}else e.allOf=l.map((e,r)=>Wq(e,[...t,`allOf`,String(r)],n));e.default===null&&delete e.default;let u=e.$ref;if(u&&qq(e,1)){if(typeof u!=`string`)throw TypeError(`Received non-string $ref - ${u}; path=${t.join(`/`)}`);let r=Gq(n,u);if(typeof r==`boolean`)throw Error(`Expected \`$ref: ${u}\` to resolve to an object schema but got boolean`);if(!Kq(r))throw Error(`Expected \`$ref: ${u}\` to resolve to an object but got ${JSON.stringify(r)}`);return Object.assign(e,{...r,...e}),delete e.$ref,Wq(e,t,n)}return e}function Gq(e,t){if(!t.startsWith(`#/`))throw Error(`Unexpected $ref format ${JSON.stringify(t)}; Does not start with #/`);let n=t.slice(2).split(`/`),r=e;for(let e of n){if(!Kq(r))throw Error(`encountered non-object entry while resolving ${t} - ${JSON.stringify(r)}`);let n=r[e];if(n===void 0)throw Error(`Key ${e} not found while resolving ${t}`);r=n}return r}function Kq(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qq(e,t){let n=0;for(let r in e)if(n++,n>t)return!0;return!1}function Jq(e,t){return Vq(e,{openaiStrictMode:!0,name:t.name,nameStrategy:`duplicate-ref`,$refStrategy:`extract-to-root`,nullableStrategy:`property`})}function Yq(e){return Hq(k_(e,{target:`draft-7`,override:({zodSchema:e,jsonSchema:t})=>{let n=e._zod.def;if(n.type===`union`&&`discriminator`in n&&Array.isArray(t.oneOf)){if(t.anyOf!==void 0)throw Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");t.anyOf=t.oneOf,delete t.oneOf}}}))}function Xq(e){return`_zod`in e}function Zq(e,t,n){return nH({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:Xq(e)?Yq(e):Jq(e,{name:t})}},t=>e.parse(JSON.parse(t)))}var Qq=[`jsonSchema`,`functionCalling`,`jsonMode`];function $q(e,t){if(t!==void 0&&!Qq.includes(t))throw Error(`Invalid method: ${t}. Supported methods are: ${Qq.join(`, `)}`);let n=!e.startsWith(`gpt-3`)&&!e.startsWith(`gpt-4-`)&&e!==`gpt-4`;if(n&&!t)return`jsonSchema`;if(!n&&t===`jsonSchema`)throw Error(`JSON Schema is not supported for model "${e}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return t??`functionCalling`}function eJ(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:`auto-parseable-response-format`,enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function tJ(e,t,n){if(j_(e))return Zq(e,t,n);if(A_(e))return eJ({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:Rx(e,{cycles:`ref`,reused:`ref`,override(e){e.jsonSchema.title=t}})}},t=>$f(e,JSON.parse(t)));throw Error(`Unsupported schema response format`)}function nJ(e,t){if(t&&typeof t==`object`&&`images`in t&&Array.isArray(t.images)){let n=t.images.filter(e=>typeof e?.image_url?.url==`string`).map(e=>({type:`image`,url:e.image_url.url}));return[{type:`text`,text:e},...n]}return e}var rJ={"gpt-4o-2024-11-20":{maxInputTokens:128e3,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,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:128e3,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:128e3,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,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:2e5,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,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:2e5,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:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,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:2e5,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:128e3,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,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},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,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},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,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:128e3,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,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:128e3,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:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,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:128e3,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}};function iJ(e,t){return typeof e==`string`?{model:e,...t??{}}:e??t}var aJ=class extends iD{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`.split(`.`)}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`openai`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(e){super(e??{});let t=typeof e?.configuration?.apiKey==`string`||typeof e?.configuration?.apiKey==`function`?e?.configuration?.apiKey:void 0;this.apiKey=e?.apiKey??t??ui(`OPENAI_API_KEY`),this.organization=e?.configuration?.organization??ui(`OPENAI_ORGANIZATION`),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoning=e?.reasoning,this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.promptCacheKey=e?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=e?.promptCacheRetention??this.promptCacheRetention,this.verbosity=e?.verbosity??this.verbosity,this.disableStreaming=e?.disableStreaming===!0,this.streaming=e?.streaming===!0,this.disableStreaming&&(this.streaming=!1),e?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},e?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),e?.service_tier!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1,this._addVersion(`@langchain/openai`,`1.5.3`)}_getReasoningParams(e){if(!uK(this.model))return;let t;return this.reasoning!==void 0&&(t={...t,...this.reasoning}),e?.reasoning!==void 0&&(t={...t,...e.reasoning}),e?.reasoningEffort!==void 0&&t?.effort===void 0&&(t={...t,effort:e.reasoningEffort}),t}_getResponseFormat(e){return e&&e.type===`json_schema`&&e.json_schema.schema&&N_(e.json_schema.schema)?tJ(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){let e=_K({baseURL:this.clientConfig.baseURL}),t={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};t.baseURL||delete t.baseURL,t.defaultHeaders=xK(t.defaultHeaders),this.client=new Y(t)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return jK(e)?RK(e.metadata.customTool):UT(e)?t?.strict===void 0?e:{...e,function:{...e.function,strict:t.strict}}:SK(e,t)}bindTools(e,t){let n;return t?.strict===void 0?this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling):n=t.strict,this.withConfig({tools:e.map(e=>{if(OK(e)||jK(e))return e;if(kK(e))return e.extras.providerToolDefinition;let t=this._convertChatOpenAIToolToCompletionsTool(e,{strict:n});return eA(e)&&e.extras?.defer_loading===!0?{...t,defer_loading:!0}:t}),...t})}async stream(e,t){return super.stream(e,this._combineCallOptions(t))}async invoke(e,t){return super.invoke(e,this._combineCallOptions(t))}_combineLLMOutput(...e){return e.reduce((e,t)=>(t&&t.tokenUsage&&(e.tokenUsage.completionTokens+=t.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=t.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=t.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=0,n=0,r=0;this.model===`gpt-3.5-turbo-0301`?(n=4,r=-1):(n=3,r=1);let i=await Promise.all(e.map(async e=>{let[i,a]=await Promise.all([this.getNumTokens(e.content),this.getNumTokens(hK(e))]),o=e.name===void 0?0:r+await this.getNumTokens(e.name),s=i+n+a+o,c=e;if(c._getType()===`function`&&(s-=2),c.additional_kwargs?.function_call&&(s+=3),c?.additional_kwargs.function_call?.name&&(s+=await this.getNumTokens(c.additional_kwargs.function_call?.name)),c.additional_kwargs.function_call?.arguments)try{s+=await this.getNumTokens(JSON.stringify(JSON.parse(c.additional_kwargs.function_call?.arguments)))}catch(e){console.error(`Error parsing function arguments`,e,JSON.stringify(c.additional_kwargs.function_call)),s+=await this.getNumTokens(c.additional_kwargs.function_call?.arguments)}return t+=s,s}));return t+=3,{totalCount:t,countPerMessage:i}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,t)=>e+t,0)}async _getEstimatedTokenCountFromPrompt(e,t,n){let r=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&n!==`auto`){let e=wK(t);r+=await this.getNumTokens(e),r+=9}return t&&e.find(e=>e._getType()===`system`)&&(r-=4),n===`none`?r+=1:typeof n==`object`&&(r+=await this.getNumTokens(n.name)+4),r}async moderateContent(e,t){let n=this._getClientOptions(t?.options),r={input:e,model:t?.model??`omni-moderation-latest`};return this.caller.call(async()=>{try{return await this.client.moderations.create(r,n)}catch(e){throw cK(e)}})}get profile(){return rJ[this.model]??{}}_getStructuredOutputMethod(e){let t={...e};if(!this.model.startsWith(`gpt-3`)&&!this.model.startsWith(`gpt-4-`)&&this.model!==`gpt-4`){if(t?.method===void 0)return`jsonSchema`}else t.method===`jsonSchema`&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return t.method}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e};if(t?.strict!==void 0&&t.method===`jsonMode`)throw Error("Argument `strict` is only supported for `method` = 'function_calling'");let s=$q(this.model,t?.method);if(s===`jsonMode`){r=EE(i);let e=Rx(i);n=this.withConfig({outputVersion:`v0`,response_format:{type:`json_object`},ls_structured_output_format:{kwargs:{method:`json_mode`},schema:{title:a??`extract`,...e}}})}else if(s===`jsonSchema`){let e=Rx(i),o={name:a??`extract`,description:V_(e),schema:N_(i)?i:e,strict:t?.strict};if(n=this.withConfig({outputVersion:`v0`,response_format:{type:`json_schema`,json_schema:o},ls_structured_output_format:{kwargs:{method:`json_schema`},schema:{title:o.name,description:o.description,...e}}}),N_(i)||Zb(i)){let e=EE(i);r=lS.from(async t=>`parsed`in t.additional_kwargs?t.additional_kwargs.parsed:e.invoke(t.content))}else r=new sE}else{let e=a??`extract`,o=Rx(i),s;N_(i)||Zb(i)?s={name:e,description:o.description,parameters:o}:typeof i.name==`string`&&typeof i.parameters==`object`&&i.parameters!=null?(s=i,e=i.name):(e=i.title??e,s={name:e,description:i.description??``,parameters:i}),n=this.withConfig({outputVersion:`v0`,tools:[{type:`function`,function:s}],tool_choice:{type:`function`,function:{name:e}},ls_structured_output_format:{kwargs:{method:`function_calling`},schema:{title:e,...o}},...t?.strict===void 0?{}:{strict:t.strict}}),r=DE(i,e)}return OE(n,r,o)}},oJ={providerName:`ChatOpenAI`,fromStandardTextBlock(e){return{type:`text`,text:e.text}},fromStandardImageBlock(e){if(e.source_type===`url`)return{type:`image_url`,image_url:{url:e.url,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};if(e.source_type===`base64`)return{type:`image_url`,image_url:{url:`data:${e.mime_type??``};base64,${e.data}`,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};throw Error(`Image content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(e){if(e.source_type===`url`){let t=et({dataUrl:e.url});if(!t)throw Error(`URL audio blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);let n=t.mime_type||e.mime_type||``,r;try{r=$e(n)}catch{throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(r.type!==`audio`||r.subtype!==`wav`&&r.subtype!==`mp3`)throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:`input_audio`,input_audio:{format:r.subtype,data:t.data}}}if(e.source_type===`base64`){let t;try{t=$e(e.mime_type??``)}catch{throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(t.type!==`audio`||t.subtype!==`wav`&&t.subtype!==`mp3`)throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:`input_audio`,input_audio:{format:t.subtype,data:e.data}}}throw Error(`Audio content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(e){if(e.source_type===`url`){let t=et({dataUrl:e.url}),n=mK(e);if(!t)throw Error(`URL file blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:`file`,file:{file_data:e.url,filename:n}}}if(e.source_type===`base64`){let t=mK(e);return{type:`file`,file:{file_data:`data:${e.mime_type??``};base64,${e.data}`,filename:t}}}if(e.source_type===`id`)return{type:`file`,file:{file_id:e.id}};throw Error(`File content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)}},sJ=({message:e,rawResponse:t,includeRawResponse:n})=>{let r=e.tool_calls,i=e.reasoning_content;switch(e.role){case`assistant`:{let a=[],o=[];for(let e of r??[])try{a.push(bE(e,{returnId:!0}))}catch(t){o.push(SE(e,t.message))}let s={function_call:e.function_call,tool_calls:r};n!==void 0&&(s.__raw_response=t),i!==void 0&&(s.reasoning_content=i);let c={model_provider:`openai`,model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};return e.audio&&(s.audio=e.audio),new An({content:nJ(e.content||``,t.choices?.[0]?.message),tool_calls:a,invalid_tool_calls:o,additional_kwargs:s,response_metadata:c,id:t.id})}default:return new Pn(e.content||``,e.role??`unknown`)}},cJ=({delta:e,rawResponse:t,includeRawResponse:n,defaultRole:r})=>{let i=e.role??r,a=e.content??``,o;o=e.function_call?{function_call:e.function_call}:e.tool_calls?{tool_calls:e.tool_calls}:{},n&&(o.__raw_response=t),e.reasoning_content!==void 0&&(o.reasoning_content=e.reasoning_content),e.audio&&(o.audio={...e.audio,index:t.choices[0].index});let s={model_provider:`openai`,usage:{...t.usage}};if(i===`user`)return new Un({content:a,response_metadata:s});if(i===`assistant`){let n=[];if(Array.isArray(e.tool_calls))for(let t of e.tool_calls)n.push({name:t.function?.name,args:t.function?.arguments,id:t.id,index:t.index,type:`tool_call_chunk`});return new Nn({content:a,tool_call_chunks:n,additional_kwargs:o,id:t.id,response_metadata:s})}else if(i===`system`)return new Jn({content:a,response_metadata:s});else if(i===`developer`)return new Jn({content:a,response_metadata:s,additional_kwargs:{__openai_role__:`developer`}});else if(i===`function`)return new zn({content:a,additional_kwargs:o,name:e.name,response_metadata:s});else if(i===`tool`)return new Zt({content:a,additional_kwargs:o,tool_call_id:e.tool_call_id,response_metadata:s});else return new Fn({content:a,role:i,response_metadata:s})},lJ=e=>{if(e.type===`image`){if(e.url)return{type:`image_url`,image_url:{url:e.url}};if(e.data)return{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}}if(e.type===`audio`&&e.data){let t=Qn(()=>{let[,t]=e.mimeType.split(`/`);return t===`wav`||t===`mp3`?t:`wav`});return{type:`input_audio`,input_audio:{data:e.data.toString(),format:t}}}if(e.type===`file`){if(e.data){let t=mK(e);return{type:`file`,file:{file_data:`data:${e.mimeType};base64,${e.data}`,filename:t}}}if(e.fileId)return{type:`file`,file:{file_id:e.fileId}}}},uJ=({message:e,model:t})=>{let n=hK(e);if(n===`system`&&uK(t)&&(n=`developer`),n===`developer`)return{role:`developer`,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`system`)return{role:`system`,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`assistant`){let t={role:`assistant`,content:e.contentBlocks.filter(e=>e.type===`text`)};return An.isInstance(e)&&e.tool_calls?.length?t.tool_calls=e.tool_calls.map(xE):e.additional_kwargs.tool_calls!=null&&(t.tool_calls=e.additional_kwargs.tool_calls),t}else if(n===`tool`&&Xt.isInstance(e))return{role:`tool`,tool_call_id:e.tool_call_id,content:e.contentBlocks.filter(e=>e.type===`text`)};else if(n===`function`)return{role:`function`,name:e.name??``,content:e.contentBlocks.filter(e=>e.type===`text`).join(``)};function*r(e){for(let t of e){t.type===`text`&&(yield{type:`text`,text:t.text});let e=lJ(t);e&&(yield e)}}return{role:`user`,content:Array.from(r(e.contentBlocks))}},dJ=({messages:e,model:t})=>e.flatMap(e=>{if(`output_version`in e.response_metadata&&e.response_metadata?.output_version===`v1`)return uJ({message:e});let n=hK(e);n===`system`&&uK(t)&&(n=`developer`);let r=typeof e.content==`string`?e.content:e.content.flatMap(e=>qe(e)?tt(e,oJ):typeof e==`object`&&e&&`type`in e&&e.type===`tool_use`?[]:e),i={role:n,content:r};return e.name!=null&&(i.name=e.name),e.additional_kwargs.function_call!=null&&(i.function_call=e.additional_kwargs.function_call),An.isInstance(e)&&e.tool_calls?.length?i.tool_calls=e.tool_calls.map(xE):(e.additional_kwargs.tool_calls!=null&&(i.tool_calls=e.additional_kwargs.tool_calls),Xt.isInstance(e)&&e.tool_call_id!=null&&(i.tool_call_id=e.tool_call_id)),e.additional_kwargs.audio&&typeof e.additional_kwargs.audio==`object`&&`id`in e.additional_kwargs.audio?[i,{role:`assistant`,audio:{id:e.additional_kwargs.audio.id}}]:i}),fJ=class extends aJ{constructor(e,t){super(iJ(e,t))}invocationParams(e,t){let n;e?.strict===void 0?this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling):n=e.strict,!(this.streaming||t?.streaming)&&e?.response_format?.type===`json_schema`&&n!==!1&&(n=!0);let r={};e?.stream_options===void 0?this.streamUsage&&(this.streaming||t?.streaming)&&(r={stream_options:{include_usage:!0}}):r={stream_options:e.stream_options};let i={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:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map(e=>this._convertChatOpenAIToolToCompletionsTool(e,{strict:n})):void 0,tool_choice:DK(e?.tool_choice),response_format:this._getResponseFormat(e?.response_format),seed:e?.seed,...r,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,verbosity:e?.verbosity??this.verbosity};e?.prediction!==void 0&&(i.prediction=e.prediction),this.service_tier!==void 0&&(i.service_tier=this.service_tier),e?.service_tier!==void 0&&(i.service_tier=e.service_tier);let a=this._getReasoningParams(e);return a!==void 0&&a.effort!==void 0&&(i.reasoning_effort=a.effort),uK(i.model)?i.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:i.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,i}async _generate(e,t,n){t.signal?.throwIfAborted();let r={},i=this.invocationParams(t),a=dJ({messages:e,model:this.model});if(i.stream){let i=this._streamResponseChunks(e,t,n),a={};for await(let e of i){e.message.response_metadata={...e.generationInfo,...e.message.response_metadata};let t=e.generationInfo?.completion??0;a[t]===void 0?a[t]=e:a[t]=a[t].concat(e)}let o=Object.entries(a).sort(([e],[t])=>parseInt(e,10)-parseInt(t,10)).map(([e,t])=>t),{functions:s,function_call:c}=this.invocationParams(t),l=await this._getEstimatedTokenCountFromPrompt(e,s,c),u=await this._getNumTokensFromGenerations(o);return r.input_tokens=l,r.output_tokens=u,r.total_tokens=l+u,{generations:o,llmOutput:{estimatedTokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}else{let e=await this.completionWithRetry({...i,stream:!1,messages:a},{signal:t?.signal,...t?.options}),{completion_tokens:n,prompt_tokens:o,total_tokens:s,prompt_tokens_details:c,completion_tokens_details:l}=e?.usage??{};n&&(r.output_tokens=(r.output_tokens??0)+n),o&&(r.input_tokens=(r.input_tokens??0)+o),s&&(r.total_tokens=(r.total_tokens??0)+s),(c?.audio_tokens!==null||c?.cached_tokens!==null)&&(r.input_token_details={...c?.audio_tokens!==null&&{audio:c?.audio_tokens},...c?.cached_tokens!==null&&{cache_read:c?.cached_tokens}}),(l?.audio_tokens!==null||l?.reasoning_tokens!==null)&&(r.output_token_details={...l?.audio_tokens!==null&&{audio:l?.audio_tokens},...l?.reasoning_tokens!==null&&{reasoning:l?.reasoning_tokens}});let u=[];for(let t of e?.choices??[]){let n={text:t.message?.content??``,message:this._convertCompletionsMessageToBaseMessage(t.message??{role:`assistant`},e)};n.generationInfo={...t.finish_reason?{finish_reason:t.finish_reason}:{},...t.logprobs?{logprobs:t.logprobs}:{}},jn(n.message)&&(n.message.usage_metadata=r),n.message=new An(Object.fromEntries(Object.entries(n.message).filter(([e])=>!e.startsWith(`lc_`)))),u.push(n)}return{generations:u,llmOutput:{tokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}}async*_streamChatModelEvents(e,t,n){let r=dJ({messages:e,model:this.model}),i={...this.invocationParams(t,{streaming:!0}),messages:r,stream:!0},a=await this.completionWithRetry(i,t),o=this.streamUsage??t.streamUsage;yield*sD(async function*(e,t){for await(let n of e){if(t?.aborted)return;yield n}}(a,t.signal),{streamUsage:o??!0,provider:this.streamEventProvider})}get streamEventProvider(){return`openai`}async*_streamResponseChunks(e,t,n){let r=dJ({messages:e,model:this.model}),i={...this.invocationParams(t,{streaming:!0}),messages:r,stream:!0},a,o=await this.completionWithRetry(i,t),s;for await(let e of o){if(t.signal?.aborted)return;let r=e?.choices?.[0];if(e.usage&&(s=e.usage),!r)continue;let{delta:i}=r;if(!i)continue;let o=this._convertCompletionsDeltaToBaseMessageChunk(i,e,a);a=i.role??a;let c={prompt:t.promptIndex??0,completion:r.index??0};if(typeof o.content!=`string`){console.log(`[WARNING]: Received non-string content from OpenAI. This is currently not supported.`);continue}let l={...c};r.finish_reason!=null&&(l.finish_reason=r.finish_reason,l.system_fingerprint=e.system_fingerprint,l.model_name=e.model,l.service_tier=e.service_tier),this.logprobs&&(l.logprobs=r.logprobs);let u=new xd({message:o,text:o.content,generationInfo:l});yield u,await n?.handleLLMNewToken(u.text??``,c,void 0,void 0,void 0,{chunk:u})}if(s){let e={...s.prompt_tokens_details?.audio_tokens!==null&&{audio:s.prompt_tokens_details?.audio_tokens},...s.prompt_tokens_details?.cached_tokens!==null&&{cache_read:s.prompt_tokens_details?.cached_tokens}},t={...s.completion_tokens_details?.audio_tokens!==null&&{audio:s.completion_tokens_details?.audio_tokens},...s.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:s.completion_tokens_details?.reasoning_tokens}},r=new xd({message:new Nn({content:``,response_metadata:{usage:{...s}},usage_metadata:{input_tokens:s.prompt_tokens,output_tokens:s.completion_tokens,total_tokens:s.total_tokens,...Object.keys(e).length>0&&{input_token_details:e},...Object.keys(t).length>0&&{output_token_details:t}}}),text:``});yield r,await n?.handleLLMNewToken(r.text??``,{prompt:0,completion:0},void 0,void 0,void 0,{chunk:r})}if(t.signal?.aborted)throw Error(`AbortError`)}async completionWithRetry(e,t){let n=this._getClientOptions(t),r=e.response_format&&e.response_format.type===`json_schema`;return this.caller.call(async()=>{try{return r&&!e.stream?await this.client.chat.completions.parse(e,n):await this.client.chat.completions.create(e,n)}catch(e){throw cK(e)}})}_convertCompletionsDeltaToBaseMessageChunk(e,t,n){return cJ({delta:e,rawResponse:t,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(e,t){return sJ({message:e,rawResponse:t,includeRawResponse:this.__includeRawResponse})}},pJ={openAIApiKey:`openai_api_key`,openAIApiVersion:`openai_api_version`,openAIBasePath:`openai_api_base`,deploymentName:`deployment_name`,azureOpenAIEndpoint:`azure_endpoint`,azureOpenAIApiVersion:`openai_api_version`,azureOpenAIBasePath:`openai_api_base`,azureOpenAIApiDeploymentName:`deployment_name`},mJ={azureOpenAIApiKey:`AZURE_OPENAI_API_KEY`},hJ=[`azureOpenAIApiKey`,`azureOpenAIApiVersion`,`azureOpenAIBasePath`,`azureOpenAIEndpoint`,`azureOpenAIApiInstanceName`,`azureOpenAIApiDeploymentName`,`deploymentName`,`openAIApiKey`,`openAIApiVersion`];function gJ(e,t){return typeof e==`string`?{model:e,deploymentName:e,azureOpenAIApiDeploymentName:e,...t??{}}:e??t}function _J(e){if(this.azureOpenAIApiKey=e?.azureOpenAIApiKey??(typeof e?.openAIApiKey==`string`?e?.openAIApiKey:void 0)??(typeof e?.apiKey==`string`?e?.apiKey:void 0)??ui(`AZURE_OPENAI_API_KEY`),this.azureOpenAIApiInstanceName=e?.azureOpenAIApiInstanceName??ui(`AZURE_OPENAI_API_INSTANCE_NAME`),this.azureOpenAIApiDeploymentName=e?.azureOpenAIApiDeploymentName??e?.deploymentName??ui(`AZURE_OPENAI_API_DEPLOYMENT_NAME`),this.azureOpenAIApiVersion=e?.azureOpenAIApiVersion??e?.openAIApiVersion??ui(`AZURE_OPENAI_API_VERSION`),this.azureOpenAIBasePath=e?.azureOpenAIBasePath??ui(`AZURE_OPENAI_BASE_PATH`),this.azureOpenAIEndpoint=e?.azureOpenAIEndpoint??ui(`AZURE_OPENAI_ENDPOINT`),this.azureADTokenProvider=e?.azureADTokenProvider,!this.azureOpenAIApiKey&&!this.apiKey&&!this.azureADTokenProvider)throw Error(`Azure OpenAI API key or Token Provider not found`)}function vJ(e){if(!this.client){let e={azureOpenAIApiDeploymentName:this.azureOpenAIApiDeploymentName,azureOpenAIApiInstanceName:this.azureOpenAIApiInstanceName,azureOpenAIApiKey:this.azureOpenAIApiKey,azureOpenAIBasePath:this.azureOpenAIBasePath,azureADTokenProvider:this.azureADTokenProvider,baseURL:this.clientConfig.baseURL,azureOpenAIEndpoint:this.azureOpenAIEndpoint},t=_K(e),{apiKey:n,...r}=this.clientConfig,i={...r,baseURL:t,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(i.apiKey=e.azureOpenAIApiKey),i.baseURL||delete i.baseURL,i.defaultHeaders=xK(i.defaultHeaders,!0,`2.0.0`),this.client=new aK({apiVersion:this.azureOpenAIApiVersion,azureADTokenProvider:this.azureADTokenProvider,deployment:this.azureOpenAIApiDeploymentName,...i})}let t={...this.clientConfig,...e};return this.azureOpenAIApiKey&&(t.headers={"api-key":this.azureOpenAIApiKey,...t.headers},t.query={"api-version":this.azureOpenAIApiVersion,...t.query}),t}function yJ(e){let t=e;function n(e){return typeof e==`object`&&!!e}if(n(t)&&n(t.kwargs)){if(delete t.kwargs.azure_openai_base_path,delete t.kwargs.azure_openai_api_deployment_name,delete t.kwargs.azure_openai_api_key,delete t.kwargs.azure_openai_api_version,delete t.kwargs.azure_open_ai_base_path,!t.kwargs.azure_endpoint&&this.azureOpenAIEndpoint&&(t.kwargs.azure_endpoint=this.azureOpenAIEndpoint),!t.kwargs.azure_endpoint&&this.azureOpenAIBasePath){let e=this.azureOpenAIBasePath.split(`/openai/deployments/`);if(e.length===2&&e[0].startsWith(`http`)){let[n]=e;t.kwargs.azure_endpoint=n}}if(!t.kwargs.azure_endpoint&&this.azureOpenAIApiInstanceName&&(t.kwargs.azure_endpoint=`https://${this.azureOpenAIApiInstanceName}.openai.azure.com/`),!t.kwargs.deployment_name&&this.azureOpenAIApiDeploymentName&&(t.kwargs.deployment_name=this.azureOpenAIApiDeploymentName),!t.kwargs.deployment_name&&this.azureOpenAIBasePath){let e=this.azureOpenAIBasePath.split(`/openai/deployments/`);if(e.length===2){let[,n]=e;t.kwargs.deployment_name=n}}t.kwargs.azure_endpoint&&t.kwargs.deployment_name&&t.kwargs.openai_api_base&&delete t.kwargs.openai_api_base,t.kwargs.azure_openai_api_instance_name&&t.kwargs.azure_endpoint&&delete t.kwargs.azure_openai_api_instance_name}return t}var bJ=class extends fJ{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,...pJ}}get lc_secrets(){return{...super.lc_secrets,...mJ}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...hJ]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=gJ(e,t);super(n),_J.call(this,n)}_getClientOptions(e){return vJ.call(this,e)}toJSON(){return yJ.call(this,super.toJSON())}},xJ=`__openai_function_call_ids__`,SJ=`__openai_custom_tool_call_ids__`;function CJ(e){return e.type===`url_citation`?{type:`citation`,source:`url_citation`,url:e.url,title:e.title,startIndex:e.start_index,endIndex:e.end_index}:e.type===`file_citation`?{type:`citation`,source:`file_citation`,title:e.filename,startIndex:e.index,file_id:e.file_id}:e.type===`container_file_citation`?{type:`citation`,source:`container_file_citation`,title:e.filename,startIndex:e.start_index,endIndex:e.end_index,file_id:e.file_id,container_id:e.container_id}:e.type===`file_path`?{type:`citation`,source:`file_path`,startIndex:e.index,file_id:e.file_id}:{type:`non_standard`,value:e}}function wJ(e){if(e.type===`url_citation`||e.type===`file_citation`||e.type===`container_file_citation`||e.type===`file_path`)return e;if(e.type===`citation`){let t=e;if(t.source===`url_citation`)return{type:`url_citation`,url:t.url??``,title:t.title??``,start_index:t.startIndex??0,end_index:t.endIndex??0};if(t.source===`file_citation`)return{type:`file_citation`,file_id:t.file_id??``,filename:t.title??``,index:t.startIndex??0};if(t.source===`container_file_citation`)return{type:`container_file_citation`,file_id:t.file_id??``,filename:t.title??``,container_id:t.container_id??``,start_index:t.startIndex??0,end_index:t.endIndex??0};if(t.source===`file_path`)return{type:`file_path`,file_id:t.file_id??``,index:t.startIndex??0}}return e.type===`non_standard`?e.value:e}var TJ=e=>{let t={...e?.input_tokens_details?.cached_tokens!=null&&{cache_read:e?.input_tokens_details?.cached_tokens}},n={...e?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:e?.output_tokens_details?.reasoning_tokens}};return{input_tokens:e?.input_tokens??0,output_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,input_token_details:t,output_token_details:n}},EJ=e=>{if(e.error){let t=Error(e.error.message);throw t.name=e.error.code,t}let t=[],n=[],r=[],i=e.output.map(e=>{if(e.type===`function_call`&&`parsed_arguments`in e){let t={...e};return delete t.parsed_arguments,t}return e}),a={model_provider:`openai`,model:e.model,created_at:e.created_at,id:e.id,incomplete_details:e.incomplete_details,metadata:e.metadata,object:e.object,output:i,status:e.status,user:e.user,service_tier:e.service_tier,model_name:e.model},o={};for(let i of e.output)if(i.type===`message`)t.push(...i.content.flatMap(e=>e.type===`output_text`?(`parsed`in e&&e.parsed!=null&&(o.parsed=e.parsed),{type:`text`,text:e.text,annotations:e.annotations.map(CJ),...i.phase===null?{}:{phase:i.phase}}):e.type===`refusal`?(o.refusal=e.refusal,[]):e));else if(i.type===`function_call`){let e={function:{name:i.name,arguments:i.arguments},id:i.call_id};try{n.push(bE(e,{returnId:!0}))}catch(t){let n;typeof t==`object`&&t&&`message`in t&&typeof t.message==`string`&&(n=t.message),r.push(SE(e,n))}o[xJ]??={},i.id&&(o[xJ][i.call_id]=i.id)}else if(i.type===`reasoning`){o.reasoning=i;let e=i.summary?.map(e=>e.text).filter(Boolean).join(``);e&&t.push({type:`reasoning`,reasoning:e})}else if(i.type===`custom_tool_call`){let e=NK(i);e?(n.push(e),o[SJ]??={},i.id&&i.call_id&&(o[SJ][i.call_id]=i.id)):r.push(SE(i,`Malformed custom tool call`))}else if(i.type===`computer_call`){let e=PK(i);e?n.push(e):r.push(SE(i,`Malformed computer call`))}else i.type===`image_generation_call`?(i.result&&t.push({type:`image`,mimeType:`image/png`,data:i.result,id:i.id,metadata:{status:i.status}}),o.tool_outputs??=[],o.tool_outputs.push(i)):(o.tool_outputs??=[],o.tool_outputs.push(i));return new An({id:e.id,content:t,tool_calls:n,invalid_tool_calls:r,usage_metadata:TJ(e.usage),additional_kwargs:o,response_metadata:a})},DJ=e=>{let t=(e.summary.length>1?e.summary.reduce((e,t)=>{let n=e[e.length-1];return n.index===t.index?n.text+=t.text:e.push(t),e},[{...e.summary[0]}]):e.summary).map(e=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==`index`)));return{...e,summary:t}},OJ=e=>{let t=[],n={},r,i=[],a={model_provider:`openai`},o={},s;if(e.type===`response.output_text.delta`)t.push({type:`text`,text:e.delta,index:e.content_index});else if(e.type===`response.output_text.annotation.added`)t.push({type:`text`,text:``,annotations:[CJ(e.annotation)],index:e.content_index});else if(e.type===`response.output_item.added`&&e.item.type===`message`){let n=`phase`in e.item?e.item.phase:void 0;n&&t.push({type:`text`,text:``,phase:n,index:0})}else if(e.type===`response.output_item.added`&&e.item.type===`function_call`)i.push({type:`tool_call_chunk`,name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),o[xJ]={[e.item.call_id]:e.item.id};else if(e.type===`response.output_item.added`&&e.item.type===`custom_tool_call`)i.push({type:`tool_call_chunk`,isCustomTool:!0,name:e.item.name,args:e.item.input,id:e.item.call_id,index:e.output_index}),o[SJ]={[e.item.call_id]:e.item.id};else if(e.type===`response.output_item.done`&&e.item.type===`computer_call`)i.push({type:`tool_call_chunk`,name:`computer_use`,args:JSON.stringify({action:e.item.action}),id:e.item.call_id,index:e.output_index}),o.tool_outputs=[e.item];else if(e.type===`response.output_item.done`&&e.item.type===`image_generation_call`)e.item.result&&t.push({type:`image`,mimeType:`image/png`,data:e.item.result,id:e.item.id,metadata:{status:e.item.status}}),o.tool_outputs=[e.item];else if(e.type===`response.output_item.done`&&[`web_search_call`,`file_search_call`,`code_interpreter_call`,`shell_call`,`local_shell_call`,`mcp_call`,`mcp_list_tools`,`mcp_approval_request`,`custom_tool_call`,`tool_search_call`,`tool_search_output`].includes(e.item.type))o.tool_outputs=[e.item];else if(e.type===`response.created`)s=e.response.id,a.id=e.response.id,a.model_name=e.response.model,a.model=e.response.model;else if(e.type===`response.completed`||e.type===`response.incomplete`){s=e.response.id;let t=EJ(e.response);if(r=TJ(e.response.usage),e.response.text?.format?.type===`json_schema`&&t.text)try{o.parsed??=JSON.parse(t.text)}catch{}for(let[n,r]of Object.entries(e.response))n!==`id`&&(n===`output`?a[n]=t.response_metadata.output:a[n]=r)}else if(e.type===`response.function_call_arguments.delta`||e.type===`response.custom_tool_call_input.delta`)i.push({type:`tool_call_chunk`,args:e.delta,index:e.output_index,...e.type===`response.custom_tool_call_input.delta`?{isCustomTool:!0}:{}});else if(e.type===`response.web_search_call.in_progress`||e.type===`response.web_search_call.searching`||e.type===`response.web_search_call.completed`||e.type===`response.file_search_call.in_progress`||e.type===`response.file_search_call.searching`||e.type===`response.file_search_call.completed`||e.type===`response.image_generation_call.in_progress`||e.type===`response.image_generation_call.generating`||e.type===`response.image_generation_call.completed`){let[,t,r]=e.type.match(/^response\.(.*)\.([^.]+)$/)??[``,``,``];n={tool_outputs:{id:e.item_id,type:t,status:r}}}else if(e.type===`response.refusal.done`)o.refusal=e.refusal;else if(e.type===`response.output_item.added`&&`item`in e&&e.item.type===`reasoning`){let n=e.item.summary?e.item.summary.map((e,t)=>({...e,index:t})):void 0;o.reasoning={id:e.item.id,type:e.item.type,...n?{summary:n}:{}};let r=e.item.summary?.map(e=>e.text).filter(Boolean).join(``);r&&t.push({type:`reasoning`,reasoning:r})}else if(e.type===`response.reasoning_summary_part.added`)o.reasoning={type:`reasoning`,summary:[{...e.part,index:e.summary_index}]},e.part.text&&t.push({type:`reasoning`,reasoning:e.part.text,index:e.summary_index});else if(e.type===`response.reasoning_summary_text.delta`)o.reasoning={type:`reasoning`,summary:[{text:e.delta,type:`summary_text`,index:e.summary_index}]},e.delta&&t.push({type:`reasoning`,reasoning:e.delta,index:e.summary_index});else if(e.type===`response.image_generation_call.partial_image`)return null;else return null;return new xd({text:t.map(e=>e.text).join(``),message:new Nn({id:s,content:t,tool_call_chunks:i,usage_metadata:r,additional_kwargs:o,response_metadata:a}),generationInfo:n})},kJ=e=>{let t=An.isInstance(e)&&e.response_metadata?.model_provider===`openai`;function*n(){let n=lK(()=>{try{let t=hK(e);return t===`system`||t===`developer`||t===`assistant`||t===`user`?t:`assistant`}catch{return`assistant`}}),r,i=new Set,a=new Set,o=new Map,s=new Map;function*c(){if(!r)return;let e=r.content;(typeof e==`string`&&e.length>0||Array.isArray(e)&&e.length>0)&&(yield r),r=void 0}let l=(e,t)=>{r||={type:`message`,role:n,content:[],...t?{phase:t}:{}},typeof r.content==`string`?r.content=r.content.length>0?[{type:`input_text`,text:r.content},...e]:[...e]:r.content.push(...e)},u=e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e??{})}catch{return`{}`}},d=e=>{let t=lK(()=>{let t=e.metadata?.detail;return t===`low`||t===`high`||t===`auto`?t:`auto`});if(e.fileId)return{type:`input_image`,detail:t,file_id:e.fileId};if(e.url)return{type:`input_image`,detail:t,image_url:e.url};if(e.data){let n=typeof e.data==`string`?e.data:Buffer.from(e.data).toString(`base64`);return{type:`input_image`,detail:t,image_url:`data:${e.mimeType??`image/png`};base64,${n}`}}},f=e=>{if(e.fileId){let t=fK(e);return{type:`input_file`,file_id:e.fileId,...t?{filename:t}:{}}}if(e.url){let t=fK(e);return{...t?{filename:t}:{},type:`input_file`,file_url:e.url}}if(e.data){let t=mK(e),n=typeof e.data==`string`?e.data:Buffer.from(e.data).toString(`base64`);return{type:`input_file`,file_data:`data:${e.mimeType??`application/octet-stream`};base64,${n}`,filename:t}}},p=e=>{let t=lK(()=>{if(Array.isArray(e.summary)){let t=e.summary?.map(e=>e?.text).filter(e=>typeof e==`string`)??[];if(t.length>0)return t}return e.reasoning?[e.reasoning]:[]}),n=t.length>0?t.map(e=>({type:`summary_text`,text:e})):[{type:`summary_text`,text:``}];return{type:`reasoning`,...e.id?{id:e.id}:{},summary:n}},m=e=>({type:`function_call`,name:e.name??``,call_id:e.id??``,arguments:u(e.args)}),h=e=>{let t=u(e.output),n=e.status===`success`?`completed`:e.status===`error`?`incomplete`:void 0;return{type:`function_call_output`,call_id:e.toolCallId??``,output:t,...n?{status:n}:{}}};for(let n of e.contentBlocks)if(n.type===`text`){let e=lK(()=>{if(`extras`in n&&typeof n.extras==`object`&&n.extras!==null&&`phase`in n.extras)return n.extras.phase});l([{type:`input_text`,text:n.text}],e)}else if(n.type!==`invalid_tool_call`){if(n.type===`reasoning`)yield*c(),yield p(n);else if(n.type===`tool_call`){yield*c();let e=n.id??``;e&&(i.add(e),o.delete(e)),yield m(n)}else if(n.type===`tool_call_chunk`){if(n.id){let e=o.get(n.id)??{name:n.name,args:[]};n.name&&(e.name=n.name),n.args&&e.args.push(n.args),o.set(n.id,e)}}else if(n.type===`server_tool_call`){yield*c();let e=n.id??``;e&&(a.add(e),s.delete(e)),yield m(n)}else if(n.type===`server_tool_call_chunk`){if(n.id){let e=s.get(n.id)??{name:n.name,args:[]};n.name&&(e.name=n.name),n.args&&e.args.push(n.args),s.set(n.id,e)}}else if(n.type===`server_tool_call_result`)yield*c(),yield h(n);else if(n.type!==`audio`)if(n.type===`file`){let e=f(n);e&&l([e])}else if(n.type===`image`){let e=d(n);e&&l([e])}else if(n.type===`video`){let e=f(n);e&&l([e])}else n.type===`text-plain`?n.text&&l([{type:`input_text`,text:n.text}]):n.type===`non_standard`&&t&&(yield*c(),yield n.value)}yield*c();for(let[e,t]of o){if(!e||i.has(e))continue;let n=t.args.join(``);!t.name&&!n||(yield{type:`function_call`,call_id:e,name:t.name??``,arguments:n})}for(let[e,t]of s){if(!e||a.has(e))continue;let n=t.args.join(``);!t.name&&!n||(yield{type:`function_call`,call_id:e,name:t.name??``,arguments:n})}}return Array.from(n())},AJ=({messages:e,zdrEnabled:t,model:n})=>e.flatMap(e=>{let r=e.response_metadata;if(r?.output_version===`v1`)return kJ(e);let i=e.additional_kwargs,a=hK(e);if(a===`system`&&uK(n)&&(a=`developer`),a===`function`)throw Error(`Function messages are not supported in Responses API`);if(a===`tool`){let t=e;if(i?.type===`computer_call_output`)return{type:`computer_call_output`,output:(()=>{if(typeof t.content==`string`)return{type:`input_image`,image_url:t.content};if(Array.isArray(t.content)){let e=t.content.find(e=>e.type===`input_image`);if(e)return e;let n=t.content.find(e=>e.type===`computer_screenshot`);if(n)return n;let r=t.content.find(e=>e.type===`image_url`);if(r)return{type:`input_image`,image_url:typeof r.image_url==`string`?r.image_url:r.image_url.url}}throw Error(`Invalid computer call output`)})(),call_id:t.tool_call_id};if(t.additional_kwargs?.customTool)return{type:`custom_tool_call_output`,call_id:t.tool_call_id,output:t.content};let n=Array.isArray(t.content)&&t.content.every(e=>typeof e==`object`&&!!e&&`type`in e&&(e.type===`input_file`||e.type===`input_image`||e.type===`input_text`));return{type:`function_call_output`,call_id:t.tool_call_id,id:t.id?.startsWith(`fc_`)?t.id:void 0,output:n||typeof t.content==`string`?t.content:JSON.stringify(t.content)}}if(a===`assistant`){if(!t&&r?.output!=null&&Array.isArray(r?.output)&&r?.output.length>0&&r?.output.every(e=>`type`in e))return r?.output;let n=[],a=i?.reasoning,o=!!a?.encrypted_content;if(a&&(!t||o)){let e=DJ(a);n.push(e)}let{content:s}=e;if(i?.refusal&&(typeof s==`string`&&(s=[{type:`output_text`,text:s,annotations:[]}]),s=[...s,{type:`refusal`,refusal:i.refusal}]),typeof s==`string`||s.length>0){let r={type:`message`,role:`assistant`,...e.id&&!t&&e.id.startsWith(`msg_`)?{id:e.id}:{},content:lK(()=>typeof s==`string`?s:s.flatMap(e=>{if(e.type===`text`){let t=e;return{type:`output_text`,text:t.text,annotations:(t.annotations??[]).map(wJ)}}return e.type===`output_text`||e.type===`refusal`?e:[]})),phase:lK(()=>{if(Array.isArray(s))return s.find(e=>`phase`in e&&typeof e.phase==`string`)?.phase})};n.push(r)}let c=i?.[xJ],l=i?.[SJ];An.isInstance(e)&&e.tool_calls?.length?n.push(...e.tool_calls.map(e=>IK(e,l)?{type:`custom_tool_call`,id:`call_id`in e&&typeof e.call_id==`string`?e.call_id:l?.[e.id??``]??``,call_id:e.id??``,input:e.args.input,name:e.name}:FK(e)?{type:`computer_call`,id:e.call_id,call_id:e.id??``,action:e.args.action}:{type:`function_call`,name:e.name,arguments:JSON.stringify(e.args),call_id:e.id,...t?{}:{id:c?.[e.id]}})):i?.tool_calls&&n.push(...i.tool_calls.map(e=>({type:`function_call`,name:e.function.name,call_id:e.id,arguments:e.function.arguments,...t?{}:{id:c?.[e.id]}})));let u=r?.output?.length?r?.output:i.tool_outputs,d=[`computer_call`,`mcp_call`,`code_interpreter_call`,`image_generation_call`,`shell_call`,`local_shell_call`];if(u!=null){let e=u?.filter(e=>d.includes(e.type));e.length>0&&n.push(...e)}return n}if(a===`user`||a===`system`||a===`developer`){if(typeof e.content==`string`)return{type:`message`,role:a,content:e.content};let t=[],n=e.content.flatMap(e=>{if(e.type===`mcp_approval_response`&&t.push({type:`mcp_approval_response`,approval_request_id:e.approval_request_id,approve:e.approve}),qe(e)){if(e.type===`file`){let t=fK(e);if(e.source_type===`url`)return{type:`input_file`,file_url:e.url,...t?{filename:t}:{}};if(e.source_type===`id`)return{type:`input_file`,file_id:e.id,...t?{filename:t}:{}};if(e.source_type===`base64`)return{type:`input_file`,file_data:`data:${e.mime_type??``};base64,${e.data}`,filename:mK(e)}}return tt(e,oJ)}return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`image_url`?{type:`input_image`,image_url:lK(()=>{if(typeof e.image_url==`string`)return e.image_url;if(typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url)return e.image_url.url}),detail:lK(()=>{if(typeof e.image_url==`string`)return`auto`;if(typeof e.image_url==`object`&&e.image_url!==null&&`detail`in e.image_url)return e.image_url.detail})}:e.type===`input_text`||e.type===`input_image`||e.type===`input_file`?e:[]});return n.length>0&&t.push({type:`message`,role:a,content:n}),t}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]});async function*jJ(e,t={}){let n=t.streamUsage??!0,r=t.provider??`openai`,i=new Map,a=new Map,o=0,s=!1,c,l,u,d,f=new Set,p=(e,t)=>{let n=a.get(e);if(n!==void 0)return{index:n,isNew:!1};let r=o++;return a.set(e,r),i.set(r,{...t}),{index:r,isNew:!0}},m=function*(){s||(s=!0,yield{event:`message-start`,id:c})},h=function*(e){if(f.has(e))return;let t=i.get(e);t&&(f.add(e),yield{event:`content-block-finish`,index:e,content:$E(t)})};for await(let t of e){if(t.type===`response.created`){c=t.response.id,yield*m(),yield{event:`provider`,provider:r,name:`response.created`,payload:{model:t.response.model,id:t.response.id}};continue}if(t.type===`response.output_text.delta`){yield*m();let{index:e,isNew:n}=p(`text:${t.output_index}:${t.content_index}`,{type:`text`,text:``});n&&(yield{event:`content-block-start`,index:e,content:{type:`text`,text:``}});let r=i.get(e);r.text=(r.text??``)+t.delta,yield{event:`content-block-delta`,index:e,delta:{type:`text-delta`,text:t.delta}};continue}if(t.type===`response.reasoning_summary_text.delta`){yield*m();let{index:e,isNew:n}=p(`reasoning:${t.output_index}:${t.summary_index}`,{type:`reasoning`,reasoning:``});n&&(yield{event:`content-block-start`,index:e,content:{type:`reasoning`,reasoning:``}});let r=i.get(e);r.reasoning=(r.reasoning??``)+t.delta,yield{event:`content-block-delta`,index:e,delta:{type:`reasoning-delta`,reasoning:t.delta}};continue}if(t.type===`response.output_item.added`&&(t.item.type===`function_call`||t.item.type===`custom_tool_call`)){yield*m();let e=`tool:${t.output_index}`,n=t.item.type===`custom_tool_call`,r=t.item.type===`function_call`?t.item.arguments??``:t.item.input??``,{index:a,isNew:o}=p(e,{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:r,index:t.output_index,...n?{isCustomTool:!0}:{}});if(o&&(yield{event:`content-block-start`,index:a,content:{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:r,index:t.output_index}}),r){let e=i.get(a);yield{event:`content-block-delta`,index:a,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,...e.id==null?{}:{id:e.id},...e.name==null?{}:{name:e.name},args:e.args}}}}continue}if(t.type===`response.function_call_arguments.delta`||t.type===`response.custom_tool_call_input.delta`){yield*m();let{index:e,isNew:n}=p(`tool:${t.output_index}`,{type:`tool_call_chunk`,args:``,index:t.output_index,...t.type===`response.custom_tool_call_input.delta`?{isCustomTool:!0}:{}});n&&(yield{event:`content-block-start`,index:e,content:{type:`tool_call_chunk`,args:``,index:t.output_index}});let r=i.get(e);r.args=(r.args??``)+t.delta,yield{event:`content-block-delta`,index:e,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,...r.id==null?{}:{id:r.id},...r.name==null?{}:{name:r.name},args:r.args}}};continue}if(t.type===`response.output_item.done`&&(t.item.type===`function_call`||t.item.type===`custom_tool_call`)){yield*m();let e=`tool:${t.output_index}`,n=t.item.type===`function_call`?t.item.arguments??``:t.item.input??``,{index:r,isNew:a}=p(e,{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:n,index:t.output_index});if(a)yield{event:`content-block-start`,index:r,content:{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:n,index:t.output_index}};else{let e=i.get(r);e.args=n,e.id=t.item.call_id,e.name=t.item.name}yield*h(r);continue}if(t.type===`response.completed`||t.type===`response.incomplete`){yield*m(),c=t.response.id,u=MJ(t.response.status,t.type),d={model_provider:r,id:t.response.id,model:t.response.model,status:t.response.status},n&&t.response.usage&&(l=TJ(t.response.usage),yield{event:`usage`,usage:l});continue}t.type!==`response.image_generation_call.partial_image`&&(yield*m(),yield{event:`provider`,provider:r,name:t.type,payload:t})}s||(yield{event:`message-start`});for(let[e]of i)f.has(e)||(yield*h(e));yield{event:`message-finish`,reason:u,...l?{usage:l}:{},...d?{responseMetadata:d}:{}}}function MJ(e,t){return t===`response.incomplete`?`length`:e===`completed`?`stop`:e===`incomplete`?`length`:`stop`}var NJ=class extends aJ{constructor(e,t){super(iJ(e,t))}invocationParams(e){let t;e?.strict!==void 0&&(t=e.strict),t===void 0&&this.supportsStrictToolCalling!==void 0&&(t=this.supportsStrictToolCalling);let n={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?this._reduceChatOpenAITools(e.tools,{stream:this.streaming,strict:t}):void 0,tool_choice:AK(e?.tool_choice)?e?.tool_choice:(()=>{let t=DK(e?.tool_choice);if(typeof t==`object`&&`type`in t){if(t.type===`function`)return{type:`function`,name:t.function.name};if(t.type===`allowed_tools`)return{type:`allowed_tools`,mode:t.allowed_tools.mode,tools:t.allowed_tools.tools};if(t.type===`custom`)return{type:`custom`,name:t.custom.name}}})(),text:(()=>{if(e?.text)return e.text;let t=this._getResponseFormat(e?.response_format);return t?.type===`json_schema`?t.json_schema.schema==null?void 0:{format:{type:`json_schema`,schema:t.json_schema.schema,description:t.json_schema.description,name:t.json_schema.name,strict:t.json_schema.strict},verbosity:e?.verbosity}:{format:t,verbosity:e?.verbosity}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},r=this._getReasoningParams(e);return r!==void 0&&(n.reasoning=r),n}async _generate(e,t,n){t.signal?.throwIfAborted();let r=this.invocationParams(t);if(r.stream){let r=this._streamResponseChunks(e,t,n),i;for await(let e of r)e.message.response_metadata={...e.generationInfo,...e.message.response_metadata},i=i?.concat(e)??e;return{generations:i?[i]:[],llmOutput:{estimatedTokenUsage:i?.message?.usage_metadata}}}else{let n=await this.completionWithRetry({input:AJ({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...r,stream:!1},{signal:t?.signal,...t?.options});return{generations:[{text:n.output_text,message:EJ(n)}],llmOutput:{id:n.id,estimatedTokenUsage:n.usage?{promptTokens:n.usage.input_tokens,completionTokens:n.usage.output_tokens,totalTokens:n.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(e,t,n){let r=await this.completionWithRetry({...this.invocationParams(t),input:AJ({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},t),i=this.streamUsage??t.streamUsage;yield*jJ(async function*(e,t){for await(let n of e){if(t?.aborted)return;yield n}}(r,t.signal),{streamUsage:i??!0,provider:this.streamEventProvider})}get streamEventProvider(){return`openai`}async*_streamResponseChunks(e,t,n){let r=await this.completionWithRetry({...this.invocationParams(t),input:AJ({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},t);try{for await(let e of r){if(t.signal?.aborted)return;let r=OJ(e);r!=null&&(yield r,await n?.handleLLMNewToken(r.text||``,{prompt:t.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:r}))}}catch(e){throw cK(e)}}async completionWithRetry(e,t){return this.caller.call(async()=>{let n=this._getClientOptions(t);try{return e.text?.format?.type===`json_schema`&&!e.stream?await this.client.responses.parse(e,n):await this.client.responses.create(e,n)}catch(e){throw cK(e)}})}_reduceChatOpenAITools(e,t){let n=[];for(let r of e)if(OK(r))r.type===`image_generation`&&t?.stream&&(r.partial_images=1),n.push(r);else if(jK(r)){let e=r.metadata.customTool;n.push({type:`custom`,name:e.name,description:e.description,format:e.format})}else if(UT(r)){let e={};for(let[t,n]of Object.entries(r))t!==`type`&&t!==`function`&&(e[t]=n);n.push({type:`function`,name:r.function.name,parameters:r.function.parameters,description:r.function.description,strict:t?.strict??null,...e})}else MK(r)&&n.push(LK(r));return n}},PJ=class extends NJ{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,...pJ}}get lc_secrets(){return{...super.lc_secrets,...mJ}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...hJ]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=gJ(e,t);super(n),_J.call(this,n)}_getClientOptions(e){return vJ.call(this,e)}toJSON(){return yJ.call(this,super.toJSON())}},FJ=class e extends aJ{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,`useResponsesApi`]}get callKeys(){return[...super.callKeys,`useResponsesApi`]}fields;constructor(e,t){let n=iJ(e,t);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new NJ(n),this.completions=n?.completions??new fJ(n)}_useResponsesApi(e){let t=e?.tools?.some(OK),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,r=e?.tools?.some(MK)||e?.tools?.some(jK);return this.useResponsesApi||t||n||r||gK(this.model)}getLsParams(e){let t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(t):this.completions.getLsParams(t)}invocationParams(e){let t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(t):this.completions.invocationParams(t)}async _generate(e,t,n){return this._useResponsesApi(t)?this.responses._generate(e,t,n):this.completions._generate(e,t,n)}async*_streamChatModelEvents(e,t,n){if(this._useResponsesApi(t)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(t),n);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(t),n)}async*_streamResponseChunks(e,t,n){if(this._useResponsesApi(t)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(t),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(t),n)}withConfig(t){let n=new e(this.fields);return n.defaultOptions={...this.defaultOptions,...t},n}},IJ=class extends FJ{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,...pJ}}get lc_secrets(){return{...super.lc_secrets,...mJ}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...hJ]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=gJ(e,t);super({...n,completions:new bJ(n),responses:new PJ(n)}),_J.call(this,n)}_getStructuredOutputMethod(e){let t={...e};return this.model.startsWith(`gpt-4o`)&&t?.method===void 0?`functionCalling`:super._getStructuredOutputMethod(t)}toJSON(){return yJ.call(this,super.toJSON())}};V({action:lj([V({type:xj(`screenshot`)}),V({type:xj(`click`),x:JA(),y:JA(),button:yj([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),V({type:xj(`double_click`),x:JA(),y:JA(),button:yj([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),V({type:xj(`drag`),path:oj(V({x:JA(),y:JA()}))}),V({type:xj(`keypress`),keys:oj(B())}),V({type:xj(`move`),x:JA(),y:JA()}),V({type:xj(`scroll`),x:JA(),y:JA(),scroll_x:JA(),scroll_y:JA()}),V({type:xj(`type`),text:B()}),V({type:xj(`wait`),duration:JA().optional()})])}),lj([V({type:xj(`exec`),command:oj(B()),env:_j(B(),B()).optional(),working_directory:B().optional(),timeout_ms:JA().optional(),user:B().optional()})]),V({commands:oj(B()).describe(`Array of shell commands to execute`),timeout_ms:JA().optional().describe(`Optional timeout in milliseconds for the commands`),max_output_length:JA().optional().describe(`Optional maximum number of characters to return from each command`)}),lj([V({type:xj(`create_file`),path:B(),diff:B()}),V({type:xj(`update_file`),path:B(),diff:B()}),V({type:xj(`delete_file`),path:B()})]);function LJ(e){if(typeof e==`object`&&e){let t={...e};`additionalProperties`in t&&delete t.additionalProperties,`$schema`in t&&delete t.$schema,`strict`in t&&delete t.strict;for(let e in t)e in t&&(Array.isArray(t[e])?t[e]=t[e].map(LJ):typeof t[e]==`object`&&t[e]!==null&&(t[e]=LJ(t[e])));return t}return e}function RJ(e){let{$schema:t,...n}=LJ(N_(e)||Zb(e)?Rx(e):e);return n}function zJ(e){let{$schema:t,...n}=LJ(e);return n}function BJ(e,t,n=[]){if(typeof e!=`object`||!e)return;let r=e;if(Array.isArray(r.enum)&&r.enum.some(e=>e===``)){let e=n.length?` at path "${n.join(`.`)}"`:``,r=t?` in tool "${t}"`:``;throw Error(`Invalid enum: empty string not allowed${r}${e}. Gemini API rejects empty strings in enums.`)}if(r.type===`object`&&r.properties&&typeof r.properties==`object`)for(let[e,i]of Object.entries(r.properties))BJ(i,t,[...n,e]);r.items&&BJ(r.items,t,[...n,`[]`]);for(let e of[`anyOf`,`oneOf`,`allOf`]){let i=r[e];Array.isArray(i)&&i.forEach((r,i)=>BJ(r,t,[...n,`${e}[${i}]`]))}r.additionalProperties&&typeof r.additionalProperties==`object`&&BJ(r.additionalProperties,t,[...n,`additionalProperties`])}var VJ=`__gemini_function_call_thought_signatures__`,HJ=`ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==`,UJ=e=>e();function WJ(e){return Pn.isInstance(e)?e.role:e.type}function GJ(e){switch(e){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: ${e}`)}}function KJ(e){if(`mimeType`in e&&`data`in e)return{inlineData:{mimeType:e.mimeType,data:e.data}};if(`mimeType`in e&&`fileUri`in e)return{fileData:{mimeType:e.mimeType,fileUri:e.fileUri}};throw Error(`Invalid media content`)}function qJ(e,t){return t.map(e=>jn(e)?e.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function JJ(e,t){if(`data`in e&&e.data!==void 0){let n=e.data instanceof Uint8Array?btoa(String.fromCharCode(...e.data)):e.data;return{inlineData:{mimeType:e.mimeType||t,data:n}}}if(`url`in e&&e.url!==void 0){let n=et({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mimeType||t,fileUri:e.url}}}throw`fileId`in e&&e.fileId!==void 0?Error(`ContentBlock.Multimodal fileId is not supported by Google Generative AI. Use a URL or base64 data instead.`):Error(`Invalid multimodal content block: must have "data", "url", or "fileId" property. Received: ${JSON.stringify(e)}`)}function YJ(e){return{providerName:`Google Gemini`,fromStandardTextBlock(e){return{text:e.text}},fromStandardImageBlock(t){if(!e)throw Error(`This model does not support images`);if(t.source_type===`url`){let e=et({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)},fromStandardAudioBlock(t){if(!e)throw Error(`This model does not support audio`);if(t.source_type===`url`){let e=et({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)},fromStandardFileBlock(t){if(!e)throw Error(`This model does not support files`);if(t.source_type===`text`)return{text:t.text};if(t.source_type===`url`){let e=et({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)}}}function XJ(e,t){if(qe(e))return tt(e,YJ(t));if(e.type===`text`)return{text:e.text};if(e.type===`executableCode`)return{executableCode:e.executableCode};if(e.type===`codeExecutionResult`)return{codeExecutionResult:e.codeExecutionResult};if(e.type===`image_url`){if(!t)throw Error(`This model does not support images`);let n;if(typeof e.image_url==`string`)n=e.image_url;else if(typeof e.image_url==`object`&&`url`in e.image_url)n=e.image_url.url;else throw Error(`Please provide image as base64 encoded data URL`);let[r,i]=n.split(`,`);if(!r.startsWith(`data:`))throw Error(`Please provide image as base64 encoded data URL`);let[a,o]=r.replace(/^data:/,``).split(`;`);if(o!==`base64`)throw Error(`Please provide image as base64 encoded data URL`);return{inlineData:{data:i,mimeType:a}}}else if(e.type===`media`)return KJ(e);else if(e.type===`image`)return JJ(e,`image/png`);else if(e.type===`video`)return JJ(e,`video/mp4`);else if(e.type===`audio`)return JJ(e,`audio/mpeg`);else if(e.type===`file`)return JJ(e,`application/octet-stream`);else if(e.type===`text-plain`)return`text`in e&&typeof e.text==`string`?{text:e.text}:JJ(e,`text/plain`);else if(e.type===`tool_use`)return{functionCall:{name:e.name,args:e.input}};else if(e.type===`tool_call`)return{functionCall:{name:e.name,args:e.args}};else if(e.type?.includes(`/`)&&e.type.split(`/`).length===2&&`data`in e&&typeof e.data==`string`)return{inlineData:{mimeType:e.type,data:e.data}};else if(e.type===`thinking`){let t=e;return{text:t.thinking,thought:!0,...t.signature?{thoughtSignature:t.signature}:{}}}else if(`functionCall`in e)return;else if(`type`in e)throw Error(`Unknown content type ${e.type}`);else throw Error(`Unknown content ${JSON.stringify(e)}`)}function ZJ(e,t,n,r){if($t(e)){let r=e.name??qJ(e,n);if(r===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 "${e.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);let i=Array.isArray(e.content)?e.content.map(e=>XJ(e,t)).filter(e=>e!==void 0):e.content;return e.status===`error`?[{functionResponse:{name:r,response:{error:{details:i}}}}]:[{functionResponse:{name:r,response:{result:i}}}]}let i=[],a=[];typeof e.content==`string`&&e.content&&a.push({text:e.content}),Array.isArray(e.content)&&a.push(...e.content.map(e=>XJ(e,t)).filter(e=>e!==void 0));let o=e.additional_kwargs?.[VJ];return jn(e)&&e.tool_calls?.length&&(i=e.tool_calls.map(e=>{let t=UJ(()=>{if(e.id){let t=o?.[e.id];if(t)return t}return r?.includes(`gemini-3`)?HJ:``});return{functionCall:{name:e.name,args:e.args},...t?{thoughtSignature:t}:{}}})),[...a,...i]}function QJ(e,t,n=!1,r){return e.reduce((i,a,o)=>{if(!Kt(a))throw Error(`Unsupported message input`);let s=WJ(a);if(s===`system`&&o!==0)throw Error(`System message should be the first one`);let c=GJ(s),l=i.content[i.content.length];if(!i.mergeWithPreviousContent&&l&&l.role===c)throw Error(`Google Generative AI requires alternate messages between authors`);let u=ZJ(a,t,e.slice(0,o),r);if(i.mergeWithPreviousContent){let e=i.content[i.content.length-1];if(!e)throw Error(`There was a problem parsing your system message. Please try a prompt without one.`);return e.parts.push(...u),{mergeWithPreviousContent:!1,content:i.content}}let d=c;(d===`function`||d===`system`&&!n)&&(d=`user`);let f={role:d,parts:u};return{mergeWithPreviousContent:s===`system`&&!n,content:[...i.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function $J(e,t){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};let[n]=e.candidates,{content:r,...i}=n,a=r?.parts?.reduce((e,t)=>(`functionCall`in t&&t.functionCall&&e.push({...t,id:`id`in t.functionCall&&typeof t.functionCall.id==`string`?t.functionCall.id:Yr()}),e),[]),o,s=r?.parts;o=Array.isArray(s)&&s.length===1&&`text`in s[0]&&s[0].text&&!s[0].thought?s[0].text:Array.isArray(s)&&s.length>0?s.map(e=>e.thought&&`text`in e&&e.text?{type:`thinking`,thinking:e.text,...e.thoughtSignature?{signature:e.thoughtSignature}:{}}:`text`in e?{type:`text`,text:e.text}:`inlineData`in e?{type:`inlineData`,inlineData:e.inlineData}:`functionCall`in e?{type:`functionCall`,functionCall:e.functionCall}:`functionResponse`in e?{type:`functionResponse`,functionResponse:e.functionResponse}:`fileData`in e?{type:`fileData`,fileData:e.fileData}:`executableCode`in e?{type:`executableCode`,executableCode:e.executableCode}:`codeExecutionResult`in e?{type:`codeExecutionResult`,codeExecutionResult:e.codeExecutionResult}:e):[];let c=a?.reduce((e,t)=>(`thoughtSignature`in t&&typeof t.thoughtSignature==`string`&&(e[t.id]=t.thoughtSignature),e),{}),l=``;return typeof o==`string`?l=o:Array.isArray(o)&&o.length>0&&(l=o.find(e=>`text`in e)?.text??l),{generations:[{text:l,message:new An({content:o??``,tool_calls:a?.map(e=>({type:`tool_call`,id:e.id,name:e.functionCall.name,args:e.functionCall.args})),additional_kwargs:{...i,[VJ]:c},usage_metadata:t?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:t?.usageMetadata?.input_tokens,completionTokens:t?.usageMetadata?.output_tokens,totalTokens:t?.usageMetadata?.total_tokens}}}}function eY(e,t){if(!e.candidates||e.candidates.length===0)return null;let[n]=e.candidates,{content:r,...i}=n,a=r.parts?.reduce((e,t)=>(`functionCall`in t&&t.functionCall&&e.push({...t,id:`id`in t.functionCall&&typeof t.functionCall.id==`string`?t.functionCall.id:Yr()}),e),[]),o,s=r?.parts;o=Array.isArray(s)&&s.every(e=>`text`in e&&!e.thought)?s.map(e=>e.text).join(``):Array.isArray(s)?s.map(e=>e.thought&&`text`in e&&e.text?{type:`thinking`,thinking:e.text,...e.thoughtSignature?{signature:e.thoughtSignature}:{}}:`text`in e?{type:`text`,text:e.text}:`inlineData`in e?{type:`inlineData`,inlineData:e.inlineData}:`functionCall`in e?{type:`functionCall`,functionCall:e.functionCall}:`functionResponse`in e?{type:`functionResponse`,functionResponse:e.functionResponse}:`fileData`in e?{type:`fileData`,fileData:e.fileData}:`executableCode`in e?{type:`executableCode`,executableCode:e.executableCode}:`codeExecutionResult`in e?{type:`codeExecutionResult`,codeExecutionResult:e.codeExecutionResult}:e):[];let c=``;o&&typeof o==`string`?c=o:Array.isArray(o)&&(c=o.find(e=>`text`in e)?.text??``);let l=[];a&&l.push(...a.map(e=>({type:`tool_call_chunk`,id:e.id,name:e.functionCall.name,args:JSON.stringify(e.functionCall.args)})));let u=a?.reduce((e,t)=>(`thoughtSignature`in t&&typeof t.thoughtSignature==`string`&&(e[t.id]=t.thoughtSignature),e),{});return new xd({text:c,message:new Nn({content:o||``,name:r?r.role:void 0,tool_call_chunks:l,additional_kwargs:{[VJ]:u},response_metadata:{model_provider:`google-genai`},usage_metadata:t.usageMetadata}),generationInfo:i})}function tY(e){return e.every(e=>`functionDeclarations`in e&&Array.isArray(e.functionDeclarations))?e:[{functionDeclarations:e.map(e=>{if(eA(e)){let t=RJ(e.schema);return t.type===`object`&&`properties`in t&&Object.keys(t.properties).length===0?{name:e.name,description:e.description}:(BJ(t,e.name),{name:e.name,description:e.description,parameters:t})}if(UT(e)){let t=zJ(e.function.parameters);return BJ(t,e.function.name),{name:e.function.name,description:e.function.description??`A function available to call.`,parameters:t}}return e})}]}function nY(e,t){let n={input_tokens:e?.promptTokenCount??0,output_tokens:e?.candidatesTokenCount??0,total_tokens:e?.totalTokenCount??0};if(e?.cachedContentTokenCount&&(n.input_token_details??={},n.input_token_details.cache_read=e.cachedContentTokenCount),t===`gemini-3-pro-preview`){let t=Math.max(0,e?.promptTokenCount??-2e5),r=Math.max(0,e?.cachedContentTokenCount??-2e5);t&&(n.input_token_details={...n.input_token_details,over_200k:t}),r&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:r})}return n}async function*rY(e,t={}){let n=t.streamUsage??!0,r=new Map,i=new Map,a=0,o=!1,s,c=`stop`,l=(e,t)=>{let n=i.get(e);if(n!==void 0)return{index:n,isNew:!1};let o=a++;return i.set(e,o),r.set(o,{...t}),{index:o,isNew:!0}};for await(let i of e){o||(o=!0,yield{event:`message-start`}),n&&`usageMetadata`in i&&i.usageMetadata&&(s=nY(i.usageMetadata,t.model??``),yield{event:`usage`,usage:s});let e=i.candidates?.[0];e?.finishReason&&(c=iY(e.finishReason));let a=e?.content?.parts;if(!a)continue;let u=0;for(let e of a)if(`text`in e&&e.text)if(`thought`in e&&e.thought){let{index:t,isNew:n}=l(`reasoning`,{type:`reasoning`,reasoning:``});n&&(yield{event:`content-block-start`,index:t,content:{type:`reasoning`,reasoning:``}});let i=r.get(t);i.reasoning=(i.reasoning??``)+e.text,yield{event:`content-block-delta`,index:t,delta:{type:`reasoning-delta`,reasoning:e.text}}}else{let{index:t,isNew:n}=l(`text`,{type:`text`,text:``});n&&(yield{event:`content-block-start`,index:t,content:{type:`text`,text:``}});let i=r.get(t);i.text=(i.text??``)+e.text,yield{event:`content-block-delta`,index:t,delta:{type:`text-delta`,text:e.text}}}else if(`functionCall`in e&&e.functionCall){let t=`tool:${u}`,n=JSON.stringify(e.functionCall.args??{}),{index:i,isNew:a}=l(t,{type:`tool_call_chunk`,name:e.functionCall.name,args:``,index:u});a&&(yield{event:`content-block-start`,index:i,content:{type:`tool_call_chunk`,name:e.functionCall.name,args:``,index:u}});let o=r.get(i);o.args=n,yield{event:`content-block-delta`,index:i,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,name:o.name,args:o.args}}},u+=1}}for(let[e,t]of r)yield{event:`content-block-finish`,index:e,content:$E(t)};yield{event:`message-finish`,reason:c,...s?{usage:s}:{},responseMetadata:{model_provider:`google-genai`}}}function iY(e){switch(e.toLowerCase()){case`max_tokens`:case`max-token`:case`max_token`:return`length`;case`safety`:case`recitation`:case`language`:case`blocklist`:case`prohibited_content`:case`prohibited-content`:case`spii`:case`image_safety`:case`image-safety`:case`image_prohibited_content`:case`image-prohibited-content`:case`image_recitation`:case`image-recitation`:return`content_filter`;default:return`stop`}}var aY=class extends YT{static lc_name(){return`GoogleGenerativeAIToolsOutputParser`}lc_namespace=[`langchain`,`google_genai`,`output_parsers`];returnId=!1;keyName;returnSingle=!1;zodSchema;serializableSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}async _validateResult(e){if(this.serializableSchema!==void 0){let t=await this.serializableSchema[`~standard`].validate(e);if(t.issues)throw new ZT(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.issues)}`,JSON.stringify(e,null,2));return t.value}if(this.zodSchema===void 0)return e;let t=await L_(this.zodSchema,e);if(t.success)return t.data;throw new ZT(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){let t=e.flatMap(e=>{let{message:t}=e;return!(`tool_calls`in t)||!Array.isArray(t.tool_calls)?[]:t.tool_calls});if(t[0]===void 0)throw Error(`No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.`);let[n]=t;return await this._validateResult(n.args)}},oY;(function(e){e.STRING=`string`,e.NUMBER=`number`,e.INTEGER=`integer`,e.BOOLEAN=`boolean`,e.ARRAY=`array`,e.OBJECT=`object`})(oY||={});var sY;(function(e){e.LANGUAGE_UNSPECIFIED=`language_unspecified`,e.PYTHON=`python`})(sY||={});var cY;(function(e){e.OUTCOME_UNSPECIFIED=`outcome_unspecified`,e.OUTCOME_OK=`outcome_ok`,e.OUTCOME_FAILED=`outcome_failed`,e.OUTCOME_DEADLINE_EXCEEDED=`outcome_deadline_exceeded`})(cY||={});var lY=[`user`,`model`,`function`,`system`],uY;(function(e){e.HARM_CATEGORY_UNSPECIFIED=`HARM_CATEGORY_UNSPECIFIED`,e.HARM_CATEGORY_HATE_SPEECH=`HARM_CATEGORY_HATE_SPEECH`,e.HARM_CATEGORY_SEXUALLY_EXPLICIT=`HARM_CATEGORY_SEXUALLY_EXPLICIT`,e.HARM_CATEGORY_HARASSMENT=`HARM_CATEGORY_HARASSMENT`,e.HARM_CATEGORY_DANGEROUS_CONTENT=`HARM_CATEGORY_DANGEROUS_CONTENT`,e.HARM_CATEGORY_CIVIC_INTEGRITY=`HARM_CATEGORY_CIVIC_INTEGRITY`})(uY||={});var dY;(function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED=`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,e.BLOCK_LOW_AND_ABOVE=`BLOCK_LOW_AND_ABOVE`,e.BLOCK_MEDIUM_AND_ABOVE=`BLOCK_MEDIUM_AND_ABOVE`,e.BLOCK_ONLY_HIGH=`BLOCK_ONLY_HIGH`,e.BLOCK_NONE=`BLOCK_NONE`})(dY||={});var fY;(function(e){e.HARM_PROBABILITY_UNSPECIFIED=`HARM_PROBABILITY_UNSPECIFIED`,e.NEGLIGIBLE=`NEGLIGIBLE`,e.LOW=`LOW`,e.MEDIUM=`MEDIUM`,e.HIGH=`HIGH`})(fY||={});var pY;(function(e){e.BLOCKED_REASON_UNSPECIFIED=`BLOCKED_REASON_UNSPECIFIED`,e.SAFETY=`SAFETY`,e.OTHER=`OTHER`})(pY||={});var mY;(function(e){e.FINISH_REASON_UNSPECIFIED=`FINISH_REASON_UNSPECIFIED`,e.STOP=`STOP`,e.MAX_TOKENS=`MAX_TOKENS`,e.SAFETY=`SAFETY`,e.RECITATION=`RECITATION`,e.LANGUAGE=`LANGUAGE`,e.BLOCKLIST=`BLOCKLIST`,e.PROHIBITED_CONTENT=`PROHIBITED_CONTENT`,e.SPII=`SPII`,e.MALFORMED_FUNCTION_CALL=`MALFORMED_FUNCTION_CALL`,e.OTHER=`OTHER`})(mY||={});var hY;(function(e){e.TASK_TYPE_UNSPECIFIED=`TASK_TYPE_UNSPECIFIED`,e.RETRIEVAL_QUERY=`RETRIEVAL_QUERY`,e.RETRIEVAL_DOCUMENT=`RETRIEVAL_DOCUMENT`,e.SEMANTIC_SIMILARITY=`SEMANTIC_SIMILARITY`,e.CLASSIFICATION=`CLASSIFICATION`,e.CLUSTERING=`CLUSTERING`})(hY||={});var gY;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.AUTO=`AUTO`,e.ANY=`ANY`,e.NONE=`NONE`})(gY||={});var _Y;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.MODE_DYNAMIC=`MODE_DYNAMIC`})(_Y||={});var vY=class extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}},yY=class extends vY{constructor(e,t){super(e),this.response=t}},bY=class extends vY{constructor(e,t,n,r){super(e),this.status=t,this.statusText=n,this.errorDetails=r}},xY=class extends vY{},SY=class extends vY{},CY=`https://generativelanguage.googleapis.com`,wY=`v1beta`,TY=`0.24.1`,EY=`genai-js`,DY;(function(e){e.GENERATE_CONTENT=`generateContent`,e.STREAM_GENERATE_CONTENT=`streamGenerateContent`,e.COUNT_TOKENS=`countTokens`,e.EMBED_CONTENT=`embedContent`,e.BATCH_EMBED_CONTENTS=`batchEmbedContents`})(DY||={});var OY=class{constructor(e,t,n,r,i){this.model=e,this.task=t,this.apiKey=n,this.stream=r,this.requestOptions=i}toString(){let e=this.requestOptions?.apiVersion||wY,t=`${this.requestOptions?.baseUrl||CY}/${e}/${this.model}:${this.task}`;return this.stream&&(t+=`?alt=sse`),t}};function kY(e){let t=[];return e?.apiClient&&t.push(e.apiClient),t.push(`${EY}/${TY}`),t.join(` `)}async function AY(e){let t=new Headers;t.append(`Content-Type`,`application/json`),t.append(`x-goog-api-client`,kY(e.requestOptions)),t.append(`x-goog-api-key`,e.apiKey);let n=e.requestOptions?.customHeaders;if(n){if(!(n instanceof Headers))try{n=new Headers(n)}catch(e){throw new xY(`unable to convert customHeaders value ${JSON.stringify(n)} to Headers: ${e.message}`)}for(let[e,r]of n.entries()){if(e===`x-goog-api-key`)throw new xY(`Cannot set reserved header name ${e}`);if(e===`x-goog-api-client`)throw new xY(`Header name ${e} can only be set using the apiClient field`);t.append(e,r)}}return t}async function jY(e,t,n,r,i,a){let o=new OY(e,t,n,r,a);return{url:o.toString(),fetchOptions:Object.assign(Object.assign({},IY(a)),{method:`POST`,headers:await AY(o),body:i})}}async function MY(e,t,n,r,i,a={},o=fetch){let{url:s,fetchOptions:c}=await jY(e,t,n,r,i,a);return NY(s,c,o)}async function NY(e,t,n=fetch){let r;try{r=await n(e,t)}catch(t){PY(t,e)}return r.ok||await FY(r,e),r}function PY(e,t){let n=e;throw n.name===`AbortError`?(n=new SY(`Request aborted when fetching ${t.toString()}: ${e.message}`),n.stack=e.stack):e instanceof bY||e instanceof xY||(n=new vY(`Error fetching from ${t.toString()}: ${e.message}`),n.stack=e.stack),n}async function FY(e,t){let n=``,r;try{let t=await e.json();n=t.error.message,t.error.details&&(n+=` ${JSON.stringify(t.error.details)}`,r=t.error.details)}catch{}throw new bY(`Error fetching from ${t.toString()}: [${e.status} ${e.statusText}] ${n}`,e.status,e.statusText,r)}function IY(e){let t={};if(e?.signal!==void 0||e?.timeout>=0){let n=new AbortController;e?.timeout>=0&&setTimeout(()=>n.abort(),e.timeout),e?.signal&&e.signal.addEventListener(`abort`,()=>{n.abort()}),t.signal=n.signal}return t}function LY(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),VY(e.candidates[0]))throw new yY(`${HY(e)}`,e);return RY(e)}else if(e.promptFeedback)throw new yY(`Text not available. ${HY(e)}`,e);return``},e.functionCall=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),VY(e.candidates[0]))throw new yY(`${HY(e)}`,e);return console.warn(`response.functionCall() is deprecated. Use response.functionCalls() instead.`),zY(e)[0]}else if(e.promptFeedback)throw new yY(`Function call not available. ${HY(e)}`,e)},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),VY(e.candidates[0]))throw new yY(`${HY(e)}`,e);return zY(e)}else if(e.promptFeedback)throw new yY(`Function call not available. ${HY(e)}`,e)},e}function RY(e){let t=[];if(e.candidates?.[0].content?.parts)for(let n of e.candidates?.[0].content?.parts)n.text&&t.push(n.text),n.executableCode&&t.push("\n```"+n.executableCode.language+`
|
|
212
|
+
`+n.executableCode.code+"\n```\n"),n.codeExecutionResult&&t.push("\n```\n"+n.codeExecutionResult.output+"\n```\n");return t.length>0?t.join(``):``}function zY(e){let t=[];if(e.candidates?.[0].content?.parts)for(let n of e.candidates?.[0].content?.parts)n.functionCall&&t.push(n.functionCall);if(t.length>0)return t}var BY=[mY.RECITATION,mY.SAFETY,mY.LANGUAGE];function VY(e){return!!e.finishReason&&BY.includes(e.finishReason)}function HY(e){let t=``;if((!e.candidates||e.candidates.length===0)&&e.promptFeedback)t+=`Response was blocked`,e.promptFeedback?.blockReason&&(t+=` due to ${e.promptFeedback.blockReason}`),e.promptFeedback?.blockReasonMessage&&(t+=`: ${e.promptFeedback.blockReasonMessage}`);else if(e.candidates?.[0]){let n=e.candidates[0];VY(n)&&(t+=`Candidate was blocked due to ${n.finishReason}`,n.finishMessage&&(t+=`: ${n.finishMessage}`))}return t}function UY(e){return this instanceof UY?(this.v=e,this):new UY(e)}function WY(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i={},o(`next`),o(`throw`),o(`return`),i[Symbol.asyncIterator]=function(){return this},i;function o(e){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||s(e,t)})})}function s(e,t){try{c(r[e](t))}catch(e){d(a[0][3],e)}}function c(e){e.value instanceof UY?Promise.resolve(e.value.v).then(l,u):d(a[0][2],e)}function l(e){s(`next`,e)}function u(e){s(`throw`,e)}function d(e,t){e(t),a.shift(),a.length&&s(a[0][0],a[0][1])}}var GY=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function KY(e){let[t,n]=YY(e.body.pipeThrough(new TextDecoderStream(`utf8`,{fatal:!0}))).tee();return{stream:JY(t),response:qY(n)}}async function qY(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)return LY(XY(t));t.push(r)}}function JY(e){return WY(this,arguments,function*(){let t=e.getReader();for(;;){let{value:e,done:n}=yield UY(t.read());if(n)break;yield yield UY(LY(e))}})}function YY(e){let t=e.getReader();return new ReadableStream({start(e){let n=``;return r();function r(){return t.read().then(({value:t,done:i})=>{if(i){if(n.trim()){e.error(new vY(`Failed to parse stream`));return}e.close();return}n+=t;let a=n.match(GY),o;for(;a;){try{o=JSON.parse(a[1])}catch{e.error(new vY(`Error parsing JSON response: "${a[1]}"`));return}e.enqueue(o),n=n.substring(a[0].length),a=n.match(GY)}return r()}).catch(e=>{let t=e;throw t.stack=e.stack,t=t.name===`AbortError`?new SY(`Request aborted when reading from the stream`):new vY(`Error reading from the stream`),t})}}})}function XY(e){let t={promptFeedback:e[e.length-1]?.promptFeedback};for(let n of e){if(n.candidates){let e=0;for(let r of n.candidates)if(t.candidates||=[],t.candidates[e]||(t.candidates[e]={index:e}),t.candidates[e].citationMetadata=r.citationMetadata,t.candidates[e].groundingMetadata=r.groundingMetadata,t.candidates[e].finishReason=r.finishReason,t.candidates[e].finishMessage=r.finishMessage,t.candidates[e].safetyRatings=r.safetyRatings,r.content&&r.content.parts){t.candidates[e].content||(t.candidates[e].content={role:r.content.role||`user`,parts:[]});let n={};for(let i of r.content.parts)i.text&&(n.text=i.text),i.functionCall&&(n.functionCall=i.functionCall),i.executableCode&&(n.executableCode=i.executableCode),i.codeExecutionResult&&(n.codeExecutionResult=i.codeExecutionResult),Object.keys(n).length===0&&(n.text=``),t.candidates[e].content.parts.push(n)}e++}n.usageMetadata&&(t.usageMetadata=n.usageMetadata)}return t}async function ZY(e,t,n,r){return KY(await MY(t,DY.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(n),r))}async function QY(e,t,n,r){return{response:LY(await(await MY(t,DY.GENERATE_CONTENT,e,!1,JSON.stringify(n),r)).json())}}function $Y(e){if(e!=null){if(typeof e==`string`)return{role:`system`,parts:[{text:e}]};if(e.text)return{role:`system`,parts:[e]};if(e.parts)return e.role?e:{role:`system`,parts:e.parts}}}function eX(e){let t=[];if(typeof e==`string`)t=[{text:e}];else for(let n of e)typeof n==`string`?t.push({text:n}):t.push(n);return tX(t)}function tX(e){let t={role:`user`,parts:[]},n={role:`function`,parts:[]},r=!1,i=!1;for(let a of e)`functionResponse`in a?(n.parts.push(a),i=!0):(t.parts.push(a),r=!0);if(r&&i)throw new vY(`Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.`);if(!r&&!i)throw new vY(`No content is provided for sending chat message.`);return r?t:n}function nX(e,t){let n={model:t?.model,generationConfig:t?.generationConfig,safetySettings:t?.safetySettings,tools:t?.tools,toolConfig:t?.toolConfig,systemInstruction:t?.systemInstruction,cachedContent:t?.cachedContent?.name,contents:[]},r=e.generateContentRequest!=null;if(e.contents){if(r)throw new xY(`CountTokensRequest must have one of contents or generateContentRequest, not both.`);n.contents=e.contents}else if(r)n=Object.assign(Object.assign({},n),e.generateContentRequest);else{let t=eX(e);n.contents=[t]}return{generateContentRequest:n}}function rX(e){let t;return t=e.contents?e:{contents:[eX(e)]},e.systemInstruction&&(t.systemInstruction=$Y(e.systemInstruction)),t}function iX(e){return typeof e==`string`||Array.isArray(e)?{content:eX(e)}:e}var aX=[`text`,`inlineData`,`functionCall`,`functionResponse`,`executableCode`,`codeExecutionResult`],oX={user:[`text`,`inlineData`],function:[`functionResponse`],model:[`text`,`functionCall`,`executableCode`,`codeExecutionResult`],system:[`text`]};function sX(e){let t=!1;for(let n of e){let{role:e,parts:r}=n;if(!t&&e!==`user`)throw new vY(`First content should be with role 'user', got ${e}`);if(!lY.includes(e))throw new vY(`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(lY)}`);if(!Array.isArray(r))throw new vY(`Content should have 'parts' property with an array of Parts`);if(r.length===0)throw new vY(`Each Content should have at least one part`);let i={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(let e of r)for(let t of aX)t in e&&(i[t]+=1);let a=oX[e];for(let t of aX)if(!a.includes(t)&&i[t]>0)throw new vY(`Content with role '${e}' can't contain '${t}' part`);t=!0}}function cX(e){if(e.candidates===void 0||e.candidates.length===0)return!1;let t=e.candidates[0]?.content;if(t===void 0||t.parts===void 0||t.parts.length===0)return!1;for(let e of t.parts)if(e===void 0||Object.keys(e).length===0||e.text!==void 0&&e.text===``)return!1;return!0}var lX=`SILENT_ERROR`,uX=class{constructor(e,t,n,r={}){this.model=t,this.params=n,this._requestOptions=r,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,n?.history&&(sX(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,t={}){await this._sendPromise;let n=eX(e),r={safetySettings:this.params?.safetySettings,generationConfig:this.params?.generationConfig,tools:this.params?.tools,toolConfig:this.params?.toolConfig,systemInstruction:this.params?.systemInstruction,cachedContent:this.params?.cachedContent,contents:[...this._history,n]},i=Object.assign(Object.assign({},this._requestOptions),t),a;return this._sendPromise=this._sendPromise.then(()=>QY(this._apiKey,this.model,r,i)).then(e=>{if(cX(e.response)){this._history.push(n);let t=Object.assign({parts:[],role:`model`},e.response.candidates?.[0].content);this._history.push(t)}else{let t=HY(e.response);t&&console.warn(`sendMessage() was unsuccessful. ${t}. Inspect response object for details.`)}a=e}).catch(e=>{throw this._sendPromise=Promise.resolve(),e}),await this._sendPromise,a}async sendMessageStream(e,t={}){await this._sendPromise;let n=eX(e),r={safetySettings:this.params?.safetySettings,generationConfig:this.params?.generationConfig,tools:this.params?.tools,toolConfig:this.params?.toolConfig,systemInstruction:this.params?.systemInstruction,cachedContent:this.params?.cachedContent,contents:[...this._history,n]},i=Object.assign(Object.assign({},this._requestOptions),t),a=ZY(this._apiKey,this.model,r,i);return this._sendPromise=this._sendPromise.then(()=>a).catch(e=>{throw Error(lX)}).then(e=>e.response).then(e=>{if(cX(e)){this._history.push(n);let t=Object.assign({},e.candidates[0].content);t.role||=`model`,this._history.push(t)}else{let t=HY(e);t&&console.warn(`sendMessageStream() was unsuccessful. ${t}. Inspect response object for details.`)}}).catch(e=>{e.message!==lX&&console.error(e)}),a}};async function dX(e,t,n,r){return(await MY(t,DY.COUNT_TOKENS,e,!1,JSON.stringify(n),r)).json()}async function fX(e,t,n,r){return(await MY(t,DY.EMBED_CONTENT,e,!1,JSON.stringify(n),r)).json()}async function pX(e,t,n,r){let i=n.requests.map(e=>Object.assign(Object.assign({},e),{model:t}));return(await MY(t,DY.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:i}),r)).json()}var mX=class{constructor(e,t,n={}){this.apiKey=e,this._requestOptions=n,t.model.includes(`/`)?this.model=t.model:this.model=`models/${t.model}`,this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=$Y(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(e,t={}){let n=rX(e),r=Object.assign(Object.assign({},this._requestOptions),t);return QY(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},n),r)}async generateContentStream(e,t={}){let n=rX(e),r=Object.assign(Object.assign({},this._requestOptions),t);return ZY(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},n),r)}startChat(e){return new uX(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},e),this._requestOptions)}async countTokens(e,t={}){let n=nX(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),r=Object.assign(Object.assign({},this._requestOptions),t);return dX(this.apiKey,this.model,n,r)}async embedContent(e,t={}){let n=iX(e),r=Object.assign(Object.assign({},this._requestOptions),t);return fX(this.apiKey,this.model,n,r)}async batchEmbedContents(e,t={}){let n=Object.assign(Object.assign({},this._requestOptions),t);return pX(this.apiKey,this.model,e,n)}},hX=class{constructor(e){this.apiKey=e}getGenerativeModel(e,t){if(!e.model)throw new vY(`Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })`);return new mX(this.apiKey,e,t)}getGenerativeModelFromCachedContent(e,t,n){if(!e.name)throw new xY("Cached content must contain a `name` field.");if(!e.model)throw new xY("Cached content must contain a `model` field.");for(let n of[`model`,`systemInstruction`])if(t?.[n]&&e[n]&&t?.[n]!==e[n]){if(n===`model`&&(t.model.startsWith(`models/`)?t.model.replace(`models/`,``):t.model)===(e.model.startsWith(`models/`)?e.model.replace(`models/`,``):e.model))continue;throw new xY(`Different value for "${n}" specified in modelParams (${t[n]}) and cachedContent (${e[n]})`)}let r=Object.assign(Object.assign({},t),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new mX(this.apiKey,r,n)}};function gX(e,t){let n=_X(e);return{tools:n,toolConfig:yX(n,t)}}function _X(e){let t=[],n=[];return e.forEach(e=>{if(eA(e)){let[n]=tY([e]);n.functionDeclarations&&t.push(...n.functionDeclarations)}else if(UT(e)){let{functionDeclarations:n}=vX(e);if(n)t.push(...n);else throw Error(`Failed to convert OpenAI structured tool to GenerativeAI tool`)}else n.push(e)}),n.find(e=>`functionDeclarations`in e)?n.map(e=>{if(t?.length>0&&`functionDeclarations`in e){let n={functionDeclarations:[...e.functionDeclarations||[],...t]};return t=[],n}return e}):[...n,...t.length>0?[{functionDeclarations:t}]:[]]}function vX(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:LJ(e.function.parameters)}]}}function yX(e,t){if(!e.length||!t)return;let{toolChoice:n,allowedFunctionNames:r}=t,i={any:gY.ANY,auto:gY.AUTO,none:gY.NONE};if(n&&[`any`,`auto`,`none`].includes(n))return{functionCallingConfig:{mode:i[n]??`MODE_UNSPECIFIED`,allowedFunctionNames:r}};if(typeof n==`string`||r)return{functionCallingConfig:{mode:gY.ANY,allowedFunctionNames:[...r??[],...n&&typeof n==`string`?[n]:[]]}}}var bX={"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:128e3,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8e3,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:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,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:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,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:64e3,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}},xX=class extends iD{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(e,t){let n=typeof e==`string`?{...t??{},model:e}:e;if(super(n),this._addVersion(`@langchain/google-genai`,`2.2.0`),this.model=n.model.replace(/^models\//,``),this.maxOutputTokens=n.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw Error("`maxOutputTokens` must be a positive integer");if(this.temperature=n.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=n.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=n.topK??this.topK,this.topK&&this.topK<0)throw Error("`topK` must be a positive integer");if(this.stopSequences=n.stopSequences??this.stopSequences,this.apiKey=n.apiKey??ui(`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=n.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(e=>e.category)).size!==this.safetySettings.length)throw Error("The categories in `safetySettings` array must be unique");this.streaming=n.streaming??this.streaming,this.json=n.json,this.thinkingConfig=n.thinkingConfig??this.thinkingConfig,this.client=new hX(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:n.apiVersion,baseUrl:n.baseUrl,customHeaders:n.customHeaders}),this.streamUsage=n.streamUsage??this.streamUsage}useCachedContent(e,t,n){this.apiKey&&(this.client=new hX(this.apiKey).getGenerativeModelFromCachedContent(e,t,n))}get useSystemInstruction(){return typeof this.convertSystemMessageToHumanContent==`boolean`?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return this.model!==`gemini-1.0-pro-001`&&!this.model.startsWith(`gemini-pro-vision`)&&!this.model.startsWith(`gemini-1.0-pro-vision`)&&this.model!==`gemini-pro`}getLsParams(e){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:e.stop}}_combineLLMOutput(){return[]}_llmType(){return`googlegenerativeai`}bindTools(e,t){return this.withConfig({tools:gX(e)?.tools,...t})}invocationParams(e){let t=e?.tools?.length?gX(e.tools,{toolChoice:e.tool_choice,allowedFunctionNames:e.allowedFunctionNames}):void 0;return{...t?.tools?{tools:t.tools}:{},...t?.toolConfig?{toolConfig:t.toolConfig}:{},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}:{},...e?.responseSchema?{responseSchema:e.responseSchema,responseMimeType:`application/json`}:{}}}}_buildGenerateContentRequest(e,t){let n=QJ(e,this._isMultimodalModel,this.useSystemInstruction,this.model),r=n,i;return n[0]?.role===`system`&&([i,...r]=n),{...this.invocationParams(t),...i?{systemInstruction:i}:{},contents:r}}async _generate(e,t,n){if(t.signal?.throwIfAborted(),this.streaming){let r={},i=this._streamResponseChunks(e,t,n),a=[];for await(let e of i){let t=e.generationInfo?.completion??0;a[t]===void 0?a[t]=e:a[t]=a[t].concat(e)}return{generations:a.filter(e=>e!==void 0),llmOutput:{estimatedTokenUsage:r}}}let r=await this.completionWithRetry(this._buildGenerateContentRequest(e,t)),i;`usageMetadata`in r.response&&(i=nY(r.response.usageMetadata,this.model));let a=$J(r.response,{usageMetadata:i});return a.generations?.length>0&&await n?.handleLLMNewToken(a.generations[0]?.text??``),a}async*_streamChatModelEvents(e,t,n){let r=this._buildGenerateContentRequest(e,t),i=await this.caller.callWithOptions({signal:t?.signal},async()=>{let{stream:e}=await this.client.generateContentStream(r,{signal:t?.signal});return e}),a=this.streamUsage!==!1&&t.streamUsage!==!1;yield*rY(async function*(e,t){for await(let n of e){if(t?.aborted)return;yield n}}(i,t.signal),{streamUsage:a,model:this.model})}async*_streamResponseChunks(e,t,n){let r=this._buildGenerateContentRequest(e,t),i=await this.caller.callWithOptions({signal:t?.signal},async()=>{let{stream:e}=await this.client.generateContentStream(r,{signal:t?.signal});return e}),a,o=0,s=0,c=0,l=0;for await(let e of i){if(t.signal?.aborted)return;if(`usageMetadata`in e&&e.usageMetadata!==void 0&&this.streamUsage!==!1&&t.streamUsage!==!1){a=nY(e.usageMetadata,this.model);let t=e.usageMetadata.promptTokenCount??0;a.input_tokens=Math.max(0,t-o),o=t;let n=e.usageMetadata.candidatesTokenCount??0;a.output_tokens=Math.max(0,n-s),s=n;let r=e.usageMetadata.totalTokenCount??0;a.total_tokens=Math.max(0,r-c),c=r}let r=eY(e,{usageMetadata:a,index:l});l+=1,r&&(yield r,await n?.handleLLMNewToken(r.text??``))}}async completionWithRetry(e,t){return this.caller.callWithOptions({signal:t?.signal},async()=>{try{return await this.client.generateContent(e,{signal:t?.signal})}catch(e){throw e.message?.includes(`400 Bad Request`)&&(e.status=400),e}})}get profile(){return bX[this.model]??{}}withStructuredOutput(e,t){let n=e,r=t?.name,i=t?.method,a=t?.includeRaw;if(i===`jsonMode`)throw Error(`ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.`);let o,s;if(i===`functionCalling`){let e=r??`extract`,t;if(N_(n)||Zb(n)){let r=RJ(n);t={name:e,description:r.description??`A function available to call.`,parameters:r}}else typeof n.name==`string`&&typeof n.parameters==`object`&&n.parameters!=null?(t=n,t.parameters=LJ(n.parameters),e=n.name):t={name:e,description:n.description??``,parameters:LJ(n)};let i=[{functionDeclarations:[t]}];o=this.bindTools(i).withConfig({allowedFunctionNames:[e]}),s=DE(n,e,aY)}else{let e=RJ(n);o=this.withConfig({responseSchema:e}),s=EE(n)}return OE(o,s,a,a?`StructuredOutputRunnable`:`ChatGoogleGenerativeAIStructuredOutput`)}},SX=class extends YT{static lc_name(){return`AnthropicToolsOutputParser`}lc_namespace=[`langchain`,`anthropic`,`output_parsers`];returnId=!1;keyName;returnSingle=!1;zodSchema;serializableSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}async _validateResult(e){let t=e;if(typeof e==`string`)try{t=JSON.parse(e)}catch(t){throw new ZT(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.message)}`,e)}else t=e;if(this.serializableSchema!==void 0){let e=await this.serializableSchema[`~standard`].validate(t);if(e.issues)throw new ZT(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(e.issues)}`,JSON.stringify(t,null,2));return e.value}if(this.zodSchema===void 0)return t;let n=await L_(this.zodSchema,t);if(n.success)return n.data;throw new ZT(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(e){let t=e.flatMap(e=>{let{message:t}=e;return Array.isArray(t.content)?CX(t.content)[0]:[]});if(t[0]===void 0)throw Error(`No parseable tool calls provided to AnthropicToolsOutputParser.`);let[n]=t;return await this._validateResult(n.args)}};function CX(e){let t=[];for(let n of e)n.type===`tool_use`&&t.push({name:n.name,args:n.input,id:n.id,type:`tool_call`});return t}var wX=[`oneOf`,`anyOf`,`allOf`];function TX(e){return typeof e.input_schema!=`object`||e.input_schema===null?[]:wX.filter(t=>Object.prototype.hasOwnProperty.call(e.input_schema,t))}function EX(e){if(e)return e===`any`||e===`required`?{type:`any`}:e===`auto`?{type:`auto`}:e===`none`?{type:`none`}:typeof e==`string`?{type:`tool`,name:e}:e}var DX=V({cache_control:Uj().optional().nullable(),defer_loading:QA().optional(),input_examples:oj(nj()).optional(),allowed_callers:oj(nj()).optional(),strict:QA().optional()}),OX={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 kX(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`thinking`}function AX(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`redacted_thinking`}function jX(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`compaction`}function MX(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`search_result`}function NX(e){return typeof e!=`object`||!e||!(`type`in e)||e.type!==`image`||!(`source`in e)||typeof e.source!=`object`||e.source==null||!(`type`in e.source)?!1:e.source.type===`base64`?!(!(`media_type`in e.source)||typeof e.source.media_type!=`string`||!(`data`in e.source)||typeof e.source.data!=`string`):e.source.type===`url`&&!(!(`url`in e.source)||typeof e.source.url!=`string`)}var PX={providerName:`anthropic`,fromStandardTextBlock(e){return{type:`text`,text:e.text,...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}},fromStandardImageBlock(e){if(e.source_type===`url`){let t=et({dataUrl:e.url,asTypedArray:!1});return t?{type:`image`,source:{type:`base64`,data:t.data,media_type:t.mime_type},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}:{type:`image`,source:{type:`url`,url:e.url},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}}else if(e.source_type===`base64`)return{type:`image`,source:{type:`base64`,data:e.data,media_type:e.mime_type??``},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}};else throw Error(`Unsupported image source type: ${e.source_type}`)},fromStandardFileBlock(e){let t=(e.mime_type??``).split(`;`)[0];if(e.source_type===`url`){if(t===`application/pdf`||t===``)return{type:`document`,source:{type:`url`,url:e.url},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file url source: ${e.mime_type}`)}else if(e.source_type===`text`){if(t===`text/plain`||t===``)return{type:`document`,source:{type:`text`,data:e.text,media_type:e.mime_type??``},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file text source: ${e.mime_type}`)}else if(e.source_type===`base64`){if(t===`application/pdf`||t===``)return{type:`document`,source:{type:`base64`,data:e.data,media_type:`application/pdf`},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};if([`image/jpeg`,`image/png`,`image/gif`,`image/webp`].includes(t))return{type:`document`,source:{type:`content`,content:[{type:`image`,source:{type:`base64`,data:e.data,media_type:t}}]},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file base64 source: ${e.mime_type}`)}else throw Error(`Unsupported file source type: ${e.source_type}`)}},FX=e=>e();function IX(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`citation`}function LX(e){function*t(){for(let t of e)IX(t)&&(t.source===`char`?yield{type:`char_location`,file_id:t.url??``,start_char_index:t.startIndex??0,end_char_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`page`?yield{type:`page_location`,file_id:t.url??``,start_page_number:t.startIndex??0,end_page_number:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`block`?yield{type:`content_block_location`,file_id:t.url??``,start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`url`?yield{type:`web_search_result_location`,url:t.url??``,title:t.title??null,encrypted_index:String(t.startIndex??0),cited_text:t.citedText??``}:t.source===`search`&&(yield{type:`search_result_location`,title:t.title??null,start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,search_result_index:0,source:t.source??``,cited_text:t.citedText??``}))}return Array.from(t())}function RX(e){return typeof e==`string`?e:zX(e)}function zX(e){let t=[];for(let n=0,{length:r}=e;n<r;n++)t.push(String.fromCharCode(e[n]));return btoa(t.join(``))}function BX(e){return(e??``).split(`;`)[0].toLowerCase()}function VX(e,t){if(typeof e==`object`&&e&&t in e)return e[t]}function HX(e,t){let n=VX(t,`cache_control`);n!==void 0&&(e.cache_control=n);let r=VX(t,`citations`);r!==void 0&&(e.citations=r);let i=VX(t,`context`);i!==void 0&&(e.context=i);let a=VX(t,`title`);return a!==void 0&&(e.title=a),e}function UX(e,t){let n=VX(t,`cache_control`);return n!==void 0&&(e.cache_control=n),e}function WX(e){return new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]).has(e)}function GX(e){let t=[],n=e.response_metadata,r=`model_provider`in n&&n?.model_provider===`anthropic`;for(let n of e.contentBlocks)if(n.type===`text`)n.annotations?t.push({type:`text`,text:n.text,citations:LX(n.annotations)}):t.push({type:`text`,text:n.text});else if(n.type===`tool_call`)t.push({type:`tool_use`,id:n.id??``,name:n.name,input:n.args});else if(n.type===`tool_call_chunk`){let e=FX(()=>{if(typeof n.args!=`string`)return n.args;try{return JSON.parse(n.args)}catch{return{}}});t.push({type:`tool_use`,id:n.id??``,name:n.name??``,input:e})}else if(n.type===`reasoning`&&r)t.push({type:`thinking`,thinking:n.reasoning,signature:String(n.signature)});else if(n.type===`server_tool_call`&&r)(n.name===`web_search`||n.name===`code_execution`)&&t.push({type:`server_tool_use`,name:n.name,id:n.id??``,input:n.args});else if(n.type===`server_tool_call_result`&&r)if(n.name===`web_search`&&Array.isArray(n.output.urls)){let e=n.output.urls.map(e=>({type:`web_search_result`,title:``,encrypted_content:``,url:e}));t.push({type:`web_search_tool_result`,tool_use_id:n.toolCallId??``,content:e})}else n.name===`code_execution`?t.push({type:`code_execution_tool_result`,tool_use_id:n.toolCallId??``,content:n.output}):n.name===`mcp_tool_result`&&t.push({type:`mcp_tool_result`,tool_use_id:n.toolCallId??``,content:n.output});else if(n.type===`audio`)throw Error(`Anthropic does not support audio content blocks.`);else if(n.type===`file`){let e=n.metadata;if(n.fileId){t.push(HX({type:`document`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){let r=BX(n.mimeType);if(r===`application/pdf`||r===``){t.push(HX({type:`document`,source:{type:`url`,url:n.url}},e));continue}}if(n.data){let r=BX(n.mimeType);if(r===``||r===`application/pdf`)t.push(HX({type:`document`,source:{type:`base64`,data:RX(n.data),media_type:`application/pdf`}},e));else if(r===`text/plain`)t.push(HX({type:`document`,source:{type:`text`,data:RX(n.data),media_type:`text/plain`}},e));else if(WX(r))t.push(HX({type:`document`,source:{type:`content`,content:[{type:`image`,source:{type:`base64`,data:RX(n.data),media_type:r}}]}},e));else throw Error(`Unsupported file mime type for Anthropic base64 source: ${r}`);continue}throw Error(`File content block must include a fileId, url, or data property.`)}else if(n.type===`image`){let e=n.metadata;if(n.fileId){t.push(UX({type:`image`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){t.push(UX({type:`image`,source:{type:`url`,url:n.url}},e));continue}if(n.data){let r=BX(n.mimeType)||`image/png`;WX(r)&&t.push(UX({type:`image`,source:{type:`base64`,data:RX(n.data),media_type:r}},e));continue}throw Error(`Image content block must include a fileId, url, or data property.`)}else n.type===`video`||(n.type===`text-plain`?n.data&&t.push(HX({type:`document`,source:{type:`text`,data:RX(n.data),media_type:`text/plain`}},n.metadata)):n.type===`non_standard`&&r&&t.push(n.value));return t}function KX(e){let t=et({dataUrl:e});if(t)return{type:`base64`,media_type:t.mime_type,data:t.data};let n;try{n=new URL(e)}catch{throw Error([`Malformed image URL: ${JSON.stringify(e)}. 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(`
|
|
213
213
|
|
|
214
214
|
`))}if(n.protocol===`http:`||n.protocol===`https:`)return{type:`url`,url:e};throw Error([`Invalid image URL protocol: ${JSON.stringify(n.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(`
|
|
215
215
|
|
|
216
|
-
`))}function zX(e){let t=[];for(let n of e)if(n._getType()===`tool`)if(typeof n.content==`string`){let e=t[t.length-1];e?._getType()===`human`&&Array.isArray(e.content)&&`type`in e.content[0]&&e.content[0].type===`tool_result`?e.content.push({type:`tool_result`,content:n.content,tool_use_id:n.tool_call_id}):t.push(new Hn({content:[{type:`tool_result`,content:n.content,tool_use_id:n.tool_call_id}]}))}else t.push(new Hn({content:[{type:`tool_result`,...n.content==null?{}:{content:HX(n)},tool_use_id:n.tool_call_id}]}));else t.push(n);return t}function BX(e){if(e.id===void 0)throw Error(`Anthropic requires all tool calls to have an "id".`);return{type:`tool_use`,id:e.id,name:e.name,input:e.args}}function*VX(e,t){let n=[`bash_code_execution_tool_result`,`input_json_delta`,`server_tool_use`,`text_editor_code_execution_tool_result`,`tool_result`,`tool_search_tool_result`,`tool_search_tool_bm25_tool_result`,`tool_search_tool_regex_tool_result`,`tool_use`,`web_search_result`,`web_search_tool_result`],r=[`text`,`text_delta`];for(let i of e){qe(i)&&(yield tt(i,EX));let a=`cache_control`in i?i.cache_control:void 0;if(i.type===`image_url`){let e;typeof i.image_url==`string`?e=RX(i.image_url):typeof i.image_url==`object`&&i.image_url!==null&&`url`in i.image_url&&typeof i.image_url.url==`string`&&(e=RX(i.image_url.url)),e&&(yield{type:`image`,source:e,...a?{cache_control:a}:{}})}else if(TX(i))yield i;else if(i.type===`image`){let e;`url`in i&&typeof i.url==`string`?e=RX(i.url):`data`in i&&(typeof i.data==`string`||i.data instanceof Uint8Array)?e={type:`base64`,media_type:`mimeType`in i&&typeof i.mimeType==`string`?i.mimeType:`image/jpeg`,data:typeof i.data==`string`?i.data:Buffer.from(i.data).toString(`base64`)}:`fileId`in i&&typeof i.fileId==`string`&&(e={type:`file`,file_id:i.fileId}),e&&(yield{type:`image`,source:e,...a?{cache_control:a}:{}})}else if(i.type===`file`){let e;`url`in i&&typeof i.url==`string`?e={type:`url`,url:i.url}:`data`in i&&(typeof i.data==`string`||i.data instanceof Uint8Array)?e={type:`base64`,media_type:`mimeType`in i&&typeof i.mimeType==`string`?i.mimeType:`application/pdf`,data:typeof i.data==`string`?i.data:Buffer.from(i.data).toString(`base64`)}:`fileId`in i&&typeof i.fileId==`string`&&(e={type:`file`,file_id:i.fileId}),e&&(yield{type:`document`,source:e,...a?{cache_control:a}:{}})}else if(i.type===`document`)yield{...i,...a?{cache_control:a}:{}};else if(xX(i))yield{type:`thinking`,thinking:i.thinking,signature:i.signature,...a?{cache_control:a}:{}};else if(SX(i))yield{type:`redacted_thinking`,data:i.data,...a?{cache_control:a}:{}};else if(CX(i))yield{type:`compaction`,content:i.content,...a?{cache_control:a}:{}};else if(wX(i))yield{type:`search_result`,title:i.title,source:i.source,...`cache_control`in i&&i.cache_control?{cache_control:i.cache_control}:{},...`citations`in i&&i.citations?{citations:i.citations}:{},content:i.content};else if(r.find(e=>e===i.type)&&`text`in i)yield{type:`text`,text:i.text,...a?{cache_control:a}:{},...`citations`in i&&i.citations?{citations:i.citations}:{}};else if(n.find(e=>e===i.type)){let n={...i};if(n.type===`input_json_delta`)continue;if(n.type===`tool_use`&&typeof n.input==`string`){let r=t?.find(e=>e.id===n.id);r?n.input=r.args:n.input=e.filter(e=>e.index===n.index&&e.type===`input_json_delta`&&typeof e.input==`string`).reduce((e,t)=>e+t.input,n.input)}if(`index`in n&&delete n.index,`input`in n&&typeof n.input==`string`)try{n.input=JSON.parse(n.input)}catch{n.input={}}yield{...n,...a?{cache_control:a}:{}}}else i.type===`container_upload`&&(yield{...i,...a?{cache_control:a}:{}})}}function HX(e,t){let{content:n}=e;return typeof n==`string`?n:Array.from(VX(n,t))}function UX(e){let t=zX(e),n;return t.length>0&&t[0]._getType()===`system`&&(n=e[0].content),{messages:WX((n===void 0?t:t.slice(1)).map(e=>{let t;if(e._getType()===`human`)t=`user`;else if(e._getType()===`ai`)t=`assistant`;else if(e._getType()===`tool`)t=`user`;else if(e._getType()===`system`)throw Error(`System messages are only permitted as the first passed message.`);else throw Error(`Message type "${e.type}" is not supported.`);if(An.isInstance(e)&&e.response_metadata?.output_version===`v1`)return{role:t,content:LX(e)};if(An.isInstance(e)&&e.tool_calls?.length){if(typeof e.content==`string`)return e.content===``?{role:t,content:e.tool_calls.map(BX)}:{role:t,content:[{type:`text`,text:e.content},...e.tool_calls.map(BX)]};{let{content:n}=e,r=HX(e,e.tool_calls),i=Array.isArray(r)?r:[{type:`text`,text:r}],a=e.tool_calls.filter(e=>!n.find(t=>(t.type===`tool_use`||t.type===`input_json_delta`||t.type===`server_tool_use`)&&t.id===e.id));return{role:t,content:[...i,...a.map(BX)]}}}else return{role:t,content:HX(e,An.isInstance(e)?e.tool_calls:void 0)}})),system:n}}function WX(e){if(!e||e.length<=1)return e;let t=[],n=e[0],r=e=>typeof e==`string`?[{type:`text`,text:e}]:e,i=e=>e.role!==`user`||typeof e.content==`string`?!1:Array.isArray(e.content)&&e.content.every(e=>e.type===`tool_result`);for(let a=1;a<e.length;a+=1){let o=e[a];i(n)&&i(o)?n={...n,content:[...r(n.content),...r(o.content)]}:(t.push(n),n=o)}return t.push(n),t}var GX=[`claude-opus-4-7`,`claude-opus-4-8`,`claude-opus-5`,`claude-fable-5`,`claude-mythos-5`,`claude-mythos-preview`];function KX(e,t){return e?t.some(t=>e.startsWith(t)):!1}function qX(e){return e.type===`enabled`||e.type===`adaptive`}function JX(e){return KX(e,[`claude-opus-4-7`])}function YX(e){return KX(e,GX)}function XX(e,t){let n=t&&typeof t==`object`&&`task_budget`in t&&t.task_budget!=null;return JX(e)&&n?[`task-budgets-2026-03-13`]:[]}function ZX(e){let{model:t,thinking:n,outputConfig:r,topK:i,topP:a,temperature:o}=e,s=YX(t),c=t??`this model`;if(s&&n.type===`enabled`)throw Error(`thinking.type="enabled" is not supported for ${c}; use thinking.type="adaptive" instead`);if(s&&typeof n==`object`&&n&&`budget_tokens`in n)throw Error(`thinking.budget_tokens is not supported for ${c}; use outputConfig.effort instead`);if(KX(t,[`claude-opus-5`])&&n.type===`disabled`&&(r?.effort===`xhigh`||r?.effort===`max`))throw Error(`thinking.type="disabled" is not supported for ${c} with outputConfig.effort="${r.effort}"; use thinking.type="adaptive" or omit thinking instead`);if(s){if(i!==void 0)throw Error(`topK is not supported for ${c}; omit topK/topP/temperature or use model prompting instead`);if(a!==void 0&&a!==1)throw Error(`topP is not supported for ${c} when set to non-default values`);if(o!==void 0&&o!==1)throw Error(`temperature is not supported for ${c} when set to non-default values`)}if(qX(n)){if(i!==void 0)throw Error(`topK is not supported when thinking is enabled`);if(a!==void 0)throw Error(`topP is not supported when thinking is enabled`);if(o!==void 0&&o!==1)throw Error(`temperature is not supported when thinking is enabled`)}}function QX(e){let{model:t,thinking:n,topK:r,topP:i,temperature:a}=e,o={};return qX(n)||YX(t)?o:(a!==void 0&&(o.temperature=a),r!==void 0&&(o.top_k=r),i!==void 0&&(o.top_p=i),o)}function $X(e,t){let n={model_provider:`anthropic`};if(e.type===`message_start`){let{content:r,usage:i,...a}=e.message,o={};for(let[e,t]of Object.entries(a))t!=null&&(o[e]=t);let{input_tokens:s,output_tokens:c,...l}=i??{},u=tZ(i);return{chunk:new Nn({content:t.coerceContentToString?``:[],additional_kwargs:o,usage_metadata:t.streamUsage?u:void 0,response_metadata:{...n,usage:{...l}},id:e.message.id})}}else if(e.type===`message_delta`){let n={input_tokens:0,output_tokens:e.usage.output_tokens,total_tokens:e.usage.output_tokens},r=DX(()=>{let t={};return`context_management`in e.delta&&(t.context_management=e.delta.context_management),`usage`in e&&`cost`in e.usage&&typeof e.usage.cost==`number`&&(t.usage={cost:e.usage.cost}),t});return{chunk:new Nn({content:t.coerceContentToString?``:[],response_metadata:r,additional_kwargs:{...e.delta},usage_metadata:t.streamUsage?n:void 0})}}else if(e.type===`content_block_start`&&[`tool_use`,`document`,`server_tool_use`,`web_search_tool_result`,`tool_search_tool_result`,`tool_search_tool_bm25_tool_result`,`tool_search_tool_regex_tool_result`].includes(e.content_block.type)){let r=e.content_block,i;return i=r.type===`tool_use`?[{id:r.id,index:e.index,name:r.name,args:``}]:[],{chunk:new Nn({content:t.coerceContentToString?``:[{index:e.index,...e.content_block,input:r.type===`server_tool_use`||r.type===`tool_use`?``:void 0}],response_metadata:n,additional_kwargs:{},tool_call_chunks:i})}}else if(e.type===`content_block_delta`&&[`text_delta`,`citations_delta`,`thinking_delta`,`signature_delta`].includes(e.delta.type)){if(t.coerceContentToString&&`text`in e.delta)return{chunk:new Nn({content:e.delta.text})};{let t=e.delta;return`citation`in t&&(t.citations=[t.citation],delete t.citation),t.type===`thinking_delta`||t.type===`signature_delta`?{chunk:new Nn({content:[{index:e.index,...t,type:`thinking`}],response_metadata:n})}:{chunk:new Nn({content:[{index:e.index,...t,type:`text`}],response_metadata:n})}}}else if(e.type===`content_block_delta`&&e.delta.type===`input_json_delta`)return{chunk:new Nn({content:t.coerceContentToString?``:[{index:e.index,input:e.delta.partial_json,type:e.delta.type}],response_metadata:n,additional_kwargs:{},tool_call_chunks:[{index:e.index,args:e.delta.partial_json}]})};else if(e.type===`content_block_start`&&e.content_block.type===`text`){let r=e.content_block?.text;if(r!==void 0)return{chunk:new Nn({content:t.coerceContentToString?r:[{index:e.index,...e.content_block}],response_metadata:n,additional_kwargs:{}})}}else if(e.type===`content_block_start`&&e.content_block.type===`redacted_thinking`)return{chunk:new Nn({content:t.coerceContentToString?``:[{index:e.index,...e.content_block}],response_metadata:n})};else if(e.type===`content_block_start`&&e.content_block.type===`thinking`){let r=e.content_block.thinking;return{chunk:new Nn({content:t.coerceContentToString?r:[{index:e.index,...e.content_block}],response_metadata:n})}}else if(e.type===`content_block_start`&&CX(e.content_block))return{chunk:new Nn({content:t.coerceContentToString?``:[{index:e.index,...e.content_block}],response_metadata:n})};else if(e.type===`content_block_delta`&&e.delta.type===`compaction_delta`)return{chunk:new Nn({content:t.coerceContentToString?``:[{index:e.index,...e.delta,type:`compaction`}],response_metadata:n})};return null}function eZ(e,t){let n={...t,model_provider:`anthropic`},r=t.usage,i=r==null?void 0:tZ(r);return e.length===1&&e[0].type===`text`?[{text:e[0].text,message:new An({content:e[0].text,additional_kwargs:t,usage_metadata:i,response_metadata:n,id:t.id})}]:[{text:``,message:new An({content:e,additional_kwargs:t,tool_calls:hX(e),usage_metadata:i,response_metadata:n,id:t.id})}]}function tZ(e){let t=e.cache_creation_input_tokens??0,n=e.cache_read_input_tokens??0,r=e.input_tokens+t+n;return{input_tokens:r,output_tokens:e.output_tokens,total_tokens:r+e.output_tokens,input_token_details:{cache_creation:t,cache_read:n}}}function nZ(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}function rZ(e){let t;return t=e.status===400&&typeof e.message==`string`&&e.message.includes(`prompt is too long`)?nZ(be.fromError(e),`CONTEXT_OVERFLOW`):e.status===400&&e.message.includes(`tool`)?ge(nZ(e,`INVALID_TOOL_RESULTS`),!1):e.status===401?ge(nZ(e,`MODEL_AUTHENTICATION`),!1):e.status===404?ge(nZ(e,`MODEL_NOT_FOUND`),!1):e.status===429?ge(nZ(e,`MODEL_RATE_LIMIT`),!0):e,t}var iZ={"claude-sonnet-4-6":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-6":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-fable-5":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-8":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5-20250929":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-5-20251101":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5-20251001":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-7":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-5":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-5":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1-20250805":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0}};async function*aZ(e,t={}){let n=t.streamUsage??!0,r=new Map,i,a={},o=null;for await(let t of e)switch(t.type){case`message_start`:{let{usage:e,id:r,model:a}=t.message;e&&n&&(i=sZ(e)),yield{event:`message-start`,id:r,...i?{usage:i}:{}},yield{event:`provider`,provider:`anthropic`,name:`message_start`,payload:{model:a,id:r}};break}case`message_delta`:o=t.delta.stop_reason,`usage`in t&&`cost`in t.usage&&typeof t.usage.cost==`number`&&(a={usage:{cost:t.usage.cost}}),n&&t.usage&&(i=i?{...i,output_tokens:i.output_tokens+t.usage.output_tokens,total_tokens:i.input_tokens+i.output_tokens+t.usage.output_tokens}:{input_tokens:0,output_tokens:t.usage.output_tokens,total_tokens:t.usage.output_tokens},yield{event:`usage`,usage:i}),`context_management`in t.delta&&t.delta.context_management&&(yield{event:`provider`,provider:`anthropic`,name:`context_management`,payload:t.delta.context_management});break;case`message_stop`:yield{event:`message-finish`,reason:oZ(o),...i?{usage:i}:{},metadata:{model_provider:`anthropic`},responseMetadata:a};break;case`content_block_start`:{let{index:e,content_block:n}=t,i=cZ(n,e);r.set(e,{...i}),yield{event:`content-block-start`,index:e,content:i};break}case`content_block_delta`:{let{index:e,delta:n}=t,i=r.get(e);if(!i)break;let{contentDelta:a,accumulated:o}=lZ(i,n);r.set(e,o),yield{event:`content-block-delta`,index:e,delta:a};break}case`content_block_stop`:{let{index:e}=t,n=r.get(e);if(!n)break;yield{event:`content-block-finish`,index:e,content:uZ(n)},r.delete(e);break}default:yield{event:`provider`,provider:`anthropic`,name:t.type,payload:t};break}}function oZ(e){switch(e){case`end_turn`:case`stop_sequence`:return`stop`;case`tool_use`:return`tool_use`;case`max_tokens`:return`length`;default:return`stop`}}function sZ(e){let t=e.cache_creation_input_tokens??0,n=e.cache_read_input_tokens??0,r=e.input_tokens+t+n;return{input_tokens:r,output_tokens:e.output_tokens,total_tokens:r+e.output_tokens,input_token_details:{cache_creation:t,cache_read:n}}}function cZ(e,t){switch(e.type){case`text`:return{type:`text`,text:e.text??``,index:t};case`thinking`:return{type:`reasoning`,reasoning:e.thinking??``,index:t};case`redacted_thinking`:return{type:`non_standard`,value:{...e},index:t};case`tool_use`:return{type:`tool_call_chunk`,id:e.id,name:e.name,args:``,index:t};case`server_tool_use`:return{type:`server_tool_call_chunk`,id:e.id,name:e.name,args:``,index:t};default:return{type:`non_standard`,value:{...e},index:t}}}function lZ(e,t){switch(t.type){case`text_delta`:return{contentDelta:{type:`text-delta`,text:t.text},accumulated:{...e,text:(e.text??``)+t.text}};case`thinking_delta`:return{contentDelta:{type:`reasoning-delta`,reasoning:t.thinking},accumulated:{...e,reasoning:(e.reasoning??``)+t.thinking}};case`input_json_delta`:{let n=(e.args??``)+t.partial_json;return{contentDelta:{type:`block-delta`,fields:{type:e.type,args:n}},accumulated:{...e,args:n}}}case`citations_delta`:{let n=[...e.annotations??[],t.citation];return{contentDelta:{type:`block-delta`,fields:{type:e.type,annotations:n}},accumulated:{...e,annotations:n}}}case`signature_delta`:return{contentDelta:{type:`block-delta`,fields:{type:e.type,signature:t.signature}},accumulated:{...e,signature:t.signature}};case`compaction_delta`:return{contentDelta:{type:`block-delta`,fields:{type:`non_standard`,value:{...e.value??{},compaction:t}}},accumulated:{...e,value:{...e.value??{},compaction:t}}};default:return{contentDelta:{type:`block-delta`,fields:{type:e.type,...t}},accumulated:e}}}function uZ(e){if(e.type===`tool_call_chunk`||e.type===`server_tool_call_chunk`){let t=e.type===`tool_call_chunk`?`tool_call`:`server_tool_call`,n;try{n=JSON.parse(e.args||`{}`)}catch{return{type:`invalid_tool_call`,id:e.id,name:e.name,args:e.args,error:`Failed to parse tool call arguments as JSON`}}return{type:t,id:e.id,name:e.name,args:n}}let{index:t,...n}=e;return n}function X(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function Z(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var dZ=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return dZ=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))},fZ=/^[a-z][a-z0-9+.-]*:/i,pZ=e=>fZ.test(e),mZ=e=>(mZ=Array.isArray,mZ(e)),hZ=mZ;function gZ(e){return typeof e==`object`?e??{}:{}}function _Z(e){if(!e)return!0;for(let t in e)return!1;return!0}function vZ(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var yZ=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new a(`${e} must be an integer`);if(t<0)throw new a(`${e} must be a positive integer`);return t},bZ=e=>{try{return JSON.parse(e)}catch{return}},xZ=(e,t)=>{let n=e[t];return delete e[t],n},SZ=(e,t)=>new Promise(n=>{if(t?.aborted)return n();let r=()=>{clearTimeout(i),n()},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n()},e);t?.addEventListener(`abort`,r,{once:!0})}),CZ=`0.115.0`,wZ=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function TZ(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var EZ=()=>{let e=TZ();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":CZ,"X-Stainless-OS":kZ(Deno.build.os),"X-Stainless-Arch":OZ(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":CZ,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":CZ,"X-Stainless-OS":kZ(globalThis.process.platform??`unknown`),"X-Stainless-Arch":OZ(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=DZ();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":CZ,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":CZ,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function DZ(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{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/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var OZ=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,kZ=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),AZ,jZ=()=>AZ??=EZ(),MZ=new WeakMap,NZ=typeof globalThis.FinalizationRegistry==`function`?new globalThis.FinalizationRegistry(e=>LZ(e)):null;function PZ(e,t){return()=>e.removeEventListener(`abort`,t)}function FZ(e,t,n){MZ.set(e,PZ(t,n))}function IZ(e,t){MZ.has(t)&&NZ?.register(e,t,t)}function LZ(e){let t=MZ.get(e);t&&(MZ.delete(e),NZ?.unregister(e),t())}function RZ(){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 zZ(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function BZ(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return zZ({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function VZ(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function HZ(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var UZ=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),WZ=`RFC3986`,GZ=e=>String(e),KZ={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:GZ},qZ=(e,t)=>(qZ=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),qZ(e,t)),JZ=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),YZ=1024,XZ=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=YZ){let t=a.length>=YZ?a.slice(e,e+YZ):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=JZ[r];continue}if(r<2048){n[n.length]=JZ[192|r>>6]+JZ[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=JZ[224|r>>12]+JZ[128|r>>6&63]+JZ[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=JZ[240|r>>18]+JZ[128|r>>12&63]+JZ[128|r>>6&63]+JZ[128|r&63]}o+=n.join(``)}return o};function ZZ(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function QZ(e,t){if(mZ(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var $Z={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},eQ=function(e,t){Array.prototype.push.apply(e,mZ(t)?t:[t])},tQ,nQ={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:XZ,encodeValuesOnly:!1,format:WZ,formatter:GZ,indices:!1,serializeDate(e){return(tQ??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function rQ(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var iQ={};function aQ(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,ee=!1;for(;(y=y.get(iQ))!==void 0&&!ee;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);ee=!0}y.get(iQ)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&mZ(v)&&(v=QZ(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,nQ.encoder,g,`key`,p):t;v=``}if(rQ(v)||ZZ(v)){if(c){let e=h?t:c(t,nQ.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,nQ.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let te=[];if(v===void 0)return te;let ne;if(n===`comma`&&mZ(v))h&&c&&(v=QZ(v,c)),ne=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(mZ(l))ne=l;else{let e=Object.keys(v);ne=u?e.sort(u):e}let x=s?String(t).replace(/\./g,`%2E`):String(t),re=r&&mZ(v)&&v.length===1?x+`[]`:x;if(i&&mZ(v)&&v.length===0)return re+`[]`;for(let t=0;t<ne.length;++t){let y=ne[t],ee=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&ee===null)continue;let x=d&&s?y.replace(/\./g,`%2E`):y,ie=mZ(v)?typeof n==`function`?n(re,x):re:re+(d?`.`+x:`[`+x+`]`);_.set(e,b);let ae=new WeakMap;ae.set(iQ,_),eQ(te,aQ(ee,ie,n,r,i,a,o,s,n===`comma`&&h&&mZ(v)?null:c,l,u,d,f,p,m,h,g,ae))}return te}function oQ(e=nQ){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||nQ.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=WZ;if(e.format!==void 0){if(!qZ(KZ,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=KZ[n],i=nQ.filter;(typeof e.filter==`function`||mZ(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in $Z?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:nQ.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:nQ.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:nQ.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:nQ.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:nQ.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?nQ.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:nQ.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:nQ.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:nQ.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:nQ.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:nQ.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:nQ.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:nQ.strictNullHandling}}function sQ(e,t={}){let n=e,r=oQ(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):mZ(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=$Z[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||eQ(o,aQ(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function cQ(e){return sQ(e,{arrayFormat:`brackets`})}var lQ=`urn:ietf:params:oauth:grant-type:jwt-bearer`,uQ=`refresh_token`,dQ=`/v1/oauth/token`,fQ=`oauth-2025-04-20`,pQ=`oidc-federation-2026-04-01`,mQ=1<<20;function hQ(e){if(!e)return;let t;try{t=new URL(e)}catch(t){throw new CQ(`Invalid token endpoint base URL "${e}": ${t}`)}if(t.protocol===`https:`)return;let n=t.hostname.toLowerCase().replace(/^\[|\]$/g,``);if(!(t.protocol===`http:`&&(n===`localhost`||n===`127.0.0.1`||n===`::1`)))throw new CQ(`Refusing to send credential over non-https token endpoint "${e}"`)}async function gQ(e,t){let n=await SQ(e),r;try{r=JSON.parse(n)}catch{throw new CQ(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,yQ(n),t)}if(!r.access_token)throw new CQ(`Token endpoint response missing access_token: ${JSON.stringify(yQ(r))}`,e.status,yQ(r),t);if(r.token_type&&r.token_type.toLowerCase()!==`bearer`)throw new CQ(`Token endpoint response: unsupported token_type "${r.token_type}" (want Bearer)`,e.status,yQ(r),t);return r}var _Q=2e3,vQ=new Set([`error`,`error_description`,`error_uri`]);function yQ(e){if(e==null)return e;if(typeof e==`string`){let t;try{t=JSON.parse(e)}catch{return e.length<=_Q?e:e.slice(0,_Q)+`... <${e.length-_Q} more chars>`}return JSON.stringify(yQ(t))}if(typeof e==`object`&&!Array.isArray(e)){let t={};for(let[n,r]of Object.entries(e))vQ.has(n)&&(t[n]=r);return t}return null}async function bQ(t,n=e=>console.warn(`anthropic-sdk: ${e}`)){if(typeof process>`u`||process.platform===`win32`)return;let r=await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1])),a=t,o;try{a=await r.promises.realpath(t),o=await r.promises.stat(a)}catch{return}let s=o.mode&511;if(s&18)throw new CQ(`Credentials file at ${a} is group/world-writable (mode 0o${s.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${a}\`.`);if(s&36)throw new CQ(`Credentials file at ${a} is group/world-readable (mode 0o${s.toString(8)}); run \`chmod 600 ${a}\` before retrying.`);typeof process.getuid==`function`&&o.uid!==process.getuid()&&n(`credentials file at ${a} is owned by uid ${o.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function xQ(t,n){let r=await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1])),a=(await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1]))).dirname(t);await r.promises.mkdir(a,{recursive:!0,mode:448});let o=`${t}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{let e=await r.promises.open(o,`w`,384);try{await e.writeFile(JSON.stringify(n,null,2)),await e.sync()}finally{await e.close()}await r.promises.rename(o,t)}catch(e){throw await r.promises.unlink(o).catch(()=>{}),e}try{let e=await r.promises.open(a,`r`);try{await e.sync()}finally{await e.close()}}catch{}}async function SQ(e){if(!e.body)return``;let t=e.body.getReader(),n=[],r=0;for(;;){let{done:e,value:i}=await t.read();if(e)break;if(r+i.length>mQ){let e=mQ-r;e>0&&n.push(i.subarray(0,e)),await t.cancel();break}n.push(i),r+=i.length}let i;if(n.length===1)i=n[0];else{i=new Uint8Array(n.reduce((e,t)=>e+t.length,0));let e=0;for(let t of n)i.set(t,e),e+=t.length}return new TextDecoder(`utf-8`).decode(i)}var CQ=class extends a{constructor(e,t=null,n=null,r=null){super(e),this.statusCode=t,this.body=n,this.requestId=r}};function wQ(){return Math.floor(Date.now()/1e3)}var TQ=class{constructor(e,t){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=e,this.onAdvisoryRefreshError=t}async getToken(){let e=this.nextForce;this.nextForce=!1;let t=this.cached;if(e||t==null)return(await this.refresh(e)).token;if(t.expiresAt==null)return t.token;let n=t.expiresAt-wQ();return n>120?t.token:n>30?(this.backgroundRefresh(),t.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(e=!1){return this.pendingRefresh&&!e?this.pendingRefresh:this.doRefresh(e)}backgroundRefresh(){this.pendingRefresh||wQ()-this.lastAdvisoryError<5||this.doRefresh().catch(e=>{this.lastAdvisoryError=wQ(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(e=>(this.cached=e,this.pendingRefresh=null,e),e=>{throw this.pendingRefresh=null,e}),this.pendingRefresh}},EQ=e=>{if(globalThis.process!==void 0)return{}[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0};function DQ(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var OQ;function kQ(e){let t;return(OQ??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var AQ;function jQ(e){let t;return(AQ??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var MQ=`warn`,NQ={off:0,error:200,warn:300,info:400,debug:500},PQ=(e,t,n)=>{if(e){if(vZ(NQ,e))return e;n.warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(NQ))}`)}};function FQ(){}function IQ(e,t,n){return!t||NQ[e]>NQ[n]?FQ:t[e].bind(t)}var LQ={error:FQ,warn:FQ,info:FQ,debug:FQ},RQ=new WeakMap;function zQ(e,t){let n=RQ.get(e);if(n&&n[0]===t)return n[1];let r={error:IQ(`error`,e,t),warn:IQ(`warn`,e,t),info:IQ(`info`,e,t),debug:IQ(`debug`,e,t)};return RQ.set(e,[t,r]),r}function BQ(e){let t=e.logger,n=e.logLevel??`off`;return t?zQ(t,n):LQ}var VQ,HQ;function UQ(){let e=EQ(`ANTHROPIC_LOG`);return(!HQ||e!==VQ)&&(VQ=e,HQ=zQ(console,PQ(e,`process.env['ANTHROPIC_LOG']`,zQ(console,`warn`))??`warn`)),HQ}var WQ=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`api-key`||e.toLowerCase()===`x-api-key`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),GQ=/^[A-Za-z0-9_.-]+$/;function KQ(e){if(!e)throw Error(`profile name is empty`);if(e===`.`||e===`..`)throw Error(`profile name "${e}" is not allowed`);if(e.includes(`/`)||e.includes(`\\`))throw Error(`profile name "${e}" must not contain path separators`);if(!GQ.test(e))throw Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var qQ=async t=>{var n,r;let a=await YQ();if(a===null)return null;let o=t??await ZQ();if(o===null)return null;KQ(o);let s=await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1])),c=(await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1]))).join(a,`configs`,`${o}.json`),l;try{l=await s.promises.readFile(c,`utf-8`)}catch(e){if(e?.code!==`ENOENT`)throw Error(`failed to read config file ${c}: ${e}`);l=null}if(l===null){let e=EQ(`ANTHROPIC_ORGANIZATION_ID`),t=EQ(`ANTHROPIC_IDENTITY_TOKEN_FILE`),n=EQ(`ANTHROPIC_FEDERATION_RULE_ID`);return n&&e?{fromFile:!1,config:{organization_id:e,workspace_id:EQ(`ANTHROPIC_WORKSPACE_ID`),base_url:EQ(`ANTHROPIC_BASE_URL`),authentication:{type:`oidc_federation`,federation_rule_id:n,service_account_id:EQ(`ANTHROPIC_SERVICE_ACCOUNT_ID`),identity_token:t?{source:`file`,path:t}:void 0,scope:EQ(`ANTHROPIC_SCOPE`)}}}:null}let u;try{u=JSON.parse(l)}catch(e){throw Error(`failed to parse config file ${c}: ${e}`)}if(!u.authentication)throw Error(`config file ${c} is missing "authentication"`);let d=u.authentication.type;if(d!==`oidc_federation`&&d!==`user_oauth`)throw Error(`authentication.type "${d}" is not a known authentication type`);if(u.organization_id??=EQ(`ANTHROPIC_ORGANIZATION_ID`),u.workspace_id??=EQ(`ANTHROPIC_WORKSPACE_ID`),u.base_url??=EQ(`ANTHROPIC_BASE_URL`),(n=u.authentication).scope??(n.scope=EQ(`ANTHROPIC_SCOPE`)),u.authentication.type===`oidc_federation`){if(!u.authentication.identity_token){let e=EQ(`ANTHROPIC_IDENTITY_TOKEN_FILE`);e&&(u.authentication.identity_token={source:`file`,path:e})}u.authentication.federation_rule_id||(u.authentication.federation_rule_id=EQ(`ANTHROPIC_FEDERATION_RULE_ID`)??``),(r=u.authentication).service_account_id??(r.service_account_id=EQ(`ANTHROPIC_SERVICE_ACCOUNT_ID`))}return{config:u,fromFile:!0}},JQ=async(t,n)=>{if(t?.authentication.credentials_path)return t.authentication.credentials_path;let r=await YQ();if(!r)return null;let a=n??await ZQ();return a?(KQ(a),(await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1]))).join(r,`credentials`,`${a}.json`)):null},YQ=async()=>{if(!XQ())return null;let t=await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1])),n=EQ(`ANTHROPIC_CONFIG_DIR`);if(n)return n;if(jZ()[`X-Stainless-OS`]===`Windows`){let e=EQ(`APPDATA`);if(e)return t.join(e,`Anthropic`);let n=EQ(`USERPROFILE`);return n?t.join(n,`AppData`,`Roaming`,`Anthropic`):null}let r=EQ(`XDG_CONFIG_HOME`);if(r)return t.join(r,`anthropic`);let a=EQ(`HOME`);return a?t.join(a,`.config`,`anthropic`):null},XQ=()=>{let e=jZ()[`X-Stainless-Runtime`];return e===`node`||e===`deno`},ZQ=async()=>{let t=await YQ();if(!t)return null;let n=EQ(`ANTHROPIC_PROFILE`);if(n)return n;let r=await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1])),a=(await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1]))).join(t,`active_config`);try{return(await r.promises.readFile(a,`utf-8`)).trim()||`default`}catch(e){if(e?.code!==`ENOENT`)throw Error(`failed to read ${a}: ${e}`);return`default`}};function QQ(t){if(!t)throw new a(`Identity token file path is empty`);return async()=>{let n=await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1])),r;try{r=await n.promises.readFile(t,`utf-8`)}catch(e){throw new a(`Failed to read identity token file at ${t}: ${e}`)}let o=r.trim();if(!o)throw new a(`Identity token file at ${t} is empty`);return o}}function $Q(e){if(!e)throw new a(`Identity token value is empty`);return()=>e}function e$(e){return async()=>{hQ(e.baseURL);let t=await e.identityTokenProvider();if(t.length>16*1024)throw new CQ(`Identity token is ${Math.ceil(t.length/1024)} KiB, exceeds the 16 KiB assertion limit`);let n={grant_type:lQ,assertion:t,federation_rule_id:e.federationRuleId,organization_id:e.organizationId};e.serviceAccountId&&(n.service_account_id=e.serviceAccountId),e.workspaceId&&(n.workspace_id=e.workspaceId);let r=`${e.baseURL}${dQ}`,i;try{i=await e.fetch(r,{method:`POST`,headers:{"Content-Type":`application/json`,"anthropic-beta":`${fQ},${pQ}`,"User-Agent":e.userAgent||`anthropic-sdk-typescript/0.115.0 oidcFederationProvider`},body:JSON.stringify(n)})}catch(e){throw new CQ(`Failed to reach token endpoint ${r}: ${e}`)}let a=i.headers.get(`Request-Id`);if(!i.ok){let t=yQ(await i.text().catch(()=>``)),n=``;throw i.status===401&&(n=` Ensure your federation rule matches your identity token. ${e.workspaceId?``:"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new CQ(`Token exchange failed with status ${i.status}${a?` (request-id ${a})`:``}: ${t}${n}`,i.status,t,a)}let o=await gQ(i,a),s=Number(o.expires_in);if(!Number.isFinite(s))throw new CQ(`Token endpoint response missing required fields: ${JSON.stringify(yQ(o))}`,i.status,yQ(o),a);return{token:o.access_token,expiresAt:wQ()+s}}}function t$(t){return async n=>{let r=await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1]));await bQ(t.credentialsPath,t.onSafetyWarning);let a;try{a=await r.promises.readFile(t.credentialsPath,`utf-8`)}catch(e){throw new CQ(`Credentials file not found at ${t.credentialsPath}: ${e}`)}let o;try{o=JSON.parse(a)}catch(e){throw new CQ(`Credentials file at ${t.credentialsPath} is not valid JSON: ${e}`)}let s=o.access_token;if(!s)throw new CQ(`Credentials file at ${t.credentialsPath} must include 'access_token'`);let c=o.expires_at;if(!n?.forceRefresh&&(c==null||wQ()<c-30))return{token:s,expiresAt:c??null};let l=o.refresh_token;if(!t.clientId||!l)throw new CQ(`Access token at ${t.credentialsPath} has expired and no refresh is available (client_id ${t.clientId?`set`:`empty`}, refresh_token ${l?`set`:`empty`})`);hQ(t.baseURL);let u={grant_type:uQ,refresh_token:l,client_id:t.clientId},d=`${t.baseURL}${dQ}`,f;try{f=await t.fetch(d,{method:`POST`,headers:{"Content-Type":`application/json`,"anthropic-beta":fQ,"User-Agent":t.userAgent||`anthropic-sdk-typescript/0.115.0 userOAuthProvider`},body:JSON.stringify(u)})}catch(e){throw new CQ(`User OAuth refresh failed to reach token endpoint: ${e}`)}let p=f.headers.get(`Request-Id`);if(!f.ok){let e=await f.text().catch(()=>``);throw new CQ(`User OAuth refresh failed (HTTP ${f.status}): ${yQ(e)}`,f.status,yQ(e),p)}let m=await gQ(f,p),h=Number(m.expires_in);if(!Number.isFinite(h))throw new CQ(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(yQ(m))}`,f.status,yQ(m),p);let g=wQ()+h,_=m.refresh_token||l;return await xQ(t.credentialsPath,{...o,version:`1.0`,type:`oauth_token`,access_token:m.access_token,expires_at:g,refresh_token:_}),{token:m.access_token,expiresAt:g}}}function n$(e,t){let n=i$(e,e.authentication.credentials_path??null,(e.base_url||t.baseURL).replace(/\/+$/,``),t),r={};return e.workspace_id&&e.authentication.type===`user_oauth`&&(r[`anthropic-workspace-id`]=e.workspace_id),{provider:n,extraHeaders:r,baseURL:e.base_url||void 0}}async function r$(e,t){let n=await qQ(t);if(!n)return null;let{config:r,fromFile:i}=n;return n$(r.authentication.credentials_path||!i?r:{...r,authentication:{...r.authentication,credentials_path:await JQ(r,t)??void 0}},e)}function i$(e,t,n,r){switch(e.authentication.type){case`oidc_federation`:{let i=e.authentication,a=a$(i);if(!a)throw new CQ(`oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)`);if(!i.federation_rule_id)throw new CQ(`oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).`);if(!e.organization_id)throw new CQ(`oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)`);let o=e$({identityTokenProvider:a,federationRuleId:i.federation_rule_id,organizationId:e.organization_id,serviceAccountId:i.service_account_id,workspaceId:e.workspace_id,baseURL:n,fetch:r.fetch,userAgent:r.userAgent});return t?o$(o,t,r.onCacheWriteError,r.onSafetyWarning):o}case`user_oauth`:if(!t)throw new CQ(`user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)`);return t$({credentialsPath:t,clientId:e.authentication.client_id,baseURL:n,fetch:r.fetch,userAgent:r.userAgent,onSafetyWarning:r.onSafetyWarning});default:{let t=e.authentication.type;throw new CQ(`authentication.type "${t}" is not a known authentication type`)}}}function a$(e){if(e.identity_token){let t=e.identity_token.source;if(t!==`file`)throw new CQ(`identity_token.source "${t}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new CQ(`identity_token.source "file" requires a non-empty path`);return QQ(e.identity_token.path)}let t=EQ(`ANTHROPIC_IDENTITY_TOKEN_FILE`);if(t)return QQ(t);let n=EQ(`ANTHROPIC_IDENTITY_TOKEN`);return n?$Q(n):null}function o$(t,n,r,a){return async o=>{let s=await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1]));await bQ(n,a);let c;try{let e=await s.promises.readFile(n,`utf-8`);c=JSON.parse(e);let t=c?.access_token;if(t&&!o?.forceRefresh){let e=c?.expires_at;if(e==null||wQ()<e-30)return{token:t,expiresAt:e??null}}}catch(e){e?.code!==`ENOENT`&&!(e instanceof SyntaxError)&&r?.(e)}let l=await t(o);try{await xQ(n,{...c??{},version:`1.0`,type:`oauth_token`,access_token:l.token,expires_at:l.expiresAt})}catch(e){r?.(e)}return l}}var s$,c$,l$=class{constructor(){s$.set(this,void 0),c$.set(this,void 0),X(this,s$,new Uint8Array,`f`),X(this,c$,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?kQ(e):e;X(this,s$,DQ([Z(this,s$,`f`),t]),`f`);let n=[],r;for(;(r=u$(Z(this,s$,`f`),Z(this,c$,`f`)))!=null;){if(r.carriage&&Z(this,c$,`f`)==null){X(this,c$,r.index,`f`);continue}if(Z(this,c$,`f`)!=null&&(r.index!==Z(this,c$,`f`)+1||r.carriage)){n.push(jQ(Z(this,s$,`f`).subarray(0,Z(this,c$,`f`)-1))),X(this,s$,Z(this,s$,`f`).subarray(Z(this,c$,`f`)),`f`),X(this,c$,null,`f`);continue}let e=Z(this,c$,`f`)===null?r.preceding:r.preceding-1,t=jQ(Z(this,s$,`f`).subarray(0,e));n.push(t),X(this,s$,Z(this,s$,`f`).subarray(r.index),`f`),X(this,c$,null,`f`)}return n}flush(){return Z(this,s$,`f`).length?this.decode(`
|
|
217
|
-
`):[]}};
|
|
218
|
-
`,`\r`]),
|
|
219
|
-
`);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*
|
|
220
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=_$(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function _$(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function v$(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return BQ(e).debug(`response`,n.status,n.url,n.headers,n.body),p$.fromSSEResponse(n,t.controller);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:y$(await n.json(),n):await n.text()})().finally(()=>{!t.options.stream&&!t.options.__binaryResponse&&LZ(t.controller)});return BQ(e).debug(`[${r}] response parsed`,WQ({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function y$(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`request-id`),enumerable:!1})}var b$=new WeakSet;function x$(e){return typeof e==`object`&&!!e&&b$.has(e)}function S$(e){let t=new Set;for(;typeof e==`object`&&e&&!t.has(e);){if(t.add(e),x$(e)||l(e)||e instanceof y||e instanceof g)return!0;e=e.cause}return!1}function C$(e,t,n,r){return async(i,o={})=>{if(t.length===0)return e.call(void 0,i,o);let s=o.headers instanceof Headers?o.headers:new Headers(o.headers),c=await E$(e,t,n,r)({...o,headers:s,url:typeof i==`string`?i:i instanceof URL?i.href:i.url});if(c.bodyUsed||c.body?.locked)throw new a(`middleware consumed the response body; use response.clone() to inspect it, or return new Response(body, response) to consume and replace it`);return c}}function w$(e,t){let n=new WeakMap;return{options:e,logger:t?BQ(t):UQ(),parse(t){if(e?.stream&&t.ok)return T$(t,e);let r=n.get(t);return r||(r=T$(t,e),n.set(t,r)),r}}}async function T$(e,t){if(e.bodyUsed||e.body?.locked)throw new a(`cannot ctx.parse() a response whose body was already consumed; call ctx.parse() instead of reading the body, or read via response.clone()`);if(t?.stream&&e.ok)return p$.fromSSEResponse(e.clone(),new AbortController);if(e.status===204)return null;if(t?.__binaryResponse)return e;let n=e.headers.get(`content-type`)?.split(`;`)[0]?.trim();return n?.includes(`application/json`)||n?.endsWith(`+json`)?e.headers.get(`content-length`)===`0`?void 0:y$(await e.clone().json(),e):await e.clone().text()}function E$(e,t,n,r){let i=async({url:t,...n})=>{try{return await e.call(void 0,t,n)}catch(e){let t=u(e);throw b$.add(t),t}},a=w$(n,r);for(let e=t.length-1;e>=0;e--){let n=t[e],r=i;i=async e=>n(e,r,a)}return i}var D$,O$=class e extends Promise{constructor(e,t,n=v$){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,D$.set(this,void 0),X(this,D$,e,`f`)}_thenUnwrap(t){return new e(Z(this,D$,`f`),this.responsePromise,async(e,n)=>y$(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(Z(this,D$,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};D$=new WeakMap;var k$,A$=class{constructor(e,t,n,r){k$.set(this,void 0),X(this,k$,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new a("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Z(this,k$,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(k$=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},j$=class extends O${constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await v$(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},M$=class extends A${constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let e=this.first_id;return e?{...this.options,query:{...gZ(this.options.query),before_id:e}}:null}let e=this.last_id;return e?{...this.options,query:{...gZ(this.options.query),after_id:e}}:null}},N$=class extends A${constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.next_page=n.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...gZ(this.options.query),page:e}}:null}},P$=class extends A${constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.next_page=n.next_page||null,this.prev_page=n.prev_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...gZ(this.options.query),page:e}}:null}},F$=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function I$(e,t,n){return F$(),new File(e,t??`unknown_file`,n)}function L$(e,t){let n=typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``;return t?n.split(/[\\/]/).pop()||void 0:n}var R$=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,z$=async(e,t,n=!0)=>({...e,body:await H$(e.body,t,n)}),B$=new WeakMap;function V$(e){let t=typeof e==`function`?e:e.fetch,n=B$.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return B$.set(t,r),r}var H$=async(e,t,n=!0)=>{if(!await V$(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>W$(r,e,t,n))),r},U$=e=>e instanceof Blob&&`name`in e,W$=async(e,t,n,r)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response){let i={},a=n.headers.get(`Content-Type`);a&&(i={type:a}),e.append(t,I$([await n.blob()],L$(n,r),i))}else if(R$(n))e.append(t,I$([await new Response(BZ(n)).blob()],L$(n,r)));else if(U$(n))e.append(t,I$([n],L$(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(n=>W$(e,t+`[]`,n,r)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,i])=>W$(e,`${t}[${n}]`,i,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},G$=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,K$=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&G$(e),q$=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function J$(e,t,n){if(F$(),e=await e,t||=L$(e,!0),K$(e))return e instanceof File&&t==null&&n==null?e:I$([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...n});if(q$(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),I$(await Y$(r),t,n)}let r=await Y$(e);if(!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return I$(r,t,n)}async function Y$(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(G$(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(R$(e))for await(let n of e)t.push(...await Y$(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${X$(e)}`)}return t}function X$(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var Z$=class{constructor(e){this._client=e}},Q$=Symbol.for(`brand.privateNullableHeaders`);function*$$(e){if(!e)return;if(Q$ in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():hZ(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=hZ(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,e1]),yield[n,e])}}var e1=Symbol(`clear`),t1=new Set([`x-stainless-helper`]),n1=(e,t)=>{let n=e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[];for(let e of t.split(`,`).map(e=>e.trim()))e&&!n.includes(e)&&n.push(e);return n.join(`, `)},Q=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of $$(r)){let r=i.toLowerCase();if(t1.has(r)){if(a===e1)continue;a===null?(t.delete(i),n.add(r)):(t.set(i,n1(t.get(i),a)),n.delete(r));continue}(a===e1||!e.has(r))&&(t.delete(i),e.add(r),a===e1)||(a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r)))}}return{[Q$]:!0,values:t,nulls:n}};function r1(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var i1=Object.freeze(Object.create(null)),$=((e=r1)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],o=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??i1)??i1)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),s=o.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(s))!==null;)i.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new a(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
|
|
221
|
-
`)}\n${o}\n${t}`)}return o})(r1),a1=class extends Z${retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/deployment_runs/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/deployment_runs?beta=true`,N$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}},o1=class extends Z${create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/deployments?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/deployments/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/deployments/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/deployments?beta=true`,N$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/deployments/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}pause(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/deployments/${e}/pause?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}run(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/deployments/${e}/run?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}unpause(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/deployments/${e}/unpause?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},s1=class extends Z${create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/dreams?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`dreaming-2026-04-21`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/dreams/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`dreaming-2026-04-21`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/dreams?beta=true`,N$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`dreaming-2026-04-21`].toString()},t?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/dreams/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`dreaming-2026-04-21`].toString()},n?.headers])})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/dreams/${e}/cancel?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`dreaming-2026-04-21`].toString()},n?.headers])})}},c1=`x-stainless-helper`,l1=`x-stainless-helper-method`;function u1(e){return{[c1]:e}}var d1=Symbol(`anthropic.sdk.stainlessHelper`);function f1(e){return typeof e==`object`&&!!e&&d1 in e}function p1(e,t){let n=new Set;if(e)for(let t of e)f1(t)&&n.add(t[d1]);if(t)for(let e of t){f1(e)&&n.add(e[d1]);let t=e.content;if(Array.isArray(t))for(let e of t)f1(e)&&n.add(e[d1])}return Array.from(n)}function m1(e,t){let n=p1(e,t);return n.length===0?{}:{[c1]:n.join(`, `)}}function h1(e){return f1(e)?{[c1]:e[d1]}:{}}var g1=class extends Z${list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/files?beta=true`,M$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/files/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}download(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/files/${e}/content?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString(),Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/files/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}upload(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/files?beta=true`,z$({body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},h1(r.file),t?.headers])},this._client))}},_1=class extends Z${retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/models/${e}?beta=true`,{...n,headers:Q([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/models?beta=true`,M$,{query:r,...t,headers:Q([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},v1=class extends Z${create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/user_profiles?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/user_profiles/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/user_profiles/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/user_profiles?beta=true`,N$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}createEnrollmentURL(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}},y1=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.timingSafeEqual=void 0;function t(e,t=``){if(!e)throw Error(t)}function n(e,n){if(e.byteLength!==n.byteLength)return!1;e instanceof DataView||(e=new DataView(ArrayBuffer.isView(e)?e.buffer:e)),n instanceof DataView||(n=new DataView(ArrayBuffer.isView(n)?n.buffer:n)),t(e instanceof DataView),t(n instanceof DataView);let r=e.byteLength,i=0,a=-1;for(;++a<r;)i|=e.getUint8(a)^n.getUint8(a);return i===0}e.timingSafeEqual=n})),b1=t((e=>{var t=e&&e.__extends||(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();Object.defineProperty(e,"__esModule",{value:!0});var n=256,r=function(){function e(e){e===void 0&&(e=`=`),this._paddingCharacter=e}return e.prototype.encodedLength=function(e){return this._paddingCharacter?(e+2)/3*4|0:(e*8+5)/6|0},e.prototype.encode=function(e){for(var t=``,n=0;n<e.length-2;n+=3){var r=e[n]<<16|e[n+1]<<8|e[n+2];t+=this._encodeByte(r>>>18&63),t+=this._encodeByte(r>>>12&63),t+=this._encodeByte(r>>>6&63),t+=this._encodeByte(r>>>0&63)}var i=e.length-n;if(i>0){var r=e[n]<<16|(i===2?e[n+1]<<8:0);t+=this._encodeByte(r>>>18&63),t+=this._encodeByte(r>>>12&63),i===2?t+=this._encodeByte(r>>>6&63):t+=this._paddingCharacter||``,t+=this._paddingCharacter||``}return t},e.prototype.maxDecodedLength=function(e){return this._paddingCharacter?e/4*3|0:(e*6+7)/8|0},e.prototype.decodedLength=function(e){return this.maxDecodedLength(e.length-this._getPaddingLength(e))},e.prototype.decode=function(e){if(e.length===0)return new Uint8Array;for(var t=this._getPaddingLength(e),r=e.length-t,i=new Uint8Array(this.maxDecodedLength(r)),a=0,o=0,s=0,c=0,l=0,u=0,d=0;o<r-4;o+=4)c=this._decodeChar(e.charCodeAt(o+0)),l=this._decodeChar(e.charCodeAt(o+1)),u=this._decodeChar(e.charCodeAt(o+2)),d=this._decodeChar(e.charCodeAt(o+3)),i[a++]=c<<2|l>>>4,i[a++]=l<<4|u>>>2,i[a++]=u<<6|d,s|=c&n,s|=l&n,s|=u&n,s|=d&n;if(o<r-1&&(c=this._decodeChar(e.charCodeAt(o)),l=this._decodeChar(e.charCodeAt(o+1)),i[a++]=c<<2|l>>>4,s|=c&n,s|=l&n),o<r-2&&(u=this._decodeChar(e.charCodeAt(o+2)),i[a++]=l<<4|u>>>2,s|=u&n),o<r-3&&(d=this._decodeChar(e.charCodeAt(o+3)),i[a++]=u<<6|d,s|=d&n),s!==0)throw Error(`Base64Coder: incorrect characters for decoding`);return i},e.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-15,t+=62-e>>>8&3,String.fromCharCode(t)},e.prototype._decodeChar=function(e){var t=n;return t+=(42-e&e-44)>>>8&-n+e-43+62,t+=(46-e&e-48)>>>8&-n+e-47+63,t+=(47-e&e-58)>>>8&-n+e-48+52,t+=(64-e&e-91)>>>8&-n+e-65+0,t+=(96-e&e-123)>>>8&-n+e-97+26,t},e.prototype._getPaddingLength=function(e){var t=0;if(this._paddingCharacter){for(var n=e.length-1;n>=0&&e[n]===this._paddingCharacter;n--)t++;if(e.length<4||t>2)throw Error(`Base64Coder: incorrect padding`)}return t},e}();e.Coder=r;var i=new r;function a(e){return i.encode(e)}e.encode=a;function o(e){return i.decode(e)}e.decode=o;var s=function(e){t(r,e);function r(){return e!==null&&e.apply(this,arguments)||this}return r.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-13,t+=62-e>>>8&49,String.fromCharCode(t)},r.prototype._decodeChar=function(e){var t=n;return t+=(44-e&e-46)>>>8&-n+e-45+62,t+=(94-e&e-96)>>>8&-n+e-95+63,t+=(47-e&e-58)>>>8&-n+e-48+52,t+=(64-e&e-91)>>>8&-n+e-65+0,t+=(96-e&e-123)>>>8&-n+e-97+26,t},r}(r);e.URLSafeCoder=s;var c=new s;function l(e){return c.encode(e)}e.encodeURLSafe=l;function u(e){return c.decode(e)}e.decodeURLSafe=u,e.encodedLength=function(e){return i.encodedLength(e)},e.maxDecodedLength=function(e){return i.maxDecodedLength(e)},e.decodedLength=function(e){return i.decodedLength(e)}})),x1=t(((e,t)=>{(function(e,n){var r={};n(r);var i=r.default;for(var a in r)i[a]=r[a];typeof t==`object`&&typeof t.exports==`object`?t.exports=i:typeof define==`function`&&define.amd?define(function(){return i}):e.sha256=i})(e,function(e){e.__esModule=!0,e.digestLength=32,e.blockSize=64;var t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function n(e,n,r,i,a){for(var o,s,c,l,u,d,f,p,m,h,g,_,v;a>=64;){for(o=n[0],s=n[1],c=n[2],l=n[3],u=n[4],d=n[5],f=n[6],p=n[7],h=0;h<16;h++)g=i+h*4,e[h]=(r[g]&255)<<24|(r[g+1]&255)<<16|(r[g+2]&255)<<8|r[g+3]&255;for(h=16;h<64;h++)m=e[h-2],_=(m>>>17|m<<15)^(m>>>19|m<<13)^m>>>10,m=e[h-15],v=(m>>>7|m<<25)^(m>>>18|m<<14)^m>>>3,e[h]=(_+e[h-7]|0)+(v+e[h-16]|0);for(h=0;h<64;h++)_=(((u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7))+(u&d^~u&f)|0)+(p+(t[h]+e[h]|0)|0)|0,v=((o>>>2|o<<30)^(o>>>13|o<<19)^(o>>>22|o<<10))+(o&s^o&c^s&c)|0,p=f,f=d,d=u,u=l+_|0,l=c,c=s,s=o,o=_+v|0;n[0]+=o,n[1]+=s,n[2]+=c,n[3]+=l,n[4]+=u,n[5]+=d,n[6]+=f,n[7]+=p,i+=64,a-=64}return i}var r=function(){function t(){this.digestLength=e.digestLength,this.blockSize=e.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return t.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},t.prototype.clean=function(){for(var e=0;e<this.buffer.length;e++)this.buffer[e]=0;for(var e=0;e<this.temp.length;e++)this.temp[e]=0;this.reset()},t.prototype.update=function(e,t){if(t===void 0&&(t=e.length),this.finished)throw Error(`SHA256: can't update because hash was finished.`);var r=0;if(this.bytesHashed+=t,this.bufferLength>0){for(;this.bufferLength<64&&t>0;)this.buffer[this.bufferLength++]=e[r++],t--;this.bufferLength===64&&(n(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(t>=64&&(r=n(this.temp,this.state,e,r,t),t%=64);t>0;)this.buffer[this.bufferLength++]=e[r++],t--;return this},t.prototype.finish=function(e){if(!this.finished){var t=this.bytesHashed,r=this.bufferLength,i=t/536870912|0,a=t<<3,o=t%64<56?64:128;this.buffer[r]=128;for(var s=r+1;s<o-8;s++)this.buffer[s]=0;this.buffer[o-8]=i>>>24&255,this.buffer[o-7]=i>>>16&255,this.buffer[o-6]=i>>>8&255,this.buffer[o-5]=i>>>0&255,this.buffer[o-4]=a>>>24&255,this.buffer[o-3]=a>>>16&255,this.buffer[o-2]=a>>>8&255,this.buffer[o-1]=a>>>0&255,n(this.temp,this.state,this.buffer,0,o),this.finished=!0}for(var s=0;s<8;s++)e[s*4+0]=this.state[s]>>>24&255,e[s*4+1]=this.state[s]>>>16&255,e[s*4+2]=this.state[s]>>>8&255,e[s*4+3]=this.state[s]>>>0&255;return this},t.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},t.prototype._saveState=function(e){for(var t=0;t<this.state.length;t++)e[t]=this.state[t]},t.prototype._restoreState=function(e,t){for(var n=0;n<this.state.length;n++)this.state[n]=e[n];this.bytesHashed=t,this.finished=!1,this.bufferLength=0},t}();e.Hash=r;var i=function(){function e(e){this.inner=new r,this.outer=new r,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var t=new Uint8Array(this.blockSize);if(e.length>this.blockSize)new r().update(e).finish(t).clean();else for(var n=0;n<e.length;n++)t[n]=e[n];for(var n=0;n<t.length;n++)t[n]^=54;this.inner.update(t);for(var n=0;n<t.length;n++)t[n]^=106;this.outer.update(t),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(var n=0;n<t.length;n++)t[n]=0}return e.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},e.prototype.clean=function(){for(var e=0;e<this.istate.length;e++)this.ostate[e]=this.istate[e]=0;this.inner.clean(),this.outer.clean()},e.prototype.update=function(e){return this.inner.update(e),this},e.prototype.finish=function(e){return this.outer.finished?this.outer.finish(e):(this.inner.finish(e),this.outer.update(e,this.digestLength).finish(e)),this},e.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},e}();e.HMAC=i;function a(e){var t=new r().update(e),n=t.digest();return t.clean(),n}e.hash=a,e.default=a;function o(e,t){var n=new i(e).update(t),r=n.digest();return n.clean(),r}e.hmac=o;function s(e,t,n,r){var i=r[0];if(i===0)throw Error(`hkdf: cannot expand more`);t.reset(),i>1&&t.update(e),n&&t.update(n),t.update(r),t.finish(e),r[0]++}var c=new Uint8Array(e.digestLength);function l(e,t,n,r){t===void 0&&(t=c),r===void 0&&(r=32);for(var a=new Uint8Array([1]),l=new i(o(t,e)),u=new Uint8Array(l.digestLength),d=u.length,f=new Uint8Array(r),p=0;p<r;p++)d===u.length&&(s(u,l,n,a),d=0),f[p]=u[d++];return l.clean(),u.fill(0),a.fill(0),f}e.hkdf=l;function u(e,t,n,r){for(var a=new i(e),o=a.digestLength,s=new Uint8Array(4),c=new Uint8Array(o),l=new Uint8Array(o),u=new Uint8Array(r),d=0;d*o<r;d++){var f=d+1;s[0]=f>>>24&255,s[1]=f>>>16&255,s[2]=f>>>8&255,s[3]=f>>>0&255,a.reset(),a.update(t),a.update(s),a.finish(l);for(var p=0;p<o;p++)c[p]=l[p];for(var p=2;p<=n;p++){a.reset(),a.update(l).finish(l);for(var m=0;m<o;m++)c[m]^=l[m]}for(var p=0;p<o&&d*o+p<r;p++)u[d*o+p]=c[p]}for(var d=0;d<o;d++)c[d]=l[d]=0;for(var d=0;d<4;d++)s[d]=0;return a.clean(),u}e.pbkdf2=u})})),S1=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Webhook=e.WebhookVerificationError=void 0;var t=y1(),n=b1(),r=x1(),i=300,a=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name=`ExtendableError`,this.stack=Error(t).stack}},o=class e extends a{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name=`WebhookVerificationError`}};e.WebhookVerificationError=o;var s=class e{constructor(t,r){if(!t)throw Error(`Secret can't be empty.`);if(r?.format===`raw`)t instanceof Uint8Array?this.key=t:this.key=Uint8Array.from(t,e=>e.charCodeAt(0));else{if(typeof t!=`string`)throw Error(`Expected secret to be of type string`);t.startsWith(e.prefix)&&(t=t.substring(e.prefix.length)),this.key=n.decode(t)}}verify(e,n){let r={};for(let e of Object.keys(n))r[e.toLowerCase()]=n[e];let i=r[`webhook-id`],a=r[`webhook-signature`],s=r[`webhook-timestamp`];if(!a||!i||!s)throw new o(`Missing required headers`);let c=this.verifyTimestamp(s),l=this.sign(i,c,e).split(`,`)[1],u=a.split(` `),d=new globalThis.TextEncoder;for(let n of u){let[r,i]=n.split(`,`);if(r===`v1`&&(0,t.timingSafeEqual)(d.encode(i),d.encode(l)))return JSON.parse(e.toString())}throw new o(`No matching signature found`)}sign(e,t,i){if(typeof i!=`string`)if(i.constructor.name===`Buffer`)i=i.toString();else throw Error(`Expected payload to be of type string or Buffer.`);let a=new TextEncoder,o=Math.floor(t.getTime()/1e3),s=a.encode(`${e}.${o}.${i}`);return`v1,${n.encode(r.hmac(this.key,s))}`}verifyTimestamp(e){let t=Math.floor(Date.now()/1e3),n=parseInt(e,10);if(isNaN(n))throw new o(`Invalid Signature Headers`);if(t-n>i)throw new o(`Message timestamp too old`);if(n>t+i)throw new o(`Message timestamp too new`);return new Date(n*1e3)}};e.Webhook=s,s.prefix=`whsec_`}))(),C1=class extends Z${unwrap(e,{headers:t,key:n}){if(t!==void 0){let r=n===void 0?this._client.webhookKey:n;if(r===null)throw Error(`Webhook key must not be null in order to unwrap`);new S1.Webhook(r).verify(e,t)}return JSON.parse(e)}},w1=class extends Z${list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/agents/${e}/versions?beta=true`,N$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},T1=class extends Z${constructor(){super(...arguments),this.versions=new w1(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/agents?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r,...i}=t??{};return this._client.get($`/v1/agents/${e}?beta=true`,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/agents/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/agents?beta=true`,N$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/agents/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};T1.Versions=w1;function E1(e,t){if(!e)return()=>{};if(e.aborted)return t.abort(),()=>{};let n=()=>t.abort();return e.addEventListener(`abort`,n),()=>e.removeEventListener(`abort`,n)}function D1(e,t){return e instanceof _&&e.status===t}function O1(e){return e instanceof _&&typeof e.status==`number`&&e.status>=400&&e.status<500}function k1(e){return O1(e)&&!D1(e,408)&&!D1(e,409)&&!D1(e,429)}function A1(e,t,n){return Math.min(t*2**e,n)}function j1(e,t){return e+Math.random()*(t-e)}function M1(e){return e*(1-Math.random()*.25)}function N1(e,{authToken:t,helper:n}){if(!t)throw new a(`copyClientForHelper: expected a non-empty authToken but received ${JSON.stringify(t)}`);let r=e,i=r._options.defaultHeaders,o=r._authState?.extraHeaders,s=Q([o?Object.fromEntries(Object.entries(o).filter(([e])=>{let t=e.toLowerCase();return t!==`authorization`&&t!==`x-api-key`})):void 0,i,{[c1]:n}]);return e.withOptions({apiKey:null,authToken:t,baseURL:e.baseURL,credentials:void 0,defaultHeaders:s})}var P1,F1,I1,L1,R1,z1,B1,V1,H1,U1=1e3,W1=6e4,G1=class{constructor(e){P1.set(this,void 0),F1.set(this,!1),I1.set(this,void 0),L1.set(this,void 0),R1.set(this,void 0),z1.set(this,void 0),B1.set(this,void 0),V1.set(this,void 0),H1.set(this,void 0),this.client=e.client,this.environmentId=e.environmentId,this.environmentKey=e.environmentKey,this.workerId=e.workerId??q1(),X(this,P1,N1(e.client,{authToken:e.environmentKey,helper:`environments-work-poller`}),`f`),X(this,R1,e.autoStop??!0,`f`),X(this,z1,e.drain??!1,`f`),X(this,B1,e.blockMs===void 0?999:e.blockMs,`f`),X(this,V1,e.reclaimOlderThanMs??null,`f`),X(this,H1,e.requestOptions,`f`),X(this,I1,new AbortController,`f`),X(this,L1,E1(e.signal,Z(this,I1,`f`)),`f`)}get signal(){return Z(this,I1,`f`).signal}abort(){Z(this,I1,`f`).abort()}async*[(P1=new WeakMap,F1=new WeakMap,I1=new WeakMap,L1=new WeakMap,R1=new WeakMap,z1=new WeakMap,B1=new WeakMap,V1=new WeakMap,H1=new WeakMap,Symbol.asyncIterator)](){if(Z(this,F1,`f`))throw new a(`Cannot iterate over a consumed WorkPoller`);X(this,F1,!0,`f`);let e=BQ(this.client);e.info(`poller starting`,{component:`work-poller`,environment_id:this.environmentId});try{let t=0;for(;!Z(this,I1,`f`).signal.aborted;){let n;try{n=await Z(this,P1,`f`).beta.environments.work.poll(this.environmentId,{"Anthropic-Worker-ID":this.workerId,...Z(this,B1,`f`)===null?{}:{block_ms:Z(this,B1,`f`)},...Z(this,V1,`f`)===null?{}:{reclaim_older_than_ms:Z(this,V1,`f`)}},{headers:Q([Z(this,H1,`f`)?.headers]),signal:Z(this,I1,`f`).signal})}catch(n){if(Z(this,I1,`f`).signal.aborted)return;if(k1(n))throw e.error(`poll failed permanently, stopping poller`,{error:String(n)}),n;let r=M1(K1(t));e.warn(`poll failed, backing off`,{error:String(n),backoff_ms:r}),t++,await SZ(r,Z(this,I1,`f`).signal);continue}if(t=0,n==null){if(Z(this,z1,`f`))return;await SZ(j1(1e3,3e3),Z(this,I1,`f`).signal);continue}e.info(`claimed work`,{component:`work-poller`,environment_id:this.environmentId,work_id:n.id,work_type:n.data.type});try{await Z(this,P1,`f`).beta.environments.work.ack(n.id,{environment_id:n.environment_id},{headers:Q([Z(this,H1,`f`)?.headers]),signal:Z(this,I1,`f`).signal})}catch(t){e.error(`ack failed`,{work_id:n.id,error:String(t)});continue}try{yield n}finally{if(Z(this,R1,`f`))try{await Z(this,P1,`f`).beta.environments.work.stop(n.id,{environment_id:n.environment_id},{headers:Q([Z(this,H1,`f`)?.headers])})}catch(t){D1(t,409)||e.warn(`stop failed`,{work_id:n.id,error:String(t)})}}}}finally{Z(this,L1,`f`).call(this)}}};function K1(e){return A1(e,U1,W1)}function q1(){let e={}.HOSTNAME;return e?`${e}-${dZ()}`:dZ()}var J1,Y1,X1,Z1=class{constructor(){J1.set(this,[]),Y1.set(this,[]),X1.set(this,!1)}push(e){if(Z(this,X1,`f`))return!1;let t=Z(this,Y1,`f`).shift();return t?t({done:!1,value:e}):Z(this,J1,`f`).push(e),!0}close(){if(!Z(this,X1,`f`))for(X(this,X1,!0,`f`);Z(this,Y1,`f`).length>0;)Z(this,Y1,`f`).shift()({done:!0,value:void 0})}next(e){return Z(this,J1,`f`).length>0?Promise.resolve({done:!1,value:Z(this,J1,`f`).shift()}):Z(this,X1,`f`)||e?.aborted?Promise.resolve({done:!0,value:void 0}):new Promise(t=>{let n=n=>{e?.removeEventListener(`abort`,r),t(n)},r=()=>{let e=Z(this,Y1,`f`).indexOf(n);e>=0&&Z(this,Y1,`f`).splice(e,1),t({done:!0,value:void 0})};Z(this,Y1,`f`).push(n),e?.addEventListener(`abort`,r,{once:!0})})}tryShift(){return Z(this,J1,`f`).shift()}};J1=new WeakMap,Y1=new WeakMap,X1=new WeakMap;var Q1=class extends Error{constructor(e){let t=typeof e==`string`?e:e.map(e=>e.type===`text`?e.text:`[${e.type}]`).join(` `);super(t),this.name=`ToolError`,this.content=e}};function $1(e){return`name`in e?e.name:e.mcp_server_name}function e0(e){return e instanceof Q1?e.content:`Error: ${e instanceof Error?e.message:String(e)}`}async function t0(e,t,n){try{let r=e.parse?e.parse(t):t;return{content:await e.run(r,n),isError:!1}}catch(e){return{content:e0(e),isError:!0}}}var n0,r0,i0,a0,o0,s0,c0,l0,u0,d0,f0,p0,m0,h0,g0,_0,v0,y0,b0,x0,S0,C0,w0,T0,E0,D0,O0,k0,A0,j0,M0,N0,P0=500,F0=1e4,I0=12e4,L0=3e4,R0=3;function z0(e){return e.type===`session.status_idle`&&e.stop_reason?.type===`end_turn`}var B0=class{constructor(e,t){n0.set(this,void 0),r0.set(this,void 0),i0.set(this,new Set),a0.set(this,!1),o0.set(this,void 0),X(this,n0,e,`f`),X(this,r0,t,`f`)}noteEvent(e){e.type!==`user.tool_confirmation`&&(z0(e)?this.arm():this.disarm())}block(e){Z(this,i0,`f`).add(e),Z(this,o0,`f`)!==void 0&&(X(this,a0,!0,`f`),clearTimeout(Z(this,o0,`f`)),X(this,o0,void 0,`f`))}unblock(e){Z(this,i0,`f`).delete(e),Z(this,i0,`f`).size===0&&Z(this,a0,`f`)&&this.arm()}arm(){if(!(Z(this,n0,`f`)<=0)){if(Z(this,i0,`f`).size>0){X(this,a0,!0,`f`);return}X(this,a0,!1,`f`),Z(this,o0,`f`)!==void 0&&clearTimeout(Z(this,o0,`f`)),X(this,o0,setTimeout(Z(this,r0,`f`),Z(this,n0,`f`)),`f`)}}disarm(){X(this,a0,!1,`f`),Z(this,o0,`f`)!==void 0&&(clearTimeout(Z(this,o0,`f`)),X(this,o0,void 0,`f`))}};n0=new WeakMap,r0=new WeakMap,i0=new WeakMap,a0=new WeakMap,o0=new WeakMap;var V0=class{constructor(e,t){s0.add(this),c0.set(this,!1),l0.set(this,void 0),u0.set(this,void 0),d0.set(this,void 0),f0.set(this,void 0),p0.set(this,void 0),m0.set(this,new Set),h0.set(this,new Set),g0.set(this,new Map),_0.set(this,new Map),v0.set(this,new Z1),y0.set(this,0),b0.set(this,null),x0.set(this,void 0),this.client=t.client,this.sessionId=e,this.tools=t.tools,this.maxIdleMs=t.maxIdleMs??6e4,X(this,p0,BQ(t.client),`f`),X(this,f0,new Map(t.tools.map(e=>[$1(e),e])),`f`),X(this,l0,new AbortController,`f`),X(this,u0,E1(t.signal,Z(this,l0,`f`)),`f`),X(this,d0,t.requestOptions,`f`),X(this,x0,new B0(this.maxIdleMs,()=>{Z(this,p0,`f`).info(`session idle after end_turn; stopping`,{component:`session-tool-runner`,session_id:this.sessionId,max_idle_ms:this.maxIdleMs}),Z(this,l0,`f`).abort()}),`f`)}get signal(){return Z(this,l0,`f`).signal}abort(){Z(this,l0,`f`).abort()}async*[(c0=new WeakMap,l0=new WeakMap,u0=new WeakMap,d0=new WeakMap,f0=new WeakMap,p0=new WeakMap,m0=new WeakMap,h0=new WeakMap,g0=new WeakMap,_0=new WeakMap,v0=new WeakMap,y0=new WeakMap,b0=new WeakMap,x0=new WeakMap,s0=new WeakSet,Symbol.asyncIterator)](){if(Z(this,c0,`f`))throw new a(`Cannot iterate over a consumed SessionToolRunner`);X(this,c0,!0,`f`),Z(this,p0,`f`).info(`session tool runner starting`,{component:`session-tool-runner`,session_id:this.sessionId});let e=Z(this,s0,`m`,C0).call(this).catch(e=>{Z(this,l0,`f`).signal.aborted||Z(this,p0,`f`).error(`stream loop failed`,{error:String(e)}),Z(this,l0,`f`).abort()});try{for(;;){let e=await Z(this,v0,`f`).next(Z(this,l0,`f`).signal);if(e.done)break;yield e.value}await e;let t;for(;(t=Z(this,v0,`f`).tryShift())!==void 0;)yield t}finally{Z(this,l0,`f`).abort(),Z(this,x0,`f`).disarm(),await e;try{await Z(this,s0,`m`,N0).call(this)}catch(e){Z(this,p0,`f`).warn(`drain failed`,{error:String(e)})}Z(this,v0,`f`).close();for(let e of this.tools)try{await e.close?.()}catch(t){Z(this,p0,`f`).warn(`tool.close failed`,{tool:$1(e),error:String(t)})}Z(this,u0,`f`).call(this)}}};S0=function(){return{...Z(this,d0,`f`),headers:Q([u1(`session-tool-runner`),Z(this,d0,`f`)?.headers]),signal:Z(this,l0,`f`).signal}},C0=async function(){let e=Z(this,l0,`f`),t=P0;for(;!e.signal.aborted;){try{let e=await this.client.beta.sessions.events.stream(this.sessionId,{},Z(this,s0,`m`,S0).call(this));await Z(this,s0,`m`,w0).call(this);for await(let n of e)if(t=P0,await Z(this,s0,`m`,E0).call(this,n))return}catch(n){if(e.signal.throwIfAborted(),k1(n))throw Z(this,p0,`f`).error(`permanent stream failure, shutting down`,{error:String(n)}),e.abort(),n;Z(this,p0,`f`).warn(`stream disconnected, reconnecting`,{error:String(n),backoff_ms:t})}e.signal.throwIfAborted(),await SZ(t,e.signal),t=Math.min(t*2,F0)}},w0=async function(){let e=Z(this,l0,`f`),t=[],n=!1;try{for await(let e of this.client.beta.sessions.events.list(this.sessionId,{limit:1e3},Z(this,s0,`m`,S0).call(this)))Z(this,s0,`m`,T0).call(this,e,t),n=z0(e)}catch(n){e.signal.throwIfAborted(),Z(this,p0,`f`).warn(`reconcile list failed`,{error:String(n)});for(let e of t)Z(this,m0,`f`).delete(e.id);return}let r=t.filter(e=>!Z(this,h0,`f`).has(e.id));Z(this,x0,`f`).disarm();for(let e of r)await Z(this,s0,`m`,D0).call(this,e);for(let e of[...Z(this,_0,`f`).values()]){let t=Z(this,g0,`f`).get(e.id);t!==void 0&&await Z(this,s0,`m`,k0).call(this,e,t)}let i=r.filter(e=>!Z(this,h0,`f`).has(e.id)&&!Z(this,_0,`f`).has(e.id));n&&i.length===0?Z(this,x0,`f`).arm():Z(this,x0,`f`).disarm()},T0=function(e,t){e.type===`agent.tool_use`||e.type===`agent.custom_tool_use`?(Z(this,m0,`f`).add(e.id),Z(this,h0,`f`).has(e.id)||t.push(e)):e.type===`user.tool_result`?Z(this,h0,`f`).add(e.tool_use_id):e.type===`user.custom_tool_result`?Z(this,h0,`f`).add(e.custom_tool_use_id):e.type===`user.tool_confirmation`&&(Z(this,h0,`f`).has(e.tool_use_id)||Z(this,g0,`f`).set(e.tool_use_id,e.result))},E0=async function(e){switch(Z(this,x0,`f`).noteEvent(e),e.type){case`agent.tool_use`:case`agent.custom_tool_use`:return Z(this,m0,`f`).has(e.id)||(Z(this,m0,`f`).add(e.id),await Z(this,s0,`m`,D0).call(this,e)),!1;case`user.tool_confirmation`:return await Z(this,s0,`m`,O0).call(this,e),!1;case`user.tool_result`:return Z(this,h0,`f`).add(e.tool_use_id),!1;case`user.custom_tool_result`:return Z(this,h0,`f`).add(e.custom_tool_use_id),!1;case`session.status_terminated`:case`session.deleted`:return Z(this,p0,`f`).info(`session terminated`,{component:`session-tool-runner`,session_id:this.sessionId}),Z(this,l0,`f`).abort(),!0;default:return!1}},D0=async function(e){let t=e.evaluated_permission,n=t===`deny`?`deny`:Z(this,g0,`f`).get(e.id);if(n===void 0){t===void 0||t===`allow`?await Z(this,s0,`m`,j0).call(this,e,void 0):Z(this,_0,`f`).has(e.id)||(Z(this,p0,`f`).info(`tool call awaiting confirmation; holding`,{component:`session-tool-runner`,session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),Z(this,_0,`f`).set(e.id,e),Z(this,x0,`f`).block(e.id));return}await Z(this,s0,`m`,k0).call(this,e,n)},O0=async function(e){Z(this,g0,`f`).set(e.tool_use_id,e.result);let t=Z(this,_0,`f`).get(e.tool_use_id);t!==void 0&&await Z(this,s0,`m`,k0).call(this,t,e.result)},k0=async function(e,t){let n=Z(this,_0,`f`).delete(e.id);if(t===`allow`){Z(this,p0,`f`).info(`tool call confirmed`,{component:`session-tool-runner`,session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),n||Z(this,x0,`f`).block(e.id);try{await Z(this,s0,`m`,j0).call(this,e,`allow`)}finally{Z(this,x0,`f`).unblock(e.id)}return}n&&Z(this,x0,`f`).unblock(e.id),Z(this,h0,`f`).add(e.id),Z(this,p0,`f`).info(`tool call denied; not executing`,{component:`session-tool-runner`,session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),Z(this,s0,`m`,A0).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:`deny`})},A0=function(e){Z(this,v0,`f`).push(e)},j0=async function(e,t){var n,r;if(!Z(this,h0,`f`).has(e.id)){Z(this,p0,`f`).info(`executing tool`,{component:`session-tool-runner`,session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),X(this,y0,(n=Z(this,y0,`f`),n++,n),`f`);try{let n=Z(this,f0,`f`).get(e.name);if(!n){Z(this,p0,`f`).info(`tool not owned by this runner; leaving the tool_use_id pending for its owner`,{component:`session-tool-runner`,session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),Z(this,s0,`m`,A0).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:t});return}let r,i,a=new AbortController,o=E1(Z(this,l0,`f`).signal,a),s=setTimeout(()=>a.abort(),I0);try{let t=await t0(n,e.input,{toolUse:e,toolUseBlock:e,signal:a.signal});r=t.content,i=t.isError}finally{clearTimeout(s),o()}let c=H0(e,i,U0(r)),l=await Z(this,s0,`m`,M0).call(this,c,e.id);Z(this,s0,`m`,A0).call(this,{event:e,result:c,toolUseId:e.id,name:e.name,isError:i,posted:l,confirmation:t})}finally{X(this,y0,(r=Z(this,y0,`f`),r--,r),`f`),Z(this,y0,`f`)===0&&Z(this,b0,`f`)?.call(this)}}},M0=async function(e,t){let n=Z(this,l0,`f`),r;for(let i=0;i<R0;i++){n.signal.throwIfAborted();try{return await this.client.beta.sessions.events.send(this.sessionId,{events:[e]},Z(this,s0,`m`,S0).call(this)),Z(this,h0,`f`).add(t),!0}catch(e){if(r=e,k1(e))break;i<R0-1&&await SZ((i+1)*1e3,n.signal)}}return Z(this,p0,`f`).error(`failed to send tool result`,{tool_use_id:t,error:String(r)}),!1},N0=async function(){Z(this,y0,`f`)!==0&&(await Promise.race([new Promise(e=>X(this,b0,e,`f`)),SZ(L0)]),X(this,b0,null,`f`),Z(this,y0,`f`)>0&&Z(this,p0,`f`).warn(`drain timeout exceeded`))};function H0(e,t,n){return e.type===`agent.custom_tool_use`?{type:`user.custom_tool_result`,custom_tool_use_id:e.id,is_error:t,content:n}:{type:`user.tool_result`,tool_use_id:e.id,is_error:t,content:n}}function U0(e){if(typeof e==`string`)return[{type:`text`,text:e||`(no output)`}];let t=e.map(e=>e.type===`text`?{type:`text`,text:e.text||`(no output)`}:e.type===`image`||e.type===`document`?e:e.type===`search_result`?{type:`search_result`,source:e.source,title:e.title,content:e.content.map(e=>({type:`text`,text:e.text})),citations:{enabled:e.citations?.enabled??!1}}:{type:`text`,text:JSON.stringify(e)});return t.length>0?t:[{type:`text`,text:`(no output)`}]}var W0,G0,K0,q0=3e4,J0=`NO_HEARTBEAT`,Y0=class{constructor(e){W0.add(this),G0.set(this,void 0),this.client=e.client,this.environmentId=e.environmentId,this.environmentKey=e.environmentKey,this.tools=e.tools,this.workdir=e.workdir??process.cwd(),this.unrestrictedPaths=e.unrestrictedPaths,this.maxFileBytes=e.maxFileBytes,this.maxIdleMs=e.maxIdleMs,this.workerId=e.workerId,this.requestOptions=e.requestOptions,X(this,G0,e.signal,`f`)}async run(e){let{environmentId:t,environmentKey:n}=this;if(t===void 0||n===void 0)throw new a(`EnvironmentWorker.run: environmentId and environmentKey are required to poll for work`);let r=e??Z(this,G0,`f`),i=new G1({client:this.client,environmentId:t,environmentKey:n,...this.workerId===void 0?{}:{workerId:this.workerId},...r?{signal:r}:{},...this.requestOptions===void 0?{}:{requestOptions:this.requestOptions},autoStop:!1});for await(let e of i)await Z(this,W0,`m`,K0).call(this,e,n,i.signal)}async handleItem(e){let t=e?.workId??EQ(`ANTHROPIC_WORK_ID`),n=e?.environmentId??EQ(`ANTHROPIC_ENVIRONMENT_ID`),r=e?.sessionId??EQ(`ANTHROPIC_SESSION_ID`),i=e?.environmentKey??this.environmentKey??EQ(`ANTHROPIC_ENVIRONMENT_KEY`);if(!t)throw new a(`handleItem: workId is required — pass it or set ANTHROPIC_WORK_ID`);if(!n)throw new a(`handleItem: environmentId is required — pass it or set ANTHROPIC_ENVIRONMENT_ID`);if(!r)throw new a(`handleItem: sessionId is required — pass it or set ANTHROPIC_SESSION_ID`);if(!i)throw new a(`handleItem: environmentKey is required — pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY`);let o={id:t,environment_id:n,data:{type:`session`,id:r}};await Z(this,W0,`m`,K0).call(this,o,i,e?.signal??Z(this,G0,`f`))}};G0=new WeakMap,W0=new WeakSet,K0=async function(e,t,n){let r=BQ(this.client),a=N1(this.client,{authToken:t,helper:`environments-worker`}),o=e.data.id,s={workdir:this.workdir,client:this.client,sessionId:o,...this.unrestrictedPaths===void 0?{}:{unrestrictedPaths:this.unrestrictedPaths},...this.maxFileBytes===void 0?{}:{maxFileBytes:this.maxFileBytes}},c=await i(()=>import(`./node.browser-U-KyT5AW.js`),__vite__mapDeps([2,3])),l=async()=>{};try{l=await c.setupSkills(s)}catch(t){r.warn(`skill setup failed`,{session_id:o,work_id:e.id,error:String(t)})}let u=typeof this.tools==`function`?this.tools(s):this.tools??c.betaAgentToolset20260401(s),d=new AbortController,f=E1(n,d),p=Z0(a,e,d,r,this.requestOptions).catch(t=>{d.signal.aborted||r.error(`heartbeat loop failed`,{work_id:e.id,error:String(t)}),d.abort()});try{let e=new V0(o,{client:a,tools:u,...this.maxIdleMs===void 0?{}:{maxIdleMs:this.maxIdleMs},...this.requestOptions===void 0?{}:{requestOptions:this.requestOptions},signal:d.signal});for await(let t of e);}finally{d.abort(),f(),await p,await l().catch(t=>{r.warn(`skill cleanup failed`,{session_id:o,work_id:e.id,error:String(t)})}),await X0(a,e,r,this.requestOptions)}};async function X0(e,t,n,r){try{await e.beta.environments.work.stop(t.id,{environment_id:t.environment_id,force:!0},{...r,headers:Q([r?.headers])})}catch(e){D1(e,409)||n.error(`force-stop on exit failed`,{work_id:t.id,error:String(e)})}}async function Z0(e,t,n,r,i){let a=q0,o=J0,s=async()=>{try{let s=await e.beta.environments.work.heartbeat(t.id,{environment_id:t.environment_id,expected_last_heartbeat:o},{...i,headers:Q([i?.headers]),signal:n.signal});o=s.last_heartbeat,s.ttl_seconds>0&&(a=Math.max(1e3,Math.min(s.ttl_seconds*1e3/2,q0))),(s.state===`stopping`||s.state===`stopped`)&&(r.info(`heartbeat signals shutdown`,{work_id:t.id,state:s.state}),n.abort()),s.lease_extended||(r.warn(`lease not extended, shutting down`,{work_id:t.id}),n.abort())}catch(e){if(n.signal.throwIfAborted(),k1(e))throw r.error(`permanent heartbeat failure`,{work_id:t.id,error:String(e)}),n.abort(),e;r.warn(`transient heartbeat failure`,{work_id:t.id,error:String(e)})}};for(await s();!n.signal.aborted;)await SZ(a,n.signal),n.signal.throwIfAborted(),await s()}var Q0=class extends Z${retrieve(e,t,n){let{environment_id:r,betas:i}=t;return this._client.get($`/v1/environments/${r}/work/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{environment_id:r,betas:i,...a}=t;return this._client.post($`/v1/environments/${r}/work/${e}?beta=true`,{body:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/environments/${e}/work?beta=true`,N$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}ack(e,t,n){let{environment_id:r,betas:i}=t;return this._client.post($`/v1/environments/${r}/work/${e}/ack?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}heartbeat(e,t,n){let{environment_id:r,desired_ttl_seconds:i,expected_last_heartbeat:a,betas:o}=t;return this._client.post($`/v1/environments/${r}/work/${e}/heartbeat?beta=true`,{query:{desired_ttl_seconds:i,expected_last_heartbeat:a},...n,headers:Q([{"anthropic-beta":[...o??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}poll(e,t={},n){let{betas:r,"Anthropic-Worker-ID":i,...a}=t??{};return this._client.get($`/v1/environments/${e}/work/poll?beta=true`,{query:a,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString(),...i==null?void 0:{"Anthropic-Worker-ID":i}},n?.headers])})}stats(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/environments/${e}/work/stats?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}stop(e,t,n){let{environment_id:r,betas:i,...a}=t;return this._client.post($`/v1/environments/${r}/work/${e}/stop?beta=true`,{body:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}poller(e){return new G1({...e,client:this._client})}worker(e){return new Y0({...e,client:this._client})}};Q0.WorkPoller=G1,Q0.EnvironmentWorker=Y0;var $0=class extends Z${constructor(){super(...arguments),this.work=new Q0(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/environments?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/environments/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/environments/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/environments?beta=true`,N$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/environments/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/environments/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};$0.Work=Q0;var e2=class extends Z${create(e,t,n){let{view:r,betas:i,...a}=t;return this._client.post($`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:r},body:a,...n,headers:Q([{"anthropic-beta":[...i??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get($`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:a,...n,headers:Q([{"anthropic-beta":[...i??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}update(e,t,n){let{memory_store_id:r,view:i,betas:a,...o}=t;return this._client.post($`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{view:i},body:o,...n,headers:Q([{"anthropic-beta":[...a??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/memory_stores/${e}/memories?beta=true`,N$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}delete(e,t,n){let{memory_store_id:r,expected_content_sha256:i,betas:a}=t;return this._client.delete($`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{expected_content_sha256:i},...n,headers:Q([{"anthropic-beta":[...a??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}},t2=class extends Z${retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get($`/v1/memory_stores/${r}/memory_versions/${e}?beta=true`,{query:a,...n,headers:Q([{"anthropic-beta":[...i??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/memory_stores/${e}/memory_versions?beta=true`,N$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}redact(e,t,n){let{memory_store_id:r,betas:i}=t;return this._client.post($`/v1/memory_stores/${r}/memory_versions/${e}/redact?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}},n2=class extends Z${constructor(){super(...arguments),this.memories=new e2(this._client),this.memoryVersions=new t2(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/memory_stores?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`agent-memory-2026-07-22`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/memory_stores/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/memory_stores/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/memory_stores?beta=true`,N$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`agent-memory-2026-07-22`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/memory_stores/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/memory_stores/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}};n2.Memories=e2,n2.MemoryVersions=t2;var r2=class e{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new l$;for await(let t of this.iterator)for(let n of e.decode(t))yield JSON.parse(n);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(t,n){if(!t.body)throw n.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new a(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new a(`Attempted to iterate over a response with no body`);return new e(VZ(t.body),n)}},i2=class extends Z${create(e,t){let{betas:n,user_profile_id:r,...i}=e;return this._client.post(`/v1/messages/batches?beta=true`,{body:i,...t,headers:Q([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString(),...r==null?void 0:{"anthropic-user-profile-id":r}},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/messages/batches/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/messages/batches?beta=true`,M$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/messages/batches/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}async results(e,t={},n){let r=await this.retrieve(e);if(!r.results_url)throw new a(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);let{betas:i}=t??{};return this._client.get(r.results_url,{...n,headers:Q([{"anthropic-beta":[...i??[],`message-batches-2024-09-24`].toString(),Accept:`application/binary`},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>r2.fromResponse(t.response,t.controller))}},a2={"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 o2(e){return e?.output_format??e?.output_config?.format}function s2(e,t,n){let r=o2(t);return!t||!(`parse`in(r??{}))?{...e,content:e.content.map(e=>{if(e.type===`text`){let t=Object.defineProperty({...e},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(t,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return e}),parsed_output:null}:c2(e,t,n)}function c2(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let i=l2(t,e.text);r===null&&(r=i);let a=Object.defineProperty({...e},"parsed_output",{value:i,enumerable:!1});return Object.defineProperty(a,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),i},enumerable:!1})}return e});return{...e,content:i,parsed_output:r}}function l2(e,t){let n=o2(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new a(`Failed to parse structured output: ${e}`)}}var u2=e=>{let t=0,n=[];for(;t<e.length;){let r=e[t];if(r===`\\`){t++;continue}if(r===`{`){n.push({type:`brace`,value:`{`}),t++;continue}if(r===`}`){n.push({type:`brace`,value:`}`}),t++;continue}if(r===`[`){n.push({type:`paren`,value:`[`}),t++;continue}if(r===`]`){n.push({type:`paren`,value:`]`}),t++;continue}if(r===`:`){n.push({type:`separator`,value:`:`}),t++;continue}if(r===`,`){n.push({type:`delimiter`,value:`,`}),t++;continue}if(r===`"`){let i=``,a=!1;for(r=e[++t];r!==`"`;){if(t===e.length){a=!0;break}if(r===`\\`){if(t++,t===e.length){a=!0;break}i+=r+e[t],r=e[++t]}else i+=r,r=e[++t]}r=e[++t],a||n.push({type:`string`,value:i});continue}if(r&&/\s/.test(r)){t++;continue}let i=/[0-9]/;if(r&&i.test(r)||r===`-`||r===`.`){let a=``;for(r===`-`&&(a+=r,r=e[++t]);r&&(i.test(r)||r===`.`||r===`e`||r===`E`||(r===`-`||r===`+`)&&(a[a.length-1]===`e`||a[a.length-1]===`E`));)a+=r,r=e[++t];n.push({type:`number`,value:a});continue}let a=/[a-z]/i;if(r&&a.test(r)){let i=``;for(;r&&a.test(r)&&t!==e.length;)i+=r,r=e[++t];if(i==`true`||i==`false`||i===`null`)n.push({type:`name`,value:i});else{t++;continue}continue}t++}return n},d2=e=>{if(e.length===0)return e;let t=e[e.length-1];switch(t.type){case`separator`:return e=e.slice(0,e.length-1),d2(e);case`number`:let n=t.value[t.value.length-1];if(n===`.`||n===`-`||n===`+`||n===`e`||n===`E`)return e=e.slice(0,e.length-1),d2(e);case`string`:let r=e[e.length-2];if(r?.type===`delimiter`||r?.type===`brace`&&r.value===`{`)return e=e.slice(0,e.length-1),d2(e);break;case`delimiter`:return e=e.slice(0,e.length-1),d2(e)}return e},f2=e=>{let t=[];return e.map(e=>{e.type===`brace`&&(e.value===`{`?t.push(`}`):t.splice(t.lastIndexOf(`}`),1)),e.type===`paren`&&(e.value===`[`?t.push(`]`):t.splice(t.lastIndexOf(`]`),1))}),t.length>0&&t.reverse().map(t=>{t===`}`?e.push({type:`brace`,value:`}`}):t===`]`&&e.push({type:`paren`,value:`]`})}),e},p2=e=>{let t=``;return e.map(e=>{switch(e.type){case`string`:t+=`"`+e.value+`"`;break;default:t+=e.value;break}}),t},m2=e=>JSON.parse(p2(f2(d2(u2(e))))),h2=`__json_buf`;function g2(e,t){let n={};for(let t of Object.keys(e))t!==`input`&&(n[t]=e[t]);Object.defineProperty(n,h2,{value:t,enumerable:!1,writable:!0});let r,i=!1;return Object.defineProperty(n,"input",{enumerable:!0,configurable:!0,get(){return i||=(r=t?m2(t):{},!0),r}}),n}var _2,v2,y2,b2,x2,S2,C2,w2,T2,E2,D2,O2,k2,A2,j2,M2,N2,P2,F2,I2,L2,R2,z2,B2,V2;function H2(e){return e.type===`tool_use`||e.type===`server_tool_use`||e.type===`mcp_tool_use`}var U2=class e{constructor(e,t){_2.add(this),this.messages=[],this.receivedMessages=[],v2.set(this,void 0),y2.set(this,null),this.controller=new AbortController,b2.set(this,void 0),x2.set(this,()=>{}),S2.set(this,()=>{}),C2.set(this,void 0),w2.set(this,()=>{}),T2.set(this,()=>{}),E2.set(this,{}),D2.set(this,!1),O2.set(this,!1),k2.set(this,!1),A2.set(this,!1),j2.set(this,void 0),M2.set(this,void 0),N2.set(this,void 0),I2.set(this,e=>{if(X(this,O2,!0,`f`),l(e)&&(e=new d),e instanceof d)return X(this,k2,!0,`f`),this._emit(`abort`,e);if(e instanceof a)return this._emit(`error`,e);if(e instanceof Error){let t=new a(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new a(String(e)))}),X(this,b2,new Promise((e,t)=>{X(this,x2,e,`f`),X(this,S2,t,`f`)}),`f`),X(this,C2,new Promise((e,t)=>{X(this,w2,e,`f`),X(this,T2,t,`f`)}),`f`),Z(this,b2,`f`).catch(()=>{}),Z(this,C2,`f`).catch(()=>{}),X(this,y2,e,`f`),X(this,N2,t?.logger??console,`f`)}get response(){return Z(this,j2,`f`)}get request_id(){return Z(this,M2,`f`)}async withResponse(){X(this,A2,!0,`f`);let e=await Z(this,b2,`f`);if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get(`request-id`)}}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,r,{logger:i}={}){let a=new e(n,{logger:i});for(let e of n.messages)a._addMessageParam(e);return X(a,y2,{...n,stream:!0},`f`),a._run(()=>a._createMessage(t,{...n,stream:!0},{...r,headers:{...r?.headers,[l1]:`stream`}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit(`end`)},Z(this,I2,`f`))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit(`message`,e)}async _createMessage(e,t,n){let r=n?.signal,i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener(`abort`,i));try{Z(this,_2,`m`,L2).call(this);let{response:r,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(let e of i)Z(this,_2,`m`,R2).call(this,e);if(i.controller.signal?.aborted)throw new d;Z(this,_2,`m`,z2).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(X(this,j2,e,`f`),X(this,M2,e?.headers.get(`request-id`),`f`),Z(this,x2,`f`).call(this,e),this._emit(`connect`))}get ended(){return Z(this,D2,`f`)}get errored(){return Z(this,O2,`f`)}get aborted(){return Z(this,k2,`f`)}abort(){this.controller.abort()}on(e,t){return(Z(this,E2,`f`)[e]||(Z(this,E2,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=Z(this,E2,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(Z(this,E2,`f`)[e]||(Z(this,E2,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{X(this,A2,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){X(this,A2,!0,`f`),await Z(this,C2,`f`)}get currentMessage(){return Z(this,v2,`f`)}async finalMessage(){return await this.done(),Z(this,_2,`m`,P2).call(this)}async finalText(){return await this.done(),Z(this,_2,`m`,F2).call(this)}_emit(e,...t){if(Z(this,D2,`f`))return;e===`end`&&(X(this,D2,!0,`f`),Z(this,w2,`f`).call(this));let n=Z(this,E2,`f`)[e];if(n&&(Z(this,E2,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!Z(this,A2,`f`)&&!n?.length&&Promise.reject(e),Z(this,S2,`f`).call(this,e),Z(this,T2,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!Z(this,A2,`f`)&&!n?.length&&Promise.reject(e),Z(this,S2,`f`).call(this,e),Z(this,T2,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,Z(this,_2,`m`,P2).call(this))}async _fromReadableStream(e,t){let n=t?.signal,r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener(`abort`,r));try{Z(this,_2,`m`,L2).call(this),this._connected(null);let t=p$.fromReadableStream(e,this.controller);for await(let e of t)Z(this,_2,`m`,R2).call(this,e);if(t.controller.signal?.aborted)throw new d;Z(this,_2,`m`,z2).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(v2=new WeakMap,y2=new WeakMap,b2=new WeakMap,x2=new WeakMap,S2=new WeakMap,C2=new WeakMap,w2=new WeakMap,T2=new WeakMap,E2=new WeakMap,D2=new WeakMap,O2=new WeakMap,k2=new WeakMap,A2=new WeakMap,j2=new WeakMap,M2=new WeakMap,N2=new WeakMap,I2=new WeakMap,_2=new WeakSet,P2=function(){if(this.receivedMessages.length===0)throw new a(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},F2=function(){if(this.receivedMessages.length===0)throw new a(`stream ended without producing a Message with role=assistant`);let e=this.receivedMessages.at(-1).content.filter(e=>e.type===`text`).map(e=>e.text);if(e.length===0)throw new a(`stream ended without producing a content block with type=text`);return e.join(` `)},L2=function(){this.ended||X(this,v2,void 0,`f`)},R2=function(e){if(this.ended)return;let t=Z(this,_2,`m`,B2).call(this,e);switch(this._emit(`streamEvent`,e,t),e.type){case`content_block_delta`:{let n=t.content.at(-1);switch(e.delta.type){case`text_delta`:n.type===`text`&&this._emit(`text`,e.delta.text,n.text||``);break;case`citations_delta`:n.type===`text`&&this._emit(`citation`,e.delta.citation,n.citations??[]);break;case`input_json_delta`:if(H2(n)&&Z(this,E2,`f`).inputJson?.length){let t;try{t=n.input}catch(e){Z(this,I2,`f`).call(this,Z(this,_2,`m`,V2).call(this,n,e));break}this._emit(`inputJson`,e.delta.partial_json,t)}break;case`thinking_delta`:n.type===`thinking`&&this._emit(`thinking`,e.delta.thinking,n.thinking);break;case`signature_delta`:n.type===`thinking`&&this._emit(`signature`,n.signature);break;case`compaction_delta`:n.type===`compaction`&&n.content&&this._emit(`compaction`,n.content);break;default:e.delta}break}case`message_stop`:this._addMessageParam(t),this._addMessage(s2(t,Z(this,y2,`f`),{logger:Z(this,N2,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:X(this,v2,t,`f`);break;case`content_block_start`:case`message_delta`:break}},z2=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);let e=Z(this,v2,`f`);if(!e)throw new a(`request ended without sending any chunks`);return X(this,v2,void 0,`f`),s2(e,Z(this,y2,`f`),{logger:Z(this,N2,`f`)})},B2=function(e){let t=Z(this,v2,`f`);if(e.type===`message_start`){if(t)throw new a(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new a(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case`message_stop`:return t;case`message_delta`:return t.container=e.delta.container,t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,e.delta.stop_details!=null&&(t.stop_details=e.delta.stop_details),t.usage.output_tokens=e.usage.output_tokens,t.context_management=e.context_management,e.usage.input_tokens!=null&&(t.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(t.usage.server_tool_use=e.usage.server_tool_use),e.usage.iterations!=null&&(t.usage.iterations=e.usage.iterations),e.usage.fallback_credit!=null&&(t.usage.fallback_credit=e.usage.fallback_credit),t;case`content_block_start`:return t.content.push(e.content_block),e.content_block.type===`fallback`&&(t.model=e.content_block.to.model),t;case`content_block_delta`:{let n=t.content.at(e.index);switch(e.delta.type){case`text_delta`:n?.type===`text`&&(t.content[e.index]={...n,text:(n.text||``)+e.delta.text});break;case`citations_delta`:n?.type===`text`&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case`input_json_delta`:if(n&&H2(n)){let r=(n.__json_buf||``)+e.delta.partial_json;t.content[e.index]=g2(n,r)}break;case`thinking_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case`signature_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,signature:e.delta.signature});break;case`compaction_delta`:n?.type===`compaction`&&(t.content[e.index]={...n,content:(n.content||``)+e.delta.content,encrypted_content:e.delta.encrypted_content});break;default:e.delta}return t}case`content_block_stop`:{let n=t.content.at(e.index);if(n&&H2(n)&&`__json_buf`in n){let e;try{e=n.input}catch(t){e={},Z(this,I2,`f`).call(this,Z(this,_2,`m`,V2).call(this,n,t))}Object.defineProperty(n,"input",{value:e,enumerable:!0,configurable:!0,writable:!0})}return t}}},V2=function(e,t){let n=e[h2];return new a(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${t}. JSON: ${n}`)},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`streamEvent`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new p$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function W2(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var G2=`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:
|
|
216
|
+
`))}function qX(e){let t=[];for(let n of e)if(n._getType()===`tool`)if(typeof n.content==`string`){let e=t[t.length-1];e?._getType()===`human`&&Array.isArray(e.content)&&`type`in e.content[0]&&e.content[0].type===`tool_result`?e.content.push({type:`tool_result`,content:n.content,tool_use_id:n.tool_call_id}):t.push(new Hn({content:[{type:`tool_result`,content:n.content,tool_use_id:n.tool_call_id}]}))}else t.push(new Hn({content:[{type:`tool_result`,...n.content==null?{}:{content:XX(n)},tool_use_id:n.tool_call_id}]}));else t.push(n);return t}function JX(e){if(e.id===void 0)throw Error(`Anthropic requires all tool calls to have an "id".`);return{type:`tool_use`,id:e.id,name:e.name,input:e.args}}function*YX(e,t){let n=[`bash_code_execution_tool_result`,`input_json_delta`,`server_tool_use`,`text_editor_code_execution_tool_result`,`tool_result`,`tool_search_tool_result`,`tool_search_tool_bm25_tool_result`,`tool_search_tool_regex_tool_result`,`tool_use`,`web_search_result`,`web_search_tool_result`],r=[`text`,`text_delta`];for(let i of e){qe(i)&&(yield tt(i,PX));let a=`cache_control`in i?i.cache_control:void 0;if(i.type===`image_url`){let e;typeof i.image_url==`string`?e=KX(i.image_url):typeof i.image_url==`object`&&i.image_url!==null&&`url`in i.image_url&&typeof i.image_url.url==`string`&&(e=KX(i.image_url.url)),e&&(yield{type:`image`,source:e,...a?{cache_control:a}:{}})}else if(NX(i))yield i;else if(i.type===`image`){let e;`url`in i&&typeof i.url==`string`?e=KX(i.url):`data`in i&&(typeof i.data==`string`||i.data instanceof Uint8Array)?e={type:`base64`,media_type:`mimeType`in i&&typeof i.mimeType==`string`?i.mimeType:`image/jpeg`,data:typeof i.data==`string`?i.data:Buffer.from(i.data).toString(`base64`)}:`fileId`in i&&typeof i.fileId==`string`&&(e={type:`file`,file_id:i.fileId}),e&&(yield{type:`image`,source:e,...a?{cache_control:a}:{}})}else if(i.type===`file`){let e;`url`in i&&typeof i.url==`string`?e={type:`url`,url:i.url}:`data`in i&&(typeof i.data==`string`||i.data instanceof Uint8Array)?e={type:`base64`,media_type:`mimeType`in i&&typeof i.mimeType==`string`?i.mimeType:`application/pdf`,data:typeof i.data==`string`?i.data:Buffer.from(i.data).toString(`base64`)}:`fileId`in i&&typeof i.fileId==`string`&&(e={type:`file`,file_id:i.fileId}),e&&(yield{type:`document`,source:e,...a?{cache_control:a}:{}})}else if(i.type===`document`)yield{...i,...a?{cache_control:a}:{}};else if(kX(i))yield{type:`thinking`,thinking:i.thinking,signature:i.signature,...a?{cache_control:a}:{}};else if(AX(i))yield{type:`redacted_thinking`,data:i.data,...a?{cache_control:a}:{}};else if(jX(i))yield{type:`compaction`,content:i.content,...a?{cache_control:a}:{}};else if(MX(i))yield{type:`search_result`,title:i.title,source:i.source,...`cache_control`in i&&i.cache_control?{cache_control:i.cache_control}:{},...`citations`in i&&i.citations?{citations:i.citations}:{},content:i.content};else if(r.find(e=>e===i.type)&&`text`in i)yield{type:`text`,text:i.text,...a?{cache_control:a}:{},...`citations`in i&&i.citations?{citations:i.citations}:{}};else if(n.find(e=>e===i.type)){let n={...i};if(n.type===`input_json_delta`)continue;if(n.type===`tool_use`&&typeof n.input==`string`){let r=t?.find(e=>e.id===n.id);r?n.input=r.args:n.input=e.filter(e=>e.index===n.index&&e.type===`input_json_delta`&&typeof e.input==`string`).reduce((e,t)=>e+t.input,n.input)}if(`index`in n&&delete n.index,`input`in n&&typeof n.input==`string`)try{n.input=JSON.parse(n.input)}catch{n.input={}}yield{...n,...a?{cache_control:a}:{}}}else i.type===`container_upload`&&(yield{...i,...a?{cache_control:a}:{}})}}function XX(e,t){let{content:n}=e;return typeof n==`string`?n:Array.from(YX(n,t))}function ZX(e){let t=qX(e),n;return t.length>0&&t[0]._getType()===`system`&&(n=e[0].content),{messages:QX((n===void 0?t:t.slice(1)).map(e=>{let t;if(e._getType()===`human`)t=`user`;else if(e._getType()===`ai`)t=`assistant`;else if(e._getType()===`tool`)t=`user`;else if(e._getType()===`system`)throw Error(`System messages are only permitted as the first passed message.`);else throw Error(`Message type "${e.type}" is not supported.`);if(An.isInstance(e)&&e.response_metadata?.output_version===`v1`)return{role:t,content:GX(e)};if(An.isInstance(e)&&e.tool_calls?.length){if(typeof e.content==`string`)return e.content===``?{role:t,content:e.tool_calls.map(JX)}:{role:t,content:[{type:`text`,text:e.content},...e.tool_calls.map(JX)]};{let{content:n}=e,r=XX(e,e.tool_calls),i=Array.isArray(r)?r:[{type:`text`,text:r}],a=e.tool_calls.filter(e=>!n.find(t=>(t.type===`tool_use`||t.type===`input_json_delta`||t.type===`server_tool_use`)&&t.id===e.id));return{role:t,content:[...i,...a.map(JX)]}}}else return{role:t,content:XX(e,An.isInstance(e)?e.tool_calls:void 0)}})),system:n}}function QX(e){if(!e||e.length<=1)return e;let t=[],n=e[0],r=e=>typeof e==`string`?[{type:`text`,text:e}]:e,i=e=>e.role!==`user`||typeof e.content==`string`?!1:Array.isArray(e.content)&&e.content.every(e=>e.type===`tool_result`);for(let a=1;a<e.length;a+=1){let o=e[a];i(n)&&i(o)?n={...n,content:[...r(n.content),...r(o.content)]}:(t.push(n),n=o)}return t.push(n),t}var $X=[`claude-opus-4-7`,`claude-opus-4-8`,`claude-opus-5`,`claude-fable-5`,`claude-mythos-5`,`claude-mythos-preview`];function eZ(e,t){return e?t.some(t=>e.startsWith(t)):!1}function tZ(e){return e.type===`enabled`||e.type===`adaptive`}function nZ(e){return eZ(e,[`claude-opus-4-7`])}function rZ(e){return eZ(e,$X)}function iZ(e,t){let n=t&&typeof t==`object`&&`task_budget`in t&&t.task_budget!=null;return nZ(e)&&n?[`task-budgets-2026-03-13`]:[]}function aZ(e){let{model:t,thinking:n,outputConfig:r,topK:i,topP:a,temperature:o}=e,s=rZ(t),c=t??`this model`;if(s&&n.type===`enabled`)throw Error(`thinking.type="enabled" is not supported for ${c}; use thinking.type="adaptive" instead`);if(s&&typeof n==`object`&&n&&`budget_tokens`in n)throw Error(`thinking.budget_tokens is not supported for ${c}; use outputConfig.effort instead`);if(eZ(t,[`claude-opus-5`])&&n.type===`disabled`&&(r?.effort===`xhigh`||r?.effort===`max`))throw Error(`thinking.type="disabled" is not supported for ${c} with outputConfig.effort="${r.effort}"; use thinking.type="adaptive" or omit thinking instead`);if(s){if(i!==void 0)throw Error(`topK is not supported for ${c}; omit topK/topP/temperature or use model prompting instead`);if(a!==void 0&&a!==1)throw Error(`topP is not supported for ${c} when set to non-default values`);if(o!==void 0&&o!==1)throw Error(`temperature is not supported for ${c} when set to non-default values`)}if(tZ(n)){if(i!==void 0)throw Error(`topK is not supported when thinking is enabled`);if(a!==void 0)throw Error(`topP is not supported when thinking is enabled`);if(o!==void 0&&o!==1)throw Error(`temperature is not supported when thinking is enabled`)}}function oZ(e){let{model:t,thinking:n,topK:r,topP:i,temperature:a}=e,o={};return tZ(n)||rZ(t)?o:(a!==void 0&&(o.temperature=a),r!==void 0&&(o.top_k=r),i!==void 0&&(o.top_p=i),o)}function sZ(e,t){let n={model_provider:`anthropic`};if(e.type===`message_start`){let{content:r,usage:i,...a}=e.message,o={};for(let[e,t]of Object.entries(a))t!=null&&(o[e]=t);let{input_tokens:s,output_tokens:c,...l}=i??{},u=lZ(i);return{chunk:new Nn({content:t.coerceContentToString?``:[],additional_kwargs:o,usage_metadata:t.streamUsage?u:void 0,response_metadata:{...n,usage:{...l}},id:e.message.id})}}else if(e.type===`message_delta`){let n={input_tokens:0,output_tokens:e.usage.output_tokens,total_tokens:e.usage.output_tokens},r=FX(()=>{let t={};return`context_management`in e.delta&&(t.context_management=e.delta.context_management),`usage`in e&&`cost`in e.usage&&typeof e.usage.cost==`number`&&(t.usage={cost:e.usage.cost}),t});return{chunk:new Nn({content:t.coerceContentToString?``:[],response_metadata:r,additional_kwargs:{...e.delta},usage_metadata:t.streamUsage?n:void 0})}}else if(e.type===`content_block_start`&&[`tool_use`,`document`,`server_tool_use`,`web_search_tool_result`,`tool_search_tool_result`,`tool_search_tool_bm25_tool_result`,`tool_search_tool_regex_tool_result`].includes(e.content_block.type)){let r=e.content_block,i;return i=r.type===`tool_use`?[{id:r.id,index:e.index,name:r.name,args:``}]:[],{chunk:new Nn({content:t.coerceContentToString?``:[{index:e.index,...e.content_block,input:r.type===`server_tool_use`||r.type===`tool_use`?``:void 0}],response_metadata:n,additional_kwargs:{},tool_call_chunks:i})}}else if(e.type===`content_block_delta`&&[`text_delta`,`citations_delta`,`thinking_delta`,`signature_delta`].includes(e.delta.type)){if(t.coerceContentToString&&`text`in e.delta)return{chunk:new Nn({content:e.delta.text})};{let t=e.delta;return`citation`in t&&(t.citations=[t.citation],delete t.citation),t.type===`thinking_delta`||t.type===`signature_delta`?{chunk:new Nn({content:[{index:e.index,...t,type:`thinking`}],response_metadata:n})}:{chunk:new Nn({content:[{index:e.index,...t,type:`text`}],response_metadata:n})}}}else if(e.type===`content_block_delta`&&e.delta.type===`input_json_delta`)return{chunk:new Nn({content:t.coerceContentToString?``:[{index:e.index,input:e.delta.partial_json,type:e.delta.type}],response_metadata:n,additional_kwargs:{},tool_call_chunks:[{index:e.index,args:e.delta.partial_json}]})};else if(e.type===`content_block_start`&&e.content_block.type===`text`){let r=e.content_block?.text;if(r!==void 0)return{chunk:new Nn({content:t.coerceContentToString?r:[{index:e.index,...e.content_block}],response_metadata:n,additional_kwargs:{}})}}else if(e.type===`content_block_start`&&e.content_block.type===`redacted_thinking`)return{chunk:new Nn({content:t.coerceContentToString?``:[{index:e.index,...e.content_block}],response_metadata:n})};else if(e.type===`content_block_start`&&e.content_block.type===`thinking`){let r=e.content_block.thinking;return{chunk:new Nn({content:t.coerceContentToString?r:[{index:e.index,...e.content_block}],response_metadata:n})}}else if(e.type===`content_block_start`&&jX(e.content_block))return{chunk:new Nn({content:t.coerceContentToString?``:[{index:e.index,...e.content_block}],response_metadata:n})};else if(e.type===`content_block_delta`&&e.delta.type===`compaction_delta`)return{chunk:new Nn({content:t.coerceContentToString?``:[{index:e.index,...e.delta,type:`compaction`}],response_metadata:n})};return null}function cZ(e,t){let n={...t,model_provider:`anthropic`},r=t.usage,i=r==null?void 0:lZ(r);return e.length===1&&e[0].type===`text`?[{text:e[0].text,message:new An({content:e[0].text,additional_kwargs:t,usage_metadata:i,response_metadata:n,id:t.id})}]:[{text:``,message:new An({content:e,additional_kwargs:t,tool_calls:CX(e),usage_metadata:i,response_metadata:n,id:t.id})}]}function lZ(e){let t=e.cache_creation_input_tokens??0,n=e.cache_read_input_tokens??0,r=e.input_tokens+t+n;return{input_tokens:r,output_tokens:e.output_tokens,total_tokens:r+e.output_tokens,input_token_details:{cache_creation:t,cache_read:n}}}function uZ(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}function dZ(e){let t;return t=e.status===400&&typeof e.message==`string`&&e.message.includes(`prompt is too long`)?uZ(be.fromError(e),`CONTEXT_OVERFLOW`):e.status===400&&e.message.includes(`tool`)?ge(uZ(e,`INVALID_TOOL_RESULTS`),!1):e.status===401?ge(uZ(e,`MODEL_AUTHENTICATION`),!1):e.status===404?ge(uZ(e,`MODEL_NOT_FOUND`),!1):e.status===429?ge(uZ(e,`MODEL_RATE_LIMIT`),!0):e,t}var fZ={"claude-sonnet-4-6":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-6":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-fable-5":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-8":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5-20250929":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-5-20251101":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5-20251001":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-7":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-5":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-5":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1-20250805":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0}};async function*pZ(e,t={}){let n=t.streamUsage??!0,r=new Map,i,a={},o=null;for await(let t of e)switch(t.type){case`message_start`:{let{usage:e,id:r,model:a}=t.message;e&&n&&(i=hZ(e)),yield{event:`message-start`,id:r,...i?{usage:i}:{}},yield{event:`provider`,provider:`anthropic`,name:`message_start`,payload:{model:a,id:r}};break}case`message_delta`:o=t.delta.stop_reason,`usage`in t&&`cost`in t.usage&&typeof t.usage.cost==`number`&&(a={usage:{cost:t.usage.cost}}),n&&t.usage&&(i=i?{...i,output_tokens:i.output_tokens+t.usage.output_tokens,total_tokens:i.input_tokens+i.output_tokens+t.usage.output_tokens}:{input_tokens:0,output_tokens:t.usage.output_tokens,total_tokens:t.usage.output_tokens},yield{event:`usage`,usage:i}),`context_management`in t.delta&&t.delta.context_management&&(yield{event:`provider`,provider:`anthropic`,name:`context_management`,payload:t.delta.context_management});break;case`message_stop`:yield{event:`message-finish`,reason:mZ(o),...i?{usage:i}:{},metadata:{model_provider:`anthropic`},responseMetadata:a};break;case`content_block_start`:{let{index:e,content_block:n}=t,i=gZ(n,e);r.set(e,{...i}),yield{event:`content-block-start`,index:e,content:i};break}case`content_block_delta`:{let{index:e,delta:n}=t,i=r.get(e);if(!i)break;let{contentDelta:a,accumulated:o}=_Z(i,n);r.set(e,o),yield{event:`content-block-delta`,index:e,delta:a};break}case`content_block_stop`:{let{index:e}=t,n=r.get(e);if(!n)break;yield{event:`content-block-finish`,index:e,content:vZ(n)},r.delete(e);break}default:yield{event:`provider`,provider:`anthropic`,name:t.type,payload:t};break}}function mZ(e){switch(e){case`end_turn`:case`stop_sequence`:return`stop`;case`tool_use`:return`tool_use`;case`max_tokens`:return`length`;default:return`stop`}}function hZ(e){let t=e.cache_creation_input_tokens??0,n=e.cache_read_input_tokens??0,r=e.input_tokens+t+n;return{input_tokens:r,output_tokens:e.output_tokens,total_tokens:r+e.output_tokens,input_token_details:{cache_creation:t,cache_read:n}}}function gZ(e,t){switch(e.type){case`text`:return{type:`text`,text:e.text??``,index:t};case`thinking`:return{type:`reasoning`,reasoning:e.thinking??``,index:t};case`redacted_thinking`:return{type:`non_standard`,value:{...e},index:t};case`tool_use`:return{type:`tool_call_chunk`,id:e.id,name:e.name,args:``,index:t};case`server_tool_use`:return{type:`server_tool_call_chunk`,id:e.id,name:e.name,args:``,index:t};default:return{type:`non_standard`,value:{...e},index:t}}}function _Z(e,t){switch(t.type){case`text_delta`:return{contentDelta:{type:`text-delta`,text:t.text},accumulated:{...e,text:(e.text??``)+t.text}};case`thinking_delta`:return{contentDelta:{type:`reasoning-delta`,reasoning:t.thinking},accumulated:{...e,reasoning:(e.reasoning??``)+t.thinking}};case`input_json_delta`:{let n=(e.args??``)+t.partial_json;return{contentDelta:{type:`block-delta`,fields:{type:e.type,args:n}},accumulated:{...e,args:n}}}case`citations_delta`:{let n=[...e.annotations??[],t.citation];return{contentDelta:{type:`block-delta`,fields:{type:e.type,annotations:n}},accumulated:{...e,annotations:n}}}case`signature_delta`:return{contentDelta:{type:`block-delta`,fields:{type:e.type,signature:t.signature}},accumulated:{...e,signature:t.signature}};case`compaction_delta`:return{contentDelta:{type:`block-delta`,fields:{type:`non_standard`,value:{...e.value??{},compaction:t}}},accumulated:{...e,value:{...e.value??{},compaction:t}}};default:return{contentDelta:{type:`block-delta`,fields:{type:e.type,...t}},accumulated:e}}}function vZ(e){if(e.type===`tool_call_chunk`||e.type===`server_tool_call_chunk`){let t=e.type===`tool_call_chunk`?`tool_call`:`server_tool_call`,n;try{n=JSON.parse(e.args||`{}`)}catch{return{type:`invalid_tool_call`,id:e.id,name:e.name,args:e.args,error:`Failed to parse tool call arguments as JSON`}}return{type:t,id:e.id,name:e.name,args:n}}let{index:t,...n}=e;return n}function X(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function Z(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var yZ=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return yZ=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))},bZ=/^[a-z][a-z0-9+.-]*:/i,xZ=e=>bZ.test(e),SZ=e=>(SZ=Array.isArray,SZ(e)),CZ=SZ;function wZ(e){return typeof e==`object`?e??{}:{}}function TZ(e){if(!e)return!0;for(let t in e)return!1;return!0}function EZ(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var DZ=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new a(`${e} must be an integer`);if(t<0)throw new a(`${e} must be a positive integer`);return t},OZ=e=>{try{return JSON.parse(e)}catch{return}},kZ=(e,t)=>{let n=e[t];return delete e[t],n},AZ=(e,t)=>new Promise(n=>{if(t?.aborted)return n();let r=()=>{clearTimeout(i),n()},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n()},e);t?.addEventListener(`abort`,r,{once:!0})}),jZ=`0.115.0`,MZ=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function NZ(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var PZ=()=>{let e=NZ();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":jZ,"X-Stainless-OS":LZ(Deno.build.os),"X-Stainless-Arch":IZ(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":jZ,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":jZ,"X-Stainless-OS":LZ(globalThis.process.platform??`unknown`),"X-Stainless-Arch":IZ(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=FZ();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":jZ,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":jZ,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function FZ(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{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/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var IZ=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,LZ=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),RZ,zZ=()=>RZ??=PZ(),BZ=new WeakMap,VZ=typeof globalThis.FinalizationRegistry==`function`?new globalThis.FinalizationRegistry(e=>GZ(e)):null;function HZ(e,t){return()=>e.removeEventListener(`abort`,t)}function UZ(e,t,n){BZ.set(e,HZ(t,n))}function WZ(e,t){BZ.has(t)&&VZ?.register(e,t,t)}function GZ(e){let t=BZ.get(e);t&&(BZ.delete(e),VZ?.unregister(e),t())}function KZ(){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 qZ(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function JZ(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return qZ({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function YZ(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function XZ(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var ZZ=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),QZ=`RFC3986`,$Z=e=>String(e),eQ={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:$Z},tQ=(e,t)=>(tQ=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),tQ(e,t)),nQ=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),rQ=1024,iQ=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=rQ){let t=a.length>=rQ?a.slice(e,e+rQ):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=nQ[r];continue}if(r<2048){n[n.length]=nQ[192|r>>6]+nQ[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=nQ[224|r>>12]+nQ[128|r>>6&63]+nQ[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=nQ[240|r>>18]+nQ[128|r>>12&63]+nQ[128|r>>6&63]+nQ[128|r&63]}o+=n.join(``)}return o};function aQ(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function oQ(e,t){if(SZ(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var sQ={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},cQ=function(e,t){Array.prototype.push.apply(e,SZ(t)?t:[t])},lQ,uQ={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:iQ,encodeValuesOnly:!1,format:QZ,formatter:$Z,indices:!1,serializeDate(e){return(lQ??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function dQ(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var fQ={};function pQ(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,ee=!1;for(;(y=y.get(fQ))!==void 0&&!ee;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);ee=!0}y.get(fQ)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&SZ(v)&&(v=oQ(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,uQ.encoder,g,`key`,p):t;v=``}if(dQ(v)||aQ(v)){if(c){let e=h?t:c(t,uQ.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,uQ.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let te=[];if(v===void 0)return te;let ne;if(n===`comma`&&SZ(v))h&&c&&(v=oQ(v,c)),ne=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(SZ(l))ne=l;else{let e=Object.keys(v);ne=u?e.sort(u):e}let x=s?String(t).replace(/\./g,`%2E`):String(t),re=r&&SZ(v)&&v.length===1?x+`[]`:x;if(i&&SZ(v)&&v.length===0)return re+`[]`;for(let t=0;t<ne.length;++t){let y=ne[t],ee=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&ee===null)continue;let x=d&&s?y.replace(/\./g,`%2E`):y,ie=SZ(v)?typeof n==`function`?n(re,x):re:re+(d?`.`+x:`[`+x+`]`);_.set(e,b);let ae=new WeakMap;ae.set(fQ,_),cQ(te,pQ(ee,ie,n,r,i,a,o,s,n===`comma`&&h&&SZ(v)?null:c,l,u,d,f,p,m,h,g,ae))}return te}function mQ(e=uQ){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||uQ.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=QZ;if(e.format!==void 0){if(!tQ(eQ,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=eQ[n],i=uQ.filter;(typeof e.filter==`function`||SZ(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in sQ?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:uQ.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:uQ.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:uQ.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:uQ.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:uQ.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?uQ.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:uQ.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:uQ.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:uQ.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:uQ.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:uQ.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:uQ.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:uQ.strictNullHandling}}function hQ(e,t={}){let n=e,r=mQ(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):SZ(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=sQ[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||cQ(o,pQ(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function gQ(e){return hQ(e,{arrayFormat:`brackets`})}var _Q=`urn:ietf:params:oauth:grant-type:jwt-bearer`,vQ=`refresh_token`,yQ=`/v1/oauth/token`,bQ=`oauth-2025-04-20`,xQ=`oidc-federation-2026-04-01`,SQ=1<<20;function CQ(e){if(!e)return;let t;try{t=new URL(e)}catch(t){throw new jQ(`Invalid token endpoint base URL "${e}": ${t}`)}if(t.protocol===`https:`)return;let n=t.hostname.toLowerCase().replace(/^\[|\]$/g,``);if(!(t.protocol===`http:`&&(n===`localhost`||n===`127.0.0.1`||n===`::1`)))throw new jQ(`Refusing to send credential over non-https token endpoint "${e}"`)}async function wQ(e,t){let n=await AQ(e),r;try{r=JSON.parse(n)}catch{throw new jQ(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,DQ(n),t)}if(!r.access_token)throw new jQ(`Token endpoint response missing access_token: ${JSON.stringify(DQ(r))}`,e.status,DQ(r),t);if(r.token_type&&r.token_type.toLowerCase()!==`bearer`)throw new jQ(`Token endpoint response: unsupported token_type "${r.token_type}" (want Bearer)`,e.status,DQ(r),t);return r}var TQ=2e3,EQ=new Set([`error`,`error_description`,`error_uri`]);function DQ(e){if(e==null)return e;if(typeof e==`string`){let t;try{t=JSON.parse(e)}catch{return e.length<=TQ?e:e.slice(0,TQ)+`... <${e.length-TQ} more chars>`}return JSON.stringify(DQ(t))}if(typeof e==`object`&&!Array.isArray(e)){let t={};for(let[n,r]of Object.entries(e))EQ.has(n)&&(t[n]=r);return t}return null}async function OQ(t,n=e=>console.warn(`anthropic-sdk: ${e}`)){if(typeof process>`u`||process.platform===`win32`)return;let r=await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1])),a=t,o;try{a=await r.promises.realpath(t),o=await r.promises.stat(a)}catch{return}let s=o.mode&511;if(s&18)throw new jQ(`Credentials file at ${a} is group/world-writable (mode 0o${s.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${a}\`.`);if(s&36)throw new jQ(`Credentials file at ${a} is group/world-readable (mode 0o${s.toString(8)}); run \`chmod 600 ${a}\` before retrying.`);typeof process.getuid==`function`&&o.uid!==process.getuid()&&n(`credentials file at ${a} is owned by uid ${o.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function kQ(t,n){let r=await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1])),a=(await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1]))).dirname(t);await r.promises.mkdir(a,{recursive:!0,mode:448});let o=`${t}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{let e=await r.promises.open(o,`w`,384);try{await e.writeFile(JSON.stringify(n,null,2)),await e.sync()}finally{await e.close()}await r.promises.rename(o,t)}catch(e){throw await r.promises.unlink(o).catch(()=>{}),e}try{let e=await r.promises.open(a,`r`);try{await e.sync()}finally{await e.close()}}catch{}}async function AQ(e){if(!e.body)return``;let t=e.body.getReader(),n=[],r=0;for(;;){let{done:e,value:i}=await t.read();if(e)break;if(r+i.length>SQ){let e=SQ-r;e>0&&n.push(i.subarray(0,e)),await t.cancel();break}n.push(i),r+=i.length}let i;if(n.length===1)i=n[0];else{i=new Uint8Array(n.reduce((e,t)=>e+t.length,0));let e=0;for(let t of n)i.set(t,e),e+=t.length}return new TextDecoder(`utf-8`).decode(i)}var jQ=class extends a{constructor(e,t=null,n=null,r=null){super(e),this.statusCode=t,this.body=n,this.requestId=r}};function MQ(){return Math.floor(Date.now()/1e3)}var NQ=class{constructor(e,t){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=e,this.onAdvisoryRefreshError=t}async getToken(){let e=this.nextForce;this.nextForce=!1;let t=this.cached;if(e||t==null)return(await this.refresh(e)).token;if(t.expiresAt==null)return t.token;let n=t.expiresAt-MQ();return n>120?t.token:n>30?(this.backgroundRefresh(),t.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(e=!1){return this.pendingRefresh&&!e?this.pendingRefresh:this.doRefresh(e)}backgroundRefresh(){this.pendingRefresh||MQ()-this.lastAdvisoryError<5||this.doRefresh().catch(e=>{this.lastAdvisoryError=MQ(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(e=>(this.cached=e,this.pendingRefresh=null,e),e=>{throw this.pendingRefresh=null,e}),this.pendingRefresh}},PQ=e=>{if(globalThis.process!==void 0)return{}[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0};function FQ(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var IQ;function LQ(e){let t;return(IQ??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var RQ;function zQ(e){let t;return(RQ??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var BQ=`warn`,VQ={off:0,error:200,warn:300,info:400,debug:500},HQ=(e,t,n)=>{if(e){if(EZ(VQ,e))return e;n.warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(VQ))}`)}};function UQ(){}function WQ(e,t,n){return!t||VQ[e]>VQ[n]?UQ:t[e].bind(t)}var GQ={error:UQ,warn:UQ,info:UQ,debug:UQ},KQ=new WeakMap;function qQ(e,t){let n=KQ.get(e);if(n&&n[0]===t)return n[1];let r={error:WQ(`error`,e,t),warn:WQ(`warn`,e,t),info:WQ(`info`,e,t),debug:WQ(`debug`,e,t)};return KQ.set(e,[t,r]),r}function JQ(e){let t=e.logger,n=e.logLevel??`off`;return t?qQ(t,n):GQ}var YQ,XQ;function ZQ(){let e=PQ(`ANTHROPIC_LOG`);return(!XQ||e!==YQ)&&(YQ=e,XQ=qQ(console,HQ(e,`process.env['ANTHROPIC_LOG']`,qQ(console,`warn`))??`warn`)),XQ}var QQ=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`api-key`||e.toLowerCase()===`x-api-key`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),$Q=/^[A-Za-z0-9_.-]+$/;function e$(e){if(!e)throw Error(`profile name is empty`);if(e===`.`||e===`..`)throw Error(`profile name "${e}" is not allowed`);if(e.includes(`/`)||e.includes(`\\`))throw Error(`profile name "${e}" must not contain path separators`);if(!$Q.test(e))throw Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var t$=async t=>{var n,r;let a=await r$();if(a===null)return null;let o=t??await a$();if(o===null)return null;e$(o);let s=await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1])),c=(await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1]))).join(a,`configs`,`${o}.json`),l;try{l=await s.promises.readFile(c,`utf-8`)}catch(e){if(e?.code!==`ENOENT`)throw Error(`failed to read config file ${c}: ${e}`);l=null}if(l===null){let e=PQ(`ANTHROPIC_ORGANIZATION_ID`),t=PQ(`ANTHROPIC_IDENTITY_TOKEN_FILE`),n=PQ(`ANTHROPIC_FEDERATION_RULE_ID`);return n&&e?{fromFile:!1,config:{organization_id:e,workspace_id:PQ(`ANTHROPIC_WORKSPACE_ID`),base_url:PQ(`ANTHROPIC_BASE_URL`),authentication:{type:`oidc_federation`,federation_rule_id:n,service_account_id:PQ(`ANTHROPIC_SERVICE_ACCOUNT_ID`),identity_token:t?{source:`file`,path:t}:void 0,scope:PQ(`ANTHROPIC_SCOPE`)}}}:null}let u;try{u=JSON.parse(l)}catch(e){throw Error(`failed to parse config file ${c}: ${e}`)}if(!u.authentication)throw Error(`config file ${c} is missing "authentication"`);let d=u.authentication.type;if(d!==`oidc_federation`&&d!==`user_oauth`)throw Error(`authentication.type "${d}" is not a known authentication type`);if(u.organization_id??=PQ(`ANTHROPIC_ORGANIZATION_ID`),u.workspace_id??=PQ(`ANTHROPIC_WORKSPACE_ID`),u.base_url??=PQ(`ANTHROPIC_BASE_URL`),(n=u.authentication).scope??(n.scope=PQ(`ANTHROPIC_SCOPE`)),u.authentication.type===`oidc_federation`){if(!u.authentication.identity_token){let e=PQ(`ANTHROPIC_IDENTITY_TOKEN_FILE`);e&&(u.authentication.identity_token={source:`file`,path:e})}u.authentication.federation_rule_id||(u.authentication.federation_rule_id=PQ(`ANTHROPIC_FEDERATION_RULE_ID`)??``),(r=u.authentication).service_account_id??(r.service_account_id=PQ(`ANTHROPIC_SERVICE_ACCOUNT_ID`))}return{config:u,fromFile:!0}},n$=async(t,n)=>{if(t?.authentication.credentials_path)return t.authentication.credentials_path;let r=await r$();if(!r)return null;let a=n??await a$();return a?(e$(a),(await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1]))).join(r,`credentials`,`${a}.json`)):null},r$=async()=>{if(!i$())return null;let t=await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1])),n=PQ(`ANTHROPIC_CONFIG_DIR`);if(n)return n;if(zZ()[`X-Stainless-OS`]===`Windows`){let e=PQ(`APPDATA`);if(e)return t.join(e,`Anthropic`);let n=PQ(`USERPROFILE`);return n?t.join(n,`AppData`,`Roaming`,`Anthropic`):null}let r=PQ(`XDG_CONFIG_HOME`);if(r)return t.join(r,`anthropic`);let a=PQ(`HOME`);return a?t.join(a,`.config`,`anthropic`):null},i$=()=>{let e=zZ()[`X-Stainless-Runtime`];return e===`node`||e===`deno`},a$=async()=>{let t=await r$();if(!t)return null;let n=PQ(`ANTHROPIC_PROFILE`);if(n)return n;let r=await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1])),a=(await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1]))).join(t,`active_config`);try{return(await r.promises.readFile(a,`utf-8`)).trim()||`default`}catch(e){if(e?.code!==`ENOENT`)throw Error(`failed to read ${a}: ${e}`);return`default`}};function o$(t){if(!t)throw new a(`Identity token file path is empty`);return async()=>{let n=await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1])),r;try{r=await n.promises.readFile(t,`utf-8`)}catch(e){throw new a(`Failed to read identity token file at ${t}: ${e}`)}let o=r.trim();if(!o)throw new a(`Identity token file at ${t} is empty`);return o}}function s$(e){if(!e)throw new a(`Identity token value is empty`);return()=>e}function c$(e){return async()=>{CQ(e.baseURL);let t=await e.identityTokenProvider();if(t.length>16*1024)throw new jQ(`Identity token is ${Math.ceil(t.length/1024)} KiB, exceeds the 16 KiB assertion limit`);let n={grant_type:_Q,assertion:t,federation_rule_id:e.federationRuleId,organization_id:e.organizationId};e.serviceAccountId&&(n.service_account_id=e.serviceAccountId),e.workspaceId&&(n.workspace_id=e.workspaceId);let r=`${e.baseURL}${yQ}`,i;try{i=await e.fetch(r,{method:`POST`,headers:{"Content-Type":`application/json`,"anthropic-beta":`${bQ},${xQ}`,"User-Agent":e.userAgent||`anthropic-sdk-typescript/0.115.0 oidcFederationProvider`},body:JSON.stringify(n)})}catch(e){throw new jQ(`Failed to reach token endpoint ${r}: ${e}`)}let a=i.headers.get(`Request-Id`);if(!i.ok){let t=DQ(await i.text().catch(()=>``)),n=``;throw i.status===401&&(n=` Ensure your federation rule matches your identity token. ${e.workspaceId?``:"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new jQ(`Token exchange failed with status ${i.status}${a?` (request-id ${a})`:``}: ${t}${n}`,i.status,t,a)}let o=await wQ(i,a),s=Number(o.expires_in);if(!Number.isFinite(s))throw new jQ(`Token endpoint response missing required fields: ${JSON.stringify(DQ(o))}`,i.status,DQ(o),a);return{token:o.access_token,expiresAt:MQ()+s}}}function l$(t){return async n=>{let r=await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1]));await OQ(t.credentialsPath,t.onSafetyWarning);let a;try{a=await r.promises.readFile(t.credentialsPath,`utf-8`)}catch(e){throw new jQ(`Credentials file not found at ${t.credentialsPath}: ${e}`)}let o;try{o=JSON.parse(a)}catch(e){throw new jQ(`Credentials file at ${t.credentialsPath} is not valid JSON: ${e}`)}let s=o.access_token;if(!s)throw new jQ(`Credentials file at ${t.credentialsPath} must include 'access_token'`);let c=o.expires_at;if(!n?.forceRefresh&&(c==null||MQ()<c-30))return{token:s,expiresAt:c??null};let l=o.refresh_token;if(!t.clientId||!l)throw new jQ(`Access token at ${t.credentialsPath} has expired and no refresh is available (client_id ${t.clientId?`set`:`empty`}, refresh_token ${l?`set`:`empty`})`);CQ(t.baseURL);let u={grant_type:vQ,refresh_token:l,client_id:t.clientId},d=`${t.baseURL}${yQ}`,f;try{f=await t.fetch(d,{method:`POST`,headers:{"Content-Type":`application/json`,"anthropic-beta":bQ,"User-Agent":t.userAgent||`anthropic-sdk-typescript/0.115.0 userOAuthProvider`},body:JSON.stringify(u)})}catch(e){throw new jQ(`User OAuth refresh failed to reach token endpoint: ${e}`)}let p=f.headers.get(`Request-Id`);if(!f.ok){let e=await f.text().catch(()=>``);throw new jQ(`User OAuth refresh failed (HTTP ${f.status}): ${DQ(e)}`,f.status,DQ(e),p)}let m=await wQ(f,p),h=Number(m.expires_in);if(!Number.isFinite(h))throw new jQ(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(DQ(m))}`,f.status,DQ(m),p);let g=MQ()+h,_=m.refresh_token||l;return await kQ(t.credentialsPath,{...o,version:`1.0`,type:`oauth_token`,access_token:m.access_token,expires_at:g,refresh_token:_}),{token:m.access_token,expiresAt:g}}}function u$(e,t){let n=f$(e,e.authentication.credentials_path??null,(e.base_url||t.baseURL).replace(/\/+$/,``),t),r={};return e.workspace_id&&e.authentication.type===`user_oauth`&&(r[`anthropic-workspace-id`]=e.workspace_id),{provider:n,extraHeaders:r,baseURL:e.base_url||void 0}}async function d$(e,t){let n=await t$(t);if(!n)return null;let{config:r,fromFile:i}=n;return u$(r.authentication.credentials_path||!i?r:{...r,authentication:{...r.authentication,credentials_path:await n$(r,t)??void 0}},e)}function f$(e,t,n,r){switch(e.authentication.type){case`oidc_federation`:{let i=e.authentication,a=p$(i);if(!a)throw new jQ(`oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)`);if(!i.federation_rule_id)throw new jQ(`oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).`);if(!e.organization_id)throw new jQ(`oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)`);let o=c$({identityTokenProvider:a,federationRuleId:i.federation_rule_id,organizationId:e.organization_id,serviceAccountId:i.service_account_id,workspaceId:e.workspace_id,baseURL:n,fetch:r.fetch,userAgent:r.userAgent});return t?m$(o,t,r.onCacheWriteError,r.onSafetyWarning):o}case`user_oauth`:if(!t)throw new jQ(`user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)`);return l$({credentialsPath:t,clientId:e.authentication.client_id,baseURL:n,fetch:r.fetch,userAgent:r.userAgent,onSafetyWarning:r.onSafetyWarning});default:{let t=e.authentication.type;throw new jQ(`authentication.type "${t}" is not a known authentication type`)}}}function p$(e){if(e.identity_token){let t=e.identity_token.source;if(t!==`file`)throw new jQ(`identity_token.source "${t}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new jQ(`identity_token.source "file" requires a non-empty path`);return o$(e.identity_token.path)}let t=PQ(`ANTHROPIC_IDENTITY_TOKEN_FILE`);if(t)return o$(t);let n=PQ(`ANTHROPIC_IDENTITY_TOKEN`);return n?s$(n):null}function m$(t,n,r,a){return async o=>{let s=await i(()=>import(`./__vite-browser-external-COxE8F0G.js`).then(t=>e(t.default,1)),__vite__mapDeps([0,1]));await OQ(n,a);let c;try{let e=await s.promises.readFile(n,`utf-8`);c=JSON.parse(e);let t=c?.access_token;if(t&&!o?.forceRefresh){let e=c?.expires_at;if(e==null||MQ()<e-30)return{token:t,expiresAt:e??null}}}catch(e){e?.code!==`ENOENT`&&!(e instanceof SyntaxError)&&r?.(e)}let l=await t(o);try{await kQ(n,{...c??{},version:`1.0`,type:`oauth_token`,access_token:l.token,expires_at:l.expiresAt})}catch(e){r?.(e)}return l}}var h$,g$,_$=class{constructor(){h$.set(this,void 0),g$.set(this,void 0),X(this,h$,new Uint8Array,`f`),X(this,g$,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?LQ(e):e;X(this,h$,FQ([Z(this,h$,`f`),t]),`f`);let n=[],r;for(;(r=v$(Z(this,h$,`f`),Z(this,g$,`f`)))!=null;){if(r.carriage&&Z(this,g$,`f`)==null){X(this,g$,r.index,`f`);continue}if(Z(this,g$,`f`)!=null&&(r.index!==Z(this,g$,`f`)+1||r.carriage)){n.push(zQ(Z(this,h$,`f`).subarray(0,Z(this,g$,`f`)-1))),X(this,h$,Z(this,h$,`f`).subarray(Z(this,g$,`f`)),`f`),X(this,g$,null,`f`);continue}let e=Z(this,g$,`f`)===null?r.preceding:r.preceding-1,t=zQ(Z(this,h$,`f`).subarray(0,e));n.push(t),X(this,h$,Z(this,h$,`f`).subarray(r.index),`f`),X(this,g$,null,`f`)}return n}flush(){return Z(this,h$,`f`).length?this.decode(`
|
|
217
|
+
`):[]}};h$=new WeakMap,g$=new WeakMap,_$.NEWLINE_CHARS=new Set([`
|
|
218
|
+
`,`\r`]),_$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function v$(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function y$(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}var b$,x$=class e{constructor(e,t,n){this.iterator=e,b$.set(this,void 0),this.controller=t,X(this,b$,n,`f`)}static rawEvents(e,t=new AbortController){return S$(e,t)}static fromSSEResponse(t,n,r){let i=!1,o=r?JQ(r):console;async function*s(){if(i)throw new a("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let e of S$(t,n)){if(e.event===`completion`)try{yield JSON.parse(e.data)}catch(t){throw o.error(`Could not parse message into JSON:`,e.data),o.error(`From chunk:`,e.raw),t}if(e.event===`message_start`||e.event===`message_delta`||e.event===`message_stop`||e.event===`content_block_start`||e.event===`content_block_delta`||e.event===`content_block_stop`||e.event===`message`||e.event===`user.message`||e.event===`user.interrupt`||e.event===`user.tool_confirmation`||e.event===`user.custom_tool_result`||e.event===`user.tool_result`||e.event===`agent.message`||e.event===`agent.thinking`||e.event===`agent.tool_use`||e.event===`agent.tool_result`||e.event===`agent.mcp_tool_use`||e.event===`agent.mcp_tool_result`||e.event===`agent.custom_tool_use`||e.event===`agent.thread_context_compacted`||e.event===`session.status_running`||e.event===`session.status_idle`||e.event===`session.status_rescheduled`||e.event===`session.status_terminated`||e.event===`session.error`||e.event===`session.deleted`||e.event===`session.updated`||e.event===`span.model_request_start`||e.event===`span.model_request_end`||e.event===`span.outcome_evaluation_start`||e.event===`span.outcome_evaluation_ongoing`||e.event===`span.outcome_evaluation_end`||e.event===`user.define_outcome`||e.event===`agent.thread_message_received`||e.event===`agent.thread_message_sent`||e.event===`agent.session_thread_message_received`||e.event===`agent.session_thread_message_sent`||e.event===`session.thread_created`||e.event===`session.thread_status_created`||e.event===`session.thread_status_running`||e.event===`session.thread_status_idle`||e.event===`session.thread_status_rescheduled`||e.event===`session.thread_status_terminated`||e.event===`event_start`||e.event===`event_delta`||e.event===`system.message`)try{yield JSON.parse(e.data)}catch(t){throw o.error(`Could not parse message into JSON:`,e.data),o.error(`From chunk:`,e.raw),t}if(e.event!==`ping`&&e.event===`error`){let n=OZ(e.data)??e.data,r=n?.error?.type;throw new _(void 0,n,void 0,t.headers,r)}}e=!0}catch(e){if(l(e))return;throw e}finally{e||n.abort(),GZ(n)}}return new e(s,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*o(){let e=new _$,n=YZ(t);for await(let t of n)for(let n of e.decode(t))yield n;for(let t of e.flush())yield t}async function*s(){if(i)throw new a("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of o())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(l(e))return;throw e}finally{e||n.abort(),GZ(n)}}return new e(s,n,r)}[(b$=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,Z(this,b$,`f`)),new e(()=>i(n),this.controller,Z(this,b$,`f`))]}toReadableStream(){let e=this,t;return qZ({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=LQ(JSON.stringify(n)+`
|
|
219
|
+
`);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*S$(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new a(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new a(`Attempted to iterate over a response with no body`);let n=new w$,r=new _$,i=YZ(e.body);for await(let e of C$(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*C$(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?LQ(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=y$(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var w$=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
|
|
220
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=T$(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function T$(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function E$(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return JQ(e).debug(`response`,n.status,n.url,n.headers,n.body),x$.fromSSEResponse(n,t.controller);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:D$(await n.json(),n):await n.text()})().finally(()=>{!t.options.stream&&!t.options.__binaryResponse&&GZ(t.controller)});return JQ(e).debug(`[${r}] response parsed`,QQ({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function D$(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`request-id`),enumerable:!1})}var O$=new WeakSet;function k$(e){return typeof e==`object`&&!!e&&O$.has(e)}function A$(e){let t=new Set;for(;typeof e==`object`&&e&&!t.has(e);){if(t.add(e),k$(e)||l(e)||e instanceof y||e instanceof g)return!0;e=e.cause}return!1}function j$(e,t,n,r){return async(i,o={})=>{if(t.length===0)return e.call(void 0,i,o);let s=o.headers instanceof Headers?o.headers:new Headers(o.headers),c=await P$(e,t,n,r)({...o,headers:s,url:typeof i==`string`?i:i instanceof URL?i.href:i.url});if(c.bodyUsed||c.body?.locked)throw new a(`middleware consumed the response body; use response.clone() to inspect it, or return new Response(body, response) to consume and replace it`);return c}}function M$(e,t){let n=new WeakMap;return{options:e,logger:t?JQ(t):ZQ(),parse(t){if(e?.stream&&t.ok)return N$(t,e);let r=n.get(t);return r||(r=N$(t,e),n.set(t,r)),r}}}async function N$(e,t){if(e.bodyUsed||e.body?.locked)throw new a(`cannot ctx.parse() a response whose body was already consumed; call ctx.parse() instead of reading the body, or read via response.clone()`);if(t?.stream&&e.ok)return x$.fromSSEResponse(e.clone(),new AbortController);if(e.status===204)return null;if(t?.__binaryResponse)return e;let n=e.headers.get(`content-type`)?.split(`;`)[0]?.trim();return n?.includes(`application/json`)||n?.endsWith(`+json`)?e.headers.get(`content-length`)===`0`?void 0:D$(await e.clone().json(),e):await e.clone().text()}function P$(e,t,n,r){let i=async({url:t,...n})=>{try{return await e.call(void 0,t,n)}catch(e){let t=u(e);throw O$.add(t),t}},a=M$(n,r);for(let e=t.length-1;e>=0;e--){let n=t[e],r=i;i=async e=>n(e,r,a)}return i}var F$,I$=class e extends Promise{constructor(e,t,n=E$){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,F$.set(this,void 0),X(this,F$,e,`f`)}_thenUnwrap(t){return new e(Z(this,F$,`f`),this.responsePromise,async(e,n)=>D$(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(Z(this,F$,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};F$=new WeakMap;var L$,R$=class{constructor(e,t,n,r){L$.set(this,void 0),X(this,L$,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new a("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Z(this,L$,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(L$=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},z$=class extends I${constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await E$(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},B$=class extends R${constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let e=this.first_id;return e?{...this.options,query:{...wZ(this.options.query),before_id:e}}:null}let e=this.last_id;return e?{...this.options,query:{...wZ(this.options.query),after_id:e}}:null}},V$=class extends R${constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.next_page=n.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...wZ(this.options.query),page:e}}:null}},H$=class extends R${constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.next_page=n.next_page||null,this.prev_page=n.prev_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...wZ(this.options.query),page:e}}:null}},U$=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function W$(e,t,n){return U$(),new File(e,t??`unknown_file`,n)}function G$(e,t){let n=typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``;return t?n.split(/[\\/]/).pop()||void 0:n}var K$=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,q$=async(e,t,n=!0)=>({...e,body:await X$(e.body,t,n)}),J$=new WeakMap;function Y$(e){let t=typeof e==`function`?e:e.fetch,n=J$.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return J$.set(t,r),r}var X$=async(e,t,n=!0)=>{if(!await Y$(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>Q$(r,e,t,n))),r},Z$=e=>e instanceof Blob&&`name`in e,Q$=async(e,t,n,r)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response){let i={},a=n.headers.get(`Content-Type`);a&&(i={type:a}),e.append(t,W$([await n.blob()],G$(n,r),i))}else if(K$(n))e.append(t,W$([await new Response(JZ(n)).blob()],G$(n,r)));else if(Z$(n))e.append(t,W$([n],G$(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(n=>Q$(e,t+`[]`,n,r)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,i])=>Q$(e,`${t}[${n}]`,i,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},$$=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,e1=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&$$(e),t1=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function n1(e,t,n){if(U$(),e=await e,t||=G$(e,!0),e1(e))return e instanceof File&&t==null&&n==null?e:W$([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...n});if(t1(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),W$(await r1(r),t,n)}let r=await r1(e);if(!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return W$(r,t,n)}async function r1(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if($$(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(K$(e))for await(let n of e)t.push(...await r1(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${i1(e)}`)}return t}function i1(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var a1=class{constructor(e){this._client=e}},o1=Symbol.for(`brand.privateNullableHeaders`);function*s1(e){if(!e)return;if(o1 in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():CZ(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=CZ(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,c1]),yield[n,e])}}var c1=Symbol(`clear`),l1=new Set([`x-stainless-helper`]),u1=(e,t)=>{let n=e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[];for(let e of t.split(`,`).map(e=>e.trim()))e&&!n.includes(e)&&n.push(e);return n.join(`, `)},Q=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of s1(r)){let r=i.toLowerCase();if(l1.has(r)){if(a===c1)continue;a===null?(t.delete(i),n.add(r)):(t.set(i,u1(t.get(i),a)),n.delete(r));continue}(a===c1||!e.has(r))&&(t.delete(i),e.add(r),a===c1)||(a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r)))}}return{[o1]:!0,values:t,nulls:n}};function d1(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var f1=Object.freeze(Object.create(null)),$=((e=d1)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],o=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??f1)??f1)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),s=o.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(s))!==null;)i.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new a(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
|
|
221
|
+
`)}\n${o}\n${t}`)}return o})(d1),p1=class extends a1{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/deployment_runs/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/deployment_runs?beta=true`,V$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}},m1=class extends a1{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/deployments?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/deployments/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/deployments/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/deployments?beta=true`,V$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/deployments/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}pause(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/deployments/${e}/pause?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}run(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/deployments/${e}/run?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}unpause(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/deployments/${e}/unpause?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},h1=class extends a1{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/dreams?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`dreaming-2026-04-21`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/dreams/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`dreaming-2026-04-21`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/dreams?beta=true`,V$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`dreaming-2026-04-21`].toString()},t?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/dreams/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`dreaming-2026-04-21`].toString()},n?.headers])})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/dreams/${e}/cancel?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`dreaming-2026-04-21`].toString()},n?.headers])})}},g1=`x-stainless-helper`,_1=`x-stainless-helper-method`;function v1(e){return{[g1]:e}}var y1=Symbol(`anthropic.sdk.stainlessHelper`);function b1(e){return typeof e==`object`&&!!e&&y1 in e}function x1(e,t){let n=new Set;if(e)for(let t of e)b1(t)&&n.add(t[y1]);if(t)for(let e of t){b1(e)&&n.add(e[y1]);let t=e.content;if(Array.isArray(t))for(let e of t)b1(e)&&n.add(e[y1])}return Array.from(n)}function S1(e,t){let n=x1(e,t);return n.length===0?{}:{[g1]:n.join(`, `)}}function C1(e){return b1(e)?{[g1]:e[y1]}:{}}var w1=class extends a1{list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/files?beta=true`,B$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/files/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}download(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/files/${e}/content?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString(),Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/files/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}upload(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/files?beta=true`,q$({body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},C1(r.file),t?.headers])},this._client))}},T1=class extends a1{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/models/${e}?beta=true`,{...n,headers:Q([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/models?beta=true`,B$,{query:r,...t,headers:Q([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},E1=class extends a1{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/user_profiles?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/user_profiles/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/user_profiles/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/user_profiles?beta=true`,V$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}createEnrollmentURL(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}},D1=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.timingSafeEqual=void 0;function t(e,t=``){if(!e)throw Error(t)}function n(e,n){if(e.byteLength!==n.byteLength)return!1;e instanceof DataView||(e=new DataView(ArrayBuffer.isView(e)?e.buffer:e)),n instanceof DataView||(n=new DataView(ArrayBuffer.isView(n)?n.buffer:n)),t(e instanceof DataView),t(n instanceof DataView);let r=e.byteLength,i=0,a=-1;for(;++a<r;)i|=e.getUint8(a)^n.getUint8(a);return i===0}e.timingSafeEqual=n})),O1=t((e=>{var t=e&&e.__extends||(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();Object.defineProperty(e,"__esModule",{value:!0});var n=256,r=function(){function e(e){e===void 0&&(e=`=`),this._paddingCharacter=e}return e.prototype.encodedLength=function(e){return this._paddingCharacter?(e+2)/3*4|0:(e*8+5)/6|0},e.prototype.encode=function(e){for(var t=``,n=0;n<e.length-2;n+=3){var r=e[n]<<16|e[n+1]<<8|e[n+2];t+=this._encodeByte(r>>>18&63),t+=this._encodeByte(r>>>12&63),t+=this._encodeByte(r>>>6&63),t+=this._encodeByte(r>>>0&63)}var i=e.length-n;if(i>0){var r=e[n]<<16|(i===2?e[n+1]<<8:0);t+=this._encodeByte(r>>>18&63),t+=this._encodeByte(r>>>12&63),i===2?t+=this._encodeByte(r>>>6&63):t+=this._paddingCharacter||``,t+=this._paddingCharacter||``}return t},e.prototype.maxDecodedLength=function(e){return this._paddingCharacter?e/4*3|0:(e*6+7)/8|0},e.prototype.decodedLength=function(e){return this.maxDecodedLength(e.length-this._getPaddingLength(e))},e.prototype.decode=function(e){if(e.length===0)return new Uint8Array;for(var t=this._getPaddingLength(e),r=e.length-t,i=new Uint8Array(this.maxDecodedLength(r)),a=0,o=0,s=0,c=0,l=0,u=0,d=0;o<r-4;o+=4)c=this._decodeChar(e.charCodeAt(o+0)),l=this._decodeChar(e.charCodeAt(o+1)),u=this._decodeChar(e.charCodeAt(o+2)),d=this._decodeChar(e.charCodeAt(o+3)),i[a++]=c<<2|l>>>4,i[a++]=l<<4|u>>>2,i[a++]=u<<6|d,s|=c&n,s|=l&n,s|=u&n,s|=d&n;if(o<r-1&&(c=this._decodeChar(e.charCodeAt(o)),l=this._decodeChar(e.charCodeAt(o+1)),i[a++]=c<<2|l>>>4,s|=c&n,s|=l&n),o<r-2&&(u=this._decodeChar(e.charCodeAt(o+2)),i[a++]=l<<4|u>>>2,s|=u&n),o<r-3&&(d=this._decodeChar(e.charCodeAt(o+3)),i[a++]=u<<6|d,s|=d&n),s!==0)throw Error(`Base64Coder: incorrect characters for decoding`);return i},e.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-15,t+=62-e>>>8&3,String.fromCharCode(t)},e.prototype._decodeChar=function(e){var t=n;return t+=(42-e&e-44)>>>8&-n+e-43+62,t+=(46-e&e-48)>>>8&-n+e-47+63,t+=(47-e&e-58)>>>8&-n+e-48+52,t+=(64-e&e-91)>>>8&-n+e-65+0,t+=(96-e&e-123)>>>8&-n+e-97+26,t},e.prototype._getPaddingLength=function(e){var t=0;if(this._paddingCharacter){for(var n=e.length-1;n>=0&&e[n]===this._paddingCharacter;n--)t++;if(e.length<4||t>2)throw Error(`Base64Coder: incorrect padding`)}return t},e}();e.Coder=r;var i=new r;function a(e){return i.encode(e)}e.encode=a;function o(e){return i.decode(e)}e.decode=o;var s=function(e){t(r,e);function r(){return e!==null&&e.apply(this,arguments)||this}return r.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-13,t+=62-e>>>8&49,String.fromCharCode(t)},r.prototype._decodeChar=function(e){var t=n;return t+=(44-e&e-46)>>>8&-n+e-45+62,t+=(94-e&e-96)>>>8&-n+e-95+63,t+=(47-e&e-58)>>>8&-n+e-48+52,t+=(64-e&e-91)>>>8&-n+e-65+0,t+=(96-e&e-123)>>>8&-n+e-97+26,t},r}(r);e.URLSafeCoder=s;var c=new s;function l(e){return c.encode(e)}e.encodeURLSafe=l;function u(e){return c.decode(e)}e.decodeURLSafe=u,e.encodedLength=function(e){return i.encodedLength(e)},e.maxDecodedLength=function(e){return i.maxDecodedLength(e)},e.decodedLength=function(e){return i.decodedLength(e)}})),k1=t(((e,t)=>{(function(e,n){var r={};n(r);var i=r.default;for(var a in r)i[a]=r[a];typeof t==`object`&&typeof t.exports==`object`?t.exports=i:typeof define==`function`&&define.amd?define(function(){return i}):e.sha256=i})(e,function(e){e.__esModule=!0,e.digestLength=32,e.blockSize=64;var t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function n(e,n,r,i,a){for(var o,s,c,l,u,d,f,p,m,h,g,_,v;a>=64;){for(o=n[0],s=n[1],c=n[2],l=n[3],u=n[4],d=n[5],f=n[6],p=n[7],h=0;h<16;h++)g=i+h*4,e[h]=(r[g]&255)<<24|(r[g+1]&255)<<16|(r[g+2]&255)<<8|r[g+3]&255;for(h=16;h<64;h++)m=e[h-2],_=(m>>>17|m<<15)^(m>>>19|m<<13)^m>>>10,m=e[h-15],v=(m>>>7|m<<25)^(m>>>18|m<<14)^m>>>3,e[h]=(_+e[h-7]|0)+(v+e[h-16]|0);for(h=0;h<64;h++)_=(((u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7))+(u&d^~u&f)|0)+(p+(t[h]+e[h]|0)|0)|0,v=((o>>>2|o<<30)^(o>>>13|o<<19)^(o>>>22|o<<10))+(o&s^o&c^s&c)|0,p=f,f=d,d=u,u=l+_|0,l=c,c=s,s=o,o=_+v|0;n[0]+=o,n[1]+=s,n[2]+=c,n[3]+=l,n[4]+=u,n[5]+=d,n[6]+=f,n[7]+=p,i+=64,a-=64}return i}var r=function(){function t(){this.digestLength=e.digestLength,this.blockSize=e.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return t.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},t.prototype.clean=function(){for(var e=0;e<this.buffer.length;e++)this.buffer[e]=0;for(var e=0;e<this.temp.length;e++)this.temp[e]=0;this.reset()},t.prototype.update=function(e,t){if(t===void 0&&(t=e.length),this.finished)throw Error(`SHA256: can't update because hash was finished.`);var r=0;if(this.bytesHashed+=t,this.bufferLength>0){for(;this.bufferLength<64&&t>0;)this.buffer[this.bufferLength++]=e[r++],t--;this.bufferLength===64&&(n(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(t>=64&&(r=n(this.temp,this.state,e,r,t),t%=64);t>0;)this.buffer[this.bufferLength++]=e[r++],t--;return this},t.prototype.finish=function(e){if(!this.finished){var t=this.bytesHashed,r=this.bufferLength,i=t/536870912|0,a=t<<3,o=t%64<56?64:128;this.buffer[r]=128;for(var s=r+1;s<o-8;s++)this.buffer[s]=0;this.buffer[o-8]=i>>>24&255,this.buffer[o-7]=i>>>16&255,this.buffer[o-6]=i>>>8&255,this.buffer[o-5]=i>>>0&255,this.buffer[o-4]=a>>>24&255,this.buffer[o-3]=a>>>16&255,this.buffer[o-2]=a>>>8&255,this.buffer[o-1]=a>>>0&255,n(this.temp,this.state,this.buffer,0,o),this.finished=!0}for(var s=0;s<8;s++)e[s*4+0]=this.state[s]>>>24&255,e[s*4+1]=this.state[s]>>>16&255,e[s*4+2]=this.state[s]>>>8&255,e[s*4+3]=this.state[s]>>>0&255;return this},t.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},t.prototype._saveState=function(e){for(var t=0;t<this.state.length;t++)e[t]=this.state[t]},t.prototype._restoreState=function(e,t){for(var n=0;n<this.state.length;n++)this.state[n]=e[n];this.bytesHashed=t,this.finished=!1,this.bufferLength=0},t}();e.Hash=r;var i=function(){function e(e){this.inner=new r,this.outer=new r,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var t=new Uint8Array(this.blockSize);if(e.length>this.blockSize)new r().update(e).finish(t).clean();else for(var n=0;n<e.length;n++)t[n]=e[n];for(var n=0;n<t.length;n++)t[n]^=54;this.inner.update(t);for(var n=0;n<t.length;n++)t[n]^=106;this.outer.update(t),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(var n=0;n<t.length;n++)t[n]=0}return e.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},e.prototype.clean=function(){for(var e=0;e<this.istate.length;e++)this.ostate[e]=this.istate[e]=0;this.inner.clean(),this.outer.clean()},e.prototype.update=function(e){return this.inner.update(e),this},e.prototype.finish=function(e){return this.outer.finished?this.outer.finish(e):(this.inner.finish(e),this.outer.update(e,this.digestLength).finish(e)),this},e.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},e}();e.HMAC=i;function a(e){var t=new r().update(e),n=t.digest();return t.clean(),n}e.hash=a,e.default=a;function o(e,t){var n=new i(e).update(t),r=n.digest();return n.clean(),r}e.hmac=o;function s(e,t,n,r){var i=r[0];if(i===0)throw Error(`hkdf: cannot expand more`);t.reset(),i>1&&t.update(e),n&&t.update(n),t.update(r),t.finish(e),r[0]++}var c=new Uint8Array(e.digestLength);function l(e,t,n,r){t===void 0&&(t=c),r===void 0&&(r=32);for(var a=new Uint8Array([1]),l=new i(o(t,e)),u=new Uint8Array(l.digestLength),d=u.length,f=new Uint8Array(r),p=0;p<r;p++)d===u.length&&(s(u,l,n,a),d=0),f[p]=u[d++];return l.clean(),u.fill(0),a.fill(0),f}e.hkdf=l;function u(e,t,n,r){for(var a=new i(e),o=a.digestLength,s=new Uint8Array(4),c=new Uint8Array(o),l=new Uint8Array(o),u=new Uint8Array(r),d=0;d*o<r;d++){var f=d+1;s[0]=f>>>24&255,s[1]=f>>>16&255,s[2]=f>>>8&255,s[3]=f>>>0&255,a.reset(),a.update(t),a.update(s),a.finish(l);for(var p=0;p<o;p++)c[p]=l[p];for(var p=2;p<=n;p++){a.reset(),a.update(l).finish(l);for(var m=0;m<o;m++)c[m]^=l[m]}for(var p=0;p<o&&d*o+p<r;p++)u[d*o+p]=c[p]}for(var d=0;d<o;d++)c[d]=l[d]=0;for(var d=0;d<4;d++)s[d]=0;return a.clean(),u}e.pbkdf2=u})})),A1=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Webhook=e.WebhookVerificationError=void 0;var t=D1(),n=O1(),r=k1(),i=300,a=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name=`ExtendableError`,this.stack=Error(t).stack}},o=class e extends a{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name=`WebhookVerificationError`}};e.WebhookVerificationError=o;var s=class e{constructor(t,r){if(!t)throw Error(`Secret can't be empty.`);if(r?.format===`raw`)t instanceof Uint8Array?this.key=t:this.key=Uint8Array.from(t,e=>e.charCodeAt(0));else{if(typeof t!=`string`)throw Error(`Expected secret to be of type string`);t.startsWith(e.prefix)&&(t=t.substring(e.prefix.length)),this.key=n.decode(t)}}verify(e,n){let r={};for(let e of Object.keys(n))r[e.toLowerCase()]=n[e];let i=r[`webhook-id`],a=r[`webhook-signature`],s=r[`webhook-timestamp`];if(!a||!i||!s)throw new o(`Missing required headers`);let c=this.verifyTimestamp(s),l=this.sign(i,c,e).split(`,`)[1],u=a.split(` `),d=new globalThis.TextEncoder;for(let n of u){let[r,i]=n.split(`,`);if(r===`v1`&&(0,t.timingSafeEqual)(d.encode(i),d.encode(l)))return JSON.parse(e.toString())}throw new o(`No matching signature found`)}sign(e,t,i){if(typeof i!=`string`)if(i.constructor.name===`Buffer`)i=i.toString();else throw Error(`Expected payload to be of type string or Buffer.`);let a=new TextEncoder,o=Math.floor(t.getTime()/1e3),s=a.encode(`${e}.${o}.${i}`);return`v1,${n.encode(r.hmac(this.key,s))}`}verifyTimestamp(e){let t=Math.floor(Date.now()/1e3),n=parseInt(e,10);if(isNaN(n))throw new o(`Invalid Signature Headers`);if(t-n>i)throw new o(`Message timestamp too old`);if(n>t+i)throw new o(`Message timestamp too new`);return new Date(n*1e3)}};e.Webhook=s,s.prefix=`whsec_`}))(),j1=class extends a1{unwrap(e,{headers:t,key:n}){if(t!==void 0){let r=n===void 0?this._client.webhookKey:n;if(r===null)throw Error(`Webhook key must not be null in order to unwrap`);new A1.Webhook(r).verify(e,t)}return JSON.parse(e)}},M1=class extends a1{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/agents/${e}/versions?beta=true`,V$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},N1=class extends a1{constructor(){super(...arguments),this.versions=new M1(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/agents?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r,...i}=t??{};return this._client.get($`/v1/agents/${e}?beta=true`,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/agents/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/agents?beta=true`,V$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/agents/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};N1.Versions=M1;function P1(e,t){if(!e)return()=>{};if(e.aborted)return t.abort(),()=>{};let n=()=>t.abort();return e.addEventListener(`abort`,n),()=>e.removeEventListener(`abort`,n)}function F1(e,t){return e instanceof _&&e.status===t}function I1(e){return e instanceof _&&typeof e.status==`number`&&e.status>=400&&e.status<500}function L1(e){return I1(e)&&!F1(e,408)&&!F1(e,409)&&!F1(e,429)}function R1(e,t,n){return Math.min(t*2**e,n)}function z1(e,t){return e+Math.random()*(t-e)}function B1(e){return e*(1-Math.random()*.25)}function V1(e,{authToken:t,helper:n}){if(!t)throw new a(`copyClientForHelper: expected a non-empty authToken but received ${JSON.stringify(t)}`);let r=e,i=r._options.defaultHeaders,o=r._authState?.extraHeaders,s=Q([o?Object.fromEntries(Object.entries(o).filter(([e])=>{let t=e.toLowerCase();return t!==`authorization`&&t!==`x-api-key`})):void 0,i,{[g1]:n}]);return e.withOptions({apiKey:null,authToken:t,baseURL:e.baseURL,credentials:void 0,defaultHeaders:s})}var H1,U1,W1,G1,K1,q1,J1,Y1,X1,Z1=1e3,Q1=6e4,$1=class{constructor(e){H1.set(this,void 0),U1.set(this,!1),W1.set(this,void 0),G1.set(this,void 0),K1.set(this,void 0),q1.set(this,void 0),J1.set(this,void 0),Y1.set(this,void 0),X1.set(this,void 0),this.client=e.client,this.environmentId=e.environmentId,this.environmentKey=e.environmentKey,this.workerId=e.workerId??t0(),X(this,H1,V1(e.client,{authToken:e.environmentKey,helper:`environments-work-poller`}),`f`),X(this,K1,e.autoStop??!0,`f`),X(this,q1,e.drain??!1,`f`),X(this,J1,e.blockMs===void 0?999:e.blockMs,`f`),X(this,Y1,e.reclaimOlderThanMs??null,`f`),X(this,X1,e.requestOptions,`f`),X(this,W1,new AbortController,`f`),X(this,G1,P1(e.signal,Z(this,W1,`f`)),`f`)}get signal(){return Z(this,W1,`f`).signal}abort(){Z(this,W1,`f`).abort()}async*[(H1=new WeakMap,U1=new WeakMap,W1=new WeakMap,G1=new WeakMap,K1=new WeakMap,q1=new WeakMap,J1=new WeakMap,Y1=new WeakMap,X1=new WeakMap,Symbol.asyncIterator)](){if(Z(this,U1,`f`))throw new a(`Cannot iterate over a consumed WorkPoller`);X(this,U1,!0,`f`);let e=JQ(this.client);e.info(`poller starting`,{component:`work-poller`,environment_id:this.environmentId});try{let t=0;for(;!Z(this,W1,`f`).signal.aborted;){let n;try{n=await Z(this,H1,`f`).beta.environments.work.poll(this.environmentId,{"Anthropic-Worker-ID":this.workerId,...Z(this,J1,`f`)===null?{}:{block_ms:Z(this,J1,`f`)},...Z(this,Y1,`f`)===null?{}:{reclaim_older_than_ms:Z(this,Y1,`f`)}},{headers:Q([Z(this,X1,`f`)?.headers]),signal:Z(this,W1,`f`).signal})}catch(n){if(Z(this,W1,`f`).signal.aborted)return;if(L1(n))throw e.error(`poll failed permanently, stopping poller`,{error:String(n)}),n;let r=B1(e0(t));e.warn(`poll failed, backing off`,{error:String(n),backoff_ms:r}),t++,await AZ(r,Z(this,W1,`f`).signal);continue}if(t=0,n==null){if(Z(this,q1,`f`))return;await AZ(z1(1e3,3e3),Z(this,W1,`f`).signal);continue}e.info(`claimed work`,{component:`work-poller`,environment_id:this.environmentId,work_id:n.id,work_type:n.data.type});try{await Z(this,H1,`f`).beta.environments.work.ack(n.id,{environment_id:n.environment_id},{headers:Q([Z(this,X1,`f`)?.headers]),signal:Z(this,W1,`f`).signal})}catch(t){e.error(`ack failed`,{work_id:n.id,error:String(t)});continue}try{yield n}finally{if(Z(this,K1,`f`))try{await Z(this,H1,`f`).beta.environments.work.stop(n.id,{environment_id:n.environment_id},{headers:Q([Z(this,X1,`f`)?.headers])})}catch(t){F1(t,409)||e.warn(`stop failed`,{work_id:n.id,error:String(t)})}}}}finally{Z(this,G1,`f`).call(this)}}};function e0(e){return R1(e,Z1,Q1)}function t0(){let e={}.HOSTNAME;return e?`${e}-${yZ()}`:yZ()}var n0,r0,i0,a0=class{constructor(){n0.set(this,[]),r0.set(this,[]),i0.set(this,!1)}push(e){if(Z(this,i0,`f`))return!1;let t=Z(this,r0,`f`).shift();return t?t({done:!1,value:e}):Z(this,n0,`f`).push(e),!0}close(){if(!Z(this,i0,`f`))for(X(this,i0,!0,`f`);Z(this,r0,`f`).length>0;)Z(this,r0,`f`).shift()({done:!0,value:void 0})}next(e){return Z(this,n0,`f`).length>0?Promise.resolve({done:!1,value:Z(this,n0,`f`).shift()}):Z(this,i0,`f`)||e?.aborted?Promise.resolve({done:!0,value:void 0}):new Promise(t=>{let n=n=>{e?.removeEventListener(`abort`,r),t(n)},r=()=>{let e=Z(this,r0,`f`).indexOf(n);e>=0&&Z(this,r0,`f`).splice(e,1),t({done:!0,value:void 0})};Z(this,r0,`f`).push(n),e?.addEventListener(`abort`,r,{once:!0})})}tryShift(){return Z(this,n0,`f`).shift()}};n0=new WeakMap,r0=new WeakMap,i0=new WeakMap;var o0=class extends Error{constructor(e){let t=typeof e==`string`?e:e.map(e=>e.type===`text`?e.text:`[${e.type}]`).join(` `);super(t),this.name=`ToolError`,this.content=e}};function s0(e){return`name`in e?e.name:e.mcp_server_name}function c0(e){return e instanceof o0?e.content:`Error: ${e instanceof Error?e.message:String(e)}`}async function l0(e,t,n){try{let r=e.parse?e.parse(t):t;return{content:await e.run(r,n),isError:!1}}catch(e){return{content:c0(e),isError:!0}}}var u0,d0,f0,p0,m0,h0,g0,_0,v0,y0,b0,x0,S0,C0,w0,T0,E0,D0,O0,k0,A0,j0,M0,N0,P0,F0,I0,L0,R0,z0,B0,V0,H0=500,U0=1e4,W0=12e4,G0=3e4,K0=3;function q0(e){return e.type===`session.status_idle`&&e.stop_reason?.type===`end_turn`}var J0=class{constructor(e,t){u0.set(this,void 0),d0.set(this,void 0),f0.set(this,new Set),p0.set(this,!1),m0.set(this,void 0),X(this,u0,e,`f`),X(this,d0,t,`f`)}noteEvent(e){e.type!==`user.tool_confirmation`&&(q0(e)?this.arm():this.disarm())}block(e){Z(this,f0,`f`).add(e),Z(this,m0,`f`)!==void 0&&(X(this,p0,!0,`f`),clearTimeout(Z(this,m0,`f`)),X(this,m0,void 0,`f`))}unblock(e){Z(this,f0,`f`).delete(e),Z(this,f0,`f`).size===0&&Z(this,p0,`f`)&&this.arm()}arm(){if(!(Z(this,u0,`f`)<=0)){if(Z(this,f0,`f`).size>0){X(this,p0,!0,`f`);return}X(this,p0,!1,`f`),Z(this,m0,`f`)!==void 0&&clearTimeout(Z(this,m0,`f`)),X(this,m0,setTimeout(Z(this,d0,`f`),Z(this,u0,`f`)),`f`)}}disarm(){X(this,p0,!1,`f`),Z(this,m0,`f`)!==void 0&&(clearTimeout(Z(this,m0,`f`)),X(this,m0,void 0,`f`))}};u0=new WeakMap,d0=new WeakMap,f0=new WeakMap,p0=new WeakMap,m0=new WeakMap;var Y0=class{constructor(e,t){h0.add(this),g0.set(this,!1),_0.set(this,void 0),v0.set(this,void 0),y0.set(this,void 0),b0.set(this,void 0),x0.set(this,void 0),S0.set(this,new Set),C0.set(this,new Set),w0.set(this,new Map),T0.set(this,new Map),E0.set(this,new a0),D0.set(this,0),O0.set(this,null),k0.set(this,void 0),this.client=t.client,this.sessionId=e,this.tools=t.tools,this.maxIdleMs=t.maxIdleMs??6e4,X(this,x0,JQ(t.client),`f`),X(this,b0,new Map(t.tools.map(e=>[s0(e),e])),`f`),X(this,_0,new AbortController,`f`),X(this,v0,P1(t.signal,Z(this,_0,`f`)),`f`),X(this,y0,t.requestOptions,`f`),X(this,k0,new J0(this.maxIdleMs,()=>{Z(this,x0,`f`).info(`session idle after end_turn; stopping`,{component:`session-tool-runner`,session_id:this.sessionId,max_idle_ms:this.maxIdleMs}),Z(this,_0,`f`).abort()}),`f`)}get signal(){return Z(this,_0,`f`).signal}abort(){Z(this,_0,`f`).abort()}async*[(g0=new WeakMap,_0=new WeakMap,v0=new WeakMap,y0=new WeakMap,b0=new WeakMap,x0=new WeakMap,S0=new WeakMap,C0=new WeakMap,w0=new WeakMap,T0=new WeakMap,E0=new WeakMap,D0=new WeakMap,O0=new WeakMap,k0=new WeakMap,h0=new WeakSet,Symbol.asyncIterator)](){if(Z(this,g0,`f`))throw new a(`Cannot iterate over a consumed SessionToolRunner`);X(this,g0,!0,`f`),Z(this,x0,`f`).info(`session tool runner starting`,{component:`session-tool-runner`,session_id:this.sessionId});let e=Z(this,h0,`m`,j0).call(this).catch(e=>{Z(this,_0,`f`).signal.aborted||Z(this,x0,`f`).error(`stream loop failed`,{error:String(e)}),Z(this,_0,`f`).abort()});try{for(;;){let e=await Z(this,E0,`f`).next(Z(this,_0,`f`).signal);if(e.done)break;yield e.value}await e;let t;for(;(t=Z(this,E0,`f`).tryShift())!==void 0;)yield t}finally{Z(this,_0,`f`).abort(),Z(this,k0,`f`).disarm(),await e;try{await Z(this,h0,`m`,V0).call(this)}catch(e){Z(this,x0,`f`).warn(`drain failed`,{error:String(e)})}Z(this,E0,`f`).close();for(let e of this.tools)try{await e.close?.()}catch(t){Z(this,x0,`f`).warn(`tool.close failed`,{tool:s0(e),error:String(t)})}Z(this,v0,`f`).call(this)}}};A0=function(){return{...Z(this,y0,`f`),headers:Q([v1(`session-tool-runner`),Z(this,y0,`f`)?.headers]),signal:Z(this,_0,`f`).signal}},j0=async function(){let e=Z(this,_0,`f`),t=H0;for(;!e.signal.aborted;){try{let e=await this.client.beta.sessions.events.stream(this.sessionId,{},Z(this,h0,`m`,A0).call(this));await Z(this,h0,`m`,M0).call(this);for await(let n of e)if(t=H0,await Z(this,h0,`m`,P0).call(this,n))return}catch(n){if(e.signal.throwIfAborted(),L1(n))throw Z(this,x0,`f`).error(`permanent stream failure, shutting down`,{error:String(n)}),e.abort(),n;Z(this,x0,`f`).warn(`stream disconnected, reconnecting`,{error:String(n),backoff_ms:t})}e.signal.throwIfAborted(),await AZ(t,e.signal),t=Math.min(t*2,U0)}},M0=async function(){let e=Z(this,_0,`f`),t=[],n=!1;try{for await(let e of this.client.beta.sessions.events.list(this.sessionId,{limit:1e3},Z(this,h0,`m`,A0).call(this)))Z(this,h0,`m`,N0).call(this,e,t),n=q0(e)}catch(n){e.signal.throwIfAborted(),Z(this,x0,`f`).warn(`reconcile list failed`,{error:String(n)});for(let e of t)Z(this,S0,`f`).delete(e.id);return}let r=t.filter(e=>!Z(this,C0,`f`).has(e.id));Z(this,k0,`f`).disarm();for(let e of r)await Z(this,h0,`m`,F0).call(this,e);for(let e of[...Z(this,T0,`f`).values()]){let t=Z(this,w0,`f`).get(e.id);t!==void 0&&await Z(this,h0,`m`,L0).call(this,e,t)}let i=r.filter(e=>!Z(this,C0,`f`).has(e.id)&&!Z(this,T0,`f`).has(e.id));n&&i.length===0?Z(this,k0,`f`).arm():Z(this,k0,`f`).disarm()},N0=function(e,t){e.type===`agent.tool_use`||e.type===`agent.custom_tool_use`?(Z(this,S0,`f`).add(e.id),Z(this,C0,`f`).has(e.id)||t.push(e)):e.type===`user.tool_result`?Z(this,C0,`f`).add(e.tool_use_id):e.type===`user.custom_tool_result`?Z(this,C0,`f`).add(e.custom_tool_use_id):e.type===`user.tool_confirmation`&&(Z(this,C0,`f`).has(e.tool_use_id)||Z(this,w0,`f`).set(e.tool_use_id,e.result))},P0=async function(e){switch(Z(this,k0,`f`).noteEvent(e),e.type){case`agent.tool_use`:case`agent.custom_tool_use`:return Z(this,S0,`f`).has(e.id)||(Z(this,S0,`f`).add(e.id),await Z(this,h0,`m`,F0).call(this,e)),!1;case`user.tool_confirmation`:return await Z(this,h0,`m`,I0).call(this,e),!1;case`user.tool_result`:return Z(this,C0,`f`).add(e.tool_use_id),!1;case`user.custom_tool_result`:return Z(this,C0,`f`).add(e.custom_tool_use_id),!1;case`session.status_terminated`:case`session.deleted`:return Z(this,x0,`f`).info(`session terminated`,{component:`session-tool-runner`,session_id:this.sessionId}),Z(this,_0,`f`).abort(),!0;default:return!1}},F0=async function(e){let t=e.evaluated_permission,n=t===`deny`?`deny`:Z(this,w0,`f`).get(e.id);if(n===void 0){t===void 0||t===`allow`?await Z(this,h0,`m`,z0).call(this,e,void 0):Z(this,T0,`f`).has(e.id)||(Z(this,x0,`f`).info(`tool call awaiting confirmation; holding`,{component:`session-tool-runner`,session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),Z(this,T0,`f`).set(e.id,e),Z(this,k0,`f`).block(e.id));return}await Z(this,h0,`m`,L0).call(this,e,n)},I0=async function(e){Z(this,w0,`f`).set(e.tool_use_id,e.result);let t=Z(this,T0,`f`).get(e.tool_use_id);t!==void 0&&await Z(this,h0,`m`,L0).call(this,t,e.result)},L0=async function(e,t){let n=Z(this,T0,`f`).delete(e.id);if(t===`allow`){Z(this,x0,`f`).info(`tool call confirmed`,{component:`session-tool-runner`,session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),n||Z(this,k0,`f`).block(e.id);try{await Z(this,h0,`m`,z0).call(this,e,`allow`)}finally{Z(this,k0,`f`).unblock(e.id)}return}n&&Z(this,k0,`f`).unblock(e.id),Z(this,C0,`f`).add(e.id),Z(this,x0,`f`).info(`tool call denied; not executing`,{component:`session-tool-runner`,session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),Z(this,h0,`m`,R0).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:`deny`})},R0=function(e){Z(this,E0,`f`).push(e)},z0=async function(e,t){var n,r;if(!Z(this,C0,`f`).has(e.id)){Z(this,x0,`f`).info(`executing tool`,{component:`session-tool-runner`,session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),X(this,D0,(n=Z(this,D0,`f`),n++,n),`f`);try{let n=Z(this,b0,`f`).get(e.name);if(!n){Z(this,x0,`f`).info(`tool not owned by this runner; leaving the tool_use_id pending for its owner`,{component:`session-tool-runner`,session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),Z(this,h0,`m`,R0).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:t});return}let r,i,a=new AbortController,o=P1(Z(this,_0,`f`).signal,a),s=setTimeout(()=>a.abort(),W0);try{let t=await l0(n,e.input,{toolUse:e,toolUseBlock:e,signal:a.signal});r=t.content,i=t.isError}finally{clearTimeout(s),o()}let c=X0(e,i,Z0(r)),l=await Z(this,h0,`m`,B0).call(this,c,e.id);Z(this,h0,`m`,R0).call(this,{event:e,result:c,toolUseId:e.id,name:e.name,isError:i,posted:l,confirmation:t})}finally{X(this,D0,(r=Z(this,D0,`f`),r--,r),`f`),Z(this,D0,`f`)===0&&Z(this,O0,`f`)?.call(this)}}},B0=async function(e,t){let n=Z(this,_0,`f`),r;for(let i=0;i<K0;i++){n.signal.throwIfAborted();try{return await this.client.beta.sessions.events.send(this.sessionId,{events:[e]},Z(this,h0,`m`,A0).call(this)),Z(this,C0,`f`).add(t),!0}catch(e){if(r=e,L1(e))break;i<K0-1&&await AZ((i+1)*1e3,n.signal)}}return Z(this,x0,`f`).error(`failed to send tool result`,{tool_use_id:t,error:String(r)}),!1},V0=async function(){Z(this,D0,`f`)!==0&&(await Promise.race([new Promise(e=>X(this,O0,e,`f`)),AZ(G0)]),X(this,O0,null,`f`),Z(this,D0,`f`)>0&&Z(this,x0,`f`).warn(`drain timeout exceeded`))};function X0(e,t,n){return e.type===`agent.custom_tool_use`?{type:`user.custom_tool_result`,custom_tool_use_id:e.id,is_error:t,content:n}:{type:`user.tool_result`,tool_use_id:e.id,is_error:t,content:n}}function Z0(e){if(typeof e==`string`)return[{type:`text`,text:e||`(no output)`}];let t=e.map(e=>e.type===`text`?{type:`text`,text:e.text||`(no output)`}:e.type===`image`||e.type===`document`?e:e.type===`search_result`?{type:`search_result`,source:e.source,title:e.title,content:e.content.map(e=>({type:`text`,text:e.text})),citations:{enabled:e.citations?.enabled??!1}}:{type:`text`,text:JSON.stringify(e)});return t.length>0?t:[{type:`text`,text:`(no output)`}]}var Q0,$0,e2,t2=3e4,n2=`NO_HEARTBEAT`,r2=class{constructor(e){Q0.add(this),$0.set(this,void 0),this.client=e.client,this.environmentId=e.environmentId,this.environmentKey=e.environmentKey,this.tools=e.tools,this.workdir=e.workdir??process.cwd(),this.unrestrictedPaths=e.unrestrictedPaths,this.maxFileBytes=e.maxFileBytes,this.maxIdleMs=e.maxIdleMs,this.workerId=e.workerId,this.requestOptions=e.requestOptions,X(this,$0,e.signal,`f`)}async run(e){let{environmentId:t,environmentKey:n}=this;if(t===void 0||n===void 0)throw new a(`EnvironmentWorker.run: environmentId and environmentKey are required to poll for work`);let r=e??Z(this,$0,`f`),i=new $1({client:this.client,environmentId:t,environmentKey:n,...this.workerId===void 0?{}:{workerId:this.workerId},...r?{signal:r}:{},...this.requestOptions===void 0?{}:{requestOptions:this.requestOptions},autoStop:!1});for await(let e of i)await Z(this,Q0,`m`,e2).call(this,e,n,i.signal)}async handleItem(e){let t=e?.workId??PQ(`ANTHROPIC_WORK_ID`),n=e?.environmentId??PQ(`ANTHROPIC_ENVIRONMENT_ID`),r=e?.sessionId??PQ(`ANTHROPIC_SESSION_ID`),i=e?.environmentKey??this.environmentKey??PQ(`ANTHROPIC_ENVIRONMENT_KEY`);if(!t)throw new a(`handleItem: workId is required — pass it or set ANTHROPIC_WORK_ID`);if(!n)throw new a(`handleItem: environmentId is required — pass it or set ANTHROPIC_ENVIRONMENT_ID`);if(!r)throw new a(`handleItem: sessionId is required — pass it or set ANTHROPIC_SESSION_ID`);if(!i)throw new a(`handleItem: environmentKey is required — pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY`);let o={id:t,environment_id:n,data:{type:`session`,id:r}};await Z(this,Q0,`m`,e2).call(this,o,i,e?.signal??Z(this,$0,`f`))}};$0=new WeakMap,Q0=new WeakSet,e2=async function(e,t,n){let r=JQ(this.client),a=V1(this.client,{authToken:t,helper:`environments-worker`}),o=e.data.id,s={workdir:this.workdir,client:this.client,sessionId:o,...this.unrestrictedPaths===void 0?{}:{unrestrictedPaths:this.unrestrictedPaths},...this.maxFileBytes===void 0?{}:{maxFileBytes:this.maxFileBytes}},c=await i(()=>import(`./node.browser-U-KyT5AW.js`),__vite__mapDeps([2,3])),l=async()=>{};try{l=await c.setupSkills(s)}catch(t){r.warn(`skill setup failed`,{session_id:o,work_id:e.id,error:String(t)})}let u=typeof this.tools==`function`?this.tools(s):this.tools??c.betaAgentToolset20260401(s),d=new AbortController,f=P1(n,d),p=a2(a,e,d,r,this.requestOptions).catch(t=>{d.signal.aborted||r.error(`heartbeat loop failed`,{work_id:e.id,error:String(t)}),d.abort()});try{let e=new Y0(o,{client:a,tools:u,...this.maxIdleMs===void 0?{}:{maxIdleMs:this.maxIdleMs},...this.requestOptions===void 0?{}:{requestOptions:this.requestOptions},signal:d.signal});for await(let t of e);}finally{d.abort(),f(),await p,await l().catch(t=>{r.warn(`skill cleanup failed`,{session_id:o,work_id:e.id,error:String(t)})}),await i2(a,e,r,this.requestOptions)}};async function i2(e,t,n,r){try{await e.beta.environments.work.stop(t.id,{environment_id:t.environment_id,force:!0},{...r,headers:Q([r?.headers])})}catch(e){F1(e,409)||n.error(`force-stop on exit failed`,{work_id:t.id,error:String(e)})}}async function a2(e,t,n,r,i){let a=t2,o=n2,s=async()=>{try{let s=await e.beta.environments.work.heartbeat(t.id,{environment_id:t.environment_id,expected_last_heartbeat:o},{...i,headers:Q([i?.headers]),signal:n.signal});o=s.last_heartbeat,s.ttl_seconds>0&&(a=Math.max(1e3,Math.min(s.ttl_seconds*1e3/2,t2))),(s.state===`stopping`||s.state===`stopped`)&&(r.info(`heartbeat signals shutdown`,{work_id:t.id,state:s.state}),n.abort()),s.lease_extended||(r.warn(`lease not extended, shutting down`,{work_id:t.id}),n.abort())}catch(e){if(n.signal.throwIfAborted(),L1(e))throw r.error(`permanent heartbeat failure`,{work_id:t.id,error:String(e)}),n.abort(),e;r.warn(`transient heartbeat failure`,{work_id:t.id,error:String(e)})}};for(await s();!n.signal.aborted;)await AZ(a,n.signal),n.signal.throwIfAborted(),await s()}var o2=class extends a1{retrieve(e,t,n){let{environment_id:r,betas:i}=t;return this._client.get($`/v1/environments/${r}/work/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{environment_id:r,betas:i,...a}=t;return this._client.post($`/v1/environments/${r}/work/${e}?beta=true`,{body:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/environments/${e}/work?beta=true`,V$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}ack(e,t,n){let{environment_id:r,betas:i}=t;return this._client.post($`/v1/environments/${r}/work/${e}/ack?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}heartbeat(e,t,n){let{environment_id:r,desired_ttl_seconds:i,expected_last_heartbeat:a,betas:o}=t;return this._client.post($`/v1/environments/${r}/work/${e}/heartbeat?beta=true`,{query:{desired_ttl_seconds:i,expected_last_heartbeat:a},...n,headers:Q([{"anthropic-beta":[...o??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}poll(e,t={},n){let{betas:r,"Anthropic-Worker-ID":i,...a}=t??{};return this._client.get($`/v1/environments/${e}/work/poll?beta=true`,{query:a,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString(),...i==null?void 0:{"Anthropic-Worker-ID":i}},n?.headers])})}stats(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/environments/${e}/work/stats?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}stop(e,t,n){let{environment_id:r,betas:i,...a}=t;return this._client.post($`/v1/environments/${r}/work/${e}/stop?beta=true`,{body:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}poller(e){return new $1({...e,client:this._client})}worker(e){return new r2({...e,client:this._client})}};o2.WorkPoller=$1,o2.EnvironmentWorker=r2;var s2=class extends a1{constructor(){super(...arguments),this.work=new o2(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/environments?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/environments/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/environments/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/environments?beta=true`,V$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/environments/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/environments/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};s2.Work=o2;var c2=class extends a1{create(e,t,n){let{view:r,betas:i,...a}=t;return this._client.post($`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:r},body:a,...n,headers:Q([{"anthropic-beta":[...i??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get($`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:a,...n,headers:Q([{"anthropic-beta":[...i??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}update(e,t,n){let{memory_store_id:r,view:i,betas:a,...o}=t;return this._client.post($`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{view:i},body:o,...n,headers:Q([{"anthropic-beta":[...a??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/memory_stores/${e}/memories?beta=true`,V$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}delete(e,t,n){let{memory_store_id:r,expected_content_sha256:i,betas:a}=t;return this._client.delete($`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{expected_content_sha256:i},...n,headers:Q([{"anthropic-beta":[...a??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}},l2=class extends a1{retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get($`/v1/memory_stores/${r}/memory_versions/${e}?beta=true`,{query:a,...n,headers:Q([{"anthropic-beta":[...i??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/memory_stores/${e}/memory_versions?beta=true`,V$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}redact(e,t,n){let{memory_store_id:r,betas:i}=t;return this._client.post($`/v1/memory_stores/${r}/memory_versions/${e}/redact?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}},u2=class extends a1{constructor(){super(...arguments),this.memories=new c2(this._client),this.memoryVersions=new l2(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/memory_stores?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`agent-memory-2026-07-22`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/memory_stores/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/memory_stores/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/memory_stores?beta=true`,V$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`agent-memory-2026-07-22`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/memory_stores/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/memory_stores/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`agent-memory-2026-07-22`].toString()},n?.headers])})}};u2.Memories=c2,u2.MemoryVersions=l2;var d2=class e{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new _$;for await(let t of this.iterator)for(let n of e.decode(t))yield JSON.parse(n);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(t,n){if(!t.body)throw n.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new a(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new a(`Attempted to iterate over a response with no body`);return new e(YZ(t.body),n)}},f2=class extends a1{create(e,t){let{betas:n,user_profile_id:r,...i}=e;return this._client.post(`/v1/messages/batches?beta=true`,{body:i,...t,headers:Q([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString(),...r==null?void 0:{"anthropic-user-profile-id":r}},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/messages/batches/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/messages/batches?beta=true`,B$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/messages/batches/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}async results(e,t={},n){let r=await this.retrieve(e);if(!r.results_url)throw new a(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);let{betas:i}=t??{};return this._client.get(r.results_url,{...n,headers:Q([{"anthropic-beta":[...i??[],`message-batches-2024-09-24`].toString(),Accept:`application/binary`},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>d2.fromResponse(t.response,t.controller))}},p2={"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 m2(e){return e?.output_format??e?.output_config?.format}function h2(e,t,n){let r=m2(t);return!t||!(`parse`in(r??{}))?{...e,content:e.content.map(e=>{if(e.type===`text`){let t=Object.defineProperty({...e},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(t,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return e}),parsed_output:null}:g2(e,t,n)}function g2(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let i=_2(t,e.text);r===null&&(r=i);let a=Object.defineProperty({...e},"parsed_output",{value:i,enumerable:!1});return Object.defineProperty(a,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),i},enumerable:!1})}return e});return{...e,content:i,parsed_output:r}}function _2(e,t){let n=m2(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new a(`Failed to parse structured output: ${e}`)}}var v2=e=>{let t=0,n=[];for(;t<e.length;){let r=e[t];if(r===`\\`){t++;continue}if(r===`{`){n.push({type:`brace`,value:`{`}),t++;continue}if(r===`}`){n.push({type:`brace`,value:`}`}),t++;continue}if(r===`[`){n.push({type:`paren`,value:`[`}),t++;continue}if(r===`]`){n.push({type:`paren`,value:`]`}),t++;continue}if(r===`:`){n.push({type:`separator`,value:`:`}),t++;continue}if(r===`,`){n.push({type:`delimiter`,value:`,`}),t++;continue}if(r===`"`){let i=``,a=!1;for(r=e[++t];r!==`"`;){if(t===e.length){a=!0;break}if(r===`\\`){if(t++,t===e.length){a=!0;break}i+=r+e[t],r=e[++t]}else i+=r,r=e[++t]}r=e[++t],a||n.push({type:`string`,value:i});continue}if(r&&/\s/.test(r)){t++;continue}let i=/[0-9]/;if(r&&i.test(r)||r===`-`||r===`.`){let a=``;for(r===`-`&&(a+=r,r=e[++t]);r&&(i.test(r)||r===`.`||r===`e`||r===`E`||(r===`-`||r===`+`)&&(a[a.length-1]===`e`||a[a.length-1]===`E`));)a+=r,r=e[++t];n.push({type:`number`,value:a});continue}let a=/[a-z]/i;if(r&&a.test(r)){let i=``;for(;r&&a.test(r)&&t!==e.length;)i+=r,r=e[++t];if(i==`true`||i==`false`||i===`null`)n.push({type:`name`,value:i});else{t++;continue}continue}t++}return n},y2=e=>{if(e.length===0)return e;let t=e[e.length-1];switch(t.type){case`separator`:return e=e.slice(0,e.length-1),y2(e);case`number`:let n=t.value[t.value.length-1];if(n===`.`||n===`-`||n===`+`||n===`e`||n===`E`)return e=e.slice(0,e.length-1),y2(e);case`string`:let r=e[e.length-2];if(r?.type===`delimiter`||r?.type===`brace`&&r.value===`{`)return e=e.slice(0,e.length-1),y2(e);break;case`delimiter`:return e=e.slice(0,e.length-1),y2(e)}return e},b2=e=>{let t=[];return e.map(e=>{e.type===`brace`&&(e.value===`{`?t.push(`}`):t.splice(t.lastIndexOf(`}`),1)),e.type===`paren`&&(e.value===`[`?t.push(`]`):t.splice(t.lastIndexOf(`]`),1))}),t.length>0&&t.reverse().map(t=>{t===`}`?e.push({type:`brace`,value:`}`}):t===`]`&&e.push({type:`paren`,value:`]`})}),e},x2=e=>{let t=``;return e.map(e=>{switch(e.type){case`string`:t+=`"`+e.value+`"`;break;default:t+=e.value;break}}),t},S2=e=>JSON.parse(x2(b2(y2(v2(e))))),C2=`__json_buf`;function w2(e,t){let n={};for(let t of Object.keys(e))t!==`input`&&(n[t]=e[t]);Object.defineProperty(n,C2,{value:t,enumerable:!1,writable:!0});let r,i=!1;return Object.defineProperty(n,"input",{enumerable:!0,configurable:!0,get(){return i||=(r=t?S2(t):{},!0),r}}),n}var T2,E2,D2,O2,k2,A2,j2,M2,N2,P2,F2,I2,L2,R2,z2,B2,V2,H2,U2,W2,G2,K2,q2,J2,Y2;function X2(e){return e.type===`tool_use`||e.type===`server_tool_use`||e.type===`mcp_tool_use`}var Z2=class e{constructor(e,t){T2.add(this),this.messages=[],this.receivedMessages=[],E2.set(this,void 0),D2.set(this,null),this.controller=new AbortController,O2.set(this,void 0),k2.set(this,()=>{}),A2.set(this,()=>{}),j2.set(this,void 0),M2.set(this,()=>{}),N2.set(this,()=>{}),P2.set(this,{}),F2.set(this,!1),I2.set(this,!1),L2.set(this,!1),R2.set(this,!1),z2.set(this,void 0),B2.set(this,void 0),V2.set(this,void 0),W2.set(this,e=>{if(X(this,I2,!0,`f`),l(e)&&(e=new d),e instanceof d)return X(this,L2,!0,`f`),this._emit(`abort`,e);if(e instanceof a)return this._emit(`error`,e);if(e instanceof Error){let t=new a(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new a(String(e)))}),X(this,O2,new Promise((e,t)=>{X(this,k2,e,`f`),X(this,A2,t,`f`)}),`f`),X(this,j2,new Promise((e,t)=>{X(this,M2,e,`f`),X(this,N2,t,`f`)}),`f`),Z(this,O2,`f`).catch(()=>{}),Z(this,j2,`f`).catch(()=>{}),X(this,D2,e,`f`),X(this,V2,t?.logger??console,`f`)}get response(){return Z(this,z2,`f`)}get request_id(){return Z(this,B2,`f`)}async withResponse(){X(this,R2,!0,`f`);let e=await Z(this,O2,`f`);if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get(`request-id`)}}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,r,{logger:i}={}){let a=new e(n,{logger:i});for(let e of n.messages)a._addMessageParam(e);return X(a,D2,{...n,stream:!0},`f`),a._run(()=>a._createMessage(t,{...n,stream:!0},{...r,headers:{...r?.headers,[_1]:`stream`}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit(`end`)},Z(this,W2,`f`))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit(`message`,e)}async _createMessage(e,t,n){let r=n?.signal,i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener(`abort`,i));try{Z(this,T2,`m`,G2).call(this);let{response:r,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(let e of i)Z(this,T2,`m`,K2).call(this,e);if(i.controller.signal?.aborted)throw new d;Z(this,T2,`m`,q2).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(X(this,z2,e,`f`),X(this,B2,e?.headers.get(`request-id`),`f`),Z(this,k2,`f`).call(this,e),this._emit(`connect`))}get ended(){return Z(this,F2,`f`)}get errored(){return Z(this,I2,`f`)}get aborted(){return Z(this,L2,`f`)}abort(){this.controller.abort()}on(e,t){return(Z(this,P2,`f`)[e]||(Z(this,P2,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=Z(this,P2,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(Z(this,P2,`f`)[e]||(Z(this,P2,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{X(this,R2,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){X(this,R2,!0,`f`),await Z(this,j2,`f`)}get currentMessage(){return Z(this,E2,`f`)}async finalMessage(){return await this.done(),Z(this,T2,`m`,H2).call(this)}async finalText(){return await this.done(),Z(this,T2,`m`,U2).call(this)}_emit(e,...t){if(Z(this,F2,`f`))return;e===`end`&&(X(this,F2,!0,`f`),Z(this,M2,`f`).call(this));let n=Z(this,P2,`f`)[e];if(n&&(Z(this,P2,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!Z(this,R2,`f`)&&!n?.length&&Promise.reject(e),Z(this,A2,`f`).call(this,e),Z(this,N2,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!Z(this,R2,`f`)&&!n?.length&&Promise.reject(e),Z(this,A2,`f`).call(this,e),Z(this,N2,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,Z(this,T2,`m`,H2).call(this))}async _fromReadableStream(e,t){let n=t?.signal,r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener(`abort`,r));try{Z(this,T2,`m`,G2).call(this),this._connected(null);let t=x$.fromReadableStream(e,this.controller);for await(let e of t)Z(this,T2,`m`,K2).call(this,e);if(t.controller.signal?.aborted)throw new d;Z(this,T2,`m`,q2).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(E2=new WeakMap,D2=new WeakMap,O2=new WeakMap,k2=new WeakMap,A2=new WeakMap,j2=new WeakMap,M2=new WeakMap,N2=new WeakMap,P2=new WeakMap,F2=new WeakMap,I2=new WeakMap,L2=new WeakMap,R2=new WeakMap,z2=new WeakMap,B2=new WeakMap,V2=new WeakMap,W2=new WeakMap,T2=new WeakSet,H2=function(){if(this.receivedMessages.length===0)throw new a(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},U2=function(){if(this.receivedMessages.length===0)throw new a(`stream ended without producing a Message with role=assistant`);let e=this.receivedMessages.at(-1).content.filter(e=>e.type===`text`).map(e=>e.text);if(e.length===0)throw new a(`stream ended without producing a content block with type=text`);return e.join(` `)},G2=function(){this.ended||X(this,E2,void 0,`f`)},K2=function(e){if(this.ended)return;let t=Z(this,T2,`m`,J2).call(this,e);switch(this._emit(`streamEvent`,e,t),e.type){case`content_block_delta`:{let n=t.content.at(-1);switch(e.delta.type){case`text_delta`:n.type===`text`&&this._emit(`text`,e.delta.text,n.text||``);break;case`citations_delta`:n.type===`text`&&this._emit(`citation`,e.delta.citation,n.citations??[]);break;case`input_json_delta`:if(X2(n)&&Z(this,P2,`f`).inputJson?.length){let t;try{t=n.input}catch(e){Z(this,W2,`f`).call(this,Z(this,T2,`m`,Y2).call(this,n,e));break}this._emit(`inputJson`,e.delta.partial_json,t)}break;case`thinking_delta`:n.type===`thinking`&&this._emit(`thinking`,e.delta.thinking,n.thinking);break;case`signature_delta`:n.type===`thinking`&&this._emit(`signature`,n.signature);break;case`compaction_delta`:n.type===`compaction`&&n.content&&this._emit(`compaction`,n.content);break;default:e.delta}break}case`message_stop`:this._addMessageParam(t),this._addMessage(h2(t,Z(this,D2,`f`),{logger:Z(this,V2,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:X(this,E2,t,`f`);break;case`content_block_start`:case`message_delta`:break}},q2=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);let e=Z(this,E2,`f`);if(!e)throw new a(`request ended without sending any chunks`);return X(this,E2,void 0,`f`),h2(e,Z(this,D2,`f`),{logger:Z(this,V2,`f`)})},J2=function(e){let t=Z(this,E2,`f`);if(e.type===`message_start`){if(t)throw new a(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new a(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case`message_stop`:return t;case`message_delta`:return t.container=e.delta.container,t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,e.delta.stop_details!=null&&(t.stop_details=e.delta.stop_details),t.usage.output_tokens=e.usage.output_tokens,t.context_management=e.context_management,e.usage.input_tokens!=null&&(t.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(t.usage.server_tool_use=e.usage.server_tool_use),e.usage.iterations!=null&&(t.usage.iterations=e.usage.iterations),e.usage.fallback_credit!=null&&(t.usage.fallback_credit=e.usage.fallback_credit),t;case`content_block_start`:return t.content.push(e.content_block),e.content_block.type===`fallback`&&(t.model=e.content_block.to.model),t;case`content_block_delta`:{let n=t.content.at(e.index);switch(e.delta.type){case`text_delta`:n?.type===`text`&&(t.content[e.index]={...n,text:(n.text||``)+e.delta.text});break;case`citations_delta`:n?.type===`text`&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case`input_json_delta`:if(n&&X2(n)){let r=(n.__json_buf||``)+e.delta.partial_json;t.content[e.index]=w2(n,r)}break;case`thinking_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case`signature_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,signature:e.delta.signature});break;case`compaction_delta`:n?.type===`compaction`&&(t.content[e.index]={...n,content:(n.content||``)+e.delta.content,encrypted_content:e.delta.encrypted_content});break;default:e.delta}return t}case`content_block_stop`:{let n=t.content.at(e.index);if(n&&X2(n)&&`__json_buf`in n){let e;try{e=n.input}catch(t){e={},Z(this,W2,`f`).call(this,Z(this,T2,`m`,Y2).call(this,n,t))}Object.defineProperty(n,"input",{value:e,enumerable:!0,configurable:!0,writable:!0})}return t}}},Y2=function(e,t){let n=e[C2];return new a(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${t}. JSON: ${n}`)},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`streamEvent`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new x$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Q2(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var $2=`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:
|
|
222
222
|
1. Task Overview
|
|
223
223
|
The user's core request and success criteria
|
|
224
224
|
Any clarifications or constraints they specified
|
|
@@ -240,20 +240,20 @@ User preferences or style requirements
|
|
|
240
240
|
Domain-specific details that aren't obvious
|
|
241
241
|
Any promises made to the user
|
|
242
242
|
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.
|
|
243
|
-
Wrap your summary in <summary></summary> tags.`,K2,q2,J2,Y2,X2,Z2,Q2,$2,e4,t4,n4,r4=class{constructor(e,t,n){K2.add(this),this.client=e,q2.set(this,!1),J2.set(this,!1),Y2.set(this,void 0),X2.set(this,void 0),Z2.set(this,void 0),Q2.set(this,void 0),$2.set(this,void 0),e4.set(this,0),X(this,Y2,{params:{...t,messages:structuredClone(t.messages)}},`f`);let r=p1(t.tools,t.messages);X(this,X2,{...n,headers:Q([u1(`BetaToolRunner`),r.length?{[c1]:r.join(`, `)}:void 0,n?.headers])},`f`),X(this,$2,W2(),`f`),t.compactionControl?.enabled&&console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[(q2=new WeakMap,J2=new WeakMap,Y2=new WeakMap,X2=new WeakMap,Z2=new WeakMap,Q2=new WeakMap,$2=new WeakMap,e4=new WeakMap,K2=new WeakSet,t4=async function(){let e=Z(this,Y2,`f`).params.compactionControl;if(!e||!e.enabled)return!1;let t=0;if(Z(this,Z2,`f`)!==void 0)try{let e=await Z(this,Z2,`f`);t=e.usage.input_tokens+(e.usage.cache_creation_input_tokens??0)+(e.usage.cache_read_input_tokens??0)+e.usage.output_tokens}catch{return!1}let n=e.contextTokenThreshold??1e5;if(t<n)return!1;let r=e.model??Z(this,Y2,`f`).params.model,i=e.summaryPrompt??G2,o=Z(this,Y2,`f`).params.messages;if(o[o.length-1].role===`assistant`){let e=o[o.length-1];if(Array.isArray(e.content)){let t=e.content.filter(e=>e.type!==`tool_use`);t.length===0?o.pop():e.content=t}}let s=await this.client.beta.messages.create({model:r,messages:[...o,{role:`user`,content:[{type:`text`,text:i}]}],max_tokens:Z(this,Y2,`f`).params.max_tokens},{signal:Z(this,X2,`f`).signal,headers:Q([Z(this,X2,`f`).headers,u1(`compaction`)])});if(s.content[0]?.type!==`text`)throw new a(`Expected text response for compaction`);return Z(this,Y2,`f`).params.messages=[{role:`user`,content:s.content}],!0},Symbol.asyncIterator)](){var e;if(Z(this,q2,`f`))throw new a(`Cannot iterate over a consumed stream`);X(this,q2,!0,`f`),X(this,J2,!0,`f`),X(this,Q2,void 0,`f`);try{for(;;){let t;try{if(Z(this,Y2,`f`).params.max_iterations&&Z(this,e4,`f`)>=Z(this,Y2,`f`).params.max_iterations)break;X(this,J2,!1,`f`),X(this,Q2,void 0,`f`),X(this,e4,(e=Z(this,e4,`f`),e++,e),`f`),X(this,Z2,void 0,`f`);let{max_iterations:n,compactionControl:r,...i}=Z(this,Y2,`f`).params;if(i.stream?(t=this.client.beta.messages.stream({...i},Z(this,X2,`f`)),X(this,Z2,t.finalMessage(),`f`),Z(this,Z2,`f`).catch(()=>{}),yield t):(X(this,Z2,this.client.beta.messages.create({...i,stream:!1},Z(this,X2,`f`)),`f`),yield Z(this,Z2,`f`)),!await Z(this,K2,`m`,t4).call(this)){if(!Z(this,J2,`f`)){let e=await Z(this,Z2,`f`);if(Z(this,Y2,`f`).params.messages.push({role:e.role,content:e.content}),e.stop_reason===`refusal`)break}let e=await Z(this,K2,`m`,n4).call(this,Z(this,Y2,`f`).params.messages.at(-1));if(e)Z(this,Y2,`f`).params.messages.push(e);else if(!Z(this,J2,`f`))break}}finally{t&&t.abort()}}if(!Z(this,Z2,`f`))throw new a(`ToolRunner concluded without a message from the server`);Z(this,$2,`f`).resolve(await Z(this,Z2,`f`))}catch(e){throw X(this,q2,!1,`f`),Z(this,$2,`f`).promise.catch(()=>{}),Z(this,$2,`f`).reject(e),X(this,$2,W2(),`f`),e}}setMessagesParams(e){typeof e==`function`?Z(this,Y2,`f`).params=e(Z(this,Y2,`f`).params):Z(this,Y2,`f`).params=e,X(this,J2,!0,`f`),X(this,Q2,void 0,`f`)}setRequestOptions(e){typeof e==`function`?X(this,X2,e(Z(this,X2,`f`)),`f`):X(this,X2,{...Z(this,X2,`f`),...e},`f`)}async generateToolResponse(e=Z(this,X2,`f`).signal){let t=await Z(this,Z2,`f`)??this.params.messages.at(-1);return t?Z(this,K2,`m`,n4).call(this,t,e):null}done(){return Z(this,$2,`f`).promise}async runUntilDone(){if(!Z(this,q2,`f`))for await(let e of this);return this.done()}get params(){return Z(this,Y2,`f`).params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}};n4=async function(e,t=Z(this,X2,`f`).signal){return Z(this,Q2,`f`)===void 0&&X(this,Q2,i4(Z(this,Y2,`f`).params,e,{...Z(this,X2,`f`),signal:t}),`f`),Z(this,Q2,`f`)};async function i4(e,t=e.messages.at(-1),n){if(!t||t.role!==`assistant`||!t.content||typeof t.content==`string`)return null;let r=t.content.filter(e=>e.type===`tool_use`);if(r.length===0)return null;let i=o4(e);return{role:`user`,content:await Promise.all(r.map(async t=>{let r=e.tools.find(e=>(`name`in e?e.name:e.mcp_server_name)===t.name);if(!r||!(`run`in r)||!i.has(t.name))return a4(t);try{let e=t.input;`parse`in r&&r.parse&&(e=r.parse(e));let i=await r.run(e,{toolUse:t,toolUseBlock:t,signal:n?.signal});return{type:`tool_result`,tool_use_id:t.id,content:i}}catch(e){return{type:`tool_result`,tool_use_id:t.id,content:e instanceof Q1?e.content:`Error: ${e instanceof Error?e.message:String(e)}`,is_error:!0}}}))}}function a4(e){return{type:`tool_result`,tool_use_id:e.id,content:`Error: Tool '${e.name}' not found`,is_error:!0}}function o4(e){let t=new Set;for(let n of e.tools)`run`in n&&t.add(n.name);for(let n of e.messages)if(!(n.role!==`system`||typeof n.content==`string`))for(let e of n.content)s4(e,t);return t}function s4(e,t){switch(e.type){case`tool_removal`:case`tool_addition`:c4(e,t);break;case`mid_conv_system`:for(let n of e.content)(n.type===`tool_removal`||n.type===`tool_addition`)&&c4(n,t);break;default:break}}function c4(e,t){let n=l4(e.tool);n!==void 0&&(e.type===`tool_removal`?t.delete(n):t.add(n))}function l4(e){switch(e.type){case`tool_reference`:return e.name;default:return}}var u4={"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`,"claude-opus-4-0":`June 15th, 2026`,"claude-opus-4-20250514":`June 15th, 2026`,"claude-sonnet-4-0":`June 15th, 2026`,"claude-sonnet-4-20250514":`June 15th, 2026`,"claude-opus-4-1":`August 5th, 2026`,"claude-opus-4-1-20250805":`August 5th, 2026`,"claude-mythos-preview":`June 30th, 2026`},d4=[`claude-mythos-preview`,`claude-opus-4-6`],f4=class extends Z${constructor(){super(...arguments),this.batches=new i2(this._client)}create(e,t){let n=p4(e),{betas:r,user_profile_id:i,...a}=n;a.model in u4&&console.warn(`The model '${a.model}' is deprecated and will reach end-of-life on ${u4[a.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),d4.includes(a.model)&&a.thinking&&a.thinking.type===`enabled`&&console.warn(`Using Claude with ${a.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 o=this._client._options.timeout;if(!a.stream&&o==null){let e=a2[a.model]??void 0;o=this._client.calculateNonstreamingTimeout(a.max_tokens,e)}let s=m1(a.tools,a.messages);return this._client.post(`/v1/messages?beta=true`,{body:a,timeout:o??6e5,...t,headers:Q([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()},...i==null?void 0:{"anthropic-user-profile-id":i}},s,t?.headers]),stream:n.stream??!1})}parse(e,t){return t={...t,headers:Q([{"anthropic-beta":[...e.betas??[],`structured-outputs-2025-12-15`].toString()},t?.headers])},this.create(e,t).then(t=>c2(t,e,{logger:this._client.logger??console}))}stream(e,t){return U2.createMessage(this,e,t)}countTokens(e,t){let{betas:n,user_profile_id:r,...i}=p4(e);return this._client.post(`/v1/messages/count_tokens?beta=true`,{body:i,...t,headers:Q([{"anthropic-beta":[...n??[],`token-counting-2024-11-01`].toString(),...r==null?void 0:{"anthropic-user-profile-id":r}},t?.headers])})}toolRunner(e,t){return new r4(this._client,e,t)}};function p4(e){if(!e.output_format)return e;if(e.output_config?.format)throw new a(`Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).`);let{output_format:t,...n}=e;return{...n,output_config:{...e.output_config,format:t}}}f4.Batches=i2,f4.BetaToolRunner=r4,f4.ToolError=Q1;var m4=class extends Z${list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/sessions/${e}/events?beta=true`,N$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}send(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/sessions/${e}/events?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}stream(e,t={},n){let{betas:r,...i}=t??{};return this._client.get($`/v1/sessions/${e}/events/stream?beta=true`,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers]),stream:!0})}toolRunner(e,t){return new V0(e,{...t,client:this._client})}};m4.SessionToolRunner=V0;var h4=class extends Z${retrieve(e,t,n){let{session_id:r,betas:i}=t;return this._client.get($`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{session_id:r,betas:i,...a}=t;return this._client.post($`/v1/sessions/${r}/resources/${e}?beta=true`,{body:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/sessions/${e}/resources?beta=true`,N$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{session_id:r,betas:i}=t;return this._client.delete($`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}add(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/sessions/${e}/resources?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},g4=class extends Z${list(e,t,n){let{session_id:r,betas:i,...a}=t;return this._client.getAPIList($`/v1/sessions/${r}/threads/${e}/events?beta=true`,N$,{query:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}stream(e,t,n){let{session_id:r,betas:i,...a}=t;return this._client.get($`/v1/sessions/${r}/threads/${e}/stream?beta=true`,{query:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers]),stream:!0})}},_4=class extends Z${constructor(){super(...arguments),this.events=new g4(this._client)}retrieve(e,t,n){let{session_id:r,betas:i}=t;return this._client.get($`/v1/sessions/${r}/threads/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/sessions/${e}/threads?beta=true`,N$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t,n){let{session_id:r,betas:i}=t;return this._client.post($`/v1/sessions/${r}/threads/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};_4.Events=g4;var v4=class extends Z${constructor(){super(...arguments),this.events=new m4(this._client),this.resources=new h4(this._client),this.threads=new _4(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/sessions?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/sessions/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/sessions/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/sessions?beta=true`,P$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/sessions/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/sessions/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};v4.Events=m4,v4.Resources=h4,v4.Threads=_4;var y4=class extends Z${create(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/skills/${e}/versions?beta=true`,z$({body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])},this._client,!1))}retrieve(e,t,n){let{skill_id:r,betas:i}=t;return this._client.get($`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/skills/${e}/versions?beta=true`,N$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}delete(e,t,n){let{skill_id:r,betas:i}=t;return this._client.delete($`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}download(e,t,n){let{skill_id:r,betas:i}=t;return this._client.get($`/v1/skills/${r}/versions/${e}/content?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString(),Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}},b4=class extends Z${constructor(){super(...arguments),this.versions=new y4(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/skills?beta=true`,z$({body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`skills-2025-10-02`].toString()},t?.headers])},this._client,!1))}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/skills/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/skills?beta=true`,N$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`skills-2025-10-02`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/skills/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}};b4.Versions=y4;var x4=class extends Z${create(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/tunnels/${e}/certificates?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`mcp-tunnels-2026-06-22`].toString()},n?.headers])})}retrieve(e,t,n){let{tunnel_id:r,betas:i}=t;return this._client.get($`/v1/tunnels/${r}/certificates/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`mcp-tunnels-2026-06-22`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/tunnels/${e}/certificates?beta=true`,N$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`mcp-tunnels-2026-06-22`].toString()},n?.headers])})}archive(e,t,n){let{tunnel_id:r,betas:i}=t;return this._client.post($`/v1/tunnels/${r}/certificates/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`mcp-tunnels-2026-06-22`].toString()},n?.headers])})}},S4=class extends Z${constructor(){super(...arguments),this.certificates=new x4(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/tunnels?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`mcp-tunnels-2026-06-22`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/tunnels/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`mcp-tunnels-2026-06-22`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/tunnels?beta=true`,N$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`mcp-tunnels-2026-06-22`].toString()},t?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/tunnels/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`mcp-tunnels-2026-06-22`].toString()},n?.headers])})}revealToken(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/tunnels/${e}/reveal_token?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`mcp-tunnels-2026-06-22`].toString()},n?.headers])})}rotateToken(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/tunnels/${e}/rotate_token?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`mcp-tunnels-2026-06-22`].toString()},n?.headers])})}};S4.Certificates=x4;var C4=class extends Z${create(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/vaults/${e}/credentials?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}retrieve(e,t,n){let{vault_id:r,betas:i}=t;return this._client.get($`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{vault_id:r,betas:i,...a}=t;return this._client.post($`/v1/vaults/${r}/credentials/${e}?beta=true`,{body:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/vaults/${e}/credentials?beta=true`,N$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{vault_id:r,betas:i}=t;return this._client.delete($`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t,n){let{vault_id:r,betas:i}=t;return this._client.post($`/v1/vaults/${r}/credentials/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}mcpOAuthValidate(e,t,n){let{vault_id:r,betas:i}=t;return this._client.post($`/v1/vaults/${r}/credentials/${e}/mcp_oauth_validate?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},w4=class extends Z${constructor(){super(...arguments),this.credentials=new C4(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/vaults?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/vaults/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/vaults/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/vaults?beta=true`,N$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/vaults/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/vaults/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};w4.Credentials=C4;var T4=class extends Z${constructor(){super(...arguments),this.models=new _1(this._client),this.messages=new f4(this._client),this.agents=new T1(this._client),this.environments=new $0(this._client),this.sessions=new v4(this._client),this.deployments=new o1(this._client),this.deploymentRuns=new a1(this._client),this.vaults=new w4(this._client),this.memoryStores=new n2(this._client),this.files=new g1(this._client),this.skills=new b4(this._client),this.webhooks=new C1(this._client),this.userProfiles=new v1(this._client),this.dreams=new s1(this._client),this.tunnels=new S4(this._client)}};T4.Models=_1,T4.Messages=f4,T4.Agents=T1,T4.Environments=$0,T4.Sessions=v4,T4.Deployments=o1,T4.DeploymentRuns=a1,T4.Vaults=w4,T4.MemoryStores=n2,T4.Files=g1,T4.Skills=b4,T4.Webhooks=C1,T4.UserProfiles=v1,T4.Dreams=s1,T4.Tunnels=S4;var E4=class extends Z${create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/complete`,{body:r,timeout:this._client._options.timeout??6e5,...t,headers:Q([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers]),stream:e.stream??!1})}};function D4(e){return e?.output_config?.format}function O4(e,t,n){let r=D4(t);return!t||!(`parse`in(r??{}))?{...e,content:e.content.map(e=>e.type===`text`?Object.defineProperty({...e},"parsed_output",{value:null,enumerable:!1}):e),parsed_output:null}:k4(e,t,n)}function k4(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let n=A4(t,e.text);return r===null&&(r=n),Object.defineProperty({...e},"parsed_output",{value:n,enumerable:!1})}return e});return{...e,content:i,parsed_output:r}}function A4(e,t){let n=D4(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new a(`Failed to parse structured output: ${e}`)}}var j4,M4,N4,P4,F4,I4,L4,R4,z4,B4,V4,H4,U4,W4,G4,K4,q4,J4,Y4,X4,Z4,Q4,$4,e3;function t3(e){return e.type===`tool_use`||e.type===`server_tool_use`}var n3=class e{constructor(e,t){j4.add(this),this.messages=[],this.receivedMessages=[],M4.set(this,void 0),N4.set(this,null),this.controller=new AbortController,P4.set(this,void 0),F4.set(this,()=>{}),I4.set(this,()=>{}),L4.set(this,void 0),R4.set(this,()=>{}),z4.set(this,()=>{}),B4.set(this,{}),V4.set(this,!1),H4.set(this,!1),U4.set(this,!1),W4.set(this,!1),G4.set(this,void 0),K4.set(this,void 0),q4.set(this,void 0),X4.set(this,e=>{if(X(this,H4,!0,`f`),l(e)&&(e=new d),e instanceof d)return X(this,U4,!0,`f`),this._emit(`abort`,e);if(e instanceof a)return this._emit(`error`,e);if(e instanceof Error){let t=new a(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new a(String(e)))}),X(this,P4,new Promise((e,t)=>{X(this,F4,e,`f`),X(this,I4,t,`f`)}),`f`),X(this,L4,new Promise((e,t)=>{X(this,R4,e,`f`),X(this,z4,t,`f`)}),`f`),Z(this,P4,`f`).catch(()=>{}),Z(this,L4,`f`).catch(()=>{}),X(this,N4,e,`f`),X(this,q4,t?.logger??console,`f`)}get response(){return Z(this,G4,`f`)}get request_id(){return Z(this,K4,`f`)}async withResponse(){X(this,W4,!0,`f`);let e=await Z(this,P4,`f`);if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get(`request-id`)}}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,r,{logger:i}={}){let a=new e(n,{logger:i});for(let e of n.messages)a._addMessageParam(e);return X(a,N4,{...n,stream:!0},`f`),a._run(()=>a._createMessage(t,{...n,stream:!0},{...r,headers:{...r?.headers,[l1]:`stream`}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit(`end`)},Z(this,X4,`f`))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit(`message`,e)}async _createMessage(e,t,n){let r=n?.signal,i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener(`abort`,i));try{Z(this,j4,`m`,Z4).call(this);let{response:r,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(let e of i)Z(this,j4,`m`,Q4).call(this,e);if(i.controller.signal?.aborted)throw new d;Z(this,j4,`m`,$4).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(X(this,G4,e,`f`),X(this,K4,e?.headers.get(`request-id`),`f`),Z(this,F4,`f`).call(this,e),this._emit(`connect`))}get ended(){return Z(this,V4,`f`)}get errored(){return Z(this,H4,`f`)}get aborted(){return Z(this,U4,`f`)}abort(){this.controller.abort()}on(e,t){return(Z(this,B4,`f`)[e]||(Z(this,B4,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=Z(this,B4,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(Z(this,B4,`f`)[e]||(Z(this,B4,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{X(this,W4,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){X(this,W4,!0,`f`),await Z(this,L4,`f`)}get currentMessage(){return Z(this,M4,`f`)}async finalMessage(){return await this.done(),Z(this,j4,`m`,J4).call(this)}async finalText(){return await this.done(),Z(this,j4,`m`,Y4).call(this)}_emit(e,...t){if(Z(this,V4,`f`))return;e===`end`&&(X(this,V4,!0,`f`),Z(this,R4,`f`).call(this));let n=Z(this,B4,`f`)[e];if(n&&(Z(this,B4,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!Z(this,W4,`f`)&&!n?.length&&Promise.reject(e),Z(this,I4,`f`).call(this,e),Z(this,z4,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!Z(this,W4,`f`)&&!n?.length&&Promise.reject(e),Z(this,I4,`f`).call(this,e),Z(this,z4,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,Z(this,j4,`m`,J4).call(this))}async _fromReadableStream(e,t){let n=t?.signal,r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener(`abort`,r));try{Z(this,j4,`m`,Z4).call(this),this._connected(null);let t=p$.fromReadableStream(e,this.controller);for await(let e of t)Z(this,j4,`m`,Q4).call(this,e);if(t.controller.signal?.aborted)throw new d;Z(this,j4,`m`,$4).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(M4=new WeakMap,N4=new WeakMap,P4=new WeakMap,F4=new WeakMap,I4=new WeakMap,L4=new WeakMap,R4=new WeakMap,z4=new WeakMap,B4=new WeakMap,V4=new WeakMap,H4=new WeakMap,U4=new WeakMap,W4=new WeakMap,G4=new WeakMap,K4=new WeakMap,q4=new WeakMap,X4=new WeakMap,j4=new WeakSet,J4=function(){if(this.receivedMessages.length===0)throw new a(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},Y4=function(){if(this.receivedMessages.length===0)throw new a(`stream ended without producing a Message with role=assistant`);let e=this.receivedMessages.at(-1).content.filter(e=>e.type===`text`).map(e=>e.text);if(e.length===0)throw new a(`stream ended without producing a content block with type=text`);return e.join(` `)},Z4=function(){this.ended||X(this,M4,void 0,`f`)},Q4=function(e){if(this.ended)return;let t=Z(this,j4,`m`,e3).call(this,e);switch(this._emit(`streamEvent`,e,t),e.type){case`content_block_delta`:{let n=t.content.at(-1);switch(e.delta.type){case`text_delta`:n.type===`text`&&this._emit(`text`,e.delta.text,n.text||``);break;case`citations_delta`:n.type===`text`&&this._emit(`citation`,e.delta.citation,n.citations??[]);break;case`input_json_delta`:t3(n)&&Z(this,B4,`f`).inputJson?.length&&this._emit(`inputJson`,e.delta.partial_json,n.input);break;case`thinking_delta`:n.type===`thinking`&&this._emit(`thinking`,e.delta.thinking,n.thinking);break;case`signature_delta`:n.type===`thinking`&&this._emit(`signature`,n.signature);break;default:e.delta}break}case`message_stop`:this._addMessageParam(t),this._addMessage(O4(t,Z(this,N4,`f`),{logger:Z(this,q4,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:X(this,M4,t,`f`);break;case`content_block_start`:case`message_delta`:break}},$4=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);let e=Z(this,M4,`f`);if(!e)throw new a(`request ended without sending any chunks`);return X(this,M4,void 0,`f`),O4(e,Z(this,N4,`f`),{logger:Z(this,q4,`f`)})},e3=function(e){let t=Z(this,M4,`f`);if(e.type===`message_start`){if(t)throw new a(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new a(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case`message_stop`:return t;case`message_delta`:return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,e.delta.stop_details!=null&&(t.stop_details=e.delta.stop_details),t.usage.output_tokens=e.usage.output_tokens,e.usage.input_tokens!=null&&(t.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(t.usage.server_tool_use=e.usage.server_tool_use),t;case`content_block_start`:return t.content.push({...e.content_block}),t;case`content_block_delta`:{let n=t.content.at(e.index);switch(e.delta.type){case`text_delta`:n?.type===`text`&&(t.content[e.index]={...n,text:(n.text||``)+e.delta.text});break;case`citations_delta`:n?.type===`text`&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case`input_json_delta`:if(n&&t3(n)){let r=(n.__json_buf||``)+e.delta.partial_json;t.content[e.index]=g2(n,r)}break;case`thinking_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case`signature_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,signature:e.delta.signature});break;default:e.delta}return t}case`content_block_stop`:{let n=t.content.at(e.index);return n&&t3(n)&&`__json_buf`in n&&Object.defineProperty(n,"input",{value:n.input,enumerable:!0,configurable:!0,writable:!0}),t}}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`streamEvent`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new p$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},r3=class extends Z${create(e,t){let{user_profile_id:n,...r}=e;return this._client.post(`/v1/messages/batches`,{body:r,...t,headers:Q([{...n==null?void 0:{"anthropic-user-profile-id":n}},t?.headers])})}retrieve(e,t){return this._client.get($`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/v1/messages/batches`,M$,{query:e,...t})}delete(e,t){return this._client.delete($`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post($`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let n=await this.retrieve(e);if(!n.results_url)throw new a(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:Q([{Accept:`application/binary`},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>r2.fromResponse(t.response,t.controller))}},i3=class extends Z${constructor(){super(...arguments),this.batches=new r3(this._client)}create(e,t){let{user_profile_id:n,...r}=e;r.model in a3&&console.warn(`The model '${r.model}' is deprecated and will reach end-of-life on ${a3[r.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),o3.includes(r.model)&&r.thinking&&r.thinking.type===`enabled`&&console.warn(`Using Claude with ${r.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 i=this._client._options.timeout;if(!r.stream&&i==null){let e=a2[r.model]??void 0;i=this._client.calculateNonstreamingTimeout(r.max_tokens,e)}let a=m1(r.tools,r.messages);return this._client.post(`/v1/messages`,{body:r,timeout:i??6e5,...t,headers:Q([{...n==null?void 0:{"anthropic-user-profile-id":n}},a,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(t=>k4(t,e,{logger:this._client.logger??console}))}stream(e,t){return n3.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){let{user_profile_id:n,...r}=e;return this._client.post(`/v1/messages/count_tokens`,{body:r,...t,headers:Q([{...n==null?void 0:{"anthropic-user-profile-id":n}},t?.headers])})}},a3={"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`,"claude-opus-4-0":`June 15th, 2026`,"claude-opus-4-20250514":`June 15th, 2026`,"claude-sonnet-4-0":`June 15th, 2026`,"claude-sonnet-4-20250514":`June 15th, 2026`,"claude-opus-4-1":`August 5th, 2026`,"claude-opus-4-1-20250805":`August 5th, 2026`,"claude-mythos-preview":`June 30th, 2026`},o3=[`claude-mythos-preview`,`claude-opus-4-6`];i3.Batches=r3;var s3=class extends Z${retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/models/${e}`,{...n,headers:Q([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/models`,M$,{query:r,...t,headers:Q([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},c3,l3,u3,d3,f3=`\\n\\nHuman:`,p3=`\\n\\nAssistant:`,m3=class{get credentials(){return this._authState.provider}constructor({baseURL:e=EQ(`ANTHROPIC_BASE_URL`),apiKey:t,authToken:n,webhookKey:r=EQ(`ANTHROPIC_WEBHOOK_SIGNING_KEY`)??null,...i}={}){if(c3.add(this),this._requestAuthFlags=new WeakMap,u3.set(this,void 0),t===void 0&&(t=i.profile==null?EQ(`ANTHROPIC_API_KEY`)??null:null),n===void 0&&(n=i.profile==null?EQ(`ANTHROPIC_AUTH_TOKEN`)??null:null),i.profile!=null&&(i.credentials!=null||i.config!=null))throw TypeError("Pass at most one of `profile`, `credentials`, or `config`.");let o={apiKey:t,authToken:n,webhookKey:r,...i,baseURL:e||`https://api.anthropic.com`};if(!o.dangerouslyAllowBrowser&&wZ())throw new a(`It looks like you're running in a browser-like environment.
|
|
243
|
+
Wrap your summary in <summary></summary> tags.`,e4,t4,n4,r4,i4,a4,o4,s4,c4,l4,u4,d4=class{constructor(e,t,n){e4.add(this),this.client=e,t4.set(this,!1),n4.set(this,!1),r4.set(this,void 0),i4.set(this,void 0),a4.set(this,void 0),o4.set(this,void 0),s4.set(this,void 0),c4.set(this,0),X(this,r4,{params:{...t,messages:structuredClone(t.messages)}},`f`);let r=x1(t.tools,t.messages);X(this,i4,{...n,headers:Q([v1(`BetaToolRunner`),r.length?{[g1]:r.join(`, `)}:void 0,n?.headers])},`f`),X(this,s4,Q2(),`f`),t.compactionControl?.enabled&&console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[(t4=new WeakMap,n4=new WeakMap,r4=new WeakMap,i4=new WeakMap,a4=new WeakMap,o4=new WeakMap,s4=new WeakMap,c4=new WeakMap,e4=new WeakSet,l4=async function(){let e=Z(this,r4,`f`).params.compactionControl;if(!e||!e.enabled)return!1;let t=0;if(Z(this,a4,`f`)!==void 0)try{let e=await Z(this,a4,`f`);t=e.usage.input_tokens+(e.usage.cache_creation_input_tokens??0)+(e.usage.cache_read_input_tokens??0)+e.usage.output_tokens}catch{return!1}let n=e.contextTokenThreshold??1e5;if(t<n)return!1;let r=e.model??Z(this,r4,`f`).params.model,i=e.summaryPrompt??$2,o=Z(this,r4,`f`).params.messages;if(o[o.length-1].role===`assistant`){let e=o[o.length-1];if(Array.isArray(e.content)){let t=e.content.filter(e=>e.type!==`tool_use`);t.length===0?o.pop():e.content=t}}let s=await this.client.beta.messages.create({model:r,messages:[...o,{role:`user`,content:[{type:`text`,text:i}]}],max_tokens:Z(this,r4,`f`).params.max_tokens},{signal:Z(this,i4,`f`).signal,headers:Q([Z(this,i4,`f`).headers,v1(`compaction`)])});if(s.content[0]?.type!==`text`)throw new a(`Expected text response for compaction`);return Z(this,r4,`f`).params.messages=[{role:`user`,content:s.content}],!0},Symbol.asyncIterator)](){var e;if(Z(this,t4,`f`))throw new a(`Cannot iterate over a consumed stream`);X(this,t4,!0,`f`),X(this,n4,!0,`f`),X(this,o4,void 0,`f`);try{for(;;){let t;try{if(Z(this,r4,`f`).params.max_iterations&&Z(this,c4,`f`)>=Z(this,r4,`f`).params.max_iterations)break;X(this,n4,!1,`f`),X(this,o4,void 0,`f`),X(this,c4,(e=Z(this,c4,`f`),e++,e),`f`),X(this,a4,void 0,`f`);let{max_iterations:n,compactionControl:r,...i}=Z(this,r4,`f`).params;if(i.stream?(t=this.client.beta.messages.stream({...i},Z(this,i4,`f`)),X(this,a4,t.finalMessage(),`f`),Z(this,a4,`f`).catch(()=>{}),yield t):(X(this,a4,this.client.beta.messages.create({...i,stream:!1},Z(this,i4,`f`)),`f`),yield Z(this,a4,`f`)),!await Z(this,e4,`m`,l4).call(this)){if(!Z(this,n4,`f`)){let e=await Z(this,a4,`f`);if(Z(this,r4,`f`).params.messages.push({role:e.role,content:e.content}),e.stop_reason===`refusal`)break}let e=await Z(this,e4,`m`,u4).call(this,Z(this,r4,`f`).params.messages.at(-1));if(e)Z(this,r4,`f`).params.messages.push(e);else if(!Z(this,n4,`f`))break}}finally{t&&t.abort()}}if(!Z(this,a4,`f`))throw new a(`ToolRunner concluded without a message from the server`);Z(this,s4,`f`).resolve(await Z(this,a4,`f`))}catch(e){throw X(this,t4,!1,`f`),Z(this,s4,`f`).promise.catch(()=>{}),Z(this,s4,`f`).reject(e),X(this,s4,Q2(),`f`),e}}setMessagesParams(e){typeof e==`function`?Z(this,r4,`f`).params=e(Z(this,r4,`f`).params):Z(this,r4,`f`).params=e,X(this,n4,!0,`f`),X(this,o4,void 0,`f`)}setRequestOptions(e){typeof e==`function`?X(this,i4,e(Z(this,i4,`f`)),`f`):X(this,i4,{...Z(this,i4,`f`),...e},`f`)}async generateToolResponse(e=Z(this,i4,`f`).signal){let t=await Z(this,a4,`f`)??this.params.messages.at(-1);return t?Z(this,e4,`m`,u4).call(this,t,e):null}done(){return Z(this,s4,`f`).promise}async runUntilDone(){if(!Z(this,t4,`f`))for await(let e of this);return this.done()}get params(){return Z(this,r4,`f`).params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}};u4=async function(e,t=Z(this,i4,`f`).signal){return Z(this,o4,`f`)===void 0&&X(this,o4,f4(Z(this,r4,`f`).params,e,{...Z(this,i4,`f`),signal:t}),`f`),Z(this,o4,`f`)};async function f4(e,t=e.messages.at(-1),n){if(!t||t.role!==`assistant`||!t.content||typeof t.content==`string`)return null;let r=t.content.filter(e=>e.type===`tool_use`);if(r.length===0)return null;let i=m4(e);return{role:`user`,content:await Promise.all(r.map(async t=>{let r=e.tools.find(e=>(`name`in e?e.name:e.mcp_server_name)===t.name);if(!r||!(`run`in r)||!i.has(t.name))return p4(t);try{let e=t.input;`parse`in r&&r.parse&&(e=r.parse(e));let i=await r.run(e,{toolUse:t,toolUseBlock:t,signal:n?.signal});return{type:`tool_result`,tool_use_id:t.id,content:i}}catch(e){return{type:`tool_result`,tool_use_id:t.id,content:e instanceof o0?e.content:`Error: ${e instanceof Error?e.message:String(e)}`,is_error:!0}}}))}}function p4(e){return{type:`tool_result`,tool_use_id:e.id,content:`Error: Tool '${e.name}' not found`,is_error:!0}}function m4(e){let t=new Set;for(let n of e.tools)`run`in n&&t.add(n.name);for(let n of e.messages)if(!(n.role!==`system`||typeof n.content==`string`))for(let e of n.content)h4(e,t);return t}function h4(e,t){switch(e.type){case`tool_removal`:case`tool_addition`:g4(e,t);break;case`mid_conv_system`:for(let n of e.content)(n.type===`tool_removal`||n.type===`tool_addition`)&&g4(n,t);break;default:break}}function g4(e,t){let n=_4(e.tool);n!==void 0&&(e.type===`tool_removal`?t.delete(n):t.add(n))}function _4(e){switch(e.type){case`tool_reference`:return e.name;default:return}}var v4={"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`,"claude-opus-4-0":`June 15th, 2026`,"claude-opus-4-20250514":`June 15th, 2026`,"claude-sonnet-4-0":`June 15th, 2026`,"claude-sonnet-4-20250514":`June 15th, 2026`,"claude-opus-4-1":`August 5th, 2026`,"claude-opus-4-1-20250805":`August 5th, 2026`,"claude-mythos-preview":`June 30th, 2026`},y4=[`claude-mythos-preview`,`claude-opus-4-6`],b4=class extends a1{constructor(){super(...arguments),this.batches=new f2(this._client)}create(e,t){let n=x4(e),{betas:r,user_profile_id:i,...a}=n;a.model in v4&&console.warn(`The model '${a.model}' is deprecated and will reach end-of-life on ${v4[a.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),y4.includes(a.model)&&a.thinking&&a.thinking.type===`enabled`&&console.warn(`Using Claude with ${a.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 o=this._client._options.timeout;if(!a.stream&&o==null){let e=p2[a.model]??void 0;o=this._client.calculateNonstreamingTimeout(a.max_tokens,e)}let s=S1(a.tools,a.messages);return this._client.post(`/v1/messages?beta=true`,{body:a,timeout:o??6e5,...t,headers:Q([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()},...i==null?void 0:{"anthropic-user-profile-id":i}},s,t?.headers]),stream:n.stream??!1})}parse(e,t){return t={...t,headers:Q([{"anthropic-beta":[...e.betas??[],`structured-outputs-2025-12-15`].toString()},t?.headers])},this.create(e,t).then(t=>g2(t,e,{logger:this._client.logger??console}))}stream(e,t){return Z2.createMessage(this,e,t)}countTokens(e,t){let{betas:n,user_profile_id:r,...i}=x4(e);return this._client.post(`/v1/messages/count_tokens?beta=true`,{body:i,...t,headers:Q([{"anthropic-beta":[...n??[],`token-counting-2024-11-01`].toString(),...r==null?void 0:{"anthropic-user-profile-id":r}},t?.headers])})}toolRunner(e,t){return new d4(this._client,e,t)}};function x4(e){if(!e.output_format)return e;if(e.output_config?.format)throw new a(`Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).`);let{output_format:t,...n}=e;return{...n,output_config:{...e.output_config,format:t}}}b4.Batches=f2,b4.BetaToolRunner=d4,b4.ToolError=o0;var S4=class extends a1{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/sessions/${e}/events?beta=true`,V$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}send(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/sessions/${e}/events?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}stream(e,t={},n){let{betas:r,...i}=t??{};return this._client.get($`/v1/sessions/${e}/events/stream?beta=true`,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers]),stream:!0})}toolRunner(e,t){return new Y0(e,{...t,client:this._client})}};S4.SessionToolRunner=Y0;var C4=class extends a1{retrieve(e,t,n){let{session_id:r,betas:i}=t;return this._client.get($`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{session_id:r,betas:i,...a}=t;return this._client.post($`/v1/sessions/${r}/resources/${e}?beta=true`,{body:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/sessions/${e}/resources?beta=true`,V$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{session_id:r,betas:i}=t;return this._client.delete($`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}add(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/sessions/${e}/resources?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},w4=class extends a1{list(e,t,n){let{session_id:r,betas:i,...a}=t;return this._client.getAPIList($`/v1/sessions/${r}/threads/${e}/events?beta=true`,V$,{query:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}stream(e,t,n){let{session_id:r,betas:i,...a}=t;return this._client.get($`/v1/sessions/${r}/threads/${e}/stream?beta=true`,{query:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers]),stream:!0})}},T4=class extends a1{constructor(){super(...arguments),this.events=new w4(this._client)}retrieve(e,t,n){let{session_id:r,betas:i}=t;return this._client.get($`/v1/sessions/${r}/threads/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/sessions/${e}/threads?beta=true`,V$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t,n){let{session_id:r,betas:i}=t;return this._client.post($`/v1/sessions/${r}/threads/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};T4.Events=w4;var E4=class extends a1{constructor(){super(...arguments),this.events=new S4(this._client),this.resources=new C4(this._client),this.threads=new T4(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/sessions?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/sessions/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/sessions/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/sessions?beta=true`,H$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/sessions/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/sessions/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};E4.Events=S4,E4.Resources=C4,E4.Threads=T4;var D4=class extends a1{create(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/skills/${e}/versions?beta=true`,q$({body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])},this._client,!1))}retrieve(e,t,n){let{skill_id:r,betas:i}=t;return this._client.get($`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/skills/${e}/versions?beta=true`,V$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}delete(e,t,n){let{skill_id:r,betas:i}=t;return this._client.delete($`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}download(e,t,n){let{skill_id:r,betas:i}=t;return this._client.get($`/v1/skills/${r}/versions/${e}/content?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString(),Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}},O4=class extends a1{constructor(){super(...arguments),this.versions=new D4(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/skills?beta=true`,q$({body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`skills-2025-10-02`].toString()},t?.headers])},this._client,!1))}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/skills/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/skills?beta=true`,V$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`skills-2025-10-02`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/skills/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}};O4.Versions=D4;var k4=class extends a1{create(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/tunnels/${e}/certificates?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`mcp-tunnels-2026-06-22`].toString()},n?.headers])})}retrieve(e,t,n){let{tunnel_id:r,betas:i}=t;return this._client.get($`/v1/tunnels/${r}/certificates/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`mcp-tunnels-2026-06-22`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/tunnels/${e}/certificates?beta=true`,V$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`mcp-tunnels-2026-06-22`].toString()},n?.headers])})}archive(e,t,n){let{tunnel_id:r,betas:i}=t;return this._client.post($`/v1/tunnels/${r}/certificates/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`mcp-tunnels-2026-06-22`].toString()},n?.headers])})}},A4=class extends a1{constructor(){super(...arguments),this.certificates=new k4(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/tunnels?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`mcp-tunnels-2026-06-22`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/tunnels/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`mcp-tunnels-2026-06-22`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/tunnels?beta=true`,V$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`mcp-tunnels-2026-06-22`].toString()},t?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/tunnels/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`mcp-tunnels-2026-06-22`].toString()},n?.headers])})}revealToken(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/tunnels/${e}/reveal_token?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`mcp-tunnels-2026-06-22`].toString()},n?.headers])})}rotateToken(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/tunnels/${e}/rotate_token?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`mcp-tunnels-2026-06-22`].toString()},n?.headers])})}};A4.Certificates=k4;var j4=class extends a1{create(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/vaults/${e}/credentials?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}retrieve(e,t,n){let{vault_id:r,betas:i}=t;return this._client.get($`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{vault_id:r,betas:i,...a}=t;return this._client.post($`/v1/vaults/${r}/credentials/${e}?beta=true`,{body:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/vaults/${e}/credentials?beta=true`,V$,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{vault_id:r,betas:i}=t;return this._client.delete($`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t,n){let{vault_id:r,betas:i}=t;return this._client.post($`/v1/vaults/${r}/credentials/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}mcpOAuthValidate(e,t,n){let{vault_id:r,betas:i}=t;return this._client.post($`/v1/vaults/${r}/credentials/${e}/mcp_oauth_validate?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},M4=class extends a1{constructor(){super(...arguments),this.credentials=new j4(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/vaults?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/vaults/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/vaults/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/vaults?beta=true`,V$,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/vaults/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/vaults/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};M4.Credentials=j4;var N4=class extends a1{constructor(){super(...arguments),this.models=new T1(this._client),this.messages=new b4(this._client),this.agents=new N1(this._client),this.environments=new s2(this._client),this.sessions=new E4(this._client),this.deployments=new m1(this._client),this.deploymentRuns=new p1(this._client),this.vaults=new M4(this._client),this.memoryStores=new u2(this._client),this.files=new w1(this._client),this.skills=new O4(this._client),this.webhooks=new j1(this._client),this.userProfiles=new E1(this._client),this.dreams=new h1(this._client),this.tunnels=new A4(this._client)}};N4.Models=T1,N4.Messages=b4,N4.Agents=N1,N4.Environments=s2,N4.Sessions=E4,N4.Deployments=m1,N4.DeploymentRuns=p1,N4.Vaults=M4,N4.MemoryStores=u2,N4.Files=w1,N4.Skills=O4,N4.Webhooks=j1,N4.UserProfiles=E1,N4.Dreams=h1,N4.Tunnels=A4;var P4=class extends a1{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/complete`,{body:r,timeout:this._client._options.timeout??6e5,...t,headers:Q([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers]),stream:e.stream??!1})}};function F4(e){return e?.output_config?.format}function I4(e,t,n){let r=F4(t);return!t||!(`parse`in(r??{}))?{...e,content:e.content.map(e=>e.type===`text`?Object.defineProperty({...e},"parsed_output",{value:null,enumerable:!1}):e),parsed_output:null}:L4(e,t,n)}function L4(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let n=R4(t,e.text);return r===null&&(r=n),Object.defineProperty({...e},"parsed_output",{value:n,enumerable:!1})}return e});return{...e,content:i,parsed_output:r}}function R4(e,t){let n=F4(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new a(`Failed to parse structured output: ${e}`)}}var z4,B4,V4,H4,U4,W4,G4,K4,q4,J4,Y4,X4,Z4,Q4,$4,e3,t3,n3,r3,i3,a3,o3,s3,c3;function l3(e){return e.type===`tool_use`||e.type===`server_tool_use`}var u3=class e{constructor(e,t){z4.add(this),this.messages=[],this.receivedMessages=[],B4.set(this,void 0),V4.set(this,null),this.controller=new AbortController,H4.set(this,void 0),U4.set(this,()=>{}),W4.set(this,()=>{}),G4.set(this,void 0),K4.set(this,()=>{}),q4.set(this,()=>{}),J4.set(this,{}),Y4.set(this,!1),X4.set(this,!1),Z4.set(this,!1),Q4.set(this,!1),$4.set(this,void 0),e3.set(this,void 0),t3.set(this,void 0),i3.set(this,e=>{if(X(this,X4,!0,`f`),l(e)&&(e=new d),e instanceof d)return X(this,Z4,!0,`f`),this._emit(`abort`,e);if(e instanceof a)return this._emit(`error`,e);if(e instanceof Error){let t=new a(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new a(String(e)))}),X(this,H4,new Promise((e,t)=>{X(this,U4,e,`f`),X(this,W4,t,`f`)}),`f`),X(this,G4,new Promise((e,t)=>{X(this,K4,e,`f`),X(this,q4,t,`f`)}),`f`),Z(this,H4,`f`).catch(()=>{}),Z(this,G4,`f`).catch(()=>{}),X(this,V4,e,`f`),X(this,t3,t?.logger??console,`f`)}get response(){return Z(this,$4,`f`)}get request_id(){return Z(this,e3,`f`)}async withResponse(){X(this,Q4,!0,`f`);let e=await Z(this,H4,`f`);if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get(`request-id`)}}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,r,{logger:i}={}){let a=new e(n,{logger:i});for(let e of n.messages)a._addMessageParam(e);return X(a,V4,{...n,stream:!0},`f`),a._run(()=>a._createMessage(t,{...n,stream:!0},{...r,headers:{...r?.headers,[_1]:`stream`}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit(`end`)},Z(this,i3,`f`))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit(`message`,e)}async _createMessage(e,t,n){let r=n?.signal,i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener(`abort`,i));try{Z(this,z4,`m`,a3).call(this);let{response:r,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(let e of i)Z(this,z4,`m`,o3).call(this,e);if(i.controller.signal?.aborted)throw new d;Z(this,z4,`m`,s3).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(X(this,$4,e,`f`),X(this,e3,e?.headers.get(`request-id`),`f`),Z(this,U4,`f`).call(this,e),this._emit(`connect`))}get ended(){return Z(this,Y4,`f`)}get errored(){return Z(this,X4,`f`)}get aborted(){return Z(this,Z4,`f`)}abort(){this.controller.abort()}on(e,t){return(Z(this,J4,`f`)[e]||(Z(this,J4,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=Z(this,J4,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(Z(this,J4,`f`)[e]||(Z(this,J4,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{X(this,Q4,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){X(this,Q4,!0,`f`),await Z(this,G4,`f`)}get currentMessage(){return Z(this,B4,`f`)}async finalMessage(){return await this.done(),Z(this,z4,`m`,n3).call(this)}async finalText(){return await this.done(),Z(this,z4,`m`,r3).call(this)}_emit(e,...t){if(Z(this,Y4,`f`))return;e===`end`&&(X(this,Y4,!0,`f`),Z(this,K4,`f`).call(this));let n=Z(this,J4,`f`)[e];if(n&&(Z(this,J4,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!Z(this,Q4,`f`)&&!n?.length&&Promise.reject(e),Z(this,W4,`f`).call(this,e),Z(this,q4,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!Z(this,Q4,`f`)&&!n?.length&&Promise.reject(e),Z(this,W4,`f`).call(this,e),Z(this,q4,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,Z(this,z4,`m`,n3).call(this))}async _fromReadableStream(e,t){let n=t?.signal,r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener(`abort`,r));try{Z(this,z4,`m`,a3).call(this),this._connected(null);let t=x$.fromReadableStream(e,this.controller);for await(let e of t)Z(this,z4,`m`,o3).call(this,e);if(t.controller.signal?.aborted)throw new d;Z(this,z4,`m`,s3).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(B4=new WeakMap,V4=new WeakMap,H4=new WeakMap,U4=new WeakMap,W4=new WeakMap,G4=new WeakMap,K4=new WeakMap,q4=new WeakMap,J4=new WeakMap,Y4=new WeakMap,X4=new WeakMap,Z4=new WeakMap,Q4=new WeakMap,$4=new WeakMap,e3=new WeakMap,t3=new WeakMap,i3=new WeakMap,z4=new WeakSet,n3=function(){if(this.receivedMessages.length===0)throw new a(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},r3=function(){if(this.receivedMessages.length===0)throw new a(`stream ended without producing a Message with role=assistant`);let e=this.receivedMessages.at(-1).content.filter(e=>e.type===`text`).map(e=>e.text);if(e.length===0)throw new a(`stream ended without producing a content block with type=text`);return e.join(` `)},a3=function(){this.ended||X(this,B4,void 0,`f`)},o3=function(e){if(this.ended)return;let t=Z(this,z4,`m`,c3).call(this,e);switch(this._emit(`streamEvent`,e,t),e.type){case`content_block_delta`:{let n=t.content.at(-1);switch(e.delta.type){case`text_delta`:n.type===`text`&&this._emit(`text`,e.delta.text,n.text||``);break;case`citations_delta`:n.type===`text`&&this._emit(`citation`,e.delta.citation,n.citations??[]);break;case`input_json_delta`:l3(n)&&Z(this,J4,`f`).inputJson?.length&&this._emit(`inputJson`,e.delta.partial_json,n.input);break;case`thinking_delta`:n.type===`thinking`&&this._emit(`thinking`,e.delta.thinking,n.thinking);break;case`signature_delta`:n.type===`thinking`&&this._emit(`signature`,n.signature);break;default:e.delta}break}case`message_stop`:this._addMessageParam(t),this._addMessage(I4(t,Z(this,V4,`f`),{logger:Z(this,t3,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:X(this,B4,t,`f`);break;case`content_block_start`:case`message_delta`:break}},s3=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);let e=Z(this,B4,`f`);if(!e)throw new a(`request ended without sending any chunks`);return X(this,B4,void 0,`f`),I4(e,Z(this,V4,`f`),{logger:Z(this,t3,`f`)})},c3=function(e){let t=Z(this,B4,`f`);if(e.type===`message_start`){if(t)throw new a(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new a(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case`message_stop`:return t;case`message_delta`:return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,e.delta.stop_details!=null&&(t.stop_details=e.delta.stop_details),t.usage.output_tokens=e.usage.output_tokens,e.usage.input_tokens!=null&&(t.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(t.usage.server_tool_use=e.usage.server_tool_use),t;case`content_block_start`:return t.content.push({...e.content_block}),t;case`content_block_delta`:{let n=t.content.at(e.index);switch(e.delta.type){case`text_delta`:n?.type===`text`&&(t.content[e.index]={...n,text:(n.text||``)+e.delta.text});break;case`citations_delta`:n?.type===`text`&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case`input_json_delta`:if(n&&l3(n)){let r=(n.__json_buf||``)+e.delta.partial_json;t.content[e.index]=w2(n,r)}break;case`thinking_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case`signature_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,signature:e.delta.signature});break;default:e.delta}return t}case`content_block_stop`:{let n=t.content.at(e.index);return n&&l3(n)&&`__json_buf`in n&&Object.defineProperty(n,"input",{value:n.input,enumerable:!0,configurable:!0,writable:!0}),t}}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`streamEvent`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new x$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},d3=class extends a1{create(e,t){let{user_profile_id:n,...r}=e;return this._client.post(`/v1/messages/batches`,{body:r,...t,headers:Q([{...n==null?void 0:{"anthropic-user-profile-id":n}},t?.headers])})}retrieve(e,t){return this._client.get($`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/v1/messages/batches`,B$,{query:e,...t})}delete(e,t){return this._client.delete($`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post($`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let n=await this.retrieve(e);if(!n.results_url)throw new a(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:Q([{Accept:`application/binary`},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>d2.fromResponse(t.response,t.controller))}},f3=class extends a1{constructor(){super(...arguments),this.batches=new d3(this._client)}create(e,t){let{user_profile_id:n,...r}=e;r.model in p3&&console.warn(`The model '${r.model}' is deprecated and will reach end-of-life on ${p3[r.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),m3.includes(r.model)&&r.thinking&&r.thinking.type===`enabled`&&console.warn(`Using Claude with ${r.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 i=this._client._options.timeout;if(!r.stream&&i==null){let e=p2[r.model]??void 0;i=this._client.calculateNonstreamingTimeout(r.max_tokens,e)}let a=S1(r.tools,r.messages);return this._client.post(`/v1/messages`,{body:r,timeout:i??6e5,...t,headers:Q([{...n==null?void 0:{"anthropic-user-profile-id":n}},a,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(t=>L4(t,e,{logger:this._client.logger??console}))}stream(e,t){return u3.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){let{user_profile_id:n,...r}=e;return this._client.post(`/v1/messages/count_tokens`,{body:r,...t,headers:Q([{...n==null?void 0:{"anthropic-user-profile-id":n}},t?.headers])})}},p3={"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`,"claude-opus-4-0":`June 15th, 2026`,"claude-opus-4-20250514":`June 15th, 2026`,"claude-sonnet-4-0":`June 15th, 2026`,"claude-sonnet-4-20250514":`June 15th, 2026`,"claude-opus-4-1":`August 5th, 2026`,"claude-opus-4-1-20250805":`August 5th, 2026`,"claude-mythos-preview":`June 30th, 2026`},m3=[`claude-mythos-preview`,`claude-opus-4-6`];f3.Batches=d3;var h3=class extends a1{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/models/${e}`,{...n,headers:Q([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/models`,B$,{query:r,...t,headers:Q([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},g3,_3,v3,y3,b3=`\\n\\nHuman:`,x3=`\\n\\nAssistant:`,S3=class{get credentials(){return this._authState.provider}constructor({baseURL:e=PQ(`ANTHROPIC_BASE_URL`),apiKey:t,authToken:n,webhookKey:r=PQ(`ANTHROPIC_WEBHOOK_SIGNING_KEY`)??null,...i}={}){if(g3.add(this),this._requestAuthFlags=new WeakMap,v3.set(this,void 0),t===void 0&&(t=i.profile==null?PQ(`ANTHROPIC_API_KEY`)??null:null),n===void 0&&(n=i.profile==null?PQ(`ANTHROPIC_AUTH_TOKEN`)??null:null),i.profile!=null&&(i.credentials!=null||i.config!=null))throw TypeError("Pass at most one of `profile`, `credentials`, or `config`.");let o={apiKey:t,authToken:n,webhookKey:r,...i,baseURL:e||`https://api.anthropic.com`};if(!o.dangerouslyAllowBrowser&&MZ())throw new a(`It looks like you're running in a browser-like environment.
|
|
244
244
|
|
|
245
245
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
246
246
|
If you understand the risks and have appropriate mitigations in place,
|
|
247
247
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
248
248
|
|
|
249
249
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
250
|
-
`);this.baseURL=o.baseURL,this._baseURLIsExplicit=i.__baseURLIsExplicit??!!e,this.timeout=o.timeout??
|
|
251
|
-
`)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}o.defaultHeaders={...e,...o.defaultHeaders}}let c=i.__auth;if(delete o.__auth,delete o.__baseURLIsExplicit,this._options=o,this.apiKey=typeof t==`string`?t:null,this.authToken=n,this.webhookKey=r,c)this._authState=c,!this._baseURLIsExplicit&&c.baseURL&&(this.baseURL=c.baseURL);else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},this.apiKey==null&&this.authToken==null){let e=o.credentials??null;if(e)this._authState.provider=e,this._authState.tokenCache=this._makeTokenCache(e);else if(o.config!=null){let e=n$(o.config,this._credentialResolverOptions());this._authState.provider=e.provider,this._authState.tokenCache=this._makeTokenCache(e.provider),this._authState.extraHeaders=e.extraHeaders,this._applyCredentialBaseURL(e.baseURL)}else o.profile==null?this._shouldResolveDefaultCredentials()&&(this._authState.resolution=this._resolveDefaultCredentials()):this._authState.resolution=this._resolveDefaultCredentials(o.profile)}}_shouldResolveDefaultCredentials(){return!0}_applyCredentialBaseURL(e){if(!e)return;let t=e.replace(/\/+$/,``);this._authState.baseURL=t,this._baseURLIsExplicit||(this.baseURL=t)}_credentialResolverOptions(){return{baseURL:this.baseURL,fetch:this._credentialsFetch(),userAgent:this.getUserAgent(),onCacheWriteError:e=>{BQ(this).debug(`credential cache write failed (best-effort)`,e)},onSafetyWarning:e=>{BQ(this).warn(e)}}}_credentialsFetch(){return C$(this.fetch,this.middleware,void 0,this)}_makeTokenCache(e){return new TQ(e,e=>{BQ(this).debug(`advisory token refresh failed; serving cached token`,e)})}withOptions(e){let t=`credentials`in e||`config`in e||`profile`in e,n=`apiKey`in e||`authToken`in e||t,r={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,middleware:this.middleware,apiKey:this.apiKey,authToken:this.authToken,webhookKey:this.webhookKey,credentials:this.credentials,...t?{credentials:void 0,config:void 0,profile:void 0}:{},...e,__auth:n?void 0:this._authState,__baseURLIsExplicit:`baseURL`in e||this._baseURLIsExplicit};return new this.constructor(r)}async _resolveDefaultCredentials(e){try{let t=await r$(this._credentialResolverOptions(),e);if(t)this._authState.provider=t.provider,this._authState.tokenCache=this._makeTokenCache(t.provider),this._authState.extraHeaders=t.extraHeaders,this._applyCredentialBaseURL(t.baseURL);else if(e!=null)throw new a(`Profile "${e}" could not be resolved (no <config_dir>/configs/${e}.json found).`)}catch(e){this._authState.error=e}finally{this._authState.resolution=null}}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.get(`x-api-key`)||e.get(`authorization`))){if(this._authState.error)throw this._authState.error;if(!(this._authState.tokenCache||this._authState.resolution)&&!(this.apiKey&&e.get(`x-api-key`))&&!t.has(`x-api-key`)&&!(this.authToken&&e.get(`authorization`))&&!t.has(`authorization`))throw Error(`Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted`)}}_authFlags(e){let t=this._requestAuthFlags.get(e);return t||(t={usedTokenCache:!1,didRefreshFor401:!1},this._requestAuthFlags.set(e,t)),t}async authHeaders(e){if(this._authState.resolution&&await this._authState.resolution,!this._authState.error){if(this._authState.tokenCache&&this.apiKey==null){let t=await this._authState.tokenCache.getToken();return this._authFlags(e).usedTokenCache=!0,Q([{Authorization:`Bearer ${t}`}])}return Q([await this.apiKeyAuth(e),await this.bearerAuth(e)])}}async apiKeyAuth(e){if(this.apiKey!=null)return Q([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return Q([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return cQ(e)}getUserAgent(){return`${this.constructor.name}/JS ${CZ}`}defaultIdempotencyKey(){return`stainless-node-retry-${dZ()}`}makeStatusError(e,t,n,r){return _.generate(e,t,n,r)}buildURL(e,t,n){let r=!Z(this,c3,`m`,d3).call(this)&&n||this.baseURL,i=pZ(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!_Z(a)||!_Z(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new a(`Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details`);return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){if(this._authState.tokenCache&&this.apiKey==null){let t=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[e,n]of Object.entries(this._authState.extraHeaders))t.has(e)||t.set(e,n);(t.get(`anthropic-beta`)?.split(`,`).map(e=>e.trim()))?.includes(`oauth-2025-04-20`)||t.append(`anthropic-beta`,fQ),e.headers=t}}backendMiddleware(){return[]}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new O$(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??(t=i,this._requestAuthFlags.delete(r)),await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t}),c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),f=n===void 0?``:`, retryOf: ${n}`,p=Date.now();if(r.signal?.aborted)throw new d;let h=new AbortController,g=await this.fetchWithTimeout(o,a,s,h,r,{requestLogID:c,retryOfRequestLogID:n}).catch(u),_=Date.now();if(g instanceof globalThis.Error){LZ(h);let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new d;let i=l(g)||/timed? ?out/i.test(String(g)+(`cause`in g?String(g.cause):``)),a=this.middleware.length>0||!!r.middleware?.length||this.backendMiddleware().length>0;if(a&&!i&&!S$(g))throw BQ(this).info(`[${c}] middleware error (not retryable)`),BQ(this).debug(`[${c}] middleware error (not retryable)`,WQ({retryOfRequestLogID:n,url:o,durationMs:_-p,message:g.message})),g;if(t)return BQ(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),BQ(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,WQ({retryOfRequestLogID:n,url:o,durationMs:_-p,message:g.message})),this.retryRequest(r,t,n??c);throw BQ(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),BQ(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,WQ({retryOfRequestLogID:n,url:o,durationMs:_-p,message:g.message})),i?new m:a&&!x$(g)?g:new y({cause:g})}let v=`[${c}${f}${[...g.headers.entries()].filter(([e])=>e===`request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${g.ok?`succeeded`:`failed`} with status ${g.status} in ${_-p}ms`;if(!g.ok){let e=await this.shouldRetry(g,r);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await HZ(g.body),LZ(h),BQ(this).info(`${v} - ${e}`),BQ(this).debug(`[${c}] response error (${e})`,WQ({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:_-p})),this.retryRequest(r,t,n??c,g.headers)}let i=e?`error; no more retries left`:`error; not retryable`;BQ(this).info(`${v} - ${i}`);let a=await g.text().catch(e=>u(e).message),o=bZ(a),s=o?void 0:a;throw BQ(this).debug(`[${c}] response error (${i})`,WQ({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,message:s,durationMs:Date.now()-p})),LZ(h),this.makeStatusError(g.status,o,s,g.headers)}return BQ(this).info(v),BQ(this).debug(`[${c}] response start`,WQ({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:_-p})),IZ(g.body??g,h),{response:g,options:r,controller:h,requestLogID:c,retryOfRequestLogID:n,startTime:p}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new j$(this,n,e)}async fetchWithTimeout(e,t,n,r,i,a){let{signal:o,method:s,...c}=t||{},l=this._makeAbort(r);o&&(o.addEventListener(`abort`,l,{once:!0}),FZ(r,o,l));let u=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body==`object`&&c.body!==null&&Symbol.asyncIterator in c.body,d={signal:r.signal,...u?{duplex:`half`}:{},method:`GET`,...c};s&&(d.method=s.toUpperCase());let f=this.fetch,p=async(e,t)=>{let r=setTimeout(l,n);try{return await f.call(void 0,e,t)}finally{clearTimeout(r)}},m=i===void 0?p:(async(e,t={})=>{let n=typeof e==`string`?e:e instanceof URL?e.href:e.url;return t.headers=t.headers instanceof Headers?t.headers:new Headers(t.headers),await this.prepareRequest(t,{url:n,options:i}),a&&BQ(this).debug(`[${a.requestLogID}] sending request`,WQ({retryOfRequestLogID:a.retryOfRequestLogID,method:t.method,url:n,options:i,headers:t.headers})),p(e,t)}),h=i?.middleware,g=this.backendMiddleware();return await C$(m,h?.length||g.length?[...this.middleware,...h??[],...g]:this.middleware,i,this)(e,d)}async shouldRetry(e,t){let n=this._authFlags(t);if(e.status===401&&this._authState.tokenCache&&n.usedTokenCache&&!n.didRefreshFor401)return n.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;let r=e.headers.get(`x-should-retry`);return r===`true`?!0:r===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await SZ(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}calculateNonstreamingTimeout(e,t){let n=600*1e3;if(36e5*e/128e3>n||t!=null&&e>t)throw new a(`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 n}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n;this._authState.resolution&&await this._authState.resolution,!this._baseURLIsExplicit&&this._authState.baseURL&&this.baseURL!==this._authState.baseURL&&(this.baseURL=this._authState.baseURL);let s=this.buildURL(i,a,o);`timeout`in n&&yZ(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=Q([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...jZ(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":`true`}:void 0,"anthropic-version":`2023-06-01`},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=Q([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&n.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:BZ(e)}:typeof e==`object`&&n.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e)}:Z(this,u3,`f`).call(this,{body:e,headers:n})}};l3=m3,u3=new WeakMap,c3=new WeakSet,d3=function(){return this.baseURL!==`https://api.anthropic.com`},m3.Anthropic=l3,m3.HUMAN_PROMPT=f3,m3.AI_PROMPT=p3,m3.DEFAULT_TIMEOUT=6e5,m3.AnthropicError=a,m3.APIError=_,m3.APIConnectionError=y,m3.APIConnectionTimeoutError=m,m3.APIUserAbortError=d,m3.NotFoundError=b,m3.ConflictError=o,m3.RateLimitError=c,m3.BadRequestError=v,m3.AuthenticationError=h,m3.InternalServerError=f,m3.PermissionDeniedError=s,m3.UnprocessableEntityError=p,m3.toFile=J$;var h3=class extends m3{constructor(){super(...arguments),this.completions=new E4(this),this.messages=new i3(this),this.models=new s3(this),this.beta=new T4(this)}};h3.Completions=E4,h3.Messages=i3,h3.Models=s3,h3.Beta=T4,new TextEncoder;var g3=new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`uri`,`ipv4`,`ipv6`,`uuid`]);function _3(e){return JSON.parse(JSON.stringify(e))}function v3(e){return y3(_3(e))}function y3(e){let t={},n=xZ(e,`$ref`);if(n!==void 0)return t.$ref=n,t;let r=xZ(e,`$defs`);if(r!==void 0){let e={};t.$defs=e;for(let[t,n]of Object.entries(r))e[t]=y3(n)}let i=xZ(e,`type`),a=xZ(e,`anyOf`),o=xZ(e,`oneOf`),s=xZ(e,`allOf`);if(Array.isArray(a))t.anyOf=a.map(e=>y3(e));else if(Array.isArray(o))t.anyOf=o.map(e=>y3(e));else if(Array.isArray(s))t.allOf=s.map(e=>y3(e));else{if(i===void 0)throw Error(`JSON schema must have a type defined if anyOf/oneOf/allOf are not used`);t.type=i}let c=xZ(e,`description`);c!==void 0&&(t.description=c);let l=xZ(e,`title`);if(l!==void 0&&(t.title=l),i===`object`){let n=xZ(e,`properties`)||{};t.properties=Object.fromEntries(Object.entries(n).map(([e,t])=>[e,y3(t)])),xZ(e,`additionalProperties`),t.additionalProperties=!1;let r=xZ(e,`required`);r!==void 0&&(t.required=r)}else if(i===`string`){let n=xZ(e,`format`);n!==void 0&&g3.has(n)?t.format=n:n!==void 0&&(e.format=n)}else if(i===`array`){let n=xZ(e,`items`);n!==void 0&&(t.items=y3(n));let r=xZ(e,`minItems`);r!==void 0&&(r===0||r===1)?t.minItems=r:r!==void 0&&(e.minItems=r)}if(Object.keys(e).length>0){let n=t.description;t.description=(n?n+`
|
|
250
|
+
`);this.baseURL=o.baseURL,this._baseURLIsExplicit=i.__baseURLIsExplicit??!!e,this.timeout=o.timeout??_3.DEFAULT_TIMEOUT,this.logger=o.logger??console,this.logLevel=BQ,this.logLevel=HQ(o.logLevel,`ClientOptions.logLevel`,JQ(this))??HQ(PQ(`ANTHROPIC_LOG`),`process.env['ANTHROPIC_LOG']`,JQ(this))??`warn`,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??KZ(),X(this,v3,ZZ,`f`),this.middleware=[...o.middleware??[]];let s=PQ(`ANTHROPIC_CUSTOM_HEADERS`);if(s){let e={};for(let t of s.split(`
|
|
251
|
+
`)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}o.defaultHeaders={...e,...o.defaultHeaders}}let c=i.__auth;if(delete o.__auth,delete o.__baseURLIsExplicit,this._options=o,this.apiKey=typeof t==`string`?t:null,this.authToken=n,this.webhookKey=r,c)this._authState=c,!this._baseURLIsExplicit&&c.baseURL&&(this.baseURL=c.baseURL);else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},this.apiKey==null&&this.authToken==null){let e=o.credentials??null;if(e)this._authState.provider=e,this._authState.tokenCache=this._makeTokenCache(e);else if(o.config!=null){let e=u$(o.config,this._credentialResolverOptions());this._authState.provider=e.provider,this._authState.tokenCache=this._makeTokenCache(e.provider),this._authState.extraHeaders=e.extraHeaders,this._applyCredentialBaseURL(e.baseURL)}else o.profile==null?this._shouldResolveDefaultCredentials()&&(this._authState.resolution=this._resolveDefaultCredentials()):this._authState.resolution=this._resolveDefaultCredentials(o.profile)}}_shouldResolveDefaultCredentials(){return!0}_applyCredentialBaseURL(e){if(!e)return;let t=e.replace(/\/+$/,``);this._authState.baseURL=t,this._baseURLIsExplicit||(this.baseURL=t)}_credentialResolverOptions(){return{baseURL:this.baseURL,fetch:this._credentialsFetch(),userAgent:this.getUserAgent(),onCacheWriteError:e=>{JQ(this).debug(`credential cache write failed (best-effort)`,e)},onSafetyWarning:e=>{JQ(this).warn(e)}}}_credentialsFetch(){return j$(this.fetch,this.middleware,void 0,this)}_makeTokenCache(e){return new NQ(e,e=>{JQ(this).debug(`advisory token refresh failed; serving cached token`,e)})}withOptions(e){let t=`credentials`in e||`config`in e||`profile`in e,n=`apiKey`in e||`authToken`in e||t,r={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,middleware:this.middleware,apiKey:this.apiKey,authToken:this.authToken,webhookKey:this.webhookKey,credentials:this.credentials,...t?{credentials:void 0,config:void 0,profile:void 0}:{},...e,__auth:n?void 0:this._authState,__baseURLIsExplicit:`baseURL`in e||this._baseURLIsExplicit};return new this.constructor(r)}async _resolveDefaultCredentials(e){try{let t=await d$(this._credentialResolverOptions(),e);if(t)this._authState.provider=t.provider,this._authState.tokenCache=this._makeTokenCache(t.provider),this._authState.extraHeaders=t.extraHeaders,this._applyCredentialBaseURL(t.baseURL);else if(e!=null)throw new a(`Profile "${e}" could not be resolved (no <config_dir>/configs/${e}.json found).`)}catch(e){this._authState.error=e}finally{this._authState.resolution=null}}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.get(`x-api-key`)||e.get(`authorization`))){if(this._authState.error)throw this._authState.error;if(!(this._authState.tokenCache||this._authState.resolution)&&!(this.apiKey&&e.get(`x-api-key`))&&!t.has(`x-api-key`)&&!(this.authToken&&e.get(`authorization`))&&!t.has(`authorization`))throw Error(`Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted`)}}_authFlags(e){let t=this._requestAuthFlags.get(e);return t||(t={usedTokenCache:!1,didRefreshFor401:!1},this._requestAuthFlags.set(e,t)),t}async authHeaders(e){if(this._authState.resolution&&await this._authState.resolution,!this._authState.error){if(this._authState.tokenCache&&this.apiKey==null){let t=await this._authState.tokenCache.getToken();return this._authFlags(e).usedTokenCache=!0,Q([{Authorization:`Bearer ${t}`}])}return Q([await this.apiKeyAuth(e),await this.bearerAuth(e)])}}async apiKeyAuth(e){if(this.apiKey!=null)return Q([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return Q([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return gQ(e)}getUserAgent(){return`${this.constructor.name}/JS ${jZ}`}defaultIdempotencyKey(){return`stainless-node-retry-${yZ()}`}makeStatusError(e,t,n,r){return _.generate(e,t,n,r)}buildURL(e,t,n){let r=!Z(this,g3,`m`,y3).call(this)&&n||this.baseURL,i=xZ(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!TZ(a)||!TZ(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new a(`Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details`);return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){if(this._authState.tokenCache&&this.apiKey==null){let t=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[e,n]of Object.entries(this._authState.extraHeaders))t.has(e)||t.set(e,n);(t.get(`anthropic-beta`)?.split(`,`).map(e=>e.trim()))?.includes(`oauth-2025-04-20`)||t.append(`anthropic-beta`,bQ),e.headers=t}}backendMiddleware(){return[]}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new I$(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??(t=i,this._requestAuthFlags.delete(r)),await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t}),c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),f=n===void 0?``:`, retryOf: ${n}`,p=Date.now();if(r.signal?.aborted)throw new d;let h=new AbortController,g=await this.fetchWithTimeout(o,a,s,h,r,{requestLogID:c,retryOfRequestLogID:n}).catch(u),_=Date.now();if(g instanceof globalThis.Error){GZ(h);let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new d;let i=l(g)||/timed? ?out/i.test(String(g)+(`cause`in g?String(g.cause):``)),a=this.middleware.length>0||!!r.middleware?.length||this.backendMiddleware().length>0;if(a&&!i&&!A$(g))throw JQ(this).info(`[${c}] middleware error (not retryable)`),JQ(this).debug(`[${c}] middleware error (not retryable)`,QQ({retryOfRequestLogID:n,url:o,durationMs:_-p,message:g.message})),g;if(t)return JQ(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),JQ(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,QQ({retryOfRequestLogID:n,url:o,durationMs:_-p,message:g.message})),this.retryRequest(r,t,n??c);throw JQ(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),JQ(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,QQ({retryOfRequestLogID:n,url:o,durationMs:_-p,message:g.message})),i?new m:a&&!k$(g)?g:new y({cause:g})}let v=`[${c}${f}${[...g.headers.entries()].filter(([e])=>e===`request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${g.ok?`succeeded`:`failed`} with status ${g.status} in ${_-p}ms`;if(!g.ok){let e=await this.shouldRetry(g,r);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await XZ(g.body),GZ(h),JQ(this).info(`${v} - ${e}`),JQ(this).debug(`[${c}] response error (${e})`,QQ({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:_-p})),this.retryRequest(r,t,n??c,g.headers)}let i=e?`error; no more retries left`:`error; not retryable`;JQ(this).info(`${v} - ${i}`);let a=await g.text().catch(e=>u(e).message),o=OZ(a),s=o?void 0:a;throw JQ(this).debug(`[${c}] response error (${i})`,QQ({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,message:s,durationMs:Date.now()-p})),GZ(h),this.makeStatusError(g.status,o,s,g.headers)}return JQ(this).info(v),JQ(this).debug(`[${c}] response start`,QQ({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:_-p})),WZ(g.body??g,h),{response:g,options:r,controller:h,requestLogID:c,retryOfRequestLogID:n,startTime:p}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new z$(this,n,e)}async fetchWithTimeout(e,t,n,r,i,a){let{signal:o,method:s,...c}=t||{},l=this._makeAbort(r);o&&(o.addEventListener(`abort`,l,{once:!0}),UZ(r,o,l));let u=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body==`object`&&c.body!==null&&Symbol.asyncIterator in c.body,d={signal:r.signal,...u?{duplex:`half`}:{},method:`GET`,...c};s&&(d.method=s.toUpperCase());let f=this.fetch,p=async(e,t)=>{let r=setTimeout(l,n);try{return await f.call(void 0,e,t)}finally{clearTimeout(r)}},m=i===void 0?p:(async(e,t={})=>{let n=typeof e==`string`?e:e instanceof URL?e.href:e.url;return t.headers=t.headers instanceof Headers?t.headers:new Headers(t.headers),await this.prepareRequest(t,{url:n,options:i}),a&&JQ(this).debug(`[${a.requestLogID}] sending request`,QQ({retryOfRequestLogID:a.retryOfRequestLogID,method:t.method,url:n,options:i,headers:t.headers})),p(e,t)}),h=i?.middleware,g=this.backendMiddleware();return await j$(m,h?.length||g.length?[...this.middleware,...h??[],...g]:this.middleware,i,this)(e,d)}async shouldRetry(e,t){let n=this._authFlags(t);if(e.status===401&&this._authState.tokenCache&&n.usedTokenCache&&!n.didRefreshFor401)return n.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;let r=e.headers.get(`x-should-retry`);return r===`true`?!0:r===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await AZ(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}calculateNonstreamingTimeout(e,t){let n=600*1e3;if(36e5*e/128e3>n||t!=null&&e>t)throw new a(`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 n}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n;this._authState.resolution&&await this._authState.resolution,!this._baseURLIsExplicit&&this._authState.baseURL&&this.baseURL!==this._authState.baseURL&&(this.baseURL=this._authState.baseURL);let s=this.buildURL(i,a,o);`timeout`in n&&DZ(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=Q([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...zZ(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":`true`}:void 0,"anthropic-version":`2023-06-01`},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=Q([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&n.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:JZ(e)}:typeof e==`object`&&n.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e)}:Z(this,v3,`f`).call(this,{body:e,headers:n})}};_3=S3,v3=new WeakMap,g3=new WeakSet,y3=function(){return this.baseURL!==`https://api.anthropic.com`},S3.Anthropic=_3,S3.HUMAN_PROMPT=b3,S3.AI_PROMPT=x3,S3.DEFAULT_TIMEOUT=6e5,S3.AnthropicError=a,S3.APIError=_,S3.APIConnectionError=y,S3.APIConnectionTimeoutError=m,S3.APIUserAbortError=d,S3.NotFoundError=b,S3.ConflictError=o,S3.RateLimitError=c,S3.BadRequestError=v,S3.AuthenticationError=h,S3.InternalServerError=f,S3.PermissionDeniedError=s,S3.UnprocessableEntityError=p,S3.toFile=n1;var C3=class extends S3{constructor(){super(...arguments),this.completions=new P4(this),this.messages=new f3(this),this.models=new h3(this),this.beta=new N4(this)}};C3.Completions=P4,C3.Messages=f3,C3.Models=h3,C3.Beta=N4,new TextEncoder;var w3=new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`uri`,`ipv4`,`ipv6`,`uuid`]);function T3(e){return JSON.parse(JSON.stringify(e))}function E3(e){return D3(T3(e))}function D3(e){let t={},n=kZ(e,`$ref`);if(n!==void 0)return t.$ref=n,t;let r=kZ(e,`$defs`);if(r!==void 0){let e={};t.$defs=e;for(let[t,n]of Object.entries(r))e[t]=D3(n)}let i=kZ(e,`type`),a=kZ(e,`anyOf`),o=kZ(e,`oneOf`),s=kZ(e,`allOf`);if(Array.isArray(a))t.anyOf=a.map(e=>D3(e));else if(Array.isArray(o))t.anyOf=o.map(e=>D3(e));else if(Array.isArray(s))t.allOf=s.map(e=>D3(e));else{if(i===void 0)throw Error(`JSON schema must have a type defined if anyOf/oneOf/allOf are not used`);t.type=i}let c=kZ(e,`description`);c!==void 0&&(t.description=c);let l=kZ(e,`title`);if(l!==void 0&&(t.title=l),i===`object`){let n=kZ(e,`properties`)||{};t.properties=Object.fromEntries(Object.entries(n).map(([e,t])=>[e,D3(t)])),kZ(e,`additionalProperties`),t.additionalProperties=!1;let r=kZ(e,`required`);r!==void 0&&(t.required=r)}else if(i===`string`){let n=kZ(e,`format`);n!==void 0&&w3.has(n)?t.format=n:n!==void 0&&(e.format=n)}else if(i===`array`){let n=kZ(e,`items`);n!==void 0&&(t.items=D3(n));let r=kZ(e,`minItems`);r!==void 0&&(r===0||r===1)?t.minItems=r:r!==void 0&&(e.minItems=r)}if(Object.keys(e).length>0){let n=t.description;t.description=(n?n+`
|
|
252
252
|
|
|
253
|
-
`:``)+`{`+Object.entries(e).map(([e,t])=>`${e}: ${JSON.stringify(t)}`).join(`, `)+`}`}return t}var b3=`**REDACTED**`,x3={"claude-opus-5":16384,"claude-fable-5":16384,"claude-mythos-5":16384,"claude-mythos-preview":16384,"claude-opus-4-7":16384,"claude-opus-4-6":16384,"claude-sonnet-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},S3=4096;function C3(e){return e?Object.entries(x3).find(([t])=>e.startsWith(t))?.[1]??S3:S3}function w3(e){return!!(e.tools&&e.tools.length>0)}function T3(e){for(let t of e.messages??[])if(typeof t.content!=`string`){for(let e of t.content??[])if(typeof e==`object`&&e&&e.type===`document`&&typeof e.citations==`object`&&e.citations?.enabled)return!0}return!1}function E3(e){return!!(e.thinking&&(e.thinking.type===`enabled`||e.thinking.type===`adaptive`))}function D3(e){return!!e.context_management?.edits?.some(e=>e.type===`compact_20260112`)}function O3(e){return`input_schema`in e}function k3(e){return typeof e==`object`&&!!e&&`type`in e&&(`name`in e||`mcp_server_name`in e)&&typeof e.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(t=>typeof e.type==`string`&&e.type.startsWith(t))}function A3(e,t,...n){return Array.from(new Set([...e??[],...t??[],...n.flatMap(e=>Array.from(e))]))}function j3(e){if(typeof e.content==`string`)return e.content;if(Array.isArray(e.content)&&e.content.length>=1&&`input`in e.content[0])return typeof e.content[0].input==`string`?e.content[0].input:JSON.stringify(e.content[0].input);if(Array.isArray(e.content)&&e.content.length>=1&&`text`in e.content[0]&&typeof e.content[0].text==`string`)return e.content[0].text}var M3=class extends iD{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`};thinkingExplicitlySet=!1;contextManagement;outputConfig;inferenceGeo;batchClient;streamingClient;streamUsage=!0;betas;createClient;constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e??{};super(n??{}),this._addVersion(`@langchain/anthropic`,`1.5.8`);let r=MM({baseURL:n.anthropicApiUrl??n.clientOptions?.baseURL??(ui(`ANTHROPIC_API_URL`)||ui(`ANTHROPIC_BASE_URL`)||void 0),providerPath:`anthropic`});if(this.anthropicApiKey=n.apiKey??n.anthropicApiKey??r.apiKey??ui(`ANTHROPIC_API_KEY`),!this.anthropicApiKey&&!n?.createClient)throw Error(`Anthropic API key not found`);this.clientOptions=n?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=r.baseURL,this.modelName=n?.model??n?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=n?.invocationKwargs??{},this.topP=n?.topP??this.topP,this.temperature=n?.temperature??this.temperature,this.topK=n?.topK??this.topK,this.maxTokens=n?.maxTokens??C3(this.model),this.stopSequences=n?.stopSequences??this.stopSequences,this.streaming=n?.streaming??!1,this.streamUsage=n?.streamUsage??this.streamUsage,n?.thinking!==void 0&&(this.thinking=n.thinking,this.thinkingExplicitlySet=!0),this.contextManagement=n?.contextManagement??this.contextManagement,this.outputConfig=n?.outputConfig??this.outputConfig,this.inferenceGeo=n?.inferenceGeo??this.inferenceGeo,this.betas=n?.betas??this.betas,this.createClient=n?.createClient??(e=>new h3(e))}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`anthropic`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e,t){if(e)return e.map(e=>{if(eA(e)&&e.extras?.providerToolDefinition)return e.extras.providerToolDefinition;if(k3(e))return e;if(O3(e))return t?.strict===void 0?e:{...e,strict:t.strict};if(UT(e)){let n=`strict`in e.function&&typeof e.function.strict==`boolean`?e.function.strict:void 0,r=t?.strict??n;return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters,...r===void 0?{}:{strict:r}}}if(eA(e)){let{strict:n,...r}=e.extras?yX.parse(e.extras):{},i=t?.strict??n;return{name:e.name,description:e.description,input_schema:N_(e.schema)?Rx(e.schema):e.schema,...r,...i===void 0?{}:{strict:i}}}throw Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)}).filter(e=>!O3(e)||_X(e).length===0)}bindTools(e,t){return this.withConfig({tools:this.formatStructuredToolToAnthropic(e,{strict:t?.strict}),...t})}invocationParams(e){let t=vX(e?.tool_choice),n=e?.tools?.reduce((e,t)=>{if(typeof t==`object`&&`type`in t&&t.type in bX){let n=bX[t.type];if(!e.includes(n))return[...e,n]}return e},[]),r=(()=>{let t={...this.outputConfig,...e?.outputConfig};return e?.outputFormat&&!t.format&&(t.format=e.outputFormat),Object.keys(t).length>0?t:void 0})(),i=this.contextManagement?.edits?.some(e=>e.type===`compact_20260112`)?[`compact-2026-01-12`]:[],a=XX(this.model,r),o=this.formatStructuredToolToAnthropic(e?.tools,{strict:e?.strict});if(t?.type===`tool`&&!o?.some(e=>`name`in e&&e.name===t.name))throw Error(`Anthropic tool_choice references "${t.name}", but that tool is not available.`);if(t?.type===`any`&&(!o||o.length===0))throw Error(`Anthropic tool_choice requires at least one available tool.`);let s={model:this.model,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:o,tool_choice:t,thinking:this.thinkingExplicitlySet?this.thinking:void 0,context_management:this.contextManagement,...this.invocationKwargs,container:e?.container,betas:A3(this.betas,e?.betas,n??[],i,a),output_config:r,inference_geo:e?.inferenceGeo??this.inferenceGeo,mcp_servers:e?.mcp_servers,cache_control:e?.cache_control};return ZX({model:this.model,thinking:this.thinking,outputConfig:r,topK:this.topK,topP:this.topP,temperature:this.temperature}),Object.assign(s,QX({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature})),s}_getInvocationParamsForTracing(e){let t=this.invocationParams(e);return Array.isArray(t.mcp_servers)?{...t,mcp_servers:t.mcp_servers.map(e=>`authorization_token`in e?{...e,authorization_token:b3}:e)}:t}_getCallOptionsForTracing(e,t){return Array.isArray(e.mcp_servers)?{...e,mcp_servers:e.mcp_servers.map(e=>`authorization_token`in e?{...e,authorization_token:b3}:e)}:e}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(e,t,n){let r=this.invocationParams(t),i=UX(e),a={...r,...i,stream:!0},o=!w3(a)&&!T3(a)&&!E3(a)&&!D3(a),s=await this.createStreamWithRetry(a,{headers:t.headers,signal:t.signal,maxRetries:t.maxRetries});for await(let e of s){if(t.signal?.aborted){s.controller.abort();return}let r=this.streamUsage??t.streamUsage,i=$X(e,{streamUsage:r,coerceContentToString:o});if(!i)continue;let{chunk:a}=i,c=j3(a),l=new xd({message:new Nn({content:a.content,additional_kwargs:a.additional_kwargs,tool_call_chunks:a.tool_call_chunks,usage_metadata:r?a.usage_metadata:void 0,response_metadata:a.response_metadata,id:a.id}),text:c??``});yield l,await n?.handleLLMNewToken(c??``,void 0,void 0,void 0,void 0,{chunk:l})}}async*_streamChatModelEvents(e,t,n){let r=this.invocationParams(t),i=UX(e),a={...r,...i,stream:!0},o=await this.createStreamWithRetry(a,{headers:t.headers,signal:t.signal,maxRetries:t.maxRetries}),s=this.streamUsage??t.streamUsage;yield*aZ(async function*(e,t){for await(let n of e){if(t?.aborted){e.controller?.abort();return}yield n}}(o,t.signal),{streamUsage:s??!0})}async _generateNonStreaming(e,t,n){let r=UX(e),{content:i,...a}=await this.completionWithRetry({...t,stream:!1,...r},n),o=eZ(i,a),{role:s,type:c,...l}=a;return{generations:o,llmOutput:l}}async _generate(e,t,n){if(t.signal?.throwIfAborted(),this.stopSequences&&t.stop)throw Error(`"stopSequence" parameter found in input and default params`);let r=this.invocationParams(t);if(r.stream){let r,i=this._streamResponseChunks(e,t,n);for await(let e of i)r=r===void 0?e:r.concat(e);if(r===void 0)throw Error(`No chunks returned from Anthropic API.`);return{generations:[{text:r.text,message:r.message}]}}else return this._generateNonStreaming(e,r,{signal:t.signal,headers:t.headers,maxRetries:t.maxRetries})}async createStreamWithRetry(e,t){if(!this.streamingClient){let e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}let{betas:n,...r}=e;return this.caller.callWithOptions({maxRetries:t?.maxRetries},async()=>{try{return e?.betas?.length?await this.streamingClient.beta.messages.create({...r,betas:n,...this.invocationKwargs,stream:!0},t):await this.streamingClient.messages.create({...r,...this.invocationKwargs,stream:!0},t)}catch(e){throw rZ(e)}})}async completionWithRetry(e,t){if(!this.batchClient){let e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}let{betas:n,...r}=e;return this.caller.callWithOptions({signal:t.signal??void 0,maxRetries:t.maxRetries},async()=>{try{return e?.betas?.length?await this.batchClient.beta.messages.create({...r,...this.invocationKwargs,betas:n},t):await this.batchClient.messages.create({...r,...this.invocationKwargs},t)}catch(e){throw rZ(e)}})}_llmType(){return`anthropic`}get profile(){return iZ[this.model]??{}}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e},s=t?.method??`functionCalling`;if(t?.strict!==void 0&&s!==`functionCalling`)throw Error(`Argument \`strict\` is only supported for \`method\` = "functionCalling" on Anthropic models. Got method = "${s}".`);if(s===`jsonMode`&&(console.warn(`"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".`),s=`jsonSchema`),s===`jsonSchema`){r=EE(i);let e=v3(Rx(i));n=this.withConfig({outputVersion:`v0`,outputConfig:{format:{type:`json_schema`,schema:e}},ls_structured_output_format:{kwargs:{method:`json_schema`},schema:e}})}else if(s===`functionCalling`){let e=a??`extract`,o;if(N_(i)||Zb(i)){let t=Rx(i);o=[{name:e,description:t.description??`A function available to call.`,input_schema:t}]}else typeof i.name==`string`&&typeof i.description==`string`&&typeof i.input_schema==`object`&&i.input_schema!=null?(o=[i],e=i.name):o=[{name:e,description:i.description??``,input_schema:i}];if(r=DE(i,e,mX),this.thinking?.type===`enabled`||this.thinking?.type===`adaptive`){let e="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(e),n=this.withConfig({outputVersion:`v0`,tools:o,ls_structured_output_format:{kwargs:{method:`functionCalling`},schema:Rx(i)},...t?.strict===void 0?{}:{strict:t.strict}}),n=n.pipe(t=>{if(!t.tool_calls||t.tool_calls.length===0)throw Error(e);return t})}else n=this.withConfig({outputVersion:`v0`,tools:o,tool_choice:{type:`tool`,name:e},ls_structured_output_format:{kwargs:{method:`functionCalling`},schema:Rx(i)},...t?.strict===void 0?{}:{strict:t.strict}})}else throw TypeError(`Unrecognized structured output method '${s}'. Expected 'functionCalling' or 'jsonSchema'`);return OE(n,r,o,o?`StructuredOutputRunnable`:`ChatAnthropicStructuredOutput`)}},N3=class extends M3{};dj(`command`,[V({command:xj(`view`),path:B()}),V({command:xj(`create`),path:B(),file_text:B()}),V({command:xj(`str_replace`),path:B(),old_str:B(),new_str:B()}),V({command:xj(`insert`),path:B(),insert_line:JA(),insert_text:B()}),V({command:xj(`delete`),path:B()}),V({command:xj(`rename`),old_path:B(),new_path:B()})]),dj(`command`,[V({command:xj(`view`),path:B(),view_range:hj([JA(),JA()]).optional()}),V({command:xj(`str_replace`),path:B(),old_str:B(),new_str:B()}),V({command:xj(`create`),path:B(),file_text:B()}),V({command:xj(`insert`),path:B(),insert_line:JA(),new_str:B()})]);var P3=hj([JA(),JA()]),F3=V({action:xj(`screenshot`)}),I3=V({action:xj(`left_click`),coordinate:P3}),L3=V({action:xj(`right_click`),coordinate:P3}),R3=V({action:xj(`middle_click`),coordinate:P3}),z3=V({action:xj(`double_click`),coordinate:P3}),B3=V({action:xj(`triple_click`),coordinate:P3}),V3=V({action:xj(`left_click_drag`),start_coordinate:P3,end_coordinate:P3}),H3=V({action:xj(`left_mouse_down`),coordinate:P3}),U3=V({action:xj(`left_mouse_up`),coordinate:P3}),W3=V({action:xj(`scroll`),coordinate:P3,scroll_direction:yj([`up`,`down`,`left`,`right`]),scroll_amount:JA()}),G3=V({action:xj(`type`),text:B()}),K3=V({action:xj(`key`),key:B()}),q3=V({action:xj(`mouse_move`),coordinate:P3}),J3=V({action:xj(`hold_key`),key:B()}),Y3=V({action:xj(`wait`),duration:JA().optional()}),X3=V({action:xj(`zoom`),region:hj([JA(),JA(),JA(),JA()])});dj(`action`,[F3,I3,L3,R3,z3,B3,V3,H3,U3,W3,G3,K3,q3,J3,Y3]),dj(`action`,[F3,I3,L3,R3,z3,B3,V3,H3,U3,W3,G3,K3,q3,J3,Y3,X3]),lj([V({command:B().describe(`The bash command to run`)}),V({restart:xj(!0).describe(`Set to true to restart the bash session`)})]);async function*Z3(e,t={}){let n=t.streamUsage??!0,r=t.think??!1,i=new Map,a=new Map,o=0,s=!1,c,l,u=(e,t)=>{let n=a.get(e);if(n!==void 0)return{index:n,isNew:!1};let r=o++;return a.set(e,r),i.set(r,{...t}),{index:r,isNew:!0}};for await(let t of e){if(s||(s=!0,yield{event:`message-start`}),n){let e=t.prompt_eval_count??0,n=t.eval_count??0;(e>0||n>0)&&(c={input_tokens:e,output_tokens:n,total_tokens:e+n},yield{event:`usage`,usage:c})}t.done_reason&&(l=Q3(t.done_reason));let{message:e}=t;if(r&&e.thinking){let{index:t,isNew:n}=u(`reasoning`,{type:`reasoning`,reasoning:``});n&&(yield{event:`content-block-start`,index:t,content:{type:`reasoning`,reasoning:``}});let r=i.get(t);r.reasoning=(r.reasoning??``)+e.thinking,yield{event:`content-block-delta`,index:t,delta:{type:`reasoning-delta`,reasoning:e.thinking}}}if(e.content){let{index:t,isNew:n}=u(`text`,{type:`text`,text:``});n&&(yield{event:`content-block-start`,index:t,content:{type:`text`,text:``}});let r=i.get(t);r.text=(r.text??``)+e.content,yield{event:`content-block-delta`,index:t,delta:{type:`text-delta`,text:e.content}}}if(e.tool_calls?.length)for(let t=0;t<e.tool_calls.length;t++){let n=e.tool_calls[t],r=`tool:${t}`,a=typeof n.function.arguments==`string`?n.function.arguments:JSON.stringify(n.function.arguments),{index:o,isNew:s}=u(r,{type:`tool_call_chunk`,name:n.function.name,args:``,index:t});s&&(yield{event:`content-block-start`,index:o,content:{type:`tool_call_chunk`,name:n.function.name,args:``,index:t}});let c=i.get(o);c.name=n.function.name,c.args=a,yield{event:`content-block-delta`,index:o,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,name:c.name,args:c.args}}}}}for(let[e,t]of i)yield{event:`content-block-finish`,index:e,content:$E(t)};yield{event:`message-finish`,reason:l,...c?{usage:c}:{},responseMetadata:{model_provider:`ollama`}}}function Q3(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;default:return`stop`}}function $3(e,t){return new Nn({content:e.content??``,additional_kwargs:e.thinking&&e.thinking!==``?{reasoning_content:e.thinking}:{},tool_call_chunks:e.tool_calls?.map(e=>({name:e.function.name,args:JSON.stringify(e.function.arguments),type:`tool_call_chunk`,index:0,id:Yr()})),response_metadata:{...t?.responseMetadata,model_provider:`ollama`},usage_metadata:t?.usageMetadata})}function e6(e){let t=e.match(/^data:.*?;base64,(.*)$/);return t?t[1]:``}function t6(e){if(typeof e.content==`string`){if(e.tool_calls?.length){let t=e.tool_calls.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:e.args}}));return[{role:`assistant`,content:e.content,tool_calls:t}]}return[{role:`assistant`,content:e.content}]}let t=e.content.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>({role:`assistant`,content:e.text})),n;if(e.content.find(e=>e.type===`tool_use`)&&e.tool_calls?.length){let t=e.tool_calls?.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:e.args}}));t&&(n={role:`assistant`,tool_calls:t,content:``})}else if(e.content.find(e=>e.type===`tool_use`)&&!e.tool_calls?.length)throw Error(`'tool_use' content type is not supported without tool calls.`);return[...t,...n?[n]:[]]}function n6(e){return typeof e.content==`string`?[{role:`user`,content:e.content}]:e.content.map(e=>{if(e.type===`text`)return{role:`user`,content:e.text};if(e.type===`image_url`){if(typeof e.image_url==`string`)return{role:`user`,content:``,images:[e6(e.image_url)]};if(e.image_url.url&&typeof e.image_url.url==`string`)return{role:`user`,content:``,images:[e6(e.image_url.url)]}}throw Error(`Unsupported content type: ${e.type}`)})}function r6(e){if(typeof e.content==`string`)return[{role:`system`,content:e.content}];if(e.content.every(e=>e.type===`text`&&typeof e.text==`string`))return e.content.map(e=>({role:`system`,content:e.text}));throw Error(`Unsupported content type(s): ${e.content.map(e=>e.type).join(`, `)}`)}function i6(e){if(typeof e.content!=`string`)throw Error(`Non string tool message content is not supported`);return[{role:`tool`,content:e.content}]}function a6(e){return e.flatMap(e=>{if([`human`,`generic`].includes(e._getType()))return n6(e);if(e._getType()===`ai`)return t6(e);if(e._getType()===`system`)return r6(e);if(e._getType()===`tool`)return i6(e);throw Error(`Unsupported message type: ${e._getType()}`)})}var o6=typeof globalThis<`u`&&globalThis||typeof self<`u`&&self||typeof global<`u`&&global||{},s6={searchParams:`URLSearchParams`in o6,iterable:`Symbol`in o6&&`iterator`in Symbol,blob:`FileReader`in o6&&`Blob`in o6&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:`FormData`in o6,arrayBuffer:`ArrayBuffer`in o6};function c6(e){return e&&DataView.prototype.isPrototypeOf(e)}if(s6.arrayBuffer)var l6=[`[object Int8Array]`,`[object Uint8Array]`,`[object Uint8ClampedArray]`,`[object Int16Array]`,`[object Uint16Array]`,`[object Int32Array]`,`[object Uint32Array]`,`[object Float32Array]`,`[object Float64Array]`],u6=ArrayBuffer.isView||function(e){return e&&l6.indexOf(Object.prototype.toString.call(e))>-1};function d6(e){if(typeof e!=`string`&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||e===``)throw TypeError(`Invalid character in header field name: "`+e+`"`);return e.toLowerCase()}function f6(e){return typeof e!=`string`&&(e=String(e)),e}function p6(e){var t={next:function(){var t=e.shift();return{done:t===void 0,value:t}}};return s6.iterable&&(t[Symbol.iterator]=function(){return t}),t}function m6(e){this.map={},e instanceof m6?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){if(e.length!=2)throw TypeError(`Headers constructor: expected name/value pair to be length 2, found`+e.length);this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}m6.prototype.append=function(e,t){e=d6(e),t=f6(t);var n=this.map[e];this.map[e]=n?n+`, `+t:t},m6.prototype.delete=function(e){delete this.map[d6(e)]},m6.prototype.get=function(e){return e=d6(e),this.has(e)?this.map[e]:null},m6.prototype.has=function(e){return this.map.hasOwnProperty(d6(e))},m6.prototype.set=function(e,t){this.map[d6(e)]=f6(t)},m6.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},m6.prototype.keys=function(){var e=[];return this.forEach(function(t,n){e.push(n)}),p6(e)},m6.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),p6(e)},m6.prototype.entries=function(){var e=[];return this.forEach(function(t,n){e.push([n,t])}),p6(e)},s6.iterable&&(m6.prototype[Symbol.iterator]=m6.prototype.entries);function h6(e){if(!e._noBody){if(e.bodyUsed)return Promise.reject(TypeError(`Already read`));e.bodyUsed=!0}}function g6(e){return new Promise(function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}})}function _6(e){var t=new FileReader,n=g6(t);return t.readAsArrayBuffer(e),n}function v6(e){var t=new FileReader,n=g6(t),r=/charset=([A-Za-z0-9_-]+)/.exec(e.type),i=r?r[1]:`utf-8`;return t.readAsText(e,i),n}function y6(e){for(var t=new Uint8Array(e),n=Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join(``)}function b6(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function x6(){return this.bodyUsed=!1,this._initBody=function(e){this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?typeof e==`string`?this._bodyText=e:s6.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:s6.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:s6.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():s6.arrayBuffer&&s6.blob&&c6(e)?(this._bodyArrayBuffer=b6(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s6.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||u6(e))?this._bodyArrayBuffer=b6(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,this._bodyText=``),this.headers.get(`content-type`)||(typeof e==`string`?this.headers.set(`content-type`,`text/plain;charset=UTF-8`):this._bodyBlob&&this._bodyBlob.type?this.headers.set(`content-type`,this._bodyBlob.type):s6.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set(`content-type`,`application/x-www-form-urlencoded;charset=UTF-8`))},s6.blob&&(this.blob=function(){var e=h6(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw Error(`could not read FormData body as blob`);return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer)return h6(this)||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer));if(s6.blob)return this.blob().then(_6);throw Error(`could not read as ArrayBuffer`)},this.text=function(){var e=h6(this);if(e)return e;if(this._bodyBlob)return v6(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(y6(this._bodyArrayBuffer));if(this._bodyFormData)throw Error(`could not read FormData body as text`);return Promise.resolve(this._bodyText)},s6.formData&&(this.formData=function(){return this.text().then(T6)}),this.json=function(){return this.text().then(JSON.parse)},this}var S6=[`CONNECT`,`DELETE`,`GET`,`HEAD`,`OPTIONS`,`PATCH`,`POST`,`PUT`,`TRACE`];function C6(e){var t=e.toUpperCase();return S6.indexOf(t)>-1?t:e}function w6(e,t){if(!(this instanceof w6))throw TypeError(`Please use the "new" operator, this DOM object constructor cannot be called as a function.`);t||={};var n=t.body;if(e instanceof w6){if(e.bodyUsed)throw TypeError(`Already read`);this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new m6(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,!n&&e._bodyInit!=null&&(n=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||`same-origin`,(t.headers||!this.headers)&&(this.headers=new m6(t.headers)),this.method=C6(t.method||this.method||`GET`),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if(`AbortController`in o6)return new AbortController().signal}(),this.referrer=null,(this.method===`GET`||this.method===`HEAD`)&&n)throw TypeError(`Body not allowed for GET or HEAD requests`);if(this._initBody(n),(this.method===`GET`||this.method===`HEAD`)&&(t.cache===`no-store`||t.cache===`no-cache`)){var r=/([?&])_=[^&]*/;if(r.test(this.url))this.url=this.url.replace(r,`$1_=`+new Date().getTime());else{var i=/\?/;this.url+=(i.test(this.url)?`&`:`?`)+`_=`+new Date().getTime()}}}w6.prototype.clone=function(){return new w6(this,{body:this._bodyInit})};function T6(e){var t=new FormData;return e.trim().split(`&`).forEach(function(e){if(e){var n=e.split(`=`),r=n.shift().replace(/\+/g,` `),i=n.join(`=`).replace(/\+/g,` `);t.append(decodeURIComponent(r),decodeURIComponent(i))}}),t}function E6(e){var t=new m6;return e.replace(/\r?\n[\t ]+/g,` `).split(`\r`).map(function(e){return e.indexOf(`
|
|
254
|
-
`)===0?e.substr(1,e.length):e}).forEach(function(e){var n=e.split(`:`),r=n.shift().trim();if(r){var i=n.join(`:`).trim();try{t.append(r,i)}catch(e){console.warn(`Response `+e.message)}}}),t}
|
|
253
|
+
`:``)+`{`+Object.entries(e).map(([e,t])=>`${e}: ${JSON.stringify(t)}`).join(`, `)+`}`}return t}var O3=`**REDACTED**`,k3={"claude-opus-5":16384,"claude-fable-5":16384,"claude-mythos-5":16384,"claude-mythos-preview":16384,"claude-opus-4-7":16384,"claude-opus-4-6":16384,"claude-sonnet-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},A3=4096;function j3(e){return e?Object.entries(k3).find(([t])=>e.startsWith(t))?.[1]??A3:A3}function M3(e){return!!(e.tools&&e.tools.length>0)}function N3(e){for(let t of e.messages??[])if(typeof t.content!=`string`){for(let e of t.content??[])if(typeof e==`object`&&e&&e.type===`document`&&typeof e.citations==`object`&&e.citations?.enabled)return!0}return!1}function P3(e){return!!(e.thinking&&(e.thinking.type===`enabled`||e.thinking.type===`adaptive`))}function F3(e){return!!e.context_management?.edits?.some(e=>e.type===`compact_20260112`)}function I3(e){return`input_schema`in e}function L3(e){return typeof e==`object`&&!!e&&`type`in e&&(`name`in e||`mcp_server_name`in e)&&typeof e.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(t=>typeof e.type==`string`&&e.type.startsWith(t))}function R3(e,t,...n){return Array.from(new Set([...e??[],...t??[],...n.flatMap(e=>Array.from(e))]))}function z3(e){if(typeof e.content==`string`)return e.content;if(Array.isArray(e.content)&&e.content.length>=1&&`input`in e.content[0])return typeof e.content[0].input==`string`?e.content[0].input:JSON.stringify(e.content[0].input);if(Array.isArray(e.content)&&e.content.length>=1&&`text`in e.content[0]&&typeof e.content[0].text==`string`)return e.content[0].text}var B3=class extends iD{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`};thinkingExplicitlySet=!1;contextManagement;outputConfig;inferenceGeo;batchClient;streamingClient;streamUsage=!0;betas;createClient;constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e??{};super(n??{}),this._addVersion(`@langchain/anthropic`,`1.5.8`);let r=MM({baseURL:n.anthropicApiUrl??n.clientOptions?.baseURL??(ui(`ANTHROPIC_API_URL`)||ui(`ANTHROPIC_BASE_URL`)||void 0),providerPath:`anthropic`});if(this.anthropicApiKey=n.apiKey??n.anthropicApiKey??r.apiKey??ui(`ANTHROPIC_API_KEY`),!this.anthropicApiKey&&!n?.createClient)throw Error(`Anthropic API key not found`);this.clientOptions=n?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=r.baseURL,this.modelName=n?.model??n?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=n?.invocationKwargs??{},this.topP=n?.topP??this.topP,this.temperature=n?.temperature??this.temperature,this.topK=n?.topK??this.topK,this.maxTokens=n?.maxTokens??j3(this.model),this.stopSequences=n?.stopSequences??this.stopSequences,this.streaming=n?.streaming??!1,this.streamUsage=n?.streamUsage??this.streamUsage,n?.thinking!==void 0&&(this.thinking=n.thinking,this.thinkingExplicitlySet=!0),this.contextManagement=n?.contextManagement??this.contextManagement,this.outputConfig=n?.outputConfig??this.outputConfig,this.inferenceGeo=n?.inferenceGeo??this.inferenceGeo,this.betas=n?.betas??this.betas,this.createClient=n?.createClient??(e=>new C3(e))}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`anthropic`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e,t){if(e)return e.map(e=>{if(eA(e)&&e.extras?.providerToolDefinition)return e.extras.providerToolDefinition;if(L3(e))return e;if(I3(e))return t?.strict===void 0?e:{...e,strict:t.strict};if(UT(e)){let n=`strict`in e.function&&typeof e.function.strict==`boolean`?e.function.strict:void 0,r=t?.strict??n;return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters,...r===void 0?{}:{strict:r}}}if(eA(e)){let{strict:n,...r}=e.extras?DX.parse(e.extras):{},i=t?.strict??n;return{name:e.name,description:e.description,input_schema:N_(e.schema)?Rx(e.schema):e.schema,...r,...i===void 0?{}:{strict:i}}}throw Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)}).filter(e=>!I3(e)||TX(e).length===0)}bindTools(e,t){return this.withConfig({tools:this.formatStructuredToolToAnthropic(e,{strict:t?.strict}),...t})}invocationParams(e){let t=EX(e?.tool_choice),n=e?.tools?.reduce((e,t)=>{if(typeof t==`object`&&`type`in t&&t.type in OX){let n=OX[t.type];if(!e.includes(n))return[...e,n]}return e},[]),r=(()=>{let t={...this.outputConfig,...e?.outputConfig};return e?.outputFormat&&!t.format&&(t.format=e.outputFormat),Object.keys(t).length>0?t:void 0})(),i=this.contextManagement?.edits?.some(e=>e.type===`compact_20260112`)?[`compact-2026-01-12`]:[],a=iZ(this.model,r),o=this.formatStructuredToolToAnthropic(e?.tools,{strict:e?.strict});if(t?.type===`tool`&&!o?.some(e=>`name`in e&&e.name===t.name))throw Error(`Anthropic tool_choice references "${t.name}", but that tool is not available.`);if(t?.type===`any`&&(!o||o.length===0))throw Error(`Anthropic tool_choice requires at least one available tool.`);let s={model:this.model,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:o,tool_choice:t,thinking:this.thinkingExplicitlySet?this.thinking:void 0,context_management:this.contextManagement,...this.invocationKwargs,container:e?.container,betas:R3(this.betas,e?.betas,n??[],i,a),output_config:r,inference_geo:e?.inferenceGeo??this.inferenceGeo,mcp_servers:e?.mcp_servers,cache_control:e?.cache_control};return aZ({model:this.model,thinking:this.thinking,outputConfig:r,topK:this.topK,topP:this.topP,temperature:this.temperature}),Object.assign(s,oZ({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature})),s}_getInvocationParamsForTracing(e){let t=this.invocationParams(e);return Array.isArray(t.mcp_servers)?{...t,mcp_servers:t.mcp_servers.map(e=>`authorization_token`in e?{...e,authorization_token:O3}:e)}:t}_getCallOptionsForTracing(e,t){return Array.isArray(e.mcp_servers)?{...e,mcp_servers:e.mcp_servers.map(e=>`authorization_token`in e?{...e,authorization_token:O3}:e)}:e}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(e,t,n){let r=this.invocationParams(t),i=ZX(e),a={...r,...i,stream:!0},o=!M3(a)&&!N3(a)&&!P3(a)&&!F3(a),s=await this.createStreamWithRetry(a,{headers:t.headers,signal:t.signal,maxRetries:t.maxRetries});for await(let e of s){if(t.signal?.aborted){s.controller.abort();return}let r=this.streamUsage??t.streamUsage,i=sZ(e,{streamUsage:r,coerceContentToString:o});if(!i)continue;let{chunk:a}=i,c=z3(a),l=new xd({message:new Nn({content:a.content,additional_kwargs:a.additional_kwargs,tool_call_chunks:a.tool_call_chunks,usage_metadata:r?a.usage_metadata:void 0,response_metadata:a.response_metadata,id:a.id}),text:c??``});yield l,await n?.handleLLMNewToken(c??``,void 0,void 0,void 0,void 0,{chunk:l})}}async*_streamChatModelEvents(e,t,n){let r=this.invocationParams(t),i=ZX(e),a={...r,...i,stream:!0},o=await this.createStreamWithRetry(a,{headers:t.headers,signal:t.signal,maxRetries:t.maxRetries}),s=this.streamUsage??t.streamUsage;yield*pZ(async function*(e,t){for await(let n of e){if(t?.aborted){e.controller?.abort();return}yield n}}(o,t.signal),{streamUsage:s??!0})}async _generateNonStreaming(e,t,n){let r=ZX(e),{content:i,...a}=await this.completionWithRetry({...t,stream:!1,...r},n),o=cZ(i,a),{role:s,type:c,...l}=a;return{generations:o,llmOutput:l}}async _generate(e,t,n){if(t.signal?.throwIfAborted(),this.stopSequences&&t.stop)throw Error(`"stopSequence" parameter found in input and default params`);let r=this.invocationParams(t);if(r.stream){let r,i=this._streamResponseChunks(e,t,n);for await(let e of i)r=r===void 0?e:r.concat(e);if(r===void 0)throw Error(`No chunks returned from Anthropic API.`);return{generations:[{text:r.text,message:r.message}]}}else return this._generateNonStreaming(e,r,{signal:t.signal,headers:t.headers,maxRetries:t.maxRetries})}async createStreamWithRetry(e,t){if(!this.streamingClient){let e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}let{betas:n,...r}=e;return this.caller.callWithOptions({maxRetries:t?.maxRetries},async()=>{try{return e?.betas?.length?await this.streamingClient.beta.messages.create({...r,betas:n,...this.invocationKwargs,stream:!0},t):await this.streamingClient.messages.create({...r,...this.invocationKwargs,stream:!0},t)}catch(e){throw dZ(e)}})}async completionWithRetry(e,t){if(!this.batchClient){let e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}let{betas:n,...r}=e;return this.caller.callWithOptions({signal:t.signal??void 0,maxRetries:t.maxRetries},async()=>{try{return e?.betas?.length?await this.batchClient.beta.messages.create({...r,...this.invocationKwargs,betas:n},t):await this.batchClient.messages.create({...r,...this.invocationKwargs},t)}catch(e){throw dZ(e)}})}_llmType(){return`anthropic`}get profile(){return fZ[this.model]??{}}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e},s=t?.method??`functionCalling`;if(t?.strict!==void 0&&s!==`functionCalling`)throw Error(`Argument \`strict\` is only supported for \`method\` = "functionCalling" on Anthropic models. Got method = "${s}".`);if(s===`jsonMode`&&(console.warn(`"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".`),s=`jsonSchema`),s===`jsonSchema`){r=EE(i);let e=E3(Rx(i));n=this.withConfig({outputVersion:`v0`,outputConfig:{format:{type:`json_schema`,schema:e}},ls_structured_output_format:{kwargs:{method:`json_schema`},schema:e}})}else if(s===`functionCalling`){let e=a??`extract`,o;if(N_(i)||Zb(i)){let t=Rx(i);o=[{name:e,description:t.description??`A function available to call.`,input_schema:t}]}else typeof i.name==`string`&&typeof i.description==`string`&&typeof i.input_schema==`object`&&i.input_schema!=null?(o=[i],e=i.name):o=[{name:e,description:i.description??``,input_schema:i}];if(r=DE(i,e,SX),this.thinking?.type===`enabled`||this.thinking?.type===`adaptive`){let e="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(e),n=this.withConfig({outputVersion:`v0`,tools:o,ls_structured_output_format:{kwargs:{method:`functionCalling`},schema:Rx(i)},...t?.strict===void 0?{}:{strict:t.strict}}),n=n.pipe(t=>{if(!t.tool_calls||t.tool_calls.length===0)throw Error(e);return t})}else n=this.withConfig({outputVersion:`v0`,tools:o,tool_choice:{type:`tool`,name:e},ls_structured_output_format:{kwargs:{method:`functionCalling`},schema:Rx(i)},...t?.strict===void 0?{}:{strict:t.strict}})}else throw TypeError(`Unrecognized structured output method '${s}'. Expected 'functionCalling' or 'jsonSchema'`);return OE(n,r,o,o?`StructuredOutputRunnable`:`ChatAnthropicStructuredOutput`)}},V3=class extends B3{};dj(`command`,[V({command:xj(`view`),path:B()}),V({command:xj(`create`),path:B(),file_text:B()}),V({command:xj(`str_replace`),path:B(),old_str:B(),new_str:B()}),V({command:xj(`insert`),path:B(),insert_line:JA(),insert_text:B()}),V({command:xj(`delete`),path:B()}),V({command:xj(`rename`),old_path:B(),new_path:B()})]),dj(`command`,[V({command:xj(`view`),path:B(),view_range:hj([JA(),JA()]).optional()}),V({command:xj(`str_replace`),path:B(),old_str:B(),new_str:B()}),V({command:xj(`create`),path:B(),file_text:B()}),V({command:xj(`insert`),path:B(),insert_line:JA(),new_str:B()})]);var H3=hj([JA(),JA()]),U3=V({action:xj(`screenshot`)}),W3=V({action:xj(`left_click`),coordinate:H3}),G3=V({action:xj(`right_click`),coordinate:H3}),K3=V({action:xj(`middle_click`),coordinate:H3}),q3=V({action:xj(`double_click`),coordinate:H3}),J3=V({action:xj(`triple_click`),coordinate:H3}),Y3=V({action:xj(`left_click_drag`),start_coordinate:H3,end_coordinate:H3}),X3=V({action:xj(`left_mouse_down`),coordinate:H3}),Z3=V({action:xj(`left_mouse_up`),coordinate:H3}),Q3=V({action:xj(`scroll`),coordinate:H3,scroll_direction:yj([`up`,`down`,`left`,`right`]),scroll_amount:JA()}),$3=V({action:xj(`type`),text:B()}),e6=V({action:xj(`key`),key:B()}),t6=V({action:xj(`mouse_move`),coordinate:H3}),n6=V({action:xj(`hold_key`),key:B()}),r6=V({action:xj(`wait`),duration:JA().optional()}),i6=V({action:xj(`zoom`),region:hj([JA(),JA(),JA(),JA()])});dj(`action`,[U3,W3,G3,K3,q3,J3,Y3,X3,Z3,Q3,$3,e6,t6,n6,r6]),dj(`action`,[U3,W3,G3,K3,q3,J3,Y3,X3,Z3,Q3,$3,e6,t6,n6,r6,i6]),lj([V({command:B().describe(`The bash command to run`)}),V({restart:xj(!0).describe(`Set to true to restart the bash session`)})]);async function*a6(e,t={}){let n=t.streamUsage??!0,r=t.think??!1,i=new Map,a=new Map,o=0,s=!1,c,l,u=(e,t)=>{let n=a.get(e);if(n!==void 0)return{index:n,isNew:!1};let r=o++;return a.set(e,r),i.set(r,{...t}),{index:r,isNew:!0}};for await(let t of e){if(s||(s=!0,yield{event:`message-start`}),n){let e=t.prompt_eval_count??0,n=t.eval_count??0;(e>0||n>0)&&(c={input_tokens:e,output_tokens:n,total_tokens:e+n},yield{event:`usage`,usage:c})}t.done_reason&&(l=o6(t.done_reason));let{message:e}=t;if(r&&e.thinking){let{index:t,isNew:n}=u(`reasoning`,{type:`reasoning`,reasoning:``});n&&(yield{event:`content-block-start`,index:t,content:{type:`reasoning`,reasoning:``}});let r=i.get(t);r.reasoning=(r.reasoning??``)+e.thinking,yield{event:`content-block-delta`,index:t,delta:{type:`reasoning-delta`,reasoning:e.thinking}}}if(e.content){let{index:t,isNew:n}=u(`text`,{type:`text`,text:``});n&&(yield{event:`content-block-start`,index:t,content:{type:`text`,text:``}});let r=i.get(t);r.text=(r.text??``)+e.content,yield{event:`content-block-delta`,index:t,delta:{type:`text-delta`,text:e.content}}}if(e.tool_calls?.length)for(let t=0;t<e.tool_calls.length;t++){let n=e.tool_calls[t],r=`tool:${t}`,a=typeof n.function.arguments==`string`?n.function.arguments:JSON.stringify(n.function.arguments),{index:o,isNew:s}=u(r,{type:`tool_call_chunk`,name:n.function.name,args:``,index:t});s&&(yield{event:`content-block-start`,index:o,content:{type:`tool_call_chunk`,name:n.function.name,args:``,index:t}});let c=i.get(o);c.name=n.function.name,c.args=a,yield{event:`content-block-delta`,index:o,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,name:c.name,args:c.args}}}}}for(let[e,t]of i)yield{event:`content-block-finish`,index:e,content:$E(t)};yield{event:`message-finish`,reason:l,...c?{usage:c}:{},responseMetadata:{model_provider:`ollama`}}}function o6(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;default:return`stop`}}function s6(e,t){return new Nn({content:e.content??``,additional_kwargs:e.thinking&&e.thinking!==``?{reasoning_content:e.thinking}:{},tool_call_chunks:e.tool_calls?.map(e=>({name:e.function.name,args:JSON.stringify(e.function.arguments),type:`tool_call_chunk`,index:0,id:Yr()})),response_metadata:{...t?.responseMetadata,model_provider:`ollama`},usage_metadata:t?.usageMetadata})}function c6(e){let t=e.match(/^data:.*?;base64,(.*)$/);return t?t[1]:``}function l6(e){if(typeof e.content==`string`){if(e.tool_calls?.length){let t=e.tool_calls.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:e.args}}));return[{role:`assistant`,content:e.content,tool_calls:t}]}return[{role:`assistant`,content:e.content}]}let t=e.content.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>({role:`assistant`,content:e.text})),n;if(e.content.find(e=>e.type===`tool_use`)&&e.tool_calls?.length){let t=e.tool_calls?.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:e.args}}));t&&(n={role:`assistant`,tool_calls:t,content:``})}else if(e.content.find(e=>e.type===`tool_use`)&&!e.tool_calls?.length)throw Error(`'tool_use' content type is not supported without tool calls.`);return[...t,...n?[n]:[]]}function u6(e){return typeof e.content==`string`?[{role:`user`,content:e.content}]:e.content.map(e=>{if(e.type===`text`)return{role:`user`,content:e.text};if(e.type===`image_url`){if(typeof e.image_url==`string`)return{role:`user`,content:``,images:[c6(e.image_url)]};if(e.image_url.url&&typeof e.image_url.url==`string`)return{role:`user`,content:``,images:[c6(e.image_url.url)]}}throw Error(`Unsupported content type: ${e.type}`)})}function d6(e){if(typeof e.content==`string`)return[{role:`system`,content:e.content}];if(e.content.every(e=>e.type===`text`&&typeof e.text==`string`))return e.content.map(e=>({role:`system`,content:e.text}));throw Error(`Unsupported content type(s): ${e.content.map(e=>e.type).join(`, `)}`)}function f6(e){if(typeof e.content!=`string`)throw Error(`Non string tool message content is not supported`);return[{role:`tool`,content:e.content}]}function p6(e){return e.flatMap(e=>{if([`human`,`generic`].includes(e._getType()))return u6(e);if(e._getType()===`ai`)return l6(e);if(e._getType()===`system`)return d6(e);if(e._getType()===`tool`)return f6(e);throw Error(`Unsupported message type: ${e._getType()}`)})}var m6=typeof globalThis<`u`&&globalThis||typeof self<`u`&&self||typeof global<`u`&&global||{},h6={searchParams:`URLSearchParams`in m6,iterable:`Symbol`in m6&&`iterator`in Symbol,blob:`FileReader`in m6&&`Blob`in m6&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:`FormData`in m6,arrayBuffer:`ArrayBuffer`in m6};function g6(e){return e&&DataView.prototype.isPrototypeOf(e)}if(h6.arrayBuffer)var _6=[`[object Int8Array]`,`[object Uint8Array]`,`[object Uint8ClampedArray]`,`[object Int16Array]`,`[object Uint16Array]`,`[object Int32Array]`,`[object Uint32Array]`,`[object Float32Array]`,`[object Float64Array]`],v6=ArrayBuffer.isView||function(e){return e&&_6.indexOf(Object.prototype.toString.call(e))>-1};function y6(e){if(typeof e!=`string`&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||e===``)throw TypeError(`Invalid character in header field name: "`+e+`"`);return e.toLowerCase()}function b6(e){return typeof e!=`string`&&(e=String(e)),e}function x6(e){var t={next:function(){var t=e.shift();return{done:t===void 0,value:t}}};return h6.iterable&&(t[Symbol.iterator]=function(){return t}),t}function S6(e){this.map={},e instanceof S6?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){if(e.length!=2)throw TypeError(`Headers constructor: expected name/value pair to be length 2, found`+e.length);this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}S6.prototype.append=function(e,t){e=y6(e),t=b6(t);var n=this.map[e];this.map[e]=n?n+`, `+t:t},S6.prototype.delete=function(e){delete this.map[y6(e)]},S6.prototype.get=function(e){return e=y6(e),this.has(e)?this.map[e]:null},S6.prototype.has=function(e){return this.map.hasOwnProperty(y6(e))},S6.prototype.set=function(e,t){this.map[y6(e)]=b6(t)},S6.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},S6.prototype.keys=function(){var e=[];return this.forEach(function(t,n){e.push(n)}),x6(e)},S6.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),x6(e)},S6.prototype.entries=function(){var e=[];return this.forEach(function(t,n){e.push([n,t])}),x6(e)},h6.iterable&&(S6.prototype[Symbol.iterator]=S6.prototype.entries);function C6(e){if(!e._noBody){if(e.bodyUsed)return Promise.reject(TypeError(`Already read`));e.bodyUsed=!0}}function w6(e){return new Promise(function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}})}function T6(e){var t=new FileReader,n=w6(t);return t.readAsArrayBuffer(e),n}function E6(e){var t=new FileReader,n=w6(t),r=/charset=([A-Za-z0-9_-]+)/.exec(e.type),i=r?r[1]:`utf-8`;return t.readAsText(e,i),n}function D6(e){for(var t=new Uint8Array(e),n=Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join(``)}function O6(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function k6(){return this.bodyUsed=!1,this._initBody=function(e){this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?typeof e==`string`?this._bodyText=e:h6.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:h6.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:h6.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():h6.arrayBuffer&&h6.blob&&g6(e)?(this._bodyArrayBuffer=O6(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):h6.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||v6(e))?this._bodyArrayBuffer=O6(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,this._bodyText=``),this.headers.get(`content-type`)||(typeof e==`string`?this.headers.set(`content-type`,`text/plain;charset=UTF-8`):this._bodyBlob&&this._bodyBlob.type?this.headers.set(`content-type`,this._bodyBlob.type):h6.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set(`content-type`,`application/x-www-form-urlencoded;charset=UTF-8`))},h6.blob&&(this.blob=function(){var e=C6(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw Error(`could not read FormData body as blob`);return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer)return C6(this)||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer));if(h6.blob)return this.blob().then(T6);throw Error(`could not read as ArrayBuffer`)},this.text=function(){var e=C6(this);if(e)return e;if(this._bodyBlob)return E6(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(D6(this._bodyArrayBuffer));if(this._bodyFormData)throw Error(`could not read FormData body as text`);return Promise.resolve(this._bodyText)},h6.formData&&(this.formData=function(){return this.text().then(N6)}),this.json=function(){return this.text().then(JSON.parse)},this}var A6=[`CONNECT`,`DELETE`,`GET`,`HEAD`,`OPTIONS`,`PATCH`,`POST`,`PUT`,`TRACE`];function j6(e){var t=e.toUpperCase();return A6.indexOf(t)>-1?t:e}function M6(e,t){if(!(this instanceof M6))throw TypeError(`Please use the "new" operator, this DOM object constructor cannot be called as a function.`);t||={};var n=t.body;if(e instanceof M6){if(e.bodyUsed)throw TypeError(`Already read`);this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new S6(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,!n&&e._bodyInit!=null&&(n=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||`same-origin`,(t.headers||!this.headers)&&(this.headers=new S6(t.headers)),this.method=j6(t.method||this.method||`GET`),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if(`AbortController`in m6)return new AbortController().signal}(),this.referrer=null,(this.method===`GET`||this.method===`HEAD`)&&n)throw TypeError(`Body not allowed for GET or HEAD requests`);if(this._initBody(n),(this.method===`GET`||this.method===`HEAD`)&&(t.cache===`no-store`||t.cache===`no-cache`)){var r=/([?&])_=[^&]*/;if(r.test(this.url))this.url=this.url.replace(r,`$1_=`+new Date().getTime());else{var i=/\?/;this.url+=(i.test(this.url)?`&`:`?`)+`_=`+new Date().getTime()}}}M6.prototype.clone=function(){return new M6(this,{body:this._bodyInit})};function N6(e){var t=new FormData;return e.trim().split(`&`).forEach(function(e){if(e){var n=e.split(`=`),r=n.shift().replace(/\+/g,` `),i=n.join(`=`).replace(/\+/g,` `);t.append(decodeURIComponent(r),decodeURIComponent(i))}}),t}function P6(e){var t=new S6;return e.replace(/\r?\n[\t ]+/g,` `).split(`\r`).map(function(e){return e.indexOf(`
|
|
254
|
+
`)===0?e.substr(1,e.length):e}).forEach(function(e){var n=e.split(`:`),r=n.shift().trim();if(r){var i=n.join(`:`).trim();try{t.append(r,i)}catch(e){console.warn(`Response `+e.message)}}}),t}k6.call(M6.prototype);function F6(e,t){if(!(this instanceof F6))throw TypeError(`Please use the "new" operator, this DOM object constructor cannot be called as a function.`);if(t||={},this.type=`default`,this.status=t.status===void 0?200:t.status,this.status<200||this.status>599)throw RangeError(`Failed to construct 'Response': The status provided (0) is outside the range [200, 599].`);this.ok=this.status>=200&&this.status<300,this.statusText=t.statusText===void 0?``:``+t.statusText,this.headers=new S6(t.headers),this.url=t.url||``,this._initBody(e)}k6.call(F6.prototype),F6.prototype.clone=function(){return new F6(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new S6(this.headers),url:this.url})},F6.error=function(){var e=new F6(null,{status:200,statusText:``});return e.ok=!1,e.status=0,e.type=`error`,e};var I6=[301,302,303,307,308];F6.redirect=function(e,t){if(I6.indexOf(t)===-1)throw RangeError(`Invalid status code`);return new F6(null,{status:t,headers:{location:e}})};var L6=m6.DOMException;try{new L6}catch{L6=function(e,t){this.message=e,this.name=t;var n=Error(e);this.stack=n.stack},L6.prototype=Object.create(Error.prototype),L6.prototype.constructor=L6}function R6(e,t){return new Promise(function(n,r){var i=new M6(e,t);if(i.signal&&i.signal.aborted)return r(new L6(`Aborted`,`AbortError`));var a=new XMLHttpRequest;function o(){a.abort()}a.onload=function(){var e={statusText:a.statusText,headers:P6(a.getAllResponseHeaders()||``)};i.url.indexOf(`file://`)===0&&(a.status<200||a.status>599)?e.status=200:e.status=a.status,e.url=`responseURL`in a?a.responseURL:e.headers.get(`X-Request-URL`);var t=`response`in a?a.response:a.responseText;setTimeout(function(){n(new F6(t,e))},0)},a.onerror=function(){setTimeout(function(){r(TypeError(`Network request failed`))},0)},a.ontimeout=function(){setTimeout(function(){r(TypeError(`Network request timed out`))},0)},a.onabort=function(){setTimeout(function(){r(new L6(`Aborted`,`AbortError`))},0)};function s(e){try{return e===``&&m6.location.href?m6.location.href:e}catch{return e}}if(a.open(i.method,s(i.url),!0),i.credentials===`include`?a.withCredentials=!0:i.credentials===`omit`&&(a.withCredentials=!1),`responseType`in a&&(h6.blob?a.responseType=`blob`:h6.arrayBuffer&&(a.responseType=`arraybuffer`)),t&&typeof t.headers==`object`&&!(t.headers instanceof S6||m6.Headers&&t.headers instanceof m6.Headers)){var c=[];Object.getOwnPropertyNames(t.headers).forEach(function(e){c.push(y6(e)),a.setRequestHeader(e,b6(t.headers[e]))}),i.headers.forEach(function(e,t){c.indexOf(t)===-1&&a.setRequestHeader(t,e)})}else i.headers.forEach(function(e,t){a.setRequestHeader(t,e)});i.signal&&(i.signal.addEventListener(`abort`,o),a.onreadystatechange=function(){a.readyState===4&&i.signal.removeEventListener(`abort`,o)}),a.send(i._bodyInit===void 0?null:i._bodyInit)})}R6.polyfill=!0,m6.fetch||(m6.fetch=R6,m6.Headers=S6,m6.Request=M6,m6.Response=F6);var z6=`11434`,B6=`http://127.0.0.1:${z6}`,V6=`0.6.3`,H6=Object.defineProperty,U6=(e,t,n)=>t in e?H6(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,W6=(e,t,n)=>(U6(e,typeof t==`symbol`?t:t+``,n),n),G6=class e extends Error{constructor(t,n){super(t),this.error=t,this.status_code=n,this.name=`ResponseError`,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},K6=class{constructor(e,t,n){W6(this,`abortController`),W6(this,`itr`),W6(this,`doneCallback`),this.abortController=e,this.itr=t,this.doneCallback=n}abort(){this.abortController.abort()}async*[Symbol.asyncIterator](){for await(let e of this.itr){if(`error`in e)throw Error(e.error);if(yield e,e.done||e.status===`success`){this.doneCallback();return}}throw Error(`Did not receive done or success response in stream.`)}},q6=async e=>{if(e.ok)return;let t=`Error ${e.status}: ${e.statusText}`,n=null;if(e.headers.get(`content-type`)?.includes(`application/json`))try{n=await e.json(),t=n.error||t}catch{console.log(`Failed to parse error response as JSON`)}else try{console.log(`Getting text from response`),t=await e.text()||t}catch{console.log(`Failed to get text from error response`)}throw new G6(t,e.status)};function J6(){if(typeof window<`u`&&window.navigator){let e=navigator;return`userAgentData`in e&&e.userAgentData?.platform?`${e.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`:navigator.platform?`${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`:`unknown Browser/${navigator.userAgent};`}else if(typeof process<`u`)return`${process.arch} ${process.platform} Node.js/${process.version}`;return``}function Y6(e){if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}else if(Array.isArray(e))return Object.fromEntries(e);else return e||{}}var X6=(e,t)=>e[t],Z6=async(e,t,n={})=>{let r={"Content-Type":`application/json`,Accept:`application/json`,"User-Agent":`ollama-js/${V6} (${J6()})`};n.headers=Y6(n.headers);try{let e=new URL(t);if(e.protocol===`https:`&&e.hostname===`ollama.com`){let e=typeof process==`object`&&process!==null?X6({},`OLLAMA_API_KEY`):void 0;!(n.headers.authorization||n.headers.Authorization)&&e&&(n.headers.Authorization=`Bearer ${e}`)}}catch(e){console.error(`error parsing url`,e)}let i=Object.fromEntries(Object.entries(n.headers).filter(([e])=>!Object.keys(r).some(t=>t.toLowerCase()===e.toLowerCase())));return n.headers={...r,...i},e(t,n)},Q6=async(e,t,n)=>{let r=await Z6(e,t,{headers:n?.headers});return await q6(r),r},$6=async(e,t,n,r)=>{let i=await Z6(e,t,{method:`POST`,body:(e=>typeof e==`object`&&!!e&&!Array.isArray(e))(n)?JSON.stringify(n):n,signal:r?.signal,headers:r?.headers});return await q6(i),i},e8=async(e,t,n,r)=>{let i=await Z6(e,t,{method:`DELETE`,body:JSON.stringify(n),headers:r?.headers});return await q6(i),i},t8=async function*(e){let t=new TextDecoder(`utf-8`),n=``,r=e.getReader();for(;;){let{done:e,value:i}=await r.read();if(e)break;n+=t.decode(i,{stream:!0});let a=n.split(`
|
|
255
255
|
`);n=a.pop()??``;for(let e of a)try{yield JSON.parse(e)}catch{console.warn(`invalid json: `,e)}}n+=t.decode();for(let e of n.split(`
|
|
256
|
-
`).filter(e=>e!==``))try{yield JSON.parse(e)}catch{console.warn(`invalid json: `,e)}},J6=e=>{if(!e)return M6;let t=e.includes(`://`);e.startsWith(`:`)&&(e=`http://127.0.0.1${e}`,t=!0),t||(e=`http://${e}`);let n=new URL(e),r=n.port;r||=t?n.protocol===`https:`?`443`:`80`:j6;let i=``;n.username&&(i=n.username,n.password&&(i+=`:${n.password}`),i+=`@`);let a=`${n.protocol}//${i}${n.hostname}:${r}${n.pathname}`;return a.endsWith(`/`)&&(a=a.slice(0,-1)),a},Y6=Object.defineProperty,X6=(e,t,n)=>t in e?Y6(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Z6=(e,t,n)=>(X6(e,typeof t==`symbol`?t:t+``,n),n),Q6=class{constructor(e){Z6(this,`config`),Z6(this,`fetch`),Z6(this,`ongoingStreamedRequests`,[]),this.config={host:``,headers:e?.headers},e?.proxy||(this.config.host=J6(e?.host??M6)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,t){t.stream=t.stream??!1;let n=`${this.config.host}/api/${e}`;if(t.stream){let e=new AbortController,r=await G6(this.fetch,n,t,{signal:e.signal,headers:this.config.headers});if(!r.body)throw Error(`Missing body`);let i=new R6(e,q6(r.body),()=>{let e=this.ongoingStreamedRequests.indexOf(i);e>-1&&this.ongoingStreamedRequests.splice(e,1)});return this.ongoingStreamedRequests.push(i),i}return await(await G6(this.fetch,n,t,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!=`string`){let t=new Uint8Array(e),n=``,r=t.byteLength;for(let e=0;e<r;e++)n+=String.fromCharCode(t[e]);return btoa(n)}return e}async generate(e){return e.images&&=await Promise.all(e.images.map(this.encodeImage.bind(this))),this.processStreamableRequest(`generate`,e)}async chat(e){if(e.messages)for(let t of e.messages)t.images&&=await Promise.all(t.images.map(this.encodeImage.bind(this)));return this.processStreamableRequest(`chat`,e)}async create(e){return this.processStreamableRequest(`create`,{...e})}async pull(e){return this.processStreamableRequest(`pull`,{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest(`push`,{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await K6(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:`success`}}async copy(e){return await G6(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:`success`}}async list(){return await(await W6(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await G6(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await G6(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await G6(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await W6(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await W6(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw Error(`Query is required`);return await(await G6(this.fetch,`https://ollama.com/api/web_search`,{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw Error(`URL is required`);return await(await G6(this.fetch,`https://ollama.com/api/web_fetch`,{...e},{headers:this.config.headers})).json()}};new Q6;var $6=class extends iD{static lc_name(){return`ChatOllama`}model=`llama3`;numa;numCtx;numBatch;numGpu;mainGpu;lowVram;f16Kv;logitsAll;vocabOnly;useMmap;useMlock;embeddingOnly;numThread;numKeep;seed;numPredict;topK;topP;tfsZ;typicalP;repeatLastN;temperature;repeatPenalty;presencePenalty;frequencyPenalty;mirostat;mirostatTau;mirostatEta;penalizeNewline;streaming;format;keepAlive;client;checkOrPullModel=!1;baseUrl=`http://127.0.0.1:11434`;think;constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e??{};super(n),this._addVersion(`@langchain/ollama`,`1.3.0`),this.baseUrl=n.baseUrl??ui(`OLLAMA_BASE_URL`)??this.baseUrl,this.client=new Q6({fetch:n.fetch,host:this.baseUrl,headers:n.headers}),this.model=n.model??this.model,this.numa=n.numa,this.numCtx=n.numCtx,this.numBatch=n.numBatch,this.numGpu=n.numGpu,this.mainGpu=n.mainGpu,this.lowVram=n.lowVram,this.f16Kv=n.f16Kv,this.logitsAll=n.logitsAll,this.vocabOnly=n.vocabOnly,this.useMmap=n.useMmap,this.useMlock=n.useMlock,this.embeddingOnly=n.embeddingOnly,this.numThread=n.numThread,this.numKeep=n.numKeep,this.seed=n.seed,this.numPredict=n.numPredict,this.topK=n.topK,this.topP=n.topP,this.tfsZ=n.tfsZ,this.typicalP=n.typicalP,this.repeatLastN=n.repeatLastN,this.temperature=n.temperature,this.repeatPenalty=n.repeatPenalty,this.presencePenalty=n.presencePenalty,this.frequencyPenalty=n.frequencyPenalty,this.mirostat=n.mirostat,this.mirostatTau=n.mirostatTau,this.mirostatEta=n.mirostatEta,this.penalizeNewline=n.penalizeNewline,this.streaming=n.streaming,this.format=n.format,this.keepAlive=n.keepAlive,this.think=n.think,this.checkOrPullModel=n.checkOrPullModel??this.checkOrPullModel}_llmType(){return`ollama`}async pull(e,t){let{stream:n,insecure:r,logProgress:i}={stream:!0,...t};if(n)for await(let t of await this.client.pull({model:e,insecure:r,stream:n}))i&&console.log(t);else{let t=await this.client.pull({model:e,insecure:r});i&&console.log(t)}}bindTools(e,t){return this.withConfig({tools:e.map(e=>CM(e)),...t})}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`ollama`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.options?.temperature??void 0,ls_max_tokens:t.options?.num_predict??void 0,ls_stop:e.stop}}invocationParams(e){return{model:this.model,format:e?.format??this.format,keep_alive:this.keepAlive,think:this.think,options:{numa:this.numa,num_ctx:this.numCtx,num_batch:this.numBatch,num_gpu:this.numGpu,main_gpu:this.mainGpu,low_vram:this.lowVram,f16_kv:this.f16Kv,logits_all:this.logitsAll,vocab_only:this.vocabOnly,use_mmap:this.useMmap,use_mlock:this.useMlock,embedding_only:this.embeddingOnly,num_thread:this.numThread,num_keep:this.numKeep,seed:this.seed,num_predict:this.numPredict,top_k:this.topK,top_p:this.topP,tfs_z:this.tfsZ,typical_p:this.typicalP,repeat_last_n:this.repeatLastN,temperature:this.temperature,repeat_penalty:this.repeatPenalty,presence_penalty:this.presencePenalty,frequency_penalty:this.frequencyPenalty,mirostat:this.mirostat,mirostat_tau:this.mirostatTau,mirostat_eta:this.mirostatEta,penalize_newline:this.penalizeNewline,stop:e?.stop},tools:e?.tools?.length?e.tools.map(e=>CM(e)):void 0}}async checkModelExistsOnMachine(e){let{models:t}=await this.client.list();return!!t.find(t=>t.name===e||t.name===`${e}:latest`)}async ensureModelAvailable(){this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}))}async _generate(e,t,n){t.signal?.throwIfAborted(),await this.ensureModelAvailable();let r;for await(let i of this._streamResponseChunks(e,t,n))r=r?Lu(r,i.message):i.message;let i=new An({id:r?.id,content:r?.content??``,additional_kwargs:r?.additional_kwargs,tool_calls:r?.tool_calls,response_metadata:r?.response_metadata,usage_metadata:r?.usage_metadata});return{generations:[{text:typeof i.content==`string`?i.content:``,message:i}]}}async*_streamChatModelEvents(e,t,n){await this.ensureModelAvailable();let r=this.invocationParams(t),i=a6(e),a=await this.client.chat({...r,messages:i,stream:!0}),o=t.streamUsage??!0;yield*Z3(async function*(e,t){for await(let n of e){if(t?.aborted)return;yield n}}(a,t.signal),{streamUsage:o,think:this.think})}async*_streamResponseChunks(e,t,n){await this.ensureModelAvailable();let r=this.invocationParams(t),i=a6(e),a={input_tokens:0,output_tokens:0,total_tokens:0},o=await this.client.chat({...r,messages:i,stream:!0}),s;for await(let e of o){if(t.signal?.aborted){this.client.abort();return}let{message:r,...i}=e;a.input_tokens+=i.prompt_eval_count??0,a.output_tokens+=i.eval_count??0,a.total_tokens=a.input_tokens+a.output_tokens,s=i;let o=this.think?r.thinking??r.content??``:r.content??``,c=new xd({text:o,message:$3(r)});yield c,await n?.handleLLMNewToken(o,void 0,void 0,void 0,void 0,{chunk:c})}yield new xd({text:``,message:new Nn({content:``,response_metadata:{...s,model_provider:`ollama`},usage_metadata:a})})}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e},s=t?.method??`jsonSchema`;if(s===`functionCalling`){let e=a??`extract`,t,o=Rx(i);N_(i)||Zb(i)?t={name:e,description:o.description,parameters:o}:typeof i.name==`string`&&typeof i.parameters==`object`&&i.parameters!=null?(t=i,e=i.name):t={name:e,description:i.description??``,parameters:i},n=this.bindTools([{type:`function`,function:t}]).withConfig({ls_structured_output_format:{kwargs:{method:s},schema:N_(i)||Zb(i)?o:i}}),r=DE(i,e)}else if(s===`jsonMode`||s===`jsonSchema`){r=EE(i);let e=Rx(i);n=this.withConfig({format:s===`jsonMode`?`json`:e,ls_structured_output_format:{kwargs:{method:s},schema:e}})}else throw TypeError(`Unrecognized structured output method '${s}'. Expected one of 'functionCalling', 'jsonMode', or 'jsonSchema'`);return OE(n,r,o,o?`StructuredOutputRunnable`:`ChatOllamaStructuredOutput`)}},e8=e=>ne.includes(e),t8=e=>x.includes(e),n8=e=>{let{executeQuery:t,search:n,grep:r,readFile:i}=e;return[Qj(async({query:e,limit:t,groupByProcess:r})=>{let i=t??10,a=r??!0,o;try{o=await n(e,{limit:i,enrich:!0})}catch{return`Search is not available. Please load a repository first.`}if(o.length===0)return`No code found matching "${e}". Try different terms or use grep for exact patterns.`;let s=o.slice(0,i).map((e,t)=>{let n=e.nodeId||``,r=e.name||e.filePath?.split(`/`).pop()||`Unknown`,i=e.label||`File`,a=e.filePath||``,o=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``,s=e.sources?.join(`+`)||`hybrid`,c=e.score?` [score: ${e.score.toFixed(2)}]`:``,l=``;if(e.connections){let t=(e.connections.outgoing||[]).filter(e=>e?.name).slice(0,3),n=(e.connections.incoming||[]).filter(e=>e?.name).slice(0,3),r=(e,t)=>{let n=e.confidence?Math.round(e.confidence*100):100;return t===`out`?`-[${e.type} ${n}%]-> ${e.name}`:`<-[${e.type} ${n}%]- ${e.name}`},i=t.map(e=>r(e,`out`)),a=n.map(e=>r(e,`in`));(i.length||a.length)&&(l=`\n Connections: ${[...i,...a].join(`, `)}`)}let u=e.cluster||`Unclustered`,d=(e.processes||[]).filter(e=>e.id&&e.label);return{idx:t+1,nodeId:n,name:r,label:i,filePath:a,location:o,sources:s,score:c,connections:l,clusterLabel:u,processes:d}}),c=(e,t)=>{let n=t?.step?` (step ${t.step}/${t.stepCount??`?`})`:``;return`[${e.idx}] ${e.label}: ${e.name}${e.score}${n}\n ID: ${e.nodeId}\n File: ${e.filePath}${e.location}\n Cluster: ${e.clusterLabel}\n Found by: ${e.sources}${e.connections}`};if(!a)return`Found ${o.length} matches:\n\n${s.map(e=>c(e)).join(`
|
|
256
|
+
`).filter(e=>e!==``))try{yield JSON.parse(e)}catch{console.warn(`invalid json: `,e)}},n8=e=>{if(!e)return B6;let t=e.includes(`://`);e.startsWith(`:`)&&(e=`http://127.0.0.1${e}`,t=!0),t||(e=`http://${e}`);let n=new URL(e),r=n.port;r||=t?n.protocol===`https:`?`443`:`80`:z6;let i=``;n.username&&(i=n.username,n.password&&(i+=`:${n.password}`),i+=`@`);let a=`${n.protocol}//${i}${n.hostname}:${r}${n.pathname}`;return a.endsWith(`/`)&&(a=a.slice(0,-1)),a},r8=Object.defineProperty,i8=(e,t,n)=>t in e?r8(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,a8=(e,t,n)=>(i8(e,typeof t==`symbol`?t:t+``,n),n),o8=class{constructor(e){a8(this,`config`),a8(this,`fetch`),a8(this,`ongoingStreamedRequests`,[]),this.config={host:``,headers:e?.headers},e?.proxy||(this.config.host=n8(e?.host??B6)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,t){t.stream=t.stream??!1;let n=`${this.config.host}/api/${e}`;if(t.stream){let e=new AbortController,r=await $6(this.fetch,n,t,{signal:e.signal,headers:this.config.headers});if(!r.body)throw Error(`Missing body`);let i=new K6(e,t8(r.body),()=>{let e=this.ongoingStreamedRequests.indexOf(i);e>-1&&this.ongoingStreamedRequests.splice(e,1)});return this.ongoingStreamedRequests.push(i),i}return await(await $6(this.fetch,n,t,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!=`string`){let t=new Uint8Array(e),n=``,r=t.byteLength;for(let e=0;e<r;e++)n+=String.fromCharCode(t[e]);return btoa(n)}return e}async generate(e){return e.images&&=await Promise.all(e.images.map(this.encodeImage.bind(this))),this.processStreamableRequest(`generate`,e)}async chat(e){if(e.messages)for(let t of e.messages)t.images&&=await Promise.all(t.images.map(this.encodeImage.bind(this)));return this.processStreamableRequest(`chat`,e)}async create(e){return this.processStreamableRequest(`create`,{...e})}async pull(e){return this.processStreamableRequest(`pull`,{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest(`push`,{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await e8(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:`success`}}async copy(e){return await $6(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:`success`}}async list(){return await(await Q6(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await $6(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await $6(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await $6(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await Q6(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await Q6(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw Error(`Query is required`);return await(await $6(this.fetch,`https://ollama.com/api/web_search`,{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw Error(`URL is required`);return await(await $6(this.fetch,`https://ollama.com/api/web_fetch`,{...e},{headers:this.config.headers})).json()}};new o8;var s8=class extends iD{static lc_name(){return`ChatOllama`}model=`llama3`;numa;numCtx;numBatch;numGpu;mainGpu;lowVram;f16Kv;logitsAll;vocabOnly;useMmap;useMlock;embeddingOnly;numThread;numKeep;seed;numPredict;topK;topP;tfsZ;typicalP;repeatLastN;temperature;repeatPenalty;presencePenalty;frequencyPenalty;mirostat;mirostatTau;mirostatEta;penalizeNewline;streaming;format;keepAlive;client;checkOrPullModel=!1;baseUrl=`http://127.0.0.1:11434`;think;constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e??{};super(n),this._addVersion(`@langchain/ollama`,`1.3.0`),this.baseUrl=n.baseUrl??ui(`OLLAMA_BASE_URL`)??this.baseUrl,this.client=new o8({fetch:n.fetch,host:this.baseUrl,headers:n.headers}),this.model=n.model??this.model,this.numa=n.numa,this.numCtx=n.numCtx,this.numBatch=n.numBatch,this.numGpu=n.numGpu,this.mainGpu=n.mainGpu,this.lowVram=n.lowVram,this.f16Kv=n.f16Kv,this.logitsAll=n.logitsAll,this.vocabOnly=n.vocabOnly,this.useMmap=n.useMmap,this.useMlock=n.useMlock,this.embeddingOnly=n.embeddingOnly,this.numThread=n.numThread,this.numKeep=n.numKeep,this.seed=n.seed,this.numPredict=n.numPredict,this.topK=n.topK,this.topP=n.topP,this.tfsZ=n.tfsZ,this.typicalP=n.typicalP,this.repeatLastN=n.repeatLastN,this.temperature=n.temperature,this.repeatPenalty=n.repeatPenalty,this.presencePenalty=n.presencePenalty,this.frequencyPenalty=n.frequencyPenalty,this.mirostat=n.mirostat,this.mirostatTau=n.mirostatTau,this.mirostatEta=n.mirostatEta,this.penalizeNewline=n.penalizeNewline,this.streaming=n.streaming,this.format=n.format,this.keepAlive=n.keepAlive,this.think=n.think,this.checkOrPullModel=n.checkOrPullModel??this.checkOrPullModel}_llmType(){return`ollama`}async pull(e,t){let{stream:n,insecure:r,logProgress:i}={stream:!0,...t};if(n)for await(let t of await this.client.pull({model:e,insecure:r,stream:n}))i&&console.log(t);else{let t=await this.client.pull({model:e,insecure:r});i&&console.log(t)}}bindTools(e,t){return this.withConfig({tools:e.map(e=>CM(e)),...t})}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`ollama`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.options?.temperature??void 0,ls_max_tokens:t.options?.num_predict??void 0,ls_stop:e.stop}}invocationParams(e){return{model:this.model,format:e?.format??this.format,keep_alive:this.keepAlive,think:this.think,options:{numa:this.numa,num_ctx:this.numCtx,num_batch:this.numBatch,num_gpu:this.numGpu,main_gpu:this.mainGpu,low_vram:this.lowVram,f16_kv:this.f16Kv,logits_all:this.logitsAll,vocab_only:this.vocabOnly,use_mmap:this.useMmap,use_mlock:this.useMlock,embedding_only:this.embeddingOnly,num_thread:this.numThread,num_keep:this.numKeep,seed:this.seed,num_predict:this.numPredict,top_k:this.topK,top_p:this.topP,tfs_z:this.tfsZ,typical_p:this.typicalP,repeat_last_n:this.repeatLastN,temperature:this.temperature,repeat_penalty:this.repeatPenalty,presence_penalty:this.presencePenalty,frequency_penalty:this.frequencyPenalty,mirostat:this.mirostat,mirostat_tau:this.mirostatTau,mirostat_eta:this.mirostatEta,penalize_newline:this.penalizeNewline,stop:e?.stop},tools:e?.tools?.length?e.tools.map(e=>CM(e)):void 0}}async checkModelExistsOnMachine(e){let{models:t}=await this.client.list();return!!t.find(t=>t.name===e||t.name===`${e}:latest`)}async ensureModelAvailable(){this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}))}async _generate(e,t,n){t.signal?.throwIfAborted(),await this.ensureModelAvailable();let r;for await(let i of this._streamResponseChunks(e,t,n))r=r?Lu(r,i.message):i.message;let i=new An({id:r?.id,content:r?.content??``,additional_kwargs:r?.additional_kwargs,tool_calls:r?.tool_calls,response_metadata:r?.response_metadata,usage_metadata:r?.usage_metadata});return{generations:[{text:typeof i.content==`string`?i.content:``,message:i}]}}async*_streamChatModelEvents(e,t,n){await this.ensureModelAvailable();let r=this.invocationParams(t),i=p6(e),a=await this.client.chat({...r,messages:i,stream:!0}),o=t.streamUsage??!0;yield*a6(async function*(e,t){for await(let n of e){if(t?.aborted)return;yield n}}(a,t.signal),{streamUsage:o,think:this.think})}async*_streamResponseChunks(e,t,n){await this.ensureModelAvailable();let r=this.invocationParams(t),i=p6(e),a={input_tokens:0,output_tokens:0,total_tokens:0},o=await this.client.chat({...r,messages:i,stream:!0}),s;for await(let e of o){if(t.signal?.aborted){this.client.abort();return}let{message:r,...i}=e;a.input_tokens+=i.prompt_eval_count??0,a.output_tokens+=i.eval_count??0,a.total_tokens=a.input_tokens+a.output_tokens,s=i;let o=this.think?r.thinking??r.content??``:r.content??``,c=new xd({text:o,message:s6(r)});yield c,await n?.handleLLMNewToken(o,void 0,void 0,void 0,void 0,{chunk:c})}yield new xd({text:``,message:new Nn({content:``,response_metadata:{...s,model_provider:`ollama`},usage_metadata:a})})}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e},s=t?.method??`jsonSchema`;if(s===`functionCalling`){let e=a??`extract`,t,o=Rx(i);N_(i)||Zb(i)?t={name:e,description:o.description,parameters:o}:typeof i.name==`string`&&typeof i.parameters==`object`&&i.parameters!=null?(t=i,e=i.name):t={name:e,description:i.description??``,parameters:i},n=this.bindTools([{type:`function`,function:t}]).withConfig({ls_structured_output_format:{kwargs:{method:s},schema:N_(i)||Zb(i)?o:i}}),r=DE(i,e)}else if(s===`jsonMode`||s===`jsonSchema`){r=EE(i);let e=Rx(i);n=this.withConfig({format:s===`jsonMode`?`json`:e,ls_structured_output_format:{kwargs:{method:s},schema:e}})}else throw TypeError(`Unrecognized structured output method '${s}'. Expected one of 'functionCalling', 'jsonMode', or 'jsonSchema'`);return OE(n,r,o,o?`StructuredOutputRunnable`:`ChatOllamaStructuredOutput`)}},c8=e=>ne.includes(e),l8=e=>x.includes(e),u8=e=>{let{executeQuery:t,search:n,grep:r,readFile:i}=e;return[Qj(async({query:e,limit:t,groupByProcess:r})=>{let i=t??10,a=r??!0,o;try{o=await n(e,{limit:i,enrich:!0})}catch{return`Search is not available. Please load a repository first.`}if(o.length===0)return`No code found matching "${e}". Try different terms or use grep for exact patterns.`;let s=o.slice(0,i).map((e,t)=>{let n=e.nodeId||``,r=e.name||e.filePath?.split(`/`).pop()||`Unknown`,i=e.label||`File`,a=e.filePath||``,o=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``,s=e.sources?.join(`+`)||`hybrid`,c=e.score?` [score: ${e.score.toFixed(2)}]`:``,l=``;if(e.connections){let t=(e.connections.outgoing||[]).filter(e=>e?.name).slice(0,3),n=(e.connections.incoming||[]).filter(e=>e?.name).slice(0,3),r=(e,t)=>{let n=e.confidence?Math.round(e.confidence*100):100;return t===`out`?`-[${e.type} ${n}%]-> ${e.name}`:`<-[${e.type} ${n}%]- ${e.name}`},i=t.map(e=>r(e,`out`)),a=n.map(e=>r(e,`in`));(i.length||a.length)&&(l=`\n Connections: ${[...i,...a].join(`, `)}`)}let u=e.cluster||`Unclustered`,d=(e.processes||[]).filter(e=>e.id&&e.label);return{idx:t+1,nodeId:n,name:r,label:i,filePath:a,location:o,sources:s,score:c,connections:l,clusterLabel:u,processes:d}}),c=(e,t)=>{let n=t?.step?` (step ${t.step}/${t.stepCount??`?`})`:``;return`[${e.idx}] ${e.label}: ${e.name}${e.score}${n}\n ID: ${e.nodeId}\n File: ${e.filePath}${e.location}\n Cluster: ${e.clusterLabel}\n Found by: ${e.sources}${e.connections}`};if(!a)return`Found ${o.length} matches:\n\n${s.map(e=>c(e)).join(`
|
|
257
257
|
|
|
258
258
|
`)}`;let l=new Map,u=`__no_process__`;for(let e of s){if(e.processes.length===0){l.has(u)||l.set(u,{label:`No process`,entries:[]}),l.get(u).entries.push({result:e});continue}for(let t of e.processes)l.has(t.id)||l.set(t.id,{label:t.label,stepCount:t.stepCount,entries:[]}),l.get(t.id).entries.push({result:e,step:t.step,stepCount:t.stepCount})}let d=Array.from(l.entries()).sort((e,t)=>{let n=e[1].entries.length;return t[1].entries.length-n}),f=[];f.push(`Found ${o.length} matches grouped by process:`),f.push(``);for(let[e,t]of d){let n=t.stepCount?`, ${t.stepCount} steps`:``,r=e===u?`NO PROCESS (${t.entries.length} matches)`:`PROCESS: ${t.label} (${t.entries.length} matches${n})`;f.push(r),t.entries.forEach(n=>{let r=n.step?{id:e,label:t.label,step:n.step,stepCount:n.stepCount}:void 0;f.push(c(n.result,r))}),f.push(``)}return f.join(`
|
|
259
259
|
`).trim()},{name:`search`,description:`Search for code by keywords or concepts. Combines keyword matching and semantic understanding. Groups results by process with cluster context.`,schema:V({query:B().describe(`What you are looking for (e.g., "authentication middleware", "database connection")`),groupByProcess:QA().optional().nullable().describe(`Group results by process (default: true)`),limit:JA().optional().nullable().describe(`Max results to return (default: 10)`)})}),Qj(async({query:e,cypher:r})=>{try{if(r.includes(`{{QUERY_VECTOR}}`)){if(!e)return`Error: Your Cypher contains {{QUERY_VECTOR}} but you didn't provide a 'query' to embed. Add a natural language query.`;try{let t=await n(e,{limit:10,mode:`semantic`});if(t.length===0)return`Semantic search returned no results. Embeddings may not be generated yet.`;let r=t.map((e,t)=>`[${t+1}] ${e.label||`File`}: ${e.name||e.filePath?.split(`/`).pop()||`?`} (score: ${(e.score??0).toFixed(3)})\n File: ${e.filePath||`n/a`}`).join(`
|
|
@@ -341,7 +341,7 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:V({cypher:B().describe(`The
|
|
|
341
341
|
ORDER BY p.stepCount DESC
|
|
342
342
|
LIMIT 20
|
|
343
343
|
`,[u,d]=await Promise.all([t(s),t(l)]),f=u.map(e=>{let t=c(e,0,`name`),n=c(e,1,`filePath`);return`- ${c(e,2,`nodeType`)}: ${t} (${n||`n/a`})`}),p=d.map(e=>`- ${c(e,1,`label`)} (${c(e,2,`stepCount`)} steps)`);return[`CLUSTER: ${n}`,`Symbols: ${i??u.length}`,`Cohesion: ${r==null?`n/a`:Number(r).toFixed(2)}`,`Description: ${a||`n/a`}`,``,`TOP MEMBERS:`,...f.length>0?f:[`- None found`],``,`PROCESSES TOUCHING THIS CLUSTER:`,...p.length>0?p:[`- None found`]].join(`
|
|
344
|
-
`)}if(i===`symbol`){let n=c(s,0,`id`),r=c(s,1,`name`),i=c(s,2,`filePath`),a=c(s,3,`nodeType`);if(!
|
|
344
|
+
`)}if(i===`symbol`){let n=c(s,0,`id`),r=c(s,1,`name`),i=c(s,2,`filePath`),a=c(s,3,`nodeType`);if(!c8(a))return`Unknown node type "${a}" for symbol "${e}".`;let o=`
|
|
345
345
|
MATCH (n:${a} {id: '${String(n).replace(/'/g,`''`)}'})
|
|
346
346
|
MATCH (n)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
|
|
347
347
|
RETURN c.label AS label, c.description AS description
|
|
@@ -360,7 +360,7 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:V({cypher:B().describe(`The
|
|
|
360
360
|
collect(DISTINCT {name: src.name, type: r2.type, confidence: r2.confidence}) AS incoming
|
|
361
361
|
LIMIT 1
|
|
362
362
|
`,[d,f,p]=await Promise.all([t(o),t(l),t(u)]),m=d.length>0?c(d[0],0,`label`):`Unclustered`,h=d.length>0?c(d[0],1,`description`):``,g=f.map(e=>`- ${c(e,0,`label`)} (step ${c(e,1,`step`)}/${c(e,2,`stepCount`)??`?`})`),_=`None`;if(p.length>0){let e=p[0],t=Array.isArray(e)?e[0]:e.outgoing||[],n=Array.isArray(e)?e[1]:e.incoming||[],r=(t||[]).filter(e=>e&&e.name).slice(0,5),i=(n||[]).filter(e=>e&&e.name).slice(0,5),a=(e,t)=>{let n=e.confidence?Math.round(e.confidence*100):100;return t===`out`?`-[${e.type} ${n}%]-> ${e.name}`:`<-[${e.type} ${n}%]- ${e.name}`},o=r.map(e=>a(e,`out`)),s=i.map(e=>a(e,`in`));(o.length||s.length)&&(_=[...o,...s].join(`, `))}return[`SYMBOL: ${a} ${r}`,`ID: ${n}`,`File: ${i||`n/a`}`,`Cluster: ${m}${h?` — ${h}`:``}`,``,`PROCESSES:`,...g.length>0?g:[`- None found`],``,`CONNECTIONS:`,_].join(`
|
|
363
|
-
`)}return`Unable to explore "${e}".`},{name:`explore`,description:`Deep dive on a symbol, cluster, or process. Shows membership, participation, and connections.`,schema:V({target:B().describe(`Name or ID of a symbol, cluster, or process`),type:yj([`symbol`,`cluster`,`process`]).optional().nullable().describe(`Optional target type (auto-detected if omitted)`)})}),Qj(async({target:e,direction:n,maxDepth:a,relationTypes:o,includeTests:s,minConfidence:c})=>{let l=Math.min(a??3,10),u=s??!1,d=c??.7,f=e=>{if(!e)return!1;let t=e.toLowerCase();return t.includes(`.test.`)||t.includes(`.spec.`)||t.includes(`__tests__`)||t.includes(`__mocks__`)||t.endsWith(`.test.ts`)||t.endsWith(`.test.tsx`)||t.endsWith(`.spec.ts`)||t.endsWith(`.spec.tsx`)},p=o&&o.length>0?o.filter(e=>
|
|
363
|
+
`)}return`Unable to explore "${e}".`},{name:`explore`,description:`Deep dive on a symbol, cluster, or process. Shows membership, participation, and connections.`,schema:V({target:B().describe(`Name or ID of a symbol, cluster, or process`),type:yj([`symbol`,`cluster`,`process`]).optional().nullable().describe(`Optional target type (auto-detected if omitted)`)})}),Qj(async({target:e,direction:n,maxDepth:a,relationTypes:o,includeTests:s,minConfidence:c})=>{let l=Math.min(a??3,10),u=s??!1,d=c??.7,f=e=>{if(!e)return!1;let t=e.toLowerCase();return t.includes(`.test.`)||t.includes(`.spec.`)||t.includes(`__tests__`)||t.includes(`__mocks__`)||t.endsWith(`.test.ts`)||t.endsWith(`.test.tsx`)||t.endsWith(`.spec.ts`)||t.endsWith(`.spec.tsx`)},p=o&&o.length>0?o.filter(e=>l8(e)):[`CALLS`,`IMPORTS`,`EXTENDS`,`IMPLEMENTS`];if(p.length===0)return`No valid relation types provided. Valid types: ${x.join(`, `)}`;let m=p.map(e=>`'${e.replace(/'/g,`''`)}'`).join(`, `),h=e.includes(`/`),g=e.replace(/'/g,`''`),_=h?`
|
|
364
364
|
MATCH (n)
|
|
365
365
|
WHERE n.filePath IS NOT NULL AND n.filePath CONTAINS '${g}'
|
|
366
366
|
RETURN n.id AS id, label(n) AS nodeType, n.filePath AS filePath
|
|
@@ -563,7 +563,7 @@ Additional output sections:
|
|
|
563
563
|
- Affected clusters (direct/indirect)
|
|
564
564
|
- RISK is the edit gate: warn before edits on HIGH/CRITICAL; UNKNOWN requires retry or corroboration
|
|
565
565
|
- Shared-axes risk compares File and symbol targets using direct/total counts only; it never waives the RISK gate
|
|
566
|
-
- riskScale notes unavailable process/module axes. This Graph-RAG tool expands File targets to in-file symbols; MCP File impact does not`,schema:V({target:B().describe(`Name of the function, class, or file to analyze`),direction:yj([`upstream`,`downstream`]).describe(`upstream = what depends on this; downstream = what this depends on`),maxDepth:JA().optional().nullable().describe(`Max traversal depth (default: 3, max: 10)`),relationTypes:oj(B()).optional().nullable().describe(`Filter by relation types: CALLS, IMPORTS, EXTENDS, IMPLEMENTS, CONTAINS, DEFINES (default: usage-based)`),includeTests:QA().optional().nullable().describe(`Include test files in results (default: false, excludes .test.ts, .spec.ts, __tests__)`),minConfidence:JA().optional().nullable().describe(`Minimum edge confidence 0-1 (default: 0.7, excludes fuzzy/inferred matches)`)})})]},
|
|
566
|
+
- riskScale notes unavailable process/module axes. This Graph-RAG tool expands File targets to in-file symbols; MCP File impact does not`,schema:V({target:B().describe(`Name of the function, class, or file to analyze`),direction:yj([`upstream`,`downstream`]).describe(`upstream = what depends on this; downstream = what this depends on`),maxDepth:JA().optional().nullable().describe(`Max traversal depth (default: 3, max: 10)`),relationTypes:oj(B()).optional().nullable().describe(`Filter by relation types: CALLS, IMPORTS, EXTENDS, IMPLEMENTS, CONTAINS, DEFINES (default: usage-based)`),includeTests:QA().optional().nullable().describe(`Include test files in results (default: false, excludes .test.ts, .spec.ts, __tests__)`),minConfidence:JA().optional().nullable().describe(`Minimum edge confidence 0-1 (default: 0.7, excludes fuzzy/inferred matches)`)})})]},d8=class extends fJ{activeMessages=null;setActiveMessages(e){if(this.activeMessages!==null)throw Error(`DeepSeekChatOpenAICompletions does not support overlapping requests`);this.activeMessages=e}async _generate(e,t,n){this.setActiveMessages(e);try{return await super._generate(e,t,n)}finally{this.activeMessages=null}}async*_streamResponseChunks(e,t,n){this.setActiveMessages(e);try{yield*super._streamResponseChunks(e,t,n)}finally{this.activeMessages=null}}async completionWithRetry(e,t){let n=this.activeMessages?y8(this.activeMessages):e.messages;return super.completionWithRetry({...e,messages:n},t)}},f8=class e extends FJ{deepSeekFields;constructor(e){let t={...e,completions:new d8(e)};super(t),this.deepSeekFields=t}withConfig(t){let n=new e(this.deepSeekFields);return n.defaultOptions={...this.defaultOptions,...t},n}},p8=e=>typeof e==`string`?e:Array.isArray(e)?e.filter(e=>e?.type===`text`||typeof e==`string`).map(e=>typeof e==`string`?e:e.text||``).join(``):e==null?``:String(e),m8=e=>{if(e?.args&&typeof e.args==`object`)return e.args;try{return e?.function?.arguments?JSON.parse(e.function.arguments):{}}catch{return{}}},h8=e=>{if(!(!Array.isArray(e)||e.length===0))return e.map(e=>({id:typeof e?.id==`string`?e.id:void 0,name:e?.name||e?.function?.name||`unknown`,args:m8(e),type:typeof e?.type==`string`?e.type:`tool_call`}))},g8=e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e??{})}catch{return`{}`}},_8=e=>{if(typeof e==`string`)return e;if(!Array.isArray(e))return p8(e);let t=e.flatMap(e=>typeof e==`string`?[{type:`text`,text:e}]:e?.type===`text`&&typeof e.text==`string`?[{type:`text`,text:e.text}]:[]);return t.length===0?``:t.length===1?t[0].text:t},v8=e=>{let t=e?._getType?.()||e?.type||e?.constructor?.name||`unknown`;if((e.additional_kwargs||{}).__openai_role__===`developer`)return`developer`;switch(t){case`human`:case`HumanMessage`:return`user`;case`ai`:case`AIMessage`:return`assistant`;case`system`:case`SystemMessage`:return`system`;case`tool`:case`ToolMessage`:return`tool`;case`function`:case`FunctionMessage`:return`function`;default:return typeof e.role==`string`?e.role:`user`}},y8=e=>e.map(e=>{let t=v8(e),n=e.additional_kwargs&&typeof e.additional_kwargs==`object`?e.additional_kwargs:{},r={role:t,content:_8(e.content)};if(typeof e.name==`string`&&e.name.length>0&&(r.name=e.name),t===`assistant`){let t=Array.isArray(e.tool_calls)?e.tool_calls:Array.isArray(n.tool_calls)?n.tool_calls:void 0;return t?.length&&(r.tool_calls=t.map(e=>e?.function?{id:e.id,type:e.type??`function`,function:{name:e.function.name,arguments:g8(e.function.arguments)}}:{id:e?.id,type:`function`,function:{name:e?.name??`unknown`,arguments:g8(e?.args)}})),n.function_call!=null&&(r.function_call=n.function_call),t?.length&&typeof n.reasoning_content==`string`&&(r.reasoning_content=n.reasoning_content),r}return t===`tool`&&typeof e.tool_call_id==`string`&&(r.tool_call_id=e.tool_call_id),t===`function`&&typeof e.name==`string`&&(r.name=e.name),r}),b8=`You are Nexus, a Code Analysis Agent with access to a Knowledge Graph. Your responses MUST be grounded.
|
|
567
567
|
|
|
568
568
|
## ⚠️ MANDATORY: GROUNDING
|
|
569
569
|
Every factual claim MUST include a citation.
|
|
@@ -663,4 +663,4 @@ When generating diagrams:
|
|
|
663
663
|
|
|
664
664
|
BAD: A[User's Data] --> B(Process & Save)
|
|
665
665
|
GOOD: A["User Data"] --> B["Process and Save"]
|
|
666
|
-
`,
|
|
666
|
+
`,x8=e=>{switch(e.provider){case`openai`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`OpenAI API key is required but was not provided`);return new FJ({apiKey:t.apiKey,modelName:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens,configuration:{apiKey:t.apiKey,...t.baseUrl?{baseURL:t.baseUrl}:{}},streaming:!0})}case`azure-openai`:{let t=e;return new IJ({azureOpenAIApiKey:t.apiKey,azureOpenAIApiInstanceName:S8(t.endpoint),azureOpenAIApiDeploymentName:t.deploymentName,azureOpenAIApiVersion:t.apiVersion??`2024-12-01-preview`,streaming:!0})}case`gemini`:{let t=e;return new xX({apiKey:t.apiKey,model:t.model,temperature:t.temperature??.1,maxOutputTokens:t.maxTokens,streaming:!0})}case`anthropic`:{let t=e;return new V3({anthropicApiKey:t.apiKey,model:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens??8192,streaming:!0})}case`ollama`:{let t=e;return new s8({baseUrl:t.baseUrl??`http://localhost:11434`,model:t.model,temperature:t.temperature??.1,streaming:!0,numPredict:3e4,numCtx:32768})}case`openrouter`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`OpenRouter API key is required but was not provided`);return new FJ({openAIApiKey:t.apiKey,apiKey:t.apiKey,modelName:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens,configuration:{apiKey:t.apiKey,baseURL:t.baseUrl??`https://openrouter.ai/api/v1`},streaming:!0})}case`minimax`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`MiniMax API key is required but was not provided`);let i=n(t.model),a=t.thinkingMode,o=a&&i?.thinkingModes.includes(a)?a:i?.thinkingModes[0]??a,s=o&&o!==`always_on`?{type:o}:void 0,c=o===`adaptive`||o===`always_on`?void 0:t.temperature??.1;return new V3({anthropicApiKey:t.apiKey,model:t.model,...c===void 0?{}:{temperature:c},maxTokens:t.maxTokens??8192,streaming:!0,...s?{thinking:s}:{},clientOptions:{baseURL:t.baseUrl??r.global_en}})}case`glm`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`GLM API key is required but was not provided`);return new FJ({apiKey:t.apiKey,modelName:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens,configuration:{apiKey:t.apiKey,baseURL:t.baseUrl??`https://api.z.ai/api/coding/paas/v4`},streaming:!0})}case`deepseek`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`DeepSeek API key is required but was not provided`);return new f8({apiKey:t.apiKey,modelName:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens,configuration:{apiKey:t.apiKey,baseURL:`https://api.deepseek.com`},streaming:!0})}default:throw Error(`Unsupported provider: ${e.provider}`)}},S8=e=>{try{let t=new URL(e).hostname,n=t.match(/^([^.]+)\.openai\.azure\.com$/);return n?n[1]:t.split(`.`)[0]}catch{return e}},C8=(e,t,n,r=!1)=>Iz({llm:x8(e),tools:u8(t),messageModifier:new qn(n?te(b8,n,r):r?`${b8}${ee}`:b8)}),w8=(e,t)=>!!(e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`||t?.aborted),T8=e=>e.map(e=>e.role===`user`?typeof e.content==`string`?new Hn(e.content):new Hn({content:e.content}):e.role===`tool`?new Xt({content:e.content,tool_call_id:e.toolCallId,...e.name?{name:e.name}:{}}):new An({content:e.content,...typeof e.reasoningContent==`string`?{additional_kwargs:{reasoning_content:e.reasoningContent}}:{},...e.toolCalls?.length?{tool_calls:e.toolCalls}:{}})),E8=(e,t=0)=>{let n=[];for(let r of e.slice(t)){let e=r,t=e?._getType?.()||e?.type||e?.constructor?.name||`unknown`;if(t===`ai`||t===`AIMessage`){let t=(e.additional_kwargs||e.kwargs)?.reasoning_content,r=h8(e.tool_calls);n.push({role:`assistant`,content:p8(e.content),...r?.length&&typeof t==`string`?{reasoningContent:t}:{},...r?.length?{toolCalls:r}:{}});continue}(t===`tool`||t===`ToolMessage`)&&n.push({role:`tool`,content:p8(e.content),toolCallId:String(e.tool_call_id??``),...typeof e.name==`string`?{name:e.name}:{}})}return n};async function*D8(e,t,n={}){try{let r=T8(t),i=await e.stream({messages:r},{streamMode:[`values`,`messages`],recursionLimit:50,signal:n.signal}),a=new Set,o=new Set,s=r.length,c=0,l=!1,u=null;for await(let e of i){if(n.signal?.aborted)break;let t,r;if(Array.isArray(e)&&e.length===2&&typeof e[0]==`string`?[t,r]=e:Array.isArray(e)&&e[0]?._getType?(t=`messages`,r=e):(t=`values`,r=e),t===`messages`){let[e]=Array.isArray(r)?r:[r];if(!e)continue;let t=e._getType?.()||e.type||e.constructor?.name||`unknown`;if(t===`ai`||t===`AIMessage`||t===`AIMessageChunk`){let t=e.content,n=e.tool_calls||[],r=``,i=``;if(typeof t==`string`?r=t:Array.isArray(t)&&(r=t.filter(e=>e.type===`text`||typeof e==`string`).map(e=>typeof e==`string`?e:e.text||``).join(``),i=t.filter(e=>e?.type===`thinking`).map(e=>e.thinking||``).join(``)),i&&(yield{type:`reasoning`,reasoning:i}),r&&r.length>0&&(!l||n.length>0||c>0?yield{type:`reasoning`,reasoning:r}:yield{type:`content`,content:r}),n.length>0){l=!0,c+=n.length;for(let e of n){let t=e.id||`tool-${Date.now()}-${Math.random().toString(36).slice(2)}`;if(!a.has(t)){a.add(t);let n;try{n=e.function?.arguments?JSON.parse(e.function.arguments):{}}catch{n={}}yield{type:`tool_call`,toolCall:{id:t,name:e.name||e.function?.name||`unknown`,args:e.args||n,status:`running`}}}}}}if(t===`tool`||t===`ToolMessage`){let t=e.tool_call_id||``;if(t&&!o.has(t)){o.add(t);let n=typeof e.content==`string`?e.content:JSON.stringify(e.content);yield{type:`tool_result`,toolCall:{id:t,name:e.name||`tool`,args:{},result:n,status:`completed`}},c=Math.max(0,c-1)}}}if(t===`values`&&r?.messages){let e=r.messages||[];n.captureHistory&&(u=e);for(let t=s;t<e.length;t++){let n=e[t],r=n._getType?.()||n.type||`unknown`;if((r===`ai`||r===`AIMessage`)&&!a.size){let e=n.tool_calls||[];for(let t of e){let e=t.id||`tool-${Date.now()}`;a.has(e)||(c++,a.add(e),yield{type:`tool_call`,toolCall:{id:e,name:t.name||`unknown`,args:t.args||{},status:`running`}})}}if(r===`tool`||r===`ToolMessage`){let e=n.tool_call_id||``;if(e&&!o.has(e)){o.add(e);let t=typeof n.content==`string`?n.content:JSON.stringify(n.content);yield{type:`tool_result`,toolCall:{id:e,name:n.name||`tool`,args:{},result:t,status:`completed`}},c=Math.max(0,c-1)}}}s=e.length}}if(n.signal?.aborted){yield{type:`cancelled`};return}yield{type:`done`,historyMessages:n.captureHistory&&u?E8(u,r.length):void 0}}catch(e){if(w8(e,n.signal)){yield{type:`cancelled`};return}yield{type:`error`,error:e instanceof Error?e.message:String(e)}}}export{C8 as createGraphRAGAgent,D8 as streamAgentResponse};
|