scordi-extension 1.15.1 → 1.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,158 @@
1
+ var Th=Object.defineProperty;var Ah=(n,e,t)=>e in n?Th(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var be=(n,e,t)=>Ah(n,typeof e!="symbol"?e+"":e,t);import{i as Ph,b as xh,c as Ih,d as Rh}from"./internal-messages-Drf0Gb9U.js";import{g as Lr,Z as P,a as Gt,o as wr,s as Ti,b as go,c as $h,l as kh,u as Ch,n as Nh,e as jh}from"./types-BId3CBm7.js";class Lh{constructor(){be(this,"activeTabs",new Map);be(this,"closedTabs",new Set);this.initializeTabClosedListener()}initializeTabClosedListener(){chrome.tabs.onRemoved.addListener(e=>{console.log("[TabManager] Tab closed:",e),this.activeTabs.has(e)&&(console.log("[TabManager] Tracked tab was closed:",e),this.activeTabs.delete(e),this.closedTabs.add(e),setTimeout(()=>{this.closedTabs.delete(e)},6e4))})}isTabClosed(e){return this.closedTabs.has(e)}async createTab(e,t=!1,r=2e3){const a=await chrome.tabs.create({url:e,active:t});if(!a.id)throw new Error("Failed to create new tab");return this.activeTabs.set(a.id,{url:e,createdAt:Date.now()}),await this.waitForTabLoad(a.id),await new Promise(s=>setTimeout(s,r)),a}async closeTab(e){await chrome.tabs.remove(e),this.activeTabs.delete(e)}async waitForTabLoad(e,t=3e4){return new Promise((r,a)=>{const s=setTimeout(()=>{chrome.tabs.onUpdated.removeListener(i),a(new Error("Tab load timeout"))},t),i=(o,u)=>{o===e&&u.status==="complete"&&(clearTimeout(s),chrome.tabs.onUpdated.removeListener(i),console.log("[8G TabManager] Tab loaded successfully:",e),r())};chrome.tabs.onUpdated.addListener(i)})}async executeBlock(e,t){return this.isTabClosed(t)?(console.log("[TabManager] Cannot execute block - tab was closed:",t),{hasError:!0,message:"Tab was closed by user",data:null}):this.executeBlockWithRetry(e,t,0)}async executeBlockWithRetry(e,t,r){return new Promise((s,i)=>{const o={isBlock:!0,type:"EXECUTE_BLOCK",data:e};chrome.tabs.sendMessage(t,o,async u=>{if(chrome.runtime.lastError){const c=chrome.runtime.lastError.message||"";if(console.log("[TabManager] Error sending message:",c),this.isTabClosed(t)){i(new Error("Tab was closed by user"));return}if((c.includes("Receiving end does not exist")||c.includes("message channel closed")||c.includes("back/forward cache"))&&r<3){console.log(`[TabManager] Page transition detected, waiting for reload and retrying (${r+1}/3)...`);try{await this.waitForTabLoad(t,1e4),await new Promise(h=>setTimeout(h,1e3));const d=await this.executeBlockWithRetry(e,t,r+1);s(d)}catch{i(new Error("Page load timeout after transition"))}}else i(new Error(c||"Communication error"))}else Ph(u)?(console.log("[TabManager] Content script error:",u.message),i(new Error(u.message))):(console.log("[TabManager] Received response from content script"),s(u||{data:null}))})})}}function U(n,e,t,r,a){if(typeof e=="function"?n!==e||!0:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(n,t),t}function E(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}let Wc=function(){const{crypto:n}=globalThis;if(n!=null&&n.randomUUID)return Wc=n.randomUUID.bind(n),n.randomUUID();const e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function Vs(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const Xs=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){const e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};class M extends Error{}class ye extends M{constructor(e,t,r,a){super(`${ye.makeMessage(e,t,r)}`),this.status=e,this.headers=a,this.requestID=a==null?void 0:a.get("x-request-id"),this.error=t;const s=t;this.code=s==null?void 0:s.code,this.param=s==null?void 0:s.param,this.type=s==null?void 0:s.type}static makeMessage(e,t,r){const a=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&a?`${e} ${a}`:e?`${e} status code (no body)`:a||"(no status code or body)"}static generate(e,t,r,a){if(!e||!a)return new Jn({message:r,cause:Xs(t)});const s=t==null?void 0:t.error;return e===400?new Jc(e,s,r,a):e===401?new Zc(e,s,r,a):e===403?new Kc(e,s,r,a):e===404?new Vc(e,s,r,a):e===409?new Xc(e,s,r,a):e===422?new Qc(e,s,r,a):e===429?new Yc(e,s,r,a):e>=500?new el(e,s,r,a):new ye(e,s,r,a)}}class Ne extends ye{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Jn extends ye{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Zn extends Jn{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Jc extends ye{}class Zc extends ye{}class Kc extends ye{}class Vc extends ye{}class Xc extends ye{}class Qc extends ye{}class Yc extends ye{}class el extends ye{}class tl extends M{constructor(){super("Could not parse response content as the length limit was reached")}}class rl extends M{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class cr extends Error{constructor(e){super(e)}}const Mh=/^[a-z][a-z0-9+.-]*:/i,Uh=n=>Mh.test(n);let Pe=n=>(Pe=Array.isArray,Pe(n)),yo=Pe;function Fh(n){return typeof n!="object"?{}:n??{}}function Dh(n){if(!n)return!0;for(const e in n)return!1;return!0}function Bh(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Ea(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}const qh=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new M(`${n} must be an integer`);if(e<0)throw new M(`${n} must be a positive integer`);return e},zh=n=>{try{return JSON.parse(n)}catch{return}},Mr=n=>new Promise(e=>setTimeout(e,n)),Bt="5.12.2",Hh=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Gh(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const Wh=()=>{var t;const n=Gh();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bt,"X-Stainless-OS":bo(Deno.build.os),"X-Stainless-Arch":_o(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((t=Deno.version)==null?void 0:t.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bt,"X-Stainless-OS":bo(globalThis.process.platform??"unknown"),"X-Stainless-Arch":_o(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=Jh();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Jh(){if(typeof navigator>"u"||!navigator)return null;const n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of n){const r=t.exec(navigator.userAgent);if(r){const a=r[1]||0,s=r[2]||0,i=r[3]||0;return{browser:e,version:`${a}.${s}.${i}`}}}return null}const _o=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",bo=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let wo;const Zh=()=>wo??(wo=Wh());function Kh(){if(typeof fetch<"u")return fetch;throw new 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 nl(...n){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...n)}function al(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return nl({start(){},async pull(t){const{done:r,value:a}=await e.next();r?t.close():t.enqueue(a)},async cancel(){var t;await((t=e.return)==null?void 0:t.call(e))}})}function sl(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();return t!=null&&t.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Vh(n){var r,a;if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await((a=(r=n[Symbol.asyncIterator]()).return)==null?void 0:a.call(r));return}const e=n.getReader(),t=e.cancel();e.releaseLock(),await t}const Xh=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),il="RFC3986",ol=n=>String(n),vo={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:ol},Qh="RFC1738";let Qs=(n,e)=>(Qs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Qs(n,e));const Ve=(()=>{const n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})(),Sa=1024,Yh=(n,e,t,r,a)=>{if(n.length===0)return n;let s=n;if(typeof n=="symbol"?s=Symbol.prototype.toString.call(n):typeof n!="string"&&(s=String(n)),t==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let i="";for(let o=0;o<s.length;o+=Sa){const u=s.length>=Sa?s.slice(o,o+Sa):s,c=[];for(let l=0;l<u.length;++l){let d=u.charCodeAt(l);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||a===Qh&&(d===40||d===41)){c[c.length]=u.charAt(l);continue}if(d<128){c[c.length]=Ve[d];continue}if(d<2048){c[c.length]=Ve[192|d>>6]+Ve[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=Ve[224|d>>12]+Ve[128|d>>6&63]+Ve[128|d&63];continue}l+=1,d=65536+((d&1023)<<10|u.charCodeAt(l)&1023),c[c.length]=Ve[240|d>>18]+Ve[128|d>>12&63]+Ve[128|d>>6&63]+Ve[128|d&63]}i+=c.join("")}return i};function ef(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function Eo(n,e){if(Pe(n)){const t=[];for(let r=0;r<n.length;r+=1)t.push(e(n[r]));return t}return e(n)}const ul={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},cl=function(n,e){Array.prototype.push.apply(n,Pe(e)?e:[e])};let So;const se={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Yh,encodeValuesOnly:!1,format:il,formatter:ol,indices:!1,serializeDate(n){return(So??(So=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function tf(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}const Oa={};function ll(n,e,t,r,a,s,i,o,u,c,l,d,h,f,m,p,g,y){let b=n,_=y,w=0,v=!1;for(;(_=_.get(Oa))!==void 0&&!v;){const G=_.get(n);if(w+=1,typeof G<"u"){if(G===w)throw new RangeError("Cyclic object value");v=!0}typeof _.get(Oa)>"u"&&(w=0)}if(typeof c=="function"?b=c(e,b):b instanceof Date?b=h==null?void 0:h(b):t==="comma"&&Pe(b)&&(b=Eo(b,function(G){return G instanceof Date?h==null?void 0:h(G):G})),b===null){if(s)return u&&!p?u(e,se.encoder,g,"key",f):e;b=""}if(tf(b)||ef(b)){if(u){const G=p?e:u(e,se.encoder,g,"key",f);return[(m==null?void 0:m(G))+"="+(m==null?void 0:m(u(b,se.encoder,g,"value",f)))]}return[(m==null?void 0:m(e))+"="+(m==null?void 0:m(String(b)))]}const S=[];if(typeof b>"u")return S;let O;if(t==="comma"&&Pe(b))p&&u&&(b=Eo(b,u)),O=[{value:b.length>0?b.join(",")||null:void 0}];else if(Pe(c))O=c;else{const G=Object.keys(b);O=l?G.sort(l):G}const T=o?String(e).replace(/\./g,"%2E"):String(e),N=r&&Pe(b)&&b.length===1?T+"[]":T;if(a&&Pe(b)&&b.length===0)return N+"[]";for(let G=0;G<O.length;++G){const z=O[G],oe=typeof z=="object"&&typeof z.value<"u"?z.value:b[z];if(i&&oe===null)continue;const Ke=d&&o?z.replace(/\./g,"%2E"):z,I=Pe(b)?typeof t=="function"?t(N,Ke):N:N+(d?"."+Ke:"["+Ke+"]");y.set(n,w);const A=new WeakMap;A.set(Oa,y),cl(S,ll(oe,I,t,r,a,s,i,o,t==="comma"&&p&&Pe(b)?null:u,c,l,d,h,f,m,p,g,A))}return S}function rf(n=se){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=n.charset||se.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=il;if(typeof n.format<"u"){if(!Qs(vo,n.format))throw new TypeError("Unknown format option provided.");t=n.format}const r=vo[t];let a=se.filter;(typeof n.filter=="function"||Pe(n.filter))&&(a=n.filter);let s;if(n.arrayFormat&&n.arrayFormat in ul?s=n.arrayFormat:"indices"in n?s=n.indices?"indices":"repeat":s=se.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:se.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:se.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:se.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:se.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?se.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:se.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:se.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:se.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:se.encodeValuesOnly,filter:a,format:t,formatter:r,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:se.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:se.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:se.strictNullHandling}}function nf(n,e={}){let t=n;const r=rf(e);let a,s;typeof r.filter=="function"?(s=r.filter,t=s("",t)):Pe(r.filter)&&(s=r.filter,a=s);const i=[];if(typeof t!="object"||t===null)return"";const o=ul[r.arrayFormat],u=o==="comma"&&r.commaRoundTrip;a||(a=Object.keys(t)),r.sort&&a.sort(r.sort);const c=new WeakMap;for(let h=0;h<a.length;++h){const f=a[h];r.skipNulls&&t[f]===null||cl(i,ll(t[f],f,o,u,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,c))}const l=i.join(r.delimiter);let d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),l.length>0?d+l:""}function af(n){let e=0;for(const a of n)e+=a.length;const t=new Uint8Array(e);let r=0;for(const a of n)t.set(a,r),r+=a.length;return t}let Oo;function Ai(n){let e;return(Oo??(e=new globalThis.TextEncoder,Oo=e.encode.bind(e)))(n)}let To;function Ao(n){let e;return(To??(e=new globalThis.TextDecoder,To=e.decode.bind(e)))(n)}var Re,$e;class Kn{constructor(){Re.set(this,void 0),$e.set(this,void 0),U(this,Re,new Uint8Array),U(this,$e,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Ai(e):e;U(this,Re,af([E(this,Re,"f"),t]));const r=[];let a;for(;(a=sf(E(this,Re,"f"),E(this,$e,"f")))!=null;){if(a.carriage&&E(this,$e,"f")==null){U(this,$e,a.index);continue}if(E(this,$e,"f")!=null&&(a.index!==E(this,$e,"f")+1||a.carriage)){r.push(Ao(E(this,Re,"f").subarray(0,E(this,$e,"f")-1))),U(this,Re,E(this,Re,"f").subarray(E(this,$e,"f"))),U(this,$e,null);continue}const s=E(this,$e,"f")!==null?a.preceding-1:a.preceding,i=Ao(E(this,Re,"f").subarray(0,s));r.push(i),U(this,Re,E(this,Re,"f").subarray(a.index)),U(this,$e,null)}return r}flush(){return E(this,Re,"f").length?this.decode(`
2
+ `):[]}}Re=new WeakMap,$e=new WeakMap;Kn.NEWLINE_CHARS=new Set([`
3
+ `,"\r"]);Kn.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function sf(n,e){for(let a=e??0;a<n.length;a++){if(n[a]===10)return{preceding:a,index:a+1,carriage:!1};if(n[a]===13)return{preceding:a,index:a+1,carriage:!0}}return null}function of(n){for(let r=0;r<n.length-1;r++){if(n[r]===10&&n[r+1]===10||n[r]===13&&n[r+1]===13)return r+2;if(n[r]===13&&n[r+1]===10&&r+3<n.length&&n[r+2]===13&&n[r+3]===10)return r+4}return-1}const Tn={off:0,error:200,warn:300,info:400,debug:500},Po=(n,e,t)=>{if(n){if(Bh(Tn,n))return n;pe(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Tn))}`)}};function lr(){}function Wr(n,e,t){return!e||Tn[n]>Tn[t]?lr:e[n].bind(e)}const uf={error:lr,warn:lr,info:lr,debug:lr};let xo=new WeakMap;function pe(n){const e=n.logger,t=n.logLevel??"off";if(!e)return uf;const r=xo.get(e);if(r&&r[0]===t)return r[1];const a={error:Wr("error",e,t),warn:Wr("warn",e,t),info:Wr("info",e,t),debug:Wr("debug",e,t)};return xo.set(e,[t,a]),a}const St=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var ar;class et{constructor(e,t,r){this.iterator=e,ar.set(this,void 0),this.controller=t,U(this,ar,r)}static fromSSEResponse(e,t,r){let a=!1;const s=r?pe(r):console;async function*i(){if(a)throw new M("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let o=!1;try{for await(const u of cf(e,t))if(!o){if(u.data.startsWith("[DONE]")){o=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let c;try{c=JSON.parse(u.data)}catch(l){throw s.error("Could not parse message into JSON:",u.data),s.error("From chunk:",u.raw),l}if(c&&c.error)throw new ye(void 0,c.error,void 0,e.headers);yield c}else{let c;try{c=JSON.parse(u.data)}catch(l){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),l}if(u.event=="error")throw new ye(void 0,c.error,c.message,void 0);yield{event:u.event,data:c}}}o=!0}catch(u){if(Vs(u))return;throw u}finally{o||t.abort()}}return new et(i,t,r)}static fromReadableStream(e,t,r){let a=!1;async function*s(){const o=new Kn,u=sl(e);for await(const c of u)for(const l of o.decode(c))yield l;for(const c of o.flush())yield c}async function*i(){if(a)throw new M("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let o=!1;try{for await(const u of s())o||u&&(yield JSON.parse(u));o=!0}catch(u){if(Vs(u))return;throw u}finally{o||t.abort()}}return new et(i,t,r)}[(ar=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],r=this.iterator(),a=s=>({next:()=>{if(s.length===0){const i=r.next();e.push(i),t.push(i)}return s.shift()}});return[new et(()=>a(e),this.controller,E(this,ar,"f")),new et(()=>a(t),this.controller,E(this,ar,"f"))]}toReadableStream(){const e=this;let t;return nl({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{const{value:a,done:s}=await t.next();if(s)return r.close();const i=Ai(JSON.stringify(a)+`
4
+ `);r.enqueue(i)}catch(a){r.error(a)}},async cancel(){var r;await((r=t.return)==null?void 0:r.call(t))}})}}async function*cf(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new M("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new M("Attempted to iterate over a response with no body");const t=new df,r=new Kn,a=sl(n.body);for await(const s of lf(a))for(const i of r.decode(s)){const o=t.decode(i);o&&(yield o)}for(const s of r.flush()){const i=t.decode(s);i&&(yield i)}}async function*lf(n){let e=new Uint8Array;for await(const t of n){if(t==null)continue;const r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Ai(t):t;let a=new Uint8Array(e.length+r.length);a.set(e),a.set(r,e.length),e=a;let s;for(;(s=of(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}class df{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const s={event:this.event,data:this.data.join(`
5
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,a]=hf(e,":");return a.startsWith(" ")&&(a=a.substring(1)),t==="event"?this.event=a:t==="data"&&this.data.push(a),null}}function hf(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function dl(n,e){const{response:t,requestLogID:r,retryOfRequestLogID:a,startTime:s}=e,i=await(async()=>{var d;if(e.options.stream)return pe(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):et.fromSSEResponse(t,e.controller,n);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const o=t.headers.get("content-type"),u=(d=o==null?void 0:o.split(";")[0])==null?void 0:d.trim();if((u==null?void 0:u.includes("application/json"))||(u==null?void 0:u.endsWith("+json"))){const h=await t.json();return hl(h,t)}return await t.text()})();return pe(n).debug(`[${r}] response parsed`,St({retryOfRequestLogID:a,url:t.url,status:t.status,body:i,durationMs:Date.now()-s})),i}function hl(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var dr;class Vn extends Promise{constructor(e,t,r=dl){super(a=>{a(null)}),this.responsePromise=t,this.parseResponse=r,dr.set(this,void 0),U(this,dr,e)}_thenUnwrap(e){return new Vn(E(this,dr,"f"),this.responsePromise,async(t,r)=>hl(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[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.parsedPromise=this.responsePromise.then(e=>this.parseResponse(E(this,dr,"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)}}dr=new WeakMap;var Jr;class fl{constructor(e,t,r,a){Jr.set(this,void 0),U(this,Jr,e),this.options=a,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new M("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await E(this,Jr,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Jr=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class ff extends Vn{constructor(e,t,r){super(e,t,async(a,s)=>new r(a,s.response,await dl(a,s),s.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class Xn extends fl{constructor(e,t,r,a){super(e,t,r,a),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class re extends fl{constructor(e,t,r,a){super(e,t,r,a),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var r;const e=this.getPaginatedItems(),t=(r=e[e.length-1])==null?void 0:r.id;return t?{...this.options,query:{...Fh(this.options.query),after:t}}:null}}const ml=()=>{var n;if(typeof File>"u"){const{process:e}=globalThis,t=typeof((n=e==null?void 0:e.versions)==null?void 0:n.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new 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 vr(n,e,t){return ml(),new File(n,e??"unknown_file",t)}function fn(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0}const pl=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",Rt=async(n,e)=>({...n,body:await pf(n.body,e)}),Io=new WeakMap;function mf(n){const e=typeof n=="function"?n:n.fetch,t=Io.get(e);if(t)return t;const r=(async()=>{try{const a="Response"in e?e.Response:(await e("data:,")).constructor,s=new FormData;return s.toString()!==await new a(s).text()}catch{return!0}})();return Io.set(e,r),r}const pf=async(n,e)=>{if(!await mf(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(n||{}).map(([r,a])=>Ys(t,r,a))),t},gf=n=>n instanceof Blob&&"name"in n,Ys=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(t instanceof Response)n.append(e,vr([await t.blob()],fn(t)));else if(pl(t))n.append(e,vr([await new Response(al(t)).blob()],fn(t)));else if(gf(t))n.append(e,t,fn(t));else if(Array.isArray(t))await Promise.all(t.map(r=>Ys(n,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,a])=>Ys(n,`${e}[${r}]`,a)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},gl=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",yf=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&gl(n),_f=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function bf(n,e,t){if(ml(),n=await n,yf(n))return n instanceof File?n:vr([await n.arrayBuffer()],n.name);if(_f(n)){const a=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),vr(await ei(a),e,t)}const r=await ei(n);if(e||(e=fn(n)),!(t!=null&&t.type)){const a=r.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof a=="string"&&(t={...t,type:a})}return vr(r,e,t)}async function ei(n){var t;let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(gl(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(pl(n))for await(const r of n)e.push(...await ei(r));else{const r=(t=n==null?void 0:n.constructor)==null?void 0:t.name;throw new Error(`Unexpected data type: ${typeof n}${r?`; constructor: ${r}`:""}${wf(n)}`)}return e}function wf(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}class F{constructor(e){this._client=e}}function yl(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Ro=Object.freeze(Object.create(null)),vf=(n=yl)=>function(t,...r){if(t.length===1)return t[0];let a=!1;const s=[],i=t.reduce((l,d,h)=>{var p;/[?#]/.test(d)&&(a=!0);const f=r[h];let m=(a?encodeURIComponent:n)(""+f);return h!==r.length&&(f==null||typeof f=="object"&&f.toString===((p=Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??Ro)??Ro))==null?void 0:p.toString))&&(m=f+"",s.push({start:l.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),l+d+(h===r.length?"":m)},""),o=i.split(/[?#]/,1)[0],u=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let c;for(;(c=u.exec(o))!==null;)s.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(s.sort((l,d)=>l.start-d.start),s.length>0){let l=0;const d=s.reduce((h,f)=>{const m=" ".repeat(f.start-l),p="^".repeat(f.length);return l=f.start+f.length,h+m+p},"");throw new M(`Path parameters result in path with invalid segments:
6
+ ${s.map(h=>h.error).join(`
7
+ `)}
8
+ ${i}
9
+ ${d}`)}return i},x=vf(yl);let _l=class extends F{list(e,t={},r){return this._client.getAPIList(x`/chat/completions/${e}/messages`,re,{query:t,...r})}};function An(n){return n!==void 0&&"function"in n&&n.function!==void 0}function Ef(n,e){const t={...n};return Object.defineProperties(t,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),t}function Pi(n){return(n==null?void 0:n.$brand)==="auto-parseable-response-format"}function Ur(n){return(n==null?void 0:n.$brand)==="auto-parseable-tool"}function Sf(n,e){return!e||!bl(e)?{...n,choices:n.choices.map(t=>(wl(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:xi(n,e)}function xi(n,e){const t=n.choices.map(r=>{var a;if(r.finish_reason==="length")throw new tl;if(r.finish_reason==="content_filter")throw new rl;return wl(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:((a=r.message.tool_calls)==null?void 0:a.map(s=>Tf(e,s)))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Of(e,r.message.content):null}}});return{...n,choices:t}}function Of(n,e){var t,r;return((t=n.response_format)==null?void 0:t.type)!=="json_schema"?null:((r=n.response_format)==null?void 0:r.type)==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function Tf(n,e){var r;const t=(r=n.tools)==null?void 0:r.find(a=>{var s;return An(a)&&((s=a.function)==null?void 0:s.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:Ur(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function Af(n,e){var r;if(!n||!("tools"in n)||!n.tools)return!1;const t=(r=n.tools)==null?void 0:r.find(a=>{var s;return An(a)&&((s=a.function)==null?void 0:s.name)===e.function.name});return An(t)&&(Ur(t)||(t==null?void 0:t.function.strict)||!1)}function bl(n){var e;return Pi(n.response_format)?!0:((e=n.tools)==null?void 0:e.some(t=>Ur(t)||t.type==="function"&&t.function.strict===!0))??!1}function wl(n){for(const e of n||[])if(e.type!=="function")throw new M(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Pf(n){for(const e of n??[]){if(e.type!=="function")throw new M(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new M(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const Pn=n=>(n==null?void 0:n.role)==="assistant",vl=n=>(n==null?void 0:n.role)==="tool";var ti,mn,pn,hr,fr,gn,mr,st,pr,xn,In,qt,El;class Ii{constructor(){ti.add(this),this.controller=new AbortController,mn.set(this,void 0),pn.set(this,()=>{}),hr.set(this,()=>{}),fr.set(this,void 0),gn.set(this,()=>{}),mr.set(this,()=>{}),st.set(this,{}),pr.set(this,!1),xn.set(this,!1),In.set(this,!1),qt.set(this,!1),U(this,mn,new Promise((e,t)=>{U(this,pn,e,"f"),U(this,hr,t,"f")})),U(this,fr,new Promise((e,t)=>{U(this,gn,e,"f"),U(this,mr,t,"f")})),E(this,mn,"f").catch(()=>{}),E(this,fr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},E(this,ti,"m",El).bind(this))},0)}_connected(){this.ended||(E(this,pn,"f").call(this),this._emit("connect"))}get ended(){return E(this,pr,"f")}get errored(){return E(this,xn,"f")}get aborted(){return E(this,In,"f")}abort(){this.controller.abort()}on(e,t){return(E(this,st,"f")[e]||(E(this,st,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=E(this,st,"f")[e];if(!r)return this;const a=r.findIndex(s=>s.listener===t);return a>=0&&r.splice(a,1),this}once(e,t){return(E(this,st,"f")[e]||(E(this,st,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{U(this,qt,!0),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){U(this,qt,!0),await E(this,fr,"f")}_emit(e,...t){if(E(this,pr,"f"))return;e==="end"&&(U(this,pr,!0),E(this,gn,"f").call(this));const r=E(this,st,"f")[e];if(r&&(E(this,st,"f")[e]=r.filter(a=>!a.once),r.forEach(({listener:a})=>a(...t))),e==="abort"){const a=t[0];!E(this,qt,"f")&&!(r!=null&&r.length)&&Promise.reject(a),E(this,hr,"f").call(this,a),E(this,mr,"f").call(this,a),this._emit("end");return}if(e==="error"){const a=t[0];!E(this,qt,"f")&&!(r!=null&&r.length)&&Promise.reject(a),E(this,hr,"f").call(this,a),E(this,mr,"f").call(this,a),this._emit("end")}}_emitFinal(){}}mn=new WeakMap,pn=new WeakMap,hr=new WeakMap,fr=new WeakMap,gn=new WeakMap,mr=new WeakMap,st=new WeakMap,pr=new WeakMap,xn=new WeakMap,In=new WeakMap,qt=new WeakMap,ti=new WeakSet,El=function(e){if(U(this,xn,!0),e instanceof Error&&e.name==="AbortError"&&(e=new Ne),e instanceof Ne)return U(this,In,!0),this._emit("abort",e);if(e instanceof M)return this._emit("error",e);if(e instanceof Error){const t=new M(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new M(String(e)))};function xf(n){return typeof n.parse=="function"}var Ee,ri,Rn,ni,ai,si,Sl,Ol;const If=10;class Tl extends Ii{constructor(){super(...arguments),Ee.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var r;this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=(r=e.choices[0])==null?void 0:r.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),vl(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Pn(e)&&e.tool_calls)for(const r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new M("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),E(this,Ee,"m",ri).call(this)}async finalMessage(){return await this.done(),E(this,Ee,"m",Rn).call(this)}async finalFunctionToolCall(){return await this.done(),E(this,Ee,"m",ni).call(this)}async finalFunctionToolCallResult(){return await this.done(),E(this,Ee,"m",ai).call(this)}async totalUsage(){return await this.done(),E(this,Ee,"m",si).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=E(this,Ee,"m",Rn).call(this);t&&this._emit("finalMessage",t);const r=E(this,Ee,"m",ri).call(this);r&&this._emit("finalContent",r);const a=E(this,Ee,"m",ni).call(this);a&&this._emit("finalFunctionToolCall",a);const s=E(this,Ee,"m",ai).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",E(this,Ee,"m",si).call(this))}async _createChatCompletion(e,t,r){const a=r==null?void 0:r.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort())),E(this,Ee,"m",Sl).call(this,t);const s=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(xi(s,t))}async _runChatCompletion(e,t,r){for(const a of t.messages)this._addMessage(a,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){var f,m,p;const a="tool",{tool_choice:s="auto",stream:i,...o}=t,u=typeof s!="string"&&s.type==="function"&&((f=s==null?void 0:s.function)==null?void 0:f.name),{maxChatCompletions:c=If}=r||{},l=t.tools.map(g=>{if(Ur(g)){if(!g.$callback)throw new M("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:g.$callback,name:g.function.name,description:g.function.description||"",parameters:g.function.parameters,parse:g.$parseRaw,strict:!0}}}return g}),d={};for(const g of l)g.type==="function"&&(d[g.function.name||g.function.function.name]=g.function);const h="tools"in t?l.map(g=>g.type==="function"?{type:"function",function:{name:g.function.name||g.function.function.name,parameters:g.function.parameters,description:g.function.description,strict:g.function.strict}}:g):void 0;for(const g of t.messages)this._addMessage(g,!1);for(let g=0;g<c;++g){const b=(m=(await this._createChatCompletion(e,{...o,tool_choice:s,tools:h,messages:[...this.messages]},r)).choices[0])==null?void 0:m.message;if(!b)throw new M("missing message in ChatCompletion response");if(!((p=b.tool_calls)!=null&&p.length))return;for(const _ of b.tool_calls){if(_.type!=="function")continue;const w=_.id,{name:v,arguments:S}=_.function,O=d[v];if(O){if(u&&u!==v){const z=`Invalid tool_call: ${JSON.stringify(v)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:a,tool_call_id:w,content:z});continue}}else{const z=`Invalid tool_call: ${JSON.stringify(v)}. Available options are: ${Object.keys(d).map(oe=>JSON.stringify(oe)).join(", ")}. Please try again`;this._addMessage({role:a,tool_call_id:w,content:z});continue}let T;try{T=xf(O)?await O.parse(S):S}catch(z){const oe=z instanceof Error?z.message:String(z);this._addMessage({role:a,tool_call_id:w,content:oe});continue}const N=await O.function(T,this),G=E(this,Ee,"m",Ol).call(this,N);if(this._addMessage({role:a,tool_call_id:w,content:G}),u)return}}}}Ee=new WeakSet,ri=function(){return E(this,Ee,"m",Rn).call(this).content??null},Rn=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(Pn(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new M("stream ended without producing a ChatCompletionMessage with role=assistant")},ni=function(){var e,t;for(let r=this.messages.length-1;r>=0;r--){const a=this.messages[r];if(Pn(a)&&((e=a==null?void 0:a.tool_calls)!=null&&e.length))return(t=a.tool_calls.filter(s=>s.type==="function").at(-1))==null?void 0:t.function}},ai=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(vl(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>{var a;return r.role==="assistant"&&((a=r.tool_calls)==null?void 0:a.some(s=>s.type==="function"&&s.id===t.tool_call_id))}))return t.content}},si=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{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},Sl=function(e){if(e.n!=null&&e.n>1)throw new M("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Ol=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Ri extends Tl{static runTools(e,t,r){const a=new Ri,s={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return a._run(()=>a._runTools(e,t,s)),a}_addMessage(e,t=!0){super._addMessage(e,t),Pn(e)&&e.content&&this._emit("content",e.content)}}const Al=1,Pl=2,xl=4,Il=8,Rl=16,$l=32,kl=64,Cl=128,Nl=256,jl=Cl|Nl,Ll=Rl|$l|jl|kl,Ml=Al|Pl|Ll,Ul=xl|Il,Rf=Ml|Ul,le={STR:Al,NUM:Pl,ARR:xl,OBJ:Il,NULL:Rl,BOOL:$l,NAN:kl,INFINITY:Cl,MINUS_INFINITY:Nl,INF:jl,SPECIAL:Ll,ATOM:Ml,COLLECTION:Ul,ALL:Rf};class $f extends Error{}class kf extends Error{}function Cf(n,e=le.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return Nf(n.trim(),e)}const Nf=(n,e)=>{const t=n.length;let r=0;const a=h=>{throw new $f(`${h} at position ${r}`)},s=h=>{throw new kf(`${h} at position ${r}`)},i=()=>(d(),r>=t&&a("Unexpected end of input"),n[r]==='"'?o():n[r]==="{"?u():n[r]==="["?c():n.substring(r,r+4)==="null"||le.NULL&e&&t-r<4&&"null".startsWith(n.substring(r))?(r+=4,null):n.substring(r,r+4)==="true"||le.BOOL&e&&t-r<4&&"true".startsWith(n.substring(r))?(r+=4,!0):n.substring(r,r+5)==="false"||le.BOOL&e&&t-r<5&&"false".startsWith(n.substring(r))?(r+=5,!1):n.substring(r,r+8)==="Infinity"||le.INFINITY&e&&t-r<8&&"Infinity".startsWith(n.substring(r))?(r+=8,1/0):n.substring(r,r+9)==="-Infinity"||le.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(n.substring(r))?(r+=9,-1/0):n.substring(r,r+3)==="NaN"||le.NAN&e&&t-r<3&&"NaN".startsWith(n.substring(r))?(r+=3,NaN):l()),o=()=>{const h=r;let f=!1;for(r++;r<t&&(n[r]!=='"'||f&&n[r-1]==="\\");)f=n[r]==="\\"?!f:!1,r++;if(n.charAt(r)=='"')try{return JSON.parse(n.substring(h,++r-Number(f)))}catch(m){s(String(m))}else if(le.STR&e)try{return JSON.parse(n.substring(h,r-Number(f))+'"')}catch{return JSON.parse(n.substring(h,n.lastIndexOf("\\"))+'"')}a("Unterminated string literal")},u=()=>{r++,d();const h={};try{for(;n[r]!=="}";){if(d(),r>=t&&le.OBJ&e)return h;const f=o();d(),r++;try{const m=i();Object.defineProperty(h,f,{value:m,writable:!0,enumerable:!0,configurable:!0})}catch(m){if(le.OBJ&e)return h;throw m}d(),n[r]===","&&r++}}catch{if(le.OBJ&e)return h;a("Expected '}' at end of object")}return r++,h},c=()=>{r++;const h=[];try{for(;n[r]!=="]";)h.push(i()),d(),n[r]===","&&r++}catch{if(le.ARR&e)return h;a("Expected ']' at end of array")}return r++,h},l=()=>{if(r===0){n==="-"&&le.NUM&e&&a("Not sure what '-' is");try{return JSON.parse(n)}catch(f){if(le.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}s(String(f))}}const h=r;for(n[r]==="-"&&r++;n[r]&&!",]}".includes(n[r]);)r++;r==t&&!(le.NUM&e)&&a("Unterminated number literal");try{return JSON.parse(n.substring(h,r))}catch{n.substring(h,r)==="-"&&le.NUM&e&&a("Not sure what '-' is");try{return JSON.parse(n.substring(h,n.lastIndexOf("e")))}catch(m){s(String(m))}}},d=()=>{for(;r<t&&`
10
+ \r `.includes(n[r]);)r++};return i()},$o=n=>Cf(n,le.ALL^le.NUM);var ne,at,Lt,lt,Ta,Zr,Aa,Pa,xa,Kr,Ia,ko;class Rr extends Tl{constructor(e){super(),ne.add(this),at.set(this,void 0),Lt.set(this,void 0),lt.set(this,void 0),U(this,at,e),U(this,Lt,[])}get currentChatCompletionSnapshot(){return E(this,lt,"f")}static fromReadableStream(e){const t=new Rr(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){const a=new Rr(t);return a._run(()=>a._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createChatCompletion(e,t,r){var i;super._createChatCompletion;const a=r==null?void 0:r.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort())),E(this,ne,"m",Ta).call(this);const s=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const o of s)E(this,ne,"m",Aa).call(this,o);if((i=s.controller.signal)!=null&&i.aborted)throw new Ne;return this._addChatCompletion(E(this,ne,"m",Kr).call(this))}async _fromReadableStream(e,t){var i;const r=t==null?void 0:t.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),E(this,ne,"m",Ta).call(this),this._connected();const a=et.fromReadableStream(e,this.controller);let s;for await(const o of a)s&&s!==o.id&&this._addChatCompletion(E(this,ne,"m",Kr).call(this)),E(this,ne,"m",Aa).call(this,o),s=o.id;if((i=a.controller.signal)!=null&&i.aborted)throw new Ne;return this._addChatCompletion(E(this,ne,"m",Kr).call(this))}[(at=new WeakMap,Lt=new WeakMap,lt=new WeakMap,ne=new WeakSet,Ta=function(){this.ended||U(this,lt,void 0)},Zr=function(t){let r=E(this,Lt,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},E(this,Lt,"f")[t.index]=r,r)},Aa=function(t){var a,s,i,o,u,c,l,d,h,f,m,p,g,y,b;if(this.ended)return;const r=E(this,ne,"m",ko).call(this,t);this._emit("chunk",t,r);for(const _ of t.choices){const w=r.choices[_.index];_.delta.content!=null&&((a=w.message)==null?void 0:a.role)==="assistant"&&((s=w.message)!=null&&s.content)&&(this._emit("content",_.delta.content,w.message.content),this._emit("content.delta",{delta:_.delta.content,snapshot:w.message.content,parsed:w.message.parsed})),_.delta.refusal!=null&&((i=w.message)==null?void 0:i.role)==="assistant"&&((o=w.message)!=null&&o.refusal)&&this._emit("refusal.delta",{delta:_.delta.refusal,snapshot:w.message.refusal}),((u=_.logprobs)==null?void 0:u.content)!=null&&((c=w.message)==null?void 0:c.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(l=_.logprobs)==null?void 0:l.content,snapshot:((d=w.logprobs)==null?void 0:d.content)??[]}),((h=_.logprobs)==null?void 0:h.refusal)!=null&&((f=w.message)==null?void 0:f.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(m=_.logprobs)==null?void 0:m.refusal,snapshot:((p=w.logprobs)==null?void 0:p.refusal)??[]});const v=E(this,ne,"m",Zr).call(this,w);w.finish_reason&&(E(this,ne,"m",xa).call(this,w),v.current_tool_call_index!=null&&E(this,ne,"m",Pa).call(this,w,v.current_tool_call_index));for(const S of _.delta.tool_calls??[])v.current_tool_call_index!==S.index&&(E(this,ne,"m",xa).call(this,w),v.current_tool_call_index!=null&&E(this,ne,"m",Pa).call(this,w,v.current_tool_call_index)),v.current_tool_call_index=S.index;for(const S of _.delta.tool_calls??[]){const O=(g=w.message.tool_calls)==null?void 0:g[S.index];O!=null&&O.type&&((O==null?void 0:O.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(y=O.function)==null?void 0:y.name,index:S.index,arguments:O.function.arguments,parsed_arguments:O.function.parsed_arguments,arguments_delta:((b=S.function)==null?void 0:b.arguments)??""}):(O==null||O.type,void 0))}}},Pa=function(t,r){var i,o,u;if(E(this,ne,"m",Zr).call(this,t).done_tool_calls.has(r))return;const s=(i=t.message.tool_calls)==null?void 0:i[r];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if(s.type==="function"){const c=(u=(o=E(this,at,"f"))==null?void 0:o.tools)==null?void 0:u.find(l=>An(l)&&l.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:r,arguments:s.function.arguments,parsed_arguments:Ur(c)?c.$parseRaw(s.function.arguments):c!=null&&c.function.strict?JSON.parse(s.function.arguments):null})}else s.type},xa=function(t){var a,s;const r=E(this,ne,"m",Zr).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;const i=E(this,ne,"m",Ia).call(this);this._emit("content.done",{content:t.message.content,parsed:i?i.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),(a=t.logprobs)!=null&&a.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),(s=t.logprobs)!=null&&s.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Kr=function(){if(this.ended)throw new M("stream has ended, this shouldn't happen");const t=E(this,lt,"f");if(!t)throw new M("request ended without sending any chunks");return U(this,lt,void 0),U(this,Lt,[]),jf(t,E(this,at,"f"))},Ia=function(){var r;const t=(r=E(this,at,"f"))==null?void 0:r.response_format;return Pi(t)?t:null},ko=function(t){var r,a,s,i;let o=E(this,lt,"f");const{choices:u,...c}=t;o?Object.assign(o,c):o=U(this,lt,{...c,choices:[]});for(const{delta:l,finish_reason:d,index:h,logprobs:f=null,...m}of t.choices){let p=o.choices[h];if(p||(p=o.choices[h]={finish_reason:d,index:h,message:{},logprobs:f,...m}),f)if(!p.logprobs)p.logprobs=Object.assign({},f);else{const{content:S,refusal:O,...T}=f;Object.assign(p.logprobs,T),S&&((r=p.logprobs).content??(r.content=[]),p.logprobs.content.push(...S)),O&&((a=p.logprobs).refusal??(a.refusal=[]),p.logprobs.refusal.push(...O))}if(d&&(p.finish_reason=d,E(this,at,"f")&&bl(E(this,at,"f")))){if(d==="length")throw new tl;if(d==="content_filter")throw new rl}if(Object.assign(p,m),!l)continue;const{content:g,refusal:y,function_call:b,role:_,tool_calls:w,...v}=l;if(Object.assign(p.message,v),y&&(p.message.refusal=(p.message.refusal||"")+y),_&&(p.message.role=_),b&&(p.message.function_call?(b.name&&(p.message.function_call.name=b.name),b.arguments&&((s=p.message.function_call).arguments??(s.arguments=""),p.message.function_call.arguments+=b.arguments)):p.message.function_call=b),g&&(p.message.content=(p.message.content||"")+g,!p.message.refusal&&E(this,ne,"m",Ia).call(this)&&(p.message.parsed=$o(p.message.content))),w){p.message.tool_calls||(p.message.tool_calls=[]);for(const{index:S,id:O,type:T,function:N,...G}of w){const z=(i=p.message.tool_calls)[S]??(i[S]={});Object.assign(z,G),O&&(z.id=O),T&&(z.type=T),N&&(z.function??(z.function={name:N.name??"",arguments:""})),N!=null&&N.name&&(z.function.name=N.name),N!=null&&N.arguments&&(z.function.arguments+=N.arguments,Af(E(this,at,"f"),z)&&(z.function.parsed_arguments=$o(z.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("chunk",a=>{const s=t.shift();s?s.resolve(a):e.push(a)}),this.on("end",()=>{r=!0;for(const a of t)a.resolve(void 0);t.length=0}),this.on("abort",a=>{r=!0;for(const s of t)s.reject(a);t.length=0}),this.on("error",a=>{r=!0;for(const s of t)s.reject(a);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((s,i)=>t.push({resolve:s,reject:i})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function jf(n,e){const{id:t,choices:r,created:a,model:s,system_fingerprint:i,...o}=n,u={...o,id:t,choices:r.map(({message:c,finish_reason:l,index:d,logprobs:h,...f})=>{if(!l)throw new M(`missing finish_reason for choice ${d}`);const{content:m=null,function_call:p,tool_calls:g,...y}=c,b=c.role;if(!b)throw new M(`missing role for choice ${d}`);if(p){const{arguments:_,name:w}=p;if(_==null)throw new M(`missing function_call.arguments for choice ${d}`);if(!w)throw new M(`missing function_call.name for choice ${d}`);return{...f,message:{content:m,function_call:{arguments:_,name:w},role:b,refusal:c.refusal??null},finish_reason:l,index:d,logprobs:h}}return g?{...f,index:d,finish_reason:l,logprobs:h,message:{...y,role:b,content:m,refusal:c.refusal??null,tool_calls:g.map((_,w)=>{const{function:v,type:S,id:O,...T}=_,{arguments:N,name:G,...z}=v||{};if(O==null)throw new M(`missing choices[${d}].tool_calls[${w}].id
11
+ ${Vr(n)}`);if(S==null)throw new M(`missing choices[${d}].tool_calls[${w}].type
12
+ ${Vr(n)}`);if(G==null)throw new M(`missing choices[${d}].tool_calls[${w}].function.name
13
+ ${Vr(n)}`);if(N==null)throw new M(`missing choices[${d}].tool_calls[${w}].function.arguments
14
+ ${Vr(n)}`);return{...T,id:O,type:S,function:{...z,name:G,arguments:N}}})}}:{...f,message:{...y,content:m,role:b,refusal:c.refusal??null},finish_reason:l,index:d,logprobs:h}}),created:a,model:s,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Sf(u,e)}function Vr(n){return JSON.stringify(n)}class $n extends Rr{static fromReadableStream(e){const t=new $n(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){const a=new $n(t),s={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return a._run(()=>a._runTools(e,t,s)),a}}let $i=class extends F{constructor(){super(...arguments),this.messages=new _l(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(x`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(x`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",re,{query:e,...t})}delete(e,t){return this._client.delete(x`/chat/completions/${e}`,t)}parse(e,t){return Pf(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t==null?void 0:t.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>xi(r,e))}runTools(e,t){return e.stream?$n.runTools(this._client,e,t):Ri.runTools(this._client,e,t)}stream(e,t){return Rr.createChatCompletion(this._client,e,t)}};$i.Messages=_l;class ki extends F{constructor(){super(...arguments),this.completions=new $i(this._client)}}ki.Completions=$i;const Fl=Symbol("brand.privateNullableHeaders");function*Lf(n){if(!n)return;if(Fl in n){const{values:r,nulls:a}=n;yield*r.entries();for(const s of a)yield[s,null];return}let e=!1,t;n instanceof Headers?t=n.entries():yo(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let r of t){const a=r[0];if(typeof a!="string")throw new TypeError("expected header name to be a string");const s=yo(r[1])?r[1]:[r[1]];let i=!1;for(const o of s)o!==void 0&&(e&&!i&&(i=!0,yield[a,null]),yield[a,o])}}const C=n=>{const e=new Headers,t=new Set;for(const r of n){const a=new Set;for(const[s,i]of Lf(r)){const o=s.toLowerCase();a.has(o)||(e.delete(s),a.add(o)),i===null?(e.delete(s),t.add(o)):(e.append(s,i),t.delete(o))}}return{[Fl]:!0,values:e,nulls:t}};class Dl extends F{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:C([{Accept:"application/octet-stream"},t==null?void 0:t.headers]),__binaryResponse:!0})}}class Bl extends F{create(e,t){return this._client.post("/audio/transcriptions",Rt({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class ql extends F{create(e,t){return this._client.post("/audio/translations",Rt({body:e,...t,__metadata:{model:e.model}},this._client))}}class Fr extends F{constructor(){super(...arguments),this.transcriptions=new Bl(this._client),this.translations=new ql(this._client),this.speech=new Dl(this._client)}}Fr.Transcriptions=Bl;Fr.Translations=ql;Fr.Speech=Dl;class zl extends F{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(x`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",re,{query:e,...t})}cancel(e,t){return this._client.post(x`/batches/${e}/cancel`,t)}}class Hl extends F{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:C([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}retrieve(e,t){return this._client.get(x`/assistants/${e}`,{...t,headers:C([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}update(e,t,r){return this._client.post(x`/assistants/${e}`,{body:t,...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e={},t){return this._client.getAPIList("/assistants",re,{query:e,...t,headers:C([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}delete(e,t){return this._client.delete(x`/assistants/${e}`,{...t,headers:C([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}}class Gl extends F{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:C([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}}class Wl extends F{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:C([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}}class Qn extends F{constructor(){super(...arguments),this.sessions=new Gl(this._client),this.transcriptionSessions=new Wl(this._client)}}Qn.Sessions=Gl;Qn.TranscriptionSessions=Wl;class Jl extends F{create(e,t,r){return this._client.post(x`/threads/${e}/messages`,{body:t,...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,t,r){const{thread_id:a}=t;return this._client.get(x`/threads/${a}/messages/${e}`,{...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,t,r){const{thread_id:a,...s}=t;return this._client.post(x`/threads/${a}/messages/${e}`,{body:s,...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e,t={},r){return this._client.getAPIList(x`/threads/${e}/messages`,re,{query:t,...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(e,t,r){const{thread_id:a}=t;return this._client.delete(x`/threads/${a}/messages/${e}`,{...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}class Zl extends F{retrieve(e,t,r){const{thread_id:a,run_id:s,...i}=t;return this._client.get(x`/threads/${a}/runs/${s}/steps/${e}`,{query:i,...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e,t,r){const{thread_id:a,...s}=t;return this._client.getAPIList(x`/threads/${a}/runs/${e}/steps`,re,{query:s,...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}const Mf=n=>{if(typeof Buffer<"u"){const e=Buffer.from(n,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(n),t=e.length,r=new Uint8Array(t);for(let a=0;a<t;a++)r[a]=e.charCodeAt(a);return Array.from(new Float32Array(r.buffer))}};var Ra={};const Mt=n=>{var e,t,r,a;if(typeof globalThis.process<"u")return((e=Ra==null?void 0:Ra[n])==null?void 0:e.trim())??void 0;if(typeof globalThis.Deno<"u")return(a=(r=(t=globalThis.Deno.env)==null?void 0:t.get)==null?void 0:r.call(t,n))==null?void 0:a.trim()};var ge,Tt,ii,Qe,yn,ze,At,Wt,Ot,kn,Ce,_n,bn,Er,gr,yr,Co,No,jo,Lo,Mo,Uo,Fo;class Sr extends Ii{constructor(){super(...arguments),ge.add(this),ii.set(this,[]),Qe.set(this,{}),yn.set(this,{}),ze.set(this,void 0),At.set(this,void 0),Wt.set(this,void 0),Ot.set(this,void 0),kn.set(this,void 0),Ce.set(this,void 0),_n.set(this,void 0),bn.set(this,void 0),Er.set(this,void 0)}[(ii=new WeakMap,Qe=new WeakMap,yn=new WeakMap,ze=new WeakMap,At=new WeakMap,Wt=new WeakMap,Ot=new WeakMap,kn=new WeakMap,Ce=new WeakMap,_n=new WeakMap,bn=new WeakMap,Er=new WeakMap,ge=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",a=>{const s=t.shift();s?s.resolve(a):e.push(a)}),this.on("end",()=>{r=!0;for(const a of t)a.resolve(void 0);t.length=0}),this.on("abort",a=>{r=!0;for(const s of t)s.reject(a);t.length=0}),this.on("error",a=>{r=!0;for(const s of t)s.reject(a);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((s,i)=>t.push({resolve:s,reject:i})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new Tt;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){var s;const r=t==null?void 0:t.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const a=et.fromReadableStream(e,this.controller);for await(const i of a)E(this,ge,"m",gr).call(this,i);if((s=a.controller.signal)!=null&&s.aborted)throw new Ne;return this._addRun(E(this,ge,"m",yr).call(this))}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,a){const s=new Tt;return s._run(()=>s._runToolAssistantStream(e,t,r,{...a,headers:{...a==null?void 0:a.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,t,r,a){var u;const s=a==null?void 0:a.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},o=await e.submitToolOutputs(t,i,{...a,signal:this.controller.signal});this._connected();for await(const c of o)E(this,ge,"m",gr).call(this,c);if((u=o.controller.signal)!=null&&u.aborted)throw new Ne;return this._addRun(E(this,ge,"m",yr).call(this))}static createThreadAssistantStream(e,t,r){const a=new Tt;return a._run(()=>a._threadAssistantStream(e,t,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),a}static createAssistantStream(e,t,r,a){const s=new Tt;return s._run(()=>s._runAssistantStream(e,t,r,{...a,headers:{...a==null?void 0:a.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return E(this,_n,"f")}currentRun(){return E(this,bn,"f")}currentMessageSnapshot(){return E(this,ze,"f")}currentRunStepSnapshot(){return E(this,Er,"f")}async finalRunSteps(){return await this.done(),Object.values(E(this,Qe,"f"))}async finalMessages(){return await this.done(),Object.values(E(this,yn,"f"))}async finalRun(){if(await this.done(),!E(this,At,"f"))throw Error("Final run was not received.");return E(this,At,"f")}async _createThreadAssistantStream(e,t,r){var o;const a=r==null?void 0:r.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const s={...t,stream:!0},i=await e.createAndRun(s,{...r,signal:this.controller.signal});this._connected();for await(const u of i)E(this,ge,"m",gr).call(this,u);if((o=i.controller.signal)!=null&&o.aborted)throw new Ne;return this._addRun(E(this,ge,"m",yr).call(this))}async _createAssistantStream(e,t,r,a){var u;const s=a==null?void 0:a.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},o=await e.create(t,i,{...a,signal:this.controller.signal});this._connected();for await(const c of o)E(this,ge,"m",gr).call(this,c);if((u=o.controller.signal)!=null&&u.aborted)throw new Ne;return this._addRun(E(this,ge,"m",yr).call(this))}static accumulateDelta(e,t){for(const[r,a]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=a;continue}let s=e[r];if(s==null){e[r]=a;continue}if(r==="index"||r==="type"){e[r]=a;continue}if(typeof s=="string"&&typeof a=="string")s+=a;else if(typeof s=="number"&&typeof a=="number")s+=a;else if(Ea(s)&&Ea(a))s=this.accumulateDelta(s,a);else if(Array.isArray(s)&&Array.isArray(a)){if(s.every(i=>typeof i=="string"||typeof i=="number")){s.push(...a);continue}for(const i of a){if(!Ea(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const o=i.index;if(o==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof o!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${o}`);const u=s[o];u==null?s.push(i):s[o]=this.accumulateDelta(u,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${a}, accValue: ${s}`);e[r]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,a){return await this._createAssistantStream(t,e,r,a)}async _runToolAssistantStream(e,t,r,a){return await this._createToolAssistantStream(t,e,r,a)}}Tt=Sr,gr=function(e){if(!this.ended)switch(U(this,_n,e),E(this,ge,"m",jo).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":E(this,ge,"m",Fo).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":E(this,ge,"m",No).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":E(this,ge,"m",Co).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},yr=function(){if(this.ended)throw new M("stream has ended, this shouldn't happen");if(!E(this,At,"f"))throw Error("Final run has not been received");return E(this,At,"f")},Co=function(e){const[t,r]=E(this,ge,"m",Mo).call(this,e,E(this,ze,"f"));U(this,ze,t),E(this,yn,"f")[t.id]=t;for(const a of r){const s=t.content[a.index];(s==null?void 0:s.type)=="text"&&this._emit("textCreated",s.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(const a of e.data.delta.content){if(a.type=="text"&&a.text){let s=a.text,i=t.content[a.index];if(i&&i.type=="text")this._emit("textDelta",s,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(a.index!=E(this,Wt,"f")){if(E(this,Ot,"f"))switch(E(this,Ot,"f").type){case"text":this._emit("textDone",E(this,Ot,"f").text,E(this,ze,"f"));break;case"image_file":this._emit("imageFileDone",E(this,Ot,"f").image_file,E(this,ze,"f"));break}U(this,Wt,a.index)}U(this,Ot,t.content[a.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(E(this,Wt,"f")!==void 0){const a=e.data.content[E(this,Wt,"f")];if(a)switch(a.type){case"image_file":this._emit("imageFileDone",a.image_file,E(this,ze,"f"));break;case"text":this._emit("textDone",a.text,E(this,ze,"f"));break}}E(this,ze,"f")&&this._emit("messageDone",e.data),U(this,ze,void 0)}},No=function(e){const t=E(this,ge,"m",Lo).call(this,e);switch(U(this,Er,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const s of r.step_details.tool_calls)s.index==E(this,kn,"f")?this._emit("toolCallDelta",s,t.step_details.tool_calls[s.index]):(E(this,Ce,"f")&&this._emit("toolCallDone",E(this,Ce,"f")),U(this,kn,s.index),U(this,Ce,t.step_details.tool_calls[s.index]),E(this,Ce,"f")&&this._emit("toolCallCreated",E(this,Ce,"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,Er,void 0),e.data.step_details.type=="tool_calls"&&E(this,Ce,"f")&&(this._emit("toolCallDone",E(this,Ce,"f")),U(this,Ce,void 0)),this._emit("runStepDone",e.data,t);break}},jo=function(e){E(this,ii,"f").push(e),this._emit("event",e)},Lo=function(e){switch(e.event){case"thread.run.step.created":return E(this,Qe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=E(this,Qe,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const a=Tt.accumulateDelta(t,r.delta);E(this,Qe,"f")[e.data.id]=a}return E(this,Qe,"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":E(this,Qe,"f")[e.data.id]=e.data;break}if(E(this,Qe,"f")[e.data.id])return E(this,Qe,"f")[e.data.id];throw new Error("No snapshot available")},Mo=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let a=e.data;if(a.delta.content)for(const s of a.delta.content)if(s.index in t.content){let i=t.content[s.index];t.content[s.index]=E(this,ge,"m",Uo).call(this,s,i)}else t.content[s.index]=s,r.push(s);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Uo=function(e,t){return Tt.accumulateDelta(t,e)},Fo=function(e){switch(U(this,bn,e.data),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,At,e.data),E(this,Ce,"f")&&(this._emit("toolCallDone",E(this,Ce,"f")),U(this,Ce,void 0));break}};let Ci=class extends F{constructor(){super(...arguments),this.steps=new Zl(this._client)}create(e,t,r){const{include:a,...s}=t;return this._client.post(x`/threads/${e}/runs`,{query:{include:a},body:s,...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:t.stream??!1})}retrieve(e,t,r){const{thread_id:a}=t;return this._client.get(x`/threads/${a}/runs/${e}`,{...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,t,r){const{thread_id:a,...s}=t;return this._client.post(x`/threads/${a}/runs/${e}`,{body:s,...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e,t={},r){return this._client.getAPIList(x`/threads/${e}/runs`,re,{query:t,...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}cancel(e,t,r){const{thread_id:a}=t;return this._client.post(x`/threads/${a}/runs/${e}/cancel`,{...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(e,t,r){const a=await this.create(e,t,r);return await this.poll(a.id,{thread_id:e},r)}createAndStream(e,t,r){return Sr.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){var s;const a=C([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((s=r==null?void 0:r.pollIntervalMs)==null?void 0:s.toString())??void 0}]);for(;;){const{data:i,response:o}=await this.retrieve(e,t,{...r,headers:{...r==null?void 0:r.headers,...a}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let u=5e3;if(r!=null&&r.pollIntervalMs)u=r.pollIntervalMs;else{const c=o.headers.get("openai-poll-after-ms");if(c){const l=parseInt(c);isNaN(l)||(u=l)}}await Mr(u);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,t,r){return Sr.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){const{thread_id:a,...s}=t;return this._client.post(x`/threads/${a}/runs/${e}/submit_tool_outputs`,{body:s,...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,r){const a=await this.submitToolOutputs(e,t,r);return await this.poll(a.id,t,r)}submitToolOutputsStream(e,t,r){return Sr.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};Ci.Steps=Zl;class Yn extends F{constructor(){super(...arguments),this.runs=new Ci(this._client),this.messages=new Jl(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:C([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}retrieve(e,t){return this._client.get(x`/threads/${e}`,{...t,headers:C([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}update(e,t,r){return this._client.post(x`/threads/${e}`,{body:t,...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(e,t){return this._client.delete(x`/threads/${e}`,{...t,headers:C([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:C([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return Sr.createThreadAssistantStream(e,this._client.beta.threads,t)}}Yn.Runs=Ci;Yn.Messages=Jl;class Dr extends F{constructor(){super(...arguments),this.realtime=new Qn(this._client),this.assistants=new Hl(this._client),this.threads=new Yn(this._client)}}Dr.Realtime=Qn;Dr.Assistants=Hl;Dr.Threads=Yn;class Kl extends F{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Vl extends F{retrieve(e,t,r){const{container_id:a}=t;return this._client.get(x`/containers/${a}/files/${e}/content`,{...r,headers:C([{Accept:"application/binary"},r==null?void 0:r.headers]),__binaryResponse:!0})}}let Ni=class extends F{constructor(){super(...arguments),this.content=new Vl(this._client)}create(e,t,r){return this._client.post(x`/containers/${e}/files`,Rt({body:t,...r},this._client))}retrieve(e,t,r){const{container_id:a}=t;return this._client.get(x`/containers/${a}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(x`/containers/${e}/files`,re,{query:t,...r})}delete(e,t,r){const{container_id:a}=t;return this._client.delete(x`/containers/${a}/files/${e}`,{...r,headers:C([{Accept:"*/*"},r==null?void 0:r.headers])})}};Ni.Content=Vl;class ji extends F{constructor(){super(...arguments),this.files=new Ni(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(x`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",re,{query:e,...t})}delete(e,t){return this._client.delete(x`/containers/${e}`,{...t,headers:C([{Accept:"*/*"},t==null?void 0:t.headers])})}}ji.Files=Ni;class Xl extends F{create(e,t){const r=!!e.encoding_format;let a=r?e.encoding_format:"base64";r&&pe(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const s=this._client.post("/embeddings",{body:{...e,encoding_format:a},...t});return r?s:(pe(this._client).debug("embeddings/decoding base64 embeddings from base64"),s._thenUnwrap(i=>(i&&i.data&&i.data.forEach(o=>{const u=o.embedding;o.embedding=Mf(u)}),i)))}}class Ql extends F{retrieve(e,t,r){const{eval_id:a,run_id:s}=t;return this._client.get(x`/evals/${a}/runs/${s}/output_items/${e}`,r)}list(e,t,r){const{eval_id:a,...s}=t;return this._client.getAPIList(x`/evals/${a}/runs/${e}/output_items`,re,{query:s,...r})}}class Li extends F{constructor(){super(...arguments),this.outputItems=new Ql(this._client)}create(e,t,r){return this._client.post(x`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){const{eval_id:a}=t;return this._client.get(x`/evals/${a}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(x`/evals/${e}/runs`,re,{query:t,...r})}delete(e,t,r){const{eval_id:a}=t;return this._client.delete(x`/evals/${a}/runs/${e}`,r)}cancel(e,t,r){const{eval_id:a}=t;return this._client.post(x`/evals/${a}/runs/${e}`,r)}}Li.OutputItems=Ql;class Mi extends F{constructor(){super(...arguments),this.runs=new Li(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(x`/evals/${e}`,t)}update(e,t,r){return this._client.post(x`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",re,{query:e,...t})}delete(e,t){return this._client.delete(x`/evals/${e}`,t)}}Mi.Runs=Li;let Yl=class extends F{create(e,t){return this._client.post("/files",Rt({body:e,...t},this._client))}retrieve(e,t){return this._client.get(x`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",re,{query:e,...t})}delete(e,t){return this._client.delete(x`/files/${e}`,t)}content(e,t){return this._client.get(x`/files/${e}/content`,{...t,headers:C([{Accept:"application/binary"},t==null?void 0:t.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=1800*1e3}={}){const a=new Set(["processed","error","deleted"]),s=Date.now();let i=await this.retrieve(e);for(;!i.status||!a.has(i.status);)if(await Mr(t),i=await this.retrieve(e),Date.now()-s>r)throw new Zn({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};class ed extends F{}let td=class extends F{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class Ui extends F{constructor(){super(...arguments),this.graders=new td(this._client)}}Ui.Graders=td;class rd extends F{create(e,t,r){return this._client.getAPIList(x`/fine_tuning/checkpoints/${e}/permissions`,Xn,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(x`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){const{fine_tuned_model_checkpoint:a}=t;return this._client.delete(x`/fine_tuning/checkpoints/${a}/permissions/${e}`,r)}}let Fi=class extends F{constructor(){super(...arguments),this.permissions=new rd(this._client)}};Fi.Permissions=rd;class nd extends F{list(e,t={},r){return this._client.getAPIList(x`/fine_tuning/jobs/${e}/checkpoints`,re,{query:t,...r})}}class Di extends F{constructor(){super(...arguments),this.checkpoints=new nd(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(x`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",re,{query:e,...t})}cancel(e,t){return this._client.post(x`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(x`/fine_tuning/jobs/${e}/events`,re,{query:t,...r})}pause(e,t){return this._client.post(x`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(x`/fine_tuning/jobs/${e}/resume`,t)}}Di.Checkpoints=nd;class Xt extends F{constructor(){super(...arguments),this.methods=new ed(this._client),this.jobs=new Di(this._client),this.checkpoints=new Fi(this._client),this.alpha=new Ui(this._client)}}Xt.Methods=ed;Xt.Jobs=Di;Xt.Checkpoints=Fi;Xt.Alpha=Ui;class ad extends F{}class Bi extends F{constructor(){super(...arguments),this.graderModels=new ad(this._client)}}Bi.GraderModels=ad;class sd extends F{createVariation(e,t){return this._client.post("/images/variations",Rt({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",Rt({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class id extends F{retrieve(e,t){return this._client.get(x`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Xn,e)}delete(e,t){return this._client.delete(x`/models/${e}`,t)}}class od extends F{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function Uf(n,e){return!e||!Df(e)?{...n,output_parsed:null,output:n.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:ud(n,e)}function ud(n,e){const t=n.output.map(a=>{if(a.type==="function_call")return{...a,parsed_arguments:zf(e,a)};if(a.type==="message"){const s=a.content.map(i=>i.type==="output_text"?{...i,parsed:Ff(e,i.text)}:i);return{...a,content:s}}return a}),r=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||oi(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(const a of r.output)if(a.type==="message"){for(const s of a.content)if(s.type==="output_text"&&s.parsed!==null)return s.parsed}return null}}),r}function Ff(n,e){var t,r,a,s;return((r=(t=n.text)==null?void 0:t.format)==null?void 0:r.type)!=="json_schema"?null:"$parseRaw"in((a=n.text)==null?void 0:a.format)?((s=n.text)==null?void 0:s.format).$parseRaw(e):JSON.parse(e)}function Df(n){var e;return!!Pi((e=n.text)==null?void 0:e.format)}function Bf(n){return(n==null?void 0:n.$brand)==="auto-parseable-tool"}function qf(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function zf(n,e){const t=qf(n.tools??[],e.name);return{...e,...e,parsed_arguments:Bf(t)?t.$parseRaw(e.arguments):t!=null&&t.strict?JSON.parse(e.arguments):null}}function oi(n){const e=[];for(const t of n.output)if(t.type==="message")for(const r of t.content)r.type==="output_text"&&e.push(r.text);n.output_text=e.join("")}var Ut,Xr,dt,Qr,Do,Bo,qo,zo;class qi extends Ii{constructor(e){super(),Ut.add(this),Xr.set(this,void 0),dt.set(this,void 0),Qr.set(this,void 0),U(this,Xr,e)}static createResponse(e,t,r){const a=new qi(t);return a._run(()=>a._createOrRetrieveResponse(e,t,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createOrRetrieveResponse(e,t,r){var o;const a=r==null?void 0:r.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort())),E(this,Ut,"m",Do).call(this);let s,i=null;"response_id"in t?(s=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):s=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const u of s)E(this,Ut,"m",Bo).call(this,u,i);if((o=s.controller.signal)!=null&&o.aborted)throw new Ne;return E(this,Ut,"m",qo).call(this)}[(Xr=new WeakMap,dt=new WeakMap,Qr=new WeakMap,Ut=new WeakSet,Do=function(){this.ended||U(this,dt,void 0)},Bo=function(t,r){if(this.ended)return;const a=(i,o)=>{(r==null||o.sequence_number>r)&&this._emit(i,o)},s=E(this,Ut,"m",zo).call(this,t);switch(a("event",t),t.type){case"response.output_text.delta":{const i=s.output[t.output_index];if(!i)throw new M(`missing output at index ${t.output_index}`);if(i.type==="message"){const o=i.content[t.content_index];if(!o)throw new M(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new M(`expected content to be 'output_text', got ${o.type}`);a("response.output_text.delta",{...t,snapshot:o.text})}break}case"response.function_call_arguments.delta":{const i=s.output[t.output_index];if(!i)throw new M(`missing output at index ${t.output_index}`);i.type==="function_call"&&a("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:a(t.type,t);break}},qo=function(){if(this.ended)throw new M("stream has ended, this shouldn't happen");const t=E(this,dt,"f");if(!t)throw new M("request ended without sending any events");U(this,dt,void 0);const r=Hf(t,E(this,Xr,"f"));return U(this,Qr,r),r},zo=function(t){let r=E(this,dt,"f");if(!r){if(t.type!=="response.created")throw new M(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=U(this,dt,t.response),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{const a=r.output[t.output_index];if(!a)throw new M(`missing output at index ${t.output_index}`);a.type==="message"&&a.content.push(t.part);break}case"response.output_text.delta":{const a=r.output[t.output_index];if(!a)throw new M(`missing output at index ${t.output_index}`);if(a.type==="message"){const s=a.content[t.content_index];if(!s)throw new M(`missing content at index ${t.content_index}`);if(s.type!=="output_text")throw new M(`expected content to be 'output_text', got ${s.type}`);s.text+=t.delta}break}case"response.function_call_arguments.delta":{const a=r.output[t.output_index];if(!a)throw new M(`missing output at index ${t.output_index}`);a.type==="function_call"&&(a.arguments+=t.delta);break}case"response.completed":{U(this,dt,t.response);break}}return r},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",a=>{const s=t.shift();s?s.resolve(a):e.push(a)}),this.on("end",()=>{r=!0;for(const a of t)a.resolve(void 0);t.length=0}),this.on("abort",a=>{r=!0;for(const s of t)s.reject(a);t.length=0}),this.on("error",a=>{r=!0;for(const s of t)s.reject(a);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((s,i)=>t.push({resolve:s,reject:i})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=E(this,Qr,"f");if(!e)throw new M("stream ended without producing a ChatCompletion");return e}}function Hf(n,e){return Uf(n,e)}class cd extends F{list(e,t={},r){return this._client.getAPIList(x`/responses/${e}/input_items`,re,{query:t,...r})}}class zi extends F{constructor(){super(...arguments),this.inputItems=new cd(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&oi(r),r))}retrieve(e,t={},r){return this._client.get(x`/responses/${e}`,{query:t,...r,stream:(t==null?void 0:t.stream)??!1})._thenUnwrap(a=>("object"in a&&a.object==="response"&&oi(a),a))}delete(e,t){return this._client.delete(x`/responses/${e}`,{...t,headers:C([{Accept:"*/*"},t==null?void 0:t.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>ud(r,e))}stream(e,t){return qi.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(x`/responses/${e}/cancel`,t)}}zi.InputItems=cd;class ld extends F{create(e,t,r){return this._client.post(x`/uploads/${e}/parts`,Rt({body:t,...r},this._client))}}class Hi extends F{constructor(){super(...arguments),this.parts=new ld(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(x`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(x`/uploads/${e}/complete`,{body:t,...r})}}Hi.Parts=ld;const Gf=async n=>{const e=await Promise.allSettled(n),t=e.filter(a=>a.status==="rejected");if(t.length){for(const a of t)console.error(a.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const r=[];for(const a of e)a.status==="fulfilled"&&r.push(a.value);return r};class dd extends F{create(e,t,r){return this._client.post(x`/vector_stores/${e}/file_batches`,{body:t,...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,t,r){const{vector_store_id:a}=t;return this._client.get(x`/vector_stores/${a}/file_batches/${e}`,{...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}cancel(e,t,r){const{vector_store_id:a}=t;return this._client.post(x`/vector_stores/${a}/file_batches/${e}/cancel`,{...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(e,t,r){const a=await this.create(e,t);return await this.poll(e,a.id,r)}listFiles(e,t,r){const{vector_store_id:a,...s}=t;return this._client.getAPIList(x`/vector_stores/${a}/file_batches/${e}/files`,re,{query:s,...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async poll(e,t,r){var s;const a=C([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((s=r==null?void 0:r.pollIntervalMs)==null?void 0:s.toString())??void 0}]);for(;;){const{data:i,response:o}=await this.retrieve(t,{vector_store_id:e},{...r,headers:a}).withResponse();switch(i.status){case"in_progress":let u=5e3;if(r!=null&&r.pollIntervalMs)u=r.pollIntervalMs;else{const c=o.headers.get("openai-poll-after-ms");if(c){const l=parseInt(c);isNaN(l)||(u=l)}}await Mr(u);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},a){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const s=(a==null?void 0:a.maxConcurrency)??5,i=Math.min(s,t.length),o=this._client,u=t.values(),c=[...r];async function l(h){for(let f of h){const m=await o.files.create({file:f,purpose:"assistants"},a);c.push(m.id)}}const d=Array(i).fill(u).map(l);return await Gf(d),await this.createAndPoll(e,{file_ids:c})}}class hd extends F{create(e,t,r){return this._client.post(x`/vector_stores/${e}/files`,{body:t,...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,t,r){const{vector_store_id:a}=t;return this._client.get(x`/vector_stores/${a}/files/${e}`,{...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,t,r){const{vector_store_id:a,...s}=t;return this._client.post(x`/vector_stores/${a}/files/${e}`,{body:s,...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e,t={},r){return this._client.getAPIList(x`/vector_stores/${e}/files`,re,{query:t,...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(e,t,r){const{vector_store_id:a}=t;return this._client.delete(x`/vector_stores/${a}/files/${e}`,{...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(e,t,r){const a=await this.create(e,t,r);return await this.poll(e,a.id,r)}async poll(e,t,r){var s;const a=C([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((s=r==null?void 0:r.pollIntervalMs)==null?void 0:s.toString())??void 0}]);for(;;){const i=await this.retrieve(t,{vector_store_id:e},{...r,headers:a}).withResponse(),o=i.data;switch(o.status){case"in_progress":let u=5e3;if(r!=null&&r.pollIntervalMs)u=r.pollIntervalMs;else{const c=i.response.headers.get("openai-poll-after-ms");if(c){const l=parseInt(c);isNaN(l)||(u=l)}}await Mr(u);break;case"failed":case"completed":return o}}}async upload(e,t,r){const a=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:a.id},r)}async uploadAndPoll(e,t,r){const a=await this.upload(e,t,r);return await this.poll(e,a.id,r)}content(e,t,r){const{vector_store_id:a}=t;return this._client.getAPIList(x`/vector_stores/${a}/files/${e}/content`,Xn,{...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}class ea extends F{constructor(){super(...arguments),this.files=new hd(this._client),this.fileBatches=new dd(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:C([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}retrieve(e,t){return this._client.get(x`/vector_stores/${e}`,{...t,headers:C([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}update(e,t,r){return this._client.post(x`/vector_stores/${e}`,{body:t,...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",re,{query:e,...t,headers:C([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}delete(e,t){return this._client.delete(x`/vector_stores/${e}`,{...t,headers:C([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}search(e,t,r){return this._client.getAPIList(x`/vector_stores/${e}/search`,Xn,{body:t,method:"post",...r,headers:C([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}ea.Files=hd;ea.FileBatches=dd;var zt,fd,wn;class md extends F{constructor(){super(...arguments),zt.add(this)}async unwrap(e,t,r=this._client.webhookSecret,a=300){return await this.verifySignature(e,t,r,a),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,a=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");E(this,zt,"m",fd).call(this,r);const s=C([t]).values,i=E(this,zt,"m",wn).call(this,s,"webhook-signature"),o=E(this,zt,"m",wn).call(this,s,"webhook-timestamp"),u=E(this,zt,"m",wn).call(this,s,"webhook-id"),c=parseInt(o,10);if(isNaN(c))throw new cr("Invalid webhook timestamp format");const l=Math.floor(Date.now()/1e3);if(l-c>a)throw new cr("Webhook timestamp is too old");if(c>l+a)throw new cr("Webhook timestamp is too new");const d=i.split(" ").map(p=>p.startsWith("v1,")?p.substring(3):p),h=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),f=u?`${u}.${o}.${e}`:`${o}.${e}`,m=await crypto.subtle.importKey("raw",h,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const p of d)try{const g=Buffer.from(p,"base64");if(await crypto.subtle.verify("HMAC",m,g,new TextEncoder().encode(f)))return}catch{continue}throw new cr("The given webhook signature does not match the expected signature")}}zt=new WeakSet,fd=function(e){if(typeof e!="string"||e.length===0)throw new 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")},wn=function(e,t){if(!e)throw new Error("Headers are required");const r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var ui,Gi,vn,pd;let W=class{constructor({baseURL:e=Mt("OPENAI_BASE_URL"),apiKey:t=Mt("OPENAI_API_KEY"),organization:r=Mt("OPENAI_ORG_ID")??null,project:a=Mt("OPENAI_PROJECT_ID")??null,webhookSecret:s=Mt("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(ui.add(this),vn.set(this,void 0),this.completions=new Kl(this),this.chat=new ki(this),this.embeddings=new Xl(this),this.files=new Yl(this),this.images=new sd(this),this.audio=new Fr(this),this.moderations=new od(this),this.models=new id(this),this.fineTuning=new Xt(this),this.graders=new Bi(this),this.vectorStores=new ea(this),this.webhooks=new md(this),this.beta=new Dr(this),this.batches=new zl(this),this.uploads=new Hi(this),this.responses=new zi(this),this.evals=new Mi(this),this.containers=new ji(this),t===void 0)throw new M("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const o={apiKey:t,organization:r,project:a,webhookSecret:s,...i,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&Hh())throw new M(`It looks like you're running in a browser-like environment.
15
+
16
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
17
+ If you understand the risks and have appropriate mitigations in place,
18
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
19
+
20
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
21
+
22
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
23
+ `);this.baseURL=o.baseURL,this.timeout=o.timeout??Gi.DEFAULT_TIMEOUT,this.logger=o.logger??console;const u="warn";this.logLevel=u,this.logLevel=Po(o.logLevel,"ClientOptions.logLevel",this)??Po(Mt("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??Kh(),U(this,vn,Xh),this._options=o,this.apiKey=t,this.organization=r,this.project=a,this.webhookSecret=s}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return C([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return nf(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Bt}`}defaultIdempotencyKey(){return`stainless-node-retry-${Wc()}`}makeStatusError(e,t,r,a){return ye.generate(e,t,r,a)}buildURL(e,t,r){const a=!E(this,ui,"m",pd).call(this)&&r||this.baseURL,s=Uh(e)?new URL(e):new URL(a+(a.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return Dh(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(s.search=this.stringifyQuery(t)),s.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}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,r){return this.request(Promise.resolve(r).then(a=>({method:e,path:t,...a})))}request(e,t=null){return new Vn(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){var y,b;const a=await e,s=a.maxRetries??this.maxRetries;t==null&&(t=s),await this.prepareOptions(a);const{req:i,url:o,timeout:u}=await this.buildRequest(a,{retryCount:s-t});await this.prepareRequest(i,{url:o,options:a});const c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(pe(this).debug(`[${c}] sending request`,St({retryOfRequestLogID:r,method:a.method,url:o,options:a,headers:i.headers})),(y=a.signal)!=null&&y.aborted)throw new Ne;const h=new AbortController,f=await this.fetchWithTimeout(o,i,u,h).catch(Xs),m=Date.now();if(f instanceof Error){const _=`retrying, ${t} attempts remaining`;if((b=a.signal)!=null&&b.aborted)throw new Ne;const w=Vs(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return pe(this).info(`[${c}] connection ${w?"timed out":"failed"} - ${_}`),pe(this).debug(`[${c}] connection ${w?"timed out":"failed"} (${_})`,St({retryOfRequestLogID:r,url:o,durationMs:m-d,message:f.message})),this.retryRequest(a,t,r??c);throw pe(this).info(`[${c}] connection ${w?"timed out":"failed"} - error; no more retries left`),pe(this).debug(`[${c}] connection ${w?"timed out":"failed"} (error; no more retries left)`,St({retryOfRequestLogID:r,url:o,durationMs:m-d,message:f.message})),w?new Zn:new Jn({cause:f})}const p=[...f.headers.entries()].filter(([_])=>_==="x-request-id").map(([_,w])=>", "+_+": "+JSON.stringify(w)).join(""),g=`[${c}${l}${p}] ${i.method} ${o} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${m-d}ms`;if(!f.ok){const _=await this.shouldRetry(f);if(t&&_){const N=`retrying, ${t} attempts remaining`;return await Vh(f.body),pe(this).info(`${g} - ${N}`),pe(this).debug(`[${c}] response error (${N})`,St({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:m-d})),this.retryRequest(a,t,r??c,f.headers)}const w=_?"error; no more retries left":"error; not retryable";pe(this).info(`${g} - ${w}`);const v=await f.text().catch(N=>Xs(N).message),S=zh(v),O=S?void 0:v;throw pe(this).debug(`[${c}] response error (${w})`,St({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:O,durationMs:Date.now()-d})),this.makeStatusError(f.status,S,O,f.headers)}return pe(this).info(g),pe(this).debug(`[${c}] response start`,St({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:m-d})),{response:f,options:a,controller:h,requestLogID:c,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}requestAPIList(e,t){const r=this.makeRequest(t,null,void 0);return new ff(this,r,e)}async fetchWithTimeout(e,t,r,a){const{signal:s,method:i,...o}=t||{};s&&s.addEventListener("abort",()=>a.abort());const u=setTimeout(()=>a.abort(),r),c=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,l={signal:a.signal,...c?{duplex:"half"}:{},method:"GET",...o};i&&(l.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(u)}}async shouldRetry(e){const 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,r,a){let s;const i=a==null?void 0:a.get("retry-after-ms");if(i){const u=parseFloat(i);Number.isNaN(u)||(s=u)}const o=a==null?void 0:a.get("retry-after");if(o&&!s){const u=parseFloat(o);Number.isNaN(u)?s=Date.parse(o)-Date.now():s=u*1e3}if(!(s&&0<=s&&s<60*1e3)){const u=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,u)}return await Mr(s),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){const s=t-e,i=Math.min(.5*Math.pow(2,s),8),o=1-Math.random()*.25;return i*o*1e3}async buildRequest(e,{retryCount:t=0}={}){const r={...e},{method:a,path:s,query:i,defaultBaseURL:o}=r,u=this.buildURL(s,i,o);"timeout"in r&&qh("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:c,body:l}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:a,bodyHeaders:c,retryCount:t});return{req:{method:a,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:a}){let s={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);const i=C([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(a),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Zh(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=C([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||e instanceof 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:al(e)}:E(this,vn,"f").call(this,{body:e,headers:r})}};Gi=W,vn=new WeakMap,ui=new WeakSet,pd=function(){return this.baseURL!=="https://api.openai.com/v1"};W.OpenAI=Gi;W.DEFAULT_TIMEOUT=6e5;W.OpenAIError=M;W.APIError=ye;W.APIConnectionError=Jn;W.APIConnectionTimeoutError=Zn;W.APIUserAbortError=Ne;W.NotFoundError=Vc;W.ConflictError=Xc;W.RateLimitError=Yc;W.BadRequestError=Jc;W.AuthenticationError=Zc;W.InternalServerError=el;W.PermissionDeniedError=Kc;W.UnprocessableEntityError=Qc;W.InvalidWebhookSignatureError=cr;W.toFile=bf;W.Completions=Kl;W.Chat=ki;W.Embeddings=Xl;W.Files=Yl;W.Images=sd;W.Audio=Fr;W.Moderations=od;W.Models=id;W.FineTuning=Xt;W.Graders=Bi;W.VectorStores=ea;W.Webhooks=md;W.Beta=Dr;W.Batches=zl;W.Uploads=Hi;W.Responses=zi;W.Evals=Mi;W.Containers=ji;function Ho(n,e=Wi){n=n.trim();const t=n.indexOf("```");if(t===-1)return e(n);let r=n.substring(t+3);r.startsWith(`json
24
+ `)?r=r.substring(5):r.startsWith("json")?r=r.substring(4):r.startsWith(`
25
+ `)&&(r=r.substring(1));const a=r.indexOf("```");let s=r;return a!==-1&&(s=r.substring(0,a)),e(s.trim())}function Wi(n){if(typeof n>"u")return null;try{return JSON.parse(n)}catch{}let e="";const t=[];let r=!1,a=!1;for(let s of n){if(r)s==='"'&&!a?r=!1:s===`
26
+ `&&!a?s="\\n":s==="\\"?a=!a:a=!1;else if(s==='"')r=!0,a=!1;else if(s==="{")t.push("}");else if(s==="[")t.push("]");else if(s==="}"||s==="]")if(t&&t[t.length-1]===s)t.pop();else return null;e+=s}r&&(e+='"');for(let s=t.length-1;s>=0;s-=1)e+=t[s];try{return JSON.parse(e)}catch{return null}}var $a,Go;function Wf(){return Go||(Go=1,$a=function(n,e){if(typeof n!="string")throw new TypeError("Expected a string");return e=typeof e>"u"?"_":e,n.replace(/([a-z\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+e+"$2").toLowerCase()}),$a}var Jf=Wf();const Zf=Lr(Jf);var Yr={exports:{}},Wo;function Kf(){if(Wo)return Yr.exports;Wo=1;const n=/[\p{Lu}]/u,e=/[\p{Ll}]/u,t=/^[\p{Lu}](?![\p{Lu}])/gu,r=/([\p{Alpha}\p{N}_]|$)/u,a=/[_.\- ]+/,s=new RegExp("^"+a.source),i=new RegExp(a.source+r.source,"gu"),o=new RegExp("\\d+"+r.source,"gu"),u=(h,f,m)=>{let p=!1,g=!1,y=!1;for(let b=0;b<h.length;b++){const _=h[b];p&&n.test(_)?(h=h.slice(0,b)+"-"+h.slice(b),p=!1,y=g,g=!0,b++):g&&y&&e.test(_)?(h=h.slice(0,b-1)+"-"+h.slice(b-1),y=g,g=!1,p=!0):(p=f(_)===_&&m(_)!==_,y=g,g=m(_)===_&&f(_)!==_)}return h},c=(h,f)=>(t.lastIndex=0,h.replace(t,m=>f(m))),l=(h,f)=>(i.lastIndex=0,o.lastIndex=0,h.replace(i,(m,p)=>f(p)).replace(o,m=>f(m))),d=(h,f)=>{if(!(typeof h=="string"||Array.isArray(h)))throw new TypeError("Expected the input to be `string | string[]`");if(f={pascalCase:!1,preserveConsecutiveUppercase:!1,...f},Array.isArray(h)?h=h.map(y=>y.trim()).filter(y=>y.length).join("-"):h=h.trim(),h.length===0)return"";const m=f.locale===!1?y=>y.toLowerCase():y=>y.toLocaleLowerCase(f.locale),p=f.locale===!1?y=>y.toUpperCase():y=>y.toLocaleUpperCase(f.locale);return h.length===1?f.pascalCase?p(h):m(h):(h!==m(h)&&(h=u(h,m,p)),h=h.replace(s,""),f.preserveConsecutiveUppercase?h=c(h,m):h=m(h),f.pascalCase&&(h=p(h.charAt(0))+h.slice(1)),l(h,p))};return Yr.exports=d,Yr.exports.default=d,Yr.exports}Kf();function Vf(n,e){return(e==null?void 0:e[n])||Zf(n)}function Xf(n,e,t){const r={};for(const a in n)Object.hasOwn(n,a)&&(r[e(a,t)]=n[a]);return r}function Jo(n){return Array.isArray(n)?[...n]:{...n}}function Qf(n,e){const t=Jo(n);for(const[r,a]of Object.entries(e)){const[s,...i]=r.split(".").reverse();let o=t;for(const u of i.reverse()){if(o[u]===void 0)break;o[u]=Jo(o[u]),o=o[u]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[a]})}return t}function gd(n){const e=Object.getPrototypeOf(n);return typeof n.lc_name=="function"&&(typeof e.lc_name!="function"||n.lc_name()!==e.lc_name())?n.lc_name():n.name}class $t{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,gd(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([r])=>{var a;return(a=this.lc_serializable_keys)==null?void 0:a.includes(r)})):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof $t||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},t={},r=Object.keys(this.lc_kwargs).reduce((a,s)=>(a[s]=s in this?this[s]:this.lc_kwargs[s],a),{});for(let a=Object.getPrototypeOf(this);a;a=Object.getPrototypeOf(a))Object.assign(e,Reflect.get(a,"lc_aliases",this)),Object.assign(t,Reflect.get(a,"lc_secrets",this)),Object.assign(r,Reflect.get(a,"lc_attributes",this));return Object.keys(t).forEach(a=>{let s=this,i=r;const[o,...u]=a.split(".").reverse();for(const c of u.reverse()){if(!(c in s)||s[c]===void 0)return;(!(c in i)||i[c]===void 0)&&(typeof s[c]=="object"&&s[c]!=null?i[c]={}:Array.isArray(s[c])&&(i[c]=[])),s=s[c],i=i[c]}o in s&&s[o]!==void 0&&(i[o]=i[o]||s[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Xf(Object.keys(t).length?Qf(r,t):r,Vf,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}function kt(n){return typeof n=="object"&&n!==null&&"type"in n&&typeof n.type=="string"&&"source_type"in n&&(n.source_type==="url"||n.source_type==="base64"||n.source_type==="text"||n.source_type==="id")}function Yf(n){return kt(n)&&n.source_type==="url"&&"url"in n&&typeof n.url=="string"}function em(n){return kt(n)&&n.source_type==="base64"&&"data"in n&&typeof n.data=="string"}function tm(n){if(kt(n)){if(n.source_type==="url")return{type:"image_url",image_url:{url:n.url}};if(n.source_type==="base64"){if(!n.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${n.mime_type};base64,${n.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Zo(n){const e=n.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${n}" - does not match type/subtype format.`);const t=e[0].trim(),r=e[1].trim();if(t===""||r==="")throw new Error(`Invalid mime type: "${n}" - type or subtype is empty.`);const a={};for(const s of n.split(";").slice(1)){const i=s.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${n}".`);const o=i[0].trim(),u=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${n}".`);a[o]=u}return{type:t,subtype:r,parameters:a}}function Ko({dataUrl:n,asTypedArray:e=!1}){const t=n.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let r;if(t){r=t[1].toLowerCase();const a=e?Uint8Array.from(atob(t[2]),s=>s.charCodeAt(0)):t[2];return{mime_type:r,data:a}}}function yd(n,e){if(n.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(n)}if(n.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(n)}if(n.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(n)}if(n.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(n)}throw new Error(`Unable to convert content block type '${n.type}' to provider-specific format: not recognized.`)}function Qt(n,e){return typeof n=="string"?n===""?e:typeof e=="string"?n+e:Array.isArray(e)&&e.some(t=>kt(t))?[{type:"text",source_type:"text",text:n},...e]:[{type:"text",text:n},...e]:Array.isArray(e)?ta(n,e)??[...n,...e]:e===""?n:Array.isArray(n)&&n.some(t=>kt(t))?[...n,{type:"file",source_type:"text",text:e}]:[...n,{type:"text",text:e}]}function rm(n,e){return n==="error"||e==="error"?"error":"success"}function nm(n,e){function t(r,a){if(typeof r!="object"||r===null||r===void 0)return r;if(a>=e)return Array.isArray(r)?"[Array]":"[Object]";if(Array.isArray(r))return r.map(i=>t(i,a+1));const s={};for(const i of Object.keys(r))s[i]=t(r[i],a+1);return s}return JSON.stringify(t(n,0),null,2)}class Nt extends $t{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}getType(){return this._getType()}constructor(e,t){typeof e=="string"&&(e={content:e,additional_kwargs:t,response_metadata:{}}),e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.content=e.content,this.additional_kwargs=e.additional_kwargs,this.response_metadata=e.response_metadata,this.id=e.id}toDict(){return{type:this._getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;const t=nm(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}}function Se(n,e){const t={...n};for(const[r,a]of Object.entries(e))if(t[r]==null)t[r]=a;else{if(a==null)continue;if(typeof t[r]!=typeof a||Array.isArray(t[r])!==Array.isArray(a))throw new Error(`field[${r}] already exists in the message chunk, but with a different type.`);if(typeof t[r]=="string"){if(r==="type")continue;["id","name","output_version","model_provider"].includes(r)?t[r]=a:t[r]+=a}else if(typeof t[r]=="object"&&!Array.isArray(t[r]))t[r]=Se(t[r],a);else if(Array.isArray(t[r]))t[r]=ta(t[r],a);else{if(t[r]===a)continue;console.warn(`field[${r}] already exists in this message chunk and value has unsupported type.`)}}return t}function ta(n,e){if(!(n===void 0&&e===void 0)){if(n===void 0||e===void 0)return n||e;{const t=[...n];for(const r of e)if(typeof r=="object"&&r!==null&&"index"in r&&typeof r.index=="number"){const a=t.findIndex(s=>{const i=typeof s=="object",o="index"in s&&s.index===r.index,u="id"in s&&"id"in r&&(s==null?void 0:s.id)===(r==null?void 0:r.id),c=!("id"in s)||!(s!=null&&s.id)||!("id"in r)||!(r!=null&&r.id);return i&&o&&(u||c)});a!==-1&&typeof t[a]=="object"&&t[a]!==null?t[a]=Se(t[a],r):t.push(r)}else{if(typeof r=="object"&&r!==null&&"text"in r&&r.text==="")continue;t.push(r)}return t}}}function am(n,e){if(!n&&!e)throw new Error("Cannot merge two undefined objects.");if(!n||!e)return n||e;if(typeof n!=typeof e)throw new Error(`Cannot merge objects of different types.
27
+ Left ${typeof n}
28
+ Right ${typeof e}`);if(typeof n=="string"&&typeof e=="string")return n+e;if(Array.isArray(n)&&Array.isArray(e))return ta(n,e);if(typeof n=="object"&&typeof e=="object")return Se(n,e);if(n===e)return n;throw new Error(`Can not merge objects of different types.
29
+ Left ${n}
30
+ Right ${e}`)}class Yt extends Nt{}function sm(n){return typeof n.role=="string"}function ra(n){return typeof(n==null?void 0:n._getType)=="function"}function im(n){return ra(n)&&typeof n.concat=="function"}class om extends Nt{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(e,t,r){typeof e=="string"&&(e={content:e,name:r,tool_call_id:t}),super(e),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status,this.metadata=e.metadata}_getType(){return"tool"}static isInstance(e){return e._getType()==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}class Ji extends Yt{constructor(e){super(e),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}_getType(){return"tool"}concat(e){return new Ji({content:Qt(this.content,e.content),additional_kwargs:Se(this.additional_kwargs,e.additional_kwargs),response_metadata:Se(this.response_metadata,e.response_metadata),artifact:am(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:rm(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}function um(n){const e=[],t=[];for(const r of n)if(r.function){const a=r.function.name;try{const s=JSON.parse(r.function.arguments),i={name:a||"",args:s||{},id:r.id};e.push(i)}catch{t.push({name:a,args:r.function.arguments,id:r.id,error:"Malformed args."})}}else continue;return[e,t]}class $r extends Nt{get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e,t){var a;let r;if(typeof e=="string")r={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:t??{}};else{r=e;const s=(a=r.additional_kwargs)==null?void 0:a.tool_calls,i=r.tool_calls;s!=null&&s.length>0&&(i===void 0||i.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
31
+
32
+ Please upgrade your packages to versions that set`,"message tool calls. e.g., `yarn add @langchain/anthropic`,","yarn add @langchain/openai`, etc."].join(" "));try{if(s!=null&&i===void 0){const[o,u]=um(s);r.tool_calls=o??[],r.invalid_tool_calls=u??[]}else r.tool_calls=r.tool_calls??[],r.invalid_tool_calls=r.invalid_tool_calls??[]}catch{r.tool_calls=[],r.invalid_tool_calls=[]}}super(r),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof r!="string"&&(this.tool_calls=r.tool_calls??this.tool_calls,this.invalid_tool_calls=r.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=r.usage_metadata}static lc_name(){return"AIMessage"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}}function Br(n){return n._getType()==="ai"}function Vo(n){return n._getType()==="ai"}class bt extends Yt{constructor(e){var r,a;let t;if(typeof e=="string")t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{const s=e.tool_call_chunks.reduce((u,c)=>{const l=u.findIndex(([d])=>"id"in c&&c.id&&"index"in c&&c.index!==void 0?c.id===d.id&&c.index===d.index:"id"in c&&c.id?c.id===d.id:"index"in c&&c.index!==void 0?c.index===d.index:!1);return l!==-1?u[l].push(c):u.push([c]),u},[]),i=[],o=[];for(const u of s){let c={};const l=((r=u[0])==null?void 0:r.name)??"",d=u.map(m=>m.args||"").join(""),h=d.length?d:"{}",f=(a=u[0])==null?void 0:a.id;try{if(c=Wi(h),!f||c===null||typeof c!="object"||Array.isArray(c))throw new Error("Malformed tool call chunk args.");i.push({name:l,args:c,id:f,type:"tool_call"})}catch{o.push({name:l,args:h,id:f,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:i,invalid_tool_calls:o,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(t),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){var r,a,s,i,o,u,c,l,d,h,f,m,p,g,y,b,_,w,v,S,O,T,N,G,z,oe,Ke,I,A,j,R,L,$,D,J,q,Y,ue,ee,ct;const t={content:Qt(this.content,e.content),additional_kwargs:Se(this.additional_kwargs,e.additional_kwargs),response_metadata:Se(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){const jt=ta(this.tool_call_chunks,e.tool_call_chunks);jt!==void 0&&jt.length>0&&(t.tool_call_chunks=jt)}if(this.usage_metadata!==void 0||e.usage_metadata!==void 0){const jt={...(((a=(r=this.usage_metadata)==null?void 0:r.input_token_details)==null?void 0:a.audio)!==void 0||((i=(s=e.usage_metadata)==null?void 0:s.input_token_details)==null?void 0:i.audio)!==void 0)&&{audio:(((u=(o=this.usage_metadata)==null?void 0:o.input_token_details)==null?void 0:u.audio)??0)+(((l=(c=e.usage_metadata)==null?void 0:c.input_token_details)==null?void 0:l.audio)??0)},...(((h=(d=this.usage_metadata)==null?void 0:d.input_token_details)==null?void 0:h.cache_read)!==void 0||((m=(f=e.usage_metadata)==null?void 0:f.input_token_details)==null?void 0:m.cache_read)!==void 0)&&{cache_read:(((g=(p=this.usage_metadata)==null?void 0:p.input_token_details)==null?void 0:g.cache_read)??0)+(((b=(y=e.usage_metadata)==null?void 0:y.input_token_details)==null?void 0:b.cache_read)??0)},...(((w=(_=this.usage_metadata)==null?void 0:_.input_token_details)==null?void 0:w.cache_creation)!==void 0||((S=(v=e.usage_metadata)==null?void 0:v.input_token_details)==null?void 0:S.cache_creation)!==void 0)&&{cache_creation:(((T=(O=this.usage_metadata)==null?void 0:O.input_token_details)==null?void 0:T.cache_creation)??0)+(((G=(N=e.usage_metadata)==null?void 0:N.input_token_details)==null?void 0:G.cache_creation)??0)}},po={...(((oe=(z=this.usage_metadata)==null?void 0:z.output_token_details)==null?void 0:oe.audio)!==void 0||((I=(Ke=e.usage_metadata)==null?void 0:Ke.output_token_details)==null?void 0:I.audio)!==void 0)&&{audio:(((j=(A=this.usage_metadata)==null?void 0:A.output_token_details)==null?void 0:j.audio)??0)+(((L=(R=e.usage_metadata)==null?void 0:R.output_token_details)==null?void 0:L.audio)??0)},...(((D=($=this.usage_metadata)==null?void 0:$.output_token_details)==null?void 0:D.reasoning)!==void 0||((q=(J=e.usage_metadata)==null?void 0:J.output_token_details)==null?void 0:q.reasoning)!==void 0)&&{reasoning:(((ue=(Y=this.usage_metadata)==null?void 0:Y.output_token_details)==null?void 0:ue.reasoning)??0)+(((ct=(ee=e.usage_metadata)==null?void 0:ee.output_token_details)==null?void 0:ct.reasoning)??0)}},wa=this.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},va=e.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},Oh={input_tokens:wa.input_tokens+va.input_tokens,output_tokens:wa.output_tokens+va.output_tokens,total_tokens:wa.total_tokens+va.total_tokens,...Object.keys(jt).length>0&&{input_token_details:jt},...Object.keys(po).length>0&&{output_token_details:po}};t.usage_metadata=Oh}return new bt(t)}}class qr extends Nt{static lc_name(){return"ChatMessage"}static _chatMessageClass(){return qr}constructor(e,t){typeof e=="string"&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}static isInstance(e){return e._getType()==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}}class na extends Yt{static lc_name(){return"ChatMessageChunk"}constructor(e,t){typeof e=="string"&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}concat(e){return new na({content:Qt(this.content,e.content),additional_kwargs:Se(this.additional_kwargs,e.additional_kwargs),response_metadata:Se(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}get _printableFields(){return{...super._printableFields,role:this.role}}}class aa extends Yt{static lc_name(){return"FunctionMessageChunk"}_getType(){return"function"}concat(e){return new aa({content:Qt(this.content,e.content),additional_kwargs:Se(this.additional_kwargs,e.additional_kwargs),response_metadata:Se(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}}class sa extends Nt{static lc_name(){return"HumanMessage"}_getType(){return"human"}constructor(e,t){super(e,t)}}class ia extends Yt{static lc_name(){return"HumanMessageChunk"}_getType(){return"human"}constructor(e,t){super(e,t)}concat(e){return new ia({content:Qt(this.content,e.content),additional_kwargs:Se(this.additional_kwargs,e.additional_kwargs),response_metadata:Se(this.response_metadata,e.response_metadata),id:this.id??e.id})}}class Xo extends Nt{static lc_name(){return"SystemMessage"}_getType(){return"system"}constructor(e,t){super(e,t)}}class kr extends Yt{static lc_name(){return"SystemMessageChunk"}_getType(){return"system"}constructor(e,t){super(e,t)}concat(e){return new kr({content:Qt(this.content,e.content),additional_kwargs:Se(this.additional_kwargs,e.additional_kwargs),response_metadata:Se(this.response_metadata,e.response_metadata),id:this.id??e.id})}}function _d(n,e){return n.lc_error_code=e,n.message=`${n.message}
33
+
34
+ Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
35
+ `,n}function bd(n){return!!(n&&typeof n=="object"&&"type"in n&&n.type==="tool_call")}class cm extends Error{constructor(e,t){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=t}}class lm extends Nt{constructor(e){super({...e,content:""}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.id=e.id}_getType(){return"remove"}get _printableFields(){return{...super._printableFields,id:this.id}}}function dm(n){return bd(n)?n:typeof n.id=="string"&&n.type==="function"&&typeof n.function=="object"&&n.function!==null&&"arguments"in n.function&&typeof n.function.arguments=="string"&&"name"in n.function&&typeof n.function.name=="string"?{id:n.id,args:JSON.parse(n.function.arguments),name:n.function.name,type:"tool_call"}:n}function hm(n){return typeof n=="object"&&n!=null&&n.lc===1&&Array.isArray(n.id)&&n.kwargs!=null&&typeof n.kwargs=="object"}function ka(n){let e,t;if(hm(n)){const r=n.id.at(-1);r==="HumanMessage"||r==="HumanMessageChunk"?e="user":r==="AIMessage"||r==="AIMessageChunk"?e="assistant":r==="SystemMessage"||r==="SystemMessageChunk"?e="system":r==="FunctionMessage"||r==="FunctionMessageChunk"?e="function":r==="ToolMessage"||r==="ToolMessageChunk"?e="tool":e="unknown",t=n.kwargs}else{const{type:r,...a}=n;e=r,t=a}if(e==="human"||e==="user")return new sa(t);if(e==="ai"||e==="assistant"){const{tool_calls:r,...a}=t;if(!Array.isArray(r))return new $r(t);const s=r.map(dm);return new $r({...a,tool_calls:s})}else{if(e==="system")return new Xo(t);if(e==="developer")return new Xo({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in t)return new om({...t,content:t.content,tool_call_id:t.tool_call_id,name:t.name});if(e==="remove"&&"id"in t&&typeof t.id=="string")return new lm({...t,id:t.id});throw _d(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
36
+
37
+ Received: ${JSON.stringify(n,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function _r(n){if(typeof n=="string")return new sa(n);if(ra(n))return n;if(Array.isArray(n)){const[e,t]=n;return ka({type:e,content:t})}else if(sm(n)){const{role:e,...t}=n;return ka({...t,type:e})}else return ka(n)}function wd(n,e="Human",t="AI"){const r=[];for(const a of n){let s;if(a._getType()==="human")s=e;else if(a._getType()==="ai")s=t;else if(a._getType()==="system")s="System";else if(a._getType()==="function")s="Function";else if(a._getType()==="tool")s="Tool";else if(a._getType()==="generic")s=a.role;else throw new Error(`Got unsupported message type: ${a._getType()}`);const i=a.name?`${a.name}, `:"",o=typeof a.content=="string"?a.content:JSON.stringify(a.content,null,2);r.push(`${s}: ${i}${o}`)}return r.join(`
38
+ `)}function fm(n){var t;const e=n._getType();if(e==="human")return new ia({...n});if(e==="ai"){let r={...n};return"tool_calls"in r&&(r={...r,tool_call_chunks:(t=r.tool_calls)==null?void 0:t.map(a=>({...a,type:"tool_call_chunk",index:void 0,args:JSON.stringify(a.args)}))}),new bt({...r})}else{if(e==="system")return new kr({...n});if(e==="function")return new aa({...n});if(qr.isInstance(n))return new na({...n});throw new Error("Unknown message type.")}}var sr={exports:{}},Ca={},Na,Qo;function mm(){if(Qo)return Na;Qo=1;function n(e,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return Na=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);else return!1;var a=this;return this._timer=setTimeout(function(){a._attempts++,a._operationTimeoutCb&&(a._timeout=setTimeout(function(){a._operationTimeoutCb(a._attempts)},a._operationTimeout),a._options.unref&&a._timeout.unref()),a._fn(a._attempts)},r),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},n.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,r=0,a=0;a<this._errors.length;a++){var s=this._errors[a],i=s.message,o=(e[i]||0)+1;e[i]=o,o>=r&&(t=s,r=o)}return t},Na}var Yo;function pm(){return Yo||(Yo=1,(function(n){var e=mm();n.operation=function(t){var r=n.timeouts(t);return new e(r,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})},n.timeouts=function(t){if(t instanceof Array)return[].concat(t);var r={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var a in t)r[a]=t[a];if(r.minTimeout>r.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var s=[],i=0;i<r.retries;i++)s.push(this.createTimeout(i,r));return t&&t.forever&&!s.length&&s.push(this.createTimeout(i,r)),s.sort(function(o,u){return o-u}),s},n.createTimeout=function(t,r){var a=r.randomize?Math.random()+1:1,s=Math.round(a*Math.max(r.minTimeout,1)*Math.pow(r.factor,t));return s=Math.min(s,r.maxTimeout),s},n.wrap=function(t,r,a){if(r instanceof Array&&(a=r,r=null),!a){a=[];for(var s in t)typeof t[s]=="function"&&a.push(s)}for(var i=0;i<a.length;i++){var o=a[i],u=t[o];t[o]=(function(l){var d=n.operation(r),h=Array.prototype.slice.call(arguments,1),f=h.pop();h.push(function(m){d.retry(m)||(m&&(arguments[0]=d.mainError()),f.apply(this,arguments))}),d.attempt(function(){l.apply(t,h)})}).bind(t,u),t[o].options=r}}})(Ca)),Ca}var ja,eu;function gm(){return eu||(eu=1,ja=pm()),ja}var tu;function ym(){if(tu)return sr.exports;tu=1;const n=gm(),e=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class t extends Error{constructor(o){super(),o instanceof Error?(this.originalError=o,{message:o}=o):(this.originalError=new Error(o),this.originalError.stack=this.stack),this.name="AbortError",this.message=o}}const r=(i,o,u)=>{const c=u.retries-(o-1);return i.attemptNumber=o,i.retriesLeft=c,i},a=i=>e.includes(i),s=(i,o)=>new Promise((u,c)=>{o={onFailedAttempt:()=>{},retries:10,...o};const l=n.operation(o);l.attempt(async d=>{try{u(await i(d))}catch(h){if(!(h instanceof Error)){c(new TypeError(`Non-error was thrown: "${h}". You should only throw errors.`));return}if(h instanceof t)l.stop(),c(h.originalError);else if(h instanceof TypeError&&!a(h.message))l.stop(),c(h);else{r(h,d,o);try{await o.onFailedAttempt(h)}catch(f){c(f);return}l.retry(h)||c(l.mainError())}}})});return sr.exports=s,sr.exports.default=s,sr.exports.AbortError=t,sr.exports}var _m=ym();const Cn=Lr(_m),bm=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function En(n){return typeof n=="string"&&bm.test(n)}var fe=[];for(var La=0;La<256;++La)fe.push((La+256).toString(16).slice(1));function wm(n,e=0){return(fe[n[e+0]]+fe[n[e+1]]+fe[n[e+2]]+fe[n[e+3]]+"-"+fe[n[e+4]]+fe[n[e+5]]+"-"+fe[n[e+6]]+fe[n[e+7]]+"-"+fe[n[e+8]]+fe[n[e+9]]+"-"+fe[n[e+10]]+fe[n[e+11]]+fe[n[e+12]]+fe[n[e+13]]+fe[n[e+14]]+fe[n[e+15]]).toLowerCase()}var en,vm=new Uint8Array(16);function Em(){if(!en&&(en=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!en))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return en(vm)}var Sm=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const ru={randomUUID:Sm};function it(n,e,t){if(ru.randomUUID&&!n)return ru.randomUUID();n=n||{};var r=n.random||(n.rng||Em)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,wm(r)}let Om=class{getStore(){}run(e,t){return t()}};const Ma=Symbol.for("ls:tracing_async_local_storage"),Tm=new Om;let Am=class{getInstance(){return globalThis[Ma]??Tm}initializeGlobalInstance(e){globalThis[Ma]===void 0&&(globalThis[Ma]=e)}};const Pm=new Am;function xm(n=!1){const e=Pm.getInstance().getStore();if(!n&&e===void 0)throw new Error(`Could not get the current run tree.
39
+
40
+ Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function Zi(n){return typeof n=="function"&&"langsmith:traceable"in n}/*!
41
+ * https://github.com/Starcounter-Jack/JSON-Patch
42
+ * (c) 2017-2022 Joachim Wester
43
+ * MIT licensed
44
+ */const Im=Object.prototype.hasOwnProperty;function ci(n,e){return Im.call(n,e)}function li(n){if(Array.isArray(n)){const t=new Array(n.length);for(let r=0;r<t.length;r++)t[r]=""+r;return t}if(Object.keys)return Object.keys(n);let e=[];for(let t in n)ci(n,t)&&e.push(t);return e}function tt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}function di(n){let e=0;const t=n.length;let r;for(;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function Ft(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}function Rm(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}function hi(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(let t=0,r=n.length;t<r;t++)if(hi(n[t]))return!0}else if(typeof n=="object"){const t=li(n),r=t.length;for(var e=0;e<r;e++)if(hi(n[t[e]]))return!0}}return!1}function nu(n,e){const t=[n];for(const r in e){const a=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof a<"u"&&t.push(`${r}: ${a}`)}return t.join(`
45
+ `)}class $m extends Error{constructor(e,t,r,a,s){super(nu(e,{name:t,index:r,operation:a,tree:s})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.setPrototypeOf(this,new.target.prototype),this.message=nu(e,{name:t,index:r,operation:a,tree:s})}}const te=$m,Jt={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){let r=fi(t,this.path);r&&(r=tt(r));const a=Or(t,{op:"remove",path:this.from}).removed;return Or(t,{op:"add",path:this.path,value:a}),{newDocument:t,removed:r}},copy:function(n,e,t){const r=fi(t,this.from);return Or(t,{op:"add",path:this.path,value:tt(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:jn(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}};var km={add:function(n,e,t){return di(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:Jt.move,copy:Jt.copy,test:Jt.test,_get:Jt._get};function fi(n,e){if(e=="")return n;var t={op:"_get",path:e};return Or(n,t),t.value}function Or(n,e,t=!1,r=!0,a=!0,s=0){if(t&&(typeof t=="function"?t(e,0,n,e.path):mi(e,0)),e.path===""){let i={newDocument:n};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=n,i;if(e.op==="move"||e.op==="copy")return i.newDocument=fi(n,e.from),e.op==="move"&&(i.removed=n),i;if(e.op==="test"){if(i.test=jn(n,e.value),i.test===!1)throw new te("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return i.newDocument=n,i}else{if(e.op==="remove")return i.removed=n,i.newDocument=null,i;if(e.op==="_get")return e.value=n,i;if(t)throw new te("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return i}}else{r||(n=tt(n));const o=(e.path||"").split("/");let u=n,c=1,l=o.length,d,h,f;for(typeof t=="function"?f=t:f=mi;;){if(h=o[c],h&&h.indexOf("~")!=-1&&(h=Rm(h)),a&&(h=="__proto__"||h=="prototype"&&c>0&&o[c-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&d===void 0&&(u[h]===void 0?d=o.slice(0,c).join("/"):c==l-1&&(d=e.path),d!==void 0&&f(e,0,n,d)),c++,Array.isArray(u)){if(h==="-")h=u.length;else{if(t&&!di(h))throw new te("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);di(h)&&(h=~~h)}if(c>=l){if(t&&e.op==="add"&&h>u.length)throw new te("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);const m=km[e.op].call(e,u,h,n);if(m.test===!1)throw new te("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return m}}else if(c>=l){const m=Jt[e.op].call(e,u,h,n);if(m.test===!1)throw new te("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return m}if(u=u[h],t&&c<l&&(!u||typeof u!="object"))throw new te("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}function Nn(n,e,t,r=!0,a=!0){if(t&&!Array.isArray(e))throw new te("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=tt(n));const s=new Array(e.length);for(let i=0,o=e.length;i<o;i++)s[i]=Or(n,e[i],t,!0,a,i),n=s[i].newDocument;return s.newDocument=n,s}function mi(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new te("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(Jt[n.op]){if(typeof n.path!="string")throw new te("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new te('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new te("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new te("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&hi(n.value))throw new te("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var a=n.path.split("/").length,s=r.split("/").length;if(a!==s+1&&a!==s)throw new te("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new te("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var i={op:"_get",path:n.from,value:void 0},o=Cm([i],t);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new te("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new te("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}function Cm(n,e,t){try{if(!Array.isArray(n))throw new te("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Nn(tt(e),tt(n),t||!0);else{t=t||mi;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(a){if(a instanceof te)return a;throw a}}function jn(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),a,s,i;if(t&&r){if(s=n.length,s!=e.length)return!1;for(a=s;a--!==0;)if(!jn(n[a],e[a]))return!1;return!0}if(t!=r)return!1;var o=Object.keys(n);if(s=o.length,s!==Object.keys(e).length)return!1;for(a=s;a--!==0;)if(!e.hasOwnProperty(o[a]))return!1;for(a=s;a--!==0;)if(i=o[a],!jn(n[i],e[i]))return!1;return!0}return n!==n&&e!==e}/*!
46
+ * https://github.com/Starcounter-Jack/JSON-Patch
47
+ * (c) 2013-2021 Joachim Wester
48
+ * MIT license
49
+ */function vd(n,e,t,r,a){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=li(e),i=li(n),o=!1,u=i.length-1;u>=0;u--){var c=i[u],l=n[c];if(ci(e,c)&&!(e[c]===void 0&&l!==void 0&&Array.isArray(e)===!1)){var d=e[c];typeof l=="object"&&l!=null&&typeof d=="object"&&d!=null&&Array.isArray(l)===Array.isArray(d)?vd(l,d,t,r+"/"+Ft(c),a):l!==d&&(a&&t.push({op:"test",path:r+"/"+Ft(c),value:tt(l)}),t.push({op:"replace",path:r+"/"+Ft(c),value:tt(d)}))}else Array.isArray(n)===Array.isArray(e)?(a&&t.push({op:"test",path:r+"/"+Ft(c),value:tt(l)}),t.push({op:"remove",path:r+"/"+Ft(c)}),o=!0):(a&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}))}if(!(!o&&s.length==i.length))for(var u=0;u<s.length;u++){var c=s[u];!ci(n,c)&&e[c]!==void 0&&t.push({op:"add",path:r+"/"+Ft(c),value:tt(e[c])})}}}function Nm(n,e,t=!1){var r=[];return vd(n,e,r,"",t),r}const jm=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Lm(n){return typeof n=="string"&&jm.test(n)}function Mm(n){if(!Lm(n))throw TypeError("Invalid UUID");var e,t=new Uint8Array(16);return t[0]=(e=parseInt(n.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(n.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(n.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(n.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(n.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var me=[];for(var Ua=0;Ua<256;++Ua)me.push((Ua+256).toString(16).slice(1));function Ed(n,e=0){return(me[n[e+0]]+me[n[e+1]]+me[n[e+2]]+me[n[e+3]]+"-"+me[n[e+4]]+me[n[e+5]]+"-"+me[n[e+6]]+me[n[e+7]]+"-"+me[n[e+8]]+me[n[e+9]]+"-"+me[n[e+10]]+me[n[e+11]]+me[n[e+12]]+me[n[e+13]]+me[n[e+14]]+me[n[e+15]]).toLowerCase()}var tn,Um=new Uint8Array(16);function Fm(){if(!tn&&(tn=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!tn))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return tn(Um)}function Dm(n){n=unescape(encodeURIComponent(n));for(var e=[],t=0;t<n.length;++t)e.push(n.charCodeAt(t));return e}var Bm="6ba7b810-9dad-11d1-80b4-00c04fd430c8",qm="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function zm(n,e,t){function r(a,s,i,o){var u;if(typeof a=="string"&&(a=Dm(a)),typeof s=="string"&&(s=Mm(s)),((u=s)===null||u===void 0?void 0:u.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var c=new Uint8Array(16+a.length);if(c.set(s),c.set(a,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){o=o||0;for(var l=0;l<16;++l)i[o+l]=c[l];return i}return Ed(c)}try{r.name=n}catch{}return r.DNS=Bm,r.URL=qm,r}var Hm=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const au={randomUUID:Hm};function Ht(n,e,t){if(au.randomUUID&&!n)return au.randomUUID();n=n||{};var r=n.random||(n.rng||Fm)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Ed(r)}function Gm(n,e,t,r){switch(n){case 0:return e&t^~e&r;case 1:return e^t^r;case 2:return e&t^e&r^t&r;case 3:return e^t^r}}function Fa(n,e){return n<<e|n>>>32-e}function Wm(n){var e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof n=="string"){var r=unescape(encodeURIComponent(n));n=[];for(var a=0;a<r.length;++a)n.push(r.charCodeAt(a))}else Array.isArray(n)||(n=Array.prototype.slice.call(n));n.push(128);for(var s=n.length/4+2,i=Math.ceil(s/16),o=new Array(i),u=0;u<i;++u){for(var c=new Uint32Array(16),l=0;l<16;++l)c[l]=n[u*64+l*4]<<24|n[u*64+l*4+1]<<16|n[u*64+l*4+2]<<8|n[u*64+l*4+3];o[u]=c}o[i-1][14]=(n.length-1)*8/Math.pow(2,32),o[i-1][14]=Math.floor(o[i-1][14]),o[i-1][15]=(n.length-1)*8&4294967295;for(var d=0;d<i;++d){for(var h=new Uint32Array(80),f=0;f<16;++f)h[f]=o[d][f];for(var m=16;m<80;++m)h[m]=Fa(h[m-3]^h[m-8]^h[m-14]^h[m-16],1);for(var p=t[0],g=t[1],y=t[2],b=t[3],_=t[4],w=0;w<80;++w){var v=Math.floor(w/20),S=Fa(p,5)+Gm(v,g,y,b)+_+e[v]+h[w]>>>0;_=b,b=y,y=Fa(g,30)>>>0,g=p,p=S}t[0]=t[0]+p>>>0,t[1]=t[1]+g>>>0,t[2]=t[2]+y>>>0,t[3]=t[3]+b>>>0,t[4]=t[4]+_>>>0}return[t[0]>>24&255,t[0]>>16&255,t[0]>>8&255,t[0]&255,t[1]>>24&255,t[1]>>16&255,t[1]>>8&255,t[1]&255,t[2]>>24&255,t[2]>>16&255,t[2]>>8&255,t[2]&255,t[3]>>24&255,t[3]>>16&255,t[3]>>8&255,t[3]&255,t[4]>>24&255,t[4]>>16&255,t[4]>>8&255,t[4]&255]}var su=zm("v5",80,Wm);const Jm="gen_ai.operation.name",Zm="gen_ai.system",iu="gen_ai.request.model",Km="gen_ai.response.model",ou="gen_ai.usage.input_tokens",uu="gen_ai.usage.output_tokens",cu="gen_ai.usage.total_tokens",Vm="gen_ai.request.max_tokens",Xm="gen_ai.request.temperature",Qm="gen_ai.request.top_p",Ym="gen_ai.request.frequency_penalty",ep="gen_ai.request.presence_penalty",tp="gen_ai.response.finish_reasons",rp="gen_ai.prompt",np="gen_ai.completion",ap="gen_ai.request.extra_query",sp="gen_ai.request.extra_body",ip="gen_ai.serialized.name",op="gen_ai.serialized.signature",up="gen_ai.serialized.doc",cp="gen_ai.response.id",lp="gen_ai.response.service_tier",dp="gen_ai.response.system_fingerprint",hp="gen_ai.usage.input_token_details",fp="gen_ai.usage.output_token_details",mp="langsmith.trace.session_id",pp="langsmith.trace.session_name",gp="langsmith.span.kind",yp="langsmith.trace.name",_p="langsmith.metadata",lu="langsmith.span.tags",bp="langsmith.request.streaming",wp="langsmith.request.headers",vp=(...n)=>fetch(...n),Sd=Symbol.for("ls:fetch_implementation"),Ep=()=>{const n=globalThis[Sd];return n?typeof n=="function"&&"Headers"in n&&"Request"in n&&"Response"in n:!1},Sp=n=>async(...e)=>{if(n||xe("DEBUG")==="true"){const[r,a]=e;console.log(`→ ${(a==null?void 0:a.method)||"GET"} ${r}`)}const t=await(globalThis[Sd]??vp)(...e);return(n||xe("DEBUG")==="true")&&console.log(`← ${t.status} ${t.statusText} ${t.url}`),t},Od=()=>xe("PROJECT")??rt("LANGCHAIN_SESSION")??"default",Td="0.3.73";var Tr={};let Xe;const Op=()=>typeof window<"u"&&typeof window.document<"u",Tp=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Ap=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Ad=()=>typeof Deno<"u",Pp=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Ad(),Pd=()=>Xe||(typeof Bun<"u"?Xe="bun":Op()?Xe="browser":Pp()?Xe="node":Tp()?Xe="webworker":Ap()?Xe="jsdom":Ad()?Xe="deno":Xe="other",Xe);let Da;function xd(){if(Da===void 0){const n=Pd(),e=Ip();Da={library:"langsmith",runtime:n,sdk:"langsmith-js",sdk_version:Td,...e}}return Da}function Id(){const n=xp(),e={},t=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[r,a]of Object.entries(n))typeof a=="string"&&!t.includes(r)&&!r.toLowerCase().includes("key")&&!r.toLowerCase().includes("secret")&&!r.toLowerCase().includes("token")&&(r==="LANGCHAIN_REVISION_ID"?e.revision_id=a:e[r]=a);return e}function xp(){const n={};try{if(typeof process<"u"&&Tr)for(const[e,t]of Object.entries(Tr))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&t!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof t=="string"?n[e]=t.slice(0,2)+"*".repeat(t.length-4)+t.slice(-2):n[e]=t)}catch{}return n}function rt(n){try{return typeof process<"u"?Tr==null?void 0:Tr[n]:void 0}catch{return}}function xe(n){return rt(`LANGSMITH_${n}`)||rt(`LANGCHAIN_${n}`)}let Ba;function Ip(){if(Ba!==void 0)return Ba;const n=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(const t of n){const r=rt(t);r!==void 0&&(e[t]=r)}return Ba=e,e}function Rd(){return rt("OTEL_ENABLED")==="true"||xe("OTEL_ENABLED")==="true"}class Rp{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){!this.hasWarned&&Rd()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let r;if(t.length===1&&typeof t[0]=="function"?r=t[0]:t.length===2&&typeof t[1]=="function"?r=t[1]:t.length===3&&typeof t[2]=="function"&&(r=t[2]),typeof r=="function")return r()}}class $p{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Rp})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}}class kp{active(){return{}}with(e,t){return t()}}const qa=Symbol.for("ls:otel_trace"),za=Symbol.for("ls:otel_context"),du=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Cp=new $p,Np=new kp;class jp{getTraceInstance(){return globalThis[qa]??Cp}getContextInstance(){return globalThis[za]??Np}initializeGlobalInstances(e){globalThis[qa]===void 0&&(globalThis[qa]=e.trace),globalThis[za]===void 0&&(globalThis[za]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[du]=e}getDefaultOTLPTracerComponents(){return globalThis[du]??void 0}}const Ki=new jp;function $d(){return Ki.getTraceInstance()}function Lp(){return Ki.getContextInstance()}function Mp(){return Ki.getDefaultOTLPTracerComponents()}const Up={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function Fp(n){return Up[n]||n}class Dp{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(const r of e)try{if(!r.run)continue;if(r.operation==="post"){const a=this.createSpanForRun(r,r.run,t.get(r.id));a&&!r.run.end_time&&this.spans.set(r.id,a)}else this.updateSpanForRun(r,r.run)}catch(a){console.error(`Error processing operation ${r.id}:`,a)}}createSpanForRun(e,t,r){const a=r&&$d().getSpan(r);if(a)try{return this.finishSpanSetup(a,t,e)}catch(s){console.error(`Failed to create span for run ${e.id}:`,s);return}}finishSpanSetup(e,t,r){return this.setSpanAttributes(e,t,r),t.error?(e.setStatus({code:2}),e.recordException(new Error(t.error))):e.setStatus({code:1}),t.end_time&&e.end(new Date(t.end_time)),e}updateSpanForRun(e,t){try{const r=this.spans.get(e.id);if(!r){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(r,t,e),t.error?(r.setStatus({code:2}),r.recordException(new Error(t.error))):r.setStatus({code:1});const a=t.end_time;a&&(r.end(new Date(a)),this.spans.delete(e.id))}catch(r){console.error(`Failed to update span for run ${e.id}:`,r)}}extractModelName(e){var t;if((t=e.extra)!=null&&t.metadata){const r=e.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){const a=r.invocation_params;if(a.model)return a.model;if(a.model_name)return a.model_name}}}setSpanAttributes(e,t,r){var o;if("run_type"in t&&t.run_type){e.setAttribute(gp,t.run_type);const u=Fp(t.run_type||"chain");e.setAttribute(Jm,u)}"name"in t&&t.name&&e.setAttribute(yp,t.name),"session_id"in t&&t.session_id&&e.setAttribute(mp,t.session_id),"session_name"in t&&t.session_name&&e.setAttribute(pp,t.session_name),this.setGenAiSystem(e,t);const a=this.extractModelName(t);a&&e.setAttribute(iu,a),"prompt_tokens"in t&&typeof t.prompt_tokens=="number"&&e.setAttribute(ou,t.prompt_tokens),"completion_tokens"in t&&typeof t.completion_tokens=="number"&&e.setAttribute(uu,t.completion_tokens),"total_tokens"in t&&typeof t.total_tokens=="number"&&e.setAttribute(cu,t.total_tokens),this.setInvocationParameters(e,t);const s=((o=t.extra)==null?void 0:o.metadata)||{};for(const[u,c]of Object.entries(s))c!=null&&e.setAttribute(`${_p}.${u}`,String(c));const i=t.tags;if(i&&Array.isArray(i)?e.setAttribute(lu,i.join(", ")):i&&e.setAttribute(lu,String(i)),"serialized"in t&&typeof t.serialized=="object"){const u=t.serialized;u.name&&e.setAttribute(ip,String(u.name)),u.signature&&e.setAttribute(op,String(u.signature)),u.doc&&e.setAttribute(up,String(u.doc))}this.setIOAttributes(e,r)}setGenAiSystem(e,t){let r="langchain";const a=this.extractModelName(t);if(a){const s=a.toLowerCase();s.includes("anthropic")||s.startsWith("claude")?r="anthropic":s.includes("bedrock")?r="aws.bedrock":s.includes("azure")&&s.includes("openai")?r="az.ai.openai":s.includes("azure")&&s.includes("inference")?r="az.ai.inference":s.includes("cohere")?r="cohere":s.includes("deepseek")?r="deepseek":s.includes("gemini")?r="gemini":s.includes("groq")?r="groq":s.includes("watson")||s.includes("ibm")?r="ibm.watsonx.ai":s.includes("mistral")?r="mistral_ai":s.includes("gpt")||s.includes("openai")?r="openai":s.includes("perplexity")||s.includes("sonar")?r="perplexity":s.includes("vertex")?r="vertex_ai":(s.includes("xai")||s.includes("grok"))&&(r="xai")}e.setAttribute(Zm,r)}setInvocationParameters(e,t){var a,s;if(!((s=(a=t.extra)==null?void 0:a.metadata)!=null&&s.invocation_params))return;const r=t.extra.metadata.invocation_params;r.max_tokens!==void 0&&e.setAttribute(Vm,r.max_tokens),r.temperature!==void 0&&e.setAttribute(Xm,r.temperature),r.top_p!==void 0&&e.setAttribute(Qm,r.top_p),r.frequency_penalty!==void 0&&e.setAttribute(Ym,r.frequency_penalty),r.presence_penalty!==void 0&&e.setAttribute(ep,r.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{const r=t.run.inputs;typeof r=="object"&&r!==null&&(r.model&&Array.isArray(r.messages)&&e.setAttribute(iu,r.model),r.stream!==void 0&&e.setAttribute(bp,r.stream),r.extra_headers&&e.setAttribute(wp,JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute(ap,JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute(sp,JSON.stringify(r.extra_body))),e.setAttribute(rp,JSON.stringify(r))}catch(r){console.debug(`Failed to process inputs for run ${t.id}`,r)}if(t.run.outputs)try{const r=t.run.outputs,a=this.getUnifiedRunTokens(r);if(a&&(e.setAttribute(ou,a[0]),e.setAttribute(uu,a[1]),e.setAttribute(cu,a[0]+a[1])),r&&typeof r=="object"){if(r.model&&e.setAttribute(Km,String(r.model)),r.id&&e.setAttribute(cp,r.id),r.choices&&Array.isArray(r.choices)){const s=r.choices.map(i=>i.finish_reason).filter(i=>i).map(String);s.length>0&&e.setAttribute(tp,s.join(", "))}if(r.service_tier&&e.setAttribute(lp,r.service_tier),r.system_fingerprint&&e.setAttribute(dp,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){const s=r.usage_metadata;s.input_token_details&&e.setAttribute(hp,JSON.stringify(s.input_token_details)),s.output_token_details&&e.setAttribute(fp,JSON.stringify(s.output_token_details))}}e.setAttribute(np,JSON.stringify(r))}catch(r){console.debug(`Failed to process outputs for run ${t.id}`,r)}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;const r=Object.keys(e);for(const i of r){const o=e[i];if(!(!o||typeof o!="object")&&(t=this.extractUnifiedRunTokens(o.usage_metadata),t||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(t=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),t)))return t}const a=e.generations||[];if(!Array.isArray(a))return null;const s=Array.isArray(a[0])?a.flat():a;for(const i of s)if(typeof i=="object"&&i.message&&typeof i.message=="object"&&i.message.kwargs&&typeof i.message.kwargs=="object"&&(t=this.extractUnifiedRunTokens(i.message.kwargs.usage_metadata),t))return t;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}}var rn={},Ha={exports:{}},hu;function Bp(){return hu||(hu=1,(function(n){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function a(u,c,l){this.fn=u,this.context=c,this.once=l||!1}function s(u,c,l,d,h){if(typeof l!="function")throw new TypeError("The listener must be a function");var f=new a(l,d||u,h),m=t?t+c:c;return u._events[m]?u._events[m].fn?u._events[m]=[u._events[m],f]:u._events[m].push(f):(u._events[m]=f,u._eventsCount++),u}function i(u,c){--u._eventsCount===0?u._events=new r:delete u._events[c]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],l,d;if(this._eventsCount===0)return c;for(d in l=this._events)e.call(l,d)&&c.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(l)):c},o.prototype.listeners=function(c){var l=t?t+c:c,d=this._events[l];if(!d)return[];if(d.fn)return[d.fn];for(var h=0,f=d.length,m=new Array(f);h<f;h++)m[h]=d[h].fn;return m},o.prototype.listenerCount=function(c){var l=t?t+c:c,d=this._events[l];return d?d.fn?1:d.length:0},o.prototype.emit=function(c,l,d,h,f,m){var p=t?t+c:c;if(!this._events[p])return!1;var g=this._events[p],y=arguments.length,b,_;if(g.fn){switch(g.once&&this.removeListener(c,g.fn,void 0,!0),y){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,l),!0;case 3:return g.fn.call(g.context,l,d),!0;case 4:return g.fn.call(g.context,l,d,h),!0;case 5:return g.fn.call(g.context,l,d,h,f),!0;case 6:return g.fn.call(g.context,l,d,h,f,m),!0}for(_=1,b=new Array(y-1);_<y;_++)b[_-1]=arguments[_];g.fn.apply(g.context,b)}else{var w=g.length,v;for(_=0;_<w;_++)switch(g[_].once&&this.removeListener(c,g[_].fn,void 0,!0),y){case 1:g[_].fn.call(g[_].context);break;case 2:g[_].fn.call(g[_].context,l);break;case 3:g[_].fn.call(g[_].context,l,d);break;case 4:g[_].fn.call(g[_].context,l,d,h);break;default:if(!b)for(v=1,b=new Array(y-1);v<y;v++)b[v-1]=arguments[v];g[_].fn.apply(g[_].context,b)}}return!0},o.prototype.on=function(c,l,d){return s(this,c,l,d,!1)},o.prototype.once=function(c,l,d){return s(this,c,l,d,!0)},o.prototype.removeListener=function(c,l,d,h){var f=t?t+c:c;if(!this._events[f])return this;if(!l)return i(this,f),this;var m=this._events[f];if(m.fn)m.fn===l&&(!h||m.once)&&(!d||m.context===d)&&i(this,f);else{for(var p=0,g=[],y=m.length;p<y;p++)(m[p].fn!==l||h&&!m[p].once||d&&m[p].context!==d)&&g.push(m[p]);g.length?this._events[f]=g.length===1?g[0]:g:i(this,f)}return this},o.prototype.removeAllListeners=function(c){var l;return c?(l=t?t+c:c,this._events[l]&&i(this,l)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,n.exports=o})(Ha)),Ha.exports}var ir={exports:{}},Ga,fu;function qp(){return fu||(fu=1,Ga=(n,e)=>(e=e||(()=>{}),n.then(t=>new Promise(r=>{r(e())}).then(()=>t),t=>new Promise(r=>{r(e())}).then(()=>{throw t})))),Ga}var mu;function zp(){if(mu)return ir.exports;mu=1;const n=qp();class e extends Error{constructor(a){super(a),this.name="TimeoutError"}}const t=(r,a,s)=>new Promise((i,o)=>{if(typeof a!="number"||a<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(a===1/0){i(r);return}const u=setTimeout(()=>{if(typeof s=="function"){try{i(s())}catch(d){o(d)}return}const c=typeof s=="string"?s:`Promise timed out after ${a} milliseconds`,l=s instanceof Error?s:new e(c);typeof r.cancel=="function"&&r.cancel(),o(l)},a);n(r.then(i,o),()=>{clearTimeout(u)})});return ir.exports=t,ir.exports.default=t,ir.exports.TimeoutError=e,ir.exports}var nn={},an={},pu;function Hp(){if(pu)return an;pu=1,Object.defineProperty(an,"__esModule",{value:!0});function n(e,t,r){let a=0,s=e.length;for(;s>0;){const i=s/2|0;let o=a+i;r(e[o],t)<=0?(a=++o,s-=i+1):s=i}return a}return an.default=n,an}var gu;function Gp(){if(gu)return nn;gu=1,Object.defineProperty(nn,"__esModule",{value:!0});const n=Hp();class e{constructor(){this._queue=[]}enqueue(r,a){a=Object.assign({priority:0},a);const s={priority:a.priority,run:r};if(this.size&&this._queue[this.size-1].priority>=a.priority){this._queue.push(s);return}const i=n.default(this._queue,s,(o,u)=>u.priority-o.priority);this._queue.splice(i,0,s)}dequeue(){const r=this._queue.shift();return r==null?void 0:r.run}filter(r){return this._queue.filter(a=>a.priority===r.priority).map(a=>a.run)}get size(){return this._queue.length}}return nn.default=e,nn}var yu;function Wp(){if(yu)return rn;yu=1,Object.defineProperty(rn,"__esModule",{value:!0});const n=Bp(),e=zp(),t=Gp(),r=()=>{},a=new e.TimeoutError;class s extends n{constructor(o){var u,c,l,d;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=r,this._resolveIdle=r,o=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:t.default},o),!(typeof o.intervalCap=="number"&&o.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(c=(u=o.intervalCap)===null||u===void 0?void 0:u.toString())!==null&&c!==void 0?c:""}\` (${typeof o.intervalCap})`);if(o.interval===void 0||!(Number.isFinite(o.interval)&&o.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(d=(l=o.interval)===null||l===void 0?void 0:l.toString())!==null&&d!==void 0?d:""}\` (${typeof o.interval})`);this._carryoverConcurrencyCount=o.carryoverConcurrencyCount,this._isIntervalIgnored=o.intervalCap===1/0||o.interval===0,this._intervalCap=o.intervalCap,this._interval=o.interval,this._queue=new o.queueClass,this._queueClass=o.queueClass,this.concurrency=o.concurrency,this._timeout=o.timeout,this._throwOnTimeout=o.throwOnTimeout===!0,this._isPaused=o.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=r,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=r,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const o=Date.now();if(this._intervalId===void 0){const u=this._intervalEnd-o;if(u<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},u)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const o=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const u=this._queue.dequeue();return u?(this.emit("active"),u(),o&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(o){if(!(typeof o=="number"&&o>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${o}\` (${typeof o})`);this._concurrency=o,this._processQueue()}async add(o,u={}){return new Promise((c,l)=>{const d=async()=>{this._pendingCount++,this._intervalCount++;try{const h=this._timeout===void 0&&u.timeout===void 0?o():e.default(Promise.resolve(o()),u.timeout===void 0?this._timeout:u.timeout,()=>{(u.throwOnTimeout===void 0?this._throwOnTimeout:u.throwOnTimeout)&&l(a)});c(await h)}catch(h){l(h)}this._next()};this._queue.enqueue(d,u),this._tryToStartAnother(),this.emit("add")})}async addAll(o,u){return Promise.all(o.map(async c=>this.add(c,u)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(o=>{const u=this._resolveEmpty;this._resolveEmpty=()=>{u(),o()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(o=>{const u=this._resolveIdle;this._resolveIdle=()=>{u(),o()}})}get size(){return this._queue.size}sizeBy(o){return this._queue.filter(o).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(o){this._timeout=o}}return rn.default=s,rn}var Jp=Wp();const ut=Lr(Jp),Zp=[429,500,502,503,504];let _u=class{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,"default"in ut?this.queue=new ut.default({concurrency:this.maxConcurrency}):this.queue=new ut({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e==null?void 0:e.onFailedResponseHook}call(e,...t){const r=this.onFailedResponseHook;return this.queue.add(()=>Cn(()=>e(...t).catch(a=>{throw a instanceof Error?a:new Error(a)}),{async onFailedAttempt(a){if(a.message.startsWith("Cancel")||a.message.startsWith("TimeoutError")||a.name==="TimeoutError"||a.message.startsWith("AbortError")||(a==null?void 0:a.code)==="ECONNABORTED")throw a;const s=a==null?void 0:a.response;if(r&&await r(s))return;const i=(s==null?void 0:s.status)??(a==null?void 0:a.status);if(i&&!Zp.includes(+i))throw a},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise((a,s)=>{var i;(i=e.signal)==null||i.addEventListener("abort",()=>{s(new Error("AbortError"))})})]):this.call(t,...r)}};function bu(n){return typeof(n==null?void 0:n._getType)=="function"}function wu(n){const e={type:n._getType(),data:{content:n.content}};return n!=null&&n.additional_kwargs&&Object.keys(n.additional_kwargs).length>0&&(e.data.additional_kwargs={...n.additional_kwargs}),e}const Kp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function B(n,e){if(!Kp.test(n)){const t=e!==void 0?`Invalid UUID for ${e}: ${n}`:`Invalid UUID: ${n}`;throw new Error(t)}return n}const vu={};function kd(n){vu[n]||(console.warn(n),vu[n]=!0)}var sn={exports:{}},Wa,Eu;function oa(){if(Eu)return Wa;Eu=1;const n="2.0.0",e=256,t=Number.MAX_SAFE_INTEGER||9007199254740991,r=16,a=e-6;return Wa={MAX_LENGTH:e,MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:a,MAX_SAFE_INTEGER:t,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:n,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},Wa}var Ja,Su;function ua(){if(Su)return Ja;Su=1;var n={};return Ja=typeof process=="object"&&n&&n.NODE_DEBUG&&/\bsemver\b/i.test(n.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{},Ja}var Ou;function zr(){return Ou||(Ou=1,(function(n,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:a}=oa(),s=ua();e=n.exports={};const i=e.re=[],o=e.safeRe=[],u=e.src=[],c=e.safeSrc=[],l=e.t={};let d=0;const h="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",a],[h,r]],m=g=>{for(const[y,b]of f)g=g.split(`${y}*`).join(`${y}{0,${b}}`).split(`${y}+`).join(`${y}{1,${b}}`);return g},p=(g,y,b)=>{const _=m(y),w=d++;s(g,w,y),l[g]=w,u[w]=y,c[w]=_,i[w]=new RegExp(y,b?"g":void 0),o[w]=new RegExp(_,b?"g":void 0)};p("NUMERICIDENTIFIER","0|[1-9]\\d*"),p("NUMERICIDENTIFIERLOOSE","\\d+"),p("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`),p("MAINVERSION",`(${u[l.NUMERICIDENTIFIER]})\\.(${u[l.NUMERICIDENTIFIER]})\\.(${u[l.NUMERICIDENTIFIER]})`),p("MAINVERSIONLOOSE",`(${u[l.NUMERICIDENTIFIERLOOSE]})\\.(${u[l.NUMERICIDENTIFIERLOOSE]})\\.(${u[l.NUMERICIDENTIFIERLOOSE]})`),p("PRERELEASEIDENTIFIER",`(?:${u[l.NONNUMERICIDENTIFIER]}|${u[l.NUMERICIDENTIFIER]})`),p("PRERELEASEIDENTIFIERLOOSE",`(?:${u[l.NONNUMERICIDENTIFIER]}|${u[l.NUMERICIDENTIFIERLOOSE]})`),p("PRERELEASE",`(?:-(${u[l.PRERELEASEIDENTIFIER]}(?:\\.${u[l.PRERELEASEIDENTIFIER]})*))`),p("PRERELEASELOOSE",`(?:-?(${u[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${u[l.PRERELEASEIDENTIFIERLOOSE]})*))`),p("BUILDIDENTIFIER",`${h}+`),p("BUILD",`(?:\\+(${u[l.BUILDIDENTIFIER]}(?:\\.${u[l.BUILDIDENTIFIER]})*))`),p("FULLPLAIN",`v?${u[l.MAINVERSION]}${u[l.PRERELEASE]}?${u[l.BUILD]}?`),p("FULL",`^${u[l.FULLPLAIN]}$`),p("LOOSEPLAIN",`[v=\\s]*${u[l.MAINVERSIONLOOSE]}${u[l.PRERELEASELOOSE]}?${u[l.BUILD]}?`),p("LOOSE",`^${u[l.LOOSEPLAIN]}$`),p("GTLT","((?:<|>)?=?)"),p("XRANGEIDENTIFIERLOOSE",`${u[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),p("XRANGEIDENTIFIER",`${u[l.NUMERICIDENTIFIER]}|x|X|\\*`),p("XRANGEPLAIN",`[v=\\s]*(${u[l.XRANGEIDENTIFIER]})(?:\\.(${u[l.XRANGEIDENTIFIER]})(?:\\.(${u[l.XRANGEIDENTIFIER]})(?:${u[l.PRERELEASE]})?${u[l.BUILD]}?)?)?`),p("XRANGEPLAINLOOSE",`[v=\\s]*(${u[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${u[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${u[l.XRANGEIDENTIFIERLOOSE]})(?:${u[l.PRERELEASELOOSE]})?${u[l.BUILD]}?)?)?`),p("XRANGE",`^${u[l.GTLT]}\\s*${u[l.XRANGEPLAIN]}$`),p("XRANGELOOSE",`^${u[l.GTLT]}\\s*${u[l.XRANGEPLAINLOOSE]}$`),p("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),p("COERCE",`${u[l.COERCEPLAIN]}(?:$|[^\\d])`),p("COERCEFULL",u[l.COERCEPLAIN]+`(?:${u[l.PRERELEASE]})?(?:${u[l.BUILD]})?(?:$|[^\\d])`),p("COERCERTL",u[l.COERCE],!0),p("COERCERTLFULL",u[l.COERCEFULL],!0),p("LONETILDE","(?:~>?)"),p("TILDETRIM",`(\\s*)${u[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",p("TILDE",`^${u[l.LONETILDE]}${u[l.XRANGEPLAIN]}$`),p("TILDELOOSE",`^${u[l.LONETILDE]}${u[l.XRANGEPLAINLOOSE]}$`),p("LONECARET","(?:\\^)"),p("CARETTRIM",`(\\s*)${u[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",p("CARET",`^${u[l.LONECARET]}${u[l.XRANGEPLAIN]}$`),p("CARETLOOSE",`^${u[l.LONECARET]}${u[l.XRANGEPLAINLOOSE]}$`),p("COMPARATORLOOSE",`^${u[l.GTLT]}\\s*(${u[l.LOOSEPLAIN]})$|^$`),p("COMPARATOR",`^${u[l.GTLT]}\\s*(${u[l.FULLPLAIN]})$|^$`),p("COMPARATORTRIM",`(\\s*)${u[l.GTLT]}\\s*(${u[l.LOOSEPLAIN]}|${u[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",p("HYPHENRANGE",`^\\s*(${u[l.XRANGEPLAIN]})\\s+-\\s+(${u[l.XRANGEPLAIN]})\\s*$`),p("HYPHENRANGELOOSE",`^\\s*(${u[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${u[l.XRANGEPLAINLOOSE]})\\s*$`),p("STAR","(<|>)?=?\\s*\\*"),p("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),p("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(sn,sn.exports)),sn.exports}var Za,Tu;function Vi(){if(Tu)return Za;Tu=1;const n=Object.freeze({loose:!0}),e=Object.freeze({});return Za=r=>r?typeof r!="object"?n:r:e,Za}var Ka,Au;function Cd(){if(Au)return Ka;Au=1;const n=/^[0-9]+$/,e=(r,a)=>{if(typeof r=="number"&&typeof a=="number")return r===a?0:r<a?-1:1;const s=n.test(r),i=n.test(a);return s&&i&&(r=+r,a=+a),r===a?0:s&&!i?-1:i&&!s?1:r<a?-1:1};return Ka={compareIdentifiers:e,rcompareIdentifiers:(r,a)=>e(a,r)},Ka}var Va,Pu;function Oe(){if(Pu)return Va;Pu=1;const n=ua(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:t}=oa(),{safeRe:r,t:a}=zr(),s=Vi(),{compareIdentifiers:i}=Cd();class o{constructor(c,l){if(l=s(l),c instanceof o){if(c.loose===!!l.loose&&c.includePrerelease===!!l.includePrerelease)return c;c=c.version}else if(typeof c!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof c}".`);if(c.length>e)throw new TypeError(`version is longer than ${e} characters`);n("SemVer",c,l),this.options=l,this.loose=!!l.loose,this.includePrerelease=!!l.includePrerelease;const d=c.trim().match(l.loose?r[a.LOOSE]:r[a.FULL]);if(!d)throw new TypeError(`Invalid Version: ${c}`);if(this.raw=c,this.major=+d[1],this.minor=+d[2],this.patch=+d[3],this.major>t||this.major<0)throw new TypeError("Invalid major version");if(this.minor>t||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>t||this.patch<0)throw new TypeError("Invalid patch version");d[4]?this.prerelease=d[4].split(".").map(h=>{if(/^[0-9]+$/.test(h)){const f=+h;if(f>=0&&f<t)return f}return h}):this.prerelease=[],this.build=d[5]?d[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(c){if(n("SemVer.compare",this.version,this.options,c),!(c instanceof o)){if(typeof c=="string"&&c===this.version)return 0;c=new o(c,this.options)}return c.version===this.version?0:this.compareMain(c)||this.comparePre(c)}compareMain(c){return c instanceof o||(c=new o(c,this.options)),this.major<c.major?-1:this.major>c.major?1:this.minor<c.minor?-1:this.minor>c.minor?1:this.patch<c.patch?-1:this.patch>c.patch?1:0}comparePre(c){if(c instanceof o||(c=new o(c,this.options)),this.prerelease.length&&!c.prerelease.length)return-1;if(!this.prerelease.length&&c.prerelease.length)return 1;if(!this.prerelease.length&&!c.prerelease.length)return 0;let l=0;do{const d=this.prerelease[l],h=c.prerelease[l];if(n("prerelease compare",l,d,h),d===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(d===void 0)return-1;if(d===h)continue;return i(d,h)}while(++l)}compareBuild(c){c instanceof o||(c=new o(c,this.options));let l=0;do{const d=this.build[l],h=c.build[l];if(n("build compare",l,d,h),d===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(d===void 0)return-1;if(d===h)continue;return i(d,h)}while(++l)}inc(c,l,d){if(c.startsWith("pre")){if(!l&&d===!1)throw new Error("invalid increment argument: identifier is empty");if(l){const h=`-${l}`.match(this.options.loose?r[a.PRERELEASELOOSE]:r[a.PRERELEASE]);if(!h||h[1]!==l)throw new Error(`invalid identifier: ${l}`)}}switch(c){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",l,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",l,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",l,d),this.inc("pre",l,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",l,d),this.inc("pre",l,d);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const h=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[h];else{let f=this.prerelease.length;for(;--f>=0;)typeof this.prerelease[f]=="number"&&(this.prerelease[f]++,f=-2);if(f===-1){if(l===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(h)}}if(l){let f=[l,h];d===!1&&(f=[l]),i(this.prerelease[0],l)===0?isNaN(this.prerelease[1])&&(this.prerelease=f):this.prerelease=f}break}default:throw new Error(`invalid increment argument: ${c}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return Va=o,Va}var Xa,xu;function er(){if(xu)return Xa;xu=1;const n=Oe();return Xa=(t,r,a=!1)=>{if(t instanceof n)return t;try{return new n(t,r)}catch(s){if(!a)return null;throw s}},Xa}var Qa,Iu;function Vp(){if(Iu)return Qa;Iu=1;const n=er();return Qa=(t,r)=>{const a=n(t,r);return a?a.version:null},Qa}var Ya,Ru;function Xp(){if(Ru)return Ya;Ru=1;const n=er();return Ya=(t,r)=>{const a=n(t.trim().replace(/^[=v]+/,""),r);return a?a.version:null},Ya}var es,$u;function Qp(){if($u)return es;$u=1;const n=Oe();return es=(t,r,a,s,i)=>{typeof a=="string"&&(i=s,s=a,a=void 0);try{return new n(t instanceof n?t.version:t,a).inc(r,s,i).version}catch{return null}},es}var ts,ku;function Yp(){if(ku)return ts;ku=1;const n=er();return ts=(t,r)=>{const a=n(t,null,!0),s=n(r,null,!0),i=a.compare(s);if(i===0)return null;const o=i>0,u=o?a:s,c=o?s:a,l=!!u.prerelease.length;if(!!c.prerelease.length&&!l){if(!c.patch&&!c.minor)return"major";if(c.compareMain(u)===0)return c.minor&&!c.patch?"minor":"patch"}const h=l?"pre":"";return a.major!==s.major?h+"major":a.minor!==s.minor?h+"minor":a.patch!==s.patch?h+"patch":"prerelease"},ts}var rs,Cu;function eg(){if(Cu)return rs;Cu=1;const n=Oe();return rs=(t,r)=>new n(t,r).major,rs}var ns,Nu;function tg(){if(Nu)return ns;Nu=1;const n=Oe();return ns=(t,r)=>new n(t,r).minor,ns}var as,ju;function rg(){if(ju)return as;ju=1;const n=Oe();return as=(t,r)=>new n(t,r).patch,as}var ss,Lu;function ng(){if(Lu)return ss;Lu=1;const n=er();return ss=(t,r)=>{const a=n(t,r);return a&&a.prerelease.length?a.prerelease:null},ss}var is,Mu;function We(){if(Mu)return is;Mu=1;const n=Oe();return is=(t,r,a)=>new n(t,a).compare(new n(r,a)),is}var os,Uu;function ag(){if(Uu)return os;Uu=1;const n=We();return os=(t,r,a)=>n(r,t,a),os}var us,Fu;function sg(){if(Fu)return us;Fu=1;const n=We();return us=(t,r)=>n(t,r,!0),us}var cs,Du;function Xi(){if(Du)return cs;Du=1;const n=Oe();return cs=(t,r,a)=>{const s=new n(t,a),i=new n(r,a);return s.compare(i)||s.compareBuild(i)},cs}var ls,Bu;function ig(){if(Bu)return ls;Bu=1;const n=Xi();return ls=(t,r)=>t.sort((a,s)=>n(a,s,r)),ls}var ds,qu;function og(){if(qu)return ds;qu=1;const n=Xi();return ds=(t,r)=>t.sort((a,s)=>n(s,a,r)),ds}var hs,zu;function ca(){if(zu)return hs;zu=1;const n=We();return hs=(t,r,a)=>n(t,r,a)>0,hs}var fs,Hu;function Qi(){if(Hu)return fs;Hu=1;const n=We();return fs=(t,r,a)=>n(t,r,a)<0,fs}var ms,Gu;function Nd(){if(Gu)return ms;Gu=1;const n=We();return ms=(t,r,a)=>n(t,r,a)===0,ms}var ps,Wu;function jd(){if(Wu)return ps;Wu=1;const n=We();return ps=(t,r,a)=>n(t,r,a)!==0,ps}var gs,Ju;function Yi(){if(Ju)return gs;Ju=1;const n=We();return gs=(t,r,a)=>n(t,r,a)>=0,gs}var ys,Zu;function eo(){if(Zu)return ys;Zu=1;const n=We();return ys=(t,r,a)=>n(t,r,a)<=0,ys}var _s,Ku;function Ld(){if(Ku)return _s;Ku=1;const n=Nd(),e=jd(),t=ca(),r=Yi(),a=Qi(),s=eo();return _s=(o,u,c,l)=>{switch(u){case"===":return typeof o=="object"&&(o=o.version),typeof c=="object"&&(c=c.version),o===c;case"!==":return typeof o=="object"&&(o=o.version),typeof c=="object"&&(c=c.version),o!==c;case"":case"=":case"==":return n(o,c,l);case"!=":return e(o,c,l);case">":return t(o,c,l);case">=":return r(o,c,l);case"<":return a(o,c,l);case"<=":return s(o,c,l);default:throw new TypeError(`Invalid operator: ${u}`)}},_s}var bs,Vu;function ug(){if(Vu)return bs;Vu=1;const n=Oe(),e=er(),{safeRe:t,t:r}=zr();return bs=(s,i)=>{if(s instanceof n)return s;if(typeof s=="number"&&(s=String(s)),typeof s!="string")return null;i=i||{};let o=null;if(!i.rtl)o=s.match(i.includePrerelease?t[r.COERCEFULL]:t[r.COERCE]);else{const f=i.includePrerelease?t[r.COERCERTLFULL]:t[r.COERCERTL];let m;for(;(m=f.exec(s))&&(!o||o.index+o[0].length!==s.length);)(!o||m.index+m[0].length!==o.index+o[0].length)&&(o=m),f.lastIndex=m.index+m[1].length+m[2].length;f.lastIndex=-1}if(o===null)return null;const u=o[2],c=o[3]||"0",l=o[4]||"0",d=i.includePrerelease&&o[5]?`-${o[5]}`:"",h=i.includePrerelease&&o[6]?`+${o[6]}`:"";return e(`${u}.${c}.${l}${d}${h}`,i)},bs}var ws,Xu;function cg(){if(Xu)return ws;Xu=1;class n{constructor(){this.max=1e3,this.map=new Map}get(t){const r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){const s=this.map.keys().next().value;this.delete(s)}this.map.set(t,r)}return this}}return ws=n,ws}var vs,Qu;function Je(){if(Qu)return vs;Qu=1;const n=/\s+/g;class e{constructor(A,j){if(j=a(j),A instanceof e)return A.loose===!!j.loose&&A.includePrerelease===!!j.includePrerelease?A:new e(A.raw,j);if(A instanceof s)return this.raw=A.value,this.set=[[A]],this.formatted=void 0,this;if(this.options=j,this.loose=!!j.loose,this.includePrerelease=!!j.includePrerelease,this.raw=A.trim().replace(n," "),this.set=this.raw.split("||").map(R=>this.parseRange(R.trim())).filter(R=>R.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const R=this.set[0];if(this.set=this.set.filter(L=>!p(L[0])),this.set.length===0)this.set=[R];else if(this.set.length>1){for(const L of this.set)if(L.length===1&&g(L[0])){this.set=[L];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let A=0;A<this.set.length;A++){A>0&&(this.formatted+="||");const j=this.set[A];for(let R=0;R<j.length;R++)R>0&&(this.formatted+=" "),this.formatted+=j[R].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(A){const R=((this.options.includePrerelease&&f)|(this.options.loose&&m))+":"+A,L=r.get(R);if(L)return L;const $=this.options.loose,D=$?u[c.HYPHENRANGELOOSE]:u[c.HYPHENRANGE];A=A.replace(D,oe(this.options.includePrerelease)),i("hyphen replace",A),A=A.replace(u[c.COMPARATORTRIM],l),i("comparator trim",A),A=A.replace(u[c.TILDETRIM],d),i("tilde trim",A),A=A.replace(u[c.CARETTRIM],h),i("caret trim",A);let J=A.split(" ").map(ee=>b(ee,this.options)).join(" ").split(/\s+/).map(ee=>z(ee,this.options));$&&(J=J.filter(ee=>(i("loose invalid filter",ee,this.options),!!ee.match(u[c.COMPARATORLOOSE])))),i("range list",J);const q=new Map,Y=J.map(ee=>new s(ee,this.options));for(const ee of Y){if(p(ee))return[ee];q.set(ee.value,ee)}q.size>1&&q.has("")&&q.delete("");const ue=[...q.values()];return r.set(R,ue),ue}intersects(A,j){if(!(A instanceof e))throw new TypeError("a Range is required");return this.set.some(R=>y(R,j)&&A.set.some(L=>y(L,j)&&R.every($=>L.every(D=>$.intersects(D,j)))))}test(A){if(!A)return!1;if(typeof A=="string")try{A=new o(A,this.options)}catch{return!1}for(let j=0;j<this.set.length;j++)if(Ke(this.set[j],A,this.options))return!0;return!1}}vs=e;const t=cg(),r=new t,a=Vi(),s=la(),i=ua(),o=Oe(),{safeRe:u,t:c,comparatorTrimReplace:l,tildeTrimReplace:d,caretTrimReplace:h}=zr(),{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:m}=oa(),p=I=>I.value==="<0.0.0-0",g=I=>I.value==="",y=(I,A)=>{let j=!0;const R=I.slice();let L=R.pop();for(;j&&R.length;)j=R.every($=>L.intersects($,A)),L=R.pop();return j},b=(I,A)=>(I=I.replace(u[c.BUILD],""),i("comp",I,A),I=S(I,A),i("caret",I),I=w(I,A),i("tildes",I),I=T(I,A),i("xrange",I),I=G(I,A),i("stars",I),I),_=I=>!I||I.toLowerCase()==="x"||I==="*",w=(I,A)=>I.trim().split(/\s+/).map(j=>v(j,A)).join(" "),v=(I,A)=>{const j=A.loose?u[c.TILDELOOSE]:u[c.TILDE];return I.replace(j,(R,L,$,D,J)=>{i("tilde",I,R,L,$,D,J);let q;return _(L)?q="":_($)?q=`>=${L}.0.0 <${+L+1}.0.0-0`:_(D)?q=`>=${L}.${$}.0 <${L}.${+$+1}.0-0`:J?(i("replaceTilde pr",J),q=`>=${L}.${$}.${D}-${J} <${L}.${+$+1}.0-0`):q=`>=${L}.${$}.${D} <${L}.${+$+1}.0-0`,i("tilde return",q),q})},S=(I,A)=>I.trim().split(/\s+/).map(j=>O(j,A)).join(" "),O=(I,A)=>{i("caret",I,A);const j=A.loose?u[c.CARETLOOSE]:u[c.CARET],R=A.includePrerelease?"-0":"";return I.replace(j,(L,$,D,J,q)=>{i("caret",I,L,$,D,J,q);let Y;return _($)?Y="":_(D)?Y=`>=${$}.0.0${R} <${+$+1}.0.0-0`:_(J)?$==="0"?Y=`>=${$}.${D}.0${R} <${$}.${+D+1}.0-0`:Y=`>=${$}.${D}.0${R} <${+$+1}.0.0-0`:q?(i("replaceCaret pr",q),$==="0"?D==="0"?Y=`>=${$}.${D}.${J}-${q} <${$}.${D}.${+J+1}-0`:Y=`>=${$}.${D}.${J}-${q} <${$}.${+D+1}.0-0`:Y=`>=${$}.${D}.${J}-${q} <${+$+1}.0.0-0`):(i("no pr"),$==="0"?D==="0"?Y=`>=${$}.${D}.${J}${R} <${$}.${D}.${+J+1}-0`:Y=`>=${$}.${D}.${J}${R} <${$}.${+D+1}.0-0`:Y=`>=${$}.${D}.${J} <${+$+1}.0.0-0`),i("caret return",Y),Y})},T=(I,A)=>(i("replaceXRanges",I,A),I.split(/\s+/).map(j=>N(j,A)).join(" ")),N=(I,A)=>{I=I.trim();const j=A.loose?u[c.XRANGELOOSE]:u[c.XRANGE];return I.replace(j,(R,L,$,D,J,q)=>{i("xRange",I,R,L,$,D,J,q);const Y=_($),ue=Y||_(D),ee=ue||_(J),ct=ee;return L==="="&&ct&&(L=""),q=A.includePrerelease?"-0":"",Y?L===">"||L==="<"?R="<0.0.0-0":R="*":L&&ct?(ue&&(D=0),J=0,L===">"?(L=">=",ue?($=+$+1,D=0,J=0):(D=+D+1,J=0)):L==="<="&&(L="<",ue?$=+$+1:D=+D+1),L==="<"&&(q="-0"),R=`${L+$}.${D}.${J}${q}`):ue?R=`>=${$}.0.0${q} <${+$+1}.0.0-0`:ee&&(R=`>=${$}.${D}.0${q} <${$}.${+D+1}.0-0`),i("xRange return",R),R})},G=(I,A)=>(i("replaceStars",I,A),I.trim().replace(u[c.STAR],"")),z=(I,A)=>(i("replaceGTE0",I,A),I.trim().replace(u[A.includePrerelease?c.GTE0PRE:c.GTE0],"")),oe=I=>(A,j,R,L,$,D,J,q,Y,ue,ee,ct)=>(_(R)?j="":_(L)?j=`>=${R}.0.0${I?"-0":""}`:_($)?j=`>=${R}.${L}.0${I?"-0":""}`:D?j=`>=${j}`:j=`>=${j}${I?"-0":""}`,_(Y)?q="":_(ue)?q=`<${+Y+1}.0.0-0`:_(ee)?q=`<${Y}.${+ue+1}.0-0`:ct?q=`<=${Y}.${ue}.${ee}-${ct}`:I?q=`<${Y}.${ue}.${+ee+1}-0`:q=`<=${q}`,`${j} ${q}`.trim()),Ke=(I,A,j)=>{for(let R=0;R<I.length;R++)if(!I[R].test(A))return!1;if(A.prerelease.length&&!j.includePrerelease){for(let R=0;R<I.length;R++)if(i(I[R].semver),I[R].semver!==s.ANY&&I[R].semver.prerelease.length>0){const L=I[R].semver;if(L.major===A.major&&L.minor===A.minor&&L.patch===A.patch)return!0}return!1}return!0};return vs}var Es,Yu;function la(){if(Yu)return Es;Yu=1;const n=Symbol("SemVer ANY");class e{static get ANY(){return n}constructor(l,d){if(d=t(d),l instanceof e){if(l.loose===!!d.loose)return l;l=l.value}l=l.trim().split(/\s+/).join(" "),i("comparator",l,d),this.options=d,this.loose=!!d.loose,this.parse(l),this.semver===n?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(l){const d=this.options.loose?r[a.COMPARATORLOOSE]:r[a.COMPARATOR],h=l.match(d);if(!h)throw new TypeError(`Invalid comparator: ${l}`);this.operator=h[1]!==void 0?h[1]:"",this.operator==="="&&(this.operator=""),h[2]?this.semver=new o(h[2],this.options.loose):this.semver=n}toString(){return this.value}test(l){if(i("Comparator.test",l,this.options.loose),this.semver===n||l===n)return!0;if(typeof l=="string")try{l=new o(l,this.options)}catch{return!1}return s(l,this.operator,this.semver,this.options)}intersects(l,d){if(!(l instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new u(l.value,d).test(this.value):l.operator===""?l.value===""?!0:new u(this.value,d).test(l.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||l.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||l.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&l.operator.startsWith(">")||this.operator.startsWith("<")&&l.operator.startsWith("<")||this.semver.version===l.semver.version&&this.operator.includes("=")&&l.operator.includes("=")||s(this.semver,"<",l.semver,d)&&this.operator.startsWith(">")&&l.operator.startsWith("<")||s(this.semver,">",l.semver,d)&&this.operator.startsWith("<")&&l.operator.startsWith(">")))}}Es=e;const t=Vi(),{safeRe:r,t:a}=zr(),s=Ld(),i=ua(),o=Oe(),u=Je();return Es}var Ss,ec;function da(){if(ec)return Ss;ec=1;const n=Je();return Ss=(t,r,a)=>{try{r=new n(r,a)}catch{return!1}return r.test(t)},Ss}var Os,tc;function lg(){if(tc)return Os;tc=1;const n=Je();return Os=(t,r)=>new n(t,r).set.map(a=>a.map(s=>s.value).join(" ").trim().split(" ")),Os}var Ts,rc;function dg(){if(rc)return Ts;rc=1;const n=Oe(),e=Je();return Ts=(r,a,s)=>{let i=null,o=null,u=null;try{u=new e(a,s)}catch{return null}return r.forEach(c=>{u.test(c)&&(!i||o.compare(c)===-1)&&(i=c,o=new n(i,s))}),i},Ts}var As,nc;function hg(){if(nc)return As;nc=1;const n=Oe(),e=Je();return As=(r,a,s)=>{let i=null,o=null,u=null;try{u=new e(a,s)}catch{return null}return r.forEach(c=>{u.test(c)&&(!i||o.compare(c)===1)&&(i=c,o=new n(i,s))}),i},As}var Ps,ac;function fg(){if(ac)return Ps;ac=1;const n=Oe(),e=Je(),t=ca();return Ps=(a,s)=>{a=new e(a,s);let i=new n("0.0.0");if(a.test(i)||(i=new n("0.0.0-0"),a.test(i)))return i;i=null;for(let o=0;o<a.set.length;++o){const u=a.set[o];let c=null;u.forEach(l=>{const d=new n(l.semver.version);switch(l.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!c||t(d,c))&&(c=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${l.operator}`)}}),c&&(!i||t(i,c))&&(i=c)}return i&&a.test(i)?i:null},Ps}var xs,sc;function mg(){if(sc)return xs;sc=1;const n=Je();return xs=(t,r)=>{try{return new n(t,r).range||"*"}catch{return null}},xs}var Is,ic;function to(){if(ic)return Is;ic=1;const n=Oe(),e=la(),{ANY:t}=e,r=Je(),a=da(),s=ca(),i=Qi(),o=eo(),u=Yi();return Is=(l,d,h,f)=>{l=new n(l,f),d=new r(d,f);let m,p,g,y,b;switch(h){case">":m=s,p=o,g=i,y=">",b=">=";break;case"<":m=i,p=u,g=s,y="<",b="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(l,d,f))return!1;for(let _=0;_<d.set.length;++_){const w=d.set[_];let v=null,S=null;if(w.forEach(O=>{O.semver===t&&(O=new e(">=0.0.0")),v=v||O,S=S||O,m(O.semver,v.semver,f)?v=O:g(O.semver,S.semver,f)&&(S=O)}),v.operator===y||v.operator===b||(!S.operator||S.operator===y)&&p(l,S.semver))return!1;if(S.operator===b&&g(l,S.semver))return!1}return!0},Is}var Rs,oc;function pg(){if(oc)return Rs;oc=1;const n=to();return Rs=(t,r,a)=>n(t,r,">",a),Rs}var $s,uc;function gg(){if(uc)return $s;uc=1;const n=to();return $s=(t,r,a)=>n(t,r,"<",a),$s}var ks,cc;function yg(){if(cc)return ks;cc=1;const n=Je();return ks=(t,r,a)=>(t=new n(t,a),r=new n(r,a),t.intersects(r,a)),ks}var Cs,lc;function _g(){if(lc)return Cs;lc=1;const n=da(),e=We();return Cs=(t,r,a)=>{const s=[];let i=null,o=null;const u=t.sort((h,f)=>e(h,f,a));for(const h of u)n(h,r,a)?(o=h,i||(i=h)):(o&&s.push([i,o]),o=null,i=null);i&&s.push([i,null]);const c=[];for(const[h,f]of s)h===f?c.push(h):!f&&h===u[0]?c.push("*"):f?h===u[0]?c.push(`<=${f}`):c.push(`${h} - ${f}`):c.push(`>=${h}`);const l=c.join(" || "),d=typeof r.raw=="string"?r.raw:String(r);return l.length<d.length?l:r},Cs}var Ns,dc;function bg(){if(dc)return Ns;dc=1;const n=Je(),e=la(),{ANY:t}=e,r=da(),a=We(),s=(d,h,f={})=>{if(d===h)return!0;d=new n(d,f),h=new n(h,f);let m=!1;e:for(const p of d.set){for(const g of h.set){const y=u(p,g,f);if(m=m||y!==null,y)continue e}if(m)return!1}return!0},i=[new e(">=0.0.0-0")],o=[new e(">=0.0.0")],u=(d,h,f)=>{if(d===h)return!0;if(d.length===1&&d[0].semver===t){if(h.length===1&&h[0].semver===t)return!0;f.includePrerelease?d=i:d=o}if(h.length===1&&h[0].semver===t){if(f.includePrerelease)return!0;h=o}const m=new Set;let p,g;for(const T of d)T.operator===">"||T.operator===">="?p=c(p,T,f):T.operator==="<"||T.operator==="<="?g=l(g,T,f):m.add(T.semver);if(m.size>1)return null;let y;if(p&&g){if(y=a(p.semver,g.semver,f),y>0)return null;if(y===0&&(p.operator!==">="||g.operator!=="<="))return null}for(const T of m){if(p&&!r(T,String(p),f)||g&&!r(T,String(g),f))return null;for(const N of h)if(!r(T,String(N),f))return!1;return!0}let b,_,w,v,S=g&&!f.includePrerelease&&g.semver.prerelease.length?g.semver:!1,O=p&&!f.includePrerelease&&p.semver.prerelease.length?p.semver:!1;S&&S.prerelease.length===1&&g.operator==="<"&&S.prerelease[0]===0&&(S=!1);for(const T of h){if(v=v||T.operator===">"||T.operator===">=",w=w||T.operator==="<"||T.operator==="<=",p){if(O&&T.semver.prerelease&&T.semver.prerelease.length&&T.semver.major===O.major&&T.semver.minor===O.minor&&T.semver.patch===O.patch&&(O=!1),T.operator===">"||T.operator===">="){if(b=c(p,T,f),b===T&&b!==p)return!1}else if(p.operator===">="&&!r(p.semver,String(T),f))return!1}if(g){if(S&&T.semver.prerelease&&T.semver.prerelease.length&&T.semver.major===S.major&&T.semver.minor===S.minor&&T.semver.patch===S.patch&&(S=!1),T.operator==="<"||T.operator==="<="){if(_=l(g,T,f),_===T&&_!==g)return!1}else if(g.operator==="<="&&!r(g.semver,String(T),f))return!1}if(!T.operator&&(g||p)&&y!==0)return!1}return!(p&&w&&!g&&y!==0||g&&v&&!p&&y!==0||O||S)},c=(d,h,f)=>{if(!d)return h;const m=a(d.semver,h.semver,f);return m>0?d:m<0||h.operator===">"&&d.operator===">="?h:d},l=(d,h,f)=>{if(!d)return h;const m=a(d.semver,h.semver,f);return m<0?d:m>0||h.operator==="<"&&d.operator==="<="?h:d};return Ns=s,Ns}var js,hc;function wg(){if(hc)return js;hc=1;const n=zr(),e=oa(),t=Oe(),r=Cd(),a=er(),s=Vp(),i=Xp(),o=Qp(),u=Yp(),c=eg(),l=tg(),d=rg(),h=ng(),f=We(),m=ag(),p=sg(),g=Xi(),y=ig(),b=og(),_=ca(),w=Qi(),v=Nd(),S=jd(),O=Yi(),T=eo(),N=Ld(),G=ug(),z=la(),oe=Je(),Ke=da(),I=lg(),A=dg(),j=hg(),R=fg(),L=mg(),$=to(),D=pg(),J=gg(),q=yg(),Y=_g(),ue=bg();return js={parse:a,valid:s,clean:i,inc:o,diff:u,major:c,minor:l,patch:d,prerelease:h,compare:f,rcompare:m,compareLoose:p,compareBuild:g,sort:y,rsort:b,gt:_,lt:w,eq:v,neq:S,gte:O,lte:T,cmp:N,coerce:G,Comparator:z,Range:oe,satisfies:Ke,toComparators:I,maxSatisfying:A,minSatisfying:j,minVersion:R,validRange:L,outside:$,gtr:D,ltr:J,intersects:q,simplifyRange:Y,subset:ue,SemVer:t,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:e.SEMVER_SPEC_VERSION,RELEASE_TYPES:e.RELEASE_TYPES,compareIdentifiers:r.compareIdentifiers,rcompareIdentifiers:r.rcompareIdentifiers},js}wg();function ht(n){if(!n||n.split("/").length>2||n.startsWith("/")||n.endsWith("/")||n.split(":").length>2)throw new Error(`Invalid identifier format: ${n}`);const[e,t]=n.split(":"),r=t||"latest";if(e.includes("/")){const[a,s]=e.split("/",2);if(!a||!s)throw new Error(`Invalid identifier format: ${n}`);return[a,s,r]}else{if(!e)throw new Error(`Invalid identifier format: ${n}`);return["-",e,r]}}class vg extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}async function k(n,e,t){let r;if(n.ok){t&&(r=await n.text());return}if(n.status===403)try{const i=await n.json();(i==null?void 0:i.error)==="org_scoped_key_requires_workspace"&&(r="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{const o=new Error(`${n.status} ${n.statusText}`);throw o.status=n==null?void 0:n.status,o}if(r===void 0)try{r=await n.text()}catch{r=""}const a=`Failed to ${e}. Received status [${n.status}]: ${n.statusText}. Message: ${r}`;if(n.status===409)throw new vg(a);const s=new Error(a);throw s.status=n.status,s}const Md="ERR_CONFLICTING_ENDPOINTS";class Eg extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:Md}),this.name="ConflictingEndpointsError"}}function Sg(n){return typeof n=="object"&&n!==null&&n.code===Md}var fc="[...]",Og={result:"[Circular]"},Ln=[],Zt=[];const Tg=new TextEncoder;function Ag(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function on(n){return Tg.encode(n)}function Ud(n){if(n&&typeof n=="object"&&n!==null){if(n instanceof Map)return Object.fromEntries(n);if(n instanceof Set)return Array.from(n);if(n instanceof Date)return n.toISOString();if(n instanceof RegExp)return n.toString();if(n instanceof Error)return{name:n.name,message:n.message}}else if(typeof n=="bigint")return n.toString();return n}function Pg(n){return function(e,t){return Ud(t)}}function ke(n,e,t,r,a){var s;try{const i=JSON.stringify(n,Pg(t),r);return on(i)}catch(i){if(!((s=i.message)!=null&&s.includes("Converting circular structure to JSON")))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
50
+ Context: ${e}`:""}`),on("[Unserializable]");xe("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
51
+ Context: ${e}`:""}`),typeof a>"u"&&(a=Ag()),pi(n,"",0,[],void 0,0,a);let o;try{Zt.length===0?o=JSON.stringify(n,t,r):o=JSON.stringify(n,xg(t),r)}catch{return on("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Ln.length!==0;){const u=Ln.pop();u.length===4?Object.defineProperty(u[0],u[1],u[3]):u[0][u[1]]=u[2]}}return on(o)}}function Ls(n,e,t,r){var a=Object.getOwnPropertyDescriptor(r,t);a.get!==void 0?a.configurable?(Object.defineProperty(r,t,{value:n}),Ln.push([r,t,e,a])):Zt.push([e,t,n]):(r[t]=n,Ln.push([r,t,e]))}function pi(n,e,t,r,a,s,i){s+=1;var o;if(typeof n=="object"&&n!==null){for(o=0;o<r.length;o++)if(r[o]===n){Ls(Og,n,e,a);return}if(typeof i.depthLimit<"u"&&s>i.depthLimit){Ls(fc,n,e,a);return}if(typeof i.edgesLimit<"u"&&t+1>i.edgesLimit){Ls(fc,n,e,a);return}if(r.push(n),Array.isArray(n))for(o=0;o<n.length;o++)pi(n[o],o,o,r,n,s,i);else{n=Ud(n);var u=Object.keys(n);for(o=0;o<u.length;o++){var c=u[o];pi(n[c],c,o,r,n,s,i)}}r.pop()}}function xg(n){return n=typeof n<"u"?n:function(e,t){return t},function(e,t){if(Zt.length>0)for(var r=0;r<Zt.length;r++){var a=Zt[r];if(a[1]===e&&a[0]===t){t=a[2],Zt.splice(r,1);break}}return n.call(this,e,t)}}function mc(n,e){const t=xd(),r=e??Id(),a=n.extra??{},s=a.metadata;return n.extra={...a,runtime:{...t,...a==null?void 0:a.runtime},metadata:{...r,...r.revision_id||"revision_id"in n&&n.revision_id?{revision_id:("revision_id"in n?n.revision_id:void 0)??r.revision_id}:{},...s}},n}const Ig=n=>{const e=(n==null?void 0:n.toString())??xe("TRACING_SAMPLING_RATE");if(e===void 0)return;const t=parseFloat(e);if(t<0||t>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${t}`);return t},Rg=n=>{const t=n.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return t==="localhost"||t==="127.0.0.1"||t==="::1"};async function $g(n){const e=[];for await(const t of n)e.push(t);return e}function un(n){if(n!==void 0)return n.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const kg=async n=>{if((n==null?void 0:n.status)===429){const e=parseInt(n.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(t=>setTimeout(t,e)),!0}return!1};function pc(n){return typeof n=="number"?Number(n.toFixed(4)):n}class Cg{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let t;const r=new Promise(s=>{t=s}),a=ke(e.item,`Serializing run with id: ${e.item.id}`).length;return this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:t,itemPromise:r,size:a}),this.sizeBytes+=a,r}pop({upToSizeBytes:e,upToSize:t}){var s;if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const r=[];let a=0;for(;a+(((s=this.peek())==null?void 0:s.size)??0)<e&&this.items.length>0&&r.length<t;){const i=this.items.shift();i&&(r.push(i),a+=i.size,this.sizeBytes-=i.size)}if(r.length===0&&this.items.length>0){const i=this.items.shift();r.push(i),a+=i.size,this.sizeBytes-=i.size}return[r.map(i=>({action:i.action,item:i.payload,otelContext:i.otelContext,apiKey:i.apiKey,apiUrl:i.apiUrl})),()=>r.forEach(i=>i.itemPromiseResolve())]}}const Ng=24*1024*1024,jg=1e4,Lg=100,gc="https://api.smith.langchain.com";class Cr{get _fetch(){return this.fetchImplementation||Sp(this.debug)}constructor(e={}){var r;Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new Cg}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:rt("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:rt("LANGSMITH_DEBUG")==="true"});const t=Cr.getDefaultClientConfig();if(this.tracingSampleRate=Ig(e.tracingSamplingRate),this.apiUrl=un(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=un(e.apiKey??t.apiKey),this.webUrl=un(e.webUrl??t.webUrl),(r=this.webUrl)!=null&&r.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=un(e.workspaceId??xe("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new _u({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.batchIngestCaller=new _u({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:kg,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,Rd()&&(this.langSmithToOTELTranslator=new Dp),this.cachedLSEnvVarsForMetadata=Id()}static getDefaultClientConfig(){const e=xe("API_KEY"),t=xe("ENDPOINT")??gc,r=xe("HIDE_INPUTS")==="true",a=xe("HIDE_OUTPUTS")==="true";return{apiUrl:t,apiKey:e,webUrl:void 0,hideInputs:r,hideOutputs:a}}getHostUrl(){return this.webUrl?this.webUrl:Rg(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){const e={"User-Agent":`langsmith-js/${Td}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){const t={...e};return t.inputs!==void 0&&(t.inputs=await this.processInputs(t.inputs)),t.outputs!==void 0&&(t.outputs=await this.processOutputs(t.outputs)),t}async _getResponse(e,t){const r=(t==null?void 0:t.toString())??"",a=`${this.apiUrl}${e}?${r}`;return await this.caller.call(async()=>{const i=await this._fetch(a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(i,`fetch ${e}`),i})}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,r){let a=Number(t.get("offset"))||0;const s=Number(t.get("limit"))||100;for(;;){t.set("offset",String(a)),t.set("limit",String(s));const i=`${this.apiUrl}${e}?${t}`,o=await this.caller.call(async()=>{const c=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(c,`fetch ${e}`),c}),u=r?r(await o.json()):await o.json();if(u.length===0||(yield u,u.length<s))break;a+=u.length}}async*_getCursorPaginatedList(e,t=null,r="POST",a="runs"){const s=t?{...t}:{};for(;;){const i=JSON.stringify(s),u=await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}${e}`,{method:r,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await k(l,`fetch ${e}`),l})).json();if(!u||!u[a])break;yield u[a];const c=u.cursors;if(!c||!c.next)break;s.cursor=c.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,t=!1){if(this.tracingSampleRate===void 0)return e;if(t){const r=[];for(const a of e)this.filteredPostUuids.has(a.trace_id)?a.id===a.trace_id&&this.filteredPostUuids.delete(a.trace_id):r.push(a);return r}else{const r=[];for(const a of e){const s=a.trace_id??a.id;this.filteredPostUuids.has(s)||(a.id===s?this._shouldSample()?r.push(a):this.filteredPostUuids.add(s):r.push(a))}return r}}async _getBatchSizeLimitBytes(){var t;const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??((t=e.batch_ingest_config)==null?void 0:t.size_limit_bytes)??Ng}async _getBatchSizeLimit(){var t;const e=await this._ensureServerInfo();return this.batchSizeLimit??((t=e.batch_ingest_config)==null?void 0:t.size_limit)??Lg}async _getDatasetExamplesMultiPartSupport(){var t;return((t=(await this._ensureServerInfo()).instance_flags)==null?void 0:t.dataset_examples_multipart_enabled)??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t}){const r=[];for(;this.autoBatchQueue.items.length>0;){const[a,s]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!a.length){s();break}const i=a.reduce((c,l)=>{const d=l.apiUrl??this.apiUrl,h=l.apiKey??this.apiKey,m=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${d}|${h}`;return c[m]||(c[m]=[]),c[m].push(l),c},{}),o=[];for(const[c,l]of Object.entries(i)){const d=this._processBatch(l,{apiUrl:c==="default"?void 0:c.split("|")[0],apiKey:c==="default"?void 0:c.split("|")[1]});o.push(d)}const u=Promise.all(o).finally(s);r.push(u)}return Promise.all(r)}async _processBatch(e,t){var r,a;if(e.length)try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{const s={runCreates:e.filter(o=>o.action==="create").map(o=>o.item),runUpdates:e.filter(o=>o.action==="update").map(o=>o.item)},i=await this._ensureServerInfo();if((r=i==null?void 0:i.batch_ingest_config)!=null&&r.use_multipart_endpoint){const o=(a=i==null?void 0:i.instance_flags)==null?void 0:a.gzip_body_enabled;await this.multipartIngestRuns(s,{...t,useGzip:o})}else await this.batchIngestRuns(s,t)}}catch(s){console.error("Error exporting batch:",s)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){const t=new Map,r=[];for(const a of e)a.item.id&&a.otelContext&&(t.set(a.item.id,a.otelContext),a.action==="create"?r.push({operation:"post",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}):r.push({operation:"patch",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}));this.langSmithToOTELTranslator.exportBatch(r,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=mc(e.item,this.cachedLSEnvVarsForMetadata);const t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;const r=await this._getBatchSizeLimitBytes(),a=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>r||this.autoBatchQueue.items.length>a)&&this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:a}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:a})},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){const t=await(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(jg),...this.fetchOptions});return await k(r,"get server info"),r})).json();return this.debug&&console.log(`
52
+ === LangSmith Server Configuration ===
53
+ `+JSON.stringify(t,null,2)+`
54
+ `),t}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const e=await this._getBatchSizeLimitBytes(),t=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t})}_cloneCurrentOTELContext(){const e=$d(),t=Lp();if(this.langSmithToOTELTranslator!==void 0){const r=e.getActiveSpan();if(r)return e.setSpan(t.active(),r)}}async createRun(e,t){if(!this._filterForSampling([e]).length)return;const r={...this.headers,"Content-Type":"application/json"},a=e.project_name;delete e.project_name;const s=await this.prepareRunCreateOrUpdateInputs({session_name:a,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){const u=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:s,otelContext:u,apiKey:t==null?void 0:t.apiKey,apiUrl:t==null?void 0:t.apiUrl}).catch(console.error);return}const i=mc(s,this.cachedLSEnvVarsForMetadata);(t==null?void 0:t.apiKey)!==void 0&&(r["x-api-key"]=t.apiKey),(t==null?void 0:t.workspaceId)!==void 0&&(r["x-tenant-id"]=t.workspaceId);const o=ke(i,`Creating run with id: ${i.id}`);await this.caller.call(async()=>{const u=await this._fetch(`${(t==null?void 0:t.apiUrl)??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await k(u,"create run",!0),u})}async batchIngestRuns({runCreates:e,runUpdates:t},r){if(e===void 0&&t===void 0)return;let a=await Promise.all((e==null?void 0:e.map(u=>this.prepareRunCreateOrUpdateInputs(u)))??[]),s=await Promise.all((t==null?void 0:t.map(u=>this.prepareRunCreateOrUpdateInputs(u)))??[]);if(a.length>0&&s.length>0){const u=a.reduce((l,d)=>(d.id&&(l[d.id]=d),l),{}),c=[];for(const l of s)l.id!==void 0&&u[l.id]?u[l.id]={...u[l.id],...l}:c.push(l);a=Object.values(u),s=c}const i={post:a,patch:s};if(!i.post.length&&!i.patch.length)return;const o={post:[],patch:[]};for(const u of["post","patch"]){const c=u,l=i[c].reverse();let d=l.pop();for(;d!==void 0;)o[c].push(d),d=l.pop()}if(o.post.length>0||o.patch.length>0){const u=o.post.map(c=>c.id).concat(o.patch.map(c=>c.id)).join(",");await this._postBatchIngestRuns(ke(o,`Ingesting runs with ids: ${u}`),r)}}async _postBatchIngestRuns(e,t){const r={...this.headers,"Content-Type":"application/json",Accept:"application/json"};(t==null?void 0:t.apiKey)!==void 0&&(r["x-api-key"]=t.apiKey),await this.batchIngestCaller.call(async()=>{const a=await this._fetch(`${(t==null?void 0:t.apiUrl)??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await k(a,"batch create run",!0),a})}async multipartIngestRuns({runCreates:e,runUpdates:t},r){if(e===void 0&&t===void 0)return;const a={};let s=[];for(const d of e??[]){const h=await this.prepareRunCreateOrUpdateInputs(d);h.id!==void 0&&h.attachments!==void 0&&(a[h.id]=h.attachments),delete h.attachments,s.push(h)}let i=[];for(const d of t??[])i.push(await this.prepareRunCreateOrUpdateInputs(d));if(s.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(s.length>0&&i.length>0){const d=s.reduce((f,m)=>(m.id&&(f[m.id]=m),f),{}),h=[];for(const f of i)f.id!==void 0&&d[f.id]?d[f.id]={...d[f.id],...f}:h.push(f);s=Object.values(d),i=h}if(s.length===0&&i.length===0)return;const c=[],l=[];for(const[d,h]of[["post",s],["patch",i]])for(const f of h){const{inputs:m,outputs:p,events:g,extra:y,error:b,serialized:_,attachments:w,...v}=f,S={inputs:m,outputs:p,events:g,extra:y,error:b,serialized:_},O=ke(v,`Serializing for multipart ingestion of run with id: ${v.id}`);l.push({name:`${d}.${v.id}`,payload:new Blob([O],{type:`application/json; length=${O.length}`})});for(const[T,N]of Object.entries(S)){if(N===void 0)continue;const G=ke(N,`Serializing ${T} for multipart ingestion of run with id: ${v.id}`);l.push({name:`${d}.${v.id}.${T}`,payload:new Blob([G],{type:`application/json; length=${G.length}`})})}if(v.id!==void 0){const T=a[v.id];if(T){delete a[v.id];for(const[N,G]of Object.entries(T)){let z,oe;if(Array.isArray(G)?[z,oe]=G:(z=G.mimeType,oe=G.data),N.includes(".")){console.warn(`Skipping attachment '${N}' for run ${v.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${v.id}.${N}`,payload:new Blob([oe],{type:`${z}; length=${oe.byteLength}`})})}}}c.push(`trace=${v.trace_id},id=${v.id}`)}await this._sendMultipartRequest(l,c.join("; "),r)}async _createNodeFetchBody(e,t){const r=[];for(const i of e)r.push(new Blob([`--${t}\r
55
+ `])),r.push(new Blob([`Content-Disposition: form-data; name="${i.name}"\r
56
+ `,`Content-Type: ${i.payload.type}\r
57
+ \r
58
+ `])),r.push(i.payload),r.push(new Blob([`\r
59
+ `]));return r.push(new Blob([`--${t}--\r
60
+ `])),await new Blob(r).arrayBuffer()}async _createMultipartStream(e,t){const r=new TextEncoder;return new ReadableStream({async start(s){const i=async o=>{typeof o=="string"?s.enqueue(r.encode(o)):s.enqueue(o)};for(const o of e){await i(`--${t}\r
61
+ `),await i(`Content-Disposition: form-data; name="${o.name}"\r
62
+ `),await i(`Content-Type: ${o.payload.type}\r
63
+ \r
64
+ `);const c=o.payload.stream().getReader();try{let l;for(;!(l=await c.read()).done;)s.enqueue(l.value)}finally{c.releaseLock()}await i(`\r
65
+ `)}await i(`--${t}--\r
66
+ `),s.close()}})}async _sendMultipartRequest(e,t,r){const a="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),s=Ep(),i=()=>this._createNodeFetchBody(e,a),o=()=>this._createMultipartStream(e,a),u=async c=>this.batchIngestCaller.call(async()=>{const l=await c(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${a}`};(r==null?void 0:r.apiKey)!==void 0&&(d["x-api-key"]=r.apiKey);let h=l;r!=null&&r.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(h=l.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");const f=await this._fetch(`${(r==null?void 0:r.apiUrl)??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:h,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(f,"Failed to send multipart request",!0),f});try{let c,l=!1;!s&&!this.multipartStreamingDisabled&&Pd()!=="bun"?(l=!0,c=await u(o)):c=await u(i),(!this.multipartStreamingDisabled||l)&&c.status===422&&((r==null?void 0:r.apiUrl)??this.apiUrl)!==gc&&(console.warn(`Streaming multipart upload to ${(r==null?void 0:r.apiUrl)??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${t}".`),this.multipartStreamingDisabled=!0,c=await u(i))}catch(c){console.warn(`${c.message.trim()}
67
+
68
+ Context: ${t}`)}}async updateRun(e,t,r){B(e),t.inputs&&(t.inputs=await this.processInputs(t.inputs)),t.outputs&&(t.outputs=await this.processOutputs(t.outputs));const a={...t,id:e};if(!this._filterForSampling([a],!0).length)return;if(this.autoBatchTracing&&a.trace_id!==void 0&&a.dotted_order!==void 0){const o=this._cloneCurrentOTELContext();if(t.end_time!==void 0&&a.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:a,otelContext:o,apiKey:r==null?void 0:r.apiKey,apiUrl:r==null?void 0:r.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:a,otelContext:o,apiKey:r==null?void 0:r.apiKey,apiUrl:r==null?void 0:r.apiUrl}).catch(console.error);return}const s={...this.headers,"Content-Type":"application/json"};(r==null?void 0:r.apiKey)!==void 0&&(s["x-api-key"]=r.apiKey),(r==null?void 0:r.workspaceId)!==void 0&&(s["x-tenant-id"]=r.workspaceId);const i=ke(t,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{const o=await this._fetch(`${(r==null?void 0:r.apiUrl)??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:s,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await k(o,"update run",!0),o})}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){B(e);let r=await this._get(`/runs/${e}`);return t&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:t,projectOpts:r}){if(t!==void 0){let a;t.session_id?a=t.session_id:r!=null&&r.projectName?a=(await this.readProject({projectName:r==null?void 0:r.projectName})).id:r!=null&&r.projectId?a=r==null?void 0:r.projectId:a=(await this.readProject({projectName:xe("PROJECT")||"default"})).id;const s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${a}/r/${t.id}?poll=true`}else if(e!==void 0){const a=await this.readRun(e);if(!a.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${a.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){var s;const t=await $g(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),r={},a={};t.sort((i,o)=>((i==null?void 0:i.dotted_order)??"").localeCompare((o==null?void 0:o.dotted_order)??""));for(const i of t){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Child run ${i.id} has no parent`);(s=i.dotted_order)!=null&&s.startsWith(e.dotted_order??"")&&i.id!==e.id&&(i.parent_run_id in r||(r[i.parent_run_id]=[]),r[i.parent_run_id].push(i),a[i.id]=i)}e.child_runs=r[e.id]||[];for(const i in r)i!==e.id&&(a[i].child_runs=r[i]);return e}async*listRuns(e){const{projectId:t,projectName:r,parentRunId:a,traceId:s,referenceExampleId:i,startTime:o,executionOrder:u,isRoot:c,runType:l,error:d,id:h,query:f,filter:m,traceFilter:p,treeFilter:g,limit:y,select:b,order:_}=e;let w=[];if(t&&(w=Array.isArray(t)?t:[t]),r){const T=Array.isArray(r)?r:[r],N=await Promise.all(T.map(G=>this.readProject({projectName:G}).then(z=>z.id)));w.push(...N)}const v=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],S={session:w.length?w:null,run_type:l,reference_example:i,query:f,filter:m,trace_filter:p,tree_filter:g,execution_order:u,parent_run:a,start_time:o?o.toISOString():null,error:d,id:h,limit:y,trace:s,select:b||v,is_root:c,order:_};let O=0;for await(const T of this._getCursorPaginatedList("/runs/query",S))if(y){if(O>=y)break;if(T.length+O>y){yield*T.slice(0,y-O);break}O+=T.length,yield*T}else yield*T}async*listGroupRuns(e){const{projectId:t,projectName:r,groupBy:a,filter:s,startTime:i,endTime:o,limit:u,offset:c}=e,d={session_id:t||(await this.readProject({projectName:r})).id,group_by:a,filter:s,start_time:i?i.toISOString():null,end_time:o?o.toISOString():null,limit:Number(u)||100};let h=Number(c)||0;const f="/runs/group",m=`${this.apiUrl}${f}`;for(;;){const p={...d,offset:h},g=Object.fromEntries(Object.entries(p).filter(([S,O])=>O!==void 0)),y=JSON.stringify(g),_=await(await this.caller.call(async()=>{const S=await this._fetch(m,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:y});return await k(S,`Failed to fetch ${f}`),S})).json(),{groups:w,total:v}=_;if(w.length===0)break;for(const S of w)yield S;if(h+=w.length,h>=v)break}}async getRunStats({id:e,trace:t,parentRun:r,runType:a,projectNames:s,projectIds:i,referenceExampleIds:o,startTime:u,endTime:c,error:l,query:d,filter:h,traceFilter:f,treeFilter:m,isRoot:p,dataSourceType:g}){let y=i||[];s&&(y=[...i||[],...await Promise.all(s.map(O=>this.readProject({projectName:O}).then(T=>T.id)))]);const _=Object.fromEntries(Object.entries({id:e,trace:t,parent_run:r,run_type:a,session:y,reference_example:o,start_time:u,end_time:c,error:l,query:d,filter:h,trace_filter:f,tree_filter:m,is_root:p,data_source_type:g}).filter(([O,T])=>T!==void 0)),w=JSON.stringify(_);return await(await this.caller.call(async()=>{const O=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:w});return await k(O,"get run stats"),O})).json()}async shareRun(e,{shareId:t}={}){const r={run_id:e,share_token:t||Ht()};B(e);const a=JSON.stringify(r),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await k(o,"share run"),o})).json();if(i===null||!("share_token"in i))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){B(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,"unshare run",!0),t})}async readRunSharedLink(e){B(e);const r=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(a,"read run shared link"),a})).json();if(!(r===null||!("share_token"in r)))return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){const r=new URLSearchParams({share_token:e});if(t!==void 0)for(const i of t)r.append("id",i);return B(e),await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(i,"list shared runs"),i})).json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id),B(e);const a=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(s,"read dataset shared schema"),s})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async shareDataset(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id);const r={dataset_id:e};B(e);const a=JSON.stringify(r),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await k(o,"share dataset"),o})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){B(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,"unshare dataset",!0),t})}async readSharedDataset(e){return B(e),await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(a,"read shared dataset"),a})).json()}async listSharedExamples(e,t){const r={};t!=null&&t.exampleIds&&(r.id=t.exampleIds);const a=new URLSearchParams;Object.entries(r).forEach(([o,u])=>{Array.isArray(u)?u.forEach(c=>a.append(o,c)):a.append(o,u)});const s=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/public/${e}/examples?${a.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(o,"list shared examples"),o}),i=await s.json();if(!s.ok)throw"detail"in i?new Error(`Failed to list shared examples.
69
+ Status: ${s.status}
70
+ Message: ${Array.isArray(i.detail)?i.detail.join(`
71
+ `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${s.status} ${s.statusText}`);return i.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:r=null,upsert:a=!1,projectExtra:s=null,referenceDatasetId:i=null}){const o=a?"?upsert=true":"",u=`${this.apiUrl}/sessions${o}`,c=s||{};r&&(c.metadata=r);const l={name:e,extra:c,description:t};i!==null&&(l.reference_dataset_id=i);const d=JSON.stringify(l);return await(await this.caller.call(async()=>{const m=await this._fetch(u,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await k(m,"create project"),m})).json()}async updateProject(e,{name:t=null,description:r=null,metadata:a=null,projectExtra:s=null,endTime:i=null}){const o=`${this.apiUrl}/sessions/${e}`;let u=s;a&&(u={...u||{},metadata:a});const c=JSON.stringify({name:t,extra:u,description:r,end_time:i?new Date(i).toISOString():null});return await(await this.caller.call(async()=>{const h=await this._fetch(o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await k(h,"update project"),h})).json()}async hasProject({projectId:e,projectName:t}){let r="/sessions";const a=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)B(e),r+=`/${e}`;else if(t!==void 0)a.append("name",t);else throw new Error("Must provide projectName or projectId");const s=await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${r}?${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(i,"has project"),i});try{const i=await s.json();return s.ok?Array.isArray(i)?i.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:t,includeStats:r}){let a="/sessions";const s=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)B(e),a+=`/${e}`;else if(t!==void 0)s.append("name",t);else throw new Error("Must provide projectName or projectId");r!==void 0&&s.append("include_stats",r.toString());const i=await this._get(a,s);let o;if(Array.isArray(i)){if(i.length===0)throw new Error(`Project[id=${e}, name=${t}] not found`);o=i[0]}else o=i;return o}async getProjectUrl({projectId:e,projectName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either projectName or projectId");const r=await this.readProject({projectId:e,projectName:t}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");const r=await this.readDataset({datasetId:e,datasetName:t}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/datasets/${r.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:t,nameContains:r,referenceDatasetId:a,referenceDatasetName:s,includeStats:i,datasetVersion:o,referenceFree:u,metadata:c}={}){const l=new URLSearchParams;if(e!==void 0)for(const d of e)l.append("id",d);if(t!==void 0&&l.append("name",t),r!==void 0&&l.append("name_contains",r),a!==void 0)l.append("reference_dataset",a);else if(s!==void 0){const d=await this.readDataset({datasetName:s});l.append("reference_dataset",d.id)}i!==void 0&&l.append("include_stats",i.toString()),o!==void 0&&l.append("dataset_version",o),u!==void 0&&l.append("reference_free",u.toString()),c!==void 0&&l.append("metadata",JSON.stringify(c));for await(const d of this._getPaginated("/sessions",l))yield*d}async deleteProject({projectId:e,projectName:t}){let r;if(e===void 0&&t===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?r=(await this.readProject({projectName:t})).id:r=e,B(r),await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(a,`delete session ${r} (${t})`,!0),a})}async uploadCsv({csvFile:e,fileName:t,inputKeys:r,outputKeys:a,description:s,dataType:i,name:o}){const u=`${this.apiUrl}/datasets/upload`,c=new FormData;return c.append("file",e,t),r.forEach(h=>{c.append("input_keys",h)}),a.forEach(h=>{c.append("output_keys",h)}),s&&c.append("description",s),i&&c.append("data_type",i),o&&c.append("name",o),await(await this.caller.call(async()=>{const h=await this._fetch(u,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await k(h,"upload CSV"),h})).json()}async createDataset(e,{description:t,dataType:r,inputsSchema:a,outputsSchema:s,metadata:i}={}){const o={name:e,description:t,extra:i?{metadata:i}:void 0};r&&(o.data_type=r),a&&(o.inputs_schema_definition=a),s&&(o.outputs_schema_definition=s);const u=JSON.stringify(o);return await(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await k(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:t}){let r="/datasets";const a=new URLSearchParams({limit:"1"});if(e&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(e)B(e),r+=`/${e}`;else if(t)a.append("name",t);else throw new Error("Must provide datasetName or datasetId");const s=await this._get(r,a);let i;if(Array.isArray(s)){if(s.length===0)throw new Error(`Dataset[id=${e}, name=${t}] not found`);i=s[0]}else i=s;return i}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(r){if(r instanceof Error&&r.message.toLocaleLowerCase().includes("not found"))return!1;throw r}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:r,toVersion:a}){let s=e;if(s===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:t})).id);const i=new URLSearchParams({from_version:typeof r=="string"?r:r.toISOString(),to_version:typeof a=="string"?a:a.toISOString()});return await this._get(`/datasets/${s}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){const r="/datasets";if(e===void 0)if(t!==void 0)e=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${r}/${e}/openai_ft`)).text()).trim().split(`
72
+ `).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:r,datasetName:a,datasetNameContains:s,metadata:i}={}){const o="/datasets",u=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(r!==void 0)for(const c of r)u.append("id",c);a!==void 0&&u.append("name",a),s!==void 0&&u.append("name_contains",s),i!==void 0&&u.append("metadata",JSON.stringify(i));for await(const c of this._getPaginated(o,u))yield*c}async updateDataset(e){const{datasetId:t,datasetName:r,...a}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const s=t??(await this.readDataset({datasetName:r})).id;B(s);const i=JSON.stringify(a);return await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await k(u,"update dataset"),u})).json()}async updateDatasetTag(e){const{datasetId:t,datasetName:r,asOf:a,tag:s}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const i=t??(await this.readDataset({datasetName:r})).id;B(i);const o=JSON.stringify({as_of:typeof a=="string"?a:a.toISOString(),tag:s});await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${i}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await k(u,"update dataset tags",!0),u})}async deleteDataset({datasetId:e,datasetName:t}){let r="/datasets",a=e;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0&&(a=(await this.readDataset({datasetName:t})).id),a!==void 0)B(a),r+=`/${a}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const s=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(s,`delete ${r}`,!0),s})}async indexDataset({datasetId:e,datasetName:t,tag:r}){let a=e;if(!a&&!t)throw new Error("Must provide either datasetName or datasetId");if(a&&t)throw new Error("Must provide either datasetName or datasetId, not both");a||(a=(await this.readDataset({datasetName:t})).id),B(a);const i=JSON.stringify({tag:r});await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${a}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await k(u,"index dataset"),u})).json()}async similarExamples(e,t,r,{filter:a}={}){const s={limit:r,inputs:e};a!==void 0&&(s.filter=a),B(t);const i=JSON.stringify(s);return(await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${t}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:i});return await k(c,"fetch similar examples"),c})).json()).examples}async createExample(e,t,r){var l;if(yc(e)&&(t!==void 0||r!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let a=t?r==null?void 0:r.datasetId:e.dataset_id;const s=t?r==null?void 0:r.datasetName:e.dataset_name;if(a===void 0&&s===void 0)throw new Error("Must provide either datasetName or datasetId");if(a!==void 0&&s!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");a===void 0&&(a=(await this.readDataset({datasetName:s})).id);const i=(t?r==null?void 0:r.createdAt:e.created_at)||new Date;let o;yc(e)?o=e:o={inputs:e,outputs:t,created_at:i==null?void 0:i.toISOString(),id:r==null?void 0:r.exampleId,metadata:r==null?void 0:r.metadata,split:r==null?void 0:r.split,source_run_id:r==null?void 0:r.sourceRunId,use_source_run_io:r==null?void 0:r.useSourceRunIO,use_source_run_attachments:r==null?void 0:r.useSourceRunAttachments,attachments:r==null?void 0:r.attachments};const u=await this._uploadExamplesMultipart(a,[o]);return await this.readExample(((l=u.example_ids)==null?void 0:l[0])??Ht())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];const b=e;let _=b[0].dataset_id;const w=b[0].dataset_name;if(_===void 0&&w===void 0)throw new Error("Must provide either datasetName or datasetId");if(_!==void 0&&w!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");_===void 0&&(_=(await this.readDataset({datasetName:w})).id);const v=await this._uploadExamplesMultipart(_,b);return await Promise.all(v.example_ids.map(O=>this.readExample(O)))}const{inputs:t,outputs:r,metadata:a,splits:s,sourceRunIds:i,useSourceRunIOs:o,useSourceRunAttachments:u,attachments:c,exampleIds:l,datasetId:d,datasetName:h}=e;if(t===void 0)throw new Error("Must provide inputs when using legacy parameters");let f=d;const m=h;if(f===void 0&&m===void 0)throw new Error("Must provide either datasetName or datasetId");if(f!==void 0&&m!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");f===void 0&&(f=(await this.readDataset({datasetName:m})).id);const p=t.map((b,_)=>({dataset_id:f,inputs:b,outputs:r==null?void 0:r[_],metadata:a==null?void 0:a[_],split:s==null?void 0:s[_],id:l==null?void 0:l[_],attachments:c==null?void 0:c[_],source_run_id:i==null?void 0:i[_],use_source_run_io:o==null?void 0:o[_],use_source_run_attachments:u==null?void 0:u[_]})),g=await this._uploadExamplesMultipart(f,p);return await Promise.all(g.example_ids.map(b=>this.readExample(b)))}async createLLMExample(e,t,r){return this.createExample({input:e},{output:t},r)}async createChatExample(e,t,r){const a=e.map(i=>bu(i)?wu(i):i),s=bu(t)?wu(t):t;return this.createExample({input:a},{output:s},r)}async readExample(e){B(e);const t=`/examples/${e}`,r=await this._get(t),{attachment_urls:a,...s}=r,i=s;return a&&(i.attachments=Object.entries(a).reduce((o,[u,c])=>(o[u.slice(11)]={presigned_url:c.presigned_url,mime_type:c.mime_type},o),{})),i}async*listExamples({datasetId:e,datasetName:t,exampleIds:r,asOf:a,splits:s,inlineS3Urls:i,metadata:o,limit:u,offset:c,filter:l,includeAttachments:d}={}){let h;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)h=e;else if(t!==void 0)h=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide a datasetName or datasetId");const f=new URLSearchParams({dataset:h}),m=a?typeof a=="string"?a:a==null?void 0:a.toISOString():void 0;m&&f.append("as_of",m);const p=i??!0;if(f.append("inline_s3_urls",p.toString()),r!==void 0)for(const y of r)f.append("id",y);if(s!==void 0)for(const y of s)f.append("splits",y);if(o!==void 0){const y=JSON.stringify(o);f.append("metadata",y)}u!==void 0&&f.append("limit",u.toString()),c!==void 0&&f.append("offset",c.toString()),l!==void 0&&f.append("filter",l),d===!0&&["attachment_urls","outputs","metadata"].forEach(y=>f.append("select",y));let g=0;for await(const y of this._getPaginated("/examples",f)){for(const b of y){const{attachment_urls:_,...w}=b,v=w;_&&(v.attachments=Object.entries(_).reduce((S,[O,T])=>(S[O.slice(11)]={presigned_url:T.presigned_url,mime_type:T.mime_type||void 0},S),{})),yield v,g++}if(u!==void 0&&g>=u)break}}async deleteExample(e){B(e);const t=`/examples/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(r,`delete ${t}`,!0),r})}async updateExample(e,t){let r;t?r=e:r=e.id,B(r);let a;t?a={id:r,...t}:a=e;let s;return a.dataset_id!==void 0?s=a.dataset_id:s=(await this.readExample(r)).dataset_id,this._updateExamplesMultipart(s,[a])}async updateExamples(e){let t;return e[0].dataset_id===void 0?t=(await this.readExample(e[0].id)).dataset_id:t=e[0].dataset_id,this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:r,tag:a}){let s;if(e?s=e:s=(await this.readDataset({datasetName:t})).id,B(s),r&&a||!r&&!a)throw new Error("Exactly one of asOf and tag must be specified.");const i=new URLSearchParams;return r!==void 0&&i.append("as_of",typeof r=="string"?r:r.toISOString()),a!==void 0&&i.append("tag",a),await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${s}/version?${i.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(u,"read dataset version"),u})).json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:r}){let a;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?a=(await this.readDataset({datasetName:t})).id:a=e,B(a);const s=new URLSearchParams,i=r?typeof r=="string"?r:r==null?void 0:r.toISOString():void 0;return i&&s.append("as_of",i),await this._get(`/datasets/${a}/splits`,s)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:r,exampleIds:a,remove:s=!1}){let i;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?i=(await this.readDataset({datasetName:t})).id:i=e,B(i);const o={split_name:r,examples:a.map(c=>(B(c),c)),remove:s},u=JSON.stringify(o);await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${i}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await k(c,"update dataset splits",!0),c})}async evaluateRun(e,t,{sourceInfo:r,loadChildRuns:a,referenceExample:s}={loadChildRuns:!1}){kd("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");let i;if(typeof e=="string")i=await this.readRun(e,{loadChildRuns:a});else if(typeof e=="object"&&"id"in e)i=e;else throw new Error(`Invalid run type: ${typeof e}`);i.reference_example_id!==null&&i.reference_example_id!==void 0&&(s=await this.readExample(i.reference_example_id));const o=await t.evaluateRun(i,s),[u,c]=await this._logEvaluationFeedback(o,i,r);return c[0]}async createFeedback(e,t,{score:r,value:a,correction:s,comment:i,sourceInfo:o,feedbackSourceType:u="api",sourceRunId:c,feedbackId:l,feedbackConfig:d,projectId:h,comparativeExperimentId:f}){var b;if(!e&&!h)throw new Error("One of runId or projectId must be provided");if(e&&h)throw new Error("Only one of runId or projectId can be provided");const m={type:u??"api",metadata:o??{}};c!==void 0&&(m==null?void 0:m.metadata)!==void 0&&!m.metadata.__run&&(m.metadata.__run={run_id:c}),(m==null?void 0:m.metadata)!==void 0&&((b=m.metadata.__run)==null?void 0:b.run_id)!==void 0&&B(m.metadata.__run.run_id);const p={id:l??Ht(),run_id:e,key:t,score:pc(r),value:a,correction:s,comment:i,feedback_source:m,comparative_experiment_id:f,feedbackConfig:d,session_id:h},g=JSON.stringify(p),y=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const _=await this._fetch(y,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:g});return await k(_,"create feedback",!0),_}),p}async updateFeedback(e,{score:t,value:r,correction:a,comment:s}){const i={};t!=null&&(i.score=pc(t)),r!=null&&(i.value=r),a!=null&&(i.correction=a),s!=null&&(i.comment=s),B(e);const o=JSON.stringify(i);await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await k(u,"update feedback",!0),u})}async readFeedback(e){B(e);const t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){B(e);const t=`/feedback/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(r,`delete ${t}`,!0),r})}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:r}={}){const a=new URLSearchParams;if(e)for(const s of e)B(s),a.append("run",s);if(t)for(const s of t)a.append("key",s);if(r)for(const s of r)a.append("source",s);for await(const s of this._getPaginated("/feedback",a))yield*s}async createPresignedFeedbackToken(e,t,{expiration:r,feedbackConfig:a}={}){const s={run_id:e,feedback_key:t,feedback_config:a};r?typeof r=="string"?s.expires_at=r:(r!=null&&r.hours||r!=null&&r.minutes||r!=null&&r.days)&&(s.expires_in=r):s.expires_in={hours:3};const i=JSON.stringify(s);return await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await k(u,"create presigned feedback token"),u})).json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:r,createdAt:a,description:s,metadata:i,id:o}){var d;if(t.length===0)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:t[0]})).reference_dataset_id),!r==null)throw new Error("A reference dataset is required");const u={id:o,name:e,experiment_ids:t,reference_dataset_id:r,description:s,created_at:(d=a??new Date)==null?void 0:d.toISOString(),extra:{}};i&&(u.extra.metadata=i);const c=JSON.stringify(u);return(await this.caller.call(async()=>{const h=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await k(h,"create comparative experiment"),h})).json()}async*listPresignedFeedbackTokens(e){B(e);const t=new URLSearchParams({run_id:e});for await(const r of this._getPaginated("/feedback/tokens",t))yield*r}_selectEvalResults(e){let t;return"results"in e?t=e.results:Array.isArray(e)?t=e:t=[e],t}async _logEvaluationFeedback(e,t,r){const a=this._selectEvalResults(e),s=[];for(const i of a){let o=r||{};i.evaluatorInfo&&(o={...i.evaluatorInfo,...o});let u=null;i.targetRunId?u=i.targetRunId:t&&(u=t.id),s.push(await this.createFeedback(u,i.key,{score:i.score,value:i.value,comment:i.comment,correction:i.correction,sourceInfo:o,sourceRunId:i.sourceRunId,feedbackConfig:i.feedbackConfig,feedbackSourceType:"model"}))}return[a,s]}async logEvaluationFeedback(e,t,r){const[a]=await this._logEvaluationFeedback(e,t,r);return a}async*listAnnotationQueues(e={}){const{queueIds:t,name:r,nameContains:a,limit:s}=e,i=new URLSearchParams;t&&t.forEach((u,c)=>{B(u,`queueIds[${c}]`),i.append("ids",u)}),r&&i.append("name",r),a&&i.append("name_contains",a),i.append("limit",(s!==void 0?Math.min(s,100):100).toString());let o=0;for await(const u of this._getPaginated("/annotation-queues",i))if(yield*u,o++,s!==void 0&&o>=s)break}async createAnnotationQueue(e){const{name:t,description:r,queueId:a,rubricInstructions:s}=e,i={name:t,description:r,id:a||Ht(),rubric_instructions:s},o=JSON.stringify(Object.fromEntries(Object.entries(i).filter(([c,l])=>l!==void 0)));return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await k(c,"create annotation queue"),c})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${B(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(r,"read annotation queue"),r})).json()}async updateAnnotationQueue(e,t){const{name:r,description:a,rubricInstructions:s}=t,i=JSON.stringify({name:r,description:a,rubric_instructions:s});await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/annotation-queues/${B(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await k(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${B(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,"delete annotation queue",!0),t})}async addRunsToAnnotationQueue(e,t){const r=JSON.stringify(t.map((a,s)=>B(a,`runIds[${s}]`).toString()));await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/annotation-queues/${B(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await k(a,"add runs to annotation queue",!0),a})}async getRunFromAnnotationQueue(e,t){const r=`/annotation-queues/${B(e,"queueId")}/run`;return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${r}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(s,"get run from annotation queue"),s})).json()}async deleteRunFromAnnotationQueue(e,t){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${B(e,"queueId")}/runs/${B(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(r,"delete run from annotation queue",!0),r})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${B(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(r,"get size from annotation queue"),r})).json()}async _currentTenantIsOwner(e){const t=await this._getSettings();return e=="-"||t.tenant_handle===e}async _ownerConflictError(e,t){const r=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
73
+
74
+ Current tenant: ${r.tenant_handle}
75
+
76
+ Requested tenant: ${t}`)}async _getLatestCommitHash(e){const r=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(a,"get latest commit hash"),a})).json();if(r.commits.length!==0)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){const[r,a,s]=ht(e),i=JSON.stringify({like:t});return(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/likes/${r}/${a}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await k(u,`${t?"like":"unlike"} prompt`),u})).json()}async _getPromptUrl(e){const[t,r,a]=ht(e);if(await this._currentTenantIsOwner(t)){const s=await this._getSettings();return a!=="latest"?`${this.getHostUrl()}/prompts/${r}/${a.substring(0,8)}?organizationId=${s.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${s.id}`}else return a!=="latest"?`${this.getHostUrl()}/hub/${t}/${r}/${a.substring(0,8)}`:`${this.getHostUrl()}/hub/${t}/${r}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(const t of this._getPaginated(`/commits/${e}/`,new URLSearchParams,r=>r.commits))yield*t}async*listPrompts(e){const t=new URLSearchParams;t.append("sort_field",(e==null?void 0:e.sortField)??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!(e!=null&&e.isArchived)).toString()),(e==null?void 0:e.isPublic)!==void 0&&t.append("is_public",e.isPublic.toString()),e!=null&&e.query&&t.append("query",e.query);for await(const r of this._getPaginated("/repos",t,a=>a.repos))yield*r}async getPrompt(e){const[t,r,a]=ht(e),s=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return(o==null?void 0:o.status)===404?null:(await k(o,"get prompt"),o)}),i=await(s==null?void 0:s.json());return i!=null&&i.repo?i.repo:null}async createPrompt(e,t){const r=await this._getSettings();if(t!=null&&t.isPublic&&!r.tenant_handle)throw new Error(`Cannot create a public prompt without first
77
+
78
+ creating a LangChain Hub handle.
79
+ You can add a handle by creating a public prompt at:
80
+
81
+ https://smith.langchain.com/prompts`);const[a,s,i]=ht(e);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("create a prompt",a);const o={repo_handle:s,...(t==null?void 0:t.description)&&{description:t.description},...(t==null?void 0:t.readme)&&{readme:t.readme},...(t==null?void 0:t.tags)&&{tags:t.tags},is_public:!!(t!=null&&t.isPublic)},u=JSON.stringify(o),c=await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await k(d,"create prompt"),d}),{repo:l}=await c.json();return l}async createCommit(e,t,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[a,s,i]=ht(e),o=(r==null?void 0:r.parentCommitHash)==="latest"||!(r!=null&&r.parentCommitHash)?await this._getLatestCommitHash(`${a}/${s}`):r==null?void 0:r.parentCommitHash,u={manifest:JSON.parse(JSON.stringify(t)),parent_commit:o},c=JSON.stringify(u),d=await(await this.caller.call(async()=>{const h=await this._fetch(`${this.apiUrl}/commits/${a}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await k(h,"create commit"),h})).json();return this._getPromptUrl(`${a}/${s}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){var i;if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const o of t){const u=o.id,c={...o.metadata&&{metadata:o.metadata},...o.split&&{split:o.split}},l=ke(c,`Serializing body for example with id: ${u}`),d=new Blob([l],{type:"application/json"});if(r.append(u,d),o.inputs){const h=ke(o.inputs,`Serializing inputs for example with id: ${u}`),f=new Blob([h],{type:"application/json"});r.append(`${u}.inputs`,f)}if(o.outputs){const h=ke(o.outputs,`Serializing outputs whle updating example with id: ${u}`),f=new Blob([h],{type:"application/json"});r.append(`${u}.outputs`,f)}if(o.attachments)for(const[h,f]of Object.entries(o.attachments)){let m,p;Array.isArray(f)?[m,p]=f:(m=f.mimeType,p=f.data);const g=new Blob([p],{type:`${m}; length=${p.byteLength}`});r.append(`${u}.attachment.${h}`,g)}if(o.attachments_operations){const h=ke(o.attachments_operations,`Serializing attachments while updating example with id: ${u}`),f=new Blob([h],{type:"application/json"});r.append(`${u}.attachments_operations`,f)}}const a=e??((i=t[0])==null?void 0:i.dataset_id);return(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${a}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await k(o,"update examples"),o})).json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const s of t){const i=(s.id??Ht()).toString(),o={created_at:s.created_at,...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split},...s.source_run_id&&{source_run_id:s.source_run_id},...s.use_source_run_io&&{use_source_run_io:s.use_source_run_io},...s.use_source_run_attachments&&{use_source_run_attachments:s.use_source_run_attachments}},u=ke(o,`Serializing body for uploaded example with id: ${i}`),c=new Blob([u],{type:"application/json"});if(r.append(i,c),s.inputs){const l=ke(s.inputs,`Serializing inputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});r.append(`${i}.inputs`,d)}if(s.outputs){const l=ke(s.outputs,`Serializing outputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});r.append(`${i}.outputs`,d)}if(s.attachments)for(const[l,d]of Object.entries(s.attachments)){let h,f;Array.isArray(d)?[h,f]=d:(h=d.mimeType,f=d.data);const m=new Blob([f],{type:`${h}; length=${f.byteLength}`});r.append(`${i}.attachment.${l}`,m)}}return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await k(s,"upload examples"),s})).json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,a]=ht(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);const s={};if((t==null?void 0:t.description)!==void 0&&(s.description=t.description),(t==null?void 0:t.readme)!==void 0&&(s.readme=t.readme),(t==null?void 0:t.tags)!==void 0&&(s.tags=t.tags),(t==null?void 0:t.isPublic)!==void 0&&(s.is_public=t.isPublic),(t==null?void 0:t.isArchived)!==void 0&&(s.is_archived=t.isArchived),Object.keys(s).length===0)throw new Error("No valid update options provided");const i=JSON.stringify(s);return(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/repos/${r}/${a}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await k(u,"update prompt"),u})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[t,r,a]=ht(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(i,"delete prompt"),i})).json()}async pullPromptCommit(e,t){const[r,a,s]=ht(e),o=await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/commits/${r}/${a}/${s}${t!=null&&t.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(u,"pull prompt commit"),u})).json();return{owner:r,repo:a,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(e,t){const r=await this.pullPromptCommit(e,{includeModel:t==null?void 0:t.includeModel});return JSON.stringify(r.manifest)}async pushPrompt(e,t){return await this.promptExists(e)?t&&Object.keys(t).some(a=>a!=="object")&&await this.updatePrompt(e,{description:t==null?void 0:t.description,readme:t==null?void 0:t.readme,tags:t==null?void 0:t.tags,isPublic:t==null?void 0:t.isPublic}):await this.createPrompt(e,{description:t==null?void 0:t.description,readme:t==null?void 0:t.readme,tags:t==null?void 0:t.tags,isPublic:t==null?void 0:t.isPublic}),t!=null&&t.object?await this.createCommit(e,t==null?void 0:t.object,{parentCommitHash:t==null?void 0:t.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,t={}){const{sourceApiUrl:r=this.apiUrl,datasetName:a}=t,[s,i]=this.parseTokenOrUrl(e,r),o=new Cr({apiUrl:s,apiKey:"placeholder"}),u=await o.readSharedDataset(i),c=a||u.name;try{if(await this.hasDataset({datasetId:c})){console.log(`Dataset ${c} already exists in your tenant. Skipping.`);return}}catch{}const l=await o.listSharedExamples(i),d=await this.createDataset(c,{description:u.description,dataType:u.data_type||"kv",inputsSchema:u.inputs_schema_definition??void 0,outputsSchema:u.outputs_schema_definition??void 0});try{await this.createExamples({inputs:l.map(h=>h.inputs),outputs:l.flatMap(h=>h.outputs?[h.outputs]:[]),datasetId:d.id})}catch(h){throw console.error(`An error occurred while creating dataset ${c}. You should delete it manually.`),h}}parseTokenOrUrl(e,t,r=2,a="dataset"){try{return B(e),[t,e]}catch{}try{const i=new URL(e).pathname.split("/").filter(o=>o!=="");if(i.length>=r){const o=i[i.length-r];return[t,o]}else throw new Error(`Invalid public ${a} URL: ${e}`)}catch{throw new Error(`Invalid public ${a} URL or token: ${e}`)}}async awaitPendingTraceBatches(){var e,t;if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:r})=>r),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await((t=(e=Mp())==null?void 0:e.DEFAULT_LANGSMITH_SPAN_PROCESSOR)==null?void 0:t.forceFlush())}}function yc(n){return"dataset_id"in n||"dataset_name"in n}const Mg=n=>!!["TRACING_V2","TRACING"].find(t=>xe(t)==="true"),Ms=Symbol.for("lc:context_variables");function Ug(n){return n.replace(/[-:.]/g,"")}function Fd(n,e,t=1){const r=t.toFixed(0).slice(0,3).padStart(3,"0"),a=`${new Date(n).toISOString().slice(0,-1)}${r}Z`;return{dottedOrder:Ug(a)+e,microsecondPrecisionDatestring:a}}class Mn{constructor(e,t,r,a){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=t,this.project_name=r,this.replicas=a}static fromHeader(e){const t=e.split(",");let r={},a=[],s,i;for(const o of t){const[u,c]=o.split("="),l=decodeURIComponent(c);u==="langsmith-metadata"?r=JSON.parse(l):u==="langsmith-tags"?a=l.split(","):u==="langsmith-project"?s=l:u==="langsmith-replicas"&&(i=JSON.parse(l))}return new Mn(r,a,s,i)}toHeader(){const e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class Ae{constructor(e){var o;if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Fg(e)){Object.assign(this,{...e});return}const t=Ae.getDefaultConfig(),{metadata:r,...a}=e,s=a.client??Ae.getSharedClient(),i={...r,...(o=a==null?void 0:a.extra)==null?void 0:o.metadata};if(a.extra={...a.extra,metadata:i},Object.assign(this,{...t,...a,client:s}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=Hg(this.replicas),this.execution_order??(this.execution_order=1),this.child_execution_order??(this.child_execution_order=1),!this.dotted_order){const{dottedOrder:u,microsecondPrecisionDatestring:c}=Fd(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+u:this.dotted_order=u,this._serialized_start_time=c}}set metadata(e){var t;this.extra={...this.extra,metadata:{...(t=this.extra)==null?void 0:t.metadata,...e}}}get metadata(){var e;return(e=this.extra)==null?void 0:e.metadata}static getDefaultConfig(){return{id:Ht(),run_type:"chain",project_name:Od(),child_runs:[],api_url:rt("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:rt("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return Ae.sharedClient||(Ae.sharedClient=new Cr),Ae.sharedClient}createChild(e){var u,c,l,d,h,f;const t=this.child_execution_order+1,r=new Ae({...e,parent_run:this,project_name:this.project_name,replicas:this.replicas,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t});Ms in this&&(r[Ms]=this[Ms]);const a=Symbol.for("lc:child_config"),s=((u=e.extra)==null?void 0:u[a])??this.extra[a];if(Bg(s)){const m={...s},p=Dg(m.callbacks)?(l=(c=m.callbacks).copy)==null?void 0:l.call(c):void 0;p&&(Object.assign(p,{_parentRunId:r.id}),(f=(h=(d=p.handlers)==null?void 0:d.find(Dd))==null?void 0:h.updateFromRunTree)==null||f.call(h,r),m.callbacks=p),r.extra[a]=m}const i=new Set;let o=this;for(;o!=null&&!i.has(o.id);)i.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,t),o=o.parent_run;return this.child_runs.push(r),r}async end(e,t,r=Date.now(),a){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??r,a&&Object.keys(a).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...a}}:{metadata:a})}_convertToCreate(e,t,r=!0){var o,u;const a=e.extra??{};if(((o=a==null?void 0:a.runtime)==null?void 0:o.library)===void 0&&(a.runtime||(a.runtime={}),t))for(const[c,l]of Object.entries(t))a.runtime[c]||(a.runtime[c]=l);let s,i;return r?(i=((u=e.parent_run)==null?void 0:u.id)??e.parent_run_id,s=[]):(s=e.child_runs.map(c=>this._convertToCreate(c,t,r)),i=void 0),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:a,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:s,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_remapForProject(e,t,r=!0){const a=this._convertToCreate(this,t,r);if(e===this.project_name)return a;const s=d=>su(`${d}:${e}`,su.DNS),i=s(a.id),o=a.trace_id?s(a.trace_id):void 0,u=a.parent_run_id?s(a.parent_run_id):void 0;let c;if(a.dotted_order){const d=qg(a.dotted_order),h=[];for(let m=0;m<d.length-1;m++){const[p,g]=d[m],y=s(g);h.push(p.toISOString().replace(/[-:]/g,"").replace(".","")+y)}const[f]=d[d.length-1];h.push(f.toISOString().replace(/[-:]/g,"").replace(".","")+i),c=h.join(".")}else c=void 0;return{...a,id:i,trace_id:o,parent_run_id:u,dotted_order:c,session_name:e}}async postRun(e=!0){try{const t=xd();if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:a,apiUrl:s,workspaceId:i}of this.replicas){const o=this._remapForProject(r??this.project_name,t,!0);await this.client.createRun(o,{apiKey:a,apiUrl:s,workspaceId:i})}else{const r=this._convertToCreate(this,t,e);await this.client.createRun(r)}if(!e){kd("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const r of this.child_runs)await r.postRun(!1)}}catch(t){console.error(`Error in postRun for run ${this.id}:`,t)}}async patchRun(e){var t;if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:a,apiUrl:s,workspaceId:i,updates:o}of this.replicas){const u=this._remapForProject(r??this.project_name),c={id:u.id,outputs:u.outputs,error:u.error,parent_run_id:u.parent_run_id,session_name:u.session_name,reference_example_id:u.reference_example_id,end_time:u.end_time,dotted_order:u.dotted_order,trace_id:u.trace_id,events:u.events,tags:u.tags,extra:u.extra,attachments:this.attachments,...o};e!=null&&e.excludeInputs||(c.inputs=u.inputs),await this.client.updateRun(u.id,c,{apiKey:a,apiUrl:s,workspaceId:i})}else try{const r={end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:((t=this.parent_run)==null?void 0:t.id)??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e!=null&&e.excludeInputs||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,t){var c,l,d,h;const r=e==null?void 0:e.callbacks;let a,s,i,o=Mg();if(r){const f=((c=r==null?void 0:r.getParentRunId)==null?void 0:c.call(r))??"",m=(l=r==null?void 0:r.handlers)==null?void 0:l.find(p=>(p==null?void 0:p.name)=="langchain_tracer");a=(d=m==null?void 0:m.getRun)==null?void 0:d.call(m,f),s=m==null?void 0:m.projectName,i=m==null?void 0:m.client,o=o||!!m}return a?new Ae({name:a.name,id:a.id,trace_id:a.trace_id,dotted_order:a.dotted_order,client:i,tracingEnabled:o,project_name:s,tags:[...new Set(((a==null?void 0:a.tags)??[]).concat((e==null?void 0:e.tags)??[]))],extra:{metadata:{...(h=a==null?void 0:a.extra)==null?void 0:h.metadata,...e==null?void 0:e.metadata}}}).createChild(t):new Ae({...t,client:i,tracingEnabled:o,project_name:s})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){var c;const r="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,a=r["langsmith-trace"];if(!a||typeof a!="string")return;const s=a.trim(),i=s.split(".").map(l=>{const[d,h]=l.split("Z");return{strTime:d,time:Date.parse(d+"Z"),uuid:h}}),o=i[0].uuid,u={...t,name:(t==null?void 0:t.name)??"parent",run_type:(t==null?void 0:t.run_type)??"chain",start_time:(t==null?void 0:t.start_time)??Date.now(),id:(c=i.at(-1))==null?void 0:c.uuid,trace_id:o,dotted_order:s};if(r.baggage&&typeof r.baggage=="string"){const l=Mn.fromHeader(r.baggage);u.metadata=l.metadata,u.tags=l.tags,u.project_name=l.project_name,u.replicas=l.replicas}return new Ae(u)}toHeaders(e){var r;const t={"langsmith-trace":this.dotted_order,baggage:new Mn((r=this.extra)==null?void 0:r.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(const[a,s]of Object.entries(t))e.set(a,s);return t}}Object.defineProperty(Ae,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Fg(n){return n!=null&&typeof n.createChild=="function"&&typeof n.postRun=="function"}function Dd(n){return typeof n=="object"&&n!=null&&typeof n.name=="string"&&n.name==="langchain_tracer"}function _c(n){return Array.isArray(n)&&n.some(e=>Dd(e))}function Dg(n){return typeof n=="object"&&n!=null&&Array.isArray(n.handlers)}function Bg(n){var e;return n!=null&&typeof n.callbacks=="object"&&(_c((e=n.callbacks)==null?void 0:e.handlers)||_c(n.callbacks))}function qg(n){return n.split(".").map(t=>{const r=t.slice(0,-36),a=t.slice(-36),s=parseInt(r.slice(0,4)),i=parseInt(r.slice(4,6))-1,o=parseInt(r.slice(6,8)),u=parseInt(r.slice(9,11)),c=parseInt(r.slice(11,13)),l=parseInt(r.slice(13,15)),d=parseInt(r.slice(15,21));return[new Date(s,i,o,u,c,l,d/1e3),a]})}function zg(){const n=rt("LANGSMITH_RUNS_ENDPOINTS");if(!n)return[];try{const e=JSON.parse(n);if(Array.isArray(e)){const t=[];for(const r of e){if(typeof r!="object"||r===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof r}`);continue}if(typeof r.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_url}`);continue}if(typeof r.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_key}`);continue}t.push({apiUrl:r.api_url.replace(/\/$/,""),apiKey:r.api_key})}return t}else if(typeof e=="object"&&e!==null){Gg(e);const t=[];for(const[r,a]of Object.entries(e)){const s=r.replace(/\/$/,"");if(typeof a=="string")t.push({apiUrl:s,apiKey:a});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${r}: expected string, got ${typeof a}`);continue}}return t}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(Sg(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function Hg(n){return n?n.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):zg()}function Gg(n){if(Object.keys(n).length>0&&xe("ENDPOINT"))throw new Eg}var Us={};const Wg=()=>typeof window<"u"&&typeof window.document<"u",Jg=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Zg=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),ro=()=>typeof Deno<"u",Kg=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!ro(),Vg=()=>{let n;return Wg()?n="browser":Kg()?n="node":Jg()?n="webworker":Zg()?n="jsdom":ro()?n="deno":n="other",n};let Fs;function Xg(){return Fs===void 0&&(Fs={library:"langchain-js",runtime:Vg()}),Fs}function _t(n){try{return typeof process<"u"?Us==null?void 0:Us[n]:ro()?Deno==null?void 0:Deno.env.get(n):void 0}catch{return}}class Qg{}function Yg(n){return"lc_prefer_streaming"in n&&n.lc_prefer_streaming}class Hr extends Qg{get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,gd(this.constructor)]}constructor(e){super(),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ignoreLLM",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreChain",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreAgent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreRetriever",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreCustomEvent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"raiseError",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"awaitHandlers",{enumerable:!0,configurable:!0,writable:!0,value:_t("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"}),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return $t.prototype.toJSON.call(this)}toJSONNotImplemented(){return $t.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends Hr{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:it()}),Object.assign(this,e)}}return new t}}const ey=n=>{const e=n;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},ty=n=>{if(n)return n.events=n.events??[],n.child_runs=n.child_runs??[],n};function gi(n,e){if(n)return new Ae({...n,start_time:n._serialized_start_time??n.start_time,parent_run:gi(e),child_runs:n.child_runs.map(t=>gi(t)).filter(t=>t!==void 0),extra:{...n.extra,runtime:Xg()},tracingEnabled:!1})}function Ds(n,e){return n&&!Array.isArray(n)&&typeof n=="object"?n:{[e]:n}}function or(n){return typeof n._addRunToRunMap=="function"}class Gr extends Hr{constructor(e){super(...arguments),Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"runTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"usesRunTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:!1})}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?ty(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e!=null&&e.stack?`
82
+
83
+ ${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const{dottedOrder:t,microsecondPrecisionDatestring:r}=Fd(new Date(e.start_time).getTime(),e.id,e.execution_order),a={...e},s=this.getRunById(a.parent_run_id);if(a.parent_run_id!==void 0?s&&(this._addChildRun(s,a),s.child_execution_order=Math.max(s.child_execution_order,a.child_execution_order),a.trace_id=s.trace_id,s.dotted_order!==void 0&&(a.dotted_order=[s.dotted_order,t].join("."),a._serialized_start_time=r)):(a.trace_id=a.id,a.dotted_order=t,a._serialized_start_time=r),this.usesRunTreeMap){const i=gi(a,s);i!==void 0&&this.runTreeMap.set(a.id,i)}else this.runMap.set(a.id,a);return a}async _endTrace(e){var r;const t=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await((r=this.onRunUpdate)==null?void 0:r.call(this,e)),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){const t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,a,s,i,o,u){const c=this._getExecutionOrder(a),l=Date.now(),d=o?{...s,metadata:o}:s,h={id:r,name:u??e.id[e.id.length-1],parent_run_id:a,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(h)}async handleLLMStart(e,t,r,a,s,i,o,u){var l,d;const c=this.getRunById(r)??this._createRunForLLMStart(e,t,r,a,s,i,o,u);return await((l=this.onRunCreate)==null?void 0:l.call(this,c)),await((d=this.onLLMStart)==null?void 0:d.call(this,c)),c}_createRunForChatModelStart(e,t,r,a,s,i,o,u){const c=this._getExecutionOrder(a),l=Date.now(),d=o?{...s,metadata:o}:s,h={id:r,name:u??e.id[e.id.length-1],parent_run_id:a,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(h)}async handleChatModelStart(e,t,r,a,s,i,o,u){var l,d;const c=this.getRunById(r)??this._createRunForChatModelStart(e,t,r,a,s,i,o,u);return await((l=this.onRunCreate)==null?void 0:l.call(this,c)),await((d=this.onLLMStart)==null?void 0:d.call(this,c)),c}async handleLLMEnd(e,t,r,a,s){var o;const i=this.getRunById(t);if(!i||(i==null?void 0:i.run_type)!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.outputs=e,i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...s},await((o=this.onLLMEnd)==null?void 0:o.call(this,i)),await this._endTrace(i),i}async handleLLMError(e,t,r,a,s){var o;const i=this.getRunById(t);if(!i||(i==null?void 0:i.run_type)!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...s},await((o=this.onLLMError)==null?void 0:o.call(this,i)),await this._endTrace(i),i}_createRunForChainStart(e,t,r,a,s,i,o,u){const c=this._getExecutionOrder(a),l=Date.now(),d={id:r,name:u??e.id[e.id.length-1],parent_run_id:a,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:t,execution_order:c,child_execution_order:c,run_type:o??"chain",child_runs:[],extra:i?{metadata:i}:{},tags:s||[]};return this._addRunToRunMap(d)}async handleChainStart(e,t,r,a,s,i,o,u){var l,d;const c=this.getRunById(r)??this._createRunForChainStart(e,t,r,a,s,i,o,u);return await((l=this.onRunCreate)==null?void 0:l.call(this,c)),await((d=this.onChainStart)==null?void 0:d.call(this,c)),c}async handleChainEnd(e,t,r,a,s){var o;const i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=Ds(e,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),(s==null?void 0:s.inputs)!==void 0&&(i.inputs=Ds(s.inputs,"input")),await((o=this.onChainEnd)==null?void 0:o.call(this,i)),await this._endTrace(i),i}async handleChainError(e,t,r,a,s){var o;const i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),(s==null?void 0:s.inputs)!==void 0&&(i.inputs=Ds(s.inputs,"input")),await((o=this.onChainError)==null?void 0:o.call(this,i)),await this._endTrace(i),i}_createRunForToolStart(e,t,r,a,s,i,o){const u=this._getExecutionOrder(a),c=Date.now(),l={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:u,child_execution_order:u,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:s||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,r,a,s,i,o){var c,l;const u=this.getRunById(r)??this._createRunForToolStart(e,t,r,a,s,i,o);return await((c=this.onRunCreate)==null?void 0:c.call(this,u)),await((l=this.onToolStart)==null?void 0:l.call(this,u)),u}async handleToolEnd(e,t){var a;const r=this.getRunById(t);if(!r||(r==null?void 0:r.run_type)!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await((a=this.onToolEnd)==null?void 0:a.call(this,r)),await this._endTrace(r),r}async handleToolError(e,t){var a;const r=this.getRunById(t);if(!r||(r==null?void 0:r.run_type)!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await((a=this.onToolError)==null?void 0:a.call(this,r)),await this._endTrace(r),r}async handleAgentAction(e,t){var s;const r=this.getRunById(t);if(!r||(r==null?void 0:r.run_type)!=="chain")return;const a=r;a.actions=a.actions||[],a.actions.push(e),a.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await((s=this.onAgentAction)==null?void 0:s.call(this,r))}async handleAgentEnd(e,t){var a;const r=this.getRunById(t);!r||(r==null?void 0:r.run_type)!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await((a=this.onAgentEnd)==null?void 0:a.call(this,r)))}_createRunForRetrieverStart(e,t,r,a,s,i,o){const u=this._getExecutionOrder(a),c=Date.now(),l={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:u,child_execution_order:u,run_type:"retriever",child_runs:[],extra:i?{metadata:i}:{},tags:s||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,r,a,s,i,o){var c,l;const u=this.getRunById(r)??this._createRunForRetrieverStart(e,t,r,a,s,i,o);return await((c=this.onRunCreate)==null?void 0:c.call(this,u)),await((l=this.onRetrieverStart)==null?void 0:l.call(this,u)),u}async handleRetrieverEnd(e,t){var a;const r=this.getRunById(t);if(!r||(r==null?void 0:r.run_type)!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await((a=this.onRetrieverEnd)==null?void 0:a.call(this,r)),await this._endTrace(r),r}async handleRetrieverError(e,t){var a;const r=this.getRunById(t);if(!r||(r==null?void 0:r.run_type)!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await((a=this.onRetrieverError)==null?void 0:a.call(this,r)),await this._endTrace(r),r}async handleText(e,t){var a;const r=this.getRunById(t);!r||(r==null?void 0:r.run_type)!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await((a=this.onText)==null?void 0:a.call(this,r)))}async handleLLMNewToken(e,t,r,a,s,i){var u;const o=this.getRunById(r);if(!o||(o==null?void 0:o.run_type)!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return o.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:i==null?void 0:i.chunk}}),await((u=this.onLLMNewToken)==null?void 0:u.call(this,o,e,{chunk:i==null?void 0:i.chunk})),o}}var Sn={exports:{}};Sn.exports;var bc;function ry(){return bc||(bc=1,(function(n){const t=(s=0)=>i=>`\x1B[${38+s};5;${i}m`,r=(s=0)=>(i,o,u)=>`\x1B[${38+s};2;${i};${o};${u}m`;function a(){const s=new Map,i={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};i.color.gray=i.color.blackBright,i.bgColor.bgGray=i.bgColor.bgBlackBright,i.color.grey=i.color.blackBright,i.bgColor.bgGrey=i.bgColor.bgBlackBright;for(const[o,u]of Object.entries(i)){for(const[c,l]of Object.entries(u))i[c]={open:`\x1B[${l[0]}m`,close:`\x1B[${l[1]}m`},u[c]=i[c],s.set(l[0],l[1]);Object.defineProperty(i,o,{value:u,enumerable:!1})}return Object.defineProperty(i,"codes",{value:s,enumerable:!1}),i.color.close="\x1B[39m",i.bgColor.close="\x1B[49m",i.color.ansi256=t(),i.color.ansi16m=r(),i.bgColor.ansi256=t(10),i.bgColor.ansi16m=r(10),Object.defineProperties(i,{rgbToAnsi256:{value:(o,u,c)=>o===u&&u===c?o<8?16:o>248?231:Math.round((o-8)/247*24)+232:16+36*Math.round(o/255*5)+6*Math.round(u/255*5)+Math.round(c/255*5),enumerable:!1},hexToRgb:{value:o=>{const u=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(o.toString(16));if(!u)return[0,0,0];let{colorString:c}=u.groups;c.length===3&&(c=c.split("").map(d=>d+d).join(""));const l=Number.parseInt(c,16);return[l>>16&255,l>>8&255,l&255]},enumerable:!1},hexToAnsi256:{value:o=>i.rgbToAnsi256(...i.hexToRgb(o)),enumerable:!1}}),i}Object.defineProperty(n,"exports",{enumerable:!0,get:a})})(Sn)),Sn.exports}var ny=ry();const Bd=Lr(ny);function we(n,e){return`${n.open}${e}${n.close}`}function Me(n,e){try{return JSON.stringify(n,null,2)}catch{return e}}function wc(n){return typeof n=="string"?n.trim():n==null?n:Me(n,n.toString())}function ft(n){if(!n.end_time)return"";const e=n.end_time-n.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}const{color:Te}=Bd;class vc extends Gr{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(e){return Promise.resolve()}getParents(e){const t=[];let r=e;for(;r.parent_run_id;){const a=this.runMap.get(r.parent_run_id);if(a)t.push(a),r=a;else break}return t}getBreadcrumbs(e){const r=[...this.getParents(e).reverse(),e].map((a,s,i)=>{const o=`${a.execution_order}:${a.run_type}:${a.name}`;return s===i.length-1?we(Bd.bold,o):o}).join(" > ");return we(Te.grey,r)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${we(Te.green,"[chain/start]")} [${t}] Entering Chain run with input: ${Me(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${we(Te.cyan,"[chain/end]")} [${t}] [${ft(e)}] Exiting Chain run with output: ${Me(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${we(Te.red,"[chain/error]")} [${t}] [${ft(e)}] Chain run errored with error: ${Me(e.error,"[error]")}`)}onLLMStart(e){const t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(a=>a.trim())}:e.inputs;console.log(`${we(Te.green,"[llm/start]")} [${t}] Entering LLM run with input: ${Me(r,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${we(Te.cyan,"[llm/end]")} [${t}] [${ft(e)}] Exiting LLM run with output: ${Me(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${we(Te.red,"[llm/error]")} [${t}] [${ft(e)}] LLM run errored with error: ${Me(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${we(Te.green,"[tool/start]")} [${t}] Entering Tool run with input: "${wc(e.inputs.input)}"`)}onToolEnd(e){var r;const t=this.getBreadcrumbs(e);console.log(`${we(Te.cyan,"[tool/end]")} [${t}] [${ft(e)}] Exiting Tool run with output: "${wc((r=e.outputs)==null?void 0:r.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${we(Te.red,"[tool/error]")} [${t}] [${ft(e)}] Tool run errored with error: ${Me(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${we(Te.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${Me(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${we(Te.cyan,"[retriever/end]")} [${t}] [${ft(e)}] Exiting Retriever run with output: ${Me(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${we(Te.red,"[retriever/error]")} [${t}] [${ft(e)}] Retriever run errored with error: ${Me(e.error,"[error]")}`)}onAgentAction(e){const t=e,r=this.getBreadcrumbs(e);console.log(`${we(Te.blue,"[agent/action]")} [${r}] Agent selected action: ${Me(t.actions[t.actions.length-1],"[action]")}`)}}let Bs;const ay=()=>{if(Bs===void 0){const n=_t("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};Bs=new Cr(n)}return Bs};class Ar extends Gr{constructor(e={}){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"usesRunTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:!0});const{exampleId:t,projectName:r,client:a,replicas:s}=e;this.projectName=r??Od(),this.replicas=s,this.exampleId=t,this.client=a??ay();const i=Ar.getTraceableRunTree();i&&this.updateFromRunTree(i)}async persistRun(e){}async onRunCreate(e){const t=this.getRunTreeWithTracingConfig(e.id);await(t==null?void 0:t.postRun())}async onRunUpdate(e){const t=this.getRunTreeWithTracingConfig(e.id);await(t==null?void 0:t.patchRun())}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let t=e;const r=new Set;for(;t.parent_run&&!(r.has(t.id)||(r.add(t.id),!t.parent_run));)t=t.parent_run;r.clear();const a=[t];for(;a.length>0;){const s=a.shift();!s||r.has(s.id)||(r.add(s.id),this.runTreeMap.set(s.id,s),s.child_runs&&a.push(...s.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(e){const t=this.runTreeMap.get(e);if(t)return new Ae({...t,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return xm(!0)}catch{return}}}const qd=Symbol.for("ls:tracing_async_local_storage"),On=Symbol.for("lc:context_variables"),sy=n=>{globalThis[qd]=n},Nr=()=>globalThis[qd];let Pr;function iy(){const n="default"in ut?ut.default:ut;return new n({autoStart:!0,concurrency:1})}function oy(){return typeof Pr>"u"&&(Pr=iy()),Pr}async function ie(n,e){if(e===!0){const t=Nr();t!==void 0?await t.run(void 0,async()=>n()):await n()}else Pr=oy(),Pr.add(async()=>{const t=Nr();t!==void 0?await t.run(void 0,async()=>n()):await n()})}const uy=n=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(t=>_t(t)==="true");function zd(n){var r;const e=Nr();if(e===void 0)return;const t=e.getStore();return(r=t==null?void 0:t[On])==null?void 0:r[n]}const cy=Symbol("lc:configure_hooks"),ly=()=>zd(cy)||[];class dy{setHandler(e){return this.setHandlers([e])}}class ha{constructor(e,t,r,a,s,i,o,u){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:u})}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>ie(async()=>{var r;try{await((r=t.handleText)==null?void 0:r.call(t,e,this.runId,this._parentRunId,this.tags))}catch(a){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${a}`),t.raiseError)throw a}},t.awaitHandlers)))}async handleCustomEvent(e,t,r,a,s){await Promise.all(this.handlers.map(i=>ie(async()=>{var o;try{await((o=i.handleCustomEvent)==null?void 0:o.call(i,e,t,this.runId,this.tags,this.metadata))}catch(u){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${u}`),i.raiseError)throw u}},i.awaitHandlers)))}}class hy extends ha{getChild(e){const t=new Ie(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>ie(async()=>{var r;if(!t.ignoreRetriever)try{await((r=t.handleRetrieverEnd)==null?void 0:r.call(t,e,this.runId,this._parentRunId,this.tags))}catch(a){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw a}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>ie(async()=>{var r;if(!t.ignoreRetriever)try{await((r=t.handleRetrieverError)==null?void 0:r.call(t,e,this.runId,this._parentRunId,this.tags))}catch(a){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${a}`),t.raiseError)throw e}},t.awaitHandlers)))}}class Ec extends ha{async handleLLMNewToken(e,t,r,a,s,i){await Promise.all(this.handlers.map(o=>ie(async()=>{var u;if(!o.ignoreLLM)try{await((u=o.handleLLMNewToken)==null?void 0:u.call(o,e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i))}catch(c){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleLLMNewToken: ${c}`),o.raiseError)throw c}},o.awaitHandlers)))}async handleLLMError(e,t,r,a,s){await Promise.all(this.handlers.map(i=>ie(async()=>{var o;if(!i.ignoreLLM)try{await((o=i.handleLLMError)==null?void 0:o.call(i,e,this.runId,this._parentRunId,this.tags,s))}catch(u){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMError: ${u}`),i.raiseError)throw u}},i.awaitHandlers)))}async handleLLMEnd(e,t,r,a,s){await Promise.all(this.handlers.map(i=>ie(async()=>{var o;if(!i.ignoreLLM)try{await((o=i.handleLLMEnd)==null?void 0:o.call(i,e,this.runId,this._parentRunId,this.tags,s))}catch(u){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMEnd: ${u}`),i.raiseError)throw u}},i.awaitHandlers)))}}class fy extends ha{getChild(e){const t=new Ie(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,r,a,s){await Promise.all(this.handlers.map(i=>ie(async()=>{var o;if(!i.ignoreChain)try{await((o=i.handleChainError)==null?void 0:o.call(i,e,this.runId,this._parentRunId,this.tags,s))}catch(u){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainError: ${u}`),i.raiseError)throw u}},i.awaitHandlers)))}async handleChainEnd(e,t,r,a,s){await Promise.all(this.handlers.map(i=>ie(async()=>{var o;if(!i.ignoreChain)try{await((o=i.handleChainEnd)==null?void 0:o.call(i,e,this.runId,this._parentRunId,this.tags,s))}catch(u){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainEnd: ${u}`),i.raiseError)throw u}},i.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>ie(async()=>{var r;if(!t.ignoreAgent)try{await((r=t.handleAgentAction)==null?void 0:r.call(t,e,this.runId,this._parentRunId,this.tags))}catch(a){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${a}`),t.raiseError)throw a}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>ie(async()=>{var r;if(!t.ignoreAgent)try{await((r=t.handleAgentEnd)==null?void 0:r.call(t,e,this.runId,this._parentRunId,this.tags))}catch(a){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${a}`),t.raiseError)throw a}},t.awaitHandlers)))}}class my extends ha{getChild(e){const t=new Ie(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>ie(async()=>{var r;if(!t.ignoreAgent)try{await((r=t.handleToolError)==null?void 0:r.call(t,e,this.runId,this._parentRunId,this.tags))}catch(a){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${a}`),t.raiseError)throw a}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>ie(async()=>{var r;if(!t.ignoreAgent)try{await((r=t.handleToolEnd)==null?void 0:r.call(t,e,this.runId,this._parentRunId,this.tags))}catch(a){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${a}`),t.raiseError)throw a}},t.awaitHandlers)))}}class Ie extends dy{constructor(e,t){super(),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"callback_manager"}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.handlers=(t==null?void 0:t.handlers)??this.handlers,this.inheritableHandlers=(t==null?void 0:t.inheritableHandlers)??this.inheritableHandlers,this.tags=(t==null?void 0:t.tags)??this.tags,this.inheritableTags=(t==null?void 0:t.inheritableTags)??this.inheritableTags,this.metadata=(t==null?void 0:t.metadata)??this.metadata,this.inheritableMetadata=(t==null?void 0:t.inheritableMetadata)??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,r=void 0,a=void 0,s=void 0,i=void 0,o=void 0,u=void 0){return Promise.all(t.map(async(c,l)=>{const d=l===0&&r?r:it();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return or(h)&&h._createRunForLLMStart(e,[c],d,this._parentRunId,s,this.tags,this.metadata,u),ie(async()=>{var f;try{await((f=h.handleLLMStart)==null?void 0:f.call(h,e,[c],d,this._parentRunId,s,this.tags,this.metadata,u))}catch(m){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${m}`),h.raiseError)throw m}},h.awaitHandlers)})),new Ec(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,r=void 0,a=void 0,s=void 0,i=void 0,o=void 0,u=void 0){return Promise.all(t.map(async(c,l)=>{const d=l===0&&r?r:it();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return or(h)&&h._createRunForChatModelStart(e,[c],d,this._parentRunId,s,this.tags,this.metadata,u),ie(async()=>{var f,m;try{if(h.handleChatModelStart)await((f=h.handleChatModelStart)==null?void 0:f.call(h,e,[c],d,this._parentRunId,s,this.tags,this.metadata,u));else if(h.handleLLMStart){const p=wd(c);await((m=h.handleLLMStart)==null?void 0:m.call(h,e,[p],d,this._parentRunId,s,this.tags,this.metadata,u))}}catch(p){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${p}`),h.raiseError)throw p}},h.awaitHandlers)})),new Ec(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,r=it(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreChain)return or(u)&&u._createRunForChainStart(e,t,r,this._parentRunId,this.tags,this.metadata,a,o),ie(async()=>{var c;try{await((c=u.handleChainStart)==null?void 0:c.call(u,e,t,r,this._parentRunId,this.tags,this.metadata,a,o))}catch(l){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleChainStart: ${l}`),u.raiseError)throw l}},u.awaitHandlers)})),new fy(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,r=it(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return or(u)&&u._createRunForToolStart(e,t,r,this._parentRunId,this.tags,this.metadata,o),ie(async()=>{var c;try{await((c=u.handleToolStart)==null?void 0:c.call(u,e,t,r,this._parentRunId,this.tags,this.metadata,o))}catch(l){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleToolStart: ${l}`),u.raiseError)throw l}},u.awaitHandlers)})),new my(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,r=it(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreRetriever)return or(u)&&u._createRunForRetrieverStart(e,t,r,this._parentRunId,this.tags,this.metadata,o),ie(async()=>{var c;try{await((c=u.handleRetrieverStart)==null?void 0:c.call(u,e,t,r,this._parentRunId,this.tags,this.metadata,o))}catch(l){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleRetrieverStart: ${l}`),u.raiseError)throw l}},u.awaitHandlers)})),new hy(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,r,a,s){await Promise.all(this.handlers.map(i=>ie(async()=>{var o;if(!i.ignoreCustomEvent)try{await((o=i.handleCustomEvent)==null?void 0:o.call(i,e,t,r,this.tags,this.metadata))}catch(u){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${u}`),i.raiseError)throw u}},i.awaitHandlers)))}addHandler(e,t=!0){this.handlers.push(e),t&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(t=>t!==e),this.inheritableHandlers=this.inheritableHandlers.filter(t=>t!==e)}setHandlers(e,t=!0){this.handlers=[],this.inheritableHandlers=[];for(const r of e)this.addHandler(r,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(t=>!e.includes(t)),this.inheritableTags=this.inheritableTags.filter(t=>!e.includes(t))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(const t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(e=[],t=!0){const r=new Ie(this._parentRunId);for(const a of this.handlers){const s=this.inheritableHandlers.includes(a);r.addHandler(a,s)}for(const a of this.tags){const s=this.inheritableTags.includes(a);r.addTags([a],s)}for(const a of Object.keys(this.metadata)){const s=Object.keys(this.inheritableMetadata).includes(a);r.addMetadata({[a]:this.metadata[a]},s)}for(const a of e)r.handlers.filter(s=>s.name==="console_callback_handler").some(s=>s.name===a.name)||r.addHandler(a,t);return r}static fromHandlers(e){class t extends Hr{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:it()}),Object.assign(this,e)}}const r=new this;return r.addHandler(new t),r}static configure(e,t,r,a,s,i,o){return this._configureSync(e,t,r,a,s,i,o)}static _configureSync(e,t,r,a,s,i,o){var h;let u;(e||t)&&(Array.isArray(e)||!e?(u=new Ie,u.setHandlers((e==null?void 0:e.map(Un))??[],!0)):u=e,u=u.copy(Array.isArray(t)?t.map(Un):t==null?void 0:t.handlers,!1));const c=_t("LANGCHAIN_VERBOSE")==="true"||(o==null?void 0:o.verbose),l=((h=Ar.getTraceableRunTree())==null?void 0:h.tracingEnabled)||uy(),d=l||(_t("LANGCHAIN_TRACING")??!1);if(c||d){if(u||(u=new Ie),c&&!u.handlers.some(f=>f.name===vc.prototype.name)){const f=new vc;u.addHandler(f,!0)}if(d&&!u.handlers.some(f=>f.name==="langchain_tracer")&&l){const f=new Ar;u.addHandler(f,!0)}if(l){const f=Ar.getTraceableRunTree();if(f&&u._parentRunId===void 0){u._parentRunId=f.id;const m=u.handlers.find(p=>p.name==="langchain_tracer");m==null||m.updateFromRunTree(f)}}}for(const{contextVar:f,inheritable:m=!0,handlerClass:p,envVar:g}of ly()){const y=g&&_t(g)==="true"&&p;let b;const _=f!==void 0?zd(f):void 0;_&&ey(_)?b=_:y&&(b=new p({})),b!==void 0&&(u||(u=new Ie),u.handlers.some(w=>w.name===b.name)||u.addHandler(b,m))}return(r||a)&&u&&(u.addTags(r??[]),u.addTags(a??[],!1)),(s||i)&&u&&(u.addMetadata(s??{}),u.addMetadata(i??{},!1)),u}}function Un(n){return"name"in n?n:Hr.fromMethods(n)}class py{getStore(){}run(e,t){return t()}enterWith(e){}}const gy=new py,Sc=Symbol.for("lc:child_config");class yy{getInstance(){return Nr()??gy}getRunnableConfig(){var t,r;return(r=(t=this.getInstance().getStore())==null?void 0:t.extra)==null?void 0:r[Sc]}runWithConfig(e,t,r){var l;const a=Ie._configureSync(e==null?void 0:e.callbacks,void 0,e==null?void 0:e.tags,void 0,e==null?void 0:e.metadata),s=this.getInstance(),i=s.getStore(),o=a==null?void 0:a.getParentRunId(),u=(l=a==null?void 0:a.handlers)==null?void 0:l.find(d=>(d==null?void 0:d.name)==="langchain_tracer");let c;return u&&o?c=u.getRunTreeWithTracingConfig(o):r||(c=new Ae({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[Sc]:e}),i!==void 0&&i[On]!==void 0&&(c===void 0&&(c={}),c[On]=i[On]),s.run(c,t)}initializeGlobalInstance(e){Nr()===void 0&&sy(e)}}const wt=new yy,qs=25;async function He(n){return Ie._configureSync(n==null?void 0:n.callbacks,void 0,n==null?void 0:n.tags,void 0,n==null?void 0:n.metadata)}function Oc(...n){const e={};for(const t of n.filter(r=>!!r))for(const r of Object.keys(t))if(r==="metadata")e[r]={...e[r],...t[r]};else if(r==="tags"){const a=e[r]??[];e[r]=[...new Set(a.concat(t[r]??[]))]}else if(r==="configurable")e[r]={...e[r],...t[r]};else if(r==="timeout")e.timeout===void 0?e.timeout=t.timeout:t.timeout!==void 0&&(e.timeout=Math.min(e.timeout,t.timeout));else if(r==="signal")e.signal===void 0?e.signal=t.signal:t.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,t.signal]):e.signal=t.signal);else if(r==="callbacks"){const a=e.callbacks,s=t.callbacks;if(Array.isArray(s))if(!a)e.callbacks=s;else if(Array.isArray(a))e.callbacks=a.concat(s);else{const i=a.copy();for(const o of s)i.addHandler(Un(o),!0);e.callbacks=i}else if(s)if(!a)e.callbacks=s;else if(Array.isArray(a)){const i=s.copy();for(const o of a)i.addHandler(Un(o),!0);e.callbacks=i}else e.callbacks=new Ie(s._parentRunId,{handlers:a.handlers.concat(s.handlers),inheritableHandlers:a.inheritableHandlers.concat(s.inheritableHandlers),tags:Array.from(new Set(a.tags.concat(s.tags))),inheritableTags:Array.from(new Set(a.inheritableTags.concat(s.inheritableTags))),metadata:{...a.metadata,...s.metadata}})}else{const a=r;e[a]=t[a]??e[a]}return e}const _y=new Set(["string","number","boolean"]);function K(n){var r;const e=wt.getRunnableConfig();let t={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){const{runId:a,runName:s,...i}=e;t=Object.entries(i).reduce((o,[u,c])=>(c!==void 0&&(o[u]=c),o),t)}if(n&&(t=Object.entries(n).reduce((a,[s,i])=>(i!==void 0&&(a[s]=i),a),t)),t!=null&&t.configurable)for(const a of Object.keys(t.configurable))_y.has(typeof t.configurable[a])&&!((r=t.metadata)!=null&&r[a])&&(t.metadata||(t.metadata={}),t.metadata[a]=t.configurable[a]);if(t.timeout!==void 0){if(t.timeout<=0)throw new Error("Timeout must be a positive number");const a=AbortSignal.timeout(t.timeout);t.signal!==void 0?"any"in AbortSignal&&(t.signal=AbortSignal.any([t.signal,a])):t.signal=a,delete t.timeout}return t}function _e(n={},{callbacks:e,maxConcurrency:t,recursionLimit:r,runName:a,configurable:s,runId:i}={}){const o=K(n);return e!==void 0&&(delete o.runName,o.callbacks=e),r!==void 0&&(o.recursionLimit=r),t!==void 0&&(o.maxConcurrency=t),a!==void 0&&(o.runName=a),s!==void 0&&(o.configurable={...o.configurable,...s}),i!==void 0&&delete o.runId,o}function Kt(n){return n?{configurable:n.configurable,recursionLimit:n.recursionLimit,callbacks:n.callbacks,tags:n.tags,metadata:n.metadata,maxConcurrency:n.maxConcurrency,timeout:n.timeout,signal:n.signal}:void 0}async function vt(n,e){if(e===void 0)return n;let t;return Promise.race([n.catch(r=>{if(!(e!=null&&e.aborted))throw r}),new Promise((r,a)=>{t=()=>{a(new Error("Aborted"))},e.addEventListener("abort",t),e.aborted&&a(new Error("Aborted"))})]).finally(()=>e.removeEventListener("abort",t))}class je extends ReadableStream{constructor(){super(...arguments),Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){const t=this.reader.cancel();this.reader.releaseLock(),await t}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){const t=e.getReader();return new je({start(r){return a();function a(){return t.read().then(({done:s,value:i})=>{if(s){r.close();return}return r.enqueue(i),a()})}},cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new je({async pull(t){const{value:r,done:a}=await e.next();a&&t.close(),t.enqueue(r)},async cancel(t){await e.return(t)}})}}function Hd(n,e=2){const t=Array.from({length:e},()=>[]);return t.map(async function*(a){for(;;)if(a.length===0){const s=await n.next();for(const i of t)i.push(s)}else{if(a[0].done)return;yield a.shift().value}})}function fa(n,e){if(Array.isArray(n)&&Array.isArray(e))return n.concat(e);if(typeof n=="string"&&typeof e=="string")return n+e;if(typeof n=="number"&&typeof e=="number")return n+e;if("concat"in n&&typeof n.concat=="function")return n.concat(e);if(typeof n=="object"&&typeof e=="object"){const t={...n};for(const[r,a]of Object.entries(e))r in t&&!Array.isArray(t[r])?t[r]=fa(t[r],a):t[r]=a;return t}else throw new Error(`Cannot concat ${typeof n} and ${typeof e}`)}class tr{constructor(e){var t;Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"setup",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signal",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResultUsed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.generator=e.generator,this.config=e.config,this.signal=e.signal??((t=this.config)==null?void 0:t.signal),this.setup=new Promise((r,a)=>{wt.runWithConfig(Kt(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(r,a):this.firstResult.then(s=>r(void 0),a)},!0)})}async next(...e){var t;return(t=this.signal)==null||t.throwIfAborted(),this.firstResultUsed?wt.runWithConfig(Kt(this.config),this.signal?async()=>vt(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}}async function by(n,e,t,r,...a){const s=new tr({generator:e,startSetup:t,signal:r}),i=await s.setup;return{output:n(s,i,...a),setup:i}}class mt{constructor(e){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),r=Nn({},t);return new jr({ops:t,state:r[r.length-1].newDocument})}}class jr extends mt{constructor(e){super(e),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=e.state}concat(e){const t=this.ops.concat(e.ops),r=Nn(this.state,e.ops);return new jr({ops:t,state:r[r.length-1].newDocument})}static fromRunLogPatch(e){const t=Nn({},e.ops);return new jr({ops:e.ops,state:t[t.length-1].newDocument})}}const wy=n=>n.name==="log_stream_tracer";async function Tc(n,e){if(e==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:t}=n;if(["retriever","llm","prompt"].includes(n.run_type))return t;if(!(Object.keys(t).length===1&&(t==null?void 0:t.input)===""))return t.input}async function Ac(n,e){const{outputs:t}=n;return e==="original"||["retriever","llm","prompt"].includes(n.run_type)?t:t!==void 0&&Object.keys(t).length===1&&(t==null?void 0:t.output)!==void 0?t.output:t}function vy(n){return n!==void 0&&n.message!==void 0}class Pc extends Gr{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaFormat",{enumerable:!0,configurable:!0,writable:!0,value:"original"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keyMapByRunId",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"counterMapByRunName",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"log_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=(e==null?void 0:e.autoClose)??!0,this.includeNames=e==null?void 0:e.includeNames,this.includeTypes=e==null?void 0:e.includeTypes,this.includeTags=e==null?void 0:e.includeTags,this.excludeNames=e==null?void 0:e.excludeNames,this.excludeTypes=e==null?void 0:e.excludeTypes,this.excludeTags=e==null?void 0:e.excludeTags,this._schemaFormat=(e==null?void 0:e._schemaFormat)??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=je.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const t=e.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(r=r||t.find(a=>{var s;return(s=this.includeTags)==null?void 0:s.includes(a)})!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(r=r&&t.every(a=>{var s;return!((s=this.excludeTags)!=null&&s.includes(a))})),r}async*tapOutputIterable(e,t){for await(const r of t){if(e!==this.rootId){const a=this.keyMapByRunId[e];a&&await this.writer.write(new mt({ops:[{op:"add",path:`/logs/${a}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){var a;if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new mt({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;const r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:((a=e.extra)==null?void 0:a.metadata)??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(r.inputs=await Tc(e,this._schemaFormat)),await this.writer.write(new mt({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(t===void 0)return;const r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await Tc(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await Ac(e,this._schemaFormat)}),e.end_time!==void 0&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const a=new mt({ops:r});await this.writer.write(a)}finally{if(e.id===this.rootId){const t=new mt({ops:[{op:"replace",path:"/final_output",value:await Ac(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){const a=this.keyMapByRunId[e.id];if(a===void 0)return;const s=e.inputs.messages!==void 0;let i;s?vy(r==null?void 0:r.chunk)?i=r==null?void 0:r.chunk:i=new bt({id:`run-${e.id}`,content:t}):i=t;const o=new mt({ops:[{op:"add",path:`/logs/${a}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${a}/streamed_output/-`,value:i}]});await this.writer.write(o)}}const xc="__run";class Vt{constructor(e){Object.defineProperty(this,"text",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generationInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new Vt({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}}class Ct extends Vt{constructor(e){super(e),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.message=e.message}concat(e){return new Ct({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo},message:this.message.concat(e.message)})}}function cn({name:n,serialized:e}){return n!==void 0?n:(e==null?void 0:e.name)!==void 0?e.name:(e==null?void 0:e.id)!==void 0&&Array.isArray(e==null?void 0:e.id)?e.id[e.id.length-1]:"Unnamed"}const Ey=n=>n.name==="event_stream_tracer";class Sy extends Gr{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"runInfoMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"tappedPromises",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"event_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=(e==null?void 0:e.autoClose)??!0,this.includeNames=e==null?void 0:e.includeNames,this.includeTypes=e==null?void 0:e.includeTypes,this.includeTags=e==null?void 0:e.includeTags,this.excludeNames=e==null?void 0:e.excludeNames,this.excludeTypes=e==null?void 0:e.excludeTypes,this.excludeTags=e==null?void 0:e.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=je.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=e.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(r=r||t.find(a=>{var s;return(s=this.includeTags)==null?void 0:s.includes(a)})!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(r=r&&t.every(a=>{var s;return!((s=this.excludeTags)!=null&&s.includes(a))})),r}async*tapOutputIterable(e,t){const r=await t.next();if(r.done)return;const a=this.runInfoMap.get(e);if(a===void 0){yield r.value;return}function s(o,u){return o==="llm"&&typeof u=="string"?new Vt({text:u}):u}let i=this.tappedPromises.get(e);if(i===void 0){let o;i=new Promise(u=>{o=u}),this.tappedPromises.set(e,i);try{const u={event:`on_${a.runType}_stream`,run_id:e,name:a.name,tags:a.tags,metadata:a.metadata,data:{}};await this.send({...u,data:{chunk:s(a.runType,r.value)}},a),yield r.value;for await(const c of t)a.runType!=="tool"&&a.runType!=="retriever"&&await this.send({...u,data:{chunk:s(a.runType,c)}},a),yield c}finally{o()}}else{yield r.value;for await(const o of t)yield o}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const r=this.tappedPromises.get(e.run_id);r!==void 0?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){var i,o;const t=cn(e),r=e.inputs.messages!==void 0?"chat_model":"llm",a={tags:e.tags??[],metadata:((i=e.extra)==null?void 0:i.metadata)??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,a);const s=`on_${r}_start`;await this.send({event:s,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:((o=e.extra)==null?void 0:o.metadata)??{}},a)}async onLLMNewToken(e,t,r){const a=this.runInfoMap.get(e.id);let s,i;if(a===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(a.runType==="chat_model")i="on_chat_model_stream",(r==null?void 0:r.chunk)===void 0?s=new bt({content:t,id:`run-${e.id}`}):s=r.chunk.message;else if(a.runType==="llm")i="on_llm_stream",(r==null?void 0:r.chunk)===void 0?s=new Vt({text:t}):s=r.chunk;else throw new Error(`Unexpected run type ${a.runType}`);await this.send({event:i,data:{chunk:s},run_id:e.id,name:a.name,tags:a.tags,metadata:a.metadata},a)}}async onLLMEnd(e){var i,o,u;const t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let r;if(t===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const a=(i=e.outputs)==null?void 0:i.generations;let s;if(t.runType==="chat_model"){for(const c of a??[]){if(s!==void 0)break;s=(o=c[0])==null?void 0:o.message}r="on_chat_model_end"}else if(t.runType==="llm")s={generations:a==null?void 0:a.map(c=>c.map(l=>({text:l.text,generationInfo:l.generationInfo}))),llmOutput:((u=e.outputs)==null?void 0:u.llmOutput)??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:r,data:{output:s,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){var i,o;const t=cn(e),r=e.run_type??"chain",a={tags:e.tags??[],metadata:((i=e.extra)==null?void 0:i.metadata)??{},name:t,runType:e.run_type};let s={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(s={},a.inputs={}):e.inputs.input!==void 0?(s.input=e.inputs.input,a.inputs=e.inputs.input):(s.input=e.inputs,a.inputs=e.inputs),this.runInfoMap.set(e.id,a),await this.send({event:`on_${r}_start`,data:s,name:t,tags:e.tags??[],run_id:e.id,metadata:((o=e.extra)==null?void 0:o.metadata)??{}},a)}async onChainEnd(e){var o;const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const r=`on_${e.run_type}_end`,a=e.inputs??t.inputs??{},i={output:((o=e.outputs)==null?void 0:o.output)??e.outputs,input:a};a.input&&Object.keys(a).length===1&&(i.input=a.input,t.inputs=a.input),await this.sendEndEvent({event:r,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){var a,s;const t=cn(e),r={tags:e.tags??[],metadata:((a=e.extra)==null?void 0:a.metadata)??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:((s=e.extra)==null?void 0:s.metadata)??{}},r)}async onToolEnd(e){var a;const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const r=((a=e.outputs)==null?void 0:a.output)===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){var s,i;const t=cn(e),a={tags:e.tags??[],metadata:((s=e.extra)==null?void 0:s.metadata)??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,a),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:((i=e.extra)==null?void 0:i.metadata)??{}},a)}async onRetrieverEnd(e){var r;const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:((r=e.outputs)==null?void 0:r.documents)??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,r){const a=this.runInfoMap.get(r);if(a===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:a.tags,metadata:a.metadata,data:t},a)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}}const Oy=[400,401,402,403,404,405,406,407,409],Ty=n=>{var t,r;if(n.message.startsWith("Cancel")||n.message.startsWith("AbortError")||n.name==="AbortError"||(n==null?void 0:n.code)==="ECONNABORTED")throw n;const e=((t=n==null?void 0:n.response)==null?void 0:t.status)??(n==null?void 0:n.status);if(e&&Oy.includes(+e))throw n;if(((r=n==null?void 0:n.error)==null?void 0:r.code)==="insufficient_quota"){const a=new Error(n==null?void 0:n.message);throw a.name="InsufficientQuotaError",a}};class no{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??Ty;const t="default"in ut?ut.default:ut;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>Cn(()=>e(...t).catch(r=>{throw r instanceof Error?r:new Error(r)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise((a,s)=>{var i;(i=e.signal)==null||i.addEventListener("abort",()=>{s(new Error("AbortError"))})})]):this.call(t,...r)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}}class Gd extends Gr{constructor({config:e,onStart:t,onEnd:r,onError:a}){super({_awaitHandler:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RootListenersTracer"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.config=e,this.argOnStart=t,this.argOnEnd=r,this.argOnError=a}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}}function ao(n){return n?n.lc_runnable:!1}class Ay{constructor(e){Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let r=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const a=e.tags??[];return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t)),this.includeTags!==void 0&&(r=r||a.some(s=>{var i;return(i=this.includeTags)==null?void 0:i.includes(s)})),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(r=r&&a.every(s=>{var i;return!((i=this.excludeTags)!=null&&i.includes(s))})),r}}function zs(n){return n.replace(/[^a-zA-Z-_0-9]/g,"_")}const Py=["*","_","`"];function xy(n){let e="";for(const[t,r]of Object.entries(n))e+=` classDef ${t} ${r};
84
+ `;return e}function Iy(n,e,t){const{firstNode:r,lastNode:a,nodeColors:s,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:u=9}=t??{};let c=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
85
+ graph TD;
86
+ `:`graph TD;
87
+ `;if(i){const f="default",m={[f]:"{0}({1})"};r!==void 0&&(m[r]="{0}([{1}]):::first"),a!==void 0&&(m[a]="{0}([{1}]):::last");for(const[p,g]of Object.entries(n)){const y=g.name.split(":").pop()??"";let _=Py.some(v=>y.startsWith(v)&&y.endsWith(v))?`<p>${y}</p>`:y;Object.keys(g.metadata??{}).length&&(_+=`<hr/><small><em>${Object.entries(g.metadata??{}).map(([v,S])=>`${v} = ${S}`).join(`
88
+ `)}</em></small>`);const w=(m[p]??m[f]).replace("{0}",zs(p)).replace("{1}",_);c+=` ${w}
89
+ `}}const l={};for(const f of e){const m=f.source.split(":"),p=f.target.split(":"),g=m.filter((y,b)=>y===p[b]).join(":");l[g]||(l[g]=[]),l[g].push(f)}const d=new Set;function h(f,m){const p=f.length===1&&f[0].source===f[0].target;if(m&&!p){const g=m.split(":").pop();if(d.has(g))throw new Error(`Found duplicate subgraph '${g}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(g),c+=` subgraph ${g}
90
+ `}for(const g of f){const{source:y,target:b,data:_,conditional:w}=g;let v="";if(_!==void 0){let S=_;const O=S.split(" ");O.length>u&&(S=Array.from({length:Math.ceil(O.length/u)},(T,N)=>O.slice(N*u,(N+1)*u).join(" ")).join("&nbsp;<br>&nbsp;")),v=w?` -. &nbsp;${S}&nbsp; .-> `:` -- &nbsp;${S}&nbsp; --> `}else v=w?" -.-> ":" --> ";c+=` ${zs(y)}${v}${zs(b)};
91
+ `}for(const g in l)g.startsWith(`${m}:`)&&g!==m&&h(l[g],g);m&&!p&&(c+=` end
92
+ `)}h(l[""]??[],"");for(const f in l)!f.includes(":")&&f!==""&&h(l[f],f);return i&&(c+=xy(s??{})),c}async function Ry(n,e){return $y(n,{...e,imageType:"png"})}async function $y(n,e){let t=(e==null?void 0:e.backgroundColor)??"white";const r=e==null?void 0:e.imageType,a=btoa(n);t!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(t)||(t=`!${t}`));const s=`https://mermaid.ink/img/${a}?bgColor=${t}&type=${r}`,i=await fetch(s);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
93
+ `));return await i.blob()}function ma(n,e,t){function r(o,u){var c;Object.defineProperty(o,"_zod",{value:o._zod??{},enumerable:!1}),(c=o._zod).traits??(c.traits=new Set),o._zod.traits.add(n),e(o,u);for(const l in i.prototype)l in o||Object.defineProperty(o,l,{value:i.prototype[l].bind(o)});o._zod.constr=i,o._zod.def=u}const a=(t==null?void 0:t.Parent)??Object;class s extends a{}Object.defineProperty(s,"name",{value:n});function i(o){var u;const c=t!=null&&t.Parent?new s:this;r(c,o),(u=c._zod).deferred??(u.deferred=[]);for(const l of c._zod.deferred)l();return c}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:o=>{var u,c;return t!=null&&t.Parent&&o instanceof t.Parent?!0:(c=(u=o==null?void 0:o._zod)==null?void 0:u.traits)==null?void 0:c.has(n)}}),Object.defineProperty(i,"name",{value:n}),i}class Fn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const ky={};function pa(n){return ky}function Cy(n){const e=Object.values(n).filter(r=>typeof r=="number");return Object.entries(n).filter(([r,a])=>e.indexOf(+r)===-1).map(([r,a])=>a)}function Ny(n,e){return typeof e=="bigint"?e.toString():e}const Wd=Error.captureStackTrace?Error.captureStackTrace:(...n)=>{};function Dn(n,e,t){const r=new n._zod.constr(e??n._zod.def);return(!e||t!=null&&t.parent)&&(r._zod.parent=n),r}function jy(n){return{}}function Hs(n,e=0){var t;for(let r=e;r<n.issues.length;r++)if(((t=n.issues[r])==null?void 0:t.continue)!==!0)return!0;return!1}function ln(n){return typeof n=="string"?n:n==null?void 0:n.message}function ga(n,e,t){var a,s,i,o,u,c;const r={...n,path:n.path??[]};if(!n.message){const l=ln((i=(s=(a=n.inst)==null?void 0:a._zod.def)==null?void 0:s.error)==null?void 0:i.call(s,n))??ln((o=e==null?void 0:e.error)==null?void 0:o.call(e,n))??ln((u=t.customError)==null?void 0:u.call(t,n))??ln((c=t.localeError)==null?void 0:c.call(t,n))??"Invalid input";r.message=l}return delete r.inst,delete r.continue,e!=null&&e.reportInput||delete r.input,r}const Jd=(n,e)=>{n.name="$ZodError",Object.defineProperty(n,"_zod",{value:n._zod,enumerable:!1}),Object.defineProperty(n,"issues",{value:e,enumerable:!1}),Object.defineProperty(n,"message",{get(){return JSON.stringify(e,Ny,2)},enumerable:!0}),Object.defineProperty(n,"toString",{value:()=>n.message,enumerable:!1})},Ly=ma("$ZodError",Jd),ya=ma("$ZodError",Jd,{Parent:Error}),My=n=>(e,t,r,a)=>{const s=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:t,issues:[]},s);if(i instanceof Promise)throw new Fn;if(i.issues.length){const o=new((a==null?void 0:a.Err)??n)(i.issues.map(u=>ga(u,s,pa())));throw Wd(o,a==null?void 0:a.callee),o}return i.value},Zd=My(ya),Uy=n=>async(e,t,r,a)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let i=e._zod.run({value:t,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){const o=new((a==null?void 0:a.Err)??n)(i.issues.map(u=>ga(u,s,pa())));throw Wd(o,a==null?void 0:a.callee),o}return i.value},Fy=Uy(ya),Dy=n=>(e,t,r)=>{const a=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:t,issues:[]},a);if(s instanceof Promise)throw new Fn;return s.issues.length?{success:!1,error:new(n??Ly)(s.issues.map(i=>ga(i,a,pa())))}:{success:!0,data:s.value}},By=Dy(ya),qy=n=>async(e,t,r)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let s=e._zod.run({value:t,issues:[]},a);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new n(s.issues.map(i=>ga(i,a,pa())))}:{success:!0,data:s.value}},zy=qy(ya),Hy={major:4,minor:0,patch:0},Gy=ma("$ZodType",(n,e)=>{var a;var t;n??(n={}),n._zod.def=e,n._zod.bag=n._zod.bag||{},n._zod.version=Hy;const r=[...n._zod.def.checks??[]];n._zod.traits.has("$ZodCheck")&&r.unshift(n);for(const s of r)for(const i of s._zod.onattach)i(n);if(r.length===0)(t=n._zod).deferred??(t.deferred=[]),(a=n._zod.deferred)==null||a.push(()=>{n._zod.run=n._zod.parse});else{const s=(i,o,u)=>{let c=Hs(i),l;for(const d of o){if(d._zod.def.when){if(!d._zod.def.when(i))continue}else if(c)continue;const h=i.issues.length,f=d._zod.check(i);if(f instanceof Promise&&(u==null?void 0:u.async)===!1)throw new Fn;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==h&&(c||(c=Hs(i,h)))});else{if(i.issues.length===h)continue;c||(c=Hs(i,h))}}return l?l.then(()=>i):i};n._zod.run=(i,o)=>{const u=n._zod.parse(i,o);if(u instanceof Promise){if(o.async===!1)throw new Fn;return u.then(c=>s(c,r,o))}return s(u,r,o)}}n["~standard"]={validate:s=>{var i;try{const o=By(n,s);return o.success?{value:o.data}:{issues:(i=o.error)==null?void 0:i.issues}}catch{return zy(n,s).then(u=>{var c;return u.success?{value:u.data}:{issues:(c=u.error)==null?void 0:c.issues}})}},vendor:"zod",version:1}}),Wy=ma("$ZodNever",(n,e)=>{Gy.init(n,e),n._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:n}),t)});class Kd{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function Jy(){return new Kd}const gt=Jy();function Zy(n,e){return new n({type:"never",...jy()})}class Ic{constructor(e){this.counter=0,this.metadataRegistry=(e==null?void 0:e.metadata)??gt,this.target=(e==null?void 0:e.target)??"draft-2020-12",this.unrepresentable=(e==null?void 0:e.unrepresentable)??"throw",this.override=(e==null?void 0:e.override)??(()=>{}),this.io=(e==null?void 0:e.io)??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var d,h,f;var r;const a=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,t.schemaPath.includes(e)&&(i.cycle=t.path),i.schema;const o={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,o);const u=(h=(d=e._zod).toJSONSchema)==null?void 0:h.call(d);if(u)o.schema=u;else{const m={...t,schemaPath:[...t.schemaPath,e],path:t.path},p=e._zod.parent;if(p)o.ref=p,this.process(p,m),this.seen.get(p).isParent=!0;else{const g=o.schema;switch(a.type){case"string":{const y=g;y.type="string";const{minimum:b,maximum:_,format:w,patterns:v,contentEncoding:S}=e._zod.bag;if(typeof b=="number"&&(y.minLength=b),typeof _=="number"&&(y.maxLength=_),w&&(y.format=s[w]??w,y.format===""&&delete y.format),S&&(y.contentEncoding=S),v&&v.size>0){const O=[...v];O.length===1?y.pattern=O[0].source:O.length>1&&(o.schema.allOf=[...O.map(T=>({...this.target==="draft-7"?{type:"string"}:{},pattern:T.source}))])}break}case"number":{const y=g,{minimum:b,maximum:_,format:w,multipleOf:v,exclusiveMaximum:S,exclusiveMinimum:O}=e._zod.bag;typeof w=="string"&&w.includes("int")?y.type="integer":y.type="number",typeof O=="number"&&(y.exclusiveMinimum=O),typeof b=="number"&&(y.minimum=b,typeof O=="number"&&(O>=b?delete y.minimum:delete y.exclusiveMinimum)),typeof S=="number"&&(y.exclusiveMaximum=S),typeof _=="number"&&(y.maximum=_,typeof S=="number"&&(S<=_?delete y.maximum:delete y.exclusiveMaximum)),typeof v=="number"&&(y.multipleOf=v);break}case"boolean":{const y=g;y.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{g.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{g.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const y=g,{minimum:b,maximum:_}=e._zod.bag;typeof b=="number"&&(y.minItems=b),typeof _=="number"&&(y.maxItems=_),y.type="array",y.items=this.process(a.element,{...m,path:[...m.path,"items"]});break}case"object":{const y=g;y.type="object",y.properties={};const b=a.shape;for(const v in b)y.properties[v]=this.process(b[v],{...m,path:[...m.path,"properties",v]});const _=new Set(Object.keys(b)),w=new Set([..._].filter(v=>{const S=a.shape[v]._zod;return this.io==="input"?S.optin===void 0:S.optout===void 0}));w.size>0&&(y.required=Array.from(w)),((f=a.catchall)==null?void 0:f._zod.def.type)==="never"?y.additionalProperties=!1:a.catchall?a.catchall&&(y.additionalProperties=this.process(a.catchall,{...m,path:[...m.path,"additionalProperties"]})):this.io==="output"&&(y.additionalProperties=!1);break}case"union":{const y=g;y.anyOf=a.options.map((b,_)=>this.process(b,{...m,path:[...m.path,"anyOf",_]}));break}case"intersection":{const y=g,b=this.process(a.left,{...m,path:[...m.path,"allOf",0]}),_=this.process(a.right,{...m,path:[...m.path,"allOf",1]}),w=S=>"allOf"in S&&Object.keys(S).length===1,v=[...w(b)?b.allOf:[b],...w(_)?_.allOf:[_]];y.allOf=v;break}case"tuple":{const y=g;y.type="array";const b=a.items.map((v,S)=>this.process(v,{...m,path:[...m.path,"prefixItems",S]}));if(this.target==="draft-2020-12"?y.prefixItems=b:y.items=b,a.rest){const v=this.process(a.rest,{...m,path:[...m.path,"items"]});this.target==="draft-2020-12"?y.items=v:y.additionalItems=v}a.rest&&(y.items=this.process(a.rest,{...m,path:[...m.path,"items"]}));const{minimum:_,maximum:w}=e._zod.bag;typeof _=="number"&&(y.minItems=_),typeof w=="number"&&(y.maxItems=w);break}case"record":{const y=g;y.type="object",y.propertyNames=this.process(a.keyType,{...m,path:[...m.path,"propertyNames"]}),y.additionalProperties=this.process(a.valueType,{...m,path:[...m.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const y=g,b=Cy(a.entries);b.every(_=>typeof _=="number")&&(y.type="number"),b.every(_=>typeof _=="string")&&(y.type="string"),y.enum=b;break}case"literal":{const y=g,b=[];for(const _ of a.values)if(_===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof _=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");b.push(Number(_))}else b.push(_);if(b.length!==0)if(b.length===1){const _=b[0];y.type=_===null?"null":typeof _,y.const=_}else b.every(_=>typeof _=="number")&&(y.type="number"),b.every(_=>typeof _=="string")&&(y.type="string"),b.every(_=>typeof _=="boolean")&&(y.type="string"),b.every(_=>_===null)&&(y.type="null"),y.enum=b;break}case"file":{const y=g,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:_,maximum:w,mime:v}=e._zod.bag;_!==void 0&&(b.minLength=_),w!==void 0&&(b.maxLength=w),v?v.length===1?(b.contentMediaType=v[0],Object.assign(y,b)):y.anyOf=v.map(S=>({...b,contentMediaType:S})):Object.assign(y,b);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const y=this.process(a.innerType,m);g.anyOf=[y,{type:"null"}];break}case"nonoptional":{this.process(a.innerType,m),o.ref=a.innerType;break}case"success":{const y=g;y.type="boolean";break}case"default":{this.process(a.innerType,m),o.ref=a.innerType,g.default=JSON.parse(JSON.stringify(a.defaultValue));break}case"prefault":{this.process(a.innerType,m),o.ref=a.innerType,this.io==="input"&&(g._prefault=JSON.parse(JSON.stringify(a.defaultValue)));break}case"catch":{this.process(a.innerType,m),o.ref=a.innerType;let y;try{y=a.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}g.default=y;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const y=g,b=e._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");y.type="string",y.pattern=b.source;break}case"pipe":{const y=this.io==="input"?a.in._zod.def.type==="transform"?a.out:a.in:a.out;this.process(y,m),o.ref=y;break}case"readonly":{this.process(a.innerType,m),o.ref=a.innerType,g.readOnly=!0;break}case"promise":{this.process(a.innerType,m),o.ref=a.innerType;break}case"optional":{this.process(a.innerType,m),o.ref=a.innerType;break}case"lazy":{const y=e._zod.innerType;this.process(y,m),o.ref=y;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),this.io==="input"&&ae(e)&&(delete o.schema.examples,delete o.schema.default),this.io==="input"&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,this.seen.get(e).schema}emit(e,t){var l,d,h,f,m,p;const r={cycles:(t==null?void 0:t.cycles)??"ref",reused:(t==null?void 0:t.reused)??"inline",external:(t==null?void 0:t.external)??void 0},a=this.seen.get(e);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=g=>{var v;const y=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const S=(v=r.external.registry.get(g[0]))==null?void 0:v.id,O=r.external.uri??(N=>N);if(S)return{ref:O(S)};const T=g[1].defId??g[1].schema.id??`schema${this.counter++}`;return g[1].defId=T,{defId:T,ref:`${O("__shared")}#/${y}/${T}`}}if(g[1]===a)return{ref:"#"};const _=`#/${y}/`,w=g[1].schema.id??`__schema${this.counter++}`;return{defId:w,ref:_+w}},i=g=>{if(g[1].schema.$ref)return;const y=g[1],{ref:b,defId:_}=s(g);y.def={...y.schema},_&&(y.defId=_);const w=y.schema;for(const v in w)delete w[v];w.$ref=b};if(r.cycles==="throw")for(const g of this.seen.entries()){const y=g[1];if(y.cycle)throw new Error(`Cycle detected: #/${(l=y.cycle)==null?void 0:l.join("/")}/<root>
94
+
95
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const g of this.seen.entries()){const y=g[1];if(e===g[0]){i(g);continue}if(r.external){const _=(d=r.external.registry.get(g[0]))==null?void 0:d.id;if(e!==g[0]&&_){i(g);continue}}if((h=this.metadataRegistry.get(g[0]))==null?void 0:h.id){i(g);continue}if(y.cycle){i(g);continue}if(y.count>1&&r.reused==="ref"){i(g);continue}}const o=(g,y)=>{const b=this.seen.get(g),_=b.def??b.schema,w={..._};if(b.ref===null)return;const v=b.ref;if(b.ref=null,v){o(v,y);const S=this.seen.get(v).schema;S.$ref&&y.target==="draft-7"?(_.allOf=_.allOf??[],_.allOf.push(S)):(Object.assign(_,S),Object.assign(_,w))}b.isParent||this.override({zodSchema:g,jsonSchema:_,path:b.path??[]})};for(const g of[...this.seen.entries()].reverse())o(g[0],{target:this.target});const u={};if(this.target==="draft-2020-12"?u.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?u.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),(f=r.external)!=null&&f.uri){const g=(m=r.external.registry.get(e))==null?void 0:m.id;if(!g)throw new Error("Schema is missing an `id` property");u.$id=r.external.uri(g)}Object.assign(u,a.def);const c=((p=r.external)==null?void 0:p.defs)??{};for(const g of this.seen.entries()){const y=g[1];y.def&&y.defId&&(c[y.defId]=y.def)}r.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?u.$defs=c:u.definitions=c);try{return JSON.parse(JSON.stringify(u))}catch{throw new Error("Error converting schema to JSON.")}}}function yi(n,e){if(n instanceof Kd){const r=new Ic(e),a={};for(const o of n._idmap.entries()){const[u,c]=o;r.process(c)}const s={},i={registry:n,uri:e==null?void 0:e.uri,defs:a};for(const o of n._idmap.entries()){const[u,c]=o;s[u]=r.emit(c,{...e,external:i})}if(Object.keys(a).length>0){const o=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[o]:a}}return{schemas:s}}const t=new Ic(e);return t.process(n),t.emit(n,e)}function ae(n,e){const t=e??{seen:new Set};if(t.seen.has(n))return!1;t.seen.add(n);const a=n._zod.def;switch(a.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return ae(a.element,t);case"object":{for(const s in a.shape)if(ae(a.shape[s],t))return!0;return!1}case"union":{for(const s of a.options)if(ae(s,t))return!0;return!1}case"intersection":return ae(a.left,t)||ae(a.right,t);case"tuple":{for(const s of a.items)if(ae(s,t))return!0;return!!(a.rest&&ae(a.rest,t))}case"record":return ae(a.keyType,t)||ae(a.valueType,t);case"map":return ae(a.keyType,t)||ae(a.valueType,t);case"set":return ae(a.valueType,t);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return ae(a.innerType,t);case"lazy":return ae(a.getter(),t);case"default":return ae(a.innerType,t);case"prefault":return ae(a.innerType,t);case"custom":return!1;case"transform":return!0;case"pipe":return ae(a.in,t)||ae(a.out,t);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${a.type}`)}const Ky=Symbol("Let zodToJsonSchema decide on which parser to use"),Vy={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Xy=n=>({...Vy,...n}),Qy=n=>{const e=Xy(n),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,a])=>[a._def,{def:a._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function Vd(n,e,t,r){r!=null&&r.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function X(n,e,t,r,a){n[e]=t,Vd(n,e,r,a)}const Xd=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")};function Le(n){if(n.target!=="openAi")return{};const e=[...n.basePath,n.definitionPath,n.openAiAnyTypeName];return n.flags.hasReferencedOpenAiAnyType=!0,{$ref:n.$refStrategy==="relative"?Xd(e,n.currentPath):e.join("/")}}function Yy(n,e){var r,a,s;const t={type:"array"};return(r=n.type)!=null&&r._def&&((s=(a=n.type)==null?void 0:a._def)==null?void 0:s.typeName)!==P.ZodAny&&(t.items=V(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&X(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&X(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(X(t,"minItems",n.exactLength.value,n.exactLength.message,e),X(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function e_(n,e){const t={type:"integer",format:"int64"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?X(t,"minimum",r.value,r.message,e):X(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),X(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?X(t,"maximum",r.value,r.message,e):X(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),X(t,"maximum",r.value,r.message,e));break;case"multipleOf":X(t,"multipleOf",r.value,r.message,e);break}return t}function t_(){return{type:"boolean"}}function Qd(n,e){return V(n.type._def,e)}const r_=(n,e)=>V(n.innerType._def,e);function Yd(n,e,t){const r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((a,s)=>Yd(n,e,a))};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 n_(n,e)}}const n_=(n,e)=>{const t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(const r of n.checks)switch(r.kind){case"min":X(t,"minimum",r.value,r.message,e);break;case"max":X(t,"maximum",r.value,r.message,e);break}return t};function a_(n,e){return{...V(n.innerType._def,e),default:n.defaultValue()}}function s_(n,e){return e.effectStrategy==="input"?V(n.schema._def,e):Le(e)}function i_(n){return{type:"string",enum:Array.from(n.values)}}const o_=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function u_(n,e){const t=[V(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),V(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s);let r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const a=[];return t.forEach(s=>{if(o_(s))a.push(...s.allOf),s.unevaluatedProperties===void 0&&(r=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:o,...u}=s;i=u}else r=void 0;a.push(i)}}),a.length?{allOf:a,...r}:void 0}function c_(n,e){const t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}let Gs;const Ue={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:()=>(Gs===void 0&&(Gs=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Gs),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])$/,ipv4Cidr:/^(?:(?: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])\/(3[0-2]|[12]?[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})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function eh(n,e){const t={type:"string"};if(n.checks)for(const r of n.checks)switch(r.kind){case"min":X(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":X(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Fe(t,"email",r.message,e);break;case"format:idn-email":Fe(t,"idn-email",r.message,e);break;case"pattern:zod":ve(t,Ue.email,r.message,e);break}break;case"url":Fe(t,"uri",r.message,e);break;case"uuid":Fe(t,"uuid",r.message,e);break;case"regex":ve(t,r.regex,r.message,e);break;case"cuid":ve(t,Ue.cuid,r.message,e);break;case"cuid2":ve(t,Ue.cuid2,r.message,e);break;case"startsWith":ve(t,RegExp(`^${Ws(r.value,e)}`),r.message,e);break;case"endsWith":ve(t,RegExp(`${Ws(r.value,e)}$`),r.message,e);break;case"datetime":Fe(t,"date-time",r.message,e);break;case"date":Fe(t,"date",r.message,e);break;case"time":Fe(t,"time",r.message,e);break;case"duration":Fe(t,"duration",r.message,e);break;case"length":X(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),X(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":{ve(t,RegExp(Ws(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&Fe(t,"ipv4",r.message,e),r.version!=="v4"&&Fe(t,"ipv6",r.message,e);break}case"base64url":ve(t,Ue.base64url,r.message,e);break;case"jwt":ve(t,Ue.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&ve(t,Ue.ipv4Cidr,r.message,e),r.version!=="v4"&&ve(t,Ue.ipv6Cidr,r.message,e);break}case"emoji":ve(t,Ue.emoji(),r.message,e);break;case"ulid":{ve(t,Ue.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Fe(t,"binary",r.message,e);break}case"contentEncoding:base64":{X(t,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{ve(t,Ue.base64,r.message,e);break}}break}case"nanoid":ve(t,Ue.nanoid,r.message,e)}return t}function Ws(n,e){return e.patternStrategy==="escape"?d_(n):n}const l_=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function d_(n){let e="";for(let t=0;t<n.length;t++)l_.has(n[t])||(e+="\\"),e+=n[t];return e}function Fe(n,e,t,r){var a;n.format||(a=n.anyOf)!=null&&a.some(s=>s.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&r.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):X(n,"format",e,t,r)}function ve(n,e,t,r){var a;n.pattern||(a=n.allOf)!=null&&a.some(s=>s.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&r.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:Rc(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):X(n,"pattern",Rc(e,r),t,r)}function Rc(n,e){var u;if(!e.applyRegexFlags||!n.flags)return n.source;const t={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=t.i?n.source.toLowerCase():n.source;let a="",s=!1,i=!1,o=!1;for(let c=0;c<r.length;c++){if(s){a+=r[c],s=!1;continue}if(t.i){if(i){if(r[c].match(/[a-z]/)){o?(a+=r[c],a+=`${r[c-2]}-${r[c]}`.toUpperCase(),o=!1):r[c+1]==="-"&&((u=r[c+2])!=null&&u.match(/[a-z]/))?(a+=r[c],o=!0):a+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){a+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(t.m){if(r[c]==="^"){a+=`(^|(?<=[\r
96
+ ]))`;continue}else if(r[c]==="$"){a+=`($|(?=[\r
97
+ ]))`;continue}}if(t.s&&r[c]==="."){a+=i?`${r[c]}\r
98
+ `:`[${r[c]}\r
99
+ ]`;continue}a+=r[c],r[c]==="\\"?s=!0:i&&r[c]==="]"?i=!1:!i&&r[c]==="["&&(i=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return a}function th(n,e){var r,a,s,i,o,u;if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&((r=n.keyType)==null?void 0:r._def.typeName)===P.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((c,l)=>({...c,[l]:V(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",l]})??Le(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const t={type:"object",additionalProperties:V(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(((a=n.keyType)==null?void 0:a._def.typeName)===P.ZodString&&((s=n.keyType._def.checks)!=null&&s.length)){const{type:c,...l}=eh(n.keyType._def,e);return{...t,propertyNames:l}}else{if(((i=n.keyType)==null?void 0:i._def.typeName)===P.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};if(((o=n.keyType)==null?void 0:o._def.typeName)===P.ZodBranded&&n.keyType._def.type._def.typeName===P.ZodString&&((u=n.keyType._def.type._def.checks)!=null&&u.length)){const{type:c,...l}=Qd(n.keyType._def,e);return{...t,propertyNames:l}}}return t}function h_(n,e){if(e.mapStrategy==="record")return th(n,e);const t=V(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Le(e),r=V(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Le(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function f_(n){const e=n.values,r=Object.keys(n.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),a=Array.from(new Set(r.map(s=>typeof s)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:r}}function m_(n){return n.target==="openAi"?void 0:{not:Le({...n,currentPath:[...n.currentPath,"not"]})}}function p_(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Bn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function g_(n,e){if(e.target==="openApi3")return $c(n,e);const t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in Bn&&(!r._def.checks||!r._def.checks.length))){const r=t.reduce((a,s)=>{const i=Bn[s._def.typeName];return i&&!a.includes(i)?[...a,i]:a},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=t.reduce((a,s)=>{const i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...a,i];case"bigint":return[...a,"integer"];case"object":if(s._def.value===null)return[...a,"null"];case"symbol":case"undefined":case"function":default:return a}},[]);if(r.length===t.length){const a=r.filter((s,i,o)=>o.indexOf(s)===i);return{type:a.length>1?a:a[0],enum:t.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,a)=>[...r,...a._def.values.filter(s=>!r.includes(s))],[])};return $c(n,e)}const $c=(n,e)=>{const t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((r,a)=>V(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${a}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function y_(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"?{type:Bn[n.innerType._def.typeName],nullable:!0}:{type:[Bn[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=V(n.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const t=V(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function __(n,e){const t={type:"number"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"int":t.type="integer",Vd(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?X(t,"minimum",r.value,r.message,e):X(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),X(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?X(t,"maximum",r.value,r.message,e):X(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),X(t,"maximum",r.value,r.message,e));break;case"multipleOf":X(t,"multipleOf",r.value,r.message,e);break}return t}function b_(n,e){const t=e.target==="openAi",r={type:"object",properties:{}},a=[],s=n.shape();for(const o in s){let u=s[o];if(u===void 0||u._def===void 0)continue;let c=v_(u);c&&t&&(u._def.typeName==="ZodOptional"&&(u=u._def.innerType),u.isNullable()||(u=u.nullable()),c=!1);const l=V(u._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});l!==void 0&&(r.properties[o]=l,c||a.push(o))}a.length&&(r.required=a);const i=w_(n,e);return i!==void 0&&(r.additionalProperties=i),r}function w_(n,e){if(n.catchall._def.typeName!=="ZodNever")return V(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(n.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function v_(n){try{return n.isOptional()}catch{return!0}}const E_=(n,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return V(n.innerType._def,e);const t=V(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:Le(e)},t]}:Le(e)},S_=(n,e)=>{if(e.pipeStrategy==="input")return V(n.in._def,e);if(e.pipeStrategy==="output")return V(n.out._def,e);const t=V(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=V(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(a=>a!==void 0)}};function O_(n,e){return V(n.type._def,e)}function T_(n,e){const r={type:"array",uniqueItems:!0,items:V(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&X(r,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&X(r,"maxItems",n.maxSize.value,n.maxSize.message,e),r}function A_(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,r)=>V(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:V(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,r)=>V(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function P_(n){return{not:Le(n)}}function x_(n){return Le(n)}const I_=(n,e)=>V(n.innerType._def,e),R_=(n,e,t)=>{switch(e){case P.ZodString:return eh(n,t);case P.ZodNumber:return __(n,t);case P.ZodObject:return b_(n,t);case P.ZodBigInt:return e_(n,t);case P.ZodBoolean:return t_();case P.ZodDate:return Yd(n,t);case P.ZodUndefined:return P_(t);case P.ZodNull:return p_(t);case P.ZodArray:return Yy(n,t);case P.ZodUnion:case P.ZodDiscriminatedUnion:return g_(n,t);case P.ZodIntersection:return u_(n,t);case P.ZodTuple:return A_(n,t);case P.ZodRecord:return th(n,t);case P.ZodLiteral:return c_(n,t);case P.ZodEnum:return i_(n);case P.ZodNativeEnum:return f_(n);case P.ZodNullable:return y_(n,t);case P.ZodOptional:return E_(n,t);case P.ZodMap:return h_(n,t);case P.ZodSet:return T_(n,t);case P.ZodLazy:return()=>n.getter()._def;case P.ZodPromise:return O_(n,t);case P.ZodNaN:case P.ZodNever:return m_(t);case P.ZodEffects:return s_(n,t);case P.ZodAny:return Le(t);case P.ZodUnknown:return x_(t);case P.ZodDefault:return a_(n,t);case P.ZodBranded:return Qd(n,t);case P.ZodReadonly:return I_(n,t);case P.ZodCatch:return r_(n,t);case P.ZodPipeline:return S_(n,t);case P.ZodFunction:case P.ZodVoid:case P.ZodSymbol:return;default:return(r=>{})()}};function V(n,e,t=!1){var o;const r=e.seen.get(n);if(e.override){const u=(o=e.override)==null?void 0:o.call(e,n,e,r,t);if(u!==Ky)return u}if(r&&!t){const u=$_(r,e);if(u!==void 0)return u}const a={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,a);const s=R_(n,n.typeName,e),i=typeof s=="function"?V(s(),e):s;if(i&&k_(n,e,i),e.postProcess){const u=e.postProcess(i,n,e);return a.jsonSchema=i,u}return a.jsonSchema=i,i}const $_=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"relative":return{$ref:Xd(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.path.every((t,r)=>e.currentPath[r]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Le(e)):e.$refStrategy==="seen"?Le(e):void 0}},k_=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t),C_=(n,e)=>{const t=Qy(e);let r;const a=e==null?void 0:e.name,s=V(n._def,t,!1)??Le(t);t.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[t.openAiAnyTypeName]||(r[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));const i=a===void 0?r?{...s,[t.definitionPath]:r}:s:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,a].join("/"),[t.definitionPath]:{...r,[a]:s}};return t.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function _i(n,e){const t=typeof n;if(t!==typeof e)return!1;if(Array.isArray(n)){if(!Array.isArray(e))return!1;const r=n.length;if(r!==e.length)return!1;for(let a=0;a<r;a++)if(!_i(n[a],e[a]))return!1;return!0}if(t==="object"){if(!n||!e)return n===e;const r=Object.keys(n),a=Object.keys(e);if(r.length!==a.length)return!1;for(const i of r)if(!_i(n[i],e[i]))return!1;return!0}return n===e}function Ze(n){if(typeof n!="object"||n===null)return!1;const e=n;if(!("_zod"in e))return!1;const t=e._zod;return typeof t=="object"&&t!==null&&"def"in t}function nt(n){if(typeof n!="object"||n===null)return!1;const e=n;if(!("_def"in e)||"_zod"in e)return!1;const t=e._def;return typeof t=="object"&&t!=null&&"typeName"in t}function Pt(n){return!n||typeof n!="object"||Array.isArray(n)?!1:!!(Ze(n)||nt(n))}async function N_(n,e){if(Ze(n))try{return{success:!0,data:await Fy(n,e)}}catch(t){return{success:!1,error:t}}if(nt(n))return n.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function rh(n,e){if(Ze(n))return Zd(n,e);if(nt(n))return n.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function so(n){var e;if(Ze(n))return(e=gt.get(n))==null?void 0:e.description;if(nt(n)||"description"in n&&typeof n.description=="string")return n.description}function j_(n){return Pt(n)?nt(n)?n._def.typeName==="ZodString":Ze(n)?n._zod.def.type==="string":!1:!1}function xr(n){return Ze(n)?typeof n=="object"&&n!==null&&"_zod"in n&&typeof n._zod=="object"&&n._zod!==null&&"def"in n._zod&&typeof n._zod.def=="object"&&n._zod.def!==null&&"type"in n._zod.def&&n._zod.def.type==="object":!1}function nh(n){return Ze(n)?typeof n=="object"&&n!==null&&"_zod"in n&&typeof n._zod=="object"&&n._zod!==null&&"def"in n._zod&&typeof n._zod.def=="object"&&n._zod.def!==null&&"type"in n._zod.def&&n._zod.def.type==="array":!1}function bi(n,e=!1){if(nt(n))return n.strict();if(xr(n)){const t=n._zod.def.shape;if(e)for(const[s,i]of Object.entries(n._zod.def.shape)){if(xr(i)){const u=bi(i,e);t[s]=u}else if(nh(i)){let u=i._zod.def.element;xr(u)&&(u=bi(u,e)),t[s]=Dn(i,{...i._zod.def,element:u})}else t[s]=i;const o=gt.get(i);o&&gt.add(t[s],o)}const r=Dn(n,{...n._zod.def,shape:t,catchall:Zy(Wy)}),a=gt.get(n);return a&&gt.add(r,a),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function L_(n){return nt(n)&&"typeName"in n._def&&n._def.typeName==="ZodEffects"}function M_(n){return Ze(n)&&n._zod.def.type==="pipe"}function br(n,e=!1){if(nt(n))return L_(n)?br(n._def.schema,e):n;if(Ze(n)){let t=n;if(M_(n)&&(t=br(n._zod.def.in,e)),e){if(xr(t)){const a=t._zod.def.shape;for(const[s,i]of Object.entries(t._zod.def.shape))a[s]=br(i,e);t=Dn(t,{...t._zod.def,shape:a})}else if(nh(t)){const a=br(t._zod.def.element,e);t=Dn(t,{...t._zod.def,element:a})}}const r=gt.get(n);return r&&gt.add(t,r),t}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function yt(n){if(Ze(n)){const e=br(n,!0);if(xr(e)){const t=bi(e,!0);return yi(t)}else return yi(n)}return nt(n)?C_(n):n}function U_(n,e){if(n!==void 0&&!En(n))return n;if(ao(e))try{let t=e.getName();return t=t.startsWith("Runnable")?t.slice(8):t,t}catch{return e.getName()}else return e.name??"UnknownSchema"}function F_(n){return ao(n.data)?{type:"runnable",data:{id:n.data.lc_id,name:n.data.getName()}}:{type:"schema",data:{...yt(n.data.schema),title:n.data.name}}}class _a{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=(e==null?void 0:e.nodes)??this.nodes,this.edges=(e==null?void 0:e.edges)??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((t,r)=>{e[t.id]=En(t.id)?r:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...F_(t)})),edges:this.edges.map(t=>{const r={source:e[t.source],target:e[t.target]};return typeof t.data<"u"&&(r.data=t.data),typeof t.conditional<"u"&&(r.conditional=t.conditional),r})}}addNode(e,t,r){if(t!==void 0&&this.nodes[t]!==void 0)throw new Error(`Node with id ${t} already exists`);const a=t??it(),s={id:a,data:e,name:U_(t,e),metadata:r};return this.nodes[a]=s,s}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,r,a){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[t.id]===void 0)throw new Error(`Target node ${t.id} not in graph`);const s={source:e.id,target:t.id,data:r,conditional:a};return this.edges.push(s),s}firstNode(){return kc(this)}lastNode(){return Cc(this)}extend(e,t=""){let r=t;Object.values(e.nodes).map(c=>c.id).every(En)&&(r="");const s=c=>r?`${r}:${c}`:c;Object.entries(e.nodes).forEach(([c,l])=>{this.nodes[s(c)]={...l,id:s(c)}});const i=e.edges.map(c=>({...c,source:s(c.source),target:s(c.target)}));this.edges=[...this.edges,...i];const o=e.firstNode(),u=e.lastNode();return[o?{id:s(o.id),data:o.data}:void 0,u?{id:s(u.id),data:u.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&kc(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&Cc(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map(a=>[a.id,a.name])),t=new Map;Object.values(e).forEach(a=>{t.set(a,(t.get(a)||0)+1)});const r=a=>{const s=e[a];return En(a)&&t.get(s)===1?s:a};return new _a({nodes:Object.fromEntries(Object.entries(this.nodes).map(([a,s])=>[r(a),{...s,id:r(a)}])),edges:this.edges.map(a=>({...a,source:r(a.source),target:r(a.target)}))})}drawMermaid(e){const{withStyles:t,curveStyle:r,nodeColors:a={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:s}=e??{},i=this.reid(),o=i.firstNode(),u=i.lastNode();return Iy(i.nodes,i.edges,{firstNode:o==null?void 0:o.id,lastNode:u==null?void 0:u.id,withStyles:t,curveStyle:r,nodeColors:a,wrapLabelNWords:s})}async drawMermaidPng(e){const t=this.drawMermaid(e);return Ry(t,{backgroundColor:e==null?void 0:e.backgroundColor})}}function kc(n,e=[]){const t=new Set(n.edges.filter(a=>!e.includes(a.source)).map(a=>a.target)),r=[];for(const a of Object.values(n.nodes))!e.includes(a.id)&&!t.has(a.id)&&r.push(a);return r.length===1?r[0]:void 0}function Cc(n,e=[]){const t=new Set(n.edges.filter(a=>!e.includes(a.target)).map(a=>a.source)),r=[];for(const a of Object.values(n.nodes))!e.includes(a.id)&&!t.has(a.id)&&r.push(a);return r.length===1?r[0]:void 0}function D_(n){const e=new TextEncoder,t=new ReadableStream({async start(r){for await(const a of n)r.enqueue(e.encode(`event: data
100
+ data: ${JSON.stringify(a)}
101
+
102
+ `));r.enqueue(e.encode(`event: end
103
+
104
+ `)),r.close()}});return je.fromReadableStream(t)}function Nc(n){return typeof n=="object"&&n!==null&&typeof n[Symbol.iterator]=="function"&&typeof n.next=="function"}const B_=n=>n!=null&&typeof n=="object"&&"next"in n&&typeof n.next=="function";function wi(n){return typeof n=="object"&&n!==null&&typeof n[Symbol.asyncIterator]=="function"}function*jc(n,e){for(;;){const{value:t,done:r}=wt.runWithConfig(Kt(n),e.next.bind(e),!0);if(r)break;yield t}}async function*vi(n,e){const t=e[Symbol.asyncIterator]();for(;;){const{value:r,done:a}=await wt.runWithConfig(Kt(n),t.next.bind(e),!0);if(a)break;yield r}}function de(n,e){return n&&!Array.isArray(n)&&!(n instanceof Date)&&typeof n=="object"?n:{[e]:n}}class he extends $t{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}bind(e){return new It({bound:this,kwargs:e,config:{}})}map(){return new qn({bound:this})}withRetry(e){return new ah({bound:this,kwargs:{},config:{},maxAttemptNumber:e==null?void 0:e.stopAfterAttempt,...e})}withConfig(e){return new It({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new z_({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(K);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const r=Object.fromEntries(Object.entries(e).filter(([a])=>a!=="runId"));return Array.from({length:t},(a,s)=>K(s===0?e:r))}return Array.from({length:t},()=>K(e))}async batch(e,t,r){var u;const a=this._getOptionsList(t??{},e.length),s=((u=a[0])==null?void 0:u.maxConcurrency)??(r==null?void 0:r.maxConcurrency),i=new no({maxConcurrency:s,onFailedAttempt:c=>{throw c}}),o=e.map((c,l)=>i.call(async()=>{try{return await this.invoke(c,a[l])}catch(d){if(r!=null&&r.returnExceptions)return d;throw d}}));return Promise.all(o)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const r=K(t),a=new tr({generator:this._streamIterator(e,r),config:r});return await a.setup,je.fromAsyncGenerator(a)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=K(e):t=K({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[t,r]}async _callWithConfig(e,t,r){const a=K(r),s=await He(a),i=await(s==null?void 0:s.handleChainStart(this.toJSON(),de(t,"input"),a.runId,a==null?void 0:a.runType,void 0,void 0,(a==null?void 0:a.runName)??this.getName()));delete a.runId;let o;try{const u=e.call(this,t,a,i);o=await vt(u,r==null?void 0:r.signal)}catch(u){throw await(i==null?void 0:i.handleChainError(u)),u}return await(i==null?void 0:i.handleChainEnd(de(o,"output"))),o}async _batchWithConfig(e,t,r,a){var c;const s=this._getOptionsList(r??{},t.length),i=await Promise.all(s.map(He)),o=await Promise.all(i.map(async(l,d)=>{const h=await(l==null?void 0:l.handleChainStart(this.toJSON(),de(t[d],"input"),s[d].runId,s[d].runType,void 0,void 0,s[d].runName??this.getName()));return delete s[d].runId,h}));let u;try{const l=e.call(this,t,s,o,a);u=await vt(l,(c=s==null?void 0:s[0])==null?void 0:c.signal)}catch(l){throw await Promise.all(o.map(d=>d==null?void 0:d.handleChainError(l))),l}return await Promise.all(o.map(l=>l==null?void 0:l.handleChainEnd(de(u,"output")))),u}_concatOutputChunks(e,t){return fa(e,t)}async*_transformStreamWithConfig(e,t,r){let a,s=!0,i,o=!0;const u=K(r),c=await He(u),l=this;async function*d(){for await(const f of e){if(s)if(a===void 0)a=f;else try{a=l._concatOutputChunks(a,f)}catch{a=void 0,s=!1}yield f}}let h;try{const f=await by(t.bind(this),d(),async()=>c==null?void 0:c.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void 0,void 0,u.runName??this.getName()),r==null?void 0:r.signal,u);delete u.runId,h=f.setup;const m=h==null?void 0:h.handlers.find(Ey);let p=f.output;m!==void 0&&h!==void 0&&(p=m.tapOutputIterable(h.runId,p));const g=h==null?void 0:h.handlers.find(wy);g!==void 0&&h!==void 0&&(p=g.tapOutputIterable(h.runId,p));for await(const y of p)if(yield y,o)if(i===void 0)i=y;else try{i=this._concatOutputChunks(i,y)}catch{i=void 0,o=!1}}catch(f){throw await(h==null?void 0:h.handleChainError(f,void 0,void 0,void 0,{inputs:de(a,"input")})),f}await(h==null?void 0:h.handleChainEnd(i??{},void 0,void 0,void 0,{inputs:de(a,"input")}))}getGraph(e){const t=new _a,r=t.addNode({name:`${this.getName()}Input`,schema:Gt()}),a=t.addNode(this),s=t.addNode({name:`${this.getName()}Output`,schema:Gt()});return t.addEdge(r,a),t.addEdge(a,s),t}pipe(e){return new ot({first:this,last:xt(e)})}pick(e){return this.pipe(new H_(e))}assign(e){return this.pipe(new sh(new rr({steps:e})))}async*transform(e,t){let r;for await(const a of e)r===void 0?r=a:r=this._concatOutputChunks(r,a);yield*this._streamIterator(r,K(t))}async*streamLog(e,t,r){const a=new Pc({...r,autoClose:!1,_schemaFormat:"original"}),s=K(t);yield*this._streamLog(e,a,s)}async*_streamLog(e,t,r){const{callbacks:a}=r;if(a===void 0)r.callbacks=[t];else if(Array.isArray(a))r.callbacks=a.concat([t]);else{const u=a.copy();u.addHandler(t,!0),r.callbacks=u}const s=this.stream(e,r);async function i(){try{const u=await s;for await(const c of u){const l=new mt({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await t.writer.write(l)}}finally{await t.writer.close()}}const o=i();try{for await(const u of t)yield u}finally{await o}}streamEvents(e,t,r){let a;if(t.version==="v1")a=this._streamEventsV1(e,t,r);else if(t.version==="v2")a=this._streamEventsV2(e,t,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?D_(a):je.fromAsyncGenerator(a)}async*_streamEventsV2(e,t,r){var m;const a=new Sy({...r,autoClose:!1}),s=K(t),i=s.runId??it();s.runId=i;const o=s.callbacks;if(o===void 0)s.callbacks=[a];else if(Array.isArray(o))s.callbacks=o.concat(a);else{const p=o.copy();p.addHandler(a,!0),s.callbacks=p}const u=new AbortController,c=this;async function l(){let p,g=null;try{t!=null&&t.signal?"any"in AbortSignal?p=AbortSignal.any([u.signal,t.signal]):(p=t.signal,g=()=>{u.abort()},t.signal.addEventListener("abort",g,{once:!0})):p=u.signal;const y=await c.stream(e,{...s,signal:p}),b=a.tapOutputIterable(i,y);for await(const _ of b)if(u.signal.aborted)break}finally{await a.finish(),p&&g&&p.removeEventListener("abort",g)}}const d=l();let h=!1,f;try{for await(const p of a){if(!h){p.data.input=e,h=!0,f=p.run_id,yield p;continue}p.run_id===f&&p.event.endsWith("_end")&&(m=p.data)!=null&&m.input&&delete p.data.input,yield p}}finally{u.abort(),await d}}async*_streamEventsV1(e,t,r){let a,s=!1;const i=K(t),o=i.tags??[],u=i.metadata??{},c=i.runName??this.getName(),l=new Pc({...r,autoClose:!1,_schemaFormat:"streaming_events"}),d=new Ay({...r}),h=this._streamLog(e,l,i);for await(const m of h){if(a?a=a.concat(m):a=jr.fromRunLogPatch(m),a.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!s){s=!0;const b={...a.state},_={run_id:b.id,event:`on_${b.type}_start`,name:c,tags:o,metadata:u,data:{input:e}};d.includeEvent(_,b.type)&&(yield _)}const p=m.ops.filter(b=>b.path.startsWith("/logs/")).map(b=>b.path.split("/")[2]),g=[...new Set(p)];for(const b of g){let _,w={};const v=a.state.logs[b];if(v.end_time===void 0?v.streamed_output.length>0?_="stream":_="start":_="end",_==="start")v.inputs!==void 0&&(w.input=v.inputs);else if(_==="end")v.inputs!==void 0&&(w.input=v.inputs),w.output=v.final_output;else if(_==="stream"){const S=v.streamed_output.length;if(S!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${S} instead. Encountered in: "${v.name}"`);w={chunk:v.streamed_output[0]},v.streamed_output=[]}yield{event:`on_${v.type}_${_}`,name:v.name,run_id:v.id,tags:v.tags,metadata:v.metadata,data:w}}const{state:y}=a;if(y.streamed_output.length>0){const b=y.streamed_output.length;if(b!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${b} instead. Encountered in: "${y.name}"`);const _={chunk:y.streamed_output[0]};y.streamed_output=[];const w={event:`on_${y.type}_stream`,run_id:y.id,tags:o,metadata:u,name:c,data:_};d.includeEvent(w,y.type)&&(yield w)}}const f=a==null?void 0:a.state;if(f!==void 0){const m={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:o,metadata:u,data:{output:f.final_output}};d.includeEvent(m,f.type)&&(yield m)}}static isRunnable(e){return ao(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new It({bound:this,config:{},configFactories:[a=>({callbacks:[new Gd({config:a,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return G_(this,e)}}class It extends he{static lc_name(){return"RunnableBinding"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configFactories",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){const t=Oc(this.config,...e);return Oc(t,...this.configFactories?await Promise.all(this.configFactories.map(async r=>await r(t))):[])}bind(e){return new this.constructor({bound:this.bound,kwargs:{...this.kwargs,...e},config:this.config})}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new ah({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e==null?void 0:e.stopAfterAttempt,...e})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(K(t),this.kwargs))}async batch(e,t,r){const a=Array.isArray(t)?await Promise.all(t.map(async s=>this._mergeConfig(K(s),this.kwargs))):await this._mergeConfig(K(t),this.kwargs);return this.bound.batch(e,a,r)}_concatOutputChunks(e,t){return this.bound._concatOutputChunks(e,t)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(K(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(K(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(K(t),this.kwargs))}streamEvents(e,t,r){const a=this,s=async function*(){yield*a.bound.streamEvents(e,{...await a._mergeConfig(K(t),a.kwargs),version:t.version},r)};return je.fromAsyncGenerator(s())}static isRunnableBinding(e){return e.bound&&he.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:r}){return new It({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[a=>({callbacks:[new Gd({config:a,onStart:e,onEnd:t,onError:r})]})]})}}class qn extends he{static lc_name(){return"RunnableEach"}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound}bind(e){return new qn({bound:this.bound.bind(e)})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,r){return this.bound.batch(e,_e(t,{callbacks:r==null?void 0:r.getChild()}))}withListeners({onStart:e,onEnd:t,onError:r}){return new qn({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:r})})}}class ah extends It{static lc_name(){return"RunnableRetry"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"maxAttemptNumber",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:()=>{}}),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,r){const a=e>1?`retry:attempt:${e}`:void 0;return _e(t,{callbacks:r==null?void 0:r.getChild(a)})}async _invoke(e,t,r){return Cn(a=>super.invoke(e,this._patchConfigForRetry(a,t,r)),{onFailedAttempt:a=>this.onFailedAttempt(a,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,r,a){const s={};try{await Cn(async i=>{const o=e.map((h,f)=>f).filter(h=>s[h.toString()]===void 0||s[h.toString()]instanceof Error),u=o.map(h=>e[h]),c=o.map(h=>this._patchConfigForRetry(i,t==null?void 0:t[h],r==null?void 0:r[h])),l=await super.batch(u,c,{...a,returnExceptions:!0});let d;for(let h=0;h<l.length;h+=1){const f=l[h],m=o[h];f instanceof Error&&d===void 0&&(d=f,d.input=u[h]),s[m.toString()]=f}if(d)throw d;return l},{onFailedAttempt:i=>this.onFailedAttempt(i,i.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(i){if((a==null?void 0:a.returnExceptions)!==!0)throw i}return Object.keys(s).sort((i,o)=>parseInt(i,10)-parseInt(o,10)).map(i=>s[parseInt(i,10)])}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}}class ot extends he{static lc_name(){return"RunnableSequence"}constructor(e){super(e),Object.defineProperty(this,"first",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"middle",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"last",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitSequenceTags",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){var u;const r=K(t),a=await He(r),s=await(a==null?void 0:a.handleChainStart(this.toJSON(),de(e,"input"),r.runId,void 0,void 0,void 0,r==null?void 0:r.runName));delete r.runId;let i=e,o;try{const c=[this.first,...this.middle];for(let l=0;l<c.length;l+=1){const h=c[l].invoke(i,_e(r,{callbacks:s==null?void 0:s.getChild(this.omitSequenceTags?void 0:`seq:step:${l+1}`)}));i=await vt(h,t==null?void 0:t.signal)}if((u=t==null?void 0:t.signal)!=null&&u.aborted)throw new Error("Aborted");o=await this.last.invoke(i,_e(r,{callbacks:s==null?void 0:s.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(c){throw await(s==null?void 0:s.handleChainError(c)),c}return await(s==null?void 0:s.handleChainEnd(de(o,"output"))),o}async batch(e,t,r){var u;const a=this._getOptionsList(t??{},e.length),s=await Promise.all(a.map(He)),i=await Promise.all(s.map(async(c,l)=>{const d=await(c==null?void 0:c.handleChainStart(this.toJSON(),de(e[l],"input"),a[l].runId,void 0,void 0,void 0,a[l].runName));return delete a[l].runId,d}));let o=e;try{for(let c=0;c<this.steps.length;c+=1){const d=this.steps[c].batch(o,i.map((h,f)=>{const m=h==null?void 0:h.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return _e(a[f],{callbacks:m})}),r);o=await vt(d,(u=a[0])==null?void 0:u.signal)}}catch(c){throw await Promise.all(i.map(l=>l==null?void 0:l.handleChainError(c))),c}return await Promise.all(i.map(c=>c==null?void 0:c.handleChainEnd(de(o,"output")))),o}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async*_streamIterator(e,t){var d;const r=await He(t),{runId:a,...s}=t??{},i=await(r==null?void 0:r.handleChainStart(this.toJSON(),de(e,"input"),a,void 0,void 0,void 0,s==null?void 0:s.runName)),o=[this.first,...this.middle,this.last];let u=!0,c;async function*l(){yield e}try{let h=o[0].transform(l(),_e(s,{callbacks:i==null?void 0:i.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let f=1;f<o.length;f+=1)h=await o[f].transform(h,_e(s,{callbacks:i==null?void 0:i.getChild(this.omitSequenceTags?void 0:`seq:step:${f+1}`)}));for await(const f of h)if((d=t==null?void 0:t.signal)==null||d.throwIfAborted(),yield f,u)if(c===void 0)c=f;else try{c=this._concatOutputChunks(c,f)}catch{c=void 0,u=!1}}catch(h){throw await(i==null?void 0:i.handleChainError(h)),h}await(i==null?void 0:i.handleChainEnd(de(c,"output")))}getGraph(e){const t=new _a;let r=null;return this.steps.forEach((a,s)=>{const i=a.getGraph(e);s!==0&&i.trimFirstNode(),s!==this.steps.length-1&&i.trimLastNode(),t.extend(i);const o=i.firstNode();if(!o)throw new Error(`Runnable ${a} has no first node`);r&&t.addEdge(r,o),r=i.lastNode()}),t}pipe(e){return ot.isRunnableSequence(e)?new ot({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new ot({first:this.first,middle:[...this.middle,this.last],last:xt(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&he.isRunnable(e)}static from([e,...t],r){let a={};return typeof r=="string"?a.name=r:r!==void 0&&(a=r),new ot({...a,first:xt(e),middle:t.slice(0,-1).map(xt),last:xt(t[t.length-1])})}}class rr extends he{static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"steps",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.steps={};for(const[t,r]of Object.entries(e.steps))this.steps[t]=xt(r)}static from(e){return new rr({steps:e})}async invoke(e,t){const r=K(t),a=await He(r),s=await(a==null?void 0:a.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r==null?void 0:r.runName));delete r.runId;const i={};try{const o=Object.entries(this.steps).map(async([u,c])=>{i[u]=await c.invoke(e,_e(r,{callbacks:s==null?void 0:s.getChild(`map:key:${u}`)}))});await vt(Promise.all(o),t==null?void 0:t.signal)}catch(o){throw await(s==null?void 0:s.handleChainError(o)),o}return await(s==null?void 0:s.handleChainEnd(i)),i}async*_transform(e,t,r){const a={...this.steps},s=Hd(e,Object.keys(a).length),i=new Map(Object.entries(a).map(([o,u],c)=>{const l=u.transform(s[c],_e(r,{callbacks:t==null?void 0:t.getChild(`map:key:${o}`)}));return[o,l.next().then(d=>({key:o,gen:l,result:d}))]}));for(;i.size;){const o=Promise.race(i.values()),{key:u,result:c,gen:l}=await vt(o,r==null?void 0:r.signal);i.delete(u),c.done||(yield{[u]:c.value},i.set(u,l.next().then(d=>({key:u,gen:l,result:d}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const a=K(t),s=new tr({generator:this.transform(r(),a),config:a});return await s.setup,je.fromAsyncGenerator(s)}}class io extends he{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!Zi(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){const[r]=this._getOptionsList(t??{},1),a=await He(r),s=this.func(_e(r,{callbacks:a}),e);return vt(s,r==null?void 0:r.signal)}async*_streamIterator(e,t){var s,i;const[r]=this._getOptionsList(t??{},1),a=await this.invoke(e,t);if(wi(a)){for await(const o of a)(s=r==null?void 0:r.signal)==null||s.throwIfAborted(),yield o;return}if(B_(a)){for(;;){(i=r==null?void 0:r.signal)==null||i.throwIfAborted();const o=a.next();if(o.done)break;yield o.value}return}yield a}static from(e){return new io({func:e})}}function q_(n){if(Zi(n))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}class nr extends he{static lc_name(){return"RunnableLambda"}constructor(e){if(Zi(e.func))return io.from(e.func);super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),q_(e.func),this.func=e.func}static from(e){return new nr({func:e})}async _invoke(e,t,r){return new Promise((a,s)=>{const i=_e(t,{callbacks:r==null?void 0:r.getChild(),recursionLimit:((t==null?void 0:t.recursionLimit)??qs)-1});wt.runWithConfig(Kt(i),async()=>{var o,u;try{let c=await this.func(e,{...i});if(c&&he.isRunnable(c)){if((t==null?void 0:t.recursionLimit)===0)throw new Error("Recursion limit reached.");c=await c.invoke(e,{...i,recursionLimit:(i.recursionLimit??qs)-1})}else if(wi(c)){let l;for await(const d of vi(i,c))if((o=t==null?void 0:t.signal)==null||o.throwIfAborted(),l===void 0)l=d;else try{l=this._concatOutputChunks(l,d)}catch{l=d}c=l}else if(Nc(c)){let l;for(const d of jc(i,c))if((u=t==null?void 0:t.signal)==null||u.throwIfAborted(),l===void 0)l=d;else try{l=this._concatOutputChunks(l,d)}catch{l=d}c=l}a(c)}catch(c){s(c)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,r){var o,u;let a;for await(const c of e)if(a===void 0)a=c;else try{a=this._concatOutputChunks(a,c)}catch{a=c}const s=_e(r,{callbacks:t==null?void 0:t.getChild(),recursionLimit:((r==null?void 0:r.recursionLimit)??qs)-1}),i=await new Promise((c,l)=>{wt.runWithConfig(Kt(s),async()=>{try{const d=await this.func(a,{...s,config:s});c(d)}catch(d){l(d)}})});if(i&&he.isRunnable(i)){if((r==null?void 0:r.recursionLimit)===0)throw new Error("Recursion limit reached.");const c=await i.stream(a,s);for await(const l of c)yield l}else if(wi(i))for await(const c of vi(s,i))(o=r==null?void 0:r.signal)==null||o.throwIfAborted(),yield c;else if(Nc(i))for(const c of jc(s,i))(u=r==null?void 0:r.signal)==null||u.throwIfAborted(),yield c;else yield i}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const a=K(t),s=new tr({generator:this.transform(r(),a),config:a});return await s.setup,je.fromAsyncGenerator(s)}}class z_ extends he{static lc_name(){return"RunnableWithFallbacks"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"runnable",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fallbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const r=K(t),a=await He(r),{runId:s,...i}=r,o=await(a==null?void 0:a.handleChainStart(this.toJSON(),de(e,"input"),s,void 0,void 0,void 0,i==null?void 0:i.runName)),u=_e(i,{callbacks:o==null?void 0:o.getChild()});return await wt.runWithConfig(u,async()=>{var d;let l;for(const h of this.runnables()){(d=r==null?void 0:r.signal)==null||d.throwIfAborted();try{const f=await h.invoke(e,u);return await(o==null?void 0:o.handleChainEnd(de(f,"output"))),f}catch(f){l===void 0&&(l=f)}}throw l===void 0?new Error("No error stored at end of fallback."):(await(o==null?void 0:o.handleChainError(l)),l)})}async*_streamIterator(e,t){var d;const r=K(t),a=await He(r),{runId:s,...i}=r,o=await(a==null?void 0:a.handleChainStart(this.toJSON(),de(e,"input"),s,void 0,void 0,void 0,i==null?void 0:i.runName));let u,c;for(const h of this.runnables()){(d=r==null?void 0:r.signal)==null||d.throwIfAborted();const f=_e(i,{callbacks:o==null?void 0:o.getChild()});try{const m=await h.stream(e,f);c=vi(f,m);break}catch(m){u===void 0&&(u=m)}}if(c===void 0){const h=u??new Error("No error stored at end of fallback.");throw await(o==null?void 0:o.handleChainError(h)),h}let l;try{for await(const h of c){yield h;try{l=l===void 0?l:this._concatOutputChunks(l,h)}catch{l=void 0}}}catch(h){throw await(o==null?void 0:o.handleChainError(h)),h}await(o==null?void 0:o.handleChainEnd(de(l,"output")))}async batch(e,t,r){var u;if(r!=null&&r.returnExceptions)throw new Error("Not implemented.");const a=this._getOptionsList(t??{},e.length),s=await Promise.all(a.map(c=>He(c))),i=await Promise.all(s.map(async(c,l)=>{const d=await(c==null?void 0:c.handleChainStart(this.toJSON(),de(e[l],"input"),a[l].runId,void 0,void 0,void 0,a[l].runName));return delete a[l].runId,d}));let o;for(const c of this.runnables()){(u=a[0].signal)==null||u.throwIfAborted();try{const l=await c.batch(e,i.map((d,h)=>_e(a[h],{callbacks:d==null?void 0:d.getChild()})),r);return await Promise.all(i.map((d,h)=>d==null?void 0:d.handleChainEnd(de(l[h],"output")))),l}catch(l){o===void 0&&(o=l)}}throw o?(await Promise.all(i.map(c=>c==null?void 0:c.handleChainError(o))),o):new Error("No error stored at end of fallbacks.")}}function xt(n){if(typeof n=="function")return new nr({func:n});if(he.isRunnable(n))return n;if(!Array.isArray(n)&&typeof n=="object"){const e={};for(const[t,r]of Object.entries(n))e[t]=xt(r);return new rr({steps:e})}else throw new Error(`Expected a Runnable, function or object.
105
+ Instead got an unsupported type.`)}class sh extends he{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof rr&&(e={mapper:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mapper=e.mapper}async invoke(e,t){const r=await this.mapper.invoke(e,t);return{...e,...r}}async*_transform(e,t,r){const a=this.mapper.getStepsKeys(),[s,i]=Hd(e),o=this.mapper.transform(i,_e(r,{callbacks:t==null?void 0:t.getChild()})),u=o.next();for await(const c of s){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);const l=Object.fromEntries(Object.entries(c).filter(([d])=>!a.includes(d)));Object.keys(l).length>0&&(yield l)}yield(await u).value;for await(const c of o)yield c}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const a=K(t),s=new tr({generator:this.transform(r(),a),config:a});return await s.setup,je.fromAsyncGenerator(s)}}class H_ extends he{static lc_name(){return"RunnablePick"}constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"keys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keys=e.keys}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{const t=this.keys.map(r=>[r,e[r]]).filter(r=>r[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(const t of e){const r=await this._pick(t);r!==void 0&&(yield r)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const a=K(t),s=new tr({generator:this.transform(r(),a),config:a});return await s.setup,je.fromAsyncGenerator(s)}}class Lc extends It{constructor(e){const t=ot.from([nr.from(async r=>{let a;if(bd(r))try{a=await rh(this.schema,r.args)}catch{throw new cm("Received tool input did not match expected schema",JSON.stringify(r.args))}else a=r;return a}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}}function G_(n,e){const t=e.name??n.getName(),r=e.description??so(e.schema);return j_(e.schema)?new Lc({name:t,description:r,schema:wr({input:Ti()}).transform(a=>a.input),bound:n}):new Lc({name:t,description:r,schema:e.schema,bound:n})}/*
106
+ * [js-sha1]{@link https://github.com/emn178/js-sha1}
107
+ *
108
+ * @version 0.6.0
109
+ * @author Chen, Yi-Cyuan [emn178@gmail.com]
110
+ * @copyright Chen, Yi-Cyuan 2014-2017
111
+ * @license MIT
112
+ */var W_=typeof window=="object"?window:{},H="0123456789abcdef".split(""),J_=[-2147483648,8388608,32768,128],De=[24,16,8,0],ce=[];function Ge(n){n?(ce[0]=ce[16]=ce[1]=ce[2]=ce[3]=ce[4]=ce[5]=ce[6]=ce[7]=ce[8]=ce[9]=ce[10]=ce[11]=ce[12]=ce[13]=ce[14]=ce[15]=0,this.blocks=ce):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.h0=1732584193,this.h1=4023233417,this.h2=2562383102,this.h3=271733878,this.h4=3285377520,this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}Ge.prototype.update=function(n){if(!this.finalized){var e=typeof n!="string";e&&n.constructor===W_.ArrayBuffer&&(n=new Uint8Array(n));for(var t,r=0,a,s=n.length||0,i=this.blocks;r<s;){if(this.hashed&&(this.hashed=!1,i[0]=this.block,i[16]=i[1]=i[2]=i[3]=i[4]=i[5]=i[6]=i[7]=i[8]=i[9]=i[10]=i[11]=i[12]=i[13]=i[14]=i[15]=0),e)for(a=this.start;r<s&&a<64;++r)i[a>>2]|=n[r]<<De[a++&3];else for(a=this.start;r<s&&a<64;++r)t=n.charCodeAt(r),t<128?i[a>>2]|=t<<De[a++&3]:t<2048?(i[a>>2]|=(192|t>>6)<<De[a++&3],i[a>>2]|=(128|t&63)<<De[a++&3]):t<55296||t>=57344?(i[a>>2]|=(224|t>>12)<<De[a++&3],i[a>>2]|=(128|t>>6&63)<<De[a++&3],i[a>>2]|=(128|t&63)<<De[a++&3]):(t=65536+((t&1023)<<10|n.charCodeAt(++r)&1023),i[a>>2]|=(240|t>>18)<<De[a++&3],i[a>>2]|=(128|t>>12&63)<<De[a++&3],i[a>>2]|=(128|t>>6&63)<<De[a++&3],i[a>>2]|=(128|t&63)<<De[a++&3]);this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=i[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};Ge.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var n=this.blocks,e=this.lastByteIndex;n[16]=this.block,n[e>>2]|=J_[e&3],this.block=n[16],e>=56&&(this.hashed||this.hash(),n[0]=this.block,n[16]=n[1]=n[2]=n[3]=n[4]=n[5]=n[6]=n[7]=n[8]=n[9]=n[10]=n[11]=n[12]=n[13]=n[14]=n[15]=0),n[14]=this.hBytes<<3|this.bytes>>>29,n[15]=this.bytes<<3,this.hash()}};Ge.prototype.hash=function(){var n=this.h0,e=this.h1,t=this.h2,r=this.h3,a=this.h4,s,i,o,u=this.blocks;for(i=16;i<80;++i)o=u[i-3]^u[i-8]^u[i-14]^u[i-16],u[i]=o<<1|o>>>31;for(i=0;i<20;i+=5)s=e&t|~e&r,o=n<<5|n>>>27,a=o+s+a+1518500249+u[i]<<0,e=e<<30|e>>>2,s=n&e|~n&t,o=a<<5|a>>>27,r=o+s+r+1518500249+u[i+1]<<0,n=n<<30|n>>>2,s=a&n|~a&e,o=r<<5|r>>>27,t=o+s+t+1518500249+u[i+2]<<0,a=a<<30|a>>>2,s=r&a|~r&n,o=t<<5|t>>>27,e=o+s+e+1518500249+u[i+3]<<0,r=r<<30|r>>>2,s=t&r|~t&a,o=e<<5|e>>>27,n=o+s+n+1518500249+u[i+4]<<0,t=t<<30|t>>>2;for(;i<40;i+=5)s=e^t^r,o=n<<5|n>>>27,a=o+s+a+1859775393+u[i]<<0,e=e<<30|e>>>2,s=n^e^t,o=a<<5|a>>>27,r=o+s+r+1859775393+u[i+1]<<0,n=n<<30|n>>>2,s=a^n^e,o=r<<5|r>>>27,t=o+s+t+1859775393+u[i+2]<<0,a=a<<30|a>>>2,s=r^a^n,o=t<<5|t>>>27,e=o+s+e+1859775393+u[i+3]<<0,r=r<<30|r>>>2,s=t^r^a,o=e<<5|e>>>27,n=o+s+n+1859775393+u[i+4]<<0,t=t<<30|t>>>2;for(;i<60;i+=5)s=e&t|e&r|t&r,o=n<<5|n>>>27,a=o+s+a-1894007588+u[i]<<0,e=e<<30|e>>>2,s=n&e|n&t|e&t,o=a<<5|a>>>27,r=o+s+r-1894007588+u[i+1]<<0,n=n<<30|n>>>2,s=a&n|a&e|n&e,o=r<<5|r>>>27,t=o+s+t-1894007588+u[i+2]<<0,a=a<<30|a>>>2,s=r&a|r&n|a&n,o=t<<5|t>>>27,e=o+s+e-1894007588+u[i+3]<<0,r=r<<30|r>>>2,s=t&r|t&a|r&a,o=e<<5|e>>>27,n=o+s+n-1894007588+u[i+4]<<0,t=t<<30|t>>>2;for(;i<80;i+=5)s=e^t^r,o=n<<5|n>>>27,a=o+s+a-899497514+u[i]<<0,e=e<<30|e>>>2,s=n^e^t,o=a<<5|a>>>27,r=o+s+r-899497514+u[i+1]<<0,n=n<<30|n>>>2,s=a^n^e,o=r<<5|r>>>27,t=o+s+t-899497514+u[i+2]<<0,a=a<<30|a>>>2,s=r^a^n,o=t<<5|t>>>27,e=o+s+e-899497514+u[i+3]<<0,r=r<<30|r>>>2,s=t^r^a,o=e<<5|e>>>27,n=o+s+n-899497514+u[i+4]<<0,t=t<<30|t>>>2;this.h0=this.h0+n<<0,this.h1=this.h1+e<<0,this.h2=this.h2+t<<0,this.h3=this.h3+r<<0,this.h4=this.h4+a<<0};Ge.prototype.hex=function(){this.finalize();var n=this.h0,e=this.h1,t=this.h2,r=this.h3,a=this.h4;return H[n>>28&15]+H[n>>24&15]+H[n>>20&15]+H[n>>16&15]+H[n>>12&15]+H[n>>8&15]+H[n>>4&15]+H[n&15]+H[e>>28&15]+H[e>>24&15]+H[e>>20&15]+H[e>>16&15]+H[e>>12&15]+H[e>>8&15]+H[e>>4&15]+H[e&15]+H[t>>28&15]+H[t>>24&15]+H[t>>20&15]+H[t>>16&15]+H[t>>12&15]+H[t>>8&15]+H[t>>4&15]+H[t&15]+H[r>>28&15]+H[r>>24&15]+H[r>>20&15]+H[r>>16&15]+H[r>>12&15]+H[r>>8&15]+H[r>>4&15]+H[r&15]+H[a>>28&15]+H[a>>24&15]+H[a>>20&15]+H[a>>16&15]+H[a>>12&15]+H[a>>8&15]+H[a>>4&15]+H[a&15]};Ge.prototype.toString=Ge.prototype.hex;Ge.prototype.digest=function(){this.finalize();var n=this.h0,e=this.h1,t=this.h2,r=this.h3,a=this.h4;return[n>>24&255,n>>16&255,n>>8&255,n&255,e>>24&255,e>>16&255,e>>8&255,e&255,t>>24&255,t>>16&255,t>>8&255,t&255,r>>24&255,r>>16&255,r>>8&255,r&255,a>>24&255,a>>16&255,a>>8&255,a&255]};Ge.prototype.array=Ge.prototype.digest;Ge.prototype.arrayBuffer=function(){this.finalize();var n=new ArrayBuffer(20),e=new DataView(n);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),n};let Mc=!1;const Z_=n=>(Mc||(console.warn(["The default method for hashing keys is insecure and will be replaced in a future version,","but hasn't been replaced yet as to not break existing caches. It's recommended that you use","a more secure hashing algorithm to avoid cache poisoning.","","See this page for more information:","|","└> https://js.langchain.com/docs/troubleshooting/warnings/insecure-cache-algorithm"].join(`
113
+ `)),Mc=!0),new Ge(!0).update(n).hex()),K_=(...n)=>Z_(n.join("_"));class V_{constructor(){Object.defineProperty(this,"keyEncoder",{enumerable:!0,configurable:!0,writable:!0,value:K_})}makeDefaultKeyEncoder(e){this.keyEncoder=e}}const X_=new Map;class oo extends V_{constructor(e){super(),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cache=e??new Map}lookup(e,t){return Promise.resolve(this.cache.get(this.keyEncoder(e,t))??null)}async update(e,t,r){this.cache.set(this.keyEncoder(e,t),r)}static global(){return new oo(X_)}}class ih extends $t{}class Q_ extends ih{static lc_name(){return"StringPromptValue"}constructor(e){super({value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=e}toString(){return this.value}toChatMessages(){return[new sa(this.value)]}}class Y_ extends ih{static lc_name(){return"ChatPromptValue"}constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.messages=e.messages}toString(){return wd(this.messages)}toChatMessages(){return this.messages}}var ur={},Uc;function eb(){if(Uc)return ur;Uc=1,ur.byteLength=o,ur.toByteArray=c,ur.fromByteArray=h;for(var n=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,s=r.length;a<s;++a)n[a]=r[a],e[r.charCodeAt(a)]=a;e[45]=62,e[95]=63;function i(f){var m=f.length;if(m%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var p=f.indexOf("=");p===-1&&(p=m);var g=p===m?0:4-p%4;return[p,g]}function o(f){var m=i(f),p=m[0],g=m[1];return(p+g)*3/4-g}function u(f,m,p){return(m+p)*3/4-p}function c(f){var m,p=i(f),g=p[0],y=p[1],b=new t(u(f,g,y)),_=0,w=y>0?g-4:g,v;for(v=0;v<w;v+=4)m=e[f.charCodeAt(v)]<<18|e[f.charCodeAt(v+1)]<<12|e[f.charCodeAt(v+2)]<<6|e[f.charCodeAt(v+3)],b[_++]=m>>16&255,b[_++]=m>>8&255,b[_++]=m&255;return y===2&&(m=e[f.charCodeAt(v)]<<2|e[f.charCodeAt(v+1)]>>4,b[_++]=m&255),y===1&&(m=e[f.charCodeAt(v)]<<10|e[f.charCodeAt(v+1)]<<4|e[f.charCodeAt(v+2)]>>2,b[_++]=m>>8&255,b[_++]=m&255),b}function l(f){return n[f>>18&63]+n[f>>12&63]+n[f>>6&63]+n[f&63]}function d(f,m,p){for(var g,y=[],b=m;b<p;b+=3)g=(f[b]<<16&16711680)+(f[b+1]<<8&65280)+(f[b+2]&255),y.push(l(g));return y.join("")}function h(f){for(var m,p=f.length,g=p%3,y=[],b=16383,_=0,w=p-g;_<w;_+=b)y.push(d(f,_,_+b>w?w:_+b));return g===1?(m=f[p-1],y.push(n[m>>2]+n[m<<4&63]+"==")):g===2&&(m=(f[p-2]<<8)+f[p-1],y.push(n[m>>10]+n[m>>4&63]+n[m<<2&63]+"=")),y.join("")}return ur}var tb=eb();const rb=Lr(tb);var nb=Object.defineProperty,ab=(n,e,t)=>e in n?nb(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,sb=(n,e,t)=>(ab(n,e+"",t),t);function ib(n,e){let t=Array.from({length:n.length},(r,a)=>({start:a,end:a+1}));for(;t.length>1;){let r=null;for(let a=0;a<t.length-1;a++){const s=n.slice(t[a].start,t[a+1].end),i=e.get(s.join(","));i!=null&&(r==null||i<r[0])&&(r=[i,a])}if(r!=null){const a=r[1];t[a]={start:t[a].start,end:t[a+1].end},t.splice(a+1,1)}else break}return t}function ob(n,e){return n.length===1?[e.get(n.join(","))]:ib(n,e).map(t=>e.get(n.slice(t.start,t.end).join(","))).filter(t=>t!=null)}function ub(n){return n.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var Ei=class{constructor(n,e){be(this,"specialTokens");be(this,"inverseSpecialTokens");be(this,"patStr");be(this,"textEncoder",new TextEncoder);be(this,"textDecoder",new TextDecoder("utf-8"));be(this,"rankMap",new Map);be(this,"textMap",new Map);this.patStr=n.pat_str;const t=n.bpe_ranks.split(`
114
+ `).filter(Boolean).reduce((r,a)=>{const[s,i,...o]=a.split(" "),u=Number.parseInt(i,10);return o.forEach((c,l)=>r[c]=u+l),r},{});for(const[r,a]of Object.entries(t)){const s=rb.toByteArray(r);this.rankMap.set(s.join(","),a),this.textMap.set(a,s)}this.specialTokens={...n.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[a,s])=>(r[s]=this.textEncoder.encode(a),r),{})}encode(n,e=[],t="all"){const r=new RegExp(this.patStr,"ug"),a=Ei.specialTokenRegex(Object.keys(this.specialTokens)),s=[],i=new Set(e==="all"?Object.keys(this.specialTokens):e),o=new Set(t==="all"?Object.keys(this.specialTokens).filter(c=>!i.has(c)):t);if(o.size>0){const c=Ei.specialTokenRegex([...o]),l=n.match(c);if(l!=null)throw new Error(`The text contains a special token that is not allowed: ${l[0]}`)}let u=0;for(;;){let c=null,l=u;for(;a.lastIndex=l,c=a.exec(n),!(c==null||i.has(c[0]));)l=c.index+1;const d=(c==null?void 0:c.index)??n.length;for(const f of n.substring(u,d).matchAll(r)){const m=this.textEncoder.encode(f[0]),p=this.rankMap.get(m.join(","));if(p!=null){s.push(p);continue}s.push(...ob(m,this.rankMap))}if(c==null)break;let h=this.specialTokens[c[0]];s.push(h),u=c.index+c[0].length}return s}decode(n){const e=[];let t=0;for(let s=0;s<n.length;++s){const i=n[s],o=this.textMap.get(i)??this.inverseSpecialTokens[i];o!=null&&(e.push(o),t+=o.length)}const r=new Uint8Array(t);let a=0;for(const s of e)r.set(s,a),a+=s.length;return this.textDecoder.decode(r)}},oh=Ei;sb(oh,"specialTokenRegex",n=>new RegExp(n.map(e=>ub(e)).join("|"),"g"));function cb(n){switch(n){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}const dn={},lb=new no({});async function db(n){return n in dn||(dn[n]=lb.fetch(`https://tiktoken.pages.dev/js/${n}.json`).then(e=>e.json()).then(e=>new oh(e)).catch(e=>{throw delete dn[n],e})),await dn[n]}async function hb(n){return db(cb(n))}const fb=n=>n.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":n.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":n.startsWith("gpt-4-32k")?"gpt-4-32k":n.startsWith("gpt-4-")?"gpt-4":n.startsWith("gpt-4o")?"gpt-4o":n;function uh(n){return typeof n!="object"||!n?!1:!!("type"in n&&n.type==="function"&&"function"in n&&typeof n.function=="object"&&n.function&&"name"in n.function&&"parameters"in n.function)}const mb=()=>!1;class pb extends he{get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verbose=e.verbose??mb(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}}class gb extends pb{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}constructor({callbacks:e,callbackManager:t,...r}){const{cache:a,...s}=r;super({callbacks:e??t,...s}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_encoding",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof a=="object"?this.cache=a:a?this.cache=oo.global():this.cache=void 0,this.caller=new no(r??{})}async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(a=>typeof a=="string"?a:a.type==="text"&&"text"in a?a.text:"").join("");let r=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await hb("modelName"in this?fb(this.modelName):"gpt2")}catch(a){console.warn("Failed to calculate number of tokens, falling back to approximate count",a)}if(this._encoding)try{r=this._encoding.encode(t).length}catch(a){console.warn("Failed to calculate number of tokens, falling back to approximate count",a)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new Q_(e):Array.isArray(e)?new Y_(e.map(_r)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){const r={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([i,o])=>o!==void 0).map(([i,o])=>`${i}:${JSON.stringify(o)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}}class zn extends he{static lc_name(){return"RunnablePassthrough"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e&&(this.func=e.func)}async invoke(e,t){const r=K(t);return this.func&&await this.func(e,r),this._callWithConfig(a=>Promise.resolve(a),e,r)}async*transform(e,t){const r=K(t);let a,s=!0;for await(const i of this._transformStreamWithConfig(e,o=>o,r))if(yield i,s)if(a===void 0)a=i;else try{a=fa(a,i)}catch{a=void 0,s=!1}this.func&&a!==void 0&&await this.func(a,r)}static assign(e){return new sh(new rr({steps:e}))}}function Js(n){const e=[];for(const t of n){let r=t;if(Array.isArray(t.content))for(let a=0;a<t.content.length;a++){const s=t.content[a];(Yf(s)||em(s))&&r===t&&(r=new t.constructor({...r,content:[...t.content.slice(0,a),tm(s),...t.content.slice(a+1)]}))}e.push(r)}return e}class pt extends gb{constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","chat_models",this._llmType()]}),Object.defineProperty(this,"disableStreaming",{enumerable:!0,configurable:!0,writable:!0,value:!1})}_separateRunnableConfigFromCallOptionsCompat(e){const[t,r]=super._separateRunnableConfigFromCallOptions(e);return r.signal=t.signal,[t,r]}async invoke(e,t){const r=pt._convertInputToPromptValue(e);return(await this.generatePrompt([r],t,t==null?void 0:t.callbacks)).generations[0][0].message}async*_streamResponseChunks(e,t,r){throw new Error("Not implemented.")}async*_streamIterator(e,t){var r;if(this._streamResponseChunks===pt.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(e,t);else{const s=pt._convertInputToPromptValue(e).toChatMessages(),[i,o]=this._separateRunnableConfigFromCallOptionsCompat(t),u={...i.metadata,...this.getLsParams(o)},c=await Ie.configure(i.callbacks,this.callbacks,i.tags,this.tags,u,this.metadata,{verbose:this.verbose}),l={options:o,invocation_params:this==null?void 0:this.invocationParams(o),batch_size:1},d=await(c==null?void 0:c.handleChatModelStart(this.toJSON(),[Js(s)],i.runId,void 0,l,void 0,void 0,i.runName));let h,f;try{for await(const m of this._streamResponseChunks(s,o,d==null?void 0:d[0])){if(m.message.id==null){const p=(r=d==null?void 0:d.at(0))==null?void 0:r.runId;p!=null&&m.message._updateId(`run-${p}`)}m.message.response_metadata={...m.generationInfo,...m.message.response_metadata},yield m.message,h?h=h.concat(m):h=m,Vo(m.message)&&m.message.usage_metadata!==void 0&&(f={tokenUsage:{promptTokens:m.message.usage_metadata.input_tokens,completionTokens:m.message.usage_metadata.output_tokens,totalTokens:m.message.usage_metadata.total_tokens}})}}catch(m){throw await Promise.all((d??[]).map(p=>p==null?void 0:p.handleLLMError(m))),m}await Promise.all((d??[]).map(m=>m==null?void 0:m.handleLLMEnd({generations:[[h]],llmOutput:f})))}}getLsParams(e){const t=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:e.stop,ls_provider:t}}async _generateUncached(e,t,r,a){var d,h;const s=e.map(f=>f.map(_r));let i;if(a!==void 0&&a.length===s.length)i=a;else{const f={...r.metadata,...this.getLsParams(t)},m=await Ie.configure(r.callbacks,this.callbacks,r.tags,this.tags,f,this.metadata,{verbose:this.verbose}),p={options:t,invocation_params:this==null?void 0:this.invocationParams(t),batch_size:1};i=await(m==null?void 0:m.handleChatModelStart(this.toJSON(),s.map(Js),r.runId,void 0,p,void 0,void 0,r.runName))}const o=[],u=[];if(!!(i!=null&&i[0].handlers.find(Yg))&&!this.disableStreaming&&s.length===1&&this._streamResponseChunks!==pt.prototype._streamResponseChunks)try{const f=await this._streamResponseChunks(s[0],t,i==null?void 0:i[0]);let m,p;for await(const g of f){if(g.message.id==null){const y=(d=i==null?void 0:i.at(0))==null?void 0:d.runId;y!=null&&g.message._updateId(`run-${y}`)}m===void 0?m=g:m=fa(m,g),Vo(g.message)&&g.message.usage_metadata!==void 0&&(p={tokenUsage:{promptTokens:g.message.usage_metadata.input_tokens,completionTokens:g.message.usage_metadata.output_tokens,totalTokens:g.message.usage_metadata.total_tokens}})}if(m===void 0)throw new Error("Received empty response from chat model call.");o.push([m]),await(i==null?void 0:i[0].handleLLMEnd({generations:o,llmOutput:p}))}catch(f){throw await(i==null?void 0:i[0].handleLLMError(f)),f}else{const f=await Promise.allSettled(s.map((m,p)=>this._generate(m,{...t,promptIndex:p},i==null?void 0:i[p])));await Promise.all(f.map(async(m,p)=>{var g,y,b;if(m.status==="fulfilled"){const _=m.value;for(const w of _.generations){if(w.message.id==null){const v=(g=i==null?void 0:i.at(0))==null?void 0:g.runId;v!=null&&w.message._updateId(`run-${v}`)}w.message.response_metadata={...w.generationInfo,...w.message.response_metadata}}return _.generations.length===1&&(_.generations[0].message.response_metadata={..._.llmOutput,..._.generations[0].message.response_metadata}),o[p]=_.generations,u[p]=_.llmOutput,(y=i==null?void 0:i[p])==null?void 0:y.handleLLMEnd({generations:[_.generations],llmOutput:_.llmOutput})}else return await((b=i==null?void 0:i[p])==null?void 0:b.handleLLMError(m.reason)),Promise.reject(m.reason)}))}const l={generations:o,llmOutput:u.length?(h=this._combineLLMOutput)==null?void 0:h.call(this,...u):void 0};return Object.defineProperty(l,xc,{value:i?{runIds:i==null?void 0:i.map(f=>f.runId)}:void 0,configurable:!0}),l}async _generateCached({messages:e,cache:t,llmStringKey:r,parsedOptions:a,handledOptions:s}){const i=e.map(g=>g.map(_r)),o={...s.metadata,...this.getLsParams(a)},u=await Ie.configure(s.callbacks,this.callbacks,s.tags,this.tags,o,this.metadata,{verbose:this.verbose}),c={options:a,invocation_params:this==null?void 0:this.invocationParams(a),batch_size:1},l=await(u==null?void 0:u.handleChatModelStart(this.toJSON(),i.map(Js),s.runId,void 0,c,void 0,void 0,s.runName)),d=[],f=(await Promise.allSettled(i.map(async(g,y)=>{const b=pt._convertInputToPromptValue(g).toString(),_=await t.lookup(b,r);return _==null&&d.push(y),_}))).map((g,y)=>({result:g,runManager:l==null?void 0:l[y]})).filter(({result:g})=>g.status==="fulfilled"&&g.value!=null||g.status==="rejected"),m=[];await Promise.all(f.map(async({result:g,runManager:y},b)=>{if(g.status==="fulfilled"){const _=g.value;return m[b]=_.map(w=>("message"in w&&ra(w.message)&&Br(w.message)&&(w.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0}),w.generationInfo={...w.generationInfo,tokenUsage:{}},w)),_.length&&await(y==null?void 0:y.handleLLMNewToken(_[0].text)),y==null?void 0:y.handleLLMEnd({generations:[_]},void 0,void 0,void 0,{cached:!0})}else return await(y==null?void 0:y.handleLLMError(g.reason,void 0,void 0,void 0,{cached:!0})),Promise.reject(g.reason)}));const p={generations:m,missingPromptIndices:d,startedRunManagers:l};return Object.defineProperty(p,xc,{value:l?{runIds:l==null?void 0:l.map(g=>g.runId)}:void 0,configurable:!0}),p}async generate(e,t,r){let a;Array.isArray(t)?a={stop:t}:a=t;const s=e.map(m=>m.map(_r)),[i,o]=this._separateRunnableConfigFromCallOptionsCompat(a);if(i.callbacks=i.callbacks??r,!this.cache)return this._generateUncached(s,o,i);const{cache:u}=this,c=this._getSerializedCacheKeyParametersForCall(o),{generations:l,missingPromptIndices:d,startedRunManagers:h}=await this._generateCached({messages:s,cache:u,llmStringKey:c,parsedOptions:o,handledOptions:i});let f={};if(d.length>0){const m=await this._generateUncached(d.map(p=>s[p]),o,i,h!==void 0?d.map(p=>h==null?void 0:h[p]):void 0);await Promise.all(m.generations.map(async(p,g)=>{const y=d[g];l[y]=p;const b=pt._convertInputToPromptValue(s[y]).toString();return u.update(b,c,p)})),f=m.llmOutput??{}}return{generations:l,llmOutput:f}}invocationParams(e){return{}}_modelType(){return"base_chat_model"}serialize(){return{...this.invocationParams(),_type:this._llmType(),_model:this._modelType()}}async generatePrompt(e,t,r){const a=e.map(s=>s.toChatMessages());return this.generate(a,t,r)}async call(e,t,r){return(await this.generate([e.map(_r)],t,r)).generations[0][0].message}async callPrompt(e,t,r){const a=e.toChatMessages();return this.call(a,t,r)}async predictMessages(e,t,r){return this.call(e,t,r)}async predict(e,t,r){const a=new sa(e),s=await this.call([a],t,r);if(typeof s.content!="string")throw new Error("Cannot use predict when output is not a string.");return s.content}withStructuredOutput(e,t){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(t!=null&&t.strict)throw new Error('"strict" mode is not supported for this model by default.');const r=e,a=t==null?void 0:t.name,s=so(r)??"A function available to call.",i=t==null?void 0:t.method,o=t==null?void 0:t.includeRaw;if(i==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let u=a??"extract",c;Pt(r)?c=[{type:"function",function:{name:u,description:s,parameters:yt(r)}}]:("name"in r&&(u=r.name),c=[{type:"function",function:{name:u,description:s,parameters:r}}]);const l=this.bindTools(c),d=nr.from(p=>{if(!p.tool_calls||p.tool_calls.length===0)throw new Error("No tool calls found in the response.");const g=p.tool_calls.find(y=>y.name===u);if(!g)throw new Error(`No tool call found with name ${u}.`);return g.args});if(!o)return l.pipe(d).withConfig({runName:"StructuredOutput"});const h=zn.assign({parsed:(p,g)=>d.invoke(p.raw,g)}),f=zn.assign({parsed:()=>null}),m=h.withFallbacks({fallbacks:[f]});return ot.from([{raw:l},m]).withConfig({runName:"StructuredOutputRunnable"})}}class yb extends he{parseResultWithPrompt(e,t,r){return this.parseResult(e,r)}_baseMessageToString(e){return typeof e.content=="string"?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return typeof e=="string"?this._callWithConfig(async(r,a)=>this.parseResult([{text:r}],a==null?void 0:a.callbacks),e,{...t,runType:"parser"}):this._callWithConfig(async(r,a)=>this.parseResult([{message:r,text:this._baseMessageToString(r)}],a==null?void 0:a.callbacks),e,{...t,runType:"parser"})}}class ch extends yb{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,r){return this.parse(e,r)}_type(){throw new Error("_type not implemented")}}class uo extends Error{constructor(e,t,r,a=!1){if(super(e),Object.defineProperty(this,"llmOutput",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"observation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sendToLLM",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.llmOutput=t,this.observation=r,this.sendToLLM=a,a&&(r===void 0||t===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");_d(this,"OUTPUT_PARSING_FAILURE")}}class _b extends ch{async*_transform(e){for await(const t of e)typeof t=="string"?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:"parser"})}}class lh extends _b{constructor(e){super(e),Object.defineProperty(this,"diff",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.diff=(e==null?void 0:e.diff)??this.diff}async*_transform(e){let t,r;for await(const a of e){if(typeof a!="string"&&typeof a.content!="string")throw new Error("Cannot handle non-string output.");let s;if(im(a)){if(typeof a.content!="string")throw new Error("Cannot handle non-string message output.");s=new Ct({message:a,text:a.content})}else if(ra(a)){if(typeof a.content!="string")throw new Error("Cannot handle non-string message output.");s=new Ct({message:fm(a),text:a.content})}else s=new Vt({text:a});r===void 0?r=s:r=r.concat(s);const i=await this.parsePartialResult([r]);i!=null&&!_i(i,t)&&(this.diff?yield this._diff(t,i):yield i,t=i)}}getFormatInstructions(){return""}}class Fc extends ch{static lc_name(){return"StructuredOutputParser"}toJSON(){return this.toJSONNotImplemented()}constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","structured"]})}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const t=wr(Object.fromEntries(Object.entries(e).map(([r,a])=>[r,Ti().describe(a)])));return new this(t)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
115
+
116
+ "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
117
+
118
+ For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
119
+ would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
120
+ Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
121
+
122
+ Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
123
+
124
+ Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
125
+ \`\`\`json
126
+ ${JSON.stringify(yt(this.schema))}
127
+ \`\`\`
128
+ `}async parse(e){var t,r;try{const a=e.trim(),i=(((t=a.match(/^```(?:json)?\s*([\s\S]*?)```/))==null?void 0:t[1])||((r=a.match(/```json\s*([\s\S]*?)```/))==null?void 0:r[1])||a).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(o,u)=>`"${u.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await rh(this.schema,JSON.parse(i))}catch(a){throw new uo(`Failed to parse. Text: "${e}". Error: ${a}`,e)}}}class Dc extends lh{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"JsonOutputParser"}_concatOutputChunks(e,t){return this.diff?super._concatOutputChunks(e,t):t}_diff(e,t){if(t)return e?Nm(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return Ho(e[0].text)}async parse(e){return Ho(e,JSON.parse)}getFormatInstructions(){return""}}function co(n,e){if(n.function===void 0)return;let t;if(e!=null&&e.partial)try{t=Wi(n.function.arguments??"{}")}catch{return}else try{t=JSON.parse(n.function.arguments)}catch(a){throw new uo([`Function "${n.function.name}" arguments:`,"",n.function.arguments,"","are not valid JSON.",`Error: ${a.message}`].join(`
129
+ `))}const r={name:n.function.name,args:t,type:"tool_call"};return e!=null&&e.returnId&&(r.id=n.id),r}function bb(n){if(n.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.args)}}}function Si(n,e){var t,r;return{name:(t=n.function)==null?void 0:t.name,args:(r=n.function)==null?void 0:r.arguments,id:n.id,error:e,type:"invalid_tool_call"}}class wb extends lh{static lc_name(){return"JsonOutputToolsParser"}constructor(e){super(e),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.returnId=(e==null?void 0:e.returnId)??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,t=!0){var i;const r=e[0].message;let a;if(Br(r)&&((i=r.tool_calls)!=null&&i.length)?a=r.tool_calls.map(o=>{const{id:u,...c}=o;return this.returnId?{id:u,...c}:c}):r.additional_kwargs.tool_calls!==void 0&&(a=JSON.parse(JSON.stringify(r.additional_kwargs.tool_calls)).map(u=>co(u,{returnId:this.returnId,partial:t}))),!a)return[];const s=[];for(const o of a)if(o!==void 0){const u={type:o.name,args:o.args,id:o.id};s.push(u)}return s}}class Bc extends wb{static lc_name(){return"JsonOutputKeyToolsParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){var r;if(this.zodSchema===void 0)return e;const t=await N_(this.zodSchema,e);if(t.success)return t.data;throw new uo(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify((r=t.error)==null?void 0:r.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){const r=(await super.parsePartialResult(e)).filter(s=>s.type===this.keyName);let a=r;if(r.length)return this.returnId||(a=r.map(s=>s.args)),this.returnSingle?a[0]:a}async parseResult(e){const r=(await super.parsePartialResult(e,!1)).filter(i=>i.type===this.keyName);let a=r;return r.length?(this.returnId||(a=r.map(i=>i.args)),this.returnSingle?this._validateResult(a[0]):await Promise.all(a.map(i=>this._validateResult(i)))):void 0}}function vb(n){const{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:t,azureOpenAIApiKey:r,azureOpenAIBasePath:a,baseURL:s,azureADTokenProvider:i,azureOpenAIEndpoint:o}=n;if((r||i)&&a&&e)return`${a}/${e}`;if((r||i)&&o&&e)return`${o}/openai/deployments/${e}`;if(r||i){if(!t)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${t}.openai.azure.com/openai/deployments/${e}`}return s}function Eb(n){return n!==void 0&&Array.isArray(n.lc_namespace)}function Sb(n){return n!==void 0&&he.isRunnable(n)&&"lc_name"in n.constructor&&typeof n.constructor.lc_name=="function"&&n.constructor.lc_name()==="RunnableToolLike"}function Ob(n){return!!n&&typeof n=="object"&&"name"in n&&"schema"in n&&(Pt(n.schema)||n.schema!=null&&typeof n.schema=="object"&&"type"in n.schema&&typeof n.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(n.schema.type))}function dh(n){return Ob(n)||Sb(n)||Eb(n)}function Tb(n,e){return{name:n.name,description:n.description,parameters:yt(n.schema)}}function Ab(n,e){let t;return dh(n)?t={type:"function",function:Tb(n)}:t=n,t}const Pb=Symbol("Let zodToJsonSchema decide on which parser to use"),qc={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"},xb=n=>typeof n=="string"?{...qc,basePath:["#"],definitions:{},name:n}:{...qc,basePath:["#"],definitions:{},...n},Oi=n=>"_def"in n?n._def:n;function Ib(n){if(!n)return!0;for(const e in n)return!1;return!0}const Rb=n=>{const e=xb(n),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([r,a])=>[Oi(a),{def:Oi(a),path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function hh(n,e,t,r){r!=null&&r.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function Q(n,e,t,r,a){n[e]=t,hh(n,e,r,a)}function $b(){return{}}function kb(n,e){var r,a;const t={type:"array"};return((a=(r=n.type)==null?void 0:r._def)==null?void 0:a.typeName)!==P.ZodAny&&(t.items=Z(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&Q(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&Q(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(Q(t,"minItems",n.exactLength.value,n.exactLength.message,e),Q(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function Cb(n,e){const t={type:"integer",format:"int64"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?Q(t,"minimum",r.value,r.message,e):Q(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),Q(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?Q(t,"maximum",r.value,r.message,e):Q(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),Q(t,"maximum",r.value,r.message,e));break;case"multipleOf":Q(t,"multipleOf",r.value,r.message,e);break}return t}function Nb(){return{type:"boolean"}}function jb(n,e){return Z(n.type._def,e)}const Lb=(n,e)=>Z(n.innerType._def,e);function fh(n,e,t){const r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((a,s)=>fh(n,e,a))};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 Mb(n,e)}}const Mb=(n,e)=>{const t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(const r of n.checks)switch(r.kind){case"min":Q(t,"minimum",r.value,r.message,e);break;case"max":Q(t,"maximum",r.value,r.message,e);break}return t};function Ub(n,e){return{...Z(n.innerType._def,e),default:n.defaultValue()}}function Fb(n,e,t){return e.effectStrategy==="input"?Z(n.schema._def,e,t):{}}function Db(n){return{type:"string",enum:[...n.values]}}const Bb=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function qb(n,e){const t=[Z(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Z(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s);let r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const a=[];return t.forEach(s=>{if(Bb(s))a.push(...s.allOf),s.unevaluatedProperties===void 0&&(r=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:o,...u}=s;i=u}else r=void 0;a.push(i)}}),a.length?{allOf:a,...r}:void 0}function zb(n,e){const t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}let Zs;const Et={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:()=>(Zs===void 0&&(Zs=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Zs),base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function mh(n,e){const t={type:"string"};function r(a){return e.patternStrategy==="escape"?Hb(a):a}if(n.checks)for(const a of n.checks)switch(a.kind){case"min":Q(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,a.value):a.value,a.message,e);break;case"max":Q(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,a.value):a.value,a.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Be(t,"email",a.message,e);break;case"format:idn-email":Be(t,"idn-email",a.message,e);break;case"pattern:zod":qe(t,Et.email,a.message,e);break}break;case"url":Be(t,"uri",a.message,e);break;case"uuid":Be(t,"uuid",a.message,e);break;case"regex":qe(t,a.regex,a.message,e);break;case"cuid":qe(t,Et.cuid,a.message,e);break;case"cuid2":qe(t,Et.cuid2,a.message,e);break;case"startsWith":qe(t,RegExp(`^${r(a.value)}`),a.message,e);break;case"endsWith":qe(t,RegExp(`${r(a.value)}$`),a.message,e);break;case"datetime":Be(t,"date-time",a.message,e);break;case"date":Be(t,"date",a.message,e);break;case"time":Be(t,"time",a.message,e);break;case"duration":Be(t,"duration",a.message,e);break;case"length":Q(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,a.value):a.value,a.message,e),Q(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,a.value):a.value,a.message,e);break;case"includes":{qe(t,RegExp(r(a.value)),a.message,e);break}case"ip":{a.version!=="v6"&&Be(t,"ipv4",a.message,e),a.version!=="v4"&&Be(t,"ipv6",a.message,e);break}case"emoji":qe(t,Et.emoji,a.message,e);break;case"ulid":{qe(t,Et.ulid,a.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Be(t,"binary",a.message,e);break}case"contentEncoding:base64":{Q(t,"contentEncoding","base64",a.message,e);break}case"pattern:zod":{qe(t,Et.base64,a.message,e);break}}break}case"nanoid":qe(t,Et.nanoid,a.message,e)}return t}const Hb=n=>Array.from(n).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Be=(n,e,t,r)=>{var a;n.format||(a=n.anyOf)!=null&&a.some(s=>s.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&r.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):Q(n,"format",e,t,r)},qe=(n,e,t,r)=>{var a;n.pattern||(a=n.allOf)!=null&&a.some(s=>s.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&r.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:zc(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):Q(n,"pattern",zc(e,r),t,r)},zc=(n,e)=>{var c;const t=typeof n=="function"?n():n;if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},a=r.i?t.source.toLowerCase():t.source;let s="",i=!1,o=!1,u=!1;for(let l=0;l<a.length;l++){if(i){s+=a[l],i=!1;continue}if(r.i){if(o){if(a[l].match(/[a-z]/)){u?(s+=a[l],s+=`${a[l-2]}-${a[l]}`.toUpperCase(),u=!1):a[l+1]==="-"&&((c=a[l+2])!=null&&c.match(/[a-z]/))?(s+=a[l],u=!0):s+=`${a[l]}${a[l].toUpperCase()}`;continue}}else if(a[l].match(/[a-z]/)){s+=`[${a[l]}${a[l].toUpperCase()}]`;continue}}if(r.m){if(a[l]==="^"){s+=`(^|(?<=[\r
130
+ ]))`;continue}else if(a[l]==="$"){s+=`($|(?=[\r
131
+ ]))`;continue}}if(r.s&&a[l]==="."){s+=o?`${a[l]}\r
132
+ `:`[${a[l]}\r
133
+ ]`;continue}s+=a[l],a[l]==="\\"?i=!0:o&&a[l]==="]"?o=!1:!o&&a[l]==="["&&(o=!0)}try{const l=new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s};function ph(n,e){var r,a,s,i;if(e.target==="openApi3"&&((r=n.keyType)==null?void 0:r._def.typeName)===P.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((o,u)=>({...o,[u]:Z(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",u]})??{}}),{}),additionalProperties:!1};const t={type:"object",additionalProperties:Z(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return t;if(((a=n.keyType)==null?void 0:a._def.typeName)===P.ZodString&&((s=n.keyType._def.checks)!=null&&s.length)){const o=Object.entries(mh(n.keyType._def,e)).reduce((u,[c,l])=>c==="type"?u:{...u,[c]:l},{});return{...t,propertyNames:o}}else if(((i=n.keyType)==null?void 0:i._def.typeName)===P.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};return t}function Gb(n,e){if(e.mapStrategy==="record")return ph(n,e);const t=Z(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=Z(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function Wb(n){const e=n.values,r=Object.keys(n.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),a=Array.from(new Set(r.map(s=>typeof s)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:r}}function Jb(){return{not:{}}}function Zb(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Hn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Kb(n,e){if(e.target==="openApi3")return Hc(n,e);const t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in Hn&&(!r._def.checks||!r._def.checks.length))){const r=t.reduce((a,s)=>{const i=Hn[s._def.typeName];return i&&!a.includes(i)?[...a,i]:a},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=t.reduce((a,s)=>{const i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...a,i];case"bigint":return[...a,"integer"];case"object":if(s._def.value===null)return[...a,"null"];case"symbol":case"undefined":case"function":default:return a}},[]);if(r.length===t.length){const a=r.filter((s,i,o)=>o.indexOf(s)===i);return{type:a.length>1?a:a[0],enum:t.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,a)=>[...r,...a._def.values.filter(s=>!r.includes(s))],[])};return Hc(n,e)}const Hc=(n,e)=>{const t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((r,a)=>Z(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${a}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function Vb(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:Hn[n.innerType._def.typeName],nullable:!0}:{type:[Hn[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=Z(n.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const t=Z(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function Xb(n,e){const t={type:"number"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"int":t.type="integer",hh(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?Q(t,"minimum",r.value,r.message,e):Q(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),Q(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?Q(t,"maximum",r.value,r.message,e):Q(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),Q(t,"maximum",r.value,r.message,e));break;case"multipleOf":Q(t,"multipleOf",r.value,r.message,e);break}return t}function Qb(n,e){return e.removeAdditionalStrategy==="strict"?n.catchall._def.typeName==="ZodNever"?n.unknownKeys!=="strict":Z(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:n.catchall._def.typeName==="ZodNever"?n.unknownKeys==="passthrough":Z(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Yb(n,e){const t={type:"object",...Object.entries(n.shape()).reduce((r,[a,s])=>{var u;if(s===void 0||s._def===void 0)return r;const i=[...e.currentPath,"properties",a],o=Z(s._def,{...e,currentPath:i,propertyPath:i});if(o===void 0)return r;if(e.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof((u=s._def)==null?void 0:u.defaultValue)>"u")throw new 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:{...r.properties,[a]:o},required:s.isOptional()&&!e.openaiStrictMode?r.required:[...r.required,a]}},{properties:{},required:[]}),additionalProperties:Qb(n,e)};return t.required.length||delete t.required,t}const ew=(n,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return Z(n.innerType._def,{...e,currentPath:e.currentPath});const t=Z(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}},tw=(n,e)=>{if(e.pipeStrategy==="input")return Z(n.in._def,e);if(e.pipeStrategy==="output")return Z(n.out._def,e);const t=Z(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=Z(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(a=>a!==void 0)}};function rw(n,e){return Z(n.type._def,e)}function nw(n,e){const r={type:"array",uniqueItems:!0,items:Z(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&Q(r,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&Q(r,"maxItems",n.maxSize.value,n.maxSize.message,e),r}function aw(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,r)=>Z(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:Z(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,r)=>Z(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function sw(){return{not:{}}}function iw(){return{}}const ow=(n,e)=>Z(n.innerType._def,e);function Z(n,e,t=!1){var i;const r=e.seen.get(n);if(e.override){const o=(i=e.override)==null?void 0:i.call(e,n,e,r,t);if(o!==Pb)return o}if(r&&!t){const o=uw(r,e);if(o!==void 0)return"$ref"in o&&e.seenRefs.add(o.$ref),o}const a={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,a);const s=lw(n,n.typeName,e,t);return s&&dw(n,e,s),a.jsonSchema=s,s}const uw=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"extract-to-root":const t=n.path.slice(e.basePath.length+1).join("_");return t!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[t]=n.def),{$ref:[...e.basePath,e.definitionPath,t].join("/")};case"relative":return{$ref:cw(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.path.every((r,a)=>e.currentPath[a]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},cw=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")},lw=(n,e,t,r)=>{switch(e){case P.ZodString:return mh(n,t);case P.ZodNumber:return Xb(n,t);case P.ZodObject:return Yb(n,t);case P.ZodBigInt:return Cb(n,t);case P.ZodBoolean:return Nb();case P.ZodDate:return fh(n,t);case P.ZodUndefined:return sw();case P.ZodNull:return Zb(t);case P.ZodArray:return kb(n,t);case P.ZodUnion:case P.ZodDiscriminatedUnion:return Kb(n,t);case P.ZodIntersection:return qb(n,t);case P.ZodTuple:return aw(n,t);case P.ZodRecord:return ph(n,t);case P.ZodLiteral:return zb(n,t);case P.ZodEnum:return Db(n);case P.ZodNativeEnum:return Wb(n);case P.ZodNullable:return Vb(n,t);case P.ZodOptional:return ew(n,t);case P.ZodMap:return Gb(n,t);case P.ZodSet:return nw(n,t);case P.ZodLazy:return Z(n.getter()._def,t);case P.ZodPromise:return rw(n,t);case P.ZodNaN:case P.ZodNever:return Jb();case P.ZodEffects:return Fb(n,t,r);case P.ZodAny:return $b();case P.ZodUnknown:return iw();case P.ZodDefault:return Ub(n,t);case P.ZodBranded:return jb(n,t);case P.ZodReadonly:return ow(n,t);case P.ZodCatch:return Lb(n,t);case P.ZodPipeline:return tw(n,t);case P.ZodFunction:case P.ZodVoid:case P.ZodSymbol:return;default:return(a=>{})()}},dw=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t),hw=(n,e)=>{const t=Rb(e),r=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,a=Z(n._def,r===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,r]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(a.title=s);const i=(()=>{if(Ib(t.definitions))return;const u={},c=new Set;for(let l=0;l<500;l++){const d=Object.entries(t.definitions).filter(([h])=>!c.has(h));if(d.length===0)break;for(const[h,f]of d)u[h]=Z(Oi(f),{...t,currentPath:[...t.basePath,t.definitionPath,h]},!0)??{},c.add(h)}return u})(),o=r===void 0?i?{...a,[t.definitionPath]:i}:a:t.nameStrategy==="duplicate-ref"?{...a,...i||t.seenRefs.size?{[t.definitionPath]:{...i,...t.seenRefs.size?{[r]:a}:void 0}}:void 0}:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,r].join("/"),[t.definitionPath]:{...i,[r]:a}};return t.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="jsonSchema2019-09"&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o};function fw(n,e){return hw(n,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function mw(n,e,t){return Ef({type:"json_schema",json_schema:{...t,name:e,strict:!0,schema:fw(n,{name:e})}},r=>n.parse(JSON.parse(r)))}function hn(n,e){return n.lc_error_code=e,n.message=`${n.message}
134
+
135
+ Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
136
+ `,n}function gh(n){let e;return n.constructor.name===Zn.name?(e=new Error(n.message),e.name="TimeoutError"):n.constructor.name===Ne.name?(e=new Error(n.message),e.name="AbortError"):n.status===400&&n.message.includes("tool_calls")?e=hn(n,"INVALID_TOOL_RESULTS"):n.status===401?e=hn(n,"MODEL_AUTHENTICATION"):n.status===429?e=hn(n,"MODEL_RATE_LIMIT"):n.status===404?e=hn(n,"MODEL_NOT_FOUND"):e=n,e}function yh(n){if(n)return n==="any"||n==="required"?"required":n==="auto"?"auto":n==="none"?"none":typeof n=="string"?{type:"function",function:{name:n}}:n}function pw(n,e){const t={...n};return Object.defineProperties(t,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),t}function gw(n,e,t){if(nt(n))return mw(n,e,t);if(Ze(n))return pw({type:"json_schema",json_schema:{...t,name:e,strict:!0,schema:yi(n,{cycles:"ref",reused:"ref",override(r){r.jsonSchema.title=e}})}},r=>Zd(n,JSON.parse(r)));throw new Error("Unsupported schema response format")}function yw(n){return n.anyOf!==void 0&&Array.isArray(n.anyOf)}function _w(n){const e=["namespace functions {",""];for(const t of n)t.description&&e.push(`// ${t.description}`),Object.keys(t.parameters.properties??{}).length>0?(e.push(`type ${t.name} = (_: {`),e.push(_h(t.parameters,0)),e.push("}) => any;")):e.push(`type ${t.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
137
+ `)}function _h(n,e){var r;const t=[];for(const[a,s]of Object.entries(n.properties??{}))s.description&&e<2&&t.push(`// ${s.description}`),(r=n.required)!=null&&r.includes(a)?t.push(`${a}: ${Gn(s,e)},`):t.push(`${a}?: ${Gn(s,e)},`);return t.map(a=>" ".repeat(e)+a).join(`
138
+ `)}function Gn(n,e){if(yw(n))return n.anyOf.map(t=>Gn(t,e)).join(" | ");switch(n.type){case"string":return n.enum?n.enum.map(t=>`"${t}"`).join(" | "):"string";case"number":return n.enum?n.enum.map(t=>`${t}`).join(" | "):"number";case"integer":return n.enum?n.enum.map(t=>`${t}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",_h(n,e+2),"}"].join(`
139
+ `);case"array":return n.items?`${Gn(n.items,e)}[]`:"any[]";default:return""}}function bw(n,e){let t;return dh(n)?t=Ab(n):t=n,t.type==="function"&&(e==null?void 0:e.strict)!==void 0&&(t.function.strict=e.strict),t}function lo(n){return"type"in n&&n.type!=="function"&&n.type!=="custom"}function ww(n){return n!=null&&typeof n=="object"&&"type"in n&&n.type!=="function"}function vw(n){return typeof n=="object"&&n!==null&&"metadata"in n&&typeof n.metadata=="object"&&n.metadata!==null&&"customTool"in n.metadata&&typeof n.metadata.customTool=="object"&&n.metadata.customTool!==null}function bh(n){return"type"in n&&n.type==="custom"&&"custom"in n&&typeof n.custom=="object"&&n.custom!==null}function Ew(n){if(n.type==="custom_tool_call")return{...n,type:"tool_call",call_id:n.id,id:n.call_id,name:n.name,isCustomTool:!0,args:{input:n.input}}}function Sw(n){return n.type==="tool_call"&&"isCustomTool"in n&&n.isCustomTool===!0}function Ow(n){const e=()=>{if(n.custom.format){if(n.custom.format.type==="grammar")return{type:"grammar",definition:n.custom.format.grammar.definition,syntax:n.custom.format.grammar.syntax};if(n.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:n.custom.name,description:n.custom.description,format:e()}}function Tw(n){const e=()=>{if(n.format){if(n.format.type==="grammar")return{type:"grammar",grammar:{definition:n.format.definition,syntax:n.format.syntax}};if(n.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:n.name,description:n.description,format:e()}}}function Aw(n,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){const t=e.images.filter(r=>{var a;return typeof((a=r==null?void 0:r.image_url)==null?void 0:a.url)=="string"}).map(r=>({type:"image",url:r.image_url.url,source_type:"url"}));return[{type:"text",text:n,source_type:"text"},...t]}return n}const Dt="__openai_function_call_ids__";function ba(n){return n?!!(/^o\d/.test(n??"")||n.startsWith("gpt-5")&&!n.startsWith("gpt-5-chat")):!1}function Pw(n){return n!==void 0&&typeof n.schema=="object"}function xw(n){return n.role!=="system"&&n.role!=="developer"&&n.role!=="assistant"&&n.role!=="user"&&n.role!=="function"&&n.role!=="tool"&&console.warn(`Unknown message role: ${n.role}`),n.role}function ho(n){const e=n._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":{if(!qr.isInstance(n))throw new Error("Invalid generic chat message");return xw(n)}default:throw new Error(`Unknown message type: ${e}`)}}const wh={providerName:"ChatOpenAI",fromStandardTextBlock(n){return{type:"text",text:n.text}},fromStandardImageBlock(n){var e,t;if(n.source_type==="url")return{type:"image_url",image_url:{url:n.url,...(e=n.metadata)!=null&&e.detail?{detail:n.metadata.detail}:{}}};if(n.source_type==="base64")return{type:"image_url",image_url:{url:`data:${n.mime_type??""};base64,${n.data}`,...(t=n.metadata)!=null&&t.detail?{detail:n.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${n.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(n){if(n.source_type==="url"){const e=Ko({dataUrl:n.url});if(!e)throw new Error(`URL audio blocks with source_type ${n.source_type} must be formatted as a data URL for ChatOpenAI`);const t=e.mime_type||n.mime_type||"";let r;try{r=Zo(t)}catch{throw new Error(`Audio blocks with source_type ${n.source_type} must have mime type of audio/wav or audio/mp3`)}if(r.type!=="audio"||r.subtype!=="wav"&&r.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${n.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:r.subtype,data:e.data}}}if(n.source_type==="base64"){let e;try{e=Zo(n.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${n.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${n.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:n.data}}}throw new Error(`Audio content blocks with source_type ${n.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(n){var e,t,r,a,s,i,o,u,c,l;if(n.source_type==="url"){if(!Ko({dataUrl:n.url}))throw new Error(`URL file blocks with source_type ${n.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:n.url,...(e=n.metadata)!=null&&e.filename||(t=n.metadata)!=null&&t.name?{filename:((r=n.metadata)==null?void 0:r.filename)||((a=n.metadata)==null?void 0:a.name)}:{}}}}if(n.source_type==="base64")return{type:"file",file:{file_data:`data:${n.mime_type??""};base64,${n.data}`,...(s=n.metadata)!=null&&s.filename||(i=n.metadata)!=null&&i.name||(o=n.metadata)!=null&&o.title?{filename:((u=n.metadata)==null?void 0:u.filename)||((c=n.metadata)==null?void 0:c.name)||((l=n.metadata)==null?void 0:l.title)}:{}}};if(n.source_type==="id")return{type:"file",file:{file_id:n.id}};throw new Error(`File content blocks with source_type ${n.source_type} are not supported for ChatOpenAI`)}};function Gc(n,e){return n.flatMap(t=>{var i;let r=ho(t);r==="system"&&ba(e)&&(r="developer");const a=typeof t.content=="string"?t.content:t.content.map(o=>kt(o)?yd(o,wh):o),s={role:r,content:a};if(t.name!=null&&(s.name=t.name),t.additional_kwargs.function_call!=null&&(s.function_call=t.additional_kwargs.function_call,s.content=""),Br(t)&&((i=t.tool_calls)!=null&&i.length)?(s.tool_calls=t.tool_calls.map(bb),s.content=""):(t.additional_kwargs.tool_calls!=null&&(s.tool_calls=t.additional_kwargs.tool_calls),t.tool_call_id!=null&&(s.tool_call_id=t.tool_call_id)),t.additional_kwargs.audio&&typeof t.additional_kwargs.audio=="object"&&"id"in t.additional_kwargs.audio){const o={role:"assistant",audio:{id:t.additional_kwargs.audio.id}};return[s,o]}return s})}class fo extends pt{_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","reasoningEffort","service_tier"]}get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model",reasoningEffort:"reasoning_effort"}}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","reasoningEffort","promptCacheKey","verbosity"]}getLsParams(e){const 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){var t,r;super(e??{}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"frequencyPenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"presencePenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logitBias",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"gpt-3.5-turbo"}),Object.defineProperty(this,"modelKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topLogprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"organization",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"__includeRawResponse",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"clientConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"supportsStrictToolCalling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"audio",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modalities",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reasoning",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"zdrEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"service_tier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"promptCacheKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"verbosity",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"defaultOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.apiKey=(e==null?void 0:e.apiKey)??((t=e==null?void 0:e.configuration)==null?void 0:t.apiKey)??_t("OPENAI_API_KEY"),this.organization=((r=e==null?void 0:e.configuration)==null?void 0:r.organization)??_t("OPENAI_ORGANIZATION"),this.model=(e==null?void 0:e.model)??(e==null?void 0:e.modelName)??this.model,this.modelKwargs=(e==null?void 0:e.modelKwargs)??{},this.timeout=e==null?void 0:e.timeout,this.temperature=(e==null?void 0:e.temperature)??this.temperature,this.topP=(e==null?void 0:e.topP)??this.topP,this.frequencyPenalty=(e==null?void 0:e.frequencyPenalty)??this.frequencyPenalty,this.presencePenalty=(e==null?void 0:e.presencePenalty)??this.presencePenalty,this.logprobs=e==null?void 0:e.logprobs,this.topLogprobs=e==null?void 0:e.topLogprobs,this.n=(e==null?void 0:e.n)??this.n,this.logitBias=e==null?void 0:e.logitBias,this.stop=(e==null?void 0:e.stopSequences)??(e==null?void 0:e.stop),this.stopSequences=this.stop,this.user=e==null?void 0:e.user,this.__includeRawResponse=e==null?void 0:e.__includeRawResponse,this.audio=e==null?void 0:e.audio,this.modalities=e==null?void 0:e.modalities,this.reasoning=(e==null?void 0:e.reasoning)??(e==null?void 0:e.reasoningEffort)?{effort:e.reasoningEffort}:void 0,this.maxTokens=(e==null?void 0:e.maxCompletionTokens)??(e==null?void 0:e.maxTokens),this.disableStreaming=(e==null?void 0:e.disableStreaming)===!0,this.streaming=(e==null?void 0:e.streaming)===!0,this.promptCacheKey=(e==null?void 0:e.promptCacheKey)??this.promptCacheKey,this.verbosity=(e==null?void 0:e.verbosity)??this.verbosity,(e==null?void 0:e.streaming)===!1&&(this.disableStreaming=!0),this.disableStreaming===!0&&(this.streaming=!1),this.streamUsage=(e==null?void 0:e.streamUsage)??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e==null?void 0:e.configuration},(e==null?void 0:e.supportsStrictToolCalling)!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),(e==null?void 0:e.service_tier)!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=(e==null?void 0:e.zdrEnabled)??!1}_getReasoningParams(e){if(!ba(this.model))return;let t;return this.reasoning!==void 0&&(t={...t,...this.reasoning}),(e==null?void 0:e.reasoning)!==void 0&&(t={...t,...e.reasoning}),t}_getResponseFormat(e){return e&&e.type==="json_schema"&&e.json_schema.schema&&Pt(e.json_schema.schema)?gw(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){const r={baseURL:this.clientConfig.baseURL},a=vb(r),s={...this.clientConfig,baseURL:a,timeout:this.timeout,maxRetries:0};s.baseURL||delete s.baseURL,this.client=new W(s)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return vw(e)?Tw(e.metadata.customTool):uh(e)?(t==null?void 0:t.strict)!==void 0?{...e,function:{...e.function,strict:t.strict}}:e:bw(e,t)}bindTools(e,t){let r;return(t==null?void 0:t.strict)!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:e.map(a=>lo(a)?a:this._convertChatOpenAIToolToCompletionsTool(a,{strict:r})),...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((t,r)=>(r&&r.tokenUsage&&(t.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,t.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,t.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),t),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=0,r=0,a=0;this.model==="gpt-3.5-turbo-0301"?(r=4,a=-1):(r=3,a=1);const s=await Promise.all(e.map(async i=>{var h,f,m,p,g,y;const o=await this.getNumTokens(i.content),u=await this.getNumTokens(ho(i)),c=i.name!==void 0?a+await this.getNumTokens(i.name):0;let l=o+r+u+c;const d=i;if(d._getType()==="function"&&(l-=2),(h=d.additional_kwargs)!=null&&h.function_call&&(l+=3),(f=d==null?void 0:d.additional_kwargs.function_call)!=null&&f.name&&(l+=await this.getNumTokens((m=d.additional_kwargs.function_call)==null?void 0:m.name)),(p=d.additional_kwargs.function_call)!=null&&p.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse((g=d.additional_kwargs.function_call)==null?void 0:g.arguments)))}catch(b){console.error("Error parsing function arguments",b,JSON.stringify(d.additional_kwargs.function_call)),l+=await this.getNumTokens((y=d.additional_kwargs.function_call)==null?void 0:y.arguments)}return t+=l,l}));return t+=3,{totalCount:t,countPerMessage:s}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async r=>{var a;return(a=r.message.additional_kwargs)!=null&&a.function_call?(await this.getNumTokensFromMessages([r.message])).countPerMessage[0]:await this.getNumTokens(r.message.content)}))).reduce((r,a)=>r+a,0)}async _getEstimatedTokenCountFromPrompt(e,t,r){let a=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&r!=="auto"){const s=_w(t);a+=await this.getNumTokens(s),a+=9}return t&&e.find(s=>s._getType()==="system")&&(a-=4),r==="none"?a+=1:typeof r=="object"&&(a+=await this.getNumTokens(r.name)+4),a}_getStructuredOutputMethod(e){const t={...e};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if((t==null?void 0: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 r,a,s,i;Pw(e)?(r=e.schema,a=e.name,s=e.method,i=e.includeRaw):(r=e,a=t==null?void 0:t.name,s=t==null?void 0:t.method,i=t==null?void 0:t.includeRaw);let o,u;if((t==null?void 0:t.strict)!==void 0&&s==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");if(s=this._getStructuredOutputMethod({...t,method:s}),s==="jsonMode"){Pt(r)?u=Fc.fromZodSchema(r):u=new Dc;const h=yt(r);o=this.withConfig({response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:a??"extract",...h}}})}else if(s==="jsonSchema"){const h={name:a??"extract",description:so(r),schema:r,strict:t==null?void 0:t.strict},f=yt(h.schema);if(o=this.withConfig({response_format:{type:"json_schema",json_schema:h},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:h.name,description:h.description,...f}}}),Pt(r)){const m=Fc.fromZodSchema(r);u=nr.from(p=>"parsed"in p.additional_kwargs?p.additional_kwargs.parsed:m)}else u=new Dc}else{let h=a??"extract";if(Pt(r)){const f=yt(r);o=this.withConfig({tools:[{type:"function",function:{name:h,description:f.description,parameters:f}}],tool_choice:{type:"function",function:{name:h}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:h,...f}},...(t==null?void 0:t.strict)!==void 0?{strict:t.strict}:{}}),u=new Bc({returnSingle:!0,keyName:h,zodSchema:r})}else{let f;typeof r.name=="string"&&typeof r.parameters=="object"&&r.parameters!=null?(f=r,h=r.name):(h=r.title??h,f={name:h,description:r.description??"",parameters:r});const m=yt(r);o=this.withConfig({tools:[{type:"function",function:f}],tool_choice:{type:"function",function:{name:h}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:h,...m}},...(t==null?void 0:t.strict)!==void 0?{strict:t.strict}:{}}),u=new Bc({returnSingle:!0,keyName:h})}}if(!i)return o.pipe(u);const c=zn.assign({parsed:(h,f)=>u.invoke(h.raw,f)}),l=zn.assign({parsed:()=>null}),d=c.withFallbacks({fallbacks:[l]});return ot.from([{raw:o},d])}}class Iw extends fo{invocationParams(e){var s;let t;(e==null?void 0:e.strict)!==void 0?t=e.strict:this.supportsStrictToolCalling!==void 0&&(t=this.supportsStrictToolCalling);const r={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,stream:this.streaming,previous_response_id:e==null?void 0:e.previous_response_id,truncation:e==null?void 0:e.truncation,include:e==null?void 0:e.include,tools:(s=e==null?void 0:e.tools)!=null&&s.length?this._reduceChatOpenAITools(e.tools,{stream:this.streaming,strict:t}):void 0,tool_choice:ww(e==null?void 0:e.tool_choice)?e==null?void 0:e.tool_choice:(()=>{const i=yh(e==null?void 0:e.tool_choice);if(typeof i=="object"&&"type"in i){if(i.type==="function")return{type:"function",name:i.function.name};if(i.type==="allowed_tools")return{type:"allowed_tools",mode:i.allowed_tools.mode,tools:i.allowed_tools.tools};if(i.type==="custom")return{type:"custom",name:i.custom.name}}})(),text:(()=>{if(e!=null&&e.text)return e.text;const i=this._getResponseFormat(e==null?void 0:e.response_format);return(i==null?void 0:i.type)==="json_schema"?i.json_schema.schema!=null?{format:{type:"json_schema",schema:i.json_schema.schema,description:i.json_schema.description,name:i.json_schema.name,strict:i.json_schema.strict},verbosity:e==null?void 0:e.verbosity}:void 0:{format:i,verbosity:e==null?void 0:e.verbosity}})(),parallel_tool_calls:e==null?void 0:e.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:(e==null?void 0:e.promptCacheKey)??this.promptCacheKey,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},a=this._getReasoningParams(e);return a!==void 0&&(r.reasoning=a),r}async _generate(e,t){var a;const r=this.invocationParams(t);if(r.stream){const s=this._streamResponseChunks(e,t);let i;for await(const o of s)o.message.response_metadata={...o.generationInfo,...o.message.response_metadata},i=(i==null?void 0:i.concat(o))??o;return{generations:i?[i]:[],llmOutput:{estimatedTokenUsage:(a=i==null?void 0:i.message)==null?void 0:a.usage_metadata}}}else{const s=this._convertMessagesToResponsesParams(e),i=await this.completionWithRetry({input:s,...r,stream:!1},{signal:t==null?void 0:t.signal,...t==null?void 0:t.options});return{generations:[{text:i.output_text,message:this._convertResponsesMessageToBaseMessage(i)}],llmOutput:{id:i.id,estimatedTokenUsage:i.usage?{promptTokens:i.usage.input_tokens,completionTokens:i.usage.output_tokens,totalTokens:i.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(e,t,r){const a=await this.completionWithRetry({...this.invocationParams(t),input:this._convertMessagesToResponsesParams(e),stream:!0},t);for await(const s of a){const i=this._convertResponsesDeltaToBaseMessageChunk(s);i!=null&&(yield i,await(r==null?void 0:r.handleLLMNewToken(i.text||"",{prompt:t.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:i})))}}async completionWithRetry(e,t){return this.caller.call(async()=>{var a,s;const r=this._getClientOptions(t);try{return((s=(a=e.text)==null?void 0:a.format)==null?void 0:s.type)==="json_schema"&&!e.stream?await this.client.responses.parse(e,r):await this.client.responses.create(e,r)}catch(i){throw gh(i)}})}_convertResponsesMessageToBaseMessage(e){if(e.error){const u=new Error(e.error.message);throw u.name=e.error.code,u}let t;const r=[],a=[],s=[],i={model:e.model,created_at:e.created_at,id:e.id,incomplete_details:e.incomplete_details,metadata:e.metadata,object:e.object,status:e.status,user:e.user,service_tier:e.service_tier,model_name:e.model},o={};for(const u of e.output)if(u.type==="message")t=u.id,r.push(...u.content.flatMap(c=>c.type==="output_text"?("parsed"in c&&c.parsed!=null&&(o.parsed=c.parsed),{type:"text",text:c.text,annotations:c.annotations}):c.type==="refusal"?(o.refusal=c.refusal,[]):c));else if(u.type==="function_call"){const c={function:{name:u.name,arguments:u.arguments},id:u.call_id};try{a.push(co(c,{returnId:!0}))}catch(l){let d;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(d=l.message),s.push(Si(c,d))}o[Dt]??(o[Dt]={}),u.id&&(o[Dt][u.call_id]=u.id)}else if(u.type==="reasoning")o.reasoning=u;else if(u.type==="custom_tool_call"){const c=Ew(u);c?a.push(c):s.push(Si(u,"Malformed custom tool call"))}else o.tool_outputs??(o.tool_outputs=[]),o.tool_outputs.push(u);return new $r({id:t,content:r,tool_calls:a,invalid_tool_calls:s,usage_metadata:e.usage,additional_kwargs:o,response_metadata:i})}_convertResponsesDeltaToBaseMessageChunk(e){var c,l;const t=[];let r={},a;const s=[],i={},o={};let u;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:[e.annotation],index:e.content_index});else if(e.type==="response.output_item.added"&&e.item.type==="message")u=e.item.id;else if(e.type==="response.output_item.added"&&e.item.type==="function_call")s.push({type:"tool_call_chunk",name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),o[Dt]={[e.item.call_id]:e.item.id};else if(e.type==="response.output_item.done"&&["web_search_call","file_search_call","computer_call","code_interpreter_call","mcp_call","mcp_list_tools","mcp_approval_request","image_generation_call","custom_tool_call"].includes(e.item.type))o.tool_outputs=[e.item];else if(e.type==="response.created")i.id=e.response.id,i.model_name=e.response.model,i.model=e.response.model;else if(e.type==="response.completed"){const d=this._convertResponsesMessageToBaseMessage(e.response);a=e.response.usage,((l=(c=e.response.text)==null?void 0:c.format)==null?void 0:l.type)==="json_schema"&&(o.parsed??(o.parsed=JSON.parse(d.text)));for(const[h,f]of Object.entries(e.response))h!=="id"&&(i[h]=f)}else if(e.type==="response.function_call_arguments.delta"||e.type==="response.custom_tool_call_input.delta")s.push({type:"tool_call_chunk",args:e.delta,index:e.output_index});else if(e.type==="response.web_search_call.completed"||e.type==="response.file_search_call.completed")r={tool_outputs:{id:e.item_id,type:e.type.replace("response.","").replace(".completed",""),status:"completed"}};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"){const d=e.item.summary?e.item.summary.map((h,f)=>({...h,index:f})):void 0;o.reasoning={id:e.item.id,type:e.item.type,...d?{summary:d}:{}}}else if(e.type==="response.reasoning_summary_part.added")o.reasoning={type:"reasoning",summary:[{...e.part,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}]};else return e.type==="response.image_generation_call.partial_image",null;return new Ct({text:t.map(d=>d.text).join(""),message:new bt({id:u,content:t,tool_call_chunks:s,usage_metadata:a,additional_kwargs:o,response_metadata:i}),generationInfo:r})}_convertMessagesToResponsesParams(e){return e.flatMap(t=>{var s,i,o,u;const r=t.additional_kwargs;let a=ho(t);if(a==="system"&&ba(this.model)&&(a="developer"),a==="function")throw new Error("Function messages are not supported in Responses API");if(a==="tool"){const c=t;return(r==null?void 0:r.type)==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeof c.content=="string")return{type:"computer_screenshot",image_url:c.content};if(Array.isArray(c.content)){const d=c.content.find(f=>f.type==="computer_screenshot");if(d)return d;const h=c.content.find(f=>f.type==="image_url");if(h)return{type:"computer_screenshot",image_url:typeof h.image_url=="string"?h.image_url:h.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:c.tool_call_id}:(s=c.metadata)!=null&&s.customTool?{type:"custom_tool_call_output",call_id:c.tool_call_id,output:c.content}:{type:"function_call_output",call_id:c.tool_call_id,id:(i=c.id)!=null&&i.startsWith("fc_")?c.id:void 0,output:typeof c.content!="string"?JSON.stringify(c.content):c.content}}if(a==="assistant"){if(!this.zdrEnabled&&t.response_metadata.output!=null&&Array.isArray(t.response_metadata.output)&&t.response_metadata.output.length>0&&t.response_metadata.output.every(m=>"type"in m))return t.response_metadata.output;const c=[];if(r!=null&&r.reasoning&&!this.zdrEnabled){const m=this._convertReasoningSummary(r.reasoning);c.push(m)}let{content:l}=t;r!=null&&r.refusal&&(typeof l=="string"&&(l=[{type:"output_text",text:l,annotations:[]}]),l=[...l,{type:"refusal",refusal:r.refusal}]),(typeof l=="string"||l.length>0)&&c.push({type:"message",role:"assistant",...t.id&&!this.zdrEnabled&&t.id.startsWith("msg_")?{id:t.id}:{},content:typeof l=="string"?l:l.flatMap(m=>m.type==="text"?{type:"output_text",text:m.text,annotations:m.annotations??[]}:m.type==="output_text"||m.type==="refusal"?m:[])});const d=r==null?void 0:r[Dt];Br(t)&&((o=t.tool_calls)!=null&&o.length)?c.push(...t.tool_calls.map(m=>Sw(m)?{type:"custom_tool_call",id:m.call_id,call_id:m.id??"",input:m.args.input,name:m.name}:{type:"function_call",name:m.name,arguments:JSON.stringify(m.args),call_id:m.id,...this.zdrEnabled?{id:d==null?void 0:d[m.id]}:{}})):r!=null&&r.tool_calls&&c.push(...r.tool_calls.map(m=>({type:"function_call",name:m.function.name,call_id:m.id,arguments:m.function.arguments,...this.zdrEnabled?{id:d==null?void 0:d[m.id]}:{}})));const h=(u=t.response_metadata.output)!=null&&u.length?t.response_metadata.output:r.tool_outputs,f=["computer_call","mcp_call","code_interpreter_call","image_generation_call"];if(h!=null){const m=h,p=m==null?void 0:m.filter(g=>f.includes(g.type));p.length>0&&c.push(...p)}return c}if(a==="user"||a==="system"||a==="developer"){if(typeof t.content=="string")return{type:"message",role:a,content:t.content};const c=[],l=t.content.flatMap(d=>(d.type==="mcp_approval_response"&&c.push({type:"mcp_approval_response",approval_request_id:d.approval_request_id,approve:d.approve}),kt(d)?yd(d,wh):d.type==="text"?{type:"input_text",text:d.text}:d.type==="image_url"?{type:"input_image",image_url:typeof d.image_url=="string"?d.image_url:d.image_url.url,detail:typeof d.image_url=="string"?"auto":d.image_url.detail}:d.type==="input_text"||d.type==="input_image"||d.type==="input_file"?d:[]));return l.length>0&&c.push({type:"message",role:a,content:l}),c}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]})}_convertReasoningSummary(e){const t=(e.summary.length>1?e.summary.reduce((r,a)=>{const s=r.at(-1);return s.index===a.index?s.text+=a.text:r.push(a),r},[{...e.summary[0]}]):e.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([a])=>a!=="index")));return{...e,summary:t}}_reduceChatOpenAITools(e,t){const r=[];for(const a of e)lo(a)?(a.type==="image_generation"&&(t!=null&&t.stream)&&(a.partial_images=1),r.push(a)):uh(a)?r.push({type:"function",name:a.function.name,parameters:a.function.parameters,description:a.function.description,strict:(t==null?void 0:t.strict)??null}):bh(a)&&r.push(Ow(a));return r}}class Rw extends fo{invocationParams(e,t){var o;let r;(e==null?void 0:e.strict)!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling);let a={};(e==null?void 0:e.stream_options)!==void 0?a={stream_options:e.stream_options}:this.streamUsage&&(this.streaming||t!=null&&t.streaming)&&(a={stream_options:{include_usage:!0}});const s={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==null?void 0:e.stop)??this.stopSequences,user:this.user,stream:this.streaming,functions:e==null?void 0:e.functions,function_call:e==null?void 0:e.function_call,tools:(o=e==null?void 0:e.tools)!=null&&o.length?e.tools.map(u=>this._convertChatOpenAIToolToCompletionsTool(u,{strict:r})):void 0,tool_choice:yh(e==null?void 0:e.tool_choice),response_format:this._getResponseFormat(e==null?void 0:e.response_format),seed:e==null?void 0:e.seed,...a,parallel_tool_calls:e==null?void 0:e.parallel_tool_calls,...this.audio||e!=null&&e.audio?{audio:this.audio||(e==null?void 0:e.audio)}:{},...this.modalities||e!=null&&e.modalities?{modalities:this.modalities||(e==null?void 0:e.modalities)}:{},...this.modelKwargs,prompt_cache_key:(e==null?void 0:e.promptCacheKey)??this.promptCacheKey,verbosity:(e==null?void 0:e.verbosity)??this.verbosity};(e==null?void 0:e.prediction)!==void 0&&(s.prediction=e.prediction),this.service_tier!==void 0&&(s.service_tier=this.service_tier),(e==null?void 0:e.service_tier)!==void 0&&(s.service_tier=e.service_tier);const i=this._getReasoningParams(e);return i!==void 0&&i.effort!==void 0&&(s.reasoning_effort=i.effort),ba(s.model)?s.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:s.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,s}async _generate(e,t,r){var o,u;const a={},s=this.invocationParams(t),i=Gc(e,this.model);if(s.stream){const c=this._streamResponseChunks(e,t,r),l={};for await(const g of c){g.message.response_metadata={...g.generationInfo,...g.message.response_metadata};const y=((o=g.generationInfo)==null?void 0:o.completion)??0;l[y]===void 0?l[y]=g:l[y]=l[y].concat(g)}const d=Object.entries(l).sort(([g],[y])=>parseInt(g,10)-parseInt(y,10)).map(([g,y])=>y),{functions:h,function_call:f}=this.invocationParams(t),m=await this._getEstimatedTokenCountFromPrompt(e,h,f),p=await this._getNumTokensFromGenerations(d);return a.input_tokens=m,a.output_tokens=p,a.total_tokens=m+p,{generations:d,llmOutput:{estimatedTokenUsage:{promptTokens:a.input_tokens,completionTokens:a.output_tokens,totalTokens:a.total_tokens}}}}else{const c=await this.completionWithRetry({...s,stream:!1,messages:i},{signal:t==null?void 0:t.signal,...t==null?void 0:t.options}),{completion_tokens:l,prompt_tokens:d,total_tokens:h,prompt_tokens_details:f,completion_tokens_details:m}=(c==null?void 0:c.usage)??{};l&&(a.output_tokens=(a.output_tokens??0)+l),d&&(a.input_tokens=(a.input_tokens??0)+d),h&&(a.total_tokens=(a.total_tokens??0)+h),((f==null?void 0:f.audio_tokens)!==null||(f==null?void 0:f.cached_tokens)!==null)&&(a.input_token_details={...(f==null?void 0:f.audio_tokens)!==null&&{audio:f==null?void 0:f.audio_tokens},...(f==null?void 0:f.cached_tokens)!==null&&{cache_read:f==null?void 0:f.cached_tokens}}),((m==null?void 0:m.audio_tokens)!==null||(m==null?void 0:m.reasoning_tokens)!==null)&&(a.output_token_details={...(m==null?void 0:m.audio_tokens)!==null&&{audio:m==null?void 0:m.audio_tokens},...(m==null?void 0:m.reasoning_tokens)!==null&&{reasoning:m==null?void 0:m.reasoning_tokens}});const p=[];for(const g of(c==null?void 0:c.choices)??[]){const b={text:((u=g.message)==null?void 0:u.content)??"",message:this._convertCompletionsMessageToBaseMessage(g.message??{role:"assistant"},c)};b.generationInfo={...g.finish_reason?{finish_reason:g.finish_reason}:{},...g.logprobs?{logprobs:g.logprobs}:{}},Br(b.message)&&(b.message.usage_metadata=a),b.message=new $r(Object.fromEntries(Object.entries(b.message).filter(([_])=>!_.startsWith("lc_")))),p.push(b)}return{generations:p,llmOutput:{tokenUsage:{promptTokens:a.input_tokens,completionTokens:a.output_tokens,totalTokens:a.total_tokens}}}}}async*_streamResponseChunks(e,t,r){var c,l,d,h,f,m,p,g,y,b;const a=Gc(e,this.model),s={...this.invocationParams(t,{streaming:!0}),messages:a,stream:!0};let i;const o=await this.completionWithRetry(s,t);let u;for await(const _ of o){const w=(c=_==null?void 0:_.choices)==null?void 0:c[0];if(_.usage&&(u=_.usage),!w)continue;const{delta:v}=w;if(!v)continue;const S=this._convertCompletionsDeltaToBaseMessageChunk(v,_,i);i=v.role??i;const O={prompt:t.promptIndex??0,completion:w.index??0};if(typeof S.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}const T={...O};w.finish_reason!=null&&(T.finish_reason=w.finish_reason,T.system_fingerprint=_.system_fingerprint,T.model_name=_.model,T.service_tier=_.service_tier),this.logprobs&&(T.logprobs=w.logprobs);const N=new Ct({message:S,text:S.content,generationInfo:T});yield N,await(r==null?void 0:r.handleLLMNewToken(N.text??"",O,void 0,void 0,void 0,{chunk:N}))}if(u){const _={...((l=u.prompt_tokens_details)==null?void 0:l.audio_tokens)!==null&&{audio:(d=u.prompt_tokens_details)==null?void 0:d.audio_tokens},...((h=u.prompt_tokens_details)==null?void 0:h.cached_tokens)!==null&&{cache_read:(f=u.prompt_tokens_details)==null?void 0:f.cached_tokens}},w={...((m=u.completion_tokens_details)==null?void 0:m.audio_tokens)!==null&&{audio:(p=u.completion_tokens_details)==null?void 0:p.audio_tokens},...((g=u.completion_tokens_details)==null?void 0:g.reasoning_tokens)!==null&&{reasoning:(y=u.completion_tokens_details)==null?void 0:y.reasoning_tokens}};yield new Ct({message:new bt({content:"",response_metadata:{usage:{...u}},usage_metadata:{input_tokens:u.prompt_tokens,output_tokens:u.completion_tokens,total_tokens:u.total_tokens,...Object.keys(_).length>0&&{input_token_details:_},...Object.keys(w).length>0&&{output_token_details:w}}}),text:""})}if((b=t.signal)!=null&&b.aborted)throw new Error("AbortError")}async completionWithRetry(e,t){const r=this._getClientOptions(t),a=e.response_format&&e.response_format.type==="json_schema";return this.caller.call(async()=>{try{return a&&!e.stream?await this.client.chat.completions.parse(e,r):await this.client.chat.completions.create(e,r)}catch(s){throw gh(s)}})}_convertCompletionsMessageToBaseMessage(e,t){var a,s;const r=e.tool_calls;switch(e.role){case"assistant":{const i=[],o=[];for(const d of r??[])try{i.push(co(d,{returnId:!0}))}catch(h){o.push(Si(d,h.message))}const u={function_call:e.function_call,tool_calls:r};this.__includeRawResponse!==void 0&&(u.__raw_response=t);const c={model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};e.audio&&(u.audio=e.audio);const l=Aw(e.content||"",(s=(a=t.choices)==null?void 0:a[0])==null?void 0:s.message);return new $r({content:l,tool_calls:i,invalid_tool_calls:o,additional_kwargs:u,response_metadata:c,id:t.id})}default:return new qr(e.content||"",e.role??"unknown")}}_convertCompletionsDeltaToBaseMessageChunk(e,t,r){var u,c;const a=e.role??r,s=e.content??"";let i;e.function_call?i={function_call:e.function_call}:e.tool_calls?i={tool_calls:e.tool_calls}:i={},this.__includeRawResponse&&(i.__raw_response=t),e.audio&&(i.audio={...e.audio,index:t.choices[0].index});const o={usage:{...t.usage}};if(a==="user")return new ia({content:s,response_metadata:o});if(a==="assistant"){const l=[];if(Array.isArray(e.tool_calls))for(const d of e.tool_calls)l.push({name:(u=d.function)==null?void 0:u.name,args:(c=d.function)==null?void 0:c.arguments,id:d.id,index:d.index,type:"tool_call_chunk"});return new bt({content:s,tool_call_chunks:l,additional_kwargs:i,id:t.id,response_metadata:o})}else return a==="system"?new kr({content:s,response_metadata:o}):a==="developer"?new kr({content:s,response_metadata:o,additional_kwargs:{__openai_role__:"developer"}}):a==="function"?new aa({content:s,additional_kwargs:i,name:e.name,response_metadata:o}):a==="tool"?new Ji({content:s,additional_kwargs:i,tool_call_id:e.tool_call_id,response_metadata:o}):new na({content:s,role:a,response_metadata:o})}}class mo extends fo{get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}constructor(e){super(e),Object.defineProperty(this,"fields",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"useResponsesApi",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"responses",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"completions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.useResponsesApi=(e==null?void 0:e.useResponsesApi)??!1,this.responses=(e==null?void 0:e.responses)??new Iw(e),this.completions=(e==null?void 0:e.completions)??new Rw(e)}_useResponsesApi(e){var s,i,o,u;const t=(s=e==null?void 0:e.tools)==null?void 0:s.some(lo),r=(e==null?void 0:e.previous_response_id)!=null||(e==null?void 0:e.text)!=null||(e==null?void 0:e.truncation)!=null||(e==null?void 0:e.include)!=null||((i=e==null?void 0:e.reasoning)==null?void 0:i.summary)!=null||((o=this.reasoning)==null?void 0:o.summary)!=null,a=(u=e==null?void 0:e.tools)==null?void 0:u.some(bh);return this.useResponsesApi||t||r||a}getLsParams(e){const t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(t):this.completions.getLsParams(t)}invocationParams(e){const t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(t):this.completions.invocationParams(t)}async _generate(e,t,r){return this._useResponsesApi(t)?this.responses._generate(e,t):this.completions._generate(e,t,r)}async*_streamResponseChunks(e,t,r){if(this._useResponsesApi(t)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(t),r);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(t),r)}withConfig(e){const t=new mo(this.fields);return t.defaultOptions={...this.defaultOptions,...e},t}}class $w{constructor(){}async handleParseData(e,t){try{console.log("[AiParsingService] Handle parse data request");const r=await this.parseData(e);r.success?t({success:!0,data:r.data}):t({$isError:!0,message:r.error||"AI parsing failed",data:null})}catch(r){console.error("[AiParsingService] Parse data error:",r),t({$isError:!0,message:r instanceof Error?r.message:"Unknown error in AI parsing",data:null})}}async parseData(e){try{const{sourceData:t,schemaDefinition:r,prompt:a,model:s="gpt-4o-mini",apiKey:i}=e;if(!i||i.trim()==="")return{success:!1,error:"OpenAI API key is required. Please provide it in the ai-parse-data block."};const o=r.type==="array",u=this.reconstructZodSchema(r),l=new mo({apiKey:i,modelName:s,temperature:0}).withStructuredOutput(u),d=this.buildPrompt(t,r,a),h=await l.invoke(d);return{success:!0,data:o&&h&&typeof h=="object"&&"items"in h?h.items:h}}catch(t){return console.error("[AI Parsing Service] Parsing failed:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error during AI parsing"}}}reconstructZodSchema(e){if(e.type==="array"&&e.items){const t=this.buildZodType(e.items);return wr({items:go(t)})}if(e.type==="object"&&e.shape){const t={};for(const[r,a]of Object.entries(e.shape))t[r]=this.buildZodType(a);return wr(t)}return Gt()}buildZodType(e){let t;switch(e.type){case"string":e.enum&&Array.isArray(e.enum)&&e.enum.length>0?t=jh(e.enum):t=Ti();break;case"number":if(e.enum&&Array.isArray(e.enum)&&e.enum.length>0){const r=e.enum.map(a=>kh(a));t=Ch(r)}else t=Nh();break;case"boolean":t=$h();break;case"array":t=go(e.items?this.buildZodType(e.items):Gt());break;case"object":if(e.shape){const r={};for(const[a,s]of Object.entries(e.shape))r[a]=this.buildZodType(s);t=wr(r)}else t=Gt();break;default:t=Gt()}return e.optional&&(t=t.optional()),t}buildPrompt(e,t,r){const a=typeof e=="string"?e:JSON.stringify(e,null,2),s=this.describeSchema(t),i=t.type==="array";return`You are a data parsing assistant. Your task is to extract and structure data according to the provided schema.
140
+
141
+ Source Data:
142
+ \`\`\`
143
+ ${a}
144
+ \`\`\`
145
+
146
+ Expected Output Schema:
147
+ ${s}
148
+
149
+ ${r?`
150
+ Additional Instructions:
151
+ ${r}
152
+ `:""}
153
+
154
+ Please parse the source data and return it in the exact format specified by the schema. Extract all relevant information and ensure the data types match the schema.${i?`
155
+
156
+ IMPORTANT: Return the array in an object with "items" field: { items: [...your array here...] }`:""}`}describeSchema(e,t=0){const r=" ".repeat(t);if(e.type==="array"&&e.items)return`Array<${this.describeSchema(e.items,0)}>`;if(e.type==="object"&&e.shape){let a=`${r}{
157
+ `;for(const[s,i]of Object.entries(e.shape)){const o=i.optional?" (optional)":"",u=i.description?` // ${i.description}`:"";a+=`${r} ${s}: ${this.describeSchema(i,t+1)}${o}${u}
158
+ `}return a+=`${r}}`,a}return e.enum&&Array.isArray(e.enum)?e.enum.map(s=>JSON.stringify(s)).join(" | "):e.type||"any"}}class kw{async handleClick(e,t){try{console.log("[CdpService] Handle click request:",e);const{tabId:r,x:a,y:s}=e;await this.click(r,a,s),t({success:!0,data:{clicked:!0}})}catch(r){console.error("[CdpService] Click error:",r),t({$isError:!0,message:r instanceof Error?r.message:"CDP click failed",data:null})}}async handleKeypress(e,t){try{console.log("[CdpService] Handle keypress request:",e);const{tabId:r,key:a,code:s,keyCode:i,modifiers:o}=e;await this.keypress(r,a,s,i,o),t({success:!0,data:{pressed:!0}})}catch(r){console.error("[CdpService] Keypress error:",r),t({$isError:!0,message:r instanceof Error?r.message:"CDP keypress failed",data:null})}}async click(e,t,r){console.log("[CdpService] Click request - tabId:",e,"x:",t,"y:",r),await chrome.debugger.attach({tabId:e},"1.3"),console.log("[CdpService] Debugger attached to tab:",e);try{await chrome.debugger.sendCommand({tabId:e},"Input.dispatchMouseEvent",{type:"mouseMoved",x:t,y:r,button:"none",clickCount:0}),await chrome.debugger.sendCommand({tabId:e},"Input.dispatchMouseEvent",{type:"mousePressed",x:t,y:r,button:"left",clickCount:1}),await chrome.debugger.sendCommand({tabId:e},"Input.dispatchMouseEvent",{type:"mouseReleased",x:t,y:r,button:"left",clickCount:1}),console.log("[CdpService] Click completed successfully")}finally{await chrome.debugger.detach({tabId:e}),console.log("[CdpService] Debugger detached from tab:",e)}}async keypress(e,t,r,a,s=[]){console.log("[CdpService] Keypress request - tabId:",e,"key:",t),await chrome.debugger.attach({tabId:e},"1.3"),console.log("[CdpService] Debugger attached to tab:",e);try{const i=this.convertModifiersToCdp(s);await chrome.debugger.sendCommand({tabId:e},"Input.dispatchKeyEvent",{type:"keyDown",key:t,code:r,windowsVirtualKeyCode:a,nativeVirtualKeyCode:a,modifiers:i}),await chrome.debugger.sendCommand({tabId:e},"Input.dispatchKeyEvent",{type:"keyUp",key:t,code:r,windowsVirtualKeyCode:a,nativeVirtualKeyCode:a,modifiers:i}),console.log("[CdpService] Keypress completed successfully")}finally{await chrome.debugger.detach({tabId:e}),console.log("[CdpService] Debugger detached from tab:",e)}}convertModifiersToCdp(e){let t=0;return e.includes("Alt")&&(t|=1),e.includes("Control")&&(t|=2),e.includes("Meta")&&(t|=4),e.includes("Shift")&&(t|=8),t}}const Cw=()=>({steps:{}}),Nw=(n,e,t)=>({steps:{...n.steps,[e]:t}}),jw=n=>n.startsWith("steps."),Lw=(n,e)=>{if(!e.startsWith("steps."))return;const t=e.slice(6);if(t)return t.split(".").reduce((r,a)=>r==null?void 0:r[a],n.steps)},Mw=()=>({vars:{}}),Uw=(n,e)=>({vars:{...n.vars,...e}}),Fw=n=>n.startsWith("vars."),Dw=(n,e)=>{if(!e.startsWith("vars."))return;const t=e.slice(5);if(t)return t.split(".").reduce((r,a)=>r==null?void 0:r[a],n.vars)},Bw=()=>({}),qw=(n,e,t,r)=>({...n,forEach:{item:e,index:t,total:r}}),zw=(n,e,t)=>({...n,loop:{index:e,count:t}}),Hw=n=>{const{forEach:e,loop:t,...r}=n;return r},Gw=n=>n.startsWith("forEach.")||n.startsWith("loop."),Ww=(n,e)=>{if(!(!e.startsWith("forEach.")&&!e.startsWith("loop.")))return e.split(".").reduce((t,r)=>t==null?void 0:t[r],n)},Jw=()=>({stepContext:Cw(),varContext:Mw(),loopContext:Bw()}),Zw=(n,e,t)=>({...n,stepContext:Nw(n.stepContext,e,t)}),Kw=(n,e)=>({...n,varContext:Uw(n.varContext,e)}),Vw=(n,e,t,r)=>({...n,loopContext:qw(n.loopContext,e,t,r)}),Xw=(n,e,t)=>({...n,loopContext:zw(n.loopContext,e,t)}),Ks=n=>({...n,loopContext:Hw(n.loopContext)}),Ye=(n,e)=>{if(jw(e))return Lw(n.stepContext,e);if(Fw(e))return Dw(n.varContext,e);if(Gw(e))return Ww(n.loopContext,e)},vh=(n,e)=>{const t=/^\$\{([^}]+)\}$/.exec(n);return t?Ye(e,t[1].trim()):n.replace(/\$\{([^}]+)\}/g,(r,a)=>{const s=Ye(e,a.trim());return s==null?"":typeof s=="object"?JSON.stringify(s):String(s)})},Qw=(n,e)=>{const{valueFrom:t,template:r,default:a}=n;try{if(t!=null){const s=Ye(e,t);return s===void 0?a:s}if(r!=null){const s=vh(r,e);return s==null||s===""?a:s}}catch{return a}return a},Wn=(n,e)=>{if(n==null)return n;if(typeof n=="string")return vh(n,e);if(Array.isArray(n))return n.map(t=>Wn(t,e));if(typeof n=="object"){if("valueFrom"in n||"template"in n)return Qw(n,e);const t={};for(const r of Object.keys(n))t[r]=Wn(n[r],e);return t}return n},Ir=(n,e)=>{if("exists"in n)return Ye(e,n.exists)!==void 0;if("equals"in n)return Ye(e,n.equals.left)===n.equals.right;if("notEquals"in n)return Ye(e,n.notEquals.left)!==n.notEquals.right;if("contains"in n){const t=Ye(e,n.contains.value),r=String(n.contains.search);return Array.isArray(t)?t.some(a=>String(a).includes(r)):String(t).includes(r)}if("regex"in n){const t=String(Ye(e,n.regex.value));return new RegExp(n.regex.pattern,n.regex.flags||"").test(t)}return"and"in n?n.and.every(t=>Ir(t,e)):"or"in n?n.or.some(t=>Ir(t,e)):"not"in n?!Ir(n.not,e):!1},Yw=(n,e)=>{try{const t=e.varContext.vars,r=e.stepContext.steps,a=e.loopContext.forEach,s=e.loopContext.loop;return!!new Function("vars","steps","forEach","loop",`return (${n});`)(t,r,a,s)}catch{return!1}},ev=n=>typeof n=="object"&&n!==null&&("exists"in n||"equals"in n||"notEquals"in n||"contains"in n||"regex"in n||"and"in n||"or"in n||"not"in n),Eh=(n,e)=>{if(!n)return!0;if(ev(n))return Ir(n,e);const t=n;return t.json?Ir(t.json,e):t.expr?Yw(t.expr,e):!0},tv=async(n,e)=>!e||e<=0?n():new Promise((t,r)=>{const a=setTimeout(()=>r(new Error("Step timeout")),e);n().then(s=>{clearTimeout(a),t(s)}).catch(s=>{clearTimeout(a),r(s)})}),Sh=async(n,e,t,r,a={})=>{const s=Math.max(1,a.maxAttempts??1),i=a.baseDelay??0,o=a.backoff??1;let u=0,c=null,l=!1,d="";for(;u<s;){u++;try{const h=Wn(n,e);if(c=await tv(()=>t(h,r),a.timeoutMs),l=!(c!=null&&c.hasError),d=(c==null?void 0:c.message)||"",l)break}catch(h){l=!1,d=(h==null?void 0:h.message)||"Workflow step error",c={hasError:!0,message:d}}if(u<s){const h=i*Math.pow(o,u-1);h>0&&await new Promise(f=>setTimeout(f,h))}}return{result:c,success:l,message:d,attempts:u}},rv=(n,e)=>{if(n.forEach){const t=Ye(e,n.forEach);return Array.isArray(t)?{items:t,isForEach:!0}:t!=null?{items:[t],isForEach:!0}:{items:[],isForEach:!0}}if(n.count!=null){let t;return typeof n.count=="string"?t=Ye(e,n.count)??0:t=n.count,{items:Array.from({length:Math.max(0,t)},(a,s)=>s),isForEach:!1}}throw new Error("repeat requires either forEach or count")},nv=async(n,e,t,r,a,s={})=>{const i=[],o=[];let u=t;try{const{items:c,isForEach:l}=rv(e,t);for(let d=0;d<c.length;d++){const h=c[d];l?u=Vw(u,h,d,c.length):u=Xw(u,d,c.length);try{const f=await Sh(n,u,r,a,s);if(f.success)i.push(f.result);else if(o.push({index:d,item:h,error:f.result}),e.continueOnError)i.push(null);else return u=Ks(u),{result:{hasError:!0,message:`Repeat failed at index ${d}: ${f.message}`,data:{results:i,errors:o,stoppedAt:d}},context:u}}catch(f){if(o.push({index:d,item:h,error:f.message}),e.continueOnError)i.push(null);else return u=Ks(u),{result:{hasError:!0,message:`Repeat failed at index ${d}: ${f.message}`,data:{results:i,errors:o,stoppedAt:d}},context:u}}e.delayBetween&&d<c.length-1&&await new Promise(f=>setTimeout(f,e.delayBetween))}return u=Ks(u),{result:{hasError:o.length>0&&!e.continueOnError,message:o.length>0?`Completed with ${o.length} error(s) out of ${c.length}`:`Completed ${c.length} iteration(s)`,data:i},context:u}}catch(c){return{result:{hasError:!0,message:c.message||"repeat requires either forEach or count",data:null},context:u}}},av=async(n,e,t,r)=>{var f,m,p,g,y,b,_,w;const a=new Date().toISOString();let s=!1,i=!0,o="",u=null,c=0,l=e;if(!Eh(n.when,e))s=!0;else if(n.block)if(n.repeat){const v=await nv(n.block,n.repeat,e,t,r,{maxAttempts:(f=n.retry)==null?void 0:f.attempts,baseDelay:(m=n.retry)==null?void 0:m.delayMs,backoff:(p=n.retry)==null?void 0:p.backoffFactor,timeoutMs:n.timeoutMs});u=v.result,i=!((g=v.result)!=null&&g.hasError),o=((y=v.result)==null?void 0:y.message)||"",l=v.context}else{const v=await Sh(n.block,e,t,r,{maxAttempts:(b=n.retry)==null?void 0:b.attempts,baseDelay:(_=n.retry)==null?void 0:_.delayMs,backoff:(w=n.retry)==null?void 0:w.backoffFactor,timeoutMs:n.timeoutMs});u=v.result,i=v.success,o=v.message,c=v.attempts}else s=!0;const h=new Date().toISOString();return l=Zw(l,n.id,{result:u,success:i,skipped:s}),{stepId:n.id,skipped:s,success:i,message:o,result:u,startedAt:a,finishedAt:h,attempts:c,context:l}},sv=(n,e,t)=>{if(n.switch&&n.switch.length>0){const r=n.switch.find(a=>Eh(a.when,t));if(r)return r.next}if(e&&n.onSuccess)return n.onSuccess;if(!e&&n.onFailure)return n.onFailure;if(n.next)return n.next},iv=async n=>{typeof n.delayAfterMs=="number"&&n.delayAfterMs>0&&await new Promise(e=>setTimeout(e,n.delayAfterMs))};class ov{constructor(e,t){this.executeBlock=e,this.createTab=t}async run(e,t,r=!1){let a=Jw();e.vars&&(a=Kw(a,e.vars)),console.log("context",e.vars),console.log("targetUrl",t),console.log(a);const s=typeof t=="string"?Wn(t,a):t;console.log("resolvedTargetUrl",s);const i=await this.createTab(s,r),o=new Map(e.steps.map(l=>[l.id,l]));let u=e.start;const c=[];for(;u;){const l=o.get(u);if(!l)break;const d=await av(l,a,this.executeBlock,i);c.push(d),a=d.context;const h=sv(l,d.success,a);h&&!d.skipped&&await iv(l),u=h}return{steps:c,tabId:i}}}class uv{constructor(e){be(this,"workflowRunner");this.tabManager=e;const t=(a,s)=>this.tabManager.executeBlock(a,s),r=async(a,s)=>{const i=await this.tabManager.createTab(a,s);if(i.id===void 0)throw new Error("Failed to create tab or tab ID is missing");return i.id};this.workflowRunner=new ov(t,r)}async handleCollectWorkflow(e,t){const r=this.validateRequest(e);if(!r.success){t({$isError:!0,message:r.error,data:{}});return}let a;try{console.log("[WorkflowService] Running workflow for:",e.targetUrl);const s=await this.workflowRunner.run(e.workflow,e.targetUrl,e.activateTab===!0);a=s.tabId,t({success:!0,targetUrl:e.targetUrl,tabId:s.tabId,result:{steps:s.steps},timestamp:new Date().toISOString(),closeTabAfterCollection:e.closeTabAfterCollection!==!1})}catch(s){console.error("[WorkflowService] Workflow execution error:",s),t({$isError:!0,message:s instanceof Error?s.message:"Workflow execution failed",data:{}})}finally{a!==void 0&&e.closeTabAfterCollection!==!1&&await this.cleanup(a)}}validateRequest(e){return e.targetUrl?e.workflow?{success:!0}:{success:!1,error:"Workflow is required"}:{success:!1,error:"Target URL is required for workflow"}}async cleanup(e){console.log("[WorkflowService] Cleanup - closing tab:",e),await new Promise(t=>setTimeout(t,1e3)),await this.tabManager.closeTab(e)}}class cv{async handleRequest(e,t){try{console.log("[ApiService] Handle API request:",e.url);const r=await this.fetchData(e);t({success:!0,data:r})}catch(r){console.error("[ApiService] API request error:",r),t({$isError:!0,message:r instanceof Error?r.message:"Unknown error in API request",data:null})}}async fetchData(e){const{url:t,method:r,headers:a,body:s,timeout:i,parseJson:o,returnHeaders:u}=e;console.log(`[ApiService] Fetching ${r} ${t}`);const c=new AbortController,l=setTimeout(()=>c.abort(),i);try{const d={method:r,headers:a,signal:c.signal};s&&!["GET","HEAD"].includes(r)&&(typeof s=="string"?d.body=s:(d.body=JSON.stringify(s),!a["Content-Type"]&&!a["content-type"]&&(d.headers={...a,"Content-Type":"application/json"})));const h=await fetch(t,d);clearTimeout(l);let f;const m=h.headers.get("content-type")||"";if(o&&m.includes("application/json"))try{f=await h.json()}catch{f=await h.text()}else f=await h.text();let p;u&&(p={},h.headers.forEach((y,b)=>{p[b]=y}));const g={status:h.status,statusText:h.statusText,data:f,headers:p};return console.log(`[ApiService] Response status: ${h.status}`),g}catch(d){throw clearTimeout(l),d instanceof Error&&d.name==="AbortError"?new Error(`Request timeout after ${i}ms`):d}}}class lv{constructor(){be(this,"aiParsingService");be(this,"cdpService");be(this,"workflowService");be(this,"apiService");this.aiParsingService=new $w,this.cdpService=new kw,this.workflowService=new uv(new Lh),this.apiService=new cv}initHandler(){chrome.runtime.onMessage.addListener((e,t,r)=>{var a,s;if(e.type==="COLLECT_WORKFLOW_NEW_TAB")return this.handleAsyncCollectWorkflow(e.data,r),!0;if(e.type==="CDP_CLICK"&&xh(e)){const i=(a=t.tab)==null?void 0:a.id;return i?(this.handleAsyncCdpClick({...e.data,tabId:i},r),!0):(r({$isError:!0,message:"Tab ID not found in sender",data:null}),!1)}if(e.type==="CDP_KEYPRESS"&&Ih(e)){const i=(s=t.tab)==null?void 0:s.id;return i?(this.handleAsyncCdpKeypress({...e.data,tabId:i},r),!0):(r({$isError:!0,message:"Tab ID not found in sender",data:null}),!1)}return e.type==="AI_PARSE_DATA"?(this.handleAsyncAiParseData(e.data,r),!0):e.type==="FETCH_API"&&Rh(e)?(this.handleAsyncFetchApi(e.data,r),!0):(r({$isError:!0,message:"Invalid message type",data:{}}),!1)})}async handleAsyncCollectWorkflow(e,t){await this.workflowService.handleCollectWorkflow(e,t)}async handleAsyncCdpClick(e,t){await this.cdpService.handleClick(e,t)}async handleAsyncCdpKeypress(e,t){await this.cdpService.handleKeypress(e,t)}async handleAsyncAiParseData(e,t){await this.aiParsingService.handleParseData(e,t)}async handleAsyncFetchApi(e,t){await this.apiService.handleRequest(e,t)}}console.log("[8G Extension] Background script starting...");const dv=new lv;dv.initHandler();