diff --git a/files/ai_side_panel/background.js b/files/ai_side_panel/background.js index 12fc424a5..9c9d2b2a3 100644 --- a/files/ai_side_panel/background.js +++ b/files/ai_side_panel/background.js @@ -1 +1 @@ -(()=>{var e,t,r={58:(e,t,r)=>{"use strict";r.r(t),r.d(t,{AsyncGeneratorWithSetup:()=>l,IterableReadableStream:()=>i,atee:()=>o,concat:()=>c,pipeGeneratorWithSetup:()=>u});var n=r(765),s=r(4350),a=r(9830);class i 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 e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){const t=e.getReader();return new i({start:e=>function r(){return t.read().then((({done:t,value:n})=>{if(!t)return e.enqueue(n),r();e.close()}))}(),cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new i({async pull(t){const{value:r,done:n}=await e.next();n&&t.close(),t.enqueue(r)},async cancel(t){await e.return(t)}})}}function o(e,t=2){const r=Array.from({length:t},(()=>[]));return r.map((async function*(t){for(;;)if(0===t.length){const t=await e.next();for(const e of r)e.push(t)}else{if(t[0].done)return;yield t.shift().value}}))}function c(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if("string"==typeof e&&"string"==typeof t)return e+t;if("number"==typeof e&&"number"==typeof t)return e+t;if("concat"in e&&"function"==typeof e.concat)return e.concat(t);if("object"==typeof e&&"object"==typeof t){const r={...e};for(const[e,n]of Object.entries(t))e in r&&!Array.isArray(r[e])?r[e]=c(r[e],n):r[e]=n;return r}throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}class l{constructor(e){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??this.config?.signal,this.setup=new Promise(((t,r)=>{s.Nx.runWithConfig((0,n.DY)(e.config),(async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then((e=>t(void 0)),r)}),!0)}))}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?s.Nx.runWithConfig((0,n.DY)(this.config),this.signal?async()=>(0,a.o)(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 u(e,t,r,n,...s){const a=new l({generator:t,startSetup:r,signal:n}),i=await a.setup;return{output:e(a,i,...s),setup:i}}},144:(e,t,r)=>{"use strict";const n=r(3908);e.exports=(e,t,r=!1)=>{if(e instanceof n)return e;try{return new n(e,t)}catch(e){if(!r)return null;throw e}}},199:(e,t,r)=>{"use strict";function n(e){return!(!e||"object"!=typeof e||!("type"in e)||"tool_call"!==e.type)}function s(e){return!!(e&&"object"==typeof e&&"toolCall"in e&&null!=e.toolCall&&"object"==typeof e.toolCall&&"id"in e.toolCall&&"string"==typeof e.toolCall.id)}r.d(t,{Ky:()=>n,hR:()=>s,qe:()=>a});class a extends Error{constructor(e,t){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=t}}},228:e=>{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function a(e,t,n,a,i){if("function"!=typeof n)throw new TypeError("The listener must be a function");var o=new s(n,a||e,i),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],o]:e._events[c].push(o):(e._events[c]=o,e._eventsCount++),e}function i(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function o(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,n,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},o.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,a=n.length,i=new Array(a);s{"use strict";const n=r(3908),s=r(8311);e.exports=(e,t,r)=>{let a=null,i=null,o=null;try{o=new s(t,r)}catch(e){return null}return e.forEach((e=>{o.test(e)&&(a&&1!==i.compare(e)||(a=e,i=new n(a,r)))})),a}},329:(e,t,r)=>{"use strict";r.d(t,{L:()=>a});var n=r(5311),s=r(6993);class a extends s.m{async formatPromptValue(e){const t=await this.format(e);return new n.StringPromptValue(t)}}},560:(e,t,r)=>{"use strict";const n=r(3908);e.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))},736:(e,t,r)=>{e.exports=function(e){function t(e){let r,s,a,i=null;function o(...e){if(!o.enabled)return;const n=o,s=Number(new Date),a=s-(r||s);n.diff=a,n.prev=r,n.curr=s,r=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,s)=>{if("%%"===r)return"%";i++;const a=t.formatters[s];if("function"==typeof a){const t=e[i];r=a.call(n,t),e.splice(i,1),i--}return r})),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return o.namespace=e,o.useColors=t.useColors(),o.color=t.selectColor(e),o.extend=n,o.destroy=t.destroy,Object.defineProperty(o,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(s!==t.namespaces&&(s=t.namespaces,a=t.enabled(e)),a),set:e=>{i=e}}),"function"==typeof t.init&&t.init(o),o}function n(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function s(e,t){let r=0,n=0,s=-1,a=0;for(;r"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(s(e,r))return!1;for(const r of t.names)if(s(e,r))return!0;return!1},t.humanize=r(6585),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{"use strict";r.d(t,{Yx:()=>o,rO:()=>i});var n=r(4785);const s=(...e)=>fetch(...e),a=Symbol.for("ls:fetch_implementation"),i=()=>{const e=globalThis[a];return!!e&&("function"==typeof e&&"Headers"in e&&"Request"in e&&"Response"in e)},o=e=>async(...t)=>{if(e||"true"===(0,n.Jz)("DEBUG")){const[e,r]=t;console.log(`→ ${r?.method||"GET"} ${e}`)}const r=await(globalThis[a]??s)(...t);return(e||"true"===(0,n.Jz)("DEBUG"))&&console.log(`← ${r.status} ${r.statusText} ${r.url}`),r}},765:(e,t,r)=>{"use strict";r.d(t,{DY:()=>d,SV:()=>o,ZI:()=>l,kJ:()=>i,p_:()=>a,tn:()=>u});var n=r(5042),s=r(4350);const a=25;async function i(e){return n.CallbackManager._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function o(...e){const t={};for(const r of e.filter((e=>!!e)))for(const e of Object.keys(r))if("metadata"===e)t[e]={...t[e],...r[e]};else if("tags"===e){const n=t[e]??[];t[e]=[...new Set(n.concat(r[e]??[]))]}else if("configurable"===e)t[e]={...t[e],...r[e]};else if("timeout"===e)void 0===t.timeout?t.timeout=r.timeout:void 0!==r.timeout&&(t.timeout=Math.min(t.timeout,r.timeout));else if("signal"===e)void 0===t.signal?t.signal=r.signal:void 0!==r.signal&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,r.signal]):t.signal=r.signal);else if("callbacks"===e){const e=t.callbacks,s=r.callbacks;if(Array.isArray(s))if(e)if(Array.isArray(e))t.callbacks=e.concat(s);else{const r=e.copy();for(const e of s)r.addHandler((0,n.ensureHandler)(e),!0);t.callbacks=r}else t.callbacks=s;else if(s)if(e)if(Array.isArray(e)){const r=s.copy();for(const t of e)r.addHandler((0,n.ensureHandler)(t),!0);t.callbacks=r}else t.callbacks=new n.CallbackManager(s._parentRunId,{handlers:e.handlers.concat(s.handlers),inheritableHandlers:e.inheritableHandlers.concat(s.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(s.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(s.inheritableTags))),metadata:{...e.metadata,...s.metadata}});else t.callbacks=s}else{const n=e;t[n]=r[n]??t[n]}return t}const c=new Set(["string","number","boolean"]);function l(e){const t=s.Nx.getRunnableConfig();let r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){const{runId:e,runName:n,...s}=t;r=Object.entries(s).reduce(((e,[t,r])=>(void 0!==r&&(e[t]=r),e)),r)}if(e&&(r=Object.entries(e).reduce(((e,[t,r])=>(void 0!==r&&(e[t]=r),e)),r)),r?.configurable)for(const e of Object.keys(r.configurable))c.has(typeof r.configurable[e])&&!r.metadata?.[e]&&(r.metadata||(r.metadata={}),r.metadata[e]=r.configurable[e]);if(void 0!==r.timeout){if(r.timeout<=0)throw new Error("Timeout must be a positive number");const e=AbortSignal.timeout(r.timeout);void 0!==r.signal?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,e])):r.signal=e,delete r.timeout}return r}function u(e={},{callbacks:t,maxConcurrency:r,recursionLimit:n,runName:s,configurable:a,runId:i}={}){const o=l(e);return void 0!==t&&(delete o.runName,o.callbacks=t),void 0!==n&&(o.recursionLimit=n),void 0!==r&&(o.maxConcurrency=r),void 0!==s&&(o.runName=s),void 0!==a&&(o.configurable={...o.configurable,...a}),void 0!==i&&delete o.runId,o}function d(e){return e?{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal}:void 0}},780:(e,t,r)=>{"use strict";function n(e,t=s){const r=(e=e.trim()).indexOf("```");if(-1===r)return t(e);let n=e.substring(r+3);n.startsWith("json\n")?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith("\n")&&(n=n.substring(1));const a=n.indexOf("```");let i=n;return-1!==a&&(i=n.substring(0,a)),t(i.trim())}function s(e){if(void 0===e)return null;try{return JSON.parse(e)}catch(e){}let t="";const r=[];let n=!1,s=!1;for(let a of e){if(n)'"'!==a||s?"\n"!==a||s?s="\\"===a&&!s:a="\\n":n=!1;else if('"'===a)n=!0,s=!1;else if("{"===a)r.push("}");else if("["===a)r.push("]");else if("}"===a||"]"===a){if(!r||r[r.length-1]!==a)return null;r.pop()}t+=a}n&&(t+='"');for(let e=r.length-1;e>=0;e-=1)t+=r[e];try{return JSON.parse(t)}catch(e){return null}}r.d(t,{D:()=>n,d:()=>s})},809:(e,t,r)=>{"use strict";r.d(t,{T:()=>n});const n="24.8.2"},874:(e,t,r)=>{"use strict";r.r(t),r.d(t,{NodeWebSocketTransport:()=>a});var n=r(1591),s=r(809);class a{static create(e,t){return new Promise(((r,i)=>{const o=new n(e,[],{followRedirects:!0,perMessageDeflate:!1,allowSynchronousEvents:!1,maxPayload:268435456,headers:{"User-Agent":`Puppeteer ${s.T}`,...t}});o.addEventListener("open",(()=>r(new a(o)))),o.addEventListener("error",i)}))}#e;onmessage;onclose;constructor(e){this.#e=e,this.#e.addEventListener("message",(e=>{this.onmessage&&this.onmessage.call(null,e.data)})),this.#e.addEventListener("close",(()=>{this.onclose&&this.onclose.call(null)})),this.#e.addEventListener("error",(()=>{}))}send(e){this.#e.send(e)}close(){this.#e.close()}}},909:(e,t,r)=>{"use strict";const n=r(3908);e.exports=(e,t,r)=>{const s=new n(e,r),a=new n(t,r);return s.compare(a)||s.compareBuild(a)}},1060:(e,t,r)=>{"use strict";r.r(t),r.d(t,{LogStreamCallbackHandler:()=>h,RunLog:()=>c,RunLogPatch:()=>o,isLogStreamHandler:()=>l});var n=r(6150),s=r(1590),a=r(58),i=r(7765);class o{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=(0,n.X6)({},t);return new c({ops:t,state:r[r.length-1].newDocument})}}class c extends o{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=(0,n.X6)(this.state,e.ops);return new c({ops:t,state:r[r.length-1].newDocument})}static fromRunLogPatch(e){const t=(0,n.X6)({},e.ops);return new c({ops:e.ops,state:t[t.length-1].newDocument})}}const l=e=>"log_stream_tracer"===e.name;async function u(e,t){if("original"===t)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:r}=e;return["retriever","llm","prompt"].includes(e.run_type)?r:1!==Object.keys(r).length||""!==r?.input?r.input:void 0}async function d(e,t){const{outputs:r}=e;return"original"===t||["retriever","llm","prompt"].includes(e.run_type)?r:void 0!==r&&1===Object.keys(r).length&&void 0!==r?.output?r.output:r}class h extends s.BaseTracer{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?.autoClose??!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,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=a.IterableReadableStream.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=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.run_type)),void 0!==this.includeTags&&(r=r||void 0!==t.find((e=>this.includeTags?.includes(e)))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.run_type)),void 0!==this.excludeTags&&(r=r&&t.every((e=>!this.excludeTags?.includes(e)))),r}async*tapOutputIterable(e,t){for await(const r of t){if(e!==this.rootId){const t=this.keyMapByRunId[e];t&&await this.writer.write(new o({ops:[{op:"add",path:`/logs/${t}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(void 0===this.rootId&&(this.rootId=e.id,await this.writer.write(new o({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;void 0===this.counterMapByRunName[e.name]&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=1===t?e.name:`${e.name}:${t}`;const r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};"streaming_events"===this._schemaFormat&&(r.inputs=await u(e,this._schemaFormat)),await this.writer.write(new o({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(void 0===t)return;const r=[];"streaming_events"===this._schemaFormat&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await u(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await d(e,this._schemaFormat)}),void 0!==e.end_time&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const n=new o({ops:r});await this.writer.write(n)}finally{if(e.id===this.rootId){const t=new o({ops:[{op:"replace",path:"/final_output",value:await d(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){const n=this.keyMapByRunId[e.id];if(void 0===n)return;let s;var a;void 0!==e.inputs.messages?(a=r?.chunk,s=void 0!==a&&void 0!==a.message?r?.chunk:new i.H({id:`run-${e.id}`,content:t})):s=t;const c=new o({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${n}/streamed_output/-`,value:s}]});await this.writer.write(c)}}},1123:e=>{"use strict";const t=/^[0-9]+$/,r=(e,r)=>{const n=t.test(e),s=t.test(r);return n&&s&&(e=+e,r=+r),e===r?0:n&&!s?-1:s&&!n?1:er(t,e)}},1259:(e,t,r)=>{"use strict";r.d(t,{Kj:()=>n.Kj,gk:()=>n.gk});var n=r(4547)},1261:(e,t,r)=>{"use strict";const n=r(3908),s=r(8311),a=r(5580);e.exports=(e,t)=>{e=new s(e,t);let r=new n("0.0.0");if(e.test(r))return r;if(r=new n("0.0.0-0"),e.test(r))return r;r=null;for(let t=0;t{const t=new n(e.semver.version);switch(e.operator){case">":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":i&&!a(t,i)||(i=t);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${e.operator}`)}})),!i||r&&!a(r,i)||(r=i)}return r&&e.test(r)?r:null}},1368:(e,t,r)=>{"use strict";function n(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t}/\n`,e}r.d(t,{Y:()=>n})},1590:(e,t,r)=>{"use strict";r.r(t),r.d(t,{BaseTracer:()=>i,isBaseTracer:()=>a});var n=r(5960);function s(e,t){return e&&!Array.isArray(e)&&"object"==typeof e?e:{[t]:e}}function a(e){return"function"==typeof e._addRunToRunMap}class i extends n.BaseCallbackHandler{constructor(e){super(...arguments),Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}copy(){return this}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`\n\n${e.stack}`:""):"string"==typeof e?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const t=function(e,t,r){const n=r.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(e).toISOString().slice(0,-1)}${n}Z`.replace(/[-:.]/g,"")+t}(e.start_time,e.id,e.execution_order),r={...e};if(void 0!==r.parent_run_id){const e=this.runMap.get(r.parent_run_id);e&&(this._addChildRun(e,r),e.child_execution_order=Math.max(e.child_execution_order,r.child_execution_order),r.trace_id=e.trace_id,void 0!==e.dotted_order&&(r.dotted_order=[e.dotted_order,t].join(".")))}else r.trace_id=r.id,r.dotted_order=t;return this.runMap.set(r.id,r),r}async _endTrace(e){const t=void 0!==e.parent_run_id&&this.runMap.get(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),this.runMap.delete(e.id),await(this.onRunUpdate?.(e))}_getExecutionOrder(e){const t=void 0!==e&&this.runMap.get(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,n,s,a,i,o){const c=this._getExecutionOrder(n),l=Date.now(),u=i?{...s,metadata:i}:s,d={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,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:u??{},tags:a||[]};return this._addRunToRunMap(d)}async handleLLMStart(e,t,r,n,s,a,i,o){const c=this.runMap.get(r)??this._createRunForLLMStart(e,t,r,n,s,a,i,o);return await(this.onRunCreate?.(c)),await(this.onLLMStart?.(c)),c}_createRunForChatModelStart(e,t,r,n,s,a,i,o){const c=this._getExecutionOrder(n),l=Date.now(),u=i?{...s,metadata:i}:s,d={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,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:u??{},tags:a||[]};return this._addRunToRunMap(d)}async handleChatModelStart(e,t,r,n,s,a,i,o){const c=this.runMap.get(r)??this._createRunForChatModelStart(e,t,r,n,s,a,i,o);return await(this.onRunCreate?.(c)),await(this.onLLMStart?.(c)),c}async handleLLMEnd(e,t,r,n,s){const a=this.runMap.get(t);if(!a||"llm"!==a?.run_type)throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=e,a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...s},await(this.onLLMEnd?.(a)),await this._endTrace(a),a}async handleLLMError(e,t,r,n,s){const a=this.runMap.get(t);if(!a||"llm"!==a?.run_type)throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...s},await(this.onLLMError?.(a)),await this._endTrace(a),a}_createRunForChainStart(e,t,r,n,s,a,i,o){const c=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:t,execution_order:c,child_execution_order:c,run_type:i??"chain",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(u)}async handleChainStart(e,t,r,n,s,a,i,o){const c=this.runMap.get(r)??this._createRunForChainStart(e,t,r,n,s,a,i,o);return await(this.onRunCreate?.(c)),await(this.onChainStart?.(c)),c}async handleChainEnd(e,t,r,n,a){const i=this.runMap.get(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=s(e,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),void 0!==a?.inputs&&(i.inputs=s(a.inputs,"input")),await(this.onChainEnd?.(i)),await this._endTrace(i),i}async handleChainError(e,t,r,n,a){const i=this.runMap.get(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()}),void 0!==a?.inputs&&(i.inputs=s(a.inputs,"input")),await(this.onChainError?.(i)),await this._endTrace(i),i}_createRunForToolStart(e,t,r,n,s,a,i){const o=this._getExecutionOrder(n),c=Date.now(),l={id:r,name:i??e.id[e.id.length-1],parent_run_id:n,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,r,n,s,a,i){const o=this.runMap.get(r)??this._createRunForToolStart(e,t,r,n,s,a,i);return await(this.onRunCreate?.(o)),await(this.onToolStart?.(o)),o}async handleToolEnd(e,t){const r=this.runMap.get(t);if(!r||"tool"!==r?.run_type)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(this.onToolEnd?.(r)),await this._endTrace(r),r}async handleToolError(e,t){const r=this.runMap.get(t);if(!r||"tool"!==r?.run_type)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(this.onToolError?.(r)),await this._endTrace(r),r}async handleAgentAction(e,t){const r=this.runMap.get(t);if(!r||"chain"!==r?.run_type)return;const n=r;n.actions=n.actions||[],n.actions.push(e),n.events.push({name:"agent_action",time:(new Date).toISOString(),kwargs:{action:e}}),await(this.onAgentAction?.(r))}async handleAgentEnd(e,t){const r=this.runMap.get(t);r&&"chain"===r?.run_type&&(r.events.push({name:"agent_end",time:(new Date).toISOString(),kwargs:{action:e}}),await(this.onAgentEnd?.(r)))}_createRunForRetrieverStart(e,t,r,n,s,a,i){const o=this._getExecutionOrder(n),c=Date.now(),l={id:r,name:i??e.id[e.id.length-1],parent_run_id:n,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,r,n,s,a,i){const o=this.runMap.get(r)??this._createRunForRetrieverStart(e,t,r,n,s,a,i);return await(this.onRunCreate?.(o)),await(this.onRetrieverStart?.(o)),o}async handleRetrieverEnd(e,t){const r=this.runMap.get(t);if(!r||"retriever"!==r?.run_type)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(this.onRetrieverEnd?.(r)),await this._endTrace(r),r}async handleRetrieverError(e,t){const r=this.runMap.get(t);if(!r||"retriever"!==r?.run_type)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(this.onRetrieverError?.(r)),await this._endTrace(r),r}async handleText(e,t){const r=this.runMap.get(t);r&&"chain"===r?.run_type&&(r.events.push({name:"text",time:(new Date).toISOString(),kwargs:{text:e}}),await(this.onText?.(r)))}async handleLLMNewToken(e,t,r,n,s,a){const i=this.runMap.get(r);if(!i||"llm"!==i?.run_type)throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return i.events.push({name:"new_token",time:(new Date).toISOString(),kwargs:{token:e,idx:t,chunk:a?.chunk}}),await(this.onLLMNewToken?.(i,e,{chunk:a?.chunk})),i}}},1591:e=>{"use strict";e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}},1673:(e,t,r)=>{"use strict";r.r(t),r.d(t,{AIMessage:()=>n.Od,AIMessageChunk:()=>n.H,BaseMessage:()=>s.XQ,BaseMessageChunk:()=>s.gj,ChatMessage:()=>a.cM,ChatMessageChunk:()=>a.XU,FunctionMessage:()=>i.mg,FunctionMessageChunk:()=>i.FK,HumanMessage:()=>o.xc,HumanMessageChunk:()=>o.a7,RemoveMessage:()=>d,SystemMessage:()=>c.tn,SystemMessageChunk:()=>c.uU,ToolMessage:()=>h.uf,ToolMessageChunk:()=>h.dr,_isMessageFieldWithRole:()=>s.dp,_mergeDicts:()=>s.ns,_mergeLists:()=>s.Vt,_mergeObj:()=>s.F7,_mergeStatus:()=>s.Iv,coerceMessageLikeToMessage:()=>l.K0,convertToChunk:()=>l.ih,convertToOpenAIImageBlock:()=>x.Vi,convertToProviderContentBlock:()=>x.up,defaultTextSplitter:()=>E,filterMessages:()=>m,getBufferString:()=>l.Sw,isAIMessage:()=>n.KX,isAIMessageChunk:()=>n.jm,isBase64ContentBlock:()=>x.cJ,isBaseMessage:()=>s.ny,isBaseMessageChunk:()=>s.AJ,isChatMessage:()=>a.kY,isChatMessageChunk:()=>a.bU,isDataContentBlock:()=>x.Fz,isFunctionMessage:()=>i.AP,isFunctionMessageChunk:()=>i.vl,isHumanMessage:()=>o.di,isHumanMessageChunk:()=>o.GZ,isIDContentBlock:()=>x.oe,isOpenAIToolCallArray:()=>s.Ao,isPlainTextContentBlock:()=>x.Ac,isSystemMessage:()=>c.X4,isSystemMessageChunk:()=>c.UF,isToolMessage:()=>h.wk,isToolMessageChunk:()=>h.P,isURLContentBlock:()=>x.W,mapChatMessagesToStoredMessages:()=>l.Js,mapStoredMessageToChatMessage:()=>l.Pz,mapStoredMessagesToChatMessages:()=>l.rf,mergeContent:()=>s._I,mergeMessageRuns:()=>g,parseBase64DataUrl:()=>x.Q7,parseMimeType:()=>x.Ej,trimMessages:()=>b});var n=r(7765),s=r(3490),a=r(4301),i=r(8675),o=r(5454),c=r(7974),l=r(6362),u=r(3313);class d extends s.XQ{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}}}var h=r(8009);const p=(e,t)=>{const r=[...new Set(t?.map((e=>{if("string"==typeof e)return e;const t=new e({});if(!("getType"in t)||"function"!=typeof t.getType)throw new Error("Invalid type provided.");return t.getType()})))],n=e.getType();return r.some((e=>e===n))};function m(e,t){return Array.isArray(e)?f(e,t):u.jY.from((t=>f(t,e)))}function f(e,t={}){const{includeNames:r,excludeNames:n,includeTypes:s,excludeTypes:a,includeIds:i,excludeIds:o}=t,c=[];for(const t of e)n&&t.name&&n.includes(t.name)||a&&p(t,a)||o&&t.id&&o.includes(t.id)||(s||i||r?(r&&t.name&&r.some((e=>e===t.name))||s&&p(t,s)||i&&t.id&&i.some((e=>e===t.id)))&&c.push(t):c.push(t));return c}function g(e){return Array.isArray(e)?y(e):u.jY.from(y)}function y(e){if(!e.length)return[];const t=[];for(const r of e){const e=r,n=t.pop();if(n)if("tool"===e.getType()||e.getType()!==n.getType())t.push(n,e);else{const r=(0,l.ih)(n),s=(0,l.ih)(e),a=r.concat(s);"string"==typeof r.content&&"string"==typeof s.content&&(a.content=`${r.content}\n${s.content}`),t.push(S(a))}else t.push(e)}return t}function b(e,t){if(Array.isArray(e)){const r=e;if(!t)throw new Error("Options parameter is required when providing messages.");return w(r,t)}{const t=e;return u.jY.from((e=>w(e,t))).withConfig({runName:"trim_messages"})}}async function w(e,t){const{maxTokens:r,tokenCounter:n,strategy:a="last",allowPartial:i=!1,endOn:o,startOn:c,includeSystem:l=!1,textSplitter:u}=t;if(c&&"first"===a)throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(l&&"first"===a)throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let d;d="getNumTokens"in n?async e=>(await Promise.all(e.map((e=>n.getNumTokens(e.content))))).reduce(((e,t)=>e+t),0):async e=>n(e);let h=E;if(u&&(h="splitText"in u?u.splitText:async e=>u(e)),"first"===a)return v(e,{maxTokens:r,tokenCounter:d,textSplitter:h,partialStrategy:i?"first":void 0,endOn:o});if("last"===a)return async function(e,t){const{allowPartial:r=!1,includeSystem:n=!1,endOn:a,startOn:i,...o}=t;let c=e.map((e=>{const t=Object.fromEntries(Object.entries(e).filter((([e])=>"type"!==e&&!e.startsWith("lc_"))));return k(e.getType(),t,(0,s.AJ)(e))}));if(a){const e=Array.isArray(a)?a:[a];for(;c.length>0&&!p(c[c.length-1],e);)c=c.slice(0,-1)}const l=n&&"system"===c[0]?.getType();let u=l?c.slice(0,1).concat(c.slice(1).reverse()):c.reverse();return u=await v(u,{...o,partialStrategy:r?"last":void 0,endOn:i}),l?[u[0],...u.slice(1).reverse()]:u.reverse()}(e,{maxTokens:r,tokenCounter:d,textSplitter:h,allowPartial:i,includeSystem:l,startOn:c,endOn:o});throw new Error(`Unrecognized strategy: '${a}'. Must be one of 'first' or 'last'.`)}async function v(e,t){const{maxTokens:r,tokenCounter:n,textSplitter:s,partialStrategy:a,endOn:i}=t;let o=[...e],c=0;for(let e=0;e0?o.slice(0,-e):o;if(await n(t)<=r){c=o.length-e;break}}if(c"type"!==e&&!e.startsWith("lc_")))),d=k(t.getType(),{...u,content:s}),h=[...o.slice(0,c),d];if(!(await n(h)<=r))break;o=h,c+=1,e=!0}e&&"last"===a&&(t.content=[...i].reverse())}if(!e){const e=o[c];let t;if(Array.isArray(e.content)&&e.content.some((e=>"string"==typeof e||"text"===e.type))){const r=e.content.find((e=>"text"===e.type&&e.text));t=r?.text}else"string"==typeof e.content&&(t=e.content);if(t){const i=await s(t),l=i.length;"last"===a&&i.reverse();for(let t=0;t0&&!p(o[c-1],e);)c-=1}return o.slice(0,c)}const _={human:{message:o.xc,messageChunk:o.a7},ai:{message:n.Od,messageChunk:n.H},system:{message:c.tn,messageChunk:c.uU},developer:{message:c.tn,messageChunk:c.uU},tool:{message:h.uf,messageChunk:h.dr},function:{message:i.mg,messageChunk:i.FK},generic:{message:a.cM,messageChunk:a.XU},remove:{message:d,messageChunk:d}};function k(e,t,r){let s,l;switch(e){case"human":r?s=new o.a7(t):l=new o.xc(t);break;case"ai":if(r){let e={...t};"tool_calls"in e&&(e={...e,tool_call_chunks:e.tool_calls?.map((e=>({...e,type:"tool_call_chunk",index:void 0,args:JSON.stringify(e.args)})))}),s=new n.H(e)}else l=new n.Od(t);break;case"system":r?s=new c.uU(t):l=new c.tn(t);break;case"developer":r?s=new c.uU({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}}):l=new c.tn({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if(!("tool_call_id"in t))throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");r?s=new h.dr(t):l=new h.uf(t);break;case"function":if(r)s=new i.FK(t);else{if(!t.name)throw new Error("FunctionMessage must have a 'name' field");l=new i.mg(t)}break;case"generic":if(!("role"in t))throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");r?s=new a.XU(t):l=new a.cM(t);break;default:throw new Error(`Unrecognized message type ${e}`)}if(r&&s)return s;if(l)return l;throw new Error(`Unrecognized message type ${e}`)}function S(e){const t=e.getType();let r;const n=Object.fromEntries(Object.entries(e).filter((([e])=>!["type","tool_call_chunks"].includes(e)&&!e.startsWith("lc_"))));if(t in _&&(r=k(t,n)),!r)throw new Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys(_)}`);return r}function E(e){const t=e.split("\n");return Promise.resolve([...t.slice(0,-1).map((e=>`${e}\n`)),t[t.length-1]])}var x=r(4291)},1688:(e,t,r)=>{"use strict";r.d(t,{gk:()=>n.gk});var n=r(3246)},1729:(e,t,r)=>{"use strict";const n=r(144);e.exports=(e,t)=>{const r=n(e,t);return r&&r.prerelease.length?r.prerelease:null}},1763:(e,t,r)=>{"use strict";const n=r(560);e.exports=(e,t)=>n(e,t,!0)},1832:(e,t,r)=>{"use strict";const n=r(144);e.exports=(e,t)=>{const r=n(e,null,!0),s=n(t,null,!0),a=r.compare(s);if(0===a)return null;const i=a>0,o=i?r:s,c=i?s:r,l=!!o.prerelease.length;if(!!c.prerelease.length&&!l){if(!c.patch&&!c.minor)return"major";if(0===c.compareMain(o))return c.minor&&!c.patch?"minor":"patch"}const u=l?"pre":"";return r.major!==s.major?u+"major":r.minor!==s.minor?u+"minor":r.patch!==s.patch?u+"patch":"prerelease"}},2111:(e,t,r)=>{"use strict";const n=r(4641),s=r(3999),a=r(5580),i=r(4089),o=r(7059),c=r(5200);e.exports=(e,t,r,l)=>{switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e===r;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e!==r;case"":case"=":case"==":return n(e,r,l);case"!=":return s(e,r,l);case">":return a(e,r,l);case">=":return i(e,r,l);case"<":return o(e,r,l);case"<=":return c(e,r,l);default:throw new TypeError(`Invalid operator: ${t}`)}}},2293:(e,t,r)=>{"use strict";r.r(t),r.d(t,{awaitAllCallbacks:()=>c,consumeCallback:()=>o});var n=r(3290),s=r(6968);let a;function i(){return void 0===a&&(a=new(0,n.default)({autoStart:!0,concurrency:1})),a}async function o(e,t){if(!0===t){const t=(0,s.X0)();void 0!==t?await t.run(void 0,(async()=>e())):await e()}else a=i(),a.add((async()=>{const t=(0,s.X0)();void 0!==t?await t.run(void 0,(async()=>e())):await e()}))}function c(){return void 0!==a?a.onIdle():Promise.resolve()}},2366:(e,t,r)=>{"use strict";r.d(t,{Ik:()=>z});const n=Symbol("Let zodToJsonSchema decide on which parser to use"),s={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"},a=e=>{const t=(e=>"string"==typeof e?{...s,name:e}:{...s,...e})(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map((([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}])))}};var i=r(4476);function o(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function c(e,t,r,n,s){e[t]=r,o(e,t,n,s)}function l(e,t){return $(e.type._def,t)}function u(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(((r,n)=>u(e,t,r)))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return d(e,t)}}const d=(e,t)=>{const r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(const n of e.checks)switch(n.kind){case"min":c(r,"minimum",n.value,n.message,t);break;case"max":c(r,"maximum",n.value,n.message,t)}return r};let h;const p=/^[cC][^\s-]{8,}$/,m=/^[0-9a-z]+$/,f=/^[0-9A-HJKMNP-TV-Z]{26}$/,g=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,y=()=>(void 0===h&&(h=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),h),b=/^(?:(?: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])$/,w=/^(([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])$/,v=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,k=/^[a-zA-Z0-9_-]{21}$/,S=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function E(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":c(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":c(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":C(r,"email",n.message,t);break;case"format:idn-email":C(r,"idn-email",n.message,t);break;case"pattern:zod":P(r,g,n.message,t)}break;case"url":C(r,"uri",n.message,t);break;case"uuid":C(r,"uuid",n.message,t);break;case"regex":P(r,n.regex,n.message,t);break;case"cuid":P(r,p,n.message,t);break;case"cuid2":P(r,m,n.message,t);break;case"startsWith":P(r,RegExp(`^${x(n.value,t)}`),n.message,t);break;case"endsWith":P(r,RegExp(`${x(n.value,t)}$`),n.message,t);break;case"datetime":C(r,"date-time",n.message,t);break;case"date":C(r,"date",n.message,t);break;case"time":C(r,"time",n.message,t);break;case"duration":C(r,"duration",n.message,t);break;case"length":c(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t),c(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":P(r,RegExp(x(n.value,t)),n.message,t);break;case"ip":"v6"!==n.version&&C(r,"ipv4",n.message,t),"v4"!==n.version&&C(r,"ipv6",n.message,t);break;case"base64url":P(r,_,n.message,t);break;case"jwt":P(r,S,n.message,t);break;case"cidr":"v6"!==n.version&&P(r,b,n.message,t),"v4"!==n.version&&P(r,w,n.message,t);break;case"emoji":P(r,y(),n.message,t);break;case"ulid":P(r,f,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":C(r,"binary",n.message,t);break;case"contentEncoding:base64":c(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":P(r,v,n.message,t)}break;case"nanoid":P(r,k,n.message,t)}return r}function x(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;re.format))?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):c(e,"format",t,r,n)}function P(e,t,r,n){e.pattern||e.allOf?.some((e=>e.pattern))?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:O(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):c(e,"pattern",O(t,n),r,n)}function O(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r=e.flags.includes("i"),n=e.flags.includes("m"),s=e.flags.includes("s"),a=r?e.source.toLowerCase():e.source;let i="",o=!1,c=!1,l=!1;for(let e=0;e({...r,[n]:$(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??{}})),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:$(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===i.kY.ZodString&&e.keyType._def.checks?.length){const{type:n,...s}=E(e.keyType._def,t);return{...r,propertyNames:s}}if(e.keyType?._def.typeName===i.kY.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===i.kY.ZodBranded&&e.keyType._def.type._def.typeName===i.kY.ZodString&&e.keyType._def.type._def.checks?.length){const{type:n,...s}=l(e.keyType._def,t);return{...r,propertyNames:s}}return r}const I={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const M=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map(((e,r)=>$(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]}))).filter((e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0)));return r.length?{anyOf:r}:void 0};function R(e,t){const r="openAi"===t.target,n={type:"object",properties:{}},s=[],a=e.shape();for(const e in a){let o=a[e];if(void 0===o||void 0===o._def)continue;let c=j(o);c&&r&&(o instanceof i.Ii&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),c=!1);const l=$(o._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==l&&(n.properties[e]=l,c||s.push(e))}s.length&&(n.required=s);const o=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return $(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==o&&(n.additionalProperties=o),n}function j(e){try{return e.isOptional()}catch{return!0}}const N=(e,t,r)=>{switch(t){case i.kY.ZodString:return E(e,r);case i.kY.ZodNumber:return function(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",o(r,"type",n.message,t);break;case"min":"jsonSchema7"===t.target?n.inclusive?c(r,"minimum",n.value,n.message,t):c(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),c(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?c(r,"maximum",n.value,n.message,t):c(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),c(r,"maximum",n.value,n.message,t));break;case"multipleOf":c(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case i.kY.ZodObject:return R(e,r);case i.kY.ZodBigInt:return function(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":"jsonSchema7"===t.target?n.inclusive?c(r,"minimum",n.value,n.message,t):c(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),c(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?c(r,"maximum",n.value,n.message,t):c(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),c(r,"maximum",n.value,n.message,t));break;case"multipleOf":c(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case i.kY.ZodBoolean:return{type:"boolean"};case i.kY.ZodDate:return u(e,r);case i.kY.ZodUndefined:return{not:{}};case i.kY.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(r);case i.kY.ZodArray:return function(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==i.kY.ZodAny&&(r.items=$(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&c(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&c(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(c(r,"minItems",e.exactLength.value,e.exactLength.message,t),c(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}(e,r);case i.kY.ZodUnion:case i.kY.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return M(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((e=>e._def.typeName in I&&(!e._def.checks||!e._def.checks.length)))){const e=r.reduce(((e,t)=>{const r=I[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e}),[]);return{type:e.length>1?e:e[0]}}if(r.every((e=>"ZodLiteral"===e._def.typeName&&!e.description))){const e=r.reduce(((e,t)=>{const r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}}),[]);if(e.length===r.length){const t=e.filter(((e,t,r)=>r.indexOf(e)===t));return{type:t.length>1?t:t[0],enum:r.reduce(((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value]),[])}}}else if(r.every((e=>"ZodEnum"===e._def.typeName)))return{type:"string",enum:r.reduce(((e,t)=>[...e,...t._def.values.filter((t=>!e.includes(t)))]),[])};return M(e,t)}(e,r);case i.kY.ZodIntersection:return function(e,t){const r=[$(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),$(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((e=>!!e));let n="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const s=[];return r.forEach((e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:r,...n}=e;t=n}else n=void 0;s.push(t)}else s.push(...e.allOf),void 0===e.unevaluatedProperties&&(n=void 0);var t})),s.length?{allOf:s,...n}:void 0}(e,r);case i.kY.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map(((e,r)=>$(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[]),additionalItems:$(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map(((e,r)=>$(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[])}}(e,r);case i.kY.ZodRecord:return A(e,r);case i.kY.ZodLiteral:return function(e,t){const r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}(e,r);case i.kY.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case i.kY.ZodNativeEnum:return function(e){const t=e.values,r=Object.keys(e.values).filter((e=>"number"!=typeof t[t[e]])).map((e=>t[e])),n=Array.from(new Set(r.map((e=>typeof e))));return{type:1===n.length?"string"===n[0]?"string":"number":["string","number"],enum:r}}(e);case i.kY.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:I[e.innerType._def.typeName],nullable:!0}:{type:[I[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const r=$(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=$(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case i.kY.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return $(e.innerType._def,t);const r=$(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}})(e,r);case i.kY.ZodMap:return function(e,t){return"record"===t.mapStrategy?A(e,t):{type:"array",maxItems:125,items:{type:"array",items:[$(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},$(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}(e,r);case i.kY.ZodSet:return function(e,t){const r={type:"array",uniqueItems:!0,items:$(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&c(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&c(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}(e,r);case i.kY.ZodLazy:return()=>e.getter()._def;case i.kY.ZodPromise:return function(e,t){return $(e.type._def,t)}(e,r);case i.kY.ZodNaN:case i.kY.ZodNever:return{not:{}};case i.kY.ZodEffects:return function(e,t){return"input"===t.effectStrategy?$(e.schema._def,t):{}}(e,r);case i.kY.ZodAny:case i.kY.ZodUnknown:return{};case i.kY.ZodDefault:return function(e,t){return{...$(e.innerType._def,t),default:e.defaultValue()}}(e,r);case i.kY.ZodBranded:return l(e,r);case i.kY.ZodReadonly:case i.kY.ZodCatch:return((e,t)=>$(e.innerType._def,t))(e,r);case i.kY.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return $(e.in._def,t);if("output"===t.pipeStrategy)return $(e.out._def,t);const r=$(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,$(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter((e=>void 0!==e))}})(e,r);case i.kY.ZodFunction:case i.kY.ZodVoid:case i.kY.ZodSymbol:default:return}};function $(e,t,r=!1){const s=t.seen.get(e);if(t.override){const a=t.override?.(e,t,s,r);if(a!==n)return a}if(s&&!r){const e=L(s,t);if(void 0!==e)return e}const a={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,a);const i=N(e,e.typeName,t),o="function"==typeof i?$(i(),t):i;if(o&&D(e,t,o),t.postProcess){const r=t.postProcess(o,e,t);return a.jsonSchema=o,r}return a.jsonSchema=o,o}const L=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:F(t.currentPath,e.path)};case"none":case"seen":return e.path.lengtht.currentPath[r]===e))?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{}):"seen"===t.$refStrategy?{}:void 0}},F=(e,t)=>{let r=0;for(;r(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),z=(e,t)=>{const r=a(t),n="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce(((e,[t,n])=>({...e,[t]:$(n._def,{...r,currentPath:[...r.basePath,r.definitionPath,t]},!0)??{}})),{}):void 0,s="string"==typeof t?t:"title"===t?.nameStrategy?void 0:t?.name,i=$(e._def,void 0===s?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??{},o="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==o&&(i.title=o);const c=void 0===s?n?{...i,[r.definitionPath]:n}:i:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:i}};return"jsonSchema7"===r.target?c.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==r.target&&"openAi"!==r.target||(c.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("anyOf"in c||"oneOf"in c||"allOf"in c||"type"in c&&Array.isArray(c.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),c}},2525:(e,t,r)=>{"use strict";const n=r(7638),s=r(560);e.exports=(e,t,r)=>{const a=[];let i=null,o=null;const c=e.sort(((e,t)=>s(e,t,r)));for(const e of c){n(e,t,r)?(o=e,i||(i=e)):(o&&a.push([i,o]),o=null,i=null)}i&&a.push([i,null]);const l=[];for(const[e,t]of a)e===t?l.push(e):t||e!==c[0]?t?e===c[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`):l.push("*");const u=l.join(" || "),d="string"==typeof t.raw?t.raw:String(t);return u.length{"use strict";const t=/[\p{Lu}]/u,r=/[\p{Ll}]/u,n=/^[\p{Lu}](?![\p{Lu}])/gu,s=/([\p{Alpha}\p{N}_]|$)/u,a=/[_.\- ]+/,i=new RegExp("^"+a.source),o=new RegExp(a.source+s.source,"gu"),c=new RegExp("\\d+"+s.source,"gu"),l=(e,s)=>{if("string"!=typeof e&&!Array.isArray(e))throw new TypeError("Expected the input to be `string | string[]`");if(s={pascalCase:!1,preserveConsecutiveUppercase:!1,...s},0===(e=Array.isArray(e)?e.map((e=>e.trim())).filter((e=>e.length)).join("-"):e.trim()).length)return"";const a=!1===s.locale?e=>e.toLowerCase():e=>e.toLocaleLowerCase(s.locale),l=!1===s.locale?e=>e.toUpperCase():e=>e.toLocaleUpperCase(s.locale);if(1===e.length)return s.pascalCase?l(e):a(e);return e!==a(e)&&(e=((e,n,s)=>{let a=!1,i=!1,o=!1;for(let c=0;c(n.lastIndex=0,e.replace(n,(e=>t(e)))))(e,a):a(e),s.pascalCase&&(e=l(e.charAt(0))+e.slice(1)),((e,t)=>(o.lastIndex=0,c.lastIndex=0,e.replace(o,((e,r)=>t(r))).replace(c,(e=>t(e)))))(e,l)};e.exports=l,e.exports.default=l},2771:(e,t,r)=>{"use strict";r.d(t,{FewShotPromptTemplate:()=>o,s:()=>c});var n=r(329),s=r(9849),a=r(3650),i=r(3766);class o extends n.L{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"exampleSeparator",{enumerable:!0,configurable:!0,writable:!0,value:"\n\n"}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.assign(this,e),void 0!==this.examples&&void 0!==this.exampleSelector)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(void 0===this.examples&&void 0===this.exampleSelector)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),(0,s.Ns)(this.prefix+this.suffix,this.templateFormat,e)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(e){if(void 0!==this.examples)return this.examples;if(void 0!==this.exampleSelector)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(e){const t=this.inputVariables.filter((t=>!(t in e))),r={...this.partialVariables??{},...e},n={...this,inputVariables:t,partialVariables:r};return new o(n)}async format(e){const t=await this.mergePartialAndUserVariables(e),r=await this.getExamples(t),n=await Promise.all(r.map((e=>this.examplePrompt.format(e)))),a=[this.prefix,...n,this.suffix].join(this.exampleSeparator);return(0,s.Xm)(a,this.templateFormat,t)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(void 0!==this.outputParser)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(e){const{example_prompt:t}=e;if(!t)throw new Error("Missing example prompt");const r=await a.PromptTemplate.deserialize(t);let n;if(!Array.isArray(e.examples))throw new Error("Invalid examples format. Only list or string are supported.");return n=e.examples,new o({inputVariables:e.input_variables,examplePrompt:r,examples:n,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}}class c extends i.qF{_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"exampleSeparator",{enumerable:!0,configurable:!0,writable:!0,value:"\n\n"}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.examples=e.examples,this.examplePrompt=e.examplePrompt,this.exampleSeparator=e.exampleSeparator??"\n\n",this.exampleSelector=e.exampleSelector,this.prefix=e.prefix??"",this.suffix=e.suffix??"",this.templateFormat=e.templateFormat??"f-string",this.validateTemplate=e.validateTemplate??!0,void 0!==this.examples&&void 0!==this.exampleSelector)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(void 0===this.examples&&void 0===this.exampleSelector)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),(0,s.Ns)(this.prefix+this.suffix,this.templateFormat,e)}}async getExamples(e){if(void 0!==this.examples)return this.examples;if(void 0!==this.exampleSelector)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(e){const t=await this.mergePartialAndUserVariables(e);let r=await this.getExamples(t);r=r.map((e=>{const t={};return this.examplePrompt.inputVariables.forEach((r=>{t[r]=e[r]})),t}));const n=[];for(const e of r){const t=await this.examplePrompt.formatMessages(e);n.push(...t)}return n}async format(e){const t=await this.mergePartialAndUserVariables(e),r=await this.getExamples(t),n=(await Promise.all(r.map((e=>this.examplePrompt.formatMessages(e))))).flat().map((e=>e.content)),a=[this.prefix,...n,this.suffix].join(this.exampleSeparator);return(0,s.Xm)(a,this.templateFormat,t)}async partial(e){const t=this.inputVariables.filter((t=>!(t in e))),r={...this.partialVariables??{},...e},n={...this,inputVariables:t,partialVariables:r};return new c(n)}}},2938:(e,t,r)=>{"use strict";const n=r(3908);e.exports=(e,t)=>new n(e,t).major},3007:(e,t,r)=>{"use strict";const n=r(3908);e.exports=(e,t,r,s,a)=>{"string"==typeof r&&(a=s,s=r,r=void 0);try{return new n(e instanceof n?e.version:e,r).inc(t,s,a).version}catch(e){return null}}},3246:(e,t,r)=>{"use strict";r.d(t,{gk:()=>l,m5:()=>u});var n=r(5230),s=r(4785),a=r(9056);var i=r(6232);const o=Symbol.for("lc:context_variables");class c{constructor(e,t,r){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}),this.metadata=e,this.tags=t,this.project_name=r}static fromHeader(e){const t=e.split(",");let r,n={},s=[];for(const e of t){const[t,a]=e.split("="),i=decodeURIComponent(a);"langsmith-metadata"===t?n=JSON.parse(i):"langsmith-tags"===t?s=i.split(","):"langsmith-project"===t&&(r=i)}return new c(n,s,r)}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 l{constructor(e){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,"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}),u(e))return void Object.assign(this,{...e});const t=l.getDefaultConfig(),{metadata:r,...n}=e,s=n.client??l.getSharedClient(),a={...r,...n?.extra?.metadata};if(n.extra={...n.extra,metadata:a},Object.assign(this,{...t,...n,client:s}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const e=function(e,t,r=1){const n=r.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(e).toISOString().slice(0,-1)}${n}Z`.replace(/[-:.]/g,"")+t}(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+e:this.dotted_order=e}}static getDefaultConfig(){return{id:n.A(),run_type:"chain",project_name:(0,s.Jz)("PROJECT")??(0,s.Az)("LANGCHAIN_SESSION")??"default",child_runs:[],api_url:(0,s.Az)("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:(0,s.Az)("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return l.sharedClient||(l.sharedClient=new a.Kj),l.sharedClient}createChild(e){const t=this.child_execution_order+1,r=new l({...e,parent_run:this,project_name:this.project_name,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t});o in this&&(r[o]=this[o]);const n=Symbol.for("lc:child_config"),s=e.extra?.[n]??this.extra[n];if(void 0!==(a=s)&&"object"==typeof a.callbacks&&(h(a.callbacks?.handlers)||h(a.callbacks))){const e={...s},t=function(e){return"object"==typeof e&&null!=e&&Array.isArray(e.handlers)}(e.callbacks)?e.callbacks.copy?.():void 0;t&&(Object.assign(t,{_parentRunId:r.id}),t.handlers?.find(d)?.updateFromRunTree?.(r),e.callbacks=t),r.extra[n]=e}var a;const i=new Set;let c=this;for(;null!=c&&!i.has(c.id);)i.add(c.id),c.child_execution_order=Math.max(c.child_execution_order,t),c=c.parent_run;return this.child_runs.push(r),r}async end(e,t,r=Date.now(),n){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??r,n&&Object.keys(n).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...n}}:{metadata:n})}_convertToCreate(e,t,r=!0){const n=e.extra??{};if(n.runtime||(n.runtime={}),t)for(const[e,r]of Object.entries(t))n.runtime[e]||(n.runtime[e]=r);let s,a;r?(a=e.parent_run?.id,s=[]):(s=e.child_runs.map((e=>this._convertToCreate(e,t,r))),a=void 0);return{id:e.id,name:e.name,start_time:e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:n,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:s,parent_run_id:a,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments}}async postRun(e=!0){try{const t=(0,s.Ec)(),r=await this._convertToCreate(this,t,!0);if(await this.client.createRun(r),!e){(0,i.m)("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const e of this.child_runs)await e.postRun(!1)}}catch(e){console.error(`Error in postRun for run ${this.id}:`,e)}}async patchRun(){try{const e={end_time:this.end_time,error:this.error,inputs:this.inputs,outputs:this.outputs,parent_run_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};await this.client.updateRun(this.id,e)}catch(e){console.error(`Error in patchRun for run ${this.id}`,e)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),"string"==typeof e?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){const r=e?.callbacks;let n,a,i,o=(e=>void 0!==e?e:!!["TRACING_V2","TRACING"].find((e=>"true"===(0,s.Jz)(e))))();if(r){const e=r?.getParentRunId?.()??"",t=r?.handlers?.find((e=>"langchain_tracer"==e?.name));n=t?.getRun?.(e),a=t?.projectName,i=t?.client,o=o||!!t}if(!n)return new l({...t,client:i,tracingEnabled:o,project_name:a});return new l({name:n.name,id:n.id,trace_id:n.trace_id,dotted_order:n.dotted_order,client:i,tracingEnabled:o,project_name:a,tags:[...new Set((n?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...n?.extra?.metadata,...e?.metadata}}}).createChild(t)}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){const r="get"in e&&"function"==typeof e.get?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,n=r["langsmith-trace"];if(!n||"string"!=typeof n)return;const s=n.trim(),a=s.split(".").map((e=>{const[t,r]=e.split("Z");return{strTime:t,time:Date.parse(t+"Z"),uuid:r}})),i=a[0].uuid,o={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:a.at(-1)?.uuid,trace_id:i,dotted_order:s};if(r.baggage&&"string"==typeof r.baggage){const e=c.fromHeader(r.baggage);o.metadata=e.metadata,o.tags=e.tags,o.project_name=e.project_name}return new l(o)}toHeaders(e){const t={"langsmith-trace":this.dotted_order,baggage:new c(this.extra?.metadata,this.tags,this.project_name).toHeader()};if(e)for(const[r,n]of Object.entries(t))e.set(r,n);return t}}function u(e){return void 0!==e&&"function"==typeof e.createChild&&"function"==typeof e.postRun}function d(e){return"object"==typeof e&&null!=e&&"string"==typeof e.name&&"langchain_tracer"===e.name}function h(e){return Array.isArray(e)&&e.some((e=>d(e)))}Object.defineProperty(l,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null})},3290:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(228),s=r(6641),a=r(4774),i=()=>{},o=new s.TimeoutError;t.default=class extends n{constructor(e){var t,r,n,s;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=i,this._resolveIdle=i,!("number"==typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:a.default},e)).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(r=null===(t=e.intervalCap)||void 0===t?void 0:t.toString())&&void 0!==r?r:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(s=null===(n=e.interval)||void 0===n?void 0:n.toString())&&void 0!==s?s:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=!0===e.throwOnTimeout,this._isPaused=!1===e.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount{this._onResumeInterval()}),t)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const t=this._queue.dequeue();return!!t&&(this.emit("active"),t(),e&&this._initializeIntervalIfNeeded(),!0)}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval((()=>{this._onInterval()}),this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&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(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise(((r,n)=>{this._queue.enqueue((async()=>{this._pendingCount++,this._intervalCount++;try{const a=void 0===this._timeout&&void 0===t.timeout?e():s.default(Promise.resolve(e()),void 0===t.timeout?this._timeout:t.timeout,(()=>{(void 0===t.throwOnTimeout?this._throwOnTimeout:t.throwOnTimeout)&&n(o)}));r(await a)}catch(e){n(e)}this._next()}),t),this._tryToStartAnother(),this.emit("add")}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise((e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}}))}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise((e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}}))}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}},3313:(e,t,r)=>{"use strict";r.d(t,{YN:()=>O,B2:()=>z,fJ:()=>A,Vi:()=>I,jY:()=>$,ck:()=>j,Pq:()=>L,Fm:()=>U,AO:()=>M,zZ:()=>R,pG:()=>B,lH:()=>F,GH:()=>P,Bp:()=>D});var n=r(4476),s=r(4116),a=r(9120),i=r(3389),o=r(1060),c=r(1590),l=r(58),u=r(7765),d=r(8028);function h({name:e,serialized:t}){return void 0!==e?e:void 0!==t?.name?t.name:void 0!==t?.id&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}const p=e=>"event_stream_tracer"===e.name;class m extends c.BaseTracer{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?.autoClose??!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,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=l.IterableReadableStream.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=e.tags??[];let r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.runType)),void 0!==this.includeTags&&(r=r||void 0!==t.find((e=>this.includeTags?.includes(e)))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.runType)),void 0!==this.excludeTags&&(r=r&&t.every((e=>!this.excludeTags?.includes(e)))),r}async*tapOutputIterable(e,t){const r=await t.next();if(r.done)return;const n=this.runInfoMap.get(e);if(void 0===n)return void(yield r.value);function s(e,t){return"llm"===e&&"string"==typeof t?new d.GenerationChunk({text:t}):t}let a=this.tappedPromises.get(e);if(void 0===a){let i;a=new Promise((e=>{i=e})),this.tappedPromises.set(e,a);try{const a={event:`on_${n.runType}_stream`,run_id:e,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};await this.send({...a,data:{chunk:s(n.runType,r.value)}},n),yield r.value;for await(const e of t)"tool"!==n.runType&&"retriever"!==n.runType&&await this.send({...a,data:{chunk:s(n.runType,e)}},n),yield e}finally{i()}}else{yield r.value;for await(const e of t)yield e}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const r=this.tappedPromises.get(e.run_id);void 0!==r?r.then((()=>{this.send(e,t)})):await this.send(e,t)}async onLLMStart(e){const t=h(e),r=void 0!==e.inputs.messages?"chat_model":"llm",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,n);const s=`on_${r}_start`;await this.send({event:s,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onLLMNewToken(e,t,r){const n=this.runInfoMap.get(e.id);let s,a;if(void 0===n)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(1!==this.runInfoMap.size){if("chat_model"===n.runType)a="on_chat_model_stream",s=void 0===r?.chunk?new u.H({content:t,id:`run-${e.id}`}):r.chunk.message;else{if("llm"!==n.runType)throw new Error(`Unexpected run type ${n.runType}`);a="on_llm_stream",s=void 0===r?.chunk?new d.GenerationChunk({text:t}):r.chunk}await this.send({event:a,data:{chunk:s},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(e){const t=this.runInfoMap.get(e.id);let r;if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const n=e.outputs?.generations;let s;if("chat_model"===t.runType){for(const e of n??[]){if(void 0!==s)break;s=e[0]?.message}r="on_chat_model_end"}else{if("llm"!==t.runType)throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);s={generations:n?.map((e=>e.map((e=>({text:e.text,generationInfo:e.generationInfo}))))),llmOutput:e.outputs?.llmOutput??{}},r="on_llm_end"}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){const t=h(e),r=e.run_type??"chain",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type};let s={};""===e.inputs.input&&1===Object.keys(e.inputs).length?(s={},n.inputs={}):void 0!==e.inputs.input?(s.input=e.inputs.input,n.inputs=e.inputs.input):(s.input=e.inputs,n.inputs=e.inputs),this.runInfoMap.set(e.id,n),await this.send({event:`on_${r}_start`,data:s,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onChainEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const r=`on_${e.run_type}_end`,n=e.inputs??t.inputs??{},s={output:e.outputs?.output??e.outputs,input:n};n.input&&1===Object.keys(n).length&&(s.input=n.input,t.inputs=n.input),await this.sendEndEvent({event:r,data:s,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=h(e),r={tags:e.tags??[],metadata:e.extra?.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:e.extra?.metadata??{}},r)}async onToolEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const r=void 0===e.outputs?.output?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){const t=h(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onRetrieverEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.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 n=this.runInfoMap.get(r);if(void 0===n)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:n.tags,metadata:n.metadata,data:t},n)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally((()=>{this.writer.close()}))}}var f=r(7380),g=r(9830),y=r(765),b=r(9624);class w extends c.BaseTracer{constructor({config:e,onStart:t,onEnd:r,onError:n}){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=n}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))}}var v=r(4850),_=r(4350),k=r(9137);function S(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.iterator]&&"function"==typeof e.next}function E(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.asyncIterator]}function*x(e,t){for(;;){const{value:r,done:n}=_.Nx.runWithConfig((0,y.DY)(e),t.next.bind(t),!0);if(n)break;yield r}}async function*T(e,t){const r=t[Symbol.asyncIterator]();for(;;){const{value:n,done:s}=await _.Nx.runWithConfig((0,y.DY)(e),r.next.bind(t),!0);if(s)break;yield n}}var C=r(199);function P(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}class O extends f.Serializable{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 A({bound:this,kwargs:e,config:{}})}map(){return new I({bound:this})}withRetry(e){return new M({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new A({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new F({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(y.ZI);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((([e])=>"runId"!==e)));return Array.from({length:t},((t,n)=>(0,y.ZI)(0===n?e:r)))}return Array.from({length:t},(()=>(0,y.ZI)(e)))}async batch(e,t,r){const n=this._getOptionsList(t??{},e.length),s=n[0]?.maxConcurrency??r?.maxConcurrency,a=new b.AsyncCaller({maxConcurrency:s,onFailedAttempt:e=>{throw e}}),i=e.map(((e,t)=>a.call((async()=>{try{return await this.invoke(e,n[t])}catch(e){if(r?.returnExceptions)return e;throw e}}))));return Promise.all(i)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const r=(0,y.ZI)(t),n=new l.AsyncGeneratorWithSetup({generator:this._streamIterator(e,r),config:r});return await n.setup,l.IterableReadableStream.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(e){let t;t=void 0===e?(0,y.ZI)(e):(0,y.ZI)({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 n=(0,y.ZI)(r),s=await(0,y.kJ)(n),a=await(s?.handleChainStart(this.toJSON(),P(t,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName()));let i;delete n.runId;try{const s=e.call(this,t,n,a);i=await(0,g.o)(s,r?.signal)}catch(e){throw await(a?.handleChainError(e)),e}return await(a?.handleChainEnd(P(i,"output"))),i}async _batchWithConfig(e,t,r,n){const s=this._getOptionsList(r??{},t.length),a=await Promise.all(s.map(y.kJ)),i=await Promise.all(a.map((async(e,r)=>{const n=await(e?.handleChainStart(this.toJSON(),P(t[r],"input"),s[r].runId,s[r].runType,void 0,void 0,s[r].runName??this.getName()));return delete s[r].runId,n})));let o;try{const r=e.call(this,t,s,i,n);o=await(0,g.o)(r,s?.[0]?.signal)}catch(e){throw await Promise.all(i.map((t=>t?.handleChainError(e)))),e}return await Promise.all(i.map((e=>e?.handleChainEnd(P(o,"output"))))),o}async*_transformStreamWithConfig(e,t,r){let n,s,a=!0,i=!0;const c=(0,y.ZI)(r),u=await(0,y.kJ)(c);let d;try{const h=await(0,l.pipeGeneratorWithSetup)(t.bind(this),async function*(){for await(const t of e){if(a)if(void 0===n)n=t;else try{n=(0,l.concat)(n,t)}catch{n=void 0,a=!1}yield t}}(),(async()=>u?.handleChainStart(this.toJSON(),{input:""},c.runId,c.runType,void 0,void 0,c.runName??this.getName())),r?.signal,c);delete c.runId,d=h.setup;const m=d?.handlers.find(p);let f=h.output;void 0!==m&&void 0!==d&&(f=m.tapOutputIterable(d.runId,f));const g=d?.handlers.find(o.isLogStreamHandler);void 0!==g&&void 0!==d&&(f=g.tapOutputIterable(d.runId,f));for await(const e of f)if(yield e,i)if(void 0===s)s=e;else try{s=(0,l.concat)(s,e)}catch{s=void 0,i=!1}}catch(e){throw await(d?.handleChainError(e,void 0,void 0,void 0,{inputs:P(n,"input")})),e}await(d?.handleChainEnd(s??{},void 0,void 0,void 0,{inputs:P(n,"input")}))}getGraph(e){const t=new k.T,r=t.addNode({name:`${this.getName()}Input`,schema:n.z.any()}),s=t.addNode(this),a=t.addNode({name:`${this.getName()}Output`,schema:n.z.any()});return t.addEdge(r,s),t.addEdge(s,a),t}pipe(e){return new R({first:this,last:D(e)})}pick(e){return this.pipe(new U(e))}assign(e){return this.pipe(new z(new j({steps:e})))}async*transform(e,t){let r;for await(const t of e)r=void 0===r?t:(0,l.concat)(r,t);yield*this._streamIterator(r,(0,y.ZI)(t))}async*streamLog(e,t,r){const n=new o.LogStreamCallbackHandler({...r,autoClose:!1,_schemaFormat:"original"}),s=(0,y.ZI)(t);yield*this._streamLog(e,n,s)}async*_streamLog(e,t,r){const{callbacks:n}=r;if(void 0===n)r.callbacks=[t];else if(Array.isArray(n))r.callbacks=n.concat([t]);else{const e=n.copy();e.addHandler(t,!0),r.callbacks=e}const s=this.stream(e,r);const a=async function(){try{const e=await s;for await(const r of e){const e=new o.RunLogPatch({ops:[{op:"add",path:"/streamed_output/-",value:r}]});await t.writer.write(e)}}finally{await t.writer.close()}}();try{for await(const e of t)yield e}finally{await a}}streamEvents(e,t,r){let n;if("v1"===t.version)n=this._streamEventsV1(e,t,r);else{if("v2"!==t.version)throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');n=this._streamEventsV2(e,t,r)}return"text/event-stream"===t.encoding?function(e){const t=new TextEncoder,r=new ReadableStream({async start(r){for await(const n of e)r.enqueue(t.encode(`event: data\ndata: ${JSON.stringify(n)}\n\n`));r.enqueue(t.encode("event: end\n\n")),r.close()}});return l.IterableReadableStream.fromReadableStream(r)}(n):l.IterableReadableStream.fromAsyncGenerator(n)}async*_streamEventsV2(e,t,r){const n=new m({...r,autoClose:!1}),s=(0,y.ZI)(t),i=s.runId??(0,a.A)();s.runId=i;const o=s.callbacks;if(void 0===o)s.callbacks=[n];else if(Array.isArray(o))s.callbacks=o.concat(n);else{const e=o.copy();e.addHandler(n,!0),s.callbacks=e}const c=new AbortController,l=this;const u=async function(){try{let r;t?.signal?"any"in AbortSignal?r=AbortSignal.any([c.signal,t.signal]):(r=t.signal,t.signal.addEventListener("abort",(()=>{c.abort()}),{once:!0})):r=c.signal;const a=await l.stream(e,{...s,signal:r}),o=n.tapOutputIterable(i,a);for await(const e of o)if(c.signal.aborted)break}finally{await n.finish()}}();let d,h=!1;try{for await(const t of n)h?(t.run_id===d&&t.event.endsWith("_end")&&t.data?.input&&delete t.data.input,yield t):(t.data.input=e,h=!0,d=t.run_id,yield t)}finally{c.abort(),await u}}async*_streamEventsV1(e,t,r){let n,s=!1;const a=(0,y.ZI)(t),i=a.tags??[],c=a.metadata??{},l=a.runName??this.getName(),u=new o.LogStreamCallbackHandler({...r,autoClose:!1,_schemaFormat:"streaming_events"}),d=new v.G({...r}),h=this._streamLog(e,u,a);for await(const t of h){if(n=n?n.concat(t):o.RunLog.fromRunLogPatch(t),void 0===n.state)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!s){s=!0;const t={...n.state},r={run_id:t.id,event:`on_${t.type}_start`,name:l,tags:i,metadata:c,data:{input:e}};d.includeEvent(r,t.type)&&(yield r)}const r=t.ops.filter((e=>e.path.startsWith("/logs/"))).map((e=>e.path.split("/")[2])),a=[...new Set(r)];for(const e of a){let t,r={};const s=n.state.logs[e];if(t=void 0===s.end_time?s.streamed_output.length>0?"stream":"start":"end","start"===t)void 0!==s.inputs&&(r.input=s.inputs);else if("end"===t)void 0!==s.inputs&&(r.input=s.inputs),r.output=s.final_output;else if("stream"===t){const e=s.streamed_output.length;if(1!==e)throw new Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${s.name}"`);r={chunk:s.streamed_output[0]},s.streamed_output=[]}yield{event:`on_${s.type}_${t}`,name:s.name,run_id:s.id,tags:s.tags,metadata:s.metadata,data:r}}const{state:u}=n;if(u.streamed_output.length>0){const e=u.streamed_output.length;if(1!==e)throw new Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${u.name}"`);const t={chunk:u.streamed_output[0]};u.streamed_output=[];const r={event:`on_${u.type}_stream`,run_id:u.id,tags:i,metadata:c,name:l,data:t};d.includeEvent(r,u.type)&&(yield r)}}const p=n?.state;if(void 0!==p){const e={event:`on_${p.type}_end`,name:l,run_id:p.id,tags:i,metadata:c,data:{output:p.final_output}};d.includeEvent(e,p.type)&&(yield e)}}static isRunnable(e){return(0,v.T)(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new A({bound:this,config:{},configFactories:[n=>({callbacks:[new w({config:n,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return function(e,t){const r=t.name??e.getName(),s=t.description??t.schema?.description;if(t.schema.constructor===n.z.ZodString)return new B({name:r,description:s,schema:n.z.object({input:n.z.string()}).transform((e=>e.input)),bound:e});return new B({name:r,description:s,schema:t.schema,bound:e})}(this,e)}}class A extends O{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=(0,y.SV)(this.config,...e);return(0,y.SV)(t,...this.configFactories?await Promise.all(this.configFactories.map((async e=>await e(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 this.constructor({bound:this.bound.withRetry(e),kwargs:this.kwargs,config:this.config})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig((0,y.ZI)(t),this.kwargs))}async batch(e,t,r){const n=Array.isArray(t)?await Promise.all(t.map((async e=>this._mergeConfig((0,y.ZI)(e),this.kwargs)))):await this._mergeConfig((0,y.ZI)(t),this.kwargs);return this.bound.batch(e,n,r)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig((0,y.ZI)(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig((0,y.ZI)(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig((0,y.ZI)(t),this.kwargs))}streamEvents(e,t,r){const n=this;return l.IterableReadableStream.fromAsyncGenerator(async function*(){yield*n.bound.streamEvents(e,{...await n._mergeConfig((0,y.ZI)(t),n.kwargs),version:t.version},r)}())}static isRunnableBinding(e){return e.bound&&O.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:r}){return new A({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[n=>({callbacks:[new w({config:n,onStart:e,onEnd:t,onError:r})]})]})}}class I extends O{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 I({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,(0,y.tn)(t,{callbacks:r?.getChild()}))}withListeners({onStart:e,onEnd:t,onError:r}){return new I({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:r})})}}class M extends A{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 n=e>1?`retry:attempt:${e}`:void 0;return(0,y.tn)(t,{callbacks:r?.getChild(n)})}async _invoke(e,t,r){return s((n=>super.invoke(e,this._patchConfigForRetry(n,t,r))),{onFailedAttempt:t=>this.onFailedAttempt(t,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,n){const a={};try{await s((async s=>{const i=e.map(((e,t)=>t)).filter((e=>void 0===a[e.toString()]||a[e.toString()]instanceof Error)),o=i.map((t=>e[t])),c=i.map((e=>this._patchConfigForRetry(s,t?.[e],r?.[e]))),l=await super.batch(o,c,{...n,returnExceptions:!0});let u;for(let e=0;ethis.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(!0!==n?.returnExceptions)throw e}return Object.keys(a).sort(((e,t)=>parseInt(e,10)-parseInt(t,10))).map((e=>a[parseInt(e,10)]))}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}}class R extends O{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){const r=(0,y.ZI)(t),n=await(0,y.kJ)(r),s=await(n?.handleChainStart(this.toJSON(),P(e,"input"),r.runId,void 0,void 0,void 0,r?.runName));delete r.runId;let a,i=e;try{const e=[this.first,...this.middle];for(let n=0;n{const s=await(t?.handleChainStart(this.toJSON(),P(e[r],"input"),n[r].runId,void 0,void 0,void 0,n[r].runName));return delete n[r].runId,s})));let i=e;try{for(let e=0;e{const s=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return(0,y.tn)(n[r],{callbacks:s})})),r);i=await(0,g.o)(t,n[0]?.signal)}}catch(e){throw await Promise.all(a.map((t=>t?.handleChainError(e)))),e}return await Promise.all(a.map((e=>e?.handleChainEnd(P(i,"output"))))),i}async*_streamIterator(e,t){const r=await(0,y.kJ)(t),{runId:n,...s}=t??{},a=await(r?.handleChainStart(this.toJSON(),P(e,"input"),n,void 0,void 0,void 0,s?.runName)),i=[this.first,...this.middle,this.last];let o,c=!0;try{let r=i[0].transform(async function*(){yield e}(),(0,y.tn)(s,{callbacks:a?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let e=1;e{const a=n.getGraph(e);0!==s&&a.trimFirstNode(),s!==this.steps.length-1&&a.trimLastNode(),t.extend(a);const i=a.firstNode();if(!i)throw new Error(`Runnable ${n} has no first node`);r&&t.addEdge(r,i),r=a.lastNode()})),t}pipe(e){return R.isRunnableSequence(e)?new R({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new R({first:this.first,middle:[...this.middle,this.last],last:D(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&O.isRunnable(e)}static from([e,...t],r){let n={};return"string"==typeof r?n.name=r:void 0!==r&&(n=r),new R({...n,first:D(e),middle:t.slice(0,-1).map(D),last:D(t[t.length-1])})}}class j extends O{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]=D(r)}static from(e){return new j({steps:e})}async invoke(e,t){const r=(0,y.ZI)(t),n=await(0,y.kJ)(r),s=await(n?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName));delete r.runId;const a={};try{const n=Object.entries(this.steps).map((async([t,n])=>{a[t]=await n.invoke(e,(0,y.tn)(r,{callbacks:s?.getChild(`map:key:${t}`)}))}));await(0,g.o)(Promise.all(n),t?.signal)}catch(e){throw await(s?.handleChainError(e)),e}return await(s?.handleChainEnd(a)),a}async*_transform(e,t,r){const n={...this.steps},s=(0,l.atee)(e,Object.keys(n).length),a=new Map(Object.entries(n).map((([e,n],a)=>{const i=n.transform(s[a],(0,y.tn)(r,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,i.next().then((t=>({key:e,gen:i,result:t})))]})));for(;a.size;){const e=Promise.race(a.values()),{key:t,result:n,gen:s}=await(0,g.o)(e,r?.signal);a.delete(t),n.done||(yield{[t]:n.value},a.set(t,s.next().then((e=>({key:t,gen:s,result:e})))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=(0,y.ZI)(t),n=new l.AsyncGeneratorWithSetup({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,l.IterableReadableStream.fromAsyncGenerator(n)}}class N extends O{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}),!(0,i.GZ)(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),n=await(0,y.kJ)(r),s=this.func((0,y.tn)(r,{callbacks:n}),e);return(0,g.o)(s,r?.signal)}async*_streamIterator(e,t){const[r]=this._getOptionsList(t??{},1),n=await this.invoke(e,t);var s;if(E(n))for await(const e of n)r?.signal?.throwIfAborted(),yield e;else if(null!=(s=n)&&"object"==typeof s&&"next"in s&&"function"==typeof s.next)for(;;){r?.signal?.throwIfAborted();const e=n.next();if(e.done)break;yield e.value}else yield n}static from(e){return new N({func:e})}}class $ extends O{static lc_name(){return"RunnableLambda"}constructor(e){if((0,i.GZ)(e.func))return N.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}),function(e){if((0,i.GZ)(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}(e.func),this.func=e.func}static from(e){return new $({func:e})}async _invoke(e,t,r){return new Promise(((n,s)=>{const a=(0,y.tn)(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??y.p_)-1});_.Nx.runWithConfig((0,y.DY)(a),(async()=>{try{let r=await this.func(e,{...a});if(r&&O.isRunnable(r)){if(0===t?.recursionLimit)throw new Error("Recursion limit reached.");r=await r.invoke(e,{...a,recursionLimit:(a.recursionLimit??y.p_)-1})}else if(E(r)){let e;for await(const n of T(a,r))if(t?.signal?.throwIfAborted(),void 0===e)e=n;else try{e=(0,l.concat)(e,n)}catch(t){e=n}r=e}else if(S(r)){let e;for(const n of x(a,r))if(t?.signal?.throwIfAborted(),void 0===e)e=n;else try{e=(0,l.concat)(e,n)}catch(t){e=n}r=e}n(r)}catch(e){s(e)}}))}))}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,r){let n;for await(const t of e)if(void 0===n)n=t;else try{n=(0,l.concat)(n,t)}catch(e){n=t}const s=(0,y.tn)(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??y.p_)-1}),a=await new Promise(((e,t)=>{_.Nx.runWithConfig((0,y.DY)(s),(async()=>{try{const t=await this.func(n,{...s,config:s});e(t)}catch(e){t(e)}}))}));if(a&&O.isRunnable(a)){if(0===r?.recursionLimit)throw new Error("Recursion limit reached.");const e=await a.stream(n,s);for await(const t of e)yield t}else if(E(a))for await(const e of T(s,a))r?.signal?.throwIfAborted(),yield e;else if(S(a))for(const e of x(s,a))r?.signal?.throwIfAborted(),yield e;else yield a}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=(0,y.ZI)(t),n=new l.AsyncGeneratorWithSetup({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,l.IterableReadableStream.fromAsyncGenerator(n)}}class L extends j{}class F extends O{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=(0,y.ZI)(t),n=await(0,y.kJ)(r),{runId:s,...a}=r,i=await(n?.handleChainStart(this.toJSON(),P(e,"input"),s,void 0,void 0,void 0,a?.runName)),o=(0,y.tn)(a,{callbacks:i?.getChild()});return await _.Nx.runWithConfig(o,(async()=>{let t;for(const n of this.runnables()){r?.signal?.throwIfAborted();try{const t=await n.invoke(e,o);return await(i?.handleChainEnd(P(t,"output"))),t}catch(e){void 0===t&&(t=e)}}if(void 0===t)throw new Error("No error stored at end of fallback.");throw await(i?.handleChainError(t)),t}))}async*_streamIterator(e,t){const r=(0,y.ZI)(t),n=await(0,y.kJ)(r),{runId:s,...a}=r,i=await(n?.handleChainStart(this.toJSON(),P(e,"input"),s,void 0,void 0,void 0,a?.runName));let o,c,u;for(const t of this.runnables()){r?.signal?.throwIfAborted();const n=(0,y.tn)(a,{callbacks:i?.getChild()});try{c=T(n,await t.stream(e,n));break}catch(e){void 0===o&&(o=e)}}if(void 0===c){const e=o??new Error("No error stored at end of fallback.");throw await(i?.handleChainError(e)),e}try{for await(const e of c){yield e;try{u=void 0===u?u:(0,l.concat)(u,e)}catch(e){u=void 0}}}catch(e){throw await(i?.handleChainError(e)),e}await(i?.handleChainEnd(P(u,"output")))}async batch(e,t,r){if(r?.returnExceptions)throw new Error("Not implemented.");const n=this._getOptionsList(t??{},e.length),s=await Promise.all(n.map((e=>(0,y.kJ)(e)))),a=await Promise.all(s.map((async(t,r)=>{const s=await(t?.handleChainStart(this.toJSON(),P(e[r],"input"),n[r].runId,void 0,void 0,void 0,n[r].runName));return delete n[r].runId,s})));let i;for(const t of this.runnables()){n[0].signal?.throwIfAborted();try{const s=await t.batch(e,a.map(((e,t)=>(0,y.tn)(n[t],{callbacks:e?.getChild()}))),r);return await Promise.all(a.map(((e,t)=>e?.handleChainEnd(P(s[t],"output"))))),s}catch(e){void 0===i&&(i=e)}}if(!i)throw new Error("No error stored at end of fallbacks.");throw await Promise.all(a.map((e=>e?.handleChainError(i)))),i}}function D(e){if("function"==typeof e)return new $({func:e});if(O.isRunnable(e))return e;if(Array.isArray(e)||"object"!=typeof e)throw new Error("Expected a Runnable, function or object.\nInstead got an unsupported type.");{const t={};for(const[r,n]of Object.entries(e))t[r]=D(n);return new j({steps:t})}}class z extends O{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof j&&(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 n=this.mapper.getStepsKeys(),[s,a]=(0,l.atee)(e),i=this.mapper.transform(a,(0,y.tn)(r,{callbacks:t?.getChild()})),o=i.next();for await(const e of s){if("object"!=typeof e||Array.isArray(e))throw new Error("RunnableAssign can only be used with objects as input, got "+typeof e);const t=Object.fromEntries(Object.entries(e).filter((([e])=>!n.includes(e))));Object.keys(t).length>0&&(yield t)}yield(await o).value;for await(const e of i)yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=(0,y.ZI)(t),n=new l.AsyncGeneratorWithSetup({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,l.IterableReadableStream.fromAsyncGenerator(n)}}class U extends O{static lc_name(){return"RunnablePick"}constructor(e){("string"==typeof e||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("string"==typeof this.keys)return e[this.keys];{const t=this.keys.map((t=>[t,e[t]])).filter((e=>void 0!==e[1]));return 0===t.length?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 e=await this._pick(t);void 0!==e&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=(0,y.ZI)(t),n=new l.AsyncGeneratorWithSetup({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,l.IterableReadableStream.fromAsyncGenerator(n)}}class B extends A{constructor(e){super({bound:R.from([$.from((async e=>{let t;if((0,C.Ky)(e))try{t=await this.schema.parseAsync(e.args)}catch(t){throw new C.qe("Received tool input did not match expected schema",JSON.stringify(e.args))}else t=e;return t})).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name}),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"}}},3389:(e,t,r)=>{"use strict";r.d(t,{vR:()=>o,GZ:()=>c});var n=r(3246);const s=Symbol.for("ls:tracing_async_local_storage"),a=new class{getStore(){}run(e,t){return t()}};const i=new class{getInstance(){return globalThis[s]??a}initializeGlobalInstance(e){void 0===globalThis[s]&&(globalThis[s]=e)}};function o(e=!1){const t=i.getInstance().getStore();if(!e&&!(0,n.m5)(t))throw new Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled.");return t}Symbol.for("langsmith:traceable:root");function c(e){return"function"==typeof e&&"langsmith:traceable"in e}},3490:(e,t,r)=>{"use strict";r.d(t,{AJ:()=>f,Ao:()=>c,F7:()=>d,Iv:()=>i,Vt:()=>u,XQ:()=>o,_I:()=>a,dp:()=>p,gj:()=>h,ns:()=>l,ny:()=>m});var n=r(7380),s=r(4291);function a(e,t){return"string"==typeof e?""===e?t:"string"==typeof t?e+t:Array.isArray(t)&&t.some((e=>(0,s.Fz)(e)))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?u(e,t)??[...e,...t]:""===t?e:Array.isArray(e)&&e.some((e=>(0,s.Fz)(e)))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}function i(e,t){return"error"===e||"error"===t?"error":"success"}class o extends n.Serializable{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){return"string"==typeof this.content?this.content:Array.isArray(this.content)?this.content.map((e=>"string"==typeof e?e:"text"===e.type?e.text:"")).join(""):""}getType(){return this._getType()}constructor(e,t){"string"==typeof e&&(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(null===e)return this;const t=(r=this._printableFields,n=Math.max(4,e),JSON.stringify(function e(t,r){if("object"!=typeof t||null==t)return t;if(r>=n)return Array.isArray(t)?"[Array]":"[Object]";if(Array.isArray(t))return t.map((t=>e(t,r+1)));const s={};for(const n of Object.keys(t))s[n]=e(t[n],r+1);return s}(r,0),null,2));var r,n;return`${this.constructor.lc_name()} ${t}`}}function c(e){return Array.isArray(e)&&e.every((e=>"number"==typeof e.index))}function l(e,t){const r={...e};for(const[e,n]of Object.entries(t))if(null==r[e])r[e]=n;else{if(null==n)continue;if(typeof r[e]!=typeof n||Array.isArray(r[e])!==Array.isArray(n))throw new Error(`field[${e}] already exists in the message chunk, but with a different type.`);if("string"==typeof r[e]){if("type"===e)continue;r[e]+=n}else if("object"!=typeof r[e]||Array.isArray(r[e]))if(Array.isArray(r[e]))r[e]=u(r[e],n);else{if(r[e]===n)continue;console.warn(`field[${e}] already exists in this message chunk and value has unsupported type.`)}else r[e]=l(r[e],n)}return r}function u(e,t){if(void 0!==e||void 0!==t){if(void 0===e||void 0===t)return e||t;{const r=[...e];for(const e of t)if("object"==typeof e&&"index"in e&&"number"==typeof e.index){const t=r.findIndex((t=>t.index===e.index));-1!==t?r[t]=l(r[t],e):r.push(e)}else{if("object"==typeof e&&"text"in e&&""===e.text)continue;r.push(e)}return r}}}function d(e,t){if(!e&&!t)throw new Error("Cannot merge two undefined objects.");if(e&&t){if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types.\nLeft ${typeof e}\nRight ${typeof t}`);if("string"==typeof e&&"string"==typeof t)return e+t;if(Array.isArray(e)&&Array.isArray(t))return u(e,t);if("object"==typeof e&&"object"==typeof t)return l(e,t);if(e===t)return e;throw new Error(`Can not merge objects of different types.\nLeft ${e}\nRight ${t}`)}return e||t}class h extends o{}function p(e){return"string"==typeof e.role}function m(e){return"function"==typeof e?._getType}function f(e){return m(e)&&"function"==typeof e.concat}},3650:(e,t,r)=>{"use strict";r.d(t,{PromptTemplate:()=>a});var n=r(329),s=r(9849);class a extends n.L{static lc_name(){return"PromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),"mustache"===e.templateFormat&&void 0===e.validateTemplate&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){if("mustache"===this.templateFormat)throw new Error("Mustache templates cannot be validated.");let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),(0,s.Ns)(this.template,this.templateFormat,e)}}_getPromptType(){return"prompt"}async format(e){const t=await this.mergePartialAndUserVariables(e);return(0,s.Xm)(this.template,this.templateFormat,t)}static fromExamples(e,t,r,n="\n\n",s=""){const i=[s,...e,t].join(n);return new a({inputVariables:r,template:i})}static fromTemplate(e,t){const{templateFormat:r="f-string",...n}=t??{},i=new Set;return(0,s.QC)(e,r).forEach((e=>{"variable"===e.type&&i.add(e.name)})),new a({inputVariables:[...i],templateFormat:r,template:e,...n})}async partial(e){const t=this.inputVariables.filter((t=>!(t in e))),r={...this.partialVariables??{},...e},n={...this,inputVariables:t,partialVariables:r};return new a(n)}serialize(){if(void 0!==this.outputParser)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(e){if(!e.template)throw new Error("Prompt template must have a template");return new a({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}}},3766:(e,t,r)=>{"use strict";r.d(t,{BJ:()=>k,FS:()=>v,GL:()=>m,OT:()=>f,RZ:()=>E,Wn:()=>y,pl:()=>p,qF:()=>g,sS:()=>_});var n=r(1673),s=r(5311),a=r(3313),i=r(329),o=r(6993),c=r(3650),l=r(6279),u=r(9849),d=r(1368),h=r(4552);class p extends a.YN{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","chat"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}async invoke(e,t){return this._callWithConfig((e=>this.formatMessages(e)),e,{...t,runType:"prompt"})}}class m extends p{static lc_name(){return"MessagesPlaceholder"}constructor(e){"string"==typeof e&&(e={variableName:e}),super(e),Object.defineProperty(this,"variableName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"optional",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.variableName=e.variableName,this.optional=e.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(e){const t=e[this.variableName];if(this.optional&&!t)return[];if(!t){const e=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw e.name="InputFormatError",e}let r;try{r=Array.isArray(t)?t.map(n.coerceMessageLikeToMessage):[(0,n.coerceMessageLikeToMessage)(t)]}catch(e){const r="string"==typeof t?t:JSON.stringify(t,null,2),n=new Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${r}`,`Additional message: ${e.message}`].join("\n\n"));throw n.name="InputFormatError",n.lc_error_code=e.lc_error_code,n}return r}}class f extends p{constructor(e){"prompt"in e||(e={prompt:e}),super(e),Object.defineProperty(this,"prompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}}class g extends o.m{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){const t=await this.formatMessages(e);return new s.ChatPromptValue(t)}}class y extends f{static lc_name(){return"ChatMessagePromptTemplate"}constructor(e,t){"prompt"in e||(e={prompt:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}async format(e){return new n.ChatMessage(await this.prompt.format(e),this.role)}static fromTemplate(e,t,r){return new this(c.PromptTemplate.fromTemplate(e,{templateFormat:r?.templateFormat}),t)}}function b(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)&&("image_url"in e&&("string"==typeof e.image_url||"object"==typeof e.image_url&&null!==e.image_url&&"url"in e.image_url&&"string"==typeof e.image_url.url))}class w extends p{static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}constructor(e,t){if("prompt"in e||(e={prompt:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","chat"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"additionalOptions",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"prompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"messageClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chatMessageClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.prompt=e.prompt,Array.isArray(this.prompt)){let e=[];this.prompt.forEach((t=>{"inputVariables"in t&&(e=e.concat(t.inputVariables))})),this.inputVariables=e}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=t??this.additionalOptions}createMessage(e){const t=this.constructor;if(t._messageClass()){return new(t._messageClass())({content:e})}if(t.chatMessageClass){const r=t.chatMessageClass();return new r({content:e,role:this.getRoleFromMessageClass(r.lc_name())})}throw new Error("No message class defined")}getRoleFromMessageClass(e){switch(e){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(e,t){if("string"==typeof e)return new this(c.PromptTemplate.fromTemplate(e,t));const r=[];for(const s of e)if("string"==typeof s)r.push(c.PromptTemplate.fromTemplate(s,t));else if(null===s);else if(null!==(n=s)&&"object"==typeof n&&!Array.isArray(n)&&1===Object.keys(n).length&&"text"in n&&"string"==typeof n.text){let e="";"string"==typeof s.text&&(e=s.text??"");const n={...t,additionalContentFields:s};r.push(c.PromptTemplate.fromTemplate(e,n))}else if(b(s)){let e,n=s.image_url??"",a=[];if("string"==typeof n){let r;r="mustache"===t?.templateFormat?(0,u.g2)(n):(0,u.D4)(n);const i=r.flatMap((e=>"variable"===e.type?[e.name]:[]));if((i?.length??0)>0){if(i.length>1)throw new Error(`Only one format variable allowed per image template.\nGot: ${i}\nFrom: ${n}`);a=[i[0]]}else a=[];n={url:n},e=new l.C({template:n,inputVariables:a,templateFormat:t?.templateFormat,additionalContentFields:s})}else{if("object"!=typeof n)throw new Error("Invalid image template");if("url"in n){let e;e="mustache"===t?.templateFormat?(0,u.g2)(n.url):(0,u.D4)(n.url),a=e.flatMap((e=>"variable"===e.type?[e.name]:[]))}else a=[];e=new l.C({template:n,inputVariables:a,templateFormat:t?.templateFormat,additionalContentFields:s})}r.push(e)}else"object"==typeof s&&r.push(new h.l({template:s,templateFormat:t?.templateFormat}));var n;return new this({prompt:r,additionalOptions:t})}async format(e){if(this.prompt instanceof i.L){const t=await this.prompt.format(e);return this.createMessage(t)}{const t=[];for(const r of this.prompt){let n={};if(!("inputVariables"in r))throw new Error(`Prompt ${r} does not have inputVariables defined.`);for(const t of r.inputVariables)n||(n={[t]:e[t]}),n={...n,[t]:e[t]};if(r instanceof i.L){const e=await r.format(n);let s;"additionalContentFields"in r&&(s=r.additionalContentFields),t.push({...s,type:"text",text:e})}else if(r instanceof l.C){const e=await r.format(n);let s;"additionalContentFields"in r&&(s=r.additionalContentFields),t.push({...s,type:"image_url",image_url:e})}else if(r instanceof h.l){const e=await r.format(n);let s;"additionalContentFields"in r&&(s=r.additionalContentFields),t.push({...s,...e})}}return this.createMessage(t)}}async formatMessages(e){return[await this.format(e)]}}class v extends w{static _messageClass(){return n.HumanMessage}static lc_name(){return"HumanMessagePromptTemplate"}}class _ extends w{static _messageClass(){return n.AIMessage}static lc_name(){return"AIMessagePromptTemplate"}}class k extends w{static _messageClass(){return n.SystemMessage}static lc_name(){return"SystemMessagePromptTemplate"}}function S(e,t){if("function"==typeof e.formatMessages||(0,n.isBaseMessage)(e))return e;if(Array.isArray(e)&&"placeholder"===e[0]){const r=e[1];if("mustache"===t?.templateFormat&&"string"==typeof r&&"{{"===r.slice(0,2)&&"}}"===r.slice(-2)){const e=r.slice(2,-2);return new m({variableName:e,optional:!0})}if("string"==typeof r&&"{"===r[0]&&"}"===r[r.length-1]){const e=r.slice(1,-1);return new m({variableName:e,optional:!0})}throw new Error(`Invalid placeholder template for format ${t?.templateFormat??'"f-string"'}: "${e[1]}". Expected a variable name surrounded by ${"mustache"===t?.templateFormat?"double":"single"} curly braces.`)}const r=(0,n.coerceMessageLikeToMessage)(e);let s;if(s="string"==typeof r.content?r.content:r.content.map((e=>"text"in e?{...e,text:e.text}:"image_url"in e?{...e,image_url:e.image_url}:e)),"human"===r._getType())return v.fromTemplate(s,t);if("ai"===r._getType())return _.fromTemplate(s,t);if("system"===r._getType())return k.fromTemplate(s,t);if(n.ChatMessage.isInstance(r))return y.fromTemplate(r.content,r.role,t);throw new Error(`Could not coerce message prompt template from input. Received message type: "${r._getType()}".`)}class E extends g{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}constructor(e){if(super(e),Object.defineProperty(this,"promptMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),"mustache"===e.templateFormat&&void 0===e.validateTemplate&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){const e=new Set;for(const t of this.promptMessages)if(!(t instanceof n.BaseMessage))for(const r of t.inputVariables)e.add(r);const t=this.inputVariables,r=new Set(this.partialVariables?t.concat(Object.keys(this.partialVariables)):t),s=new Set([...r].filter((t=>!e.has(t))));if(s.size>0)throw new Error(`Input variables \`${[...s]}\` are not used in any of the prompt messages.`);const a=new Set([...e].filter((e=>!r.has(e))));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(e,t){if("string"==typeof e.content)return e;const r=await Promise.all(e.content.map((async e=>{if("image_url"!==e.type)return e;let r="";r="string"==typeof e.image_url?e.image_url:e.image_url.url;const n=c.PromptTemplate.fromTemplate(r,{templateFormat:this.templateFormat}),s=await n.format(t);return"string"!=typeof e.image_url&&"url"in e.image_url?e.image_url.url=s:e.image_url=s,e})));return e.content=r,e}async formatMessages(e){const t=await this.mergePartialAndUserVariables(e);let r=[];for(const e of this.promptMessages)if(e instanceof n.BaseMessage)r.push(await this._parseImagePrompts(e,t));else{const n=e.inputVariables.reduce(((r,n)=>{if(!(n in t)&&("MessagesPlaceholder"!==e.constructor.lc_name()||!e.optional)){throw(0,d.Y)(new Error(`Missing value for input variable \`${n.toString()}\``),"INVALID_PROMPT_INPUT")}return r[n]=t[n],r}),{}),s=await e.formatMessages(n);r=r.concat(s)}return r}async partial(e){const t=this.inputVariables.filter((t=>!(t in e))),r={...this.partialVariables??{},...e},n={...this,inputVariables:t,partialVariables:r};return new E(n)}static fromTemplate(e,t){const r=c.PromptTemplate.fromTemplate(e,t),n=new v({prompt:r});return this.fromMessages([n])}static fromMessages(e,t){const r=e.reduce(((e,r)=>e.concat(r instanceof E?r.promptMessages:[S(r,t)])),[]),s=e.reduce(((e,t)=>t instanceof E?Object.assign(e,t.partialVariables):e),Object.create(null)),a=new Set;for(const e of r)if(!(e instanceof n.BaseMessage))for(const t of e.inputVariables)t in s||a.add(t);return new this({...t,inputVariables:[...a],promptMessages:r,partialVariables:s,templateFormat:t?.templateFormat})}static fromPromptMessages(e){return this.fromMessages(e)}}},3874:(e,t,r)=>{"use strict";const n=r(8311);e.exports=(e,t)=>{try{return new n(e,t).range||"*"}catch(e){return null}}},3904:(e,t,r)=>{"use strict";const n=Symbol("SemVer ANY");class s{static get ANY(){return n}constructor(e,t){if(t=a(t),e instanceof s){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),l("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===n?this.value="":this.value=this.operator+this.semver.version,l("comp",this)}parse(e){const t=this.options.loose?i[o.COMPARATORLOOSE]:i[o.COMPARATOR],r=e.match(t);if(!r)throw new TypeError(`Invalid comparator: ${e}`);this.operator=void 0!==r[1]?r[1]:"","="===this.operator&&(this.operator=""),r[2]?this.semver=new u(r[2],this.options.loose):this.semver=n}toString(){return this.value}test(e){if(l("Comparator.test",e,this.options.loose),this.semver===n||e===n)return!0;if("string"==typeof e)try{e=new u(e,this.options)}catch(e){return!1}return c(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof s))throw new TypeError("a Comparator is required");return""===this.operator?""===this.value||new d(e.value,t).test(this.value):""===e.operator?""===e.value||new d(this.value,t).test(e.semver):(!(t=a(t)).includePrerelease||"<0.0.0-0"!==this.value&&"<0.0.0-0"!==e.value)&&(!(!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0")))&&(!(!this.operator.startsWith(">")||!e.operator.startsWith(">"))||(!(!this.operator.startsWith("<")||!e.operator.startsWith("<"))||(!(this.semver.version!==e.semver.version||!this.operator.includes("=")||!e.operator.includes("="))||(!!(c(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<"))||!!(c(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))))))}}e.exports=s;const a=r(8587),{safeRe:i,t:o}=r(9718),c=r(2111),l=r(7272),u=r(3908),d=r(8311)},3908:(e,t,r)=>{"use strict";const n=r(7272),{MAX_LENGTH:s,MAX_SAFE_INTEGER:a}=r(6874),{safeRe:i,t:o}=r(9718),c=r(8587),{compareIdentifiers:l}=r(1123);class u{constructor(e,t){if(t=c(t),e instanceof u){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if("string"!=typeof e)throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>s)throw new TypeError(`version is longer than ${s} characters`);n("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const r=e.trim().match(t.loose?i[o.LOOSE]:i[o.FULL]);if(!r)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>a||this.major<0)throw new TypeError("Invalid major version");if(this.minor>a||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>a||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map((e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t=0;)"number"==typeof this.prerelease[n]&&(this.prerelease[n]++,n=-2);if(-1===n){if(t===this.prerelease.join(".")&&!1===r)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let n=[t,e];!1===r&&(n=[t]),0===l(this.prerelease[0],t)?isNaN(this.prerelease[1])&&(this.prerelease=n):this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}e.exports=u},3927:(e,t,r)=>{"use strict";const n=r(909);e.exports=(e,t)=>e.sort(((e,r)=>n(e,r,t)))},3961:e=>{function t(e,t){"boolean"==typeof t&&(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))}e.exports=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},t.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(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout((function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout((function(){n._operationTimeoutCb(n._attempts)}),n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)}),r),this._options.unref&&this._timer.unref(),!0},t.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)},t.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},t.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n=r&&(t=s,r=i)}return t}},3997:(e,t,r)=>{"use strict";r.r(t),r.d(t,{LangChainTracer:()=>u});var n=r(1688),s=r(3389),a=r(9583),i=r(1590),o=r(1259);let c;const l=()=>{if(void 0===c){const e="false"===(0,a.getEnvironmentVariable)("LANGCHAIN_CALLBACKS_BACKGROUND")?{blockOnRootRunFinalization:!0}:{};c=new o.Kj(e)}return c};class u extends i.BaseTracer{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});const{exampleId:t,projectName:r,client:n}=e;this.projectName=r??(0,a.getEnvironmentVariable)("LANGCHAIN_PROJECT")??(0,a.getEnvironmentVariable)("LANGCHAIN_SESSION"),this.exampleId=t,this.client=n??l();const s=u.getTraceableRunTree();s&&this.updateFromRunTree(s)}async _convertToCreate(e,t=void 0){return{...e,extra:{...e.extra,runtime:await(0,a.getRuntimeEnvironment)()},child_runs:void 0,session_name:this.projectName,reference_example_id:e.parent_run_id?void 0:t}}async persistRun(e){}async onRunCreate(e){const t=await this._convertToCreate(e,this.exampleId);await this.client.createRun(t)}async onRunUpdate(e){const t={end_time:e.end_time,error:e.error,outputs:e.outputs,events:e.events,inputs:e.inputs,trace_id:e.trace_id,dotted_order:e.dotted_order,parent_run_id:e.parent_run_id,extra:e.extra,session_name:this.projectName};await this.client.updateRun(e.id,t)}getRun(e){return this.runMap.get(e)}updateFromRunTree(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 n=[t];for(;n.length>0;){const e=n.shift();e&&!r.has(e.id)&&(r.add(e.id),this.runMap.set(e.id,e),e.child_runs&&n.push(...e.child_runs))}this.client=e.client??this.client,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}convertToRunTree(e){const t={},r=[];for(const[e,s]of this.runMap){const a=new n.gk({...s,child_runs:[],parent_run:void 0,client:this.client,project_name:this.projectName,reference_example_id:this.exampleId,tracingEnabled:!0});t[e]=a,r.push([e,s.dotted_order])}r.sort(((e,t)=>e[1]&&t[1]?e[1].localeCompare(t[1]):0));for(const[e]of r){const r=this.runMap.get(e),n=t[e];if(r&&n&&r.parent_run_id){const e=t[r.parent_run_id];e&&(e.child_runs.push(n),n.parent_run=e)}}return t[e]}static getTraceableRunTree(){try{return(0,s.vR)(!0)}catch{return}}}},3999:(e,t,r)=>{"use strict";const n=r(560);e.exports=(e,t,r)=>0!==n(e,t,r)},4089:(e,t,r)=>{"use strict";const n=r(560);e.exports=(e,t,r)=>n(e,t,r)>=0},4116:(e,t,r)=>{"use strict";const n=r(5617),s=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class a extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const i=(e,t)=>new Promise(((r,i)=>{t={onFailedAttempt:()=>{},retries:10,...t};const o=n.operation(t);o.attempt((async n=>{try{r(await e(n))}catch(e){if(!(e instanceof Error))return void i(new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));if(e instanceof a)o.stop(),i(e.originalError);else if(e instanceof TypeError&&(c=e.message,!s.includes(c)))o.stop(),i(e);else{((e,t,r)=>{const n=r.retries-(t-1);e.attemptNumber=t,e.retriesLeft=n})(e,n,t);try{await t.onFailedAttempt(e)}catch(e){return void i(e)}o.retry(e)||i(o.mainError())}}var c}))}));e.exports=i,e.exports.default=i,e.exports.AbortError=a},4277:(e,t,r)=>{"use strict";const n=r(909);e.exports=(e,t)=>e.sort(((e,r)=>n(r,e,t)))},4291:(e,t,r)=>{"use strict";function n(e){return"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&"source_type"in e&&("url"===e.source_type||"base64"===e.source_type||"text"===e.source_type||"id"===e.source_type)}function s(e){return n(e)&&"url"===e.source_type&&"url"in e&&"string"==typeof e.url}function a(e){return n(e)&&"base64"===e.source_type&&"data"in e&&"string"==typeof e.data}function i(e){return n(e)&&"text"===e.source_type&&"text"in e&&"string"==typeof e.text}function o(e){return n(e)&&"id"===e.source_type&&"id"in e&&"string"==typeof e.id}function c(e){if(n(e)){if("url"===e.source_type)return{type:"image_url",image_url:{url:e.url}};if("base64"===e.source_type){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function l(e){const t=e.split(";")[0].split("/");if(2!==t.length)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const r=t[0].trim(),n=t[1].trim();if(""===r||""===n)throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const s={};for(const t of e.split(";").slice(1)){const r=t.split("=");if(2!==r.length)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const n=r[0].trim(),a=r[1].trim();if(""===n)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);s[n]=a}return{type:r,subtype:n,parameters:s}}function u({dataUrl:e,asTypedArray:t=!1}){const r=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let n;if(r){n=r[1].toLowerCase();return{mime_type:n,data:t?Uint8Array.from(atob(r[2]),(e=>e.charCodeAt(0))):r[2]}}}function d(e,t){if("text"===e.type){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if("image"===e.type){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if("audio"===e.type){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if("file"===e.type){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}r.d(t,{Ac:()=>i,Ej:()=>l,Fz:()=>n,Q7:()=>u,Vi:()=>c,W:()=>s,cJ:()=>a,oe:()=>o,up:()=>d})},4301:(e,t,r)=>{"use strict";r.d(t,{XU:()=>a,bU:()=>o,cM:()=>s,kY:()=>i});var n=r(3490);class s extends n.XQ{static lc_name(){return"ChatMessage"}static _chatMessageClass(){return s}constructor(e,t){"string"==typeof e&&(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"generic"===e._getType()}get _printableFields(){return{...super._printableFields,role:this.role}}}class a extends n.gj{static lc_name(){return"ChatMessageChunk"}constructor(e,t){"string"==typeof e&&(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 a({content:(0,n._I)(this.content,e.content),additional_kwargs:(0,n.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,n.ns)(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}get _printableFields(){return{...super._printableFields,role:this.role}}}function i(e){return"generic"===e._getType()}function o(e){return"generic"===e._getType()}},4350:(e,t,r)=>{"use strict";r.d(t,{Nx:()=>c});var n=r(1259),s=r(6968),a=r(5042);const i=new class{getStore(){}run(e,t){return t()}enterWith(e){}},o=Symbol.for("lc:child_config");const c=new class{getInstance(){return(0,s.X0)()??i}getRunnableConfig(){const e=this.getInstance();return e.getStore()?.extra?.[o]}runWithConfig(e,t,r){const i=a.CallbackManager._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),c=this.getInstance(),l=c.getStore(),u=i?.getParentRunId(),d=i?.handlers?.find((e=>"langchain_tracer"===e?.name));let h;return d&&u?h=d.convertToRunTree(u):r||(h=new n.gk({name:"",tracingEnabled:!1})),h&&(h.extra={...h.extra,[o]:e}),void 0!==l&&void 0!==l[s.hr]&&(void 0===h&&(h={}),h[s.hr]=l[s.hr]),c.run(h,t)}initializeGlobalInstance(e){void 0===(0,s.X0)()&&(0,s.pH)(e)}}},4476:(e,t,r)=>{"use strict";var n,s;r.d(t,{Ii:()=>Ie,kY:()=>qe,z:()=>Tt}),function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter((e=>"number"!=typeof t[t[e]])),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map((function(e){return t[e]})),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(n||(n={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(s||(s={}));const a=n.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),i=e=>{switch(typeof e){case"undefined":return a.undefined;case"string":return a.string;case"number":return isNaN(e)?a.nan:a.number;case"boolean":return a.boolean;case"function":return a.function;case"bigint":return a.bigint;case"symbol":return a.symbol;case"object":return Array.isArray(e)?a.array:null===e?a.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?a.promise:"undefined"!=typeof Map&&e instanceof Map?a.map:"undefined"!=typeof Set&&e instanceof Set?a.set:"undefined"!=typeof Date&&e instanceof Date?a.date:a.object;default:return a.unknown}},o=n.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class c extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(n);else if("invalid_return_type"===s.code)n(s.returnTypeError);else if("invalid_arguments"===s.code)n(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,n=0;for(;ne.message){const t={},r=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}c.create=e=>new c(e);const l=(e,t)=>{let r;switch(e.code){case o.invalid_type:r=e.received===a.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case o.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,n.jsonStringifyReplacer)}`;break;case o.unrecognized_keys:r=`Unrecognized key(s) in object: ${n.joinValues(e.keys,", ")}`;break;case o.invalid_union:r="Invalid input";break;case o.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${n.joinValues(e.options)}`;break;case o.invalid_enum_value:r=`Invalid enum value. Expected ${n.joinValues(e.options)}, received '${e.received}'`;break;case o.invalid_arguments:r="Invalid function arguments";break;case o.invalid_return_type:r="Invalid function return type";break;case o.invalid_date:r="Invalid date";break;case o.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:n.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case o.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case o.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case o.custom:r="Invalid input";break;case o.invalid_intersection_types:r="Intersection results could not be merged";break;case o.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case o.not_finite:r="Number must be finite";break;default:r=t.defaultError,n.assertNever(e)}return{message:r}};let u=l;function d(){return u}const h=e=>{const{data:t,path:r,errorMaps:n,issueData:s}=e,a=[...r,...s.path||[]],i={...s,path:a};if(void 0!==s.message)return{...s,path:a,message:s.message};let o="";const c=n.filter((e=>!!e)).slice().reverse();for(const e of c)o=e(i,{data:t,defaultError:o}).message;return{...s,path:a,message:o}};function p(e,t){const r=d(),n=h({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===l?void 0:l].filter((e=>!!e))});e.common.issues.push(n)}class m{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return f;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,n=await e.value;r.push({key:t,value:n})}return m.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:s}=n;if("aborted"===t.status)return f;if("aborted"===s.status)return f;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!n.alwaysSet||(r[t.value]=s.value)}return{status:e.value,value:r}}}const f=Object.freeze({status:"aborted"}),g=e=>({status:"dirty",value:e}),y=e=>({status:"valid",value:e}),b=e=>"aborted"===e.status,w=e=>"dirty"===e.status,v=e=>"valid"===e.status,_=e=>"undefined"!=typeof Promise&&e instanceof Promise;function k(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}function S(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r}var E,x,T;"function"==typeof SuppressedError&&SuppressedError,function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(E||(E={}));class C{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const P=(e,t)=>{if(v(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new c(e.common.issues);return this._error=t,this._error}}};function O(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:s}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:s};return{errorMap:(t,s)=>{var a,i;const{message:o}=e;return"invalid_enum_value"===t.code?{message:null!=o?o:s.defaultError}:void 0===s.data?{message:null!==(a=null!=o?o:n)&&void 0!==a?a:s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:null!==(i=null!=o?o:r)&&void 0!==i?i:s.defaultError}},description:s}}class A{get description(){return this._def.description}_getType(e){return i(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:i(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new m,ctx:{common:e.parent.common,data:e.data,parsedType:i(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(_(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const n={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)},s=this._parseSync({data:e,path:n.path,parent:n});return P(n,s)}"~validate"(e){var t,r;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:n});return v(t)?{value:t.value}:{issues:n.common.issues}}catch(e){(null===(r=null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.toLowerCase())||void 0===r?void 0:r.includes("encountered"))&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then((e=>v(e)?{value:e.value}:{issues:n.common.issues}))}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)},n=this._parse({data:e,path:r.path,parent:r}),s=await(_(n)?n:Promise.resolve(n));return P(r,s)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,n)=>{const s=e(t),a=()=>n.addIssue({code:o.custom,...r(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then((e=>!!e||(a(),!1))):!!s||(a(),!1)}))}refinement(e,t){return this._refinement(((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1)))}_refinement(e){return new Ae({schema:this,typeName:qe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Ie.create(this,this._def)}nullable(){return Me.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return de.create(this)}promise(){return Oe.create(this,this._def)}or(e){return me.create([this,e],this._def)}and(e){return be.create(this,e,this._def)}transform(e){return new Ae({...O(this._def),schema:this,typeName:qe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Re({...O(this._def),innerType:this,defaultValue:t,typeName:qe.ZodDefault})}brand(){return new Le({typeName:qe.ZodBranded,type:this,...O(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new je({...O(this._def),innerType:this,catchValue:t,typeName:qe.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Fe.create(this,e)}readonly(){return De.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const I=/^c[^\s-]{8,}$/i,M=/^[0-9a-z]+$/,R=/^[0-9A-HJKMNP-TV-Z]{26}$/i,j=/^[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}$/i,N=/^[a-z0-9_-]{21}$/i,$=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,L=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,F=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let D;const z=/^(?:(?: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])$/,U=/^(?:(?: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])$/,B=/^(([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]))$/,q=/^(([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])$/,K=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,W=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,H="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",V=new RegExp(`^${H}$`);function G(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function J(e){let t=`${H}T${G(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function Z(e,t){if(!$.test(e))return!1;try{const[r]=e.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return"object"==typeof s&&null!==s&&(!(!s.typ||!s.alg)&&(!t||s.alg===t))}catch(e){return!1}}function X(e,t){return!("v4"!==t&&t||!U.test(e))||!("v6"!==t&&t||!q.test(e))}class Y extends A{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==a.string){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.string,received:t.parsedType}),f}const t=new m;let r;for(const a of this._def.checks)if("min"===a.kind)e.data.lengtha.value&&(r=this._getOrReturnCtx(e,r),p(r,{code:o.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if("length"===a.kind){const n=e.data.length>a.value,s=e.data.lengthe.test(t)),{validation:t,code:o.invalid_string,...E.errToObj(r)})}_addCheck(e){return new Y({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...E.errToObj(e)})}url(e){return this._addCheck({kind:"url",...E.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...E.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...E.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...E.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...E.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...E.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...E.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...E.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...E.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...E.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...E.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...E.errToObj(e)})}datetime(e){var t,r;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(r=null==e?void 0:e.local)&&void 0!==r&&r,...E.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...E.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...E.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...E.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...E.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...E.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...E.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...E.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...E.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...E.errToObj(t)})}nonempty(e){return this.min(1,E.errToObj(e))}trim(){return new Y({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Y({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Y({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.valuen?r:n;return parseInt(e.toFixed(s).replace(".",""))%parseInt(t.toFixed(s).replace(".",""))/Math.pow(10,s)}Y.create=e=>{var t;return new Y({checks:[],typeName:qe.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...O(e)})};class ee extends A{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==a.number){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.number,received:t.parsedType}),f}let t;const r=new m;for(const s of this._def.checks)if("int"===s.kind)n.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),p(t,{code:o.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty());else if("min"===s.kind){(s.inclusive?e.datas.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),p(t,{code:o.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else"multipleOf"===s.kind?0!==Q(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),p(t,{code:o.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),p(t,{code:o.not_finite,message:s.message}),r.dirty()):n.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,E.toString(t))}gt(e,t){return this.setLimit("min",e,!1,E.toString(t))}lte(e,t){return this.setLimit("max",e,!0,E.toString(t))}lt(e,t){return this.setLimit("max",e,!1,E.toString(t))}setLimit(e,t,r,n){return new ee({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:E.toString(n)}]})}_addCheck(e){return new ee({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:E.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:E.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:E.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:E.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:E.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:E.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:E.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:E.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:E.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value"int"===e.kind||"multipleOf"===e.kind&&n.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.valuenew ee({checks:[],typeName:qe.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...O(e)});class te extends A{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch(t){return this._getInvalidInput(e)}if(this._getType(e)!==a.bigint)return this._getInvalidInput(e);let t;const r=new m;for(const s of this._def.checks)if("min"===s.kind){(s.inclusive?e.datas.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),p(t,{code:o.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty())}else"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),p(t,{code:o.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):n.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.bigint,received:t.parsedType}),f}gte(e,t){return this.setLimit("min",e,!0,E.toString(t))}gt(e,t){return this.setLimit("min",e,!1,E.toString(t))}lte(e,t){return this.setLimit("max",e,!0,E.toString(t))}lt(e,t){return this.setLimit("max",e,!1,E.toString(t))}setLimit(e,t,r,n){return new te({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:E.toString(n)}]})}_addCheck(e){return new te({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:E.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:E.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:E.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:E.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:E.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value{var t;return new te({checks:[],typeName:qe.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...O(e)})};class re extends A{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==a.boolean){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.boolean,received:t.parsedType}),f}return y(e.data)}}re.create=e=>new re({typeName:qe.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...O(e)});class ne extends A{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==a.date){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.date,received:t.parsedType}),f}if(isNaN(e.data.getTime())){return p(this._getOrReturnCtx(e),{code:o.invalid_date}),f}const t=new m;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()s.value&&(r=this._getOrReturnCtx(e,r),p(r,{code:o.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):n.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ne({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:E.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:E.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.valuenew ne({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:qe.ZodDate,...O(e)});class se extends A{_parse(e){if(this._getType(e)!==a.symbol){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.symbol,received:t.parsedType}),f}return y(e.data)}}se.create=e=>new se({typeName:qe.ZodSymbol,...O(e)});class ae extends A{_parse(e){if(this._getType(e)!==a.undefined){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.undefined,received:t.parsedType}),f}return y(e.data)}}ae.create=e=>new ae({typeName:qe.ZodUndefined,...O(e)});class ie extends A{_parse(e){if(this._getType(e)!==a.null){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.null,received:t.parsedType}),f}return y(e.data)}}ie.create=e=>new ie({typeName:qe.ZodNull,...O(e)});class oe extends A{constructor(){super(...arguments),this._any=!0}_parse(e){return y(e.data)}}oe.create=e=>new oe({typeName:qe.ZodAny,...O(e)});class ce extends A{constructor(){super(...arguments),this._unknown=!0}_parse(e){return y(e.data)}}ce.create=e=>new ce({typeName:qe.ZodUnknown,...O(e)});class le extends A{_parse(e){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.never,received:t.parsedType}),f}}le.create=e=>new le({typeName:qe.ZodNever,...O(e)});class ue extends A{_parse(e){if(this._getType(e)!==a.undefined){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.void,received:t.parsedType}),f}return y(e.data)}}ue.create=e=>new ue({typeName:qe.ZodVoid,...O(e)});class de extends A{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==a.array)return p(t,{code:o.invalid_type,expected:a.array,received:t.parsedType}),f;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,s=t.data.lengthn.maxLength.value&&(p(t,{code:o.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map(((e,r)=>n.type._parseAsync(new C(t,e,t.path,r))))).then((e=>m.mergeArray(r,e)));const s=[...t.data].map(((e,r)=>n.type._parseSync(new C(t,e,t.path,r))));return m.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new de({...this._def,minLength:{value:e,message:E.toString(t)}})}max(e,t){return new de({...this._def,maxLength:{value:e,message:E.toString(t)}})}length(e,t){return new de({...this._def,exactLength:{value:e,message:E.toString(t)}})}nonempty(e){return this.min(1,e)}}function he(e){if(e instanceof pe){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Ie.create(he(n))}return new pe({...e._def,shape:()=>t})}return e instanceof de?new de({...e._def,type:he(e.element)}):e instanceof Ie?Ie.create(he(e.unwrap())):e instanceof Me?Me.create(he(e.unwrap())):e instanceof we?we.create(e.items.map((e=>he(e)))):e}de.create=(e,t)=>new de({type:e,minLength:null,maxLength:null,exactLength:null,typeName:qe.ZodArray,...O(t)});class pe extends A{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=n.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==a.object){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.object,received:t.parsedType}),f}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:s}=this._getCached(),i=[];if(!(this._def.catchall instanceof le&&"strip"===this._def.unknownKeys))for(const e in r.data)s.includes(e)||i.push(e);const c=[];for(const e of s){const t=n[e],s=r.data[e];c.push({key:{status:"valid",value:e},value:t._parse(new C(r,s,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof le){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)c.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)i.length>0&&(p(r,{code:o.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const n=r.data[t];c.push({key:{status:"valid",value:t},value:e._parse(new C(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of c){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e})).then((e=>m.mergeObjectSync(t,e))):m.mergeObjectSync(t,c)}get shape(){return this._def.shape()}strict(e){return E.errToObj,new pe({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,s,a,i;const o=null!==(a=null===(s=(n=this._def).errorMap)||void 0===s?void 0:s.call(n,t,r).message)&&void 0!==a?a:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(i=E.errToObj(e).message)&&void 0!==i?i:o}:{message:o}}}:{}})}strip(){return new pe({...this._def,unknownKeys:"strip"})}passthrough(){return new pe({...this._def,unknownKeys:"passthrough"})}extend(e){return new pe({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new pe({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:qe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new pe({...this._def,catchall:e})}pick(e){const t={};return n.objectKeys(e).forEach((r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])})),new pe({...this._def,shape:()=>t})}omit(e){const t={};return n.objectKeys(this.shape).forEach((r=>{e[r]||(t[r]=this.shape[r])})),new pe({...this._def,shape:()=>t})}deepPartial(){return he(this)}partial(e){const t={};return n.objectKeys(this.shape).forEach((r=>{const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()})),new pe({...this._def,shape:()=>t})}required(e){const t={};return n.objectKeys(this.shape).forEach((r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Ie;)e=e._def.innerType;t[r]=e}})),new pe({...this._def,shape:()=>t})}keyof(){return Te(n.objectKeys(this.shape))}}pe.create=(e,t)=>new pe({shape:()=>e,unknownKeys:"strip",catchall:le.create(),typeName:qe.ZodObject,...O(t)}),pe.strictCreate=(e,t)=>new pe({shape:()=>e,unknownKeys:"strict",catchall:le.create(),typeName:qe.ZodObject,...O(t)}),pe.lazycreate=(e,t)=>new pe({shape:e,unknownKeys:"strip",catchall:le.create(),typeName:qe.ZodObject,...O(t)});class me extends A{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map((async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map((e=>new c(e.ctx.common.issues)));return p(t,{code:o.invalid_union,unionErrors:r}),f}));{let e;const n=[];for(const s of r){const r={...t,common:{...t.common,issues:[]},parent:null},a=s._parseSync({data:t.data,path:t.path,parent:r});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=n.map((e=>new c(e)));return p(t,{code:o.invalid_union,unionErrors:s}),f}}get options(){return this._def.options}}me.create=(e,t)=>new me({options:e,typeName:qe.ZodUnion,...O(t)});const fe=e=>e instanceof Ee?fe(e.schema):e instanceof Ae?fe(e.innerType()):e instanceof xe?[e.value]:e instanceof Ce?e.options:e instanceof Pe?n.objectValues(e.enum):e instanceof Re?fe(e._def.innerType):e instanceof ae?[void 0]:e instanceof ie?[null]:e instanceof Ie?[void 0,...fe(e.unwrap())]:e instanceof Me?[null,...fe(e.unwrap())]:e instanceof Le||e instanceof De?fe(e.unwrap()):e instanceof je?fe(e._def.innerType):[];class ge extends A{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==a.object)return p(t,{code:o.invalid_type,expected:a.object,received:t.parsedType}),f;const r=this.discriminator,n=t.data[r],s=this.optionsMap.get(n);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:o.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),f)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const n=new Map;for(const r of t){const t=fe(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const s of t){if(n.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,r)}}return new ge({typeName:qe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...O(r)})}}function ye(e,t){const r=i(e),s=i(t);if(e===t)return{valid:!0,data:e};if(r===a.object&&s===a.object){const r=n.objectKeys(t),s=n.objectKeys(e).filter((e=>-1!==r.indexOf(e))),a={...e,...t};for(const r of s){const n=ye(e[r],t[r]);if(!n.valid)return{valid:!1};a[r]=n.data}return{valid:!0,data:a}}if(r===a.array&&s===a.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n{if(b(e)||b(n))return f;const s=ye(e.value,n.value);return s.valid?((w(e)||w(n))&&t.dirty(),{status:t.value,value:s.data}):(p(r,{code:o.invalid_intersection_types}),f)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then((([e,t])=>n(e,t))):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}be.create=(e,t,r)=>new be({left:e,right:t,typeName:qe.ZodIntersection,...O(r)});class we extends A{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.array)return p(r,{code:o.invalid_type,expected:a.array,received:r.parsedType}),f;if(r.data.lengththis._def.items.length&&(p(r,{code:o.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map(((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new C(r,e,r.path,t)):null})).filter((e=>!!e));return r.common.async?Promise.all(n).then((e=>m.mergeArray(t,e))):m.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new we({...this._def,rest:e})}}we.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new we({items:e,typeName:qe.ZodTuple,rest:null,...O(t)})};class ve extends A{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.object)return p(r,{code:o.invalid_type,expected:a.object,received:r.parsedType}),f;const n=[],s=this._def.keyType,i=this._def.valueType;for(const e in r.data)n.push({key:s._parse(new C(r,e,r.path,e)),value:i._parse(new C(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?m.mergeObjectAsync(t,n):m.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new ve(t instanceof A?{keyType:e,valueType:t,typeName:qe.ZodRecord,...O(r)}:{keyType:Y.create(),valueType:e,typeName:qe.ZodRecord,...O(t)})}}class _e extends A{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.map)return p(r,{code:o.invalid_type,expected:a.map,received:r.parsedType}),f;const n=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map((([e,t],a)=>({key:n._parse(new C(r,e,r.path,[a,"key"])),value:s._parse(new C(r,t,r.path,[a,"value"]))})));if(r.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const r of i){const n=await r.key,s=await r.value;if("aborted"===n.status||"aborted"===s.status)return f;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const r of i){const n=r.key,s=r.value;if("aborted"===n.status||"aborted"===s.status)return f;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}_e.create=(e,t,r)=>new _e({valueType:t,keyType:e,typeName:qe.ZodMap,...O(r)});class ke extends A{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.set)return p(r,{code:o.invalid_type,expected:a.set,received:r.parsedType}),f;const n=this._def;null!==n.minSize&&r.data.sizen.maxSize.value&&(p(r,{code:o.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const s=this._def.valueType;function i(e){const r=new Set;for(const n of e){if("aborted"===n.status)return f;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const c=[...r.data.values()].map(((e,t)=>s._parse(new C(r,e,r.path,t))));return r.common.async?Promise.all(c).then((e=>i(e))):i(c)}min(e,t){return new ke({...this._def,minSize:{value:e,message:E.toString(t)}})}max(e,t){return new ke({...this._def,maxSize:{value:e,message:E.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ke.create=(e,t)=>new ke({valueType:e,minSize:null,maxSize:null,typeName:qe.ZodSet,...O(t)});class Se extends A{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==a.function)return p(t,{code:o.invalid_type,expected:a.function,received:t.parsedType}),f;function r(e,r){return h({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,d(),l].filter((e=>!!e)),issueData:{code:o.invalid_arguments,argumentsError:r}})}function n(e,r){return h({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,d(),l].filter((e=>!!e)),issueData:{code:o.invalid_return_type,returnTypeError:r}})}const s={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof Oe){const e=this;return y((async function(...t){const a=new c([]),o=await e._def.args.parseAsync(t,s).catch((e=>{throw a.addIssue(r(t,e)),a})),l=await Reflect.apply(i,this,o);return await e._def.returns._def.type.parseAsync(l,s).catch((e=>{throw a.addIssue(n(l,e)),a}))}))}{const e=this;return y((function(...t){const a=e._def.args.safeParse(t,s);if(!a.success)throw new c([r(t,a.error)]);const o=Reflect.apply(i,this,a.data),l=e._def.returns.safeParse(o,s);if(!l.success)throw new c([n(o,l.error)]);return l.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Se({...this._def,args:we.create(e).rest(ce.create())})}returns(e){return new Se({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new Se({args:e||we.create([]).rest(ce.create()),returns:t||ce.create(),typeName:qe.ZodFunction,...O(r)})}}class Ee extends A{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Ee.create=(e,t)=>new Ee({getter:e,typeName:qe.ZodLazy,...O(t)});class xe extends A{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:o.invalid_literal,expected:this._def.value}),f}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Te(e,t){return new Ce({values:e,typeName:qe.ZodEnum,...O(t)})}xe.create=(e,t)=>new xe({value:e,typeName:qe.ZodLiteral,...O(t)});class Ce extends A{constructor(){super(...arguments),x.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return p(t,{expected:n.joinValues(r),received:t.parsedType,code:o.invalid_type}),f}if(k(this,x,"f")||S(this,x,new Set(this._def.values),"f"),!k(this,x,"f").has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return p(t,{received:t.data,code:o.invalid_enum_value,options:r}),f}return y(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Ce.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ce.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}x=new WeakMap,Ce.create=Te;class Pe extends A{constructor(){super(...arguments),T.set(this,void 0)}_parse(e){const t=n.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==a.string&&r.parsedType!==a.number){const e=n.objectValues(t);return p(r,{expected:n.joinValues(e),received:r.parsedType,code:o.invalid_type}),f}if(k(this,T,"f")||S(this,T,new Set(n.getValidEnumValues(this._def.values)),"f"),!k(this,T,"f").has(e.data)){const e=n.objectValues(t);return p(r,{received:r.data,code:o.invalid_enum_value,options:e}),f}return y(e.data)}get enum(){return this._def.values}}T=new WeakMap,Pe.create=(e,t)=>new Pe({values:e,typeName:qe.ZodNativeEnum,...O(t)});class Oe extends A{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==a.promise&&!1===t.common.async)return p(t,{code:o.invalid_type,expected:a.promise,received:t.parsedType}),f;const r=t.parsedType===a.promise?t.data:Promise.resolve(t.data);return y(r.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}Oe.create=(e,t)=>new Oe({type:e,typeName:qe.ZodPromise,...O(t)});class Ae extends A{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===qe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:e=>{p(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),"preprocess"===s.type){const e=s.transform(r.data,a);if(r.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return f;const n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?f:"dirty"===n.status||"dirty"===t.value?g(n.value):n}));{if("aborted"===t.value)return f;const n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?f:"dirty"===n.status||"dirty"===t.value?g(n.value):n}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,a);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?f:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((r=>"aborted"===r.status?f:("dirty"===r.status&&t.dirty(),e(r.value).then((()=>({status:t.value,value:r.value}))))))}if("transform"===s.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!v(e))return e;const n=s.transform(e.value,a);if(n instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((e=>v(e)?Promise.resolve(s.transform(e.value,a)).then((e=>({status:t.value,value:e}))):e))}n.assertNever(s)}}Ae.create=(e,t,r)=>new Ae({schema:e,typeName:qe.ZodEffects,effect:t,...O(r)}),Ae.createWithPreprocess=(e,t,r)=>new Ae({schema:t,effect:{type:"preprocess",transform:e},typeName:qe.ZodEffects,...O(r)});class Ie extends A{_parse(e){return this._getType(e)===a.undefined?y(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:qe.ZodOptional,...O(t)});class Me extends A{_parse(e){return this._getType(e)===a.null?y(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Me.create=(e,t)=>new Me({innerType:e,typeName:qe.ZodNullable,...O(t)});class Re extends A{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===a.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Re.create=(e,t)=>new Re({innerType:e,typeName:qe.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...O(t)});class je extends A{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return _(n)?n.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new c(r.common.issues)},input:r.data})}))):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new c(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}je.create=(e,t)=>new je({innerType:e,typeName:qe.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...O(t)});class Ne extends A{_parse(e){if(this._getType(e)!==a.nan){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.nan,received:t.parsedType}),f}return{status:"valid",value:e.data}}}Ne.create=e=>new Ne({typeName:qe.ZodNaN,...O(e)});const $e=Symbol("zod_brand");class Le extends A{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Fe extends A{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?f:"dirty"===e.status?(t.dirty(),g(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?f:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Fe({in:e,out:t,typeName:qe.ZodPipeline})}}class De extends A{_parse(e){const t=this._def.innerType._parse(e),r=e=>(v(e)&&(e.value=Object.freeze(e.value)),e);return _(t)?t.then((e=>r(e))):r(t)}unwrap(){return this._def.innerType}}function ze(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function Ue(e,t={},r){return e?oe.create().superRefine(((n,s)=>{var a,i;const o=e(n);if(o instanceof Promise)return o.then((e=>{var a,i;if(!e){const e=ze(t,n),o=null===(i=null!==(a=e.fatal)&&void 0!==a?a:r)||void 0===i||i;s.addIssue({code:"custom",...e,fatal:o})}}));if(!o){const e=ze(t,n),o=null===(i=null!==(a=e.fatal)&&void 0!==a?a:r)||void 0===i||i;s.addIssue({code:"custom",...e,fatal:o})}})):oe.create()}De.create=(e,t)=>new De({innerType:e,typeName:qe.ZodReadonly,...O(t)});const Be={object:pe.lazycreate};var qe;!function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(qe||(qe={}));const Ke=Y.create,We=ee.create,He=Ne.create,Ve=te.create,Ge=re.create,Je=ne.create,Ze=se.create,Xe=ae.create,Ye=ie.create,Qe=oe.create,et=ce.create,tt=le.create,rt=ue.create,nt=de.create,st=pe.create,at=pe.strictCreate,it=me.create,ot=ge.create,ct=be.create,lt=we.create,ut=ve.create,dt=_e.create,ht=ke.create,pt=Se.create,mt=Ee.create,ft=xe.create,gt=Ce.create,yt=Pe.create,bt=Oe.create,wt=Ae.create,vt=Ie.create,_t=Me.create,kt=Ae.createWithPreprocess,St=Fe.create,Et={string:e=>Y.create({...e,coerce:!0}),number:e=>ee.create({...e,coerce:!0}),boolean:e=>re.create({...e,coerce:!0}),bigint:e=>te.create({...e,coerce:!0}),date:e=>ne.create({...e,coerce:!0})},xt=f;var Tt=Object.freeze({__proto__:null,defaultErrorMap:l,setErrorMap:function(e){u=e},getErrorMap:d,makeIssue:h,EMPTY_PATH:[],addIssueToContext:p,ParseStatus:m,INVALID:f,DIRTY:g,OK:y,isAborted:b,isDirty:w,isValid:v,isAsync:_,get util(){return n},get objectUtil(){return s},ZodParsedType:a,getParsedType:i,ZodType:A,datetimeRegex:J,ZodString:Y,ZodNumber:ee,ZodBigInt:te,ZodBoolean:re,ZodDate:ne,ZodSymbol:se,ZodUndefined:ae,ZodNull:ie,ZodAny:oe,ZodUnknown:ce,ZodNever:le,ZodVoid:ue,ZodArray:de,ZodObject:pe,ZodUnion:me,ZodDiscriminatedUnion:ge,ZodIntersection:be,ZodTuple:we,ZodRecord:ve,ZodMap:_e,ZodSet:ke,ZodFunction:Se,ZodLazy:Ee,ZodLiteral:xe,ZodEnum:Ce,ZodNativeEnum:Pe,ZodPromise:Oe,ZodEffects:Ae,ZodTransformer:Ae,ZodOptional:Ie,ZodNullable:Me,ZodDefault:Re,ZodCatch:je,ZodNaN:Ne,BRAND:$e,ZodBranded:Le,ZodPipeline:Fe,ZodReadonly:De,custom:Ue,Schema:A,ZodSchema:A,late:Be,get ZodFirstPartyTypeKind(){return qe},coerce:Et,any:Qe,array:nt,bigint:Ve,boolean:Ge,date:Je,discriminatedUnion:ot,effect:wt,enum:gt,function:pt,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>Ue((t=>t instanceof e),t),intersection:ct,lazy:mt,literal:ft,map:dt,nan:He,nativeEnum:yt,never:tt,null:Ye,nullable:_t,number:We,object:st,oboolean:()=>Ge().optional(),onumber:()=>We().optional(),optional:vt,ostring:()=>Ke().optional(),pipeline:St,preprocess:kt,promise:bt,record:ut,set:ht,strictObject:at,string:Ke,symbol:Ze,transformer:wt,tuple:lt,undefined:Xe,union:it,unknown:et,void:rt,NEVER:xt,ZodIssueCode:o,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:c})},4493:(e,t,r)=>{"use strict";const n=r(3908);e.exports=(e,t)=>new n(e,t).patch},4547:(e,t,r)=>{"use strict";r.d(t,{Kj:()=>n.Kj,Ls:()=>a,gk:()=>s.gk});var n=r(9056),s=r(3246);r(747);const a="0.3.29"},4552:(e,t,r)=>{"use strict";r.d(t,{l:()=>a});var n=r(3313),s=r(9849);class a extends n.YN{static lc_name(){return"DictPromptTemplate"}constructor(e){const t=e.templateFormat??"f-string",r=i(e.template,t);super({inputVariables:r,...e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","dict"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.template=e.template,this.templateFormat=t,this.inputVariables=r}async format(e){return o(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}}function i(e,t){const r=[];for(const n of Object.values(e))if("string"==typeof n)(0,s.QC)(n,t).forEach((e=>{"variable"===e.type&&r.push(e.name)}));else if(Array.isArray(n))for(const e of n)"string"==typeof e?(0,s.QC)(e,t).forEach((e=>{"variable"===e.type&&r.push(e.name)})):"object"==typeof e&&r.push(...i(e,t));else"object"==typeof n&&null!==n&&r.push(...i(n,t));return Array.from(new Set(r))}function o(e,t,r){const n={};for(const[a,i]of Object.entries(e))if("string"==typeof i)n[a]=(0,s.Xm)(i,r,t);else if(Array.isArray(i)){const e=[];for(const n of i)"string"==typeof n?e.push((0,s.Xm)(n,r,t)):"object"==typeof n&&e.push(o(n,t,r));n[a]=e}else n[a]="object"==typeof i&&null!==i?o(i,t,r):i;return n}},4617:e=>{"use strict";e.exports=(e,t)=>(t=t||(()=>{}),e.then((e=>new Promise((e=>{e(t())})).then((()=>e))),(e=>new Promise((e=>{e(t())})).then((()=>{throw e})))))},4641:(e,t,r)=>{"use strict";const n=r(560);e.exports=(e,t,r)=>0===n(e,t,r)},4774:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(9998);t.default=class{constructor(){this._queue=[]}enqueue(e,t){const r={priority:(t=Object.assign({priority:0},t)).priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority)return void this._queue.push(r);const s=n.default(this._queue,r,((e,t)=>t.priority-e.priority));this._queue.splice(s,0,r)}dequeue(){const e=this._queue.shift();return null==e?void 0:e.run}filter(e){return this._queue.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this._queue.length}}},4785:(e,t,r)=>{"use strict";r.d(t,{Az:()=>h,Ec:()=>l,Jz:()=>p,yk:()=>u});var n=r(4547);let s;const a=()=>"undefined"!=typeof Deno,i=()=>s||(s="undefined"!=typeof window&&void 0!==window.document?"browser":"undefined"==typeof process||void 0===process.versions||void 0===process.versions.node||a()?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"))?"jsdom":a()?"deno":"other":"node",s);let o,c;function l(){if(void 0===o){const e=i(),t=function(){if(void 0!==c)return c;const e=["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"],t={};for(const r of e){const e=h(r);void 0!==e&&(t[r]=e)}return c=t,t}();o={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:n.Ls,...t}}return o}function u(){const e=d()||{},t={},r=["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[n,s]of Object.entries(e))!n.startsWith("LANGCHAIN_")&&!n.startsWith("LANGSMITH_")||"string"!=typeof s||r.includes(n)||n.toLowerCase().includes("key")||n.toLowerCase().includes("secret")||n.toLowerCase().includes("token")||("LANGCHAIN_REVISION_ID"===n?t.revision_id=s:t[n]=s);return t}function d(){try{return"undefined"!=typeof process&&process.env?Object.entries(process.env).reduce(((e,[t,r])=>(e[t]=String(r),e)),{}):void 0}catch(e){return}}function h(e){try{return"undefined"!=typeof process?process.env?.[e]:void 0}catch(e){return}}function p(e){return h(`LANGSMITH_${e}`)||h(`LANGCHAIN_${e}`)}},4850:(e,t,r)=>{"use strict";function n(e){return!!e&&e.lc_runnable}r.d(t,{G:()=>s,T:()=>n});class s{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=void 0===this.includeNames&&void 0===this.includeTypes&&void 0===this.includeTags;const n=e.tags??[];return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(t)),void 0!==this.includeTags&&(r=r||n.some((e=>this.includeTags?.includes(e)))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(t)),void 0!==this.excludeTags&&(r=r&&n.every((e=>!this.excludeTags?.includes(e)))),r}}},5001:(e,t,r)=>{"use strict";r.r(t),r.d(t,{BrowserWebSocketTransport:()=>n});class n{static create(e){return new Promise(((t,r)=>{const s=new WebSocket(e);s.addEventListener("open",(()=>t(new n(s)))),s.addEventListener("error",r)}))}#e;onmessage;onclose;constructor(e){this.#e=e,this.#e.addEventListener("message",(e=>{this.onmessage&&this.onmessage.call(null,e.data)})),this.#e.addEventListener("close",(()=>{this.onclose&&this.onclose.call(null)})),this.#e.addEventListener("error",(()=>{}))}send(e){this.#e.send(e)}close(){this.#e.close()}}},5032:(e,t,r)=>{"use strict";const n=r(8311),s=r(3904),{ANY:a}=s,i=r(7638),o=r(560),c=[new s(">=0.0.0-0")],l=[new s(">=0.0.0")],u=(e,t,r)=>{if(e===t)return!0;if(1===e.length&&e[0].semver===a){if(1===t.length&&t[0].semver===a)return!0;e=r.includePrerelease?c:l}if(1===t.length&&t[0].semver===a){if(r.includePrerelease)return!0;t=l}const n=new Set;let s,u,p,m,f,g,y;for(const t of e)">"===t.operator||">="===t.operator?s=d(s,t,r):"<"===t.operator||"<="===t.operator?u=h(u,t,r):n.add(t.semver);if(n.size>1)return null;if(s&&u){if(p=o(s.semver,u.semver,r),p>0)return null;if(0===p&&(">="!==s.operator||"<="!==u.operator))return null}for(const e of n){if(s&&!i(e,String(s),r))return null;if(u&&!i(e,String(u),r))return null;for(const n of t)if(!i(e,String(n),r))return!1;return!0}let b=!(!u||r.includePrerelease||!u.semver.prerelease.length)&&u.semver,w=!(!s||r.includePrerelease||!s.semver.prerelease.length)&&s.semver;b&&1===b.prerelease.length&&"<"===u.operator&&0===b.prerelease[0]&&(b=!1);for(const e of t){if(y=y||">"===e.operator||">="===e.operator,g=g||"<"===e.operator||"<="===e.operator,s)if(w&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===w.major&&e.semver.minor===w.minor&&e.semver.patch===w.patch&&(w=!1),">"===e.operator||">="===e.operator){if(m=d(s,e,r),m===e&&m!==s)return!1}else if(">="===s.operator&&!i(s.semver,String(e),r))return!1;if(u)if(b&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===b.major&&e.semver.minor===b.minor&&e.semver.patch===b.patch&&(b=!1),"<"===e.operator||"<="===e.operator){if(f=h(u,e,r),f===e&&f!==u)return!1}else if("<="===u.operator&&!i(u.semver,String(e),r))return!1;if(!e.operator&&(u||s)&&0!==p)return!1}return!(s&&g&&!u&&0!==p)&&(!(u&&y&&!s&&0!==p)&&(!w&&!b))},d=(e,t,r)=>{if(!e)return t;const n=o(e.semver,t.semver,r);return n>0?e:n<0||">"===t.operator&&">="===e.operator?t:e},h=(e,t,r)=>{if(!e)return t;const n=o(e.semver,t.semver,r);return n<0?e:n>0||"<"===t.operator&&"<="===e.operator?t:e};e.exports=(e,t,r={})=>{if(e===t)return!0;e=new n(e,r),t=new n(t,r);let s=!1;e:for(const n of e.set){for(const e of t.set){const t=u(n,e,r);if(s=s||null!==t,t)continue e}if(s)return!1}return!0}},5042:(e,t,r)=>{"use strict";r.r(t),r.d(t,{BaseCallbackManager:()=>g,BaseRunManager:()=>y,CallbackManager:()=>k,CallbackManagerForChainRun:()=>v,CallbackManagerForLLMRun:()=>w,CallbackManagerForRetrieverRun:()=>b,CallbackManagerForToolRun:()=>_,TraceGroup:()=>E,ensureHandler:()=>S,parseCallbackConfigArg:()=>f,traceAsGroup:()=>x});var n=r(9120),s=r(5960),a=r(6906),i=r(6362),o=r(9583),c=r(3997),l=r(2293);var u=r(1590),d=(r(1688),r(6968));function h(e){const t=(0,d.X0)();if(void 0===t)return;const r=t.getStore();return r?.[d.hr]?.[e]}const p=Symbol("lc:configure_hooks"),m=()=>h(p)||[];function f(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}class g{setHandler(e){return this.setHandlers([e])}}class y{constructor(e,t,r,n,s,a,i,o){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:n}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:o})}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{try{await(t.handleText?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleCustomEvent(e,t,r,n,s){await Promise.all(this.handlers.map((r=>(0,l.consumeCallback)((async()=>{try{await(r.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleCustomEvent: ${e}`),r.raiseError)throw e}}),r.awaitHandlers))))}}class b extends y{getChild(e){const t=new k(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=>(0,l.consumeCallback)((async()=>{if(!t.ignoreRetriever)try{await(t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleRetrieverError(e){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{if(!t.ignoreRetriever)try{await(t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags))}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${r}`),t.raiseError)throw e}}),t.awaitHandlers))))}}class w extends y{async handleLLMNewToken(e,t,r,n,s,a){await Promise.all(this.handlers.map((r=>(0,l.consumeCallback)((async()=>{if(!r.ignoreLLM)try{await(r.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMNewToken: ${e}`),r.raiseError)throw e}}),r.awaitHandlers))))}async handleLLMError(e,t,r,n,s){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{if(!t.ignoreLLM)try{await(t.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,s))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMError: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleLLMEnd(e,t,r,n,s){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{if(!t.ignoreLLM)try{await(t.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,s))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMEnd: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}}class v extends y{getChild(e){const t=new k(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,n,s){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{if(!t.ignoreChain)try{await(t.handleChainError?.(e,this.runId,this._parentRunId,this.tags,s))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainError: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleChainEnd(e,t,r,n,s){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{if(!t.ignoreChain)try{await(t.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,s))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainEnd: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleAgentAction(e){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{if(!t.ignoreAgent)try{await(t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleAgentEnd(e){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{if(!t.ignoreAgent)try{await(t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}}class _ extends y{getChild(e){const t=new k(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=>(0,l.consumeCallback)((async()=>{if(!t.ignoreAgent)try{await(t.handleToolError?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleToolEnd(e){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{if(!t.ignoreAgent)try{await(t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}}class k extends g{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?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,r=void 0,s=void 0,a=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(t.map((async(t,s)=>{const i=0===s&&r?r:(0,n.A)();return await Promise.all(this.handlers.map((r=>{if(!r.ignoreLLM)return(0,u.isBaseTracer)(r)&&r._createRunForLLMStart(e,[t],i,this._parentRunId,a,this.tags,this.metadata,c),(0,l.consumeCallback)((async()=>{try{await(r.handleLLMStart?.(e,[t],i,this._parentRunId,a,this.tags,this.metadata,c))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}}),r.awaitHandlers)}))),new w(i,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)})))}async handleChatModelStart(e,t,r=void 0,s=void 0,a=void 0,o=void 0,c=void 0,d=void 0){return Promise.all(t.map((async(t,s)=>{const o=0===s&&r?r:(0,n.A)();return await Promise.all(this.handlers.map((r=>{if(!r.ignoreLLM)return(0,u.isBaseTracer)(r)&&r._createRunForChatModelStart(e,[t],o,this._parentRunId,a,this.tags,this.metadata,d),(0,l.consumeCallback)((async()=>{try{if(r.handleChatModelStart)await(r.handleChatModelStart?.(e,[t],o,this._parentRunId,a,this.tags,this.metadata,d));else if(r.handleLLMStart){const n=(0,i.Sw)(t);await(r.handleLLMStart?.(e,[n],o,this._parentRunId,a,this.tags,this.metadata,d))}}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}}),r.awaitHandlers)}))),new w(o,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)})))}async handleChainStart(e,t,r=(0,n.A)(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map((n=>{if(!n.ignoreChain)return(0,u.isBaseTracer)(n)&&n._createRunForChainStart(e,t,r,this._parentRunId,this.tags,this.metadata,s,o),(0,l.consumeCallback)((async()=>{try{await(n.handleChainStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s,o))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleChainStart: ${e}`),n.raiseError)throw e}}),n.awaitHandlers)}))),new v(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,r=(0,n.A)(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map((n=>{if(!n.ignoreAgent)return(0,u.isBaseTracer)(n)&&n._createRunForToolStart(e,t,r,this._parentRunId,this.tags,this.metadata,o),(0,l.consumeCallback)((async()=>{try{await(n.handleToolStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,o))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleToolStart: ${e}`),n.raiseError)throw e}}),n.awaitHandlers)}))),new _(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,r=(0,n.A)(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map((n=>{if(!n.ignoreRetriever)return(0,u.isBaseTracer)(n)&&n._createRunForRetrieverStart(e,t,r,this._parentRunId,this.tags,this.metadata,o),(0,l.consumeCallback)((async()=>{try{await(n.handleRetrieverStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,o))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleRetrieverStart: ${e}`),n.raiseError)throw e}}),n.awaitHandlers)}))),new b(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,r,n,s){await Promise.all(this.handlers.map((n=>(0,l.consumeCallback)((async()=>{if(!n.ignoreCustomEvent)try{await(n.handleCustomEvent?.(e,t,r,this.tags,this.metadata))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleCustomEvent: ${e}`),n.raiseError)throw e}}),n.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 k(this._parentRunId);for(const e of this.handlers){const t=this.inheritableHandlers.includes(e);r.addHandler(e,t)}for(const e of this.tags){const t=this.inheritableTags.includes(e);r.addTags([e],t)}for(const e of Object.keys(this.metadata)){const t=Object.keys(this.inheritableMetadata).includes(e);r.addMetadata({[e]:this.metadata[e]},t)}for(const n of e)r.handlers.filter((e=>"console_callback_handler"===e.name)).some((e=>e.name===n.name))||r.addHandler(n,t);return r}static fromHandlers(e){class t extends s.BaseCallbackHandler{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:(0,n.A)()}),Object.assign(this,e)}}const r=new this;return r.addHandler(new t),r}static configure(e,t,r,n,s,a,i){return this._configureSync(e,t,r,n,s,a,i)}static _configureSync(e,t,r,n,i,l,u){let d;(e||t)&&(Array.isArray(e)||!e?(d=new k,d.setHandlers(e?.map(S)??[],!0)):d=e,d=d.copy(Array.isArray(t)?t.map(S):t?.handlers,!1));const p="true"===(0,o.getEnvironmentVariable)("LANGCHAIN_VERBOSE")||u?.verbose,f=c.LangChainTracer.getTraceableRunTree()?.tracingEnabled||(e=>void 0!==e?e:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find((e=>"true"===(0,o.getEnvironmentVariable)(e))))(),g=f||((0,o.getEnvironmentVariable)("LANGCHAIN_TRACING")??!1);if(p||g){if(d||(d=new k),p&&!d.handlers.some((e=>e.name===a.ConsoleCallbackHandler.prototype.name))){const e=new a.ConsoleCallbackHandler;d.addHandler(e,!0)}if(g&&!d.handlers.some((e=>"langchain_tracer"===e.name))&&f){const e=new c.LangChainTracer;d.addHandler(e,!0),d._parentRunId=c.LangChainTracer.getTraceableRunTree()?.id??d._parentRunId}}for(const{contextVar:e,inheritable:t=!0,handlerClass:r,envVar:n}of m()){const a=n&&"true"===(0,o.getEnvironmentVariable)(n)&&r;let i;const c=void 0!==e?h(e):void 0;c&&(0,s.isBaseCallbackHandler)(c)?i=c:a&&(i=new r({})),void 0!==i&&(d||(d=new k),d.handlers.some((e=>e.name===i.name))||d.addHandler(i,t))}return(r||n)&&d&&(d.addTags(r??[]),d.addTags(n??[],!1)),(i||l)&&d&&(d.addMetadata(i??{}),d.addMetadata(l??{},!1)),d}}function S(e){return"name"in e?e:s.BaseCallbackHandler.fromMethods(e)}class E{constructor(e,t){Object.defineProperty(this,"groupName",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"runManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async getTraceGroupCallbackManager(e,t,r){const n=new c.LangChainTracer(r),s=await k.configure([n]),a=await(s?.handleChainStart({lc:1,type:"not_implemented",id:["langchain","callbacks","groups",e]},t??{}));if(!a)throw new Error("Failed to create run group callback manager.");return a}async start(e){return this.runManager||(this.runManager=await this.getTraceGroupCallbackManager(this.groupName,e,this.options)),this.runManager.getChild()}async error(e){this.runManager&&(await this.runManager.handleChainError(e),this.runManager=void 0)}async end(e){this.runManager&&(await this.runManager.handleChainEnd(e??{}),this.runManager=void 0)}}async function x(e,t,...r){const n=new E(e.name,e),s=await n.start({...r});try{const e=await t(s,...r);return await n.end((a=e,i="output",a&&!Array.isArray(a)&&"object"==typeof a?a:{[i]:a})),e}catch(e){throw await n.error(e),e}var a,i}},5200:(e,t,r)=>{"use strict";const n=r(560);e.exports=(e,t,r)=>n(e,t,r)<=0},5230:(e,t,r)=>{"use strict";r.d(t,{A:()=>u});const n={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};var s,a=new Uint8Array(16);function i(){if(!s&&!(s="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return s(a)}for(var o=[],c=0;c<256;++c)o.push((c+256).toString(16).slice(1));function l(e,t=0){return(o[e[t+0]]+o[e[t+1]]+o[e[t+2]]+o[e[t+3]]+"-"+o[e[t+4]]+o[e[t+5]]+"-"+o[e[t+6]]+o[e[t+7]]+"-"+o[e[t+8]]+o[e[t+9]]+"-"+o[e[t+10]]+o[e[t+11]]+o[e[t+12]]+o[e[t+13]]+o[e[t+14]]+o[e[t+15]]).toLowerCase()}const u=function(e,t,r){if(n.randomUUID&&!t&&!e)return n.randomUUID();var s=(e=e||{}).random||(e.rng||i)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){r=r||0;for(var a=0;a<16;++a)t[r+a]=s[a];return t}return l(s)}},5311:(e,t,r)=>{"use strict";r.r(t),r.d(t,{BasePromptValue:()=>i,ChatPromptValue:()=>c,ImagePromptValue:()=>l,StringPromptValue:()=>o});var n=r(7380),s=r(5454),a=r(6362);class i extends n.Serializable{}class o extends i{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 s.xc(this.value)]}}class c extends i{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(0,a.Sw)(this.messages)}toChatMessages(){return this.messages}}class l extends i{static lc_name(){return"ImagePromptValue"}constructor(e){"imageUrl"in e||(e={imageUrl: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,"imageUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new s.xc({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}},5342:(e,t,r)=>{"use strict";const n=r(7075);e.exports=(e,t,r)=>n(e,t,"<",r)},5454:(e,t,r)=>{"use strict";r.d(t,{GZ:()=>o,a7:()=>a,di:()=>i,xc:()=>s});var n=r(3490);class s extends n.XQ{static lc_name(){return"HumanMessage"}_getType(){return"human"}constructor(e,t){super(e,t)}}class a extends n.gj{static lc_name(){return"HumanMessageChunk"}_getType(){return"human"}constructor(e,t){super(e,t)}concat(e){return new a({content:(0,n._I)(this.content,e.content),additional_kwargs:(0,n.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,n.ns)(this.response_metadata,e.response_metadata),id:this.id??e.id})}}function i(e){return"human"===e.getType()}function o(e){return"human"===e.getType()}},5571:(e,t,r)=>{"use strict";const n=r(7075);e.exports=(e,t,r)=>n(e,t,">",r)},5580:(e,t,r)=>{"use strict";const n=r(560);e.exports=(e,t,r)=>n(e,t,r)>0},5617:(e,t,r)=>{e.exports=r(8303)},5960:(e,t,r)=>{"use strict";r.r(t),r.d(t,{BaseCallbackHandler:()=>c,callbackHandlerPrefersStreaming:()=>o,isBaseCallbackHandler:()=>l});var n=r(9120),s=r(7380),a=r(9583);class i{}function o(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}class c extends i{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,(0,s.get_lc_unique_name)(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:"false"===(0,a.getEnvironmentVariable)("LANGCHAIN_CALLBACKS_BACKGROUND")}),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 s.Serializable.prototype.toJSON.call(this)}toJSONNotImplemented(){return s.Serializable.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){return new class extends c{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:n.A()}),Object.assign(this,e)}}}}const l=e=>{const t=e;return void 0!==t&&"function"==typeof t.copy&&"string"==typeof t.name&&"boolean"==typeof t.awaitHandlers}},6150:(e,t,r)=>{"use strict";r.d(t,{X6:()=>v,UD:()=>T});var n={};r.r(n),r.d(n,{JsonPatchError:()=>m,_areEquals:()=>E,applyOperation:()=>w,applyPatch:()=>v,applyReducer:()=>_,deepClone:()=>f,getValueByPointer:()=>b,validate:()=>S,validator:()=>k});const s=Object.prototype.hasOwnProperty;function a(e,t){return s.call(e,t)}function i(e){if(Array.isArray(e)){const t=new Array(e.length);for(let e=0;e=48&&n<=57))return!1;t++}return!0}function l(e){return-1===e.indexOf("/")&&-1===e.indexOf("~")?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function u(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function d(e){if(void 0===e)return!0;if(e)if(Array.isArray(e)){for(let t=0,r=e.length;t0&&"constructor"==i[f-1]))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(r&&void 0===l&&(void 0===p[d]?l=i.slice(0,f).join("/"):f==b-1&&(l=t.path),void 0!==l&&h(t,0,e,l)),f++,Array.isArray(p)){if("-"===d)d=p.length;else{if(r&&!c(d))throw new m("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",a,t,e);c(d)&&(d=~~d)}if(f>=b){if(r&&"add"===t.op&&d>p.length)throw new m("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a,t,e);const n=y[t.op].call(t,p,d,e);if(!1===n.test)throw new m("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return n}}else if(f>=b){const r=g[t.op].call(t,p,d,e);if(!1===r.test)throw new m("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return r}if(p=p[d],r&&f0)throw new m('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new m("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new m("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&d(e.value))throw new m("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);if(r)if("add"==e.op){var s=e.path.split("/").length,a=n.split("/").length;if(s!==a+1&&s!==a)throw new m("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==n)throw new m("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if("move"===e.op||"copy"===e.op){var i=S([{op:"_get",path:e.from,value:void 0}],r);if(i&&"OPERATION_PATH_UNRESOLVABLE"===i.name)throw new m("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}function S(e,t,r){try{if(!Array.isArray(e))throw new m("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)v(o(t),o(e),r||!0);else{r=r||k;for(var n=0;n=0;h--){var p=e[f=u[h]];if(!a(t,f)||void 0===t[f]&&void 0!==p&&!1===Array.isArray(t))Array.isArray(e)===Array.isArray(t)?(s&&r.push({op:"test",path:n+"/"+l(f),value:o(p)}),r.push({op:"remove",path:n+"/"+l(f)}),d=!0):(s&&r.push({op:"test",path:n,value:e}),r.push({op:"replace",path:n,value:t}),!0);else{var m=t[f];"object"==typeof p&&null!=p&&"object"==typeof m&&null!=m&&Array.isArray(p)===Array.isArray(m)?x(p,m,r,n+"/"+l(f),s):p!==m&&(s&&r.push({op:"test",path:n+"/"+l(f),value:o(p)}),r.push({op:"replace",path:n+"/"+l(f),value:o(m)}))}}if(d||c.length!=u.length)for(h=0;h{"use strict";const n=r(3908),s=r(144),{safeRe:a,t:i}=r(9718);e.exports=(e,t)=>{if(e instanceof n)return e;if("number"==typeof e&&(e=String(e)),"string"!=typeof e)return null;let r=null;if((t=t||{}).rtl){const n=t.includePrerelease?a[i.COERCERTLFULL]:a[i.COERCERTL];let s;for(;(s=n.exec(e))&&(!r||r.index+r[0].length!==e.length);)r&&s.index+s[0].length===r.index+r[0].length||(r=s),n.lastIndex=s.index+s[1].length+s[2].length;n.lastIndex=-1}else r=e.match(t.includePrerelease?a[i.COERCEFULL]:a[i.COERCE]);if(null===r)return null;const o=r[2],c=r[3]||"0",l=r[4]||"0",u=t.includePrerelease&&r[5]?`-${r[5]}`:"",d=t.includePrerelease&&r[6]?`+${r[6]}`:"";return s(`${o}.${c}.${l}${u}${d}`,t)}},6232:(e,t,r)=>{"use strict";r.d(t,{m:()=>s});const n={};function s(e){n[e]||(console.warn(e),n[e]=!0)}},6254:(e,t,r)=>{"use strict";const n=r(3908);e.exports=(e,t)=>new n(e,t).minor},6279:(e,t,r)=>{"use strict";r.d(t,{C:()=>i});var n=r(5311),s=r(6993),a=r(9849);class i extends s.m{static lc_name(){return"ImagePromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","image"]}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.template=e.template,this.templateFormat=e.templateFormat??this.templateFormat,this.validateTemplate=e.validateTemplate??this.validateTemplate,this.additionalContentFields=e.additionalContentFields,this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),(0,a.Ns)([{type:"image_url",image_url:this.template}],this.templateFormat,e)}}_getPromptType(){return"prompt"}async partial(e){const t=this.inputVariables.filter((t=>!(t in e))),r={...this.partialVariables??{},...e},n={...this,inputVariables:t,partialVariables:r};return new i(n)}async format(e){const t={};for(const[r,n]of Object.entries(this.template))t[r]="string"==typeof n?(0,a.Xm)(n,this.templateFormat,e):n;const r=e.url||t.url,n=e.detail||t.detail;if(!r)throw new Error("Must provide either an image URL.");if("string"!=typeof r)throw new Error("url must be a string.");const s={url:r};return n&&(s.detail=n),s}async formatPromptValue(e){const t=await this.format(e);return new n.ImagePromptValue(t)}}},6362:(e,t,r)=>{"use strict";r.d(t,{Js:()=>b,K0:()=>m,Pz:()=>g,Sw:()=>f,ih:()=>w,rf:()=>y});var n=r(1368),s=r(199),a=r(7765),i=r(3490),o=r(4301),c=r(8675),l=r(5454),u=r(7974),d=r(8009);function h(e){return(0,s.Ky)(e)?e:"string"==typeof e.id&&"function"===e.type&&"object"==typeof e.function&&null!==e.function&&"arguments"in e.function&&"string"==typeof e.function.arguments&&"name"in e.function&&"string"==typeof e.function.name?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function p(e){let t,r;if("object"==typeof(s=e)&&null!=s&&1===s.lc&&Array.isArray(s.id)&&null!=s.kwargs&&"object"==typeof s.kwargs){const n=e.id.at(-1);t="HumanMessage"===n||"HumanMessageChunk"===n?"user":"AIMessage"===n||"AIMessageChunk"===n?"assistant":"SystemMessage"===n||"SystemMessageChunk"===n?"system":"FunctionMessage"===n||"FunctionMessageChunk"===n?"function":"ToolMessage"===n||"ToolMessageChunk"===n?"tool":"unknown",r=e.kwargs}else{const{type:n,...s}=e;t=n,r=s}var s;if("human"===t||"user"===t)return new l.xc(r);if("ai"===t||"assistant"===t){const{tool_calls:e,...t}=r;if(!Array.isArray(e))return new a.Od(r);const n=e.map(h);return new a.Od({...t,tool_calls:n})}if("system"===t)return new u.tn(r);if("developer"===t)return new u.tn({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if("tool"===t&&"tool_call_id"in r)return new d.uf({...r,content:r.content,tool_call_id:r.tool_call_id,name:r.name});throw(0,n.Y)(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\n\nReceived: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}function m(e){if("string"==typeof e)return new l.xc(e);if((0,i.ny)(e))return e;if(Array.isArray(e)){const[t,r]=e;return p({type:t,content:r})}if((0,i.dp)(e)){const{role:t,...r}=e;return p({...r,type:t})}return p(e)}function f(e,t="Human",r="AI"){const n=[];for(const s of e){let e;if("human"===s._getType())e=t;else if("ai"===s._getType())e=r;else if("system"===s._getType())e="System";else if("function"===s._getType())e="Function";else if("tool"===s._getType())e="Tool";else{if("generic"!==s._getType())throw new Error(`Got unsupported message type: ${s._getType()}`);e=s.role}const a=s.name?`${s.name}, `:"",i="string"==typeof s.content?s.content:JSON.stringify(s.content,null,2);n.push(`${e}: ${a}${i}`)}return n.join("\n")}function g(e){const t=function(e){if(void 0!==e.data)return e;{const t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}(e);switch(t.type){case"human":return new l.xc(t.data);case"ai":return new a.Od(t.data);case"system":return new u.tn(t.data);case"function":if(void 0===t.data.name)throw new Error("Name must be defined for function messages");return new c.mg(t.data);case"tool":if(void 0===t.data.tool_call_id)throw new Error("Tool call ID must be defined for tool messages");return new d.uf(t.data);case"generic":if(void 0===t.data.role)throw new Error("Role must be defined for chat messages");return new o.cM(t.data);default:throw new Error(`Got unexpected type: ${t.type}`)}}function y(e){return e.map(g)}function b(e){return e.map((e=>e.toDict()))}function w(e){const t=e._getType();if("human"===t)return new l.a7({...e});if("ai"===t){let t={...e};return"tool_calls"in t&&(t={...t,tool_call_chunks:t.tool_calls?.map((e=>({...e,type:"tool_call_chunk",index:void 0,args:JSON.stringify(e.args)})))}),new a.H({...t})}if("system"===t)return new u.uU({...e});if("function"===t)return new c.FK({...e});if(o.cM.isInstance(e))return new o.XU({...e});throw new Error("Unknown message type.")}},6585:e=>{var t=1e3,r=60*t,n=60*r,s=24*n,a=7*s,i=365.25*s;function o(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}e.exports=function(e,c){c=c||{};var l=typeof e;if("string"===l&&e.length>0)return function(e){if((e=String(e)).length>100)return;var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!o)return;var c=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*i;case"weeks":case"week":case"w":return c*a;case"days":case"day":case"d":return c*s;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*r;case"seconds":case"second":case"secs":case"sec":case"s":return c*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(e);if("number"===l&&isFinite(e))return c.long?function(e){var a=Math.abs(e);if(a>=s)return o(e,a,s,"day");if(a>=n)return o(e,a,n,"hour");if(a>=r)return o(e,a,r,"minute");if(a>=t)return o(e,a,t,"second");return e+" ms"}(e):function(e){var a=Math.abs(e);if(a>=s)return Math.round(e/s)+"d";if(a>=n)return Math.round(e/n)+"h";if(a>=r)return Math.round(e/r)+"m";if(a>=t)return Math.round(e/t)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},6641:(e,t,r)=>{"use strict";const n=r(4617);class s extends Error{constructor(e){super(e),this.name="TimeoutError"}}const a=(e,t,r)=>new Promise(((a,i)=>{if("number"!=typeof t||t<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(t===1/0)return void a(e);const o=setTimeout((()=>{if("function"==typeof r){try{a(r())}catch(e){i(e)}return}const n=r instanceof Error?r:new s("string"==typeof r?r:`Promise timed out after ${t} milliseconds`);"function"==typeof e.cancel&&e.cancel(),i(n)}),t);n(e.then(a,i),(()=>{clearTimeout(o)}))}));e.exports=a,e.exports.default=a,e.exports.TimeoutError=s},6780:(e,t,r)=>{"use strict";const n=r(8311);e.exports=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r))},6874:e=>{"use strict";const t=Number.MAX_SAFE_INTEGER||9007199254740991;e.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:t,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}},6906:(e,t,r)=>{"use strict";r.r(t),r.d(t,{ConsoleCallbackHandler:()=>u});var n=r(9418),s=r(1590);function a(e,t){return`${e.open}${t}${e.close}`}function i(e,t){try{return JSON.stringify(e,null,2)}catch(e){return t}}function o(e){return"string"==typeof e?e.trim():null==e?e:i(e,e.toString())}function c(e){if(!e.end_time)return"";const t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}const{color:l}=n;class u extends s.BaseTracer{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 e=this.runMap.get(r.parent_run_id);if(!e)break;t.push(e),r=e}return t}getBreadcrumbs(e){const t=[...this.getParents(e).reverse(),e].map(((e,t,r)=>{const s=`${e.execution_order}:${e.run_type}:${e.name}`;return t===r.length-1?a(n.bold,s):s})).join(" > ");return a(l.grey,t)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.green,"[chain/start]")} [${t}] Entering Chain run with input: ${i(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.cyan,"[chain/end]")} [${t}] [${c(e)}] Exiting Chain run with output: ${i(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.red,"[chain/error]")} [${t}] [${c(e)}] Chain run errored with error: ${i(e.error,"[error]")}`)}onLLMStart(e){const t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map((e=>e.trim()))}:e.inputs;console.log(`${a(l.green,"[llm/start]")} [${t}] Entering LLM run with input: ${i(r,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.cyan,"[llm/end]")} [${t}] [${c(e)}] Exiting LLM run with output: ${i(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.red,"[llm/error]")} [${t}] [${c(e)}] LLM run errored with error: ${i(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.green,"[tool/start]")} [${t}] Entering Tool run with input: "${o(e.inputs.input)}"`)}onToolEnd(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.cyan,"[tool/end]")} [${t}] [${c(e)}] Exiting Tool run with output: "${o(e.outputs?.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.red,"[tool/error]")} [${t}] [${c(e)}] Tool run errored with error: ${i(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${i(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.cyan,"[retriever/end]")} [${t}] [${c(e)}] Exiting Retriever run with output: ${i(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.red,"[retriever/error]")} [${t}] [${c(e)}] Retriever run errored with error: ${i(e.error,"[error]")}`)}onAgentAction(e){const t=e,r=this.getBreadcrumbs(e);console.log(`${a(l.blue,"[agent/action]")} [${r}] Agent selected action: ${i(t.actions[t.actions.length-1],"[action]")}`)}}},6953:(e,t,r)=>{"use strict";const n=r(144);e.exports=(e,t)=>{const r=n(e,t);return r?r.version:null}},6968:(e,t,r)=>{"use strict";r.d(t,{X0:()=>i,hr:()=>s,pH:()=>a});const n=Symbol.for("ls:tracing_async_local_storage"),s=Symbol.for("lc:context_variables"),a=e=>{globalThis[n]=e},i=()=>globalThis[n]},6993:(e,t,r)=>{"use strict";r.d(t,{m:()=>s});var n=r(3313);class s extends n.YN{get lc_attributes(){return{partialVariables:void 0}}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","prompts",this._getPromptType()]}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"partialVariables",{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,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const{inputVariables:t}=e;if(t.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}async mergePartialAndUserVariables(e){const t=this.partialVariables??{},r={};for(const[e,n]of Object.entries(t))r[e]="string"==typeof n?n:await n();return{...r,...e}}async invoke(e,t){const r={...this.metadata,...t?.metadata},n=[...this.tags??[],...t?.tags??[]];return this._callWithConfig((e=>this.formatPromptValue(e)),e,{...t,tags:n,metadata:r,runType:"prompt"})}serialize(){throw new Error("Use .toJSON() instead")}static async deserialize(e){switch(e._type){case"prompt":{const{PromptTemplate:t}=await Promise.resolve().then(r.bind(r,3650));return t.deserialize(e)}case void 0:{const{PromptTemplate:t}=await Promise.resolve().then(r.bind(r,3650));return t.deserialize({...e,_type:"prompt"})}case"few_shot":{const{FewShotPromptTemplate:t}=await Promise.resolve().then(r.bind(r,2771));return t.deserialize(e)}default:throw new Error(`Invalid prompt type in config: ${e._type}`)}}}},7059:(e,t,r)=>{"use strict";const n=r(560);e.exports=(e,t,r)=>n(e,t,r)<0},7075:(e,t,r)=>{"use strict";const n=r(3908),s=r(3904),{ANY:a}=s,i=r(8311),o=r(7638),c=r(5580),l=r(7059),u=r(5200),d=r(4089);e.exports=(e,t,r,h)=>{let p,m,f,g,y;switch(e=new n(e,h),t=new i(t,h),r){case">":p=c,m=u,f=l,g=">",y=">=";break;case"<":p=l,m=d,f=c,g="<",y="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(o(e,t,h))return!1;for(let r=0;r{e.semver===a&&(e=new s(">=0.0.0")),i=i||e,o=o||e,p(e.semver,i.semver,h)?i=e:f(e.semver,o.semver,h)&&(o=e)})),i.operator===g||i.operator===y)return!1;if((!o.operator||o.operator===g)&&m(e,o.semver))return!1;if(o.operator===y&&f(e,o.semver))return!1}return!0}},7272:e=>{"use strict";const t="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};e.exports=t},7380:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Serializable:()=>o,get_lc_unique_name:()=>i});var n=r(7492);function s(e){return Array.isArray(e)?[...e]:{...e}}function a(e,t){const r=s(e);for(const[e,n]of Object.entries(t)){const[t,...a]=e.split(".").reverse();let i=r;for(const e of a.reverse()){if(void 0===i[e])break;i[e]=s(i[e]),i=i[e]}void 0!==i[t]&&(i[t]={lc:1,type:"secret",id:[n]})}return r}function i(e){const t=Object.getPrototypeOf(e);return"function"==typeof e.lc_name&&("function"!=typeof t.lc_name||e.lc_name()!==t.lc_name())?e.lc_name():e.name}class o{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,i(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}),void 0!==this.lc_serializable_keys?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter((([e])=>this.lc_serializable_keys?.includes(e)))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof o||"object"!=typeof this.lc_kwargs||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},t={},r=Object.keys(this.lc_kwargs).reduce(((e,t)=>(e[t]=t in this?this[t]:this.lc_kwargs[t],e)),{});for(let n=Object.getPrototypeOf(this);n;n=Object.getPrototypeOf(n))Object.assign(e,Reflect.get(n,"lc_aliases",this)),Object.assign(t,Reflect.get(n,"lc_secrets",this)),Object.assign(r,Reflect.get(n,"lc_attributes",this));return Object.keys(t).forEach((e=>{let t=this,n=r;const[s,...a]=e.split(".").reverse();for(const e of a.reverse()){if(!(e in t)||void 0===t[e])return;e in n&&void 0!==n[e]||("object"==typeof t[e]&&null!=t[e]?n[e]={}:Array.isArray(t[e])&&(n[e]=[])),t=t[e],n=n[e]}s in t&&void 0!==t[s]&&(n[s]=n[s]||t[s])})),{lc:1,type:"constructor",id:this.lc_id,kwargs:(0,n.d4)(Object.keys(t).length?a(r,t):r,n.$o,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}},7414:(e,t,r)=>{"use strict";const n=r(144);e.exports=(e,t)=>{const r=n(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null}},7492:(e,t,r)=>{"use strict";r.d(t,{$o:()=>a,O3:()=>i,d4:()=>o});var n=r(9478),s=r(2729);function a(e,t){return t?.[e]||n(e)}function i(e,t){return t?.[e]||s(e)}function o(e,t,r){const n={};for(const s in e)Object.hasOwn(e,s)&&(n[t(s,r)]=e[s]);return n}},7526:(e,t)=>{"use strict";t.byteLength=function(e){var t=o(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,a=o(e),i=a[0],c=a[1],l=new s(function(e,t,r){return 3*(t+r)/4-r}(0,i,c)),u=0,d=c>0?i-4:i;for(r=0;r>16&255,l[u++]=t>>8&255,l[u++]=255&t;2===c&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,l[u++]=255&t);1===c&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,l[u++]=t>>8&255,l[u++]=255&t);return l},t.fromByteArray=function(e){for(var t,n=e.length,s=n%3,a=[],i=16383,o=0,l=n-s;ol?l:o+i));1===s?(t=e[n-1],a.push(r[t>>2]+r[t<<4&63]+"==")):2===s&&(t=(e[n-2]<<8)+e[n-1],a.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return a.join("")};for(var r=[],n=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)r[i]=a[i],n[a.charCodeAt(i)]=i;function o(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function c(e,t,n){for(var s,a,i=[],o=t;o>18&63]+r[a>>12&63]+r[a>>6&63]+r[63&a]);return i.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},7631:(e,t,r)=>{"use strict";const n=r(8311);e.exports=(e,t)=>new n(e,t).set.map((e=>e.map((e=>e.value)).join(" ").trim().split(" ")))},7638:(e,t,r)=>{"use strict";const n=r(8311);e.exports=(e,t,r)=>{try{t=new n(t,r)}catch(e){return!1}return t.test(e)}},7765:(e,t,r)=>{"use strict";r.d(t,{H:()=>l,KX:()=>o,Od:()=>i,jm:()=>c});var n=r(780),s=r(3490),a=r(8009);class i extends s.XQ{get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e,t){let r;if("string"==typeof e)r={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:t??{}};else{r=e;const t=r.additional_kwargs?.tool_calls,n=r.tool_calls;null!=t&&t.length>0&&(void 0===n||0===n.length)&&console.warn(["New LangChain packages are available that more efficiently handle","tool calling.\n\nPlease upgrade your packages to versions that set","message tool calls. e.g., `yarn add @langchain/anthropic`,","yarn add @langchain/openai`, etc."].join(" "));try{if(null!=t&&void 0===n){const[e,n]=(0,a.p1)(t);r.tool_calls=e??[],r.invalid_tool_calls=n??[]}else r.tool_calls=r.tool_calls??[],r.invalid_tool_calls=r.invalid_tool_calls??[]}catch(e){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}),"string"!=typeof r&&(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 o(e){return"ai"===e._getType()}function c(e){return"ai"===e._getType()}class l extends s.gj{constructor(e){let t;if("string"==typeof e)t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(void 0===e.tool_call_chunks)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0};else{const r=[],s=[];for(const t of e.tool_call_chunks){let e={};try{if(e=(0,n.d)(t.args||"{}"),null===e||"object"!=typeof e||Array.isArray(e))throw new Error("Malformed tool call chunk args.");r.push({name:t.name??"",args:e,id:t.id,type:"tool_call"})}catch(e){s.push({name:t.name,args:t.args,id:t.id,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:r,invalid_tool_calls:s,usage_metadata:void 0!==e.usage_metadata?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){const t={content:(0,s._I)(this.content,e.content),additional_kwargs:(0,s.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,s.ns)(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(void 0!==this.tool_call_chunks||void 0!==e.tool_call_chunks){const r=(0,s.Vt)(this.tool_call_chunks,e.tool_call_chunks);void 0!==r&&r.length>0&&(t.tool_call_chunks=r)}if(void 0!==this.usage_metadata||void 0!==e.usage_metadata){const r={...(void 0!==this.usage_metadata?.input_token_details?.audio||void 0!==e.usage_metadata?.input_token_details?.audio)&&{audio:(this.usage_metadata?.input_token_details?.audio??0)+(e.usage_metadata?.input_token_details?.audio??0)},...(void 0!==this.usage_metadata?.input_token_details?.cache_read||void 0!==e.usage_metadata?.input_token_details?.cache_read)&&{cache_read:(this.usage_metadata?.input_token_details?.cache_read??0)+(e.usage_metadata?.input_token_details?.cache_read??0)},...(void 0!==this.usage_metadata?.input_token_details?.cache_creation||void 0!==e.usage_metadata?.input_token_details?.cache_creation)&&{cache_creation:(this.usage_metadata?.input_token_details?.cache_creation??0)+(e.usage_metadata?.input_token_details?.cache_creation??0)}},n={...(void 0!==this.usage_metadata?.output_token_details?.audio||void 0!==e.usage_metadata?.output_token_details?.audio)&&{audio:(this.usage_metadata?.output_token_details?.audio??0)+(e.usage_metadata?.output_token_details?.audio??0)},...(void 0!==this.usage_metadata?.output_token_details?.reasoning||void 0!==e.usage_metadata?.output_token_details?.reasoning)&&{reasoning:(this.usage_metadata?.output_token_details?.reasoning??0)+(e.usage_metadata?.output_token_details?.reasoning??0)}},s=this.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},a=e.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},i={input_tokens:s.input_tokens+a.input_tokens,output_tokens:s.output_tokens+a.output_tokens,total_tokens:s.total_tokens+a.total_tokens,...Object.keys(r).length>0&&{input_token_details:r},...Object.keys(n).length>0&&{output_token_details:n}};t.usage_metadata=i}return new l(t)}}},7833:(e,t,r)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),t.splice(s,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(736)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},7974:(e,t,r)=>{"use strict";r.d(t,{UF:()=>o,X4:()=>i,tn:()=>s,uU:()=>a});var n=r(3490);class s extends n.XQ{static lc_name(){return"SystemMessage"}_getType(){return"system"}constructor(e,t){super(e,t)}}class a extends n.gj{static lc_name(){return"SystemMessageChunk"}_getType(){return"system"}constructor(e,t){super(e,t)}concat(e){return new a({content:(0,n._I)(this.content,e.content),additional_kwargs:(0,n.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,n.ns)(this.response_metadata,e.response_metadata),id:this.id??e.id})}}function i(e){return"system"===e._getType()}function o(e){return"system"===e._getType()}},8009:(e,t,r)=>{"use strict";r.d(t,{P:()=>l,dr:()=>i,fK:()=>s,p1:()=>o,uf:()=>a,wk:()=>c});var n=r(3490);function s(e){return null!=e&&"object"==typeof e&&"lc_direct_tool_output"in e&&!0===e.lc_direct_tool_output}class a extends n.XQ{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(e,t,r){"string"==typeof e&&(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,"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}_getType(){return"tool"}static isInstance(e){return"tool"===e._getType()}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}class i extends n.gj{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 i({content:(0,n._I)(this.content,e.content),additional_kwargs:(0,n.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,n.ns)(this.response_metadata,e.response_metadata),artifact:(0,n.F7)(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:(0,n.Iv)(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}function o(e){const t=[],r=[];for(const n of e)if(n.function){const e=n.function.name;try{const r={name:e||"",args:JSON.parse(n.function.arguments)||{},id:n.id};t.push(r)}catch(t){r.push({name:e,args:n.function.arguments,id:n.id,error:"Malformed args."})}}return[t,r]}function c(e){return"tool"===e._getType()}function l(e){return"tool"===e._getType()}},8028:(e,t,r)=>{"use strict";r.r(t),r.d(t,{ChatGenerationChunk:()=>a,GenerationChunk:()=>s,RUN_KEY:()=>n});const n="__run";class s{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 s({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}}class a extends s{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 a({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo},message:this.message.concat(e.message)})}}},8303:(e,t,r)=>{var n=r(3961);t.operation=function(e){var r=t.timeouts(e);return new n(r,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})},t.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],s=0;s{"use strict";const n=/\s+/g;class s{constructor(e,t){if(t=i(t),e instanceof s)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new s(e.raw,t);if(e instanceof o)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(n," "),this.set=this.raw.split("||").map((e=>this.parseRange(e.trim()))).filter((e=>e.length)),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const e=this.set[0];if(this.set=this.set.filter((e=>!y(e[0]))),0===this.set.length)this.set=[e];else if(this.set.length>1)for(const e of this.set)if(1===e.length&&b(e[0])){this.set=[e];break}}this.formatted=void 0}get range(){if(void 0===this.formatted){this.formatted="";for(let e=0;e0&&(this.formatted+="||");const t=this.set[e];for(let e=0;e0&&(this.formatted+=" "),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){const t=((this.options.includePrerelease&&f)|(this.options.loose&&g))+":"+e,r=a.get(t);if(r)return r;const n=this.options.loose,s=n?u[d.HYPHENRANGELOOSE]:u[d.HYPHENRANGE];e=e.replace(s,A(this.options.includePrerelease)),c("hyphen replace",e),e=e.replace(u[d.COMPARATORTRIM],h),c("comparator trim",e),e=e.replace(u[d.TILDETRIM],p),c("tilde trim",e),e=e.replace(u[d.CARETTRIM],m),c("caret trim",e);let i=e.split(" ").map((e=>v(e,this.options))).join(" ").split(/\s+/).map((e=>O(e,this.options)));n&&(i=i.filter((e=>(c("loose invalid filter",e,this.options),!!e.match(u[d.COMPARATORLOOSE]))))),c("range list",i);const l=new Map,b=i.map((e=>new o(e,this.options)));for(const e of b){if(y(e))return[e];l.set(e.value,e)}l.size>1&&l.has("")&&l.delete("");const w=[...l.values()];return a.set(t,w),w}intersects(e,t){if(!(e instanceof s))throw new TypeError("a Range is required");return this.set.some((r=>w(r,t)&&e.set.some((e=>w(e,t)&&r.every((r=>e.every((e=>r.intersects(e,t)))))))))}test(e){if(!e)return!1;if("string"==typeof e)try{e=new l(e,this.options)}catch(e){return!1}for(let t=0;t"<0.0.0-0"===e.value,b=e=>""===e.value,w=(e,t)=>{let r=!0;const n=e.slice();let s=n.pop();for(;r&&n.length;)r=n.every((e=>s.intersects(e,t))),s=n.pop();return r},v=(e,t)=>(c("comp",e,t),e=E(e,t),c("caret",e),e=k(e,t),c("tildes",e),e=T(e,t),c("xrange",e),e=P(e,t),c("stars",e),e),_=e=>!e||"x"===e.toLowerCase()||"*"===e,k=(e,t)=>e.trim().split(/\s+/).map((e=>S(e,t))).join(" "),S=(e,t)=>{const r=t.loose?u[d.TILDELOOSE]:u[d.TILDE];return e.replace(r,((t,r,n,s,a)=>{let i;return c("tilde",e,t,r,n,s,a),_(r)?i="":_(n)?i=`>=${r}.0.0 <${+r+1}.0.0-0`:_(s)?i=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`:a?(c("replaceTilde pr",a),i=`>=${r}.${n}.${s}-${a} <${r}.${+n+1}.0-0`):i=`>=${r}.${n}.${s} <${r}.${+n+1}.0-0`,c("tilde return",i),i}))},E=(e,t)=>e.trim().split(/\s+/).map((e=>x(e,t))).join(" "),x=(e,t)=>{c("caret",e,t);const r=t.loose?u[d.CARETLOOSE]:u[d.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,((t,r,s,a,i)=>{let o;return c("caret",e,t,r,s,a,i),_(r)?o="":_(s)?o=`>=${r}.0.0${n} <${+r+1}.0.0-0`:_(a)?o="0"===r?`>=${r}.${s}.0${n} <${r}.${+s+1}.0-0`:`>=${r}.${s}.0${n} <${+r+1}.0.0-0`:i?(c("replaceCaret pr",i),o="0"===r?"0"===s?`>=${r}.${s}.${a}-${i} <${r}.${s}.${+a+1}-0`:`>=${r}.${s}.${a}-${i} <${r}.${+s+1}.0-0`:`>=${r}.${s}.${a}-${i} <${+r+1}.0.0-0`):(c("no pr"),o="0"===r?"0"===s?`>=${r}.${s}.${a}${n} <${r}.${s}.${+a+1}-0`:`>=${r}.${s}.${a}${n} <${r}.${+s+1}.0-0`:`>=${r}.${s}.${a} <${+r+1}.0.0-0`),c("caret return",o),o}))},T=(e,t)=>(c("replaceXRanges",e,t),e.split(/\s+/).map((e=>C(e,t))).join(" ")),C=(e,t)=>{e=e.trim();const r=t.loose?u[d.XRANGELOOSE]:u[d.XRANGE];return e.replace(r,((r,n,s,a,i,o)=>{c("xRange",e,r,n,s,a,i,o);const l=_(s),u=l||_(a),d=u||_(i),h=d;return"="===n&&h&&(n=""),o=t.includePrerelease?"-0":"",l?r=">"===n||"<"===n?"<0.0.0-0":"*":n&&h?(u&&(a=0),i=0,">"===n?(n=">=",u?(s=+s+1,a=0,i=0):(a=+a+1,i=0)):"<="===n&&(n="<",u?s=+s+1:a=+a+1),"<"===n&&(o="-0"),r=`${n+s}.${a}.${i}${o}`):u?r=`>=${s}.0.0${o} <${+s+1}.0.0-0`:d&&(r=`>=${s}.${a}.0${o} <${s}.${+a+1}.0-0`),c("xRange return",r),r}))},P=(e,t)=>(c("replaceStars",e,t),e.trim().replace(u[d.STAR],"")),O=(e,t)=>(c("replaceGTE0",e,t),e.trim().replace(u[t.includePrerelease?d.GTE0PRE:d.GTE0],"")),A=e=>(t,r,n,s,a,i,o,c,l,u,d,h)=>`${r=_(n)?"":_(s)?`>=${n}.0.0${e?"-0":""}`:_(a)?`>=${n}.${s}.0${e?"-0":""}`:i?`>=${r}`:`>=${r}${e?"-0":""}`} ${c=_(l)?"":_(u)?`<${+l+1}.0.0-0`:_(d)?`<${l}.${+u+1}.0-0`:h?`<=${l}.${u}.${d}-${h}`:e?`<${l}.${u}.${+d+1}-0`:`<=${c}`}`.trim(),I=(e,t,r)=>{for(let r=0;r0){const n=e[r].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch)return!0}return!1}return!0}},8587:e=>{"use strict";const t=Object.freeze({loose:!0}),r=Object.freeze({});e.exports=e=>e?"object"!=typeof e?t:e:r},8675:(e,t,r)=>{"use strict";r.d(t,{AP:()=>i,FK:()=>a,mg:()=>s,vl:()=>o});var n=r(3490);class s extends n.XQ{static lc_name(){return"FunctionMessage"}constructor(e,t){"string"==typeof e&&(e={content:e,name:t}),super(e)}_getType(){return"function"}}class a extends n.gj{static lc_name(){return"FunctionMessageChunk"}_getType(){return"function"}concat(e){return new a({content:(0,n._I)(this.content,e.content),additional_kwargs:(0,n.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,n.ns)(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}}function i(e){return"function"===e._getType()}function o(e){return"function"===e._getType()}},8794:e=>{"use strict";e.exports=class{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);return void 0===t?void 0:(this.map.delete(e),this.map.set(e,t),t)}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&void 0!==t){if(this.map.size>=this.max){const e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}},9056:(e,t,r)=>{"use strict";r.d(t,{Kj:()=>L});var n=r(5230),s=r(4116),a=r(3290),i=r(747);const o=[400,401,403,404,405,406,407,408],c=[409];class l{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}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.debug=e.debug,this.queue=new a.default({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){const r=this.onFailedResponseHook;return this.queue.add((()=>s((()=>e(...t).catch((e=>{throw e instanceof Error?e:new Error(e)}))),{async onFailedAttempt(e){if(e.message.startsWith("Cancel")||e.message.startsWith("TimeoutError")||e.message.startsWith("AbortError"))throw e;if("ECONNABORTED"===e?.code)throw e;const t=e?.response,n=t?.status;if(n){if(o.includes(+n))throw e;if(c.includes(+n))return;r&&await r(t)}},retries:this.maxRetries,randomize:!0})),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise(((t,r)=>{e.signal?.addEventListener("abort",(()=>{r(new Error("AbortError"))}))}))]):this.call(t,...r)}fetch(...e){return this.call((()=>(0,i.Yx)(this.debug)(...e).then((e=>e.ok?e:Promise.reject(e)))))}}function u(e){return"function"==typeof e?._getType}function d(e){const t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}var h=r(4785),p=r(4547);const m=/^(?:[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;const f=function(e){return"string"==typeof e&&m.test(e)};function g(e,t){if(!f(e)){throw new Error(void 0!==t?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`)}return e}var y=r(6232);r(9589);function b(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw new Error(`Invalid identifier format: ${e}`);const[t,r]=e.split(":"),n=r||"latest";if(t.includes("/")){const[r,s]=t.split("/",2);if(!r||!s)throw new Error(`Invalid identifier format: ${e}`);return[r,s,n]}if(!t)throw new Error(`Invalid identifier format: ${e}`);return["-",t,n]}class w 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 v(e,t,r){let n;if(e.ok)return void(r&&(n=await e.text()));n=await e.text();const s=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Server response: ${n}`;if(409===e.status)throw new w(s);const a=new Error(s);throw a.status=e.status,a}var _="[...]",k={result:"[Circular]"},S=[],E=[];const x=new TextEncoder;function T(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function C(e){return x.encode(e)}function P(e,t,r,n,s){try{return C(JSON.stringify(e,r,n))}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn("[WARNING]: LangSmith received unserializable value."+(t?`\nContext: ${t}`:"")),C("[Unserializable]");let i;console.warn("[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. "+(t?`\nContext: ${t}`:"")),void 0===s&&(s=T()),A(e,"",0,[],void 0,0,s);try{i=0===E.length?JSON.stringify(e,r,n):JSON.stringify(e,I(r),n)}catch(e){return C("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==S.length;){const e=S.pop();4===e.length?Object.defineProperty(e[0],e[1],e[3]):e[0][e[1]]=e[2]}}return C(i)}}function O(e,t,r,n){var s=Object.getOwnPropertyDescriptor(n,r);void 0!==s.get?s.configurable?(Object.defineProperty(n,r,{value:e}),S.push([n,r,t,s])):E.push([t,r,e]):(n[r]=e,S.push([n,r,t]))}function A(e,t,r,n,s,a,i){var o;if(a+=1,"object"==typeof e&&null!==e){for(o=0;oi.depthLimit)return void O(_,e,t,s);if(void 0!==i.edgesLimit&&r+1>i.edgesLimit)return void O(_,e,t,s);if(n.push(e),Array.isArray(e))for(o=0;o0)for(var n=0;n{if(429===e?.status){const t=1e3*parseInt(e.headers.get("retry-after")??"30",10);if(t>0)return await new Promise((e=>setTimeout(e,t))),!0}return!1};function N(e){return"number"==typeof e?Number(e.toFixed(4)):e}class ${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((e=>{t=e})),n=P(e.item,`Serializing run with id: ${e.item.id}`).length;return this.items.push({action:e.action,payload:e.item,itemPromiseResolve:t,itemPromise:r,size:n}),this.sizeBytes+=n,r}pop(e){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const t=[];let r=0;for(;r+(this.peek()?.size??0)0;){const e=this.items.shift();e&&(t.push(e),r+=e.size,this.sizeBytes-=e.size)}if(0===t.length&&this.items.length>0){const e=this.items.shift();t.push(e),r+=e.size,this.sizeBytes-=e.size}return[t.map((e=>({action:e.action,item:e.payload}))),()=>t.forEach((e=>e.itemPromiseResolve()))]}}class L{constructor(e={}){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,"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 $}),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,"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:"false"===(0,h.Az)("LANGSMITH_TRACING_BACKGROUND")}),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,"debug",{enumerable:!0,configurable:!0,writable:!0,value:"true"===(0,h.Az)("LANGSMITH_DEBUG")});const t=L.getDefaultClientConfig();if(this.tracingSampleRate=(e=>{const t=e?.toString()??(0,h.Jz)("TRACING_SAMPLING_RATE");if(void 0===t)return;const r=parseFloat(t);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r})(e.tracingSamplingRate),this.apiUrl=R(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=R(e.apiKey??t.apiKey),this.webUrl=R(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.timeout_ms=e.timeout_ms??9e4,this.caller=new l({...e.callerOptions??{},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.batchIngestCaller=new l({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:j,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.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode}static getDefaultClientConfig(){const e=(0,h.Jz)("API_KEY");return{apiUrl:(0,h.Jz)("ENDPOINT")??"https://api.smith.langchain.com",apiKey:e,webUrl:void 0,hideInputs:"true"===(0,h.Jz)("HIDE_INPUTS"),hideOutputs:"true"===(0,h.Jz)("HIDE_OUTPUTS")}}getHostUrl(){return this.webUrl?this.webUrl:(e=>{const t=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return"localhost"===t||"127.0.0.1"===t||"::1"===t})(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/${p.Ls}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),e}async processInputs(e){return!1===this.hideInputs?e:!0===this.hideInputs?{}:"function"==typeof this.hideInputs?this.hideInputs(e):e}async processOutputs(e){return!1===this.hideOutputs?e:!0===this.hideOutputs?{}:"function"==typeof this.hideOutputs?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){const t={...e};return void 0!==t.inputs&&(t.inputs=await this.processInputs(t.inputs)),void 0!==t.outputs&&(t.outputs=await this.processOutputs(t.outputs)),t}async _getResponse(e,t){const r=t?.toString()??"",n=`${this.apiUrl}${e}?${r}`,s=await this.caller.call((0,i.Yx)(this.debug),n,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v(s,`Failed to fetch ${e}`),s}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,r){let n=Number(t.get("offset"))||0;const s=Number(t.get("limit"))||100;for(;;){t.set("offset",String(n)),t.set("limit",String(s));const a=`${this.apiUrl}${e}?${t}`,o=await this.caller.call((0,i.Yx)(this.debug),a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(o,`Failed to fetch ${e}`);const c=r?r(await o.json()):await o.json();if(0===c.length)break;if(yield c,c.length0;){const[r,n]=this.autoBatchQueue.pop(e);if(!r.length){n();break}const s=this._processBatch(r,n).catch(console.error);t.push(s)}return Promise.all(t)}async _processBatch(e,t){if(e.length)try{const t={runCreates:e.filter((e=>"create"===e.action)).map((e=>e.item)),runUpdates:e.filter((e=>"update"===e.action)).map((e=>e.item))},r=await this._ensureServerInfo();r?.batch_ingest_config?.use_multipart_endpoint?await this.multipartIngestRuns(t):await this.batchIngestRuns(t)}finally{t()}else t()}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,"create"===e.action&&(e.item=M(e.item));const t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;const r=await this._getBatchSizeLimitBytes();return this.autoBatchQueue.sizeBytes>r&&this.drainAutoBatchQueue(r),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout((()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue(r)}),this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){const e=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(2500),...this.fetchOptions});await v(e,"get server info");const t=await e.json();return this.debug&&console.log("\n=== LangSmith Server Configuration ===\n"+JSON.stringify(t,null,2)+"\n"),t}async _ensureServerInfo(){return void 0===this._getServerInfoPromise&&(this._getServerInfoPromise=(async()=>{if(void 0===this._serverInfo)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[WARNING]: LangSmith failed to fetch info on supported operations with status code ${e.status}. Falling back to batch operations and default limits.`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then((e=>(void 0===this._serverInfo&&(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();await this.drainAutoBatchQueue(e)}async createRun(e){if(!this._filterForSampling([e]).length)return;const t={...this.headers,"Content-Type":"application/json"},r=e.project_name;delete e.project_name;const n=await this.prepareRunCreateOrUpdateInputs({session_name:r,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&void 0!==n.trace_id&&void 0!==n.dotted_order)return void this.processRunOperation({action:"create",item:n}).catch(console.error);const s=M(n),a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/runs`,{method:"POST",headers:t,body:P(s,`Creating run with id: ${s.id}`),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(a,"create run",!0)}async batchIngestRuns({runCreates:e,runUpdates:t}){if(void 0===e&&void 0===t)return;let r=await Promise.all(e?.map((e=>this.prepareRunCreateOrUpdateInputs(e)))??[]),n=await Promise.all(t?.map((e=>this.prepareRunCreateOrUpdateInputs(e)))??[]);if(r.length>0&&n.length>0){const e=r.reduce(((e,t)=>t.id?(e[t.id]=t,e):e),{}),t=[];for(const r of n)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);r=Object.values(e),n=t}const s={post:r,patch:n};if(!s.post.length&&!s.patch.length)return;const a={post:[],patch:[]};for(const e of["post","patch"]){const t=e,r=s[t].reverse();let n=r.pop();for(;void 0!==n;)a[t].push(n),n=r.pop()}if(a.post.length>0||a.patch.length>0){const e=a.post.map((e=>e.id)).concat(a.patch.map((e=>e.id))).join(",");await this._postBatchIngestRuns(P(a,`Ingesting runs with ids: ${e}`))}}async _postBatchIngestRuns(e){const t={...this.headers,"Content-Type":"application/json",Accept:"application/json"},r=await this.batchIngestCaller.call((0,i.Yx)(this.debug),`${this.apiUrl}/runs/batch`,{method:"POST",headers:t,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(r,"batch create run",!0)}async multipartIngestRuns({runCreates:e,runUpdates:t}){if(void 0===e&&void 0===t)return;const r={};let n=[];for(const t of e??[]){const e=await this.prepareRunCreateOrUpdateInputs(t);void 0!==e.id&&void 0!==e.attachments&&(r[e.id]=e.attachments),delete e.attachments,n.push(e)}let s=[];for(const e of t??[])s.push(await this.prepareRunCreateOrUpdateInputs(e));if(void 0!==n.find((e=>void 0===e.trace_id||void 0===e.dotted_order)))throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(void 0!==s.find((e=>void 0===e.trace_id||void 0===e.dotted_order)))throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(n.length>0&&s.length>0){const e=n.reduce(((e,t)=>t.id?(e[t.id]=t,e):e),{}),t=[];for(const r of s)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);n=Object.values(e),s=t}if(0===n.length&&0===s.length)return;const a=[],i=[];for(const[e,t]of[["post",n],["patch",s]])for(const n of t){const{inputs:t,outputs:s,events:o,attachments:c,...l}=n,u={inputs:t,outputs:s,events:o},d=P(l,`Serializing for multipart ingestion of run with id: ${l.id}`);i.push({name:`${e}.${l.id}`,payload:new Blob([d],{type:`application/json; length=${d.length}`})});for(const[t,r]of Object.entries(u)){if(void 0===r)continue;const n=P(r,`Serializing ${t} for multipart ingestion of run with id: ${l.id}`);i.push({name:`${e}.${l.id}.${t}`,payload:new Blob([n],{type:`application/json; length=${n.length}`})})}if(void 0!==l.id){const e=r[l.id];if(e){delete r[l.id];for(const[t,r]of Object.entries(e)){let e,n;Array.isArray(r)?[e,n]=r:(e=r.mimeType,n=r.data),t.includes(".")?console.warn(`Skipping attachment '${t}' for run ${l.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`):i.push({name:`attachment.${l.id}.${t}`,payload:new Blob([n],{type:`${e}; length=${n.byteLength}`})})}}}a.push(`trace=${l.trace_id},id=${l.id}`)}await this._sendMultipartRequest(i,a.join("; "))}async _createNodeFetchBody(e,t){const r=[];for(const n of e)r.push(new Blob([`--${t}\r\n`])),r.push(new Blob([`Content-Disposition: form-data; name="${n.name}"\r\n`,`Content-Type: ${n.payload.type}\r\n\r\n`])),r.push(n.payload),r.push(new Blob(["\r\n"]));r.push(new Blob([`--${t}--\r\n`]));const n=new Blob(r);return await n.arrayBuffer()}async _createMultipartStream(e,t){const r=new TextEncoder;return new ReadableStream({async start(n){const s=async e=>{"string"==typeof e?n.enqueue(r.encode(e)):n.enqueue(e)};for(const r of e){await s(`--${t}\r\n`),await s(`Content-Disposition: form-data; name="${r.name}"\r\n`),await s(`Content-Type: ${r.payload.type}\r\n\r\n`);const e=r.payload.stream().getReader();try{let t;for(;!(t=await e.read()).done;)n.enqueue(t.value)}finally{e.releaseLock()}await s("\r\n")}await s(`--${t}--\r\n`),n.close()}})}async _sendMultipartRequest(e,t){try{const t="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),r=await((0,i.rO)()?this._createNodeFetchBody(e,t):this._createMultipartStream(e,t)),n=await this.batchIngestCaller.call((0,i.Yx)(this.debug),`${this.apiUrl}/runs/multipart`,{method:"POST",headers:{...this.headers,"Content-Type":`multipart/form-data; boundary=${t}`},body:r,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(n,"ingest multipart runs",!0)}catch(e){console.warn(`${e.message.trim()}\n\nContext: ${t}`)}}async updateRun(e,t){g(e),t.inputs&&(t.inputs=await this.processInputs(t.inputs)),t.outputs&&(t.outputs=await this.processOutputs(t.outputs));const r={...t,id:e};if(!this._filterForSampling([r],!0).length)return;if(this.autoBatchTracing&&void 0!==r.trace_id&&void 0!==r.dotted_order)return void 0!==t.end_time&&void 0===r.parent_run_id&&this.blockOnRootRunFinalization&&!this.manualFlushMode?void await this.processRunOperation({action:"update",item:r}).catch(console.error):void this.processRunOperation({action:"update",item:r}).catch(console.error);const n={...this.headers,"Content-Type":"application/json"},s=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/runs/${e}`,{method:"PATCH",headers:n,body:P(t,`Serializing payload to update run with id: ${e}`),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(s,"update run",!0)}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){g(e);let r=await this._get(`/runs/${e}`);return t&&r.child_run_ids&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:t,projectOpts:r}){if(void 0!==t){let e;if(t.session_id)e=t.session_id;else if(r?.projectName)e=(await this.readProject({projectName:r?.projectName})).id;else if(r?.projectId)e=r?.projectId;else{e=(await this.readProject({projectName:(0,h.Jz)("PROJECT")||"default"})).id}const n=await this._getTenantId();return`${this.getHostUrl()}/o/${n}/projects/p/${e}/r/${t.id}?poll=true`}if(void 0!==e){const t=await this.readRun(e);if(!t.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${t.app_path}`}throw new Error("Must provide either runId or run")}async _loadChildRuns(e){const t=await async function(e){const t=[];for await(const r of e)t.push(r);return t}(this.listRuns({id:e.child_run_ids})),r={},n={};t.sort(((e,t)=>(e?.dotted_order??"").localeCompare(t?.dotted_order??"")));for(const e of t){if(null===e.parent_run_id||void 0===e.parent_run_id)throw new Error(`Child run ${e.id} has no parent`);e.parent_run_id in r||(r[e.parent_run_id]=[]),r[e.parent_run_id].push(e),n[e.id]=e}e.child_runs=r[e.id]||[];for(const t in r)t!==e.id&&(n[t].child_runs=r[t]);return e}async*listRuns(e){const{projectId:t,projectName:r,parentRunId:n,traceId:s,referenceExampleId:a,startTime:i,executionOrder:o,isRoot:c,runType:l,error:u,id:d,query:h,filter:p,traceFilter:m,treeFilter:f,limit:g,select:y,order:b}=e;let w=[];if(t&&(w=Array.isArray(t)?t:[t]),r){const e=Array.isArray(r)?r:[r],t=await Promise.all(e.map((e=>this.readProject({projectName:e}).then((e=>e.id)))));w.push(...t)}const v={session:w.length?w:null,run_type:l,reference_example:a,query:h,filter:p,trace_filter:m,tree_filter:f,execution_order:o,parent_run:n,start_time:i?i.toISOString():null,error:u,id:d,limit:g,trace:s,select:y||["app_path","child_run_ids","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"],is_root:c,order:b};let _=0;for await(const e of this._getCursorPaginatedList("/runs/query",v))if(g){if(_>=g)break;if(e.length+_>g){const t=e.slice(0,g-_);yield*t;break}_+=e.length,yield*e}else yield*e}async*listGroupRuns(e){const{projectId:t,projectName:r,groupBy:n,filter:s,startTime:a,endTime:o,limit:c,offset:l}=e,u={session_id:t||(await this.readProject({projectName:r})).id,group_by:n,filter:s,start_time:a?a.toISOString():null,end_time:o?o.toISOString():null,limit:Number(c)||100};let d=Number(l)||0;const h="/runs/group",p=`${this.apiUrl}${h}`;for(;;){const e={...u,offset:d},t=Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t))),r=await this.caller.call((0,i.Yx)(),p,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(r,`Failed to fetch ${h}`);const n=await r.json(),{groups:s,total:a}=n;if(0===s.length)break;for(const e of s)yield e;if(d+=s.length,d>=a)break}}async getRunStats({id:e,trace:t,parentRun:r,runType:n,projectNames:s,projectIds:a,referenceExampleIds:o,startTime:c,endTime:l,error:u,query:d,filter:h,traceFilter:p,treeFilter:m,isRoot:f,dataSourceType:g}){let y=a||[];s&&(y=[...a||[],...await Promise.all(s.map((e=>this.readProject({projectName:e}).then((e=>e.id)))))]);const b={id:e,trace:t,parent_run:r,run_type:n,session:y,reference_example:o,start_time:c,end_time:l,error:u,query:d,filter:h,trace_filter:p,tree_filter:m,is_root:f,data_source_type:g},w=Object.fromEntries(Object.entries(b).filter((([e,t])=>void 0!==t))),v=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(w),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v.json()}async shareRun(e,{shareId:t}={}){const r={run_id:e,share_token:t||n.A()};g(e);const s=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),a=await s.json();if(null===a||!("share_token"in a))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${a.share_token}/r`}async unshareRun(e){g(e);const t=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(t,"unshare run",!0)}async readRunSharedLink(e){g(e);const t=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await t.json();if(null!==r&&"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(void 0!==t)for(const e of t)r.append("id",e);g(e);const n=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await n.json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");if(!e){e=(await this.readDataset({datasetName:t})).id}g(e);const r=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),n=await r.json();return n.url=`${this.getHostUrl()}/public/${n.share_token}/d`,n}async shareDataset(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");if(!e){e=(await this.readDataset({datasetName:t})).id}const r={dataset_id:e};g(e);const n=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),s=await n.json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async unshareDataset(e){g(e);const t=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(t,"unshare dataset",!0)}async readSharedDataset(e){g(e);const t=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await t.json()}async listSharedExamples(e,t){const r={};t?.exampleIds&&(r.id=t.exampleIds);const n=new URLSearchParams;Object.entries(r).forEach((([e,t])=>{Array.isArray(t)?t.forEach((t=>n.append(e,t))):n.append(e,t)}));const s=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/public/${e}/examples?${n.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),a=await s.json();if(!s.ok){if("detail"in a)throw new Error(`Failed to list shared examples.\nStatus: ${s.status}\nMessage: ${Array.isArray(a.detail)?a.detail.join("\n"):"Unspecified error"}`);throw new Error(`Failed to list shared examples: ${s.status} ${s.statusText}`)}return a.map((e=>({...e,_hostUrl:this.getHostUrl()})))}async createProject({projectName:e,description:t=null,metadata:r=null,upsert:n=!1,projectExtra:s=null,referenceDatasetId:a=null}){const o=n?"?upsert=true":"",c=`${this.apiUrl}/sessions${o}`,l=s||{};r&&(l.metadata=r);const u={name:e,extra:l,description:t};null!==a&&(u.reference_dataset_id=a);const d=await this.caller.call((0,i.Yx)(this.debug),c,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(d,"create project");return await d.json()}async updateProject(e,{name:t=null,description:r=null,metadata:n=null,projectExtra:s=null,endTime:a=null}){const o=`${this.apiUrl}/sessions/${e}`;let c=s;n&&(c={...c||{},metadata:n});const l={name:t,extra:c,description:r,end_time:a?new Date(a).toISOString():null},u=await this.caller.call((0,i.Yx)(this.debug),o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(u,"update project");return await u.json()}async hasProject({projectId:e,projectName:t}){let r="/sessions";const n=new URLSearchParams;if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");if(void 0!==e)g(e),r+=`/${e}`;else{if(void 0===t)throw new Error("Must provide projectName or projectId");n.append("name",t)}const s=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}${r}?${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{const e=await s.json();return!!s.ok&&(!Array.isArray(e)||e.length>0)}catch(e){return!1}}async readProject({projectId:e,projectName:t,includeStats:r}){let n="/sessions";const s=new URLSearchParams;if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");if(void 0!==e)g(e),n+=`/${e}`;else{if(void 0===t)throw new Error("Must provide projectName or projectId");s.append("name",t)}void 0!==r&&s.append("include_stats",r.toString());const a=await this._get(n,s);let i;if(Array.isArray(a)){if(0===a.length)throw new Error(`Project[id=${e}, name=${t}] not found`);i=a[0]}else i=a;return i}async getProjectUrl({projectId:e,projectName:t}){if(void 0===e&&void 0===t)throw new Error("Must provide either projectName or projectId");const r=await this.readProject({projectId:e,projectName:t}),n=await this._getTenantId();return`${this.getHostUrl()}/o/${n}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(void 0===e&&void 0===t)throw new Error("Must provide either datasetName or datasetId");const r=await this.readDataset({datasetId:e,datasetName:t}),n=await this._getTenantId();return`${this.getHostUrl()}/o/${n}/datasets/${r.id}`}async _getTenantId(){if(null!==this._tenantId)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:n,referenceDatasetName:s,referenceFree:a,metadata:i}={}){const o=new URLSearchParams;if(void 0!==e)for(const t of e)o.append("id",t);if(void 0!==t&&o.append("name",t),void 0!==r&&o.append("name_contains",r),void 0!==n)o.append("reference_dataset",n);else if(void 0!==s){const e=await this.readDataset({datasetName:s});o.append("reference_dataset",e.id)}void 0!==a&&o.append("reference_free",a.toString()),void 0!==i&&o.append("metadata",JSON.stringify(i));for await(const e of this._getPaginated("/sessions",o))yield*e}async deleteProject({projectId:e,projectName:t}){let r;if(void 0===e&&void 0===t)throw new Error("Must provide projectName or projectId");if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");r=void 0===e?(await this.readProject({projectName:t})).id:e,g(r);const n=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(n,`delete session ${r} (${t})`,!0)}async uploadCsv({csvFile:e,fileName:t,inputKeys:r,outputKeys:n,description:s,dataType:a,name:o}){const c=`${this.apiUrl}/datasets/upload`,l=new FormData;l.append("file",e,t),r.forEach((e=>{l.append("input_keys",e)})),n.forEach((e=>{l.append("output_keys",e)})),s&&l.append("description",s),a&&l.append("data_type",a),o&&l.append("name",o);const u=await this.caller.call((0,i.Yx)(this.debug),c,{method:"POST",headers:this.headers,body:l,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(u,"upload CSV");return await u.json()}async createDataset(e,{description:t,dataType:r,inputsSchema:n,outputsSchema:s,metadata:a}={}){const o={name:e,description:t,extra:a?{metadata:a}:void 0};r&&(o.data_type=r),n&&(o.inputs_schema_definition=n),s&&(o.outputs_schema_definition=s);const c=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(c,"create dataset");return await c.json()}async readDataset({datasetId:e,datasetName:t}){let r="/datasets";const n=new URLSearchParams({limit:"1"});if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)g(e),r+=`/${e}`;else{if(void 0===t)throw new Error("Must provide datasetName or datasetId");n.append("name",t)}const s=await this._get(r,n);let a;if(Array.isArray(s)){if(0===s.length)throw new Error(`Dataset[id=${e}, name=${t}] not found`);a=s[0]}else a=s;return a}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(e){if(e instanceof Error&&e.message.toLocaleLowerCase().includes("not found"))return!1;throw e}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:r,toVersion:n}){let s=e;if(void 0===s&&void 0===t)throw new Error("Must provide either datasetName or datasetId");if(void 0!==s&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===s){s=(await this.readDataset({datasetName:t})).id}const a=new URLSearchParams({from_version:"string"==typeof r?r:r.toISOString(),to_version:"string"==typeof n?n:n.toISOString()});return await this._get(`/datasets/${s}/versions/diff`,a)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){if(void 0!==e);else{if(void 0===t)throw new Error("Must provide either datasetName or datasetId");e=(await this.readDataset({datasetName:t})).id}const r=await this._getResponse(`/datasets/${e}/openai_ft`);return(await r.text()).trim().split("\n").map((e=>JSON.parse(e)))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:r,datasetName:n,datasetNameContains:s,metadata:a}={}){const i=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(void 0!==r)for(const e of r)i.append("id",e);void 0!==n&&i.append("name",n),void 0!==s&&i.append("name_contains",s),void 0!==a&&i.append("metadata",JSON.stringify(a));for await(const e of this._getPaginated("/datasets",i))yield*e}async updateDataset(e){const{datasetId:t,datasetName:r,...n}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const s=t??(await this.readDataset({datasetName:r})).id;g(s);const a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v(a,"update dataset"),await a.json()}async updateDatasetTag(e){const{datasetId:t,datasetName:r,asOf:n,tag:s}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const a=t??(await this.readDataset({datasetName:r})).id;g(a);const o=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({as_of:"string"==typeof n?n:n.toISOString(),tag:s}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(o,"update dataset tags")}async deleteDataset({datasetId:e,datasetName:t}){let r="/datasets",n=e;if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==t){n=(await this.readDataset({datasetName:t})).id}if(void 0===n)throw new Error("Must provide datasetName or datasetId");g(n),r+=`/${n}`;const s=await this.caller.call((0,i.Yx)(this.debug),this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(s,`delete ${r}`),await s.json()}async indexDataset({datasetId:e,datasetName:t,tag:r}){let n=e;if(!n&&!t)throw new Error("Must provide either datasetName or datasetId");if(n&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(!n){n=(await this.readDataset({datasetName:t})).id}g(n);const s={tag:r},a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${n}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(a,"index dataset"),await a.json()}async similarExamples(e,t,r,{filter:n}={}){const s={limit:r,inputs:e};void 0!==n&&(s.filter=n),g(t);const a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${t}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(a,"fetch similar examples");return(await a.json()).examples}async createExample(e,t,r){if(F(e)&&(void 0!==t||void 0!==r))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let s=t?r?.datasetId:e.dataset_id;const a=t?r?.datasetName:e.dataset_name;if(void 0===s&&void 0===a)throw new Error("Must provide either datasetName or datasetId");if(void 0!==s&&void 0!==a)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===s){s=(await this.readDataset({datasetName:a})).id}const i=(t?r?.createdAt:e.created_at)||new Date;let o;o=F(e)?e:{inputs:e,outputs:t,created_at:i?.toISOString(),id:r?.exampleId,metadata:r?.metadata,split:r?.split,source_run_id:r?.sourceRunId,use_source_run_io:r?.useSourceRunIO,use_source_run_attachments:r?.useSourceRunAttachments,attachments:r?.attachments};const c=await this._uploadExamplesMultipart(s,[o]);return await this.readExample(c.example_ids?.[0]??n.A())}async createExamples(e){if(Array.isArray(e)){if(0===e.length)return[];const t=e;let r=t[0].dataset_id;const n=t[0].dataset_name;if(void 0===r&&void 0===n)throw new Error("Must provide either datasetName or datasetId");if(void 0!==r&&void 0!==n)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===r){r=(await this.readDataset({datasetName:n})).id}const s=await this._uploadExamplesMultipart(r,t);return await Promise.all(s.example_ids.map((e=>this.readExample(e))))}const{inputs:t,outputs:r,metadata:n,splits:s,sourceRunIds:a,useSourceRunIOs:i,useSourceRunAttachments:o,attachments:c,exampleIds:l,datasetId:u,datasetName:d}=e;if(void 0===t)throw new Error("Must provide inputs when using legacy parameters");let h=u;const p=d;if(void 0===h&&void 0===p)throw new Error("Must provide either datasetName or datasetId");if(void 0!==h&&void 0!==p)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===h){const e=await this.readDataset({datasetName:p});h=e.id}const m=t.map(((e,t)=>({dataset_id:h,inputs:e,outputs:r?.[t],metadata:n?.[t],split:s?.[t],id:l?.[t],attachments:c?.[t],source_run_id:a?.[t],use_source_run_io:i?.[t],use_source_run_attachments:o?.[t]}))),f=await this._uploadExamplesMultipart(h,m);return await Promise.all(f.example_ids.map((e=>this.readExample(e))))}async createLLMExample(e,t,r){return this.createExample({input:e},{output:t},r)}async createChatExample(e,t,r){const n=e.map((e=>u(e)?d(e):e)),s=u(t)?d(t):t;return this.createExample({input:n},{output:s},r)}async readExample(e){g(e);const t=`/examples/${e}`,r=await this._get(t),{attachment_urls:n,...s}=r,a=s;return n&&(a.attachments=Object.entries(n).reduce(((e,[t,r])=>(e[t.slice(11)]={presigned_url:r.presigned_url,mime_type:r.mime_type},e)),{})),a}async*listExamples({datasetId:e,datasetName:t,exampleIds:r,asOf:n,splits:s,inlineS3Urls:a,metadata:i,limit:o,offset:c,filter:l,includeAttachments:u}={}){let d;if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)d=e;else{if(void 0===t)throw new Error("Must provide a datasetName or datasetId");d=(await this.readDataset({datasetName:t})).id}const h=new URLSearchParams({dataset:d}),p=n?"string"==typeof n?n:n?.toISOString():void 0;p&&h.append("as_of",p);const m=a??!0;if(h.append("inline_s3_urls",m.toString()),void 0!==r)for(const e of r)h.append("id",e);if(void 0!==s)for(const e of s)h.append("splits",e);if(void 0!==i){const e=JSON.stringify(i);h.append("metadata",e)}void 0!==o&&h.append("limit",o.toString()),void 0!==c&&h.append("offset",c.toString()),void 0!==l&&h.append("filter",l),!0===u&&["attachment_urls","outputs","metadata"].forEach((e=>h.append("select",e)));let f=0;for await(const e of this._getPaginated("/examples",h)){for(const t of e){const{attachment_urls:e,...r}=t,n=r;e&&(n.attachments=Object.entries(e).reduce(((e,[t,r])=>(e[t.slice(11)]={presigned_url:r.presigned_url,mime_type:r.mime_type||void 0},e)),{})),yield n,f++}if(void 0!==o&&f>=o)break}}async deleteExample(e){g(e);const t=`/examples/${e}`,r=await this.caller.call((0,i.Yx)(this.debug),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(r,`delete ${t}`),await r.json()}async updateExample(e,t){let r,n,s;if(r=t?e:e.id,g(r),n=t?{id:r,...t}:e,void 0!==n.dataset_id)s=n.dataset_id;else{s=(await this.readExample(r)).dataset_id}return this._updateExamplesMultipart(s,[n])}async updateExamples(e){let t;if(void 0===e[0].dataset_id){t=(await this.readExample(e[0].id)).dataset_id}else t=e[0].dataset_id;return this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:r,tag:n}){let s;if(e)s=e;else{s=(await this.readDataset({datasetName:t})).id}if(g(s),r&&n||!r&&!n)throw new Error("Exactly one of asOf and tag must be specified.");const a=new URLSearchParams;void 0!==r&&a.append("as_of","string"==typeof r?r:r.toISOString()),void 0!==n&&a.append("tag",n);const o=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${s}/version?${a.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v(o,"read dataset version"),await o.json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:r}){let n;if(void 0===e&&void 0===t)throw new Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===e){n=(await this.readDataset({datasetName:t})).id}else n=e;g(n);const s=new URLSearchParams,a=r?"string"==typeof r?r:r?.toISOString():void 0;a&&s.append("as_of",a);return await this._get(`/datasets/${n}/splits`,s)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:r,exampleIds:n,remove:s=!1}){let a;if(void 0===e&&void 0===t)throw new Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===e){a=(await this.readDataset({datasetName:t})).id}else a=e;g(a);const o={split_name:r,examples:n.map((e=>(g(e),e))),remove:s},c=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${a}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(c,"update dataset splits",!0)}async evaluateRun(e,t,{sourceInfo:r,loadChildRuns:n,referenceExample:s}={loadChildRuns:!1}){let a;if((0,y.m)("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."),"string"==typeof e)a=await this.readRun(e,{loadChildRuns:n});else{if("object"!=typeof e||!("id"in e))throw new Error("Invalid run type: "+typeof e);a=e}null!==a.reference_example_id&&void 0!==a.reference_example_id&&(s=await this.readExample(a.reference_example_id));const i=await t.evaluateRun(a,s),[o,c]=await this._logEvaluationFeedback(i,a,r);return c[0]}async createFeedback(e,t,{score:r,value:s,correction:a,comment:o,sourceInfo:c,feedbackSourceType:l="api",sourceRunId:u,feedbackId:d,feedbackConfig:h,projectId:p,comparativeExperimentId:m}){if(!e&&!p)throw new Error("One of runId or projectId must be provided");if(e&&p)throw new Error("Only one of runId or projectId can be provided");const f={type:l??"api",metadata:c??{}};void 0===u||void 0===f?.metadata||f.metadata.__run||(f.metadata.__run={run_id:u}),void 0!==f?.metadata&&void 0!==f.metadata.__run?.run_id&&g(f.metadata.__run.run_id);const y={id:d??n.A(),run_id:e,key:t,score:N(r),value:s,correction:a,comment:o,feedback_source:f,comparative_experiment_id:m,feedbackConfig:h,session_id:p},b=`${this.apiUrl}/feedback`,w=await this.caller.call((0,i.Yx)(this.debug),b,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(y),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v(w,"create feedback",!0),y}async updateFeedback(e,{score:t,value:r,correction:n,comment:s}){const a={};null!=t&&(a.score=N(t)),null!=r&&(a.value=r),null!=n&&(a.correction=n),null!=s&&(a.comment=s),g(e);const o=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(o,"update feedback",!0)}async readFeedback(e){g(e);const t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){g(e);const t=`/feedback/${e}`,r=await this.caller.call((0,i.Yx)(this.debug),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(r,`delete ${t}`),await r.json()}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:r}={}){const n=new URLSearchParams;if(e&&n.append("run",e.join(",")),t)for(const e of t)n.append("key",e);if(r)for(const e of r)n.append("source",e);for await(const e of this._getPaginated("/feedback",n))yield*e}async createPresignedFeedbackToken(e,t,{expiration:r,feedbackConfig:n}={}){const s={run_id:e,feedback_key:t,feedback_config:n};r?"string"==typeof r?s.expires_at=r:(r?.hours||r?.minutes||r?.days)&&(s.expires_in=r):s.expires_in={hours:3};const a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await a.json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:r,createdAt:n,description:s,metadata:a,id:o}){if(0===t.length)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:t[0]})).reference_dataset_id),null==!r)throw new Error("A reference dataset is required");const c={id:o,name:e,experiment_ids:t,reference_dataset_id:r,description:s,created_at:(n??new Date)?.toISOString(),extra:{}};a&&(c.extra.metadata=a);const l=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await l.json()}async*listPresignedFeedbackTokens(e){g(e);const t=new URLSearchParams({run_id:e});for await(const e of this._getPaginated("/feedback/tokens",t))yield*e}_selectEvalResults(e){let t;return t="results"in e?e.results:Array.isArray(e)?e:[e],t}async _logEvaluationFeedback(e,t,r){const n=this._selectEvalResults(e),s=[];for(const e of n){let n=r||{};e.evaluatorInfo&&(n={...e.evaluatorInfo,...n});let a=null;e.targetRunId?a=e.targetRunId:t&&(a=t.id),s.push(await this.createFeedback(a,e.key,{score:e.score,value:e.value,comment:e.comment,correction:e.correction,sourceInfo:n,sourceRunId:e.sourceRunId,feedbackConfig:e.feedbackConfig,feedbackSourceType:"model"}))}return[n,s]}async logEvaluationFeedback(e,t,r){const[n]=await this._logEvaluationFeedback(e,t,r);return n}async*listAnnotationQueues(e={}){const{queueIds:t,name:r,nameContains:n,limit:s}=e,a=new URLSearchParams;t&&t.forEach(((e,t)=>{g(e,`queueIds[${t}]`),a.append("ids",e)})),r&&a.append("name",r),n&&a.append("name_contains",n),a.append("limit",(void 0!==s?Math.min(s,100):100).toString());let i=0;for await(const e of this._getPaginated("/annotation-queues",a))if(yield*e,i++,void 0!==s&&i>=s)break}async createAnnotationQueue(e){const{name:t,description:r,queueId:s,rubricInstructions:a}=e,o={name:t,description:r,id:s||n.A(),rubric_instructions:a},c=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(Object.fromEntries(Object.entries(o).filter((([e,t])=>void 0!==t)))),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(c,"create annotation queue");return await c.json()}async readAnnotationQueue(e){const t=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/annotation-queues/${g(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(t,"read annotation queue");return await t.json()}async updateAnnotationQueue(e,t){const{name:r,description:n,rubricInstructions:s}=t,a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/annotation-queues/${g(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({name:r,description:n,rubric_instructions:s}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(a,"update annotation queue")}async deleteAnnotationQueue(e){const t=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/annotation-queues/${g(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(t,"delete annotation queue")}async addRunsToAnnotationQueue(e,t){const r=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/annotation-queues/${g(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t.map(((e,t)=>g(e,`runIds[${t}]`).toString()))),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(r,"add runs to annotation queue")}async getRunFromAnnotationQueue(e,t){const r=`/annotation-queues/${g(e,"queueId")}/run`,n=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}${r}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v(n,"get run from annotation queue"),await n.json()}async deleteRunFromAnnotationQueue(e,t){const r=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/annotation-queues/${g(e,"queueId")}/runs/${g(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(r,"delete run from annotation queue")}async getSizeFromAnnotationQueue(e){const t=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/annotation-queues/${g(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v(t,"get size from annotation queue"),await t.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.\n\n Current tenant: ${r.tenant_handle}\n\n Requested tenant: ${t}`)}async _getLatestCommitHash(e){const t=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await t.json();if(!t.ok){const e="string"==typeof r.detail?r.detail:JSON.stringify(r.detail),n=new Error(`Error ${t.status}: ${t.statusText}\n${e}`);throw n.statusCode=t.status,n}if(0!==r.commits.length)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){const[r,n,s]=b(e),a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/likes/${r}/${n}`,{method:"POST",body:JSON.stringify({like:t}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v(a,(t?"like":"unlike")+" prompt"),await a.json()}async _getPromptUrl(e){const[t,r,n]=b(e);if(await this._currentTenantIsOwner(t)){const e=await this._getSettings();return"latest"!==n?`${this.getHostUrl()}/prompts/${r}/${n.substring(0,8)}?organizationId=${e.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${e.id}`}return"latest"!==n?`${this.getHostUrl()}/hub/${t}/${r}/${n.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,(e=>e.commits)))yield*t}async*listPrompts(e){const t=new URLSearchParams;t.append("sort_field",e?.sortField??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!e?.isArchived).toString()),void 0!==e?.isPublic&&t.append("is_public",e.isPublic.toString()),e?.query&&t.append("query",e.query);for await(const e of this._getPaginated("/repos",t,(e=>e.repos)))yield*e}async getPrompt(e){const[t,r,n]=b(e),s=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/repos/${t}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(404===s.status)return null;await v(s,"get prompt");const a=await s.json();return a.repo?a.repo:null}async createPrompt(e,t){const r=await this._getSettings();if(t?.isPublic&&!r.tenant_handle)throw new Error("Cannot create a public prompt without first\n\n creating a LangChain Hub handle. \n You can add a handle by creating a public prompt at:\n\n https://smith.langchain.com/prompts");const[n,s,a]=b(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("create a prompt",n);const o={repo_handle:s,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},c=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(c,"create prompt");const{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[n,s,a]=b(e),o="latest"!==r?.parentCommitHash&&r?.parentCommitHash?r?.parentCommitHash:await this._getLatestCommitHash(`${n}/${s}`),c={manifest:JSON.parse(JSON.stringify(t)),parent_commit:o},l=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/commits/${n}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(l,"create commit");const u=await l.json();return this._getPromptUrl(`${n}/${s}${u.commit_hash?`:${u.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){if(!await this._getMultiPartSupport())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 e of t){const t=e.id,n=P({...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}},`Serializing body for example with id: ${t}`),s=new Blob([n],{type:"application/json"});if(r.append(t,s),e.inputs){const n=P(e.inputs,`Serializing inputs for example with id: ${t}`),s=new Blob([n],{type:"application/json"});r.append(`${t}.inputs`,s)}if(e.outputs){const n=P(e.outputs,`Serializing outputs whle updating example with id: ${t}`),s=new Blob([n],{type:"application/json"});r.append(`${t}.outputs`,s)}if(e.attachments)for(const[n,s]of Object.entries(e.attachments)){let e,a;Array.isArray(s)?[e,a]=s:(e=s.mimeType,a=s.data);const i=new Blob([a],{type:`${e}; length=${a.byteLength}`});r.append(`${t}.attachment.${n}`,i)}if(e.attachments_operations){const n=P(e.attachments_operations,`Serializing attachments while updating example with id: ${t}`),s=new Blob([n],{type:"application/json"});r.append(`${t}.attachments_operations`,s)}}const n=e??t[0]?.dataset_id,s=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/v1/platform/datasets/${n}/examples`,{method:"PATCH",headers:this.headers,body:r});return await s.json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){if(!await this._getMultiPartSupport())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 e of t){const t=(e.id??n.A()).toString(),s=P({created_at:e.created_at,...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split},...e.source_run_id&&{source_run_id:e.source_run_id},...e.use_source_run_io&&{use_source_run_io:e.use_source_run_io},...e.use_source_run_attachments&&{use_source_run_attachments:e.use_source_run_attachments}},`Serializing body for uploaded example with id: ${t}`),a=new Blob([s],{type:"application/json"});if(r.append(t,a),e.inputs){const n=P(e.inputs,`Serializing inputs for uploaded example with id: ${t}`),s=new Blob([n],{type:"application/json"});r.append(`${t}.inputs`,s)}if(e.outputs){const n=P(e.outputs,`Serializing outputs for uploaded example with id: ${t}`),s=new Blob([n],{type:"application/json"});r.append(`${t}.outputs`,s)}if(e.attachments)for(const[n,s]of Object.entries(e.attachments)){let e,a;Array.isArray(s)?[e,a]=s:(e=s.mimeType,a=s.data);const i=new Blob([a],{type:`${e}; length=${a.byteLength}`});r.append(`${t}.attachment.${n}`,i)}}const s=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/v1/platform/datasets/${e}/examples`,{method:"POST",headers:this.headers,body:r});await v(s,"upload examples");return await 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,n]=b(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);const s={};if(void 0!==t?.description&&(s.description=t.description),void 0!==t?.readme&&(s.readme=t.readme),void 0!==t?.tags&&(s.tags=t.tags),void 0!==t?.isPublic&&(s.is_public=t.isPublic),void 0!==t?.isArchived&&(s.is_archived=t.isArchived),0===Object.keys(s).length)throw new Error("No valid update options provided");const a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/repos/${r}/${n}`,{method:"PATCH",body:JSON.stringify(s),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v(a,"update prompt"),a.json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[t,r,n]=b(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);const s=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/repos/${t}/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await s.json()}async pullPromptCommit(e,t){const[r,n,s]=b(e),a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/commits/${r}/${n}/${s}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(a,"pull prompt commit");const o=await a.json();return{owner:r,repo:n,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(e,t){const r=await this.pullPromptCommit(e,{includeModel:t?.includeModel});return JSON.stringify(r.manifest)}async pushPrompt(e,t){if(await this.promptExists(e)?t&&Object.keys(t).some((e=>"object"!==e))&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),!t?.object)return await this._getPromptUrl(e);return await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash})}async clonePublicDataset(e,t={}){const{sourceApiUrl:r=this.apiUrl,datasetName:n}=t,[s,a]=this.parseTokenOrUrl(e,r),i=new L({apiUrl:s,apiKey:"placeholder"}),o=await i.readSharedDataset(a),c=n||o.name;try{if(await this.hasDataset({datasetId:c}))return void console.log(`Dataset ${c} already exists in your tenant. Skipping.`)}catch(e){}const l=await i.listSharedExamples(a),u=await this.createDataset(c,{description:o.description,dataType:o.data_type||"kv",inputsSchema:o.inputs_schema_definition??void 0,outputsSchema:o.outputs_schema_definition??void 0});try{await this.createExamples({inputs:l.map((e=>e.inputs)),outputs:l.flatMap((e=>e.outputs?[e.outputs]:[])),datasetId:u.id})}catch(e){throw console.error(`An error occurred while creating dataset ${c}. You should delete it manually.`),e}}parseTokenOrUrl(e,t,r=2,n="dataset"){try{return g(e),[t,e]}catch(e){}try{const s=new URL(e).pathname.split("/").filter((e=>""!==e));if(s.length>=r){return[t,s[s.length-r]]}throw new Error(`Invalid public ${n} URL: ${e}`)}catch(t){throw new Error(`Invalid public ${n} URL or token: ${e}`)}}awaitPendingTraceBatches(){return this.manualFlushMode?(console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve()):Promise.all([...this.autoBatchQueue.items.map((({itemPromise:e})=>e)),this.batchIngestCaller.queue.onIdle()])}}function F(e){return"dataset_id"in e||"dataset_name"in e}},9120:(e,t,r)=>{"use strict";r.d(t,{A:()=>u});const n={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};var s,a=new Uint8Array(16);function i(){if(!s&&!(s="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return s(a)}for(var o=[],c=0;c<256;++c)o.push((c+256).toString(16).slice(1));function l(e,t=0){return(o[e[t+0]]+o[e[t+1]]+o[e[t+2]]+o[e[t+3]]+"-"+o[e[t+4]]+o[e[t+5]]+"-"+o[e[t+6]]+o[e[t+7]]+"-"+o[e[t+8]]+o[e[t+9]]+"-"+o[e[t+10]]+o[e[t+11]]+o[e[t+12]]+o[e[t+13]]+o[e[t+14]]+o[e[t+15]]).toLowerCase()}const u=function(e,t,r){if(n.randomUUID&&!t&&!e)return n.randomUUID();var s=(e=e||{}).random||(e.rng||i)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){r=r||0;for(var a=0;a<16;++a)t[r+a]=s[a];return t}return l(s)}},9137:(e,t,r)=>{"use strict";r.d(t,{T:()=>p});var n=r(2366);const s=/^(?:[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;const a=function(e){return"string"==typeof e&&s.test(e)};var i=r(9120),o=r(4850);function c(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const l=["*","_","`"];function u(e,t,r){const{firstNode:n,lastNode:s,nodeColors:a,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:u=9}=r??{};let d=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%\ngraph TD;\n`:"graph TD;\n";if(i){const t="default",r={[t]:"{0}({1})"};void 0!==n&&(r[n]="{0}([{1}]):::first"),void 0!==s&&(r[s]="{0}([{1}]):::last");for(const[n,s]of Object.entries(e)){const e=s.name.split(":").pop()??"";let a=l.some((t=>e.startsWith(t)&&e.endsWith(t)))?`

${e}

`:e;Object.keys(s.metadata??{}).length&&(a+=`
${Object.entries(s.metadata??{}).map((([e,t])=>`${e} = ${t}`)).join("\n")}`);const i=(r[n]??r[t]).replace("{0}",c(n)).replace("{1}",a);d+=`\t${i}\n`}}const h={};for(const e of t){const t=e.source.split(":"),r=e.target.split(":"),n=t.filter(((e,t)=>e===r[t])).join(":");h[n]||(h[n]=[]),h[n].push(e)}const p=new Set;function m(e,t){const r=1===e.length&&e[0].source===e[0].target;if(t&&!r){const e=t.split(":").pop();if(p.has(e))throw new Error(`Found duplicate subgraph '${e}' -- 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.`);p.add(e),d+=`\tsubgraph ${e}\n`}for(const t of e){const{source:e,target:r,data:n,conditional:s}=t;let a="";if(void 0!==n){let e=n;const t=e.split(" ");t.length>u&&(e=Array.from({length:Math.ceil(t.length/u)},((e,r)=>t.slice(r*u,(r+1)*u).join(" "))).join(" 
 ")),a=s?` -.  ${e}  .-> `:` --  ${e}  --\x3e `}else a=s?" -.-> ":" --\x3e ";d+=`\t${c(e)}${a}${c(r)};\n`}for(const e in h)e.startsWith(`${t}:`)&&e!==t&&m(h[e],e);t&&!r&&(d+="\tend\n")}m(h[""]??[],"");for(const e in h)e.includes(":")||""===e||m(h[e],e);return i&&(d+=function(e){let t="";for(const[r,n]of Object.entries(e))t+=`\tclassDef ${r} ${n};\n`;return t}(a??{})),d}function d(e,t){if(void 0!==e&&!a(e))return e;if(!(0,o.T)(t))return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e,e}catch(e){return t.getName()}}function h(e){return(0,o.T)(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...(0,n.Ik)(e.data.schema),title:e.data.name}}}class p{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?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach(((t,r)=>{e[t.id]=a(t.id)?r:t.id})),{nodes:Object.values(this.nodes).map((t=>({id:e[t.id],...h(t)}))),edges:this.edges.map((t=>{const r={source:e[t.source],target:e[t.target]};return void 0!==t.data&&(r.data=t.data),void 0!==t.conditional&&(r.conditional=t.conditional),r}))}}addNode(e,t,r){if(void 0!==t&&void 0!==this.nodes[t])throw new Error(`Node with id ${t} already exists`);const n=t??(0,i.A)(),s={id:n,data:e,name:d(t,e),metadata:r};return this.nodes[n]=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,n){if(void 0===this.nodes[e.id])throw new Error(`Source node ${e.id} not in graph`);if(void 0===this.nodes[t.id])throw new Error(`Target node ${t.id} not in graph`);const s={source:e.id,target:t.id,data:r,conditional:n};return this.edges.push(s),s}firstNode(){return m(this)}lastNode(){return f(this)}extend(e,t=""){let r=t;Object.values(e.nodes).map((e=>e.id)).every(a)&&(r="");const n=e=>r?`${r}:${e}`:e;Object.entries(e.nodes).forEach((([e,t])=>{this.nodes[n(e)]={...t,id:n(e)}}));const s=e.edges.map((e=>({...e,source:n(e.source),target:n(e.target)})));this.edges=[...this.edges,...s];const i=e.firstNode(),o=e.lastNode();return[i?{id:n(i.id),data:i.data}:void 0,o?{id:n(o.id),data:o.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&m(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&f(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map((e=>[e.id,e.name]))),t=new Map;Object.values(e).forEach((e=>{t.set(e,(t.get(e)||0)+1)}));const r=r=>{const n=e[r];return a(r)&&1===t.get(n)?n:r};return new p({nodes:Object.fromEntries(Object.entries(this.nodes).map((([e,t])=>[r(e),{...t,id:r(e)}]))),edges:this.edges.map((e=>({...e,source:r(e.source),target:r(e.target)})))})}drawMermaid(e){const{withStyles:t,curveStyle:r,nodeColors:n={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:s}=e??{},a=this.reid(),i=a.firstNode(),o=a.lastNode();return u(a.nodes,a.edges,{firstNode:i?.id,lastNode:o?.id,withStyles:t,curveStyle:r,nodeColors:n,wrapLabelNWords:s})}async drawMermaidPng(e){return async function(e,t){let{backgroundColor:r="white"}=t??{};const n=btoa(e);void 0!==r&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));const s=`https://mermaid.ink/img/${n}?bgColor=${r}`,a=await fetch(s);if(!a.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${a.status}`,`Status text: ${a.statusText}`].join("\n"));return await a.blob()}(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}}function m(e,t=[]){const r=new Set(e.edges.filter((e=>!t.includes(e.source))).map((e=>e.target))),n=[];for(const s of Object.values(e.nodes))t.includes(s.id)||r.has(s.id)||n.push(s);return 1===n.length?n[0]:void 0}function f(e,t=[]){const r=new Set(e.edges.filter((e=>!t.includes(e.target))).map((e=>e.source))),n=[];for(const s of Object.values(e.nodes))t.includes(s.id)||r.has(s.id)||n.push(s);return 1===n.length?n[0]:void 0}},9418:(e,t,r)=>{"use strict";e=r.nmd(e);const n=(e=0)=>t=>`[${38+e};5;${t}m`,s=(e=0)=>(t,r,n)=>`[${38+e};2;${t};${r};${n}m`;Object.defineProperty(e,"exports",{enumerable:!0,get:function(){const e=new Map,t={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]}};t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright;for(const[r,n]of Object.entries(t)){for(const[r,s]of Object.entries(n))t[r]={open:`[${s[0]}m`,close:`[${s[1]}m`},n[r]=t[r],e.set(s[0],s[1]);Object.defineProperty(t,r,{value:n,enumerable:!1})}return Object.defineProperty(t,"codes",{value:e,enumerable:!1}),t.color.close="",t.bgColor.close="",t.color.ansi256=n(),t.color.ansi16m=s(),t.bgColor.ansi256=n(10),t.bgColor.ansi16m=s(10),Object.defineProperties(t,{rgbToAnsi256:{value:(e,t,r)=>e===t&&t===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(r/255*5),enumerable:!1},hexToRgb:{value:e=>{const t=/(?[a-f\d]{6}|[a-f\d]{3})/i.exec(e.toString(16));if(!t)return[0,0,0];let{colorString:r}=t.groups;3===r.length&&(r=r.split("").map((e=>e+e)).join(""));const n=Number.parseInt(r,16);return[n>>16&255,n>>8&255,255&n]},enumerable:!1},hexToAnsi256:{value:e=>t.rgbToAnsi256(...t.hexToRgb(e)),enumerable:!1}}),t}})},9478:e=>{"use strict";e.exports=function(e,t){if("string"!=typeof e)throw new TypeError("Expected a string");return t=void 0===t?"_":t,e.replace(/([a-z\d])([A-Z])/g,"$1"+t+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+t+"$2").toLowerCase()}},9583:(e,t,r)=>{"use strict";r.r(t),r.d(t,{getEnv:()=>c,getEnvironmentVariable:()=>d,getRuntimeEnvironment:()=>u,isBrowser:()=>n,isDeno:()=>i,isJsDom:()=>a,isNode:()=>o,isWebWorker:()=>s});const n=()=>"undefined"!=typeof window&&void 0!==window.document,s=()=>"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name,a=()=>"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),i=()=>"undefined"!=typeof Deno,o=()=>"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node&&!i(),c=()=>{let e;return e=n()?"browser":o()?"node":s()?"webworker":a()?"jsdom":i()?"deno":"other",e};let l;async function u(){if(void 0===l){const e=c();l={library:"langchain-js",runtime:e}}return l}function d(e){try{return"undefined"!=typeof process?process.env?.[e]:i()?Deno?.env.get(e):void 0}catch(e){return}}},9589:(e,t,r)=>{"use strict";const n=r(9718),s=r(6874),a=r(3908),i=r(1123),o=r(144),c=r(6953),l=r(7414),u=r(3007),d=r(1832),h=r(2938),p=r(6254),m=r(4493),f=r(1729),g=r(560),y=r(9970),b=r(1763),w=r(909),v=r(3927),_=r(4277),k=r(5580),S=r(7059),E=r(4641),x=r(3999),T=r(4089),C=r(5200),P=r(2111),O=r(6170),A=r(3904),I=r(8311),M=r(7638),R=r(7631),j=r(9628),N=r(270),$=r(1261),L=r(3874),F=r(7075),D=r(5571),z=r(5342),U=r(6780),B=r(2525),q=r(5032);e.exports={parse:o,valid:c,clean:l,inc:u,diff:d,major:h,minor:p,patch:m,prerelease:f,compare:g,rcompare:y,compareLoose:b,compareBuild:w,sort:v,rsort:_,gt:k,lt:S,eq:E,neq:x,gte:T,lte:C,cmp:P,coerce:O,Comparator:A,Range:I,satisfies:M,toComparators:R,maxSatisfying:j,minSatisfying:N,minVersion:$,validRange:L,outside:F,gtr:D,ltr:z,intersects:U,simplifyRange:B,subset:q,SemVer:a,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:s.SEMVER_SPEC_VERSION,RELEASE_TYPES:s.RELEASE_TYPES,compareIdentifiers:i.compareIdentifiers,rcompareIdentifiers:i.rcompareIdentifiers}},9624:(e,t,r)=>{"use strict";r.r(t),r.d(t,{AsyncCaller:()=>o});var n=r(4116),s=r(3290);const a=[400,401,402,403,404,405,406,407,409],i=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||"AbortError"===e.name)throw e;if("ECONNABORTED"===e?.code)throw e;const t=e?.response?.status??e?.status;if(t&&a.includes(+t))throw e;if("insufficient_quota"===e?.error?.code){const t=new Error(e?.message);throw t.name="InsufficientQuotaError",t}};class o{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??i;const t=s.default;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add((()=>n((()=>e(...t).catch((e=>{throw e instanceof Error?e:new Error(e)}))),{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(((t,r)=>{e.signal?.addEventListener("abort",(()=>{r(new Error("AbortError"))}))}))]):this.call(t,...r)}fetch(...e){return this.call((()=>fetch(...e).then((e=>e.ok?e:Promise.reject(e)))))}}},9628:(e,t,r)=>{"use strict";const n=r(3908),s=r(8311);e.exports=(e,t,r)=>{let a=null,i=null,o=null;try{o=new s(t,r)}catch(e){return null}return e.forEach((e=>{o.test(e)&&(a&&-1!==i.compare(e)||(a=e,i=new n(a,r)))})),a}},9718:(e,t,r)=>{"use strict";const{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:s,MAX_LENGTH:a}=r(6874),i=r(7272),o=(t=e.exports={}).re=[],c=t.safeRe=[],l=t.src=[],u=t.safeSrc=[],d=t.t={};let h=0;const p="[a-zA-Z0-9-]",m=[["\\s",1],["\\d",a],[p,s]],f=(e,t,r)=>{const n=(e=>{for(const[t,r]of m)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e})(t),s=h++;i(e,s,t),d[e]=s,l[s]=t,u[s]=n,o[s]=new RegExp(t,r?"g":void 0),c[s]=new RegExp(n,r?"g":void 0)};f("NUMERICIDENTIFIER","0|[1-9]\\d*"),f("NUMERICIDENTIFIERLOOSE","\\d+"),f("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),f("MAINVERSION",`(${l[d.NUMERICIDENTIFIER]})\\.(${l[d.NUMERICIDENTIFIER]})\\.(${l[d.NUMERICIDENTIFIER]})`),f("MAINVERSIONLOOSE",`(${l[d.NUMERICIDENTIFIERLOOSE]})\\.(${l[d.NUMERICIDENTIFIERLOOSE]})\\.(${l[d.NUMERICIDENTIFIERLOOSE]})`),f("PRERELEASEIDENTIFIER",`(?:${l[d.NONNUMERICIDENTIFIER]}|${l[d.NUMERICIDENTIFIER]})`),f("PRERELEASEIDENTIFIERLOOSE",`(?:${l[d.NONNUMERICIDENTIFIER]}|${l[d.NUMERICIDENTIFIERLOOSE]})`),f("PRERELEASE",`(?:-(${l[d.PRERELEASEIDENTIFIER]}(?:\\.${l[d.PRERELEASEIDENTIFIER]})*))`),f("PRERELEASELOOSE",`(?:-?(${l[d.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${l[d.PRERELEASEIDENTIFIERLOOSE]})*))`),f("BUILDIDENTIFIER",`${p}+`),f("BUILD",`(?:\\+(${l[d.BUILDIDENTIFIER]}(?:\\.${l[d.BUILDIDENTIFIER]})*))`),f("FULLPLAIN",`v?${l[d.MAINVERSION]}${l[d.PRERELEASE]}?${l[d.BUILD]}?`),f("FULL",`^${l[d.FULLPLAIN]}$`),f("LOOSEPLAIN",`[v=\\s]*${l[d.MAINVERSIONLOOSE]}${l[d.PRERELEASELOOSE]}?${l[d.BUILD]}?`),f("LOOSE",`^${l[d.LOOSEPLAIN]}$`),f("GTLT","((?:<|>)?=?)"),f("XRANGEIDENTIFIERLOOSE",`${l[d.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),f("XRANGEIDENTIFIER",`${l[d.NUMERICIDENTIFIER]}|x|X|\\*`),f("XRANGEPLAIN",`[v=\\s]*(${l[d.XRANGEIDENTIFIER]})(?:\\.(${l[d.XRANGEIDENTIFIER]})(?:\\.(${l[d.XRANGEIDENTIFIER]})(?:${l[d.PRERELEASE]})?${l[d.BUILD]}?)?)?`),f("XRANGEPLAINLOOSE",`[v=\\s]*(${l[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[d.XRANGEIDENTIFIERLOOSE]})(?:${l[d.PRERELEASELOOSE]})?${l[d.BUILD]}?)?)?`),f("XRANGE",`^${l[d.GTLT]}\\s*${l[d.XRANGEPLAIN]}$`),f("XRANGELOOSE",`^${l[d.GTLT]}\\s*${l[d.XRANGEPLAINLOOSE]}$`),f("COERCEPLAIN",`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),f("COERCE",`${l[d.COERCEPLAIN]}(?:$|[^\\d])`),f("COERCEFULL",l[d.COERCEPLAIN]+`(?:${l[d.PRERELEASE]})?`+`(?:${l[d.BUILD]})?(?:$|[^\\d])`),f("COERCERTL",l[d.COERCE],!0),f("COERCERTLFULL",l[d.COERCEFULL],!0),f("LONETILDE","(?:~>?)"),f("TILDETRIM",`(\\s*)${l[d.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",f("TILDE",`^${l[d.LONETILDE]}${l[d.XRANGEPLAIN]}$`),f("TILDELOOSE",`^${l[d.LONETILDE]}${l[d.XRANGEPLAINLOOSE]}$`),f("LONECARET","(?:\\^)"),f("CARETTRIM",`(\\s*)${l[d.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",f("CARET",`^${l[d.LONECARET]}${l[d.XRANGEPLAIN]}$`),f("CARETLOOSE",`^${l[d.LONECARET]}${l[d.XRANGEPLAINLOOSE]}$`),f("COMPARATORLOOSE",`^${l[d.GTLT]}\\s*(${l[d.LOOSEPLAIN]})$|^$`),f("COMPARATOR",`^${l[d.GTLT]}\\s*(${l[d.FULLPLAIN]})$|^$`),f("COMPARATORTRIM",`(\\s*)${l[d.GTLT]}\\s*(${l[d.LOOSEPLAIN]}|${l[d.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",f("HYPHENRANGE",`^\\s*(${l[d.XRANGEPLAIN]})\\s+-\\s+(${l[d.XRANGEPLAIN]})\\s*$`),f("HYPHENRANGELOOSE",`^\\s*(${l[d.XRANGEPLAINLOOSE]})\\s+-\\s+(${l[d.XRANGEPLAINLOOSE]})\\s*$`),f("STAR","(<|>)?=?\\s*\\*"),f("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),f("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")},9830:(e,t,r)=>{"use strict";async function n(e,t){if(void 0===t)return e;let r;return Promise.race([e.catch((e=>{if(!t?.aborted)throw e})),new Promise(((e,n)=>{r=()=>{n(new Error("Aborted"))},t.addEventListener("abort",r),t.aborted&&n(new Error("Aborted"))}))]).finally((()=>t.removeEventListener("abort",r)))}r.d(t,{o:()=>n})},9849:(e,t,r)=>{"use strict";r.d(t,{ez:()=>O,RG:()=>A,Ns:()=>R,Vt:()=>C,Qs:()=>P,D4:()=>x,g2:()=>T,QC:()=>M,Xm:()=>I});var n=Object.prototype.toString,s=Array.isArray||function(e){return"[object Array]"===n.call(e)};function a(e){return"function"==typeof e}function i(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function o(e,t){return null!=e&&"object"==typeof e&&t in e}var c=RegExp.prototype.test;var l=/\S/;function u(e){return!function(e,t){return c.call(e,t)}(l,e)}var d={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};var h=/\s*/,p=/\s+/,m=/\s*=/,f=/\s*\}/,g=/#|\^|\/|>|\{|&|=|!/;function y(e){this.string=e,this.tail=e,this.pos=0}function b(e,t){this.view=e,this.cache={".":this.view},this.parent=t}function w(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}y.prototype.eos=function(){return""===this.tail},y.prototype.scan=function(e){var t=this.tail.match(e);if(!t||0!==t.index)return"";var r=t[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r},y.prototype.scanUntil=function(e){var t,r=this.tail.search(e);switch(r){case-1:t=this.tail,this.tail="";break;case 0:t="";break;default:t=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=t.length,t},b.prototype.push=function(e){return new b(e,this)},b.prototype.lookup=function(e){var t,r,n,s=this.cache;if(s.hasOwnProperty(e))t=s[e];else{for(var i,c,l,u=this,d=!1;u;){if(e.indexOf(".")>0)for(i=u.view,c=e.split("."),l=0;null!=i&&l0?s[s.length-1][4]:r;break;default:n.push(t)}return r}(function(e){for(var t,r,n=[],s=0,a=e.length;s"===i?o=this.renderPartial(a,t,r,s):"&"===i?o=this.unescapedValue(a,t):"name"===i?o=this.escapedValue(a,t,s):"text"===i&&(o=this.rawValue(a)),void 0!==o&&(c+=o);return c},w.prototype.renderSection=function(e,t,r,n,i){var o=this,c="",l=t.lookup(e[1]);if(l){if(s(l))for(var u=0,d=l.length;u0||!r)&&(s[a]=n+s[a]);return s.join("\n")},w.prototype.renderPartial=function(e,t,r,n){if(r){var s=this.getConfigTags(n),i=a(r)?r(e[1]):r[e[1]];if(null!=i){var o=e[6],c=e[5],l=e[4],u=i;0==c&&l&&(u=this.indentPartial(i,l,o));var d=this.parse(u,s);return this.renderTokens(d,t,r,u,n)}}},w.prototype.unescapedValue=function(e,t){var r=t.lookup(e[1]);if(null!=r)return r},w.prototype.escapedValue=function(e,t,r){var n=this.getConfigEscape(r)||v.escape,s=t.lookup(e[1]);if(null!=s)return"number"==typeof s&&n===v.escape?String(s):n(s)},w.prototype.rawValue=function(e){return e[1]},w.prototype.getConfigTags=function(e){return s(e)?e:e&&"object"==typeof e?e.tags:void 0},w.prototype.getConfigEscape=function(e){return e&&"object"==typeof e&&!s(e)?e.escape:void 0};var v={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){_.templateCache=e},get templateCache(){return _.templateCache}},_=new w;v.clearCache=function(){return _.clearCache()},v.parse=function(e,t){return _.parse(e,t)},v.render=function(e,t,r,n){if("string"!=typeof e)throw new TypeError('Invalid template! Template should be a "string" but "'+((s(a=e)?"array":typeof a)+'" was given as the first argument for mustache#render(template, view, partials)'));var a;return _.render(e,t,r,n)},v.escape=function(e){return String(e).replace(/[&<>"'`=\/]/g,(function(e){return d[e]}))},v.Scanner=y,v.Context=b,v.Writer=w;const k=v;var S=r(1368);function E(){k.escape=e=>e}const x=e=>{const t=e.split(""),r=[],n=(e,r)=>{for(let n=r;n{E();return(e=>e.map((e=>"name"===e[0]?{type:"variable",name:e[1].includes(".")?e[1].split(".")[0]:e[1]}:["#","&","^",">"].includes(e[0])?{type:"variable",name:e[1]}:{type:"literal",text:e[1]})))(k.parse(e))},C=(e,t)=>x(e).reduce(((e,r)=>{if("variable"===r.type){if(r.name in t){return e+("string"==typeof t[r.name]?t[r.name]:JSON.stringify(t[r.name]))}throw new Error(`(f-string) Missing value for input ${r.name}`)}return e+r.text}),""),P=(e,t)=>(E(),k.render(e,t)),O={"f-string":C,mustache:P},A={"f-string":x,mustache:T},I=(e,t,r)=>{try{return O[t](e,r)}catch(e){throw(0,S.Y)(e,"INVALID_PROMPT_INPUT")}},M=(e,t)=>A[t](e),R=(e,t,r)=>{if(!(t in O)){const e=Object.keys(O);throw new Error(`Invalid template format. Got \`${t}\`;\n should be one of ${e}`)}try{const n=r.reduce(((e,t)=>(e[t]="foo",e)),{});Array.isArray(e)?e.forEach((e=>{if("text"===e.type)I(e.text,t,n);else{if("image_url"!==e.type)throw new Error(`Invalid message template received. ${JSON.stringify(e,null,2)}`);if("string"==typeof e.image_url)I(e.image_url,t,n);else{const r=e.image_url.url;I(r,t,n)}}})):I(e,t,n)}catch(e){throw new Error(`Invalid prompt schema: ${e.message}`)}}},9970:(e,t,r)=>{"use strict";const n=r(560);e.exports=(e,t,r)=>n(t,e,r)},9998:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){let n=0,s=e.length;for(;s>0;){const a=s/2|0;let i=n+a;r(e[i],t)<=0?(n=++i,s-=a+1):s=a}return n}}},n={};function s(e){var t=n[e];if(void 0!==t)return t.exports;var a=n[e]={id:e,loaded:!1,exports:{}};return r[e](a,a.exports,s),a.loaded=!0,a.exports}t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,s.t=function(r,n){if(1&n&&(r=this(r)),8&n)return r;if("object"==typeof r&&r){if(4&n&&r.__esModule)return r;if(16&n&&"function"==typeof r.then)return r}var a=Object.create(null);s.r(a);var i={};e=e||[null,t({}),t([]),t(t)];for(var o=2&n&&r;"object"==typeof o&&!~e.indexOf(o);o=t(o))Object.getOwnPropertyNames(o).forEach((e=>i[e]=()=>r[e]));return i.default=()=>r,s.d(a,i),a},s.d=(e,t)=>{for(var r in t)s.o(t,r)&&!s.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),(()=>{"use strict";var e={};s.r(e),s.d(e,{RouterRunnable:()=>re,Runnable:()=>Y.YN,RunnableAssign:()=>Y.B2,RunnableBinding:()=>Y.fJ,RunnableBranch:()=>ne,RunnableEach:()=>Y.Vi,RunnableLambda:()=>Y.jY,RunnableMap:()=>Y.ck,RunnableParallel:()=>Y.Pq,RunnablePassthrough:()=>te,RunnablePick:()=>Y.Fm,RunnableRetry:()=>Y.AO,RunnableSequence:()=>Y.zZ,RunnableToolLike:()=>Y.pG,RunnableWithFallbacks:()=>Y.lH,RunnableWithMessageHistory:()=>ae,_coerceToRunnable:()=>Y.Bp,ensureConfig:()=>Q.ZI,getCallbackManagerForConfig:()=>Q.kJ,mergeConfigs:()=>Q.SV,patchConfig:()=>Q.tn,pickRunnableConfigKeys:()=>Q.DY});var t={};s.r(t);var r={};s.r(r),s.d(r,{insecureHash:()=>Be});var n={};s.r(n),s.d(n,{BaseCache:()=>Ve,InMemoryCache:()=>Je,deserializeStoredGeneration:()=>We,getCacheKey:()=>Ke,serializeGeneration:()=>He});var a={};s.r(a),s.d(a,{BaseChatMessageHistory:()=>Qe,BaseListChatMessageHistory:()=>et,InMemoryChatMessageHistory:()=>tt});var i={};s.r(i),s.d(i,{BaseDocumentTransformer:()=>nt,Document:()=>rt,MappingDocumentTransformer:()=>st});var o={};s.r(o),s.d(o,{Embeddings:()=>it});var c={};s.r(c),s.d(c,{BaseExampleSelector:()=>ot,BasePromptSelector:()=>ct,ConditionalPromptSelector:()=>lt,LengthBasedExampleSelector:()=>pt,SemanticSimilarityExampleSelector:()=>ft,isChatModel:()=>dt,isLLM:()=>ut});var l={};s.r(l),s.d(l,{encodingForModel:()=>Ct,getEncoding:()=>Tt});var u={};s.r(u),s.d(u,{BaseLangChain:()=>Rt,BaseLanguageModel:()=>jt,calculateMaxTokens:()=>Mt,getEmbeddingContextSize:()=>Ot,getModelContextSize:()=>At,getModelNameForTiktoken:()=>Pt,isOpenAITool:()=>It});var d={};s.r(d),s.d(d,{BaseChatModel:()=>zt,SimpleChatModel:()=>Ut,createChatMessageChunkEncoderStream:()=>Ft});var h={};s.r(h),s.d(h,{BaseLLM:()=>Bt,LLM:()=>qt});var p={};s.r(p),s.d(p,{BaseMemory:()=>Kt,getInputValue:()=>Ht,getOutputValue:()=>Vt,getPromptInputKey:()=>Gt});var m={};s.r(m),s.d(m,{applyPatch:()=>Rr.X6,compare:()=>Rr.UD});var f={};s.r(f),s.d(f,{AsymmetricStructuredOutputParser:()=>Mr,BaseCumulativeTransformOutputParser:()=>kr,BaseLLMOutputParser:()=>Zt,BaseOutputParser:()=>Xt,BaseTransformOutputParser:()=>_r,BytesOutputParser:()=>Sr,CommaSeparatedListOutputParser:()=>xr,CustomListOutputParser:()=>Tr,JsonMarkdownStructuredOutputParser:()=>Ir,JsonOutputParser:()=>Nr,ListOutputParser:()=>Er,MarkdownListOutputParser:()=>Pr,NumberedListOutputParser:()=>Cr,OutputParserException:()=>Yt,StringOutputParser:()=>Or,StructuredOutputParser:()=>Ar,XMLOutputParser:()=>Dr,XML_FORMAT_INSTRUCTIONS:()=>Fr,parseJsonMarkdown:()=>jr.D,parsePartialJson:()=>jr.d,parseXMLMarkdown:()=>Br});var g={};s.r(g),s.d(g,{AIMessagePromptTemplate:()=>Kr.sS,BaseChatPromptTemplate:()=>Kr.qF,BaseMessagePromptTemplate:()=>Kr.pl,BaseMessageStringPromptTemplate:()=>Kr.OT,BasePromptTemplate:()=>qr.m,BaseStringPromptTemplate:()=>Gr.L,ChatMessagePromptTemplate:()=>Kr.Wn,ChatPromptTemplate:()=>Kr.RZ,DEFAULT_FORMATTER_MAPPING:()=>Jr.ez,DEFAULT_PARSER_MAPPING:()=>Jr.RG,DictPromptTemplate:()=>Qr.l,FewShotChatMessagePromptTemplate:()=>Wr.s,FewShotPromptTemplate:()=>Wr.FewShotPromptTemplate,HumanMessagePromptTemplate:()=>Kr.FS,ImagePromptTemplate:()=>Zr.C,MessagesPlaceholder:()=>Kr.GL,PipelinePromptTemplate:()=>Hr,PromptTemplate:()=>Vr.PromptTemplate,StructuredPrompt:()=>Yr,SystemMessagePromptTemplate:()=>Kr.BJ,checkValidTemplate:()=>Jr.Ns,interpolateFString:()=>Jr.Vt,interpolateMustache:()=>Jr.Qs,parseFString:()=>Jr.D4,parseMustache:()=>Jr.g2,parseTemplate:()=>Jr.QC,renderTemplate:()=>Jr.Xm});var y={};s.r(y),s.d(y,{BaseRetriever:()=>en});var b={};s.r(b),s.d(b,{BaseStore:()=>tn,InMemoryStore:()=>rn});var w={};s.r(w),s.d(w,{Validator:()=>wr,deepCompareStrict:()=>Qt,toJsonSchema:()=>on,validatesOnlyStrings:()=>cn});var v={};s.r(v),s.d(v,{BaseToolkit:()=>yn,DynamicStructuredTool:()=>gn,DynamicTool:()=>fn,StructuredTool:()=>pn,Tool:()=>mn,ToolInputParsingException:()=>an.qe,isLangChainTool:()=>hn,isRunnableToolLike:()=>un,isStructuredTool:()=>ln,isStructuredToolParams:()=>dn,tool:()=>bn});var _={};s.r(_),s.d(_,{LangChainTracerV1:()=>En});var k={};s.r(k),s.d(k,{getTracingCallbackHandler:()=>xn,getTracingV2CallbackHandler:()=>Tn});var S={};s.r(S),s.d(S,{RunCollectorCallbackHandler:()=>Pn});var E={};s.r(E),s.d(E,{chunkArray:()=>On});var x={};s.r(x),s.d(x,{convertToOpenAIFunction:()=>An,convertToOpenAITool:()=>In,isLangChainTool:()=>hn,isRunnableToolLike:()=>un,isStructuredTool:()=>ln,isStructuredToolParams:()=>dn});var T={};s.r(T),s.d(T,{cosineSimilarity:()=>Ln,euclideanDistance:()=>Dn,innerProduct:()=>Fn,matrixFunc:()=>Nn,maximalMarginalRelevance:()=>zn,normalize:()=>$n});var C={};s.r(C),s.d(C,{SaveableVectorStore:()=>Kn,VectorStore:()=>qn,VectorStoreRetriever:()=>Bn});var P={};s.r(P),s.d(P,{FakeChatMessageHistory:()=>Qn,FakeChatModel:()=>Jn,FakeEmbeddings:()=>ns,FakeLLM:()=>Vn,FakeListChatMessageHistory:()=>es,FakeListChatModel:()=>Yn,FakeRetriever:()=>Xn,FakeRunnable:()=>Hn,FakeSplitIntoListParser:()=>Wn,FakeStreamingChatModel:()=>Zn,FakeStreamingLLM:()=>Gn,FakeTool:()=>rs,FakeTracer:()=>ts,FakeVectorStore:()=>is,SingleRunExtractor:()=>as,SyntheticEmbeddings:()=>ss});var O={};s.r(O),s.d(O,{isZodSchema:()=>Lt});var A={};s.r(A),s.d(A,{agents:()=>t,caches:()=>n,callbacks__base:()=>Ze,callbacks__manager:()=>Xe,callbacks__promises:()=>Ye,chat_history:()=>a,documents:()=>i,embeddings:()=>o,example_selectors:()=>c,language_models__base:()=>u,language_models__chat_models:()=>d,language_models__llms:()=>h,load__serializable:()=>Ne,memory:()=>p,messages:()=>se,output_parsers:()=>f,outputs:()=>$t,prompt_values:()=>gt,prompts:()=>g,retrievers:()=>y,runnables:()=>e,stores:()=>b,tools:()=>v,tracers__base:()=>vn,tracers__console:()=>_n,tracers__initialize:()=>k,tracers__log_stream:()=>Cn,tracers__run_collector:()=>S,tracers__tracer_langchain:()=>kn,tracers__tracer_langchain_v1:()=>_,utils__async_caller:()=>at,utils__chunk_array:()=>E,utils__env:()=>Sn,utils__function_calling:()=>x,utils__hash:()=>r,utils__json_patch:()=>m,utils__json_schema:()=>w,utils__math:()=>T,utils__stream:()=>ee,utils__testing:()=>P,utils__tiktoken:()=>l,utils__types:()=>O,vectorstores:()=>C});var I,M=s(4476);!function(e){e.NAVIGATE="NAVIGATE",e.CLICK="CLICK",e.EXTRACT="EXTRACT",e.LOG="LOG",e.CONTENT_READY="CONTENT_READY",e.EXECUTE_WORKFLOW="EXECUTE_WORKFLOW",e.WORKFLOW_STATUS="WORKFLOW_STATUS",e.CONNECTION_STATUS="CONNECTION_STATUS",e.EXECUTE_QUERY="EXECUTE_QUERY",e.RUN_EXAMPLE="RUN_EXAMPLE",e.HEARTBEAT="HEARTBEAT",e.HEARTBEAT_ACK="HEARTBEAT_ACK",e.AGENT_STREAM_UPDATE="AGENT_STREAM_UPDATE",e.CANCEL_TASK="CANCEL_TASK"}(I||(I={}));const R=M.z.nativeEnum(I),j=M.z.object({type:R,payload:M.z.unknown()}),N=j.extend({type:M.z.literal(I.NAVIGATE),payload:M.z.object({url:M.z.string()})}),$=j.extend({type:M.z.literal(I.CLICK),payload:M.z.object({selector:M.z.string()})}),L=j.extend({type:M.z.literal(I.LOG),payload:M.z.object({source:M.z.string(),message:M.z.string(),level:M.z.enum(["info","error","warning"]),timestamp:M.z.string()})}),F=j.extend({type:M.z.literal(I.CONTENT_READY),payload:M.z.object({url:M.z.string(),title:M.z.string()})}),D=j.extend({type:M.z.literal(I.EXECUTE_WORKFLOW),payload:M.z.object({dsl:M.z.string()})}),z=j.extend({type:M.z.literal(I.WORKFLOW_STATUS),payload:M.z.object({workflowId:M.z.string(),steps:M.z.array(M.z.object({id:M.z.string(),status:M.z.string(),message:M.z.string().optional(),error:M.z.string().optional()})),output:M.z.unknown().optional()})}),U=j.extend({type:M.z.literal(I.CONNECTION_STATUS),payload:M.z.object({connected:M.z.boolean(),port:M.z.string().optional()})}),B=j.extend({type:M.z.literal(I.EXECUTE_QUERY),payload:M.z.object({query:M.z.string()})}),q=j.extend({type:M.z.literal(I.RUN_EXAMPLE),payload:M.z.object({exampleType:M.z.enum(["basic","multiTab"]).default("basic")})}),K=j.extend({type:M.z.literal(I.HEARTBEAT),payload:M.z.object({timestamp:M.z.number()})}),W=j.extend({type:M.z.literal(I.HEARTBEAT_ACK),payload:M.z.object({timestamp:M.z.number()})}),H=j.extend({type:M.z.literal(I.AGENT_STREAM_UPDATE),payload:M.z.object({step:M.z.number(),action:M.z.string(),status:M.z.enum(["thinking","executing","completed","error"]),details:M.z.object({content:M.z.string().optional(),toolName:M.z.string().optional(),toolArgs:M.z.any().optional(),toolResult:M.z.string().optional(),error:M.z.string().optional(),messageType:M.z.string().optional()})})}),V=j.extend({type:M.z.literal(I.CANCEL_TASK),payload:M.z.object({reason:M.z.string().optional(),source:M.z.string().optional()})});M.z.discriminatedUnion("type",[N,$,L,F,D,z,U,B,q,K,W,H,V]);var G;!function(e){e.OPTIONS_TO_BACKGROUND="options-to-background",e.SIDEPANEL_TO_BACKGROUND="sidepanel-to-background"}(G||(G={}));M.z.nativeEnum(G),M.z.object({type:M.z.nativeEnum(I),payload:M.z.unknown(),id:M.z.string().optional()});M.z.object({DEV_MODE:M.z.boolean(),VERSION:M.z.string(),LOG_LEVEL:M.z.enum(["info","error","warning","debug"]).default("info")});const J={DEV_MODE:!0,VERSION:"0.1.0",LOG_LEVEL:"info"};const Z=M.z.enum(["info","error","warning"]);M.z.object({source:M.z.string(),message:M.z.string(),level:Z,timestamp:M.z.string()});class X{static initialize(e={}){this.debugMode=e.debugMode||!1}static registerPort(e,t){this.connectedPorts.set(e,t)}static unregisterPort(e){this.connectedPorts.delete(e)}static log(e,t,r="info"){if(!this.debugMode&&"info"===r)return;const n=`[${e}]`;switch(r){case"error":console.error(`${n} ${t}`);break;case"warning":console.warn(`${n} ${t}`);break;default:console.log(`${n} ${t}`)}const s={source:e,message:t,level:r,timestamp:(new Date).toISOString()};let a=!1;if(J.DEV_MODE){const e=this.connectedPorts.get(G.OPTIONS_TO_BACKGROUND);if(e)try{void 0!==e.name?(e.postMessage({type:I.LOG,payload:s}),a=!0):this.unregisterPort(G.OPTIONS_TO_BACKGROUND)}catch(e){this.unregisterPort(G.OPTIONS_TO_BACKGROUND),"info"===r&&t.includes("heartbeat")||console.warn(`Failed to send log to options page: ${e instanceof Error?e.message:String(e)}`)}}!a&&"undefined"!=typeof chrome&&chrome.runtime&&chrome.runtime.sendMessage({type:I.LOG,payload:s}).catch((e=>{}))}}X.connectedPorts=new Map,X.debugMode=!1;var Y=s(3313),Q=s(765),ee=s(58);class te extends Y.YN{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=(0,Q.ZI)(t);return this.func&&await this.func(e,r),this._callWithConfig((e=>Promise.resolve(e)),e,r)}async*transform(e,t){const r=(0,Q.ZI)(t);let n,s=!0;for await(const t of this._transformStreamWithConfig(e,(e=>e),r))if(yield t,s)if(void 0===n)n=t;else try{n=(0,ee.concat)(n,t)}catch{n=void 0,s=!1}this.func&&void 0!==n&&await this.func(n,r)}static assign(e){return new Y.B2(new Y.ck({steps:e}))}}class re extends Y.YN{static lc_name(){return"RouterRunnable"}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,"runnables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.runnables=e.runnables}async invoke(e,t){const{key:r,input:n}=e,s=this.runnables[r];if(void 0===s)throw new Error(`No runnable associated with key "${r}".`);return s.invoke(n,(0,Q.ZI)(t))}async batch(e,t,r){const n=e.map((e=>e.key)),s=e.map((e=>e.input));if(void 0!==n.find((e=>void 0===this.runnables[e])))throw new Error("One or more keys do not have a corresponding runnable.");const a=n.map((e=>this.runnables[e])),i=this._getOptionsList(t??{},e.length),o=i[0]?.maxConcurrency??r?.maxConcurrency,c=o&&o>0?o:e.length,l=[];for(let e=0;ea[t].invoke(e,i[t]))),r=await Promise.all(t);l.push(r)}return l.flat()}async stream(e,t){const{key:r,input:n}=e,s=this.runnables[r];if(void 0===s)throw new Error(`No runnable associated with key "${r}".`);return s.stream(n,t)}}class ne extends Y.YN{static lc_name(){return"RunnableBranch"}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,"default",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"branches",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");return new this({branches:e.slice(0,-1).map((([e,t])=>[(0,Y.Bp)(e),(0,Y.Bp)(t)])),default:(0,Y.Bp)(e[e.length-1])})}async _invoke(e,t,r){let n;for(let s=0;sthis._enterHistory(e,t??{}))).withConfig({runName:"loadHistory"});const r=e.historyMessagesKey??e.inputMessagesKey;r&&(t=te.assign({[r]:t}).withConfig({runName:"insertHistory"}));const n=t.pipe(e.runnable.withListeners({onEnd:(e,t)=>this._exitHistory(e,t??{})})).withConfig({runName:"RunnableWithMessageHistory"}),s=e.config??{};super({...e,config:s,bound:n}),Object.defineProperty(this,"runnable",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputMessagesKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputMessagesKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"historyMessagesKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"getMessageHistory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if("object"!=typeof e||Array.isArray(e)||(0,se.isBaseMessage)(e))t=e;else{let r;r=this.inputMessagesKey?this.inputMessagesKey:1===Object.keys(e).length?Object.keys(e)[0]:"input",t=Array.isArray(e[r])&&Array.isArray(e[r][0])?e[r][0]:e[r]}if("string"==typeof t)return[new se.HumanMessage(t)];if(Array.isArray(t))return t;if((0,se.isBaseMessage)(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.\nGot ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(Array.isArray(e)||(0,se.isBaseMessage)(e)||"string"==typeof e)t=e;else{let r;r=void 0!==this.outputMessagesKey?this.outputMessagesKey:1===Object.keys(e).length?Object.keys(e)[0]:"output",t=void 0!==e.generations?e.generations[0][0].message:e[r]}if("string"==typeof t)return[new se.AIMessage(t)];if(Array.isArray(t))return t;if((0,se.isBaseMessage)(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(t,null,2)}`)}async _enterHistory(e,t){const r=t?.configurable?.messageHistory,n=await r.getMessages();return void 0===this.historyMessagesKey?n.concat(this._getInputMessages(e)):n}async _exitHistory(e,t){const r=t.configurable?.messageHistory;let n;n=Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?e.inputs[0]:e.inputs;let s=this._getInputMessages(n);if(void 0===this.historyMessagesKey){const e=await r.getMessages();s=s.slice(e.length)}const a=e.outputs;if(!a)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);const i=this._getOutputMessages(a);await r.addMessages([...s,...i])}async _mergeConfig(...e){const t=await super._mergeConfig(...e);if(!t.configurable||!t.configurable.sessionId){const e={[this.inputMessagesKey??"input"]:"foo"},t={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\neg. chain.invoke(${JSON.stringify(e)}, ${JSON.stringify(t)})`)}const{sessionId:r}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(r),t}}Y.fJ;for(var ie=[],oe=0;oe<256;++oe)ie.push((oe+256).toString(16).slice(1));function ce(e,t=0){return(ie[e[t+0]]+ie[e[t+1]]+ie[e[t+2]]+ie[e[t+3]]+"-"+ie[e[t+4]]+ie[e[t+5]]+"-"+ie[e[t+6]]+ie[e[t+7]]+"-"+ie[e[t+8]]+ie[e[t+9]]+"-"+ie[e[t+10]]+ie[e[t+11]]+ie[e[t+12]]+ie[e[t+13]]+ie[e[t+14]]+ie[e[t+15]]).toLowerCase()}var le,ue,de,he=new Uint8Array(16);function pe(){if(!le&&!(le="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return le(he)}var me=0,fe=0;const ge=function(e,t,r){var n=t&&r||0,s=t||new Array(16),a=(e=e||{}).node,i=e.clockseq;if(e._v6||(a||(a=ue),null==i&&(i=de)),null==a||null==i){var o=e.random||(e.rng||pe)();null==a&&(a=[o[0],o[1],o[2],o[3],o[4],o[5]],ue||e._v6||(a[0]|=1,ue=a)),null==i&&(i=16383&(o[6]<<8|o[7]),void 0!==de||e._v6||(de=i))}var c=void 0!==e.msecs?e.msecs:Date.now(),l=void 0!==e.nsecs?e.nsecs:fe+1,u=c-me+(l-fe)/1e4;if(u<0&&void 0===e.clockseq&&(i=i+1&16383),(u<0||c>me)&&void 0===e.nsecs&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");me=c,fe=l,de=i;var d=(1e4*(268435455&(c+=122192928e5))+l)%4294967296;s[n++]=d>>>24&255,s[n++]=d>>>16&255,s[n++]=d>>>8&255,s[n++]=255&d;var h=c/4294967296*1e4&268435455;s[n++]=h>>>8&255,s[n++]=255&h,s[n++]=h>>>24&15|16,s[n++]=h>>>16&255,s[n++]=i>>>8|128,s[n++]=255&i;for(var p=0;p<6;++p)s[n+p]=a[p];return t||ce(s)},ye=/^(?:[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;const be=function(e){return"string"==typeof e&&ye.test(e)};const we=function(e){if(!be(e))throw TypeError("Invalid UUID");var t,r=new Uint8Array(16);return r[0]=(t=parseInt(e.slice(0,8),16))>>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r};function ve(e){var t=function(e){return Uint8Array.of((15&e[6])<<4|e[7]>>4&15,(15&e[7])<<4|(240&e[4])>>4,(15&e[4])<<4|(240&e[5])>>4,(15&e[5])<<4|(240&e[0])>>4,(15&e[0])<<4|(240&e[1])>>4,(15&e[1])<<4|(240&e[2])>>4,96|15&e[2],e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}("string"==typeof e?we(e):e);return"string"==typeof e?ce(t):t}function _e(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function ke(e){for(var t=1;t>>32-t}const Te=function(e){var t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var n=unescape(encodeURIComponent(e));e=[];for(var s=0;s>>0;w=b,b=y,y=xe(g,30)>>>0,g=f,f=k}r[0]=r[0]+f>>>0,r[1]=r[1]+g>>>0,r[2]=r[2]+y>>>0,r[3]=r[3]+b>>>0,r[4]=r[4]+w>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,255&r[0],r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,255&r[1],r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,255&r[2],r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,255&r[3],r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,255&r[4]]};var Ce=function(e,t,r){function n(e,n,s,a){var i;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],r=0;rparseInt(e,16)));return Pe(e,new Uint8Array(r))}const Ie="__error__",Me="__scheduled__",Re="__interrupt__",je="__resume__";var Ne=s(7380);var $e="object"==typeof window?window:{},Le="0123456789abcdef".split(""),Fe=[-2147483648,8388608,32768,128],De=[24,16,8,0],ze=[];function Ue(e){e?(ze[0]=ze[16]=ze[1]=ze[2]=ze[3]=ze[4]=ze[5]=ze[6]=ze[7]=ze[8]=ze[9]=ze[10]=ze[11]=ze[12]=ze[13]=ze[14]=ze[15]=0,this.blocks=ze):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}Ue.prototype.update=function(e){if(!this.finalized){var t="string"!=typeof e;t&&e.constructor===$e.ArrayBuffer&&(e=new Uint8Array(e));for(var r,n,s=0,a=e.length||0,i=this.blocks;s>2]|=e[s]<>2]|=r<>2]|=(192|r>>6)<>2]|=(128|63&r)<=57344?(i[n>>2]|=(224|r>>12)<>2]|=(128|r>>6&63)<>2]|=(128|63&r)<>2]|=(240|r>>18)<>2]|=(128|r>>12&63)<>2]|=(128|r>>6&63)<>2]|=(128|63&r)<=64?(this.block=i[16],this.start=n-64,this.hash(),this.hashed=!0):this.start=n}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this}},Ue.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>2]|=Fe[3&t],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},Ue.prototype.hash=function(){var e,t,r=this.h0,n=this.h1,s=this.h2,a=this.h3,i=this.h4,o=this.blocks;for(e=16;e<80;++e)t=o[e-3]^o[e-8]^o[e-14]^o[e-16],o[e]=t<<1|t>>>31;for(e=0;e<20;e+=5)r=(t=(n=(t=(s=(t=(a=(t=(i=(t=r<<5|r>>>27)+(n&s|~n&a)+i+1518500249+o[e]|0)<<5|i>>>27)+(r&(n=n<<30|n>>>2)|~r&s)+a+1518500249+o[e+1]|0)<<5|a>>>27)+(i&(r=r<<30|r>>>2)|~i&n)+s+1518500249+o[e+2]|0)<<5|s>>>27)+(a&(i=i<<30|i>>>2)|~a&r)+n+1518500249+o[e+3]|0)<<5|n>>>27)+(s&(a=a<<30|a>>>2)|~s&i)+r+1518500249+o[e+4]|0,s=s<<30|s>>>2;for(;e<40;e+=5)r=(t=(n=(t=(s=(t=(a=(t=(i=(t=r<<5|r>>>27)+(n^s^a)+i+1859775393+o[e]|0)<<5|i>>>27)+(r^(n=n<<30|n>>>2)^s)+a+1859775393+o[e+1]|0)<<5|a>>>27)+(i^(r=r<<30|r>>>2)^n)+s+1859775393+o[e+2]|0)<<5|s>>>27)+(a^(i=i<<30|i>>>2)^r)+n+1859775393+o[e+3]|0)<<5|n>>>27)+(s^(a=a<<30|a>>>2)^i)+r+1859775393+o[e+4]|0,s=s<<30|s>>>2;for(;e<60;e+=5)r=(t=(n=(t=(s=(t=(a=(t=(i=(t=r<<5|r>>>27)+(n&s|n&a|s&a)+i-1894007588+o[e]|0)<<5|i>>>27)+(r&(n=n<<30|n>>>2)|r&s|n&s)+a-1894007588+o[e+1]|0)<<5|a>>>27)+(i&(r=r<<30|r>>>2)|i&n|r&n)+s-1894007588+o[e+2]|0)<<5|s>>>27)+(a&(i=i<<30|i>>>2)|a&r|i&r)+n-1894007588+o[e+3]|0)<<5|n>>>27)+(s&(a=a<<30|a>>>2)|s&i|a&i)+r-1894007588+o[e+4]|0,s=s<<30|s>>>2;for(;e<80;e+=5)r=(t=(n=(t=(s=(t=(a=(t=(i=(t=r<<5|r>>>27)+(n^s^a)+i-899497514+o[e]|0)<<5|i>>>27)+(r^(n=n<<30|n>>>2)^s)+a-899497514+o[e+1]|0)<<5|a>>>27)+(i^(r=r<<30|r>>>2)^n)+s-899497514+o[e+2]|0)<<5|s>>>27)+(a^(i=i<<30|i>>>2)^r)+n-899497514+o[e+3]|0)<<5|n>>>27)+(s^(a=a<<30|a>>>2)^i)+r-899497514+o[e+4]|0,s=s<<30|s>>>2;this.h0=this.h0+r|0,this.h1=this.h1+n|0,this.h2=this.h2+s|0,this.h3=this.h3+a|0,this.h4=this.h4+i|0},Ue.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,s=this.h4;return Le[e>>28&15]+Le[e>>24&15]+Le[e>>20&15]+Le[e>>16&15]+Le[e>>12&15]+Le[e>>8&15]+Le[e>>4&15]+Le[15&e]+Le[t>>28&15]+Le[t>>24&15]+Le[t>>20&15]+Le[t>>16&15]+Le[t>>12&15]+Le[t>>8&15]+Le[t>>4&15]+Le[15&t]+Le[r>>28&15]+Le[r>>24&15]+Le[r>>20&15]+Le[r>>16&15]+Le[r>>12&15]+Le[r>>8&15]+Le[r>>4&15]+Le[15&r]+Le[n>>28&15]+Le[n>>24&15]+Le[n>>20&15]+Le[n>>16&15]+Le[n>>12&15]+Le[n>>8&15]+Le[n>>4&15]+Le[15&n]+Le[s>>28&15]+Le[s>>24&15]+Le[s>>20&15]+Le[s>>16&15]+Le[s>>12&15]+Le[s>>8&15]+Le[s>>4&15]+Le[15&s]},Ue.prototype.toString=Ue.prototype.hex,Ue.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,s=this.h4;return[e>>24&255,e>>16&255,e>>8&255,255&e,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24&255,r>>16&255,r>>8&255,255&r,n>>24&255,n>>16&255,n>>8&255,255&n,s>>24&255,s>>16&255,s>>8&255,255&s]},Ue.prototype.array=Ue.prototype.digest,Ue.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(20),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),e};const Be=e=>new Ue(!0).update(e).hex();var qe=s(6362);const Ke=(...e)=>Be(e.join("_"));function We(e){return void 0!==e.message?{text:e.text,message:(0,qe.Pz)(e.message)}:{text:e.text}}function He(e){const t={text:e.text};return void 0!==e.message&&(t.message=e.message.toDict()),t}class Ve{}const Ge=new Map;class Je extends Ve{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(Ke(e,t))??null)}async update(e,t,r){this.cache.set(Ke(e,t),r)}static global(){return new Je(Ge)}}var Ze=s(5960),Xe=s(5042),Ye=s(2293);class Qe extends Ne.Serializable{async addMessages(e){for(const t of e)await this.addMessage(t)}}class et extends Ne.Serializable{addUserMessage(e){return this.addMessage(new se.HumanMessage(e))}addAIChatMessage(e){return this.addMessage(new se.AIMessage(e))}addAIMessage(e){return this.addMessage(new se.AIMessage(e))}async addMessages(e){for(const t of e)await this.addMessage(t)}clear(){throw new Error("Not implemented.")}}class tt extends et{constructor(e){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","stores","message","in_memory"]}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}}class rt{constructor(e){Object.defineProperty(this,"pageContent",{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,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.pageContent=void 0!==e.pageContent?e.pageContent.toString():"",this.metadata=e.metadata??{},this.id=e.id}}class nt extends Y.YN{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","documents","transformers"]})}invoke(e,t){return this.transformDocuments(e)}}class st extends nt{async transformDocuments(e){const t=[];for(const r of e){const e=await this._transformDocument(r);t.push(e)}return t}}var at=s(9624);class it{constructor(e){Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.caller=new at.AsyncCaller(e??{})}}class ot extends Ne.Serializable{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","example_selectors","base"]})}}class ct{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}}class lt extends ct{constructor(e,t=[]){super(),Object.defineProperty(this,"defaultPrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"conditionals",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(const[t,r]of this.conditionals)if(t(e))return r;return this.defaultPrompt}}function ut(e){return"base_llm"===e._modelType()}function dt(e){return"base_chat_model"===e._modelType()}function ht(e){return e.split(/\n| /).length}class pt extends ot{constructor(e){super(e),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"getTextLength",{enumerable:!0,configurable:!0,writable:!0,value:ht}),Object.defineProperty(this,"maxLength",{enumerable:!0,configurable:!0,writable:!0,value:2048}),Object.defineProperty(this,"exampleTextLengths",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??ht}async addExample(e){this.examples.push(e);const t=await this.examplePrompt.format(e);this.exampleTextLengths.push(this.getTextLength(t))}async calculateExampleTextLengths(e,t){if(e.length>0)return e;const{examples:r,examplePrompt:n}=t;return(await Promise.all(r.map((e=>n.format(e))))).map((e=>this.getTextLength(e)))}async selectExamples(e){const t=Object.values(e).join(" ");let r=this.maxLength-this.getTextLength(t),n=0;const s=[];for(;r>0&&nr.addExample(e)))),r}}function mt(e){return Object.keys(e).sort().map((t=>e[t]))}class ft extends ot{constructor(e){if(super(e),Object.defineProperty(this,"vectorStoreRetriever",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleKeys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputKeys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.exampleKeys=e.exampleKeys,this.inputKeys=e.inputKeys,void 0!==e.vectorStore)this.vectorStoreRetriever=e.vectorStore.asRetriever({k:e.k??4,filter:e.filter});else{if(!e.vectorStoreRetriever)throw new Error('You must specify one of "vectorStore" and "vectorStoreRetriever".');this.vectorStoreRetriever=e.vectorStoreRetriever}}async addExample(e){const t=mt((this.inputKeys??Object.keys(e)).reduce(((t,r)=>({...t,[r]:e[r]})),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new rt({pageContent:t,metadata:e})])}async selectExamples(e){const t=mt((this.inputKeys??Object.keys(e)).reduce(((t,r)=>({...t,[r]:e[r]})),{})).join(" "),r=(await this.vectorStoreRetriever.invoke(t)).map((e=>e.metadata));return this.exampleKeys?r.map((e=>this.exampleKeys.reduce(((t,r)=>({...t,[r]:e[r]})),{}))):r}static async fromExamples(e,t,r,n={}){const s=n.inputKeys??null,a=e.map((e=>mt(s?s.reduce(((t,r)=>({...t,[r]:e[r]})),{}):e).join(" "))),i=await r.fromTexts(a,e,t,n);return new ft({vectorStore:i,k:n.k??4,exampleKeys:n.exampleKeys,inputKeys:n.inputKeys})}}var gt=s(5311),yt=s(7526),bt=Object.defineProperty;function wt(e,t){return 1===e.length?[t.get(e.join(","))]:function(e,t){let r=Array.from({length:e.length},((e,t)=>({start:t,end:t+1})));for(;r.length>1;){let n=null;for(let s=0;st.get(e.slice(r.start,r.end).join(",")))).filter((e=>null!=e))}var vt,_t,kt=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,t){this.patStr=e.pat_str;const r=e.bpe_ranks.split("\n").filter(Boolean).reduce(((e,t)=>{const[r,n,...s]=t.split(" "),a=Number.parseInt(n,10);return s.forEach(((t,r)=>e[t]=a+r)),e}),{});for(const[e,t]of Object.entries(r)){const r=yt.toByteArray(e);this.rankMap.set(r.join(","),t),this.textMap.set(t,r)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce(((e,[t,r])=>(e[r]=this.textEncoder.encode(t),e)),{})}encode(e,t=[],r="all"){const n=new RegExp(this.patStr,"ug"),s=kt.specialTokenRegex(Object.keys(this.specialTokens)),a=[],i=new Set("all"===t?Object.keys(this.specialTokens):t),o=new Set("all"===r?Object.keys(this.specialTokens).filter((e=>!i.has(e))):r);if(o.size>0){const t=kt.specialTokenRegex([...o]),r=e.match(t);if(null!=r)throw new Error(`The text contains a special token that is not allowed: ${r[0]}`)}let c=0;for(;;){let t=null,r=c;for(;s.lastIndex=r,t=s.exec(e),null!=t&&!i.has(t[0]);)r=t.index+1;const o=t?.index??e.length;for(const t of e.substring(c,o).matchAll(n)){const e=this.textEncoder.encode(t[0]),r=this.rankMap.get(e.join(","));null==r?a.push(...wt(e,this.rankMap)):a.push(r)}if(null==t)break;let l=this.specialTokens[t[0]];a.push(l),c=t.index+t[0].length}return a}decode(e){const t=[];let r=0;for(let n=0;nnew RegExp(e.map((e=>function(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}(e))).join("|"),"g"),((e,t,r)=>{t in e?bt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r})(St,"symbol"!=typeof(vt="specialTokenRegex")?vt+"":vt,_t);const Et={},xt=new at.AsyncCaller({});async function Tt(e){return e in Et||(Et[e]=xt.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then((e=>e.json())).then((e=>new St(e))).catch((t=>{throw delete Et[e],t}))),await Et[e]}async function Ct(e){return Tt(function(e){switch(e){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":return"o200k_base";default:throw new Error("Unknown model")}}(e))}const Pt=e=>e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,Ot=e=>"text-embedding-ada-002"===e?8191:2046,At=e=>{switch(Pt(e)){case"gpt-3.5-turbo-16k":return 16384;case"gpt-3.5-turbo":return 4096;case"gpt-4-32k":return 32768;case"gpt-4":return 8192;case"text-davinci-003":default:return 4097;case"text-curie-001":case"text-babbage-001":case"text-ada-001":case"code-cushman-001":return 2048;case"code-davinci-002":return 8e3}};function It(e){return!("object"!=typeof e||!e)&&!!("type"in e&&"function"===e.type&&"function"in e&&"object"==typeof e.function&&e.function&&"name"in e.function&&"parameters"in e.function)}const Mt=async({prompt:e,modelName:t})=>{let r;try{r=(await Ct(Pt(t))).encode(e).length}catch(t){console.warn("Failed to calculate number of tokens, falling back to approximate count"),r=Math.ceil(e.length/4)}return At(t)-r};class Rt extends Y.YN{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??!1,this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}}class jt extends Rt{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}constructor({callbacks:e,callbackManager:t,...r}){const{cache:n,...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}),this.cache="object"==typeof n?n:n?Je.global():void 0,this.caller=new at.AsyncCaller(r??{})}async getNumTokens(e){if("string"!=typeof e)return 0;let t=Math.ceil(e.length/4);if(!this._encoding)try{this._encoding=await Ct("modelName"in this?Pt(this.modelName):"gpt2")}catch(e){console.warn("Failed to calculate number of tokens, falling back to approximate count",e)}if(this._encoding)try{t=this._encoding.encode(e).length}catch(e){console.warn("Failed to calculate number of tokens, falling back to approximate count",e)}return t}static _convertInputToPromptValue(e){return"string"==typeof e?new gt.StringPromptValue(e):Array.isArray(e)?new gt.ChatPromptValue(e.map(qe.K0)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){const r={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()},n=Object.entries(r).filter((([e,t])=>void 0!==t)),s=n.map((([e,t])=>`${e}:${JSON.stringify(t)}`)).sort().join(",");return s}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}}var Nt=s(2366),$t=s(8028);function Lt(e){if(!e)return!1;if("object"!=typeof e)return!1;if(Array.isArray(e))return!1;const t=e;if(t._def)return!0;return!!Object.values(M.z.ZodFirstPartyTypeKind).includes(t.constructor?.name??"NOT_INCLUDED")||"function"==typeof t.parse&&"function"==typeof t.parseAsync&&"function"==typeof t.safeParse&&"function"==typeof t.safeParseAsync}function Ft(){const e=new TextEncoder;return new TransformStream({transform(t,r){r.enqueue(e.encode("string"==typeof t.content?t.content:JSON.stringify(t.content)))}})}function Dt(e){const t=[];for(const r of e){let e=r;if(Array.isArray(r.content))for(let t=0;tt?.handleLLMError(e)))),e}await Promise.all((c??[]).map((e=>e?.handleLLMEnd({generations:[[l]],llmOutput:u}))))}}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,n){const s=e.map((e=>e.map(se.coerceMessageLikeToMessage)));let a;if(void 0!==n&&n.length===s.length)a=n;else{const e={...r.metadata,...this.getLsParams(t)},n=await Xe.CallbackManager.configure(r.callbacks,this.callbacks,r.tags,this.tags,e,this.metadata,{verbose:this.verbose}),i={options:t,invocation_params:this?.invocationParams(t),batch_size:1};a=await(n?.handleChatModelStart(this.toJSON(),s.map(Dt),r.runId,void 0,i,void 0,void 0,r.runName))}const i=[],o=[];if(!!a?.[0].handlers.find(Ze.callbackHandlerPrefersStreaming)&&!this.disableStreaming&&1===s.length&&this._streamResponseChunks!==zt.prototype._streamResponseChunks)try{const e=await this._streamResponseChunks(s[0],t,a?.[0]);let r,n;for await(const t of e){if(null==t.message.id){const e=a?.at(0)?.runId;null!=e&&t.message._updateId(`run-${e}`)}r=void 0===r?t:(0,ee.concat)(r,t),(0,se.isAIMessageChunk)(t.message)&&void 0!==t.message.usage_metadata&&(n={tokenUsage:{promptTokens:t.message.usage_metadata.input_tokens,completionTokens:t.message.usage_metadata.output_tokens,totalTokens:t.message.usage_metadata.total_tokens}})}if(void 0===r)throw new Error("Received empty response from chat model call.");i.push([r]),await(a?.[0].handleLLMEnd({generations:i,llmOutput:n}))}catch(e){throw await(a?.[0].handleLLMError(e)),e}else{const e=await Promise.allSettled(s.map(((e,r)=>this._generate(e,{...t,promptIndex:r},a?.[r]))));await Promise.all(e.map((async(e,t)=>{if("fulfilled"===e.status){const r=e.value;for(const e of r.generations){if(null==e.message.id){const t=a?.at(0)?.runId;null!=t&&e.message._updateId(`run-${t}`)}e.message.response_metadata={...e.generationInfo,...e.message.response_metadata}}return 1===r.generations.length&&(r.generations[0].message.response_metadata={...r.llmOutput,...r.generations[0].message.response_metadata}),i[t]=r.generations,o[t]=r.llmOutput,a?.[t]?.handleLLMEnd({generations:[r.generations],llmOutput:r.llmOutput})}return await(a?.[t]?.handleLLMError(e.reason)),Promise.reject(e.reason)})))}const c={generations:i,llmOutput:o.length?this._combineLLMOutput?.(...o):void 0};return Object.defineProperty(c,$t.RUN_KEY,{value:a?{runIds:a?.map((e=>e.runId))}:void 0,configurable:!0}),c}async _generateCached({messages:e,cache:t,llmStringKey:r,parsedOptions:n,handledOptions:s}){const a=e.map((e=>e.map(se.coerceMessageLikeToMessage))),i={...s.metadata,...this.getLsParams(n)},o=await Xe.CallbackManager.configure(s.callbacks,this.callbacks,s.tags,this.tags,i,this.metadata,{verbose:this.verbose}),c={options:n,invocation_params:this?.invocationParams(n),batch_size:1},l=await(o?.handleChatModelStart(this.toJSON(),a.map(Dt),s.runId,void 0,c,void 0,void 0,s.runName)),u=[],d=(await Promise.allSettled(a.map((async(e,n)=>{const s=zt._convertInputToPromptValue(e).toString(),a=await t.lookup(s,r);return null==a&&u.push(n),a})))).map(((e,t)=>({result:e,runManager:l?.[t]}))).filter((({result:e})=>"fulfilled"===e.status&&null!=e.value||"rejected"===e.status)),h=[];await Promise.all(d.map((async({result:e,runManager:t},r)=>{if("fulfilled"===e.status){const n=e.value;return h[r]=n.map((e=>("message"in e&&(0,se.isBaseMessage)(e.message)&&(0,se.isAIMessage)(e.message)&&(e.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0}),e.generationInfo={...e.generationInfo,tokenUsage:{}},e))),n.length&&await(t?.handleLLMNewToken(n[0].text)),t?.handleLLMEnd({generations:[n]},void 0,void 0,void 0,{cached:!0})}return await(t?.handleLLMError(e.reason,void 0,void 0,void 0,{cached:!0})),Promise.reject(e.reason)})));const p={generations:h,missingPromptIndices:u,startedRunManagers:l};return Object.defineProperty(p,$t.RUN_KEY,{value:l?{runIds:l?.map((e=>e.runId))}:void 0,configurable:!0}),p}async generate(e,t,r){let n;n=Array.isArray(t)?{stop:t}:t;const s=e.map((e=>e.map(se.coerceMessageLikeToMessage))),[a,i]=this._separateRunnableConfigFromCallOptionsCompat(n);if(a.callbacks=a.callbacks??r,!this.cache)return this._generateUncached(s,i,a);const{cache:o}=this,c=this._getSerializedCacheKeyParametersForCall(i),{generations:l,missingPromptIndices:u,startedRunManagers:d}=await this._generateCached({messages:s,cache:o,llmStringKey:c,parsedOptions:i,handledOptions:a});let h={};if(u.length>0){const e=await this._generateUncached(u.map((e=>s[e])),i,a,void 0!==d?u.map((e=>d?.[e])):void 0);await Promise.all(e.generations.map((async(e,t)=>{const r=u[t];l[r]=e;const n=zt._convertInputToPromptValue(s[r]).toString();return o.update(n,c,e)}))),h=e.llmOutput??{}}return{generations:l,llmOutput:h}}invocationParams(e){return{}}_modelType(){return"base_chat_model"}serialize(){return{...this.invocationParams(),_type:this._llmType(),_model:this._modelType()}}async generatePrompt(e,t,r){const n=e.map((e=>e.toChatMessages()));return this.generate(n,t,r)}async call(e,t,r){return(await this.generate([e.map(se.coerceMessageLikeToMessage)],t,r)).generations[0][0].message}async callPrompt(e,t,r){const n=e.toChatMessages();return this.call(n,t,r)}async predictMessages(e,t,r){return this.call(e,t,r)}async predict(e,t,r){const n=new se.HumanMessage(e),s=await this.call([n],t,r);if("string"!=typeof s.content)throw new Error("Cannot use predict when output is not a string.");return s.content}withStructuredOutput(e,t){if("function"!=typeof this.bindTools)throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(t?.strict)throw new Error('"strict" mode is not supported for this model by default.');const r=e,n=t?.name,s=r.description??"A function available to call.",a=t?.method,i=t?.includeRaw;if("jsonMode"===a)throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let o,c=n??"extract";Lt(r)?o=[{type:"function",function:{name:c,description:s,parameters:(0,Nt.Ik)(r)}}]:("name"in r&&(c=r.name),o=[{type:"function",function:{name:c,description:s,parameters:r}}]);const l=this.bindTools(o),u=Y.jY.from((e=>{if(!e.tool_calls||0===e.tool_calls.length)throw new Error("No tool calls found in the response.");const t=e.tool_calls.find((e=>e.name===c));if(!t)throw new Error(`No tool call found with name ${c}.`);return t.args}));if(!i)return l.pipe(u).withConfig({runName:"StructuredOutput"});const d=te.assign({parsed:(e,t)=>u.invoke(e.raw,t)}),h=te.assign({parsed:()=>null}),p=d.withFallbacks({fallbacks:[h]});return Y.zZ.from([{raw:l},p]).withConfig({runName:"StructuredOutputRunnable"})}}class Ut extends zt{async _generate(e,t,r){const n=await this._call(e,t,r),s=new se.AIMessage(n);if("string"!=typeof s.content)throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:s.content,message:s}]}}}class Bt extends jt{constructor({concurrency:e,...t}){super(e?{maxConcurrency:e,...t}:t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","llms",this._llmType()]})}async invoke(e,t){const r=Bt._convertInputToPromptValue(e);return(await this.generatePrompt([r],t,t?.callbacks)).generations[0][0].text}async*_streamResponseChunks(e,t,r){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(e){const[t,r]=super._separateRunnableConfigFromCallOptions(e);return r.signal=t.signal,[t,r]}async*_streamIterator(e,t){if(this._streamResponseChunks===Bt.prototype._streamResponseChunks)yield this.invoke(e,t);else{const r=Bt._convertInputToPromptValue(e),[n,s]=this._separateRunnableConfigFromCallOptionsCompat(t),a=await Xe.CallbackManager.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}),i={options:s,invocation_params:this?.invocationParams(s),batch_size:1},o=await(a?.handleLLMStart(this.toJSON(),[r.toString()],n.runId,void 0,i,void 0,void 0,n.runName));let c=new $t.GenerationChunk({text:""});try{for await(const e of this._streamResponseChunks(r.toString(),s,o?.[0]))c=c?c.concat(e):e,"string"==typeof e.text&&(yield e.text)}catch(e){throw await Promise.all((o??[]).map((t=>t?.handleLLMError(e)))),e}await Promise.all((o??[]).map((e=>e?.handleLLMEnd({generations:[[c]]}))))}}async generatePrompt(e,t,r){const n=e.map((e=>e.toString()));return this.generate(n,t,r)}invocationParams(e){return{}}_flattenLLMResult(e){const t=[];for(let r=0;rt?.handleLLMError(e)))),e}const r=this._flattenLLMResult(a);await Promise.all((s??[]).map(((e,t)=>e?.handleLLMEnd(r[t]))))}const i=s?.map((e=>e.runId))||void 0;return Object.defineProperty(a,$t.RUN_KEY,{value:i?{runIds:i}:void 0,configurable:!0}),a}async _generateCached({prompts:e,cache:t,llmStringKey:r,parsedOptions:n,handledOptions:s,runId:a}){const i=await Xe.CallbackManager.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),o={options:n,invocation_params:this?.invocationParams(n),batch_size:e.length},c=await(i?.handleLLMStart(this.toJSON(),e,a,void 0,o,void 0,void 0,s?.runName)),l=[],u=(await Promise.allSettled(e.map((async(e,n)=>{const s=await t.lookup(e,r);return null==s&&l.push(n),s})))).map(((e,t)=>({result:e,runManager:c?.[t]}))).filter((({result:e})=>"fulfilled"===e.status&&null!=e.value||"rejected"===e.status)),d=[];await Promise.all(u.map((async({result:e,runManager:t},r)=>{if("fulfilled"===e.status){const n=e.value;return d[r]=n.map((e=>(e.generationInfo={...e.generationInfo,tokenUsage:{}},e))),n.length&&await(t?.handleLLMNewToken(n[0].text)),t?.handleLLMEnd({generations:[n]},void 0,void 0,void 0,{cached:!0})}return await(t?.handleLLMError(e.reason,void 0,void 0,void 0,{cached:!0})),Promise.reject(e.reason)})));const h={generations:d,missingPromptIndices:l,startedRunManagers:c};return Object.defineProperty(h,$t.RUN_KEY,{value:c?{runIds:c?.map((e=>e.runId))}:void 0,configurable:!0}),h}async generate(e,t,r){if(!Array.isArray(e))throw new Error("Argument 'prompts' is expected to be a string[]");let n;n=Array.isArray(t)?{stop:t}:t;const[s,a]=this._separateRunnableConfigFromCallOptionsCompat(n);if(s.callbacks=s.callbacks??r,!this.cache)return this._generateUncached(e,a,s);const{cache:i}=this,o=this._getSerializedCacheKeyParametersForCall(a),{generations:c,missingPromptIndices:l,startedRunManagers:u}=await this._generateCached({prompts:e,cache:i,llmStringKey:o,parsedOptions:a,handledOptions:s,runId:s.runId});let d={};if(l.length>0){const t=await this._generateUncached(l.map((t=>e[t])),a,s,void 0!==u?l.map((e=>u?.[e])):void 0);await Promise.all(t.generations.map((async(t,r)=>{const n=l[r];return c[n]=t,i.update(e[n],o,t)}))),d=t.llmOutput??{}}return{generations:c,llmOutput:d}}async call(e,t,r){const{generations:n}=await this.generate([e],t,r);return n[0][0].text}async predict(e,t,r){return this.call(e,t,r)}async predictMessages(e,t,r){const n=(0,se.getBufferString)(e),s=await this.call(n,t,r);return new se.AIMessage(s)}_identifyingParams(){return{}}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}_modelType(){return"base_llm"}}class qt extends Bt{async _generate(e,t,r){return{generations:await Promise.all(e.map(((e,n)=>this._call(e,{...t,promptIndex:n},r).then((e=>[{text:e}])))))}}}class Kt{}const Wt=(e,t)=>{if(void 0!==t)return e[t];const r=Object.keys(e);return 1===r.length?e[r[0]]:void 0},Ht=(e,t)=>{const r=Wt(e,t);if(!r){const t=Object.keys(e);throw new Error(`input values have ${t.length} keys, you must specify an input key or pass only 1 key as input`)}return r},Vt=(e,t)=>{const r=Wt(e,t);if(!r&&""!==r){const t=Object.keys(e);throw new Error(`output values have ${t.length} keys, you must specify an output key or pass only 1 key as output`)}return r};function Gt(e,t){const r=Object.keys(e).filter((e=>!t.includes(e)&&"stop"!==e));if(1!==r.length)throw new Error(`One input key expected, but got ${r.length}`);return r[0]}var Jt=s(1368);class Zt extends Y.YN{parseResultWithPrompt(e,t,r){return this.parseResult(e,r)}_baseMessageToString(e){return"string"==typeof e.content?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return"string"==typeof e?this._callWithConfig((async(e,t)=>this.parseResult([{text:e}],t?.callbacks)),e,{...t,runType:"parser"}):this._callWithConfig((async(e,t)=>this.parseResult([{message:e,text:this._baseMessageToString(e)}],t?.callbacks)),e,{...t,runType:"parser"})}}class Xt extends Zt{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 Yt extends Error{constructor(e,t,r,n=!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=n,n&&(void 0===r||void 0===t))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");(0,Jt.Y)(this,"OUTPUT_PARSING_FAILURE")}}function Qt(e,t){const r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;const r=e.length;if(r!==t.length)return!1;for(let n=0;n1?t[a.href]=e:(a.hash="",""===n?r=a:ar(e,t,r))}}else if(!0!==e&&!1!==e)return t;const s=r.href+(n?"#"+n:"");if(void 0!==t[s])throw new Error(`Duplicate schema URI "${s}".`);if(t[s]=e,!0===e||!1===e)return t;if(void 0===e.__absolute_uri__&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:s}),e.$ref&&void 0===e.__absolute_ref__){const t=new URL(e.$ref,r.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&void 0===e.__absolute_recursive_ref__){const t=new URL(e.$recursiveRef,r.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){t[new URL("#"+e.$anchor,r.href).href]=e}for(let s in e){if(nr[s])continue;const a=`${n}/${er(s)}`,i=e[s];if(Array.isArray(i)){if(tr[s]){const e=i.length;for(let n=0;ne.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),uri:function(e){return mr.test(e)&&fr.test(e)},"uri-reference":lr(/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i),"uri-template":lr(/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i),url:lr(/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu),email:e=>{if('"'===e[0])return!1;const[t,r,...n]=e.split("@");return!(!t||!r||0!==n.length||t.length>64||r.length>253)&&("."!==t[0]&&!t.endsWith(".")&&!t.includes("..")&&(!(!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t))&&r.split(".").every((e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e)))))},hostname:lr(/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i),ipv4:lr(/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/),ipv6:lr(/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i),regex:function(e){if(gr.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(e){return!1}},uuid:lr(/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i),"json-pointer":lr(/^(?:\/(?:[^~/]|~0|~1)*)*$/),"json-pointer-uri-fragment":lr(/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i),"relative-json-pointer":lr(/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/)};function dr(e){const t=e.match(ir);if(!t)return!1;const r=+t[1],n=+t[2],s=+t[3];return n>=1&&n<=12&&s>=1&&s<=(2==n&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(r)?29:or[n])}function hr(e,t){const r=t.match(cr);if(!r)return!1;const n=+r[1],s=+r[2],a=+r[3],i=!!r[5];return(n<=23&&s<=59&&a<=59||23==n&&59==s&&60==a)&&(!e||i)}const pr=/t|\s/i;const mr=/\/|:/,fr=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;const gr=/[^\\]\\Z/;var yr;function br(e,t,r="2019-09",n=ar(t),s=!0,a=null,i="#",o="#",c=Object.create(null)){if(!0===t)return{valid:!0,errors:[]};if(!1===t)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};const l=typeof e;let u;switch(l){case"boolean":case"number":case"string":u=l;break;case"object":u=null===e?"null":Array.isArray(e)?"array":"object";break;default:throw new Error(`Instances of "${l}" type are not supported.`)}const{$ref:d,$recursiveRef:h,$recursiveAnchor:p,type:m,const:f,enum:g,required:y,not:b,anyOf:w,allOf:v,oneOf:_,if:k,then:S,else:E,format:x,properties:T,patternProperties:C,additionalProperties:P,unevaluatedProperties:O,minProperties:A,maxProperties:I,propertyNames:M,dependentRequired:R,dependentSchemas:j,dependencies:N,prefixItems:$,items:L,additionalItems:F,unevaluatedItems:D,contains:z,minContains:U,maxContains:B,minItems:q,maxItems:K,uniqueItems:W,minimum:H,maximum:V,exclusiveMinimum:G,exclusiveMaximum:J,multipleOf:Z,minLength:X,maxLength:Y,pattern:Q,__absolute_ref__:ee,__absolute_recursive_ref__:te}=t,re=[];if(!0===p&&null===a&&(a=t),"#"===h){const l=null===a?n[te]:a,u=`${o}/$recursiveRef`,d=br(e,null===a?t:a,r,n,s,l,i,u,c);d.valid||re.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:u,error:"A subschema had errors."},...d.errors)}if(void 0!==d){const t=n[ee||d];if(void 0===t){let e=`Unresolved $ref "${d}".`;throw ee&&ee!==d&&(e+=` Absolute URI "${ee}".`),e+=`\nKnown schemas:\n- ${Object.keys(n).join("\n- ")}`,new Error(e)}const l=`${o}/$ref`,u=br(e,t,r,n,s,a,i,l,c);if(u.valid||re.push({instanceLocation:i,keyword:"$ref",keywordLocation:l,error:"A subschema had errors."},...u.errors),"4"===r||"7"===r)return{valid:0===re.length,errors:re}}if(Array.isArray(m)){let t=m.length,r=!1;for(let n=0;nQt(e,t)))||re.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some((t=>e===t))||re.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),void 0!==b){const t=`${o}/not`;br(e,b,r,n,s,a,i,t).valid&&re.push({instanceLocation:i,keyword:"not",keywordLocation:t,error:'Instance matched "not" schema.'})}let ne=[];if(void 0!==w){const t=`${o}/anyOf`,l=re.length;let u=!1;for(let o=0;o{const u=Object.create(c),d=br(e,o,r,n,s,!0===p?a:null,i,`${t}/${l}`,u);return re.push(...d.errors),d.valid&&ne.push(u),d.valid})).length;1===u?re.length=l:re.splice(l,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if("object"!==u&&"array"!==u||Object.assign(c,...ne),void 0!==k){const t=`${o}/if`;if(br(e,k,r,n,s,a,i,t,c).valid){if(void 0!==S){const l=br(e,S,r,n,s,a,i,`${o}/then`,c);l.valid||re.push({instanceLocation:i,keyword:"if",keywordLocation:t,error:'Instance does not match "then" schema.'},...l.errors)}}else if(void 0!==E){const l=br(e,E,r,n,s,a,i,`${o}/else`,c);l.valid||re.push({instanceLocation:i,keyword:"if",keywordLocation:t,error:'Instance does not match "else" schema.'},...l.errors)}}if("object"===u){if(void 0!==y)for(const t of y)t in e||re.push({instanceLocation:i,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${t}".`});const t=Object.keys(e);if(void 0!==A&&t.lengthI&&re.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${I} properties.`}),void 0!==M){const t=`${o}/propertyNames`;for(const o in e){const e=`${i}/${er(o)}`,c=br(o,M,r,n,s,a,e,t);c.valid||re.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:t,error:`Property name "${o}" does not match schema.`},...c.errors)}}if(void 0!==R){const t=`${o}/dependantRequired`;for(const r in R)if(r in e){const n=R[r];for(const s of n)s in e||re.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:t,error:`Instance has "${r}" but does not have "${s}".`})}}if(void 0!==j)for(const t in j){const l=`${o}/dependentSchemas`;if(t in e){const o=br(e,j[t],r,n,s,a,i,`${l}/${er(t)}`,c);o.valid||re.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...o.errors)}}if(void 0!==N){const t=`${o}/dependencies`;for(const o in N)if(o in e){const c=N[o];if(Array.isArray(c))for(const r of c)r in e||re.push({instanceLocation:i,keyword:"dependencies",keywordLocation:t,error:`Instance has "${o}" but does not have "${r}".`});else{const l=br(e,c,r,n,s,a,i,`${t}/${er(o)}`);l.valid||re.push({instanceLocation:i,keyword:"dependencies",keywordLocation:t,error:`Instance has "${o}" but does not match dependant schema.`},...l.errors)}}}const l=Object.create(null);let u=!1;if(void 0!==T){const t=`${o}/properties`;for(const o in T){if(!(o in e))continue;const d=`${i}/${er(o)}`,h=br(e[o],T[o],r,n,s,a,d,`${t}/${er(o)}`);if(h.valid)c[o]=l[o]=!0;else if(u=s,re.push({instanceLocation:i,keyword:"properties",keywordLocation:t,error:`Property "${o}" does not match schema.`},...h.errors),u)break}}if(!u&&void 0!==C){const t=`${o}/patternProperties`;for(const o in C){const d=new RegExp(o,"u"),h=C[o];for(const p in e){if(!d.test(p))continue;const m=`${i}/${er(p)}`,f=br(e[p],h,r,n,s,a,m,`${t}/${er(o)}`);f.valid?c[p]=l[p]=!0:(u=s,re.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:t,error:`Property "${p}" matches pattern "${o}" but does not match associated schema.`},...f.errors))}}}if(u||void 0===P){if(!u&&void 0!==O){const t=`${o}/unevaluatedProperties`;for(const o in e)if(!c[o]){const l=`${i}/${er(o)}`,u=br(e[o],O,r,n,s,a,l,t);u.valid?c[o]=!0:re.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:t,error:`Property "${o}" does not match unevaluated properties schema.`},...u.errors)}}}else{const t=`${o}/additionalProperties`;for(const o in e){if(l[o])continue;const d=`${i}/${er(o)}`,h=br(e[o],P,r,n,s,a,d,t);h.valid?c[o]=!0:(u=s,re.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:t,error:`Property "${o}" does not match additional properties schema.`},...h.errors))}}}else if("array"===u){void 0!==K&&e.length>K&&re.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${e.length} > ${K}).`}),void 0!==q&&e.length=(U||0)&&(re.length=u),void 0===U&&void 0===B&&0===d?re.splice(u,0,{instanceLocation:i,keyword:"contains",keywordLocation:l,error:"Array does not contain item matching schema."}):void 0!==U&&dB&&re.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${B} items matching schema. ${d} items were found.`})}if(!u&&void 0!==D){const u=`${o}/unevaluatedItems`;for(;l=V||e>V)&&re.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${J?"or equal to ":""} ${V}.`})):(void 0!==H&&eV&&re.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${V}.`}),void 0!==G&&e<=G&&re.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${e} is less than ${G}.`}),void 0!==J&&e>=J&&re.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${e} is greater than or equal to ${J}.`})),void 0!==Z){const t=e%Z;Math.abs(0-t)>=1.1920929e-7&&Math.abs(Z-t)>=1.1920929e-7&&re.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${e} is not a multiple of ${Z}.`})}}else if("string"===u){const t=void 0===X&&void 0===Y?0:function(e){let t,r=0,n=e.length,s=0;for(;s=55296&&t<=56319&&sY&&re.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${t} > ${Y}).`}),void 0===Q||new RegExp(Q,"u").test(e)||re.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),void 0!==x&&ur[x]&&!ur[x](e)&&re.push({instanceLocation:i,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${x}".`})}return{valid:0===re.length,errors:re}}!function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"}(yr||(yr={}));class wr{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=ar(e)}validate(e){return br(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),ar(e,this.lookup)}}var vr=s(3490);class _r extends Xt{async*_transform(e){for await(const t of e)"string"==typeof t?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 kr extends _r{constructor(e){super(e),Object.defineProperty(this,"diff",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.diff=e?.diff??this.diff}async*_transform(e){let t,r;for await(const n of e){if("string"!=typeof n&&"string"!=typeof n.content)throw new Error("Cannot handle non-string output.");let e;if((0,vr.AJ)(n)){if("string"!=typeof n.content)throw new Error("Cannot handle non-string message output.");e=new $t.ChatGenerationChunk({message:n,text:n.content})}else if((0,vr.ny)(n)){if("string"!=typeof n.content)throw new Error("Cannot handle non-string message output.");e=new $t.ChatGenerationChunk({message:(0,qe.ih)(n),text:n.content})}else e=new $t.GenerationChunk({text:n});r=void 0===r?e:r.concat(e);const s=await this.parsePartialResult([r]);null==s||Qt(s,t)||(this.diff?yield this._diff(t,s):yield s,t=s)}}getFormatInstructions(){return""}}class Sr extends _r{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","bytes"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"textEncoder",{enumerable:!0,configurable:!0,writable:!0,value:new TextEncoder})}static lc_name(){return"BytesOutputParser"}parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}}class Er extends _r{constructor(){super(...arguments),Object.defineProperty(this,"re",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async*_transform(e){let t="";for await(const r of e)if(t+="string"==typeof r?r:r.content,this.re){const e=[...t.matchAll(this.re)];if(e.length>1){let r=0;for(const t of e.slice(0,-1))yield[t[1]],r+=(t.index??0)+t[0].length;t=t.slice(r)}}else{const e=await this.parse(t);if(e.length>1){for(const t of e.slice(0,-1))yield[t];t=e[e.length-1]}}for(const e of await this.parse(t))yield[e]}}class xr extends Er{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","list"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"CommaSeparatedListOutputParser"}async parse(e){try{return e.trim().split(",").map((e=>e.trim()))}catch(t){throw new Yt(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}}class Tr extends Er{constructor({length:e,separator:t}){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","list"]}),Object.defineProperty(this,"length",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"separator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.length=e,this.separator=t||","}async parse(e){try{const t=e.trim().split(this.separator).map((e=>e.trim()));if(void 0!==this.length&&t.length!==this.length)throw new Yt(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){if(Object.getPrototypeOf(t)===Yt.prototype)throw t;throw new Yt(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${void 0===this.length?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}}class Cr extends Er{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","list"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"re",{enumerable:!0,configurable:!0,writable:!0,value:/\d+\.\s([^\n]+)/g})}static lc_name(){return"NumberedListOutputParser"}getFormatInstructions(){return"Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz"}async parse(e){return[...e.matchAll(this.re)??[]].map((e=>e[1]))}}class Pr extends Er{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","list"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"re",{enumerable:!0,configurable:!0,writable:!0,value:/^\s*[-*]\s([^\n]+)$/gm})}static lc_name(){return"NumberedListOutputParser"}getFormatInstructions(){return"Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz"}async parse(e){return[...e.matchAll(this.re)??[]].map((e=>e[1]))}}class Or extends _r{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","string"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"StrOutputParser"}parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentComplexToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce(((e,t)=>e+this._messageContentComplexToString(t)),"")}}class Ar extends Xt{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){return new this(M.z.object(Object.fromEntries(Object.entries(e).map((([e,t])=>[e,M.z.string().describe(t)])))))}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.\n\n"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.\n\nFor example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}\nwould 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.\nThus, 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.\n\nYour 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!\n\nHere is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:\n\`\`\`json\n${JSON.stringify((0,Nt.Ik)(this.schema))}\n\`\`\`\n`}async parse(e){try{const t=(e.includes("```")?e.trim().split(/```(?:json)?/)[1]:e.trim()).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,((e,t)=>`"${t.replace(/\n/g,"\\n")}"`)).replace(/\n/g,"");return await this.schema.parseAsync(JSON.parse(t))}catch(t){throw new Yt(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}}class Ir extends Ar{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(e){const t=e?.interpolationDepth??1;if(t<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:\n\`\`\`json\n${this._schemaToInstruction((0,Nt.Ik)(this.schema)).replaceAll("{","{".repeat(t)).replaceAll("}","}".repeat(t))}\n\`\`\``}_schemaToInstruction(e,t=2){const r=e;if("type"in r){let e,n=!1;if(Array.isArray(r.type)){const t=r.type.findIndex((e=>"null"===e));-1!==t&&(n=!0,r.type.splice(t,1)),e=r.type.join(" | ")}else e=r.type;if("object"===r.type&&r.properties){const e=r.description?` // ${r.description}`:"",n=Object.entries(r.properties).map((([e,n])=>{const s=r.required?.includes(e)?"":" (optional)";return`${" ".repeat(t)}"${e}": ${this._schemaToInstruction(n,t+2)}${s}`})).join("\n");return`{\n${n}\n${" ".repeat(t-2)}}${e}`}if("array"===r.type&&r.items){const e=r.description?` // ${r.description}`:"";return`array[\n${" ".repeat(t)}${this._schemaToInstruction(r.items,t+2)}\n${" ".repeat(t-2)}] ${e}`}const s=n?" (nullable)":"";return`${e}${r.description?` // ${r.description}`:""}${s}`}if("anyOf"in r)return r.anyOf.map((e=>this._schemaToInstruction(e,t))).join(`\n${" ".repeat(t-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){return new this(M.z.object(Object.fromEntries(Object.entries(e).map((([e,t])=>[e,M.z.string().describe(t)])))))}}class Mr extends Xt{constructor({inputSchema:e}){super(...arguments),Object.defineProperty(this,"structuredInputParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.structuredInputParser=new Ir(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(t){throw new Yt(`Failed to parse. Text: "${e}". Error: ${t}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}}var Rr=s(6150),jr=s(780);class Nr extends kr{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"}_diff(e,t){if(t)return e?(0,Rr.UD)(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return(0,jr.D)(e[0].text)}async parse(e){return(0,jr.D)(e,JSON.parse)}getFormatInstructions(){return""}}const $r=function(){const e={parser:function(e,t){return new r(e,t)}};e.SAXParser=r,e.SAXStream=a,e.createStream=function(e,t){return new a(e,t)},e.MAX_BUFFER_LENGTH=65536;const t=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];function r(n,s){if(!(this instanceof r))return new r(n,s);var a=this;!function(e){for(var r=0,n=t.length;r"===a?(T(n,"onsgmldeclaration",n.sgmlDecl),n.sgmlDecl="",n.state=S.TEXT):g(a)?(n.state=S.SGML_DECL_QUOTED,n.sgmlDecl+=a):n.sgmlDecl+=a;continue;case S.SGML_DECL_QUOTED:a===n.q&&(n.state=S.SGML_DECL,n.q=""),n.sgmlDecl+=a;continue;case S.DOCTYPE:">"===a?(n.state=S.TEXT,T(n,"ondoctype",n.doctype),n.doctype=!0):(n.doctype+=a,"["===a?n.state=S.DOCTYPE_DTD:g(a)&&(n.state=S.DOCTYPE_QUOTED,n.q=a));continue;case S.DOCTYPE_QUOTED:n.doctype+=a,a===n.q&&(n.q="",n.state=S.DOCTYPE);continue;case S.DOCTYPE_DTD:n.doctype+=a,"]"===a?n.state=S.DOCTYPE:g(a)&&(n.state=S.DOCTYPE_DTD_QUOTED,n.q=a);continue;case S.DOCTYPE_DTD_QUOTED:n.doctype+=a,a===n.q&&(n.state=S.DOCTYPE_DTD,n.q="");continue;case S.COMMENT:"-"===a?n.state=S.COMMENT_ENDING:n.comment+=a;continue;case S.COMMENT_ENDING:"-"===a?(n.state=S.COMMENT_ENDED,n.comment=P(n.opt,n.comment),n.comment&&T(n,"oncomment",n.comment),n.comment=""):(n.comment+="-"+a,n.state=S.COMMENT);continue;case S.COMMENT_ENDED:">"!==a?(I(n,"Malformed comment"),n.comment+="--"+a,n.state=S.COMMENT):n.state=S.TEXT;continue;case S.CDATA:"]"===a?n.state=S.CDATA_ENDING:n.cdata+=a;continue;case S.CDATA_ENDING:"]"===a?n.state=S.CDATA_ENDING_2:(n.cdata+="]"+a,n.state=S.CDATA);continue;case S.CDATA_ENDING_2:">"===a?(n.cdata&&T(n,"oncdata",n.cdata),T(n,"onclosecdata"),n.cdata="",n.state=S.TEXT):"]"===a?n.cdata+="]":(n.cdata+="]]"+a,n.state=S.CDATA);continue;case S.PROC_INST:"?"===a?n.state=S.PROC_INST_ENDING:f(a)?n.state=S.PROC_INST_BODY:n.procInstName+=a;continue;case S.PROC_INST_BODY:if(!n.procInstBody&&f(a))continue;"?"===a?n.state=S.PROC_INST_ENDING:n.procInstBody+=a;continue;case S.PROC_INST_ENDING:">"===a?(T(n,"onprocessinginstruction",{name:n.procInstName,body:n.procInstBody}),n.procInstName=n.procInstBody="",n.state=S.TEXT):(n.procInstBody+="?"+a,n.state=S.PROC_INST_BODY);continue;case S.OPEN_TAG:b(h,a)?n.tagName+=a:(M(n),">"===a?N(n):"/"===a?n.state=S.OPEN_TAG_SLASH:(f(a)||I(n,"Invalid character in tag name"),n.state=S.ATTRIB));continue;case S.OPEN_TAG_SLASH:">"===a?(N(n,!0),$(n)):(I(n,"Forward-slash in opening tag not followed by >"),n.state=S.ATTRIB);continue;case S.ATTRIB:if(f(a))continue;">"===a?N(n):"/"===a?n.state=S.OPEN_TAG_SLASH:b(d,a)?(n.attribName=a,n.attribValue="",n.state=S.ATTRIB_NAME):I(n,"Invalid attribute name");continue;case S.ATTRIB_NAME:"="===a?n.state=S.ATTRIB_VALUE:">"===a?(I(n,"Attribute without value"),n.attribValue=n.attribName,j(n),N(n)):f(a)?n.state=S.ATTRIB_NAME_SAW_WHITE:b(h,a)?n.attribName+=a:I(n,"Invalid attribute name");continue;case S.ATTRIB_NAME_SAW_WHITE:if("="===a)n.state=S.ATTRIB_VALUE;else{if(f(a))continue;I(n,"Attribute without value"),n.tag.attributes[n.attribName]="",n.attribValue="",T(n,"onattribute",{name:n.attribName,value:""}),n.attribName="",">"===a?N(n):b(d,a)?(n.attribName=a,n.state=S.ATTRIB_NAME):(I(n,"Invalid attribute name"),n.state=S.ATTRIB)}continue;case S.ATTRIB_VALUE:if(f(a))continue;g(a)?(n.q=a,n.state=S.ATTRIB_VALUE_QUOTED):(I(n,"Unquoted attribute value"),n.state=S.ATTRIB_VALUE_UNQUOTED,n.attribValue=a);continue;case S.ATTRIB_VALUE_QUOTED:if(a!==n.q){"&"===a?n.state=S.ATTRIB_VALUE_ENTITY_Q:n.attribValue+=a;continue}j(n),n.q="",n.state=S.ATTRIB_VALUE_CLOSED;continue;case S.ATTRIB_VALUE_CLOSED:f(a)?n.state=S.ATTRIB:">"===a?N(n):"/"===a?n.state=S.OPEN_TAG_SLASH:b(d,a)?(I(n,"No whitespace between attributes"),n.attribName=a,n.attribValue="",n.state=S.ATTRIB_NAME):I(n,"Invalid attribute name");continue;case S.ATTRIB_VALUE_UNQUOTED:if(!y(a)){"&"===a?n.state=S.ATTRIB_VALUE_ENTITY_U:n.attribValue+=a;continue}j(n),">"===a?N(n):n.state=S.ATTRIB;continue;case S.CLOSE_TAG:if(n.tagName)">"===a?$(n):b(h,a)?n.tagName+=a:n.script?(n.script+=""===a?$(n):I(n,"Invalid characters in closing tag");continue;case S.TEXT_ENTITY:case S.ATTRIB_VALUE_ENTITY_Q:case S.ATTRIB_VALUE_ENTITY_U:var u,v;switch(n.state){case S.TEXT_ENTITY:u=S.TEXT,v="textNode";break;case S.ATTRIB_VALUE_ENTITY_Q:u=S.ATTRIB_VALUE_QUOTED,v="attribValue";break;case S.ATTRIB_VALUE_ENTITY_U:u=S.ATTRIB_VALUE_UNQUOTED,v="attribValue"}if(";"===a)if(n.opt.unparsedEntities){var _=L(n);n.entity="",n.state=u,n.write(_)}else n[v]+=L(n),n.entity="",n.state=u;else b(n.entity.length?m:p,a)?n.entity+=a:(I(n,"Invalid character in entity name"),n[v]+="&"+n.entity+a,n.entity="",n.state=u);continue;default:throw new Error(n,"Unknown state: "+n.state)}n.position>=n.bufferCheckPosition&&function(r){for(var n=Math.max(e.MAX_BUFFER_LENGTH,10),s=0,a=0,i=t.length;an)switch(t[a]){case"textNode":C(r);break;case"cdata":T(r,"oncdata",r.cdata),r.cdata="";break;case"script":T(r,"onscript",r.script),r.script="";break;default:O(r,"Max buffer length exceeded: "+t[a])}s=Math.max(s,o)}var c=e.MAX_BUFFER_LENGTH-s;r.bufferCheckPosition=c+r.position}(n);return n},resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){var e;C(e=this),""!==e.cdata&&(T(e,"oncdata",e.cdata),e.cdata=""),""!==e.script&&(T(e,"onscript",e.script),e.script="")}};var n=ReadableStream;n||(n=function(){});var s=e.EVENTS.filter((function(e){return"error"!==e&&"end"!==e}));function a(e,t){if(!(this instanceof a))return new a(e,t);n.apply(this),this._parser=new r(e,t),this.writable=!0,this.readable=!0;var i=this;this._parser.onend=function(){i.emit("end")},this._parser.onerror=function(e){i.emit("error",e),i._parser.error=null},this._decoder=null,s.forEach((function(e){Object.defineProperty(i,"on"+e,{get:function(){return i._parser["on"+e]},set:function(t){if(!t)return i.removeAllListeners(e),i._parser["on"+e]=t,t;i.on(e,t)},enumerable:!0,configurable:!1})}))}a.prototype=Object.create(n.prototype,{constructor:{value:a}}),a.prototype.write=function(e){return this._parser.write(e.toString()),this.emit("data",e),!0},a.prototype.end=function(e){return e&&e.length&&this.write(e),this._parser.end(),!0},a.prototype.on=function(e,t){var r=this;return r._parser["on"+e]||-1===s.indexOf(e)||(r._parser["on"+e]=function(){var t=1===arguments.length?[arguments[0]]:Array.apply(null,arguments);t.splice(0,0,e),r.emit.apply(r,t)}),n.prototype.on.call(r,e,t)};var i="[CDATA[",o="DOCTYPE",c="http://www.w3.org/XML/1998/namespace",l="http://www.w3.org/2000/xmlns/",u={xml:c,xmlns:l},d=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,h=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,p=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,m=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function f(e){return" "===e||"\n"===e||"\r"===e||"\t"===e}function g(e){return'"'===e||"'"===e}function y(e){return">"===e||f(e)}function b(e,t){return e.test(t)}function w(e,t){return!b(e,t)}var v,_,k,S=0;for(var E in e.STATE={BEGIN:S++,BEGIN_WHITESPACE:S++,TEXT:S++,TEXT_ENTITY:S++,OPEN_WAKA:S++,SGML_DECL:S++,SGML_DECL_QUOTED:S++,DOCTYPE:S++,DOCTYPE_QUOTED:S++,DOCTYPE_DTD:S++,DOCTYPE_DTD_QUOTED:S++,COMMENT_STARTING:S++,COMMENT:S++,COMMENT_ENDING:S++,COMMENT_ENDED:S++,CDATA:S++,CDATA_ENDING:S++,CDATA_ENDING_2:S++,PROC_INST:S++,PROC_INST_BODY:S++,PROC_INST_ENDING:S++,OPEN_TAG:S++,OPEN_TAG_SLASH:S++,ATTRIB:S++,ATTRIB_NAME:S++,ATTRIB_NAME_SAW_WHITE:S++,ATTRIB_VALUE:S++,ATTRIB_VALUE_QUOTED:S++,ATTRIB_VALUE_CLOSED:S++,ATTRIB_VALUE_UNQUOTED:S++,ATTRIB_VALUE_ENTITY_Q:S++,ATTRIB_VALUE_ENTITY_U:S++,CLOSE_TAG:S++,CLOSE_TAG_SAW_WHITE:S++,SCRIPT:S++,SCRIPT_ENDING:S++},e.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},e.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(e.ENTITIES).forEach((function(t){var r=e.ENTITIES[t],n="number"==typeof r?String.fromCharCode(r):r;e.ENTITIES[t]=n})),e.STATE)e.STATE[e.STATE[E]]=E;function x(e,t,r){e[t]&&e[t](r)}function T(e,t,r){e.textNode&&C(e),x(e,t,r)}function C(e){e.textNode=P(e.opt,e.textNode),e.textNode&&x(e,"ontext",e.textNode),e.textNode=""}function P(e,t){return e.trim&&(t=t.trim()),e.normalize&&(t=t.replace(/\s+/g," ")),t}function O(e,t){return C(e),e.trackPosition&&(t+="\nLine: "+e.line+"\nColumn: "+e.column+"\nChar: "+e.c),t=new Error(t),e.error=t,x(e,"onerror",t),e}function A(e){return e.sawRoot&&!e.closedRoot&&I(e,"Unclosed root tag"),e.state!==S.BEGIN&&e.state!==S.BEGIN_WHITESPACE&&e.state!==S.TEXT&&O(e,"Unexpected end"),C(e),e.c="",e.closed=!0,x(e,"onend"),r.call(e,e.strict,e.opt),e}function I(e,t){if("object"!=typeof e||!(e instanceof r))throw new Error("bad call to strictFail");e.strict&&O(e,t)}function M(e){e.strict||(e.tagName=e.tagName[e.looseCase]());var t=e.tags[e.tags.length-1]||e,r=e.tag={name:e.tagName,attributes:{}};e.opt.xmlns&&(r.ns=t.ns),e.attribList.length=0,T(e,"onopentagstart",r)}function R(e,t){var r=e.indexOf(":")<0?["",e]:e.split(":"),n=r[0],s=r[1];return t&&"xmlns"===e&&(n="xmlns",s=""),{prefix:n,local:s}}function j(e){if(e.strict||(e.attribName=e.attribName[e.looseCase]()),-1!==e.attribList.indexOf(e.attribName)||e.tag.attributes.hasOwnProperty(e.attribName))e.attribName=e.attribValue="";else{if(e.opt.xmlns){var t=R(e.attribName,!0),r=t.prefix,n=t.local;if("xmlns"===r)if("xml"===n&&e.attribValue!==c)I(e,"xml: prefix must be bound to "+c+"\nActual: "+e.attribValue);else if("xmlns"===n&&e.attribValue!==l)I(e,"xmlns: prefix must be bound to "+l+"\nActual: "+e.attribValue);else{var s=e.tag,a=e.tags[e.tags.length-1]||e;s.ns===a.ns&&(s.ns=Object.create(a.ns)),s.ns[n]=e.attribValue}e.attribList.push([e.attribName,e.attribValue])}else e.tag.attributes[e.attribName]=e.attribValue,T(e,"onattribute",{name:e.attribName,value:e.attribValue});e.attribName=e.attribValue=""}}function N(e,t){if(e.opt.xmlns){var r=e.tag,n=R(e.tagName);r.prefix=n.prefix,r.local=n.local,r.uri=r.ns[n.prefix]||"",r.prefix&&!r.uri&&(I(e,"Unbound namespace prefix: "+JSON.stringify(e.tagName)),r.uri=n.prefix);var s=e.tags[e.tags.length-1]||e;r.ns&&s.ns!==r.ns&&Object.keys(r.ns).forEach((function(t){T(e,"onopennamespace",{prefix:t,uri:r.ns[t]})}));for(var a=0,i=e.attribList.length;a",e.tagName="",void(e.state=S.SCRIPT);T(e,"onscript",e.script),e.script=""}var t=e.tags.length,r=e.tagName;e.strict||(r=r[e.looseCase]());for(var n=r;t--;){if(e.tags[t].name===n)break;I(e,"Unexpected close tag")}if(t<0)return I(e,"Unmatched closing tag: "+e.tagName),e.textNode+="",void(e.state=S.TEXT);e.tagName=r;for(var s=e.tags.length;s-- >t;){var a=e.tag=e.tags.pop();e.tagName=e.tag.name,T(e,"onclosetag",e.tagName);var i={};for(var o in a.ns)i[o]=a.ns[o];var c=e.tags[e.tags.length-1]||e;e.opt.xmlns&&a.ns!==c.ns&&Object.keys(a.ns).forEach((function(t){var r=a.ns[t];T(e,"onclosenamespace",{prefix:t,uri:r})}))}0===t&&(e.closedRoot=!0),e.tagName=e.attribValue=e.attribName="",e.attribList.length=0,e.state=S.TEXT}function L(e){var t,r=e.entity,n=r.toLowerCase(),s="";return e.ENTITIES[r]?e.ENTITIES[r]:e.ENTITIES[n]?e.ENTITIES[n]:("#"===(r=n).charAt(0)&&("x"===r.charAt(1)?(r=r.slice(2),s=(t=parseInt(r,16)).toString(16)):(r=r.slice(1),s=(t=parseInt(r,10)).toString(10))),r=r.replace(/^0+/,""),isNaN(t)||s.toLowerCase()!==r?(I(e,"Invalid character entity"),"&"+e.entity+";"):String.fromCodePoint(t))}function F(e,t){"<"===t?(e.state=S.OPEN_WAKA,e.startTagPosition=e.position):f(t)||(I(e,"Non-whitespace before first tag."),e.textNode=t,e.state=S.TEXT)}function D(e,t){var r="";return t1114111||_(i)!==i)throw RangeError("Invalid code point: "+i);i<=65535?r.push(i):(e=55296+((i-=65536)>>10),t=i%1024+56320,r.push(e,t)),(n+1===s||r.length>16384)&&(a+=v.apply(null,r),r.length=0)}return a},Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:k,configurable:!0,writable:!0}):String.fromCodePoint=k),e},Lr=$r(),Fr='The output should be formatted as a XML file.\n1. Output should conform to the tags below. \n2. If tags are not given, make them on your own.\n3. Remember to always open and close all the tags.\n\nAs an example, for the tags ["foo", "bar", "baz"]:\n1. String "\n \n \n \n" is a well-formatted instance of the schema. \n2. String "\n \n " is a badly-formatted instance.\n3. String "\n \n \n" is a badly-formatted instance.\n\nHere are the output tags:\n```\n{tags}\n```';class Dr extends kr{constructor(e){super(e),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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}),this.tags=e?.tags}static lc_name(){return"XMLOutputParser"}_diff(e,t){if(t)return e?(0,Rr.UD)(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return Br(e[0].text)}async parse(e){return Br(e)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?Fr.replace("{tags}",this.tags?.join(", ")??""):Fr}}const zr=e=>e.split("\n").map((e=>e.replace(/^\s+/,""))).join("\n").trim(),Ur=e=>{if(0===Object.keys(e).length)return{};const t={};return e.children.length>0?(t[e.name]=e.children.map(Ur),t):(t[e.name]=e.text??void 0,t)};function Br(e){const t=zr(e),r=Lr.parser(!0);let n={};const s=[];r.onopentag=e=>{const t={name:e.name,attributes:e.attributes,children:[],text:"",isSelfClosing:e.isSelfClosing};if(s.length>0){s[s.length-1].children.push(t)}else n=t;e.isSelfClosing||s.push(t)},r.onclosetag=()=>{if(s.length>0){const e=s.pop();0===s.length&&e&&(n=e)}},r.ontext=e=>{if(s.length>0){s[s.length-1].text+=e}},r.onattribute=e=>{if(s.length>0){s[s.length-1].attributes[e.name]=e.value}};const a=/```(xml)?(.*)```/s.exec(t),i=a?a[2]:t;return r.write(i).close(),n&&"?xml"===n.name&&(n=n.children[0]),Ur(n)}var qr=s(6993),Kr=s(3766),Wr=s(2771);class Hr extends qr.m{static lc_name(){return"PipelinePromptTemplate"}constructor(e){super({...e,inputVariables:[]}),Object.defineProperty(this,"pipelinePrompts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"finalPrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.pipelinePrompts=e.pipelinePrompts,this.finalPrompt=e.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){const e=this.pipelinePrompts.map((e=>e.name)),t=this.pipelinePrompts.map((t=>t.prompt.inputVariables.filter((t=>!e.includes(t))))).flat();return[...new Set(t)]}static extractRequiredInputValues(e,t){return t.reduce(((t,r)=>(t[r]=e[r],t)),{})}async formatPipelinePrompts(e){const t=await this.mergePartialAndUserVariables(e);for(const{name:e,prompt:r}of this.pipelinePrompts){const n=Hr.extractRequiredInputValues(t,r.inputVariables);r instanceof Kr.RZ?t[e]=await r.formatMessages(n):t[e]=await r.format(n)}return Hr.extractRequiredInputValues(t,this.finalPrompt.inputVariables)}async formatPromptValue(e){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(e))}async format(e){return this.finalPrompt.format(await this.formatPipelinePrompts(e))}async partial(e){const t={...this};return t.inputVariables=this.inputVariables.filter((t=>!(t in e))),t.partialVariables={...this.partialVariables??{},...e},new Hr(t)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}}var Vr=s(3650),Gr=s(329),Jr=s(9849),Zr=s(6279);function Xr(e){return"object"==typeof e&&null!=e&&"withStructuredOutput"in e&&"function"==typeof e.withStructuredOutput}class Yr extends Kr.RZ{get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"method",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","structured"]}),this.schema=e.schema,this.method=e.method}pipe(e){if(Xr(e))return super.pipe(e.withStructuredOutput(this.schema));if("object"==typeof(t=e)&&null!=t&&"lc_id"in t&&Array.isArray(t.lc_id)&&"langchain_core/runnables/RunnableBinding"===t.lc_id.join("/")&&Xr(e.bound))return super.pipe(this.method?e.bound.withStructuredOutput(this.schema,{method:this.method}).bind(e.kwargs??{}).withConfig(e.config):e.bound.withStructuredOutput(this.schema).bind(e.kwargs??{}).withConfig(e.config));var t;throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(e,t,r){return Yr.fromMessages(e,{schema:t,method:r})}}var Qr=s(4552);class en extends Y.YN{constructor(e){super(e),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}),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw new Error("Not implemented!")}async invoke(e,t){return this.getRelevantDocuments(e,(0,Q.ZI)(t))}async getRelevantDocuments(e,t){const r=(0,Q.ZI)((0,Xe.parseCallbackConfigArg)(t)),n=await Xe.CallbackManager.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}),s=await(n?.handleRetrieverStart(this.toJSON(),e,r.runId,void 0,void 0,void 0,r.runName));try{const t=await this._getRelevantDocuments(e,s);return await(s?.handleRetrieverEnd(t)),t}catch(e){throw await(s?.handleRetrieverError(e)),e}}}class tn extends Ne.Serializable{}class rn extends tn{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","storage"]}),Object.defineProperty(this,"store",{enumerable:!0,configurable:!0,writable:!0,value:{}})}async mget(e){return e.map((e=>this.store[e]))}async mset(e){for(const[t,r]of e)this.store[t]=r}async mdelete(e){for(const t of e)delete this.store[t]}async*yieldKeys(e){const t=Object.keys(this.store);for(const r of t)(void 0===e||r.startsWith(e))&&(yield r)}}var nn=s(8009),sn=s(4350),an=s(199);function on(e){return Lt(e)?(0,Nt.Ik)(e):e}function cn(e){if(!e||"object"!=typeof e||0===Object.keys(e).length||Array.isArray(e))return!1;if("type"in e)return"string"==typeof e.type?"string"===e.type:!!Array.isArray(e.type)&&e.type.every((e=>"string"===e));if("enum"in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every((e=>"string"==typeof e));if("const"in e)return"string"==typeof e.const;if("allOf"in e&&Array.isArray(e.allOf))return e.allOf.some((e=>cn(e)));if("anyOf"in e&&Array.isArray(e.anyOf)||"oneOf"in e&&Array.isArray(e.oneOf)){const t="anyOf"in e?e.anyOf:e.oneOf;return t.length>0&&t.every((e=>cn(e)))}if("not"in e)return!1;if("$ref"in e&&"string"==typeof e.$ref){const t=e.$ref,r=ar(e);return!!r[t]&&cn(r[t])}return!1}function ln(e){return void 0!==e&&Array.isArray(e.lc_namespace)}function un(e){return void 0!==e&&Y.YN.isRunnable(e)&&"lc_name"in e.constructor&&"function"==typeof e.constructor.lc_name&&"RunnableToolLike"===e.constructor.lc_name()}function dn(e){return!!e&&"object"==typeof e&&"name"in e&&"schema"in e&&(Lt(e.schema)||null!=e.schema&&"object"==typeof e.schema&&"type"in e.schema&&"string"==typeof e.schema.type&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function hn(e){return dn(e)||un(e)||ln(e)}class pn extends Rt{get lc_namespace(){return["langchain","tools"]}constructor(e){super(e??{}),Object.defineProperty(this,"returnDirect",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"verboseParsingErrors",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"responseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"content"}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat}async invoke(e,t){let r,n=(0,Q.ZI)(t);return(0,an.Ky)(e)?(r=e.args,n={...n,toolCall:e}):r=e,this.call(r,n)}async call(e,t,r){const n=(0,an.Ky)(e)?e.args:e;let s;if(Lt(this.schema))try{s=await this.schema.parseAsync(n)}catch(t){let r="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(r=`${r}\nDetails: ${t.message}`),new an.qe(r,JSON.stringify(e))}else{const t=br(n,this.schema);if(!t.valid){let r="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(r=`${r}\nDetails: ${t.errors.map((e=>`${e.keywordLocation}: ${e.error}`)).join("\n")}`),new an.qe(r,JSON.stringify(e))}s=n}const a=(0,Xe.parseCallbackConfigArg)(t),i=Xe.CallbackManager.configure(a.callbacks,this.callbacks,a.tags||r,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),o=await(i?.handleToolStart(this.toJSON(),"string"==typeof e?e:JSON.stringify(e),a.runId,void 0,void 0,void 0,a.runName));let c,l,u,d;delete a.runId;try{c=await this._call(s,o,a)}catch(e){throw await(o?.handleToolError(e)),e}if("content_and_artifact"===this.responseFormat){if(!Array.isArray(c)||2!==c.length)throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(c)}`);[l,u]=c}else l=c;(0,an.Ky)(e)&&(d=e.id),!d&&(0,an.hR)(a)&&(d=a.toolCall.id);const h=function(e){const{content:t,artifact:r,toolCallId:n}=e;return n&&!(0,nn.fK)(t)?"string"==typeof t||Array.isArray(t)&&t.every((e=>"object"==typeof e))?new nn.uf({content:t,artifact:r,tool_call_id:n,name:e.name}):new nn.uf({content:wn(t),artifact:r,tool_call_id:n,name:e.name}):t}({content:l,artifact:u,toolCallId:d,name:this.name});return await(o?.handleToolEnd(h)),h}}class mn extends pn{constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:M.z.object({input:M.z.string().optional()}).transform((e=>e.input))})}call(e,t){const r="string"==typeof e||null==e?{input:e}:e;return super.call(r,t)}}class fn extends mn{static lc_name(){return"DynamicTool"}constructor(e){super(e),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,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,t){const r=(0,Xe.parseCallbackConfigArg)(t);return void 0===r.runName&&(r.runName=this.name),super.call(e,r)}async _call(e,t,r){return this.func(e,t,r)}}class gn extends pn{static lc_name(){return"DynamicStructuredTool"}constructor(e){super(e),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,"func",{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.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}async call(e,t,r){const n=(0,Xe.parseCallbackConfigArg)(t);return void 0===n.runName&&(n.runName=this.name),super.call(e,n,r)}_call(e,t,r){return this.func(e,t,r)}}class yn{getTools(){return this.tools}}function bn(e,t){const r=t.schema&&Lt(t.schema)&&(!("shape"in t.schema)||!t.schema.shape),n=cn(t.schema);if(!t.schema||r||n)return new fn({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(t,r,n)=>new Promise(((s,a)=>{const i=(0,Q.tn)(n,{callbacks:r?.getChild()});sn.Nx.runWithConfig((0,Q.DY)(i),(async()=>{try{s(e(t,i))}catch(e){a(e)}}))}))});const s=t.schema,a=t.description??t.schema.description??`${t.name} tool`;return new gn({...t,description:a,schema:s,func:async(t,r,n)=>new Promise(((s,a)=>{const i=(0,Q.tn)(n,{callbacks:r?.getChild()});sn.Nx.runWithConfig((0,Q.DY)(i),(async()=>{try{s(e(t,i))}catch(e){a(e)}}))}))})}function wn(e){try{return JSON.stringify(e,null,2)}catch(t){return`${e}`}}var vn=s(1590),_n=s(6906),kn=s(3997),Sn=s(9583);class En extends vn.BaseTracer{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"endpoint",{enumerable:!0,configurable:!0,writable:!0,value:(0,Sn.getEnvironmentVariable)("LANGCHAIN_ENDPOINT")||"http://localhost:1984"}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:{"Content-Type":"application/json"}}),Object.defineProperty(this,"session",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const e=(0,Sn.getEnvironmentVariable)("LANGCHAIN_API_KEY");e&&(this.headers["x-api-key"]=e)}async newSession(e){const t={start_time:Date.now(),name:e},r=await this.persistSession(t);return this.session=r,r}async loadSession(e){const t=`${this.endpoint}/sessions?name=${e}`;return this._handleSessionResponse(t)}async loadDefaultSession(){const e=`${this.endpoint}/sessions?name=default`;return this._handleSessionResponse(e)}async convertV2RunToRun(e){const t=this.session??await this.loadDefaultSession(),r=e.serialized;let n;if("llm"===e.run_type){const s=e.inputs.prompts?e.inputs.prompts:e.inputs.messages.map((e=>(0,qe.Sw)(e)));n={uuid:e.id,start_time:e.start_time,end_time:e.end_time,execution_order:e.execution_order,child_execution_order:e.child_execution_order,serialized:r,type:e.run_type,session_id:t.id,prompts:s,response:e.outputs}}else if("chain"===e.run_type){const s=await Promise.all(e.child_runs.map((e=>this.convertV2RunToRun(e))));n={uuid:e.id,start_time:e.start_time,end_time:e.end_time,execution_order:e.execution_order,child_execution_order:e.child_execution_order,serialized:r,type:e.run_type,session_id:t.id,inputs:e.inputs,outputs:e.outputs,child_llm_runs:s.filter((e=>"llm"===e.type)),child_chain_runs:s.filter((e=>"chain"===e.type)),child_tool_runs:s.filter((e=>"tool"===e.type))}}else{if("tool"!==e.run_type)throw new Error(`Unknown run type: ${e.run_type}`);{const s=await Promise.all(e.child_runs.map((e=>this.convertV2RunToRun(e))));n={uuid:e.id,start_time:e.start_time,end_time:e.end_time,execution_order:e.execution_order,child_execution_order:e.child_execution_order,serialized:r,type:e.run_type,session_id:t.id,tool_input:e.inputs.input,output:e.outputs?.output,action:JSON.stringify(r),child_llm_runs:s.filter((e=>"llm"===e.type)),child_chain_runs:s.filter((e=>"chain"===e.type)),child_tool_runs:s.filter((e=>"tool"===e.type))}}}return n}async persistRun(e){let t,r;r=void 0!==e.run_type?await this.convertV2RunToRun(e):e,t="llm"===r.type?`${this.endpoint}/llm-runs`:"chain"===r.type?`${this.endpoint}/chain-runs`:`${this.endpoint}/tool-runs`;const n=await fetch(t,{method:"POST",headers:this.headers,body:JSON.stringify(r)});n.ok||console.error(`Failed to persist run: ${n.status} ${n.statusText}`)}async persistSession(e){const t=`${this.endpoint}/sessions`,r=await fetch(t,{method:"POST",headers:this.headers,body:JSON.stringify(e)});return r.ok?{id:(await r.json()).id,...e}:(console.error(`Failed to persist session: ${r.status} ${r.statusText}, using default session.`),{id:1,...e})}async _handleSessionResponse(e){const t=await fetch(e,{method:"GET",headers:this.headers});let r;if(!t.ok)return console.error(`Failed to load session: ${t.status} ${t.statusText}`),r={id:1,start_time:Date.now()},this.session=r,r;const n=await t.json();return 0===n.length?(r={id:1,start_time:Date.now()},this.session=r,r):([r]=n,this.session=r,r)}}async function xn(e){const t=new En;return e?await t.loadSession(e):await t.loadDefaultSession(),t}async function Tn(){return new kn.LangChainTracer}var Cn=s(1060);class Pn extends vn.BaseTracer{constructor({exampleId:e}={}){super({_awaitHandler:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"run_collector"}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracedRuns",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.exampleId=e,this.tracedRuns=[]}async persistRun(e){const t={...e};t.reference_example_id=this.exampleId,this.tracedRuns.push(t)}}const On=(e,t)=>e.reduce(((e,r,n)=>{const s=Math.floor(n/t),a=e[s]||[];return e[s]=a.concat([r]),e}),[]);function An(e,t){const r="number"==typeof t?void 0:t;return{name:e.name,description:e.description,parameters:on(e.schema),...void 0!==r?.strict?{strict:r.strict}:{}}}function In(e,t){const r="number"==typeof t?void 0:t;let n;return n=hn(e)?{type:"function",function:An(e)}:e,void 0!==r?.strict&&(n.function.strict=r.strict),n}function Mn(e,t){let r=0,n=0,s=0;for(let a=0;at.map((t=>r(e,t))).map((e=>Number.isNaN(e)?0:e))))}function $n(e,t=!1){const r=e.reduce(((e,t)=>Math.max(e,Un(t).maxValue)),0);return e.map((e=>e.map((e=>t?1-e/r:e/r))))}function Ln(e,t){return Nn(e,t,Mn)}function Fn(e,t){return Nn(e,t,Rn)}function Dn(e,t){return Nn(e,t,jn)}function zn(e,t,r=.5,n=4){if(Math.min(n,t.length)<=0)return[];const s=Ln(Array.isArray(e[0])?e:[e],t)[0],a=Un(s).maxIndex,i=[t[a]],o=[a];for(;o.length{if(o.includes(s))return;const i=Math.max(...a[s]),c=r*t-(1-r)*i;c>e&&(e=c,n=s)})),i.push(t[n]),o.push(n)}return o}function Un(e){if(0===e.length)return{maxIndex:-1,maxValue:NaN};let t=e[0],r=0;for(let n=1;nt&&(r=n,t=e[n]);return{maxIndex:r,maxValue:t}}class Bn extends en{static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),Object.defineProperty(this,"vectorStore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"k",{enumerable:!0,configurable:!0,writable:!0,value:4}),Object.defineProperty(this,"searchType",{enumerable:!0,configurable:!0,writable:!0,value:"similarity"}),Object.defineProperty(this,"searchKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,"mmr"===e.searchType&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if("mmr"===this.searchType){if("function"!=typeof this.vectorStore.maxMarginalRelevanceSearch)throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild("vectorstore"))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}}class qn extends Ne.Serializable{constructor(e,t){super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","vectorstores",this._vectorstoreType()]}),Object.defineProperty(this,"embeddings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,t=4,r=void 0,n=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)).map((e=>e[0]))}async similaritySearchWithScore(e,t=4,r=void 0,n=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)}static fromTexts(e,t,r,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,t,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,t,r,n,s,a){if("number"==typeof e)return new Bn({vectorStore:this,k:e,filter:t,tags:[...n??[],this._vectorstoreType()],metadata:s,verbose:a,callbacks:r});{const t={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return new Bn("mmr"===e?.searchType?{...t,searchKwargs:e.searchKwargs}:{...t})}}}class Kn extends qn{static load(e,t){throw new Error("Not implemented")}}class Wn extends Xt{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["tests","fake"]})}getFormatInstructions(){return""}async parse(e){return e.split(",").map((e=>e.trim()))}}class Hn extends Y.YN{constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["tests","fake"]}),Object.defineProperty(this,"returnOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}}class Vn extends qt{constructor(e){super(e),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"thrownErrorString",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const n=this.response??e;return await(r?.handleLLMNewToken(n)),n}}class Gn extends qt{constructor(e){super(e),Object.defineProperty(this,"sleep",{enumerable:!0,configurable:!0,writable:!0,value:50}),Object.defineProperty(this,"responses",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"thrownErrorString",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const n=this.responses?.[0];this.responses=this.responses?.slice(1);for(const t of n??e)await new Promise((e=>setTimeout(e,this.sleep))),yield{text:t,generationInfo:{}},await(r?.handleLLMNewToken(t))}}class Jn extends zt{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(e,t,r){if(t?.stop?.length)return{generations:[{message:new se.AIMessage(t.stop[0]),text:t.stop[0]}]};const n=e.map((e=>"string"==typeof e.content?e.content:JSON.stringify(e.content,null,2))).join("\n");return await(r?.handleLLMNewToken(n)),{generations:[{message:new se.AIMessage(n),text:n}],llmOutput:{}}}}class Zn extends zt{constructor({sleep:e=50,responses:t=[],chunks:r=[],toolStyle:n="openai",thrownErrorString:s,...a}){super(a),Object.defineProperty(this,"sleep",{enumerable:!0,configurable:!0,writable:!0,value:50}),Object.defineProperty(this,"responses",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"toolStyle",{enumerable:!0,configurable:!0,writable:!0,value:"openai"}),Object.defineProperty(this,"thrownErrorString",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tools",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.sleep=e,this.responses=t,this.chunks=r,this.toolStyle=n,this.thrownErrorString=s}_llmType(){return"fake"}bindTools(e){const t=[...this.tools,...e],r=t.map((e=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:e.name,description:e.description,parameters:on(e.schema)}};case"anthropic":return{name:e.name,description:e.description,input_schema:on(e.schema)};case"bedrock":return{toolSpec:{name:e.name,description:e.description,inputSchema:on(e.schema)}};case"google":return{name:e.name,description:e.description,parameters:on(e.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}})),n="google"===this.toolStyle?[{functionDeclarations:r}]:r,s=new Zn({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return s.tools=t,s.bind({tools:n})}async _generate(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const n=this.responses?.[0]?.content??e[0].content??"";return{generations:[{text:"",message:new se.AIMessage({content:n,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(const e of this.chunks){const t=new $t.ChatGenerationChunk({message:new se.AIMessageChunk({content:e.content,tool_calls:e.tool_calls,additional_kwargs:e.additional_kwargs??{}}),text:e.content?.toString()??""});yield t,await(r?.handleLLMNewToken(e.content,void 0,void 0,void 0,void 0,{chunk:t}))}return}const n=this.responses?.[0]??new se.AIMessage("string"==typeof e[0].content?e[0].content:""),s="string"==typeof n.content?n.content:"";for(const e of s){await new Promise((e=>setTimeout(e,this.sleep)));const t=new $t.ChatGenerationChunk({message:new se.AIMessageChunk({content:e}),text:e});yield t,await(r?.handleLLMNewToken(e,void 0,void 0,void 0,void 0,{chunk:t}))}}}class Xn extends en{constructor(e){super(),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["test","fake"]}),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:[new rt({pageContent:"foo"}),new rt({pageContent:"bar"})]}),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}}class Yn extends zt{static lc_name(){return"FakeListChatModel"}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"responses",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"i",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"sleep",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"emitCustomEvent",{enumerable:!0,configurable:!0,writable:!0,value:!1});const{responses:t,sleep:r,emitCustomEvent:n}=e;this.responses=t,this.sleep=r,this.emitCustomEvent=n??this.emitCustomEvent}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(e,t,r){if(await this._sleepIfRequested(),t?.thrownErrorString)throw new Error(t.thrownErrorString);if(this.emitCustomEvent&&await(r?.handleCustomEvent("some_test_event",{someval:!0})),t?.stop?.length)return{generations:[this._formatGeneration(t.stop[0])]};{const e=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(e)],llmOutput:{}}}}_formatGeneration(e){return{message:new se.AIMessage(e),text:e}}async*_streamResponseChunks(e,t,r){const n=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await(r?.handleCustomEvent("some_test_event",{someval:!0}));for await(const e of n){if(await this._sleepIfRequested(),t?.thrownErrorString)throw new Error(t.thrownErrorString);const n=this._createResponseChunk(e);yield n,r?.handleLLMNewToken(e)}}async _sleepIfRequested(){void 0!==this.sleep&&await this._sleep()}async _sleep(){return new Promise((e=>{setTimeout((()=>e()),this.sleep)}))}_createResponseChunk(e){return new $t.ChatGenerationChunk({message:new se.AIMessageChunk({content:e}),text:e})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i{const t=await this.invoke(e);if(t.tool_calls?.[0]?.args)return t.tool_calls[0].args;if("string"==typeof t.content)return JSON.parse(t.content);throw new Error("No structured output found")}))}}class Qn extends Qe{constructor(){super(),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","message","fake"]}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:[]})}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new se.HumanMessage(e))}async addAIChatMessage(e){this.messages.push(new se.AIMessage(e))}async clear(){this.messages=[]}}class es extends et{constructor(){super(),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","message","fake"]}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:[]})}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}}class ts extends vn.BaseTracer{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"fake_tracer"}),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:[]})}persistRun(e){return this.runs.push(e),Promise.resolve()}}class rs extends pn{constructor(e){super(e),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}async _call(e,t){return JSON.stringify(e)}}class ns extends it{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map((()=>[.1,.2,.3,.4])))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}}class ss extends it{constructor(e){super(e??{}),Object.defineProperty(this,"vectorSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map((e=>this.embedQuery(e))))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,"");const r=t.length%this.vectorSize,n=0===r?0:this.vectorSize-r,s=t.length+n;t=t.padEnd(s," ");const a=t.length/this.vectorSize,i=[];for(let e=0;e{let t=0;for(let r=0;r{this.runPromiseResolver=e}))}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}}class is extends qn{_vectorstoreType(){return"memory"}constructor(e,{similarity:t,...r}={}){super(e,r),Object.defineProperty(this,"memoryVectors",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"similarity",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.similarity=t??Mn}async addDocuments(e){const t=e.map((({pageContent:e})=>e));return this.addVectors(await this.embeddings.embedDocuments(t),e)}async addVectors(e,t){const r=e.map(((e,r)=>({content:t[r].pageContent,embedding:e,metadata:t[r].metadata})));this.memoryVectors=this.memoryVectors.concat(r)}async similaritySearchVectorWithScore(e,t,r){const n=this.memoryVectors.filter((e=>{if(!r)return!0;const t=new rt({metadata:e.metadata,pageContent:e.content});return r(t)}));return n.map(((t,r)=>({similarity:this.similarity(e,t.embedding),index:r}))).sort(((e,t)=>e.similarity>t.similarity?-1:0)).slice(0,t).map((e=>[new rt({metadata:n[e.index].metadata,pageContent:n[e.index].content}),e.similarity]))}static async fromTexts(e,t,r,n){const s=[];for(let r=0;r0===r?t:us(e,t)>=0?e:t))}const hs={[Ie]:-1,[Me]:-2,[Re]:-3,[je]:-4};class ps extends Error{constructor(e){super(e),this.name="InvalidNamespaceError"}}class ms{async get(e,t){return(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){const{filter:r,limit:n=10,offset:s=0,query:a}=t;return(await this.batch([{namespacePrefix:e,filter:r,limit:n,offset:s,query:a}]))[0]}async put(e,t,r,n){!function(e){if(0===e.length)throw new ps("Namespace cannot be empty.");for(const t of e){if("string"!=typeof t)throw new ps(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes("."))throw new ps(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(""===t)throw new ps(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if("langgraph"===e[0])throw new ps(`Root label for namespace cannot be "langgraph". Got: ${e}`)}(e),await this.batch([{namespace:e,key:t,value:r,index:n}])}async delete(e,t){await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){const{prefix:t,suffix:r,maxDepth:n,limit:s=100,offset:a=0}=e,i=[];return t&&i.push({matchType:"prefix",path:t}),r&&i.push({matchType:"suffix",path:r}),(await this.batch([{matchConditions:i.length?i:void 0,maxDepth:n,limit:s,offset:a}]))[0]}start(){}stop(){}}class fs extends ms{constructor(e){var t;super(),Object.defineProperty(this,"lg_name",{enumerable:!0,configurable:!0,writable:!0,value:"AsyncBatchedStore"}),Object.defineProperty(this,"store",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"nextKey",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"running",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"processingTask",{enumerable:!0,configurable:!0,writable:!0,value:null}),this.store="lg_name"in(t=e)&&"AsyncBatchedStore"===t.lg_name?t.store:t}get isRunning(){return this.running}async batch(e){throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){const{filter:r,limit:n=10,offset:s=0,query:a}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:r,limit:n,offset:s,query:a})}async put(e,t,r){return this.enqueueOperation({namespace:e,key:t,value:r})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise(((t,r)=>{const n=this.nextKey;this.nextKey+=1,this.queue.set(n,{operation:e,resolve:t,reject:r})}))}async processBatchQueue(){for(;this.running;){if(await new Promise((e=>{setTimeout(e,0)})),0===this.queue.size)continue;const e=new Map(this.queue);this.queue.clear();try{const t=Array.from(e.values()).map((({operation:e})=>e)),r=await this.store.batch(t);e.forEach((({resolve:t},n)=>{const s=Array.from(e.keys()).indexOf(n);t(r[s])}))}catch(t){e.forEach((({reject:e})=>{e(t)}))}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}}class gs extends Error{constructor(e,t){let r=e??"";t?.lc_error_code&&(r=`${r}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t.lc_error_code}/\n`),super(r),Object.defineProperty(this,"lc_error_code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lc_error_code=t?.lc_error_code}}class ys extends gs{get is_bubble_up(){return!0}}class bs extends gs{constructor(e,t){super(e,t),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}}class ws extends gs{constructor(e,t){super(e,t),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}}class vs extends ys{constructor(e,t){super(JSON.stringify(e,null,2),t),Object.defineProperty(this,"interrupts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="GraphInterrupt",this.interrupts=e??[]}static get unminifiable_name(){return"GraphInterrupt"}}class _s extends vs{constructor(e,t){super([{value:e,when:"during"}],t),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}}class ks extends ys{constructor(e){super(),Object.defineProperty(this,"command",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="ParentCommand",this.command=e}static get unminifiable_name(){return"ParentCommand"}}function Ss(e){return void 0!==e&&e.name===ks.unminifiable_name}function Es(e){return void 0!==e&&!0===e.is_bubble_up}function xs(e){return void 0!==e&&[vs.unminifiable_name,_s.unminifiable_name].includes(e.name)}class Ts extends gs{constructor(e,t){super(e,t),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}}class Cs extends gs{constructor(e,t){super(e,t),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}}class Ps extends gs{constructor(e,t){super(e,t),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}}class Os extends gs{constructor(e,t){super(e,t),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}}function As(e){return null!=e&&!0===e.lg_is_channel}class Is{constructor(){Object.defineProperty(this,"ValueType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"UpdateType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lg_is_channel",{enumerable:!0,configurable:!0,writable:!0,value:!0})}consume(){return!1}}function Ms(e,t){const r=Object.fromEntries(Object.entries(e).filter((([,e])=>As(e)))),n={};for(const e in r)if(Object.prototype.hasOwnProperty.call(r,e)){const s=t.channel_values[e];n[e]=r[e].fromCheckpoint(s)}return n}function Rs(e,t,r){let n;if(void 0===t)n=e.channel_values;else{n={};for(const e of Object.keys(t))try{n[e]=t[e].checkpoint()}catch(e){if(e.name!==Cs.unminifiable_name)throw e}}return{v:1,id:Oe(r),ts:(new Date).toISOString(),channel_values:n,channel_versions:{...e.channel_versions},versions_seen:os(e.versions_seen),pending_sends:e.pending_sends??[]}}var js=s(9137);const Ns=/^(?:[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;const $s=function(e){return"string"==typeof e&&Ns.test(e)},Ls="__start__",Fs="__end__",Ds="__input__",zs="__error__",Us="__pregel_send",Bs="__pregel_call",qs="__pregel_read",Ks="__pregel_checkpointer",Ws="__pregel_resuming",Hs="__pregel_task_id",Vs="__pregel_stream",Gs="__pregel_scratchpad",Js="__pregel_previous",Zs="checkpoint_ns",Xs="checkpoint_map",Ys="__pregel_abort_signals",Qs="__interrupt__",ea="__resume__",ta="__no_writes__",ra="__return__",na="__previous__",sa="__pregel_runtime_placeholder__",aa="langsmith:hidden",ia="__self__",oa="__pregel_tasks",ca="__pregel_push",la="__pregel_pull",ua="00000000-0000-0000-0000-000000000000",da=[aa,Ds,Qs,ea,zs,ta,oa,Us,qs,Ks,Vs,Ws,Hs,Bs,"__pregel_resume_value",Gs,Js,Xs,Zs,"checkpoint_id"],ha="|",pa=":";function ma(e){const t=e;return null!=t&&"string"==typeof t.node&&void 0!==t.args}class fa{constructor(e,t){Object.defineProperty(this,"lg_name",{enumerable:!0,configurable:!0,writable:!0,value:"Send"}),Object.defineProperty(this,"node",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.node=e,this.args=wa(t)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}}function ga(e){return e instanceof fa}class ya{constructor(e){Object.defineProperty(this,"lg_name",{enumerable:!0,configurable:!0,writable:!0,value:"Command"}),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"graph",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"update",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"resume",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"goto",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.resume=e.resume,this.graph=e.graph,this.update=e.update,e.goto&&(this.goto=Array.isArray(e.goto)?wa(e.goto):[wa(e.goto)])}_updateAsTuples(){return this.update&&"object"==typeof this.update&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every((e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]))?this.update:[["__root__",this.update]]}toJSON(){let e;return e="string"==typeof this.goto?this.goto:ga(this.goto)?this.goto.toJSON():this.goto?.map((e=>"string"==typeof e?e:e.toJSON())),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:e}}}function ba(e){return"object"==typeof e&&(null!=e&&("lg_name"in e&&"Command"===e.lg_name))}function wa(e,t=new Map){if(null!=e&&"object"==typeof e){if(t.has(e))return t.get(e);let r;if(Array.isArray(e))r=[],t.set(e,r),e.forEach(((e,n)=>{r[n]=wa(e,t)}));else if(!ba(e)||e instanceof ya)if(!ma(e)||e instanceof fa)if(ba(e)||ga(e))r=e,t.set(e,r);else if("lc_serializable"in e&&e.lc_serializable)r=e,t.set(e,r);else{r={},t.set(e,r);for(const[n,s]of Object.entries(e))r[n]=wa(s,t)}else r=new fa(e.node,e.args),t.set(e,r);else r=new ya(e),t.set(e,r);return r}return e}Object.defineProperty(ya,"PARENT",{enumerable:!0,configurable:!0,writable:!0,value:"__parent__"});const va=["tags","metadata","callbacks","configurable"],_a=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interruptBefore","interruptAfter","signal"];function ka(...e){const t={tags:[],metadata:{},callbacks:void 0,recursionLimit:25,configurable:{}},r=sn.Nx.getRunnableConfig();if(void 0!==r)for(const[e,n]of Object.entries(r))if(void 0!==n)if(va.includes(e)){let r;r=Array.isArray(n)?[...n]:"object"==typeof n?"callbacks"===e&&"copy"in n&&"function"==typeof n.copy?n.copy():{...n}:n,t[e]=r}else t[e]=n;for(const r of e)if(void 0!==r)for(const[e,n]of Object.entries(r))void 0!==n&&_a.includes(e)&&(t[e]=n);for(const[e,r]of Object.entries(t.configurable))t.metadata=t.metadata??{},e.startsWith("__")||"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r||e in t.metadata||(t.metadata[e]=r);return t}function Sa(e){return e.split(ha).filter((e=>!e.match(/^\d+$/))).map((e=>e.split(pa)[0])).join(ha)}function Ea(e){const t=e.split(ha);for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join(ha)}class xa extends Y.YN{constructor(e){super(),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langgraph"]}),Object.defineProperty(this,"func",{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,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"recurse",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,t,r){return new Promise(((n,s)=>{const a=(0,Q.tn)(t,{callbacks:r?.getChild()});sn.Nx.runWithConfig(a,(async()=>{try{const t=await this.func(e,a);n(t)}catch(e){s(e)}}))}))}async invoke(e,t){let r;const n=ka(t),s=(0,Q.SV)(this.config,n);return r=this.trace?await this._callWithConfig(this._tracedInvoke,e,s):await sn.Nx.runWithConfig(s,(async()=>this.func(e,s))),Y.YN.isRunnable(r)&&this.recurse?await sn.Nx.runWithConfig(s,(async()=>r.invoke(e,s))):r}}function*Ta(e,t){if(void 0===t)yield*e;else for(const r of e)yield[t,r]}async function Ca(e){const t=[];for await(const r of await e)t.push(r);return t}function Pa(e){const t=[];for(const r of e)t.push(r);return t}function Oa(e,t){return e?"configurable"in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}Symbol.for("LG_SKIP_WRITE");const Aa={[Symbol.for("LG_PASSTHROUGH")]:!0};function Ia(e){return"object"==typeof e&&void 0!==e?.[Symbol.for("LG_PASSTHROUGH")]}const Ma=Symbol("IS_WRITER");class Ra extends xa{constructor(e,t){const r=`ChannelWrite<${e.map((e=>ga(e)?e.node:"channel"in e?e.channel:"...")).join(",")}>`;super({writes:e,name:r,tags:t,func:async(e,t)=>this._write(e,t??{})}),Object.defineProperty(this,"writes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.writes=e}async _write(e,t){const r=this.writes.map((t=>Na(t)&&Ia(t.value)?{mapper:t.mapper,value:e}:ja(t)&&Ia(t.value)?{channel:t.channel,value:e,skipNone:t.skipNone,mapper:t.mapper}:t));return await Ra.doWrite(t,r),e}static async doWrite(e,t){for(const e of t){if(ja(e)){if(e.channel===oa)throw new Ps("Cannot write to the reserved channel TASKS");if(Ia(e.value))throw new Ps("PASSTHROUGH value must be replaced")}if(Na(e)&&Ia(e.value))throw new Ps("PASSTHROUGH value must be replaced")}const r=[];for(const s of t)if(ga(s))r.push([oa,s]);else if(Na(s)){const t=await s.mapper.invoke(s.value,e);null!=t&&t.length>0&&r.push(...t)}else{if(!ja(s))throw new Error(`Invalid write entry: ${JSON.stringify(s)}`);{const t=void 0!==s.mapper?await s.mapper.invoke(s.value,e):s.value;if("object"==typeof(n=t)&&void 0!==n?.[Symbol.for("LG_SKIP_WRITE")])continue;if(s.skipNone&&void 0===t)continue;r.push([s.channel,t])}}var n;const s=e.configurable?.[Us];s(r)}static isWriter(e){return e instanceof Ra||Ma in e&&!!e[Ma]}static registerWriter(e){return Object.defineProperty(e,Ma,{value:!0})}}function ja(e){return void 0!==e&&"string"==typeof e.channel}function Na(e){return void 0!==e&&!ja(e)&&Y.YN.isRunnable(e.mapper)}class $a extends xa{constructor(e,t,r=!1){super({func:(e,t)=>$a.doRead(t,this.channel,this.fresh,this.mapper)}),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"ChannelRead"}),Object.defineProperty(this,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fresh",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.fresh=r,this.mapper=t,this.channel=e,this.name=Array.isArray(e)?`ChannelRead<${e.join(",")}>`:`ChannelRead<${e}>`}static doRead(e,t,r,n){const s=e.configurable?.[qs];if(!s)throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process");return n?n(s(t,r)):s(t,r)}}const La=new te;class Fa extends Y.fJ{constructor(e){const{channels:t,triggers:r,mapper:n,writers:s,bound:a,kwargs:i,metadata:o,retryPolicy:c,tags:l,subgraphs:u,ends:d}=e,h=[...e.config?.tags?e.config.tags:[],...l??[]];super({...e,bound:e.bound??La,config:{...e.config?e.config:{},tags:h}}),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"PregelNode"}),Object.defineProperty(this,"channels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"triggers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:La}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"retryPolicy",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"subgraphs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ends",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.channels=t,this.triggers=r,this.mapper=n,this.writers=s??this.writers,this.bound=a??this.bound,this.kwargs=i??this.kwargs,this.metadata=o??this.metadata,this.tags=h,this.retryPolicy=c,this.subgraphs=u,this.ends=d}getWriters(){const e=[...this.writers];for(;e.length>1&&e[e.length-1]instanceof Ra&&e[e.length-2]instanceof Ra;){const t=e.slice(-2),r=t[0].writes.concat(t[1].writes);e[e.length-2]=new Ra(r,t[0].config?.tags),e.pop()}return e}getNode(){const e=this.getWriters();return this.bound===La&&0===e.length?void 0:this.bound===La&&1===e.length?e[0]:this.bound===La?new Y.zZ({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new Y.zZ({first:this.bound,middle:e.slice(0,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):this.bound}join(e){if(!Array.isArray(e))throw new Error("channels must be a list");if("object"!=typeof this.channels)throw new Error("all channels must be named when using .join()");return new Fa({channels:{...this.channels,...Object.fromEntries(e.map((e=>[e,e])))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy})}pipe(e){return Ra.isWriter(e)?new Fa({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,e],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy}):this.bound===La?new Fa({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:(0,Y.Bp)(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy}):new Fa({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy})}}class Da extends Error{constructor(e){super(e),this.name="GraphValidationError"}}function za(e,t){if(Array.isArray(e)){for(const r of e)if(!(r in t))throw new Error(`Key ${String(r)} not found in channels`)}else if(!(e in t))throw new Error(`Key ${String(e)} not found in channels`)}function Ua(e,t,r=!0,n=!1){try{return e[t].get()}catch(e){if(e.name===Cs.unminifiable_name){if(n)return e;if(r)return null}throw e}}function Ba(e,t,r=!0){if(Array.isArray(t)){const n={};for(const s of t)try{n[s]=Ua(e,s,!r)}catch(e){if(e.name===Cs.unminifiable_name)continue}return n}return Ua(e,t)}function*qa(e,t){if(null!=t)if(Array.isArray(e)&&"object"==typeof t&&!Array.isArray(t))for(const r in t)e.includes(r)&&(yield[r,t[r]]);else{if(Array.isArray(e))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[e,t]}}function*Ka(e,t,r){Array.isArray(e)?(!0===t||t.find((([t,r])=>e.includes(t))))&&(yield Ba(r,e)):(!0===t||t.some((([t,r])=>t===e)))&&(yield Ua(r,e))}function*Wa(e,t,r){const n=t.filter((([e,t])=>(void 0===e.config||!e.config.tags?.includes(aa))&&t[0][0]!==zs&&t[0][0]!==Qs));if(!n.length)return;let s;s=n.some((([e])=>e.writes.some((([e,t])=>e===ra))))?n.flatMap((([e])=>e.writes.filter((([e,t])=>e===ra)).map((([t,r])=>[e.name,r])))):Array.isArray(e)?n.flatMap((([t])=>{const{writes:r}=t,n={};for(const[t]of r)e.includes(t)&&(n[t]=(n[t]||0)+1);return Object.values(n).some((e=>e>1))?r.filter((([t])=>e.includes(t))).map((([e,r])=>[t.name,{[e]:r}])):[[t.name,Object.fromEntries(r.filter((([t])=>e.includes(t))))]]})):n.flatMap((([t])=>t.writes.filter((([t,r])=>t===e)).map((([e,r])=>[t.name,r]))));const a={};for(const[e,t]of s)e in a||(a[e]=[]),a[e].push(t);const i={};for(const e in a)if(1===a[e].length){const[t]=a[e];i[e]=t}else i[e]=a[e];r&&(i.__metadata__={cached:r}),yield i}function Ha(e){return"lg_is_pregel"in e&&!0===e.lg_is_pregel}function Va(e){const t=[e];for(const e of t){if(Ha(e))return e;"steps"in(r=e)&&Array.isArray(r.steps)&&t.push(...e.steps)}var r}const Ga={start:"",end:""},Ja={start:"",end:""},Za={start:"",end:""},Xa=(e,t)=>`${e.start}${t}${e.end}`;function*Ya(e,t){const r=(new Date).toISOString();for(const{id:n,name:s,input:a,config:i,triggers:o,writes:c}of t){if(i?.tags?.includes(aa))continue;const t=c.filter((([e,t])=>e===n&&t===Qs)).map((([,e])=>e));yield{type:"task",timestamp:r,step:e,payload:{id:n,name:s,input:a,triggers:o,interrupts:t}}}}function Qa(e,t,r){return e.map((e=>{const n=t.find((([t,r])=>t===e.id&&r===zs))?.[2],s=t.filter((([t,r])=>t===e.id&&r===Qs)).map((([,,e])=>e));if(n)return{id:e.id,name:e.name,path:e.path,error:n,interrupts:s};const a=r?.[e.id];return{id:e.id,name:e.name,path:e.path,interrupts:s,...void 0!==a?{state:a}:{}}}))}function ei(e,t){const r=t.length;console.log([`${Xa(Ga,`[${e}:tasks]`)}`,` Starting step ${e} with ${r} task${1===r?"":"s"}:\n`,t.map((e=>`- ${Xa(Ja,String(e.name))} -> ${JSON.stringify(e.input,null,2)}`)).join("\n")].join(""))}function ti(e,t,r){const n={};for(const[e,s]of t)r.includes(e)&&(n[e]||(n[e]=[]),n[e].push(s));console.log([`${Xa(Ga,`[${e}:writes]`)}`,` Finished step ${e} with writes to ${Object.keys(n).length} channel${1!==Object.keys(n).length?"s":""}:\n`,Object.entries(n).map((([e,t])=>`- ${Xa(Za,e)} -> ${t.map((e=>JSON.stringify(e))).join(", ")}`)).join("\n")].join(""))}class ri{constructor({func:e,name:t,input:r,retry:n,callbacks:s}){Object.defineProperty(this,"func",{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,"input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"retry",{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,"__lg_type",{enumerable:!0,configurable:!0,writable:!0,value:"call"}),this.func=e,this.name=t,this.input=r,this.retry=n,this.callbacks=s}}function ni(e){const t=Object.values(e),r=t.length>0?typeof t[0]:void 0;let n;return"number"===r?n=0:"string"===r&&(n=""),n}function si(e,t){if(Object.keys(e).length>0){const r=ni(t);return Object.fromEntries(Object.entries(t).filter((([t,n])=>n>(e[t]??r))))}return t}function ai(e,t){return null===e?{configurable:t}:void 0===e?.configurable?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function ii(e,t){const r=t?.parents??{};return Object.keys(r).length>0?ai(e,{[Xs]:{...r,[e.configurable?.checkpoint_ns??""]:e.configurable?.checkpoint_id}}):e}function oi(...e){if(1===e.length)return e[0];if("any"in AbortSignal)return AbortSignal.any(e);const t=new AbortController,r=()=>{t.abort(),e.forEach((e=>e.removeEventListener("abort",r)))};return e.forEach((e=>e.addEventListener("abort",r))),e.some((e=>e.aborted))&&t.abort(),t.signal}const ci=e=>void 0!==e?e+1:1;function li(e,t,r){const n=Object.values(e.channel_versions),s=n.length>0?typeof n[0]:void 0;let a;"number"===s?a=0:"string"===s&&(a="");const i=e.versions_seen[Qs]??{},o=Object.entries(e.channel_versions).some((([e,t])=>t>(i[e]??a))),c=r.some((e=>"*"===t?!e.config?.tags?.includes(aa):t.includes(e.name)));return o&&c}function ui(e,t,r,n,s,a,i=!1){let o,c=[],l=new Set;if(Array.isArray(a))c=a.filter((e=>n.get(e))),a=a.filter((e=>!n.get(e))),l=new Set(a.filter((e=>s.writes.some((([t,r])=>t===e)))));else{for(const[e]of s.writes)if(e===a){l=new Set([e]);break}l=l||new Set}if(i&&l.size>0){const e=Object.fromEntries(Object.entries(r).filter((([e,t])=>l.has(e)))),n=Rs(t,e,-1),i=Ms(e,n);pi(ls(n),i,[s]),o=Ba({...r,...i},a)}else o=Ba(r,a);if(c.length>0)for(const t of c){const r=n.get(t);if(r){const n=r.call(e);o[t]=n}}return o}function di(e,t,r,n,s){for(const[t,a]of s)if([ca,oa].includes(t)&&null!=a){if(!ga(a))throw new Ps(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(a)}`);if(!(a.node in r))throw new Ps(`Invalid node name "${a.node}" in Send packet`);n.replaceRuntimeValues(e,a.args)}t(s)}const hi=new Set([ta,ca,ea,Qs,ra,zs]);function pi(e,t,r,n){r.sort(((e,t)=>{const r=e.path?.slice(0,3)||[],n=t.path?.slice(0,3)||[];for(let e=0;en[e])return 1}return r.length-n.length}));const s=r.some((e=>e.triggers.length>0)),a=Object.fromEntries(Object.entries(t).filter((([e,t])=>As(t))));for(const t of r){void 0===e.versions_seen[t.name]&&(e.versions_seen[t.name]={});for(const r of t.triggers)r in e.channel_versions&&(e.versions_seen[t.name][r]=e.channel_versions[r])}let i;Object.keys(e.channel_versions).length>0&&(i=ds(...Object.values(e.channel_versions)));const o=new Set(r.flatMap((e=>e.triggers)).filter((e=>!da.includes(e))));for(const t of o)t in a&&a[t].consume()&&void 0!==n&&(e.channel_versions[t]=n(i,a[t]));e.pending_sends?.length&&s&&(e.pending_sends=[]);const c={},l={};for(const t of r)for(const[r,n]of t.writes)hi.has(r)||(r===oa?e.pending_sends.push({node:n.node,args:n.args}):r in a?r in c?c[r].push(n):c[r]=[n]:r in l?l[r].push(n):l[r]=[n]);i=void 0,Object.keys(e.channel_versions).length>0&&(i=ds(...Object.values(e.channel_versions)));const u=new Set;for(const[t,r]of Object.entries(c))if(t in a){let s;try{s=a[t].update(r)}catch(e){if(e.name===Ps.unminifiable_name){const n=new Ps(`Invalid update for channel "${t}" with values ${JSON.stringify(r)}: ${e.message}`);throw n.lc_error_code=e.lc_error_code,n}throw e}s&&void 0!==n&&(e.channel_versions[t]=n(i,a[t])),u.add(t)}if(s)for(const t of Object.keys(a))if(!u.has(t)){a[t].update([])&&void 0!==n&&(e.channel_versions[t]=n(i,a[t]))}return l}function mi(e,t,r,n,s,a,i,o){const c={};for(let l=0;lt(...e),name:e,trace:!1,recurse:!1});return new Y.zZ({name:e,first:r,last:new Ra([{channel:ra,value:Aa}],[aa])})}(m.name,m.func),g=[ca],y=""===p?m.name:`${p}${ha}${m.name}`,b=Ae(JSON.stringify([y,l.toString(),m.name,ca,e[1],e[2]]),t.id),w=`${y}${pa}${b}`,v={langgraph_step:l,langgraph_node:m.name,langgraph_triggers:g,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:w};if(o){const o=[];return{name:m.name,input:m.input,proc:f,writes:o,config:(0,Q.tn)((0,Q.SV)(i,{metadata:v,store:c.store??i.store}),{runName:m.name,callbacks:d?.getChild(`graph:step:${l}`),configurable:{[Hs]:b,[Us]:e=>di(l,(e=>o.push(...e)),n,a,e),[qs]:(r,n=!1)=>ui(l,t,s,a,{name:m.name,writes:o,triggers:g,path:e.slice(0,3)},r,n),[Ks]:u??h[Ks],[Xs]:{...h[Xs],[p]:t.id},[Gs]:gi({pendingWrites:r??[],taskId:b,currentTaskInput:m.input}),[Js]:t.channel_values[na],checkpoint_id:void 0,checkpoint_ns:w}}),triggers:g,retry_policy:m.retry,id:b,path:e.slice(0,3),writers:[]}}return{id:b,name:m.name,interrupts:[],path:e.slice(0,3)}}if(e[0]===ca){const m="number"==typeof e[1]?e[1]:parseInt(e[1],10);if(m>=t.pending_sends.length)return;const f=ma(t.pending_sends[m])&&!ga(t.pending_sends[m])?new fa(t.pending_sends[m].node,t.pending_sends[m].args):t.pending_sends[m];if(!ma(f))return void console.warn(`Ignoring invalid packet ${JSON.stringify(f)} in pending sends.`);if(!(f.node in n))return void console.warn(`Ignoring unknown node name ${f.node} in pending sends.`);const g=[ca],y=""===p?f.node:`${p}${ha}${f.node}`,b=Ae(JSON.stringify([y,l.toString(),f.node,ca,m.toString()]),t.id),w=`${y}${pa}${b}`;let v={langgraph_step:l,langgraph_node:f.node,langgraph_triggers:g,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:w};if(!o)return{id:b,name:f.node,interrupts:[],path:e};{const o=n[f.node],m=o.getNode();if(void 0!==m){a.replaceRuntimePlaceholders(l,f.args),void 0!==o.metadata&&(v={...v,...o.metadata});const y=[];return{name:f.node,input:f.args,proc:m,subgraphs:o.subgraphs,writes:y,config:(0,Q.tn)((0,Q.SV)(i,{metadata:v,tags:o.tags,store:c.store??i.store}),{runName:f.node,callbacks:d?.getChild(`graph:step:${l}`),configurable:{[Hs]:b,[Us]:e=>di(l,(e=>y.push(...e)),n,a,e),[qs]:(r,n=!1)=>ui(l,t,s,a,{name:f.node,writes:y,triggers:g,path:e},r,n),[Ks]:u??h[Ks],[Xs]:{...h[Xs],[p]:t.id},[Gs]:gi({pendingWrites:r??[],taskId:b,currentTaskInput:f.args}),[Js]:t.channel_values[na],checkpoint_id:void 0,checkpoint_ns:w}}),triggers:g,retry_policy:o.retryPolicy,id:b,path:e,writers:o.getWriters()}}}}else if(e[0]===la){const m=e[1].toString(),f=n[m];if(void 0===f)return;if(r?.length){const e=""===p?m:`${p}${ha}${m}`,n=Ae(JSON.stringify([e,l.toString(),m,la,m]),t.id);if(r.some((e=>e[0]===n&&e[1]!==zs)))return}const g=ni(t.channel_versions);if(void 0===g)return;const y=t.versions_seen[m]??{},b=f.triggers.filter((e=>{const r=Ua(s,e,!1,!0);return!(r instanceof Error&&r.name===Cs.unminifiable_name)&&(t.channel_versions[e]??g)>(y[e]??g)})).sort();if(b.length>0){const g=function(e,t,r,n,s){let a;if("object"!=typeof t.channels||Array.isArray(t.channels)){if(!Array.isArray(t.channels))throw new Error(`Invalid channels type, expected list or dict, got ${t.channels}`);{let e=!1;for(const r of t.channels)try{a=Ua(n,r,!1),e=!0;break}catch(e){if(e.name===Cs.unminifiable_name)continue;throw e}if(!e)return}}else{a={};for(const[s,i]of Object.entries(t.channels))if(t.triggers.includes(i))try{a[s]=Ua(n,i,!1)}catch(e){if(e.name===Cs.unminifiable_name)return;throw e}else if(i in n)try{a[s]=Ua(n,i,!1)}catch(e){if(e.name===Cs.unminifiable_name)continue;throw e}else a[s]=r.get(s)?.call(e)}s&&void 0!==t.mapper&&(a=t.mapper(a));return a}(l,f,a,s,o);if(void 0===g)return;const y=""===p?m:`${p}${ha}${m}`,w=Ae(JSON.stringify([y,l.toString(),m,la,b]),t.id),v=`${y}${pa}${w}`;let _={langgraph_step:l,langgraph_node:m,langgraph_triggers:b,langgraph_path:e,langgraph_checkpoint_ns:v};if(!o)return{id:w,name:m,interrupts:[],path:e};{const o=f.getNode();if(void 0!==o){void 0!==f.metadata&&(_={..._,...f.metadata});const y=[];return{name:m,input:g,proc:o,subgraphs:f.subgraphs,writes:y,config:(0,Q.tn)((0,Q.SV)(i,{metadata:_,tags:f.tags,store:c.store??i.store}),{runName:m,callbacks:d?.getChild(`graph:step:${l}`),configurable:{[Hs]:w,[Us]:e=>di(l,(e=>{y.push(...e)}),n,a,e),[qs]:(r,n=!1)=>ui(l,t,s,a,{name:m,writes:y,triggers:b,path:e},r,n),[Ks]:u??h[Ks],[Xs]:{...h[Xs],[p]:t.id},[Gs]:gi({pendingWrites:r??[],taskId:w,currentTaskInput:g}),[Js]:t.channel_values[na],checkpoint_id:void 0,checkpoint_ns:v}}),triggers:b,retry_policy:f.retryPolicy,id:w,path:e,writers:f.getWriters()}}}}}}function gi({pendingWrites:e,taskId:t,currentTaskInput:r}){const n=e.find((([e,t])=>e===ua&&t===ea))?.[2],s={callCounter:0,interruptCounter:-1,resume:e.filter((([e,r])=>e===t&&r===ea)).flatMap((([e,t,r])=>r)),nullResume:n,subgraphCounter:0,currentTaskInput:r,consumeNullResume:()=>{if(s.nullResume)return delete s.nullResume,e.splice(e.findIndex((([e,t])=>e===ua&&t===ea)),1),n}};return s}class yi extends ee.IterableReadableStream{constructor(e,t){const r=e.getReader(),n=t??new AbortController;super({start:e=>function t(){return r.read().then((({done:r,value:n})=>{if(!r)return e.enqueue(n),t();e.close()}))}()}),Object.defineProperty(this,"_abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._abortController=n,this._reader=r}async cancel(e){this._abortController.abort(e),this._reader.releaseLock()}get signal(){return this._abortController.signal}}class bi extends ee.IterableReadableStream{get closed(){return this._closed}constructor(e){let t;const r=new Promise((e=>{t=e}));super({start:e=>{t(e)}}),Object.defineProperty(this,"modes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"passthroughFn",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_closed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),r.then((e=>{this.controller=e})),this.passthroughFn=e.passthroughFn,this.modes=e.modes}push(e){this.passthroughFn?.(e),this.controller.enqueue(e)}close(){try{this.controller.close()}catch(e){}finally{this._closed=!0}}error(e){this.controller.error(e)}}const wi=Symbol.for("INPUT_DONE"),vi=Symbol.for("INPUT_RESUMING");class _i{get isResuming(){const e=0!==Object.keys(this.checkpoint.channel_versions).length,t=void 0!==this.config.configurable?.[Ws]&&this.config.configurable?.[Ws],r=null===this.input||void 0===this.input,n=ba(this.input)&&null!=this.input.resume,s=this.input===vi;return e&&(t||r||n||s)}constructor(e){Object.defineProperty(this,"input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"output",{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,"checkpointer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointerGetNextVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"channels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"managed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpoint",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointNamespace",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointPendingWrites",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"checkpointPreviousVersions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"step",{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,"outputKeys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamKeys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"skipDoneTasks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"prevCheckpointConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:"pending"}),Object.defineProperty(this,"tasks",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointerPromises",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"isNested",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_checkpointerChainedPromise",{enumerable:!0,configurable:!0,writable:!0,value:Promise.resolve()}),Object.defineProperty(this,"store",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"interruptAfter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"interruptBefore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"toInterrupt",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.input=e.input,this.checkpointer=e.checkpointer,void 0!==this.checkpointer?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=ci,this.checkpoint=e.checkpoint,this.checkpointMetadata=e.checkpointMetadata,this.checkpointPreviousVersions=e.checkpointPreviousVersions,this.channels=e.channels,this.managed=e.managed,this.checkpointPendingWrites=e.checkpointPendingWrites,this.step=e.step,this.stop=e.stop,this.config=e.config,this.checkpointConfig=e.checkpointConfig,this.isNested=e.isNested,this.manager=e.manager,this.outputKeys=e.outputKeys,this.streamKeys=e.streamKeys,this.nodes=e.nodes,this.skipDoneTasks=e.skipDoneTasks,this.store=e.store,this.stream=e.stream,this.checkpointNamespace=e.checkpointNamespace,this.prevCheckpointConfig=e.prevCheckpointConfig,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.debug=e.debug}static async initialize(e){let{config:t,stream:r}=e;void 0!==r&&void 0!==t.configurable?.[Vs]&&(r=function(...e){return new bi({passthroughFn:t=>{for(const r of e)r.modes.has(t[1])&&r.push(t)},modes:new Set(e.flatMap((e=>Array.from(e.modes))))})}(r,t.configurable[Vs]));const n=!t.configurable||!("checkpoint_id"in t.configurable),s=t.configurable?.[Gs];t.configurable&&s&&(s.subgraphCounter>0&&(t=ai(t,{[Zs]:[t.configurable[Zs],s.subgraphCounter.toString()].join(ha)})),s.subgraphCounter+=1);const a=qs in(t.configurable??{});a||void 0===t.configurable?.checkpoint_ns||""===t.configurable?.checkpoint_ns||(t=ai(t,{checkpoint_ns:"",checkpoint_id:void 0}));let i=t;void 0!==t.configurable?.[Xs]&&t.configurable?.[Xs]?.[t.configurable?.checkpoint_ns]&&(i=ai(t,{checkpoint_id:t.configurable[Xs][t.configurable?.checkpoint_ns]}));const o=t.configurable?.checkpoint_ns?.split(ha)??[],c=await(e.checkpointer?.getTuple(i))??{config:t,checkpoint:cs(),metadata:{source:"input",step:-2,writes:null,parents:{}},pendingWrites:[]};i={...t,...c.config,configurable:{checkpoint_ns:"",...t.configurable,...c.config.configurable}};const l=c.parentConfig,u=ls(c.checkpoint),d={...c.metadata},h=c.pendingWrites??[],p=Ms(e.channelSpecs,u),m=(d.step??0)+1,f=m+(t.recursionLimit??25)+1,g={...u.channel_versions},y=e.store?new fs(e.store):void 0;return y&&y.start(),new _i({input:e.input,config:t,checkpointer:e.checkpointer,checkpoint:u,checkpointMetadata:d,checkpointConfig:i,prevCheckpointConfig:l,checkpointNamespace:o,channels:p,managed:e.managed,isNested:a,manager:e.manager,skipDoneTasks:n,step:m,stop:f,checkpointPreviousVersions:g,checkpointPendingWrites:h,outputKeys:e.outputKeys??[],streamKeys:e.streamKeys??[],nodes:e.nodes,stream:r,store:y,interruptAfter:e.interruptAfter,interruptBefore:e.interruptBefore,debug:e.debug})}_checkpointerPutAfterPrevious(e){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then((()=>this.checkpointer?.put(e.config,e.checkpoint,e.metadata,e.newVersions))),this.checkpointerPromises.push(this._checkpointerChainedPromise)}async updateManagedValues(e,t){const r=this.managed.get(e);r&&"update"in r&&"function"==typeof r.update&&await r.update(t)}putWrites(e,t){let r=t;if(0===r.length)return;r.every((([e])=>e in hs))&&(r=Array.from(new Map(r.map((e=>[e[0],e]))).values()));for(const[t,n]of r){const r=this.checkpointPendingWrites.findIndex((r=>r[0]===e&&r[1]===t));t in hs&&-1!==r?this.checkpointPendingWrites[r]=[e,t,n]:this.checkpointPendingWrites.push([e,t,n])}const n=this.checkpointer?.putWrites({...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_ns:this.config.configurable?.checkpoint_ns??"",checkpoint_id:this.checkpoint.id}},r,e);void 0!==n&&this.checkpointerPromises.push(n),this.tasks&&this._outputWrites(e,r)}_outputWrites(e,t,r=!1){const n=this.tasks[e];if(void 0!==n){if(void 0!==n.config&&(n.config.tags??[]).includes(aa))return;t.length>0&&t[0][0]!==zs&&t[0][0]!==Qs&&this._emit(Pa(Ta(Wa(this.outputKeys,[[n,t]],r),"updates"))),r||this._emit(Pa(Ta(function*(e,t,r){const n=(new Date).toISOString();for(const[{id:s,name:a,config:i},o]of t)i?.tags?.includes(aa)||(yield{type:"task_result",timestamp:n,step:e,payload:{id:s,name:a,result:o.filter((([e])=>Array.isArray(r)?r.includes(e):e===r)),interrupts:o.filter((e=>e[0]===Qs)).map((e=>e[1]))}})}(this.step,[[n,t]],this.streamKeys),"debug")))}}async tick(e){this.store&&!this.store.isRunning&&this.store?.start();const{inputKeys:t=[]}=e;if("pending"!==this.status)throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if([wi,vi].includes(this.input)){if(this.toInterrupt.length>0)throw this.status="interrupt_before",new vs;if(!Object.values(this.tasks).every((e=>e.writes.length>0)))return!1;{const e=Object.values(this.tasks).flatMap((e=>e.writes)),t=pi(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion);for(const[e,r]of Object.entries(t))await this.updateManagedValues(e,r);const r=await Ca(Ta(Ka(this.outputKeys,e,this.channels),"values"));if(this._emit(r),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop",writes:Wa(this.outputKeys,Object.values(this.tasks).map((e=>[e,e.writes]))).next().value??null}),li(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new vs;void 0!==this.config.configurable?.[Ws]&&delete this.config.configurable?.[Ws]}}else await this._first(t);if(this.step>this.stop)return this.status="out_of_steps",!1;const r=mi(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.managed,this.config,!0,{step:this.step,checkpointer:this.checkpointer,isResuming:this.isResuming,manager:this.manager,store:this.store,stream:this.stream});if(this.tasks=r,this.checkpointer&&this._emit(await Ca(Ta(function*(e,t,r,n,s,a,i,o){function c(e){const t={};return null!=e.callbacks&&(t.callbacks=e.callbacks),null!=e.configurable&&(t.configurable=e.configurable),null!=e.maxConcurrency&&(t.max_concurrency=e.maxConcurrency),null!=e.metadata&&(t.metadata=e.metadata),null!=e.recursionLimit&&(t.recursion_limit=e.recursionLimit),null!=e.runId&&(t.run_id=e.runId),null!=e.runName&&(t.run_name=e.runName),null!=e.tags&&(t.tags=e.tags),t}const l=t.configurable?.checkpoint_ns,u={};for(const e of a){if(!(e.subgraphs?.length?e.subgraphs:[e.proc]).find(Va))continue;let r=`${e.name}:${e.id}`;l&&(r=`${l}|${r}`),u[e.id]={configurable:{thread_id:t.configurable?.thread_id,checkpoint_ns:r}}}const d=(new Date).toISOString();yield{type:"checkpoint",timestamp:d,step:e,payload:{config:c(t),values:Ba(r,n),metadata:s,next:a.map((e=>e.name)),tasks:Qa(a,i,u),parentConfig:o?c(o):void 0}}}(this.step-1,this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig),"debug"))),0===Object.values(this.tasks).length)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(const[e,t,r]of this.checkpointPendingWrites){if(t===zs||t===Qs||t===ea)continue;const n=Object.values(this.tasks).find((t=>t.id===e));n&&n.writes.push([t,r])}for(const e of Object.values(this.tasks))e.writes.length>0&&this._outputWrites(e.id,e.writes,!0)}if(Object.values(this.tasks).every((e=>e.writes.length>0)))return this.tick({inputKeys:t});if(li(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new vs;const n=await Ca(Ta(Ya(this.step,Object.values(this.tasks)),"debug"));return this._emit(n),!0}async finishAndHandleError(e){const t=this._suppressInterrupt(e);if((t||void 0===e)&&(this.output=Ba(this.channels,this.outputKeys)),t){if(void 0!==this.tasks&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some((e=>e.writes.length>0))){const e=pi(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion);for(const[t,r]of Object.entries(e))await this.updateManagedValues(t,r);this._emit(Pa(Ta(Ka(this.outputKeys,Object.values(this.tasks).flatMap((e=>e.writes)),this.channels),"values")))}this._emit([["updates",{[Qs]:e.interrupts}]])}return t}acceptPush(e,t,r){if(this.interruptAfter?.length>0&&li(this.checkpoint,this.interruptAfter,[e]))return void this.toInterrupt.push(e);const n=fi([ca,e.path??[],t,e.id,r],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.managed,e.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});return n?this.interruptBefore?.length>0&&li(this.checkpoint,this.interruptBefore,[n])?void this.toInterrupt.push(n):(this._emit(Pa(Ta(Ya(this.step,[n]),"debug"))),this.debug&&ei(this.step,[n]),this.tasks[n.id]=n,this.skipDoneTasks&&this._matchWrites({[n.id]:n}),n):void 0}_suppressInterrupt(e){return xs(e)&&!this.isNested}async _first(e){const{configurable:t}=this.config,r=t?.[Gs];if(r&&void 0!==r.nullResume&&this.putWrites(ua,[[ea,r.nullResume]]),ba(this.input)){if(null!=this.input.resume&&null==this.checkpointer)throw new Error("Cannot use Command(resume=...) without checkpointer");const e={};for(const[t,r,n]of function*(e,t){if(e.graph===ya.PARENT)throw new Ps("There is no parent graph.");if(e.goto){let t;t=Array.isArray(e.goto)?e.goto:[e.goto];for(const e of t)if(ga(e))yield[ua,oa,e];else{if("string"!=typeof e)throw new Error("In Command.send, expected Send or string, got "+typeof e);yield[ua,`branch:__start__:${ia}:${e}`,"__start__"]}}if(e.resume)if("object"==typeof e.resume&&Object.keys(e.resume).length&&Object.keys(e.resume).every($s))for(const[r,n]of Object.entries(e.resume)){const e=t.filter((e=>e[0]===r&&e[1]===ea)).map((e=>e[2])).slice(0,1)??[];e.push(n),yield[r,ea,e]}else yield[ua,ea,e.resume];if(e.update){if("object"!=typeof e.update||!e.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(e.update))for(const[t,r]of e.update)yield[ua,t,r];else for(const[t,r]of Object.entries(e.update))yield[ua,t,r]}}(this.input,this.checkpointPendingWrites))void 0===e[t]&&(e[t]=[]),e[t].push([r,n]);if(0===Object.keys(e).length)throw new Ts("Received empty Command input");for(const[t,r]of Object.entries(e))this.putWrites(t,r)}const n=(this.checkpointPendingWrites??[]).filter((e=>e[0]===ua)).map((e=>e.slice(1)));n.length>0&&pi(this.checkpoint,this.channels,[{name:Ds,writes:n,triggers:[]}],this.checkpointerGetNextVersion);const s=ba(this.input)&&n.length>0;if(this.isResuming||s){for(const e of Object.keys(this.channels))if(void 0!==this.checkpoint.channel_versions[e]){const t=this.checkpoint.channel_versions[e];this.checkpoint.versions_seen[Qs]={...this.checkpoint.versions_seen[Qs],[e]:t}}const e=await Ca(Ta(Ka(this.outputKeys,!0,this.channels),"values"));this._emit(e)}if(this.isResuming)this.input=vi;else if(s)await this._putCheckpoint({source:"input",writes:{}}),this.input=wi;else{const t=await Ca(qa(e,this.input));if(t.length>0){const e=mi(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.managed,this.config,!0,{step:this.step});pi(this.checkpoint,this.channels,Object.values(e).concat([{name:Ds,writes:t,triggers:[]}]),this.checkpointerGetNextVersion),await this._putCheckpoint({source:"input",writes:Object.fromEntries(t)}),this.input=wi}else{if(!(Ws in(this.config.configurable??{})))throw new Ts(`Received no input writes for ${JSON.stringify(e,null,2)}`);this.input=wi}}this.isNested||(this.config=ai(this.config,{[Ws]:this.isResuming}))}_emit(e){for(const t of e)this.stream.modes.has(t[0])&&this.stream.push([this.checkpointNamespace,...t])}async _putCheckpoint(e){const t={...e,step:this.step,parents:this.config.configurable?.[Xs]??{}};if(void 0!==this.checkpointer){this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointMetadata=t,this.checkpoint=Rs(this.checkpoint,this.channels,this.step),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_ns:this.config.configurable?.checkpoint_ns??""}};const e={...this.checkpoint.channel_versions},r=si(this.checkpointPreviousVersions,e);this.checkpointPreviousVersions=e,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:ls(this.checkpoint),metadata:{...this.checkpointMetadata},newVersions:r}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}}this.step+=1}_matchWrites(e){for(const[t,r,n]of this.checkpointPendingWrites){if(r===zs||r===Qs||r===ea)continue;const s=Object.values(e).find((e=>e.id===t));s&&s.writes.push([r,n])}for(const t of Object.values(e))t.writes.length>0&&this._outputWrites(t.id,t.writes,!0)}}class ki{constructor(e,t){Object.defineProperty(this,"runtime",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_promises",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"lg_is_managed_value",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.config=e}static async initialize(e,t){throw new Error("Not implemented")}async promises(){return Promise.all(this._promises)}addPromise(e){this._promises.push(e)}}class Si extends Map{constructor(e){super(e?Array.from(e):void 0)}replaceRuntimeValues(e,t){if(0!==this.size&&t&&!Array.from(this.values()).every((e=>!e.runtime)))if("object"!=typeof t||Array.isArray(t)){if("object"==typeof t&&"constructor"in t)for(const r of Object.getOwnPropertyNames(Object.getPrototypeOf(t)))try{const n=t[r];for(const[s,a]of this.entries())a.runtime&&a.call(e)===n&&(t[r]={[sa]:s})}catch(e){if(e.name!==TypeError.name)throw e}}else for(const[r,n]of Object.entries(t))for(const[s,a]of this.entries())a.runtime&&a.call(e)===n&&(t[r]={[sa]:s})}replaceRuntimePlaceholders(e,t){if(0!==this.size&&t&&!Array.from(this.values()).every((e=>!e.runtime)))if("object"!=typeof t||Array.isArray(t)){if("object"==typeof t&&"constructor"in t)for(const r of Object.getOwnPropertyNames(Object.getPrototypeOf(t)))try{const n=t[r];if("object"==typeof n&&null!==n&&sa in n){const s=this.get(n[sa]);s&&(t[r]=s.call(e))}}catch(e){if(e.name!==TypeError.name)throw e}}else for(const[r,n]of Object.entries(t))if("object"==typeof n&&null!==n&&sa in n){const s=n[sa];"string"==typeof s&&(t[r]=this.get(s)?.call(e))}}}function Ei(e){return!!("object"==typeof e&&e&&"cls"in e&&"params"in e)}class xi extends ki{call(){}static async initialize(e,t){return Promise.resolve(new xi(e))}}class Ti extends Ze.BaseCallbackHandler{constructor(e){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"StreamMessagesHandler"}),Object.defineProperty(this,"streamFn",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadatas",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"seen",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"emittedChatModelRunIds",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"stableMessageIdMap",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.streamFn=e}_emit(e,t,r,n=!1){if(n&&void 0!==t.id&&void 0!==this.seen[t.id])return;let s=t.id;(0,se.isToolMessage)(t)?s??=`run-${r}-tool-${t.tool_call_id}`:(null!=s&&s!==`run-${r}`||(s=this.stableMessageIdMap[r]??s??`run-${r}`),this.stableMessageIdMap[r]??=s),s!==t.id&&(t.id=s,t.lc_kwargs.id=s),null!=t.id&&(this.seen[t.id]=t),this.streamFn([e[0],"messages",[t,e[1]]])}handleChatModelStart(e,t,r,n,s,a,i,o){!i||a&&(a.includes("langsmith:nostream")||a.includes("nostream"))||(this.metadatas[r]=[i.langgraph_checkpoint_ns.split("|"),{tags:a,name:o,...i}])}handleLLMNewToken(e,t,r,n,s,a){const i=a?.chunk;var o;this.emittedChatModelRunIds[r]=!0,void 0!==this.metadatas[r]&&(o=i,(0,se.isBaseMessage)(o?.message)?this._emit(this.metadatas[r],i.message,r):this._emit(this.metadatas[r],new se.AIMessageChunk({content:e}),r))}handleLLMEnd(e,t){if(!this.emittedChatModelRunIds[t]){const r=e.generations?.[0]?.[0];(0,se.isBaseMessage)(r?.message)&&this._emit(this.metadatas[t],r?.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,r,n,s,a,i,o){if(void 0!==a&&o===a.langgraph_node&&(void 0===s||!s.includes(aa))&&(this.metadatas[r]=[a.langgraph_checkpoint_ns.split("|"),{tags:s,name:o,...a}],"object"==typeof t))for(const e of Object.values(t))if(((0,se.isBaseMessage)(e)||(0,se.isBaseMessageChunk)(e))&&void 0!==e.id)this.seen[e.id]=e;else if(Array.isArray(e))for(const t of e)((0,se.isBaseMessage)(t)||(0,se.isBaseMessageChunk)(t))&&void 0!==t.id&&(this.seen[t.id]=t)}handleChainEnd(e,t){const r=this.metadatas[t];if(delete this.metadatas[t],void 0!==r)if((0,se.isBaseMessage)(e))this._emit(r,e,t,!0);else if(Array.isArray(e))for(const n of e)(0,se.isBaseMessage)(n)&&this._emit(r,n,t,!0);else if(null!=e&&"object"==typeof e)for(const n of Object.values(e))if((0,se.isBaseMessage)(n))this._emit(r,n,t,!0);else if(Array.isArray(n))for(const e of n)(0,se.isBaseMessage)(e)&&this._emit(r,e,t,!0)}handleChainError(e,t){delete this.metadatas[t]}}const Ci=[400,401,402,403,404,405,406,407,409],Pi=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||"AbortError"===e.name)return!1;if("ECONNABORTED"===e?.code)return!1;const t=e?.response?.status??e?.status;return(!t||!Ci.includes(+t))&&"insufficient_quota"!==e?.error?.code};async function Oi(e,t,r,n){const s=e.retry_policy??t;let a,i,o=void 0!==s?s.initialInterval??500:0,c=0,{config:l}=e;for(r&&(l=ai(l,r)),l={...l,signal:n};!n?.aborted;){e.writes.splice(0,e.writes.length),a=void 0;try{i=await e.proc.invoke(e.input,l);break}catch(t){if(a=t,a.pregelTaskId=e.id,Ss(a)){const t=l?.configurable?.checkpoint_ns,r=a.command;if(r.graph===t){for(const t of e.writers)await t.invoke(r,l);a=void 0;break}if(r.graph===ya.PARENT){const e=Ea(t);a.command=new ya({...a.command,graph:e})}}if(Es(a))break;if(void 0===s)break;if(c+=1,c>=(s.maxAttempts??3))break;if(!(s.retryOn??Pi)(a))break;o=Math.min(s.maxInterval??128e3,o*(s.backoffFactor??2));const r=s.jitter?Math.floor(o+1e3*Math.random()):o;await new Promise((e=>setTimeout(e,r)));const n=a.name??a.constructor.unminifiable_name??a.constructor.name;(s?.logWarning??1)&&console.log(`Retrying task "${String(e.name)}" after ${o.toFixed(2)}ms (attempt ${c}) after ${n}: ${a}`),l=ai(l,{[Ws]:!0})}}return{task:e,result:i,error:a,signalAborted:n?.aborted}}class Ai{constructor({loop:e,nodeFinished:t}){Object.defineProperty(this,"nodeFinished",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"loop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.loop=e,this.nodeFinished=t}async tick(e={}){const{timeout:t,retryPolicy:r,onStepWrite:n,maxConcurrency:s}=e,a=new Set;let i;const o=new AbortController,c=Object.values(this.loop.tasks).filter((e=>0===e.writes.length)),l=this._initializeAbortSignals({exceptionSignalController:o,timeout:t,signal:e.signal}),u=this._executeTasksWithRetry(c,{signals:l,retryPolicy:r,maxConcurrency:s});for await(const{task:e,error:t,signalAborted:r}of u)this._commit(e,t),xs(t)||Es(t)&&!xs(i)?i=t:!t||0!==a.size&&r||(o.abort(),a.add(t));if(n?.(this.loop.step,Object.values(this.loop.tasks).map((e=>e.writes)).flat()),1===a.size)throw Array.from(a)[0];if(a.size>1)throw new AggregateError(Array.from(a),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(xs(i))throw i;if(Es(i)&&this.loop.isNested)throw i}_initializeAbortSignals({exceptionSignalController:e,timeout:t,signal:r}){const n=this.loop.config.configurable?.[Ys]??{},s=r&&n.composedAbortSignal&&r!==n.composedAbortSignal?oi(n.externalAbortSignal,r):n.externalAbortSignal??r,a=n.errorAbortSignal?oi(n.errorAbortSignal,e.signal):e.signal,i=t?AbortSignal.timeout(t):void 0,o={externalAbortSignal:s,errorAbortSignal:a,timeoutAbortSignal:i,composedAbortSignal:oi(...s?[s]:[],...i?[i]:[],a)};return this.loop.config=ai(this.loop.config,{[Ys]:o}),o}async*_executeTasksWithRetry(e,t){const{retryPolicy:r,maxConcurrency:n,signals:s}=t??{},a=Symbol.for("promiseAdded");let i,o;o=new Promise((function e(t){i=()=>{o=new Promise(e),t(a)}}));const c={};function l(e,t,n,{calls:s}={}){if(n.every((([e])=>e!==ca)))return t.config?.configurable?.[Us]?.(n)??[];const a=t.config?.configurable?.[Gs];if(!a)throw new Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);const o={};for(const[d,h]of n.entries()){const[n]=h;if(n!==ca)continue;const p=s?.[d],m=a.callCounter;if(a.callCounter+=1,null==p)throw new Error("BUG: No call found");const f=e.loop.acceptPush(t,m,p);if(!f)continue;const g=c[f.id];if(void 0!==g)o[d]=g;else if(f.writes.length>0){const e=f.writes.filter((([e])=>e===ra)),t=f.writes.filter((([e])=>e===zs));if(e.length>0){if(1!==e.length)throw new Error(`BUG: multiple returns found for task ${f.name}__${f.id}`);o[d]=Promise.resolve(e[0][1])}else if(t.length>0){if(1!==t.length)throw new Error(`BUG: multiple errors found for task ${f.name}__${f.id}`);{const e=t[0][1],r=e instanceof Error?e:new Error(String(e));o[d]=Promise.reject(r)}}}else{const t=Oi(f,r,{[Us]:l.bind(null,e,f),[Bs]:u.bind(null,e,f)});c[f.id]=t,i(),o[d]=t.then((({result:e,error:t})=>t?Promise.reject(t):e))}}return Object.values(o)}function u(e,t,r,n,s,a={}){const i=l(e,t,[[ca,null]],{calls:[new ri({func:r,name:n,input:s,retry:a.retry,callbacks:a.callbacks})]});return void 0!==i?1===i.length?i[0]:Promise.all(i):Promise.resolve()}if(s?.composedAbortSignal?.aborted)throw new Error("Abort");let d,h=0;const p=s?.externalAbortSignal||s?.timeoutAbortSignal?oi(...s.externalAbortSignal?[s.externalAbortSignal]:[],...s.timeoutAbortSignal?[s.timeoutAbortSignal]:[]):void 0,m=p?new Promise(((e,t)=>{d=()=>t(new Error("Abort")),p.addEventListener("abort",d,{once:!0})})):void 0;for(;(0===h||Object.keys(c).length>0)&&e.length;){for(;Object.values(c).length<(n??e.length)&&h({task:t,error:e,signalAborted:s?.composedAbortSignal?.aborted})))}const t=await Promise.race([...Object.values(c),...m?[m]:[],o]);t!==a&&(yield t,delete c[t.task.id])}}_commit(e,t){if(void 0!==t)if(xs(t)){if(t.interrupts.length){const r=t.interrupts.map((e=>[Qs,e])),n=e.writes.filter((e=>e[0]===ea));n.length&&r.push(...n),this.loop.putWrites(e.id,r)}}else Es(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):this.loop.putWrites(e.id,[[zs,{message:t.message,name:t.name}]]);else!this.nodeFinished||null!=e.config?.tags&&e.config.tags.includes(aa)||this.nodeFinished(String(e.name)),0===e.writes.length&&e.writes.push([ta,null]),this.loop.putWrites(e.id,e.writes)}}class Ii{static subscribeTo(e,t){const{key:r,tags:n}={key:void 0,tags:void 0,...t??{}};if(Array.isArray(e)&&void 0!==r)throw new Error("Can't specify a key when subscribing to multiple channels");let s;s=function(e){return"string"==typeof e}(e)?r?{[r]:e}:[e]:Object.fromEntries(e.map((e=>[e,e])));const a=Array.isArray(e)?e:[e];return new Fa({channels:s,triggers:a,tags:n})}static writeTo(e,t){const r=[];for(const t of e)r.push({channel:t,value:Aa,skipNone:!1});for(const[e,n]of Object.entries(t??{}))Y.YN.isRunnable(n)||"function"==typeof n?r.push({channel:e,value:Aa,skipNone:!0,mapper:(0,Y.Bp)(n)}):r.push({channel:e,value:n,skipNone:!1});return new Ra(r)}}class Mi extends Y.YN{static lc_name(){return"LangGraph"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langgraph","pregel"]}),Object.defineProperty(this,"lg_is_pregel",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"channels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputChannels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputChannels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoValidate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"streamMode",{enumerable:!0,configurable:!0,writable:!0,value:["values"]}),Object.defineProperty(this,"streamChannels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"interruptAfter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"interruptBefore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stepTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"checkpointer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"retryPolicy",{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,"store",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let{streamMode:t}=e;null==t||Array.isArray(t)||(t=[t]),this.nodes=e.nodes,this.channels=e.channels,this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.name=e.name,this.autoValidate&&this.validate()}withConfig(e){const t=(0,Q.SV)(this.config,e);return new this.constructor({...this,config:t})}validate(){return function({nodes:e,channels:t,inputChannels:r,outputChannels:n,streamChannels:s,interruptAfterNodes:a,interruptBeforeNodes:i}){if(!t)throw new Da("Channels not provided");const o=new Set,c=new Set;for(const[t,r]of Object.entries(e)){if(t===Qs)throw new Da(`"Node name ${Qs} is reserved"`);if(r.constructor!==Fa)throw new Da(`Invalid node type ${typeof r}, expected PregelNode`);r.triggers.forEach((e=>o.add(e)))}for(const e of o)if(!(e in t))throw new Da(`Subcribed channel '${String(e)}' not in channels`);if(Array.isArray(r)){if(r.every((e=>!o.has(e))))throw new Da(`None of the input channels ${r} are subscribed to by any node`)}else if(!o.has(r))throw new Da(`Input channel ${String(r)} is not subscribed to by any node`);Array.isArray(n)?n.forEach((e=>c.add(e))):c.add(n),s&&!Array.isArray(s)?c.add(s):Array.isArray(s)&&s.forEach((e=>c.add(e)));for(const e of c)if(!(e in t))throw new Da(`Output channel '${String(e)}' not in channels`);if(a&&"*"!==a)for(const t of a)if(!(t in e))throw new Da(`Node ${String(t)} not in nodes`);if(i&&"*"!==i)for(const t of i)if(!(t in e))throw new Da(`Node ${String(t)} not in nodes`)}({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore}),this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(e){return this.getGraph(e)}*getSubgraphs(e,t){for(const[r,n]of Object.entries(this.nodes)){if(void 0!==e&&!e.startsWith(r))continue;const s=n.subgraphs?.length?n.subgraphs:[n.bound];for(const n of s){const s=Va(n);if(void 0!==s){if(r===e)return void(yield[r,s]);if(void 0===e&&(yield[r,s]),t){let n=e;void 0!==e&&(n=e.slice(r.length+1));for(const[e,a]of s.getSubgraphs(n,t))yield[`${r}${ha}${e}`,a]}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}async _prepareStateSnapshot({config:e,saved:t,subgraphCheckpointer:r,applyPendingWrites:n=!1}){if(void 0===t)return{values:{},next:[],config:e,tasks:[]};const{managed:s}=await this.prepareSpecs(e,{skipManaged:!0}),a=Ms(this.channels,t.checkpoint);if(t.pendingWrites?.length){const e=t.pendingWrites.filter((([e,t])=>e===ua)).map((([e,t,r])=>[String(t),r]));e.length>0&&pi(t.checkpoint,a,[{name:Ds,writes:e,triggers:[]}])}const i=Object.values(mi(t.checkpoint,t.pendingWrites,this.nodes,a,s,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),o=await Ca(this.getSubgraphsAsync()),c=t.config.configurable?.checkpoint_ns??"",l={};for(const e of i){const n=o.find((([t])=>t===e.name));if(!n)continue;let s=`${String(e.name)}${pa}${e.id}`;if(c&&(s=`${c}${ha}${s}`),void 0===r){const r={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:s}};l[e.id]=r}else{const a={configurable:{[Ks]:r,thread_id:t.config.configurable?.thread_id,checkpoint_ns:s}},i=n[1];l[e.id]=await i.getState(a,{subgraphs:!0})}}if(n&&t.pendingWrites?.length){const e=Object.fromEntries(i.map((e=>[e.id,e])));for(const[r,n,s]of t.pendingWrites)[zs,Qs,Me].includes(n)||r in e&&e[r].writes.push([String(n),s]);const r=i.filter((e=>e.writes.length>0));r.length>0&&pi(t.checkpoint,a,r)}let u=t?.metadata;u&&t?.config?.configurable?.thread_id&&(u={...u,thread_id:t.config.configurable.thread_id});const d=i.filter((e=>0===e.writes.length)).map((e=>e.name));return{values:Ba(a,this.streamChannelsAsIs),next:d,tasks:Qa(i,t?.pendingWrites??[],l),metadata:u,config:ii(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){const r=e.configurable?.[Ks]??this.checkpointer;if(!r)throw new ws("No checkpointer set");const n=e.configurable?.checkpoint_ns??"";if(""!==n&&void 0===e.configurable?.[Ks]){const s=Sa(n);for await(const[n,a]of this.getSubgraphsAsync(s,!0))if(n===s)return await a.getState(Oa(e,{[Ks]:r}),{subgraphs:t?.subgraphs});throw new Error(`Subgraph with namespace "${s}" not found.`)}const s=(0,Q.SV)(this.config,e),a=await r.getTuple(e);return await this._prepareStateSnapshot({config:s,saved:a,subgraphCheckpointer:t?.subgraphs?r:void 0,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){const r=e.configurable?.[Ks]??this.checkpointer;if(!r)throw new Error("No checkpointer set");const n=e.configurable?.checkpoint_ns??"";if(""!==n&&void 0===e.configurable?.[Ks]){const s=Sa(n);for await(const[n,a]of this.getSubgraphsAsync(s,!0))if(n===s)return void(yield*a.getStateHistory(Oa(e,{[Ks]:r}),t));throw new Error(`Subgraph with namespace "${s}" not found.`)}const s=(0,Q.SV)(this.config,e,{configurable:{checkpoint_ns:n}});for await(const e of r.list(s,t))yield this._prepareStateSnapshot({config:e.config,saved:e})}async bulkUpdateState(e,t){const r=e.configurable?.[Ks]??this.checkpointer;if(!r)throw new ws("No checkpointer set");if(0===t.length)throw new Error("No supersteps provided");if(t.some((e=>0===e.updates.length)))throw new Error("No updates provided");const n=e.configurable?.checkpoint_ns??"";if(""!==n&&void 0===e.configurable?.[Ks]){const s=Sa(n);for await(const[,n]of this.getSubgraphsAsync(s,!0))return await n.bulkUpdateState(Oa(e,{[Ks]:r}),t);throw new Error(`Subgraph "${s}" not found`)}const s=async(e,t)=>{const n=this.config?(0,Q.SV)(this.config,e):e,s=await r.getTuple(n),a=void 0!==s?ls(s.checkpoint):cs(),i={...s?.checkpoint.channel_versions},o=s?.metadata?.step??-1;let c=Oa(n,{checkpoint_ns:n.configurable?.checkpoint_ns??""}),l=n.metadata??{};s?.config.configurable&&(c=Oa(n,s.config.configurable),l={...s.metadata,...l});const{values:u,asNode:d}=t[0];if(null==u&&void 0===d){if(t.length>1)throw new Ps("Cannot create empty checkpoint with multiple updates");return ii(await r.put(c,Rs(a,void 0,o),{source:"update",step:o+1,writes:{},parents:s?.metadata?.parents??{}},{}),s?s.metadata:void 0)}const h=Ms(this.channels,a),{managed:p}=await this.prepareSpecs(n,{skipManaged:!0});if(null===u&&d===Fs){if(t.length>1)throw new Ps("Cannot apply multiple updates when clearing state");if(s){const e=mi(a,s.pendingWrites||[],this.nodes,h,p,s.config,!0,{step:(s.metadata?.step??-1)+1,checkpointer:this.checkpointer||void 0,store:this.store}),t=(s.pendingWrites||[]).filter((e=>e[0]===ua)).map((e=>e.slice(1)));t.length>0&&pi(s.checkpoint,h,[{name:Ds,writes:t,triggers:[]}]);for(const[t,r,n]of s.pendingWrites||[])[zs,Qs,Me].includes(r)||t in e&&e[t].writes.push([r,n]);pi(a,h,Object.values(e))}return ii(await r.put(c,Rs(a,void 0,o),{...l,source:"update",step:o+1,writes:{},parents:s?.metadata?.parents??{}},{}),s?s.metadata:void 0)}if(null==u&&"__copy__"===d){if(t.length>1)throw new Ps("Cannot copy checkpoint with multiple updates");return ii(await r.put(s?.parentConfig??c,Rs(a,void 0,o),{source:"fork",step:o+1,writes:{},parents:s?.metadata?.parents??{}},{}),s?s.metadata:void 0)}if(d===Ds){if(t.length>1)throw new Ps("Cannot apply multiple updates when updating as input");const e=await Ca(qa(this.inputChannels,u));if(0===e.length)throw new Ps(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);pi(a,h,[{name:Ds,writes:e,triggers:[]}],r.getNextVersion.bind(this.checkpointer));const n=null!=s?.metadata?.step?s.metadata.step+1:-1,o=await r.put(c,Rs(a,h,n),{source:"input",step:n,writes:Object.fromEntries(e),parents:s?.metadata?.parents??{}},si(i,a.channel_versions));return await r.putWrites(o,e,Ae(Ds,a.id)),ii(o,s?s.metadata:void 0)}if(void 0===n.configurable?.checkpoint_id&&void 0!==s?.pendingWrites&&s.pendingWrites.length>0){const e=mi(a,s.pendingWrites,this.nodes,h,p,s.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(s.metadata?.step??-1)+1}),t=(s.pendingWrites??[]).filter((e=>e[0]===ua)).map((e=>e.slice(1)));t.length>0&&pi(s.checkpoint,h,[{name:Ds,writes:t,triggers:[]}]);for(const[t,r,n]of s.pendingWrites)[zs,Qs,Me].includes(r)||void 0===e[t]||e[t].writes.push([r,n]);const r=Object.values(e).filter((e=>e.writes.length>0));r.length>0&&pi(a,h,r)}const m=Object.values(a.versions_seen).map((e=>Object.values(e))).flat().find((e=>!!e)),f=[];if(1===t.length){let{values:e,asNode:r}=t[0];if(void 0===r&&1===Object.keys(this.nodes).length)[r]=Object.keys(this.nodes);else if(void 0===r&&void 0===m)"string"==typeof this.inputChannels&&void 0!==this.nodes[this.inputChannels]&&(r=this.inputChannels);else if(void 0===r){const e=Object.entries(a.versions_seen).map((([e,t])=>Object.values(t).map((t=>[t,e])))).flat().sort((([e],[t])=>us(e,t)));e&&(1===e.length?r=e[0][1]:e[e.length-1][0]!==e[e.length-2][0]&&(r=e[e.length-1][1]))}if(void 0===r)throw new Ps('Ambiguous update, specify "asNode"');f.push({values:e,asNode:r})}else for(const{asNode:e,values:r}of t){if(null==e)throw new Ps('"asNode" is required when applying multiple updates');f.push({values:r,asNode:e})}const g=[];for(const{asNode:e,values:t}of f){if(void 0===this.nodes[e])throw new Ps(`Node "${e.toString()}" does not exist`);const r=this.nodes[e].getWriters();if(!r.length)throw new Ps(`No writers found for node "${e.toString()}"`);g.push({name:e,input:t,proc:r.length>1?Y.zZ.from(r,{omitSequenceTags:!0}):r[0],writes:[],triggers:[Qs],id:Ae(Qs,a.id),writers:[]})}for(const e of g)await e.proc.invoke(e.input,(0,Q.tn)({...n,store:n?.store??this.store},{runName:n.runName??`${this.getName()}UpdateState`,configurable:{[Us]:t=>e.writes.push(...t),[qs]:(t,r=!1)=>ui(o,a,h,p,e,t,r)}}));for(const e of g){const t=e.writes.filter((e=>e[0]!==ca));void 0!==s&&t.length>0&&await r.putWrites(c,t,e.id)}pi(a,h,g,r.getNextVersion.bind(this.checkpointer));const y=si(i,a.channel_versions),b=await r.put(c,Rs(a,h,o+1),{source:"update",step:o+1,writes:Object.fromEntries(f.map((e=>[e.asNode,e.values]))),parents:s?.metadata?.parents??{}},y);for(const e of g){const t=e.writes.filter((e=>e[0]===ca));t.length>0&&await r.putWrites(b,t,e.id)}return ii(b,s?s.metadata:void 0)};let a=e;for(const{updates:e}of t)a=await s(a,e);return a}async updateState(e,t,r){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:r}]}])}_defaults(e){const{debug:t,streamMode:r,inputKeys:n,outputKeys:s,interruptAfter:a,interruptBefore:i,...o}=e;let c=!0;const l=void 0!==t?t:this.debug;let u=s;void 0===u?u=this.streamChannelsAsIs:za(u,this.channels);let d=n;void 0===d?d=this.inputChannels:za(d,this.channels);const h=i??this.interruptBefore??[],p=a??this.interruptAfter??[];let m,f;void 0!==r?(m=Array.isArray(r)?r:[r],c="string"==typeof r):(m=this.streamMode,c=!0),void 0!==e.configurable?.[Hs]&&(m=["values"]),f=!1===this.checkpointer?void 0:void 0!==e&&void 0!==e.configurable?.[Ks]?e.configurable[Ks]:this.checkpointer;return[l,m,d,u,o,h,p,f,e.store??this.store,c]}async stream(e,t){const r=new AbortController,n={recursionLimit:this.config?.recursionLimit,...t,signal:t?.signal?oi(t.signal,r.signal):r.signal};return new yi(await super.stream(e,n),r)}streamEvents(e,t,r){const n=new AbortController,s={recursionLimit:this.config?.recursionLimit,callbacks:this.config?.callbacks,...t,signal:t?.signal?oi(t.signal,n.signal):n.signal};return new yi(super.streamEvents(e,s,r),n)}async prepareSpecs(e,t){const r={...e,store:this.store},n={},s={};for(const[e,r]of Object.entries(this.channels))As(r)?n[e]=r:s[e]=t?.skipManaged?{cls:xi,params:{config:{}}}:r;const a=new Si(await Object.entries(s).reduce((async(e,[t,n])=>{const s=await e;let a;return Ei(n)?("key"in n.params&&"__channel_key_placeholder__"===n.params.key&&(n.params.key=t),a=await n.cls.initialize(r,n.params)):a=await n.initialize(r),void 0!==a&&s.push([t,a]),s}),Promise.resolve([])));return{channelSpecs:n,managed:a}}async _validateInput(e){return e}async _validateConfigurable(e){return e}async*_streamIterator(e,t){const r=t?.subgraphs,n=ka(this.config,t);if(void 0===n.recursionLimit||n.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(void 0!==this.checkpointer&&!1!==this.checkpointer&&void 0===n.configurable)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');const s=await this._validateInput(e),{runId:a,...i}=n,[o,c,,l,u,d,h,p,m,f]=this._defaults(i);u.configurable=await this._validateConfigurable(u.configurable);const g=new bi({modes:new Set(c)});if(c.includes("messages")){const e=new Ti((e=>g.push(e))),{callbacks:t}=u;if(void 0===t)u.callbacks=[e];else if(Array.isArray(t))u.callbacks=t.concat(e);else{const r=t.copy();r.addHandler(e,!0),u.callbacks=r}}c.includes("custom")&&(u.writer=e=>g.push([[],"custom",e]));const y=await(0,Q.kJ)(u),b=await(y?.handleChainStart(this.toJSON(),function(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}(e,"input"),a,void 0,void 0,void 0,u?.runName??this.getName())),{channelSpecs:w,managed:v}=await this.prepareSpecs(u);let _,k;const S=(async()=>{try{_=await _i.initialize({input:s,config:u,checkpointer:p,nodes:this.nodes,channelSpecs:w,managed:v,outputKeys:l,streamKeys:this.streamChannelsAsIs,store:m,stream:g,interruptAfter:h,interruptBefore:d,manager:b,debug:this.debug});const e=new Ai({loop:_,nodeFinished:u.configurable?.__pregel_node_finished});t?.subgraphs&&(_.config.configurable={..._.config.configurable,[Vs]:_.stream}),await this._runLoop({loop:_,runner:e,debug:o,config:u})}catch(e){k=e}finally{try{_&&await(_.store?.stop()),await Promise.all([..._?.checkpointerPromises??[],...Array.from(v.values()).map((e=>e.promises()))])}catch(e){k=k??e}k?g.error(k):g.close()}})();try{for await(const e of g){if(void 0===e)throw new Error("Data structure error.");const[t,n,s]=e;c.includes(n)&&(r&&!f?yield[t,n,s]:f?r?yield[t,s]:yield s:yield[n,s])}}catch(e){throw await(b?.handleChainError(k)),e}finally{await S}await(b?.handleChainEnd(_?.output??{},a,void 0,void 0,void 0))}async invoke(e,t){const r=t?.streamMode??"values",n={...t,outputKeys:t?.outputKeys??this.outputChannels,streamMode:r},s=[],a=await this.stream(e,n);for await(const e of a)s.push(e);return"values"===r?s[s.length-1]:s}async _runLoop(e){const{loop:t,runner:r,debug:n,config:s}=e;let a;try{for(;await t.tick({inputKeys:this.inputChannels});)n&&(i=t.checkpointMetadata.step,o=t.channels,c=this.streamChannelsList,console.log([`${Xa(Ga,`[${i}:checkpoint]`)}`,` State at the end of step ${i}:\n`,JSON.stringify(Ba(o,c),null,2)].join(""))),n&&ei(t.step,Object.values(t.tasks)),await r.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(e,t)=>{n&&ti(e,t,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal});if("out_of_steps"===t.status)throw new bs([`Recursion limit of ${s.recursionLimit} reached`,"without hitting a stop condition. You can increase the",'limit by setting the "recursionLimit" config key.'].join(" "),{lc_error_code:"GRAPH_RECURSION_LIMIT"})}catch(e){a=e;if(!await t.finishAndHandleError(a))throw e}finally{void 0===a&&await t.finishAndHandleError()}var i,o,c}}class Ri extends Is{constructor(e,t){super(),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"BinaryOperatorAggregate"}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"operator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialValueFactory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.operator=e,this.initialValueFactory=t,this.value=t?.()}fromCheckpoint(e){const t=new Ri(this.operator,this.initialValueFactory);return e&&(t.value=e),t}update(e){let t=e;if(!t.length)return!1;void 0===this.value&&([this.value]=t,t=t.slice(1));for(const e of t)void 0!==this.value&&(this.value=this.operator(this.value,e));return!0}get(){if(void 0===this.value)throw new Cs;return this.value}checkpoint(){if(void 0===this.value)throw new Cs;return this.value}}class ji extends Is{constructor(e=!0){super(),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"EphemeralValue"}),Object.defineProperty(this,"guard",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.guard=e}fromCheckpoint(e){const t=new ji(this.guard);return e&&(t.value=[e]),t}update(e){if(0===e.length){const e=this.value.length>0;return this.value=[],e}if(1!==e.length&&this.guard)throw new Ps("EphemeralValue can only receive one value per step.");return this.value=[e[e.length-1]],!0}get(){if(0===this.value.length)throw new Cs;return this.value[0]}checkpoint(){if(0===this.value.length)throw new Cs;return this.value[0]}}class Ni{constructor(e){Object.defineProperty(this,"condition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ends",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Y.YN.isRunnable(e.path)?this.condition=e.path:this.condition=(0,Y.Bp)(e.path).withConfig({runName:"Branch"}),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce(((e,t)=>(e[t]=t,e)),{}):e.pathMap}run(e,t){return Ra.registerWriter(new xa({name:"",trace:!1,func:async(r,n)=>{try{return await this._route(r,n,e,t)}catch(e){throw e.name===_s.unminifiable_name&&console.warn("[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.\nNodeInterrupt should only be thrown inside a node, not in edge conditions."),e}}}))}async _route(e,t,r,n){let s,a=await this.condition.invoke(n?n(t):e,t);if(Array.isArray(a)||(a=[a]),s=this.ends?a.map((e=>ga(e)?e:this.ends[e])):a,s.some((e=>!e)))throw new Error("Branch condition returned unknown or null destination");if(s.filter(ga).some((e=>e.node===Fs)))throw new Ps("Cannot send a packet to the END node");return await r(s,t)??e}}class $i{constructor(){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"branches",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"entryPoint",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"compiled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(e){this.compiled&&console.warn(e)}get allEdges(){return this.edges}addNode(e,t,r){for(const t of[ha,pa])if(e.includes(t))throw new Error(`"${t}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),e in this.nodes)throw new Error(`Node \`${e}\` already present.`);if(e===Fs)throw new Error(`Node \`${e}\` is reserved.`);const n=(0,Y.Bp)(t);return this.nodes[e]={runnable:n,metadata:r?.metadata,subgraphs:Ha(n)?[n]:r?.subgraphs,ends:r?.ends},this}addEdge(e,t){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),e===Fs)throw new Error("END cannot be a start node");if(t===Ls)throw new Error("START cannot be an end node");if(Array.from(this.edges).some((([t])=>t===e))&&!("channels"in this))throw new Error(`Already found path for ${e}. For multiple edges, use StateGraph.`);return this.edges.add([e,t]),this}addConditionalEdges(e,t,r){const n="object"==typeof e?e:{source:e,path:t,pathMap:r};if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),!Y.YN.isRunnable(n.path)){const e=Array.isArray(n.pathMap)?n.pathMap.join(","):Object.keys(n.pathMap??{}).join(",");n.path=(0,Y.Bp)(n.path).withConfig({runName:`Branch<${n.source}${""!==e?`,${e}`:""}>`.slice(0,63)})}const s="RunnableLambda"===n.path.getName()?"condition":n.path.getName();if(this.branches[n.source]&&this.branches[n.source][s])throw new Error(`Condition \`${s}\` already present for node \`${e}\``);return this.branches[n.source]||(this.branches[n.source]={}),this.branches[n.source][s]=new Ni(n),this}setEntryPoint(e){return this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(Ls,e)}setFinishPoint(e){return this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(e,Fs)}compile({checkpointer:e,interruptBefore:t,interruptAfter:r,name:n}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(r)?r:[]]);const s=new Li({builder:this,checkpointer:e,interruptAfter:r,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[Ls]:new ji,[Fs]:new ji},inputChannels:Ls,outputChannels:Fs,streamChannels:[],streamMode:"values",name:n});for(const[e,t]of Object.entries(this.nodes))s.attachNode(e,t);for(const[e,t]of this.edges)s.attachEdge(e,t);for(const[e,t]of Object.entries(this.branches))for(const[r,n]of Object.entries(t))s.attachBranch(e,r,n);return s.validate()}validate(e){const t=new Set([...this.allEdges].map((([e,t])=>e)));for(const[e]of Object.entries(this.branches))t.add(e);for(const e of t)if(e!==Ls&&!(e in this.nodes))throw new Error(`Found edge starting at unknown node \`${e}\``);const r=new Set([...this.allEdges].map((([e,t])=>t)));for(const[e,t]of Object.entries(this.branches))for(const n of Object.values(t))if(n.ends)for(const e of Object.values(n.ends))r.add(e);else{r.add(Fs);for(const t of Object.keys(this.nodes))t!==e&&r.add(t)}for(const e of Object.values(this.nodes))for(const t of e.ends??[])r.add(t);for(const e of Object.keys(this.nodes))if(!r.has(e))throw new Os([`Node \`${e}\` is not reachable.`,"","If you are returning Command objects from your node,",'make sure you are passing names of potential destination nodes as an "ends" array','into ".addNode(..., { ends: ["node1", "node2"] })".'].join("\n"),{lc_error_code:"UNREACHABLE_NODE"});for(const e of r)if(e!==Fs&&!(e in this.nodes))throw new Error(`Found edge ending at unknown node \`${e}\``);if(e)for(const t of e)if(!(t in this.nodes))throw new Error(`Interrupt node \`${t}\` is not present`);this.compiled=!0}}class Li extends Mi{constructor({builder:e,...t}){super(t),Object.defineProperty(this,"builder",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.builder=e}attachNode(e,t){this.channels[e]=new ji,this.nodes[e]=new Fa({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new Ra([{channel:e,value:Aa}],[aa])),this.streamChannels.push(e)}attachEdge(e,t){if(t===Fs){if(e===Ls)throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new Ra([{channel:Fs,value:Aa}],[aa]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,r){e!==Ls||this.nodes[Ls]||(this.nodes[Ls]=Ii.subscribeTo(Ls,{tags:[aa]})),this.nodes[e].pipe(r.run((r=>{const n=r.map((r=>ga(r)?r:{channel:r===Fs?Fs:`branch:${e}:${t}:${r}`,value:Aa}));return new Ra(n,[aa])})));const n=r.ends?Object.values(r.ends):Object.keys(this.nodes);for(const r of n)if(r!==Fs){const n=`branch:${e}:${t}:${r}`;this.channels[n]=new ji,this.nodes[r].triggers.push(n),this.nodes[r].channels.push(n)}}async getGraphAsync(e){const t=e?.xray,r=new js.T,n={[Ls]:r.addNode({schema:M.z.any()},Ls)},s={};let a={};function i(e,t,a,i=!1){if(t===Fs&&void 0===s[Fs]&&(s[Fs]=r.addNode({schema:M.z.any()},Fs)),void 0!==n[e]){if(void 0===s[t])throw new Error(`End node ${t} not found!`);return r.addEdge(n[e],s[t],a!==t?a:void 0,i)}}t&&(a=Object.fromEntries((await Ca(this.getSubgraphsAsync())).filter((e=>Fi(e[1])))));for(const[c,l]of Object.entries(this.builder.nodes)){const u=Di(c),d=l.runnable,h=l.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?h.__interrupt="before,after":this.interruptBefore?.includes(c)?h.__interrupt="before":this.interruptAfter?.includes(c)&&(h.__interrupt="after"),t){const p="number"==typeof t?t-1:t,m=void 0!==a[c]?await a[c].getGraphAsync({...e,xray:p}):d.getGraph(e);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){const[f,g]=r.extend(m,u);if(void 0===f)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);function y(e,t){if(void 0!==e&&!$s(e))return e;if(!(r=t)||!r.lc_runnable)return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e,e}catch(e){return t.getName()}var r}void 0!==g&&(n[u]={name:y(g.id,g.data),...g}),s[u]={name:y(f.id,f.data),...f}}else{const b=r.addNode(d,u,h);n[u]=b,s[u]=b}}else{const w=r.addNode(d,u,h);n[u]=w,s[u]=w}}const o=[...this.builder.allEdges].sort((([e],[t])=>ee?1:0));for(const[v,_]of o)i(Di(v),Di(_));for(const[k,S]of Object.entries(this.builder.branches)){const E={...Object.fromEntries(Object.keys(this.builder.nodes).filter((e=>e!==k)).map((e=>[Di(e),Di(e)]))),[Fs]:Fs};for(const x of Object.values(S)){let T;T=void 0!==x.ends?x.ends:E;for(const[C,P]of Object.entries(T))i(Di(k),Di(P),C,!0)}}for(const[O,A]of Object.entries(this.builder.nodes))if(void 0!==A.ends)for(const I of A.ends)i(Di(O),Di(I),void 0,!0);return r}getGraph(e){const t=e?.xray,r=new js.T,n={[Ls]:r.addNode({schema:M.z.any()},Ls)},s={};let a={};function i(e,t,a,i=!1){return t===Fs&&void 0===s[Fs]&&(s[Fs]=r.addNode({schema:M.z.any()},Fs)),r.addEdge(n[e],s[t],a!==t?a:void 0,i)}t&&(a=Object.fromEntries(Pa(this.getSubgraphs()).filter((e=>Fi(e[1])))));for(const[c,l]of Object.entries(this.builder.nodes)){const u=Di(c),d=l.runnable,h=l.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?h.__interrupt="before,after":this.interruptBefore?.includes(c)?h.__interrupt="before":this.interruptAfter?.includes(c)&&(h.__interrupt="after"),t){const p="number"==typeof t?t-1:t,m=void 0!==a[c]?a[c].getGraph({...e,xray:p}):d.getGraph(e);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){const[f,g]=r.extend(m,u);if(void 0===f)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);function y(e,t){if(void 0!==e&&!$s(e))return e;if(!(r=t)||!r.lc_runnable)return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e,e}catch(e){return t.getName()}var r}void 0!==g&&(n[u]={name:y(g.id,g.data),...g}),s[u]={name:y(f.id,f.data),...f}}else{const b=r.addNode(d,u,h);n[u]=b,s[u]=b}}else{const w=r.addNode(d,u,h);n[u]=w,s[u]=w}}const o=[...this.builder.allEdges].sort((([e],[t])=>ee?1:0));for(const[v,_]of o)i(Di(v),Di(_));for(const[k,S]of Object.entries(this.builder.branches)){const E={...Object.fromEntries(Object.keys(this.builder.nodes).filter((e=>e!==k)).map((e=>[Di(e),Di(e)]))),[Fs]:Fs};for(const x of Object.values(S)){let T;T=void 0!==x.ends?x.ends:E;for(const[C,P]of Object.entries(T))i(Di(k),Di(P),C,!0)}}return r}}function Fi(e){return"function"==typeof e.attachNode&&"function"==typeof e.attachEdge}function Di(e){return"subgraph"===e?`"${e}"`:e}const zi=(e,t)=>e.size===t.size&&[...e].every((e=>t.has(e)));class Ui extends Is{constructor(e){super(),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"NamedBarrierValue"}),Object.defineProperty(this,"names",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"seen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.names=e,this.seen=new Set}fromCheckpoint(e){const t=new Ui(this.names);return e&&(t.seen=new Set(e)),t}update(e){let t=!1;for(const r of e){if(!this.names.has(r))throw new Ps(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);this.seen.has(r)||(this.seen.add(r),t=!0)}return t}get(){if(!zi(this.names,this.seen))throw new Cs}checkpoint(){return[...this.seen]}consume(){return!!(this.seen&&this.names&&zi(this.seen,this.names))&&(this.seen=new Set,!0)}}class Bi extends Is{constructor(){super(...arguments),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"LastValue"}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:[]})}fromCheckpoint(e){const t=new Bi;return e&&(t.value=[e]),t}update(e){if(0===e.length)return!1;if(1!==e.length)throw new Ps("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[e[e.length-1]],!0}get(){if(0===this.value.length)throw new Cs;return this.value[0]}checkpoint(){if(0===this.value.length)throw new Cs;return this.value[0]}}class qi{constructor(e){Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"AnnotationRoot"}),Object.defineProperty(this,"spec",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.spec=e}}const Ki=function(e){return Ei(e)?e:e?Wi(e):new Bi};function Wi(e){return"object"==typeof e&&e&&"reducer"in e&&e.reducer?new Ri(e.reducer,e.default):"object"==typeof e&&e&&"value"in e&&e.value?new Ri(e.value,e.default):new Bi}Ki.Root=e=>new qi(e);const Hi=new WeakMap;function Vi(e){return"object"==typeof e&&null!=e&&"_parse"in e&&"function"==typeof e._parse}function Gi(e){return Vi(e)&&"partial"in e&&"function"==typeof e.partial}function Ji(e){return Hi.get(e)}function Zi(e){const t={};for(const r in e.shape)if(Object.prototype.hasOwnProperty.call(e.shape,r)){const n=Ji(e.shape[r]);t[r]=n?.reducer?new Ri(n.reducer.fn,n.default):new Bi}return t}const Xi="__root__";class Yi extends $i{constructor(e,t){if(super(),Object.defineProperty(this,"channels",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"waitingEdges",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_schemaDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaRuntimeDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_inputDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_inputRuntimeDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_outputDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_outputRuntimeDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaDefinitions",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_configSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_configRuntimeSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),function(e){if("object"!=typeof e||null==e)return!1;if(!("state"in e)||!Gi(e.state))return!1;if("input"in e&&!Gi(e.input))return!1;if("output"in e&&!Gi(e.output))return!1;return!0}(e)){const t=Zi(e.state),r=null!=e.input?Zi(e.input):t,n=null!=e.output?Zi(e.output):t;this._schemaDefinition=t,this._schemaRuntimeDefinition=e.state,this._inputDefinition=r,this._inputRuntimeDefinition=e.input??e.state.partial(),this._outputDefinition=n,this._outputRuntimeDefinition=e.output??e.state}else if(Gi(e)){const t=Zi(e);this._schemaDefinition=t,this._schemaRuntimeDefinition=e,this._inputDefinition=t,this._inputRuntimeDefinition=e.partial(),this._outputDefinition=t,this._outputRuntimeDefinition=e}else if(function(e){return"object"==typeof e&&null!==e&&void 0===e.stateSchema&&void 0!==e.input&&void 0!==e.output}(e))this._schemaDefinition=e.input.spec,this._inputDefinition=e.input.spec,this._outputDefinition=e.output.spec;else if(function(e){return"object"==typeof e&&null!==e&&void 0!==e.stateSchema}(e))this._schemaDefinition=e.stateSchema.spec,this._inputDefinition=e.input?.spec??this._schemaDefinition,this._outputDefinition=e.output?.spec??this._schemaDefinition;else if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every((e=>"function"==typeof e||As(e)))}(e)||eo(e)){const t=eo(e)?e.spec:e;this._schemaDefinition=t}else{if(!function(e){return"object"==typeof e&&null!==e&&void 0!==e.channels}(e))throw new Error("Invalid StateGraph input.");{const t=function(e){const t={};for(const[r,n]of Object.entries(e))if(r===Xi)t[r]=Wi(n);else{t[r]=Wi(n)}return t}(e.channels);this._schemaDefinition=t}}this._inputDefinition??=this._schemaDefinition,this._outputDefinition??=this._schemaDefinition,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),Gi(t)&&(this._configRuntimeSchema=t.passthrough())}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap((([e,t])=>e.map((e=>[e,t]))))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(const[t,r]of Object.entries(e)){let e;if(e="function"==typeof r?r():r,void 0!==this.channels[t]){if(this.channels[t]!==e&&!Ei(e)&&"LastValue"!==e.lc_graph_name)throw new Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=e}}}addNode(e,t,r){if(e in this.channels)throw new Error(`${e} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(const t of[ha,pa])if(e.includes(t))throw new Error(`"${t}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),e in this.nodes)throw new Error(`Node \`${e}\` already present.`);if(e===Fs||e===Ls)throw new Error(`Node \`${e}\` is reserved.`);let n;void 0!==r?.input&&this._addSchema(r.input.spec),n=Y.YN.isRunnable(t)?t:"function"==typeof t?new xa({func:t,name:e,trace:!1}):(0,Y.Bp)(t);const s={runnable:n,retryPolicy:r?.retryPolicy,metadata:r?.metadata,input:r?.input?.spec??this._schemaDefinition,subgraphs:Ha(n)?[n]:r?.subgraphs,ends:r?.ends};return this.nodes[e]=s,this}addEdge(e,t){if("string"==typeof e)return super.addEdge(e,t);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(const t of e){if(t===Fs)throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some((e=>e===t)))throw new Error(`Need to add a node named "${t}" first`)}if(t===Fs)throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some((e=>e===t)))throw new Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}compile({checkpointer:e,store:t,interruptBefore:r,interruptAfter:n,name:s}={}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(n)?n:[]]);const a=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),i=1===a.length&&a[0]===Xi?Xi:a,o=Object.keys(this.channels),c=1===o.length&&o[0]===Xi?Xi:o,l=new Qi({builder:this,checkpointer:e,interruptAfter:n,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[Ls]:new ji},inputChannels:Ls,outputChannels:i,streamChannels:c,streamMode:"updates",store:t,name:s});l.attachNode(Ls);for(const[e,t]of Object.entries(this.nodes))l.attachNode(e,t);l.attachBranch(Ls,ia,ro(),{withReader:!1});for(const[e]of Object.entries(this.nodes))l.attachBranch(e,ia,ro(),{withReader:!1});for(const[e,t]of this.edges)l.attachEdge(e,t);for(const[e,t]of this.waitingEdges)l.attachEdge(e,t);for(const[e,t]of Object.entries(this.branches))for(const[r,n]of Object.entries(t))l.attachBranch(e,r,n);return l.validate()}}class Qi extends Li{attachNode(e,t){let r;r=e===Ls?Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).filter((([e,t])=>!Ei(t))).map((([e])=>e)):Object.keys(this.builder.channels);const n=e;const s=[{value:Aa,mapper:new xa({func:r.length&&r[0]===Xi?function(e){if(ba(e))return e.graph===ya.PARENT?null:e._updateAsTuples();if(Array.isArray(e)&&e.length>0&&e.some((e=>ba(e)))){const t=[];for(const r of e)if(ba(r)){if(r.graph===ya.PARENT)continue;t.push(...r._updateAsTuples())}else t.push([Xi,r]);return t}return null!=e?[[Xi,e]]:null}:function e(t){if(t){if(ba(t))return t.graph===ya.PARENT?null:t._updateAsTuples().filter((([e])=>r.includes(e)));if(Array.isArray(t)&&t.length>0&&t.some(ba)){const n=[];for(const s of t)if(ba(s)){if(s.graph===ya.PARENT)continue;n.push(...s._updateAsTuples().filter((([e])=>r.includes(e))))}else{const t=e(s);t&&n.push(...t??[])}return n}if("object"!=typeof t||Array.isArray(t)){const e=Array.isArray(t)?"array":typeof t;throw new Ps(`Expected node "${n.toString()}" to return an object or an array containing at least one Command object, received ${e}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}return Object.entries(t).filter((([e])=>r.includes(e)))}return null},trace:!1,recurse:!1})}];if(e===Ls)this.nodes[e]=new Fa({tags:[aa],triggers:[Ls],channels:[Ls],writers:[new Ra(s,[aa])]});else{const r=t?.input??this.builder._schemaDefinition,n=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(r)).map((e=>[e,e]))),a=1===Object.keys(n).length&&Xi in n;this.channels[e]=new ji(!1),this.nodes[e]=new Fa({triggers:[],channels:a?Object.keys(n):n,writers:[new Ra(s.concat({channel:e,value:e}),[aa])],mapper:a?void 0:e=>Object.fromEntries(Object.entries(e).filter((([e])=>e in n))),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,subgraphs:t?.subgraphs,ends:t?.ends})}}attachEdge(e,t){if(t!==Fs)if(Array.isArray(e)){const r=`join:${e.join("+")}:${t}`;this.channels[r]=new Ui(new Set(e)),this.nodes[t].triggers.push(r);for(const t of e)this.nodes[t].writers.push(new Ra([{channel:r,value:t}],[aa]))}else if(e===Ls){const e=`${Ls}:${t}`;this.channels[e]=new ji,this.nodes[t].triggers.push(e),this.nodes[Ls].writers.push(new Ra([{channel:e,value:Ls}],[aa]))}else this.nodes[t].triggers.push(e)}attachBranch(e,t,r,n={withReader:!0}){this.nodes[e].writers.push(r.run((async(r,n)=>{const s=r.filter((e=>e!==Fs));if(!s.length)return;const a=s.map((r=>ga(r)?r:{channel:`branch:${e}:${t}:${r}`,value:e}));await Ra.doWrite({...n,tags:(n.tags??[]).concat([aa])},a)}),n.withReader?e=>$a.doRead(e,this.streamChannels??this.outputChannels,!0):void 0));const s=r.ends?Object.values(r.ends):Object.keys(this.builder.nodes);for(const r of s){if(r===Fs)continue;const n=`branch:${e}:${t}:${r}`;this.channels[n]=new ji(!1),this.nodes[r].triggers.push(n)}}async _validateInput(e){const t=this.builder._inputRuntimeDefinition;if(ba(e)){const r=e;return e.update&&Gi(t)&&(r.update=t.parse(e.update)),r}return Gi(t)?t.parse(e):e}async _validateConfigurable(e){const t=this.builder._configRuntimeSchema;return Gi(t)&&t.parse(e),e}}function eo(e){return"object"==typeof e&&null!==e&&"lc_graph_name"in e&&"AnnotationRoot"===e.lc_graph_name}function to(e){if(ga(e))return[e];const t=[];ba(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(ba));const r=[];for(const e of t){if(e.graph===ya.PARENT)throw new ks(e);ga(e.goto)||"string"==typeof e.goto?r.push(e.goto):Array.isArray(e.goto)&&r.push(...e.goto)}return r}function ro(){const e=new xa({func:to,tags:[aa],trace:!1,recurse:!1,name:""});return new Ni({path:e})}const no={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};var so,ao=new Uint8Array(16);function io(){if(!so&&!(so="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return so(ao)}for(var oo=[],co=0;co<256;++co)oo.push((co+256).toString(16).slice(1));function lo(e,t=0){return(oo[e[t+0]]+oo[e[t+1]]+oo[e[t+2]]+oo[e[t+3]]+"-"+oo[e[t+4]]+oo[e[t+5]]+"-"+oo[e[t+6]]+oo[e[t+7]]+"-"+oo[e[t+8]]+oo[e[t+9]]+"-"+oo[e[t+10]]+oo[e[t+11]]+oo[e[t+12]]+oo[e[t+13]]+oo[e[t+14]]+oo[e[t+15]]).toLowerCase()}const uo=function(e,t,r){if(no.randomUUID&&!t&&!e)return no.randomUUID();var n=(e=e||{}).random||(e.rng||io)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(var s=0;s<16;++s)t[r+s]=n[s];return t}return lo(n)};function ho(e,t){const r=Array.isArray(e)?e:[e],n=Array.isArray(t)?t:[t],s=r.map(se.coerceMessageLikeToMessage),a=n.map(se.coerceMessageLikeToMessage);for(const e of s)null!==e.id&&void 0!==e.id||(e.id=uo(),e.lc_kwargs.id=e.id);for(const e of a)null!==e.id&&void 0!==e.id||(e.id=uo(),e.lc_kwargs.id=e.id);const i=[...s],o=new Map(i.map(((e,t)=>[e.id,t]))),c=new Set;for(const e of a){const t=o.get(e.id);if(void 0!==t)"remove"===e._getType()?c.add(e.id):(c.delete(e.id),i[t]=e);else{if("remove"===e._getType())throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${e.id}')`);o.set(e.id,i.length),i.push(e)}}return i.filter((e=>!c.has(e.id)))}class po extends xa{constructor(e,t){const{name:r,tags:n,handleToolErrors:s}=t??{};super({name:r,tags:n,func:(e,t)=>this.run(e,t)}),Object.defineProperty(this,"tools",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handleToolErrors",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"trace",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.tools=e,this.handleToolErrors=s??this.handleToolErrors}async run(e,t){const r=Array.isArray(e)?e[e.length-1]:e.messages[e.messages.length-1];if("ai"!==r?._getType())throw new Error("ToolNode only accepts AIMessages as input.");const n=await Promise.all(r.tool_calls?.map((async e=>{const r=this.tools.find((t=>t.name===e.name));try{if(void 0===r)throw new Error(`Tool "${e.name}" not found.`);const n=await r.invoke({...e,type:"tool_call"},t);return(0,se.isBaseMessage)(n)&&"tool"===n._getType()||ba(n)?n:new se.ToolMessage({name:r.name,content:"string"==typeof n?n:JSON.stringify(n),tool_call_id:e.id})}catch(t){if(!this.handleToolErrors)throw t;if(xs(t))throw t;return new se.ToolMessage({content:`Error: ${t.message}\n Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}))??[]);if(!n.some(ba))return Array.isArray(e)?n:{messages:n};const s=[];let a=null;for(const t of n)ba(t)?t.graph===ya.PARENT&&Array.isArray(t.goto)&&t.goto.every((e=>ga(e)))?a?a.goto.push(...t.goto):a=new ya({graph:ya.PARENT,goto:t.goto}):s.push(t):s.push(Array.isArray(e)?[t]:{messages:[t]});return a&&s.push(a),s}}const mo=/(.*?)<\/name>/s,fo=/(.*?)<\/content>/s;function go(e){if(!((0,se.isBaseMessage)(e)&&((0,se.isAIMessage)(e)||(0,se.isBaseMessageChunk)(e)&&(0,se.isAIMessageChunk)(e)))||!e.name)return e;const{name:t}=e;if("string"==typeof e.content)return new se.AIMessage({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:`${t}${e.content}`,name:void 0});const r=[];let n=0;for(const s of e.content)"string"==typeof s?(n+=1,r.push(`${t}${s}`)):"object"==typeof s&&"type"in s&&"text"===s.type?(n+=1,r.push({...s,text:`${t}${s.text}`})):r.push(s);return n||r.unshift({type:"text",text:`${t}`}),new se.AIMessage({...e.lc_kwargs,content:r,name:void 0})}function yo(e){if(!(0,se.isAIMessage)(e)||!e.content)return e;let t,r=[];if(Array.isArray(e.content))r=e.content.filter((e=>{if("text"===e.type){const r=e.text.match(mo),n=e.text.match(fo);return!(r&&(!n||""===n[1]))||(t=r[1],!1)}return!0})).map((e=>{if("text"===e.type){const r=e.text.match(mo),n=e.text.match(fo);return r&&n?(t=r[1],{...e,text:n[1]}):e}return e}));else{const n=e.content,s=n.match(mo),a=n.match(fo);if(!s||!a)return e;t=s[1],r=a[1]}return new se.AIMessage({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:r,name:t})}const bo="prompt";function wo(e,t,r){if([e,t,r].filter((e=>null!=e)).length>1)throw new Error("Expected only one of prompt, stateModifier, or messageModifier, got multiple values");let n=e;return null!=t?n=t:null!=r&&(n=function(e){if("string"==typeof e||(0,se.isBaseMessage)(e)&&"system"===e._getType())return e;if("function"==typeof e)return async t=>e(t.messages);if(Y.YN.isRunnable(e))return Y.jY.from((e=>e.messages)).pipe(e);throw new Error("Unexpected type for messageModifier: "+typeof e)}(r)),function(e){let t;if(null==e)t=Y.jY.from((e=>e.messages)).withConfig({runName:bo});else if("string"==typeof e){const r=new se.SystemMessage(e);t=Y.jY.from((e=>[r,...e.messages??[]])).withConfig({runName:bo})}else if((0,se.isBaseMessage)(e)&&"system"===e._getType())t=Y.jY.from((t=>[e,...t.messages])).withConfig({runName:bo});else if("function"==typeof e)t=Y.jY.from(e).withConfig({runName:bo});else{if(!Y.YN.isRunnable(e))throw new Error("Got unexpected type for 'prompt': "+typeof e);t=e}return t}(n)}function vo(e){return"invoke"in e&&"function"==typeof e.invoke&&"_modelType"in e}function _o(e){return"_queuedMethodOperations"in e&&"_model"in e&&"function"==typeof e._model}async function ko(e){let t=e;if(Y.zZ.isRunnableSequence(t)&&(t=t.steps.find((e=>Y.fJ.isRunnableBinding(e)||vo(e)||_o(e)))||t),_o(t)&&(t=await t._model()),Y.fJ.isRunnableBinding(t)&&(t=t.bound),!vo(t))throw new Error(`Expected \`llm\` to be a ChatModel or RunnableBinding (e.g. llm.bind_tools(...)) with invoke() and generate() methods, got ${t.constructor.name}`);return t}function So(e){const{llm:t,tools:r,messageModifier:n,stateModifier:s,prompt:a,stateSchema:i,checkpointSaver:o,checkpointer:c,interruptBefore:l,interruptAfter:u,store:d,responseFormat:h,name:p,includeAgentName:m}=e;let f,g;Array.isArray(r)?(f=r,g=new po(r)):(f=r.tools,g=r);let y=null;const b=async e=>{if(y)return y;let t;if(await async function(e,t){let r=e;if(Y.zZ.isRunnableSequence(r)&&(r=r.steps.find((e=>Y.fJ.isRunnableBinding(e)||vo(e)||_o(e)))||r),_o(r)&&(r=await r._model()),!Y.fJ.isRunnableBinding(r))return!0;if(!r.kwargs||"object"!=typeof r.kwargs||!("tools"in r.kwargs))return!0;let n=r.kwargs.tools;if(1===n.length&&"functionDeclarations"in n[0]&&(n=n[0].functionDeclarations),t.length!==n.length)throw new Error("Number of tools in the model.bindTools() and tools passed to createReactAgent must match");const s=new Set(t.map((e=>e.name))),a=new Set;for(const e of n){let t;if("type"in e&&"function"===e.type)t=e.function.name;else if("name"in e)t=e.name;else{if(!("toolSpec"in e)||!("name"in e.toolSpec))continue;t=e.toolSpec.name}t&&a.add(t)}const i=[...s].filter((e=>!a.has(e)));if(i.length>0)throw new Error(`Missing tools '${i}' in the model.bindTools().Tools in the model.bindTools() must match the tools passed to createReactAgent.`);return!1}(e,f)){if(!("bindTools"in e)||"function"!=typeof e.bindTools)throw new Error(`llm ${e} must define bindTools method.`);t=e.bindTools(f)}else t=e;const r=wo(a,s,n),i="inline"===m?r.pipe(function(e,t){let r,n;if("inline"!==t)throw new Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);return r=go,n=yo,Y.zZ.from([Y.jY.from((function(e){return e.map(r)})),e,Y.jY.from(n)])}(t,m)):r.pipe(t);return y=i,i},w=new Set(f.filter((e=>"returnDirect"in e&&e.returnDirect)).map((e=>e.name))),v=e=>{const{messages:t}=e,r=t[t.length-1];return!(0,se.isAIMessage)(r)||r.tool_calls&&0!==r.tool_calls.length?"continue":null!=h?"generate_structured_response":Fs},_=async(e,r)=>{if(null==h)throw new Error("Attempted to generate structured output with no passed response schema. Please contact us for help.");const n=[...e.messages];let s;if("object"==typeof h&&"prompt"in h&&"schema"in h){const{prompt:e,schema:r}=h;s=(await ko(t)).withStructuredOutput(r),n.unshift(new se.SystemMessage({content:e}))}else s=(await ko(t)).withStructuredOutput(h);return{structuredResponse:await s.invoke(n,r)}},k=new Yi(i??Ki.Root({messages:Ki({reducer:ho,default:()=>[]}),structuredResponse:Ki})).addNode("agent",(async(e,r)=>{const n=await b(t),s=await n.invoke(e,r);return s.name=p,s.lc_kwargs.name=p,{messages:[s]}})).addNode("tools",g).addEdge(Ls,"agent");void 0!==h?k.addNode("generate_structured_response",_).addEdge("generate_structured_response",Fs).addConditionalEdges("agent",v,{continue:"tools",[Fs]:Fs,generate_structured_response:"generate_structured_response"}):k.addConditionalEdges("agent",v,{continue:"tools",[Fs]:Fs});const S=e=>{for(let t=e.messages.length-1;t>=0;t-=1){const r=e.messages[t];if(!(0,se.isToolMessage)(r))break;if(void 0!==r.name&&w.has(r.name))return Fs}return"agent"};return w.size>0?k.addConditionalEdges("tools",S,["agent",Fs]):k.addEdge("tools","agent"),k.compile({checkpointer:c??o,interruptBefore:l,interruptAfter:u,store:d,name:p})}var Eo=function(e,t){return(Eo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(e,t)};function xo(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}Eo(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function To(e,t,r,n){return new(r||(r=Promise))((function(s,a){function i(e){try{c(n.next(e))}catch(e){a(e)}}function o(e){try{c(n.throw(e))}catch(e){a(e)}}function c(e){e.done?s(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(i,o)}c((n=n.apply(e,t||[])).next())}))}function Co(e,t){var r,n,s,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=o(0),i.throw=o(1),i.return=o(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function o(o){return function(c){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,o[0]&&(a=0)),a;)try{if(r=1,n&&(s=2&o[0]?n.return:o[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,o[1])).done)return s;switch(n=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(s=a.trys,(s=s.length>0&&s[s.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Oo(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,s,a=r.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(s)throw s.error}}return i}function Ao(e,t,r){if(r||2===arguments.length)for(var n,s=0,a=t.length;s1||o(e,t)}))},t&&(n[e]=t(n[e])))}function o(e,t){try{(r=s[e](t)).value instanceof Io?Promise.resolve(r.value.v).then(c,l):u(a[0][2],r)}catch(e){u(a[0][3],e)}var r}function c(e){o("next",e)}function l(e){o("throw",e)}function u(e,t){e(t),a.shift(),a.length&&o(a[0][0],a[0][1])}}function Ro(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=Po(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,s){(function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)})(n,s,(t=e[r](t)).done,t.value)}))}}}function jo(e){return"function"==typeof e}function No(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var $o=No((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function Lo(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var Fo=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,r,n,s;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var i=Po(a),o=i.next();!o.done;o=i.next()){o.value.remove(this)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}else a.remove(this);var c=this.initialTeardown;if(jo(c))try{c()}catch(e){s=e instanceof $o?e.errors:[e]}var l=this._finalizers;if(l){this._finalizers=null;try{for(var u=Po(l),d=u.next();!d.done;d=u.next()){var h=d.value;try{Uo(h)}catch(e){s=null!=s?s:[],e instanceof $o?s=Ao(Ao([],Oo(s)),Oo(e.errors)):s.push(e)}}}catch(e){r={error:e}}finally{try{d&&!d.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}}if(s)throw new $o(s)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)Uo(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&Lo(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&Lo(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}(),Do=Fo.EMPTY;function zo(e){return e instanceof Fo||e&&"closed"in e&&jo(e.remove)&&jo(e.add)&&jo(e.unsubscribe)}function Uo(e){jo(e)?e():e.unsubscribe()}var Bo=null,qo=null,Ko=void 0,Wo=!1,Ho=!1,Vo={setTimeout:function(e,t){for(var r=[],n=2;n0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,r=this,n=r.hasError,s=r.isStopped,a=r.observers;return n||s?Do:(this.currentObservers=null,a.push(e),new Fo((function(){t.currentObservers=null,Lo(a,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,r=t.hasError,n=t.thrownError,s=t.isStopped;r?e.error(n):s&&e.complete()},t.prototype.asObservable=function(){var e=new dc;return e.source=this,e},t.create=function(e,t){return new bc(e,t)},t}(dc),bc=function(e){function t(t,r){var n=e.call(this)||this;return n.destination=t,n.source=r,n}return xo(t,e),t.prototype.next=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===r||r.call(t,e)},t.prototype.error=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===r||r.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,r;return null!==(r=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==r?r:Do},t}(yc),wc={now:function(){return(wc.delegate||Date).now()},delegate:void 0},vc=function(e){function t(t,r,n){void 0===t&&(t=1/0),void 0===r&&(r=1/0),void 0===n&&(n=wc);var s=e.call(this)||this;return s._bufferSize=t,s._windowTime=r,s._timestampProvider=n,s._buffer=[],s._infiniteTimeWindow=!0,s._infiniteTimeWindow=r===1/0,s._bufferSize=Math.max(1,t),s._windowTime=Math.max(1,r),s}return xo(t,e),t.prototype.next=function(t){var r=this,n=r.isStopped,s=r._buffer,a=r._infiniteTimeWindow,i=r._timestampProvider,o=r._windowTime;n||(s.push(t),!a&&s.push(i.now()+o)),this._trimBuffer(),e.prototype.next.call(this,t)},t.prototype._subscribe=function(e){this._throwIfClosed(),this._trimBuffer();for(var t=this._innerSubscribe(e),r=this._infiniteTimeWindow,n=this._buffer.slice(),s=0;s=2;return function(n){return n.pipe(e?fl((function(t,r){return e(t,r,n)})):lc,wl(1),r?bl(t):_l((function(){return new Jc})))}}function El(){for(var e=[],t=0;t1){let t=null;for(const r of e.reverse())t=null===t?r:new Il(r,t);throw t}}[Symbol.toStringTag]="DisposableStack"}class Al{#t=!1;#r=[];get disposed(){return this.#t}async dispose(){await this[Pl]()}use(e){if(e){const t=e[Pl],r=e[Cl];"function"==typeof t?this.#r.push(e):"function"==typeof r&&this.#r.push({[Pl]:async()=>{e[Cl]()}})}return e}adopt(e,t){return this.#r.push({[Pl]:()=>t(e)}),e}defer(e){this.#r.push({[Pl]:()=>e()})}move(){if(this.#t)throw new ReferenceError("A disposed stack can not use anything new");const e=new Al;return e.#r=this.#r,this.#r=[],this.#t=!0,e}async[Pl](){if(this.#t)return;this.#t=!0;const e=[];for(const t of this.#r.reverse())try{await t[Pl]()}catch(t){e.push(t)}if(1===e.length)throw e[0];if(e.length>1){let t=null;for(const r of e.reverse())t=null===t?r:new Il(r,t);throw t}}[Symbol.toStringTag]="AsyncDisposableStack"}class Il extends Error{#n;#s;constructor(e,t,r="An error was suppressed during disposal"){super(r),this.name="SuppressedError",this.#n=e,this.#s=t}get error(){return this.#n}get suppressed(){return this.#s}}class Ml{#a;#i=new Map;constructor(e=function(e){return{all:e=e||new Map,on:function(t,r){var n=e.get(t);n?n.push(r):e.set(t,[r])},off:function(t,r){var n=e.get(t);n&&(r?n.splice(n.indexOf(r)>>>0,1):e.set(t,[]))},emit:function(t,r){var n=e.get(t);n&&n.slice().map((function(e){e(r)})),(n=e.get("*"))&&n.slice().map((function(e){e(t,r)}))}}}(new Map)){this.#a=e}on(e,t){const r=this.#i.get(e);return void 0===r?this.#i.set(e,[t]):r.push(t),this.#a.on(e,t),this}off(e,t){const r=this.#i.get(e)??[];if(void 0===t){for(const t of r)this.#a.off(e,t);return this.#i.delete(e),this}const n=r.lastIndexOf(t);return n>-1&&this.#a.off(e,...r.splice(n,1)),this}emit(e,t){return this.#a.emit(e,t),this.listenerCount(e)>0}once(e,t){const r=n=>{t(n),this.off(e,r)};return this.on(e,r)}listenerCount(e){return this.#i.get(e)?.length||0}removeAllListeners(e){return void 0!==e?this.off(e):(this[Cl](),this)}[Cl](){for(const[e,t]of this.#i)for(const r of t)this.#a.off(e,r);this.#i.clear()}}const Rl=!("undefined"==typeof process||!process.version),jl={value:{get fs(){throw new Error("fs is not available in this environment")},get ScreenRecorder(){throw new Error("ScreenRecorder is not available in this environment")}}};var Nl=s(809);const $l=(e,t)=>{if(!e)throw new Error(t)};function Ll(e,t=!1){return t?"function"==typeof Buffer?Buffer.from(e,"base64"):Uint8Array.from(atob(e),(e=>e.codePointAt(0))):(new TextEncoder).encode(e)}function Fl(e){const t=[];for(let r=0;rRl?async(...t)=>{Bl&&Ul.push(e+t),(await async function(){return Dl||(Dl=(await Promise.resolve().then(s.t.bind(s,7833,19))).default),Dl}())(e)(t)}:(...t)=>{const r=globalThis.__PUPPETEER_DEBUG;if(!r)return;("*"===r||(r.endsWith("*")?e.startsWith(r):e===r))&&console.log(`${e}:`,...t)};let Ul=[],Bl=!1;class ql extends Error{constructor(e,t){super(e,t),this.name=this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}class Kl extends ql{}class Wl extends ql{}class Hl extends ql{#o;#c="";set code(e){this.#o=e}get code(){return this.#o}set originalMessage(e){this.#c=e}get originalMessage(){return this.#c}}class Vl extends ql{}class Gl extends Hl{}const Jl={letter:{cm:{width:21.59,height:27.94},in:{width:8.5,height:11}},legal:{cm:{width:21.59,height:35.56},in:{width:8.5,height:14}},tabloid:{cm:{width:27.94,height:43.18},in:{width:11,height:17}},ledger:{cm:{width:43.18,height:27.94},in:{width:17,height:11}},a0:{cm:{width:84.1,height:118.9},in:{width:33.1102,height:46.811}},a1:{cm:{width:59.4,height:84.1},in:{width:23.3858,height:33.1102}},a2:{cm:{width:42,height:59.4},in:{width:16.5354,height:23.3858}},a3:{cm:{width:29.7,height:42},in:{width:11.6929,height:16.5354}},a4:{cm:{width:21,height:29.7},in:{width:8.2677,height:11.6929}},a5:{cm:{width:14.8,height:21},in:{width:5.8268,height:8.2677}},a6:{cm:{width:10.5,height:14.8},in:{width:4.1339,height:5.8268}}},Zl=zl("puppeteer:error"),Xl=Object.freeze({width:800,height:600}),Yl=Symbol("Source URL for Puppeteer evaluation scripts");class Ql{static INTERNAL_URL="pptr:internal";static fromCallSite(e,t){const r=new Ql;return r.#l=e,r.#u=t.toString(),r}static parse=e=>{e=e.slice(5);const[t="",r=""]=e.split(";"),n=new Ql;return n.#l=t,n.#u=decodeURIComponent(r),n};static isPuppeteerURL=e=>e.startsWith("pptr:");#l;#u;get functionName(){return this.#l}get siteString(){return this.#u}toString(){return`pptr:${[this.#l,encodeURIComponent(this.#u)].join(";")}`}}const eu=(e,t)=>{if(Object.prototype.hasOwnProperty.call(t,Yl))return t;const r=Error.prepareStackTrace;Error.prepareStackTrace=(e,t)=>t[2];const n=(new Error).stack;return Error.prepareStackTrace=r,Object.assign(t,{[Yl]:Ql.fromCallSite(e,n)})},tu=e=>"string"==typeof e||e instanceof String;function ru(e,...t){if(tu(e))return $l(0===t.length,"Cannot evaluate a string with arguments"),e;return`(${e})(${t.map((function(e){return Object.is(e,void 0)?"undefined":JSON.stringify(e)})).join(",")})`}async function nu(e,t){const r=[],n=e.getReader();if(t){const e=await jl.value.fs.promises.open(t,"w+");try{for(;;){const{done:t,value:s}=await n.read();if(t)break;r.push(s),await e.writeFile(s)}}finally{await e.close()}}else for(;;){const{done:e,value:t}=await n.read();if(e)break;r.push(t)}try{const e=function(e){let t=0;for(const r of e)t+=r.length;const r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}(r);return 0===e.length?null:e}catch(e){return Zl(e),null}}async function su(e,t){return new ReadableStream({async pull(r){const{data:n,base64Encoded:s,eof:a}=await e.send("IO.read",{handle:t});r.enqueue(Ll(n,s??!1)),a&&(await e.send("IO.close",{handle:t}),r.close())}})}function au(e,t){return 0===e?hl:ul(e).pipe(Xc((()=>{throw new Kl(`Timed out after waiting ${e}ms`,{cause:t})})))}const iu="__puppeteer_utility_world__"+Nl.T,ou=/^[\x20\t]*\/\/[@#] sourceURL=\s{0,10}(\S*?)\s{0,10}$/m;const cu=500;const lu={px:1,in:96,cm:37.8,mm:3.78};function uu(e,t="in"){if(void 0===e)return;let r;if((e=>"number"==typeof e||e instanceof Number)(e))r=e;else{if(!tu(e))throw new Error("page.pdf() Cannot handle parameter type: "+typeof e);{const t=e;let n=t.substring(t.length-2).toLowerCase(),s="";n in lu?s=t.substring(0,t.length-2):(n="px",s=t);const a=Number(s);$l(!isNaN(a),"Failed to parse parameter value: "+t),r=a*lu[n]}}return r/lu[t]}function du(e,t){return new dc((r=>{const n=e=>{r.next(e)};return e.on(t,n),()=>{e.off(t,n)}}))}function hu(e,t){return e?cl(e,"abort").pipe(Xc((()=>{if(e.reason instanceof Error)throw e.reason.cause=t,e.reason;throw new Error(e.reason,{cause:t})}))):hl}function pu(e){return tl((t=>Vc(Promise.resolve(e(t))).pipe(fl((e=>e)),Xc((()=>t)))))}const mu=new Map([["accelerometer","sensors"],["ambient-light-sensor","sensors"],["background-sync","backgroundSync"],["camera","videoCapture"],["clipboard-read","clipboardReadWrite"],["clipboard-sanitized-write","clipboardSanitizedWrite"],["clipboard-write","clipboardReadWrite"],["geolocation","geolocation"],["gyroscope","sensors"],["idle-detection","idleDetection"],["keyboard-lock","keyboardLock"],["magnetometer","sensors"],["microphone","audioCapture"],["midi","midi"],["notifications","notifications"],["payment-handler","paymentHandler"],["persistent-storage","durableStorage"],["pointer-lock","pointerLock"],["midi-sysex","midiSysex"]]);class fu extends Ml{constructor(){super()}async waitForTarget(e,t={}){const{timeout:r=3e4,signal:n}=t;return await Zc(dl(du(this,"targetcreated"),du(this,"targetchanged"),Vc(this.targets())).pipe(pu(e),El(hu(n),au(r))))}async pages(){const e=await Promise.all(this.browserContexts().map((e=>e.pages())));return e.reduce(((e,t)=>e.concat(t)),[])}async cookies(){return await this.defaultBrowserContext().cookies()}async setCookie(...e){return await this.defaultBrowserContext().setCookie(...e)}async deleteCookie(...e){return await this.defaultBrowserContext().deleteCookie(...e)}isConnected(){return this.connected}[Cl](){this.process()?this.close().catch(Zl):this.disconnect().catch(Zl)}[Pl](){return this.process()?this.close():this.disconnect()}}class gu{static create(e){return new gu(e)}static async race(e){const t=new Set;try{const r=e.map((e=>e instanceof gu?(e.#d&&t.add(e),e.valueOrThrow()):e));return await Promise.race(r)}finally{for(const e of t)e.reject(new Error("Timeout cleared"))}}#h=!1;#p=!1;#m;#f;#g=new Promise((e=>{this.#f=e}));#d;#y;constructor(e){e&&e.timeout>0&&(this.#y=new Kl(e.message),this.#d=setTimeout((()=>{this.reject(this.#y)}),e.timeout))}#b(e){clearTimeout(this.#d),this.#m=e,this.#f()}resolve(e){this.#p||this.#h||(this.#h=!0,this.#b(e))}reject(e){this.#p||this.#h||(this.#p=!0,this.#b(e))}resolved(){return this.#h}finished(){return this.#h||this.#p}value(){return this.#m}#w;valueOrThrow(){return this.#w||(this.#w=(async()=>{if(await this.#g,this.#p)throw this.#m;return this.#m})()),this.#w}}class yu{static Guard=class{#v;#_;constructor(e,t){this.#v=e,this.#_=t}[Cl](){return this.#_?.(),this.#v.release()}};#k=!1;#S=[];async acquire(e){if(!this.#k)return this.#k=!0,new yu.Guard(this);const t=gu.create();return this.#S.push(t.resolve.bind(t)),await t.valueOrThrow(),new yu.Guard(this,e)}release(){const e=this.#S.shift();e?e():this.#k=!1}}class bu extends Ml{constructor(){super()}#E;#x=0;startScreenshot(){const e=this.#E||new yu;return this.#E=e,this.#x++,e.acquire((()=>{this.#x--,0===this.#x&&(this.#E=void 0)}))}waitForScreenshotOperations(){return this.#E?.acquire()}async waitForTarget(e,t={}){const{timeout:r=3e4}=t;return await Zc(dl(du(this,"targetcreated"),du(this,"targetchanged"),Vc(this.targets())).pipe(pu(e),El(au(r))))}async deleteCookie(...e){return await this.setCookie(...e.map((e=>({...e,expires:1}))))}get closed(){return!this.browser().browserContexts().includes(this)}get id(){}[Cl](){this.close().catch(Zl)}[Pl](){return this.close()}}var wu;!function(e){e.Disconnected=Symbol("CDPSession.Disconnected"),e.Swapped=Symbol("CDPSession.Swapped"),e.Ready=Symbol("CDPSession.Ready"),e.SessionAttached="sessionattached",e.SessionDetached="sessiondetached"}(wu||(wu={}));class vu extends Ml{constructor(){super()}parentSession(){}}const _u=Symbol("_isElementHandle");function ku(e){return"object"==typeof e&&null!==e&&"name"in e&&"message"in e}function Su(e,t,r){return e.message=t,e.originalMessage=r??e.originalMessage,e}function Eu(e){let t=e.error.message;return e.error&&"object"==typeof e.error&&"data"in e.error&&(t+=` ${e.error.data}`),t}const xu=new Map;function Tu(e){let t=e.toString();try{new Function(`(${t})`)}catch(e){if(e.message.includes("Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive"))return t;let r="function ";t.startsWith("async ")&&(r=`async ${r}`,t=t.substring(6)),t=`${r}${t}`;try{new Function(`(${t})`)}catch{throw new Error("Passed function cannot be serialized!")}}return t}const Cu=(e,t)=>{let r=Tu(e);for(const[e,n]of Object.entries(t))r=r.replace(new RegExp(`PLACEHOLDER\\(\\s*(?:'${e}'|"${e}")\\s*\\)`,"g"),`(${n})`);return(e=>{let t=xu.get(e);return t||(t=new Function(`return ${e}`)(),xu.set(e,t),t)})(r)};var Pu=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Ou=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,s=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===s)return s=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return s|=2,Promise.resolve(a).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});async function*Au(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Pu(r,await e.evaluateHandle((async(e,t)=>{const r=[];for(;r.length{for(const e of a){const t={stack:[],error:void 0,hasError:!1};try{Pu(t,e,!1)[Cl]()}catch(e){t.error=e,t.hasError=!0}finally{Ou(t)}}})),yield*a,0===s.size}catch(e){r.error=e,r.hasError=!0}finally{Ou(r)}}async function*Iu(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Pu(t,await e.evaluateHandle((e=>async function*(){yield*e}())),!1);yield*async function*(e){let t=20;for(;!(yield*Au(e,t));)t<<=1}(r)}catch(e){t.error=e,t.hasError=!0}finally{Ou(t)}}class Mu{static create=e=>new Mu(e);#T;constructor(e){this.#T=e}async get(e){return await this.#T(e)}}var Ru=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},ju=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,s=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===s)return s=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return s|=2,Promise.resolve(a).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Nu{static querySelectorAll;static querySelector;static get _querySelector(){if(this.querySelector)return this.querySelector;if(!this.querySelectorAll)throw new Error("Cannot create default `querySelector`.");return this.querySelector=Cu((async(e,t,r)=>{const n=PLACEHOLDER("querySelectorAll")(e,t,r);for await(const e of n)return e;return null}),{querySelectorAll:Tu(this.querySelectorAll)})}static get _querySelectorAll(){if(this.querySelectorAll)return this.querySelectorAll;if(!this.querySelector)throw new Error("Cannot create default `querySelectorAll`.");return this.querySelectorAll=Cu((async function*(e,t,r){const n=PLACEHOLDER("querySelector"),s=await n(e,t,r);s&&(yield s)}),{querySelector:Tu(this.querySelector)})}static async*queryAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Ru(r,await e.evaluateHandle(this._querySelectorAll,t,Mu.create((e=>e.puppeteerUtil))),!1);yield*Iu(n)}catch(e){r.error=e,r.hasError=!0}finally{ju(r)}}static async queryOne(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Ru(r,await e.evaluateHandle(this._querySelector,t,Mu.create((e=>e.puppeteerUtil))),!1);return _u in n?n.move():null}catch(e){r.error=e,r.hasError=!0}finally{ju(r)}}static async waitFor(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{let s;const a=Ru(n,await(async()=>{if(_u in e)return s=e.frame,await s.isolatedRealm().adoptHandle(e);s=e})(),!1),{visible:i=!1,hidden:o=!1,timeout:c,signal:l}=r,u=i||o?"raf":r.polling;try{const e={stack:[],error:void 0,hasError:!1};try{l?.throwIfAborted();const r=Ru(e,await s.isolatedRealm().waitForFunction((async(e,t,r,n,s)=>{const a=e.createFunction(t),i=await a(n??document,r,e);return e.checkVisibility(i,s)}),{polling:u,root:a,timeout:c,signal:l},Mu.create((e=>e.puppeteerUtil)),Tu(this._querySelector),t,a,!!i||!o&&void 0),!1);if(l?.aborted)throw l.reason;return _u in r?await s.mainRealm().transferHandle(r):null}catch(t){e.error=t,e.hasError=!0}finally{ju(e)}}catch(e){if(!ku(e))throw e;if("AbortError"===e.name)throw e;throw e.message=`Waiting for selector \`${t}\` failed: ${e.message}`,e}}catch(e){n.error=e,n.hasError=!0}finally{ju(n)}}}class $u{static async*map(e,t){for await(const r of e)yield await t(r)}static async*flatMap(e,t){for await(const r of e)yield*t(r)}static async collect(e){const t=[];for await(const r of e)t.push(r);return t}static async first(e){for await(const t of e)return t}}const Lu=/\[\s*(?\w+)\s*=\s*(?"|')(?\\.|.*?(?=\k))\k\s*\]/g;class Fu extends Nu{static querySelector=async(e,t,{ariaQuerySelector:r})=>await r(e,t);static async*queryAll(e,t){const{name:r,role:n}=(e=>{if(e.length>1e4)throw new Error(`Selector ${e} is too long`);const t={},r=e.replace(Lu,((e,r,n,s)=>($l((e=>["name","role"].includes(e))(r),`Unknown aria attribute "${r}" in selector`),t[r]=s,"")));return r&&!t.name&&(t.name=r),t})(t);yield*e.queryAXTree(r,n)}static queryOne=async(e,t)=>await $u.first(this.queryAll(e,t))??null}class Du extends Nu{static querySelector=(e,t,{cssQuerySelector:r})=>r(e,t);static querySelectorAll=(e,t,{cssQuerySelectorAll:r})=>r(e,t)}const zu=new class{#C=!1;#P=new Set;append(e){this.#O((()=>{this.#P.add(e)}))}pop(e){this.#O((()=>{this.#P.delete(e)}))}inject(e,t=!1){(this.#C||t)&&e(this.#T()),this.#C=!1}#O(e){e(),this.#C=!0}#T(){return`(() => {\n const module = {};\n "use strict";var g=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var l=(t,e)=>{for(var r in e)g(t,r,{get:e[r],enumerable:!0})},J=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of B(e))!Y.call(t,n)&&n!==r&&g(t,n,{get:()=>e[n],enumerable:!(o=X(e,n))||o.enumerable});return t};var z=t=>J(g({},"__esModule",{value:!0}),t);var pe={};l(pe,{default:()=>he});module.exports=z(pe);var N=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}},p=class extends N{};var c=class t{static create(e){return new t(e)}static async race(e){let r=new Set;try{let o=e.map(n=>n instanceof t?(n.#n&&r.add(n),n.valueOrThrow()):n);return await Promise.race(o)}finally{for(let o of r)o.reject(new Error("Timeout cleared"))}}#e=!1;#r=!1;#o;#t;#a=new Promise(e=>{this.#t=e});#n;#i;constructor(e){e&&e.timeout>0&&(this.#i=new p(e.message),this.#n=setTimeout(()=>{this.reject(this.#i)},e.timeout))}#l(e){clearTimeout(this.#n),this.#o=e,this.#t()}resolve(e){this.#r||this.#e||(this.#e=!0,this.#l(e))}reject(e){this.#r||this.#e||(this.#r=!0,this.#l(e))}resolved(){return this.#e}finished(){return this.#e||this.#r}value(){return this.#o}#s;valueOrThrow(){return this.#s||(this.#s=(async()=>{if(await this.#a,this.#r)throw this.#o;return this.#o})()),this.#s}};var L=new Map,F=t=>{let e=L.get(t);return e||(e=new Function(\`return \${t}\`)(),L.set(t,e),e)};var x={};l(x,{ariaQuerySelector:()=>G,ariaQuerySelectorAll:()=>b});var G=(t,e)=>globalThis.__ariaQuerySelector(t,e),b=async function*(t,e){yield*await globalThis.__ariaQuerySelectorAll(t,e)};var E={};l(E,{cssQuerySelector:()=>K,cssQuerySelectorAll:()=>Z});var K=(t,e)=>t.querySelector(e),Z=function(t,e){return t.querySelectorAll(e)};var A={};l(A,{customQuerySelectors:()=>P});var v=class{#e=new Map;register(e,r){if(!r.queryOne&&r.queryAll){let o=r.queryAll;r.queryOne=(n,i)=>{for(let s of o(n,i))return s;return null}}else if(r.queryOne&&!r.queryAll){let o=r.queryOne;r.queryAll=(n,i)=>{let s=o(n,i);return s?[s]:[]}}else if(!r.queryOne||!r.queryAll)throw new Error("At least one query method must be defined.");this.#e.set(e,{querySelector:r.queryOne,querySelectorAll:r.queryAll})}unregister(e){this.#e.delete(e)}get(e){return this.#e.get(e)}clear(){this.#e.clear()}},P=new v;var R={};l(R,{pierceQuerySelector:()=>ee,pierceQuerySelectorAll:()=>te});var ee=(t,e)=>{let r=null,o=n=>{let i=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT);do{let s=i.currentNode;s.shadowRoot&&o(s.shadowRoot),!(s instanceof ShadowRoot)&&s!==n&&!r&&s.matches(e)&&(r=s)}while(!r&&i.nextNode())};return t instanceof Document&&(t=t.documentElement),o(t),r},te=(t,e)=>{let r=[],o=n=>{let i=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT);do{let s=i.currentNode;s.shadowRoot&&o(s.shadowRoot),!(s instanceof ShadowRoot)&&s!==n&&s.matches(e)&&r.push(s)}while(i.nextNode())};return t instanceof Document&&(t=t.documentElement),o(t),r};var u=(t,e)=>{if(!t)throw new Error(e)};var y=class{#e;#r;#o;#t;constructor(e,r){this.#e=e,this.#r=r}async start(){let e=this.#t=c.create(),r=await this.#e();if(r){e.resolve(r);return}this.#o=new MutationObserver(async()=>{let o=await this.#e();o&&(e.resolve(o),await this.stop())}),this.#o.observe(this.#r,{childList:!0,subtree:!0,attributes:!0})}async stop(){u(this.#t,"Polling never started."),this.#t.finished()||this.#t.reject(new Error("Polling stopped")),this.#o&&(this.#o.disconnect(),this.#o=void 0)}result(){return u(this.#t,"Polling never started."),this.#t.valueOrThrow()}},w=class{#e;#r;constructor(e){this.#e=e}async start(){let e=this.#r=c.create(),r=await this.#e();if(r){e.resolve(r);return}let o=async()=>{if(e.finished())return;let n=await this.#e();if(!n){window.requestAnimationFrame(o);return}e.resolve(n),await this.stop()};window.requestAnimationFrame(o)}async stop(){u(this.#r,"Polling never started."),this.#r.finished()||this.#r.reject(new Error("Polling stopped"))}result(){return u(this.#r,"Polling never started."),this.#r.valueOrThrow()}},S=class{#e;#r;#o;#t;constructor(e,r){this.#e=e,this.#r=r}async start(){let e=this.#t=c.create(),r=await this.#e();if(r){e.resolve(r);return}this.#o=setInterval(async()=>{let o=await this.#e();o&&(e.resolve(o),await this.stop())},this.#r)}async stop(){u(this.#t,"Polling never started."),this.#t.finished()||this.#t.reject(new Error("Polling stopped")),this.#o&&(clearInterval(this.#o),this.#o=void 0)}result(){return u(this.#t,"Polling never started."),this.#t.valueOrThrow()}};var _={};l(_,{PCombinator:()=>H,pQuerySelector:()=>fe,pQuerySelectorAll:()=>$});var a=class{static async*map(e,r){for await(let o of e)yield await r(o)}static async*flatMap(e,r){for await(let o of e)yield*r(o)}static async collect(e){let r=[];for await(let o of e)r.push(o);return r}static async first(e){for await(let r of e)return r}};var C={};l(C,{textQuerySelectorAll:()=>m});var re=new Set(["checkbox","image","radio"]),oe=t=>t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLInputElement&&!re.has(t.type),ne=new Set(["SCRIPT","STYLE"]),f=t=>!ne.has(t.nodeName)&&!document.head?.contains(t),I=new WeakMap,j=t=>{for(;t;)I.delete(t),t instanceof ShadowRoot?t=t.host:t=t.parentNode},W=new WeakSet,se=new MutationObserver(t=>{for(let e of t)j(e.target)}),d=t=>{let e=I.get(t);if(e||(e={full:"",immediate:[]},!f(t)))return e;let r="";if(oe(t))e.full=t.value,e.immediate.push(t.value),t.addEventListener("input",o=>{j(o.target)},{once:!0,capture:!0});else{for(let o=t.firstChild;o;o=o.nextSibling){if(o.nodeType===Node.TEXT_NODE){e.full+=o.nodeValue??"",r+=o.nodeValue??"";continue}r&&e.immediate.push(r),r="",o.nodeType===Node.ELEMENT_NODE&&(e.full+=d(o).full)}r&&e.immediate.push(r),t instanceof Element&&t.shadowRoot&&(e.full+=d(t.shadowRoot).full),W.has(t)||(se.observe(t,{childList:!0,characterData:!0,subtree:!0}),W.add(t))}return I.set(t,e),e};var m=function*(t,e){let r=!1;for(let o of t.childNodes)if(o instanceof Element&&f(o)){let n;o.shadowRoot?n=m(o.shadowRoot,e):n=m(o,e);for(let i of n)yield i,r=!0}r||t instanceof Element&&f(t)&&d(t).full.includes(e)&&(yield t)};var k={};l(k,{checkVisibility:()=>le,pierce:()=>T,pierceAll:()=>O});var ie=["hidden","collapse"],le=(t,e)=>{if(!t)return e===!1;if(e===void 0)return t;let r=t.nodeType===Node.TEXT_NODE?t.parentElement:t,o=window.getComputedStyle(r),n=o&&!ie.includes(o.visibility)&&!ae(r);return e===n?t:!1};function ae(t){let e=t.getBoundingClientRect();return e.width===0||e.height===0}var ce=t=>"shadowRoot"in t&&t.shadowRoot instanceof ShadowRoot;function*T(t){ce(t)?yield t.shadowRoot:yield t}function*O(t){t=T(t).next().value,yield t;let e=[document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT)];for(let r of e){let o;for(;o=r.nextNode();)o.shadowRoot&&(yield o.shadowRoot,e.push(document.createTreeWalker(o.shadowRoot,NodeFilter.SHOW_ELEMENT)))}}var Q={};l(Q,{xpathQuerySelectorAll:()=>q});var q=function*(t,e,r=-1){let n=(t.ownerDocument||document).evaluate(e,t,null,XPathResult.ORDERED_NODE_ITERATOR_TYPE),i=[],s;for(;(s=n.iterateNext())&&(i.push(s),!(r&&i.length===r)););for(let h=0;h(r.Descendent=">>>",r.Child=">>>>",r))(H||{}),V=t=>"querySelectorAll"in t,M=class{#e;#r=[];#o=void 0;elements;constructor(e,r){this.elements=[e],this.#e=r,this.#t()}async run(){if(typeof this.#o=="string")switch(this.#o.trimStart()){case":scope":this.#t();break}for(;this.#o!==void 0;this.#t()){let e=this.#o;typeof e=="string"?e[0]&&ue.test(e[0])?this.elements=a.flatMap(this.elements,async function*(r){V(r)&&(yield*r.querySelectorAll(e))}):this.elements=a.flatMap(this.elements,async function*(r){if(!r.parentElement){if(!V(r))return;yield*r.querySelectorAll(e);return}let o=0;for(let n of r.parentElement.children)if(++o,n===r)break;yield*r.parentElement.querySelectorAll(\`:scope>:nth-child(\${o})\${e}\`)}):this.elements=a.flatMap(this.elements,async function*(r){switch(e.name){case"text":yield*m(r,e.value);break;case"xpath":yield*q(r,e.value);break;case"aria":yield*b(r,e.value);break;default:let o=P.get(e.name);if(!o)throw new Error(\`Unknown selector type: \${e.name}\`);yield*o.querySelectorAll(r,e.value)}})}}#t(){if(this.#r.length!==0){this.#o=this.#r.shift();return}if(this.#e.length===0){this.#o=void 0;return}let e=this.#e.shift();switch(e){case">>>>":{this.elements=a.flatMap(this.elements,T),this.#t();break}case">>>":{this.elements=a.flatMap(this.elements,O),this.#t();break}default:this.#r=e,this.#t();break}}},D=class{#e=new WeakMap;calculate(e,r=[]){if(e===null)return r;e instanceof ShadowRoot&&(e=e.host);let o=this.#e.get(e);if(o)return[...o,...r];let n=0;for(let s=e.previousSibling;s;s=s.previousSibling)++n;let i=this.calculate(e.parentNode,[n]);return this.#e.set(e,i),[...i,...r]}},U=(t,e)=>{if(t.length+e.length===0)return 0;let[r=-1,...o]=t,[n=-1,...i]=e;return r===n?U(o,i):r[o,r.calculate(o)]).sort(([,o],[,n])=>U(o,n)).map(([o])=>o)},$=function(t,e){let r=JSON.parse(e);if(r.some(o=>{let n=0;return o.some(i=>(typeof i=="string"?++n:n=0,n>1))}))throw new Error("Multiple deep combinators found in sequence.");return de(a.flatMap(r,o=>{let n=new M(t,o);return n.run(),n.elements}))},fe=async function(t,e){for await(let r of $(t,e))return r;return null};var me=Object.freeze({...x,...A,...R,..._,...C,...k,...Q,...E,Deferred:c,createFunction:F,createTextContent:d,IntervalPoller:S,isSuitableNodeForTextMatching:f,MutationPoller:y,RAFPoller:w}),he=me;\n\n ${[...this.#P].map((e=>`(${e})(module.exports.default);`)).join("")}\n return module.exports.default;\n })()`}};const Uu=new class{#i=new Map;get(e){const t=this.#i.get(e);return t?t[1]:void 0}register(e,t){$l(!this.#i.has(e),`Cannot register over existing handler: ${e}`),$l(/^[a-zA-Z]+$/.test(e),"Custom query handler names may only contain [a-zA-Z]"),$l(t.queryAll||t.queryOne,"At least one query method must be implemented.");const r=class extends Nu{static querySelectorAll=Cu(((e,t,r)=>r.customQuerySelectors.get(PLACEHOLDER("name")).querySelectorAll(e,t)),{name:JSON.stringify(e)});static querySelector=Cu(((e,t,r)=>r.customQuerySelectors.get(PLACEHOLDER("name")).querySelector(e,t)),{name:JSON.stringify(e)})},n=Cu((e=>{e.customQuerySelectors.register(PLACEHOLDER("name"),{queryAll:PLACEHOLDER("queryAll"),queryOne:PLACEHOLDER("queryOne")})}),{name:JSON.stringify(e),queryAll:t.queryAll?Tu(t.queryAll):String(void 0),queryOne:t.queryOne?Tu(t.queryOne):String(void 0)}).toString();this.#i.set(e,[n,r]),zu.append(n)}unregister(e){const t=this.#i.get(e);if(!t)throw new Error(`Cannot unregister unknown handler: ${e}`);zu.pop(t[0]),this.#i.delete(e)}names(){return[...this.#i.keys()]}clear(){for(const[e]of this.#i)zu.pop(e);this.#i.clear()}};class Bu extends Nu{static querySelectorAll=(e,t,{pQuerySelectorAll:r})=>r(e,t);static querySelector=(e,t,{pQuerySelector:r})=>r(e,t)}var qu={attribute:/\[\s*(?:(?\*|[-\w\P{ASCII}]*)\|)?(?[-\w\P{ASCII}]+)\s*(?:(?\W?=)\s*(?.+?)\s*(\s(?[iIsS]))?\s*)?\]/gu,id:/#(?[-\w\P{ASCII}]+)/gu,class:/\.(?[-\w\P{ASCII}]+)/gu,comma:/\s*,\s*/g,combinator:/\s*[\s>+~]\s*/g,"pseudo-element":/::(?[-\w\P{ASCII}]+)(?:\((?¶*)\))?/gu,"pseudo-class":/:(?[-\w\P{ASCII}]+)(?:\((?¶*)\))?/gu,universal:/(?:(?\*|[-\w\P{ASCII}]*)\|)?\*/gu,type:/(?:(?\*|[-\w\P{ASCII}]*)\|)?(?[-\w\P{ASCII}]+)/gu},Ku=new Set(["combinator","comma"]),Wu=e=>{switch(e){case"pseudo-element":case"pseudo-class":return new RegExp(qu[e].source.replace("(?¶*)","(?.*)"),"gu");default:return qu[e]}};function Hu(e,t){let r=0,n="";for(;t(r.push({value:e,offset:t}),"".repeat(e.length)))),e=e.replace(Vu,((e,t,n,s)=>(r.push({value:e,offset:s}),`${t}${"".repeat(n.length)}${t}`)));{let t,n=0;for(;(t=e.indexOf("(",n))>-1;){const s=Hu(e,t);r.push({value:s,offset:t}),e=`${e.substring(0,t)}(${"¶".repeat(s.length-2)})${e.substring(t+s.length)}`,n=t+s.length}}const n=function(e,t=qu){if(!e)return[];const r=[e];for(const[e,n]of Object.entries(t))for(let t=0;te.content)).join("");switch(e.type){case"list":return e.list.map(Zu).join(",");case"relative":return e.combinator+Zu(e.right);case"complex":return Zu(e.left)+e.combinator+Zu(e.right);case"compound":return e.list.map(Zu).join("");default:return e.content}}qu.nesting=/&/g,qu.combinator=/\s*(>>>>?|[\s>+~])\s*/g;const Xu=/\\[\s\S]/g;const Yu={aria:Fu,pierce:class extends Nu{static querySelector=(e,t,{pierceQuerySelector:r})=>r(e,t);static querySelectorAll=(e,t,{pierceQuerySelectorAll:r})=>r(e,t)},xpath:class extends Nu{static querySelectorAll=(e,t,{xpathQuerySelectorAll:r})=>r(e,t);static querySelector=(e,t,{xpathQuerySelectorAll:r})=>{for(const n of r(e,t,1))return n;return null}},text:class extends Nu{static querySelectorAll=(e,t,{textQuerySelectorAll:r})=>r(e,t)}},Qu=["=","/"];function ed(e){for(const t of[Uu.names().map((e=>[e,Uu.get(e)])),Object.entries(Yu)])for(const[r,n]of t)for(const t of Qu){const s=`${r}${t}`;if(e.startsWith(s))return{updatedSelector:e=e.slice(s.length),polling:"aria"===r?"raf":"mutation",QueryHandler:n}}try{const[t,r,n,s]=function(e){let t=!0,r=!1,n=!1;const s=Ju(e);if(0===s.length)return[[],t,n,!1];let a=[],i=[a];const o=[i],c=[];for(const e of s){switch(e.type){case"combinator":switch(e.content){case">>>":t=!1,c.length&&(a.push(Zu(c)),c.splice(0)),a=[],i.push(">>>"),i.push(a);continue;case">>>>":t=!1,c.length&&(a.push(Zu(c)),c.splice(0)),a=[],i.push(">>>>"),i.push(a);continue}break;case"pseudo-element":if(!e.name.startsWith("-p-"))break;t=!1,c.length&&(a.push(Zu(c)),c.splice(0));const s=e.name.slice(3);"aria"===s&&(r=!0),a.push({name:s,value:(l=e.argument??"",l.length<=1?l:('"'!==l[0]&&"'"!==l[0]||!l.endsWith(l[0])||(l=l.slice(1,-1)),l.replace(Xu,(e=>e[1]))))});continue;case"pseudo-class":n=!0;break;case"comma":c.length&&(a.push(Zu(c)),c.splice(0)),a=[],i=[a],o.push(i);continue}c.push(e)}var l;return c.length&&a.push(Zu(c)),[o,t,n,r]}(e);return r?{updatedSelector:e,polling:n?"raf":"mutation",QueryHandler:Du}:{updatedSelector:JSON.stringify(t),polling:s?"raf":"mutation",QueryHandler:Bu}}catch{return{updatedSelector:e,polling:"mutation",QueryHandler:Du}}}var td=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},rd=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,s=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===s)return s=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return s|=2,Promise.resolve(a).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const nd=new WeakSet;function sd(e,t){let r=!1;if(e.prototype[Cl]){const t=e.prototype[Cl];e.prototype[Cl]=function(){if(!nd.has(this))return t.call(this);nd.delete(this)},r=!0}if(e.prototype[Pl]){const t=e.prototype[Pl];e.prototype[Pl]=function(){if(!nd.has(this))return t.call(this);nd.delete(this)},r=!0}return r&&(e.prototype.move=function(){return nd.add(this),this}),e}function ad(e=e=>`Attempted to use disposed ${e.constructor.name}.`){return(t,r)=>function(...r){if(this.disposed)throw new Error(e(this));return t.call(this,...r)}}function id(e,t){const r=new WeakMap;let n=-1;return function(...t){if(-1===n&&(n=t.length),n!==t.length)throw new Error("Memoized method was called with the wrong number of arguments");let s=!1,a=r;for(const e of t)a.has(e)||(s=!0,a.set(e,new WeakMap)),a=a.get(e);if(s)return e.call(this,...t)}}function od(e=function(){return this}){return(t,r)=>{const n=new WeakMap;return async function(...r){const s={stack:[],error:void 0,hasError:!1};try{const a=e.call(this);let i=n.get(a);i||(i=new yu,n.set(a,i));td(s,await i.acquire(),!0);return await t.call(this,...r)}catch(e){s.error=e,s.hasError=!0}finally{const e=rd(s);e&&await e}}}}new WeakMap;var cd=function(e,t,r){for(var n=arguments.length>2,s=0;s=0;p--){var m={};for(var f in n)m[f]="access"===f?{}:n[f];for(var f in n.access)m.access[f]=n.access[f];m.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");a.push(i(e||null))};var g=(0,r[p])("accessor"===c?{get:d.get,set:d.set}:d[l],m);if("accessor"===c){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(o=i(g.get))&&(d.get=o),(o=i(g.set))&&(d.set=o),(o=i(g.init))&&s.unshift(o)}else(o=i(g))&&("field"===c?s.unshift(o):d[l]=o)}u&&Object.defineProperty(u,n.name,d),h=!0},ud=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},dd=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,s=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===s)return s=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return s|=2,Promise.resolve(a).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});let hd=(()=>{let e,t,r,n,s=[sd],a=[],i=[];(class{static{t=this}static{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ld(this,null,r,{kind:"method",name:"getProperty",static:!1,private:!1,access:{has:e=>"getProperty"in e,get:e=>e.getProperty},metadata:o},null,i),ld(this,null,n,{kind:"method",name:"getProperties",static:!1,private:!1,access:{has:e=>"getProperties"in e,get:e=>e.getProperties},metadata:o},null,i),ld(null,e={value:t},s,{kind:"class",name:t.name,metadata:o},null,a),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cd(t,a)}constructor(){cd(this,i)}async evaluate(e,...t){return e=eu(this.evaluate.name,e),await this.realm.evaluate(e,this,...t)}async evaluateHandle(e,...t){return e=eu(this.evaluateHandle.name,e),await this.realm.evaluateHandle(e,this,...t)}async getProperty(e){return await this.evaluateHandle(((e,t)=>e[t]),e)}async getProperties(){const e=await this.evaluate((e=>{const t=[],r=Object.getOwnPropertyDescriptors(e);for(const e in r)r[e]?.enumerable&&t.push(e);return t})),t=new Map,r=await Promise.all(e.map((e=>this.getProperty(e))));for(const[n,s]of Object.entries(e)){const e={stack:[],error:void 0,hasError:!1};try{const a=ud(e,r[n],!1);a&&t.set(s,a.move())}catch(t){e.error=t,e.hasError=!0}finally{dd(e)}}return t}[(r=[ad()],n=[ad()],Cl)](){this.dispose().catch(Zl)}[Pl](){return this.dispose()}});return t})();var pd=function(e,t,r){for(var n=arguments.length>2,s=0;s=0;p--){var m={};for(var f in n)m[f]="access"===f?{}:n[f];for(var f in n.access)m.access[f]=n.access[f];m.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");a.push(i(e||null))};var g=(0,r[p])("accessor"===c?{get:d.get,set:d.set}:d[l],m);if("accessor"===c){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(o=i(g.get))&&(d.get=o),(o=i(g.set))&&(d.set=o),(o=i(g.init))&&s.unshift(o)}else(o=i(g))&&("field"===c?s.unshift(o):d[l]=o)}u&&Object.defineProperty(u,n.name,d),h=!0},fd=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},gd=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,s=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===s)return s=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return s|=2,Promise.resolve(a).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n}),yd=function(e,t,r){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:r?"".concat(r," ",t):t})};function bd(e,t){return async function(...t){if(this.realm===this.frame.isolatedRealm())return await e.call(this,...t);let r;this.isolatedHandle?r=this.isolatedHandle:this.isolatedHandle=r=await this.frame.isolatedRealm().adoptHandle(this);const n=await e.call(r,...t);return n===r?this:n instanceof hd?await this.realm.transferHandle(n):(Array.isArray(n)&&await Promise.all(n.map((async(e,t,r)=>{e instanceof hd&&(r[t]=await this.realm.transferHandle(e))}))),n instanceof Map&&await Promise.all([...n.entries()].map((async([e,t])=>{t instanceof hd&&n.set(e,await this.realm.transferHandle(t))}))),n)}}let wd=(()=>{let e,t,r,n,s,a,i,o,c,l,u,d,h,p,m,f,g,y,b,w,v,_,k,S,E,x,T,C,P,O,A,I,M=hd,R=[];return class j extends M{static{const j="function"==typeof Symbol&&Symbol.metadata?Object.create(M[Symbol.metadata]??null):void 0;e=[ad(),bd],t=[ad(),bd],r=[ad(),bd],n=[ad(),bd],s=[ad()],a=[bd],o=[ad(),bd],c=[ad(),bd],l=[ad(),bd],u=[ad(),bd],d=[ad(),bd],h=[ad(),bd],p=[ad(),bd],m=[ad(),bd],f=[ad(),bd],g=[ad(),bd],y=[ad(),bd],b=[ad(),bd],w=[ad(),bd],v=[ad(),bd],_=[ad(),bd],k=[ad(),bd],S=[ad(),bd],E=[ad(),bd],x=[ad(),bd],T=[ad(),bd],C=[ad(),bd],P=[ad(),bd],O=[ad(),bd],A=[ad(),bd],I=[ad(),bd],md(this,null,e,{kind:"method",name:"getProperty",static:!1,private:!1,access:{has:e=>"getProperty"in e,get:e=>e.getProperty},metadata:j},null,R),md(this,null,t,{kind:"method",name:"getProperties",static:!1,private:!1,access:{has:e=>"getProperties"in e,get:e=>e.getProperties},metadata:j},null,R),md(this,null,r,{kind:"method",name:"jsonValue",static:!1,private:!1,access:{has:e=>"jsonValue"in e,get:e=>e.jsonValue},metadata:j},null,R),md(this,null,n,{kind:"method",name:"$",static:!1,private:!1,access:{has:e=>"$"in e,get:e=>e.$},metadata:j},null,R),md(this,null,s,{kind:"method",name:"$$",static:!1,private:!1,access:{has:e=>"$$"in e,get:e=>e.$$},metadata:j},null,R),md(this,i={value:yd((async function(e){return await this.#A(e)}),"#$$")},a,{kind:"method",name:"#$$",static:!1,private:!0,access:{has:e=>#I in e,get:e=>e.#I},metadata:j},null,R),md(this,null,o,{kind:"method",name:"waitForSelector",static:!1,private:!1,access:{has:e=>"waitForSelector"in e,get:e=>e.waitForSelector},metadata:j},null,R),md(this,null,c,{kind:"method",name:"isVisible",static:!1,private:!1,access:{has:e=>"isVisible"in e,get:e=>e.isVisible},metadata:j},null,R),md(this,null,l,{kind:"method",name:"isHidden",static:!1,private:!1,access:{has:e=>"isHidden"in e,get:e=>e.isHidden},metadata:j},null,R),md(this,null,u,{kind:"method",name:"toElement",static:!1,private:!1,access:{has:e=>"toElement"in e,get:e=>e.toElement},metadata:j},null,R),md(this,null,d,{kind:"method",name:"clickablePoint",static:!1,private:!1,access:{has:e=>"clickablePoint"in e,get:e=>e.clickablePoint},metadata:j},null,R),md(this,null,h,{kind:"method",name:"hover",static:!1,private:!1,access:{has:e=>"hover"in e,get:e=>e.hover},metadata:j},null,R),md(this,null,p,{kind:"method",name:"click",static:!1,private:!1,access:{has:e=>"click"in e,get:e=>e.click},metadata:j},null,R),md(this,null,m,{kind:"method",name:"drag",static:!1,private:!1,access:{has:e=>"drag"in e,get:e=>e.drag},metadata:j},null,R),md(this,null,f,{kind:"method",name:"dragEnter",static:!1,private:!1,access:{has:e=>"dragEnter"in e,get:e=>e.dragEnter},metadata:j},null,R),md(this,null,g,{kind:"method",name:"dragOver",static:!1,private:!1,access:{has:e=>"dragOver"in e,get:e=>e.dragOver},metadata:j},null,R),md(this,null,y,{kind:"method",name:"drop",static:!1,private:!1,access:{has:e=>"drop"in e,get:e=>e.drop},metadata:j},null,R),md(this,null,b,{kind:"method",name:"dragAndDrop",static:!1,private:!1,access:{has:e=>"dragAndDrop"in e,get:e=>e.dragAndDrop},metadata:j},null,R),md(this,null,w,{kind:"method",name:"select",static:!1,private:!1,access:{has:e=>"select"in e,get:e=>e.select},metadata:j},null,R),md(this,null,v,{kind:"method",name:"tap",static:!1,private:!1,access:{has:e=>"tap"in e,get:e=>e.tap},metadata:j},null,R),md(this,null,_,{kind:"method",name:"touchStart",static:!1,private:!1,access:{has:e=>"touchStart"in e,get:e=>e.touchStart},metadata:j},null,R),md(this,null,k,{kind:"method",name:"touchMove",static:!1,private:!1,access:{has:e=>"touchMove"in e,get:e=>e.touchMove},metadata:j},null,R),md(this,null,S,{kind:"method",name:"touchEnd",static:!1,private:!1,access:{has:e=>"touchEnd"in e,get:e=>e.touchEnd},metadata:j},null,R),md(this,null,E,{kind:"method",name:"focus",static:!1,private:!1,access:{has:e=>"focus"in e,get:e=>e.focus},metadata:j},null,R),md(this,null,x,{kind:"method",name:"type",static:!1,private:!1,access:{has:e=>"type"in e,get:e=>e.type},metadata:j},null,R),md(this,null,T,{kind:"method",name:"press",static:!1,private:!1,access:{has:e=>"press"in e,get:e=>e.press},metadata:j},null,R),md(this,null,C,{kind:"method",name:"boundingBox",static:!1,private:!1,access:{has:e=>"boundingBox"in e,get:e=>e.boundingBox},metadata:j},null,R),md(this,null,P,{kind:"method",name:"boxModel",static:!1,private:!1,access:{has:e=>"boxModel"in e,get:e=>e.boxModel},metadata:j},null,R),md(this,null,O,{kind:"method",name:"screenshot",static:!1,private:!1,access:{has:e=>"screenshot"in e,get:e=>e.screenshot},metadata:j},null,R),md(this,null,A,{kind:"method",name:"isIntersectingViewport",static:!1,private:!1,access:{has:e=>"isIntersectingViewport"in e,get:e=>e.isIntersectingViewport},metadata:j},null,R),md(this,null,I,{kind:"method",name:"scrollIntoView",static:!1,private:!1,access:{has:e=>"scrollIntoView"in e,get:e=>e.scrollIntoView},metadata:j},null,R),j&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:j})}isolatedHandle=pd(this,R);handle;constructor(e){super(),this.handle=e,this[_u]=!0}get id(){return this.handle.id}get disposed(){return this.handle.disposed}async getProperty(e){return await this.handle.getProperty(e)}async getProperties(){return await this.handle.getProperties()}async evaluate(e,...t){return e=eu(this.evaluate.name,e),await this.handle.evaluate(e,...t)}async evaluateHandle(e,...t){return e=eu(this.evaluateHandle.name,e),await this.handle.evaluateHandle(e,...t)}async jsonValue(){return await this.handle.jsonValue()}toString(){return this.handle.toString()}remoteObject(){return this.handle.remoteObject()}async dispose(){await Promise.all([this.handle.dispose(),this.isolatedHandle?.dispose()])}asElement(){return this}async $(e){const{updatedSelector:t,QueryHandler:r}=ed(e);return await r.queryOne(this,t)}async $$(e,t){return!1===t?.isolate?await this.#A(e):await this.#I(e)}get#I(){return i.value}async#A(e){const{updatedSelector:t,QueryHandler:r}=ed(e);return await $u.collect(r.queryAll(this,t))}async $eval(e,t,...r){const n={stack:[],error:void 0,hasError:!1};try{t=eu(this.$eval.name,t);const s=fd(n,await this.$(e),!1);if(!s)throw new Error(`Error: failed to find element matching selector "${e}"`);return await s.evaluate(t,...r)}catch(e){n.error=e,n.hasError=!0}finally{gd(n)}}async $$eval(e,t,...r){const n={stack:[],error:void 0,hasError:!1};try{t=eu(this.$$eval.name,t);const s=await this.$$(e),a=fd(n,await this.evaluateHandle(((e,...t)=>t),...s),!1),[i]=await Promise.all([a.evaluate(t,...r),...s.map((e=>e.dispose()))]);return i}catch(e){n.error=e,n.hasError=!0}finally{gd(n)}}async waitForSelector(e,t={}){const{updatedSelector:r,QueryHandler:n,polling:s}=ed(e);return await n.waitFor(this,r,{polling:s,...t})}async#M(e){return await this.evaluate((async(e,t,r)=>Boolean(t.checkVisibility(e,r))),Mu.create((e=>e.puppeteerUtil)),e)}async isVisible(){return await this.#M(!0)}async isHidden(){return await this.#M(!1)}async toElement(e){const t=await this.evaluate(((e,t)=>e.nodeName===t.toUpperCase()),e);if(!t)throw new Error(`Element is not a(n) \`${e}\` element`);return this}async clickablePoint(e){const t=await this.#R();if(!t)throw new Error("Node is either not clickable or not an Element");return void 0!==e?{x:t.x+e.x,y:t.y+e.y}:{x:t.x+t.width/2,y:t.y+t.height/2}}async hover(){await this.scrollIntoViewIfNeeded();const{x:e,y:t}=await this.clickablePoint();await this.frame.page().mouse.move(e,t)}async click(e={}){await this.scrollIntoViewIfNeeded();const{x:t,y:r}=await this.clickablePoint(e.offset);await this.frame.page().mouse.click(t,r,e)}async drag(e){await this.scrollIntoViewIfNeeded();const t=this.frame.page();if(t.isDragInterceptionEnabled()){const r=await this.clickablePoint();return e instanceof j&&(e=await e.clickablePoint()),await t.mouse.drag(r,e)}try{t._isDragging||(t._isDragging=!0,await this.hover(),await t.mouse.down()),e instanceof j?await e.hover():await t.mouse.move(e.x,e.y)}catch(e){throw t._isDragging=!1,e}}async dragEnter(e={items:[],dragOperationsMask:1}){const t=this.frame.page();await this.scrollIntoViewIfNeeded();const r=await this.clickablePoint();await t.mouse.dragEnter(r,e)}async dragOver(e={items:[],dragOperationsMask:1}){const t=this.frame.page();await this.scrollIntoViewIfNeeded();const r=await this.clickablePoint();await t.mouse.dragOver(r,e)}async drop(e={items:[],dragOperationsMask:1}){const t=this.frame.page();if("items"in e){await this.scrollIntoViewIfNeeded();const r=await this.clickablePoint();await t.mouse.drop(r,e)}else await e.drag(this),t._isDragging=!1,await t.mouse.up()}async dragAndDrop(e,t){const r=this.frame.page();$l(r.isDragInterceptionEnabled(),"Drag Interception is not enabled!"),await this.scrollIntoViewIfNeeded();const n=await this.clickablePoint(),s=await e.clickablePoint();await r.mouse.dragAndDrop(n,s,t)}async select(...e){for(const t of e)$l(tu(t),'Values must be strings. Found value "'+t+'" of type "'+typeof t+'"');return await this.evaluate(((e,t)=>{const r=new Set(t);if(!(e instanceof HTMLSelectElement))throw new Error("Element is not a ");const r=jl.value.path;if(r&&(e=e.map((e=>r.win32.isAbsolute(e)||r.posix.isAbsolute(e)?e:r.resolve(e)))),0===e.length)return void await this.evaluate((e=>{e.files=(new DataTransfer).files,e.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}));const{node:{backendNodeId:n}}=await this.client.send("DOM.describeNode",{objectId:this.id});await this.client.send("DOM.setFileInputFiles",{objectId:this.id,files:e,backendNodeId:n})}async autofill(e){const t=(await this.client.send("DOM.describeNode",{objectId:this.handle.id})).node.backendNodeId,r=this.frame._id;await this.client.send("Autofill.trigger",{fieldId:t,frameId:r,card:e.creditCard})}async*queryAXTree(e,t){const{nodes:r}=await this.client.send("Accessibility.queryAXTree",{objectId:this.id,accessibleName:e,role:t}),n=r.filter((e=>!e.ignored&&(!!e.role&&!Xh.has(e.role.value))));return yield*$u.map(n,(e=>this.realm.adoptBackendNode(e.backendDOMNodeId)))}async backendNodeId(){if(this.#hr)return this.#hr;const{node:e}=await this.client.send("DOM.describeNode",{objectId:this.handle.id});return this.#hr=e.backendNodeId,this.#hr}}})();var Qh=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},ep=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,s=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===s)return s=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return s|=2,Promise.resolve(a).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const tp=new yh("__ariaQuerySelector",Fu.queryOne,""),rp=new yh("__ariaQuerySelectorAll",(async(e,t)=>{const r=Fu.queryAll(e,t);return await e.realm.evaluateHandle(((...e)=>e),...await $u.collect(r))}),"");class np extends Ml{#mt;#pe;#Je;#Me;#mr=new Ol;constructor(e,t,r){super(),this.#mt=e,this.#pe=r,this.#Je=t.id,t.name&&(this.#Me=t.name);const n=this.#mr.use(new Ml(this.#mt));n.on("Runtime.bindingCalled",this.#fr.bind(this)),n.on("Runtime.executionContextDestroyed",(async e=>{e.executionContextId===this.#Je&&this[Cl]()})),n.on("Runtime.executionContextsCleared",(async()=>{this[Cl]()})),n.on("Runtime.consoleAPICalled",this.#gr.bind(this)),n.on(wu.Disconnected,(()=>{this[Cl]()}))}#yr=new Map;#v=new yu;async#br(e){const t={stack:[],error:void 0,hasError:!1};try{if(this.#yr.has(e.name))return;Qh(t,await this.#v.acquire(),!1);try{await this.#mt.send("Runtime.addBinding",this.#Me?{name:Hh+e.name,executionContextName:this.#Me}:{name:Hh+e.name,executionContextId:this.#Je}),await this.evaluate(Wh,"internal",e.name,Hh),this.#yr.set(e.name,e)}catch(e){if(e instanceof Error){if(e.message.includes("Execution context was destroyed"))return;if(e.message.includes("Cannot find context with specified id"))return}Zl(e)}}catch(e){t.error=e,t.hasError=!0}finally{ep(t)}}async#fr(e){if(e.executionContextId!==this.#Je)return;let t;try{t=JSON.parse(e.payload)}catch{return}const{type:r,name:n,seq:s,args:a,isTrivial:i}=t;if("internal"===r)if(this.#yr.has(n))try{const e=this.#yr.get(n);await(e?.run(this,s,a,i))}catch(e){Zl(e)}else this.emit("bindingcalled",e);else this.emit("bindingcalled",e)}get id(){return this.#Je}#gr(e){e.executionContextId===this.#Je&&this.emit("consoleapicalled",e)}#wr=!1;#vr;get puppeteerUtil(){let e=Promise.resolve();return this.#wr||(e=Promise.all([this.#_r(tp),this.#_r(rp)]),this.#wr=!0),zu.inject((t=>{this.#vr&&this.#vr.then((e=>{e.dispose()})),this.#vr=e.then((()=>this.evaluateHandle(t)))}),!this.#vr),this.#vr}async#_r(e){try{await this.#br(e)}catch(e){Zl(e)}}async evaluate(e,...t){return await this.#kr(!0,e,...t)}async evaluateHandle(e,...t){return await this.#kr(!1,e,...t)}async#kr(e,t,...r){const n=`//# sourceURL=${(e=>{if(Object.prototype.hasOwnProperty.call(e,Yl))return e[Yl]})(t)?.toString()??Ql.INTERNAL_URL}`;if(tu(t)){const r=this.#Je,s=t,a=ou.test(s)?s:`${s}\n${n}\n`,{exceptionDetails:i,result:o}=await this.#mt.send("Runtime.evaluate",{expression:a,contextId:r,returnByValue:e,awaitPromise:!0,userGesture:!0}).catch(sp);if(i)throw Bh(i);return e?Kh(o):this.#pe.createCdpHandle(o)}const s=Tu(t),a=ou.test(s)?s:`${s}\n${n}\n`;let i;try{i=this.#mt.send("Runtime.callFunctionOn",{functionDeclaration:a,executionContextId:this.#Je,arguments:r.some((e=>e instanceof Mu))?await Promise.all(r.map((e=>async function(e,t){t instanceof Mu&&(t=await t.get(e));return l(e,t)}(this,e)))):r.map((e=>l(this,e))),returnByValue:e,awaitPromise:!0,userGesture:!0})}catch(e){throw e instanceof TypeError&&e.message.startsWith("Converting circular structure to JSON")&&(e.message+=" Recursive objects are not allowed."),e}const{exceptionDetails:o,result:c}=await i.catch(sp);if(o)throw Bh(o);return e?Kh(c):this.#pe.createCdpHandle(c);function l(e,t){if("bigint"==typeof t)return{unserializableValue:`${t.toString()}n`};if(Object.is(t,-0))return{unserializableValue:"-0"};if(Object.is(t,1/0))return{unserializableValue:"Infinity"};if(Object.is(t,-1/0))return{unserializableValue:"-Infinity"};if(Object.is(t,NaN))return{unserializableValue:"NaN"};const r=t&&(t instanceof Vh||t instanceof Yh)?t:null;if(r){if(r.realm!==e.#pe)throw new Error("JSHandles can be evaluated only in the context they were created!");if(r.disposed)throw new Error("JSHandle is disposed!");return r.remoteObject().unserializableValue?{unserializableValue:r.remoteObject().unserializableValue}:r.remoteObject().objectId?{objectId:r.remoteObject().objectId}:{value:r.remoteObject().value}}return{value:t}}}[Cl](){this.#mr.dispose(),this.emit("disposed",void 0)}}const sp=e=>{if(e.message.includes("Object reference chain is too long"))return{result:{type:"undefined"}};if(e.message.includes("Object couldn't be returned by value"))return{result:{type:"undefined"}};if(e.message.endsWith("Cannot find context with specified id")||e.message.endsWith("Inspected target navigated or closed"))throw new Error("Execution context was destroyed, most likely because of a navigation.");throw e};var ap;!function(e){e.FrameAttached=Symbol("FrameManager.FrameAttached"),e.FrameNavigated=Symbol("FrameManager.FrameNavigated"),e.FrameDetached=Symbol("FrameManager.FrameDetached"),e.FrameSwapped=Symbol("FrameManager.FrameSwapped"),e.LifecycleEvent=Symbol("FrameManager.LifecycleEvent"),e.FrameNavigatedWithinDocument=Symbol("FrameManager.FrameNavigatedWithinDocument"),e.ConsoleApiCalled=Symbol("FrameManager.ConsoleApiCalled"),e.BindingCalled=Symbol("FrameManager.BindingCalled")}(ap||(ap={}));class ip extends ih{#Sr;#a=new Ml;#Er;constructor(e,t){super(t),this.#Er=e}get environment(){return this.#Er}get client(){return this.#Er.client}get emitter(){return this.#a}setContext(e){this.#Sr?.[Cl](),e.once("disposed",this.#xr.bind(this)),e.on("consoleapicalled",this.#Tr.bind(this)),e.on("bindingcalled",this.#Cr.bind(this)),this.#Sr=e,this.#a.emit("context",e),this.taskManager.rerunAll()}#xr(){this.#Sr=void 0,"clearDocumentHandle"in this.#Er&&this.#Er.clearDocumentHandle()}#Tr(e){this.#a.emit("consoleapicalled",e)}#Cr(e){this.#a.emit("bindingcalled",e)}hasContext(){return!!this.#Sr}get context(){return this.#Sr}#Pr(){if(this.disposed)throw new Error(`Execution context is not available in detached frame or worker "${this.environment.url()}" (are you trying to evaluate?)`);return this.#Sr}async#Or(){const e=new Error("Execution context was destroyed");return await Zc(du(this.#a,"context").pipe(El(du(this.#a,"disposed").pipe(Xc((()=>{throw e}))),au(this.timeoutSettings.timeout()))))}async evaluateHandle(e,...t){e=eu(this.evaluateHandle.name,e);let r=this.#Pr();return r||(r=await this.#Or()),await r.evaluateHandle(e,...t)}async evaluate(e,...t){e=eu(this.evaluate.name,e);let r=this.#Pr();return r||(r=await this.#Or()),await r.evaluate(e,...t)}async adoptBackendNode(e){let t=this.#Pr();t||(t=await this.#Or());const{object:r}=await this.client.send("DOM.resolveNode",{backendNodeId:e,executionContextId:t.id});return this.createCdpHandle(r)}async adoptHandle(e){if(e.realm===this)return await e.evaluateHandle((e=>e));const t=await this.client.send("DOM.describeNode",{objectId:e.id});return await this.adoptBackendNode(t.node.backendNodeId)}async transferHandle(e){if(e.realm===this)return e;if(void 0===e.remoteObject().objectId)return e;const t=await this.client.send("DOM.describeNode",{objectId:e.remoteObject().objectId}),r=await this.adoptBackendNode(t.node.backendNodeId);return await e.dispose(),r}createCdpHandle(e){return"node"===e.subtype?new Yh(this,e):new Vh(this,e)}[Cl](){this.#Sr?.[Cl](),this.#a.emit("disposed",void 0),super[Cl](),this.#a.removeAllListeners()}}const op=Symbol("mainWorld"),cp=Symbol("puppeteerWorld"),lp=new Map([["load","load"],["domcontentloaded","DOMContentLoaded"],["networkidle0","networkIdle"],["networkidle2","networkAlmostIdle"]]);class up{#Ar;#qe;#be;#Ir=null;#bt=new Ol;#Mr;#Rr;#jr=gu.create();#Nr=gu.create();#$r=gu.create();#Lr;#Fr;#Dr;constructor(e,t,r,n,s){Array.isArray(r)?r=r.slice():"string"==typeof r&&(r=[r]),this.#Mr=t._loaderId,this.#Ar=r.map((e=>{const t=lp.get(e);return $l(t,"Unknown value for options.waitUntil: "+e),t})),s?.addEventListener("abort",(()=>{this.#Rr.reject(s.reason)})),this.#qe=t,this.#be=n;this.#bt.use(new Ml(t._frameManager)).on(ap.LifecycleEvent,this.#zr.bind(this));const a=this.#bt.use(new Ml(t));a.on(Md.FrameNavigatedWithinDocument,this.#Ur.bind(this)),a.on(Md.FrameNavigated,this.#Br.bind(this)),a.on(Md.FrameSwapped,this.#qr.bind(this)),a.on(Md.FrameSwappedByActivation,this.#qr.bind(this)),a.on(Md.FrameDetached,this.#Kr.bind(this));const i=this.#bt.use(new Ml(e));i.on(mh.Request,this.#Wr.bind(this)),i.on(mh.Response,this.#Hr.bind(this)),i.on(mh.RequestFailed,this.#Vr.bind(this)),this.#Rr=gu.create({timeout:this.#be,message:`Navigation timeout of ${this.#be} ms exceeded`}),this.#zr()}#Wr(e){e.frame()===this.#qe&&e.isNavigationRequest()&&(this.#Ir=e,this.#Dr?.resolve(),this.#Dr=gu.create(),null!==e.response()&&this.#Dr?.resolve())}#Vr(e){this.#Ir?.id===e.id&&this.#Dr?.resolve()}#Hr(e){this.#Ir?.id===e.request().id&&this.#Dr?.resolve()}#Kr(e){this.#qe!==e?this.#zr():this.#Rr.resolve(new Error("Navigating frame was detached"))}async navigationResponse(){return await(this.#Dr?.valueOrThrow()),this.#Ir?this.#Ir.response():null}sameDocumentNavigationPromise(){return this.#jr.valueOrThrow()}newDocumentNavigationPromise(){return this.#$r.valueOrThrow()}lifecyclePromise(){return this.#Nr.valueOrThrow()}terminationPromise(){return this.#Rr.valueOrThrow()}#Ur(){this.#Lr=!0,this.#zr()}#Br(e){if("BackForwardCacheRestore"===e)return this.#qr();this.#zr()}#qr(){this.#Fr=!0,this.#zr()}#zr(){(function e(t,r){for(const e of r)if(!t._lifecycleEvents.has(e))return!1;for(const n of t.childFrames())if(n._hasStartedLoading&&!e(n,r))return!1;return!0})(this.#qe,this.#Ar)&&(this.#Nr.resolve(),this.#Lr&&this.#jr.resolve(void 0),(this.#Fr||this.#qe._loaderId!==this.#Mr)&&this.#$r.resolve(void 0))}dispose(){this.#bt.dispose(),this.#Rr.resolve(new Error("LifecycleWatcher disposed"))}}var dp=function(e,t,r){for(var n=arguments.length>2,s=0;s=0;p--){var m={};for(var f in n)m[f]="access"===f?{}:n[f];for(var f in n.access)m.access[f]=n.access[f];m.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");a.push(i(e||null))};var g=(0,r[p])("accessor"===c?{get:d.get,set:d.set}:d[l],m);if("accessor"===c){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(o=i(g.get))&&(d.get=o),(o=i(g.set))&&(d.set=o),(o=i(g.init))&&s.unshift(o)}else(o=i(g))&&("field"===c?s.unshift(o):d[l]=o)}u&&Object.defineProperty(u,n.name,d),h=!0};let pp=(()=>{let e,t,r,n,s,a,i,o=Fd,c=[];return class extends o{static{const l="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;hp(this,null,e,{kind:"method",name:"goto",static:!1,private:!1,access:{has:e=>"goto"in e,get:e=>e.goto},metadata:l},null,c),hp(this,null,t,{kind:"method",name:"waitForNavigation",static:!1,private:!1,access:{has:e=>"waitForNavigation"in e,get:e=>e.waitForNavigation},metadata:l},null,c),hp(this,null,r,{kind:"method",name:"setContent",static:!1,private:!1,access:{has:e=>"setContent"in e,get:e=>e.setContent},metadata:l},null,c),hp(this,null,n,{kind:"method",name:"addPreloadScript",static:!1,private:!1,access:{has:e=>"addPreloadScript"in e,get:e=>e.addPreloadScript},metadata:l},null,c),hp(this,null,s,{kind:"method",name:"addExposedFunctionBinding",static:!1,private:!1,access:{has:e=>"addExposedFunctionBinding"in e,get:e=>e.addExposedFunctionBinding},metadata:l},null,c),hp(this,null,a,{kind:"method",name:"removeExposedFunctionBinding",static:!1,private:!1,access:{has:e=>"removeExposedFunctionBinding"in e,get:e=>e.removeExposedFunctionBinding},metadata:l},null,c),hp(this,null,i,{kind:"method",name:"waitForDevicePrompt",static:!1,private:!1,access:{has:e=>"waitForDevicePrompt"in e,get:e=>e.waitForDevicePrompt},metadata:l},null,c),l&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:l})}#xe=(dp(this,c),"");#at=!1;#mt;_frameManager;_loaderId="";_lifecycleEvents=new Set;_id;_parentId;accessibility;worlds;constructor(e,t,r,n){super(),this._frameManager=e,this.#xe="",this._id=t,this._parentId=r,this.#at=!1,this.#mt=n,this._loaderId="",this.worlds={[op]:new ip(this,this._frameManager.timeoutSettings),[cp]:new ip(this,this._frameManager.timeoutSettings)},this.accessibility=new hh(this.worlds[op],t),this.on(Md.FrameSwappedByActivation,(()=>{this._onLoadingStarted(),this._onLoadingStopped()})),this.worlds[op].emitter.on("consoleapicalled",this.#Gr.bind(this)),this.worlds[op].emitter.on("bindingcalled",this.#Jr.bind(this))}#Gr(e){this._frameManager.emit(ap.ConsoleApiCalled,[this.worlds[op],e])}#Jr(e){this._frameManager.emit(ap.BindingCalled,[this.worlds[op],e])}_client(){return this.#mt}updateId(e){this._id=e}updateClient(e){this.#mt=e}page(){return this._frameManager.page()}async goto(e,t={}){const{referer:r=this._frameManager.networkManager.extraHTTPHeaders().referer,referrerPolicy:n=this._frameManager.networkManager.extraHTTPHeaders()["referer-policy"],waitUntil:s=["load"],timeout:a=this._frameManager.timeoutSettings.navigationTimeout()}=t;let i=!1;const o=new up(this._frameManager.networkManager,this,s,a);let c=await gu.race([async function(e,t,r,n,s){try{const a=await e.send("Page.navigate",{url:t,referrer:r,frameId:s,referrerPolicy:n});return i=!!a.loaderId,"net::ERR_HTTP_RESPONSE_CODE_FAILURE"===a.errorText?null:a.errorText?new Error(`${a.errorText} at ${t}`):null}catch(e){if(ku(e))return e;throw e}}(this.#mt,e,r,n,this._id),o.terminationPromise()]);c||(c=await gu.race([o.terminationPromise(),i?o.newDocumentNavigationPromise():o.sameDocumentNavigationPromise()]));try{if(c)throw c;return await o.navigationResponse()}finally{o.dispose()}}async waitForNavigation(e={}){const{waitUntil:t=["load"],timeout:r=this._frameManager.timeoutSettings.navigationTimeout(),signal:n}=e,s=new up(this._frameManager.networkManager,this,t,r,n),a=await gu.race([s.terminationPromise(),...e.ignoreSameDocumentNavigation?[]:[s.sameDocumentNavigationPromise()],s.newDocumentNavigationPromise()]);try{if(a)throw a;const e=await gu.race([s.terminationPromise(),s.navigationResponse()]);if(e instanceof Error)throw a;return e||null}finally{s.dispose()}}get client(){return this.#mt}mainRealm(){return this.worlds[op]}isolatedRealm(){return this.worlds[cp]}async setContent(e,t={}){const{waitUntil:r=["load"],timeout:n=this._frameManager.timeoutSettings.navigationTimeout()}=t;await this.setFrameContent(e);const s=new up(this._frameManager.networkManager,this,r,n),a=await gu.race([s.terminationPromise(),s.lifecyclePromise()]);if(s.dispose(),a)throw a}url(){return this.#xe}parentFrame(){return this._frameManager._frameTree.parentFrame(this._id)||null}childFrames(){return this._frameManager._frameTree.childFrames(this._id)}#Zr(){return this._frameManager._deviceRequestPromptManager(this.#mt)}async addPreloadScript(e){const t=this.parentFrame();if(t&&this.#mt===t.client)return;if(e.getIdForFrame(this))return;const{identifier:r}=await this.#mt.send("Page.addScriptToEvaluateOnNewDocument",{source:e.source});e.setIdForFrame(this,r)}async addExposedFunctionBinding(e){(this===this._frameManager.mainFrame()||this._hasStartedLoading)&&await Promise.all([this.#mt.send("Runtime.addBinding",{name:Hh+e.name}),this.evaluate(e.initSource).catch(Zl)])}async removeExposedFunctionBinding(e){(this===this._frameManager.mainFrame()||this._hasStartedLoading)&&await Promise.all([this.#mt.send("Runtime.removeBinding",{name:Hh+e.name}),this.evaluate((e=>{globalThis[e]=void 0}),e.name).catch(Zl)])}async waitForDevicePrompt(e={}){return await this.#Zr().waitForDevicePrompt(e)}_navigated(e){this._name=e.name,this.#xe=`${e.url}${e.urlFragment||""}`}_navigatedWithinDocument(e){this.#xe=e}_onLifecycleEvent(e,t){"init"===t&&(this._loaderId=e,this._lifecycleEvents.clear()),this._lifecycleEvents.add(t)}_onLoadingStopped(){this._lifecycleEvents.add("DOMContentLoaded"),this._lifecycleEvents.add("load")}_onLoadingStarted(){this._hasStartedLoading=!0}get detached(){return this.#at}[(e=[Ld],t=[Ld],r=[Ld],n=[Ld],s=[Ld],a=[Ld],i=[Ld],Cl)](){this.#at||(this.#at=!0,this.worlds[op][Cl](),this.worlds[cp][Cl]())}exposeFunction(){throw new Vl}async frameElement(){const e=this.parentFrame();if(!e)return null;const{backendNodeId:t}=await e.client.send("DOM.getFrameOwner",{frameId:this._id});return await e.mainRealm().adoptBackendNode(t)}}})();class mp{#Xr=new Map;#Yr=new Map;#Qr=new Map;#en;#tn=!1;#rn=new Map;getMainFrame(){return this.#en}getById(e){return this.#Xr.get(e)}waitForFrame(e){const t=this.getById(e);if(t)return Promise.resolve(t);const r=gu.create();return(this.#rn.get(e)||new Set).add(r),r.valueOrThrow()}frames(){return Array.from(this.#Xr.values())}addFrame(e){this.#Xr.set(e._id,e),e._parentId?(this.#Yr.set(e._id,e._parentId),this.#Qr.has(e._parentId)||this.#Qr.set(e._parentId,new Set),this.#Qr.get(e._parentId).add(e._id)):this.#en&&!this.#tn||(this.#en=e,this.#tn=!1),this.#rn.get(e._id)?.forEach((t=>t.resolve(e)))}removeFrame(e){this.#Xr.delete(e._id),this.#Yr.delete(e._id),e._parentId?this.#Qr.get(e._parentId)?.delete(e._id):this.#tn=!0}childFrames(e){const t=this.#Qr.get(e);return t?Array.from(t).map((e=>this.getById(e))).filter((e=>void 0!==e)):[]}parentFrame(e){const t=this.#Yr.get(e);return t?this.getById(t):void 0}}class fp extends Dd{id;#mt;#nn;#xe;#sn;#an;#in=!1;#on;#cn={};#qe;#ln;get client(){return this.#mt}set client(e){this.#mt=e}constructor(e,t,r,n,s,a){super(),this.#mt=e,this.id=s.requestId,this.#nn=s.requestId===s.loaderId&&"Document"===s.type,this._interceptionId=r,this.#xe=s.request.url+(s.request.urlFragment??""),this.#sn=(s.type||"other").toLowerCase(),this.#an=s.request.method,this.#on=s.request.postData,this.#in=s.request.hasPostData??!1,this.#qe=t,this._redirectChain=a,this.#ln=s.initiator,this.interception.enabled=n;for(const[e,t]of Object.entries(s.request.headers))this.#cn[e.toLowerCase()]=t}url(){return this.#xe}resourceType(){return this.#sn}method(){return this.#an}postData(){return this.#on}hasPostData(){return this.#in}async fetchPostData(){try{return(await this.#mt.send("Network.getRequestPostData",{requestId:this.id})).postData}catch(e){return void Zl(e)}}headers(){return this.#cn}response(){return this._response}frame(){return this.#qe}isNavigationRequest(){return this.#nn}initiator(){return this.#ln}redirectChain(){return this._redirectChain.slice()}failure(){return this._failureText?{errorText:this._failureText}:null}async _continue(e={}){const{url:t,method:r,postData:n,headers:s}=e;this.interception.handled=!0;const a=n?function(e){return Fl((new TextEncoder).encode(e))}(n):void 0;if(void 0===this._interceptionId)throw new Error("HTTPRequest is missing _interceptionId needed for Fetch.continueRequest");await this.#mt.send("Fetch.continueRequest",{requestId:this._interceptionId,url:t,method:r,postData:a,headers:s?Ud(s):void 0}).catch((e=>(this.interception.handled=!1,Kd(e))))}async _respond(e){let t;this.interception.handled=!0,e.body&&(t=Dd.getResponse(e.body));const r={};if(e.headers)for(const t of Object.keys(e.headers)){const n=e.headers[t];r[t.toLowerCase()]=Array.isArray(n)?n.map((e=>String(e))):String(n)}e.contentType&&(r["content-type"]=e.contentType),t?.contentLength&&!("content-length"in r)&&(r["content-length"]=String(t.contentLength));const n=e.status||200;if(void 0===this._interceptionId)throw new Error("HTTPRequest is missing _interceptionId needed for Fetch.fulfillRequest");await this.#mt.send("Fetch.fulfillRequest",{requestId:this._interceptionId,responseCode:n,responsePhrase:Bd[n],responseHeaders:Ud(r),body:t?.base64}).catch((e=>(this.interception.handled=!1,Kd(e))))}async _abort(e){if(this.interception.handled=!0,void 0===this._interceptionId)throw new Error("HTTPRequest is missing _interceptionId needed for Fetch.failRequest");await this.#mt.send("Fetch.failRequest",{requestId:this._interceptionId,errorReason:e||"Failed"}).catch(Kd)}}class gp{constructor(){}ok(){const e=this.status();return 0===e||e>=200&&e<=299}async buffer(){const e=await this.content();return Buffer.from(e)}async text(){const e=await this.content();return(new TextDecoder).decode(e)}async json(){const e=await this.text();return JSON.parse(e)}}class yp{#un;#dn;#hn;#pn;#mn;#fn;constructor(e){this.#un=e.subjectName,this.#dn=e.issuer,this.#hn=e.validFrom,this.#pn=e.validTo,this.#mn=e.protocol,this.#fn=e.sanList}issuer(){return this.#dn}validFrom(){return this.#hn}validTo(){return this.#pn}protocol(){return this.#mn}subjectName(){return this.#un}subjectAlternativeNames(){return this.#fn}}class bp extends gp{#gn;#yn=null;#bn=gu.create();#wn;#vn;#_n;#kn;#Sn;#cn={};#En;#xn;constructor(e,t,r){super(),this.#gn=e,this.#wn={ip:t.remoteIPAddress,port:t.remotePort},this.#_n=this.#Tn(r)||t.statusText,this.#kn=!!t.fromDiskCache,this.#Sn=!!t.fromServiceWorker,this.#vn=r?r.statusCode:t.status;const n=r?r.headers:t.headers;for(const[e,t]of Object.entries(n))this.#cn[e.toLowerCase()]=t;this.#En=t.securityDetails?new yp(t.securityDetails):null,this.#xn=t.timing||null}#Tn(e){if(!e||!e.headersText)return;const t=e.headersText.split("\r",1)[0];if(!t||t.length>1e3)return;const r=t.match(/[^ ]* [^ ]* (.*)/);if(!r)return;const n=r[1];return n||void 0}_resolveBody(e){return e?this.#bn.reject(e):this.#bn.resolve()}remoteAddress(){return this.#wn}url(){return this.#gn.url()}status(){return this.#vn}statusText(){return this.#_n}headers(){return this.#cn}securityDetails(){return this.#En}timing(){return this.#xn}content(){return this.#yn||(this.#yn=this.#bn.valueOrThrow().then((async()=>{try{const e=await this.#gn.client.send("Network.getResponseBody",{requestId:this.#gn.id});return Ll(e.body,e.base64Encoded)}catch(e){if(e instanceof Hl&&"No resource with given identifier found"===e.originalMessage)throw new Hl("Could not load body for this request. This might happen if the request is a preflight request.");throw e}}))),this.#yn}request(){return this.#gn}fromCache(){return this.#kn||this.#gn._fromMemoryCache}fromServiceWorker(){return this.#Sn}frame(){return this.#gn.frame()}}class wp{#Cn=new Map;#Pn=new Map;#On=new Map;#An=new Map;#In=new Map;#Mn=new Map;forget(e){this.#Cn.delete(e),this.#Pn.delete(e),this.#Mn.delete(e),this.#In.delete(e),this.#An.delete(e)}responseExtraInfo(e){return this.#An.has(e)||this.#An.set(e,[]),this.#An.get(e)}queuedRedirectInfo(e){return this.#In.has(e)||this.#In.set(e,[]),this.#In.get(e)}queueRedirectInfo(e,t){this.queuedRedirectInfo(e).push(t)}takeQueuedRedirectInfo(e){return this.queuedRedirectInfo(e).shift()}inFlightRequestsCount(){let e=0;for(const t of this.#On.values())t.response()||e++;return e}storeRequestWillBeSent(e,t){this.#Cn.set(e,t)}getRequestWillBeSent(e){return this.#Cn.get(e)}forgetRequestWillBeSent(e){this.#Cn.delete(e)}getRequestPaused(e){return this.#Pn.get(e)}forgetRequestPaused(e){this.#Pn.delete(e)}storeRequestPaused(e,t){this.#Pn.set(e,t)}getRequest(e){return this.#On.get(e)}storeRequest(e,t){this.#On.set(e,t)}forgetRequest(e){this.#On.delete(e)}getQueuedEventGroup(e){return this.#Mn.get(e)}queueEventGroup(e,t){this.#Mn.set(e,t)}forgetQueuedEventGroup(e){this.#Mn.delete(e)}printState(){function e(e,t){return t instanceof Map?{dataType:"Map",value:Array.from(t.entries())}:t instanceof fp?{dataType:"CdpHTTPRequest",value:`${t.id}: ${t.url()}`}:t}console.log("httpRequestsMap",JSON.stringify(this.#On,e,2)),console.log("requestWillBeSentMap",JSON.stringify(this.#Cn,e,2)),console.log("requestWillBeSentMap",JSON.stringify(this.#An,e,2)),console.log("requestWillBeSentMap",JSON.stringify(this.#Pn,e,2))}}class vp extends Ml{#pr;#Rn=new wp;#jn;#Nn=null;#$n=new Set;#Ln=!1;#Fn=!1;#Dn;#zn;#Un;#Bn;#i=[["Fetch.requestPaused",this.#qn],["Fetch.authRequired",this.#Kn],["Network.requestWillBeSent",this.#Wn],["Network.requestServedFromCache",this.#Hn],["Network.responseReceived",this.#Vn],["Network.loadingFinished",this.#Gn],["Network.loadingFailed",this.#Jn],["Network.responseReceivedExtraInfo",this.#Zn],[wu.Disconnected,this.#Xn]];#Yn=new Map;constructor(e){super(),this.#pr=e}async addClient(e){if(this.#Yn.has(e))return;const t=new Ol;this.#Yn.set(e,t);const r=t.use(new Ml(e));for(const[t,n]of this.#i)r.on(t,(t=>n.bind(this)(e,t)));await Promise.all([e.send("Network.enable"),this.#Qn(e),this.#es(e),this.#ts(e),this.#rs(e),this.#ns(e)])}async#Xn(e){this.#Yn.get(e)?.dispose(),this.#Yn.delete(e)}async authenticate(e){this.#Nn=e;const t=this.#Ln||!!this.#Nn;t!==this.#Fn&&(this.#Fn=t,await this.#ss(this.#rs.bind(this)))}async setExtraHTTPHeaders(e){const t={};for(const[r,n]of Object.entries(e))$l(tu(n),`Expected value of header "${r}" to be String, but "${typeof n}" is found.`),t[r.toLowerCase()]=n;this.#jn=t,await this.#ss(this.#Qn.bind(this))}async#Qn(e){void 0!==this.#jn&&await e.send("Network.setExtraHTTPHeaders",{headers:this.#jn})}extraHTTPHeaders(){return Object.assign({},this.#jn)}inFlightRequestsCount(){return this.#Rn.inFlightRequestsCount()}async setOfflineMode(e){this.#zn||(this.#zn={offline:!1,upload:-1,download:-1,latency:0}),this.#zn.offline=e,await this.#ss(this.#es.bind(this))}async emulateNetworkConditions(e){this.#zn||(this.#zn={offline:!1,upload:-1,download:-1,latency:0}),this.#zn.upload=e?e.upload:-1,this.#zn.download=e?e.download:-1,this.#zn.latency=e?e.latency:0,await this.#ss(this.#es.bind(this))}async#ss(e){await Promise.all(Array.from(this.#Yn.keys()).map((t=>e(t))))}async#es(e){void 0!==this.#zn&&await e.send("Network.emulateNetworkConditions",{offline:this.#zn.offline,latency:this.#zn.latency,uploadThroughput:this.#zn.upload,downloadThroughput:this.#zn.download})}async setUserAgent(e,t){this.#Un=e,this.#Bn=t,await this.#ss(this.#ns.bind(this))}async#ns(e){void 0!==this.#Un&&await e.send("Network.setUserAgentOverride",{userAgent:this.#Un,userAgentMetadata:this.#Bn})}async setCacheEnabled(e){this.#Dn=!e,await this.#ss(this.#ts.bind(this))}async setRequestInterception(e){this.#Ln=e;const t=this.#Ln||!!this.#Nn;t!==this.#Fn&&(this.#Fn=t,await this.#ss(this.#rs.bind(this)))}async#rs(e){void 0===this.#Dn&&(this.#Dn=!1),this.#Fn?await Promise.all([this.#ts(e),e.send("Fetch.enable",{handleAuthRequests:!0,patterns:[{urlPattern:"*"}]})]):await Promise.all([this.#ts(e),e.send("Fetch.disable")])}async#ts(e){void 0!==this.#Dn&&await e.send("Network.setCacheDisabled",{cacheDisabled:this.#Dn})}#Wn(e,t){if(!this.#Ln||t.request.url.startsWith("data:"))this.#Wr(e,t,void 0);else{const{requestId:r}=t;this.#Rn.storeRequestWillBeSent(r,t);const n=this.#Rn.getRequestPaused(r);if(n){const{requestId:s}=n;this.#as(t,n),this.#Wr(e,t,s),this.#Rn.forgetRequestPaused(r)}}}#Kn(e,t){let r="Default";this.#$n.has(t.requestId)?r="CancelAuth":this.#Nn&&(r="ProvideCredentials",this.#$n.add(t.requestId));const{username:n,password:s}=this.#Nn||{username:void 0,password:void 0};e.send("Fetch.continueWithAuth",{requestId:t.requestId,authChallengeResponse:{response:r,username:n,password:s}}).catch(Zl)}#qn(e,t){!this.#Ln&&this.#Fn&&e.send("Fetch.continueRequest",{requestId:t.requestId}).catch(Zl);const{networkId:r,requestId:n}=t;if(!r)return void this.#is(e,t);const s=(()=>{const e=this.#Rn.getRequestWillBeSent(r);if(!e||e.request.url===t.request.url&&e.request.method===t.request.method)return e;this.#Rn.forgetRequestWillBeSent(r)})();s?(this.#as(s,t),this.#Wr(e,s,n)):this.#Rn.storeRequestPaused(r,t)}#as(e,t){e.request.headers={...e.request.headers,...t.request.headers}}#is(e,t){const r=t.frameId?this.#pr.frame(t.frameId):null,n=new fp(e,r,t.requestId,this.#Ln,t,[]);this.emit(mh.Request,n),n.finalizeInterceptions()}#Wr(e,t,r,n=!1){let s=[];if(t.redirectResponse){let n=null;if(t.redirectHasExtraInfo&&(n=this.#Rn.responseExtraInfo(t.requestId).shift(),!n))return void this.#Rn.queueRedirectInfo(t.requestId,{event:t,fetchRequestId:r});const a=this.#Rn.getRequest(t.requestId);a&&(this.#os(e,a,t.redirectResponse,n),s=a._redirectChain)}const a=t.frameId?this.#pr.frame(t.frameId):null,i=new fp(e,a,r,this.#Ln,t,s);i._fromMemoryCache=n,this.#Rn.storeRequest(t.requestId,i),this.emit(mh.Request,i),i.finalizeInterceptions()}#Hn(e,t){const r=this.#Rn.getRequestWillBeSent(t.requestId);let n=this.#Rn.getRequest(t.requestId);n&&(n._fromMemoryCache=!0),!n&&r&&(this.#Wr(e,r,void 0,!0),n=this.#Rn.getRequest(t.requestId)),n?this.emit(mh.RequestServedFromCache,n):Zl(new Error(`Request ${t.requestId} was served from cache but we could not find the corresponding request object`))}#os(e,t,r,n){const s=new bp(t,r,n);t._response=s,t._redirectChain.push(t),s._resolveBody(new Error("Response body is unavailable for redirect responses")),this.#cs(t,!1),this.emit(mh.Response,s),this.emit(mh.RequestFinished,t)}#ls(e,t,r){const n=this.#Rn.getRequest(t.requestId);if(!n)return;this.#Rn.responseExtraInfo(t.requestId).length&&Zl(new Error("Unexpected extraInfo events for request "+t.requestId)),t.response.fromDiskCache&&(r=null);const s=new bp(n,t.response,r);n._response=s,this.emit(mh.Response,s)}#Vn(e,t){const r=this.#Rn.getRequest(t.requestId);let n=null;!r||r._fromMemoryCache||!t.hasExtraInfo||(n=this.#Rn.responseExtraInfo(t.requestId).shift(),n)?this.#ls(e,t,n):this.#Rn.queueEventGroup(t.requestId,{responseReceivedEvent:t})}#Zn(e,t){const r=this.#Rn.takeQueuedRedirectInfo(t.requestId);if(r)return this.#Rn.responseExtraInfo(t.requestId).push(t),void this.#Wr(e,r.event,r.fetchRequestId);const n=this.#Rn.getQueuedEventGroup(t.requestId);if(n)return this.#Rn.forgetQueuedEventGroup(t.requestId),this.#ls(e,n.responseReceivedEvent,t),n.loadingFinishedEvent&&this.#us(e,n.loadingFinishedEvent),void(n.loadingFailedEvent&&this.#ds(e,n.loadingFailedEvent));this.#Rn.responseExtraInfo(t.requestId).push(t)}#cs(e,t){const r=e.id,n=e._interceptionId;this.#Rn.forgetRequest(r),void 0!==n&&this.#$n.delete(n),t&&this.#Rn.forget(r)}#Gn(e,t){const r=this.#Rn.getQueuedEventGroup(t.requestId);r?r.loadingFinishedEvent=t:this.#us(e,t)}#us(e,t){const r=this.#Rn.getRequest(t.requestId);r&&(this.#hs(e,r),r.response()&&r.response()?._resolveBody(),this.#cs(r,!0),this.emit(mh.RequestFinished,r))}#Jn(e,t){const r=this.#Rn.getQueuedEventGroup(t.requestId);r?r.loadingFailedEvent=t:this.#ds(e,t)}#ds(e,t){const r=this.#Rn.getRequest(t.requestId);if(!r)return;this.#hs(e,r),r._failureText=t.errorText;const n=r.response();n&&n._resolveBody(),this.#cs(r,!0),this.emit(mh.RequestFailed,r)}#hs(e,t){e!==t.client&&(t.client=e)}}class _p extends Ml{#ps;#ms;#ar;#fs=new Set;#mt;#gs=new Map;#yr=new Set;_frameTree=new mp;#ys=new Set;#bs=new WeakMap;#ws;get timeoutSettings(){return this.#ar}get networkManager(){return this.#ms}get client(){return this.#mt}constructor(e,t,r){super(),this.#mt=e,this.#ps=t,this.#ms=new vp(this),this.#ar=r,this.setupEventListeners(this.#mt),e.once(wu.Disconnected,(()=>{this.#vs().catch(Zl)}))}async#vs(){const e=this._frameTree.getMainFrame();if(!e)return;if(!this.#ps.browser().connected)return void this.#_s(e);for(const t of e.childFrames())this.#_s(t);const t=gu.create({timeout:100,message:"Frame was not swapped"});e.once(Md.FrameSwappedByActivation,(()=>{t.resolve()}));try{await t.valueOrThrow()}catch{this.#_s(e)}}async swapFrameTree(e){this.#mt=e;const t=this._frameTree.getMainFrame();t&&(this.#ys.add(this.#mt.target()._targetId),this._frameTree.removeFrame(t),t.updateId(this.#mt.target()._targetId),this._frameTree.addFrame(t),t.updateClient(e)),this.setupEventListeners(e),e.once(wu.Disconnected,(()=>{this.#vs().catch(Zl)})),await this.initialize(e,t),await this.#ms.addClient(e),t&&t.emit(Md.FrameSwappedByActivation,void 0)}async registerSpeculativeSession(e){await this.#ms.addClient(e)}setupEventListeners(e){e.on("Page.frameAttached",(async t=>{await(this.#ws?.valueOrThrow()),this.#ks(e,t.frameId,t.parentFrameId)})),e.on("Page.frameNavigated",(async e=>{this.#ys.add(e.frame.id),await(this.#ws?.valueOrThrow()),this.#Ss(e.frame,e.type)})),e.on("Page.navigatedWithinDocument",(async e=>{await(this.#ws?.valueOrThrow()),this.#Es(e.frameId,e.url)})),e.on("Page.frameDetached",(async e=>{await(this.#ws?.valueOrThrow()),this.#Kr(e.frameId,e.reason)})),e.on("Page.frameStartedLoading",(async e=>{await(this.#ws?.valueOrThrow()),this.#xs(e.frameId)})),e.on("Page.frameStoppedLoading",(async e=>{await(this.#ws?.valueOrThrow()),this.#Ts(e.frameId)})),e.on("Runtime.executionContextCreated",(async t=>{await(this.#ws?.valueOrThrow()),this.#Cs(t.context,e)})),e.on("Page.lifecycleEvent",(async e=>{await(this.#ws?.valueOrThrow()),this.#Ps(e)}))}async initialize(e,t){try{this.#ws?.resolve(),this.#ws=gu.create(),await Promise.all([this.#ms.addClient(e),e.send("Page.enable"),e.send("Page.getFrameTree").then((({frameTree:t})=>{this.#Os(e,t),this.#ws?.resolve()})),e.send("Page.setLifecycleEventsEnabled",{enabled:!0}),e.send("Runtime.enable").then((()=>this.#As(e,iu))),...(t?Array.from(this.#gs.values()):[]).map((e=>t?.addPreloadScript(e))),...(t?Array.from(this.#yr.values()):[]).map((e=>t?.addExposedFunctionBinding(e)))])}catch(e){if(this.#ws?.resolve(),ku(e)&&Th(e))return;throw e}}page(){return this.#ps}mainFrame(){const e=this._frameTree.getMainFrame();return $l(e,"Requesting main frame too early!"),e}frames(){return Array.from(this._frameTree.frames())}frame(e){return this._frameTree.getById(e)||null}async addExposedFunctionBinding(e){this.#yr.add(e),await Promise.all(this.frames().map((async t=>await t.addExposedFunctionBinding(e))))}async removeExposedFunctionBinding(e){this.#yr.delete(e),await Promise.all(this.frames().map((async t=>await t.removeExposedFunctionBinding(e))))}async evaluateOnNewDocument(e){const{identifier:t}=await this.mainFrame()._client().send("Page.addScriptToEvaluateOnNewDocument",{source:e}),r=new Fh(this.mainFrame(),t,e);return this.#gs.set(t,r),await Promise.all(this.frames().map((async e=>await e.addPreloadScript(r)))),{identifier:t}}async removeScriptToEvaluateOnNewDocument(e){const t=this.#gs.get(e);if(!t)throw new Error(`Script to evaluate on new document with id ${e} not found`);this.#gs.delete(e),await Promise.all(this.frames().map((e=>{const r=t.getIdForFrame(e);if(r)return e._client().send("Page.removeScriptToEvaluateOnNewDocument",{identifier:r}).catch(Zl)})))}onAttachedToTarget(e){if("iframe"!==e._getTargetInfo().type)return;const t=this.frame(e._getTargetInfo().targetId);t&&t.updateClient(e._session()),this.setupEventListeners(e._session()),this.initialize(e._session(),t)}_deviceRequestPromptManager(e){let t=this.#bs.get(e);return void 0===t&&(t=new Uh(e,this.#ar),this.#bs.set(e,t)),t}#Ps(e){const t=this.frame(e.frameId);t&&(t._onLifecycleEvent(e.loaderId,e.name),this.emit(ap.LifecycleEvent,t),t.emit(Md.LifecycleEvent,void 0))}#xs(e){const t=this.frame(e);t&&t._onLoadingStarted()}#Ts(e){const t=this.frame(e);t&&(t._onLoadingStopped(),this.emit(ap.LifecycleEvent,t),t.emit(Md.LifecycleEvent,void 0))}#Os(e,t){if(t.frame.parentId&&this.#ks(e,t.frame.id,t.frame.parentId),this.#ys.has(t.frame.id)?this.#ys.delete(t.frame.id):this.#Ss(t.frame,"Navigation"),t.childFrames)for(const r of t.childFrames)this.#Os(e,r)}#ks(e,t,r){let n=this.frame(t);if(n){const t=this.frame(r);e&&t&&n.client!==t?.client&&n.updateClient(e)}else n=new pp(this,t,r,e),this._frameTree.addFrame(n),this.emit(ap.FrameAttached,n)}async#Ss(e,t){const r=e.id,n=!e.parentId;let s=this._frameTree.getById(r);if(s)for(const e of s.childFrames())this.#_s(e);n&&(s?(this._frameTree.removeFrame(s),s._id=r):s=new pp(this,r,void 0,this.#mt),this._frameTree.addFrame(s)),s=await this._frameTree.waitForFrame(r),s._navigated(e),this.emit(ap.FrameNavigated,s),s.emit(Md.FrameNavigated,t)}async#As(e,t){const r=`${e.id()}:${t}`;this.#fs.has(r)||(await e.send("Page.addScriptToEvaluateOnNewDocument",{source:`//# sourceURL=${Ql.INTERNAL_URL}`,worldName:t}),await Promise.all(this.frames().filter((t=>t.client===e)).map((r=>e.send("Page.createIsolatedWorld",{frameId:r._id,worldName:t,grantUniveralAccess:!0}).catch(Zl)))),this.#fs.add(r))}#Es(e,t){const r=this.frame(e);r&&(r._navigatedWithinDocument(t),this.emit(ap.FrameNavigatedWithinDocument,r),r.emit(Md.FrameNavigatedWithinDocument,void 0),this.emit(ap.FrameNavigated,r),r.emit(Md.FrameNavigated,"Navigation"))}#Kr(e,t){const r=this.frame(e);if(r)switch(t){case"remove":this.#_s(r);break;case"swap":this.emit(ap.FrameSwapped,r),r.emit(Md.FrameSwapped,void 0)}}#Cs(e,t){const r=e.auxData,n=r&&r.frameId,s="string"==typeof n?this.frame(n):void 0;let a;if(s){if(s.client!==t)return;e.auxData&&e.auxData.isDefault?a=s.worlds[op]:e.name===iu&&(a=s.worlds[cp])}if(!a)return;const i=new np(s?.client||this.#mt,e,a);a.setContext(i)}#_s(e){for(const t of e.childFrames())this.#_s(t);e[Cl](),this._frameTree.removeFrame(e),this.emit(ap.FrameDetached,e),e.emit(Md.FrameDetached,e)}}const kp={0:{keyCode:48,key:"0",code:"Digit0"},1:{keyCode:49,key:"1",code:"Digit1"},2:{keyCode:50,key:"2",code:"Digit2"},3:{keyCode:51,key:"3",code:"Digit3"},4:{keyCode:52,key:"4",code:"Digit4"},5:{keyCode:53,key:"5",code:"Digit5"},6:{keyCode:54,key:"6",code:"Digit6"},7:{keyCode:55,key:"7",code:"Digit7"},8:{keyCode:56,key:"8",code:"Digit8"},9:{keyCode:57,key:"9",code:"Digit9"},Power:{key:"Power",code:"Power"},Eject:{key:"Eject",code:"Eject"},Abort:{keyCode:3,code:"Abort",key:"Cancel"},Help:{keyCode:6,code:"Help",key:"Help"},Backspace:{keyCode:8,code:"Backspace",key:"Backspace"},Tab:{keyCode:9,code:"Tab",key:"Tab"},Numpad5:{keyCode:12,shiftKeyCode:101,key:"Clear",code:"Numpad5",shiftKey:"5",location:3},NumpadEnter:{keyCode:13,code:"NumpadEnter",key:"Enter",text:"\r",location:3},Enter:{keyCode:13,code:"Enter",key:"Enter",text:"\r"},"\r":{keyCode:13,code:"Enter",key:"Enter",text:"\r"},"\n":{keyCode:13,code:"Enter",key:"Enter",text:"\r"},ShiftLeft:{keyCode:16,code:"ShiftLeft",key:"Shift",location:1},ShiftRight:{keyCode:16,code:"ShiftRight",key:"Shift",location:2},ControlLeft:{keyCode:17,code:"ControlLeft",key:"Control",location:1},ControlRight:{keyCode:17,code:"ControlRight",key:"Control",location:2},AltLeft:{keyCode:18,code:"AltLeft",key:"Alt",location:1},AltRight:{keyCode:18,code:"AltRight",key:"Alt",location:2},Pause:{keyCode:19,code:"Pause",key:"Pause"},CapsLock:{keyCode:20,code:"CapsLock",key:"CapsLock"},Escape:{keyCode:27,code:"Escape",key:"Escape"},Convert:{keyCode:28,code:"Convert",key:"Convert"},NonConvert:{keyCode:29,code:"NonConvert",key:"NonConvert"},Space:{keyCode:32,code:"Space",key:" "},Numpad9:{keyCode:33,shiftKeyCode:105,key:"PageUp",code:"Numpad9",shiftKey:"9",location:3},PageUp:{keyCode:33,code:"PageUp",key:"PageUp"},Numpad3:{keyCode:34,shiftKeyCode:99,key:"PageDown",code:"Numpad3",shiftKey:"3",location:3},PageDown:{keyCode:34,code:"PageDown",key:"PageDown"},End:{keyCode:35,code:"End",key:"End"},Numpad1:{keyCode:35,shiftKeyCode:97,key:"End",code:"Numpad1",shiftKey:"1",location:3},Home:{keyCode:36,code:"Home",key:"Home"},Numpad7:{keyCode:36,shiftKeyCode:103,key:"Home",code:"Numpad7",shiftKey:"7",location:3},ArrowLeft:{keyCode:37,code:"ArrowLeft",key:"ArrowLeft"},Numpad4:{keyCode:37,shiftKeyCode:100,key:"ArrowLeft",code:"Numpad4",shiftKey:"4",location:3},Numpad8:{keyCode:38,shiftKeyCode:104,key:"ArrowUp",code:"Numpad8",shiftKey:"8",location:3},ArrowUp:{keyCode:38,code:"ArrowUp",key:"ArrowUp"},ArrowRight:{keyCode:39,code:"ArrowRight",key:"ArrowRight"},Numpad6:{keyCode:39,shiftKeyCode:102,key:"ArrowRight",code:"Numpad6",shiftKey:"6",location:3},Numpad2:{keyCode:40,shiftKeyCode:98,key:"ArrowDown",code:"Numpad2",shiftKey:"2",location:3},ArrowDown:{keyCode:40,code:"ArrowDown",key:"ArrowDown"},Select:{keyCode:41,code:"Select",key:"Select"},Open:{keyCode:43,code:"Open",key:"Execute"},PrintScreen:{keyCode:44,code:"PrintScreen",key:"PrintScreen"},Insert:{keyCode:45,code:"Insert",key:"Insert"},Numpad0:{keyCode:45,shiftKeyCode:96,key:"Insert",code:"Numpad0",shiftKey:"0",location:3},Delete:{keyCode:46,code:"Delete",key:"Delete"},NumpadDecimal:{keyCode:46,shiftKeyCode:110,code:"NumpadDecimal",key:"\0",shiftKey:".",location:3},Digit0:{keyCode:48,code:"Digit0",shiftKey:")",key:"0"},Digit1:{keyCode:49,code:"Digit1",shiftKey:"!",key:"1"},Digit2:{keyCode:50,code:"Digit2",shiftKey:"@",key:"2"},Digit3:{keyCode:51,code:"Digit3",shiftKey:"#",key:"3"},Digit4:{keyCode:52,code:"Digit4",shiftKey:"$",key:"4"},Digit5:{keyCode:53,code:"Digit5",shiftKey:"%",key:"5"},Digit6:{keyCode:54,code:"Digit6",shiftKey:"^",key:"6"},Digit7:{keyCode:55,code:"Digit7",shiftKey:"&",key:"7"},Digit8:{keyCode:56,code:"Digit8",shiftKey:"*",key:"8"},Digit9:{keyCode:57,code:"Digit9",shiftKey:"(",key:"9"},KeyA:{keyCode:65,code:"KeyA",shiftKey:"A",key:"a"},KeyB:{keyCode:66,code:"KeyB",shiftKey:"B",key:"b"},KeyC:{keyCode:67,code:"KeyC",shiftKey:"C",key:"c"},KeyD:{keyCode:68,code:"KeyD",shiftKey:"D",key:"d"},KeyE:{keyCode:69,code:"KeyE",shiftKey:"E",key:"e"},KeyF:{keyCode:70,code:"KeyF",shiftKey:"F",key:"f"},KeyG:{keyCode:71,code:"KeyG",shiftKey:"G",key:"g"},KeyH:{keyCode:72,code:"KeyH",shiftKey:"H",key:"h"},KeyI:{keyCode:73,code:"KeyI",shiftKey:"I",key:"i"},KeyJ:{keyCode:74,code:"KeyJ",shiftKey:"J",key:"j"},KeyK:{keyCode:75,code:"KeyK",shiftKey:"K",key:"k"},KeyL:{keyCode:76,code:"KeyL",shiftKey:"L",key:"l"},KeyM:{keyCode:77,code:"KeyM",shiftKey:"M",key:"m"},KeyN:{keyCode:78,code:"KeyN",shiftKey:"N",key:"n"},KeyO:{keyCode:79,code:"KeyO",shiftKey:"O",key:"o"},KeyP:{keyCode:80,code:"KeyP",shiftKey:"P",key:"p"},KeyQ:{keyCode:81,code:"KeyQ",shiftKey:"Q",key:"q"},KeyR:{keyCode:82,code:"KeyR",shiftKey:"R",key:"r"},KeyS:{keyCode:83,code:"KeyS",shiftKey:"S",key:"s"},KeyT:{keyCode:84,code:"KeyT",shiftKey:"T",key:"t"},KeyU:{keyCode:85,code:"KeyU",shiftKey:"U",key:"u"},KeyV:{keyCode:86,code:"KeyV",shiftKey:"V",key:"v"},KeyW:{keyCode:87,code:"KeyW",shiftKey:"W",key:"w"},KeyX:{keyCode:88,code:"KeyX",shiftKey:"X",key:"x"},KeyY:{keyCode:89,code:"KeyY",shiftKey:"Y",key:"y"},KeyZ:{keyCode:90,code:"KeyZ",shiftKey:"Z",key:"z"},MetaLeft:{keyCode:91,code:"MetaLeft",key:"Meta",location:1},MetaRight:{keyCode:92,code:"MetaRight",key:"Meta",location:2},ContextMenu:{keyCode:93,code:"ContextMenu",key:"ContextMenu"},NumpadMultiply:{keyCode:106,code:"NumpadMultiply",key:"*",location:3},NumpadAdd:{keyCode:107,code:"NumpadAdd",key:"+",location:3},NumpadSubtract:{keyCode:109,code:"NumpadSubtract",key:"-",location:3},NumpadDivide:{keyCode:111,code:"NumpadDivide",key:"/",location:3},F1:{keyCode:112,code:"F1",key:"F1"},F2:{keyCode:113,code:"F2",key:"F2"},F3:{keyCode:114,code:"F3",key:"F3"},F4:{keyCode:115,code:"F4",key:"F4"},F5:{keyCode:116,code:"F5",key:"F5"},F6:{keyCode:117,code:"F6",key:"F6"},F7:{keyCode:118,code:"F7",key:"F7"},F8:{keyCode:119,code:"F8",key:"F8"},F9:{keyCode:120,code:"F9",key:"F9"},F10:{keyCode:121,code:"F10",key:"F10"},F11:{keyCode:122,code:"F11",key:"F11"},F12:{keyCode:123,code:"F12",key:"F12"},F13:{keyCode:124,code:"F13",key:"F13"},F14:{keyCode:125,code:"F14",key:"F14"},F15:{keyCode:126,code:"F15",key:"F15"},F16:{keyCode:127,code:"F16",key:"F16"},F17:{keyCode:128,code:"F17",key:"F17"},F18:{keyCode:129,code:"F18",key:"F18"},F19:{keyCode:130,code:"F19",key:"F19"},F20:{keyCode:131,code:"F20",key:"F20"},F21:{keyCode:132,code:"F21",key:"F21"},F22:{keyCode:133,code:"F22",key:"F22"},F23:{keyCode:134,code:"F23",key:"F23"},F24:{keyCode:135,code:"F24",key:"F24"},NumLock:{keyCode:144,code:"NumLock",key:"NumLock"},ScrollLock:{keyCode:145,code:"ScrollLock",key:"ScrollLock"},AudioVolumeMute:{keyCode:173,code:"AudioVolumeMute",key:"AudioVolumeMute"},AudioVolumeDown:{keyCode:174,code:"AudioVolumeDown",key:"AudioVolumeDown"},AudioVolumeUp:{keyCode:175,code:"AudioVolumeUp",key:"AudioVolumeUp"},MediaTrackNext:{keyCode:176,code:"MediaTrackNext",key:"MediaTrackNext"},MediaTrackPrevious:{keyCode:177,code:"MediaTrackPrevious",key:"MediaTrackPrevious"},MediaStop:{keyCode:178,code:"MediaStop",key:"MediaStop"},MediaPlayPause:{keyCode:179,code:"MediaPlayPause",key:"MediaPlayPause"},Semicolon:{keyCode:186,code:"Semicolon",shiftKey:":",key:";"},Equal:{keyCode:187,code:"Equal",shiftKey:"+",key:"="},NumpadEqual:{keyCode:187,code:"NumpadEqual",key:"=",location:3},Comma:{keyCode:188,code:"Comma",shiftKey:"<",key:","},Minus:{keyCode:189,code:"Minus",shiftKey:"_",key:"-"},Period:{keyCode:190,code:"Period",shiftKey:">",key:"."},Slash:{keyCode:191,code:"Slash",shiftKey:"?",key:"/"},Backquote:{keyCode:192,code:"Backquote",shiftKey:"~",key:"`"},BracketLeft:{keyCode:219,code:"BracketLeft",shiftKey:"{",key:"["},Backslash:{keyCode:220,code:"Backslash",shiftKey:"|",key:"\\"},BracketRight:{keyCode:221,code:"BracketRight",shiftKey:"}",key:"]"},Quote:{keyCode:222,code:"Quote",shiftKey:'"',key:"'"},AltGraph:{keyCode:225,code:"AltGraph",key:"AltGraph"},Props:{keyCode:247,code:"Props",key:"CrSel"},Cancel:{keyCode:3,key:"Cancel",code:"Abort"},Clear:{keyCode:12,key:"Clear",code:"Numpad5",location:3},Shift:{keyCode:16,key:"Shift",code:"ShiftLeft",location:1},Control:{keyCode:17,key:"Control",code:"ControlLeft",location:1},Alt:{keyCode:18,key:"Alt",code:"AltLeft",location:1},Accept:{keyCode:30,key:"Accept"},ModeChange:{keyCode:31,key:"ModeChange"}," ":{keyCode:32,key:" ",code:"Space"},Print:{keyCode:42,key:"Print"},Execute:{keyCode:43,key:"Execute",code:"Open"},"\0":{keyCode:46,key:"\0",code:"NumpadDecimal",location:3},a:{keyCode:65,key:"a",code:"KeyA"},b:{keyCode:66,key:"b",code:"KeyB"},c:{keyCode:67,key:"c",code:"KeyC"},d:{keyCode:68,key:"d",code:"KeyD"},e:{keyCode:69,key:"e",code:"KeyE"},f:{keyCode:70,key:"f",code:"KeyF"},g:{keyCode:71,key:"g",code:"KeyG"},h:{keyCode:72,key:"h",code:"KeyH"},i:{keyCode:73,key:"i",code:"KeyI"},j:{keyCode:74,key:"j",code:"KeyJ"},k:{keyCode:75,key:"k",code:"KeyK"},l:{keyCode:76,key:"l",code:"KeyL"},m:{keyCode:77,key:"m",code:"KeyM"},n:{keyCode:78,key:"n",code:"KeyN"},o:{keyCode:79,key:"o",code:"KeyO"},p:{keyCode:80,key:"p",code:"KeyP"},q:{keyCode:81,key:"q",code:"KeyQ"},r:{keyCode:82,key:"r",code:"KeyR"},s:{keyCode:83,key:"s",code:"KeyS"},t:{keyCode:84,key:"t",code:"KeyT"},u:{keyCode:85,key:"u",code:"KeyU"},v:{keyCode:86,key:"v",code:"KeyV"},w:{keyCode:87,key:"w",code:"KeyW"},x:{keyCode:88,key:"x",code:"KeyX"},y:{keyCode:89,key:"y",code:"KeyY"},z:{keyCode:90,key:"z",code:"KeyZ"},Meta:{keyCode:91,key:"Meta",code:"MetaLeft",location:1},"*":{keyCode:106,key:"*",code:"NumpadMultiply",location:3},"+":{keyCode:107,key:"+",code:"NumpadAdd",location:3},"-":{keyCode:109,key:"-",code:"NumpadSubtract",location:3},"/":{keyCode:111,key:"/",code:"NumpadDivide",location:3},";":{keyCode:186,key:";",code:"Semicolon"},"=":{keyCode:187,key:"=",code:"Equal"},",":{keyCode:188,key:",",code:"Comma"},".":{keyCode:190,key:".",code:"Period"},"`":{keyCode:192,key:"`",code:"Backquote"},"[":{keyCode:219,key:"[",code:"BracketLeft"},"\\":{keyCode:220,key:"\\",code:"Backslash"},"]":{keyCode:221,key:"]",code:"BracketRight"},"'":{keyCode:222,key:"'",code:"Quote"},Attn:{keyCode:246,key:"Attn"},CrSel:{keyCode:247,key:"CrSel",code:"Props"},ExSel:{keyCode:248,key:"ExSel"},EraseEof:{keyCode:249,key:"EraseEof"},Play:{keyCode:250,key:"Play"},ZoomOut:{keyCode:251,key:"ZoomOut"},")":{keyCode:48,key:")",code:"Digit0"},"!":{keyCode:49,key:"!",code:"Digit1"},"@":{keyCode:50,key:"@",code:"Digit2"},"#":{keyCode:51,key:"#",code:"Digit3"},$:{keyCode:52,key:"$",code:"Digit4"},"%":{keyCode:53,key:"%",code:"Digit5"},"^":{keyCode:54,key:"^",code:"Digit6"},"&":{keyCode:55,key:"&",code:"Digit7"},"(":{keyCode:57,key:"(",code:"Digit9"},A:{keyCode:65,key:"A",code:"KeyA"},B:{keyCode:66,key:"B",code:"KeyB"},C:{keyCode:67,key:"C",code:"KeyC"},D:{keyCode:68,key:"D",code:"KeyD"},E:{keyCode:69,key:"E",code:"KeyE"},F:{keyCode:70,key:"F",code:"KeyF"},G:{keyCode:71,key:"G",code:"KeyG"},H:{keyCode:72,key:"H",code:"KeyH"},I:{keyCode:73,key:"I",code:"KeyI"},J:{keyCode:74,key:"J",code:"KeyJ"},K:{keyCode:75,key:"K",code:"KeyK"},L:{keyCode:76,key:"L",code:"KeyL"},M:{keyCode:77,key:"M",code:"KeyM"},N:{keyCode:78,key:"N",code:"KeyN"},O:{keyCode:79,key:"O",code:"KeyO"},P:{keyCode:80,key:"P",code:"KeyP"},Q:{keyCode:81,key:"Q",code:"KeyQ"},R:{keyCode:82,key:"R",code:"KeyR"},S:{keyCode:83,key:"S",code:"KeyS"},T:{keyCode:84,key:"T",code:"KeyT"},U:{keyCode:85,key:"U",code:"KeyU"},V:{keyCode:86,key:"V",code:"KeyV"},W:{keyCode:87,key:"W",code:"KeyW"},X:{keyCode:88,key:"X",code:"KeyX"},Y:{keyCode:89,key:"Y",code:"KeyY"},Z:{keyCode:90,key:"Z",code:"KeyZ"},":":{keyCode:186,key:":",code:"Semicolon"},"<":{keyCode:188,key:"<",code:"Comma"},_:{keyCode:189,key:"_",code:"Minus"},">":{keyCode:190,key:">",code:"Period"},"?":{keyCode:191,key:"?",code:"Slash"},"~":{keyCode:192,key:"~",code:"Backquote"},"{":{keyCode:219,key:"{",code:"BracketLeft"},"|":{keyCode:220,key:"|",code:"Backslash"},"}":{keyCode:221,key:"}",code:"BracketRight"},'"':{keyCode:222,key:'"',code:"Quote"},SoftLeft:{key:"SoftLeft",code:"SoftLeft",location:4},SoftRight:{key:"SoftRight",code:"SoftRight",location:4},Camera:{keyCode:44,key:"Camera",code:"Camera",location:4},Call:{key:"Call",code:"Call",location:4},EndCall:{keyCode:95,key:"EndCall",code:"EndCall",location:4},VolumeDown:{keyCode:182,key:"VolumeDown",code:"VolumeDown",location:4},VolumeUp:{keyCode:183,key:"VolumeUp",code:"VolumeUp",location:4}};class Sp extends Hd{#mt;#Is=new Set;_modifiers=0;constructor(e){super(),this.#mt=e}updateClient(e){this.#mt=e}async down(e,t={text:void 0,commands:[]}){const r=this.#Ms(e),n=this.#Is.has(r.code);this.#Is.add(r.code),this._modifiers|=this.#Rs(r.key);const s=void 0===t.text?r.text:t.text;await this.#mt.send("Input.dispatchKeyEvent",{type:s?"keyDown":"rawKeyDown",modifiers:this._modifiers,windowsVirtualKeyCode:r.keyCode,code:r.code,key:r.key,text:s,unmodifiedText:s,autoRepeat:n,location:r.location,isKeypad:3===r.location,commands:t.commands})}#Rs(e){return"Alt"===e?1:"Control"===e?2:"Meta"===e?4:"Shift"===e?8:0}#Ms(e){const t=8&this._modifiers,r={key:"",keyCode:0,code:"",text:"",location:0},n=kp[e];return $l(n,`Unknown key: "${e}"`),n.key&&(r.key=n.key),t&&n.shiftKey&&(r.key=n.shiftKey),n.keyCode&&(r.keyCode=n.keyCode),t&&n.shiftKeyCode&&(r.keyCode=n.shiftKeyCode),n.code&&(r.code=n.code),n.location&&(r.location=n.location),1===r.key.length&&(r.text=r.key),n.text&&(r.text=n.text),t&&n.shiftText&&(r.text=n.shiftText),-9&this._modifiers&&(r.text=""),r}async up(e){const t=this.#Ms(e);this._modifiers&=~this.#Rs(t.key),this.#Is.delete(t.code),await this.#mt.send("Input.dispatchKeyEvent",{type:"keyUp",modifiers:this._modifiers,key:t.key,windowsVirtualKeyCode:t.keyCode,code:t.code,location:t.location})}async sendCharacter(e){await this.#mt.send("Input.insertText",{text:e})}charIsKey(e){return!!kp[e]}async type(e,t={}){const r=t.delay||void 0;for(const t of e)this.charIsKey(t)?await this.press(t,{delay:r}):(r&&await new Promise((e=>setTimeout(e,r))),await this.sendCharacter(t))}async press(e,t={}){const{delay:r=null}=t;await this.down(e,t),r&&await new Promise((e=>setTimeout(e,t.delay))),await this.up(e)}}const Ep=e=>{switch(e){case Vd.Left:return 1;case Vd.Right:return 2;case Vd.Middle:return 4;case Vd.Back:return 8;case Vd.Forward:return 16}},xp=e=>1&e?Vd.Left:2&e?Vd.Right:4&e?Vd.Middle:8&e?Vd.Back:16&e?Vd.Forward:"none";class Tp extends Gd{#mt;#js;constructor(e,t){super(),this.#mt=e,this.#js=t}updateClient(e){this.#mt=e}#Ns={position:{x:0,y:0},buttons:0};get#At(){return Object.assign({...this.#Ns},...this.#$s)}#$s=[];#Ls(){const e={};this.#$s.push(e);const t=()=>{this.#$s.splice(this.#$s.indexOf(e),1)};return{update:t=>{Object.assign(e,t)},commit:()=>{this.#Ns={...this.#Ns,...e},t()},rollback:t}}async#Fs(e){const{update:t,commit:r,rollback:n}=this.#Ls();try{await e(t),r()}catch(e){throw n(),e}}async reset(){const e=[];for(const[t,r]of[[1,Vd.Left],[4,Vd.Middle],[2,Vd.Right],[16,Vd.Forward],[8,Vd.Back]])this.#At.buttons&t&&e.push(this.up({button:r}));0===this.#At.position.x&&0===this.#At.position.y||e.push(this.move(0,0)),await Promise.all(e)}async move(e,t,r={}){const{steps:n=1}=r,s=this.#At.position,a=e,i=t;for(let e=1;e<=n;e++)await this.#Fs((t=>{t({position:{x:s.x+(a-s.x)*(e/n),y:s.y+(i-s.y)*(e/n)}});const{buttons:r,position:o}=this.#At;return this.#mt.send("Input.dispatchMouseEvent",{type:"mouseMoved",modifiers:this.#js._modifiers,buttons:r,button:xp(r),...o})}))}async down(e={}){const{button:t=Vd.Left,clickCount:r=1}=e,n=Ep(t);if(!n)throw new Error(`Unsupported mouse button: ${t}`);if(this.#At.buttons&n)throw new Error(`'${t}' is already pressed.`);await this.#Fs((e=>{e({buttons:this.#At.buttons|n});const{buttons:s,position:a}=this.#At;return this.#mt.send("Input.dispatchMouseEvent",{type:"mousePressed",modifiers:this.#js._modifiers,clickCount:r,buttons:s,button:t,...a})}))}async up(e={}){const{button:t=Vd.Left,clickCount:r=1}=e,n=Ep(t);if(!n)throw new Error(`Unsupported mouse button: ${t}`);if(!(this.#At.buttons&n))throw new Error(`'${t}' is not pressed.`);await this.#Fs((e=>{e({buttons:this.#At.buttons&~n});const{buttons:s,position:a}=this.#At;return this.#mt.send("Input.dispatchMouseEvent",{type:"mouseReleased",modifiers:this.#js._modifiers,clickCount:r,buttons:s,button:t,...a})}))}async click(e,t,r={}){const{delay:n,count:s=1,clickCount:a=s}=r;if(s<1)throw new Error("Click must occur a positive number of times.");const i=[this.move(e,t)];if(a===s)for(let e=1;e{setTimeout(e,n)}))),i.push(this.up({...r,clickCount:a})),await Promise.all(i)}async wheel(e={}){const{deltaX:t=0,deltaY:r=0}=e,{position:n,buttons:s}=this.#At;await this.#mt.send("Input.dispatchMouseEvent",{type:"mouseWheel",pointerType:"mouse",modifiers:this.#js._modifiers,deltaY:r,deltaX:t,buttons:s,...n})}async drag(e,t){const r=new Promise((e=>{this.#mt.once("Input.dragIntercepted",(t=>e(t.data)))}));return await this.move(e.x,e.y),await this.down(),await this.move(t.x,t.y),await r}async dragEnter(e,t){await this.#mt.send("Input.dispatchDragEvent",{type:"dragEnter",x:e.x,y:e.y,modifiers:this.#js._modifiers,data:t})}async dragOver(e,t){await this.#mt.send("Input.dispatchDragEvent",{type:"dragOver",x:e.x,y:e.y,modifiers:this.#js._modifiers,data:t})}async drop(e,t){await this.#mt.send("Input.dispatchDragEvent",{type:"drop",x:e.x,y:e.y,modifiers:this.#js._modifiers,data:t})}async dragAndDrop(e,t,r={}){const{delay:n=null}=r,s=await this.drag(e,t);await this.dragEnter(t,s),await this.dragOver(t,s),n&&await new Promise((e=>setTimeout(e,n))),await this.drop(t,s),await this.up()}}class Cp{#Ds=!1;#zs;#Us;#mt;#js;constructor(e,t,r,n){this.#mt=e,this.#zs=t,this.#js=r,this.#Us=n}updateClient(e){this.#mt=e}async start(){if(this.#Ds)throw new Wl("Touch has already started");await this.#mt.send("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[this.#Us],modifiers:this.#js._modifiers}),this.#Ds=!0}move(e,t){return this.#Us.x=Math.round(e),this.#Us.y=Math.round(t),this.#mt.send("Input.dispatchTouchEvent",{type:"touchMove",touchPoints:[this.#Us],modifiers:this.#js._modifiers})}async end(){await this.#mt.send("Input.dispatchTouchEvent",{type:"touchEnd",touchPoints:[this.#Us],modifiers:this.#js._modifiers}),this.#zs.removeHandle(this)}}class Pp extends Jd{#mt;#js;constructor(e,t){super(),this.#mt=e,this.#js=t}updateClient(e){this.#mt=e,this.touches.forEach((t=>{t.updateClient(e)}))}async touchStart(e,t){const r=this.idGenerator(),n={x:Math.round(e),y:Math.round(t),radiusX:.5,radiusY:.5,force:.5,id:r},s=new Cp(this.#mt,this,this.#js,n);return await s.start(),this.touches.push(s),s}}class Op{#mt;#Bs=!1;#qs;constructor(e){this.#mt=e}updateClient(e){this.#mt=e}async start(e={}){$l(!this.#Bs,"Cannot start recording trace while already recording trace.");const t=["-*","devtools.timeline","v8.execute","disabled-by-default-devtools.timeline","disabled-by-default-devtools.timeline.frame","toplevel","blink.console","blink.user_timing","latencyInfo","disabled-by-default-devtools.timeline.stack","disabled-by-default-v8.cpu_profiler"],{path:r,screenshots:n=!1,categories:s=t}=e;n&&s.push("disabled-by-default-devtools.screenshot");const a=s.filter((e=>e.startsWith("-"))).map((e=>e.slice(1))),i=s.filter((e=>!e.startsWith("-")));this.#qs=r,this.#Bs=!0,await this.#mt.send("Tracing.start",{transferMode:"ReturnAsStream",traceConfig:{excludedCategories:a,includedCategories:i}})}async stop(){const e=gu.create();return this.#mt.once("Tracing.tracingComplete",(async t=>{try{$l(t.stream,'Missing "stream"');const r=await su(this.#mt,t.stream),n=await nu(r,this.#qs);e.resolve(n??void 0)}catch(t){ku(t)?e.reject(t):e.reject(new Error(`Unknown error: ${t}`))}})),await this.#mt.send("Tracing.end"),this.#Bs=!1,await e.valueOrThrow()}}class Ap extends lh{#pe;#mt;#Je;#et;constructor(e,t,r,n,s,a,i){super(t),this.#Je=r,this.#mt=e,this.#et=n,this.#pe=new ip(this,new Zd),this.#mt.once("Runtime.executionContextCreated",(async t=>{this.#pe.setContext(new np(e,t.context,this.#pe))})),this.#pe.emitter.on("consoleapicalled",(async e=>{try{return s(e.type,e.args.map((e=>new Vh(this.#pe,e))),e.stackTrace)}catch(e){Zl(e)}})),this.#mt.on("Runtime.exceptionThrown",a),this.#mt.once(wu.Disconnected,(()=>{this.#pe.dispose()})),i?.addClient(this.#mt).catch(Zl),this.#mt.send("Runtime.enable").catch(Zl)}mainRealm(){return this.#pe}get client(){return this.#mt}async close(){switch(this.#et){case oh.SERVICE_WORKER:case oh.SHARED_WORKER:await(this.client.connection()?.send("Target.closeTarget",{targetId:this.#Je})),await(this.client.connection()?.send("Target.detachFromTarget",{sessionId:this.client.id()}));break;default:await this.evaluate((()=>{self.close()}))}}}var Ip=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Mp=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,s=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===s)return s=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return s|=2,Promise.resolve(a).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Rp(e){return"warning"===e?"warn":e}class jp extends th{static async _create(e,t,r){const n=new jp(e,t);if(await n.#Ks(),r)try{await n.setViewport(r)}catch(e){if(!ku(e)||!Th(e))throw e;Zl(e)}return n}#lt=!1;#Ws;#Hs;#Vs;#Gs;#Js;#js;#Zs;#Xs;#pr;#Ys;#Qs;#yr=new Map;#ea=new Map;#ta;#ra;#na=new Map;#sa=new Set;#aa=gu.create();#ia=!1;#oa=!1;constructor(e,t){super(),this.#Hs=e,this.#Gs=e.parentSession(),$l(this.#Gs,"Tab target session is not defined."),this.#Js=this.#Gs.target(),$l(this.#Js,"Tab target is not defined."),this.#Vs=t,this.#Ws=t._targetManager(),this.#js=new Sp(e),this.#Zs=new Tp(e,this.#js),this.#Xs=new Pp(e,this.#js),this.#pr=new _p(e,this,this._timeoutSettings),this.#Ys=new Lh(e),this.#Qs=new Op(e),this.#ta=new Ch(e),this.#ra=null;const r=new Ml(this.#pr);r.on(ap.FrameAttached,(e=>{this.emit("frameattached",e)})),r.on(ap.FrameDetached,(e=>{this.emit("framedetached",e)})),r.on(ap.FrameNavigated,(e=>{this.emit("framenavigated",e)})),r.on(ap.ConsoleApiCalled,(([e,t])=>{this.#gr(e,t)})),r.on(ap.BindingCalled,(([e,t])=>{this.#fr(e,t)}));const n=new Ml(this.#pr.networkManager);n.on(mh.Request,(e=>{this.emit("request",e)})),n.on(mh.RequestServedFromCache,(e=>{this.emit("requestservedfromcache",e)})),n.on(mh.Response,(e=>{this.emit("response",e)})),n.on(mh.RequestFailed,(e=>{this.emit("requestfailed",e)})),n.on(mh.RequestFinished,(e=>{this.emit("requestfinished",e)})),this.#Gs.on(wu.Swapped,this.#ca.bind(this)),this.#Gs.on(wu.Ready,this.#la.bind(this)),this.#Ws.on("targetGone",this.#ua),this.#Js._isClosedDeferred.valueOrThrow().then((()=>{this.#Ws.off("targetGone",this.#ua),this.emit("close",void 0),this.#lt=!0})).catch(Zl),this.#da(),this.#ha()}#ha(){const e=[];for(const t of this.#Ws.getChildTargets(this.#Vs))e.push(t);let t=0;for(;t{this.#aa.reject(new Gl("Target closed"))})),e.on("Page.domContentEventFired",(()=>{this.emit("domcontentloaded",void 0)})),e.on("Page.loadEventFired",(()=>{this.emit("load",void 0)})),e.on("Page.javascriptDialogOpening",this.#ma.bind(this)),e.on("Runtime.exceptionThrown",this.#fa.bind(this)),e.on("Inspector.targetCrashed",this.#ga.bind(this)),e.on("Performance.metrics",this.#ya.bind(this)),e.on("Log.entryAdded",this.#ba.bind(this)),e.on("Page.fileChooserOpened",this.#wa.bind(this))}#ua=e=>{const t=e._session()?.id(),r=this.#na.get(t);r&&(this.#na.delete(t),this.emit("workerdestroyed",r))};#pa=e=>{if($l(e instanceof kh),this.#pr.onAttachedToTarget(e.target()),"worker"===e.target()._getTargetInfo().type){const t=new Ap(e,e.target().url(),e.target()._targetId,e.target().type(),this.#va.bind(this),this.#fa.bind(this),this.#pr.networkManager);this.#na.set(e.id(),t),this.emit("workercreated",t)}e.on(wu.Ready,this.#pa)};async#Ks(){try{await Promise.all([this.#pr.initialize(this.#Hs),this.#Hs.send("Performance.enable"),this.#Hs.send("Log.enable")])}catch(e){if(!ku(e)||!Th(e))throw e;Zl(e)}}async#wa(e){const t={stack:[],error:void 0,hasError:!1};try{if(!this.#sa.size)return;const r=this.#pr.frame(e.frameId);$l(r,"This should never happen.");const n=Ip(t,await r.worlds[op].adoptBackendNode(e.backendNodeId),!1),s=new wh(n.move(),"selectSingle"!==e.mode);for(const e of this.#sa)e.resolve(s);this.#sa.clear()}catch(e){t.error=e,t.hasError=!0}finally{Mp(t)}}_client(){return this.#Hs}isServiceWorkerBypassed(){return this.#ia}isDragInterceptionEnabled(){return this.#oa}isJavaScriptEnabled(){return this.#Ys.javascriptEnabled}async waitForFileChooser(e={}){const t=0===this.#sa.size,{timeout:r=this._timeoutSettings.timeout()}=e,n=gu.create({message:`Waiting for \`FileChooser\` failed: ${r}ms exceeded`,timeout:r});let s;e.signal&&e.signal.addEventListener("abort",(()=>{n.reject(e.signal?.reason)}),{once:!0}),this.#sa.add(n),t&&(s=this.#Hs.send("Page.setInterceptFileChooserDialog",{enabled:!0}));try{const[e]=await Promise.all([n.valueOrThrow(),s]);return e}catch(e){throw this.#sa.delete(n),e}}async setGeolocation(e){return await this.#Ys.setGeolocation(e)}target(){return this.#Vs}browser(){return this.#Vs.browser()}browserContext(){return this.#Vs.browserContext()}#ga(){this.emit("error",new Error("Page crashed!"))}#ba(e){const{level:t,text:r,args:n,source:s,url:a,lineNumber:i}=e.entry;n&&n.map((e=>{Gh(this.#Hs,e)})),"worker"!==s&&this.emit("console",new bh(Rp(t),r,[],[{url:a,lineNumber:i}]))}mainFrame(){return this.#pr.mainFrame()}get keyboard(){return this.#js}get touchscreen(){return this.#Xs}get coverage(){return this.#ta}get tracing(){return this.#Qs}frames(){return this.#pr.frames()}workers(){return Array.from(this.#na.values())}async setRequestInterception(e){return await this.#pr.networkManager.setRequestInterception(e)}async setBypassServiceWorker(e){return this.#ia=e,await this.#Hs.send("Network.setBypassServiceWorker",{bypass:e})}async setDragInterception(e){return this.#oa=e,await this.#Hs.send("Input.setInterceptDrags",{enabled:e})}async setOfflineMode(e){return await this.#pr.networkManager.setOfflineMode(e)}async emulateNetworkConditions(e){return await this.#pr.networkManager.emulateNetworkConditions(e)}setDefaultNavigationTimeout(e){this._timeoutSettings.setDefaultNavigationTimeout(e)}setDefaultTimeout(e){this._timeoutSettings.setDefaultTimeout(e)}getDefaultTimeout(){return this._timeoutSettings.timeout()}getDefaultNavigationTimeout(){return this._timeoutSettings.navigationTimeout()}async queryObjects(e){$l(!e.disposed,"Prototype JSHandle is disposed!"),$l(e.id,"Prototype JSHandle must not be referencing primitive value");const t=await this.mainFrame().client.send("Runtime.queryObjects",{prototypeObjectId:e.id});return this.mainFrame().mainRealm().createCdpHandle(t.objects)}async cookies(...e){const t=(await this.#Hs.send("Network.getCookies",{urls:e.length?e:[this.url()]})).cookies,r=["sourcePort"];return t.map((e=>{for(const t of r)delete e[t];return e})).map((e=>({...e,partitionKey:e.partitionKey?e.partitionKey.topLevelSite:void 0})))}async deleteCookie(...e){const t=this.url();for(const r of e){const e={...r,partitionKey:$p(r.partitionKey)};if(!r.url&&t.startsWith("http")&&(e.url=t),await this.#Hs.send("Network.deleteCookies",e),t.startsWith("http")&&!e.partitionKey){const r=new URL(t);await this.#Hs.send("Network.deleteCookies",{...e,partitionKey:{topLevelSite:r.origin.replace(`:${r.port}`,""),hasCrossSiteAncestor:!1}})}}}async setCookie(...e){const t=this.url(),r=t.startsWith("http"),n=e.map((e=>{const n=Object.assign({},e);return!n.url&&r&&(n.url=t),$l("about:blank"!==n.url,`Blank page can not have cookie "${n.name}"`),$l(!String.prototype.startsWith.call(n.url||"","data:"),`Data URL page can not have cookie "${n.name}"`),n}));await this.deleteCookie(...n),n.length&&await this.#Hs.send("Network.setCookies",{cookies:n.map((e=>({...e,partitionKey:$p(e.partitionKey)})))})}async exposeFunction(e,t){if(this.#yr.has(e))throw new Error(`Failed to add page binding with name ${e}: window['${e}'] already exists!`);const r=function(e,t){return ru(Wh,e,t,Hh)}("exposedFun",e);let n;if("function"==typeof t)n=new yh(e,t,r);else n=new yh(e,t.default,r);this.#yr.set(e,n);const[{identifier:s}]=await Promise.all([this.#pr.evaluateOnNewDocument(r),this.#pr.addExposedFunctionBinding(n)]);this.#ea.set(e,s)}async removeExposedFunction(e){const t=this.#ea.get(e);if(!t)throw new Error(`Function with name "${e}" does not exist`);const r=this.#yr.get(e);this.#ea.delete(e),this.#yr.delete(e),await Promise.all([this.#pr.removeScriptToEvaluateOnNewDocument(t),this.#pr.removeExposedFunctionBinding(r)])}async authenticate(e){return await this.#pr.networkManager.authenticate(e)}async setExtraHTTPHeaders(e){return await this.#pr.networkManager.setExtraHTTPHeaders(e)}async setUserAgent(e,t){return await this.#pr.networkManager.setUserAgent(e,t)}async metrics(){const e=await this.#Hs.send("Performance.getMetrics");return this.#_a(e.metrics)}#ya(e){this.emit("metrics",{title:e.title,metrics:this.#_a(e.metrics)})}#_a(e){const t={};for(const r of e||[])Np.has(r.name)&&(t[r.name]=r.value);return t}#fa(e){this.emit("pageerror",function(e){let t,r;if(e.exception){if(!("object"===e.exception.type&&"error"===e.exception.subtype||e.exception.objectId))return Kh(e.exception);{const n=qh(e);t=n.name,r=n.message}}else t="Error",r=e.text;const n=new Error(r);n.name=t;const s=n.message.split("\n").length,a=n.stack.split("\n").splice(0,s),i=[];if(e.stackTrace)for(const t of e.stackTrace.callFrames)if(i.push(` at ${t.functionName||""} (${t.url}:${t.lineNumber+1}:${t.columnNumber+1})`),i.length>=Error.stackTraceLimit)break;return n.stack=[...a,...i].join("\n"),n}(e.exceptionDetails))}#gr(e,t){const r=t.args.map((t=>e.createCdpHandle(t)));this.#va(Rp(t.type),r,t.stackTrace)}async#fr(e,t){let r;try{r=JSON.parse(t.payload)}catch{return}const{type:n,name:s,seq:a,args:i,isTrivial:o}=r;if("exposedFun"!==n)return;const c=e.context;if(!c)return;const l=this.#yr.get(s);await(l?.run(c,a,i,o))}#va(e,t,r){if(!this.listenerCount("console"))return void t.forEach((e=>e.dispose()));const n=[];for(const e of t){const t=e.remoteObject();t.objectId?n.push(e.toString()):n.push(Kh(t))}const s=[];if(r)for(const e of r.callFrames)s.push({url:e.url,lineNumber:e.lineNumber,columnNumber:e.columnNumber});const a=new bh(Rp(e),n.join(" "),t,s);this.emit("console",a)}#ma(e){const t=function(e){let t=null;return new Set(["alert","confirm","prompt","beforeunload"]).has(e)&&(t=e),$l(t,`Unknown javascript dialog type: ${e}`),t}(e.type),r=new Mh(this.#Hs,t,e.message,e.defaultPrompt);this.emit("dialog",r)}async reload(e){const[t]=await Promise.all([this.waitForNavigation({...e,ignoreSameDocumentNavigation:!0}),this.#Hs.send("Page.reload")]);return t}async createCDPSession(){return await this.target().createCDPSession()}async goBack(e={}){return await this.#ka(-1,e)}async goForward(e={}){return await this.#ka(1,e)}async#ka(e,t){const r=await this.#Hs.send("Page.getNavigationHistory"),n=r.entries[r.currentIndex+e];if(!n)return null;return(await Promise.all([this.waitForNavigation(t),this.#Hs.send("Page.navigateToHistoryEntry",{entryId:n.id})]))[0]}async bringToFront(){await this.#Hs.send("Page.bringToFront")}async setJavaScriptEnabled(e){return await this.#Ys.setJavaScriptEnabled(e)}async setBypassCSP(e){await this.#Hs.send("Page.setBypassCSP",{enabled:e})}async emulateMediaType(e){return await this.#Ys.emulateMediaType(e)}async emulateCPUThrottling(e){return await this.#Ys.emulateCPUThrottling(e)}async emulateMediaFeatures(e){return await this.#Ys.emulateMediaFeatures(e)}async emulateTimezone(e){return await this.#Ys.emulateTimezone(e)}async emulateIdleState(e){return await this.#Ys.emulateIdleState(e)}async emulateVisionDeficiency(e){return await this.#Ys.emulateVisionDeficiency(e)}async setViewport(e){const t=await this.#Ys.emulateViewport(e);this.#ra=e,t&&await this.reload()}viewport(){return this.#ra}async evaluateOnNewDocument(e,...t){const r=ru(e,...t);return await this.#pr.evaluateOnNewDocument(r)}async removeScriptToEvaluateOnNewDocument(e){return await this.#pr.removeScriptToEvaluateOnNewDocument(e)}async setCacheEnabled(e=!0){await this.#pr.networkManager.setCacheEnabled(e)}async _screenshot(e){const t={stack:[],error:void 0,hasError:!1};try{const{fromSurface:r,omitBackground:n,optimizeForSpeed:s,quality:a,clip:i,type:o,captureBeyondViewport:c}=e,l=Ip(t,new Al,!0);!n||"png"!==o&&"webp"!==o||(await this.#Ys.setTransparentBackgroundColor(),l.defer((async()=>{await this.#Ys.resetDefaultBackgroundColor().catch(Zl)})));let u=i;if(u&&!c){u=function(e,t){const r=Math.max(e.x,t.x),n=Math.max(e.y,t.y);return{x:r,y:n,width:Math.max(Math.min(e.x+e.width,t.x+t.width)-r,0),height:Math.max(Math.min(e.y+e.height,t.y+t.height)-n,0)}}(u,await this.mainFrame().isolatedRealm().evaluate((()=>{const{height:e,pageLeft:t,pageTop:r,width:n}=window.visualViewport;return{x:t,y:r,height:e,width:n}})))}const{data:d}=await this.#Hs.send("Page.captureScreenshot",{format:o,optimizeForSpeed:s,fromSurface:r,...void 0!==a?{quality:Math.round(a)}:{},...u?{clip:{...u,scale:u.scale??1}}:{},captureBeyondViewport:c});return d}catch(e){t.error=e,t.hasError=!0}finally{const e=Mp(t);e&&await e}}async createPDFStream(e={}){const{timeout:t=this._timeoutSettings.timeout()}=e,{landscape:r,displayHeaderFooter:n,headerTemplate:s,footerTemplate:a,printBackground:i,scale:o,width:c,height:l,margin:u,pageRanges:d,preferCSSPageSize:h,omitBackground:p,tagged:m,outline:f,waitForFonts:g}=function(e={},t="in"){let r=8.5,n=11;if(e.format){const s=Jl[e.format.toLowerCase()][t];$l(s,"Unknown paper format: "+e.format),r=s.width,n=s.height}else r=uu(e.width,t)??r,n=uu(e.height,t)??n;const s={top:uu(e.margin?.top,t)||0,left:uu(e.margin?.left,t)||0,bottom:uu(e.margin?.bottom,t)||0,right:uu(e.margin?.right,t)||0};return e.outline&&(e.tagged=!0),{scale:1,displayHeaderFooter:!1,headerTemplate:"",footerTemplate:"",printBackground:!1,landscape:!1,pageRanges:"",preferCSSPageSize:!1,omitBackground:!1,outline:!1,tagged:!0,waitForFonts:!0,...e,width:r,height:n,margin:s}}(e);p&&await this.#Ys.setTransparentBackgroundColor(),g&&await Zc(Vc(this.mainFrame().isolatedRealm().evaluate((()=>document.fonts.ready))).pipe(El(au(t))));const y=this.#Hs.send("Page.printToPDF",{transferMode:"ReturnAsStream",landscape:r,displayHeaderFooter:n,headerTemplate:s,footerTemplate:a,printBackground:i,scale:o,paperWidth:c,paperHeight:l,marginTop:u.top,marginBottom:u.bottom,marginLeft:u.left,marginRight:u.right,pageRanges:d,preferCSSPageSize:h,generateTaggedPDF:m,generateDocumentOutline:f}),b=await Zc(Vc(y).pipe(El(au(t))));return p&&await this.#Ys.resetDefaultBackgroundColor(),$l(b.stream,"`stream` is missing from `Page.printToPDF"),await su(this.#Hs,b.stream)}async pdf(e={}){const{path:t}=e,r=await this.createPDFStream(e),n=await nu(r,t);return $l(n,"Could not create typed array"),n}async close(e={runBeforeUnload:void 0}){const t={stack:[],error:void 0,hasError:!1};try{Ip(t,await this.browserContext().waitForScreenshotOperations(),!1);const r=this.#Hs.connection();$l(r,"Protocol error: Connection closed. Most likely the page has been closed.");!!e.runBeforeUnload?await this.#Hs.send("Page.close"):(await r.send("Target.closeTarget",{targetId:this.#Vs._targetId}),await this.#Js._isClosedDeferred.valueOrThrow())}catch(e){t.error=e,t.hasError=!0}finally{Mp(t)}}isClosed(){return this.#lt}get mouse(){return this.#Zs}async waitForDevicePrompt(e={}){return await this.mainFrame().waitForDevicePrompt(e)}}const Np=new Set(["Timestamp","Documents","Frames","JSEventListeners","Nodes","LayoutCount","RecalcStyleCount","LayoutDuration","RecalcStyleDuration","ScriptDuration","TaskDuration","JSHeapUsedSize","JSHeapTotalSize"]);function $p(e){if(void 0!==e)return"string"==typeof e?{topLevelSite:e,hasCrossSiteAncestor:!1}:{topLevelSite:e.sourceOrigin,hasCrossSiteAncestor:e.hasCrossSiteAncestor??!1}}var Lp,Fp=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Dp=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,s=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===s)return s=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return s|=2,Promise.resolve(a).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class zp extends bu{#tt;#Sa;#Je;constructor(e,t,r){super(),this.#tt=e,this.#Sa=t,this.#Je=r}get id(){return this.#Je}targets(){return this.#Sa.targets().filter((e=>e.browserContext()===this))}async pages(){return(await Promise.all(this.targets().filter((e=>"page"===e.type()||"other"===e.type()&&this.#Sa._getIsPageTargetCallback()?.(e))).map((e=>e.page())))).filter((e=>!!e))}async overridePermissions(e,t){const r=t.map((e=>{const t=mu.get(e);if(!t)throw new Error("Unknown permission: "+e);return t}));await this.#tt.send("Browser.grantPermissions",{origin:e,browserContextId:this.#Je||void 0,permissions:r})}async clearPermissionOverrides(){await this.#tt.send("Browser.resetPermissions",{browserContextId:this.#Je||void 0})}async newPage(){const e={stack:[],error:void 0,hasError:!1};try{Fp(e,await this.waitForScreenshotOperations(),!1);return await this.#Sa._createPageInContext(this.#Je)}catch(t){e.error=t,e.hasError=!0}finally{Dp(e)}}browser(){return this.#Sa}async close(){$l(this.#Je,"Default BrowserContext cannot be closed!"),await this.#Sa._disposeContext(this.#Je)}async cookies(){const{cookies:e}=await this.#tt.send("Storage.getCookies",{browserContextId:this.#Je});return e.map((e=>({...e,partitionKey:e.partitionKey?{sourceOrigin:e.partitionKey.topLevelSite,hasCrossSiteAncestor:e.partitionKey.hasCrossSiteAncestor}:void 0})))}async setCookie(...e){return await this.#tt.send("Storage.setCookies",{browserContextId:this.#Je,cookies:e.map((e=>({...e,partitionKey:$p(e.partitionKey)})))})}async setDownloadBehavior(e){await this.#tt.send("Browser.setDownloadBehavior",{behavior:e.policy,downloadPath:e.downloadPath,browserContextId:this.#Je})}}!function(e){e.SUCCESS="success",e.ABORTED="aborted"}(Lp||(Lp={}));class Up extends ch{#Ea;#xa;#Ta;#Ws;#Ca;#Pa=new Set;_initializedDeferred=gu.create();_isClosedDeferred=gu.create();_targetId;constructor(e,t,r,n,s){super(),this.#xa=t,this.#Ws=n,this.#Ta=e,this.#Ea=r,this._targetId=e.targetId,this.#Ca=s,this.#xa&&this.#xa.setTarget(this)}async asPage(){const e=this._session();return e?await jp._create(e,this,null):await this.createCDPSession().then((e=>jp._create(e,this,null)))}_subtype(){return this.#Ta.subtype}_session(){return this.#xa}_addChildTarget(e){this.#Pa.add(e)}_removeChildTarget(e){this.#Pa.delete(e)}_childTargets(){return this.#Pa}_sessionFactory(){if(!this.#Ca)throw new Error("sessionFactory is not initialized");return this.#Ca}createCDPSession(){if(!this.#Ca)throw new Error("sessionFactory is not initialized");return this.#Ca(!1).then((e=>(e.setTarget(this),e)))}url(){return this.#Ta.url}type(){switch(this.#Ta.type){case"page":return oh.PAGE;case"background_page":return oh.BACKGROUND_PAGE;case"service_worker":return oh.SERVICE_WORKER;case"shared_worker":return oh.SHARED_WORKER;case"browser":return oh.BROWSER;case"webview":return oh.WEBVIEW;case"tab":return oh.TAB;default:return oh.OTHER}}_targetManager(){if(!this.#Ws)throw new Error("targetManager is not initialized");return this.#Ws}_getTargetInfo(){return this.#Ta}browser(){if(!this.#Ea)throw new Error("browserContext is not initialized");return this.#Ea.browser()}browserContext(){if(!this.#Ea)throw new Error("browserContext is not initialized");return this.#Ea}opener(){const{openerId:e}=this.#Ta;if(e)return this.browser().targets().find((t=>t._targetId===e))}_targetInfoChanged(e){this.#Ta=e,this._checkIfInitialized()}_initialize(){this._initializedDeferred.resolve(Lp.SUCCESS)}_isTargetExposed(){return this.type()!==oh.TAB&&!this._subtype()}_checkIfInitialized(){this._initializedDeferred.resolved()||this._initializedDeferred.resolve(Lp.SUCCESS)}}class Bp extends Up{#Oa;pagePromise;constructor(e,t,r,n,s,a){super(e,t,r,n,s),this.#Oa=a??void 0}_initialize(){this._initializedDeferred.valueOrThrow().then((async e=>{if(e===Lp.ABORTED)return;const t=this.opener();if(!(t instanceof Bp))return;if(!t||!t.pagePromise||"page"!==this.type())return!0;const r=await t.pagePromise;if(!r.listenerCount("popup"))return!0;const n=await this.page();return r.emit("popup",n),!0})).catch(Zl),this._checkIfInitialized()}async page(){if(!this.pagePromise){const e=this._session();this.pagePromise=(e?Promise.resolve(e):this._sessionFactory()(!1)).then((e=>jp._create(e,this,this.#Oa??null)))}return await this.pagePromise??null}_checkIfInitialized(){this._initializedDeferred.resolved()||""!==this._getTargetInfo().url&&this._initializedDeferred.resolve(Lp.SUCCESS)}}class qp extends Bp{}class Kp extends Up{#Aa;async worker(){if(!this.#Aa){const e=this._session();this.#Aa=(e?Promise.resolve(e):this._sessionFactory()(!1)).then((e=>new Ap(e,this._getTargetInfo().url,this._targetId,this.type(),(()=>{}),(()=>{}),void 0)))}return await this.#Aa}}class Wp extends Up{}class Hp extends Ml{#tt;#Ia=new Map;#Ma=new Map;#Ra=new Map;#ja=new Set;#Na;#$a;#La=new WeakMap;#Fa=new WeakMap;#Da=gu.create();#za=new Set;#Ua=!0;#Ba=[{}];constructor(e,t,r,n=!0){super(),this.#tt=e,this.#Na=r,this.#$a=t,this.#Ua=n,this.#tt.on("Target.targetCreated",this.#qa),this.#tt.on("Target.targetDestroyed",this.#Ka),this.#tt.on("Target.targetInfoChanged",this.#Wa),this.#tt.on(wu.SessionDetached,this.#Ha),this.#Va(this.#tt)}#Ga=()=>{if(this.#Ua)for(const[e,t]of this.#Ia.entries()){const r=new Up(t,void 0,void 0,this,void 0),n="page"===t.type||"iframe"===t.type,s=t.url.startsWith("chrome-extension://");this.#Na&&!this.#Na(r)||!n||s||this.#za.add(e)}};async initialize(){await this.#tt.send("Target.setDiscoverTargets",{discover:!0,filter:this.#Ba}),this.#Ga(),await this.#tt.send("Target.setAutoAttach",{waitForDebuggerOnStart:!0,flatten:!0,autoAttach:!0,filter:[{type:"page",exclude:!0},...this.#Ba]}),this.#Ja(),await this.#Da.valueOrThrow()}getChildTargets(e){return e._childTargets()}dispose(){this.#tt.off("Target.targetCreated",this.#qa),this.#tt.off("Target.targetDestroyed",this.#Ka),this.#tt.off("Target.targetInfoChanged",this.#Wa),this.#tt.off(wu.SessionDetached,this.#Ha),this.#Za(this.#tt)}getAvailableTargets(){return this.#Ma}#Va(e){const t=t=>{this.#pa(e,t)};$l(!this.#La.has(e)),this.#La.set(e,t),e.on("Target.attachedToTarget",t);const r=t=>this.#ua(e,t);$l(!this.#Fa.has(e)),this.#Fa.set(e,r),e.on("Target.detachedFromTarget",r)}#Za(e){const t=this.#La.get(e);t&&(e.off("Target.attachedToTarget",t),this.#La.delete(e)),this.#Fa.has(e)&&(e.off("Target.detachedFromTarget",this.#Fa.get(e)),this.#Fa.delete(e))}#Ha=e=>{this.#Za(e)};#qa=async e=>{if(this.#Ia.set(e.targetInfo.targetId,e.targetInfo),this.emit("targetDiscovered",e.targetInfo),"browser"===e.targetInfo.type&&e.targetInfo.attached){if(this.#Ma.has(e.targetInfo.targetId))return;const t=this.#$a(e.targetInfo,void 0);t._initialize(),this.#Ma.set(e.targetInfo.targetId,t)}};#Ka=e=>{const t=this.#Ia.get(e.targetId);if(this.#Ia.delete(e.targetId),this.#Ja(e.targetId),"service_worker"===t?.type&&this.#Ma.has(e.targetId)){const t=this.#Ma.get(e.targetId);t&&(this.emit("targetGone",t),this.#Ma.delete(e.targetId))}};#Wa=e=>{if(this.#Ia.set(e.targetInfo.targetId,e.targetInfo),this.#ja.has(e.targetInfo.targetId)||!this.#Ma.has(e.targetInfo.targetId)||!e.targetInfo.attached)return;const t=this.#Ma.get(e.targetInfo.targetId);if(!t)return;const r=t.url(),n=t._initializedDeferred.value()===Lp.SUCCESS;if(function(e,t){return Boolean(e._subtype())&&!t.subtype}(t,e.targetInfo)){const e=t?._session();$l(e,"Target that is being activated is missing a CDPSession."),e.parentSession()?.emit(wu.Swapped,e)}t._targetInfoChanged(e.targetInfo),n&&r!==t.url()&&this.emit("targetChanged",{target:t,wasInitialized:n,previousURL:r})};#pa=async(e,t)=>{const r=t.targetInfo,n=this.#tt._session(t.sessionId);if(!n)throw new Error(`Session ${t.sessionId} was not created.`);const s=async()=>{await n.send("Runtime.runIfWaitingForDebugger").catch(Zl),await e.send("Target.detachFromTarget",{sessionId:n.id()}).catch(Zl)};if(!this.#tt.isAutoAttached(r.targetId))return;if("service_worker"===r.type){if(this.#Ja(r.targetId),await s(),this.#Ma.has(r.targetId))return;const e=this.#$a(r);return e._initialize(),this.#Ma.set(r.targetId,e),void this.emit("targetAvailable",e)}const a=this.#Ma.has(r.targetId),i=a?this.#Ma.get(r.targetId):this.#$a(r,n,e instanceof kh?e:void 0);if(this.#Na&&!this.#Na(i))return this.#ja.add(r.targetId),this.#Ja(r.targetId),void await s();this.#Va(n),a?(n.setTarget(i),this.#Ra.set(n.id(),this.#Ma.get(r.targetId))):(i._initialize(),this.#Ma.set(r.targetId,i),this.#Ra.set(n.id(),i));const o=e instanceof vu?e.target():null;o?._addChildTarget(i),e.emit(wu.Ready,n),this.#za.delete(i._targetId),a||this.emit("targetAvailable",i),this.#Ja(),await Promise.all([n.send("Target.setAutoAttach",{waitForDebuggerOnStart:!0,flatten:!0,autoAttach:!0,filter:this.#Ba}),n.send("Runtime.runIfWaitingForDebugger")]).catch(Zl)};#Ja(e){void 0!==e&&this.#za.delete(e),0===this.#za.size&&this.#Da.resolve()}#ua=(e,t)=>{const r=this.#Ra.get(t.sessionId);this.#Ra.delete(t.sessionId),r&&(e instanceof vu&&e.target()._removeChildTarget(r),this.#Ma.delete(r._targetId),this.emit("targetGone",r))}}class Vp extends fu{protocol="cdp";static async _create(e,t,r,n,s,a,i,o,c,l=!0){const u=new Vp(e,t,n,a,i,o,c,l);return r&&await e.send("Security.setIgnoreCertificateErrors",{ignore:!0}),await u._attach(s),u}#Oa;#Xa;#tt;#Ya;#Na;#Qa;#ei;#ti=new Map;#Ws;constructor(e,t,r,n,s,a,i,o=!0){super(),this.#Oa=r,this.#Xa=n,this.#tt=e,this.#Ya=s||(()=>{}),this.#Na=a||(()=>!0),this.#ri(i),this.#Ws=new Hp(e,this.#ni,this.#Na,o),this.#ei=new zp(this.#tt,this);for(const e of t)this.#ti.set(e,new zp(this.#tt,this,e))}#si=()=>{this.emit("disconnected",void 0)};async _attach(e){this.#tt.on(wu.Disconnected,this.#si),e&&await this.#ei.setDownloadBehavior(e),this.#Ws.on("targetAvailable",this.#pa),this.#Ws.on("targetGone",this.#ua),this.#Ws.on("targetChanged",this.#ai),this.#Ws.on("targetDiscovered",this.#ii),await this.#Ws.initialize()}_detach(){this.#tt.off(wu.Disconnected,this.#si),this.#Ws.off("targetAvailable",this.#pa),this.#Ws.off("targetGone",this.#ua),this.#Ws.off("targetChanged",this.#ai),this.#Ws.off("targetDiscovered",this.#ii)}process(){return this.#Xa??null}_targetManager(){return this.#Ws}#ri(e){this.#Qa=e||(e=>"page"===e.type()||"background_page"===e.type()||"webview"===e.type())}_getIsPageTargetCallback(){return this.#Qa}async createBrowserContext(e={}){const{proxyServer:t,proxyBypassList:r,downloadBehavior:n}=e,{browserContextId:s}=await this.#tt.send("Target.createBrowserContext",{proxyServer:t,proxyBypassList:r&&r.join(",")}),a=new zp(this.#tt,this,s);return n&&await a.setDownloadBehavior(n),this.#ti.set(s,a),a}browserContexts(){return[this.#ei,...Array.from(this.#ti.values())]}defaultBrowserContext(){return this.#ei}async _disposeContext(e){e&&(await this.#tt.send("Target.disposeBrowserContext",{browserContextId:e}),this.#ti.delete(e))}#ni=(e,t)=>{const{browserContextId:r}=e,n=r&&this.#ti.has(r)?this.#ti.get(r):this.#ei;if(!n)throw new Error("Missing browser context");const s=t=>this.#tt._createSession(e,t),a=new Wp(e,t,n,this.#Ws,s);return e.url?.startsWith("devtools://")?new qp(e,t,n,this.#Ws,s,this.#Oa??null):this.#Qa(a)?new Bp(e,t,n,this.#Ws,s,this.#Oa??null):"service_worker"===e.type||"shared_worker"===e.type?new Kp(e,t,n,this.#Ws,s):a};#pa=async e=>{e._isTargetExposed()&&await e._initializedDeferred.valueOrThrow()===Lp.SUCCESS&&(this.emit("targetcreated",e),e.browserContext().emit("targetcreated",e))};#ua=async e=>{e._initializedDeferred.resolve(Lp.ABORTED),e._isClosedDeferred.resolve(),e._isTargetExposed()&&await e._initializedDeferred.valueOrThrow()===Lp.SUCCESS&&(this.emit("targetdestroyed",e),e.browserContext().emit("targetdestroyed",e))};#ai=({target:e})=>{this.emit("targetchanged",e),e.browserContext().emit("targetchanged",e)};#ii=e=>{this.emit("targetdiscovered",e)};wsEndpoint(){return this.#tt.url()}async newPage(){return await this.#ei.newPage()}async _createPageInContext(e){const{targetId:t}=await this.#tt.send("Target.createTarget",{url:"about:blank",browserContextId:e||void 0}),r=await this.waitForTarget((e=>e._targetId===t));if(!r)throw new Error(`Missing target for page (id = ${t})`);if(!(await r._initializedDeferred.valueOrThrow()===Lp.SUCCESS))throw new Error(`Failed to create target for page (id = ${t})`);const n=await r.page();if(!n)throw new Error(`Failed to create a page for context (id = ${e})`);return n}async installExtension(e){const{id:t}=await this.#tt.send("Extensions.loadUnpacked",{path:e});return t}uninstallExtension(e){return this.#tt.send("Extensions.uninstall",{id:e})}targets(){return Array.from(this.#Ws.getAvailableTargets().values()).filter((e=>e._isTargetExposed()&&e._initializedDeferred.value()===Lp.SUCCESS))}target(){const e=this.targets().find((e=>"browser"===e.type()));if(!e)throw new Error("Browser target is not found");return e}async version(){return(await this.#oi()).product}async userAgent(){return(await this.#oi()).userAgent}async close(){await this.#Ya.call(null),await this.disconnect()}disconnect(){return this.#Ws.dispose(),this.#tt.dispose(),this._detach(),Promise.resolve()}get connected(){return!this.#tt._closed}#oi(){return this.#tt.send("Browser.getVersion")}get debugInfo(){return{pendingProtocolErrors:this.#tt.getPendingProtocolErrors()}}}const Gp={targetId:"tabTargetId",type:"tab",title:"tab",url:"about:blank",attached:!1,canAccessOpener:!1},Jp={targetId:"pageTargetId",type:"page",title:"page",url:"about:blank",attached:!1,canAccessOpener:!1};class Zp{static async connectTab(e){return await chrome.debugger.attach({tabId:e},"1.3"),new Zp(e)}onmessage;onclose;#ci;constructor(e){this.#ci=e,chrome.debugger.onEvent.addListener(this.#li)}#li=(e,t,r)=>{e.tabId===this.#ci&&this.#ui({sessionId:e.sessionId??"pageTargetSessionId",method:t,params:r})};#ui(e){this.onmessage?.(JSON.stringify(e))}send(e){const t=JSON.parse(e);switch(t.method){case"Browser.getVersion":return void this.#ui({id:t.id,sessionId:t.sessionId,method:t.method,result:{protocolVersion:"1.3",product:"chrome",revision:"unknown",userAgent:"chrome",jsVersion:"unknown"}});case"Target.getBrowserContexts":return void this.#ui({id:t.id,sessionId:t.sessionId,method:t.method,result:{browserContextIds:[]}});case"Target.setDiscoverTargets":return this.#ui({method:"Target.targetCreated",params:{targetInfo:Gp}}),this.#ui({method:"Target.targetCreated",params:{targetInfo:Jp}}),void this.#ui({id:t.id,sessionId:t.sessionId,method:t.method,result:{}});case"Target.setAutoAttach":if("tabTargetSessionId"===t.sessionId)return this.#ui({method:"Target.attachedToTarget",params:{targetInfo:Jp,sessionId:"pageTargetSessionId"}}),void this.#ui({id:t.id,sessionId:t.sessionId,method:t.method,result:{}});if(!t.sessionId)return this.#ui({method:"Target.attachedToTarget",params:{targetInfo:Gp,sessionId:"tabTargetSessionId"}}),void this.#ui({id:t.id,sessionId:t.sessionId,method:t.method,result:{}})}"pageTargetSessionId"===t.sessionId&&delete t.sessionId,chrome.debugger.sendCommand({tabId:this.#ci,sessionId:t.sessionId},t.method,t.params).then((e=>{this.#ui({id:t.id,sessionId:t.sessionId??"pageTargetSessionId",method:t.method,result:e})})).catch((e=>{this.#ui({id:t.id,sessionId:t.sessionId??"pageTargetSessionId",method:t.method,error:{code:e?.code,data:e?.data,message:e?.message??"CDP error had no message"}})}))}close(){chrome.debugger.onEvent.removeListener(this.#li),chrome.debugger.detach({tabId:this.#ci})}}Object.freeze({"Slow 3G":{download:5e4,upload:5e4,latency:2e3},"Fast 3G":{download:18e4,upload:84375,latency:562.5},"Slow 4G":{download:18e4,upload:84375,latency:562.5},"Fast 4G":{download:1012500,upload:168750,latency:165}});const Xp=[{name:"Blackberry PlayBook",userAgent:"Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+",viewport:{width:600,height:1024,deviceScaleFactor:1,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Blackberry PlayBook landscape",userAgent:"Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+",viewport:{width:1024,height:600,deviceScaleFactor:1,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"BlackBerry Z30",userAgent:"Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+",viewport:{width:360,height:640,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"BlackBerry Z30 landscape",userAgent:"Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+",viewport:{width:640,height:360,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Galaxy Note 3",userAgent:"Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",viewport:{width:360,height:640,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Galaxy Note 3 landscape",userAgent:"Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",viewport:{width:640,height:360,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Galaxy Note II",userAgent:"Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",viewport:{width:360,height:640,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Galaxy Note II landscape",userAgent:"Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",viewport:{width:640,height:360,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Galaxy S III",userAgent:"Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",viewport:{width:360,height:640,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Galaxy S III landscape",userAgent:"Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",viewport:{width:640,height:360,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Galaxy S5",userAgent:"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:360,height:640,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Galaxy S5 landscape",userAgent:"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:640,height:360,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Galaxy S8",userAgent:"Mozilla/5.0 (Linux; Android 7.0; SM-G950U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",viewport:{width:360,height:740,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Galaxy S8 landscape",userAgent:"Mozilla/5.0 (Linux; Android 7.0; SM-G950U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",viewport:{width:740,height:360,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Galaxy S9+",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",viewport:{width:320,height:658,deviceScaleFactor:4.5,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Galaxy S9+ landscape",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",viewport:{width:658,height:320,deviceScaleFactor:4.5,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Galaxy Tab S4",userAgent:"Mozilla/5.0 (Linux; Android 8.1.0; SM-T837A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Safari/537.36",viewport:{width:712,height:1138,deviceScaleFactor:2.25,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Galaxy Tab S4 landscape",userAgent:"Mozilla/5.0 (Linux; Android 8.1.0; SM-T837A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Safari/537.36",viewport:{width:1138,height:712,deviceScaleFactor:2.25,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPad",userAgent:"Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",viewport:{width:768,height:1024,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPad landscape",userAgent:"Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",viewport:{width:1024,height:768,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPad (gen 6)",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:768,height:1024,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPad (gen 6) landscape",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:1024,height:768,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPad (gen 7)",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:810,height:1080,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPad (gen 7) landscape",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:1080,height:810,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPad Mini",userAgent:"Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",viewport:{width:768,height:1024,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPad Mini landscape",userAgent:"Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",viewport:{width:1024,height:768,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPad Pro",userAgent:"Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",viewport:{width:1024,height:1366,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPad Pro landscape",userAgent:"Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",viewport:{width:1366,height:1024,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPad Pro 11",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:834,height:1194,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPad Pro 11 landscape",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:1194,height:834,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 4",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53",viewport:{width:320,height:480,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 4 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53",viewport:{width:480,height:320,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 5",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",viewport:{width:320,height:568,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 5 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",viewport:{width:568,height:320,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 6",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:375,height:667,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 6 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:667,height:375,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 6 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:414,height:736,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 6 Plus landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:736,height:414,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 7",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:375,height:667,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 7 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:667,height:375,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 7 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:414,height:736,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 7 Plus landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:736,height:414,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 8",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:375,height:667,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 8 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:667,height:375,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 8 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:414,height:736,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 8 Plus landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:736,height:414,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone SE",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",viewport:{width:320,height:568,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone SE landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",viewport:{width:568,height:320,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone X",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:375,height:812,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone X landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:812,height:375,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone XR",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",viewport:{width:414,height:896,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone XR landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",viewport:{width:896,height:414,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 11",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",viewport:{width:414,height:828,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 11 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",viewport:{width:828,height:414,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 11 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",viewport:{width:375,height:812,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 11 Pro landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",viewport:{width:812,height:375,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 11 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",viewport:{width:414,height:896,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 11 Pro Max landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",viewport:{width:896,height:414,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 12",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:390,height:844,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 12 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:844,height:390,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 12 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:390,height:844,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 12 Pro landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:844,height:390,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 12 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:428,height:926,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 12 Pro Max landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:926,height:428,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 12 Mini",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:375,height:812,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 12 Mini landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:812,height:375,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 13",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:390,height:844,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 13 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:844,height:390,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 13 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:390,height:844,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 13 Pro landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:844,height:390,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 13 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:428,height:926,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 13 Pro Max landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:926,height:428,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 13 Mini",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:375,height:812,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 13 Mini landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:812,height:375,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 14",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",viewport:{width:390,height:663,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 14 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",viewport:{width:750,height:340,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 14 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",viewport:{width:428,height:745,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 14 Plus landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",viewport:{width:832,height:378,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 14 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",viewport:{width:393,height:659,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 14 Pro landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",viewport:{width:734,height:343,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 14 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",viewport:{width:430,height:739,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 14 Pro Max landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",viewport:{width:814,height:380,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 15",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",viewport:{width:393,height:659,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 15 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",viewport:{width:734,height:343,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 15 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",viewport:{width:430,height:739,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 15 Plus landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",viewport:{width:814,height:380,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 15 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",viewport:{width:393,height:659,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 15 Pro landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",viewport:{width:734,height:343,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 15 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",viewport:{width:430,height:739,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 15 Pro Max landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",viewport:{width:814,height:380,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"JioPhone 2",userAgent:"Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5",viewport:{width:240,height:320,deviceScaleFactor:1,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"JioPhone 2 landscape",userAgent:"Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5",viewport:{width:320,height:240,deviceScaleFactor:1,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Kindle Fire HDX",userAgent:"Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",viewport:{width:800,height:1280,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Kindle Fire HDX landscape",userAgent:"Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",viewport:{width:1280,height:800,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"LG Optimus L70",userAgent:"Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:384,height:640,deviceScaleFactor:1.25,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"LG Optimus L70 landscape",userAgent:"Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:640,height:384,deviceScaleFactor:1.25,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Microsoft Lumia 550",userAgent:"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263",viewport:{width:640,height:360,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Microsoft Lumia 950",userAgent:"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263",viewport:{width:360,height:640,deviceScaleFactor:4,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Microsoft Lumia 950 landscape",userAgent:"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263",viewport:{width:640,height:360,deviceScaleFactor:4,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nexus 10",userAgent:"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36",viewport:{width:800,height:1280,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nexus 10 landscape",userAgent:"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36",viewport:{width:1280,height:800,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nexus 4",userAgent:"Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:384,height:640,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nexus 4 landscape",userAgent:"Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:640,height:384,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nexus 5",userAgent:"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:360,height:640,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nexus 5 landscape",userAgent:"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:640,height:360,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nexus 5X",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:412,height:732,deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nexus 5X landscape",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:732,height:412,deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nexus 6",userAgent:"Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:412,height:732,deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nexus 6 landscape",userAgent:"Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:732,height:412,deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nexus 6P",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:412,height:732,deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nexus 6P landscape",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:732,height:412,deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nexus 7",userAgent:"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36",viewport:{width:600,height:960,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nexus 7 landscape",userAgent:"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36",viewport:{width:960,height:600,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nokia Lumia 520",userAgent:"Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)",viewport:{width:320,height:533,deviceScaleFactor:1.5,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nokia Lumia 520 landscape",userAgent:"Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)",viewport:{width:533,height:320,deviceScaleFactor:1.5,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nokia N9",userAgent:"Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13",viewport:{width:480,height:854,deviceScaleFactor:1,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nokia N9 landscape",userAgent:"Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13",viewport:{width:854,height:480,deviceScaleFactor:1,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Pixel 2",userAgent:"Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:411,height:731,deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Pixel 2 landscape",userAgent:"Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:731,height:411,deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Pixel 2 XL",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:411,height:823,deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Pixel 2 XL landscape",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:823,height:411,deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Pixel 3",userAgent:"Mozilla/5.0 (Linux; Android 9; Pixel 3 Build/PQ1A.181105.017.A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.158 Mobile Safari/537.36",viewport:{width:393,height:786,deviceScaleFactor:2.75,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Pixel 3 landscape",userAgent:"Mozilla/5.0 (Linux; Android 9; Pixel 3 Build/PQ1A.181105.017.A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.158 Mobile Safari/537.36",viewport:{width:786,height:393,deviceScaleFactor:2.75,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Pixel 4",userAgent:"Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36",viewport:{width:353,height:745,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Pixel 4 landscape",userAgent:"Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36",viewport:{width:745,height:353,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Pixel 4a (5G)",userAgent:"Mozilla/5.0 (Linux; Android 11; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",viewport:{width:353,height:745,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Pixel 4a (5G) landscape",userAgent:"Mozilla/5.0 (Linux; Android 11; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",viewport:{width:745,height:353,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Pixel 5",userAgent:"Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",viewport:{width:393,height:851,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Pixel 5 landscape",userAgent:"Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",viewport:{width:851,height:393,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Moto G4",userAgent:"Mozilla/5.0 (Linux; Android 7.0; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",viewport:{width:360,height:640,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Moto G4 landscape",userAgent:"Mozilla/5.0 (Linux; Android 7.0; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",viewport:{width:640,height:360,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}}],Yp={};for(const e of Xp)Yp[e.name]=e;Object.freeze(Yp);async function Qp(e,t,r){const{acceptInsecureCerts:n=!1,defaultViewport:s=Xl}=r,{bidiConnection:a,cdpConnection:i,closeCallback:o}=await async function(e,t,r){const n=await import("./bidi.js"),{slowMo:s=0,protocolTimeout:a}=r,i=new n.BidiConnection(t,e,s,a);try{const e=await i.send("session.status",{});if("type"in e&&"success"===e.type)return{bidiConnection:i,closeCallback:async()=>{await i.send("browser.close",{}).catch(Zl)}}}catch(e){if(!(e instanceof Hl))throw e}i.unbind();const o=new xh(t,e,s,a,!0),c=await o.send("Browser.getVersion");if(c.product.toLowerCase().includes("firefox"))throw new Vl("Firefox is not supported in BiDi over CDP mode.");const l=await n.connectBidiOverCdp(o);return{cdpConnection:o,bidiConnection:l,closeCallback:async()=>{await o.send("Browser.close").catch(Zl)}}}(e,t,r),c=await import("./bidi.js");return await c.BidiBrowser.create({connection:a,cdpConnection:i,closeCallback:o,process:void 0,defaultViewport:s,acceptInsecureCerts:n,capabilities:r.capabilities})}const em=async()=>Rl?(await Promise.resolve().then(s.bind(s,874))).NodeWebSocketTransport:(await Promise.resolve().then(s.bind(s,5001))).BrowserWebSocketTransport;async function tm(e){const{connectionTransport:t,endpointUrl:r}=await async function(e){const{browserWSEndpoint:t,browserURL:r,transport:n,headers:s={}}=e;if($l(Number(!!t)+Number(!!r)+Number(!!n)===1,"Exactly one of browserWSEndpoint, browserURL or transport must be passed to puppeteer.connect"),n)return{connectionTransport:n,endpointUrl:""};if(t){const e=await em();return{connectionTransport:await e.create(t,s),endpointUrl:t}}if(r){const e=await async function(e){const t=new URL("/json/version",e);try{const e=await globalThis.fetch(t.toString(),{method:"GET"});if(!e.ok)throw new Error(`HTTP ${e.statusText}`);return(await e.json()).webSocketDebuggerUrl}catch(e){throw ku(e)&&(e.message=`Failed to fetch browser webSocket URL from ${t}: `+e.message),e}}(r),t=await em();return{connectionTransport:await t.create(e),endpointUrl:e}}throw new Error("Invalid connection options")}(e);if("webDriverBiDi"===e.protocol){return await Qp(t,r,e)}{const n=await async function(e,t,r){const{acceptInsecureCerts:n=!1,defaultViewport:s=Xl,downloadBehavior:a,targetFilter:i,_isPageTarget:o,slowMo:c=0,protocolTimeout:l}=r,u=new xh(t,e,c,l),{browserContextIds:d}=await u.send("Target.getBrowserContexts");return await Vp._create(u,d,n,s,a,void 0,(()=>u.send("Browser.close").catch(Zl)),i,o)}(t,r,e);return n}}Object.freeze({chrome:"136.0.7103.92","chrome-headless-shell":"136.0.7103.92",firefox:"stable_138.0.1"});const rm=new class{static customQueryHandlers=Uu;static registerCustomQueryHandler(e,t){return this.customQueryHandlers.register(e,t)}static unregisterCustomQueryHandler(e){return this.customQueryHandlers.unregister(e)}static customQueryHandlerNames(){return this.customQueryHandlers.names()}static clearCustomQueryHandlers(){return this.customQueryHandlers.clear()}_isPuppeteerCore;_changedBrowsers=!1;constructor(e){this._isPuppeteerCore=e.isPuppeteerCore,this.connect=this.connect.bind(this)}connect(e){return tm(e)}}({isPuppeteerCore:!0}),{connect:nm}=rm,sm=M.z.object({debugMode:M.z.boolean().default(!1)}),am=M.z.object({url:M.z.string(),title:M.z.string(),tabId:M.z.number().int().positive(),isLoading:M.z.boolean().default(!1),timestamp:M.z.number().int().positive()});class im{constructor(e,t,r={debugMode:!1}){this.puppeteerPage=e,this.tabId=t,this.options=sm.parse(r),this.options.debugMode&&X.log("NxtscapePage",`Page wrapper created for tab ${t}`)}async getState(){try{const e=this.puppeteerPage.url(),t=await this.puppeteerPage.title();return am.parse({url:e,title:t,tabId:this.tabId,isLoading:!1,timestamp:Date.now()})}catch(e){return X.log("NxtscapePage",`Error getting page state: ${e}`,"error"),am.parse({url:"about:blank",title:"Unknown",tabId:this.tabId,isLoading:!1,timestamp:Date.now()})}}async navigate(e){try{this.options.debugMode&&X.log("NxtscapePage",`Navigating to: ${e}`),await this.puppeteerPage.goto(e,{waitUntil:"domcontentloaded",timeout:3e4}),this.options.debugMode&&X.log("NxtscapePage",`Navigation to ${e} completed`)}catch(t){const r=t instanceof Error?t.message:String(t);throw X.log("NxtscapePage",`Navigation failed: ${r}`,"error"),new Error(`Navigation to ${e} failed: ${r}`)}}async click(e){try{this.options.debugMode&&X.log("NxtscapePage",`Clicking element: ${e}`),await this.puppeteerPage.waitForSelector(e,{visible:!0,timeout:1e4}),await this.puppeteerPage.click(e),this.options.debugMode&&X.log("NxtscapePage",`Click on ${e} completed`)}catch(t){const r=t instanceof Error?t.message:String(t);throw X.log("NxtscapePage",`Click failed: ${r}`,"error"),new Error(`Click on ${e} failed: ${r}`)}}async findElementByDescription(e){try{this.options.debugMode&&X.log("NxtscapePage",`Finding element by description: ${e}`);const t={"search box":'input[type="search"], input[name*="search"], input[placeholder*="search"], textarea[placeholder*="search"]',"search input":'input[type="search"], input[name*="search"], input[placeholder*="search"]',"search button":'button[type="submit"], input[type="submit"], button:contains("Search")',"email input":'input[type="email"], input[name*="email"], input[placeholder*="email"]',"email field":'input[type="email"], input[name*="email"], input[placeholder*="email"]',"password field":'input[type="password"], input[name*="password"], input[placeholder*="password"]',"password input":'input[type="password"], input[name*="password"], input[placeholder*="password"]',"username input":'input[name*="username"], input[name*="user"], input[placeholder*="username"]',"username field":'input[name*="username"], input[name*="user"], input[placeholder*="username"]',"text input":'input[type="text"], textarea',"text field":'input[type="text"], textarea',"message box":'textarea[placeholder*="message"], textarea[name*="message"]',"comment box":'textarea[placeholder*="comment"], textarea[name*="comment"]',"login button":'button:contains("Login"), button:contains("Sign in"), a:contains("Login"), input[type="submit"][value*="Login"]',"sign in button":'button:contains("Sign in"), button:contains("Login"), a:contains("Sign in"), input[type="submit"][value*="Sign"]',"submit button":'button[type="submit"], input[type="submit"]',"menu button":'button[aria-label*="menu"], button:contains("Menu"), button[class*="menu"]',"close button":'button:contains("Close"), button[aria-label*="close"], button[class*="close"]'},r=e.toLowerCase();for(const[e,n]of Object.entries(t))if(r.includes(e)){if(await this.puppeteerPage.$(n))return n}return null}catch(e){return X.log("NxtscapePage",`Error finding element: ${e}`,"error"),null}}async type(e,t){try{this.options.debugMode&&X.log("NxtscapePage",`Typing into ${e}: ${t}`),await this.puppeteerPage.click(e,{clickCount:3}),await this.puppeteerPage.keyboard.press("Backspace"),await this.puppeteerPage.type(e,t),this.options.debugMode&&X.log("NxtscapePage","Text input completed")}catch(t){const r=t instanceof Error?t.message:String(t);throw X.log("NxtscapePage",`Type failed: ${r}`,"error"),new Error(`Type into ${e} failed: ${r}`)}}async waitForElement(e,t=1e4){try{this.options.debugMode&&X.log("NxtscapePage",`Waiting for element: ${e}`),await this.puppeteerPage.waitForSelector(e,{visible:!0,timeout:t}),this.options.debugMode&&X.log("NxtscapePage",`Element ${e} is now visible`)}catch(t){const r=t instanceof Error?t.message:String(t);throw X.log("NxtscapePage",`Wait for element failed: ${r}`,"error"),new Error(`Wait for ${e} failed: ${r}`)}}async screenshot(){try{this.options.debugMode&&X.log("NxtscapePage","Taking screenshot");const e=await this.puppeteerPage.screenshot({type:"png",fullPage:!1,encoding:"base64"});return this.options.debugMode&&X.log("NxtscapePage",`Screenshot captured (${e.length} chars)`),e}catch(e){const t=e instanceof Error?e.message:String(e);throw X.log("NxtscapePage",`Screenshot failed: ${t}`,"error"),new Error(`Screenshot failed: ${t}`)}}getPuppeteerPage(){return this.puppeteerPage}getPlaywrightPage(){return this.puppeteerPage}getTabId(){return this.tabId}async evaluate(e){try{return this.options.debugMode&&X.log("NxtscapePage","Evaluating JavaScript"),await this.puppeteerPage.evaluate(e)}catch(e){const t=e instanceof Error?e.message:String(e);throw X.log("NxtscapePage",`Evaluation failed: ${t}`,"error"),new Error(`JavaScript evaluation failed: ${t}`)}}async close(){try{this.options.debugMode&&X.log("NxtscapePage",`Closing page for tab ${this.tabId}`),await chrome.tabs.remove(this.tabId),this.options.debugMode&&X.log("NxtscapePage",`Tab ${this.tabId} closed`)}catch(e){X.log("NxtscapePage",`Error closing page: ${e}`,"error")}}}const om=M.z.object({debugMode:M.z.boolean().default(!1).optional()});class cm{constructor(e={}){this.currentPage=null,this.currentTabId=null,this.isInitialized=!1,this.attachedTabs=new Map,this.options=om.parse(e),this.options.debugMode&&X.log("NxtscapeBrowserContext","Browser context created")}async initialize(){if(!this.isInitialized)try{X.log("NxtscapeBrowserContext","Initializing browser context with event listeners"),this.setupTabEventListeners(),this.isInitialized=!0,X.log("NxtscapeBrowserContext","Browser context initialized successfully")}catch(e){const t=e instanceof Error?e.message:String(e);throw X.log("NxtscapeBrowserContext",`Failed to initialize: ${t}`,"error"),new Error(`Browser context initialization failed: ${t}`)}}setupTabEventListeners(){chrome.tabs.onRemoved.addListener((e=>{this.isTabAttached(e)&&(X.log("NxtscapeBrowserContext",`Tab ${e} was closed, cleaning up state`),this.cleanupTab(e),e===this.currentTabId&&(this.currentTabId=null,this.currentPage=null))})),chrome.windows.onRemoved.addListener((async e=>{X.log("NxtscapeBrowserContext",`Window ${e} was closed, cleaning up tabs`);for(const[t,r]of this.attachedTabs.entries())try{const r=await chrome.tabs.get(t).catch((()=>null));r&&r.windowId!==e||this.cleanupTab(t)}catch(e){this.cleanupTab(t)}})),X.log("NxtscapeBrowserContext","Tab event listeners set up")}isTabAttached(e){return this.attachedTabs.has(e)}async cleanupTab(e){const t=this.attachedTabs.get(e);if(t){try{await t.browser.disconnect(),X.log("NxtscapeBrowserContext",`Disconnected browser for tab ${e}`)}catch(t){X.log("NxtscapeBrowserContext",`Error disconnecting browser for tab ${e}: ${t}`,"warning")}this.attachedTabs.delete(e)}try{await new Promise((t=>{chrome.debugger.detach({tabId:e},(()=>{t()}))}))}catch(e){}}async createPuppeteerConnection(e){X.log("NxtscapeBrowserContext",`Creating Puppeteer connection for tab ${e}`);const t=await nm({transport:await Zp.connectTab(e),defaultViewport:null,protocol:"cdp"}),[r]=await t.pages();if(!r)throw new Error("No page found in browser");return await this.addAntiDetectionScripts(r),{browser:t,page:r}}async addAntiDetectionScripts(e){await e.evaluateOnNewDocument("\n // Webdriver property\n Object.defineProperty(navigator, 'webdriver', {\n get: () => undefined\n });\n\n // Chrome runtime\n window.chrome = { runtime: {} };\n\n // Permissions\n const originalQuery = window.navigator.permissions.query;\n window.navigator.permissions.query = (parameters) => (\n parameters.name === 'notifications' ?\n Promise.resolve({ state: Notification.permission }) :\n originalQuery(parameters)\n );\n ")}async getCurrentPage(){if(this.isInitialized||await this.initialize(),this.currentPage&&this.currentTabId&&this.isTabAttached(this.currentTabId))try{const e=this.attachedTabs.get(this.currentTabId);if(e)return await e.page.evaluate("1"),this.currentPage}catch(e){X.log("NxtscapeBrowserContext","Current page health check failed, will get fresh page"),this.currentPage=null,this.currentTabId=null}const e=await this.getActiveTab();if(!(e.length>0&&e[0].id))return X.log("NxtscapeBrowserContext","No active tab found, creating new tab"),await this.createNewTab();{const t=e[0].id;X.log("NxtscapeBrowserContext",`Getting page for active tab ${t}`);try{return await this.attachToTab(t)}catch(e){const r=e instanceof Error?e.message:String(e);if(r.includes("Another debugger is already attached")||r.includes("has another debugger attached"))return X.log("NxtscapeBrowserContext",`Active tab ${t} has debugger conflict, creating new tab as fallback`,"warning"),await this.createNewTab();throw e}}}async getActiveTab(){let e=await chrome.tabs.query({active:!0,lastFocusedWindow:!0});if(0===e.length){const t=(await chrome.windows.getAll({populate:!0})).find((e=>e.focused));t&&t.tabs&&(e=t.tabs.filter((e=>e.active)))}return 0===e.length&&(e=await chrome.tabs.query({active:!0})),e}async getCurrentWindow(){let e=await chrome.tabs.query({active:!0,lastFocusedWindow:!0});if(e.length>0){return await chrome.windows.get(e[0].windowId)}const t=await chrome.windows.getAll({populate:!0}),r=t.find((e=>e.focused));if(r&&r.id)return r;const n=t[0];if(n&&n.id)return n;throw new Error("No window found")}isDebuggerAvailable(){return!!(chrome&&chrome.debugger&&chrome.debugger.detach)}async forceDetachDebuggers(e){if(this.isDebuggerAvailable())try{X.log("NxtscapeBrowserContext",`Force detaching debuggers from tab ${e}`);if(!await chrome.tabs.get(e).catch((()=>null)))return void X.log("NxtscapeBrowserContext",`Tab ${e} not found, cannot detach debugger`);await new Promise((t=>{chrome.debugger.detach({tabId:e},(()=>{chrome.runtime.lastError?X.log("NxtscapeBrowserContext",`No debugger to detach from tab ${e}: ${chrome.runtime.lastError.message}`):X.log("NxtscapeBrowserContext",`Successfully detached debugger from tab ${e}`),t()}))})),await new Promise((e=>setTimeout(e,500))),X.log("NxtscapeBrowserContext",`Debugger detach process completed for tab ${e}`)}catch(t){X.log("NxtscapeBrowserContext",`Error force detaching debuggers from tab ${e}: ${t}`,"warning")}else X.log("NxtscapeBrowserContext","Chrome debugger API not available, skipping detach","warning")}async attachToTab(e,t=0){this.isInitialized||await this.initialize();try{if(X.log("NxtscapeBrowserContext",`Attaching to tab ${e}${t>0?` (retry ${t})`:""}`),this.isTabAttached(e)&&(X.log("NxtscapeBrowserContext",`Tab ${e} already attached`),this.currentTabId===e&&this.currentPage))return this.currentPage;const r=await chrome.tabs.get(e);if(X.log("NxtscapeBrowserContext",`Tab details: URL=${r.url}, status=${r.status}, windowId=${r.windowId}`),!r)throw new Error(`Tab ${e} not found`);r.discarded&&(X.log("NxtscapeBrowserContext",`Tab ${e} is discarded, activating...`),await chrome.tabs.update(e,{active:!0}),await new Promise((e=>setTimeout(e,1e3))));this.isProblematicUrl(r.url)&&(X.log("NxtscapeBrowserContext",`Tab has problematic URL: ${r.url}, navigating to Google...`),await chrome.tabs.update(e,{url:"https://www.google.com"}),await new Promise((e=>setTimeout(e,2e3)))),"loading"===r.status&&(X.log("NxtscapeBrowserContext",`Tab ${e} is loading, waiting...`),await this.waitForTabToLoad(e,5e3)),await this.cleanupTab(e);const{browser:n,page:s}=await this.createPuppeteerConnection(e);this.attachedTabs.set(e,{browser:n,page:s});const a=new im(s,e,{debugMode:this.options.debugMode||!1});return this.currentPage=a,this.currentTabId=e,X.log("NxtscapeBrowserContext",`Successfully attached to tab ${e}`),a}catch(r){const n=r instanceof Error?r.message:String(r);if(X.log("NxtscapeBrowserContext",`Failed to attach to tab ${e}: ${n}`,"error"),await this.cleanupTab(e),n.includes("Another debugger is already attached")&&t<2){X.log("NxtscapeBrowserContext",`Debugger conflict detected for tab ${e}, attempting to detach and retry...`);try{return await this.forceDetachDebuggers(e),await this.attachToTab(e,t+1)}catch(t){const r=t instanceof Error?t.message:String(t);throw X.log("NxtscapeBrowserContext",`Retry failed for tab ${e}: ${r}`,"error"),new Error(`Failed to attach to tab ${e} after detaching debuggers: ${r}`)}}if(n.includes("Cannot attach to this target"))throw new Error(`Tab ${e} cannot be attached. This usually happens when Chrome DevTools is open on this tab. Please close DevTools and try again.`);if(n.includes("Target closed"))throw new Error(`Tab ${e} target was closed. The tab may have been closed or navigated to a restricted page.`);if(n.includes("Another debugger is already attached"))throw new Error(`Tab ${e} has another debugger attached. Please close Chrome DevTools or other debugging tools and try again.`);throw new Error(`Cannot attach to tab ${e}: ${n}`)}}isProblematicUrl(e){if(!e)return!0;return["chrome://","chrome-extension://","edge://","about:","moz-extension://","devtools://","chrome-devtools://","file://"].some((t=>e.startsWith(t)))}async waitForTabToLoad(e,t=5e3){const r=Date.now();for(;Date.now()-rsetTimeout(e,200)))}catch(t){X.log("NxtscapeBrowserContext",`Error checking tab ${e} status: ${t}`,"warning");break}X.log("NxtscapeBrowserContext",`Tab ${e} loading timeout after ${t}ms`,"warning")}async forceReset(){try{X.log("NxtscapeBrowserContext","Force resetting all browser connections"),this.currentPage=null,this.currentTabId=null;const e=[];for(const[t]of this.attachedTabs.entries())e.push(this.cleanupTab(t));return await Promise.all(e),this.isInitialized=!1,await this.initialize(),!0}catch(e){return X.log("NxtscapeBrowserContext",`Force reset failed: ${e}`,"error"),!1}}async forceDetachFromTab(e){try{return X.log("NxtscapeBrowserContext",`Public request to force detach debuggers from tab ${e}`),await this.cleanupTab(e),await this.forceDetachDebuggers(e),this.currentTabId===e&&(this.currentTabId=null,this.currentPage=null),X.log("NxtscapeBrowserContext",`Successfully force detached from tab ${e}`),!0}catch(t){return X.log("NxtscapeBrowserContext",`Failed to force detach from tab ${e}: ${t}`,"error"),!1}}async createNewTab(e="https://www.google.com"){try{X.log("NxtscapeBrowserContext",`Creating new tab with URL: ${e}`);const t=await chrome.tabs.create({url:e,active:!0});if(!t.id)throw new Error("Failed to create new tab");return X.log("NxtscapeBrowserContext",`Created new tab ${t.id}`),await new Promise((e=>setTimeout(e,1500))),await this.attachToTab(t.id)}catch(e){const t=e instanceof Error?e.message:String(e);throw X.log("NxtscapeBrowserContext",`Error creating new tab: ${t}`,"error"),new Error(`Failed to create new tab: ${t}`)}}getCurrentTabId(){return this.currentTabId}isReady(){return this.isInitialized}async executeScript(e){if(!this.currentPage)throw new Error("No current page available for script execution");try{const t=this.currentPage.getPuppeteerPage();if(e.files&&e.files.length>0)for(const r of e.files)"Readability.js"===r&&await t.evaluate((()=>{window.Readability||(window.Readability=class{constructor(e){this.doc=e}parse(){return{title:document.title||"Unknown Title",byline:null,textContent:document.body?.innerText||"",excerpt:document.body?.innerText?.substring(0,200)||"",url:window.location.href}}})}));return e.func?await t.evaluate(e.func):{}}catch(e){const t=e instanceof Error?e.message:String(e);throw X.log("NxtscapeBrowserContext",`Script execution failed: ${t}`,"error"),new Error(`Script execution failed: ${t}`)}}async cleanup(){try{X.log("NxtscapeBrowserContext","Cleaning up browser context"),this.currentPage=null,this.currentTabId=null;const e=[];for(const[t]of this.attachedTabs.entries())e.push(this.cleanupTab(t));await Promise.all(e),this.isInitialized=!1,X.log("NxtscapeBrowserContext","Browser context cleaned up successfully")}catch(e){X.log("NxtscapeBrowserContext",`Error during cleanup: ${e}`,"error")}}}const lm=cm;class um{constructor(e,t){this.callbacks=e,this.toolRegistry=t,this.currentSegmentId=0,this.currentSegmentContent="",this.isProcessingTool=!1,this.stepCount=0}getToolDisplayInfo(e,t){if(this.toolRegistry){const r=this.toolRegistry.getByName(e);if(r)return r.getDisplayInfo(t)}const r=this.getFallbackDisplay(e);return{displayName:r.displayName,icon:r.icon,description:r.displayName}}getFallbackDisplay(e){return{displayName:e,icon:"šŸ”§"}}cleanToolResult(e){if(!e)return"Completed";try{const t=JSON.parse(e);let r=t;return this.isLangChainToolMessage(t)&&(r=JSON.parse(t.kwargs.content)),r._displayResult?r._displayResult:r.message?r.message:"Completed successfully"}catch(t){return e.length>150?`${e.substring(0,150).trim()}...`:e.trim()}}isLangChainToolMessage(e){return e&&1===e.lc&&"constructor"===e.type&&e.id&&Array.isArray(e.id)&&e.id.includes("ToolMessage")&&e.kwargs?.content}async processEvent(e){if(this.callbacks.abortController?.signal.aborted)return;const t=e.event;try{switch(t){case"on_chat_model_stream":this.handleChatModelStream(e);break;case"on_tool_start":this.handleToolStart(e);break;case"on_tool_end":this.handleToolEnd(e);break;case"on_chain_start":"RunnableAgent"!==e.name&&"agent"!==e.name||this.handleAgentStart();break;case"on_llm_end":this.handleLlmEnd();break;case"on_chain_error":case"on_tool_error":this.handleError(e)}}catch(e){X.log("StreamProcessor",`Error processing event: ${e}`,"error"),this.callbacks.onError?.(e)}}handleChatModelStream(e){const t=e.data?.chunk;if(t?.content){let e="";if("string"==typeof t.content)e=t.content;else if(Array.isArray(t.content)){e=t.content.filter((e=>"text"===e.type)).map((e=>e.text||"")).join("")}e&&(this.currentSegmentContent+=e,this.callbacks.onStreamingChunk?.(e))}}handleToolStart(e){this.currentSegmentContent&&(this.callbacks.onFinalizeSegment?.(this.currentSegmentId,this.currentSegmentContent),this.currentSegmentContent="",this.currentSegmentId++);const t=e.name||"unknown",r=e.data?.input||{};this.isProcessingTool=!0,this.stepCount++;let n=r;if("string"==typeof r)try{n=JSON.parse(r)}catch{n={input:r}}const s=this.getToolDisplayInfo(t,n);this.callbacks.onToolCall?.(s.displayName,{description:s.description,icon:s.icon,args:n})}handleToolEnd(e){const t=e.name||"unknown",r=e.data?.output||"";this.isProcessingTool=!1;let n="";"string"==typeof r?n=r:"object"==typeof r&&(n=JSON.stringify(r,null,2));const s=this.cleanToolResult(n),a=this.getToolDisplayInfo(t,{});this.callbacks.onToolResult?.(a.displayName,s),this.currentSegmentId++,this.callbacks.onStartNewSegment?.(this.currentSegmentId)}handleAgentStart(){this.stepCount++,this.callbacks.onStartNewSegment?.(this.currentSegmentId)}handleLlmEnd(){this.currentSegmentContent&&!this.isProcessingTool&&(this.callbacks.onFinalizeSegment?.(this.currentSegmentId,this.currentSegmentContent),this.currentSegmentContent="")}handleError(e){const t=e.data?.error||e.error||"Unknown error occurred";X.log("StreamProcessor",`[ERROR_EVENT] ${t}`,"error"),this.callbacks.onSystemMessage?.(`āŒ Error: ${t}`),this.callbacks.onError&&this.callbacks.onError(new Error(t))}completeStreaming(){this.currentSegmentContent&&(this.callbacks.onFinalizeSegment?.(this.currentSegmentId,this.currentSegmentContent),this.currentSegmentContent=""),this.callbacks.onStreamingComplete?.()}getStepCount(){return this.stepCount}reset(){this.currentSegmentId=0,this.currentSegmentContent="",this.isProcessingTool=!1,this.stepCount=0}}const dm=M.z.object({llmProvider:M.z.custom((e=>null!==e&&"object"==typeof e&&"invoke"in e&&"function"==typeof e.invoke)).refine((e=>!0),{message:"llmProvider must be a valid LLM implementation (like ChatOpenAI, ChatAnthropic, or similar)"}),browserContext:M.z.instanceof(lm),systemPrompt:M.z.string().optional(),maxSteps:M.z.number().int().positive().optional().default(10),debugMode:M.z.boolean().default(!1)});class hm{constructor(e){this.isInitialized=!1,this.options=dm.parse(e),this.browserContext=this.options.browserContext,this.debugMode=this.options.debugMode}async initialize(){if(!this.isInitialized)try{this.toolRegistry=this.createToolRegistry(),this.systemPrompt=this.options.systemPrompt||this.getDefaultSystemPrompt();const e=this.createTools();this.agent=So({llm:this.options.llmProvider,tools:e}),this.isInitialized=!0,this.debugMode&&this.log(`${this.getAgentName()} initialized with ${e.length} tools`)}catch(e){throw this.log(`Failed to initialize ${this.getAgentName()}: ${e}`,"error"),e}}createToolRegistry(){throw new Error("createToolRegistry must be implemented by subclasses")}getToolRegistry(){return this.toolRegistry}getInitializationMessage(){return`šŸš€ Initializing ${this.getAgentName().toLowerCase()}...`}async ensureInitialized(){this.isInitialized||await this.initialize()}async execute(e,t,r){await this.ensureInitialized();try{const{instruction:n}=e;this.debugMode&&this.log(`šŸš€ Starting streaming agent execution: ${n}`);const s=await this.browserContext.getCurrentPage(),a=await s.getState(),i=this.addBrowserContext(n,a),o=r?.abortController||new AbortController,c=o.signal,l=this.getToolRegistry(),u=new um({onStreamingChunk:r?.onStreamingChunk,onFinalizeSegment:r?.onFinalizeSegment,onStartNewSegment:r?.onStartNewSegment,onSystemMessage:r?.onSystemMessage,onToolCall:r?.onToolCall,onToolResult:r?.onToolResult,onStreamingComplete:r?.onStreamingComplete,onError:r?.onError,onCancel:r?.onCancel,abortController:o},l);if(l?this.log(`StreamProcessor initialized with tool registry (${l.getAll().length} tools)`):this.log("StreamProcessor initialized without tool registry (using fallback display)"),c.aborted)throw new Error("Task was cancelled before execution");const d=await this.agent.streamEvents({messages:[new se.SystemMessage(this.systemPrompt),new se.HumanMessage(i)]},{version:"v2",signal:c}),h=[];let p=!1;try{for await(const e of d){if(c.aborted){p=!0;break}if(await u.processEvent(e),"on_chat_model_end"===e.event||"on_tool_end"===e.event){const t=e.data?.output;t&&h.push(t)}}}catch(e){if(!(e instanceof Error&&"AbortError"===e.name))throw e;p=!0,this.log("Task was cancelled by user","info")}u.completeStreaming();const m={success:!p,messages:h,pageState:await s.getState(),stepCount:u.getStepCount(),cancelled:p};if(p){const e=n.length>60?n.substring(0,60)+"...":n;m.error=`Task cancelled: "${e}"`,r?.onCancel?.(),r?.onSystemMessage?.(`šŸ›‘ Task cancelled: "${e}"`),r?.onStreamingComplete?.(),this.debugMode&&this.log(`šŸ›‘ EXECUTION CANCELLED: "${e}"`)}else{const e=h.some((e=>!(!e?.tool_calls||0===e.tool_calls.length)&&e.tool_calls.some((e=>{if("terminate"!==e.name)return!1;const t=e.args??e.arguments;return t&&!1===t.success}))));e&&(m.success=!1),this.debugMode&&this.log(`\nāœ… STREAMING EXECUTION COMPLETED in ${u.getStepCount()} steps`)}return t.setVariable("result",m),m}catch(e){this.log(`āŒ Streaming execution error: ${e instanceof Error?e.message:String(e)}`,"error");const r={success:!1,error:e instanceof Error?e.message:String(e)};return t.setVariable("result",r),r}}addBrowserContext(e,t){const r=t.url||"about:blank",n=t.title||"New Tab";let s="unknown";try{if(r&&"about:blank"!==r){s=new URL(r).hostname}}catch{}return`${e}\n\n## CURRENT BROWSER CONTEXT\nYou are currently on ${r} (${n})\nDomain: ${s}\n\nCurrent browser state:\n• URL: ${r}\n• Title: ${n}\n• Domain: ${s}\n\nCONTEXT GUIDANCE:\n• If the user's request seems to continue a previous task on this domain, work with the current page\n• If the request requires going to a different website, navigate there first\n• If the current page is 'about:blank' or doesn't match the task, navigation will be needed\n• Always observe the current page state before taking action\n\nPlease analyze the current context and user request, then proceed accordingly.`}log(e,t="info"){(this.debugMode||"error"===t)&&X.log(this.getAgentName(),e,t)}}const pm=M.z.enum(["navigation","observation","interaction","tab_management","control","sessions","bookmarks"]),mm=M.z.object({description:M.z.string(),input:M.z.record(M.z.unknown()),output:M.z.unknown()});M.z.object({name:M.z.string(),description:M.z.string(),category:pm,version:M.z.string().default("1.0.0"),inputSchema:M.z.instanceof(M.z.ZodType),outputSchema:M.z.instanceof(M.z.ZodType),examples:M.z.array(mm).optional(),systemPromptTemplate:M.z.string().optional(),streamingConfig:M.z.object({displayName:M.z.string().optional(),icon:M.z.string().optional(),progressMessage:M.z.string().optional()}).optional()});class fm{constructor(e,t){this.config=e,this.browserContext=t}formatDisplayResult(e){if("object"==typeof e&&null!==e){const t=e;if(!1===t.success&&t.error)return`āŒ ${t.error}`;if(!0===t.success&&t.message)return`āœ… ${t.message}`;if(t.message)return t.message}return"Completed successfully"}getConfig(){return this.config}getLangChainTool(){return bn((async e=>{try{const t=this.config.inputSchema.parse(e),r=await this.execute(t),n=this.config.outputSchema.parse(r),s={...n,_displayResult:this.formatDisplayResult(n),_toolName:this.config.name};return JSON.stringify(s)}catch(e){if(e instanceof M.z.ZodError){const t=`Validation error: ${e.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,r={success:!1,error:t,_displayResult:`āŒ ${t}`,_toolName:this.config.name};return JSON.stringify(r)}const t=e instanceof Error?e.message:String(e),r={success:!1,error:t,_displayResult:`āŒ ${t}`,_toolName:this.config.name};return JSON.stringify(r)}}),{name:this.config.name,description:this.config.description,schema:this.config.inputSchema})}getStreamingConfig(){return this.config.streamingConfig||{displayName:this.config.name,icon:"šŸ”§",progressMessage:`Running ${this.config.name}...`}}getDisplayMessage(e){return this.getStreamingConfig().progressMessage||`Running ${this.config.name}...`}getDisplayInfo(e){const t=this.getStreamingConfig();return{displayName:t.displayName||this.config.name,icon:t.icon||"šŸ”§",description:this.getDisplayMessage(e)}}}class gm{constructor(){this.tools=new Map,this.toolsByCategory=new Map}register(e){const t=e.getConfig();this.tools.set(t.name,e),this.toolsByCategory.has(t.category)||this.toolsByCategory.set(t.category,[]),this.toolsByCategory.get(t.category).push(e)}registerAll(e){e.forEach((e=>this.register(e)))}getByName(e){return this.tools.get(e)}getByCategory(e){return this.toolsByCategory.get(e)||[]}getAll(){return Array.from(this.tools.values())}getLangChainTools(){return this.getAll().map((e=>e.getLangChainTool()))}generateSystemPrompt(e){const t=(e?e.flatMap((e=>this.getByCategory(e))):this.getAll()).map((e=>{const t=e.getConfig(),r=this.zodSchemaToString(t.inputSchema),n=this.zodSchemaToString(t.outputSchema);let s=`### ${t.name}\n`;return s+=`**Category**: ${t.category}\n`,s+=`**Description**: ${t.description}\n`,s+=`**Input Schema**:\n\`\`\`json\n${r}\n\`\`\`\n`,s+=`**Output Schema**:\n\`\`\`json\n${n}\n\`\`\`\n`,t.examples&&t.examples.length>0&&(s+="**Examples**:\n",t.examples.forEach(((e,t)=>{s+=`${t+1}. ${e.description}\n`,s+=` Input: \`${JSON.stringify(e.input)}\`\n`,s+=` Output: \`${JSON.stringify(e.output)}\`\n`}))),s})).join("\n---\n\n");return`## Available Tools\n\n${t}`}zodSchemaToString(e){try{return JSON.stringify(e._def,null,2)}catch{return"Schema details available at runtime"}}validateCompatibility(e){return this.getAll().every((t=>t.getConfig().version>=e))}}M.z.object({id:M.z.number(),url:M.z.string(),title:M.z.string(),active:M.z.boolean(),windowId:M.z.number()});const ym=M.z.object({tab_id:M.z.number(),title:M.z.string(),url:M.z.string()}),bm=M.z.object({windowId:M.z.number().optional()}),wm=M.z.object({success:M.z.boolean(),tabs:M.z.array(ym),total_count:M.z.number(),message:M.z.string()});class vm extends fm{constructor(e){super({name:"list_tabs",description:"List all open browser tabs with their IDs, titles, and URLs. Returns structured JSON with tab_id, title, and url for each tab. Optionally filter by window ID.",category:"tab_management",version:"1.0.0",inputSchema:bm,outputSchema:wm,examples:[{description:"List all tabs across all windows",input:{},output:{success:!0,tabs:[{tab_id:123,title:"Google",url:"https://google.com"},{tab_id:124,title:"GitHub",url:"https://github.com"}],total_count:2,message:"Found 2 tabs across all windows"}},{description:"List tabs in a specific window",input:{windowId:1},output:{success:!0,tabs:[{tab_id:123,title:"Google",url:"https://google.com"}],total_count:1,message:"Found 1 tabs in window 1"}}],streamingConfig:{displayName:"List Tabs",icon:"šŸ“‘",progressMessage:"Retrieving browser tabs..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.windowId;return void 0!==r?`Listing tabs in window ${r}`:"Listing all browser tabs"}catch{return"Retrieving browser tabs..."}}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;const t=e.total_count;return 0===t?"šŸ“‘ No tabs found":`šŸ“‘ Found ${t} tab${1===t?"":"s"}`}async execute(e){try{const t=await this.getAllTabs(e.windowId),r=t.map((e=>({tab_id:e.id,title:e.title,url:e.url}))),n=e.windowId?`Found ${t.length} tabs in window ${e.windowId}`:`Found ${t.length} tabs across all windows`;return{success:!0,tabs:r,total_count:t.length,message:n}}catch(e){return{success:!1,tabs:[],total_count:0,message:`Error listing tabs: ${e instanceof Error?e.message:String(e)}`}}}async getAllTabs(e){const t={};void 0!==e&&(t.windowId=e);return(await chrome.tabs.query(t)).filter((e=>void 0!==e.id&&e.url&&e.title)).map((e=>({id:e.id,url:e.url,title:e.title,active:e.active||!1,windowId:e.windowId||0})))}}const _m=M.z.object({tabIds:M.z.array(M.z.number()).min(1),reason:M.z.string().optional()}),km=M.z.object({success:M.z.boolean(),closedCount:M.z.number(),closedTabs:M.z.array(M.z.object({id:M.z.number(),title:M.z.string(),url:M.z.string()})),message:M.z.string()});class Sm extends fm{constructor(e){super({name:"close_tabs",description:'Close browser tabs by their specific tab IDs. Use the tab IDs from list_tabs command. Example: {"tabIds": [123, 456]}',category:"tab_management",version:"1.0.0",inputSchema:_m,outputSchema:km,examples:[{description:"Close specific tabs by ID",input:{tabIds:[123,456]},output:{success:!0,closedCount:2,closedTabs:[{id:123,title:"Google",url:"https://google.com"},{id:456,title:"GitHub",url:"https://github.com"}],message:"Successfully closed 2 tab(s)"}},{description:"Close tabs with a reason",input:{tabIds:[789],reason:"Cleaning up old tabs"},output:{success:!0,closedCount:1,closedTabs:[{id:789,title:"Old Documentation",url:"https://docs.example.com"}],message:"Successfully closed 1 tab(s) (Cleaning up old tabs)"}}],streamingConfig:{displayName:"Close Tabs",icon:"āŒ",progressMessage:"Closing browser tabs..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.tabIds,n=t?.reason;if(r&&Array.isArray(r)){const e=r.length,t=`Closing ${e} ${1===e?"tab":"tabs"}`;return n?`${t} (${n})`:t}return"Closing browser tabs..."}catch{return"Closing browser tabs..."}}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;const t=e.closedCount;if(0===t)return"āš ļø No tabs were closed";return`āŒ Closed ${t} ${1===t?"tab":"tabs"}`}async execute(e){try{const t=(await this.getAllTabs()).filter((t=>e.tabIds.includes(t.id)));if(0===t.length)return{success:!0,closedCount:0,closedTabs:[],message:`No valid tabs found for the provided tab IDs: ${e.tabIds.join(", ")}`};await chrome.tabs.remove(e.tabIds);const r=t.map((e=>({id:e.id,title:e.title,url:e.url}))),n=e.reason?` (${e.reason})`:"",s=`Successfully closed ${r.length} tab(s)${n}`;return{success:!0,closedCount:r.length,closedTabs:r,message:s}}catch(e){return console.error("[close_tabs] Error:",e),{success:!1,closedCount:0,closedTabs:[],message:`Error closing tabs: ${e instanceof Error?e.message:String(e)}`}}}async getAllTabs(){return(await chrome.tabs.query({})).filter((e=>void 0!==e.id&&e.url&&e.title)).map((e=>({id:e.id,url:e.url,title:e.title,active:e.active||!1,windowId:e.windowId||0})))}}const Em=M.z.object({tabId:M.z.number()}),xm=M.z.object({success:M.z.boolean(),tabId:M.z.number(),title:M.z.string().optional(),url:M.z.string().optional(),message:M.z.string()});class Tm extends fm{constructor(e){super({name:"switch_tab",description:"Switch to a specific tab by its ID. Use the tab ID from list_tabs command. Updates the browser context to work with the new active tab.",category:"tab_management",version:"1.0.0",inputSchema:Em,outputSchema:xm,examples:[{description:"Switch to a specific tab",input:{tabId:123},output:{success:!0,tabId:123,title:"Google",url:"https://google.com",message:'Successfully switched to tab 123: "Google" (https://google.com)'}}],streamingConfig:{displayName:"Switch Tab",icon:"šŸ”„",progressMessage:"Switching to tab..."}},e)}formatDisplayResult(e){return e.success?e.title?`šŸ”„ Switched to "${e.title}"`:`šŸ”„ Switched to tab ${e.tabId}`:`āŒ ${e.message}`}async execute(e){try{await chrome.tabs.update(e.tabId,{active:!0});const t=await chrome.tabs.get(e.tabId);return await this.browserContext.attachToTab(e.tabId),{success:!0,tabId:e.tabId,title:t.title,url:t.url,message:`Successfully switched to tab ${e.tabId}: "${t.title}" (${t.url})`}}catch(t){return{success:!1,tabId:e.tabId,message:`Failed to switch to tab ${e.tabId}: ${t instanceof Error?t.message:String(t)}`}}}}const Cm=M.z.object({url:M.z.string().url().optional(),active:M.z.boolean().optional(),windowId:M.z.number().optional()}),Pm=M.z.object({success:M.z.boolean(),tabId:M.z.number().optional(),url:M.z.string(),active:M.z.boolean(),message:M.z.string()});class Om extends fm{constructor(e){super({name:"new_tab",description:'Create a new browser tab, optionally with a specific URL. Example: {"url": "https://google.com"} or {} for blank tab.',category:"tab_management",version:"1.0.0",inputSchema:Cm,outputSchema:Pm,examples:[{description:"Create a new tab with a specific URL",input:{url:"https://google.com"},output:{success:!0,tabId:789,url:"https://google.com",message:"Successfully created new tab with URL: https://google.com"}},{description:"Create a blank new tab",input:{},output:{success:!0,tabId:790,url:"chrome://newtab/",message:"Successfully created new blank tab"}}],streamingConfig:{displayName:"New Tab",icon:"āž•",progressMessage:"Creating new tab..."}},e)}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;if(e.url&&"chrome://newtab/"!==e.url)try{return`āœ… Created new tab: ${new URL(e.url).hostname}`}catch{return`āœ… Created new tab: ${e.url}`}return"āœ… Created new blank tab"}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.url;if(r)try{return`Creating new tab: ${new URL(r).hostname}`}catch{return`Creating new tab: ${r}`}return"Creating new blank tab"}catch{return"Creating new tab..."}}async execute(e){try{const t={active:e.active??!0};e.url&&(t.url=e.url),e.windowId&&(t.windowId=e.windowId);const r=await chrome.tabs.create(t);if(!r.id)throw new Error("Failed to create new tab");const n=e.active??!0;n&&(await new Promise((e=>setTimeout(e,1e3))),await this.browserContext.attachToTab(r.id));const s=e.url||"about:blank";return{success:!0,tabId:r.id,url:s,active:n,message:`Successfully created new tab ${r.id} with URL: ${s}${n?" (now active)":""}`}}catch(t){return{success:!1,url:e.url||"about:blank",active:e.active??!0,message:`Failed to create new tab: ${t instanceof Error?t.message:String(t)}`}}}}const Am=M.z.object({tabIds:M.z.array(M.z.number()).min(1),groupName:M.z.string().optional(),color:M.z.enum(["grey","blue","red","yellow","green","pink","purple","cyan","orange"]).optional(),windowId:M.z.number().optional()}),Im=M.z.object({success:M.z.boolean(),groupId:M.z.number().optional(),groupName:M.z.string().optional(),color:M.z.string(),tabCount:M.z.number(),message:M.z.string()});class Mm extends fm{constructor(e){super({name:"group_tabs",description:"Group browser tabs together. Takes an array of tab IDs and creates a group with optional name and color. Colors: grey, blue, red, yellow, green, pink, purple, cyan, orange.",category:"tab_management",version:"1.0.0",inputSchema:Am,outputSchema:Im,examples:[{description:"Group work-related tabs with a blue color",input:{tabIds:[123,456],groupName:"Work Research",color:"blue"},output:{success:!0,groupId:1,groupName:"Work Research",groupedCount:2,groupedTabs:[{id:123,title:"GitHub",url:"https://github.com"},{id:456,title:"Documentation",url:"https://docs.example.com"}],message:'Successfully grouped 2 tabs into "Work Research"'}}],streamingConfig:{displayName:"Group Tabs",icon:"šŸ“",progressMessage:"Organizing tabs into groups..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.tabIds,n=t?.groupName;if(r&&Array.isArray(r)){const e=r.length,t=1===e?"tab":"tabs";return n?`Grouping ${e} ${t} into "${n}"`:`Grouping ${e} ${t}`}return"Organizing tabs into groups..."}catch{return"Organizing tabs into groups..."}}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;const t=e.tabCount,r=1===t?"tab":"tabs";return e.groupName?`šŸ“ Created "${e.groupName}" group with ${t} ${r}`:`šŸ“ Grouped ${t} ${r} together`}async execute(e){try{const t=await this.getAllTabs(e.windowId),r=e.tabIds.filter((e=>t.some((t=>t.id===e))));if(0===r.length)return{success:!1,color:e.color||"blue",tabCount:0,message:`No valid tabs found for the provided tab IDs: ${e.tabIds.join(", ")}`};if(r.length!==e.tabIds.length){const t=e.tabIds.filter((e=>!r.includes(e)));console.warn(`[group_tabs] Some tab IDs were invalid and skipped: ${t.join(", ")}`)}const n={tabIds:r};e.windowId&&(n.createProperties={windowId:e.windowId});const s=await chrome.tabs.group(n),a=e.color||"blue";if(chrome.tabGroups&&chrome.tabGroups.update){const t={color:a};e.groupName&&(t.title=e.groupName),await chrome.tabGroups.update(s,t)}else console.warn("[group_tabs] chrome.tabGroups API not available, cannot set group properties");return{success:!0,groupId:s,groupName:e.groupName,color:a,tabCount:r.length,message:`Successfully created group${e.groupName?` "${e.groupName}"`:""} with ${r.length} tab(s)`}}catch(t){return console.error("[group_tabs] Error:",t),{success:!1,color:e.color||"blue",tabCount:0,message:`Error grouping tabs: ${t instanceof Error?t.message:String(t)}`}}}async getAllTabs(e){const t={};void 0!==e&&(t.windowId=e);const r=await chrome.tabs.getCurrent();r&&void 0===e&&(e=r.windowId);return(await chrome.tabs.query(t)).filter((e=>void 0!==e.id&&e.url&&e.title)).map((e=>({id:e.id,url:e.url,title:e.title,active:e.active||!1,windowId:e.windowId||0})))}}const Rm=M.z.object({url:M.z.string().url().optional(),title:M.z.string().optional(),category:M.z.string().optional(),subcategory:M.z.string().optional(),tags:M.z.array(M.z.string()).optional(),notes:M.z.string().optional()}),jm=M.z.object({success:M.z.boolean(),bookmarkId:M.z.string().optional(),title:M.z.string().optional(),url:M.z.string().optional(),folderPath:M.z.string().optional(),message:M.z.string()});class Nm extends fm{constructor(e){super({name:"save_bookmark",description:'Save a URL as a bookmark in an organized folder structure under "AI Bookmarks" on the bookmark bar.',category:"bookmarks",version:"1.0.0",inputSchema:Rm,outputSchema:jm,examples:[{description:"Save current tab with category",input:{category:"Research",subcategory:"AI Papers",tags:["machine-learning","nlp"]},output:{success:!0,bookmarkId:"bookmark_123",title:"Attention Is All You Need",url:"https://arxiv.org/abs/1706.03762",folderPath:"AI Bookmarks > Research > AI Papers",message:'Successfully saved bookmark to "AI Bookmarks > Research > AI Papers"'}},{description:"Save specific URL with custom title",input:{url:"https://example.com",title:"My Custom Title",category:"Tools"},output:{success:!0,bookmarkId:"bookmark_456",title:"My Custom Title",url:"https://example.com",folderPath:"AI Bookmarks > Tools",message:'Successfully saved bookmark to "AI Bookmarks > Tools"'}}],streamingConfig:{displayName:"Save Bookmark",icon:"šŸ”–",progressMessage:"Saving bookmark..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.category||Nm.DEFAULT_CATEGORY,n=t?.subcategory;return n?`Saving to ${r} > ${n}...`:r!==Nm.DEFAULT_CATEGORY?`Saving to ${r}...`:"Saving bookmark..."}catch{return"Saving bookmark..."}}formatDisplayResult(e){return e.success?`šŸ”– Saved to ${e.folderPath}`:`āŒ ${e.message}`}async execute(e){try{let t=e.url,r=e.title;if(!t){const e=this.browserContext.getCurrentTabId();if(!e)return{success:!1,message:"No active tab found"};const n=await chrome.tabs.get(e);if(!n||!n.url)return{success:!1,message:"No active tab found or tab has no URL"};t=n.url,r=r||n.title||"Untitled"}if(!this.isBookmarkableUrl(t))return{success:!1,message:`Cannot bookmark this URL type: ${t}`};const n=e.category||Nm.DEFAULT_CATEGORY,s=e.subcategory,a=await this.getOrCreateFolderStructure(n,s),i=await this.findExistingBookmark(t,a);if(i){r&&r!==i.title&&await chrome.bookmarks.update(i.id,{title:r});const e=await this.getFolderPath(a);return{success:!0,bookmarkId:i.id,title:r||i.title,url:t,folderPath:e,message:`Bookmark already exists in "${e}"`}}const o=await chrome.bookmarks.create({parentId:a,title:r||"Untitled",url:t});(e.tags||e.notes)&&await this.saveBookmarkMetadata(o.id,{tags:e.tags,notes:e.notes});const c=await this.getFolderPath(a);return{success:!0,bookmarkId:o.id,title:o.title,url:o.url,folderPath:c,message:`Successfully saved bookmark to "${c}"`}}catch(e){return console.error("[save_bookmark] Error:",e),{success:!1,message:`Error saving bookmark: ${e instanceof Error?e.message:String(e)}`}}}isBookmarkableUrl(e){try{const t=new URL(e);return!["chrome:","chrome-extension:","about:","data:","blob:"].includes(t.protocol)}catch{return!1}}async getOrCreateFolderStructure(e,t){const r=await this.getBookmarkBar();if(!r)throw new Error("Could not find bookmark bar");let n=await this.findChildFolder(r.id,Nm.ROOT_FOLDER_NAME);n||(n=await chrome.bookmarks.create({parentId:r.id,title:Nm.ROOT_FOLDER_NAME}));let s=await this.findChildFolder(n.id,e);if(s||(s=await chrome.bookmarks.create({parentId:n.id,title:e})),t){let e=await this.findChildFolder(s.id,t);return e||(e=await chrome.bookmarks.create({parentId:s.id,title:t})),e.id}return s.id}async getBookmarkBar(){const e=(await chrome.bookmarks.getTree())[0];for(const t of e.children||[])if("1"===t.id||"Bookmarks Bar"===t.title)return t;return null}async findChildFolder(e,t){return(await chrome.bookmarks.getChildren(e)).find((e=>!e.url&&e.title===t))||null}async findExistingBookmark(e,t){return(await chrome.bookmarks.getChildren(t)).find((t=>t.url===e))||null}async getFolderPath(e){const t=[];let r=e;for(;r;){const e=await chrome.bookmarks.get(r);if(!(e.length>0))break;{const n=e[0];if(n.title&&"Bookmarks Bar"!==n.title&&t.unshift(n.title),r=n.parentId||"","1"===r||!r)break}}return t.join(" > ")}async saveBookmarkMetadata(e,t){const r=`bookmark_meta_${e}`,n=await chrome.storage.local.get(r);await chrome.storage.local.set({[r]:{...n[r],...t,updatedAt:(new Date).toISOString()}})}}function $m(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r}function Lm(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}Nm.ROOT_FOLDER_NAME="AI Bookmarks",Nm.DEFAULT_CATEGORY="Uncategorized";let Fm=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return Fm=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(e=>(+e^r()&15>>+e/4).toString(16)))};function Dm(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const zm=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};class Um extends Error{}class Bm extends Um{constructor(e,t,r,n){super(`${Bm.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("request-id"),this.error=t}static makeMessage(e,t,r){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new Km({message:r,cause:zm(t)});const s=t;return 400===e?new Hm(e,s,r,n):401===e?new Vm(e,s,r,n):403===e?new Gm(e,s,r,n):404===e?new Jm(e,s,r,n):409===e?new Zm(e,s,r,n):422===e?new Xm(e,s,r,n):429===e?new Ym(e,s,r,n):e>=500?new Qm(e,s,r,n):new Bm(e,s,r,n)}}class qm extends Bm{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Km extends Bm{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Wm extends Km{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Hm extends Bm{}class Vm extends Bm{}class Gm extends Bm{}class Jm extends Bm{}class Zm extends Bm{}class Xm extends Bm{}class Ym extends Bm{}class Qm extends Bm{}const ef=/^[a-z][a-z0-9+.-]*:/i;function tf(e){return"object"!=typeof e?{}:e??{}}const rf=e=>{try{return JSON.parse(e)}catch(e){return}},nf={off:0,error:200,warn:300,info:400,debug:500},sf=(e,t,r)=>{if(e)return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(nf,e)?e:void uf(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(nf))}`)};function af(){}function of(e,t,r){return!t||nf[e]>nf[r]?af:t[e].bind(t)}const cf={error:af,warn:af,info:af,debug:af};let lf=new WeakMap;function uf(e){const t=e.logger,r=e.logLevel??"off";if(!t)return cf;const n=lf.get(t);if(n&&n[0]===r)return n[1];const s={error:of("error",t,r),warn:of("warn",t,r),info:of("info",t,r),debug:of("debug",t,r)};return lf.set(t,[r,s]),s}const df=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map((([e,t])=>[e,"x-api-key"===e.toLowerCase()||"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t])))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),hf="0.50.4";const pf=()=>{const e="undefined"!=typeof Deno&&null!=Deno.build?"deno":"undefined"!=typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":hf,"X-Stainless-OS":ff(Deno.build.os),"X-Stainless-Arch":mf(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":hf,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if("node"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":hf,"X-Stainless-OS":ff(globalThis.process.platform),"X-Stainless-Arch":mf(globalThis.process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version};const t=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{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:t,pattern:r}of e){const e=r.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":hf,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":hf,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const mf=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",ff=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let gf;function yf(...e){const t=globalThis.ReadableStream;if(void 0===t)throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function bf(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return yf({start(){},async pull(e){const{done:r,value:n}=await t.next();r?e.close():e.enqueue(n)},async cancel(){await(t.return?.())}})}function wf(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}const vf=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});let _f,kf;function Sf(e){let t;return(_f??(t=new globalThis.TextEncoder,_f=t.encode.bind(t)))(e)}function Ef(e){let t;return(kf??(t=new globalThis.TextDecoder,kf=t.decode.bind(t)))(e)}var xf,Tf,Cf,Pf;class Of{constructor(){xf.set(this,void 0),Tf.set(this,void 0),$m(this,xf,new Uint8Array,"f"),$m(this,Tf,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?Sf(e):e;$m(this,xf,function(e){let t=0;for(const r of e)t+=r.length;const r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}([Lm(this,xf,"f"),t]),"f");const r=[];let n;for(;null!=(n=Af(Lm(this,xf,"f"),Lm(this,Tf,"f")));){if(n.carriage&&null==Lm(this,Tf,"f")){$m(this,Tf,n.index,"f");continue}if(null!=Lm(this,Tf,"f")&&(n.index!==Lm(this,Tf,"f")+1||n.carriage)){r.push(Ef(Lm(this,xf,"f").subarray(0,Lm(this,Tf,"f")-1))),$m(this,xf,Lm(this,xf,"f").subarray(Lm(this,Tf,"f")),"f"),$m(this,Tf,null,"f");continue}const e=null!==Lm(this,Tf,"f")?n.preceding-1:n.preceding,t=Ef(Lm(this,xf,"f").subarray(0,e));r.push(t),$m(this,xf,Lm(this,xf,"f").subarray(n.index),"f"),$m(this,Tf,null,"f")}return r}flush(){return Lm(this,xf,"f").length?this.decode("\n"):[]}}function Af(e,t){for(let r=t??0;r0&&(yield t)}(s))for(const t of n.decode(e)){const e=r.decode(t);e&&(yield e)}for(const e of n.flush()){const t=r.decode(e);t&&(yield t)}}(e,t)){if("completion"===r.event)try{yield JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if("message_start"===r.event||"message_delta"===r.event||"message_stop"===r.event||"content_block_start"===r.event||"content_block_delta"===r.event||"content_block_stop"===r.event)try{yield JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if("ping"!==r.event&&"error"===r.event)throw new Bm(void 0,rf(r.data)??r.data,void 0,e.headers)}n=!0}catch(e){if(Dm(e))return;throw e}finally{n||t.abort()}}),t)}static fromReadableStream(e,t){let r=!1;return new Mf((async function*(){if(r)throw new Um("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let n=!1;try{for await(const t of async function*(){const t=new Of,r=wf(e);for await(const e of r)for(const r of t.decode(e))yield r;for(const e of t.flush())yield e}())n||t&&(yield JSON.parse(t));n=!0}catch(e){if(Dm(e))return;throw e}finally{n||t.abort()}}),t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],r=this.iterator(),n=n=>({next:()=>{if(0===n.length){const n=r.next();e.push(n),t.push(n)}return n.shift()}});return[new Mf((()=>n(e)),this.controller),new Mf((()=>n(t)),this.controller)]}toReadableStream(){const e=this;let t;return yf({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:r,done:n}=await t.next();if(n)return e.close();const s=Sf(JSON.stringify(r)+"\n");e.enqueue(s)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class Rf{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 e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=function(e,t){const r=e.indexOf(t);if(-1!==r)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}async function jf(e,t){const{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:a}=t,i=await(async()=>{if(t.options.stream)return uf(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(r,t.controller):Mf.fromSSEResponse(r,t.controller);if(204===r.status)return null;if(t.options.__binaryResponse)return r;const n=r.headers.get("content-type"),s=n?.split(";")[0]?.trim();if(s?.includes("application/json")||s?.endsWith("+json")){return Nf(await r.json(),r)}return await r.text()})();return uf(e).debug(`[${n}] response parsed`,df({retryOfRequestLogID:s,url:r.url,status:r.status,body:i,durationMs:Date.now()-a})),i}function Nf(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("request-id"),enumerable:!1})}class $f extends Promise{constructor(e,t,r=jf){super((e=>{e(null)})),this.responsePromise=t,this.parseResponse=r,Cf.set(this,void 0),$m(this,Cf,e,"f")}_thenUnwrap(e){return new $f(Lm(this,Cf,"f"),this.responsePromise,(async(t,r)=>Nf(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("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then((e=>this.parseResponse(Lm(this,Cf,"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)}}Cf=new WeakMap;class Lf{constructor(e,t,r,n){Pf.set(this,void 0),$m(this,Pf,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new Um("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Lm(this,Pf,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Pf=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Ff extends $f{constructor(e,t,r){super(e,t,(async(e,t)=>new r(e,t.response,await jf(e,t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}class Df extends Lf{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){const e=this.first_id;return e?{...this.options,query:{...tf(this.options.query),before_id:e}}:null}const e=this.last_id;return e?{...this.options,query:{...tf(this.options.query),after_id:e}}:null}}const zf=()=>{if("undefined"==typeof File){const{process:e}=globalThis,t="string"==typeof e?.versions?.node&&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 Uf(e,t,r){return zf(),new File(e,t??"unknown_file",r)}function Bf(e){return("object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}const qf=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator];new WeakMap;const Kf=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function Wf(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Kf(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!qf(e)){const t=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";const t=Object.getOwnPropertyNames(e);return`; props: [${t.map((e=>`"${e}"`)).join(", ")}]`}(e)}`)}for await(const r of e)t.push(...await Wf(r))}return t}class Hf{constructor(e){this._client=e}}const Vf=Symbol.for("brand.privateNullableHeaders"),Gf=Array.isArray;function*Jf(e){if(!e)return;if(Vf in e){const{values:t,nulls:r}=e;yield*t.entries();for(const e of r)yield[e,null];return}let t,r=!1;e instanceof Headers?t=e.entries():Gf(e)?t=e:(r=!0,t=Object.entries(e??{}));for(let e of t){const t=e[0];if("string"!=typeof t)throw new TypeError("expected header name to be a string");const n=Gf(e[1])?e[1]:[e[1]];let s=!1;for(const e of n)void 0!==e&&(r&&!s&&(s=!0,yield[t,null]),yield[t,e])}}const Zf=e=>{const t=new Headers,r=new Set;for(const n of e){const e=new Set;for(const[s,a]of Jf(n)){const n=s.toLowerCase();e.has(n)||(t.delete(s),e.add(n)),null===a?(t.delete(s),r.add(n)):(t.append(s,a),r.delete(n))}}return{[Vf]:!0,values:t,nulls:r}};function Xf(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Yf=((e=Xf)=>function(t,...r){if(1===t.length)return t[0];let n=!1;const s=t.reduce(((t,s,a)=>(/[?#]/.test(s)&&(n=!0),t+s+(a===r.length?"":(n?encodeURIComponent:e)(String(r[a]))))),""),a=s.split(/[?#]/,1)[0],i=[],o=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let c;for(;null!==(c=o.exec(a));)i.push({start:c.index,length:c[0].length});if(i.length>0){let e=0;const t=i.reduce(((t,r)=>{const n=" ".repeat(r.start-e),s="^".repeat(r.length);return e=r.start+r.length,t+n+s}),"");throw new Um(`Path parameters result in path with invalid segments:\n${s}\n${t}`)}return s})(Xf);class Qf extends Hf{retrieve(e,t={},r){const{betas:n}=t??{};return this._client.get(Yf`/v1/models/${e}?beta=true`,{...r,headers:Zf([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}list(e={},t){const{betas:r,...n}=e??{};return this._client.getAPIList("/v1/models?beta=true",Df,{query:n,...t,headers:Zf([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}}class eg{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new Of;for await(const t of this.iterator)for(const r of e.decode(t))yield JSON.parse(r);for(const t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new Um("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new Um("Attempted to iterate over a response with no body")}return new eg(wf(e.body),t)}}class tg extends Hf{create(e,t){const{betas:r,...n}=e;return this._client.post("/v1/messages/batches?beta=true",{body:n,...t,headers:Zf([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},r){const{betas:n}=t??{};return this._client.get(Yf`/v1/messages/batches/${e}?beta=true`,{...r,headers:Zf([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}list(e={},t){const{betas:r,...n}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",Df,{query:n,...t,headers:Zf([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},r){const{betas:n}=t??{};return this._client.delete(Yf`/v1/messages/batches/${e}?beta=true`,{...r,headers:Zf([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}cancel(e,t={},r){const{betas:n}=t??{};return this._client.post(Yf`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:Zf([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}async results(e,t={},r){const n=await this.retrieve(e);if(!n.results_url)throw new Um(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);const{betas:s}=t??{};return this._client.get(n.results_url,{...r,headers:Zf([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},r?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap(((e,t)=>eg.fromResponse(t.response,t.controller)))}}const rg=e=>{if(0===e.length)return e;let t=e[e.length-1];switch(t.type){case"separator":return e=e.slice(0,e.length-1),rg(e);case"number":let r=t.value[t.value.length-1];if("."===r||"-"===r)return e=e.slice(0,e.length-1),rg(e);case"string":let n=e[e.length-2];if("delimiter"===n?.type)return e=e.slice(0,e.length-1),rg(e);if("brace"===n?.type&&"{"===n.value)return e=e.slice(0,e.length-1),rg(e);break;case"delimiter":return e=e.slice(0,e.length-1),rg(e)}return e},ng=e=>JSON.parse((e=>{let t="";return e.map((e=>{"string"===e.type?t+='"'+e.value+'"':t+=e.value})),t})((e=>{let t=[];return e.map((e=>{"brace"===e.type&&("{"===e.value?t.push("}"):t.splice(t.lastIndexOf("}"),1)),"paren"===e.type&&("["===e.value?t.push("]"):t.splice(t.lastIndexOf("]"),1))})),t.length>0&&t.reverse().map((t=>{"}"===t?e.push({type:"brace",value:"}"}):"]"===t&&e.push({type:"paren",value:"]"})})),e})(rg((e=>{let t=0,r=[];for(;t{})),cg.set(this,(()=>{})),lg.set(this,void 0),ug.set(this,(()=>{})),dg.set(this,(()=>{})),hg.set(this,{}),pg.set(this,!1),mg.set(this,!1),fg.set(this,!1),gg.set(this,!1),yg.set(this,void 0),bg.set(this,void 0),_g.set(this,(e=>{if($m(this,mg,!0,"f"),Dm(e)&&(e=new qm),e instanceof qm)return $m(this,fg,!0,"f"),this._emit("abort",e);if(e instanceof Um)return this._emit("error",e);if(e instanceof Error){const t=new Um(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Um(String(e)))})),$m(this,ig,new Promise(((e,t)=>{$m(this,og,e,"f"),$m(this,cg,t,"f")})),"f"),$m(this,lg,new Promise(((e,t)=>{$m(this,ug,e,"f"),$m(this,dg,t,"f")})),"f"),Lm(this,ig,"f").catch((()=>{})),Lm(this,lg,"f").catch((()=>{}))}get response(){return Lm(this,yg,"f")}get request_id(){return Lm(this,bg,"f")}async withResponse(){const e=await Lm(this,ig,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new Cg;return t._run((()=>t._fromReadableStream(e))),t}static createMessage(e,t,r){const n=new Cg;for(const e of t.messages)n._addMessageParam(e);return n._run((()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}_run(e){e().then((()=>{this._emitFinal(),this._emit("end")}),Lm(this,_g,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),Lm(this,sg,"m",kg).call(this);const{response:s,data:a}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(s);for await(const e of a)Lm(this,sg,"m",Sg).call(this,e);if(a.controller.signal?.aborted)throw new qm;Lm(this,sg,"m",Eg).call(this)}_connected(e){this.ended||($m(this,yg,e,"f"),$m(this,bg,e?.headers.get("request-id"),"f"),Lm(this,og,"f").call(this,e),this._emit("connect"))}get ended(){return Lm(this,pg,"f")}get errored(){return Lm(this,mg,"f")}get aborted(){return Lm(this,fg,"f")}abort(){this.controller.abort()}on(e,t){return(Lm(this,hg,"f")[e]||(Lm(this,hg,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=Lm(this,hg,"f")[e];if(!r)return this;const n=r.findIndex((e=>e.listener===t));return n>=0&&r.splice(n,1),this}once(e,t){return(Lm(this,hg,"f")[e]||(Lm(this,hg,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,r)=>{$m(this,gg,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)}))}async done(){$m(this,gg,!0,"f"),await Lm(this,lg,"f")}get currentMessage(){return Lm(this,ag,"f")}async finalMessage(){return await this.done(),Lm(this,sg,"m",wg).call(this)}async finalText(){return await this.done(),Lm(this,sg,"m",vg).call(this)}_emit(e,...t){if(Lm(this,pg,"f"))return;"end"===e&&($m(this,pg,!0,"f"),Lm(this,ug,"f").call(this));const r=Lm(this,hg,"f")[e];if(r&&(Lm(this,hg,"f")[e]=r.filter((e=>!e.once)),r.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return Lm(this,gg,"f")||r?.length||Promise.reject(e),Lm(this,cg,"f").call(this,e),Lm(this,dg,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];Lm(this,gg,"f")||r?.length||Promise.reject(e),Lm(this,cg,"f").call(this,e),Lm(this,dg,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",Lm(this,sg,"m",wg).call(this))}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),Lm(this,sg,"m",kg).call(this),this._connected(null);const n=Mf.fromReadableStream(e,this.controller);for await(const e of n)Lm(this,sg,"m",Sg).call(this,e);if(n.controller.signal?.aborted)throw new qm;Lm(this,sg,"m",Eg).call(this)}[(ag=new WeakMap,ig=new WeakMap,og=new WeakMap,cg=new WeakMap,lg=new WeakMap,ug=new WeakMap,dg=new WeakMap,hg=new WeakMap,pg=new WeakMap,mg=new WeakMap,fg=new WeakMap,gg=new WeakMap,yg=new WeakMap,bg=new WeakMap,_g=new WeakMap,sg=new WeakSet,wg=function(){if(0===this.receivedMessages.length)throw new Um("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},vg=function(){if(0===this.receivedMessages.length)throw new Um("stream ended without producing a Message with role=assistant");const e=this.receivedMessages.at(-1).content.filter((e=>"text"===e.type)).map((e=>e.text));if(0===e.length)throw new Um("stream ended without producing a content block with type=text");return e.join(" ")},kg=function(){this.ended||$m(this,ag,void 0,"f")},Sg=function(e){if(this.ended)return;const t=Lm(this,sg,"m",xg).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{const r=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===r.type&&this._emit("text",e.delta.text,r.text||"");break;case"citations_delta":"text"===r.type&&this._emit("citation",e.delta.citation,r.citations??[]);break;case"input_json_delta":"tool_use"===r.type&&r.input&&this._emit("inputJson",e.delta.partial_json,r.input);break;case"thinking_delta":"thinking"===r.type&&this._emit("thinking",e.delta.thinking,r.thinking);break;case"signature_delta":"thinking"===r.type&&this._emit("signature",r.signature);break;default:e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(t,!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":$m(this,ag,t,"f")}},Eg=function(){if(this.ended)throw new Um("stream has ended, this shouldn't happen");const e=Lm(this,ag,"f");if(!e)throw new Um("request ended without sending any chunks");return $m(this,ag,void 0,"f"),e},xg=function(e){let t=Lm(this,ag,"f");if("message_start"===e.type){if(t)throw new Um(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new Um(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,null!=e.usage.input_tokens&&(t.usage.input_tokens=e.usage.input_tokens),null!=e.usage.cache_creation_input_tokens&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),null!=e.usage.cache_read_input_tokens&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),null!=e.usage.server_tool_use&&(t.usage.server_tool_use=e.usage.server_tool_use),t;case"content_block_start":return t.content.push(e.content_block),t;case"content_block_delta":{const r=t.content.at(e.index);switch(e.delta.type){case"text_delta":"text"===r?.type&&(r.text+=e.delta.text);break;case"citations_delta":"text"===r?.type&&(r.citations??(r.citations=[]),r.citations.push(e.delta.citation));break;case"input_json_delta":if("tool_use"===r?.type){let t=r[Tg]||"";t+=e.delta.partial_json,Object.defineProperty(r,Tg,{value:t,enumerable:!1,writable:!0}),t&&(r.input=ng(t))}break;case"thinking_delta":"thinking"===r?.type&&(r.thinking+=e.delta.thinking);break;case"signature_delta":"thinking"===r?.type&&(r.signature=e.delta.signature);break;default:e.delta}return t}}},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("streamEvent",(r=>{const n=t.shift();n?n.resolve(r):e.push(r)})),this.on("end",(()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),this.on("error",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise(((e,r)=>t.push({resolve:e,reject:r}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Mf(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}const Pg={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};class Og extends Hf{constructor(){super(...arguments),this.batches=new tg(this._client)}create(e,t){const{betas:r,...n}=e;return n.model in Pg&&console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${Pg[n.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:n,timeout:this._client._options.timeout??(n.stream?6e5:this._client._calculateNonstreamingTimeout(n.max_tokens)),...t,headers:Zf([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}stream(e,t){return Cg.createMessage(this,e,t)}countTokens(e,t){const{betas:r,...n}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:n,...t,headers:Zf([{"anthropic-beta":[...r??[],"token-counting-2024-11-01"].toString()},t?.headers])})}}Og.Batches=tg;class Ag extends Hf{constructor(){super(...arguments),this.models=new Qf(this._client),this.messages=new Og(this._client)}}Ag.Models=Qf,Ag.Messages=Og;class Ig extends Hf{create(e,t){const{betas:r,...n}=e;return this._client.post("/v1/complete",{body:n,timeout:this._client._options.timeout??6e5,...t,headers:Zf([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}}class Mg extends Hf{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(Yf`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",Df,{query:e,...t})}delete(e,t){return this._client.delete(Yf`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(Yf`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){const r=await this.retrieve(e);if(!r.results_url)throw new Um(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...t,headers:Zf([{Accept:"application/binary"},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap(((e,t)=>eg.fromResponse(t.response,t.controller)))}}var Rg,jg,Ng,$g,Lg,Fg,Dg,zg,Ug,Bg,qg,Kg,Wg,Hg,Vg,Gg,Jg,Zg,Xg,Yg,Qg,ey;const ty="__json_buf";class ry{constructor(){Rg.add(this),this.messages=[],this.receivedMessages=[],jg.set(this,void 0),this.controller=new AbortController,Ng.set(this,void 0),$g.set(this,(()=>{})),Lg.set(this,(()=>{})),Fg.set(this,void 0),Dg.set(this,(()=>{})),zg.set(this,(()=>{})),Ug.set(this,{}),Bg.set(this,!1),qg.set(this,!1),Kg.set(this,!1),Wg.set(this,!1),Hg.set(this,void 0),Vg.set(this,void 0),Zg.set(this,(e=>{if($m(this,qg,!0,"f"),Dm(e)&&(e=new qm),e instanceof qm)return $m(this,Kg,!0,"f"),this._emit("abort",e);if(e instanceof Um)return this._emit("error",e);if(e instanceof Error){const t=new Um(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Um(String(e)))})),$m(this,Ng,new Promise(((e,t)=>{$m(this,$g,e,"f"),$m(this,Lg,t,"f")})),"f"),$m(this,Fg,new Promise(((e,t)=>{$m(this,Dg,e,"f"),$m(this,zg,t,"f")})),"f"),Lm(this,Ng,"f").catch((()=>{})),Lm(this,Fg,"f").catch((()=>{}))}get response(){return Lm(this,Hg,"f")}get request_id(){return Lm(this,Vg,"f")}async withResponse(){const e=await Lm(this,Ng,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new ry;return t._run((()=>t._fromReadableStream(e))),t}static createMessage(e,t,r){const n=new ry;for(const e of t.messages)n._addMessageParam(e);return n._run((()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}_run(e){e().then((()=>{this._emitFinal(),this._emit("end")}),Lm(this,Zg,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),Lm(this,Rg,"m",Xg).call(this);const{response:s,data:a}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(s);for await(const e of a)Lm(this,Rg,"m",Yg).call(this,e);if(a.controller.signal?.aborted)throw new qm;Lm(this,Rg,"m",Qg).call(this)}_connected(e){this.ended||($m(this,Hg,e,"f"),$m(this,Vg,e?.headers.get("request-id"),"f"),Lm(this,$g,"f").call(this,e),this._emit("connect"))}get ended(){return Lm(this,Bg,"f")}get errored(){return Lm(this,qg,"f")}get aborted(){return Lm(this,Kg,"f")}abort(){this.controller.abort()}on(e,t){return(Lm(this,Ug,"f")[e]||(Lm(this,Ug,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=Lm(this,Ug,"f")[e];if(!r)return this;const n=r.findIndex((e=>e.listener===t));return n>=0&&r.splice(n,1),this}once(e,t){return(Lm(this,Ug,"f")[e]||(Lm(this,Ug,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,r)=>{$m(this,Wg,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)}))}async done(){$m(this,Wg,!0,"f"),await Lm(this,Fg,"f")}get currentMessage(){return Lm(this,jg,"f")}async finalMessage(){return await this.done(),Lm(this,Rg,"m",Gg).call(this)}async finalText(){return await this.done(),Lm(this,Rg,"m",Jg).call(this)}_emit(e,...t){if(Lm(this,Bg,"f"))return;"end"===e&&($m(this,Bg,!0,"f"),Lm(this,Dg,"f").call(this));const r=Lm(this,Ug,"f")[e];if(r&&(Lm(this,Ug,"f")[e]=r.filter((e=>!e.once)),r.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return Lm(this,Wg,"f")||r?.length||Promise.reject(e),Lm(this,Lg,"f").call(this,e),Lm(this,zg,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];Lm(this,Wg,"f")||r?.length||Promise.reject(e),Lm(this,Lg,"f").call(this,e),Lm(this,zg,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",Lm(this,Rg,"m",Gg).call(this))}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),Lm(this,Rg,"m",Xg).call(this),this._connected(null);const n=Mf.fromReadableStream(e,this.controller);for await(const e of n)Lm(this,Rg,"m",Yg).call(this,e);if(n.controller.signal?.aborted)throw new qm;Lm(this,Rg,"m",Qg).call(this)}[(jg=new WeakMap,Ng=new WeakMap,$g=new WeakMap,Lg=new WeakMap,Fg=new WeakMap,Dg=new WeakMap,zg=new WeakMap,Ug=new WeakMap,Bg=new WeakMap,qg=new WeakMap,Kg=new WeakMap,Wg=new WeakMap,Hg=new WeakMap,Vg=new WeakMap,Zg=new WeakMap,Rg=new WeakSet,Gg=function(){if(0===this.receivedMessages.length)throw new Um("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Jg=function(){if(0===this.receivedMessages.length)throw new Um("stream ended without producing a Message with role=assistant");const e=this.receivedMessages.at(-1).content.filter((e=>"text"===e.type)).map((e=>e.text));if(0===e.length)throw new Um("stream ended without producing a content block with type=text");return e.join(" ")},Xg=function(){this.ended||$m(this,jg,void 0,"f")},Yg=function(e){if(this.ended)return;const t=Lm(this,Rg,"m",ey).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{const r=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===r.type&&this._emit("text",e.delta.text,r.text||"");break;case"citations_delta":"text"===r.type&&this._emit("citation",e.delta.citation,r.citations??[]);break;case"input_json_delta":"tool_use"===r.type&&r.input&&this._emit("inputJson",e.delta.partial_json,r.input);break;case"thinking_delta":"thinking"===r.type&&this._emit("thinking",e.delta.thinking,r.thinking);break;case"signature_delta":"thinking"===r.type&&this._emit("signature",r.signature);break;default:e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(t,!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":$m(this,jg,t,"f")}},Qg=function(){if(this.ended)throw new Um("stream has ended, this shouldn't happen");const e=Lm(this,jg,"f");if(!e)throw new Um("request ended without sending any chunks");return $m(this,jg,void 0,"f"),e},ey=function(e){let t=Lm(this,jg,"f");if("message_start"===e.type){if(t)throw new Um(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new Um(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,null!=e.usage.input_tokens&&(t.usage.input_tokens=e.usage.input_tokens),null!=e.usage.cache_creation_input_tokens&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),null!=e.usage.cache_read_input_tokens&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),null!=e.usage.server_tool_use&&(t.usage.server_tool_use=e.usage.server_tool_use),t;case"content_block_start":return t.content.push(e.content_block),t;case"content_block_delta":{const r=t.content.at(e.index);switch(e.delta.type){case"text_delta":"text"===r?.type&&(r.text+=e.delta.text);break;case"citations_delta":"text"===r?.type&&(r.citations??(r.citations=[]),r.citations.push(e.delta.citation));break;case"input_json_delta":if("tool_use"===r?.type){let t=r[ty]||"";t+=e.delta.partial_json,Object.defineProperty(r,ty,{value:t,enumerable:!1,writable:!0}),t&&(r.input=ng(t))}break;case"thinking_delta":"thinking"===r?.type&&(r.thinking+=e.delta.thinking);break;case"signature_delta":"thinking"===r?.type&&(r.signature=e.delta.signature);break;default:e.delta}return t}}},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("streamEvent",(r=>{const n=t.shift();n?n.resolve(r):e.push(r)})),this.on("end",(()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),this.on("error",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise(((e,r)=>t.push({resolve:e,reject:r}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Mf(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class ny extends Hf{constructor(){super(...arguments),this.batches=new Mg(this._client)}create(e,t){return e.model in sy&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${sy[e.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??(e.stream?6e5:this._client._calculateNonstreamingTimeout(e.max_tokens)),...t,stream:e.stream??!1})}stream(e,t){return ry.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}const sy={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};ny.Batches=Mg;class ay extends Hf{retrieve(e,t={},r){const{betas:n}=t??{};return this._client.get(Yf`/v1/models/${e}`,{...r,headers:Zf([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}list(e={},t){const{betas:r,...n}=e??{};return this._client.getAPIList("/v1/models",Df,{query:n,...t,headers:Zf([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}}const iy=e=>void 0!==globalThis.process?globalThis.process.env?.[e]?.trim()??void 0:void 0!==globalThis.Deno?globalThis.Deno.env?.get?.(e)?.trim():void 0;var oy,cy;class ly{constructor({baseURL:e=iy("ANTHROPIC_BASE_URL"),apiKey:t=iy("ANTHROPIC_API_KEY")??null,authToken:r=iy("ANTHROPIC_AUTH_TOKEN")??null,...n}={}){cy.set(this,void 0);const s={apiKey:t,authToken:r,...n,baseURL:e||"https://api.anthropic.com"};if(!s.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new Um("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");this.baseURL=s.baseURL,this.timeout=s.timeout??uy.DEFAULT_TIMEOUT,this.logger=s.logger??console;const a="warn";this.logLevel=a,this.logLevel=sf(s.logLevel,"ClientOptions.logLevel",this)??sf(iy("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??a,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??function(){if("undefined"!=typeof fetch)return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),$m(this,cy,vf,"f"),this._options=s,this.apiKey=t,this.authToken=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(this.apiKey&&e.get("x-api-key")||t.has("x-api-key")||this.authToken&&e.get("authorization")||t.has("authorization")))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders(e){return Zf([this.apiKeyAuth(e),this.bearerAuth(e)])}apiKeyAuth(e){if(null!=this.apiKey)return Zf([{"X-Api-Key":this.apiKey}])}bearerAuth(e){if(null!=this.authToken)return Zf([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new Um(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)})).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${hf}`}defaultIdempotencyKey(){return`stainless-node-retry-${Fm()}`}makeStatusError(e,t,r,n){return Bm.generate(e,t,r,n)}buildURL(e,t){const r=(e=>ef.test(e))(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return function(e){if(!e)return!0;for(const t in e)return!1;return!0}(n)||(t={...n,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new Um("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");return 6e5}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((r=>({method:e,path:t,...r}))))}request(e,t=null){return new $f(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){const n=await e,s=n.maxRetries??this.maxRetries;null==t&&(t=s),await this.prepareOptions(n);const{req:a,url:i,timeout:o}=this.buildRequest(n,{retryCount:s-t});await this.prepareRequest(a,{url:i,options:n});const c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=void 0===r?"":`, retryOf: ${r}`,u=Date.now();if(uf(this).debug(`[${c}] sending request`,df({retryOfRequestLogID:r,method:n.method,url:i,options:n,headers:a.headers})),n.signal?.aborted)throw new qm;const d=new AbortController,h=await this.fetchWithTimeout(i,a,o,d).catch(zm),p=Date.now();if(h instanceof Error){const e=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new qm;const s=Dm(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return uf(this).info(`[${c}] connection ${s?"timed out":"failed"} - ${e}`),uf(this).debug(`[${c}] connection ${s?"timed out":"failed"} (${e})`,df({retryOfRequestLogID:r,url:i,durationMs:p-u,message:h.message})),this.retryRequest(n,t,r??c);if(uf(this).info(`[${c}] connection ${s?"timed out":"failed"} - error; no more retries left`),uf(this).debug(`[${c}] connection ${s?"timed out":"failed"} (error; no more retries left)`,df({retryOfRequestLogID:r,url:i,durationMs:p-u,message:h.message})),s)throw new Wm;throw new Km({cause:h})}const m=[...h.headers.entries()].filter((([e])=>"request-id"===e)).map((([e,t])=>", "+e+": "+JSON.stringify(t))).join(""),f=`[${c}${l}${m}] ${a.method} ${i} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${p-u}ms`;if(!h.ok){const e=this.shouldRetry(h);if(t&&e){const e=`retrying, ${t} attempts remaining`;return await async function(e){if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void await(e[Symbol.asyncIterator]().return?.());const t=e.getReader(),r=t.cancel();t.releaseLock(),await r}(h.body),uf(this).info(`${f} - ${e}`),uf(this).debug(`[${c}] response error (${e})`,df({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),this.retryRequest(n,t,r??c,h.headers)}const s=e?"error; no more retries left":"error; not retryable";uf(this).info(`${f} - ${s}`);const a=await h.text().catch((e=>zm(e).message)),i=rf(a),o=i?void 0:a;uf(this).debug(`[${c}] response error (${s})`,df({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,message:o,durationMs:Date.now()-u}));throw this.makeStatusError(h.status,i,o,h.headers)}return uf(this).info(f),uf(this).debug(`[${c}] response start`,df({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),{response:h,options:n,controller:d,requestLogID:c,retryOfRequestLogID:r,startTime:u}}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,n){const{signal:s,method:a,...i}=t||{};s&&s.addEventListener("abort",(()=>n.abort()));const o=setTimeout((()=>n.abort()),r),c=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||"object"==typeof i.body&&null!==i.body&&Symbol.asyncIterator in i.body,l={signal:n.signal,...c?{duplex:"half"}:{},method:"GET",...i};a&&(l.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(o)}}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,r,n){let s;const a=n?.get("retry-after-ms");if(a){const e=parseFloat(a);Number.isNaN(e)||(s=e)}const i=n?.get("retry-after");if(i&&!s){const e=parseFloat(i);s=Number.isNaN(e)?Date.parse(i)-Date.now():1e3*e}if(!(s&&0<=s&&s<6e4)){const r=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,r)}var o;return await(o=s,new Promise((e=>setTimeout(e,o)))),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){const r=t-e;return Math.min(.5*Math.pow(2,r),8)*(1-.25*Math.random())*1e3}buildRequest(e,{retryCount:t=0}={}){const r={...e},{method:n,path:s,query:a}=r,i=this.buildURL(s,a);"timeout"in r&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new Um(`${e} must be an integer`);if(t<0)throw new Um(`${e} must be a positive integer`)})("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:o,body:c}=this.buildBody({options:r});return{req:{method:n,headers:this.buildHeaders({options:e,method:n,bodyHeaders:o,retryCount:t}),...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&c instanceof globalThis.ReadableStream&&{duplex:"half"},...c&&{body:c},...this.fetchOptions??{},...r.fetchOptions??{}},url:i,timeout:r.timeout}}buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let s={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);const a=Zf([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...gf??(gf=pf()),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=Zf([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&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}:"object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)?{bodyHeaders:void 0,body:bf(e)}:Lm(this,cy,"f").call(this,{body:e,headers:r})}}oy=ly,cy=new WeakMap,ly.Anthropic=oy,ly.HUMAN_PROMPT="\n\nHuman:",ly.AI_PROMPT="\n\nAssistant:",ly.DEFAULT_TIMEOUT=6e5,ly.AnthropicError=Um,ly.APIError=Bm,ly.APIConnectionError=Km,ly.APIConnectionTimeoutError=Wm,ly.APIUserAbortError=qm,ly.NotFoundError=Jm,ly.ConflictError=Zm,ly.RateLimitError=Ym,ly.BadRequestError=Hm,ly.AuthenticationError=Vm,ly.InternalServerError=Qm,ly.PermissionDeniedError=Gm,ly.UnprocessableEntityError=Xm,ly.toFile=async function(e,t,r){if(zf(),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&Kf(e))(e=await e))return e instanceof File?e:Uf([await e.arrayBuffer()],e.name);if((e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob)(e)){const n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Uf(await Wf(n),t,r)}const n=await Wf(e);if(t||(t=Bf(e)),!r?.type){const e=n.find((e=>"object"==typeof e&&"type"in e&&e.type));"string"==typeof e&&(r={...r,type:e})}return Uf(n,t,r)};class uy extends ly{constructor(){super(...arguments),this.completions=new Ig(this),this.messages=new ny(this),this.models=new ay(this),this.beta=new Ag(this)}}uy.Completions=Ig,uy.Messages=ny,uy.Models=ay,uy.Beta=Ag;const{HUMAN_PROMPT:dy,AI_PROMPT:hy}=uy;M.z.object({llm:M.z.literal("claude"),apiKey:M.z.string(),modelName:M.z.string().optional(),baseURL:M.z.string().default("http://llm.nxtscape.ai"),options:M.z.record(M.z.unknown()).optional()});class py{constructor(e,t,r){if(this.defaultModel="claude-3-7-sonnet",this.defaultBaseURL="http://llm.nxtscape.ai",t&&(this.defaultModel=t),"string"==typeof e)this.client=new uy({apiKey:e,baseURL:this.defaultBaseURL,dangerouslyAllowBrowser:!0,...r});else if(e.messages&&e.completions)this.client=e;else{const t=e;t.dangerouslyAllowBrowser=!0,t.baseURL||(t.baseURL=this.defaultBaseURL),this.client=new uy(t)}}processResponse(e){const t=e.content.filter((e=>"tool_use"===e.type)).map((e=>({id:e.id,name:e.name,input:e.input})));return{textContent:e.content.filter((e=>"text"===e.type)).map((e=>e.text)).join("\n")||null,content:e.content,toolCalls:t,stop_reason:e.stop_reason}}async generateText(e,t){const r=this.extractSystemMessage(e),n=t.toolChoice,s=await this.client.messages.create({system:r,model:t.model||this.defaultModel,max_tokens:t.maxTokens||1024,temperature:t.temperature,messages:this.convertToAnthropicMessages(e),tools:t.tools,tool_choice:n});return this.processResponse(s)}async generateStream(e,t,r){const n=this.extractSystemMessage(e),s=t.toolChoice,a=await this.client.messages.stream({system:n,model:t.model||this.defaultModel,max_tokens:t.maxTokens||4096,temperature:t.temperature,messages:this.convertToAnthropicMessages(e),tools:t.tools,tool_choice:s});r.onStart?.();let i=null;try{for await(const e of a)switch(e.type){case"content_block_start":"text"===e.content_block.type?r.onContent?.(""):"tool_use"===e.content_block.type&&(i={id:e.content_block.id,name:e.content_block.name,accumulatedJson:""});break;case"content_block_delta":"text_delta"===e.delta.type?r.onContent?.(e.delta.text):"input_json_delta"===e.delta.type&&i&&(i.accumulatedJson+=e.delta.partial_json);break;case"content_block_stop":if(i){try{const e=JSON.parse(i.accumulatedJson);r.onToolCall?.({id:i.id,name:i.name,input:e})}catch(e){console.error("Failed to parse tool use JSON:",e)}i=null}break;case"message_stop":r.onEnd?.()}}catch(e){r.onError?.(e)}}extractSystemMessage(e){return e.filter((e=>"system"===e.role)).map((e=>"string"==typeof e.content?e.content:e.content[0].text))[0]||""}convertToAnthropicMessages(e){return e.filter((e=>"system"!==e.role)).map((e=>{const t="tool"===e.role?"assistant":e.role;return"user"!==t&&"assistant"!==t?(console.warn(`Unsupported message role ${e.role} for Anthropic API, defaulting to 'user'`),{role:"user",content:(e.content,e.content)}):{role:t,content:e.content}}))}async generateStructured(e,t,r){const n=(0,Nt.Ik)(e,{target:"openApi3"}),s=JSON.stringify(n,null,2);let a=r?.systemPrompt||"You are a helpful assistant that generates structured data based on user requests. Follow the user's instructions carefully and output valid JSON data according to the schema.";a+=`\n\nYou must respond with a valid JSON object conforming to this schema:\n${s}\nOnly output the JSON object and nothing else. No explanations, no markdown formatting, just pure JSON.`;const i=await this.client.messages.create({model:r?.model||this.defaultModel,system:a,max_tokens:r?.maxTokens||1024,temperature:r?.temperature??.2,messages:[{role:"user",content:`${t}\n\nRespond only with a valid JSON object according to the schema. No explanations.`}]});try{const t=i.content.filter((e=>"text"===e.type)).map((e=>e.text)).join("\n"),r=t.match(/```json\n([\s\S]*?)\n```/)||t.match(/```\n([\s\S]*?)\n```/)||t.match(/\{[\s\S]*\}/),n=(r?r[0]:t).replace(/```json\n/g,"").replace(/```\n/g,"").replace(/```/g,"").trim(),s=JSON.parse(n);return e.parse(s)}catch(e){throw new Error(`Failed to generate valid structured data: ${e}`)}}}const my="RFC3986",fy={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:e=>String(e)},gy=(Object.prototype.hasOwnProperty,Array.isArray),yy=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();const by=1024;function wy(e,t){if(gy(e)){const r=[];for(let n=0;nString(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},ky=Array.isArray,Sy=Array.prototype.push,Ey=function(e,t){Sy.apply(e,ky(t)?t:[t])},xy=Date.prototype.toISOString,Ty={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,r,n,s)=>{if(0===e.length)return e;let a=e;if("symbol"==typeof e?a=Symbol.prototype.toString.call(e):"string"!=typeof e&&(a=String(e)),"iso-8859-1"===r)return escape(a).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));let i="";for(let e=0;e=by?a.slice(e,e+by):a,r=[];for(let e=0;e=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||"RFC1738"===s&&(40===n||41===n)?r[r.length]=t.charAt(e):n<128?r[r.length]=yy[n]:n<2048?r[r.length]=yy[192|n>>6]+yy[128|63&n]:n<55296||n>=57344?r[r.length]=yy[224|n>>12]+yy[128|n>>6&63]+yy[128|63&n]:(e+=1,n=65536+((1023&n)<<10|1023&t.charCodeAt(e)),r[r.length]=yy[240|n>>18]+yy[128|n>>12&63]+yy[128|n>>6&63]+yy[128|63&n])}i+=r.join("")}return i},encodeValuesOnly:!1,format:my,formatter:fy[my],indices:!1,serializeDate:e=>xy.call(e),skipNulls:!1,strictNullHandling:!1};const Cy={};function Py(e,t,r,n,s,a,i,o,c,l,u,d,h,p,m,f,g,y){let b=e,w=y,v=0,_=!1;for(;void 0!==(w=w.get(Cy))&&!_;){const t=w.get(e);if(v+=1,void 0!==t){if(t===v)throw new RangeError("Cyclic object value");_=!0}void 0===w.get(Cy)&&(v=0)}if("function"==typeof l?b=l(t,b):b instanceof Date?b=h?.(b):"comma"===r&&ky(b)&&(b=wy(b,(function(e){return e instanceof Date?h?.(e):e}))),null===b){if(a)return c&&!f?c(t,Ty.encoder,g,"key",p):t;b=""}if("string"==typeof(k=b)||"number"==typeof k||"boolean"==typeof k||"symbol"==typeof k||"bigint"==typeof k||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(b)){if(c){const e=f?t:c(t,Ty.encoder,g,"key",p);return[m?.(e)+"="+m?.(c(b,Ty.encoder,g,"value",p))]}return[m?.(t)+"="+m?.(String(b))]}var k;const S=[];if(void 0===b)return S;let E;if("comma"===r&&ky(b))f&&c&&(b=wy(b,c)),E=[{value:b.length>0?b.join(",")||null:void 0}];else if(ky(l))E=l;else{const e=Object.keys(b);E=u?e.sort(u):e}const x=o?String(t).replace(/\./g,"%2E"):String(t),T=n&&ky(b)&&1===b.length?x+"[]":x;if(s&&ky(b)&&0===b.length)return T+"[]";for(let t=0;t0?d+u:""}const Ay="4.98.0";let Iy,My,Ry,jy,Ny,$y,Ly,Fy,Dy,zy=!1,Uy=null,By=null,qy=null,Ky=null;class Wy{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}const Hy=()=>{Iy||function(e,t={auto:!1}){if(zy)throw new Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`);if(Iy)throw new Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${Iy}'\``);zy=t.auto,Iy=e.kind,My=e.fetch,Uy=e.Request,By=e.Response,qy=e.Headers,Ry=e.FormData,Ky=e.Blob,jy=e.File,Ny=e.ReadableStream,$y=e.getMultipartRequestOptions,Ly=e.getDefaultAgent,Fy=e.fileFromPath,Dy=e.isFsReadStream}(function({manuallyImported:e}={}){const t=e?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let r,n,s,a;try{r=fetch,n=Request,s=Response,a=Headers}catch(e){throw new Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${t}`)}return{kind:"web",fetch:r,Request:n,Response:s,Headers:a,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new Wy(e)}),getDefaultAgent:e=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:e=>!1}}(),{auto:!0})};Hy();class Vy extends Error{}class Gy extends Vy{constructor(e,t,r,n){super(`${Gy.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.request_id=n?.["x-request-id"],this.error=t;const s=t;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(e,t,r){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new Zy({message:r,cause:Zb(t)});const s=t?.error;return 400===e?new Yy(e,s,r,n):401===e?new Qy(e,s,r,n):403===e?new eb(e,s,r,n):404===e?new tb(e,s,r,n):409===e?new rb(e,s,r,n):422===e?new nb(e,s,r,n):429===e?new sb(e,s,r,n):e>=500?new ab(e,s,r,n):new Gy(e,s,r,n)}}class Jy extends Gy{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Zy extends Gy{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Xy extends Zy{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Yy extends Gy{}class Qy extends Gy{}class eb extends Gy{}class tb extends Gy{}class rb extends Gy{}class nb extends Gy{}class sb extends Gy{}class ab extends Gy{}class ib extends Vy{constructor(){super("Could not parse response content as the length limit was reached")}}class ob extends Vy{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var cb,lb=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},ub=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class db{constructor(){cb.set(this,void 0),this.buffer=new Uint8Array,lb(this,cb,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?(new TextEncoder).encode(e):e;let r=new Uint8Array(this.buffer.length+t.length);r.set(this.buffer),r.set(t,this.buffer.length),this.buffer=r;const n=[];let s;for(;null!=(s=hb(this.buffer,ub(this,cb,"f")));){if(s.carriage&&null==ub(this,cb,"f")){lb(this,cb,s.index,"f");continue}if(null!=ub(this,cb,"f")&&(s.index!==ub(this,cb,"f")+1||s.carriage)){n.push(this.decodeText(this.buffer.slice(0,ub(this,cb,"f")-1))),this.buffer=this.buffer.slice(ub(this,cb,"f")),lb(this,cb,null,"f");continue}const e=null!==ub(this,cb,"f")?s.preceding-1:s.preceding,t=this.decodeText(this.buffer.slice(0,e));n.push(t),this.buffer=this.buffer.slice(s.index),lb(this,cb,null,"f")}return n}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof Buffer){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new Vy(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new Vy(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new Vy("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode("\n"):[]}}function hb(e,t){for(let r=t??0;r0&&(yield t)}(s))for(const t of n.decode(e)){const e=r.decode(t);e&&(yield e)}for(const e of n.flush()){const t=r.decode(e);t&&(yield t)}}(e,t))if(!n)if(r.data.startsWith("[DONE]"))n=!0;else if(null===r.event||r.event.startsWith("response.")||r.event.startsWith("transcript.")){let t;try{t=JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if(t&&t.error)throw new Gy(void 0,t.error,void 0,Lb(e.headers));yield t}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if("error"==r.event)throw new Gy(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}}),t)}static fromReadableStream(e,t){let r=!1;return new fb((async function*(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let n=!1;try{for await(const t of async function*(){const t=new db,r=mb(e);for await(const e of r)for(const r of t.decode(e))yield r;for(const e of t.flush())yield e}())n||t&&(yield JSON.parse(t));n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}}),t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],r=this.iterator(),n=n=>({next:()=>{if(0===n.length){const n=r.next();e.push(n),t.push(n)}return n.shift()}});return[new fb((()=>n(e)),this.controller),new fb((()=>n(t)),this.controller)]}toReadableStream(){const e=this;let t;const r=new TextEncoder;return new Ny({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:n,done:s}=await t.next();if(s)return e.close();const a=r.encode(JSON.stringify(n)+"\n");e.enqueue(a)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class gb{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 e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=function(e,t){const r=e.indexOf(t);if(-1!==r)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}const yb=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,bb=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&wb(e),wb=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer,vb=e=>bb(e)||yb(e)||Dy(e);async function _b(e,t,r){if(e=await e,bb(e))return e;if(yb(e)){const n=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");const s=wb(n)?[await n.arrayBuffer()]:[n];return new jy(s,t,r)}const n=await async function(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(wb(e))t.push(await e.arrayBuffer());else{if(!Sb(e))throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${function(e){const t=Object.getOwnPropertyNames(e);return`[${t.map((e=>`"${e}"`)).join(", ")}]`}(e)}`);for await(const r of e)t.push(r)}return t}(e);if(t||(t=function(e){return kb(e.name)||kb(e.filename)||kb(e.path)?.split(/[\\/]/).pop()}(e)??"unknown_file"),!r?.type){const e=n[0]?.type;"string"==typeof e&&(r={...r,type:e})}return new jy(n,t,r)}const kb=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,Sb=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],Eb=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],xb=async e=>{const t=await Tb(e.body);return $y(t,e)},Tb=async e=>{const t=new Ry;return await Promise.all(Object.entries(e||{}).map((([e,r])=>Cb(t,e,r)))),t},Cb=async(e,t,r)=>{if(void 0!==r){if(null==r)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof r||"number"==typeof r||"boolean"==typeof r)e.append(t,String(r));else if(vb(r)){const n=await _b(r);e.append(t,n)}else if(Array.isArray(r))await Promise.all(r.map((r=>Cb(e,t+"[]",r))));else{if("object"!=typeof r)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`);await Promise.all(Object.entries(r).map((([r,n])=>Cb(e,`${t}[${r}]`,n))))}}};var Pb,Ob=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},Ab=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};async function Ib(e){const{response:t}=e;if(e.options.stream)return rw("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):fb.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;const r=t.headers.get("content-type"),n=r?.split(";")[0]?.trim();if(n?.includes("application/json")||n?.endsWith("+json")){const e=await t.json();return rw("response",t.status,t.url,t.headers,e),Mb(e,t)}const s=await t.text();return rw("response",t.status,t.url,t.headers,s),s}function Mb(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}Hy();class Rb extends Promise{constructor(e,t=Ib){super((e=>{e(null)})),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new Rb(this.responsePromise,(async t=>Mb(e(await this.parseResponse(t),t),t.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(this.parseResponse)),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)}}class jb{constructor({baseURL:e,maxRetries:t=2,timeout:r=6e5,httpAgent:n,fetch:s}){this.baseURL=e,this.maxRetries=Jb("maxRetries",t),this.timeout=Jb("timeout",r),this.httpAgent=n,this.fetch=s??My}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Kb(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${nw()}`}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((async r=>{const n=r&&wb(r?.body)?new DataView(await r.body.arrayBuffer()):r?.body instanceof DataView?r.body:r?.body instanceof ArrayBuffer?new DataView(r.body):r&&ArrayBuffer.isView(r?.body)?new DataView(r.body.buffer):r?.body;return{method:e,path:t,...r,body:n}})))}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}calculateContentLength(e){if("string"==typeof e){if("undefined"!=typeof Buffer)return Buffer.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder){return(new TextEncoder).encode(e).length.toString()}}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){const r={...e},{method:n,path:s,query:a,headers:i={}}=r,o=ArrayBuffer.isView(r.body)||r.__binaryRequest&&"string"==typeof r.body?r.body:Eb(r.body)?r.body.body:r.body?JSON.stringify(r.body,null,2):null,c=this.calculateContentLength(o),l=this.buildURL(s,a);"timeout"in r&&Jb("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const u=r.httpAgent??this.httpAgent??Ly(l),d=r.timeout+1e3;"number"==typeof u?.options?.timeout&&d>(u.options.timeout??0)&&(u.options.timeout=d),this.idempotencyHeader&&"get"!==n&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);return{req:{method:n,...o&&{body:o},headers:this.buildHeaders({options:r,headers:i,contentLength:c,retryCount:t}),...u&&{agent:u},signal:r.signal??null},url:l,timeout:r.timeout}}buildHeaders({options:e,headers:t,contentLength:r,retryCount:n}){const s={};r&&(s["content-length"]=r);const a=this.defaultHeaders(e);return ew(s,a),ew(s,t),Eb(e.body)&&"node"!==Iy&&delete s["content-type"],void 0===sw(a,"x-stainless-retry-count")&&void 0===sw(t,"x-stainless-retry-count")&&(s["x-stainless-retry-count"]=String(n)),void 0===sw(a,"x-stainless-timeout")&&void 0===sw(t,"x-stainless-timeout")&&e.timeout&&(s["x-stainless-timeout"]=String(Math.trunc(e.timeout/1e3))),this.validateHeaders(s,t),s}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map((e=>[...e]))):{...e}:{}}makeStatusError(e,t,r,n){return Gy.generate(e,t,r,n)}request(e,t=null){return new Rb(this.makeRequest(e,t))}async makeRequest(e,t){const r=await e,n=r.maxRetries??this.maxRetries;null==t&&(t=n),await this.prepareOptions(r);const{req:s,url:a,timeout:i}=this.buildRequest(r,{retryCount:n-t});if(await this.prepareRequest(s,{url:a,options:r}),rw("request",a,r,s.headers),r.signal?.aborted)throw new Jy;const o=new AbortController,c=await this.fetchWithTimeout(a,s,i,o).catch(Zb);if(c instanceof Error){if(r.signal?.aborted)throw new Jy;if(t)return this.retryRequest(r,t);if("AbortError"===c.name)throw new Xy;throw new Zy({cause:c})}const l=Lb(c.headers);if(!c.ok){if(t&&this.shouldRetry(c)){return rw(`response (error; ${`retrying, ${t} attempts remaining`})`,c.status,a,l),this.retryRequest(r,t,l)}const e=await c.text().catch((e=>Zb(e).message)),n=Wb(e),s=n?void 0:e;rw(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,c.status,a,l,s);throw this.makeStatusError(c.status,n,s,l)}return{response:c,options:r,controller:o}}requestAPIList(e,t){const r=this.makeRequest(t,null);return new $b(this,r,e)}buildURL(e,t){const r=Vb(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return Yb(n)||(t={...n,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}stringifyQuery(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new Vy(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)})).join("&")}async fetchWithTimeout(e,t,r,n){const{signal:s,...a}=t||{};s&&s.addEventListener("abort",(()=>n.abort()));const i=setTimeout((()=>n.abort()),r),o={signal:n.signal,...a};return o.method&&(o.method=o.method.toUpperCase()),this.fetch.call(void 0,e,o).finally((()=>{clearTimeout(i)}))}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,r){let n;const s=r?.["retry-after-ms"];if(s){const e=parseFloat(s);Number.isNaN(e)||(n=e)}const a=r?.["retry-after"];if(a&&!n){const e=parseFloat(a);n=Number.isNaN(e)?Date.parse(a)-Date.now():1e3*e}if(!(n&&0<=n&&n<6e4)){const r=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,r)}return await Gb(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const r=t-e;return Math.min(.5*Math.pow(2,r),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${Ay}`}}class Nb{constructor(e,t,r,n){Pb.set(this,void 0),Ob(this,Pb,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new Vy("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&"object"==typeof t.query)t.query={...t.query,...e.params};else if("url"in e){const r=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[t,n]of r)e.url.searchParams.set(t,n);t.query=void 0,t.path=e.url.toString()}return await Ab(this,Pb,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Pb=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class $b extends Rb{constructor(e,t,r){super(t,(async t=>new r(e,t.response,await Ib(t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const Lb=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const r=t.toString();return e[r.toLowerCase()]||e[r]}}),Fb={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},Db=e=>"object"==typeof e&&null!==e&&!Yb(e)&&Object.keys(e).every((e=>Qb(Fb,e))),zb=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ay,"X-Stainless-OS":Bb(Deno.build.os),"X-Stainless-Arch":Ub(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ay,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ay,"X-Stainless-OS":Bb(process.platform),"X-Stainless-Arch":Ub(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const e=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{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:t,pattern:r}of e){const e=r.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ay,"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":Ay,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const Ub=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",Bb=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let qb;const Kb=()=>qb??(qb=zb()),Wb=e=>{try{return JSON.parse(e)}catch(e){return}},Hb=/^[a-z][a-z0-9+.-]*:/i,Vb=e=>Hb.test(e),Gb=e=>new Promise((t=>setTimeout(t,e))),Jb=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new Vy(`${e} must be an integer`);if(t<0)throw new Vy(`${e} must be a positive integer`);return t},Zb=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e)try{return new Error(JSON.stringify(e))}catch{}return new Error(e)},Xb=e=>"undefined"!=typeof process?process.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function Yb(e){if(!e)return!0;for(const t in e)return!1;return!0}function Qb(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ew(e,t){for(const r in t){if(!Qb(t,r))continue;const n=r.toLowerCase();if(!n)continue;const s=t[r];null===s?delete e[n]:void 0!==s&&(e[n]=s)}}const tw=new Set(["authorization","api-key"]);function rw(e,...t){if("undefined"!=typeof process&&"true"===process?.env?.DEBUG){const r=t.map((e=>{if(!e)return e;if(e.headers){const t={...e,headers:{...e.headers}};for(const r in e.headers)tw.has(r.toLowerCase())&&(t.headers[r]="REDACTED");return t}let t=null;for(const r in e)tw.has(r.toLowerCase())&&(t??(t={...e}),t[r]="REDACTED");return t??e}));console.log(`OpenAI:DEBUG:${e}`,...r)}}const nw=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),sw=(e,t)=>{const r=t.toLowerCase();if((e=>"function"==typeof e?.get)(e)){const n=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,((e,t,r)=>t+r.toUpperCase()));for(const s of[t,r,t.toUpperCase(),n]){const t=e.get(s);if(t)return t}}for(const[n,s]of Object.entries(e))if(n.toLowerCase()===r)return Array.isArray(s)?(s.length<=1||console.warn(`Received ${s.length} entries for the ${t} header, using the first entry.`),s[0]):s};function aw(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}class iw{constructor(e){this._client=e}}class ow extends iw{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class cw extends iw{list(e,t={},r){return Db(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,pw,{query:t,...r})}}class lw extends Nb{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class uw extends Nb{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){const e=this.getPaginatedItems();if(!e.length)return null;const t=e[e.length-1]?.id;return t?{params:{after:t}}:null}}class dw extends iw{constructor(){super(...arguments),this.messages=new cw(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(`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return Db(e)?this.list({},e):this._client.getAPIList("/chat/completions",hw,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}}class hw extends uw{}class pw extends uw{}dw.ChatCompletionsPage=hw,dw.Messages=cw;class mw extends iw{constructor(){super(...arguments),this.completions=new dw(this._client)}}mw.Completions=dw,mw.ChatCompletionsPage=hw;class fw extends iw{create(e,t){const r=!!e.encoding_format;let n=r?e.encoding_format:"base64";r&&rw("Request","User defined encoding_format:",e.encoding_format);const s=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return r?s:(rw("response","Decoding base64 embeddings to float32 array"),s._thenUnwrap((e=>(e&&e.data&&e.data.forEach((e=>{const t=e.embedding;e.embedding=(e=>{if("undefined"!=typeof Buffer){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{const t=atob(e),r=t.length,n=new Uint8Array(r);for(let e=0;er)throw new Xy({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return a}}class yw extends uw{}gw.FileObjectsPage=yw;class bw extends iw{createVariation(e,t){return this._client.post("/images/variations",xb({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",xb({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class ww extends iw{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t?.headers},__binaryResponse:!0})}}class vw extends iw{create(e,t){return this._client.post("/audio/transcriptions",xb({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class _w extends iw{create(e,t){return this._client.post("/audio/translations",xb({body:e,...t,__metadata:{model:e.model}}))}}class kw extends iw{constructor(){super(...arguments),this.transcriptions=new vw(this._client),this.translations=new _w(this._client),this.speech=new ww(this._client)}}kw.Transcriptions=vw,kw.Translations=_w,kw.Speech=ww;class Sw extends iw{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class Ew extends iw{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",xw,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class xw extends lw{}Ew.ModelsPage=xw;class Tw extends iw{}class Cw extends iw{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 Pw extends iw{constructor(){super(...arguments),this.graders=new Cw(this._client)}}Pw.Graders=Cw;class Ow extends iw{create(e,t,r){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,Aw,{body:t,method:"post",...r})}retrieve(e,t={},r){return Db(t)?this.retrieve(e,{},t):this._client.get(`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}del(e,t,r){return this._client.delete(`/fine_tuning/checkpoints/${e}/permissions/${t}`,r)}}class Aw extends lw{}Ow.PermissionCreateResponsesPage=Aw;class Iw extends iw{constructor(){super(...arguments),this.permissions=new Ow(this._client)}}Iw.Permissions=Ow,Iw.PermissionCreateResponsesPage=Aw;class Mw extends iw{list(e,t={},r){return Db(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,Rw,{query:t,...r})}}class Rw extends uw{}Mw.FineTuningJobCheckpointsPage=Rw;class jw extends iw{constructor(){super(...arguments),this.checkpoints=new Mw(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return Db(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",Nw,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return Db(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,$w,{query:t,...r})}pause(e,t){return this._client.post(`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(`/fine_tuning/jobs/${e}/resume`,t)}}class Nw extends uw{}class $w extends uw{}jw.FineTuningJobsPage=Nw,jw.FineTuningJobEventsPage=$w,jw.Checkpoints=Mw,jw.FineTuningJobCheckpointsPage=Rw;class Lw extends iw{constructor(){super(...arguments),this.methods=new Tw(this._client),this.jobs=new jw(this._client),this.checkpoints=new Iw(this._client),this.alpha=new Pw(this._client)}}Lw.Methods=Tw,Lw.Jobs=jw,Lw.FineTuningJobsPage=Nw,Lw.FineTuningJobEventsPage=$w,Lw.Checkpoints=Iw,Lw.Alpha=Pw;class Fw extends iw{}class Dw extends iw{constructor(){super(...arguments),this.graderModels=new Fw(this._client)}}Dw.GraderModels=Fw;class zw extends iw{create(e,t,r){return this._client.post(`/vector_stores/${e}/files`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/vector_stores/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}update(e,t,r,n){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},r){return Db(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,Uw,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}del(e,t,r){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){const n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){const n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){const s=await this.retrieve(e,t,{...r,headers:n}).withResponse(),a=s.data;switch(a.status){case"in_progress":let e=5e3;if(r?.pollIntervalMs)e=r.pollIntervalMs;else{const t=s.response.headers.get("openai-poll-after-ms");if(t){const r=parseInt(t);isNaN(r)||(e=r)}}await Gb(e);break;case"failed":case"completed":return a}}}async upload(e,t,r){const n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){const n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){return this._client.getAPIList(`/vector_stores/${e}/files/${t}/content`,Bw,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}}class Uw extends uw{}class Bw extends lw{}zw.VectorStoreFilesPage=Uw,zw.FileContentResponsesPage=Bw;class qw extends iw{create(e,t,r){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}cancel(e,t,r){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){const n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r={},n){return Db(r)?this.listFiles(e,t,{},r):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,Uw,{query:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async poll(e,t,r){const n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){const{data:s,response:a}=await this.retrieve(e,t,{...r,headers:n}).withResponse();switch(s.status){case"in_progress":let e=5e3;if(r?.pollIntervalMs)e=r.pollIntervalMs;else{const t=a.headers.get("openai-poll-after-ms");if(t){const r=parseInt(t);isNaN(r)||(e=r)}}await Gb(e);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){if(null==t||0==t.length)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const s=n?.maxConcurrency??5,a=Math.min(s,t.length),i=this._client,o=t.values(),c=[...r];const l=Array(a).fill(o).map((async function(e){for(let t of e){const e=await i.files.create({file:t,purpose:"assistants"},n);c.push(e.id)}}));return await(async e=>{const t=await Promise.allSettled(e),r=t.filter((e=>"rejected"===e.status));if(r.length){for(const e of r)console.error(e.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}const n=[];for(const e of t)"fulfilled"===e.status&&n.push(e.value);return n})(l),await this.createAndPoll(e,{file_ids:c})}}class Kw extends iw{constructor(){super(...arguments),this.files=new zw(this._client),this.fileBatches=new qw(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,r){return this._client.post(`/vector_stores/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e={},t){return Db(e)?this.list({},e):this._client.getAPIList("/vector_stores",Ww,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}search(e,t,r){return this._client.getAPIList(`/vector_stores/${e}/search`,Hw,{body:t,method:"post",...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}}class Ww extends uw{}class Hw extends lw{}Kw.VectorStoresPage=Ww,Kw.VectorStoreSearchResponsesPage=Hw,Kw.Files=zw,Kw.VectorStoreFilesPage=Uw,Kw.FileContentResponsesPage=Bw,Kw.FileBatches=qw;class Vw extends iw{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,r){return this._client.post(`/assistants/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e={},t){return Db(e)?this.list({},e):this._client.getAPIList("/assistants",Gw,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class Gw extends uw{}function Jw(e){return"function"==typeof e.parse}Vw.AssistantsPage=Gw;const Zw=e=>"assistant"===e?.role,Xw=e=>"function"===e?.role,Yw=e=>"tool"===e?.role;var Qw,ev,tv,rv,nv,sv,av,iv,ov,cv,lv,uv,dv,hv=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},pv=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class mv{constructor(){Qw.add(this),this.controller=new AbortController,ev.set(this,void 0),tv.set(this,(()=>{})),rv.set(this,(()=>{})),nv.set(this,void 0),sv.set(this,(()=>{})),av.set(this,(()=>{})),iv.set(this,{}),ov.set(this,!1),cv.set(this,!1),lv.set(this,!1),uv.set(this,!1),hv(this,ev,new Promise(((e,t)=>{hv(this,tv,e,"f"),hv(this,rv,t,"f")})),"f"),hv(this,nv,new Promise(((e,t)=>{hv(this,sv,e,"f"),hv(this,av,t,"f")})),"f"),pv(this,ev,"f").catch((()=>{})),pv(this,nv,"f").catch((()=>{}))}_run(e){setTimeout((()=>{e().then((()=>{this._emitFinal(),this._emit("end")}),pv(this,Qw,"m",dv).bind(this))}),0)}_connected(){this.ended||(pv(this,tv,"f").call(this),this._emit("connect"))}get ended(){return pv(this,ov,"f")}get errored(){return pv(this,cv,"f")}get aborted(){return pv(this,lv,"f")}abort(){this.controller.abort()}on(e,t){return(pv(this,iv,"f")[e]||(pv(this,iv,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=pv(this,iv,"f")[e];if(!r)return this;const n=r.findIndex((e=>e.listener===t));return n>=0&&r.splice(n,1),this}once(e,t){return(pv(this,iv,"f")[e]||(pv(this,iv,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,r)=>{hv(this,uv,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)}))}async done(){hv(this,uv,!0,"f"),await pv(this,nv,"f")}_emit(e,...t){if(pv(this,ov,"f"))return;"end"===e&&(hv(this,ov,!0,"f"),pv(this,sv,"f").call(this));const r=pv(this,iv,"f")[e];if(r&&(pv(this,iv,"f")[e]=r.filter((e=>!e.once)),r.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return pv(this,uv,"f")||r?.length||Promise.reject(e),pv(this,rv,"f").call(this,e),pv(this,av,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];pv(this,uv,"f")||r?.length||Promise.reject(e),pv(this,rv,"f").call(this,e),pv(this,av,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function fv(e){return"auto-parseable-response-format"===e?.$brand}function gv(e){return"auto-parseable-tool"===e?.$brand}function yv(e,t){const r=e.choices.map((e=>{if("length"===e.finish_reason)throw new ib;if("content_filter"===e.finish_reason)throw new ob;return{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map((e=>function(e,t){const r=e.tools?.find((e=>e.function?.name===t.function.name));return{...t,function:{...t.function,parsed_arguments:gv(r)?r.$parseRaw(t.function.arguments):r?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e)))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?bv(t,e.message.content):null}}}));return{...e,choices:r}}function bv(e,t){if("json_schema"!==e.response_format?.type)return null;if("json_schema"===e.response_format?.type){if("$parseRaw"in e.response_format){return e.response_format.$parseRaw(t)}return JSON.parse(t)}return null}function wv(e,t){if(!e)return!1;const r=e.tools?.find((e=>e.function?.name===t.function.name));return gv(r)||r?.function.strict||!1}function vv(e){return!!fv(e.response_format)||(e.tools?.some((e=>gv(e)||"function"===e.type&&!0===e.function.strict))??!1)}ev=new WeakMap,tv=new WeakMap,rv=new WeakMap,nv=new WeakMap,sv=new WeakMap,av=new WeakMap,iv=new WeakMap,ov=new WeakMap,cv=new WeakMap,lv=new WeakMap,uv=new WeakMap,Qw=new WeakSet,dv=function(e){if(hv(this,cv,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new Jy),e instanceof Jy)return hv(this,lv,!0,"f"),this._emit("abort",e);if(e instanceof Vy)return this._emit("error",e);if(e instanceof Error){const t=new Vy(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Vy(String(e)))};var _v,kv,Sv,Ev,xv,Tv,Cv,Pv,Ov=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};const Av=10;class Iv extends mv{constructor(){super(...arguments),_v.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t)if(this._emit("message",e),(Xw(e)||Yw(e))&&e.content)this._emit("functionCallResult",e.content);else if(Zw(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(Zw(e)&&e.tool_calls)for(const t of e.tool_calls)"function"===t.type&&this._emit("functionCall",t.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new Vy("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),Ov(this,_v,"m",kv).call(this)}async finalMessage(){return await this.done(),Ov(this,_v,"m",Sv).call(this)}async finalFunctionCall(){return await this.done(),Ov(this,_v,"m",Ev).call(this)}async finalFunctionCallResult(){return await this.done(),Ov(this,_v,"m",xv).call(this)}async totalUsage(){return await this.done(),Ov(this,_v,"m",Tv).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=Ov(this,_v,"m",Sv).call(this);t&&this._emit("finalMessage",t);const r=Ov(this,_v,"m",kv).call(this);r&&this._emit("finalContent",r);const n=Ov(this,_v,"m",Ev).call(this);n&&this._emit("finalFunctionCall",n);const s=Ov(this,_v,"m",xv).call(this);null!=s&&this._emit("finalFunctionCallResult",s),this._chatCompletions.some((e=>e.usage))&&this._emit("totalUsage",Ov(this,_v,"m",Tv).call(this))}async _createChatCompletion(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),Ov(this,_v,"m",Cv).call(this,t);const s=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(yv(s,t))}async _runChatCompletion(e,t,r){for(const e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,r)}async _runFunctions(e,t,r){const n="function",{function_call:s="auto",stream:a,...i}=t,o="string"!=typeof s&&s?.name,{maxChatCompletions:c=Av}=r||{},l={};for(const e of t.functions)l[e.name||e.function.name]=e;const u=t.functions.map((e=>({name:e.name||e.function.name,parameters:e.parameters,description:e.description})));for(const e of t.messages)this._addMessage(e,!1);for(let t=0;tJSON.stringify(e.name))).join(", ")}. Please try again`;this._addMessage({role:n,name:c,content:e});continue}if(o&&o!==c){const e=`Invalid function_call: ${JSON.stringify(c)}. ${JSON.stringify(o)} requested. Please try again`;this._addMessage({role:n,name:c,content:e});continue}let p;try{p=Jw(h)?await h.parse(d):d}catch(e){this._addMessage({role:n,name:c,content:e instanceof Error?e.message:String(e)});continue}const m=await h.function(p,this),f=Ov(this,_v,"m",Pv).call(this,m);if(this._addMessage({role:n,name:c,content:f}),o)return}}async _runTools(e,t,r){const n="tool",{tool_choice:s="auto",stream:a,...i}=t,o="string"!=typeof s&&s?.function?.name,{maxChatCompletions:c=Av}=r||{},l=t.tools.map((e=>{if(gv(e)){if(!e.$callback)throw new Vy("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e})),u={};for(const e of l)"function"===e.type&&(u[e.function.name||e.function.function.name]=e.function);const d="tools"in t?l.map((e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e)):void 0;for(const e of t.messages)this._addMessage(e,!1);for(let t=0;tJSON.stringify(e))).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}if(o&&o!==r){const e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(o)} requested. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}let i;try{i=Jw(a)?await a.parse(s):s}catch(e){const r=e instanceof Error?e.message:String(e);this._addMessage({role:n,tool_call_id:t,content:r});continue}const c=await a.function(i,this),l=Ov(this,_v,"m",Pv).call(this,c);if(this._addMessage({role:n,tool_call_id:t,content:l}),o)return}}}}_v=new WeakSet,kv=function(){return Ov(this,_v,"m",Sv).call(this).content??null},Sv=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(Zw(t)){const{function_call:e,...r}=t,n={...r,content:t.content??null,refusal:t.refusal??null};return e&&(n.function_call=e),n}}throw new Vy("stream ended without producing a ChatCompletionMessage with role=assistant")},Ev=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Zw(t)&&t?.function_call)return t.function_call;if(Zw(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},xv=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Xw(t)&&null!=t.content)return t.content;if(Yw(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some((e=>"assistant"===e.role&&e.tool_calls?.some((e=>"function"===e.type&&e.id===t.tool_call_id)))))return t.content}},Tv=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},Cv=function(e){if(null!=e.n&&e.n>1)throw new Vy("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Pv=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class Mv extends Iv{static runFunctions(e,t,r){const n=new Mv,s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run((()=>n._runFunctions(e,t,s))),n}static runTools(e,t,r){const n=new Mv,s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run((()=>n._runTools(e,t,s))),n}_addMessage(e,t=!0){super._addMessage(e,t),Zw(e)&&e.content&&this._emit("content",e.content)}}const Rv=1,jv=2,Nv=4,$v=8,Lv=16,Fv=32,Dv=64,zv=128,Uv=256,Bv=511;class qv extends Error{}class Kv extends Error{}const Wv=(e,t)=>{const r=e.length;let n=0;const s=e=>{throw new qv(`${e} at position ${n}`)},a=e=>{throw new Kv(`${e} at position ${n}`)},i=()=>(d(),n>=r&&s("Unexpected end of input"),'"'===e[n]?o():"{"===e[n]?c():"["===e[n]?l():"null"===e.substring(n,n+4)||Lv&t&&r-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):"true"===e.substring(n,n+4)||Fv&t&&r-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):"false"===e.substring(n,n+5)||Fv&t&&r-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):"Infinity"===e.substring(n,n+8)||zv&t&&r-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):"-Infinity"===e.substring(n,n+9)||Uv&t&&1{const i=n;let o=!1;for(n++;n{n++,d();const a={};try{for(;"}"!==e[n];){if(d(),n>=r&&$v&t)return a;const s=o();d(),n++;try{const e=i();Object.defineProperty(a,s,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if($v&t)return a;throw e}d(),","===e[n]&&n++}}catch(e){if($v&t)return a;s("Expected '}' at end of object")}return n++,a},l=()=>{n++;const r=[];try{for(;"]"!==e[n];)r.push(i()),d(),","===e[n]&&n++}catch(e){if(Nv&t)return r;s("Expected ']' at end of array")}return n++,r},u=()=>{if(0===n){"-"===e&&jv&t&&s("Not sure what '-' is");try{return JSON.parse(e)}catch(r){if(jv&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(e){}a(String(r))}}const i=n;for("-"===e[n]&&n++;e[n]&&!",]}".includes(e[n]);)n++;n!=r||jv&t||s("Unterminated number literal");try{return JSON.parse(e.substring(i,n))}catch(r){"-"===e.substring(i,n)&&jv&t&&s("Not sure what '-' is");try{return JSON.parse(e.substring(i,e.lastIndexOf("e")))}catch(e){a(String(e))}}},d=()=>{for(;nfunction(e,t=Bv){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return Wv(e.trim(),t)}(e,Bv^jv);var Vv,Gv,Jv,Zv,Xv,Yv,Qv,e_,t_,r_,n_,s_,a_=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},i_=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class o_ extends Iv{constructor(e){super(),Vv.add(this),Gv.set(this,void 0),Jv.set(this,void 0),Zv.set(this,void 0),a_(this,Gv,e,"f"),a_(this,Jv,[],"f")}get currentChatCompletionSnapshot(){return i_(this,Zv,"f")}static fromReadableStream(e){const t=new o_(null);return t._run((()=>t._fromReadableStream(e))),t}static createChatCompletion(e,t,r){const n=new o_(t);return n._run((()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}async _createChatCompletion(e,t,r){super._createChatCompletion;const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),i_(this,Vv,"m",Xv).call(this);const s=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const e of s)i_(this,Vv,"m",Qv).call(this,e);if(s.controller.signal?.aborted)throw new Jy;return this._addChatCompletion(i_(this,Vv,"m",r_).call(this))}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),i_(this,Vv,"m",Xv).call(this),this._connected();const n=fb.fromReadableStream(e,this.controller);let s;for await(const e of n)s&&s!==e.id&&this._addChatCompletion(i_(this,Vv,"m",r_).call(this)),i_(this,Vv,"m",Qv).call(this,e),s=e.id;if(n.controller.signal?.aborted)throw new Jy;return this._addChatCompletion(i_(this,Vv,"m",r_).call(this))}[(Gv=new WeakMap,Jv=new WeakMap,Zv=new WeakMap,Vv=new WeakSet,Xv=function(){this.ended||a_(this,Zv,void 0,"f")},Yv=function(e){let t=i_(this,Jv,"f")[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},i_(this,Jv,"f")[e.index]=t,t)},Qv=function(e){if(this.ended)return;const t=i_(this,Vv,"m",s_).call(this,e);this._emit("chunk",e,t);for(const r of e.choices){const e=t.choices[r.index];null!=r.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",r.delta.content,e.message.content),this._emit("content.delta",{delta:r.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=r.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:r.delta.refusal,snapshot:e.message.refusal}),null!=r.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:r.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=r.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:r.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const n=i_(this,Vv,"m",Yv).call(this,e);e.finish_reason&&(i_(this,Vv,"m",t_).call(this,e),null!=n.current_tool_call_index&&i_(this,Vv,"m",e_).call(this,e,n.current_tool_call_index));for(const t of r.delta.tool_calls??[])n.current_tool_call_index!==t.index&&(i_(this,Vv,"m",t_).call(this,e),null!=n.current_tool_call_index&&i_(this,Vv,"m",e_).call(this,e,n.current_tool_call_index)),n.current_tool_call_index=t.index;for(const t of r.delta.tool_calls??[]){const r=e.message.tool_calls?.[t.index];r?.type&&("function"===r?.type&&this._emit("tool_calls.function.arguments.delta",{name:r.function?.name,index:t.index,arguments:r.function.arguments,parsed_arguments:r.function.parsed_arguments,arguments_delta:t.function?.arguments??""}))}}},e_=function(e,t){if(i_(this,Vv,"m",Yv).call(this,e).done_tool_calls.has(t))return;const r=e.message.tool_calls?.[t];if(!r)throw new Error("no tool call snapshot");if(!r.type)throw new Error("tool call snapshot missing `type`");if("function"===r.type){const e=i_(this,Gv,"f")?.tools?.find((e=>"function"===e.type&&e.function.name===r.function.name));this._emit("tool_calls.function.arguments.done",{name:r.function.name,index:t,arguments:r.function.arguments,parsed_arguments:gv(e)?e.$parseRaw(r.function.arguments):e?.function.strict?JSON.parse(r.function.arguments):null})}else r.type},t_=function(e){const t=i_(this,Vv,"m",Yv).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const r=i_(this,Vv,"m",n_).call(this);this._emit("content.done",{content:e.message.content,parsed:r?r.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},r_=function(){if(this.ended)throw new Vy("stream has ended, this shouldn't happen");const e=i_(this,Zv,"f");if(!e)throw new Vy("request ended without sending any chunks");return a_(this,Zv,void 0,"f"),a_(this,Jv,[],"f"),function(e,t){const{id:r,choices:n,created:s,model:a,system_fingerprint:i,...o}=e,c={...o,id:r,choices:n.map((({message:t,finish_reason:r,index:n,logprobs:s,...a})=>{if(!r)throw new Vy(`missing finish_reason for choice ${n}`);const{content:i=null,function_call:o,tool_calls:c,...l}=t,u=t.role;if(!u)throw new Vy(`missing role for choice ${n}`);if(o){const{arguments:e,name:c}=o;if(null==e)throw new Vy(`missing function_call.arguments for choice ${n}`);if(!c)throw new Vy(`missing function_call.name for choice ${n}`);return{...a,message:{content:i,function_call:{arguments:e,name:c},role:u,refusal:t.refusal??null},finish_reason:r,index:n,logprobs:s}}return c?{...a,index:n,finish_reason:r,logprobs:s,message:{...l,role:u,content:i,refusal:t.refusal??null,tool_calls:c.map(((t,r)=>{const{function:s,type:a,id:i,...o}=t,{arguments:c,name:l,...u}=s||{};if(null==i)throw new Vy(`missing choices[${n}].tool_calls[${r}].id\n${c_(e)}`);if(null==a)throw new Vy(`missing choices[${n}].tool_calls[${r}].type\n${c_(e)}`);if(null==l)throw new Vy(`missing choices[${n}].tool_calls[${r}].function.name\n${c_(e)}`);if(null==c)throw new Vy(`missing choices[${n}].tool_calls[${r}].function.arguments\n${c_(e)}`);return{...o,id:i,type:a,function:{...u,name:l,arguments:c}}}))}}:{...a,message:{...l,content:i,role:u,refusal:t.refusal??null},finish_reason:r,index:n,logprobs:s}})),created:s,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return function(e,t){return t&&vv(t)?yv(e,t):{...e,choices:e.choices.map((e=>({...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}})))}}(c,t)}(e,i_(this,Gv,"f"))},n_=function(){const e=i_(this,Gv,"f")?.response_format;return fv(e)?e:null},s_=function(e){var t,r,n,s;let a=i_(this,Zv,"f");const{choices:i,...o}=e;a?Object.assign(a,o):a=a_(this,Zv,{...o,choices:[]},"f");for(const{delta:i,finish_reason:o,index:c,logprobs:l=null,...u}of e.choices){let e=a.choices[c];if(e||(e=a.choices[c]={finish_reason:o,index:c,message:{},logprobs:l,...u}),l)if(e.logprobs){const{content:n,refusal:s,...a}=l;Object.assign(e.logprobs,a),n&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...n)),s&&((r=e.logprobs).refusal??(r.refusal=[]),e.logprobs.refusal.push(...s))}else e.logprobs=Object.assign({},l);if(o&&(e.finish_reason=o,i_(this,Gv,"f")&&vv(i_(this,Gv,"f")))){if("length"===o)throw new ib;if("content_filter"===o)throw new ob}if(Object.assign(e,u),!i)continue;const{content:d,refusal:h,function_call:p,role:m,tool_calls:f,...g}=i;if(Object.assign(e.message,g),h&&(e.message.refusal=(e.message.refusal||"")+h),m&&(e.message.role=m),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((n=e.message.function_call).arguments??(n.arguments=""),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),d&&(e.message.content=(e.message.content||"")+d,!e.message.refusal&&i_(this,Vv,"m",n_).call(this)&&(e.message.parsed=Hv(e.message.content))),f){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:r,type:n,function:a,...i}of f){const o=(s=e.message.tool_calls)[t]??(s[t]={});Object.assign(o,i),r&&(o.id=r),n&&(o.type=n),a&&(o.function??(o.function={name:a.name??"",arguments:""})),a?.name&&(o.function.name=a.name),a?.arguments&&(o.function.arguments+=a.arguments,wv(i_(this,Gv,"f"),o)&&(o.function.parsed_arguments=Hv(o.function.arguments)))}}}return a},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("chunk",(r=>{const n=t.shift();n?n.resolve(r):e.push(r)})),this.on("end",(()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),this.on("error",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise(((e,r)=>t.push({resolve:e,reject:r}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new fb(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function c_(e){return JSON.stringify(e)}class l_ extends o_{static fromReadableStream(e){const t=new l_(null);return t._run((()=>t._fromReadableStream(e))),t}static runFunctions(e,t,r){const n=new l_(null),s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run((()=>n._runFunctions(e,t,s))),n}static runTools(e,t,r){const n=new l_(t),s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run((()=>n._runTools(e,t,s))),n}}class u_ extends iw{parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new Vy(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new Vy(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap((t=>yv(t,e)))}runFunctions(e,t){return e.stream?l_.runFunctions(this._client,e,t):Mv.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?l_.runTools(this._client,e,t):Mv.runTools(this._client,e,t)}stream(e,t){return o_.createChatCompletion(this._client,e,t)}}class d_ extends iw{constructor(){super(...arguments),this.completions=new u_(this._client)}}!function(e){e.Completions=u_}(d_||(d_={}));class h_ extends iw{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class p_ extends iw{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class m_ extends iw{constructor(){super(...arguments),this.sessions=new h_(this._client),this.transcriptionSessions=new p_(this._client)}}m_.Sessions=h_,m_.TranscriptionSessions=p_;var f_,g_,y_,b_,w_,v_,__,k_,S_,E_,x_,T_,C_,P_,O_,A_,I_,M_,R_,j_,N_,$_,L_=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)},F_=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r};class D_ extends mv{constructor(){super(...arguments),f_.add(this),g_.set(this,[]),y_.set(this,{}),b_.set(this,{}),w_.set(this,void 0),v_.set(this,void 0),__.set(this,void 0),k_.set(this,void 0),S_.set(this,void 0),E_.set(this,void 0),x_.set(this,void 0),T_.set(this,void 0),C_.set(this,void 0)}[(g_=new WeakMap,y_=new WeakMap,b_=new WeakMap,w_=new WeakMap,v_=new WeakMap,__=new WeakMap,k_=new WeakMap,S_=new WeakMap,E_=new WeakMap,x_=new WeakMap,T_=new WeakMap,C_=new WeakMap,f_=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",(r=>{const n=t.shift();n?n.resolve(r):e.push(r)})),this.on("end",(()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),this.on("error",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise(((e,r)=>t.push({resolve:e,reject:r}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new D_;return t._run((()=>t._fromReadableStream(e))),t}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),this._connected();const n=fb.fromReadableStream(e,this.controller);for await(const e of n)L_(this,f_,"m",P_).call(this,e);if(n.controller.signal?.aborted)throw new Jy;return this._addRun(L_(this,f_,"m",O_).call(this))}toReadableStream(){return new fb(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n,s){const a=new D_;return a._run((()=>a._runToolAssistantStream(e,t,r,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),a}async _createToolAssistantStream(e,t,r,n,s){const a=s?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",(()=>this.controller.abort())));const i={...n,stream:!0},o=await e.submitToolOutputs(t,r,i,{...s,signal:this.controller.signal});this._connected();for await(const e of o)L_(this,f_,"m",P_).call(this,e);if(o.controller.signal?.aborted)throw new Jy;return this._addRun(L_(this,f_,"m",O_).call(this))}static createThreadAssistantStream(e,t,r){const n=new D_;return n._run((()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}static createAssistantStream(e,t,r,n){const s=new D_;return s._run((()=>s._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),s}currentEvent(){return L_(this,x_,"f")}currentRun(){return L_(this,T_,"f")}currentMessageSnapshot(){return L_(this,w_,"f")}currentRunStepSnapshot(){return L_(this,C_,"f")}async finalRunSteps(){return await this.done(),Object.values(L_(this,y_,"f"))}async finalMessages(){return await this.done(),Object.values(L_(this,b_,"f"))}async finalRun(){if(await this.done(),!L_(this,v_,"f"))throw Error("Final run was not received.");return L_(this,v_,"f")}async _createThreadAssistantStream(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort())));const s={...t,stream:!0},a=await e.createAndRun(s,{...r,signal:this.controller.signal});this._connected();for await(const e of a)L_(this,f_,"m",P_).call(this,e);if(a.controller.signal?.aborted)throw new Jy;return this._addRun(L_(this,f_,"m",O_).call(this))}async _createAssistantStream(e,t,r,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort())));const a={...r,stream:!0},i=await e.create(t,a,{...n,signal:this.controller.signal});this._connected();for await(const e of i)L_(this,f_,"m",P_).call(this,e);if(i.controller.signal?.aborted)throw new Jy;return this._addRun(L_(this,f_,"m",O_).call(this))}static accumulateDelta(e,t){for(const[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let t=e[r];if(null!=t)if("index"!==r&&"type"!==r){if("string"==typeof t&&"string"==typeof n)t+=n;else if("number"==typeof t&&"number"==typeof n)t+=n;else{if(!aw(t)||!aw(n)){if(Array.isArray(t)&&Array.isArray(n)){if(t.every((e=>"string"==typeof e||"number"==typeof e))){t.push(...n);continue}for(const e of n){if(!aw(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const r=e.index;if(null==r)throw console.error(e),new Error("Expected array delta entry to have an `index` property");if("number"!=typeof r)throw new Error(`Expected array delta entry \`index\` property to be a number but got ${r}`);const n=t[r];null==n?t.push(e):t[r]=this.accumulateDelta(n,e)}continue}throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${t}`)}t=this.accumulateDelta(t,n)}e[r]=t}else e[r]=n;else e[r]=n}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n,s){return await this._createToolAssistantStream(r,e,t,n,s)}}P_=function(e){if(!this.ended)switch(F_(this,x_,e,"f"),L_(this,f_,"m",M_).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":L_(this,f_,"m",$_).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":L_(this,f_,"m",I_).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":L_(this,f_,"m",A_).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},O_=function(){if(this.ended)throw new Vy("stream has ended, this shouldn't happen");if(!L_(this,v_,"f"))throw Error("Final run has not been received");return L_(this,v_,"f")},A_=function(e){const[t,r]=L_(this,f_,"m",j_).call(this,e,L_(this,w_,"f"));F_(this,w_,t,"f"),L_(this,b_,"f")[t.id]=t;for(const e of r){const r=t.content[e.index];"text"==r?.type&&this._emit("textCreated",r.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 r of e.data.delta.content){if("text"==r.type&&r.text){let e=r.text,n=t.content[r.index];if(!n||"text"!=n.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,n.text)}if(r.index!=L_(this,__,"f")){if(L_(this,k_,"f"))switch(L_(this,k_,"f").type){case"text":this._emit("textDone",L_(this,k_,"f").text,L_(this,w_,"f"));break;case"image_file":this._emit("imageFileDone",L_(this,k_,"f").image_file,L_(this,w_,"f"))}F_(this,__,r.index,"f")}F_(this,k_,t.content[r.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==L_(this,__,"f")){const t=e.data.content[L_(this,__,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,L_(this,w_,"f"));break;case"text":this._emit("textDone",t.text,L_(this,w_,"f"))}}L_(this,w_,"f")&&this._emit("messageDone",e.data),F_(this,w_,void 0,"f")}},I_=function(e){const t=L_(this,f_,"m",R_).call(this,e);switch(F_(this,C_,t,"f"),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&&"tool_calls"==r.step_details.type&&r.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(const e of r.step_details.tool_calls)e.index==L_(this,S_,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(L_(this,E_,"f")&&this._emit("toolCallDone",L_(this,E_,"f")),F_(this,S_,e.index,"f"),F_(this,E_,t.step_details.tool_calls[e.index],"f"),L_(this,E_,"f")&&this._emit("toolCallCreated",L_(this,E_,"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":F_(this,C_,void 0,"f");"tool_calls"==e.data.step_details.type&&L_(this,E_,"f")&&(this._emit("toolCallDone",L_(this,E_,"f")),F_(this,E_,void 0,"f")),this._emit("runStepDone",e.data,t)}},M_=function(e){L_(this,g_,"f").push(e),this._emit("event",e)},R_=function(e){switch(e.event){case"thread.run.step.created":return L_(this,y_,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=L_(this,y_,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const n=D_.accumulateDelta(t,r.delta);L_(this,y_,"f")[e.data.id]=n}return L_(this,y_,"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":L_(this,y_,"f")[e.data.id]=e.data}if(L_(this,y_,"f")[e.data.id])return L_(this,y_,"f")[e.data.id];throw new Error("No snapshot available")},j_=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 n=e.data;if(n.delta.content)for(const e of n.delta.content)if(e.index in t.content){let r=t.content[e.index];t.content[e.index]=L_(this,f_,"m",N_).call(this,e,r)}else t.content[e.index]=e,r.push(e);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")},N_=function(e,t){return D_.accumulateDelta(t,e)},$_=function(e){switch(F_(this,T_,e.data,"f"),e.event){case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.cancelling":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":F_(this,v_,e.data,"f"),L_(this,E_,"f")&&(this._emit("toolCallDone",L_(this,E_,"f")),F_(this,E_,void 0,"f"))}};class z_ extends iw{create(e,t,r){return this._client.post(`/threads/${e}/messages`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/threads/${e}/messages/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}update(e,t,r,n){return this._client.post(`/threads/${e}/messages/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},r){return Db(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,U_,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}del(e,t,r){return this._client.delete(`/threads/${e}/messages/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}}class U_ extends uw{}z_.MessagesPage=U_;class B_ extends iw{retrieve(e,t,r,n={},s){return Db(n)?this.retrieve(e,t,r,{},n):this._client.get(`/threads/${e}/runs/${t}/steps/${r}`,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t,r={},n){return Db(r)?this.list(e,t,{},r):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,q_,{query:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class q_ extends uw{}B_.RunStepsPage=q_;class K_ extends iw{constructor(){super(...arguments),this.steps=new B_(this._client)}create(e,t,r){const{include:n,...s}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:n},body:s,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers},stream:t.stream??!1})}retrieve(e,t,r){return this._client.get(`/threads/${e}/runs/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}update(e,t,r,n){return this._client.post(`/threads/${e}/runs/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},r){return Db(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,W_,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}cancel(e,t,r){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){const n=await this.create(e,t,r);return await this.poll(e,n.id,r)}createAndStream(e,t,r){return D_.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){const n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){const{data:s,response:a}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(r?.pollIntervalMs)e=r.pollIntervalMs;else{const t=a.headers.get("openai-poll-after-ms");if(t){const r=parseInt(t);isNaN(r)||(e=r)}}await Gb(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,t,r){return D_.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r,n){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers},stream:r.stream??!1})}async submitToolOutputsAndPoll(e,t,r,n){const s=await this.submitToolOutputs(e,t,r,n);return await this.poll(e,s.id,n)}submitToolOutputsStream(e,t,r,n){return D_.createToolAssistantStream(e,t,this._client.beta.threads.runs,r,n)}}class W_ extends uw{}K_.RunsPage=W_,K_.Steps=B_,K_.RunStepsPage=q_;class H_ extends iw{constructor(){super(...arguments),this.runs=new K_(this._client),this.messages=new z_(this._client)}create(e={},t){return Db(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,r){return this._client.post(`/threads/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){const r=await this.createAndRun(e,t);return await this.runs.poll(r.thread_id,r.id,t)}createAndRunStream(e,t){return D_.createThreadAssistantStream(e,this._client.beta.threads,t)}}H_.Runs=K_,H_.RunsPage=W_,H_.Messages=z_,H_.MessagesPage=U_;class V_ extends iw{constructor(){super(...arguments),this.realtime=new m_(this._client),this.chat=new d_(this._client),this.assistants=new Vw(this._client),this.threads=new H_(this._client)}}V_.Realtime=m_,V_.Assistants=Vw,V_.AssistantsPage=Gw,V_.Threads=H_;class G_ extends iw{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return Db(e)?this.list({},e):this._client.getAPIList("/batches",J_,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class J_ extends uw{}G_.BatchesPage=J_;class Z_ extends iw{create(e,t,r){return this._client.post(`/uploads/${e}/parts`,xb({body:t,...r}))}}class X_ extends iw{constructor(){super(...arguments),this.parts=new Z_(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(`/uploads/${e}/complete`,{body:t,...r})}}function Y_(e,t){return t&&function(e){if(fv(e.text?.format))return!0;return!1}(t)?Q_(e,t):{...e,output_parsed:null,output:e.output.map((e=>"function_call"===e.type?{...e,parsed_arguments:null}:"message"===e.type?{...e,content:e.content.map((e=>({...e,parsed:null})))}:e))}}function Q_(e,t){const r=e.output.map((e=>{if("function_call"===e.type)return{...e,parsed_arguments:nk(t,e)};if("message"===e.type){const r=e.content.map((e=>"output_text"===e.type?{...e,parsed:ek(t,e.text)}:e));return{...e,content:r}}return e})),n=Object.assign({},e,{output:r});return Object.getOwnPropertyDescriptor(e,"output_text")||sk(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const e of n.output)if("message"===e.type)for(const t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed;return null}}),n}function ek(e,t){if("json_schema"!==e.text?.format?.type)return null;if("$parseRaw"in e.text?.format){const r=e.text?.format;return r.$parseRaw(t)}return JSON.parse(t)}function tk(e){return"auto-parseable-tool"===e?.$brand}function rk(e,t){return e.find((e=>"function"===e.type&&e.name===t))}function nk(e,t){const r=rk(e.tools??[],t.name);return{...t,...t,parsed_arguments:tk(r)?r.$parseRaw(t.arguments):r?.strict?JSON.parse(t.arguments):null}}function sk(e){const t=[];for(const r of e.output)if("message"===r.type)for(const e of r.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}X_.Parts=Z_;class ak extends iw{list(e,t={},r){return Db(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,wk,{query:t,...r})}}var ik,ok,ck,lk,uk,dk,hk,pk,mk,fk=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},gk=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class yk extends mv{constructor(e){super(),ik.add(this),ok.set(this,void 0),ck.set(this,void 0),lk.set(this,void 0),fk(this,ok,e,"f")}static createResponse(e,t,r){const n=new yk(t);return n._run((()=>n._createResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}async _createResponse(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),gk(this,ik,"m",uk).call(this);const s=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const e of s)gk(this,ik,"m",dk).call(this,e);if(s.controller.signal?.aborted)throw new Jy;return gk(this,ik,"m",hk).call(this)}[(ok=new WeakMap,ck=new WeakMap,lk=new WeakMap,ik=new WeakSet,uk=function(){this.ended||fk(this,ck,void 0,"f")},dk=function(e){if(this.ended)return;const t=gk(this,ik,"m",pk).call(this,e);switch(this._emit("event",e),e.type){case"response.output_text.delta":{const r=t.output[e.output_index];if(!r)throw new Vy(`missing output at index ${e.output_index}`);if("message"===r.type){const t=r.content[e.content_index];if(!t)throw new Vy(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new Vy(`expected content to be 'output_text', got ${t.type}`);this._emit("response.output_text.delta",{...e,snapshot:t.text})}break}case"response.function_call_arguments.delta":{const r=t.output[e.output_index];if(!r)throw new Vy(`missing output at index ${e.output_index}`);"function_call"===r.type&&this._emit("response.function_call_arguments.delta",{...e,snapshot:r.arguments});break}default:this._emit(e.type,e)}},hk=function(){if(this.ended)throw new Vy("stream has ended, this shouldn't happen");const e=gk(this,ck,"f");if(!e)throw new Vy("request ended without sending any events");fk(this,ck,void 0,"f");const t=function(e,t){return Y_(e,t)}(e,gk(this,ok,"f"));return fk(this,lk,t,"f"),t},pk=function(e){let t=gk(this,ck,"f");if(!t){if("response.created"!==e.type)throw new Vy(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=fk(this,ck,e.response,"f"),t}switch(e.type){case"response.output_item.added":t.output.push(e.item);break;case"response.content_part.added":{const r=t.output[e.output_index];if(!r)throw new Vy(`missing output at index ${e.output_index}`);"message"===r.type&&r.content.push(e.part);break}case"response.output_text.delta":{const r=t.output[e.output_index];if(!r)throw new Vy(`missing output at index ${e.output_index}`);if("message"===r.type){const t=r.content[e.content_index];if(!t)throw new Vy(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new Vy(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case"response.function_call_arguments.delta":{const r=t.output[e.output_index];if(!r)throw new Vy(`missing output at index ${e.output_index}`);"function_call"===r.type&&(r.arguments+=e.delta);break}case"response.completed":fk(this,ck,e.response,"f")}return t},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",(r=>{const n=t.shift();n?n.resolve(r):e.push(r)})),this.on("end",(()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),this.on("error",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise(((e,r)=>t.push({resolve:e,reject:r}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=gk(this,lk,"f");if(!e)throw new Vy("stream ended without producing a ChatCompletion");return e}}class bk extends iw{constructor(){super(...arguments),this.inputItems=new ak(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap((e=>("object"in e&&"response"===e.object&&sk(e),e)))}retrieve(e,t={},r){return Db(t)?this.retrieve(e,{},t):this._client.get(`/responses/${e}`,{query:t,...r})}del(e,t){return this._client.delete(`/responses/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((t=>Q_(t,e)))}stream(e,t){return yk.createResponse(this._client,e,t)}}class wk extends uw{}bk.InputItems=ak;class vk extends iw{retrieve(e,t,r,n){return this._client.get(`/evals/${e}/runs/${t}/output_items/${r}`,n)}list(e,t,r={},n){return Db(r)?this.list(e,t,{},r):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,_k,{query:r,...n})}}class _k extends uw{}vk.OutputItemListResponsesPage=_k;class kk extends iw{constructor(){super(...arguments),this.outputItems=new vk(this._client)}create(e,t,r){return this._client.post(`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){return this._client.get(`/evals/${e}/runs/${t}`,r)}list(e,t={},r){return Db(t)?this.list(e,{},t):this._client.getAPIList(`/evals/${e}/runs`,Sk,{query:t,...r})}del(e,t,r){return this._client.delete(`/evals/${e}/runs/${t}`,r)}cancel(e,t,r){return this._client.post(`/evals/${e}/runs/${t}`,r)}}class Sk extends uw{}kk.RunListResponsesPage=Sk,kk.OutputItems=vk,kk.OutputItemListResponsesPage=_k;class Ek extends iw{constructor(){super(...arguments),this.runs=new kk(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(`/evals/${e}`,t)}update(e,t,r){return this._client.post(`/evals/${e}`,{body:t,...r})}list(e={},t){return Db(e)?this.list({},e):this._client.getAPIList("/evals",xk,{query:e,...t})}del(e,t){return this._client.delete(`/evals/${e}`,t)}}class xk extends uw{}Ek.EvalListResponsesPage=xk,Ek.Runs=kk,Ek.RunListResponsesPage=Sk;class Tk extends jb{constructor({baseURL:e=Xb("OPENAI_BASE_URL"),apiKey:t=Xb("OPENAI_API_KEY"),organization:r=Xb("OPENAI_ORG_ID")??null,project:n=Xb("OPENAI_PROJECT_ID")??null,...s}={}){if(void 0===t)throw new Vy("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 a={apiKey:t,organization:r,project:n,...s,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new Vy("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:a.baseURL,timeout:a.timeout??6e5,httpAgent:a.httpAgent,maxRetries:a.maxRetries,fetch:a.fetch}),this.completions=new ow(this),this.chat=new mw(this),this.embeddings=new fw(this),this.files=new gw(this),this.images=new bw(this),this.audio=new kw(this),this.moderations=new Sw(this),this.models=new Ew(this),this.fineTuning=new Lw(this),this.graders=new Dw(this),this.vectorStores=new Kw(this),this.beta=new V_(this),this.batches=new G_(this),this.uploads=new X_(this),this.responses=new bk(this),this.evals=new Ek(this),this._options=a,this.apiKey=t,this.organization=r,this.project=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return Oy(e,{arrayFormat:"brackets"})}}mk=Tk,Tk.OpenAI=mk,Tk.DEFAULT_TIMEOUT=6e5,Tk.OpenAIError=Vy,Tk.APIError=Gy,Tk.APIConnectionError=Zy,Tk.APIConnectionTimeoutError=Xy,Tk.APIUserAbortError=Jy,Tk.NotFoundError=tb,Tk.ConflictError=rb,Tk.RateLimitError=sb,Tk.BadRequestError=Yy,Tk.AuthenticationError=Qy,Tk.InternalServerError=ab,Tk.PermissionDeniedError=eb,Tk.UnprocessableEntityError=nb,Tk.toFile=_b,Tk.fileFromPath=Fy,Tk.Completions=ow,Tk.Chat=mw,Tk.ChatCompletionsPage=hw,Tk.Embeddings=fw,Tk.Files=gw,Tk.FileObjectsPage=yw,Tk.Images=bw,Tk.Audio=kw,Tk.Moderations=Sw,Tk.Models=Ew,Tk.ModelsPage=xw,Tk.FineTuning=Lw,Tk.Graders=Dw,Tk.VectorStores=Kw,Tk.VectorStoresPage=Ww,Tk.VectorStoreSearchResponsesPage=Hw,Tk.Beta=V_,Tk.Batches=G_,Tk.BatchesPage=J_,Tk.Uploads=X_,Tk.Responses=bk,Tk.Evals=Ek,Tk.EvalListResponsesPage=xk;new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations"]);const Ck=Tk;M.z.object({llm:M.z.literal("openai"),apiKey:M.z.string(),modelName:M.z.string().optional(),baseURL:M.z.string().default("http://llm.nxtscape.ai"),options:M.z.record(M.z.unknown()).optional()});class Pk{constructor(e,t,r){if(this.defaultModel="gpt-4o",this.defaultBaseURL="http://llm.nxtscape.ai",t&&(this.defaultModel=t),"string"==typeof e)this.client=new Ck({apiKey:e,baseURL:this.defaultBaseURL,dangerouslyAllowBrowser:!0,...r});else if(e.chat&&e.chat.completions)this.client=e;else{const t=e;t.dangerouslyAllowBrowser=!0,t.baseURL||(t.baseURL=this.defaultBaseURL),this.client=new Ck(t)}}processResponse(e){const t=e.choices[0]?.message.tool_calls?.map((e=>({id:e.id,name:e.function.name,input:JSON.parse(e.function.arguments)})))||[];return{textContent:e.choices[0]?.message.content||null,content:e.choices[0]?.message.content?[{type:"text",text:e.choices[0].message.content}]:[],toolCalls:t,stop_reason:e.choices[0]?.finish_reason||null}}async generateText(e,t){const r=await this.client.chat.completions.create({model:t.model||this.defaultModel,messages:this.formatMessages(e),temperature:t.temperature,max_tokens:t.maxTokens,tools:this.formatTools(t.tools),tool_choice:this.formatToolChoice(t.toolChoice)});return this.processResponse(r)}async generateStream(e,t,r){const n=await this.client.chat.completions.create({model:t.model||this.defaultModel,messages:this.formatMessages(e),temperature:t.temperature,max_tokens:t.maxTokens,tools:this.formatTools(t.tools),tool_choice:this.formatToolChoice(t.toolChoice),stream:!0});r.onStart?.();let s={};try{for await(const e of n){const t=e.choices[0]?.delta;if(t?.content&&r.onContent?.(t.content),t?.tool_calls&&t.tool_calls.length>0)for(const e of t.tool_calls){const t=e.id;t&&!s[t]&&(s[t]={id:t,function:{name:"",arguments:""}}),t&&e.function?.name&&(s[t].function.name=e.function.name),t&&e.function?.arguments&&(s[t].function.arguments+=e.function.arguments),t&&s[t].function.name&&this.isValidJson(s[t].function.arguments)&&(r.onToolCall?.({id:t,name:s[t].function.name,input:JSON.parse(s[t].function.arguments)}),delete s[t])}}r.onEnd?.()}catch(e){r.onError?.(e)}}formatMessages(e){return e.map((e=>(e.content,{role:e.role,content:e.content,...e.name?{name:e.name}:{},...e.tool_call_id?{tool_call_id:e.tool_call_id}:{}})))}formatTools(e){if(e&&0!==e.length)return e.map((e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.input_schema}})))}formatToolChoice(e){if(e)return"auto"===e.type?"auto":"tool"===e.type?e.name?{type:"function",function:{name:e.name}}:"required":void 0}isValidJson(e){try{return JSON.parse(e),!0}catch(e){return!1}}async generateStructured(e,t,r){const n=(0,Nt.Ik)(e,{target:"openApi3"}),s=JSON.stringify(n,null,2);let a=r?.systemPrompt||"You are a helpful assistant that generates structured data based on user requests. Follow the user's instructions carefully and output valid JSON data.";a+=`\n\nYou must respond with a valid JSON object conforming to this schema:\n${s}\nOnly output the JSON object and nothing else. No explanations, no markdown formatting, just pure JSON.`;const i=await this.client.chat.completions.create({model:r?.model||this.defaultModel,response_format:{type:"json_object"},temperature:r?.temperature??.2,max_tokens:r?.maxTokens,messages:[{role:"system",content:a},{role:"user",content:`${t}\n\nRespond with a valid JSON object that follows the schema.`}]});try{const t=i.choices[0]?.message?.content;if(!t)throw new Error("No structured data was generated");const r=JSON.parse(t);return e.parse(r)}catch(e){throw new Error(`Failed to generate valid structured data: ${e}`)}}}const Ok="sk-xmIa7rAyujEDHPLRyYpwzQ";if(!Ok)throw new Error("BUILD ERROR: LITELLM_API_KEY is missing or not replaced by webpack");const Ak=Ok,Ik={default:"claude-3-5-sonnet",options:["claude-3-5-sonnet","claude-3-opus","claude-3-5-haiku","claude-3-opus","claude-3-7-sonnet"]},Mk={default:"gpt-4o",options:["gpt-4o","gpt-4o-mini"]};class Rk{static getApiKey(e){return Ak}static buildLLMProvider(e){let t;if("string"==typeof e)t=new py(e);else if("llm"in e)if("claude"===e.llm){const r=e,n=r.apiKey||this.getApiKey("claude");t=new py(n,r.modelName,r.options)}else{if("openai"!==e.llm)throw new Error(`Unknown LLM provider: ${e.llm}`);{const r=e,n=r.apiKey||this.getApiKey("openai");t=new Pk(n,r.modelName,r.options)}}else t=e;return t}static createClaudeProvider(e){const t=this.getApiKey("claude");return new py(t,e||Ik.default)}static createOpenAIProvider(e){const t=this.getApiKey("openai");return new Pk(t,e||Mk.default)}static createProvider(e,t){return"claude"===e?this.createClaudeProvider(t):this.createOpenAIProvider(t)}}const jk=M.z.object({instruction:M.z.string().optional(),targetFolder:M.z.string().optional(),dryRun:M.z.boolean().optional(),maxCategories:M.z.number().optional(),includeSubcategories:M.z.boolean().optional()}),Nk=M.z.object({id:M.z.string(),title:M.z.string(),url:M.z.string(),category:M.z.string(),subcategory:M.z.string().optional()}),$k=M.z.object({category:M.z.string(),subcategories:M.z.array(M.z.string()),count:M.z.number(),bookmarks:M.z.array(Nk)}),Lk=M.z.object({success:M.z.boolean(),totalBookmarks:M.z.number(),organizedCount:M.z.number(),categories:M.z.array($k),message:M.z.string()});class Fk extends fm{constructor(e){super({name:"organize_bookmarks",description:"Intelligently organize all bookmarks from the bookmark bar (including those in folders) using AI based on custom instructions. Consolidates scattered bookmarks into a clean folder structure.",category:"bookmarks",version:"2.1.0",inputSchema:jk,outputSchema:Lk,examples:[{description:"Organize with custom instruction",input:{instruction:"Organize by project type and technology stack",dryRun:!0},output:{success:!0,totalBookmarks:25,organizedCount:25,categories:[{category:"Frontend Projects",subcategories:["React","Vue","Angular"],count:8,bookmarks:[]}],message:"Would organize 25 bookmarks into 5 categories"}},{description:"Organize into custom folder",input:{instruction:"Create work and personal categories only",targetFolder:"My Organized Bookmarks",maxCategories:2},output:{success:!0,totalBookmarks:20,organizedCount:20,categories:[{category:"Work",subcategories:[],count:12,bookmarks:[]},{category:"Personal",subcategories:[],count:8,bookmarks:[]}],message:"Successfully organized 20 bookmarks into 2 categories"}}],streamingConfig:{displayName:"Organize Bookmarks",icon:"šŸ“š",progressMessage:"Analyzing and organizing all bookmarks..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.instruction,n=t?.targetFolder,s=t?.dryRun;let a=s?"Analyzing":"Organizing";return a+=" bookmarks",a+=r?` with instruction: "${r}"`:" with AI",n&&!s&&(a+=` into "${n}"`),a+="...",a}catch{return"Organizing bookmarks..."}}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;if(0===e.organizedCount)return"šŸ“š No bookmarks to organize!";const t=e.categories.length,r=e.categories.reduce(((e,t)=>e+t.subcategories.length),0);return r>0?`šŸ“š Organized ${e.organizedCount} bookmarks into ${t} categories with ${r} subcategories`:`šŸ“š Organized ${e.organizedCount} bookmarks into ${t} categories`}async execute(e){try{const t=e.dryRun??!1,r=e.maxCategories??8,n=e.includeSubcategories??!0,s=e.targetFolder||Fk.DEFAULT_FOLDER_NAME,a=e.instruction,i=await this.getBookmarkBar();if(!i)return{success:!1,totalBookmarks:0,organizedCount:0,categories:[],message:"Could not find bookmark bar"};const o=await chrome.bookmarks.getChildren(i.id),c=o.filter((e=>e.url)),l=o.filter((e=>!e.url)),u=[];c.forEach((e=>{u.push({id:e.id,title:e.title,url:e.url})}));for(const e of l){if(e.title===s)continue;const t=await chrome.bookmarks.getChildren(e.id);t.filter((e=>e.url)).forEach((t=>{u.push({id:t.id,title:t.title,url:t.url,parentTitle:e.title})}))}if(0===u.length)return{success:!0,totalBookmarks:0,organizedCount:0,categories:[],message:"No bookmarks found to organize"};const d=await this.categorizeBookmarksWithLLM(u,r,n,a);if(t)return{success:!0,totalBookmarks:u.length,organizedCount:u.length,categories:d,message:`Would organize ${u.length} bookmarks into ${d.length} categories`};const h=await this.applyOrganization(i.id,d,s);return{success:!0,totalBookmarks:u.length,organizedCount:h.organizedCount,categories:h.categories,message:`Successfully organized ${h.organizedCount} bookmarks into ${h.categories.length} categories`}}catch(e){return console.error("[organize_bookmarks] Error:",e),{success:!1,totalBookmarks:0,organizedCount:0,categories:[],message:`Error organizing bookmarks: ${e instanceof Error?e.message:String(e)}`}}}async categorizeBookmarksWithLLM(e,t,r,n){const s=Rk.createClaudeProvider(),a=`You are an expert at organizing bookmarks into logical categories. Your task is to analyze a list of bookmarks and create a clean, intuitive folder structure.\n\n**REQUIREMENTS:**\n1. Create at most ${t} main categories\n2. ${r?"Create subcategories when it makes sense (max 2 levels deep)":"Do NOT create subcategories"}\n3. Category names should be:\n - Clear and descriptive (2-3 words max)\n - Professional and consistent\n - Not too specific or too broad\n4. Every bookmark must be assigned to exactly one category${r?" (and optionally one subcategory)":""}\n5. Similar websites should be grouped together\n6. Consider the domain, title, purpose, and current folder (if any) of each bookmark\n\n${n?`**CUSTOM INSTRUCTION:**\n${n}\n\nFollow this instruction while organizing the bookmarks. Adapt your categorization strategy based on this guidance.\n`:""}\n\n**OUTPUT FORMAT:**\nReturn a JSON array of category objects. Each object should have:\n- category: string (main category name)\n- subcategories: string[] (list of subcategory names, empty if none)\n- bookmarks: array of objects with:\n - id: string (the bookmark ID)\n - category: string (assigned category)\n - subcategory: string (assigned subcategory, optional)\n\nExample:\n[\n {\n "category": "Development",\n "subcategories": ["Documentation", "Tools"],\n "bookmarks": [\n {"id": "123", "category": "Development", "subcategory": "Documentation"},\n {"id": "456", "category": "Development", "subcategory": "Tools"}\n ]\n }\n]`,i=`Please organize these bookmarks into categories${n?" following the custom instruction provided":""}:\n\n${e.map(((e,t)=>`${t+1}. ID: ${e.id}\n Title: ${e.title}\n URL: ${e.url}${e.parentTitle?`\n Current Folder: ${e.parentTitle}`:""}`)).join("\n\n")}\n\nRemember to:\n- Create intuitive categories that make sense for these specific bookmarks\n- Group similar content together\n- Consider existing folder names as hints for categorization\n- Use professional, clear category names\n- Ensure every bookmark is assigned to a category\n${n?"- Follow the custom instruction provided in the system prompt":""}\n\nReturn the organization as a JSON array.`;try{const t=(await s.generateText([{role:"system",content:a},{role:"user",content:i}],{temperature:.3,maxTokens:4e3})).textContent||"[]",r=t.match(/```(?:json)?\s*([\s\S]*?)\s*```/)||t.match(/(\[[\s\S]*\])/),n=r?r[1]:t;try{const t=JSON.parse(n);return this.validateCategorization(t,e)}catch(e){throw console.error("[organize_bookmarks] Failed to parse LLM response:",e),new Error("Failed to parse categorization from AI response")}}catch(e){throw new Error(`LLM categorization failed: ${e instanceof Error?e.message:String(e)}`)}}validateCategorization(e,t){const r=new Set(t.map((e=>e.id))),n=new Set,s=e.map((e=>{const s={category:e.category||"Uncategorized",subcategories:Array.isArray(e.subcategories)?e.subcategories:[],count:0,bookmarks:[]};return Array.isArray(e.bookmarks)&&(s.bookmarks=e.bookmarks.filter((e=>{if(e.id&&r.has(e.id)&&!n.has(e.id)){n.add(e.id);if(t.find((t=>t.id===e.id)))return!0}return!1})).map((e=>({id:e.id,title:t.find((t=>t.id===e.id)).title,url:t.find((t=>t.id===e.id)).url,category:s.category,subcategory:e.subcategory||void 0})))),s.count=s.bookmarks.length,s})).filter((e=>e.count>0)),a=t.filter((e=>!n.has(e.id)));return a.length>0&&s.push({category:"Other",subcategories:[],count:a.length,bookmarks:a.map((e=>({id:e.id,title:e.title,url:e.url,category:"Other"})))}),s}async applyOrganization(e,t,r){let n=await this.findChildFolder(e,r);n||(n=await chrome.bookmarks.create({parentId:e,title:r}));let s=0;const a=[];for(const e of t){if(0===e.bookmarks.length)continue;let t=await this.findChildFolder(n.id,e.category);t||(t=await chrome.bookmarks.create({parentId:n.id,title:e.category}));const r=new Map;for(const n of e.subcategories){let e=await this.findChildFolder(t.id,n);e||(e=await chrome.bookmarks.create({parentId:t.id,title:n})),r.set(n,e)}const i=[];for(const n of e.bookmarks)try{const e=n.subcategory&&r.has(n.subcategory)?r.get(n.subcategory).id:t.id;await chrome.bookmarks.move(n.id,{parentId:e}),i.push(n),s++}catch(e){console.error(`Failed to move bookmark ${n.title}:`,e)}a.push({...e,bookmarks:i,count:i.length})}return{organizedCount:s,categories:a}}async getBookmarkBar(){const e=(await chrome.bookmarks.getTree())[0];for(const t of e.children||[])if("1"===t.id||"Bookmarks Bar"===t.title)return t;return null}async findChildFolder(e,t){return(await chrome.bookmarks.getChildren(e)).find((e=>!e.url&&e.title===t))||null}}Fk.DEFAULT_FOLDER_NAME="AI Bookmarks";const Dk=M.z.object({name:M.z.string().min(1),description:M.z.string().optional(),windowId:M.z.number().optional()}),zk=M.z.object({url:M.z.string(),title:M.z.string(),favIconUrl:M.z.string().optional(),index:M.z.number()}),Uk=M.z.object({id:M.z.string(),name:M.z.string(),description:M.z.string().optional(),tabs:M.z.array(zk),createdAt:M.z.string(),tabCount:M.z.number()}),Bk=M.z.object({success:M.z.boolean(),sessionId:M.z.string().optional(),sessionName:M.z.string().optional(),tabCount:M.z.number(),message:M.z.string()});class qk extends fm{constructor(e){super({name:"save_session",description:"Save all tabs in the current window as a named session for later restoration.",category:"sessions",version:"1.0.0",inputSchema:Dk,outputSchema:Bk,examples:[{description:"Save current tabs as a work session",input:{name:"Morning Work Session",description:"Email, calendar, and project docs"},output:{success:!0,sessionId:"sess_123abc",sessionName:"Morning Work Session",tabCount:5,message:'Successfully saved session "Morning Work Session" with 5 tabs'}}],streamingConfig:{displayName:"Save Session",icon:"šŸ’¾",progressMessage:"Saving current session..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.name;return r?`Saving session "${r}"...`:"Saving current session..."}catch{return"Saving current session..."}}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;const t=e.tabCount,r=1===t?"tab":"tabs";return`šŸ’¾ Saved "${e.sessionName}" with ${t} ${r}`}async execute(e){try{let t=e.windowId;if(!t)try{t=(await this.browserContext.getCurrentWindow()).id}catch(e){return console.error("[save_session] Error getting current window:",e),{success:!1,tabCount:0,message:"Error getting current window"}}const r=await chrome.tabs.query({windowId:t});if(0===r.length)return{success:!1,tabCount:0,message:"No tabs found in the specified window"};const n=r.filter((e=>e.url&&e.title)).map(((e,t)=>({url:e.url,title:e.title,favIconUrl:e.favIconUrl,index:e.index??t}))),s=`sess_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,a={id:s,name:e.name,description:e.description,tabs:n,createdAt:(new Date).toISOString(),tabCount:n.length};return await this.saveSession(a),{success:!0,sessionId:s,sessionName:e.name,tabCount:n.length,message:`Successfully saved session "${e.name}" with ${n.length} tab(s)`}}catch(e){return console.error("[save_session] Error:",e),{success:!1,tabCount:0,message:`Error saving session: ${e instanceof Error?e.message:String(e)}`}}}async saveSession(e){try{const t=await chrome.storage.local.get([qk.STORAGE_KEY]),r=[e,...t[qk.STORAGE_KEY]||[]];await chrome.storage.local.set({[qk.STORAGE_KEY]:r})}catch(e){throw new Error(`Failed to save session to storage: ${e instanceof Error?e.message:String(e)}`)}}}qk.STORAGE_KEY="nxtscape_sessions";const Kk=M.z.object({limit:M.z.number().positive().optional(),sortBy:M.z.enum(["name","createdAt","tabCount"]).optional()}),Wk=M.z.object({id:M.z.string(),name:M.z.string(),description:M.z.string().optional(),tabCount:M.z.number(),createdAt:M.z.string(),previewTabs:M.z.array(M.z.object({title:M.z.string(),url:M.z.string()})).optional()}),Hk=M.z.object({success:M.z.boolean(),sessions:M.z.array(Wk),totalCount:M.z.number(),message:M.z.string()});class Vk extends fm{constructor(e){super({name:"list_sessions",description:"List all saved browser sessions with their names, descriptions, and tab counts.",category:"sessions",version:"1.0.0",inputSchema:Kk,outputSchema:Hk,examples:[{description:"List all saved sessions",input:{sortBy:"createdAt"},output:{success:!0,sessions:[{id:"sess_123",name:"Morning Work",description:"Daily work tabs",tabCount:5,createdAt:new Date,previewTabs:[{title:"Gmail",url:"https://gmail.com"},{title:"Calendar",url:"https://calendar.google.com"}]}],totalCount:1,message:"Found 1 saved session"}}],streamingConfig:{displayName:"List Sessions",icon:"šŸ“‹",progressMessage:"Loading saved sessions..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.limit;return r?`Loading ${r} most recent sessions...`:"Loading saved sessions..."}catch{return"Loading saved sessions..."}}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;if(0===e.sessions.length)return"šŸ“‹ No saved sessions found";const t=1===e.sessions.length?"session":"sessions";let r=`šŸ“‹ Found ${e.sessions.length} ${t}:\n\n`;return e.sessions.forEach(((e,t)=>{const n=new Date(e.createdAt).toLocaleDateString(),s=1===e.tabCount?"tab":"tabs";r+=`${t+1}. **${e.name}** (${e.tabCount} ${s}) - ${n}\n`,e.description&&(r+=` ${e.description}\n`),e.previewTabs&&e.previewTabs.length>0&&(r+=` Preview: ${e.previewTabs.map((e=>e.title)).join(", ")}\n`),r+="\n"})),r.trim()}async execute(e){try{const t=await this.loadSessions();if(0===t.length)return{success:!0,sessions:[],totalCount:0,message:"No saved sessions found"};const r=this.sortSessions(t,e.sortBy||"createdAt"),n=(e.limit?r.slice(0,e.limit):r).map((e=>({id:e.id,name:e.name,description:e.description,tabCount:e.tabCount,createdAt:e.createdAt,previewTabs:e.tabs.slice(0,3).map((e=>({title:e.title,url:e.url})))}))),s=1===n.length?"session":"sessions",a=e.limit&&t.length>e.limit?`Found ${n.length} of ${t.length} sessions`:`Found ${n.length} ${s}`;return{success:!0,sessions:n,totalCount:t.length,message:a}}catch(e){return console.error("[list_sessions] Error:",e),{success:!1,sessions:[],totalCount:0,message:`Error listing sessions: ${e instanceof Error?e.message:String(e)}`}}}async loadSessions(){try{const e=await chrome.storage.local.get([Vk.STORAGE_KEY]);return(e[Vk.STORAGE_KEY]||[]).map((e=>{try{return Uk.parse(e)}catch(e){return console.warn("[list_sessions] Invalid session found, skipping:",e),null}})).filter((e=>null!==e))}catch(e){throw new Error(`Failed to load sessions from storage: ${e instanceof Error?e.message:String(e)}`)}}sortSessions(e,t){return[...e].sort(((e,r)=>{switch(t){case"name":return e.name.localeCompare(r.name);case"tabCount":return r.tabCount-e.tabCount;default:return new Date(r.createdAt).getTime()-new Date(e.createdAt).getTime()}}))}}Vk.STORAGE_KEY="nxtscape_sessions";const Gk=M.z.object({sessionId:M.z.string().min(1),newWindow:M.z.boolean().optional(),focusWindow:M.z.boolean().optional()}),Jk=M.z.object({success:M.z.boolean(),sessionName:M.z.string().optional(),tabsOpened:M.z.number(),windowId:M.z.number().optional(),failedTabs:M.z.array(M.z.object({url:M.z.string(),title:M.z.string(),error:M.z.string()})).optional(),message:M.z.string()});class Zk extends fm{constructor(e){super({name:"resume_session",description:"Resume a saved session by opening all its tabs. By default opens in a new window.",category:"sessions",version:"1.0.0",inputSchema:Gk,outputSchema:Jk,examples:[{description:"Resume a session in a new window",input:{sessionId:"sess_123abc",newWindow:!0},output:{success:!0,sessionName:"Morning Work Session",tabsOpened:5,windowId:2,message:'Successfully resumed "Morning Work Session" with 5 tabs in new window'}}],streamingConfig:{displayName:"Resume Session",icon:"šŸ”„",progressMessage:"Resuming session..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.sessionId;return r?`Resuming session ${r}...`:"Resuming session..."}catch{return"Resuming session..."}}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;const t=1===e.tabsOpened?"tab":"tabs";let r=`šŸ”„ Resumed "${e.sessionName}" with ${e.tabsOpened} ${t}`;if(e.failedTabs&&e.failedTabs.length>0){const t=e.failedTabs.length;r+=` (${t} ${1===t?"tab":"tabs"} failed to open)`}return r}async execute(e){try{const t=await this.loadSession(e.sessionId);if(!t)return{success:!1,tabsOpened:0,message:`Session with ID ${e.sessionId} not found`};if(0===t.tabs.length)return{success:!1,sessionName:t.name,tabsOpened:0,message:`Session "${t.name}" has no tabs to open`};let r;const n=e.newWindow??!0,s=e.focusWindow??!0;if(n){const e=t.tabs[0],n=await chrome.windows.create({url:e.url,focused:s});if(!n?.id)throw new Error("Failed to create new window");r=n.id}else{const e=await chrome.tabs.getCurrent();if(e?.windowId)r=e.windowId;else{const e=(await chrome.windows.getAll({populate:!1})).find((e=>e.focused));if(!e?.id)throw new Error("Could not determine target window");r=e.id}}const a=n?t.tabs.slice(1):t.tabs,i=[];let o=n?1:0;for(const e of a)try{await chrome.tabs.create({windowId:r,url:e.url,active:!1}),o++}catch(t){console.warn("[resume_session] Failed to open tab:",e.url,t),i.push({url:e.url,title:e.title,error:t instanceof Error?t.message:String(t)})}if(s&&r)try{await chrome.windows.update(r,{focused:!0})}catch(e){console.warn("[resume_session] Failed to focus window:",e)}const c=t.tabs.length,l=i.length>0;return{success:o>0,sessionName:t.name,tabsOpened:o,windowId:r,failedTabs:l?i:void 0,message:l?`Resumed "${t.name}" with ${o}/${c} tabs (${i.length} failed)`:`Successfully resumed "${t.name}" with ${o} tab(s)`}}catch(e){return console.error("[resume_session] Error:",e),{success:!1,tabsOpened:0,message:`Error resuming session: ${e instanceof Error?e.message:String(e)}`}}}async loadSession(e){try{const t=await chrome.storage.local.get([Zk.STORAGE_KEY]),r=(t[Zk.STORAGE_KEY]||[]).find((t=>t.id===e));if(!r)return null;try{return Uk.parse(r)}catch(e){return console.warn("[resume_session] Invalid session data found:",e),null}}catch(e){throw new Error(`Failed to load session from storage: ${e instanceof Error?e.message:String(e)}`)}}}Zk.STORAGE_KEY="nxtscape_sessions";const Xk=M.z.object({sessionIds:M.z.array(M.z.string()).min(1),confirmDelete:M.z.boolean().optional()}),Yk=M.z.object({success:M.z.boolean(),deletedCount:M.z.number(),notFoundCount:M.z.number(),deletedSessions:M.z.array(M.z.object({id:M.z.string(),name:M.z.string()})).optional(),notFoundIds:M.z.array(M.z.string()).optional(),message:M.z.string()});class Qk extends fm{constructor(e){super({name:"delete_sessions",description:"Delete one or multiple saved browser sessions by their IDs.",category:"sessions",version:"1.0.0",inputSchema:Xk,outputSchema:Yk,examples:[{description:"Delete a single session",input:{sessionIds:["sess_123abc"],confirmDelete:!0},output:{success:!0,deletedCount:1,notFoundCount:0,deletedSessions:[{id:"sess_123abc",name:"Morning Work Session"}],message:"Successfully deleted 1 session"}},{description:"Delete multiple sessions",input:{sessionIds:["sess_123abc","sess_456def"],confirmDelete:!0},output:{success:!0,deletedCount:2,notFoundCount:0,deletedSessions:[{id:"sess_123abc",name:"Morning Work Session"},{id:"sess_456def",name:"Research Project"}],message:"Successfully deleted 2 sessions"}}],streamingConfig:{displayName:"Delete Sessions",icon:"šŸ—‘ļø",progressMessage:"Deleting sessions..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.sessionIds;if(r&&Array.isArray(r)){const e=r.length;return`Deleting ${e} ${1===e?"session":"sessions"}...`}return"Deleting sessions..."}catch{return"Deleting sessions..."}}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;const t=1===e.deletedCount?"session":"sessions";let r=`šŸ—‘ļø Deleted ${e.deletedCount} ${t}`;if(e.notFoundCount>0){const t=1===e.notFoundCount?"session":"sessions";r+=` (${e.notFoundCount} ${t} not found)`}return r}async execute(e){try{if(!(e.confirmDelete??!0))return{success:!1,deletedCount:0,notFoundCount:0,message:"Deletion cancelled - confirmDelete was false"};const t=await this.loadSessions();if(0===t.length)return{success:!1,deletedCount:0,notFoundCount:e.sessionIds.length,notFoundIds:e.sessionIds,message:"No sessions found to delete"};const r=[],n=[];for(const s of e.sessionIds){const e=t.find((e=>e.id===s));e?r.push({id:e.id,name:e.name}):n.push(s)}if(0===r.length)return{success:!1,deletedCount:0,notFoundCount:n.length,notFoundIds:n,message:`No sessions found with the provided IDs: ${e.sessionIds.join(", ")}`};const s=t.filter((t=>!e.sessionIds.includes(t.id)));await this.saveSessions(s);const a=r.length,i=n.length;let o=`Successfully deleted ${a} session${1===a?"":"s"}`;return i>0&&(o+=` (${i} not found)`),{success:!0,deletedCount:a,notFoundCount:i,deletedSessions:r,notFoundIds:i>0?n:void 0,message:o}}catch(e){return console.error("[delete_sessions] Error:",e),{success:!1,deletedCount:0,notFoundCount:0,message:`Error deleting sessions: ${e instanceof Error?e.message:String(e)}`}}}async loadSessions(){try{const e=await chrome.storage.local.get([Qk.STORAGE_KEY]);return(e[Qk.STORAGE_KEY]||[]).map((e=>{try{return Uk.parse(e)}catch(e){return console.warn("[delete_sessions] Invalid session found, skipping:",e),null}})).filter((e=>null!==e))}catch(e){throw new Error(`Failed to load sessions from storage: ${e instanceof Error?e.message:String(e)}`)}}async saveSessions(e){try{await chrome.storage.local.set({[Qk.STORAGE_KEY]:e})}catch(e){throw new Error(`Failed to save sessions to storage: ${e instanceof Error?e.message:String(e)}`)}}}Qk.STORAGE_KEY="nxtscape_sessions";const eS=M.z.object({reason:M.z.string().optional()}),tS=M.z.object({success:M.z.boolean(),action:M.z.literal("skipped"),reason:M.z.string().optional(),message:M.z.string()});class rS extends fm{constructor(e){super({name:"noop",description:"Skip an action when it is unnecessary, redundant, or already completed. Use this when an instruction does not require any action.",category:"control",version:"1.0.0",inputSchema:eS,outputSchema:tS,examples:[{description:"Skip an action without a reason",input:{},output:{success:!0,action:"skipped",message:"Action skipped (no operation performed)."}},{description:"Skip an action with a reason",input:{reason:"Page is already loaded"},output:{success:!0,action:"skipped",reason:"Page is already loaded",message:"Action skipped (no operation performed). Reason: Page is already loaded"}}],streamingConfig:{displayName:"No Operation",icon:"ā­ļø",progressMessage:"Skipping action..."}},e)}formatDisplayResult(e){return e.reason?`ā­ļø Skipped action - ${e.reason}`:"ā­ļø Skipped unnecessary action"}async execute(e){const t=e.reason?` Reason: ${e.reason}`:"";return{success:!0,action:"skipped",reason:e.reason,message:`Action skipped (no operation performed).${t}`}}}const nS=M.z.object({success:M.z.boolean(),reason:M.z.string().optional()}),sS=M.z.object({success:M.z.boolean(),action:M.z.literal("terminate"),status:M.z.enum(["SUCCESS","FAILED"]),reason:M.z.string().optional(),message:M.z.string()});class aS extends fm{constructor(e){super({name:"terminate",description:"Terminate the current task. Use this when the task is complete (success: true) or when you cannot proceed further (success: false). Always provide a reason.",category:"control",version:"1.0.0",inputSchema:nS,outputSchema:sS,examples:[{description:"Terminate with success",input:{success:!0,reason:"Task completed successfully"},output:{success:!0,action:"terminate",status:"SUCCESS",reason:"Task completed successfully",message:"TASK SUCCESS - Task completed successfully"}},{description:"Terminate with failure",input:{success:!1,reason:"Unable to find the required element"},output:{success:!1,action:"terminate",status:"FAILED",reason:"Unable to find the required element",message:"TASK FAILED - Unable to find the required element"}}],streamingConfig:{displayName:"Terminate",icon:"šŸ",progressMessage:"Terminating task..."}},e)}formatDisplayResult(e){return"SUCCESS"===e.status?"šŸ Task completed successfully"+(e.reason?` - ${e.reason}`:""):"šŸ’„ Task failed"+(e.reason?` - ${e.reason}`:"")}async execute(e){const t=e.success?"SUCCESS":"FAILED",r=e.reason?` - ${e.reason}`:"";return{success:e.success,action:"terminate",status:t,reason:e.reason,message:`TASK ${t}${r}`}}}const iS=M.z.object({instruction:M.z.string(),focus:M.z.string().optional()}),oS=M.z.object({success:M.z.boolean(),summary:M.z.string(),content_length:M.z.number(),summary_length:M.z.number(),message:M.z.string()});class cS extends fm{constructor(e){super({name:"summarize",description:"Summarize the content of the current page using accessible tree extraction and LLM. Takes custom instructions for how to analyze and present the content with markdown formatting and emojis.",category:"observation",version:"1.0.0",inputSchema:iS,outputSchema:oS,examples:[{description:"Quick overview with emojis",input:{instruction:"Give me a quick overview with key points"},output:{success:!0,summary:"šŸ“„ **Page Overview**\n\nThis page contains information about browser automation tools...",content_length:5420,summary_length:180,message:"Generated summary based on instruction"}},{description:"Detailed analysis focused on specific content",input:{instruction:"Analyze the main features in detail",focus:"product features"},output:{success:!0,summary:"šŸš€ **Product Features Analysis**\n\n### Main Features:\n1. šŸ¤– Automated browsing...",content_length:8932,summary_length:420,message:"Generated detailed analysis focused on product features"}}],streamingConfig:{displayName:"Summarize Content",icon:"šŸ“„",progressMessage:"Extracting and summarizing page content..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.instruction,n=t?.focus;return r&&n?`Following instruction: "${r}" focused on "${n}"`:r?`Following instruction: "${r}"`:"Extracting and summarizing page content..."}catch{return"Extracting and summarizing page content..."}}formatDisplayResult(e){return e.success?e.summary:`āŒ ${e.message}`}async execute(e){try{const t=(await this.browserContext.getCurrentPage()).getPuppeteerPage(),r=!0,n=await t.accessibility.snapshot({interestingOnly:r});if(!n)return{success:!1,summary:"",content_length:0,summary_length:0,message:"Failed to extract accessibility tree from page"};const s=this.extractMainContent(n);if(!s||0===s.trim().length)return{success:!1,summary:"",content_length:0,summary_length:0,message:"No meaningful content found on the page"};const a=await this.generateSummary(s,e.instruction,e.focus);return{success:!0,summary:a,content_length:s.length,summary_length:a.length,message:`Generated summary based on instruction (${s.length} → ${a.length} chars)`}}catch(e){return{success:!1,summary:"",content_length:0,summary_length:0,message:`Unable to summarize content: ${e instanceof Error?e.message:String(e)}`}}}extractMainContent(e){const t=[],r=(e,n=0)=>{if(!e)return;const s=e.role?.toLowerCase(),a=e.name?.trim(),i=e.description?.trim();if(a&&a.length>2&&(this.isContentRole(s)?t.push(a):this.isMetaContentRole(s)&&(this.isIgnorableText(a)||t.push(a))),i&&i!==a&&i.length>5&&(this.isIgnorableText(i)||t.push(i)),e.value&&"string"==typeof e.value){const r=e.value.trim();r.length>2&&!this.isIgnorableText(r)&&t.push(r)}e.children&&Array.isArray(e.children)&&e.children.forEach((e=>r(e,n+1)))};r(e);return t.join(" ").replace(/\s+/g," ").replace(/\s*[,;]\s*/g,", ").trim()}isContentRole(e){if(!e)return!1;return["article","main","section","paragraph","text","heading","listitem","definition","term","cell","columnheader","rowheader","statictext"].some((t=>e.includes(t)))}isMetaContentRole(e){if(!e)return!1;return["link","button","menuitem","tab","option","listbox","combobox","textbox","searchbox","spinbutton"].some((t=>e.includes(t)))}isIgnorableText(e){return[/^(menu|nav|navigation|header|footer|sidebar|toolbar)$/i,/^(home|about|contact|login|logout|sign in|sign up|register)$/i,/^(click|tap|press|button|link|search|submit|cancel|close|open)$/i,/^(more|less|show|hide|toggle|expand|collapse|next|previous|prev)$/i,/^(back|forward|up|down|left|right|top|bottom)$/i,/^(username|password|email|search|query)$/i,/^\d+$/,/^[^\w]+$/,/^.{1,2}$/,/^(ok|yes|no|on|off|true|false)$/i,/^(loading|please wait|wait)$/i,/^(share|like|follow|subscribe|ad|advertisement|sponsored)$/i,/^(privacy|terms|cookies|policy|legal)$/i].some((t=>t.test(e)))}async generateSummary(e,t,r){const n=Rk.createClaudeProvider();let s=`Content to analyze:\n\n${e}\n\n`;s+=`Instruction: ${t}\n\n`,r&&(s+=`Please focus specifically on: ${r}\n\n`),s+="Please provide your analysis following the formatting guidelines above.";const a=e.length>8e3?e.substring(0,8e3)+"...[content truncated]":e,i=s.replace(e,a);try{return(await n.generateText([{role:"system",content:"You are an expert content summarizer and analyst. Create engaging, well-formatted summaries based on user instructions.\n\n**FORMATTING GUIDELINES:**\n- Use **markdown formatting** for structure and readability\n- Add relevant **emojis** to make content more engaging and scannable\n- Use **headings (##, ###)** to organize information\n- Use **bullet points** or **numbered lists** for key points\n- Use **bold** and *italics* for emphasis\n- Create clear, scannable content that's easy to read\n\n**STYLE GUIDELINES:**\n- Be concise but informative\n- Focus on the most important and relevant information\n- Use active voice and clear language\n- Structure information logically\n- Include relevant context when helpful\n\nFollow the user's specific instruction for analysis depth and focus."},{role:"user",content:i}],{temperature:.4,maxTokens:8e3})).textContent||"Failed to generate summary"}catch(e){throw new Error(`LLM summarization failed: ${e instanceof Error?e.message:String(e)}`)}}}class lS extends hm{constructor(e){super(e)}async initialize(){await super.initialize()}createToolRegistry(){const e=new gm;return e.registerAll([new vm(this.browserContext),new Sm(this.browserContext),new Tm(this.browserContext),new Om(this.browserContext),new Mm(this.browserContext),new cS(this.browserContext),new rS(this.browserContext),new aS(this.browserContext),new qk(this.browserContext),new Vk(this.browserContext),new Zk(this.browserContext),new Qk(this.browserContext),new Nm(this.browserContext),new Fk(this.browserContext)]),e}createTools(){const e=this.getToolRegistry();if(!e)throw new Error("Tool registry not available during tool creation");return e.getLangChainTools()}getDefaultSystemPrompt(){const e=this.getToolRegistry();return"You are a Nxtscape Productivity Assistant specialized in browser tab management and content analysis.\n\n## YOUR MISSION\nHelp users organize, manage, and optimize their browser tabs for better productivity.\nYou can list tabs, close unwanted tabs, switch between tabs, create new tabs, group related tabs, summarize page content, save/resume browsing sessions, manage bookmarks, and optimize browser workflow.\n\n## COMMUNICATION STYLE\n- **Be concise**: Use short, clear sentences\n- **Be direct**: State what you're doing without excessive explanation\n- **Be human**: Use natural language, not technical jargon\n- **Be minimal**: Only mention essential information\n- **Example**: Instead of 'I'll help you close all Google tabs. Let me first list all tabs to identify the Google ones.', just say 'Checking for Google tabs...'\n\n"+(e?.generateSystemPrompt()||"")+"\n\n## WORKFLOW GUIDELINES\n\n### For Tab Management Tasks:\n1. **Always start with list_tabs** to understand the current workspace\n2. **Analyze the user's request** and identify the most appropriate action\n3. **Use specific tab IDs** from list_tabs results for precise operations\n4. **Keep feedback brief** - just confirm what was done\n\n### For Content Summarization:\n1. Use the **summarize tool** with clear instructions based on user needs\n2. **Instruction examples:**\n - 'Give me a quick overview with key points'\n - 'Analyze this in detail with main features'\n - 'Summarize the article focusing on benefits'\n - 'Extract key information for decision making'\n3. Optionally specify a **focus area** (e.g., 'product features', 'main article')\n4. The tool uses accessibility tree for clean content extraction\n5. Results are formatted with markdown and emojis for clarity\n\n### For Grouping Tabs:\n1. Call list_tabs to see all open tabs\n2. Analyze tabs to identify grouping criteria:\n - Domain similarity (e.g., all google.com tabs)\n - Topic similarity (e.g., all documentation tabs)\n - User's intent (e.g., 'group my work tabs')\n3. Extract tab_id numbers for tabs to group\n4. Choose meaningful group name and color\n5. Call group_tabs with the selected tabs\n\n### For Closing Tabs:\n1. Call list_tabs to see what's available\n2. Identify tabs to close based on user request\n3. Use close_tabs with specific tab IDs\n4. Confirm the action was completed\n\n### For Session Management:\n1. **Saving Sessions**: Use save_session with meaningful name and description\n - Example: { name: 'React Project Research', description: 'Documentation and tutorials for React hooks' }\n - Saves all tabs in current window automatically\n - **If user doesn't provide a name**: Create one based on tab content (e.g., 'GitHub Development', 'AWS Console Work', 'Research Articles')\n - Look at domains and titles to infer the session purpose\n2. **Listing Sessions**: Use list_sessions to show all saved sessions\n - Shows session names, tab counts, creation dates, and preview tabs\n - Can sort by name, date, or tab count\n3. **Resuming Sessions**: Use resume_session with session ID\n - Opens all session tabs in new window by default\n - Can specify newWindow: false to open in current window\n - Handles failed tab opens gracefully\n4. **Deleting Sessions**: Use delete_sessions with session IDs\n - Can delete single or multiple sessions at once\n - Requires session IDs from list_sessions output\n - Confirmation is optional (defaults to true)\n\n### For Bookmark Management:\n1. **Saving Bookmarks**: Use save_bookmark to organize URLs in structured folders\n - **Auto-organization**: Creates 'AI Bookmarks' folder on bookmark bar\n - **Categories**: Suggest appropriate categories based on content:\n - 'Research' for academic/technical articles\n - 'Tools' for web applications and utilities\n - 'Documentation' for API docs, guides, tutorials\n - 'Articles' for blog posts and news\n - 'Resources' for reference materials\n - 'Projects' for project-related links\n - **Subcategories**: Add depth when appropriate (e.g., Research > AI Papers)\n - **Smart defaults**: If no URL provided, bookmarks current tab\n - **Metadata**: Can add tags and notes for better organization\n2. **Organizing Existing Bookmarks**: Use organize_bookmarks to clean up bookmark bar\n - **AI-powered categorization**: Uses LLM to intelligently analyze and categorize bookmarks\n - **Custom instructions**: Pass specific organization instructions:\n - 'Organize by project type' - Groups by project categories\n - 'Create work and personal folders only' - Simple two-category split\n - 'Group by technology stack' - Technical categorization\n - 'Organize by frequency of use' - Usage-based organization\n - **Flexible options**:\n - instruction: Custom organization instruction (optional)\n - targetFolder: Folder name to organize into (default: 'AI Bookmarks')\n - dryRun: Preview organization before applying (default: false)\n - maxCategories: Maximum number of main categories (default: 8)\n - includeSubcategories: Whether to create subcategories (default: true)\n - **Smart folder structure**: Creates up to 2 levels (categories and subcategories)\n - **Automatic grouping**: AI groups similar websites based on instruction\n3. **Examples**:\n - Basic save: { category: 'Tools' }\n - Detailed save: { category: 'Research', subcategory: 'Machine Learning', tags: ['nlp', 'transformers'], notes: 'Great paper on attention mechanisms' }\n - Preview with instruction: { instruction: 'Organize by project type', dryRun: true }\n - Custom folder: { instruction: 'Create work and personal only', targetFolder: 'My Bookmarks', maxCategories: 2 }\n - Simple organization: { maxCategories: 5, includeSubcategories: false }\n4. **Best Practices**:\n - Always run organize_bookmarks with dryRun: true first to preview\n - Provide clear instructions for better organization results\n - Use targetFolder to organize into custom locations\n - Let AI adapt categories based on your specific instruction\n - For simple organization, set includeSubcategories: false\n\n### Interpreting Bookmark Organization Requests:\nWhen users ask to organize bookmarks, extract their intent and convert to proper instruction:\n- 'organize my bookmarks' → Use default AI categorization\n- 'organize bookmarks by work and personal' → { instruction: 'Create work and personal categories only', maxCategories: 2 }\n- 'organize into Projects folder' → { targetFolder: 'Projects' }\n- 'organize by programming language' → { instruction: 'Group by programming language and technology' }\n- 'simple organization, no subfolders' → { includeSubcategories: false }\n- 'organize into 3 main categories' → { maxCategories: 3 }\n- 'preview organization first' → { dryRun: true }\n\n## SUMMARIZATION INSTRUCTION EXAMPLES:\nWhen using the summarize tool, provide clear, specific instructions:\n- **Quick overviews**: 'Give me a quick overview with main points'\n- **Detailed analysis**: 'Provide detailed analysis with structure and examples'\n- **Focused summaries**: 'Summarize focusing on [specific aspect]'\n- **Decision support**: 'Extract key information to help me decide'\n- **Learning**: 'Explain the main concepts and how they work'\n\n## COLOR GUIDELINES FOR GROUPING:\n- **Blue**: General/default groups\n- **Red**: Important/urgent content\n- **Green**: Completed/reference material\n- **Yellow**: In-progress/needs attention\n- **Purple**: Personal content\n- **Orange**: Work/professional content\n- **Grey**: Archive/less important\n\n## IMPORTANT NOTES:\n- Always use tab IDs from list_tabs for precise operations\n- Be smart about understanding user intent\n- For summaries, craft specific instructions based on user context\n- Group names should be concise but descriptive\n- Always terminate with success/failure status and clear reason\n- Focus on productivity and organization benefits\n\n## RESPONSE EXAMPLES:\n**Tab Management:**\nāŒ BAD: 'I'll help you close all Google tabs. Let me first list all tabs to identify the Google ones. I found several Google-related tabs. Let me identify and close them.'\nāœ… GOOD: 'Found 4 Google tabs. Closing them now.'\n\nāŒ BAD: 'I've successfully completed the task of closing all the Google-related tabs as requested.'\nāœ… GOOD: 'Done. Closed 4 Google tabs.'\n\n**Session Management:**\nāŒ BAD: 'I'll save your current browsing session. Let me capture all the tabs you have open and store them for later retrieval.'\nāœ… GOOD: 'Saving current session as \"Research Project\"...'\n\nāŒ BAD: 'I found your saved session and I'll now restore all the tabs from that session in a new window for you.'\nāœ… GOOD: 'Resuming \"Morning Work\" session with 8 tabs.'\n\nāŒ BAD: 'I will now delete the sessions you requested. Let me remove them from storage for you.'\nāœ… GOOD: 'Deleting 2 sessions...'\n\n**Bookmark Management:**\nāŒ BAD: 'I'll bookmark this page for you. Let me save it to your bookmarks with an appropriate category.'\nāœ… GOOD: 'Bookmarking to Research > AI Papers...'\n\nāŒ BAD: 'I've successfully saved the bookmark to the AI Bookmarks folder under the Tools category.'\nāœ… GOOD: 'Saved to AI Bookmarks > Tools'\n\nāŒ BAD: 'I'll organize your bookmarks now. Let me analyze them and create a good folder structure.'\nāœ… GOOD: 'Organizing bookmarks by project type...'\n\nRemember: Keep it simple, direct, and human-friendly. Users want results, not explanations."}getAgentName(){return"ProductivityAgent"}getInitializationMessage(){return"šŸš€ Initializing productivity agent..."}}class uS{constructor(){this.variables={}}setVariable(e,t){this.variables[e]=t}getVariable(e){return this.variables[e]}resolveInput(e){if(void 0!==e)return Array.isArray(e)?e.map((e=>this.getVariable(e))):this.getVariable(e)}getAllVariables(){return{...this.variables}}hasVariable(e){return e in this.variables}createChild(){const e=new uS;return Object.assign(e.variables,this.variables),e}}var dS=s(7765);function hS(e,t){if(void 0===e.function)return;let r;if(t?.partial)try{r=(0,jr.d)(e.function.arguments??"{}")}catch(e){return}else try{r=JSON.parse(e.function.arguments)}catch(t){throw new Yt([`Function "${e.function.name}" arguments:`,"",e.function.arguments,"","are not valid JSON.",`Error: ${t.message}`].join("\n"))}const n={name:e.function.name,args:r,type:"tool_call"};return t?.returnId&&(n.id=e.id),n}function pS(e){if(void 0===e.id)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}}function mS(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:"invalid_tool_call"}}class fS extends kr{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?.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){const r=e[0].message;let n;if((0,dS.KX)(r)&&r.tool_calls?.length)n=r.tool_calls.map((e=>{const{id:t,...r}=e;return this.returnId?{id:t,...r}:r}));else if(void 0!==r.additional_kwargs.tool_calls){n=JSON.parse(JSON.stringify(r.additional_kwargs.tool_calls)).map((e=>hS(e,{returnId:this.returnId,partial:t})))}if(!n)return[];const s=[];for(const e of n)if(void 0!==e){const t={type:e.name,args:e.args,id:e.id};s.push(t)}return s}}class gS extends fS{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){if(void 0===this.zodSchema)return e;const t=await this.zodSchema.safeParseAsync(e);if(t.success)return t.data;throw new Yt(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error.errors)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){const t=(await super.parsePartialResult(e)).filter((e=>e.type===this.keyName));let r=t;if(t.length)return this.returnId||(r=t.map((e=>e.args))),this.returnSingle?r[0]:r}async parseResult(e){const t=(await super.parsePartialResult(e,!1)).filter((e=>e.type===this.keyName));let r=t;if(!t.length)return;if(this.returnId||(r=t.map((e=>e.args))),this.returnSingle)return this._validateResult(r[0]);const n=await Promise.all(r.map((e=>this._validateResult(e))));return n}}function yS(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function bS(e,t,r,n,s){e[t]=r,yS(e,t,n,s)}function wS(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(((r,n)=>wS(e,t,r)))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return vS(e,t)}}const vS=(e,t)=>{const r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(const n of e.checks)switch(n.kind){case"min":bS(r,"minimum",n.value,n.message,t);break;case"max":bS(r,"maximum",n.value,n.message,t)}return r};let _S;const kS=/^[cC][^\s-]{8,}$/,SS=/^[0-9a-z]+$/,ES=/^[0-9A-HJKMNP-TV-Z]{26}$/,xS=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,TS=()=>(void 0===_S&&(_S=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),_S),CS=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,PS=/^[a-zA-Z0-9_-]{21}$/;function OS(e,t){const r={type:"string"};function n(e){return"escape"===t.patternStrategy?AS(e):e}if(e.checks)for(const s of e.checks)switch(s.kind){case"min":bS(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,s.value):s.value,s.message,t);break;case"max":bS(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,s.value):s.value,s.message,t);break;case"email":switch(t.emailStrategy){case"format:email":IS(r,"email",s.message,t);break;case"format:idn-email":IS(r,"idn-email",s.message,t);break;case"pattern:zod":MS(r,xS,s.message,t)}break;case"url":IS(r,"uri",s.message,t);break;case"uuid":IS(r,"uuid",s.message,t);break;case"regex":MS(r,s.regex,s.message,t);break;case"cuid":MS(r,kS,s.message,t);break;case"cuid2":MS(r,SS,s.message,t);break;case"startsWith":MS(r,RegExp(`^${n(s.value)}`),s.message,t);break;case"endsWith":MS(r,RegExp(`${n(s.value)}$`),s.message,t);break;case"datetime":IS(r,"date-time",s.message,t);break;case"date":IS(r,"date",s.message,t);break;case"time":IS(r,"time",s.message,t);break;case"duration":IS(r,"duration",s.message,t);break;case"length":bS(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,s.value):s.value,s.message,t),bS(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,s.value):s.value,s.message,t);break;case"includes":MS(r,RegExp(n(s.value)),s.message,t);break;case"ip":"v6"!==s.version&&IS(r,"ipv4",s.message,t),"v4"!==s.version&&IS(r,"ipv6",s.message,t);break;case"emoji":MS(r,TS,s.message,t);break;case"ulid":MS(r,ES,s.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":IS(r,"binary",s.message,t);break;case"contentEncoding:base64":bS(r,"contentEncoding","base64",s.message,t);break;case"pattern:zod":MS(r,CS,s.message,t)}break;case"nanoid":MS(r,PS,s.message,t)}return r}const AS=e=>Array.from(e).map((e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`)).join(""),IS=(e,t,r,n)=>{e.format||e.anyOf?.some((e=>e.format))?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):bS(e,"format",t,r,n)},MS=(e,t,r,n)=>{e.pattern||e.allOf?.some((e=>e.pattern))?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:RS(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):bS(e,"pattern",RS(t,n),r,n)},RS=(e,t)=>{const r="function"==typeof e?e():e;if(!t.applyRegexFlags||!r.flags)return r.source;const n=r.flags.includes("i"),s=r.flags.includes("m"),a=r.flags.includes("s"),i=n?r.source.toLowerCase():r.source;let o="",c=!1,l=!1,u=!1;for(let e=0;e({...r,[n]:zS(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??{}})),{}),additionalProperties:!1};const r={type:"object",additionalProperties:zS(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===M.kY.ZodString&&e.keyType._def.checks?.length){const n=Object.entries(OS(e.keyType._def,t)).reduce(((e,[t,r])=>"type"===t?e:{...e,[t]:r}),{});return{...r,propertyNames:n}}return e.keyType?._def.typeName===M.kY.ZodEnum?{...r,propertyNames:{enum:e.keyType._def.values}}:r}const NS={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const $S=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map(((e,r)=>zS(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]}))).filter((e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0)));return r.length?{anyOf:r}:void 0};function LS(e,t){return"strict"===t.removeAdditionalStrategy?"ZodNever"===e.catchall._def.typeName?"strict"!==e.unknownKeys:zS(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0:"ZodNever"===e.catchall._def.typeName?"passthrough"===e.unknownKeys:zS(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0}const FS=Symbol("Let zodToJsonSchema decide on which parser to use"),DS={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"};function zS(e,t,r=!1){const n=t.seen.get(e);if(t.override){const s=t.override?.(e,t,n,r);if(s!==FS)return s}if(n&&!r){const e=US(n,t);if(void 0!==e)return"$ref"in e&&t.seenRefs.add(e.$ref),e}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=qS(e,e.typeName,t,r);return a&&KS(e,t,a),s.jsonSchema=a,a}const US=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"extract-to-root":const r=e.path.slice(t.basePath.length+1).join("_");return r!==t.name&&"duplicate-ref"===t.nameStrategy&&(t.definitions[r]=e.def),{$ref:[...t.basePath,t.definitionPath,r].join("/")};case"relative":return{$ref:BS(t.currentPath,e.path)};case"none":case"seen":return e.path.lengtht.currentPath[r]===e))?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{}):"seen"===t.$refStrategy?{}:void 0}},BS=(e,t)=>{let r=0;for(;r{switch(t){case M.kY.ZodString:return OS(e,r);case M.kY.ZodNumber:return function(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",yS(r,"type",n.message,t);break;case"min":"jsonSchema7"===t.target?n.inclusive?bS(r,"minimum",n.value,n.message,t):bS(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),bS(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?bS(r,"maximum",n.value,n.message,t):bS(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),bS(r,"maximum",n.value,n.message,t));break;case"multipleOf":bS(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case M.kY.ZodObject:return function(e,t){const r={type:"object",...Object.entries(e.shape()).reduce(((e,[r,n])=>{if(void 0===n||void 0===n._def)return e;const s=[...t.currentPath,"properties",r],a=zS(n._def,{...t,currentPath:s,propertyPath:s});return void 0===a?e:(t.openaiStrictMode&&n.isOptional()&&!n.isNullable()&&console.warn(`Zod field at \`${s.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\nThis will become an error in a future version of the SDK.`),{properties:{...e.properties,[r]:a},required:n.isOptional()&&!t.openaiStrictMode?e.required:[...e.required,r]})}),{properties:{},required:[]}),additionalProperties:LS(e,t)};return r.required.length||delete r.required,r}(e,r);case M.kY.ZodBigInt:return function(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":"jsonSchema7"===t.target?n.inclusive?bS(r,"minimum",n.value,n.message,t):bS(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),bS(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?bS(r,"maximum",n.value,n.message,t):bS(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),bS(r,"maximum",n.value,n.message,t));break;case"multipleOf":bS(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case M.kY.ZodBoolean:return{type:"boolean"};case M.kY.ZodDate:return wS(e,r);case M.kY.ZodUndefined:return{not:{}};case M.kY.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(r);case M.kY.ZodArray:return function(e,t){const r={type:"array"};return e.type?._def?.typeName!==M.kY.ZodAny&&(r.items=zS(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&bS(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&bS(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(bS(r,"minItems",e.exactLength.value,e.exactLength.message,t),bS(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}(e,r);case M.kY.ZodUnion:case M.kY.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return $S(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((e=>e._def.typeName in NS&&(!e._def.checks||!e._def.checks.length)))){const e=r.reduce(((e,t)=>{const r=NS[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e}),[]);return{type:e.length>1?e:e[0]}}if(r.every((e=>"ZodLiteral"===e._def.typeName&&!e.description))){const e=r.reduce(((e,t)=>{const r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}}),[]);if(e.length===r.length){const t=e.filter(((e,t,r)=>r.indexOf(e)===t));return{type:t.length>1?t:t[0],enum:r.reduce(((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value]),[])}}}else if(r.every((e=>"ZodEnum"===e._def.typeName)))return{type:"string",enum:r.reduce(((e,t)=>[...e,...t._def.values.filter((t=>!e.includes(t)))]),[])};return $S(e,t)}(e,r);case M.kY.ZodIntersection:return function(e,t){const r=[zS(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),zS(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((e=>!!e));let n="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const s=[];return r.forEach((e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:r,...n}=e;t=n}else n=void 0;s.push(t)}else s.push(...e.allOf),void 0===e.unevaluatedProperties&&(n=void 0);var t})),s.length?{allOf:s,...n}:void 0}(e,r);case M.kY.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map(((e,r)=>zS(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[]),additionalItems:zS(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map(((e,r)=>zS(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[])}}(e,r);case M.kY.ZodRecord:return jS(e,r);case M.kY.ZodLiteral:return function(e,t){const r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}(e,r);case M.kY.ZodEnum:return function(e){return{type:"string",enum:[...e.values]}}(e);case M.kY.ZodNativeEnum:return function(e){const t=e.values,r=Object.keys(e.values).filter((e=>"number"!=typeof t[t[e]])),n=r.map((e=>t[e])),s=Array.from(new Set(n.map((e=>typeof e))));return{type:1===s.length?"string"===s[0]?"string":"number":["string","number"],enum:n}}(e);case M.kY.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target||"property"===t.nullableStrategy?{type:NS[e.innerType._def.typeName],nullable:!0}:{type:[NS[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const r=zS(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=zS(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case M.kY.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return zS(e.innerType._def,t);const r=zS(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}})(e,r);case M.kY.ZodMap:return function(e,t){return"record"===t.mapStrategy?jS(e,t):{type:"array",maxItems:125,items:{type:"array",items:[zS(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},zS(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}(e,r);case M.kY.ZodSet:return function(e,t){const r={type:"array",uniqueItems:!0,items:zS(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&bS(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&bS(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}(e,r);case M.kY.ZodLazy:return zS(e.getter()._def,r);case M.kY.ZodPromise:return function(e,t){return zS(e.type._def,t)}(e,r);case M.kY.ZodNaN:case M.kY.ZodNever:return{not:{}};case M.kY.ZodEffects:return function(e,t,r){return"input"===t.effectStrategy?zS(e.schema._def,t,r):{}}(e,r,n);case M.kY.ZodAny:case M.kY.ZodUnknown:return{};case M.kY.ZodDefault:return function(e,t){return{...zS(e.innerType._def,t),default:e.defaultValue()}}(e,r);case M.kY.ZodBranded:return function(e,t){return zS(e.type._def,t)}(e,r);case M.kY.ZodReadonly:case M.kY.ZodCatch:return((e,t)=>zS(e.innerType._def,t))(e,r);case M.kY.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return zS(e.in._def,t);if("output"===t.pipeStrategy)return zS(e.out._def,t);const r=zS(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,zS(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter((e=>void 0!==e))}})(e,r);case M.kY.ZodFunction:case M.kY.ZodVoid:case M.kY.ZodSymbol:default:return}},KS=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),WS=e=>"_def"in e?e._def:e;const HS=e=>{const t=(e=>"string"==typeof e?{...DS,basePath:["#"],definitions:{},name:e}:{...DS,basePath:["#"],definitions:{},...e})(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(t.definitions).map((([e,r])=>[WS(r),{def:WS(r),path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}])))}};function VS(e,t){return((e,t)=>{const r=HS(t),n="string"==typeof t?t:"title"===t?.nameStrategy?void 0:t?.name,s=zS(e._def,void 0===n?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},a="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==a&&(s.title=a);const i=(()=>{if(function(e){if(!e)return!0;for(const t in e)return!1;return!0}(r.definitions))return;const e={},t=new Set;for(let n=0;n<500;n++){const n=Object.entries(r.definitions).filter((([e])=>!t.has(e)));if(0===n.length)break;for(const[s,a]of n)e[s]=zS(WS(a),{...r,currentPath:[...r.basePath,r.definitionPath,s]},!0)??{},t.add(s)}return e})(),o=void 0===n?i?{...s,[r.definitionPath]:i}:s:"duplicate-ref"===r.nameStrategy?{...s,...i||r.seenRefs.size?{[r.definitionPath]:{...i,...r.seenRefs.size?{[n]:s}:void 0}}:void 0}:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...i,[n]:s}};return"jsonSchema7"===r.target?o.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"===r.target&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o})(e,{openaiStrictMode:!0,name:t.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function GS(e,t,r){return function(e,t){const r={...e};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),r}({type:"json_schema",json_schema:{...r,name:t,strict:!0,schema:VS(e,{name:t})}},(t=>e.parse(JSON.parse(t))))}function JS(e){const{azureOpenAIApiDeploymentName:t,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:s,baseURL:a,azureADTokenProvider:i,azureOpenAIEndpoint:o}=e;if((n||i)&&s&&t)return`${s}/${t}`;if((n||i)&&o&&t)return`${o}/openai/deployments/${t}`;if(n||i){if(!r)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!t)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${t}`}return a}function ZS(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t}/\n`,e}function XS(e){let t;return e.constructor.name===Xy.name?(t=new Error(e.message),t.name="TimeoutError"):e.constructor.name===Jy.name?(t=new Error(e.message),t.name="AbortError"):t=400===e.status&&e.message.includes("tool_calls")?ZS(e,"INVALID_TOOL_RESULTS"):401===e.status?ZS(e,"MODEL_AUTHENTICATION"):429===e.status?ZS(e,"MODEL_RATE_LIMIT"):404===e.status?ZS(e,"MODEL_NOT_FOUND"):e,t}function YS(e){return e?"any"===e||"required"===e?"required":"auto"===e?"auto":"none"===e?"none":"string"==typeof e?{type:"function",function:{name:e}}:e:void 0}function QS(e,t){const r=[];for(const[n,s]of Object.entries(e.properties??{}))s.description&&t<2&&r.push(`// ${s.description}`),e.required?.includes(n)?r.push(`${n}: ${eE(s,t)},`):r.push(`${n}?: ${eE(s,t)},`);return r.map((e=>" ".repeat(t)+e)).join("\n")}function eE(e,t){if(void 0!==(r=e).anyOf&&Array.isArray(r.anyOf))return e.anyOf.map((e=>eE(e,t))).join(" | ");var r;switch(e.type){case"string":return e.enum?e.enum.map((e=>`"${e}"`)).join(" | "):"string";case"number":case"integer":return e.enum?e.enum.map((e=>`${e}`)).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",QS(e,t+2),"}"].join("\n");case"array":return e.items?`${eE(e.items,t)}[]`:"any[]";default:return""}}function tE(e){const t=e._getType();switch(t){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!se.ChatMessage.isInstance(e))throw new Error("Invalid generic chat message");return function(e){return"system"!==e.role&&"developer"!==e.role&&"assistant"!==e.role&&"user"!==e.role&&"function"!==e.role&&"tool"!==e.role&&console.warn(`Unknown message role: ${e.role}`),e.role}(e);default:throw new Error(`Unknown message type: ${t}`)}}const rE={providerName:"ChatOpenAI",fromStandardTextBlock:e=>({type:"text",text:e.text}),fromStandardImageBlock(e){if("url"===e.source_type)return{type:"image_url",image_url:{url:e.url,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};if("base64"===e.source_type){return{type:"image_url",image_url:{url:`data:${e.mime_type??""};base64,${e.data}`,...e.metadata?.detail?{detail:e.metadata.detail}:{}}}}throw new Error(`Image content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(e){if("url"===e.source_type){const t=(0,se.parseBase64DataUrl)({dataUrl:e.url});if(!t)throw new Error(`URL audio blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);const r=t.mime_type||e.mime_type||"";let n;try{n=(0,se.parseMimeType)(r)}catch{throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if("audio"!==n.type||"wav"!==n.subtype&&"mp3"!==n.subtype)throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:n.subtype,data:t.data}}}if("base64"===e.source_type){let t;try{t=(0,se.parseMimeType)(e.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if("audio"!==t.type||"wav"!==t.subtype&&"mp3"!==t.subtype)throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:t.subtype,data:e.data}}}throw new Error(`Audio content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(e){if("url"===e.source_type){if(!(0,se.parseBase64DataUrl)({dataUrl:e.url}))throw new Error(`URL file blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:e.url,...e.metadata?.filename||e.metadata?.name?{filename:e.metadata?.filename||e.metadata?.name}:{}}}}if("base64"===e.source_type)return{type:"file",file:{file_data:`data:${e.mime_type??""};base64,${e.data}`,...e.metadata?.filename||e.metadata?.name||e.metadata?.title?{filename:e.metadata?.filename||e.metadata?.name||e.metadata?.title}:{}}};if("id"===e.source_type)return{type:"file",file:{file_id:e.id}};throw new Error(`File content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)}};function nE(e,t){return e.flatMap((e=>{let r=tE(e);"system"===r&&uE(t)&&(r="developer");const n={role:r,content:"string"==typeof e.content?e.content:e.content.map((e=>(0,se.isDataContentBlock)(e)?(0,se.convertToProviderContentBlock)(e,rE):e))};if(null!=e.name&&(n.name=e.name),null!=e.additional_kwargs.function_call&&(n.function_call=e.additional_kwargs.function_call,n.content=""),(0,se.isAIMessage)(e)&&e.tool_calls?.length?(n.tool_calls=e.tool_calls.map(pS),n.content=""):(null!=e.additional_kwargs.tool_calls&&(n.tool_calls=e.additional_kwargs.tool_calls),null!=e.tool_call_id&&(n.tool_call_id=e.tool_call_id)),e.additional_kwargs.audio&&"object"==typeof e.additional_kwargs.audio&&"id"in e.additional_kwargs.audio){return[n,{role:"assistant",audio:{id:e.additional_kwargs.audio.id}}]}return n}))}const sE="__openai_function_call_ids__";function aE(e,t,r){const n=e.filter((e=>(0,se.isAIMessage)(e))).pop(),s=n?.response_metadata?.id;return(s&&s.startsWith("resp_")&&!r?e.slice(e.indexOf(n)+1):e).flatMap((e=>{let n=tE(e);if("system"===n&&uE(t)&&(n="developer"),"function"===n)throw new Error("Function messages are not supported in Responses API");if("tool"===n){const t=e;if("computer_call_output"===t.additional_kwargs?.type){const e=(()=>{if("string"==typeof t.content)return{type:"computer_screenshot",image_url:t.content};if(Array.isArray(t.content)){const e=t.content.find((e=>"computer_screenshot"===e.type));if(e)return e;const r=t.content.find((e=>"image_url"===e.type));if(r)return{type:"computer_screenshot",image_url:"string"==typeof r.image_url?r.image_url:r.image_url.url}}throw new Error("Invalid computer call output")})();return{type:"computer_call_output",output:e,call_id:t.tool_call_id}}return{type:"function_call_output",call_id:t.tool_call_id,id:t.id,output:"string"!=typeof t.content?JSON.stringify(t.content):t.content}}if("assistant"===n){if(!r&&null!=e.response_metadata.output&&Array.isArray(e.response_metadata.output)&&e.response_metadata.output.length>0&&e.response_metadata.output.every((e=>"type"in e)))return e.response_metadata.output;const t=[];if(!r&&null!=e.additional_kwargs.reasoning){if((e=>"object"==typeof e&&null!=e&&"type"in e&&"reasoning"===e.type)(e.additional_kwargs.reasoning)){const r=function(e){const t=(e.summary.length>1?e.summary.reduce(((e,t)=>{const r=e.at(-1);return r.index===t.index?r.text+=t.text:e.push(t),e}),[{...e.summary[0]}]):e.summary).map((e=>Object.fromEntries(Object.entries(e).filter((([e])=>"index"!==e)))));return{...e,summary:t}}(e.additional_kwargs.reasoning);t.push(r)}}let{content:n}=e;null!=e.additional_kwargs.refusal&&("string"==typeof n&&(n=[{type:"output_text",text:n,annotations:[]}]),n=[...n,{type:"refusal",refusal:e.additional_kwargs.refusal}]),t.push({type:"message",role:"assistant",...e.id&&!r?{id:e.id}:{},content:"string"==typeof n?n:n.flatMap((e=>"text"===e.type?{type:"output_text",text:e.text,annotations:e.annotations??[]}:"output_text"===e.type||"refusal"===e.type?e:[]))});const s=e.additional_kwargs[sE];(0,se.isAIMessage)(e)&&e.tool_calls?.length?t.push(...e.tool_calls.map((e=>({type:"function_call",name:e.name,arguments:JSON.stringify(e.args),call_id:e.id,...r?{id:s?.[e.id]}:{}})))):null!=e.additional_kwargs.tool_calls&&t.push(...e.additional_kwargs.tool_calls.map((e=>({type:"function_call",name:e.function.name,call_id:e.id,...r?{id:s?.[e.id]}:{},arguments:e.function.arguments}))));const a=e.response_metadata.output?.length?e.response_metadata.output:e.additional_kwargs.tool_outputs;let i=[];if(null!=a){const e=a;i=e?.filter((e=>"computer_call"===e.type)),i.length>0&&t.push(...i)}return t}const s="string"==typeof e.content?e.content:e.content.flatMap((e=>{if((0,se.isDataContentBlock)(e))return(0,se.convertToProviderContentBlock)(e,rE);if("text"===e.type)return{type:"input_text",text:e.text};if("image_url"===e.type){return{type:"input_image",image_url:"string"==typeof e.image_url?e.image_url:e.image_url.url,detail:"string"==typeof e.image_url?"auto":e.image_url.detail}}return"input_text"===e.type||"input_image"===e.type||"input_file"===e.type?e:[]}));return"user"===n||"system"===n||"developer"===n?{type:"message",role:n,content:s}:(console.warn(`Unsupported role found when converting to OpenAI Responses API: ${n}`),[])}))}function iE(e){if(e.error){const t=new Error(e.error.message);throw t.name=e.error.code,t}let t;const r=[],n=[],s=[],a={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,model_name:e.model},i={};for(const a of e.output)if("message"===a.type)t=a.id,r.push(...a.content.flatMap((e=>"output_text"===e.type?("parsed"in e&&null!=e.parsed&&(i.parsed=e.parsed),{type:"text",text:e.text,annotations:e.annotations}):"refusal"===e.type?(i.refusal=e.refusal,[]):e)));else if("function_call"===a.type){const e={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{n.push(hS(e,{returnId:!0}))}catch(t){let r;"object"==typeof t&&null!=t&&"message"in t&&"string"==typeof t.message&&(r=t.message),s.push(mS(e,r))}i[sE]??={},a.id&&(i[sE][a.call_id]=a.id)}else"reasoning"===a.type?i.reasoning=a:(i.tool_outputs??=[],i.tool_outputs.push(a));return new se.AIMessage({id:t,content:r,tool_calls:n,invalid_tool_calls:s,usage_metadata:e.usage,additional_kwargs:i,response_metadata:a})}function oE(e){const t=[];let r,n={};const s=[],a={},i={};let o;if("response.output_text.delta"===e.type)t.push({type:"text",text:e.delta,index:e.content_index});else if("response.output_text.annotation.added"===e.type)t.push({type:"text",text:"",annotations:[e.annotation],index:e.content_index});else if("response.output_item.added"===e.type&&"message"===e.item.type)o=e.item.id;else if("response.output_item.added"===e.type&&"function_call"===e.item.type)s.push({type:"tool_call_chunk",name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),i[sE]={[e.item.call_id]:e.item.id};else if("response.output_item.done"!==e.type||"web_search_call"!==e.item.type&&"file_search_call"!==e.item.type&&"computer_call"!==e.item.type)if("response.created"===e.type)a.id=e.response.id,a.model_name=e.response.model,a.model=e.response.model;else if("response.completed"===e.type){const t=iE(e.response);r=e.response.usage,"json_schema"===e.response.text?.format?.type&&(i.parsed??=JSON.parse(t.text));for(const[t,r]of Object.entries(e.response))"id"!==t&&(a[t]=r)}else if("response.function_call_arguments.delta"===e.type)s.push({type:"tool_call_chunk",args:e.delta,index:e.output_index});else if("response.web_search_call.completed"===e.type||"response.file_search_call.completed"===e.type)n={tool_outputs:{id:e.item_id,type:e.type.replace("response.","").replace(".completed",""),status:"completed"}};else if("response.refusal.done"===e.type)i.refusal=e.refusal;else if("response.output_item.added"===e.type&&"item"in e&&"reasoning"===e.item.type){const t=e.item.summary?e.item.summary.map(((e,t)=>({...e,index:t}))):void 0;i.reasoning={id:e.item.id,type:e.item.type,...t?{summary:t}:{}}}else if("response.reasoning_summary_part.added"===e.type)i.reasoning={type:"reasoning",summary:[{...e.part,index:e.summary_index}]};else{if("response.reasoning_summary_text.delta"!==e.type)return null;i.reasoning={type:"reasoning",summary:[{text:e.delta,type:"summary_text",index:e.summary_index}]}}else i.tool_outputs=[e.item];return new $t.ChatGenerationChunk({text:t.map((e=>e.text)).join(""),message:new se.AIMessageChunk({id:o,content:t,tool_call_chunks:s,usage_metadata:r,additional_kwargs:i,response_metadata:a}),generationInfo:n})}function cE(e){return"type"in e&&"function"!==e.type}function lE(e,t){return It(e)?void 0!==t?.strict?{...e,function:{...e.function,strict:t.strict}}:e:function(e,t){let r;return r=hn(e)?In(e):e,void 0!==t?.strict&&(r.function.strict=t.strict),r}(e,t)}function uE(e){return e&&/^o\d/.test(e)}class dE extends zt{static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning_effort"]}get lc_secrets(){return{openAIApiKey:"OPENAI_API_KEY",apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{modelName:"model",openAIApiKey:"openai_api_key",apiKey:"openai_api_key"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","reasoningEffort","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","modelName","model","modelKwargs","stop","stopSequences","timeout","openAIApiKey","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","useResponsesApi","zdrEnabled","reasoning"]}constructor(e){super(e??{}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),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,"modelName",{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,"openAIApiKey",{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,"reasoningEffort",{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,"useResponsesApi",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zdrEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.openAIApiKey=e?.apiKey??e?.openAIApiKey??e?.configuration?.apiKey??(0,Sn.getEnvironmentVariable)("OPENAI_API_KEY"),this.apiKey=this.openAIApiKey,this.organization=e?.configuration?.organization??(0,Sn.getEnvironmentVariable)("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelName=this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoningEffort=e?.reasoningEffort??e?.reasoning?.effort,this.reasoning=e?.reasoning??(e?.reasoningEffort?{effort:e.reasoningEffort}:void 0),this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.useResponsesApi=e?.useResponsesApi??this.useResponsesApi,this.disableStreaming=e?.disableStreaming??this.disableStreaming,"o1"===this.model&&(this.disableStreaming=!0),this.streaming=e?.streaming??!1,this.disableStreaming&&(this.streaming=!1),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},void 0!==e?.supportsStrictToolCalling&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),this.zdrEnabled=e?.zdrEnabled??!1}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}}bindTools(e,t){let r;return void 0!==t?.strict?r=t.strict:void 0!==this.supportsStrictToolCalling&&(r=this.supportsStrictToolCalling),this.bind({tools:e.map((e=>cE(e)?e:lE(e,{strict:r}))),...t})}createResponseFormat(e){return e&&"json_schema"===e.type&&e.json_schema.schema&&hE(e.json_schema.schema)?GS(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}getReasoningParams(e){if(!uE(this.model))return;let t;return void 0!==this.reasoningEffort&&(t={effort:this.reasoningEffort}),void 0!==this.reasoning&&(t={...t,...this.reasoning}),void 0!==e?.reasoning_effort&&(t={...t,effort:e.reasoning_effort}),void 0!==e?.reasoning&&(t={...t,...e.reasoning}),t}invocationParams(e,t){let r;if(void 0!==e?.strict?r=e.strict:void 0!==this.supportsStrictToolCalling&&(r=this.supportsStrictToolCalling),this._useResponseApi(e)){const t={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,stream:this.streaming,previous_response_id:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?e.tools.map((e=>cE(e)?e:It(e)?{type:"function",name:e.function.name,parameters:e.function.parameters,description:e.function.description,strict:r}:null)).filter((e=>null!==e)):void 0,tool_choice:(n=e?.tool_choice,null!=n&&"object"==typeof n&&"type"in n&&"function"!==n.type?e?.tool_choice:(()=>{const t=YS(e?.tool_choice);return"object"==typeof t&&"type"in t?{type:"function",name:t.function.name}:void 0})()),text:(()=>{if(e?.text)return e.text;const t=this.createResponseFormat(e?.response_format);return"json_schema"===t?.type?null!=t.json_schema.schema?{format:{type:"json_schema",schema:t.json_schema.schema,description:t.json_schema.description,name:t.json_schema.name,strict:t.json_schema.strict}}:void 0:{format:t}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:-1===this.maxTokens?void 0:this.maxTokens,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},s=this.getReasoningParams(e);return void 0!==s&&(t.reasoning=s),t}var n;let s={};void 0!==e?.stream_options?s={stream_options:e.stream_options}:this.streamUsage&&(this.streaming||t?.streaming)&&(s={stream_options:{include_usage:!0}});const a={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map((e=>lE(e,{strict:r}))):void 0,tool_choice:YS(e?.tool_choice),response_format:this.createResponseFormat(e?.response_format),seed:e?.seed,...s,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs};void 0!==e?.prediction&&(a.prediction=e.prediction);const i=this.getReasoningParams(e);return void 0!==i&&void 0!==i.effort&&(a.reasoning_effort=i.effort),uE(a.model)?a.max_completion_tokens=-1===this.maxTokens?void 0:this.maxTokens:a.max_tokens=-1===this.maxTokens?void 0:this.maxTokens,a}_convertOpenAIChatCompletionMessageToBaseMessage(e,t){const r=e.tool_calls;if("assistant"===e.role){const n=[],s=[];for(const e of r??[])try{n.push(hS(e,{returnId:!0}))}catch(t){s.push(mS(e,t.message))}const a={function_call:e.function_call,tool_calls:r};void 0!==this.__includeRawResponse&&(a.__raw_response=t);const i={model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};return e.audio&&(a.audio=e.audio),new se.AIMessage({content:e.content||"",tool_calls:n,invalid_tool_calls:s,additional_kwargs:a,response_metadata:i,id:t.id})}return new se.ChatMessage(e.content||"",e.role??"unknown")}_convertOpenAIDeltaToBaseMessageChunk(e,t,r){const n=e.role??r,s=e.content??"";let a;a=e.function_call?{function_call:e.function_call}:e.tool_calls?{tool_calls:e.tool_calls}:{},this.__includeRawResponse&&(a.__raw_response=t),e.audio&&(a.audio={...e.audio,index:t.choices[0].index});const i={usage:{...t.usage}};if("user"===n)return new se.HumanMessageChunk({content:s,response_metadata:i});if("assistant"===n){const r=[];if(Array.isArray(e.tool_calls))for(const t of e.tool_calls)r.push({name:t.function?.name,args:t.function?.arguments,id:t.id,index:t.index,type:"tool_call_chunk"});return new se.AIMessageChunk({content:s,tool_call_chunks:r,additional_kwargs:a,id:t.id,response_metadata:i})}return"system"===n?new se.SystemMessageChunk({content:s,response_metadata:i}):"developer"===n?new se.SystemMessageChunk({content:s,response_metadata:i,additional_kwargs:{__openai_role__:"developer"}}):"function"===n?new se.FunctionMessageChunk({content:s,additional_kwargs:a,name:e.name,response_metadata:i}):"tool"===n?new se.ToolMessageChunk({content:s,additional_kwargs:a,tool_call_id:e.tool_call_id,response_metadata:i}):new se.ChatMessageChunk({content:s,role:n,response_metadata:i})}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}async*_streamResponseChunks(e,t,r){if(this._useResponseApi(t)){const r=e.filter((e=>(0,se.isAIMessage)(e))).pop(),n=r?.response_metadata?.id,s=await this.responseApiWithRetry({...this.invocationParams(t,{streaming:!0}),input:aE(e,this.model,this.zdrEnabled),stream:!0,...n&&n.startsWith("resp_")&&!this.zdrEnabled?{previous_response_id:n}:{}},t);for await(const e of s){const t=oE(e);null!=t&&(yield t)}return}const n=nE(e,this.model),s={...this.invocationParams(t,{streaming:!0}),messages:n,stream:!0};let a;const i=await this.completionWithRetry(s,t);let o;for await(const e of i){const n=e?.choices?.[0];if(e.usage&&(o=e.usage),!n)continue;const{delta:s}=n;if(!s)continue;const i=this._convertOpenAIDeltaToBaseMessageChunk(s,e,a);a=s.role??a;const c={prompt:t.promptIndex??0,completion:n.index??0};if("string"!=typeof i.content){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}const l={...c};null!=n.finish_reason&&(l.finish_reason=n.finish_reason,l.system_fingerprint=e.system_fingerprint,l.model_name=e.model),this.logprobs&&(l.logprobs=n.logprobs);const u=new $t.ChatGenerationChunk({message:i,text:i.content,generationInfo:l});yield u,await(r?.handleLLMNewToken(u.text??"",c,void 0,void 0,void 0,{chunk:u}))}if(o){const e={...null!==o.prompt_tokens_details?.audio_tokens&&{audio:o.prompt_tokens_details?.audio_tokens},...null!==o.prompt_tokens_details?.cached_tokens&&{cache_read:o.prompt_tokens_details?.cached_tokens}},t={...null!==o.completion_tokens_details?.audio_tokens&&{audio:o.completion_tokens_details?.audio_tokens},...null!==o.completion_tokens_details?.reasoning_tokens&&{reasoning:o.completion_tokens_details?.reasoning_tokens}},r=new $t.ChatGenerationChunk({message:new se.AIMessageChunk({content:"",response_metadata:{usage:{...o}},usage_metadata:{input_tokens:o.prompt_tokens,output_tokens:o.completion_tokens,total_tokens:o.total_tokens,...Object.keys(e).length>0&&{input_token_details:e},...Object.keys(t).length>0&&{output_token_details:t}}}),text:""});yield r}if(t.signal?.aborted)throw new Error("AbortError")}identifyingParams(){return this._identifyingParams()}async _responseApiGenerate(e,t,r){const n=this.invocationParams(t);if(n.stream){const n=this._streamResponseChunks(e,t,r);let s;for await(const e of n)e.message.response_metadata={...e.generationInfo,...e.message.response_metadata},s=s?.concat(e)??e;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}const s=e.filter((e=>(0,se.isAIMessage)(e))).pop(),a=s?.response_metadata?.id,i=aE(e,this.model,this.zdrEnabled),o=await this.responseApiWithRetry({input:i,...n,...a&&a.startsWith("resp_")&&!this.zdrEnabled?{previous_response_id:a}:{}},{signal:t?.signal,...t?.options});return{generations:[{text:o.output_text,message:iE(o)}],llmOutput:{id:o.id,estimatedTokenUsage:o.usage?{promptTokens:o.usage.input_tokens,completionTokens:o.usage.output_tokens,totalTokens:o.usage.total_tokens}:void 0}}}_useResponseApi(e){const t=e?.tools?.some(cE),r=null!=e?.previous_response_id||null!=e?.text||null!=e?.truncation||null!=e?.include||null!=e?.reasoning?.summary||null!=this.reasoning?.summary;return this.useResponsesApi||t||r}async _generate(e,t,r){if(this._useResponseApi(t))return this._responseApiGenerate(e,t,r);const n={},s=this.invocationParams(t),a=nE(e,this.model);if(s.stream){const s=this._streamResponseChunks(e,t,r),a={};for await(const e of s){e.message.response_metadata={...e.generationInfo,...e.message.response_metadata};const t=e.generationInfo?.completion??0;void 0===a[t]?a[t]=e:a[t]=a[t].concat(e)}const i=Object.entries(a).sort((([e],[t])=>parseInt(e,10)-parseInt(t,10))).map((([e,t])=>t)),{functions:o,function_call:c}=this.invocationParams(t),l=await this.getEstimatedTokenCountFromPrompt(e,o,c),u=await this.getNumTokensFromGenerations(i);return n.input_tokens=l,n.output_tokens=u,n.total_tokens=l+u,{generations:i,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}{let e;e=t.response_format&&"json_schema"===t.response_format.type?await this.betaParsedCompletionWithRetry({...s,stream:!1,messages:a},{signal:t?.signal,...t?.options}):await this.completionWithRetry({...s,stream:!1,messages:a},{signal:t?.signal,...t?.options});const{completion_tokens:r,prompt_tokens:i,total_tokens:o,prompt_tokens_details:c,completion_tokens_details:l}=e?.usage??{};r&&(n.output_tokens=(n.output_tokens??0)+r),i&&(n.input_tokens=(n.input_tokens??0)+i),o&&(n.total_tokens=(n.total_tokens??0)+o),null===c?.audio_tokens&&null===c?.cached_tokens||(n.input_token_details={...null!==c?.audio_tokens&&{audio:c?.audio_tokens},...null!==c?.cached_tokens&&{cache_read:c?.cached_tokens}}),null===l?.audio_tokens&&null===l?.reasoning_tokens||(n.output_token_details={...null!==l?.audio_tokens&&{audio:l?.audio_tokens},...null!==l?.reasoning_tokens&&{reasoning:l?.reasoning_tokens}});const u=[];for(const t of e?.choices??[]){const r={text:t.message?.content??"",message:this._convertOpenAIChatCompletionMessageToBaseMessage(t.message??{role:"assistant"},e)};r.generationInfo={...t.finish_reason?{finish_reason:t.finish_reason}:{},...t.logprobs?{logprobs:t.logprobs}:{}},(0,se.isAIMessage)(r.message)&&(r.message.usage_metadata=n),r.message=new se.AIMessage(Object.fromEntries(Object.entries(r.message).filter((([e])=>!e.startsWith("lc_"))))),u.push(r)}return{generations:u,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async getEstimatedTokenCountFromPrompt(e,t,r){let n=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&"auto"!==r){const e=function(e){const t=["namespace functions {",""];for(const r of e)r.description&&t.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(t.push(`type ${r.name} = (_: {`),t.push(QS(r.parameters,0)),t.push("}) => any;")):t.push(`type ${r.name} = () => any;`),t.push("");return t.push("} // namespace functions"),t.join("\n")}(t);n+=await this.getNumTokens(e),n+=9}return t&&e.find((e=>"system"===e._getType()))&&(n-=4),"none"===r?n+=1:"object"==typeof r&&(n+=await this.getNumTokens(r.name)+4),n}async getNumTokensFromGenerations(e){return(await Promise.all(e.map((async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content))))).reduce(((e,t)=>e+t),0)}async getNumTokensFromMessages(e){let t=0,r=0,n=0;"gpt-3.5-turbo-0301"===this.model?(r=4,n=-1):(r=3,n=1);const s=await Promise.all(e.map((async e=>{const s=await this.getNumTokens(e.content),a=await this.getNumTokens(tE(e)),i=void 0!==e.name?n+await this.getNumTokens(e.name):0;let o=s+r+a+i;const c=e;if("function"===c._getType()&&(o-=2),c.additional_kwargs?.function_call&&(o+=3),c?.additional_kwargs.function_call?.name&&(o+=await this.getNumTokens(c.additional_kwargs.function_call?.name)),c.additional_kwargs.function_call?.arguments)try{o+=await this.getNumTokens(JSON.stringify(JSON.parse(c.additional_kwargs.function_call?.arguments)))}catch(e){console.error("Error parsing function arguments",e,JSON.stringify(c.additional_kwargs.function_call)),o+=await this.getNumTokens(c.additional_kwargs.function_call?.arguments)}return t+=o,o})));return t+=3,{totalCount:t,countPerMessage:s}}async completionWithRetry(e,t){const r=this._getClientOptions(t);return this.caller.call((async()=>{try{return await this.client.chat.completions.create(e,r)}catch(e){throw XS(e)}}))}async responseApiWithRetry(e,t){return this.caller.call((async()=>{const r=this._getClientOptions(t);try{return"json_schema"!==e.text?.format?.type||e.stream?await this.client.responses.create(e,r):await this.client.responses.parse(e,r)}catch(e){throw XS(e)}}))}async betaParsedCompletionWithRetry(e,t){const r=this._getClientOptions(t);return this.caller.call((async()=>{try{return await this.client.beta.chat.completions.parse(e,r)}catch(e){throw XS(e)}}))}_getClientOptions(e){if(!this.client){const e=JS({baseURL:this.clientConfig.baseURL}),t={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};t.baseURL||delete t.baseURL,this.client=new Tk(t)}return{...this.clientConfig,...e}}_llmType(){return"openai"}_combineLLMOutput(...e){return e.reduce(((e,t)=>(t&&t.tokenUsage&&(e.tokenUsage.completionTokens+=t.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=t.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=t.tokenUsage.totalTokens??0),e)),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}withStructuredOutput(e,t){let r,n,s,a;var i;let o,c;if(void 0!==(i=e)&&"object"==typeof i.schema?(r=e.schema,n=e.name,s=e.method,a=e.includeRaw):(r=e,n=t?.name,s=t?.method,a=t?.includeRaw),void 0!==t?.strict&&"jsonMode"===s)throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");if(this.model.startsWith("gpt-3")||this.model.startsWith("gpt-4-")||"gpt-4"===this.model?"jsonSchema"===s&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`):void 0===s&&(s="jsonSchema"),"jsonMode"===s)o=this.bind({response_format:{type:"json_object"}}),c=hE(r)?Ar.fromZodSchema(r):new Nr;else if("jsonSchema"===s)if(o=this.bind({response_format:{type:"json_schema",json_schema:{name:n??"extract",description:r.description,schema:r,strict:t?.strict}}}),hE(r)){const e=Ar.fromZodSchema(r);c=Y.jY.from((t=>"parsed"in t.additional_kwargs?t.additional_kwargs.parsed:e))}else c=new Nr;else{let e=n??"extract";if(hE(r)){const n=(0,Nt.Ik)(r);o=this.bind({tools:[{type:"function",function:{name:e,description:n.description,parameters:n}}],tool_choice:{type:"function",function:{name:e}},...void 0!==t?.strict?{strict:t.strict}:{}}),c=new gS({returnSingle:!0,keyName:e,zodSchema:r})}else{let n;"string"==typeof r.name&&"object"==typeof r.parameters&&null!=r.parameters?(n=r,e=r.name):(e=r.title??e,n={name:e,description:r.description??"",parameters:r}),o=this.bind({tools:[{type:"function",function:n}],tool_choice:{type:"function",function:{name:e}},...void 0!==t?.strict?{strict:t.strict}:{}}),c=new gS({returnSingle:!0,keyName:e})}}if(!a)return o.pipe(c);const l=te.assign({parsed:(e,t)=>c.invoke(e.raw,t)}),u=te.assign({parsed:()=>null}),d=l.withFallbacks({fallbacks:[u]});return Y.zZ.from([{raw:o},d])}}function hE(e){return"function"==typeof e?.parse}Object.defineProperty(class extends mn{static lc_name(){return"DallEAPIWrapper"}constructor(e){void 0!==e?.responseFormat&&["url","b64_json"].includes(e.responseFormat)&&(e.dallEResponseFormat=e.responseFormat,e.responseFormat="content"),super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description."}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"dall-e-3"}),Object.defineProperty(this,"style",{enumerable:!0,configurable:!0,writable:!0,value:"vivid"}),Object.defineProperty(this,"quality",{enumerable:!0,configurable:!0,writable:!0,value:"standard"}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:"1024x1024"}),Object.defineProperty(this,"dallEResponseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"url"}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const t={apiKey:e?.apiKey??e?.openAIApiKey??(0,Sn.getEnvironmentVariable)("OPENAI_API_KEY"),organization:e?.organization??(0,Sn.getEnvironmentVariable)("OPENAI_ORGANIZATION"),dangerouslyAllowBrowser:!0,baseURL:e?.baseUrl};this.client=new Tk(t),this.model=e?.model??e?.modelName??this.model,this.style=e?.style??this.style,this.quality=e?.quality??this.quality,this.n=e?.n??this.n,this.size=e?.size??this.size,this.dallEResponseFormat=e?.dallEResponseFormat??this.dallEResponseFormat,this.user=e?.user}processMultipleGeneratedUrls(e){return"url"===this.dallEResponseFormat?e.flatMap((e=>e.data?.flatMap((e=>e.url?{type:"image_url",image_url:e.url}:[])).filter((e=>void 0!==e&&"image_url"===e.type&&"string"==typeof e.image_url&&void 0!==e.image_url))??[])):e.flatMap((e=>e.data?.flatMap((e=>e.b64_json?{type:"image_url",image_url:{url:e.b64_json}}:[])).filter((e=>void 0!==e&&"image_url"===e.type&&"object"==typeof e.image_url&&"url"in e.image_url&&"string"==typeof e.image_url.url&&void 0!==e.image_url.url))??[]))}async _call(e){const t={model:this.model,prompt:e,n:1,size:this.size,response_format:this.dallEResponseFormat,style:this.style,quality:this.quality,user:this.user};if(this.n>1){const e=await Promise.all(Array.from({length:this.n}).map((()=>this.client.images.generate(t))));return this.processMultipleGeneratedUrls(e)}const r=await this.client.images.generate(t);let n="";return"url"===this.dallEResponseFormat?[n]=r.data?.map((e=>e.url)).filter((e=>"undefined"!==e))??[]:[n]=r.data?.map((e=>e.b64_json)).filter((e=>"undefined"!==e))??[],n}},"toolName",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"});const pE="0.39.0";let mE,fE,gE,yE,bE,wE,vE=!1,_E=null,kE=null,SE=null,EE=null,xE=null,TE=null,CE=null;class PE{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}mE||function(e,t={auto:!1}){if(vE)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${e.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(mE)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${e.kind}'\` after \`import '@anthropic-ai/sdk/shims/${mE}'\``);vE=t.auto,mE=e.kind,fE=e.fetch,_E=e.Request,kE=e.Response,SE=e.Headers,EE=e.FormData,xE=e.Blob,gE=e.File,yE=e.ReadableStream,TE=e.getMultipartRequestOptions,bE=e.getDefaultAgent,wE=e.fileFromPath,CE=e.isFsReadStream}(function({manuallyImported:e}={}){const t=e?"You may need to use polyfills":"Add one of these imports before your first `import … from '@anthropic-ai/sdk'`:\n- `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n- `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n";let r,n,s,a;try{r=fetch,n=Request,s=Response,a=Headers}catch(e){throw new Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${t}`)}return{kind:"web",fetch:r,Request:n,Response:s,Headers:a,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new PE(e)}),getDefaultAgent:e=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads")},isFsReadStream:e=>!1}}(),{auto:!0});class OE extends Error{}class AE extends OE{constructor(e,t,r,n){super(`${AE.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.request_id=n?.["request-id"],this.error=t}static makeMessage(e,t,r){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new ME({message:r,cause:Tx(t)});const s=t;return 400===e?new jE(e,s,r,n):401===e?new NE(e,s,r,n):403===e?new $E(e,s,r,n):404===e?new LE(e,s,r,n):409===e?new FE(e,s,r,n):422===e?new DE(e,s,r,n):429===e?new zE(e,s,r,n):e>=500?new UE(e,s,r,n):new AE(e,s,r,n)}}class IE extends AE{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class ME extends AE{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class RE extends ME{constructor({message:e}={}){super({message:e??"Request timed out."})}}class jE extends AE{}class NE extends AE{}class $E extends AE{}class LE extends AE{}class FE extends AE{}class DE extends AE{}class zE extends AE{}class UE extends AE{}var BE,qE=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},KE=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class WE{constructor(){BE.set(this,void 0),this.buffer=new Uint8Array,qE(this,BE,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?(new TextEncoder).encode(e):e;let r=new Uint8Array(this.buffer.length+t.length);r.set(this.buffer),r.set(t,this.buffer.length),this.buffer=r;const n=[];let s;for(;null!=(s=HE(this.buffer,KE(this,BE,"f")));){if(s.carriage&&null==KE(this,BE,"f")){qE(this,BE,s.index,"f");continue}if(null!=KE(this,BE,"f")&&(s.index!==KE(this,BE,"f")+1||s.carriage)){n.push(this.decodeText(this.buffer.slice(0,KE(this,BE,"f")-1))),this.buffer=this.buffer.slice(KE(this,BE,"f")),qE(this,BE,null,"f");continue}const e=null!==KE(this,BE,"f")?s.preceding-1:s.preceding,t=this.decodeText(this.buffer.slice(0,e));n.push(t),this.buffer=this.buffer.slice(s.index),qE(this,BE,null,"f")}return n}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof Buffer){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new OE(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new OE(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new OE("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode("\n"):[]}}function HE(e,t){for(let r=t??0;r0&&(yield t)}(s))for(const t of n.decode(e)){const e=r.decode(t);e&&(yield e)}for(const e of n.flush()){const t=r.decode(e);t&&(yield t)}}(e,t)){if("completion"===r.event)try{yield JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if("message_start"===r.event||"message_delta"===r.event||"message_stop"===r.event||"content_block_start"===r.event||"content_block_delta"===r.event||"content_block_stop"===r.event)try{yield JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if("ping"!==r.event&&"error"===r.event)throw AE.generate(void 0,`SSE Error: ${r.data}`,r.data,px(e.headers))}n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}}),t)}static fromReadableStream(e,t){let r=!1;return new JE((async function*(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let n=!1;try{for await(const t of async function*(){const t=new WE,r=GE(e);for await(const e of r)for(const r of t.decode(e))yield r;for(const e of t.flush())yield e}())n||t&&(yield JSON.parse(t));n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}}),t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],r=this.iterator(),n=n=>({next:()=>{if(0===n.length){const n=r.next();e.push(n),t.push(n)}return n.shift()}});return[new JE((()=>n(e)),this.controller),new JE((()=>n(t)),this.controller)]}toReadableStream(){const e=this;let t;const r=new TextEncoder;return new yE({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:n,done:s}=await t.next();if(s)return e.close();const a=r.encode(JSON.stringify(n)+"\n");e.enqueue(a)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class ZE{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 e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=function(e,t){const r=e.indexOf(t);if(-1!==r)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}const XE=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,YE=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&QE(e),QE=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function ex(e,t,r){if(e=await e,YE(e))return e;if(XE(e)){const n=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");const s=QE(n)?[await n.arrayBuffer()]:[n];return new gE(s,t,r)}const n=await async function(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(QE(e))t.push(await e.arrayBuffer());else{if(!rx(e))throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${function(e){const t=Object.getOwnPropertyNames(e);return`[${t.map((e=>`"${e}"`)).join(", ")}]`}(e)}`);for await(const r of e)t.push(r)}return t}(e);if(t||(t=function(e){return tx(e.name)||tx(e.filename)||tx(e.path)?.split(/[\\/]/).pop()}(e)??"unknown_file"),!r?.type){const e=n[0]?.type;"string"==typeof e&&(r={...r,type:e})}return new gE(n,t,r)}const tx=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,rx=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],nx=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag];var sx,ax=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},ix=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};async function ox(e){const{response:t}=e;if(e.options.stream)return Ix("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):JE.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;const r=t.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){const e=await t.json();return Ix("response",t.status,t.url,t.headers,e),cx(e,t)}const n=await t.text();return Ix("response",t.status,t.url,t.headers,n),n}function cx(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("request-id"),enumerable:!1})}class lx extends Promise{constructor(e,t=ox){super((e=>{e(null)})),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new lx(this.responsePromise,(async t=>cx(e(await this.parseResponse(t),t),t.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("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),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)}}class ux{constructor({baseURL:e,maxRetries:t=2,timeout:r=6e5,httpAgent:n,fetch:s}){this.baseURL=e,this.maxRetries=xx("maxRetries",t),this.timeout=xx("timeout",r),this.httpAgent=n,this.fetch=s??fE}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...vx(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${Mx()}`}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((async r=>{const n=r&&QE(r?.body)?new DataView(await r.body.arrayBuffer()):r?.body instanceof DataView?r.body:r?.body instanceof ArrayBuffer?new DataView(r.body):r&&ArrayBuffer.isView(r?.body)?new DataView(r.body.buffer):r?.body;return{method:e,path:t,...r,body:n}})))}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}calculateContentLength(e){if("string"==typeof e){if("undefined"!=typeof Buffer)return Buffer.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder){return(new TextEncoder).encode(e).length.toString()}}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){e={...e};const{method:r,path:n,query:s,headers:a={}}=e,i=ArrayBuffer.isView(e.body)||e.__binaryRequest&&"string"==typeof e.body?e.body:nx(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,o=this.calculateContentLength(i),c=this.buildURL(n,s);"timeout"in e&&xx("timeout",e.timeout),e.timeout=e.timeout??this.timeout;const l=e.httpAgent??this.httpAgent??bE(c),u=e.timeout+1e3;"number"==typeof l?.options?.timeout&&u>(l.options.timeout??0)&&(l.options.timeout=u),this.idempotencyHeader&&"get"!==r&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);return{req:{method:r,...i&&{body:i},headers:this.buildHeaders({options:e,headers:a,contentLength:o,retryCount:t}),...l&&{agent:l},signal:e.signal??null},url:c,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:r,retryCount:n}){const s={};r&&(s["content-length"]=r);const a=this.defaultHeaders(e);return Ax(s,a),Ax(s,t),nx(e.body)&&"node"!==mE&&delete s["content-type"],void 0===Rx(a,"x-stainless-retry-count")&&void 0===Rx(t,"x-stainless-retry-count")&&(s["x-stainless-retry-count"]=String(n)),void 0===Rx(a,"x-stainless-timeout")&&void 0===Rx(t,"x-stainless-timeout")&&e.timeout&&(s["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(s,t),s}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new OE("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");return 6e5}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map((e=>[...e]))):{...e}:{}}makeStatusError(e,t,r,n){return AE.generate(e,t,r,n)}request(e,t=null){return new lx(this.makeRequest(e,t))}async makeRequest(e,t){const r=await e,n=r.maxRetries??this.maxRetries;null==t&&(t=n),await this.prepareOptions(r);const{req:s,url:a,timeout:i}=this.buildRequest(r,{retryCount:n-t});if(await this.prepareRequest(s,{url:a,options:r}),Ix("request",a,r,s.headers),r.signal?.aborted)throw new IE;const o=new AbortController,c=await this.fetchWithTimeout(a,s,i,o).catch(Tx);if(c instanceof Error){if(r.signal?.aborted)throw new IE;if(t)return this.retryRequest(r,t);if("AbortError"===c.name)throw new RE;throw new ME({cause:c})}const l=px(c.headers);if(!c.ok){if(t&&this.shouldRetry(c)){return Ix(`response (error; ${`retrying, ${t} attempts remaining`})`,c.status,a,l),this.retryRequest(r,t,l)}const e=await c.text().catch((e=>Tx(e).message)),n=_x(e),s=n?void 0:e;Ix(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,c.status,a,l,s);throw this.makeStatusError(c.status,n,s,l)}return{response:c,options:r,controller:o}}requestAPIList(e,t){const r=this.makeRequest(t,null);return new hx(this,r,e)}buildURL(e,t){const r=Sx(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return Px(n)||(t={...n,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}stringifyQuery(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new OE(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)})).join("&")}async fetchWithTimeout(e,t,r,n){const{signal:s,...a}=t||{};s&&s.addEventListener("abort",(()=>n.abort()));const i=setTimeout((()=>n.abort()),r),o={signal:n.signal,...a};o.method&&(o.method=o.method.toUpperCase());const c=setTimeout((()=>{if(o&&o?.agent?.sockets)for(const e of Object.values(o?.agent?.sockets).flat())e?.setKeepAlive&&e.setKeepAlive(!0,6e4)}),6e4);return this.fetch.call(void 0,e,o).finally((()=>{clearTimeout(i),clearTimeout(c)}))}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,r){let n;const s=r?.["retry-after-ms"];if(s){const e=parseFloat(s);Number.isNaN(e)||(n=e)}const a=r?.["retry-after"];if(a&&!n){const e=parseFloat(a);n=Number.isNaN(e)?Date.parse(a)-Date.now():1e3*e}if(!(n&&0<=n&&n<6e4)){const r=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,r)}return await Ex(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const r=t-e;return Math.min(.5*Math.pow(2,r),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${pE}`}}class dx{constructor(e,t,r,n){sx.set(this,void 0),ax(this,sx,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new OE("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&"object"==typeof t.query)t.query={...t.query,...e.params};else if("url"in e){const r=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[t,n]of r)e.url.searchParams.set(t,n);t.query=void 0,t.path=e.url.toString()}return await ix(this,sx,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(sx=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class hx extends lx{constructor(e,t,r){super(t,(async t=>new r(e,t.response,await ox(t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const px=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const r=t.toString();return e[r.toLowerCase()]||e[r]}}),mx={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},fx=e=>"object"==typeof e&&null!==e&&!Px(e)&&Object.keys(e).every((e=>Ox(mx,e))),gx=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":pE,"X-Stainless-OS":bx(Deno.build.os),"X-Stainless-Arch":yx(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":pE,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":pE,"X-Stainless-OS":bx(process.platform),"X-Stainless-Arch":yx(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const e=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{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:t,pattern:r}of e){const e=r.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":pE,"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":pE,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const yx=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",bx=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let wx;const vx=()=>wx??(wx=gx()),_x=e=>{try{return JSON.parse(e)}catch(e){return}},kx=/^[a-z][a-z0-9+.-]*:/i,Sx=e=>kx.test(e),Ex=e=>new Promise((t=>setTimeout(t,e))),xx=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new OE(`${e} must be an integer`);if(t<0)throw new OE(`${e} must be a positive integer`);return t},Tx=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e)try{return new Error(JSON.stringify(e))}catch{}return new Error(String(e))},Cx=e=>"undefined"!=typeof process?process.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function Px(e){if(!e)return!0;for(const t in e)return!1;return!0}function Ox(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ax(e,t){for(const r in t){if(!Ox(t,r))continue;const n=r.toLowerCase();if(!n)continue;const s=t[r];null===s?delete e[n]:void 0!==s&&(e[n]=s)}}function Ix(e,...t){"undefined"!=typeof process&&"true"===process?.env?.DEBUG&&console.log(`Anthropic:DEBUG:${e}`,...t)}const Mx=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),Rx=(e,t)=>{const r=t.toLowerCase();if((e=>"function"==typeof e?.get)(e)){const n=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,((e,t,r)=>t+r.toUpperCase()));for(const s of[t,r,t.toUpperCase(),n]){const t=e.get(s);if(t)return t}}for(const[n,s]of Object.entries(e))if(n.toLowerCase()===r)return Array.isArray(s)?(s.length<=1||console.warn(`Received ${s.length} entries for the ${t} header, using the first entry.`),s[0]):s};class jx{constructor(e){this._client=e}}class Nx extends jx{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}}class $x extends dx{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){if(this.options.query?.before_id){const e=this.first_id;return e?{params:{before_id:e}}:null}const e=this.last_id;return e?{params:{after_id:e}}:null}}class Lx{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new WE;for await(const t of this.iterator)for(const r of e.decode(t))yield JSON.parse(r);for(const t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),new OE("Attempted to iterate over a response with no body");return new Lx(GE(e.body),t)}}class Fx extends jx{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/v1/messages/batches/${e}`,t)}list(e={},t){return fx(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",Dx,{query:e,...t})}delete(e,t){return this._client.delete(`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){const r=await this.retrieve(e);if(!r.results_url)throw new OE(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})._thenUnwrap(((e,t)=>Lx.fromResponse(t.response,t.controller)))}}class Dx extends $x{}Fx.MessageBatchesPage=Dx;const zx=e=>{if(0===e.length)return e;let t=e[e.length-1];switch(t.type){case"separator":return e=e.slice(0,e.length-1),zx(e);case"number":let r=t.value[t.value.length-1];if("."===r||"-"===r)return e=e.slice(0,e.length-1),zx(e);case"string":let n=e[e.length-2];if("delimiter"===n?.type)return e=e.slice(0,e.length-1),zx(e);if("brace"===n?.type&&"{"===n.value)return e=e.slice(0,e.length-1),zx(e);break;case"delimiter":return e=e.slice(0,e.length-1),zx(e)}return e},Ux=e=>JSON.parse((e=>{let t="";return e.map((e=>{"string"===e.type?t+='"'+e.value+'"':t+=e.value})),t})((e=>{let t=[];return e.map((e=>{"brace"===e.type&&("{"===e.value?t.push("}"):t.splice(t.lastIndexOf("}"),1)),"paren"===e.type&&("["===e.value?t.push("]"):t.splice(t.lastIndexOf("]"),1))})),t.length>0&&t.reverse().map((t=>{"}"===t?e.push({type:"brace",value:"}"}):"]"===t&&e.push({type:"paren",value:"]"})})),e})(zx((e=>{let t=0,r=[];for(;t{})),Hx.set(this,(()=>{})),Vx.set(this,void 0),Gx.set(this,(()=>{})),Jx.set(this,(()=>{})),Zx.set(this,{}),Xx.set(this,!1),Yx.set(this,!1),Qx.set(this,!1),eT.set(this,!1),tT.set(this,void 0),rT.set(this,void 0),aT.set(this,(e=>{if(uT(this,Yx,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new IE),e instanceof IE)return uT(this,Qx,!0,"f"),this._emit("abort",e);if(e instanceof OE)return this._emit("error",e);if(e instanceof Error){const t=new OE(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new OE(String(e)))})),uT(this,Kx,new Promise(((e,t)=>{uT(this,Wx,e,"f"),uT(this,Hx,t,"f")})),"f"),uT(this,Vx,new Promise(((e,t)=>{uT(this,Gx,e,"f"),uT(this,Jx,t,"f")})),"f"),dT(this,Kx,"f").catch((()=>{})),dT(this,Vx,"f").catch((()=>{}))}get response(){return dT(this,tT,"f")}get request_id(){return dT(this,rT,"f")}async withResponse(){const e=await dT(this,Kx,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new pT;return t._run((()=>t._fromReadableStream(e))),t}static createMessage(e,t,r){const n=new pT;for(const e of t.messages)n._addMessageParam(e);return n._run((()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}_run(e){e().then((()=>{this._emitFinal(),this._emit("end")}),dT(this,aT,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),dT(this,Bx,"m",iT).call(this);const{response:s,data:a}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(s);for await(const e of a)dT(this,Bx,"m",oT).call(this,e);if(a.controller.signal?.aborted)throw new IE;dT(this,Bx,"m",cT).call(this)}_connected(e){this.ended||(uT(this,tT,e,"f"),uT(this,rT,e?.headers.get("request-id"),"f"),dT(this,Wx,"f").call(this,e),this._emit("connect"))}get ended(){return dT(this,Xx,"f")}get errored(){return dT(this,Yx,"f")}get aborted(){return dT(this,Qx,"f")}abort(){this.controller.abort()}on(e,t){return(dT(this,Zx,"f")[e]||(dT(this,Zx,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=dT(this,Zx,"f")[e];if(!r)return this;const n=r.findIndex((e=>e.listener===t));return n>=0&&r.splice(n,1),this}once(e,t){return(dT(this,Zx,"f")[e]||(dT(this,Zx,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,r)=>{uT(this,eT,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)}))}async done(){uT(this,eT,!0,"f"),await dT(this,Vx,"f")}get currentMessage(){return dT(this,qx,"f")}async finalMessage(){return await this.done(),dT(this,Bx,"m",nT).call(this)}async finalText(){return await this.done(),dT(this,Bx,"m",sT).call(this)}_emit(e,...t){if(dT(this,Xx,"f"))return;"end"===e&&(uT(this,Xx,!0,"f"),dT(this,Gx,"f").call(this));const r=dT(this,Zx,"f")[e];if(r&&(dT(this,Zx,"f")[e]=r.filter((e=>!e.once)),r.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return dT(this,eT,"f")||r?.length||Promise.reject(e),dT(this,Hx,"f").call(this,e),dT(this,Jx,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];dT(this,eT,"f")||r?.length||Promise.reject(e),dT(this,Hx,"f").call(this,e),dT(this,Jx,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",dT(this,Bx,"m",nT).call(this))}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),dT(this,Bx,"m",iT).call(this),this._connected(null);const n=JE.fromReadableStream(e,this.controller);for await(const e of n)dT(this,Bx,"m",oT).call(this,e);if(n.controller.signal?.aborted)throw new IE;dT(this,Bx,"m",cT).call(this)}[(qx=new WeakMap,Kx=new WeakMap,Wx=new WeakMap,Hx=new WeakMap,Vx=new WeakMap,Gx=new WeakMap,Jx=new WeakMap,Zx=new WeakMap,Xx=new WeakMap,Yx=new WeakMap,Qx=new WeakMap,eT=new WeakMap,tT=new WeakMap,rT=new WeakMap,aT=new WeakMap,Bx=new WeakSet,nT=function(){if(0===this.receivedMessages.length)throw new OE("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},sT=function(){if(0===this.receivedMessages.length)throw new OE("stream ended without producing a Message with role=assistant");const e=this.receivedMessages.at(-1).content.filter((e=>"text"===e.type)).map((e=>e.text));if(0===e.length)throw new OE("stream ended without producing a content block with type=text");return e.join(" ")},iT=function(){this.ended||uT(this,qx,void 0,"f")},oT=function(e){if(this.ended)return;const t=dT(this,Bx,"m",lT).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{const r=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===r.type&&this._emit("text",e.delta.text,r.text||"");break;case"citations_delta":"text"===r.type&&this._emit("citation",e.delta.citation,r.citations??[]);break;case"input_json_delta":"tool_use"===r.type&&r.input&&this._emit("inputJson",e.delta.partial_json,r.input);break;case"thinking_delta":"thinking"===r.type&&this._emit("thinking",e.delta.thinking,r.thinking);break;case"signature_delta":"thinking"===r.type&&this._emit("signature",r.signature);break;default:e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(t,!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":uT(this,qx,t,"f")}},cT=function(){if(this.ended)throw new OE("stream has ended, this shouldn't happen");const e=dT(this,qx,"f");if(!e)throw new OE("request ended without sending any chunks");return uT(this,qx,void 0,"f"),e},lT=function(e){let t=dT(this,qx,"f");if("message_start"===e.type){if(t)throw new OE(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new OE(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t;case"content_block_start":return t.content.push(e.content_block),t;case"content_block_delta":{const r=t.content.at(e.index);switch(e.delta.type){case"text_delta":"text"===r?.type&&(r.text+=e.delta.text);break;case"citations_delta":"text"===r?.type&&(r.citations??(r.citations=[]),r.citations.push(e.delta.citation));break;case"input_json_delta":if("tool_use"===r?.type){let t=r[hT]||"";t+=e.delta.partial_json,Object.defineProperty(r,hT,{value:t,enumerable:!1,writable:!0}),t&&(r.input=Ux(t))}break;case"thinking_delta":"thinking"===r?.type&&(r.thinking+=e.delta.thinking);break;case"signature_delta":"thinking"===r?.type&&(r.signature=e.delta.signature);break;default:e.delta}return t}}},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("streamEvent",(r=>{const n=t.shift();n?n.resolve(r):e.push(r)})),this.on("end",(()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),this.on("error",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise(((e,r)=>t.push({resolve:e,reject:r}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new JE(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class mT extends jx{constructor(){super(...arguments),this.batches=new Fx(this._client)}create(e,t){return e.model in fT&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${fT[e.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??(e.stream?6e5:this._client._calculateNonstreamingTimeout(e.max_tokens)),...t,stream:e.stream??!1})}stream(e,t){return pT.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}const fT={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};mT.Batches=Fx,mT.MessageBatchesPage=Dx;class gT extends jx{retrieve(e,t){return this._client.get(`/v1/models/${e}`,t)}list(e={},t){return fx(e)?this.list({},e):this._client.getAPIList("/v1/models",yT,{query:e,...t})}}class yT extends $x{}gT.ModelInfosPage=yT;class bT extends jx{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return fx(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",wT,{query:e,...t})}}class wT extends $x{}bT.BetaModelInfosPage=wT;class vT extends jx{create(e,t){const{betas:r,...n}=e;return this._client.post("/v1/messages/batches?beta=true",{body:n,...t,headers:{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},r){if(fx(t))return this.retrieve(e,{},t);const{betas:n}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...r,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}list(e={},t){if(fx(e))return this.list({},e);const{betas:r,...n}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",_T,{query:n,...t,headers:{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},r){if(fx(t))return this.delete(e,{},t);const{betas:n}=t;return this._client.delete(`/v1/messages/batches/${e}?beta=true`,{...r,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}cancel(e,t={},r){if(fx(t))return this.cancel(e,{},t);const{betas:n}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}async results(e,t={},r){if(fx(t))return this.results(e,{},t);const n=await this.retrieve(e);if(!n.results_url)throw new OE(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);const{betas:s}=t;return this._client.get(n.results_url,{...r,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...r?.headers},__binaryResponse:!0})._thenUnwrap(((e,t)=>Lx.fromResponse(t.response,t.controller)))}}class _T extends $x{}vT.BetaMessageBatchesPage=_T;var kT,ST,ET,xT,TT,CT,PT,OT,AT,IT,MT,RT,jT,NT,$T,LT,FT,DT,zT,UT,BT,qT,KT=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},WT=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};const HT="__json_buf";class VT{constructor(){kT.add(this),this.messages=[],this.receivedMessages=[],ST.set(this,void 0),this.controller=new AbortController,ET.set(this,void 0),xT.set(this,(()=>{})),TT.set(this,(()=>{})),CT.set(this,void 0),PT.set(this,(()=>{})),OT.set(this,(()=>{})),AT.set(this,{}),IT.set(this,!1),MT.set(this,!1),RT.set(this,!1),jT.set(this,!1),NT.set(this,void 0),$T.set(this,void 0),DT.set(this,(e=>{if(KT(this,MT,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new IE),e instanceof IE)return KT(this,RT,!0,"f"),this._emit("abort",e);if(e instanceof OE)return this._emit("error",e);if(e instanceof Error){const t=new OE(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new OE(String(e)))})),KT(this,ET,new Promise(((e,t)=>{KT(this,xT,e,"f"),KT(this,TT,t,"f")})),"f"),KT(this,CT,new Promise(((e,t)=>{KT(this,PT,e,"f"),KT(this,OT,t,"f")})),"f"),WT(this,ET,"f").catch((()=>{})),WT(this,CT,"f").catch((()=>{}))}get response(){return WT(this,NT,"f")}get request_id(){return WT(this,$T,"f")}async withResponse(){const e=await WT(this,ET,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new VT;return t._run((()=>t._fromReadableStream(e))),t}static createMessage(e,t,r){const n=new VT;for(const e of t.messages)n._addMessageParam(e);return n._run((()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}_run(e){e().then((()=>{this._emitFinal(),this._emit("end")}),WT(this,DT,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),WT(this,kT,"m",zT).call(this);const{response:s,data:a}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(s);for await(const e of a)WT(this,kT,"m",UT).call(this,e);if(a.controller.signal?.aborted)throw new IE;WT(this,kT,"m",BT).call(this)}_connected(e){this.ended||(KT(this,NT,e,"f"),KT(this,$T,e?.headers.get("request-id"),"f"),WT(this,xT,"f").call(this,e),this._emit("connect"))}get ended(){return WT(this,IT,"f")}get errored(){return WT(this,MT,"f")}get aborted(){return WT(this,RT,"f")}abort(){this.controller.abort()}on(e,t){return(WT(this,AT,"f")[e]||(WT(this,AT,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=WT(this,AT,"f")[e];if(!r)return this;const n=r.findIndex((e=>e.listener===t));return n>=0&&r.splice(n,1),this}once(e,t){return(WT(this,AT,"f")[e]||(WT(this,AT,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,r)=>{KT(this,jT,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)}))}async done(){KT(this,jT,!0,"f"),await WT(this,CT,"f")}get currentMessage(){return WT(this,ST,"f")}async finalMessage(){return await this.done(),WT(this,kT,"m",LT).call(this)}async finalText(){return await this.done(),WT(this,kT,"m",FT).call(this)}_emit(e,...t){if(WT(this,IT,"f"))return;"end"===e&&(KT(this,IT,!0,"f"),WT(this,PT,"f").call(this));const r=WT(this,AT,"f")[e];if(r&&(WT(this,AT,"f")[e]=r.filter((e=>!e.once)),r.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return WT(this,jT,"f")||r?.length||Promise.reject(e),WT(this,TT,"f").call(this,e),WT(this,OT,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];WT(this,jT,"f")||r?.length||Promise.reject(e),WT(this,TT,"f").call(this,e),WT(this,OT,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",WT(this,kT,"m",LT).call(this))}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),WT(this,kT,"m",zT).call(this),this._connected(null);const n=JE.fromReadableStream(e,this.controller);for await(const e of n)WT(this,kT,"m",UT).call(this,e);if(n.controller.signal?.aborted)throw new IE;WT(this,kT,"m",BT).call(this)}[(ST=new WeakMap,ET=new WeakMap,xT=new WeakMap,TT=new WeakMap,CT=new WeakMap,PT=new WeakMap,OT=new WeakMap,AT=new WeakMap,IT=new WeakMap,MT=new WeakMap,RT=new WeakMap,jT=new WeakMap,NT=new WeakMap,$T=new WeakMap,DT=new WeakMap,kT=new WeakSet,LT=function(){if(0===this.receivedMessages.length)throw new OE("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},FT=function(){if(0===this.receivedMessages.length)throw new OE("stream ended without producing a Message with role=assistant");const e=this.receivedMessages.at(-1).content.filter((e=>"text"===e.type)).map((e=>e.text));if(0===e.length)throw new OE("stream ended without producing a content block with type=text");return e.join(" ")},zT=function(){this.ended||KT(this,ST,void 0,"f")},UT=function(e){if(this.ended)return;const t=WT(this,kT,"m",qT).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{const r=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===r.type&&this._emit("text",e.delta.text,r.text||"");break;case"citations_delta":"text"===r.type&&this._emit("citation",e.delta.citation,r.citations??[]);break;case"input_json_delta":"tool_use"===r.type&&r.input&&this._emit("inputJson",e.delta.partial_json,r.input);break;case"thinking_delta":"thinking"===r.type&&this._emit("thinking",e.delta.thinking,r.thinking);break;case"signature_delta":"thinking"===r.type&&this._emit("signature",r.signature);break;default:e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(t,!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":KT(this,ST,t,"f")}},BT=function(){if(this.ended)throw new OE("stream has ended, this shouldn't happen");const e=WT(this,ST,"f");if(!e)throw new OE("request ended without sending any chunks");return KT(this,ST,void 0,"f"),e},qT=function(e){let t=WT(this,ST,"f");if("message_start"===e.type){if(t)throw new OE(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new OE(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t;case"content_block_start":return t.content.push(e.content_block),t;case"content_block_delta":{const r=t.content.at(e.index);switch(e.delta.type){case"text_delta":"text"===r?.type&&(r.text+=e.delta.text);break;case"citations_delta":"text"===r?.type&&(r.citations??(r.citations=[]),r.citations.push(e.delta.citation));break;case"input_json_delta":if("tool_use"===r?.type){let t=r[HT]||"";t+=e.delta.partial_json,Object.defineProperty(r,HT,{value:t,enumerable:!1,writable:!0}),t&&(r.input=Ux(t))}break;case"thinking_delta":"thinking"===r?.type&&(r.thinking+=e.delta.thinking);break;case"signature_delta":"thinking"===r?.type&&(r.signature=e.delta.signature);break;default:e.delta}return t}}},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("streamEvent",(r=>{const n=t.shift();n?n.resolve(r):e.push(r)})),this.on("end",(()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),this.on("error",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise(((e,r)=>t.push({resolve:e,reject:r}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new JE(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}const GT={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};class JT extends jx{constructor(){super(...arguments),this.batches=new vT(this._client)}create(e,t){const{betas:r,...n}=e;return n.model in GT&&console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${GT[n.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:n,timeout:this._client._options.timeout??(n.stream?6e5:this._client._calculateNonstreamingTimeout(n.max_tokens)),...t,headers:{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}stream(e,t){return VT.createMessage(this,e,t)}countTokens(e,t){const{betas:r,...n}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:n,...t,headers:{"anthropic-beta":[...r??[],"token-counting-2024-11-01"].toString(),...t?.headers}})}}JT.Batches=vT,JT.BetaMessageBatchesPage=_T;class ZT extends jx{constructor(){super(...arguments),this.models=new bT(this._client),this.messages=new JT(this._client)}}var XT;ZT.Models=bT,ZT.BetaModelInfosPage=wT,ZT.Messages=JT;class YT extends ux{constructor({baseURL:e=Cx("ANTHROPIC_BASE_URL"),apiKey:t=Cx("ANTHROPIC_API_KEY")??null,authToken:r=Cx("ANTHROPIC_AUTH_TOKEN")??null,...n}={}){const s={apiKey:t,authToken:r,...n,baseURL:e||"https://api.anthropic.com"};if(!s.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new OE("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");super({baseURL:s.baseURL,timeout:s.timeout??6e5,httpAgent:s.httpAgent,maxRetries:s.maxRetries,fetch:s.fetch}),this.completions=new Nx(this),this.messages=new mT(this),this.models=new gT(this),this.beta=new ZT(this),this._options=s,this.apiKey=t,this.authToken=r}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(e,t){if(!(this.apiKey&&e["x-api-key"]||null===t["x-api-key"]||this.authToken&&e.authorization||null===t.authorization))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders(e){const t=this.apiKeyAuth(e),r=this.bearerAuth(e);return null==t||Px(t)?null==r||Px(r)?{}:r:t}apiKeyAuth(e){return null==this.apiKey?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){return null==this.authToken?{}:{Authorization:`Bearer ${this.authToken}`}}}XT=YT,YT.Anthropic=XT,YT.HUMAN_PROMPT="\n\nHuman:",YT.AI_PROMPT="\n\nAssistant:",YT.DEFAULT_TIMEOUT=6e5,YT.AnthropicError=OE,YT.APIError=AE,YT.APIConnectionError=ME,YT.APIConnectionTimeoutError=RE,YT.APIUserAbortError=IE,YT.NotFoundError=LE,YT.ConflictError=FE,YT.RateLimitError=zE,YT.BadRequestError=jE,YT.AuthenticationError=NE,YT.InternalServerError=UE,YT.PermissionDeniedError=$E,YT.UnprocessableEntityError=DE,YT.toFile=ex,YT.fileFromPath=wE,YT.Completions=Nx,YT.Messages=mT,YT.Models=gT,YT.ModelInfosPage=yT,YT.Beta=ZT;const{HUMAN_PROMPT:QT,AI_PROMPT:eC}=YT;class tC extends Zt{static lc_name(){return"AnthropicToolsOutputParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","anthropic","output_parsers"]}),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){let t=e;if("string"==typeof e)try{t=JSON.parse(e)}catch(t){throw new Yt(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.message)}`,e)}else t=e;if(void 0===this.zodSchema)return t;const r=await this.zodSchema.safeParseAsync(t);if(r.success)return r.data;throw new Yt(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.error.errors)}`,JSON.stringify(t,null,2))}async parseResult(e){const t=e.flatMap((e=>{const{message:t}=e;if(!Array.isArray(t.content))return[];return rC(t.content)[0]}));if(void 0===t[0])throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[r]=t;return await this._validateResult(r.args)}}function rC(e){const t=[];for(const r of e)"tool_use"===r.type&&t.push({name:r.name,args:r.input,id:r.id,type:"tool_call"});return t}function nC(e){const t=(0,se.parseBase64DataUrl)({dataUrl:e});if(t)return{type:"base64",media_type:t.mime_type,data:t.data};let r;try{r=new URL(e)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(e)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join("\n\n"))}if("http:"===r.protocol||"https:"===r.protocol)return{type:"url",url:e};throw new Error([`Invalid image URL protocol: ${JSON.stringify(r.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join("\n\n"))}function sC(e){if(void 0===e.id)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:e.id,name:e.name,input:e.args}}const aC={providerName:"anthropic",fromStandardTextBlock:e=>({type:"text",text:e.text,..."citations"in(e.metadata??{})?{citations:e.metadata.citations}:{},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}),fromStandardImageBlock(e){if("url"===e.source_type){const t=(0,se.parseBase64DataUrl)({dataUrl:e.url,asTypedArray:!1});return t?{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:e.url,media_type:e.mime_type??""},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}}if("base64"===e.source_type)return{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type??""},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${e.source_type}`)},fromStandardFileBlock(e){const t=(e.mime_type??"").split(";")[0];if("url"===e.source_type){if("application/pdf"===t||""===t)return{type:"document",source:{type:"url",url:e.url,media_type:e.mime_type??""},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},..."citations"in(e.metadata??{})?{citations:e.metadata.citations}:{},..."context"in(e.metadata??{})?{context:e.metadata.context}:{},..."title"in(e.metadata??{})?{title:e.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${e.mime_type}`)}if("text"===e.source_type){if("text/plain"===t||""===t)return{type:"document",source:{type:"text",data:e.text,media_type:e.mime_type??""},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},..."citations"in(e.metadata??{})?{citations:e.metadata.citations}:{},..."context"in(e.metadata??{})?{context:e.metadata.context}:{},..."title"in(e.metadata??{})?{title:e.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${e.mime_type}`)}if("base64"===e.source_type){if("application/pdf"===t||""===t)return{type:"document",source:{type:"base64",data:e.data,media_type:"application/pdf"},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},..."citations"in(e.metadata??{})?{citations:e.metadata.citations}:{},..."context"in(e.metadata??{})?{context:e.metadata.context}:{},..."title"in(e.metadata??{})?{title:e.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(t))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:e.data,media_type:t}}]},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},..."citations"in(e.metadata??{})?{citations:e.metadata.citations}:{},..."context"in(e.metadata??{})?{context:e.metadata.context}:{},..."title"in(e.metadata??{})?{title:e.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${e.mime_type}`)}throw new Error(`Unsupported file source type: ${e.source_type}`)}};function iC(e){const t=["tool_use","tool_result","input_json_delta"],r=["text","text_delta"];if("string"==typeof e)return e;{const n=e.map((e=>{if((0,se.isDataContentBlock)(e))return(0,se.convertToProviderContentBlock)(e,aC);const n="cache_control"in e?e.cache_control:void 0;if("image_url"===e.type){let t;return t="string"==typeof e.image_url?nC(e.image_url):nC(e.image_url.url),{type:"image",source:t,...n?{cache_control:n}:{}}}if(null!=(s=e)&&"object"==typeof s&&"type"in s&&"image"===s.type&&"source"in s&&"object"==typeof s.source&&null!=s.source&&"type"in s.source&&("base64"===s.source.type?"media_type"in s.source&&"string"==typeof s.source.media_type&&"data"in s.source&&"string"==typeof s.source.data:"url"===s.source.type&&"url"in s.source&&"string"==typeof s.source.url))return e;if("document"===e.type)return{...e,...n?{cache_control:n}:{}};if("thinking"===e.type){return{type:"thinking",thinking:e.thinking,signature:e.signature,...n?{cache_control:n}:{}}}if("redacted_thinking"===e.type){return{type:"redacted_thinking",data:e.data,...n?{cache_control:n}:{}}}if(r.find((t=>t===e.type))&&"text"in e)return{type:"text",text:e.text,...n?{cache_control:n}:{}};if(t.find((t=>t===e.type))){const t={...e};if("index"in t&&delete t.index,"input_json_delta"===t.type&&(t.type="tool_use"),"input"in t&&"string"==typeof t.input)try{t.input=JSON.parse(t.input)}catch{t.input={}}return{...t,...n?{cache_control:n}:{}}}throw new Error("Unsupported message content format");var s}));return n}}function oC(e){const t=function(e){const t=[];for(const r of e)if("tool"===r._getType())if("string"==typeof r.content){const e=t[t.length-1];"human"===e?._getType()&&Array.isArray(e.content)&&"type"in e.content[0]&&"tool_result"===e.content[0].type?e.content.push({type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}):t.push(new se.HumanMessage({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}else t.push(new se.HumanMessage({content:[{type:"tool_result",content:iC(r.content),tool_use_id:r.tool_call_id}]}));else t.push(r);return t}(e);let r;t.length>0&&"system"===t[0]._getType()&&(r=e[0].content);return{messages:cC((void 0!==r?t.slice(1):t).map((e=>{let t;if("human"===e._getType())t="user";else if("ai"===e._getType())t="assistant";else{if("tool"!==e._getType())throw"system"===e._getType()?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${e._getType()}" is not supported.`);t="user"}if((0,se.isAIMessage)(e)&&e.tool_calls?.length){if("string"==typeof e.content)return""===e.content?{role:t,content:e.tool_calls.map(sC)}:{role:t,content:[{type:"text",text:e.content},...e.tool_calls.map(sC)]};{const{content:r}=e;return!e.tool_calls.every((e=>r.find((t=>("tool_use"===t.type||"input_json_delta"===t.type)&&t.id===e.id))))&&console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:t,content:iC(e.content)}}}return{role:t,content:iC(e.content)}}))),system:r}}function cC(e){if(!e||e.length<=1)return e;const t=[];let r=e[0];const n=e=>"string"==typeof e?[{type:"text",text:e}]:e,s=e=>"user"===e.role&&("string"!=typeof e.content&&(Array.isArray(e.content)&&e.content.every((e=>"tool_result"===e.type))));for(let a=1;a=1&&"input"in e.content[0]?"string"==typeof e.content[0].input?e.content[0].input:JSON.stringify(e.content[0].input):Array.isArray(e.content)&&e.content.length>=1&&"text"in e.content[0]?e.content[0].text:void 0}class pC extends zt{static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}constructor(e){if(super(e??{}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"anthropicApiKey",{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,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"topK",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:2048}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"claude-2.1"}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"claude-2.1"}),Object.defineProperty(this,"invocationKwargs",{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,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"clientOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"thinking",{enumerable:!0,configurable:!0,writable:!0,value:{type:"disabled"}}),Object.defineProperty(this,"batchClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamingClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"createClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.anthropicApiKey=e?.apiKey??e?.anthropicApiKey??(0,Sn.getEnvironmentVariable)("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!e?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=e?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=e?.anthropicApiUrl,this.modelName=e?.model??e?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=e?.invocationKwargs??{},this.temperature=e?.temperature??this.temperature,this.topK=e?.topK??this.topK,this.topP=e?.topP??this.topP,this.maxTokens=e?.maxTokensToSample??e?.maxTokens??this.maxTokens,this.stopSequences=e?.stopSequences??this.stopSequences,this.streaming=e?.streaming??!1,this.streamUsage=e?.streamUsage??this.streamUsage,this.thinking=e?.thinking??this.thinking,this.createClient=e?.createClient??(e=>new YT(e))}getLsParams(e){const t=this.invocationParams(e);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e){if(e&&e.length)return e.map((e=>{if(function(e){return"input_schema"in e}(e))return e;if(It(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if(hn(e))return{name:e.name,description:e.description,input_schema:Lt(e.schema)?(0,Nt.Ik)(e.schema):e.schema};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)}))}bindTools(e,t){return this.bind({tools:this.formatStructuredToolToAnthropic(e),...t})}invocationParams(e){const t=(r=e?.tool_choice,r?"any"===r?{type:"any"}:"auto"===r?{type:"auto"}:"string"==typeof r?{type:"tool",name:r}:r:void 0);var r;if("enabled"===this.thinking.type){if(-1!==this.topK)throw new Error("topK is not supported when thinking is enabled");if(-1!==this.topP)throw new Error("topP is not supported when thinking is enabled");if(1!==this.temperature)throw new Error("temperature is not supported when thinking is enabled");return{model:this.model,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e?.tools),tool_choice:t,thinking:this.thinking,...this.invocationKwargs}}return{model:this.model,temperature:this.temperature,top_k:this.topK,top_p:this.topP,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e?.tools),tool_choice:t,thinking:this.thinking,...this.invocationKwargs}}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(e,t,r){const n={...this.invocationParams(t),...oC(e),stream:!0},s=!function(e){return!!(e.tools&&e.tools.length>0)}(n)&&!function(e){for(const t of e.messages??[])if("string"!=typeof t.content)for(const e of t.content??[])if("object"==typeof e&&null!=e&&"document"===e.type&&"object"==typeof e.citations&&e.citations.enabled)return!0;return!1}(n)&&!function(e){return!(!e.thinking||"enabled"!==e.thinking.type)}(n),a=await this.createStreamWithRetry(n,{headers:t.headers});for await(const e of a){if(t.signal?.aborted)throw a.controller.abort(),new Error("AbortError: User aborted the request.");const n=this.streamUsage??t.streamUsage,i=lC(e,{streamUsage:n,coerceContentToString:s});if(!i)continue;const{chunk:o}=i,c=hC(o),l=new $t.ChatGenerationChunk({message:new se.AIMessageChunk({content:o.content,additional_kwargs:o.additional_kwargs,tool_call_chunks:o.tool_call_chunks,usage_metadata:n?o.usage_metadata:void 0,response_metadata:o.response_metadata,id:o.id}),text:c??""});yield l,await(r?.handleLLMNewToken(c??"",void 0,void 0,void 0,void 0,{chunk:l}))}}async _generateNonStreaming(e,t,r){const n=await this.completionWithRetry({...t,stream:!1,...oC(e)},r),{content:s,...a}=n,i=function(e,t){const r=t.usage,n=null!=r?{input_tokens:r.input_tokens??0,output_tokens:r.output_tokens??0,total_tokens:(r.input_tokens??0)+(r.output_tokens??0),input_token_details:{cache_creation:r.cache_creation_input_tokens,cache_read:r.cache_read_input_tokens}}:void 0;if(1===e.length&&"text"===e[0].type)return[{text:e[0].text,message:new se.AIMessage({content:e[0].text,additional_kwargs:t,usage_metadata:n,response_metadata:t,id:t.id})}];{const r=rC(e);return[{text:"",message:new se.AIMessage({content:e,additional_kwargs:t,tool_calls:r,usage_metadata:n,response_metadata:t,id:t.id})}]}}(s,a),{role:o,type:c,...l}=a;return{generations:i,llmOutput:l}}async _generate(e,t,r){if(this.stopSequences&&t.stop)throw new Error('"stopSequence" parameter found in input and default params');const n=this.invocationParams(t);if(n.stream){let n;const s=this._streamResponseChunks(e,t,r);for await(const e of s)n=void 0===n?e:n.concat(e);if(void 0===n)throw new Error("No chunks returned from Anthropic API.");return{generations:[{text:n.text,message:n.message}]}}return this._generateNonStreaming(e,n,{signal:t.signal,headers:t.headers})}async createStreamWithRetry(e,t){if(!this.streamingClient){const e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}return this.caller.call((async()=>{try{return await this.streamingClient.messages.create({...e,...this.invocationKwargs,stream:!0},t)}catch(e){throw dC(e)}}))}async completionWithRetry(e,t){if(!this.batchClient){const e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}return this.caller.callWithOptions({signal:t.signal??void 0},(async()=>{try{return await this.batchClient.messages.create({...e,...this.invocationKwargs},t)}catch(e){throw dC(e)}}))}_llmType(){return"anthropic"}withStructuredOutput(e,t){const r=e,n=t?.name,s=t?.method,a=t?.includeRaw;if("jsonMode"===s)throw new Error('Anthropic only supports "functionCalling" as a method.');let i,o,c,l=n??"extract";if(Lt(r)){const e=(0,Nt.Ik)(r);o=[{name:l,description:e.description??"A function available to call.",input_schema:e}],i=new tC({returnSingle:!0,keyName:l,zodSchema:r})}else{let e;"string"==typeof r.name&&"string"==typeof r.description&&"object"==typeof r.input_schema&&null!=r.input_schema?(e=r,l=r.name):e={name:l,description:r.description??"",input_schema:r},o=[e],i=new tC({returnSingle:!0,keyName:l})}if("enabled"===this.thinking?.type){const e="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(e),c=this.bind({tools:o});const t=t=>{if(!t.tool_calls||0===t.tool_calls.length)throw new Error(e);return t};c=c.pipe(t)}else c=this.bind({tools:o,tool_choice:{type:"tool",name:l}});if(!a)return c.pipe(i).withConfig({runName:"ChatAnthropicStructuredOutput"});const u=te.assign({parsed:(e,t)=>i.invoke(e.raw,t)}),d=te.assign({parsed:()=>null}),h=u.withFallbacks({fallbacks:[d]});return Y.zZ.from([{raw:c},h]).withConfig({runName:"StructuredOutputRunnable"})}}class mC extends pC{}const fC=M.z.object({provider:M.z.enum(["openai","claude"]),model:M.z.string().optional(),temperature:M.z.number().min(0).max(2).optional().default(.2),apiKey:M.z.string().optional(),proxyUrl:M.z.string().url().optional(),debugMode:M.z.boolean().default(!1)}),gC="gpt-4o",yC="claude-3-5-sonnet";class bC{static createOpenAIProvider(e){const t=e.model||gC,r=e.apiKey||this.DEFAULT_API_KEY,n=e.proxyUrl||this.DEFAULT_PROXY_URL,s=new dE({modelName:t,temperature:e.temperature||.2,apiKey:r,configuration:{baseURL:n,apiKey:r,dangerouslyAllowBrowser:!0}});return e.debugMode&&X.log("LangChainProviderFactory",`Created OpenAI provider with model: ${t}`),s}static createAnthropicProvider(e){const t=e.model||yC,r=e.apiKey||this.DEFAULT_API_KEY,n=e.proxyUrl||this.DEFAULT_PROXY_URL,s=new mC({model:t,temperature:e.temperature||0,apiKey:r,anthropicApiUrl:n});return e.debugMode&&X.log("LangChainProviderFactory",`Created Anthropic provider with model: ${t}`),s}static createProvider(e){const t=fC.parse(e);switch(t.provider){case"openai":return this.createOpenAIProvider(t);case"claude":return this.createAnthropicProvider(t);default:throw new Error(`Unsupported LangChain provider: ${t.provider}. Supported providers: 'openai', 'claude'`)}}static createOpenAI(e,t){const r={provider:"openai",temperature:t?.temperature??.2,debugMode:t?.debugMode??!1,model:e,apiKey:t?.apiKey,proxyUrl:t?.proxyUrl};return this.createOpenAIProvider(r)}static createClaude(e,t){const r={provider:"claude",temperature:t?.temperature??0,debugMode:t?.debugMode??!1,model:e,apiKey:t?.apiKey,proxyUrl:t?.proxyUrl};return this.createAnthropicProvider(r)}static create(e,t,r){return this.createProvider({provider:e,model:t,temperature:"claude"===e?0:.2,debugMode:r??!1})}}bC.DEFAULT_PROXY_URL="http://llm.nxtscape.ai",bC.DEFAULT_API_KEY="sk-xmIa7rAyujEDHPLRyYpwzQ";const wC=M.z.object({llmProvider:M.z.object({provider:M.z.enum(["claude","openai"]).default("claude"),model:M.z.string().optional()}),debug:M.z.boolean().default(!1).optional()});M.z.object({success:M.z.boolean(),messages:M.z.array(M.z.any()).optional(),pageState:M.z.object({url:M.z.string(),title:M.z.string(),domain:M.z.string()}).optional(),error:M.z.string().optional(),duration:M.z.number().optional(),timestamp:M.z.string().optional(),debug:M.z.object({stepCount:M.z.number(),executionTrace:M.z.array(M.z.object({step:M.z.number(),type:M.z.string(),role:M.z.string(),content:M.z.any().optional(),toolCalls:M.z.array(M.z.any()).optional(),toolCallId:M.z.string().optional()}))}).optional()});const vC=!0;X.initialize({debugMode:vC});const _C=new class{constructor(e){this.productivityAgent=null,this.browserContext=null,this.currentAbortController=null,this.currentQuery=null,this.config=wC.parse(e),X.initialize({debugMode:this.config.debug||!1}),X.log("NxtScape","Initializing NxtScape with ProductivityAgent for enhanced tab management")}async initialize(){X.log("NxtScape","Initializing browser context and ProductivityAgent");try{this.browserContext=new cm({debugMode:this.config.debug});const e=this.config.llmProvider.provider,t=this.config.llmProvider.model,r=this.config.debug,n=bC.create(e,t,r);this.productivityAgent=new lS({llmProvider:n,browserContext:this.browserContext,debugMode:!!this.config.debug,maxSteps:15}),X.log("NxtScape","NxtScape initialized successfully with ProductivityAgent")}catch(e){const t=e instanceof Error?e.message:String(e);throw X.log("NxtScape",`Failed to initialize: ${t}`,"error"),new Error(`NxtScape initialization failed: ${t}`)}}async getBrowserState(){try{if(!this.browserContext)return{url:"about:blank",title:"New Tab",domain:"unknown"};const e=await this.browserContext.getCurrentPage(),t=await e.getState();let r="unknown";try{if(t.url&&"about:blank"!==t.url){r=new URL(t.url).hostname}}catch{}return{url:t.url,title:t.title,domain:r}}catch(e){return X.log("NxtScape",`Error getting browser state: ${e}`,"error"),{url:"about:blank",title:"New Tab",domain:"unknown"}}}async close(){try{X.log("NxtScape","Closing resources"),this.browserContext&&await this.browserContext.cleanup(),this.productivityAgent=null,this.browserContext=null,X.log("NxtScape","Resources closed successfully")}catch(e){X.log("NxtScape",`Error during close: ${e}`,"error")}}async run(e,t){const r=Date.now();if(X.log("NxtScape",`Processing user query with ProductivityAgent streaming: ${e}`),!this.productivityAgent||!this.browserContext)throw new Error("NxtScape.initialize() must be awaited before run()");if(this.isRunning())throw new Error("Another task is already running. Cancel it first or wait for completion.");this.currentAbortController=new AbortController,this.currentQuery=e;try{const n={id:"user-query",kind:"browse",instruction:e,output:"result"},s=new uS;X.log("NxtScape","Executing query with ProductivityAgent streaming support");const a={...t,abortController:this.currentAbortController},i=await this.productivityAgent.execute(n,s,a),o=await this.getBrowserState(),c=Date.now()-r,l=this.currentAbortController.signal.aborted||i?.cancelled;l?X.log("NxtScape",`Query execution cancelled after ${c}ms`):X.log("NxtScape",`Query execution completed with ProductivityAgent in ${c}ms`);const u={success:!1!==i?.success&&!l,messages:i?.messages||[],pageState:o,duration:c,timestamp:(new Date).toISOString()};return i?.stepCount&&(u.debug={stepCount:i.stepCount,executionTrace:i.messages?.map(((e,t)=>({step:t+1,type:e.constructor?.name||"Unknown",role:e._getType?.()||e.type||"unknown",content:e.content,toolCalls:e.tool_calls,toolCallId:e.tool_call_id})))||[]}),(i?.error||l)&&(u.error=i?.error||"Task was cancelled by user",u.success=!1),u}catch(e){const t=e instanceof Error?e.message:String(e),n=Date.now()-r,s=e instanceof Error&&"AbortError"===e.name;s?X.log("NxtScape",`Query execution cancelled: ${t}`):X.log("NxtScape",`Error processing query with ProductivityAgent: ${t}`,"error");return{success:!1,error:s?"Task was cancelled by user":t,pageState:await this.getBrowserState(),duration:n,timestamp:(new Date).toISOString()}}finally{this.currentAbortController=null,this.currentQuery=null}}async getCurrentState(){return this.getBrowserState()}isInitialized(){return null!==this.productivityAgent&&null!==this.browserContext}cancel(){if(this.currentAbortController&&!this.currentAbortController.signal.aborted){const e=this.currentQuery;return X.log("NxtScape",`Cancelling current ProductivityAgent task execution: "${e}"`),this.currentAbortController.abort(),{wasCancelled:!0,query:e||void 0}}return{wasCancelled:!1}}isRunning(){return null!==this.currentAbortController&&!this.currentAbortController.signal.aborted}}({llmProvider:{provider:"claude",model:"claude-3-5-sonnet"},debug:vC});function kC(e,t="info"){X.log("Background",e,t)}const SC=new Map,EC=new Map;function xC(e){const t=e.name;kC(`Port connected: ${t}`),EC.set(t,e),X.registerPort(t,e),e.onMessage.addListener(((e,t)=>{!function(e,t){try{const{type:r,payload:n,id:s}=e;switch(r!==I.HEARTBEAT&&kC(`Port message received: ${JSON.stringify(e)} on port: ${t.name}`),r===I.EXECUTE_QUERY&&kC(`šŸŽÆ EXECUTE_QUERY received from ${t.name}: ${JSON.stringify(n)}`),r){case I.LOG:!function(e){const{source:t,message:r,level:n="info"}=e;kC(`[${t}] ${r}`,n)}(n);break;case I.EXECUTE_QUERY:!async function(e,t,r){try{const{query:n}=e;kC(`Received user query via port: ${n}`),t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"running",message:"Processing query..."},id:r}),await _C.initialize();const s=function(){let e=0;return{onSystemMessage:t=>{kC(`šŸ”„ System message: ${t}`);const r={step:++e,action:t,details:{content:t,messageType:"SystemMessage"}};CC({step:r.step,action:r.action,status:TC(r.action),details:{content:r.details?.content,messageType:r.details?.messageType}})},onToolCall:(t,r)=>{kC(`šŸ”„ Tool call: ${t} with args: ${JSON.stringify(r)}`);const n={step:++e,action:`šŸ› ļø ${t}`,details:{toolName:t,toolArgs:r,messageType:"ToolCall"}};CC({step:n.step,action:n.action,status:TC(n.action),details:{toolName:n.details?.toolName,toolArgs:n.details?.toolArgs,messageType:n.details?.messageType}})},onToolResult:(t,r)=>{kC(`šŸ”„ Tool result: ${t} -> ${r.substring(0,100)}...`);const n={step:e,action:`āœ… ${t}`,details:{toolResult:r,content:r,messageType:"ToolResponse"}};CC({step:n.step,action:n.action,status:TC(n.action),details:{content:n.details?.content,toolResult:n.details?.toolResult,messageType:n.details?.messageType}})},onFinalizeSegment:(t,r)=>{if(r.trim()){kC(`šŸ”„ Agent response: ${r.substring(0,100)}...`);const t={step:++e,action:"Agent Response",details:{content:r,messageType:"LLMResponse"}};CC({step:t.step,action:t.action,status:TC(t.action),details:{content:t.details?.content,messageType:t.details?.messageType}})}},onError:e=>{kC(`šŸ”„ Stream error: ${e.message}`,"error")},onStreamingComplete:()=>{kC("šŸ”„ Streaming completed")}}}(),a=await _C.run(n,s);t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"completed",message:"Query executed successfully",result:a},id:r}),PC(a)}catch(e){const n=e instanceof Error?e.message:String(e);kC(`Query execution failed: ${n}`,"error"),t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"failed",error:n},id:r})}}(n,t,s);break;case I.RUN_EXAMPLE:!async function(e,t,r){try{const{exampleType:n}=e;let s;switch(kC(`Running browser example: ${n}`),t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"running",message:`Running ${n} browser automation example...`},id:r}),await _C.initialize(),n){case"basic":s="Find under 100$ headphones on amazon";break;case"multiTab":s="Navigate to https://www.google.com, take a screenshot, then navigate to https://www.example.com and describe the page";break;default:throw new Error(`Unknown example type: ${n}`)}const a=await _C.run(s);t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"completed",message:`${n} example executed successfully`,result:a},id:r}),PC(a)}catch(e){const n=e instanceof Error?e.message:String(e);kC(`Example execution failed: ${n}`,"error"),t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"failed",error:n},id:r})}}(n,t,s);break;case I.HEARTBEAT:!function(e,t){t.postMessage({type:I.HEARTBEAT_ACK,payload:{timestamp:e.timestamp}})}(n,t);break;case I.CANCEL_TASK:!function(e,t,r){try{const{reason:n,source:s}=e;kC(`Task cancellation requested from ${s||"unknown"}: ${n||"No reason provided"}`);const a=_C.cancel();if(a.wasCancelled){const e=a.query||"Unknown query";kC(`Task successfully cancelled: "${e}"`);const s=`Task cancelled: "${e}"`;t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"cancelled",message:s},id:r}),PC({success:!1,cancelled:!0,error:s,cancelledQuery:e,reason:n||"User requested cancellation"})}else kC("No running task to cancel","warning"),t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"idle",message:"No running task to cancel"},id:r})}catch(e){const n=e instanceof Error?e.message:String(e);kC(`Error handling task cancellation: ${n}`,"error"),t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"error",error:`Failed to cancel task: ${n}`},id:r})}}(n,t,s);break;case I.AGENT_STREAM_UPDATE:kC("Received AGENT_STREAM_UPDATE (this shouldn't happen)","warning");break;default:kC(`Unknown port message type: ${r}`,"warning"),t.postMessage({type:I.WORKFLOW_STATUS,payload:{error:`Unknown message type: ${r}`},id:s})}}catch(r){const n=r instanceof Error?r.message:String(r);kC(`Error handling port message: ${n}`,"error"),t.postMessage({type:I.WORKFLOW_STATUS,id:e.id,payload:{error:n}})}}(e,t)})),e.onDisconnect.addListener((()=>{kC(`Port disconnected: ${t}`),EC.delete(t),X.unregisterPort(t)}))}function TC(e){return e.includes("Error")||e.includes("Failed")?"error":e.includes("Thinking")||e.includes("Processing")?"thinking":(e.includes("Executing"),"executing")}function CC(e){for(const[t,r]of EC)if(t===G.OPTIONS_TO_BACKGROUND||t===G.SIDEPANEL_TO_BACKGROUND)try{r.postMessage({type:I.AGENT_STREAM_UPDATE,payload:e})}catch(e){kC(`Failed to broadcast stream update to ${t}: ${e}`,"warning")}}function PC(e){for(const[t,r]of EC)t!==G.OPTIONS_TO_BACKGROUND&&t!==G.SIDEPANEL_TO_BACKGROUND||r.postMessage({type:I.WORKFLOW_STATUS,payload:{success:!0,result:e}})}kC("ParallelManus extension initialized"),chrome.runtime.onConnect.addListener(xC),chrome.action.onClicked.addListener((async e=>{kC("Extension icon clicked, toggling side panel");try{e.id?(await chrome.sidePanel.open({tabId:e.id}),kC(`Side panel opened for tab ${e.id}`)):kC("No active tab found for side panel","warning")}catch(e){kC(`Error toggling side panel: ${e instanceof Error?e.message:String(e)}`,"error"),chrome.runtime.openOptionsPage()}})),chrome.tabs.onCreated.addListener((e=>{e.id&&(SC.set(e.id,{url:e.url||""}),kC(`Tab created: ${e.id}`))})),chrome.tabs.onUpdated.addListener(((e,t,r)=>{"complete"===t.status&&r.url&&(SC.set(e,{url:r.url}),kC(`Tab updated: ${e}, URL: ${r.url}`))})),chrome.tabs.onRemoved.addListener((e=>{SC.delete(e),kC(`Tab removed: ${e}`)}))})()})(); \ No newline at end of file +(()=>{var e,t,r={58:(e,t,r)=>{"use strict";r.r(t),r.d(t,{AsyncGeneratorWithSetup:()=>l,IterableReadableStream:()=>i,atee:()=>o,concat:()=>c,pipeGeneratorWithSetup:()=>u});var n=r(765),s=r(4350),a=r(9830);class i 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 e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){const t=e.getReader();return new i({start:e=>function r(){return t.read().then((({done:t,value:n})=>{if(!t)return e.enqueue(n),r();e.close()}))}(),cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new i({async pull(t){const{value:r,done:n}=await e.next();n&&t.close(),t.enqueue(r)},async cancel(t){await e.return(t)}})}}function o(e,t=2){const r=Array.from({length:t},(()=>[]));return r.map((async function*(t){for(;;)if(0===t.length){const t=await e.next();for(const e of r)e.push(t)}else{if(t[0].done)return;yield t.shift().value}}))}function c(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if("string"==typeof e&&"string"==typeof t)return e+t;if("number"==typeof e&&"number"==typeof t)return e+t;if("concat"in e&&"function"==typeof e.concat)return e.concat(t);if("object"==typeof e&&"object"==typeof t){const r={...e};for(const[e,n]of Object.entries(t))e in r&&!Array.isArray(r[e])?r[e]=c(r[e],n):r[e]=n;return r}throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}class l{constructor(e){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??this.config?.signal,this.setup=new Promise(((t,r)=>{s.Nx.runWithConfig((0,n.DY)(e.config),(async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then((e=>t(void 0)),r)}),!0)}))}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?s.Nx.runWithConfig((0,n.DY)(this.config),this.signal?async()=>(0,a.o)(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 u(e,t,r,n,...s){const a=new l({generator:t,startSetup:r,signal:n}),i=await a.setup;return{output:e(a,i,...s),setup:i}}},144:(e,t,r)=>{"use strict";const n=r(3908);e.exports=(e,t,r=!1)=>{if(e instanceof n)return e;try{return new n(e,t)}catch(e){if(!r)return null;throw e}}},199:(e,t,r)=>{"use strict";function n(e){return!(!e||"object"!=typeof e||!("type"in e)||"tool_call"!==e.type)}function s(e){return!!(e&&"object"==typeof e&&"toolCall"in e&&null!=e.toolCall&&"object"==typeof e.toolCall&&"id"in e.toolCall&&"string"==typeof e.toolCall.id)}r.d(t,{Ky:()=>n,hR:()=>s,qe:()=>a});class a extends Error{constructor(e,t){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=t}}},228:e=>{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function a(e,t,n,a,i){if("function"!=typeof n)throw new TypeError("The listener must be a function");var o=new s(n,a||e,i),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],o]:e._events[c].push(o):(e._events[c]=o,e._eventsCount++),e}function i(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function o(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,n,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},o.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,a=n.length,i=new Array(a);s{"use strict";const n=r(3908),s=r(8311);e.exports=(e,t,r)=>{let a=null,i=null,o=null;try{o=new s(t,r)}catch(e){return null}return e.forEach((e=>{o.test(e)&&(a&&1!==i.compare(e)||(a=e,i=new n(a,r)))})),a}},329:(e,t,r)=>{"use strict";r.d(t,{L:()=>a});var n=r(5311),s=r(6993);class a extends s.m{async formatPromptValue(e){const t=await this.format(e);return new n.StringPromptValue(t)}}},560:(e,t,r)=>{"use strict";const n=r(3908);e.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))},736:(e,t,r)=>{e.exports=function(e){function t(e){let r,s,a,i=null;function o(...e){if(!o.enabled)return;const n=o,s=Number(new Date),a=s-(r||s);n.diff=a,n.prev=r,n.curr=s,r=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,s)=>{if("%%"===r)return"%";i++;const a=t.formatters[s];if("function"==typeof a){const t=e[i];r=a.call(n,t),e.splice(i,1),i--}return r})),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return o.namespace=e,o.useColors=t.useColors(),o.color=t.selectColor(e),o.extend=n,o.destroy=t.destroy,Object.defineProperty(o,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(s!==t.namespaces&&(s=t.namespaces,a=t.enabled(e)),a),set:e=>{i=e}}),"function"==typeof t.init&&t.init(o),o}function n(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function s(e,t){let r=0,n=0,s=-1,a=0;for(;r"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(s(e,r))return!1;for(const r of t.names)if(s(e,r))return!0;return!1},t.humanize=r(6585),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{"use strict";r.d(t,{Yx:()=>o,rO:()=>i});var n=r(4785);const s=(...e)=>fetch(...e),a=Symbol.for("ls:fetch_implementation"),i=()=>{const e=globalThis[a];return!!e&&("function"==typeof e&&"Headers"in e&&"Request"in e&&"Response"in e)},o=e=>async(...t)=>{if(e||"true"===(0,n.Jz)("DEBUG")){const[e,r]=t;console.log(`→ ${r?.method||"GET"} ${e}`)}const r=await(globalThis[a]??s)(...t);return(e||"true"===(0,n.Jz)("DEBUG"))&&console.log(`← ${r.status} ${r.statusText} ${r.url}`),r}},765:(e,t,r)=>{"use strict";r.d(t,{DY:()=>d,SV:()=>o,ZI:()=>l,kJ:()=>i,p_:()=>a,tn:()=>u});var n=r(5042),s=r(4350);const a=25;async function i(e){return n.CallbackManager._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function o(...e){const t={};for(const r of e.filter((e=>!!e)))for(const e of Object.keys(r))if("metadata"===e)t[e]={...t[e],...r[e]};else if("tags"===e){const n=t[e]??[];t[e]=[...new Set(n.concat(r[e]??[]))]}else if("configurable"===e)t[e]={...t[e],...r[e]};else if("timeout"===e)void 0===t.timeout?t.timeout=r.timeout:void 0!==r.timeout&&(t.timeout=Math.min(t.timeout,r.timeout));else if("signal"===e)void 0===t.signal?t.signal=r.signal:void 0!==r.signal&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,r.signal]):t.signal=r.signal);else if("callbacks"===e){const e=t.callbacks,s=r.callbacks;if(Array.isArray(s))if(e)if(Array.isArray(e))t.callbacks=e.concat(s);else{const r=e.copy();for(const e of s)r.addHandler((0,n.ensureHandler)(e),!0);t.callbacks=r}else t.callbacks=s;else if(s)if(e)if(Array.isArray(e)){const r=s.copy();for(const t of e)r.addHandler((0,n.ensureHandler)(t),!0);t.callbacks=r}else t.callbacks=new n.CallbackManager(s._parentRunId,{handlers:e.handlers.concat(s.handlers),inheritableHandlers:e.inheritableHandlers.concat(s.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(s.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(s.inheritableTags))),metadata:{...e.metadata,...s.metadata}});else t.callbacks=s}else{const n=e;t[n]=r[n]??t[n]}return t}const c=new Set(["string","number","boolean"]);function l(e){const t=s.Nx.getRunnableConfig();let r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){const{runId:e,runName:n,...s}=t;r=Object.entries(s).reduce(((e,[t,r])=>(void 0!==r&&(e[t]=r),e)),r)}if(e&&(r=Object.entries(e).reduce(((e,[t,r])=>(void 0!==r&&(e[t]=r),e)),r)),r?.configurable)for(const e of Object.keys(r.configurable))c.has(typeof r.configurable[e])&&!r.metadata?.[e]&&(r.metadata||(r.metadata={}),r.metadata[e]=r.configurable[e]);if(void 0!==r.timeout){if(r.timeout<=0)throw new Error("Timeout must be a positive number");const e=AbortSignal.timeout(r.timeout);void 0!==r.signal?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,e])):r.signal=e,delete r.timeout}return r}function u(e={},{callbacks:t,maxConcurrency:r,recursionLimit:n,runName:s,configurable:a,runId:i}={}){const o=l(e);return void 0!==t&&(delete o.runName,o.callbacks=t),void 0!==n&&(o.recursionLimit=n),void 0!==r&&(o.maxConcurrency=r),void 0!==s&&(o.runName=s),void 0!==a&&(o.configurable={...o.configurable,...a}),void 0!==i&&delete o.runId,o}function d(e){return e?{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal}:void 0}},780:(e,t,r)=>{"use strict";function n(e,t=s){const r=(e=e.trim()).indexOf("```");if(-1===r)return t(e);let n=e.substring(r+3);n.startsWith("json\n")?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith("\n")&&(n=n.substring(1));const a=n.indexOf("```");let i=n;return-1!==a&&(i=n.substring(0,a)),t(i.trim())}function s(e){if(void 0===e)return null;try{return JSON.parse(e)}catch(e){}let t="";const r=[];let n=!1,s=!1;for(let a of e){if(n)'"'!==a||s?"\n"!==a||s?s="\\"===a&&!s:a="\\n":n=!1;else if('"'===a)n=!0,s=!1;else if("{"===a)r.push("}");else if("["===a)r.push("]");else if("}"===a||"]"===a){if(!r||r[r.length-1]!==a)return null;r.pop()}t+=a}n&&(t+='"');for(let e=r.length-1;e>=0;e-=1)t+=r[e];try{return JSON.parse(t)}catch(e){return null}}r.d(t,{D:()=>n,d:()=>s})},809:(e,t,r)=>{"use strict";r.d(t,{T:()=>n});const n="24.8.2"},874:(e,t,r)=>{"use strict";r.r(t),r.d(t,{NodeWebSocketTransport:()=>a});var n=r(1591),s=r(809);class a{static create(e,t){return new Promise(((r,i)=>{const o=new n(e,[],{followRedirects:!0,perMessageDeflate:!1,allowSynchronousEvents:!1,maxPayload:268435456,headers:{"User-Agent":`Puppeteer ${s.T}`,...t}});o.addEventListener("open",(()=>r(new a(o)))),o.addEventListener("error",i)}))}#e;onmessage;onclose;constructor(e){this.#e=e,this.#e.addEventListener("message",(e=>{this.onmessage&&this.onmessage.call(null,e.data)})),this.#e.addEventListener("close",(()=>{this.onclose&&this.onclose.call(null)})),this.#e.addEventListener("error",(()=>{}))}send(e){this.#e.send(e)}close(){this.#e.close()}}},909:(e,t,r)=>{"use strict";const n=r(3908);e.exports=(e,t,r)=>{const s=new n(e,r),a=new n(t,r);return s.compare(a)||s.compareBuild(a)}},1060:(e,t,r)=>{"use strict";r.r(t),r.d(t,{LogStreamCallbackHandler:()=>h,RunLog:()=>c,RunLogPatch:()=>o,isLogStreamHandler:()=>l});var n=r(6150),s=r(1590),a=r(58),i=r(7765);class o{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=(0,n.X6)({},t);return new c({ops:t,state:r[r.length-1].newDocument})}}class c extends o{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=(0,n.X6)(this.state,e.ops);return new c({ops:t,state:r[r.length-1].newDocument})}static fromRunLogPatch(e){const t=(0,n.X6)({},e.ops);return new c({ops:e.ops,state:t[t.length-1].newDocument})}}const l=e=>"log_stream_tracer"===e.name;async function u(e,t){if("original"===t)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:r}=e;return["retriever","llm","prompt"].includes(e.run_type)?r:1!==Object.keys(r).length||""!==r?.input?r.input:void 0}async function d(e,t){const{outputs:r}=e;return"original"===t||["retriever","llm","prompt"].includes(e.run_type)?r:void 0!==r&&1===Object.keys(r).length&&void 0!==r?.output?r.output:r}class h extends s.BaseTracer{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?.autoClose??!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,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=a.IterableReadableStream.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=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.run_type)),void 0!==this.includeTags&&(r=r||void 0!==t.find((e=>this.includeTags?.includes(e)))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.run_type)),void 0!==this.excludeTags&&(r=r&&t.every((e=>!this.excludeTags?.includes(e)))),r}async*tapOutputIterable(e,t){for await(const r of t){if(e!==this.rootId){const t=this.keyMapByRunId[e];t&&await this.writer.write(new o({ops:[{op:"add",path:`/logs/${t}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(void 0===this.rootId&&(this.rootId=e.id,await this.writer.write(new o({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;void 0===this.counterMapByRunName[e.name]&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=1===t?e.name:`${e.name}:${t}`;const r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};"streaming_events"===this._schemaFormat&&(r.inputs=await u(e,this._schemaFormat)),await this.writer.write(new o({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(void 0===t)return;const r=[];"streaming_events"===this._schemaFormat&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await u(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await d(e,this._schemaFormat)}),void 0!==e.end_time&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const n=new o({ops:r});await this.writer.write(n)}finally{if(e.id===this.rootId){const t=new o({ops:[{op:"replace",path:"/final_output",value:await d(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){const n=this.keyMapByRunId[e.id];if(void 0===n)return;let s;var a;void 0!==e.inputs.messages?(a=r?.chunk,s=void 0!==a&&void 0!==a.message?r?.chunk:new i.H({id:`run-${e.id}`,content:t})):s=t;const c=new o({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${n}/streamed_output/-`,value:s}]});await this.writer.write(c)}}},1123:e=>{"use strict";const t=/^[0-9]+$/,r=(e,r)=>{const n=t.test(e),s=t.test(r);return n&&s&&(e=+e,r=+r),e===r?0:n&&!s?-1:s&&!n?1:er(t,e)}},1259:(e,t,r)=>{"use strict";r.d(t,{Kj:()=>n.Kj,gk:()=>n.gk});var n=r(4547)},1261:(e,t,r)=>{"use strict";const n=r(3908),s=r(8311),a=r(5580);e.exports=(e,t)=>{e=new s(e,t);let r=new n("0.0.0");if(e.test(r))return r;if(r=new n("0.0.0-0"),e.test(r))return r;r=null;for(let t=0;t{const t=new n(e.semver.version);switch(e.operator){case">":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":i&&!a(t,i)||(i=t);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${e.operator}`)}})),!i||r&&!a(r,i)||(r=i)}return r&&e.test(r)?r:null}},1368:(e,t,r)=>{"use strict";function n(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t}/\n`,e}r.d(t,{Y:()=>n})},1590:(e,t,r)=>{"use strict";r.r(t),r.d(t,{BaseTracer:()=>i,isBaseTracer:()=>a});var n=r(5960);function s(e,t){return e&&!Array.isArray(e)&&"object"==typeof e?e:{[t]:e}}function a(e){return"function"==typeof e._addRunToRunMap}class i extends n.BaseCallbackHandler{constructor(e){super(...arguments),Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}copy(){return this}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`\n\n${e.stack}`:""):"string"==typeof e?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const t=function(e,t,r){const n=r.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(e).toISOString().slice(0,-1)}${n}Z`.replace(/[-:.]/g,"")+t}(e.start_time,e.id,e.execution_order),r={...e};if(void 0!==r.parent_run_id){const e=this.runMap.get(r.parent_run_id);e&&(this._addChildRun(e,r),e.child_execution_order=Math.max(e.child_execution_order,r.child_execution_order),r.trace_id=e.trace_id,void 0!==e.dotted_order&&(r.dotted_order=[e.dotted_order,t].join(".")))}else r.trace_id=r.id,r.dotted_order=t;return this.runMap.set(r.id,r),r}async _endTrace(e){const t=void 0!==e.parent_run_id&&this.runMap.get(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),this.runMap.delete(e.id),await(this.onRunUpdate?.(e))}_getExecutionOrder(e){const t=void 0!==e&&this.runMap.get(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,n,s,a,i,o){const c=this._getExecutionOrder(n),l=Date.now(),u=i?{...s,metadata:i}:s,d={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,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:u??{},tags:a||[]};return this._addRunToRunMap(d)}async handleLLMStart(e,t,r,n,s,a,i,o){const c=this.runMap.get(r)??this._createRunForLLMStart(e,t,r,n,s,a,i,o);return await(this.onRunCreate?.(c)),await(this.onLLMStart?.(c)),c}_createRunForChatModelStart(e,t,r,n,s,a,i,o){const c=this._getExecutionOrder(n),l=Date.now(),u=i?{...s,metadata:i}:s,d={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,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:u??{},tags:a||[]};return this._addRunToRunMap(d)}async handleChatModelStart(e,t,r,n,s,a,i,o){const c=this.runMap.get(r)??this._createRunForChatModelStart(e,t,r,n,s,a,i,o);return await(this.onRunCreate?.(c)),await(this.onLLMStart?.(c)),c}async handleLLMEnd(e,t,r,n,s){const a=this.runMap.get(t);if(!a||"llm"!==a?.run_type)throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=e,a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...s},await(this.onLLMEnd?.(a)),await this._endTrace(a),a}async handleLLMError(e,t,r,n,s){const a=this.runMap.get(t);if(!a||"llm"!==a?.run_type)throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...s},await(this.onLLMError?.(a)),await this._endTrace(a),a}_createRunForChainStart(e,t,r,n,s,a,i,o){const c=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:t,execution_order:c,child_execution_order:c,run_type:i??"chain",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(u)}async handleChainStart(e,t,r,n,s,a,i,o){const c=this.runMap.get(r)??this._createRunForChainStart(e,t,r,n,s,a,i,o);return await(this.onRunCreate?.(c)),await(this.onChainStart?.(c)),c}async handleChainEnd(e,t,r,n,a){const i=this.runMap.get(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=s(e,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),void 0!==a?.inputs&&(i.inputs=s(a.inputs,"input")),await(this.onChainEnd?.(i)),await this._endTrace(i),i}async handleChainError(e,t,r,n,a){const i=this.runMap.get(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()}),void 0!==a?.inputs&&(i.inputs=s(a.inputs,"input")),await(this.onChainError?.(i)),await this._endTrace(i),i}_createRunForToolStart(e,t,r,n,s,a,i){const o=this._getExecutionOrder(n),c=Date.now(),l={id:r,name:i??e.id[e.id.length-1],parent_run_id:n,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,r,n,s,a,i){const o=this.runMap.get(r)??this._createRunForToolStart(e,t,r,n,s,a,i);return await(this.onRunCreate?.(o)),await(this.onToolStart?.(o)),o}async handleToolEnd(e,t){const r=this.runMap.get(t);if(!r||"tool"!==r?.run_type)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(this.onToolEnd?.(r)),await this._endTrace(r),r}async handleToolError(e,t){const r=this.runMap.get(t);if(!r||"tool"!==r?.run_type)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(this.onToolError?.(r)),await this._endTrace(r),r}async handleAgentAction(e,t){const r=this.runMap.get(t);if(!r||"chain"!==r?.run_type)return;const n=r;n.actions=n.actions||[],n.actions.push(e),n.events.push({name:"agent_action",time:(new Date).toISOString(),kwargs:{action:e}}),await(this.onAgentAction?.(r))}async handleAgentEnd(e,t){const r=this.runMap.get(t);r&&"chain"===r?.run_type&&(r.events.push({name:"agent_end",time:(new Date).toISOString(),kwargs:{action:e}}),await(this.onAgentEnd?.(r)))}_createRunForRetrieverStart(e,t,r,n,s,a,i){const o=this._getExecutionOrder(n),c=Date.now(),l={id:r,name:i??e.id[e.id.length-1],parent_run_id:n,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,r,n,s,a,i){const o=this.runMap.get(r)??this._createRunForRetrieverStart(e,t,r,n,s,a,i);return await(this.onRunCreate?.(o)),await(this.onRetrieverStart?.(o)),o}async handleRetrieverEnd(e,t){const r=this.runMap.get(t);if(!r||"retriever"!==r?.run_type)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(this.onRetrieverEnd?.(r)),await this._endTrace(r),r}async handleRetrieverError(e,t){const r=this.runMap.get(t);if(!r||"retriever"!==r?.run_type)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(this.onRetrieverError?.(r)),await this._endTrace(r),r}async handleText(e,t){const r=this.runMap.get(t);r&&"chain"===r?.run_type&&(r.events.push({name:"text",time:(new Date).toISOString(),kwargs:{text:e}}),await(this.onText?.(r)))}async handleLLMNewToken(e,t,r,n,s,a){const i=this.runMap.get(r);if(!i||"llm"!==i?.run_type)throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return i.events.push({name:"new_token",time:(new Date).toISOString(),kwargs:{token:e,idx:t,chunk:a?.chunk}}),await(this.onLLMNewToken?.(i,e,{chunk:a?.chunk})),i}}},1591:e=>{"use strict";e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}},1673:(e,t,r)=>{"use strict";r.r(t),r.d(t,{AIMessage:()=>n.Od,AIMessageChunk:()=>n.H,BaseMessage:()=>s.XQ,BaseMessageChunk:()=>s.gj,ChatMessage:()=>a.cM,ChatMessageChunk:()=>a.XU,FunctionMessage:()=>i.mg,FunctionMessageChunk:()=>i.FK,HumanMessage:()=>o.xc,HumanMessageChunk:()=>o.a7,RemoveMessage:()=>d,SystemMessage:()=>c.tn,SystemMessageChunk:()=>c.uU,ToolMessage:()=>h.uf,ToolMessageChunk:()=>h.dr,_isMessageFieldWithRole:()=>s.dp,_mergeDicts:()=>s.ns,_mergeLists:()=>s.Vt,_mergeObj:()=>s.F7,_mergeStatus:()=>s.Iv,coerceMessageLikeToMessage:()=>l.K0,convertToChunk:()=>l.ih,convertToOpenAIImageBlock:()=>x.Vi,convertToProviderContentBlock:()=>x.up,defaultTextSplitter:()=>E,filterMessages:()=>m,getBufferString:()=>l.Sw,isAIMessage:()=>n.KX,isAIMessageChunk:()=>n.jm,isBase64ContentBlock:()=>x.cJ,isBaseMessage:()=>s.ny,isBaseMessageChunk:()=>s.AJ,isChatMessage:()=>a.kY,isChatMessageChunk:()=>a.bU,isDataContentBlock:()=>x.Fz,isFunctionMessage:()=>i.AP,isFunctionMessageChunk:()=>i.vl,isHumanMessage:()=>o.di,isHumanMessageChunk:()=>o.GZ,isIDContentBlock:()=>x.oe,isOpenAIToolCallArray:()=>s.Ao,isPlainTextContentBlock:()=>x.Ac,isSystemMessage:()=>c.X4,isSystemMessageChunk:()=>c.UF,isToolMessage:()=>h.wk,isToolMessageChunk:()=>h.P,isURLContentBlock:()=>x.W,mapChatMessagesToStoredMessages:()=>l.Js,mapStoredMessageToChatMessage:()=>l.Pz,mapStoredMessagesToChatMessages:()=>l.rf,mergeContent:()=>s._I,mergeMessageRuns:()=>g,parseBase64DataUrl:()=>x.Q7,parseMimeType:()=>x.Ej,trimMessages:()=>b});var n=r(7765),s=r(3490),a=r(4301),i=r(8675),o=r(5454),c=r(7974),l=r(6362),u=r(3313);class d extends s.XQ{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}}}var h=r(8009);const p=(e,t)=>{const r=[...new Set(t?.map((e=>{if("string"==typeof e)return e;const t=new e({});if(!("getType"in t)||"function"!=typeof t.getType)throw new Error("Invalid type provided.");return t.getType()})))],n=e.getType();return r.some((e=>e===n))};function m(e,t){return Array.isArray(e)?f(e,t):u.jY.from((t=>f(t,e)))}function f(e,t={}){const{includeNames:r,excludeNames:n,includeTypes:s,excludeTypes:a,includeIds:i,excludeIds:o}=t,c=[];for(const t of e)n&&t.name&&n.includes(t.name)||a&&p(t,a)||o&&t.id&&o.includes(t.id)||(s||i||r?(r&&t.name&&r.some((e=>e===t.name))||s&&p(t,s)||i&&t.id&&i.some((e=>e===t.id)))&&c.push(t):c.push(t));return c}function g(e){return Array.isArray(e)?y(e):u.jY.from(y)}function y(e){if(!e.length)return[];const t=[];for(const r of e){const e=r,n=t.pop();if(n)if("tool"===e.getType()||e.getType()!==n.getType())t.push(n,e);else{const r=(0,l.ih)(n),s=(0,l.ih)(e),a=r.concat(s);"string"==typeof r.content&&"string"==typeof s.content&&(a.content=`${r.content}\n${s.content}`),t.push(S(a))}else t.push(e)}return t}function b(e,t){if(Array.isArray(e)){const r=e;if(!t)throw new Error("Options parameter is required when providing messages.");return w(r,t)}{const t=e;return u.jY.from((e=>w(e,t))).withConfig({runName:"trim_messages"})}}async function w(e,t){const{maxTokens:r,tokenCounter:n,strategy:a="last",allowPartial:i=!1,endOn:o,startOn:c,includeSystem:l=!1,textSplitter:u}=t;if(c&&"first"===a)throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(l&&"first"===a)throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let d;d="getNumTokens"in n?async e=>(await Promise.all(e.map((e=>n.getNumTokens(e.content))))).reduce(((e,t)=>e+t),0):async e=>n(e);let h=E;if(u&&(h="splitText"in u?u.splitText:async e=>u(e)),"first"===a)return v(e,{maxTokens:r,tokenCounter:d,textSplitter:h,partialStrategy:i?"first":void 0,endOn:o});if("last"===a)return async function(e,t){const{allowPartial:r=!1,includeSystem:n=!1,endOn:a,startOn:i,...o}=t;let c=e.map((e=>{const t=Object.fromEntries(Object.entries(e).filter((([e])=>"type"!==e&&!e.startsWith("lc_"))));return k(e.getType(),t,(0,s.AJ)(e))}));if(a){const e=Array.isArray(a)?a:[a];for(;c.length>0&&!p(c[c.length-1],e);)c=c.slice(0,-1)}const l=n&&"system"===c[0]?.getType();let u=l?c.slice(0,1).concat(c.slice(1).reverse()):c.reverse();return u=await v(u,{...o,partialStrategy:r?"last":void 0,endOn:i}),l?[u[0],...u.slice(1).reverse()]:u.reverse()}(e,{maxTokens:r,tokenCounter:d,textSplitter:h,allowPartial:i,includeSystem:l,startOn:c,endOn:o});throw new Error(`Unrecognized strategy: '${a}'. Must be one of 'first' or 'last'.`)}async function v(e,t){const{maxTokens:r,tokenCounter:n,textSplitter:s,partialStrategy:a,endOn:i}=t;let o=[...e],c=0;for(let e=0;e0?o.slice(0,-e):o;if(await n(t)<=r){c=o.length-e;break}}if(c"type"!==e&&!e.startsWith("lc_")))),d=k(t.getType(),{...u,content:s}),h=[...o.slice(0,c),d];if(!(await n(h)<=r))break;o=h,c+=1,e=!0}e&&"last"===a&&(t.content=[...i].reverse())}if(!e){const e=o[c];let t;if(Array.isArray(e.content)&&e.content.some((e=>"string"==typeof e||"text"===e.type))){const r=e.content.find((e=>"text"===e.type&&e.text));t=r?.text}else"string"==typeof e.content&&(t=e.content);if(t){const i=await s(t),l=i.length;"last"===a&&i.reverse();for(let t=0;t0&&!p(o[c-1],e);)c-=1}return o.slice(0,c)}const _={human:{message:o.xc,messageChunk:o.a7},ai:{message:n.Od,messageChunk:n.H},system:{message:c.tn,messageChunk:c.uU},developer:{message:c.tn,messageChunk:c.uU},tool:{message:h.uf,messageChunk:h.dr},function:{message:i.mg,messageChunk:i.FK},generic:{message:a.cM,messageChunk:a.XU},remove:{message:d,messageChunk:d}};function k(e,t,r){let s,l;switch(e){case"human":r?s=new o.a7(t):l=new o.xc(t);break;case"ai":if(r){let e={...t};"tool_calls"in e&&(e={...e,tool_call_chunks:e.tool_calls?.map((e=>({...e,type:"tool_call_chunk",index:void 0,args:JSON.stringify(e.args)})))}),s=new n.H(e)}else l=new n.Od(t);break;case"system":r?s=new c.uU(t):l=new c.tn(t);break;case"developer":r?s=new c.uU({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}}):l=new c.tn({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if(!("tool_call_id"in t))throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");r?s=new h.dr(t):l=new h.uf(t);break;case"function":if(r)s=new i.FK(t);else{if(!t.name)throw new Error("FunctionMessage must have a 'name' field");l=new i.mg(t)}break;case"generic":if(!("role"in t))throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");r?s=new a.XU(t):l=new a.cM(t);break;default:throw new Error(`Unrecognized message type ${e}`)}if(r&&s)return s;if(l)return l;throw new Error(`Unrecognized message type ${e}`)}function S(e){const t=e.getType();let r;const n=Object.fromEntries(Object.entries(e).filter((([e])=>!["type","tool_call_chunks"].includes(e)&&!e.startsWith("lc_"))));if(t in _&&(r=k(t,n)),!r)throw new Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys(_)}`);return r}function E(e){const t=e.split("\n");return Promise.resolve([...t.slice(0,-1).map((e=>`${e}\n`)),t[t.length-1]])}var x=r(4291)},1688:(e,t,r)=>{"use strict";r.d(t,{gk:()=>n.gk});var n=r(3246)},1729:(e,t,r)=>{"use strict";const n=r(144);e.exports=(e,t)=>{const r=n(e,t);return r&&r.prerelease.length?r.prerelease:null}},1763:(e,t,r)=>{"use strict";const n=r(560);e.exports=(e,t)=>n(e,t,!0)},1832:(e,t,r)=>{"use strict";const n=r(144);e.exports=(e,t)=>{const r=n(e,null,!0),s=n(t,null,!0),a=r.compare(s);if(0===a)return null;const i=a>0,o=i?r:s,c=i?s:r,l=!!o.prerelease.length;if(!!c.prerelease.length&&!l){if(!c.patch&&!c.minor)return"major";if(0===c.compareMain(o))return c.minor&&!c.patch?"minor":"patch"}const u=l?"pre":"";return r.major!==s.major?u+"major":r.minor!==s.minor?u+"minor":r.patch!==s.patch?u+"patch":"prerelease"}},2111:(e,t,r)=>{"use strict";const n=r(4641),s=r(3999),a=r(5580),i=r(4089),o=r(7059),c=r(5200);e.exports=(e,t,r,l)=>{switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e===r;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e!==r;case"":case"=":case"==":return n(e,r,l);case"!=":return s(e,r,l);case">":return a(e,r,l);case">=":return i(e,r,l);case"<":return o(e,r,l);case"<=":return c(e,r,l);default:throw new TypeError(`Invalid operator: ${t}`)}}},2293:(e,t,r)=>{"use strict";r.r(t),r.d(t,{awaitAllCallbacks:()=>c,consumeCallback:()=>o});var n=r(3290),s=r(6968);let a;function i(){return void 0===a&&(a=new(0,n.default)({autoStart:!0,concurrency:1})),a}async function o(e,t){if(!0===t){const t=(0,s.X0)();void 0!==t?await t.run(void 0,(async()=>e())):await e()}else a=i(),a.add((async()=>{const t=(0,s.X0)();void 0!==t?await t.run(void 0,(async()=>e())):await e()}))}function c(){return void 0!==a?a.onIdle():Promise.resolve()}},2366:(e,t,r)=>{"use strict";r.d(t,{Ik:()=>z});const n=Symbol("Let zodToJsonSchema decide on which parser to use"),s={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"},a=e=>{const t=(e=>"string"==typeof e?{...s,name:e}:{...s,...e})(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map((([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}])))}};var i=r(4476);function o(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function c(e,t,r,n,s){e[t]=r,o(e,t,n,s)}function l(e,t){return $(e.type._def,t)}function u(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(((r,n)=>u(e,t,r)))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return d(e,t)}}const d=(e,t)=>{const r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(const n of e.checks)switch(n.kind){case"min":c(r,"minimum",n.value,n.message,t);break;case"max":c(r,"maximum",n.value,n.message,t)}return r};let h;const p=/^[cC][^\s-]{8,}$/,m=/^[0-9a-z]+$/,f=/^[0-9A-HJKMNP-TV-Z]{26}$/,g=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,y=()=>(void 0===h&&(h=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),h),b=/^(?:(?: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])$/,w=/^(([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])$/,v=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,k=/^[a-zA-Z0-9_-]{21}$/,S=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function E(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":c(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":c(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":C(r,"email",n.message,t);break;case"format:idn-email":C(r,"idn-email",n.message,t);break;case"pattern:zod":P(r,g,n.message,t)}break;case"url":C(r,"uri",n.message,t);break;case"uuid":C(r,"uuid",n.message,t);break;case"regex":P(r,n.regex,n.message,t);break;case"cuid":P(r,p,n.message,t);break;case"cuid2":P(r,m,n.message,t);break;case"startsWith":P(r,RegExp(`^${x(n.value,t)}`),n.message,t);break;case"endsWith":P(r,RegExp(`${x(n.value,t)}$`),n.message,t);break;case"datetime":C(r,"date-time",n.message,t);break;case"date":C(r,"date",n.message,t);break;case"time":C(r,"time",n.message,t);break;case"duration":C(r,"duration",n.message,t);break;case"length":c(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t),c(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":P(r,RegExp(x(n.value,t)),n.message,t);break;case"ip":"v6"!==n.version&&C(r,"ipv4",n.message,t),"v4"!==n.version&&C(r,"ipv6",n.message,t);break;case"base64url":P(r,_,n.message,t);break;case"jwt":P(r,S,n.message,t);break;case"cidr":"v6"!==n.version&&P(r,b,n.message,t),"v4"!==n.version&&P(r,w,n.message,t);break;case"emoji":P(r,y(),n.message,t);break;case"ulid":P(r,f,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":C(r,"binary",n.message,t);break;case"contentEncoding:base64":c(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":P(r,v,n.message,t)}break;case"nanoid":P(r,k,n.message,t)}return r}function x(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;re.format))?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):c(e,"format",t,r,n)}function P(e,t,r,n){e.pattern||e.allOf?.some((e=>e.pattern))?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:O(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):c(e,"pattern",O(t,n),r,n)}function O(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r=e.flags.includes("i"),n=e.flags.includes("m"),s=e.flags.includes("s"),a=r?e.source.toLowerCase():e.source;let i="",o=!1,c=!1,l=!1;for(let e=0;e({...r,[n]:$(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??{}})),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:$(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===i.kY.ZodString&&e.keyType._def.checks?.length){const{type:n,...s}=E(e.keyType._def,t);return{...r,propertyNames:s}}if(e.keyType?._def.typeName===i.kY.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===i.kY.ZodBranded&&e.keyType._def.type._def.typeName===i.kY.ZodString&&e.keyType._def.type._def.checks?.length){const{type:n,...s}=l(e.keyType._def,t);return{...r,propertyNames:s}}return r}const I={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const M=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map(((e,r)=>$(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]}))).filter((e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0)));return r.length?{anyOf:r}:void 0};function R(e,t){const r="openAi"===t.target,n={type:"object",properties:{}},s=[],a=e.shape();for(const e in a){let o=a[e];if(void 0===o||void 0===o._def)continue;let c=j(o);c&&r&&(o instanceof i.Ii&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),c=!1);const l=$(o._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==l&&(n.properties[e]=l,c||s.push(e))}s.length&&(n.required=s);const o=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return $(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==o&&(n.additionalProperties=o),n}function j(e){try{return e.isOptional()}catch{return!0}}const N=(e,t,r)=>{switch(t){case i.kY.ZodString:return E(e,r);case i.kY.ZodNumber:return function(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",o(r,"type",n.message,t);break;case"min":"jsonSchema7"===t.target?n.inclusive?c(r,"minimum",n.value,n.message,t):c(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),c(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?c(r,"maximum",n.value,n.message,t):c(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),c(r,"maximum",n.value,n.message,t));break;case"multipleOf":c(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case i.kY.ZodObject:return R(e,r);case i.kY.ZodBigInt:return function(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":"jsonSchema7"===t.target?n.inclusive?c(r,"minimum",n.value,n.message,t):c(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),c(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?c(r,"maximum",n.value,n.message,t):c(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),c(r,"maximum",n.value,n.message,t));break;case"multipleOf":c(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case i.kY.ZodBoolean:return{type:"boolean"};case i.kY.ZodDate:return u(e,r);case i.kY.ZodUndefined:return{not:{}};case i.kY.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(r);case i.kY.ZodArray:return function(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==i.kY.ZodAny&&(r.items=$(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&c(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&c(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(c(r,"minItems",e.exactLength.value,e.exactLength.message,t),c(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}(e,r);case i.kY.ZodUnion:case i.kY.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return M(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((e=>e._def.typeName in I&&(!e._def.checks||!e._def.checks.length)))){const e=r.reduce(((e,t)=>{const r=I[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e}),[]);return{type:e.length>1?e:e[0]}}if(r.every((e=>"ZodLiteral"===e._def.typeName&&!e.description))){const e=r.reduce(((e,t)=>{const r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}}),[]);if(e.length===r.length){const t=e.filter(((e,t,r)=>r.indexOf(e)===t));return{type:t.length>1?t:t[0],enum:r.reduce(((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value]),[])}}}else if(r.every((e=>"ZodEnum"===e._def.typeName)))return{type:"string",enum:r.reduce(((e,t)=>[...e,...t._def.values.filter((t=>!e.includes(t)))]),[])};return M(e,t)}(e,r);case i.kY.ZodIntersection:return function(e,t){const r=[$(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),$(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((e=>!!e));let n="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const s=[];return r.forEach((e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:r,...n}=e;t=n}else n=void 0;s.push(t)}else s.push(...e.allOf),void 0===e.unevaluatedProperties&&(n=void 0);var t})),s.length?{allOf:s,...n}:void 0}(e,r);case i.kY.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map(((e,r)=>$(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[]),additionalItems:$(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map(((e,r)=>$(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[])}}(e,r);case i.kY.ZodRecord:return A(e,r);case i.kY.ZodLiteral:return function(e,t){const r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}(e,r);case i.kY.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case i.kY.ZodNativeEnum:return function(e){const t=e.values,r=Object.keys(e.values).filter((e=>"number"!=typeof t[t[e]])).map((e=>t[e])),n=Array.from(new Set(r.map((e=>typeof e))));return{type:1===n.length?"string"===n[0]?"string":"number":["string","number"],enum:r}}(e);case i.kY.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:I[e.innerType._def.typeName],nullable:!0}:{type:[I[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const r=$(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=$(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case i.kY.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return $(e.innerType._def,t);const r=$(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}})(e,r);case i.kY.ZodMap:return function(e,t){return"record"===t.mapStrategy?A(e,t):{type:"array",maxItems:125,items:{type:"array",items:[$(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},$(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}(e,r);case i.kY.ZodSet:return function(e,t){const r={type:"array",uniqueItems:!0,items:$(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&c(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&c(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}(e,r);case i.kY.ZodLazy:return()=>e.getter()._def;case i.kY.ZodPromise:return function(e,t){return $(e.type._def,t)}(e,r);case i.kY.ZodNaN:case i.kY.ZodNever:return{not:{}};case i.kY.ZodEffects:return function(e,t){return"input"===t.effectStrategy?$(e.schema._def,t):{}}(e,r);case i.kY.ZodAny:case i.kY.ZodUnknown:return{};case i.kY.ZodDefault:return function(e,t){return{...$(e.innerType._def,t),default:e.defaultValue()}}(e,r);case i.kY.ZodBranded:return l(e,r);case i.kY.ZodReadonly:case i.kY.ZodCatch:return((e,t)=>$(e.innerType._def,t))(e,r);case i.kY.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return $(e.in._def,t);if("output"===t.pipeStrategy)return $(e.out._def,t);const r=$(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,$(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter((e=>void 0!==e))}})(e,r);case i.kY.ZodFunction:case i.kY.ZodVoid:case i.kY.ZodSymbol:default:return}};function $(e,t,r=!1){const s=t.seen.get(e);if(t.override){const a=t.override?.(e,t,s,r);if(a!==n)return a}if(s&&!r){const e=L(s,t);if(void 0!==e)return e}const a={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,a);const i=N(e,e.typeName,t),o="function"==typeof i?$(i(),t):i;if(o&&D(e,t,o),t.postProcess){const r=t.postProcess(o,e,t);return a.jsonSchema=o,r}return a.jsonSchema=o,o}const L=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:F(t.currentPath,e.path)};case"none":case"seen":return e.path.lengtht.currentPath[r]===e))?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{}):"seen"===t.$refStrategy?{}:void 0}},F=(e,t)=>{let r=0;for(;r(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),z=(e,t)=>{const r=a(t),n="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce(((e,[t,n])=>({...e,[t]:$(n._def,{...r,currentPath:[...r.basePath,r.definitionPath,t]},!0)??{}})),{}):void 0,s="string"==typeof t?t:"title"===t?.nameStrategy?void 0:t?.name,i=$(e._def,void 0===s?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??{},o="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==o&&(i.title=o);const c=void 0===s?n?{...i,[r.definitionPath]:n}:i:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:i}};return"jsonSchema7"===r.target?c.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==r.target&&"openAi"!==r.target||(c.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("anyOf"in c||"oneOf"in c||"allOf"in c||"type"in c&&Array.isArray(c.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),c}},2525:(e,t,r)=>{"use strict";const n=r(7638),s=r(560);e.exports=(e,t,r)=>{const a=[];let i=null,o=null;const c=e.sort(((e,t)=>s(e,t,r)));for(const e of c){n(e,t,r)?(o=e,i||(i=e)):(o&&a.push([i,o]),o=null,i=null)}i&&a.push([i,null]);const l=[];for(const[e,t]of a)e===t?l.push(e):t||e!==c[0]?t?e===c[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`):l.push("*");const u=l.join(" || "),d="string"==typeof t.raw?t.raw:String(t);return u.length{"use strict";const t=/[\p{Lu}]/u,r=/[\p{Ll}]/u,n=/^[\p{Lu}](?![\p{Lu}])/gu,s=/([\p{Alpha}\p{N}_]|$)/u,a=/[_.\- ]+/,i=new RegExp("^"+a.source),o=new RegExp(a.source+s.source,"gu"),c=new RegExp("\\d+"+s.source,"gu"),l=(e,s)=>{if("string"!=typeof e&&!Array.isArray(e))throw new TypeError("Expected the input to be `string | string[]`");if(s={pascalCase:!1,preserveConsecutiveUppercase:!1,...s},0===(e=Array.isArray(e)?e.map((e=>e.trim())).filter((e=>e.length)).join("-"):e.trim()).length)return"";const a=!1===s.locale?e=>e.toLowerCase():e=>e.toLocaleLowerCase(s.locale),l=!1===s.locale?e=>e.toUpperCase():e=>e.toLocaleUpperCase(s.locale);if(1===e.length)return s.pascalCase?l(e):a(e);return e!==a(e)&&(e=((e,n,s)=>{let a=!1,i=!1,o=!1;for(let c=0;c(n.lastIndex=0,e.replace(n,(e=>t(e)))))(e,a):a(e),s.pascalCase&&(e=l(e.charAt(0))+e.slice(1)),((e,t)=>(o.lastIndex=0,c.lastIndex=0,e.replace(o,((e,r)=>t(r))).replace(c,(e=>t(e)))))(e,l)};e.exports=l,e.exports.default=l},2771:(e,t,r)=>{"use strict";r.d(t,{FewShotPromptTemplate:()=>o,s:()=>c});var n=r(329),s=r(9849),a=r(3650),i=r(3766);class o extends n.L{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"exampleSeparator",{enumerable:!0,configurable:!0,writable:!0,value:"\n\n"}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.assign(this,e),void 0!==this.examples&&void 0!==this.exampleSelector)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(void 0===this.examples&&void 0===this.exampleSelector)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),(0,s.Ns)(this.prefix+this.suffix,this.templateFormat,e)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(e){if(void 0!==this.examples)return this.examples;if(void 0!==this.exampleSelector)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(e){const t=this.inputVariables.filter((t=>!(t in e))),r={...this.partialVariables??{},...e},n={...this,inputVariables:t,partialVariables:r};return new o(n)}async format(e){const t=await this.mergePartialAndUserVariables(e),r=await this.getExamples(t),n=await Promise.all(r.map((e=>this.examplePrompt.format(e)))),a=[this.prefix,...n,this.suffix].join(this.exampleSeparator);return(0,s.Xm)(a,this.templateFormat,t)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(void 0!==this.outputParser)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(e){const{example_prompt:t}=e;if(!t)throw new Error("Missing example prompt");const r=await a.PromptTemplate.deserialize(t);let n;if(!Array.isArray(e.examples))throw new Error("Invalid examples format. Only list or string are supported.");return n=e.examples,new o({inputVariables:e.input_variables,examplePrompt:r,examples:n,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}}class c extends i.qF{_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"exampleSeparator",{enumerable:!0,configurable:!0,writable:!0,value:"\n\n"}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.examples=e.examples,this.examplePrompt=e.examplePrompt,this.exampleSeparator=e.exampleSeparator??"\n\n",this.exampleSelector=e.exampleSelector,this.prefix=e.prefix??"",this.suffix=e.suffix??"",this.templateFormat=e.templateFormat??"f-string",this.validateTemplate=e.validateTemplate??!0,void 0!==this.examples&&void 0!==this.exampleSelector)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(void 0===this.examples&&void 0===this.exampleSelector)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),(0,s.Ns)(this.prefix+this.suffix,this.templateFormat,e)}}async getExamples(e){if(void 0!==this.examples)return this.examples;if(void 0!==this.exampleSelector)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(e){const t=await this.mergePartialAndUserVariables(e);let r=await this.getExamples(t);r=r.map((e=>{const t={};return this.examplePrompt.inputVariables.forEach((r=>{t[r]=e[r]})),t}));const n=[];for(const e of r){const t=await this.examplePrompt.formatMessages(e);n.push(...t)}return n}async format(e){const t=await this.mergePartialAndUserVariables(e),r=await this.getExamples(t),n=(await Promise.all(r.map((e=>this.examplePrompt.formatMessages(e))))).flat().map((e=>e.content)),a=[this.prefix,...n,this.suffix].join(this.exampleSeparator);return(0,s.Xm)(a,this.templateFormat,t)}async partial(e){const t=this.inputVariables.filter((t=>!(t in e))),r={...this.partialVariables??{},...e},n={...this,inputVariables:t,partialVariables:r};return new c(n)}}},2938:(e,t,r)=>{"use strict";const n=r(3908);e.exports=(e,t)=>new n(e,t).major},3007:(e,t,r)=>{"use strict";const n=r(3908);e.exports=(e,t,r,s,a)=>{"string"==typeof r&&(a=s,s=r,r=void 0);try{return new n(e instanceof n?e.version:e,r).inc(t,s,a).version}catch(e){return null}}},3246:(e,t,r)=>{"use strict";r.d(t,{gk:()=>l,m5:()=>u});var n=r(5230),s=r(4785),a=r(9056);var i=r(6232);const o=Symbol.for("lc:context_variables");class c{constructor(e,t,r){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}),this.metadata=e,this.tags=t,this.project_name=r}static fromHeader(e){const t=e.split(",");let r,n={},s=[];for(const e of t){const[t,a]=e.split("="),i=decodeURIComponent(a);"langsmith-metadata"===t?n=JSON.parse(i):"langsmith-tags"===t?s=i.split(","):"langsmith-project"===t&&(r=i)}return new c(n,s,r)}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 l{constructor(e){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,"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}),u(e))return void Object.assign(this,{...e});const t=l.getDefaultConfig(),{metadata:r,...n}=e,s=n.client??l.getSharedClient(),a={...r,...n?.extra?.metadata};if(n.extra={...n.extra,metadata:a},Object.assign(this,{...t,...n,client:s}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const e=function(e,t,r=1){const n=r.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(e).toISOString().slice(0,-1)}${n}Z`.replace(/[-:.]/g,"")+t}(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+e:this.dotted_order=e}}static getDefaultConfig(){return{id:n.A(),run_type:"chain",project_name:(0,s.Jz)("PROJECT")??(0,s.Az)("LANGCHAIN_SESSION")??"default",child_runs:[],api_url:(0,s.Az)("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:(0,s.Az)("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return l.sharedClient||(l.sharedClient=new a.Kj),l.sharedClient}createChild(e){const t=this.child_execution_order+1,r=new l({...e,parent_run:this,project_name:this.project_name,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t});o in this&&(r[o]=this[o]);const n=Symbol.for("lc:child_config"),s=e.extra?.[n]??this.extra[n];if(void 0!==(a=s)&&"object"==typeof a.callbacks&&(h(a.callbacks?.handlers)||h(a.callbacks))){const e={...s},t=function(e){return"object"==typeof e&&null!=e&&Array.isArray(e.handlers)}(e.callbacks)?e.callbacks.copy?.():void 0;t&&(Object.assign(t,{_parentRunId:r.id}),t.handlers?.find(d)?.updateFromRunTree?.(r),e.callbacks=t),r.extra[n]=e}var a;const i=new Set;let c=this;for(;null!=c&&!i.has(c.id);)i.add(c.id),c.child_execution_order=Math.max(c.child_execution_order,t),c=c.parent_run;return this.child_runs.push(r),r}async end(e,t,r=Date.now(),n){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??r,n&&Object.keys(n).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...n}}:{metadata:n})}_convertToCreate(e,t,r=!0){const n=e.extra??{};if(n.runtime||(n.runtime={}),t)for(const[e,r]of Object.entries(t))n.runtime[e]||(n.runtime[e]=r);let s,a;r?(a=e.parent_run?.id,s=[]):(s=e.child_runs.map((e=>this._convertToCreate(e,t,r))),a=void 0);return{id:e.id,name:e.name,start_time:e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:n,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:s,parent_run_id:a,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments}}async postRun(e=!0){try{const t=(0,s.Ec)(),r=await this._convertToCreate(this,t,!0);if(await this.client.createRun(r),!e){(0,i.m)("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const e of this.child_runs)await e.postRun(!1)}}catch(e){console.error(`Error in postRun for run ${this.id}:`,e)}}async patchRun(){try{const e={end_time:this.end_time,error:this.error,inputs:this.inputs,outputs:this.outputs,parent_run_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};await this.client.updateRun(this.id,e)}catch(e){console.error(`Error in patchRun for run ${this.id}`,e)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),"string"==typeof e?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){const r=e?.callbacks;let n,a,i,o=(e=>void 0!==e?e:!!["TRACING_V2","TRACING"].find((e=>"true"===(0,s.Jz)(e))))();if(r){const e=r?.getParentRunId?.()??"",t=r?.handlers?.find((e=>"langchain_tracer"==e?.name));n=t?.getRun?.(e),a=t?.projectName,i=t?.client,o=o||!!t}if(!n)return new l({...t,client:i,tracingEnabled:o,project_name:a});return new l({name:n.name,id:n.id,trace_id:n.trace_id,dotted_order:n.dotted_order,client:i,tracingEnabled:o,project_name:a,tags:[...new Set((n?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...n?.extra?.metadata,...e?.metadata}}}).createChild(t)}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){const r="get"in e&&"function"==typeof e.get?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,n=r["langsmith-trace"];if(!n||"string"!=typeof n)return;const s=n.trim(),a=s.split(".").map((e=>{const[t,r]=e.split("Z");return{strTime:t,time:Date.parse(t+"Z"),uuid:r}})),i=a[0].uuid,o={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:a.at(-1)?.uuid,trace_id:i,dotted_order:s};if(r.baggage&&"string"==typeof r.baggage){const e=c.fromHeader(r.baggage);o.metadata=e.metadata,o.tags=e.tags,o.project_name=e.project_name}return new l(o)}toHeaders(e){const t={"langsmith-trace":this.dotted_order,baggage:new c(this.extra?.metadata,this.tags,this.project_name).toHeader()};if(e)for(const[r,n]of Object.entries(t))e.set(r,n);return t}}function u(e){return void 0!==e&&"function"==typeof e.createChild&&"function"==typeof e.postRun}function d(e){return"object"==typeof e&&null!=e&&"string"==typeof e.name&&"langchain_tracer"===e.name}function h(e){return Array.isArray(e)&&e.some((e=>d(e)))}Object.defineProperty(l,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null})},3290:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(228),s=r(6641),a=r(4774),i=()=>{},o=new s.TimeoutError;t.default=class extends n{constructor(e){var t,r,n,s;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=i,this._resolveIdle=i,!("number"==typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:a.default},e)).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(r=null===(t=e.intervalCap)||void 0===t?void 0:t.toString())&&void 0!==r?r:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(s=null===(n=e.interval)||void 0===n?void 0:n.toString())&&void 0!==s?s:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=!0===e.throwOnTimeout,this._isPaused=!1===e.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount{this._onResumeInterval()}),t)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const t=this._queue.dequeue();return!!t&&(this.emit("active"),t(),e&&this._initializeIntervalIfNeeded(),!0)}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval((()=>{this._onInterval()}),this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&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(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise(((r,n)=>{this._queue.enqueue((async()=>{this._pendingCount++,this._intervalCount++;try{const a=void 0===this._timeout&&void 0===t.timeout?e():s.default(Promise.resolve(e()),void 0===t.timeout?this._timeout:t.timeout,(()=>{(void 0===t.throwOnTimeout?this._throwOnTimeout:t.throwOnTimeout)&&n(o)}));r(await a)}catch(e){n(e)}this._next()}),t),this._tryToStartAnother(),this.emit("add")}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise((e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}}))}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise((e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}}))}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}},3313:(e,t,r)=>{"use strict";r.d(t,{YN:()=>O,B2:()=>z,fJ:()=>A,Vi:()=>I,jY:()=>$,ck:()=>j,Pq:()=>L,Fm:()=>U,AO:()=>M,zZ:()=>R,pG:()=>B,lH:()=>F,GH:()=>P,Bp:()=>D});var n=r(4476),s=r(4116),a=r(9120),i=r(3389),o=r(1060),c=r(1590),l=r(58),u=r(7765),d=r(8028);function h({name:e,serialized:t}){return void 0!==e?e:void 0!==t?.name?t.name:void 0!==t?.id&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}const p=e=>"event_stream_tracer"===e.name;class m extends c.BaseTracer{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?.autoClose??!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,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=l.IterableReadableStream.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=e.tags??[];let r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.runType)),void 0!==this.includeTags&&(r=r||void 0!==t.find((e=>this.includeTags?.includes(e)))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.runType)),void 0!==this.excludeTags&&(r=r&&t.every((e=>!this.excludeTags?.includes(e)))),r}async*tapOutputIterable(e,t){const r=await t.next();if(r.done)return;const n=this.runInfoMap.get(e);if(void 0===n)return void(yield r.value);function s(e,t){return"llm"===e&&"string"==typeof t?new d.GenerationChunk({text:t}):t}let a=this.tappedPromises.get(e);if(void 0===a){let i;a=new Promise((e=>{i=e})),this.tappedPromises.set(e,a);try{const a={event:`on_${n.runType}_stream`,run_id:e,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};await this.send({...a,data:{chunk:s(n.runType,r.value)}},n),yield r.value;for await(const e of t)"tool"!==n.runType&&"retriever"!==n.runType&&await this.send({...a,data:{chunk:s(n.runType,e)}},n),yield e}finally{i()}}else{yield r.value;for await(const e of t)yield e}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const r=this.tappedPromises.get(e.run_id);void 0!==r?r.then((()=>{this.send(e,t)})):await this.send(e,t)}async onLLMStart(e){const t=h(e),r=void 0!==e.inputs.messages?"chat_model":"llm",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,n);const s=`on_${r}_start`;await this.send({event:s,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onLLMNewToken(e,t,r){const n=this.runInfoMap.get(e.id);let s,a;if(void 0===n)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(1!==this.runInfoMap.size){if("chat_model"===n.runType)a="on_chat_model_stream",s=void 0===r?.chunk?new u.H({content:t,id:`run-${e.id}`}):r.chunk.message;else{if("llm"!==n.runType)throw new Error(`Unexpected run type ${n.runType}`);a="on_llm_stream",s=void 0===r?.chunk?new d.GenerationChunk({text:t}):r.chunk}await this.send({event:a,data:{chunk:s},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(e){const t=this.runInfoMap.get(e.id);let r;if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const n=e.outputs?.generations;let s;if("chat_model"===t.runType){for(const e of n??[]){if(void 0!==s)break;s=e[0]?.message}r="on_chat_model_end"}else{if("llm"!==t.runType)throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);s={generations:n?.map((e=>e.map((e=>({text:e.text,generationInfo:e.generationInfo}))))),llmOutput:e.outputs?.llmOutput??{}},r="on_llm_end"}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){const t=h(e),r=e.run_type??"chain",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type};let s={};""===e.inputs.input&&1===Object.keys(e.inputs).length?(s={},n.inputs={}):void 0!==e.inputs.input?(s.input=e.inputs.input,n.inputs=e.inputs.input):(s.input=e.inputs,n.inputs=e.inputs),this.runInfoMap.set(e.id,n),await this.send({event:`on_${r}_start`,data:s,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onChainEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const r=`on_${e.run_type}_end`,n=e.inputs??t.inputs??{},s={output:e.outputs?.output??e.outputs,input:n};n.input&&1===Object.keys(n).length&&(s.input=n.input,t.inputs=n.input),await this.sendEndEvent({event:r,data:s,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=h(e),r={tags:e.tags??[],metadata:e.extra?.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:e.extra?.metadata??{}},r)}async onToolEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const r=void 0===e.outputs?.output?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){const t=h(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onRetrieverEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.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 n=this.runInfoMap.get(r);if(void 0===n)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:n.tags,metadata:n.metadata,data:t},n)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally((()=>{this.writer.close()}))}}var f=r(7380),g=r(9830),y=r(765),b=r(9624);class w extends c.BaseTracer{constructor({config:e,onStart:t,onEnd:r,onError:n}){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=n}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))}}var v=r(4850),_=r(4350),k=r(9137);function S(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.iterator]&&"function"==typeof e.next}function E(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.asyncIterator]}function*x(e,t){for(;;){const{value:r,done:n}=_.Nx.runWithConfig((0,y.DY)(e),t.next.bind(t),!0);if(n)break;yield r}}async function*T(e,t){const r=t[Symbol.asyncIterator]();for(;;){const{value:n,done:s}=await _.Nx.runWithConfig((0,y.DY)(e),r.next.bind(t),!0);if(s)break;yield n}}var C=r(199);function P(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}class O extends f.Serializable{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 A({bound:this,kwargs:e,config:{}})}map(){return new I({bound:this})}withRetry(e){return new M({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new A({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new F({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(y.ZI);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((([e])=>"runId"!==e)));return Array.from({length:t},((t,n)=>(0,y.ZI)(0===n?e:r)))}return Array.from({length:t},(()=>(0,y.ZI)(e)))}async batch(e,t,r){const n=this._getOptionsList(t??{},e.length),s=n[0]?.maxConcurrency??r?.maxConcurrency,a=new b.AsyncCaller({maxConcurrency:s,onFailedAttempt:e=>{throw e}}),i=e.map(((e,t)=>a.call((async()=>{try{return await this.invoke(e,n[t])}catch(e){if(r?.returnExceptions)return e;throw e}}))));return Promise.all(i)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const r=(0,y.ZI)(t),n=new l.AsyncGeneratorWithSetup({generator:this._streamIterator(e,r),config:r});return await n.setup,l.IterableReadableStream.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(e){let t;t=void 0===e?(0,y.ZI)(e):(0,y.ZI)({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 n=(0,y.ZI)(r),s=await(0,y.kJ)(n),a=await(s?.handleChainStart(this.toJSON(),P(t,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName()));let i;delete n.runId;try{const s=e.call(this,t,n,a);i=await(0,g.o)(s,r?.signal)}catch(e){throw await(a?.handleChainError(e)),e}return await(a?.handleChainEnd(P(i,"output"))),i}async _batchWithConfig(e,t,r,n){const s=this._getOptionsList(r??{},t.length),a=await Promise.all(s.map(y.kJ)),i=await Promise.all(a.map((async(e,r)=>{const n=await(e?.handleChainStart(this.toJSON(),P(t[r],"input"),s[r].runId,s[r].runType,void 0,void 0,s[r].runName??this.getName()));return delete s[r].runId,n})));let o;try{const r=e.call(this,t,s,i,n);o=await(0,g.o)(r,s?.[0]?.signal)}catch(e){throw await Promise.all(i.map((t=>t?.handleChainError(e)))),e}return await Promise.all(i.map((e=>e?.handleChainEnd(P(o,"output"))))),o}async*_transformStreamWithConfig(e,t,r){let n,s,a=!0,i=!0;const c=(0,y.ZI)(r),u=await(0,y.kJ)(c);let d;try{const h=await(0,l.pipeGeneratorWithSetup)(t.bind(this),async function*(){for await(const t of e){if(a)if(void 0===n)n=t;else try{n=(0,l.concat)(n,t)}catch{n=void 0,a=!1}yield t}}(),(async()=>u?.handleChainStart(this.toJSON(),{input:""},c.runId,c.runType,void 0,void 0,c.runName??this.getName())),r?.signal,c);delete c.runId,d=h.setup;const m=d?.handlers.find(p);let f=h.output;void 0!==m&&void 0!==d&&(f=m.tapOutputIterable(d.runId,f));const g=d?.handlers.find(o.isLogStreamHandler);void 0!==g&&void 0!==d&&(f=g.tapOutputIterable(d.runId,f));for await(const e of f)if(yield e,i)if(void 0===s)s=e;else try{s=(0,l.concat)(s,e)}catch{s=void 0,i=!1}}catch(e){throw await(d?.handleChainError(e,void 0,void 0,void 0,{inputs:P(n,"input")})),e}await(d?.handleChainEnd(s??{},void 0,void 0,void 0,{inputs:P(n,"input")}))}getGraph(e){const t=new k.T,r=t.addNode({name:`${this.getName()}Input`,schema:n.z.any()}),s=t.addNode(this),a=t.addNode({name:`${this.getName()}Output`,schema:n.z.any()});return t.addEdge(r,s),t.addEdge(s,a),t}pipe(e){return new R({first:this,last:D(e)})}pick(e){return this.pipe(new U(e))}assign(e){return this.pipe(new z(new j({steps:e})))}async*transform(e,t){let r;for await(const t of e)r=void 0===r?t:(0,l.concat)(r,t);yield*this._streamIterator(r,(0,y.ZI)(t))}async*streamLog(e,t,r){const n=new o.LogStreamCallbackHandler({...r,autoClose:!1,_schemaFormat:"original"}),s=(0,y.ZI)(t);yield*this._streamLog(e,n,s)}async*_streamLog(e,t,r){const{callbacks:n}=r;if(void 0===n)r.callbacks=[t];else if(Array.isArray(n))r.callbacks=n.concat([t]);else{const e=n.copy();e.addHandler(t,!0),r.callbacks=e}const s=this.stream(e,r);const a=async function(){try{const e=await s;for await(const r of e){const e=new o.RunLogPatch({ops:[{op:"add",path:"/streamed_output/-",value:r}]});await t.writer.write(e)}}finally{await t.writer.close()}}();try{for await(const e of t)yield e}finally{await a}}streamEvents(e,t,r){let n;if("v1"===t.version)n=this._streamEventsV1(e,t,r);else{if("v2"!==t.version)throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');n=this._streamEventsV2(e,t,r)}return"text/event-stream"===t.encoding?function(e){const t=new TextEncoder,r=new ReadableStream({async start(r){for await(const n of e)r.enqueue(t.encode(`event: data\ndata: ${JSON.stringify(n)}\n\n`));r.enqueue(t.encode("event: end\n\n")),r.close()}});return l.IterableReadableStream.fromReadableStream(r)}(n):l.IterableReadableStream.fromAsyncGenerator(n)}async*_streamEventsV2(e,t,r){const n=new m({...r,autoClose:!1}),s=(0,y.ZI)(t),i=s.runId??(0,a.A)();s.runId=i;const o=s.callbacks;if(void 0===o)s.callbacks=[n];else if(Array.isArray(o))s.callbacks=o.concat(n);else{const e=o.copy();e.addHandler(n,!0),s.callbacks=e}const c=new AbortController,l=this;const u=async function(){try{let r;t?.signal?"any"in AbortSignal?r=AbortSignal.any([c.signal,t.signal]):(r=t.signal,t.signal.addEventListener("abort",(()=>{c.abort()}),{once:!0})):r=c.signal;const a=await l.stream(e,{...s,signal:r}),o=n.tapOutputIterable(i,a);for await(const e of o)if(c.signal.aborted)break}finally{await n.finish()}}();let d,h=!1;try{for await(const t of n)h?(t.run_id===d&&t.event.endsWith("_end")&&t.data?.input&&delete t.data.input,yield t):(t.data.input=e,h=!0,d=t.run_id,yield t)}finally{c.abort(),await u}}async*_streamEventsV1(e,t,r){let n,s=!1;const a=(0,y.ZI)(t),i=a.tags??[],c=a.metadata??{},l=a.runName??this.getName(),u=new o.LogStreamCallbackHandler({...r,autoClose:!1,_schemaFormat:"streaming_events"}),d=new v.G({...r}),h=this._streamLog(e,u,a);for await(const t of h){if(n=n?n.concat(t):o.RunLog.fromRunLogPatch(t),void 0===n.state)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!s){s=!0;const t={...n.state},r={run_id:t.id,event:`on_${t.type}_start`,name:l,tags:i,metadata:c,data:{input:e}};d.includeEvent(r,t.type)&&(yield r)}const r=t.ops.filter((e=>e.path.startsWith("/logs/"))).map((e=>e.path.split("/")[2])),a=[...new Set(r)];for(const e of a){let t,r={};const s=n.state.logs[e];if(t=void 0===s.end_time?s.streamed_output.length>0?"stream":"start":"end","start"===t)void 0!==s.inputs&&(r.input=s.inputs);else if("end"===t)void 0!==s.inputs&&(r.input=s.inputs),r.output=s.final_output;else if("stream"===t){const e=s.streamed_output.length;if(1!==e)throw new Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${s.name}"`);r={chunk:s.streamed_output[0]},s.streamed_output=[]}yield{event:`on_${s.type}_${t}`,name:s.name,run_id:s.id,tags:s.tags,metadata:s.metadata,data:r}}const{state:u}=n;if(u.streamed_output.length>0){const e=u.streamed_output.length;if(1!==e)throw new Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${u.name}"`);const t={chunk:u.streamed_output[0]};u.streamed_output=[];const r={event:`on_${u.type}_stream`,run_id:u.id,tags:i,metadata:c,name:l,data:t};d.includeEvent(r,u.type)&&(yield r)}}const p=n?.state;if(void 0!==p){const e={event:`on_${p.type}_end`,name:l,run_id:p.id,tags:i,metadata:c,data:{output:p.final_output}};d.includeEvent(e,p.type)&&(yield e)}}static isRunnable(e){return(0,v.T)(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new A({bound:this,config:{},configFactories:[n=>({callbacks:[new w({config:n,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return function(e,t){const r=t.name??e.getName(),s=t.description??t.schema?.description;if(t.schema.constructor===n.z.ZodString)return new B({name:r,description:s,schema:n.z.object({input:n.z.string()}).transform((e=>e.input)),bound:e});return new B({name:r,description:s,schema:t.schema,bound:e})}(this,e)}}class A extends O{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=(0,y.SV)(this.config,...e);return(0,y.SV)(t,...this.configFactories?await Promise.all(this.configFactories.map((async e=>await e(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 this.constructor({bound:this.bound.withRetry(e),kwargs:this.kwargs,config:this.config})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig((0,y.ZI)(t),this.kwargs))}async batch(e,t,r){const n=Array.isArray(t)?await Promise.all(t.map((async e=>this._mergeConfig((0,y.ZI)(e),this.kwargs)))):await this._mergeConfig((0,y.ZI)(t),this.kwargs);return this.bound.batch(e,n,r)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig((0,y.ZI)(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig((0,y.ZI)(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig((0,y.ZI)(t),this.kwargs))}streamEvents(e,t,r){const n=this;return l.IterableReadableStream.fromAsyncGenerator(async function*(){yield*n.bound.streamEvents(e,{...await n._mergeConfig((0,y.ZI)(t),n.kwargs),version:t.version},r)}())}static isRunnableBinding(e){return e.bound&&O.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:r}){return new A({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[n=>({callbacks:[new w({config:n,onStart:e,onEnd:t,onError:r})]})]})}}class I extends O{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 I({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,(0,y.tn)(t,{callbacks:r?.getChild()}))}withListeners({onStart:e,onEnd:t,onError:r}){return new I({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:r})})}}class M extends A{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 n=e>1?`retry:attempt:${e}`:void 0;return(0,y.tn)(t,{callbacks:r?.getChild(n)})}async _invoke(e,t,r){return s((n=>super.invoke(e,this._patchConfigForRetry(n,t,r))),{onFailedAttempt:t=>this.onFailedAttempt(t,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,n){const a={};try{await s((async s=>{const i=e.map(((e,t)=>t)).filter((e=>void 0===a[e.toString()]||a[e.toString()]instanceof Error)),o=i.map((t=>e[t])),c=i.map((e=>this._patchConfigForRetry(s,t?.[e],r?.[e]))),l=await super.batch(o,c,{...n,returnExceptions:!0});let u;for(let e=0;ethis.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(!0!==n?.returnExceptions)throw e}return Object.keys(a).sort(((e,t)=>parseInt(e,10)-parseInt(t,10))).map((e=>a[parseInt(e,10)]))}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}}class R extends O{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){const r=(0,y.ZI)(t),n=await(0,y.kJ)(r),s=await(n?.handleChainStart(this.toJSON(),P(e,"input"),r.runId,void 0,void 0,void 0,r?.runName));delete r.runId;let a,i=e;try{const e=[this.first,...this.middle];for(let n=0;n{const s=await(t?.handleChainStart(this.toJSON(),P(e[r],"input"),n[r].runId,void 0,void 0,void 0,n[r].runName));return delete n[r].runId,s})));let i=e;try{for(let e=0;e{const s=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return(0,y.tn)(n[r],{callbacks:s})})),r);i=await(0,g.o)(t,n[0]?.signal)}}catch(e){throw await Promise.all(a.map((t=>t?.handleChainError(e)))),e}return await Promise.all(a.map((e=>e?.handleChainEnd(P(i,"output"))))),i}async*_streamIterator(e,t){const r=await(0,y.kJ)(t),{runId:n,...s}=t??{},a=await(r?.handleChainStart(this.toJSON(),P(e,"input"),n,void 0,void 0,void 0,s?.runName)),i=[this.first,...this.middle,this.last];let o,c=!0;try{let r=i[0].transform(async function*(){yield e}(),(0,y.tn)(s,{callbacks:a?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let e=1;e{const a=n.getGraph(e);0!==s&&a.trimFirstNode(),s!==this.steps.length-1&&a.trimLastNode(),t.extend(a);const i=a.firstNode();if(!i)throw new Error(`Runnable ${n} has no first node`);r&&t.addEdge(r,i),r=a.lastNode()})),t}pipe(e){return R.isRunnableSequence(e)?new R({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new R({first:this.first,middle:[...this.middle,this.last],last:D(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&O.isRunnable(e)}static from([e,...t],r){let n={};return"string"==typeof r?n.name=r:void 0!==r&&(n=r),new R({...n,first:D(e),middle:t.slice(0,-1).map(D),last:D(t[t.length-1])})}}class j extends O{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]=D(r)}static from(e){return new j({steps:e})}async invoke(e,t){const r=(0,y.ZI)(t),n=await(0,y.kJ)(r),s=await(n?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName));delete r.runId;const a={};try{const n=Object.entries(this.steps).map((async([t,n])=>{a[t]=await n.invoke(e,(0,y.tn)(r,{callbacks:s?.getChild(`map:key:${t}`)}))}));await(0,g.o)(Promise.all(n),t?.signal)}catch(e){throw await(s?.handleChainError(e)),e}return await(s?.handleChainEnd(a)),a}async*_transform(e,t,r){const n={...this.steps},s=(0,l.atee)(e,Object.keys(n).length),a=new Map(Object.entries(n).map((([e,n],a)=>{const i=n.transform(s[a],(0,y.tn)(r,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,i.next().then((t=>({key:e,gen:i,result:t})))]})));for(;a.size;){const e=Promise.race(a.values()),{key:t,result:n,gen:s}=await(0,g.o)(e,r?.signal);a.delete(t),n.done||(yield{[t]:n.value},a.set(t,s.next().then((e=>({key:t,gen:s,result:e})))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=(0,y.ZI)(t),n=new l.AsyncGeneratorWithSetup({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,l.IterableReadableStream.fromAsyncGenerator(n)}}class N extends O{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}),!(0,i.GZ)(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),n=await(0,y.kJ)(r),s=this.func((0,y.tn)(r,{callbacks:n}),e);return(0,g.o)(s,r?.signal)}async*_streamIterator(e,t){const[r]=this._getOptionsList(t??{},1),n=await this.invoke(e,t);var s;if(E(n))for await(const e of n)r?.signal?.throwIfAborted(),yield e;else if(null!=(s=n)&&"object"==typeof s&&"next"in s&&"function"==typeof s.next)for(;;){r?.signal?.throwIfAborted();const e=n.next();if(e.done)break;yield e.value}else yield n}static from(e){return new N({func:e})}}class $ extends O{static lc_name(){return"RunnableLambda"}constructor(e){if((0,i.GZ)(e.func))return N.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}),function(e){if((0,i.GZ)(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}(e.func),this.func=e.func}static from(e){return new $({func:e})}async _invoke(e,t,r){return new Promise(((n,s)=>{const a=(0,y.tn)(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??y.p_)-1});_.Nx.runWithConfig((0,y.DY)(a),(async()=>{try{let r=await this.func(e,{...a});if(r&&O.isRunnable(r)){if(0===t?.recursionLimit)throw new Error("Recursion limit reached.");r=await r.invoke(e,{...a,recursionLimit:(a.recursionLimit??y.p_)-1})}else if(E(r)){let e;for await(const n of T(a,r))if(t?.signal?.throwIfAborted(),void 0===e)e=n;else try{e=(0,l.concat)(e,n)}catch(t){e=n}r=e}else if(S(r)){let e;for(const n of x(a,r))if(t?.signal?.throwIfAborted(),void 0===e)e=n;else try{e=(0,l.concat)(e,n)}catch(t){e=n}r=e}n(r)}catch(e){s(e)}}))}))}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,r){let n;for await(const t of e)if(void 0===n)n=t;else try{n=(0,l.concat)(n,t)}catch(e){n=t}const s=(0,y.tn)(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??y.p_)-1}),a=await new Promise(((e,t)=>{_.Nx.runWithConfig((0,y.DY)(s),(async()=>{try{const t=await this.func(n,{...s,config:s});e(t)}catch(e){t(e)}}))}));if(a&&O.isRunnable(a)){if(0===r?.recursionLimit)throw new Error("Recursion limit reached.");const e=await a.stream(n,s);for await(const t of e)yield t}else if(E(a))for await(const e of T(s,a))r?.signal?.throwIfAborted(),yield e;else if(S(a))for(const e of x(s,a))r?.signal?.throwIfAborted(),yield e;else yield a}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=(0,y.ZI)(t),n=new l.AsyncGeneratorWithSetup({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,l.IterableReadableStream.fromAsyncGenerator(n)}}class L extends j{}class F extends O{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=(0,y.ZI)(t),n=await(0,y.kJ)(r),{runId:s,...a}=r,i=await(n?.handleChainStart(this.toJSON(),P(e,"input"),s,void 0,void 0,void 0,a?.runName)),o=(0,y.tn)(a,{callbacks:i?.getChild()});return await _.Nx.runWithConfig(o,(async()=>{let t;for(const n of this.runnables()){r?.signal?.throwIfAborted();try{const t=await n.invoke(e,o);return await(i?.handleChainEnd(P(t,"output"))),t}catch(e){void 0===t&&(t=e)}}if(void 0===t)throw new Error("No error stored at end of fallback.");throw await(i?.handleChainError(t)),t}))}async*_streamIterator(e,t){const r=(0,y.ZI)(t),n=await(0,y.kJ)(r),{runId:s,...a}=r,i=await(n?.handleChainStart(this.toJSON(),P(e,"input"),s,void 0,void 0,void 0,a?.runName));let o,c,u;for(const t of this.runnables()){r?.signal?.throwIfAborted();const n=(0,y.tn)(a,{callbacks:i?.getChild()});try{c=T(n,await t.stream(e,n));break}catch(e){void 0===o&&(o=e)}}if(void 0===c){const e=o??new Error("No error stored at end of fallback.");throw await(i?.handleChainError(e)),e}try{for await(const e of c){yield e;try{u=void 0===u?u:(0,l.concat)(u,e)}catch(e){u=void 0}}}catch(e){throw await(i?.handleChainError(e)),e}await(i?.handleChainEnd(P(u,"output")))}async batch(e,t,r){if(r?.returnExceptions)throw new Error("Not implemented.");const n=this._getOptionsList(t??{},e.length),s=await Promise.all(n.map((e=>(0,y.kJ)(e)))),a=await Promise.all(s.map((async(t,r)=>{const s=await(t?.handleChainStart(this.toJSON(),P(e[r],"input"),n[r].runId,void 0,void 0,void 0,n[r].runName));return delete n[r].runId,s})));let i;for(const t of this.runnables()){n[0].signal?.throwIfAborted();try{const s=await t.batch(e,a.map(((e,t)=>(0,y.tn)(n[t],{callbacks:e?.getChild()}))),r);return await Promise.all(a.map(((e,t)=>e?.handleChainEnd(P(s[t],"output"))))),s}catch(e){void 0===i&&(i=e)}}if(!i)throw new Error("No error stored at end of fallbacks.");throw await Promise.all(a.map((e=>e?.handleChainError(i)))),i}}function D(e){if("function"==typeof e)return new $({func:e});if(O.isRunnable(e))return e;if(Array.isArray(e)||"object"!=typeof e)throw new Error("Expected a Runnable, function or object.\nInstead got an unsupported type.");{const t={};for(const[r,n]of Object.entries(e))t[r]=D(n);return new j({steps:t})}}class z extends O{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof j&&(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 n=this.mapper.getStepsKeys(),[s,a]=(0,l.atee)(e),i=this.mapper.transform(a,(0,y.tn)(r,{callbacks:t?.getChild()})),o=i.next();for await(const e of s){if("object"!=typeof e||Array.isArray(e))throw new Error("RunnableAssign can only be used with objects as input, got "+typeof e);const t=Object.fromEntries(Object.entries(e).filter((([e])=>!n.includes(e))));Object.keys(t).length>0&&(yield t)}yield(await o).value;for await(const e of i)yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=(0,y.ZI)(t),n=new l.AsyncGeneratorWithSetup({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,l.IterableReadableStream.fromAsyncGenerator(n)}}class U extends O{static lc_name(){return"RunnablePick"}constructor(e){("string"==typeof e||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("string"==typeof this.keys)return e[this.keys];{const t=this.keys.map((t=>[t,e[t]])).filter((e=>void 0!==e[1]));return 0===t.length?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 e=await this._pick(t);void 0!==e&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=(0,y.ZI)(t),n=new l.AsyncGeneratorWithSetup({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,l.IterableReadableStream.fromAsyncGenerator(n)}}class B extends A{constructor(e){super({bound:R.from([$.from((async e=>{let t;if((0,C.Ky)(e))try{t=await this.schema.parseAsync(e.args)}catch(t){throw new C.qe("Received tool input did not match expected schema",JSON.stringify(e.args))}else t=e;return t})).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name}),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"}}},3389:(e,t,r)=>{"use strict";r.d(t,{vR:()=>o,GZ:()=>c});var n=r(3246);const s=Symbol.for("ls:tracing_async_local_storage"),a=new class{getStore(){}run(e,t){return t()}};const i=new class{getInstance(){return globalThis[s]??a}initializeGlobalInstance(e){void 0===globalThis[s]&&(globalThis[s]=e)}};function o(e=!1){const t=i.getInstance().getStore();if(!e&&!(0,n.m5)(t))throw new Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled.");return t}Symbol.for("langsmith:traceable:root");function c(e){return"function"==typeof e&&"langsmith:traceable"in e}},3490:(e,t,r)=>{"use strict";r.d(t,{AJ:()=>f,Ao:()=>c,F7:()=>d,Iv:()=>i,Vt:()=>u,XQ:()=>o,_I:()=>a,dp:()=>p,gj:()=>h,ns:()=>l,ny:()=>m});var n=r(7380),s=r(4291);function a(e,t){return"string"==typeof e?""===e?t:"string"==typeof t?e+t:Array.isArray(t)&&t.some((e=>(0,s.Fz)(e)))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?u(e,t)??[...e,...t]:""===t?e:Array.isArray(e)&&e.some((e=>(0,s.Fz)(e)))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}function i(e,t){return"error"===e||"error"===t?"error":"success"}class o extends n.Serializable{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){return"string"==typeof this.content?this.content:Array.isArray(this.content)?this.content.map((e=>"string"==typeof e?e:"text"===e.type?e.text:"")).join(""):""}getType(){return this._getType()}constructor(e,t){"string"==typeof e&&(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(null===e)return this;const t=(r=this._printableFields,n=Math.max(4,e),JSON.stringify(function e(t,r){if("object"!=typeof t||null==t)return t;if(r>=n)return Array.isArray(t)?"[Array]":"[Object]";if(Array.isArray(t))return t.map((t=>e(t,r+1)));const s={};for(const n of Object.keys(t))s[n]=e(t[n],r+1);return s}(r,0),null,2));var r,n;return`${this.constructor.lc_name()} ${t}`}}function c(e){return Array.isArray(e)&&e.every((e=>"number"==typeof e.index))}function l(e,t){const r={...e};for(const[e,n]of Object.entries(t))if(null==r[e])r[e]=n;else{if(null==n)continue;if(typeof r[e]!=typeof n||Array.isArray(r[e])!==Array.isArray(n))throw new Error(`field[${e}] already exists in the message chunk, but with a different type.`);if("string"==typeof r[e]){if("type"===e)continue;r[e]+=n}else if("object"!=typeof r[e]||Array.isArray(r[e]))if(Array.isArray(r[e]))r[e]=u(r[e],n);else{if(r[e]===n)continue;console.warn(`field[${e}] already exists in this message chunk and value has unsupported type.`)}else r[e]=l(r[e],n)}return r}function u(e,t){if(void 0!==e||void 0!==t){if(void 0===e||void 0===t)return e||t;{const r=[...e];for(const e of t)if("object"==typeof e&&"index"in e&&"number"==typeof e.index){const t=r.findIndex((t=>t.index===e.index));-1!==t?r[t]=l(r[t],e):r.push(e)}else{if("object"==typeof e&&"text"in e&&""===e.text)continue;r.push(e)}return r}}}function d(e,t){if(!e&&!t)throw new Error("Cannot merge two undefined objects.");if(e&&t){if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types.\nLeft ${typeof e}\nRight ${typeof t}`);if("string"==typeof e&&"string"==typeof t)return e+t;if(Array.isArray(e)&&Array.isArray(t))return u(e,t);if("object"==typeof e&&"object"==typeof t)return l(e,t);if(e===t)return e;throw new Error(`Can not merge objects of different types.\nLeft ${e}\nRight ${t}`)}return e||t}class h extends o{}function p(e){return"string"==typeof e.role}function m(e){return"function"==typeof e?._getType}function f(e){return m(e)&&"function"==typeof e.concat}},3650:(e,t,r)=>{"use strict";r.d(t,{PromptTemplate:()=>a});var n=r(329),s=r(9849);class a extends n.L{static lc_name(){return"PromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),"mustache"===e.templateFormat&&void 0===e.validateTemplate&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){if("mustache"===this.templateFormat)throw new Error("Mustache templates cannot be validated.");let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),(0,s.Ns)(this.template,this.templateFormat,e)}}_getPromptType(){return"prompt"}async format(e){const t=await this.mergePartialAndUserVariables(e);return(0,s.Xm)(this.template,this.templateFormat,t)}static fromExamples(e,t,r,n="\n\n",s=""){const i=[s,...e,t].join(n);return new a({inputVariables:r,template:i})}static fromTemplate(e,t){const{templateFormat:r="f-string",...n}=t??{},i=new Set;return(0,s.QC)(e,r).forEach((e=>{"variable"===e.type&&i.add(e.name)})),new a({inputVariables:[...i],templateFormat:r,template:e,...n})}async partial(e){const t=this.inputVariables.filter((t=>!(t in e))),r={...this.partialVariables??{},...e},n={...this,inputVariables:t,partialVariables:r};return new a(n)}serialize(){if(void 0!==this.outputParser)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(e){if(!e.template)throw new Error("Prompt template must have a template");return new a({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}}},3766:(e,t,r)=>{"use strict";r.d(t,{BJ:()=>k,FS:()=>v,GL:()=>m,OT:()=>f,RZ:()=>E,Wn:()=>y,pl:()=>p,qF:()=>g,sS:()=>_});var n=r(1673),s=r(5311),a=r(3313),i=r(329),o=r(6993),c=r(3650),l=r(6279),u=r(9849),d=r(1368),h=r(4552);class p extends a.YN{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","chat"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}async invoke(e,t){return this._callWithConfig((e=>this.formatMessages(e)),e,{...t,runType:"prompt"})}}class m extends p{static lc_name(){return"MessagesPlaceholder"}constructor(e){"string"==typeof e&&(e={variableName:e}),super(e),Object.defineProperty(this,"variableName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"optional",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.variableName=e.variableName,this.optional=e.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(e){const t=e[this.variableName];if(this.optional&&!t)return[];if(!t){const e=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw e.name="InputFormatError",e}let r;try{r=Array.isArray(t)?t.map(n.coerceMessageLikeToMessage):[(0,n.coerceMessageLikeToMessage)(t)]}catch(e){const r="string"==typeof t?t:JSON.stringify(t,null,2),n=new Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${r}`,`Additional message: ${e.message}`].join("\n\n"));throw n.name="InputFormatError",n.lc_error_code=e.lc_error_code,n}return r}}class f extends p{constructor(e){"prompt"in e||(e={prompt:e}),super(e),Object.defineProperty(this,"prompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}}class g extends o.m{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){const t=await this.formatMessages(e);return new s.ChatPromptValue(t)}}class y extends f{static lc_name(){return"ChatMessagePromptTemplate"}constructor(e,t){"prompt"in e||(e={prompt:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}async format(e){return new n.ChatMessage(await this.prompt.format(e),this.role)}static fromTemplate(e,t,r){return new this(c.PromptTemplate.fromTemplate(e,{templateFormat:r?.templateFormat}),t)}}function b(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)&&("image_url"in e&&("string"==typeof e.image_url||"object"==typeof e.image_url&&null!==e.image_url&&"url"in e.image_url&&"string"==typeof e.image_url.url))}class w extends p{static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}constructor(e,t){if("prompt"in e||(e={prompt:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","chat"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"additionalOptions",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"prompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"messageClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chatMessageClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.prompt=e.prompt,Array.isArray(this.prompt)){let e=[];this.prompt.forEach((t=>{"inputVariables"in t&&(e=e.concat(t.inputVariables))})),this.inputVariables=e}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=t??this.additionalOptions}createMessage(e){const t=this.constructor;if(t._messageClass()){return new(t._messageClass())({content:e})}if(t.chatMessageClass){const r=t.chatMessageClass();return new r({content:e,role:this.getRoleFromMessageClass(r.lc_name())})}throw new Error("No message class defined")}getRoleFromMessageClass(e){switch(e){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(e,t){if("string"==typeof e)return new this(c.PromptTemplate.fromTemplate(e,t));const r=[];for(const s of e)if("string"==typeof s)r.push(c.PromptTemplate.fromTemplate(s,t));else if(null===s);else if(null!==(n=s)&&"object"==typeof n&&!Array.isArray(n)&&1===Object.keys(n).length&&"text"in n&&"string"==typeof n.text){let e="";"string"==typeof s.text&&(e=s.text??"");const n={...t,additionalContentFields:s};r.push(c.PromptTemplate.fromTemplate(e,n))}else if(b(s)){let e,n=s.image_url??"",a=[];if("string"==typeof n){let r;r="mustache"===t?.templateFormat?(0,u.g2)(n):(0,u.D4)(n);const i=r.flatMap((e=>"variable"===e.type?[e.name]:[]));if((i?.length??0)>0){if(i.length>1)throw new Error(`Only one format variable allowed per image template.\nGot: ${i}\nFrom: ${n}`);a=[i[0]]}else a=[];n={url:n},e=new l.C({template:n,inputVariables:a,templateFormat:t?.templateFormat,additionalContentFields:s})}else{if("object"!=typeof n)throw new Error("Invalid image template");if("url"in n){let e;e="mustache"===t?.templateFormat?(0,u.g2)(n.url):(0,u.D4)(n.url),a=e.flatMap((e=>"variable"===e.type?[e.name]:[]))}else a=[];e=new l.C({template:n,inputVariables:a,templateFormat:t?.templateFormat,additionalContentFields:s})}r.push(e)}else"object"==typeof s&&r.push(new h.l({template:s,templateFormat:t?.templateFormat}));var n;return new this({prompt:r,additionalOptions:t})}async format(e){if(this.prompt instanceof i.L){const t=await this.prompt.format(e);return this.createMessage(t)}{const t=[];for(const r of this.prompt){let n={};if(!("inputVariables"in r))throw new Error(`Prompt ${r} does not have inputVariables defined.`);for(const t of r.inputVariables)n||(n={[t]:e[t]}),n={...n,[t]:e[t]};if(r instanceof i.L){const e=await r.format(n);let s;"additionalContentFields"in r&&(s=r.additionalContentFields),t.push({...s,type:"text",text:e})}else if(r instanceof l.C){const e=await r.format(n);let s;"additionalContentFields"in r&&(s=r.additionalContentFields),t.push({...s,type:"image_url",image_url:e})}else if(r instanceof h.l){const e=await r.format(n);let s;"additionalContentFields"in r&&(s=r.additionalContentFields),t.push({...s,...e})}}return this.createMessage(t)}}async formatMessages(e){return[await this.format(e)]}}class v extends w{static _messageClass(){return n.HumanMessage}static lc_name(){return"HumanMessagePromptTemplate"}}class _ extends w{static _messageClass(){return n.AIMessage}static lc_name(){return"AIMessagePromptTemplate"}}class k extends w{static _messageClass(){return n.SystemMessage}static lc_name(){return"SystemMessagePromptTemplate"}}function S(e,t){if("function"==typeof e.formatMessages||(0,n.isBaseMessage)(e))return e;if(Array.isArray(e)&&"placeholder"===e[0]){const r=e[1];if("mustache"===t?.templateFormat&&"string"==typeof r&&"{{"===r.slice(0,2)&&"}}"===r.slice(-2)){const e=r.slice(2,-2);return new m({variableName:e,optional:!0})}if("string"==typeof r&&"{"===r[0]&&"}"===r[r.length-1]){const e=r.slice(1,-1);return new m({variableName:e,optional:!0})}throw new Error(`Invalid placeholder template for format ${t?.templateFormat??'"f-string"'}: "${e[1]}". Expected a variable name surrounded by ${"mustache"===t?.templateFormat?"double":"single"} curly braces.`)}const r=(0,n.coerceMessageLikeToMessage)(e);let s;if(s="string"==typeof r.content?r.content:r.content.map((e=>"text"in e?{...e,text:e.text}:"image_url"in e?{...e,image_url:e.image_url}:e)),"human"===r._getType())return v.fromTemplate(s,t);if("ai"===r._getType())return _.fromTemplate(s,t);if("system"===r._getType())return k.fromTemplate(s,t);if(n.ChatMessage.isInstance(r))return y.fromTemplate(r.content,r.role,t);throw new Error(`Could not coerce message prompt template from input. Received message type: "${r._getType()}".`)}class E extends g{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}constructor(e){if(super(e),Object.defineProperty(this,"promptMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),"mustache"===e.templateFormat&&void 0===e.validateTemplate&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){const e=new Set;for(const t of this.promptMessages)if(!(t instanceof n.BaseMessage))for(const r of t.inputVariables)e.add(r);const t=this.inputVariables,r=new Set(this.partialVariables?t.concat(Object.keys(this.partialVariables)):t),s=new Set([...r].filter((t=>!e.has(t))));if(s.size>0)throw new Error(`Input variables \`${[...s]}\` are not used in any of the prompt messages.`);const a=new Set([...e].filter((e=>!r.has(e))));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(e,t){if("string"==typeof e.content)return e;const r=await Promise.all(e.content.map((async e=>{if("image_url"!==e.type)return e;let r="";r="string"==typeof e.image_url?e.image_url:e.image_url.url;const n=c.PromptTemplate.fromTemplate(r,{templateFormat:this.templateFormat}),s=await n.format(t);return"string"!=typeof e.image_url&&"url"in e.image_url?e.image_url.url=s:e.image_url=s,e})));return e.content=r,e}async formatMessages(e){const t=await this.mergePartialAndUserVariables(e);let r=[];for(const e of this.promptMessages)if(e instanceof n.BaseMessage)r.push(await this._parseImagePrompts(e,t));else{const n=e.inputVariables.reduce(((r,n)=>{if(!(n in t)&&("MessagesPlaceholder"!==e.constructor.lc_name()||!e.optional)){throw(0,d.Y)(new Error(`Missing value for input variable \`${n.toString()}\``),"INVALID_PROMPT_INPUT")}return r[n]=t[n],r}),{}),s=await e.formatMessages(n);r=r.concat(s)}return r}async partial(e){const t=this.inputVariables.filter((t=>!(t in e))),r={...this.partialVariables??{},...e},n={...this,inputVariables:t,partialVariables:r};return new E(n)}static fromTemplate(e,t){const r=c.PromptTemplate.fromTemplate(e,t),n=new v({prompt:r});return this.fromMessages([n])}static fromMessages(e,t){const r=e.reduce(((e,r)=>e.concat(r instanceof E?r.promptMessages:[S(r,t)])),[]),s=e.reduce(((e,t)=>t instanceof E?Object.assign(e,t.partialVariables):e),Object.create(null)),a=new Set;for(const e of r)if(!(e instanceof n.BaseMessage))for(const t of e.inputVariables)t in s||a.add(t);return new this({...t,inputVariables:[...a],promptMessages:r,partialVariables:s,templateFormat:t?.templateFormat})}static fromPromptMessages(e){return this.fromMessages(e)}}},3874:(e,t,r)=>{"use strict";const n=r(8311);e.exports=(e,t)=>{try{return new n(e,t).range||"*"}catch(e){return null}}},3904:(e,t,r)=>{"use strict";const n=Symbol("SemVer ANY");class s{static get ANY(){return n}constructor(e,t){if(t=a(t),e instanceof s){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),l("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===n?this.value="":this.value=this.operator+this.semver.version,l("comp",this)}parse(e){const t=this.options.loose?i[o.COMPARATORLOOSE]:i[o.COMPARATOR],r=e.match(t);if(!r)throw new TypeError(`Invalid comparator: ${e}`);this.operator=void 0!==r[1]?r[1]:"","="===this.operator&&(this.operator=""),r[2]?this.semver=new u(r[2],this.options.loose):this.semver=n}toString(){return this.value}test(e){if(l("Comparator.test",e,this.options.loose),this.semver===n||e===n)return!0;if("string"==typeof e)try{e=new u(e,this.options)}catch(e){return!1}return c(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof s))throw new TypeError("a Comparator is required");return""===this.operator?""===this.value||new d(e.value,t).test(this.value):""===e.operator?""===e.value||new d(this.value,t).test(e.semver):(!(t=a(t)).includePrerelease||"<0.0.0-0"!==this.value&&"<0.0.0-0"!==e.value)&&(!(!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0")))&&(!(!this.operator.startsWith(">")||!e.operator.startsWith(">"))||(!(!this.operator.startsWith("<")||!e.operator.startsWith("<"))||(!(this.semver.version!==e.semver.version||!this.operator.includes("=")||!e.operator.includes("="))||(!!(c(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<"))||!!(c(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))))))}}e.exports=s;const a=r(8587),{safeRe:i,t:o}=r(9718),c=r(2111),l=r(7272),u=r(3908),d=r(8311)},3908:(e,t,r)=>{"use strict";const n=r(7272),{MAX_LENGTH:s,MAX_SAFE_INTEGER:a}=r(6874),{safeRe:i,t:o}=r(9718),c=r(8587),{compareIdentifiers:l}=r(1123);class u{constructor(e,t){if(t=c(t),e instanceof u){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if("string"!=typeof e)throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>s)throw new TypeError(`version is longer than ${s} characters`);n("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const r=e.trim().match(t.loose?i[o.LOOSE]:i[o.FULL]);if(!r)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>a||this.major<0)throw new TypeError("Invalid major version");if(this.minor>a||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>a||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map((e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t=0;)"number"==typeof this.prerelease[n]&&(this.prerelease[n]++,n=-2);if(-1===n){if(t===this.prerelease.join(".")&&!1===r)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let n=[t,e];!1===r&&(n=[t]),0===l(this.prerelease[0],t)?isNaN(this.prerelease[1])&&(this.prerelease=n):this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}e.exports=u},3927:(e,t,r)=>{"use strict";const n=r(909);e.exports=(e,t)=>e.sort(((e,r)=>n(e,r,t)))},3961:e=>{function t(e,t){"boolean"==typeof t&&(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))}e.exports=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},t.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(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout((function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout((function(){n._operationTimeoutCb(n._attempts)}),n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)}),r),this._options.unref&&this._timer.unref(),!0},t.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)},t.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},t.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n=r&&(t=s,r=i)}return t}},3997:(e,t,r)=>{"use strict";r.r(t),r.d(t,{LangChainTracer:()=>u});var n=r(1688),s=r(3389),a=r(9583),i=r(1590),o=r(1259);let c;const l=()=>{if(void 0===c){const e="false"===(0,a.getEnvironmentVariable)("LANGCHAIN_CALLBACKS_BACKGROUND")?{blockOnRootRunFinalization:!0}:{};c=new o.Kj(e)}return c};class u extends i.BaseTracer{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});const{exampleId:t,projectName:r,client:n}=e;this.projectName=r??(0,a.getEnvironmentVariable)("LANGCHAIN_PROJECT")??(0,a.getEnvironmentVariable)("LANGCHAIN_SESSION"),this.exampleId=t,this.client=n??l();const s=u.getTraceableRunTree();s&&this.updateFromRunTree(s)}async _convertToCreate(e,t=void 0){return{...e,extra:{...e.extra,runtime:await(0,a.getRuntimeEnvironment)()},child_runs:void 0,session_name:this.projectName,reference_example_id:e.parent_run_id?void 0:t}}async persistRun(e){}async onRunCreate(e){const t=await this._convertToCreate(e,this.exampleId);await this.client.createRun(t)}async onRunUpdate(e){const t={end_time:e.end_time,error:e.error,outputs:e.outputs,events:e.events,inputs:e.inputs,trace_id:e.trace_id,dotted_order:e.dotted_order,parent_run_id:e.parent_run_id,extra:e.extra,session_name:this.projectName};await this.client.updateRun(e.id,t)}getRun(e){return this.runMap.get(e)}updateFromRunTree(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 n=[t];for(;n.length>0;){const e=n.shift();e&&!r.has(e.id)&&(r.add(e.id),this.runMap.set(e.id,e),e.child_runs&&n.push(...e.child_runs))}this.client=e.client??this.client,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}convertToRunTree(e){const t={},r=[];for(const[e,s]of this.runMap){const a=new n.gk({...s,child_runs:[],parent_run:void 0,client:this.client,project_name:this.projectName,reference_example_id:this.exampleId,tracingEnabled:!0});t[e]=a,r.push([e,s.dotted_order])}r.sort(((e,t)=>e[1]&&t[1]?e[1].localeCompare(t[1]):0));for(const[e]of r){const r=this.runMap.get(e),n=t[e];if(r&&n&&r.parent_run_id){const e=t[r.parent_run_id];e&&(e.child_runs.push(n),n.parent_run=e)}}return t[e]}static getTraceableRunTree(){try{return(0,s.vR)(!0)}catch{return}}}},3999:(e,t,r)=>{"use strict";const n=r(560);e.exports=(e,t,r)=>0!==n(e,t,r)},4089:(e,t,r)=>{"use strict";const n=r(560);e.exports=(e,t,r)=>n(e,t,r)>=0},4116:(e,t,r)=>{"use strict";const n=r(5617),s=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class a extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const i=(e,t)=>new Promise(((r,i)=>{t={onFailedAttempt:()=>{},retries:10,...t};const o=n.operation(t);o.attempt((async n=>{try{r(await e(n))}catch(e){if(!(e instanceof Error))return void i(new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));if(e instanceof a)o.stop(),i(e.originalError);else if(e instanceof TypeError&&(c=e.message,!s.includes(c)))o.stop(),i(e);else{((e,t,r)=>{const n=r.retries-(t-1);e.attemptNumber=t,e.retriesLeft=n})(e,n,t);try{await t.onFailedAttempt(e)}catch(e){return void i(e)}o.retry(e)||i(o.mainError())}}var c}))}));e.exports=i,e.exports.default=i,e.exports.AbortError=a},4277:(e,t,r)=>{"use strict";const n=r(909);e.exports=(e,t)=>e.sort(((e,r)=>n(r,e,t)))},4291:(e,t,r)=>{"use strict";function n(e){return"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&"source_type"in e&&("url"===e.source_type||"base64"===e.source_type||"text"===e.source_type||"id"===e.source_type)}function s(e){return n(e)&&"url"===e.source_type&&"url"in e&&"string"==typeof e.url}function a(e){return n(e)&&"base64"===e.source_type&&"data"in e&&"string"==typeof e.data}function i(e){return n(e)&&"text"===e.source_type&&"text"in e&&"string"==typeof e.text}function o(e){return n(e)&&"id"===e.source_type&&"id"in e&&"string"==typeof e.id}function c(e){if(n(e)){if("url"===e.source_type)return{type:"image_url",image_url:{url:e.url}};if("base64"===e.source_type){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function l(e){const t=e.split(";")[0].split("/");if(2!==t.length)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const r=t[0].trim(),n=t[1].trim();if(""===r||""===n)throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const s={};for(const t of e.split(";").slice(1)){const r=t.split("=");if(2!==r.length)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const n=r[0].trim(),a=r[1].trim();if(""===n)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);s[n]=a}return{type:r,subtype:n,parameters:s}}function u({dataUrl:e,asTypedArray:t=!1}){const r=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let n;if(r){n=r[1].toLowerCase();return{mime_type:n,data:t?Uint8Array.from(atob(r[2]),(e=>e.charCodeAt(0))):r[2]}}}function d(e,t){if("text"===e.type){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if("image"===e.type){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if("audio"===e.type){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if("file"===e.type){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}r.d(t,{Ac:()=>i,Ej:()=>l,Fz:()=>n,Q7:()=>u,Vi:()=>c,W:()=>s,cJ:()=>a,oe:()=>o,up:()=>d})},4301:(e,t,r)=>{"use strict";r.d(t,{XU:()=>a,bU:()=>o,cM:()=>s,kY:()=>i});var n=r(3490);class s extends n.XQ{static lc_name(){return"ChatMessage"}static _chatMessageClass(){return s}constructor(e,t){"string"==typeof e&&(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"generic"===e._getType()}get _printableFields(){return{...super._printableFields,role:this.role}}}class a extends n.gj{static lc_name(){return"ChatMessageChunk"}constructor(e,t){"string"==typeof e&&(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 a({content:(0,n._I)(this.content,e.content),additional_kwargs:(0,n.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,n.ns)(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}get _printableFields(){return{...super._printableFields,role:this.role}}}function i(e){return"generic"===e._getType()}function o(e){return"generic"===e._getType()}},4350:(e,t,r)=>{"use strict";r.d(t,{Nx:()=>c});var n=r(1259),s=r(6968),a=r(5042);const i=new class{getStore(){}run(e,t){return t()}enterWith(e){}},o=Symbol.for("lc:child_config");const c=new class{getInstance(){return(0,s.X0)()??i}getRunnableConfig(){const e=this.getInstance();return e.getStore()?.extra?.[o]}runWithConfig(e,t,r){const i=a.CallbackManager._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),c=this.getInstance(),l=c.getStore(),u=i?.getParentRunId(),d=i?.handlers?.find((e=>"langchain_tracer"===e?.name));let h;return d&&u?h=d.convertToRunTree(u):r||(h=new n.gk({name:"",tracingEnabled:!1})),h&&(h.extra={...h.extra,[o]:e}),void 0!==l&&void 0!==l[s.hr]&&(void 0===h&&(h={}),h[s.hr]=l[s.hr]),c.run(h,t)}initializeGlobalInstance(e){void 0===(0,s.X0)()&&(0,s.pH)(e)}}},4476:(e,t,r)=>{"use strict";var n,s;r.d(t,{Ii:()=>Ie,kY:()=>qe,z:()=>Tt}),function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter((e=>"number"!=typeof t[t[e]])),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map((function(e){return t[e]})),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(n||(n={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(s||(s={}));const a=n.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),i=e=>{switch(typeof e){case"undefined":return a.undefined;case"string":return a.string;case"number":return isNaN(e)?a.nan:a.number;case"boolean":return a.boolean;case"function":return a.function;case"bigint":return a.bigint;case"symbol":return a.symbol;case"object":return Array.isArray(e)?a.array:null===e?a.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?a.promise:"undefined"!=typeof Map&&e instanceof Map?a.map:"undefined"!=typeof Set&&e instanceof Set?a.set:"undefined"!=typeof Date&&e instanceof Date?a.date:a.object;default:return a.unknown}},o=n.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class c extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(n);else if("invalid_return_type"===s.code)n(s.returnTypeError);else if("invalid_arguments"===s.code)n(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,n=0;for(;ne.message){const t={},r=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}c.create=e=>new c(e);const l=(e,t)=>{let r;switch(e.code){case o.invalid_type:r=e.received===a.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case o.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,n.jsonStringifyReplacer)}`;break;case o.unrecognized_keys:r=`Unrecognized key(s) in object: ${n.joinValues(e.keys,", ")}`;break;case o.invalid_union:r="Invalid input";break;case o.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${n.joinValues(e.options)}`;break;case o.invalid_enum_value:r=`Invalid enum value. Expected ${n.joinValues(e.options)}, received '${e.received}'`;break;case o.invalid_arguments:r="Invalid function arguments";break;case o.invalid_return_type:r="Invalid function return type";break;case o.invalid_date:r="Invalid date";break;case o.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:n.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case o.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case o.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case o.custom:r="Invalid input";break;case o.invalid_intersection_types:r="Intersection results could not be merged";break;case o.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case o.not_finite:r="Number must be finite";break;default:r=t.defaultError,n.assertNever(e)}return{message:r}};let u=l;function d(){return u}const h=e=>{const{data:t,path:r,errorMaps:n,issueData:s}=e,a=[...r,...s.path||[]],i={...s,path:a};if(void 0!==s.message)return{...s,path:a,message:s.message};let o="";const c=n.filter((e=>!!e)).slice().reverse();for(const e of c)o=e(i,{data:t,defaultError:o}).message;return{...s,path:a,message:o}};function p(e,t){const r=d(),n=h({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===l?void 0:l].filter((e=>!!e))});e.common.issues.push(n)}class m{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return f;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,n=await e.value;r.push({key:t,value:n})}return m.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:s}=n;if("aborted"===t.status)return f;if("aborted"===s.status)return f;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!n.alwaysSet||(r[t.value]=s.value)}return{status:e.value,value:r}}}const f=Object.freeze({status:"aborted"}),g=e=>({status:"dirty",value:e}),y=e=>({status:"valid",value:e}),b=e=>"aborted"===e.status,w=e=>"dirty"===e.status,v=e=>"valid"===e.status,_=e=>"undefined"!=typeof Promise&&e instanceof Promise;function k(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}function S(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r}var E,x,T;"function"==typeof SuppressedError&&SuppressedError,function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(E||(E={}));class C{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const P=(e,t)=>{if(v(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new c(e.common.issues);return this._error=t,this._error}}};function O(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:s}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:s};return{errorMap:(t,s)=>{var a,i;const{message:o}=e;return"invalid_enum_value"===t.code?{message:null!=o?o:s.defaultError}:void 0===s.data?{message:null!==(a=null!=o?o:n)&&void 0!==a?a:s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:null!==(i=null!=o?o:r)&&void 0!==i?i:s.defaultError}},description:s}}class A{get description(){return this._def.description}_getType(e){return i(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:i(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new m,ctx:{common:e.parent.common,data:e.data,parsedType:i(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(_(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const n={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)},s=this._parseSync({data:e,path:n.path,parent:n});return P(n,s)}"~validate"(e){var t,r;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:n});return v(t)?{value:t.value}:{issues:n.common.issues}}catch(e){(null===(r=null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.toLowerCase())||void 0===r?void 0:r.includes("encountered"))&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then((e=>v(e)?{value:e.value}:{issues:n.common.issues}))}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)},n=this._parse({data:e,path:r.path,parent:r}),s=await(_(n)?n:Promise.resolve(n));return P(r,s)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,n)=>{const s=e(t),a=()=>n.addIssue({code:o.custom,...r(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then((e=>!!e||(a(),!1))):!!s||(a(),!1)}))}refinement(e,t){return this._refinement(((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1)))}_refinement(e){return new Ae({schema:this,typeName:qe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Ie.create(this,this._def)}nullable(){return Me.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return de.create(this)}promise(){return Oe.create(this,this._def)}or(e){return me.create([this,e],this._def)}and(e){return be.create(this,e,this._def)}transform(e){return new Ae({...O(this._def),schema:this,typeName:qe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Re({...O(this._def),innerType:this,defaultValue:t,typeName:qe.ZodDefault})}brand(){return new Le({typeName:qe.ZodBranded,type:this,...O(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new je({...O(this._def),innerType:this,catchValue:t,typeName:qe.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Fe.create(this,e)}readonly(){return De.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const I=/^c[^\s-]{8,}$/i,M=/^[0-9a-z]+$/,R=/^[0-9A-HJKMNP-TV-Z]{26}$/i,j=/^[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}$/i,N=/^[a-z0-9_-]{21}$/i,$=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,L=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,F=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let D;const z=/^(?:(?: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])$/,U=/^(?:(?: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])$/,B=/^(([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]))$/,q=/^(([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])$/,K=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,W=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,H="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",V=new RegExp(`^${H}$`);function G(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function J(e){let t=`${H}T${G(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function Z(e,t){if(!$.test(e))return!1;try{const[r]=e.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return"object"==typeof s&&null!==s&&(!(!s.typ||!s.alg)&&(!t||s.alg===t))}catch(e){return!1}}function Y(e,t){return!("v4"!==t&&t||!U.test(e))||!("v6"!==t&&t||!q.test(e))}class X extends A{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==a.string){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.string,received:t.parsedType}),f}const t=new m;let r;for(const a of this._def.checks)if("min"===a.kind)e.data.lengtha.value&&(r=this._getOrReturnCtx(e,r),p(r,{code:o.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if("length"===a.kind){const n=e.data.length>a.value,s=e.data.lengthe.test(t)),{validation:t,code:o.invalid_string,...E.errToObj(r)})}_addCheck(e){return new X({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...E.errToObj(e)})}url(e){return this._addCheck({kind:"url",...E.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...E.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...E.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...E.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...E.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...E.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...E.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...E.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...E.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...E.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...E.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...E.errToObj(e)})}datetime(e){var t,r;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(r=null==e?void 0:e.local)&&void 0!==r&&r,...E.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...E.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...E.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...E.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...E.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...E.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...E.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...E.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...E.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...E.errToObj(t)})}nonempty(e){return this.min(1,E.errToObj(e))}trim(){return new X({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new X({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new X({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.valuen?r:n;return parseInt(e.toFixed(s).replace(".",""))%parseInt(t.toFixed(s).replace(".",""))/Math.pow(10,s)}X.create=e=>{var t;return new X({checks:[],typeName:qe.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...O(e)})};class ee extends A{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==a.number){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.number,received:t.parsedType}),f}let t;const r=new m;for(const s of this._def.checks)if("int"===s.kind)n.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),p(t,{code:o.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty());else if("min"===s.kind){(s.inclusive?e.datas.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),p(t,{code:o.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty())}else"multipleOf"===s.kind?0!==Q(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),p(t,{code:o.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),p(t,{code:o.not_finite,message:s.message}),r.dirty()):n.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,E.toString(t))}gt(e,t){return this.setLimit("min",e,!1,E.toString(t))}lte(e,t){return this.setLimit("max",e,!0,E.toString(t))}lt(e,t){return this.setLimit("max",e,!1,E.toString(t))}setLimit(e,t,r,n){return new ee({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:E.toString(n)}]})}_addCheck(e){return new ee({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:E.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:E.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:E.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:E.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:E.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:E.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:E.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:E.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:E.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value"int"===e.kind||"multipleOf"===e.kind&&n.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.valuenew ee({checks:[],typeName:qe.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...O(e)});class te extends A{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch(t){return this._getInvalidInput(e)}if(this._getType(e)!==a.bigint)return this._getInvalidInput(e);let t;const r=new m;for(const s of this._def.checks)if("min"===s.kind){(s.inclusive?e.datas.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),p(t,{code:o.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty())}else"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),p(t,{code:o.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):n.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.bigint,received:t.parsedType}),f}gte(e,t){return this.setLimit("min",e,!0,E.toString(t))}gt(e,t){return this.setLimit("min",e,!1,E.toString(t))}lte(e,t){return this.setLimit("max",e,!0,E.toString(t))}lt(e,t){return this.setLimit("max",e,!1,E.toString(t))}setLimit(e,t,r,n){return new te({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:E.toString(n)}]})}_addCheck(e){return new te({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:E.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:E.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:E.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:E.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:E.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value{var t;return new te({checks:[],typeName:qe.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...O(e)})};class re extends A{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==a.boolean){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.boolean,received:t.parsedType}),f}return y(e.data)}}re.create=e=>new re({typeName:qe.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...O(e)});class ne extends A{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==a.date){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.date,received:t.parsedType}),f}if(isNaN(e.data.getTime())){return p(this._getOrReturnCtx(e),{code:o.invalid_date}),f}const t=new m;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()s.value&&(r=this._getOrReturnCtx(e,r),p(r,{code:o.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):n.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ne({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:E.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:E.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.valuenew ne({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:qe.ZodDate,...O(e)});class se extends A{_parse(e){if(this._getType(e)!==a.symbol){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.symbol,received:t.parsedType}),f}return y(e.data)}}se.create=e=>new se({typeName:qe.ZodSymbol,...O(e)});class ae extends A{_parse(e){if(this._getType(e)!==a.undefined){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.undefined,received:t.parsedType}),f}return y(e.data)}}ae.create=e=>new ae({typeName:qe.ZodUndefined,...O(e)});class ie extends A{_parse(e){if(this._getType(e)!==a.null){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.null,received:t.parsedType}),f}return y(e.data)}}ie.create=e=>new ie({typeName:qe.ZodNull,...O(e)});class oe extends A{constructor(){super(...arguments),this._any=!0}_parse(e){return y(e.data)}}oe.create=e=>new oe({typeName:qe.ZodAny,...O(e)});class ce extends A{constructor(){super(...arguments),this._unknown=!0}_parse(e){return y(e.data)}}ce.create=e=>new ce({typeName:qe.ZodUnknown,...O(e)});class le extends A{_parse(e){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.never,received:t.parsedType}),f}}le.create=e=>new le({typeName:qe.ZodNever,...O(e)});class ue extends A{_parse(e){if(this._getType(e)!==a.undefined){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.void,received:t.parsedType}),f}return y(e.data)}}ue.create=e=>new ue({typeName:qe.ZodVoid,...O(e)});class de extends A{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==a.array)return p(t,{code:o.invalid_type,expected:a.array,received:t.parsedType}),f;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,s=t.data.lengthn.maxLength.value&&(p(t,{code:o.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map(((e,r)=>n.type._parseAsync(new C(t,e,t.path,r))))).then((e=>m.mergeArray(r,e)));const s=[...t.data].map(((e,r)=>n.type._parseSync(new C(t,e,t.path,r))));return m.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new de({...this._def,minLength:{value:e,message:E.toString(t)}})}max(e,t){return new de({...this._def,maxLength:{value:e,message:E.toString(t)}})}length(e,t){return new de({...this._def,exactLength:{value:e,message:E.toString(t)}})}nonempty(e){return this.min(1,e)}}function he(e){if(e instanceof pe){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Ie.create(he(n))}return new pe({...e._def,shape:()=>t})}return e instanceof de?new de({...e._def,type:he(e.element)}):e instanceof Ie?Ie.create(he(e.unwrap())):e instanceof Me?Me.create(he(e.unwrap())):e instanceof we?we.create(e.items.map((e=>he(e)))):e}de.create=(e,t)=>new de({type:e,minLength:null,maxLength:null,exactLength:null,typeName:qe.ZodArray,...O(t)});class pe extends A{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=n.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==a.object){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.object,received:t.parsedType}),f}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:s}=this._getCached(),i=[];if(!(this._def.catchall instanceof le&&"strip"===this._def.unknownKeys))for(const e in r.data)s.includes(e)||i.push(e);const c=[];for(const e of s){const t=n[e],s=r.data[e];c.push({key:{status:"valid",value:e},value:t._parse(new C(r,s,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof le){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)c.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)i.length>0&&(p(r,{code:o.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const n=r.data[t];c.push({key:{status:"valid",value:t},value:e._parse(new C(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of c){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e})).then((e=>m.mergeObjectSync(t,e))):m.mergeObjectSync(t,c)}get shape(){return this._def.shape()}strict(e){return E.errToObj,new pe({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,s,a,i;const o=null!==(a=null===(s=(n=this._def).errorMap)||void 0===s?void 0:s.call(n,t,r).message)&&void 0!==a?a:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(i=E.errToObj(e).message)&&void 0!==i?i:o}:{message:o}}}:{}})}strip(){return new pe({...this._def,unknownKeys:"strip"})}passthrough(){return new pe({...this._def,unknownKeys:"passthrough"})}extend(e){return new pe({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new pe({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:qe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new pe({...this._def,catchall:e})}pick(e){const t={};return n.objectKeys(e).forEach((r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])})),new pe({...this._def,shape:()=>t})}omit(e){const t={};return n.objectKeys(this.shape).forEach((r=>{e[r]||(t[r]=this.shape[r])})),new pe({...this._def,shape:()=>t})}deepPartial(){return he(this)}partial(e){const t={};return n.objectKeys(this.shape).forEach((r=>{const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()})),new pe({...this._def,shape:()=>t})}required(e){const t={};return n.objectKeys(this.shape).forEach((r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Ie;)e=e._def.innerType;t[r]=e}})),new pe({...this._def,shape:()=>t})}keyof(){return Te(n.objectKeys(this.shape))}}pe.create=(e,t)=>new pe({shape:()=>e,unknownKeys:"strip",catchall:le.create(),typeName:qe.ZodObject,...O(t)}),pe.strictCreate=(e,t)=>new pe({shape:()=>e,unknownKeys:"strict",catchall:le.create(),typeName:qe.ZodObject,...O(t)}),pe.lazycreate=(e,t)=>new pe({shape:e,unknownKeys:"strip",catchall:le.create(),typeName:qe.ZodObject,...O(t)});class me extends A{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map((async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map((e=>new c(e.ctx.common.issues)));return p(t,{code:o.invalid_union,unionErrors:r}),f}));{let e;const n=[];for(const s of r){const r={...t,common:{...t.common,issues:[]},parent:null},a=s._parseSync({data:t.data,path:t.path,parent:r});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=n.map((e=>new c(e)));return p(t,{code:o.invalid_union,unionErrors:s}),f}}get options(){return this._def.options}}me.create=(e,t)=>new me({options:e,typeName:qe.ZodUnion,...O(t)});const fe=e=>e instanceof Ee?fe(e.schema):e instanceof Ae?fe(e.innerType()):e instanceof xe?[e.value]:e instanceof Ce?e.options:e instanceof Pe?n.objectValues(e.enum):e instanceof Re?fe(e._def.innerType):e instanceof ae?[void 0]:e instanceof ie?[null]:e instanceof Ie?[void 0,...fe(e.unwrap())]:e instanceof Me?[null,...fe(e.unwrap())]:e instanceof Le||e instanceof De?fe(e.unwrap()):e instanceof je?fe(e._def.innerType):[];class ge extends A{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==a.object)return p(t,{code:o.invalid_type,expected:a.object,received:t.parsedType}),f;const r=this.discriminator,n=t.data[r],s=this.optionsMap.get(n);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:o.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),f)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const n=new Map;for(const r of t){const t=fe(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const s of t){if(n.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,r)}}return new ge({typeName:qe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...O(r)})}}function ye(e,t){const r=i(e),s=i(t);if(e===t)return{valid:!0,data:e};if(r===a.object&&s===a.object){const r=n.objectKeys(t),s=n.objectKeys(e).filter((e=>-1!==r.indexOf(e))),a={...e,...t};for(const r of s){const n=ye(e[r],t[r]);if(!n.valid)return{valid:!1};a[r]=n.data}return{valid:!0,data:a}}if(r===a.array&&s===a.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n{if(b(e)||b(n))return f;const s=ye(e.value,n.value);return s.valid?((w(e)||w(n))&&t.dirty(),{status:t.value,value:s.data}):(p(r,{code:o.invalid_intersection_types}),f)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then((([e,t])=>n(e,t))):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}be.create=(e,t,r)=>new be({left:e,right:t,typeName:qe.ZodIntersection,...O(r)});class we extends A{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.array)return p(r,{code:o.invalid_type,expected:a.array,received:r.parsedType}),f;if(r.data.lengththis._def.items.length&&(p(r,{code:o.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map(((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new C(r,e,r.path,t)):null})).filter((e=>!!e));return r.common.async?Promise.all(n).then((e=>m.mergeArray(t,e))):m.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new we({...this._def,rest:e})}}we.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new we({items:e,typeName:qe.ZodTuple,rest:null,...O(t)})};class ve extends A{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.object)return p(r,{code:o.invalid_type,expected:a.object,received:r.parsedType}),f;const n=[],s=this._def.keyType,i=this._def.valueType;for(const e in r.data)n.push({key:s._parse(new C(r,e,r.path,e)),value:i._parse(new C(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?m.mergeObjectAsync(t,n):m.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new ve(t instanceof A?{keyType:e,valueType:t,typeName:qe.ZodRecord,...O(r)}:{keyType:X.create(),valueType:e,typeName:qe.ZodRecord,...O(t)})}}class _e extends A{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.map)return p(r,{code:o.invalid_type,expected:a.map,received:r.parsedType}),f;const n=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map((([e,t],a)=>({key:n._parse(new C(r,e,r.path,[a,"key"])),value:s._parse(new C(r,t,r.path,[a,"value"]))})));if(r.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const r of i){const n=await r.key,s=await r.value;if("aborted"===n.status||"aborted"===s.status)return f;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const r of i){const n=r.key,s=r.value;if("aborted"===n.status||"aborted"===s.status)return f;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}_e.create=(e,t,r)=>new _e({valueType:t,keyType:e,typeName:qe.ZodMap,...O(r)});class ke extends A{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.set)return p(r,{code:o.invalid_type,expected:a.set,received:r.parsedType}),f;const n=this._def;null!==n.minSize&&r.data.sizen.maxSize.value&&(p(r,{code:o.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const s=this._def.valueType;function i(e){const r=new Set;for(const n of e){if("aborted"===n.status)return f;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const c=[...r.data.values()].map(((e,t)=>s._parse(new C(r,e,r.path,t))));return r.common.async?Promise.all(c).then((e=>i(e))):i(c)}min(e,t){return new ke({...this._def,minSize:{value:e,message:E.toString(t)}})}max(e,t){return new ke({...this._def,maxSize:{value:e,message:E.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ke.create=(e,t)=>new ke({valueType:e,minSize:null,maxSize:null,typeName:qe.ZodSet,...O(t)});class Se extends A{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==a.function)return p(t,{code:o.invalid_type,expected:a.function,received:t.parsedType}),f;function r(e,r){return h({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,d(),l].filter((e=>!!e)),issueData:{code:o.invalid_arguments,argumentsError:r}})}function n(e,r){return h({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,d(),l].filter((e=>!!e)),issueData:{code:o.invalid_return_type,returnTypeError:r}})}const s={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof Oe){const e=this;return y((async function(...t){const a=new c([]),o=await e._def.args.parseAsync(t,s).catch((e=>{throw a.addIssue(r(t,e)),a})),l=await Reflect.apply(i,this,o);return await e._def.returns._def.type.parseAsync(l,s).catch((e=>{throw a.addIssue(n(l,e)),a}))}))}{const e=this;return y((function(...t){const a=e._def.args.safeParse(t,s);if(!a.success)throw new c([r(t,a.error)]);const o=Reflect.apply(i,this,a.data),l=e._def.returns.safeParse(o,s);if(!l.success)throw new c([n(o,l.error)]);return l.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Se({...this._def,args:we.create(e).rest(ce.create())})}returns(e){return new Se({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new Se({args:e||we.create([]).rest(ce.create()),returns:t||ce.create(),typeName:qe.ZodFunction,...O(r)})}}class Ee extends A{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Ee.create=(e,t)=>new Ee({getter:e,typeName:qe.ZodLazy,...O(t)});class xe extends A{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:o.invalid_literal,expected:this._def.value}),f}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Te(e,t){return new Ce({values:e,typeName:qe.ZodEnum,...O(t)})}xe.create=(e,t)=>new xe({value:e,typeName:qe.ZodLiteral,...O(t)});class Ce extends A{constructor(){super(...arguments),x.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return p(t,{expected:n.joinValues(r),received:t.parsedType,code:o.invalid_type}),f}if(k(this,x,"f")||S(this,x,new Set(this._def.values),"f"),!k(this,x,"f").has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return p(t,{received:t.data,code:o.invalid_enum_value,options:r}),f}return y(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Ce.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ce.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}x=new WeakMap,Ce.create=Te;class Pe extends A{constructor(){super(...arguments),T.set(this,void 0)}_parse(e){const t=n.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==a.string&&r.parsedType!==a.number){const e=n.objectValues(t);return p(r,{expected:n.joinValues(e),received:r.parsedType,code:o.invalid_type}),f}if(k(this,T,"f")||S(this,T,new Set(n.getValidEnumValues(this._def.values)),"f"),!k(this,T,"f").has(e.data)){const e=n.objectValues(t);return p(r,{received:r.data,code:o.invalid_enum_value,options:e}),f}return y(e.data)}get enum(){return this._def.values}}T=new WeakMap,Pe.create=(e,t)=>new Pe({values:e,typeName:qe.ZodNativeEnum,...O(t)});class Oe extends A{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==a.promise&&!1===t.common.async)return p(t,{code:o.invalid_type,expected:a.promise,received:t.parsedType}),f;const r=t.parsedType===a.promise?t.data:Promise.resolve(t.data);return y(r.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}Oe.create=(e,t)=>new Oe({type:e,typeName:qe.ZodPromise,...O(t)});class Ae extends A{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===qe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:e=>{p(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),"preprocess"===s.type){const e=s.transform(r.data,a);if(r.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return f;const n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?f:"dirty"===n.status||"dirty"===t.value?g(n.value):n}));{if("aborted"===t.value)return f;const n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?f:"dirty"===n.status||"dirty"===t.value?g(n.value):n}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,a);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?f:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((r=>"aborted"===r.status?f:("dirty"===r.status&&t.dirty(),e(r.value).then((()=>({status:t.value,value:r.value}))))))}if("transform"===s.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!v(e))return e;const n=s.transform(e.value,a);if(n instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((e=>v(e)?Promise.resolve(s.transform(e.value,a)).then((e=>({status:t.value,value:e}))):e))}n.assertNever(s)}}Ae.create=(e,t,r)=>new Ae({schema:e,typeName:qe.ZodEffects,effect:t,...O(r)}),Ae.createWithPreprocess=(e,t,r)=>new Ae({schema:t,effect:{type:"preprocess",transform:e},typeName:qe.ZodEffects,...O(r)});class Ie extends A{_parse(e){return this._getType(e)===a.undefined?y(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:qe.ZodOptional,...O(t)});class Me extends A{_parse(e){return this._getType(e)===a.null?y(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Me.create=(e,t)=>new Me({innerType:e,typeName:qe.ZodNullable,...O(t)});class Re extends A{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===a.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Re.create=(e,t)=>new Re({innerType:e,typeName:qe.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...O(t)});class je extends A{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return _(n)?n.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new c(r.common.issues)},input:r.data})}))):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new c(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}je.create=(e,t)=>new je({innerType:e,typeName:qe.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...O(t)});class Ne extends A{_parse(e){if(this._getType(e)!==a.nan){const t=this._getOrReturnCtx(e);return p(t,{code:o.invalid_type,expected:a.nan,received:t.parsedType}),f}return{status:"valid",value:e.data}}}Ne.create=e=>new Ne({typeName:qe.ZodNaN,...O(e)});const $e=Symbol("zod_brand");class Le extends A{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Fe extends A{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?f:"dirty"===e.status?(t.dirty(),g(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?f:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Fe({in:e,out:t,typeName:qe.ZodPipeline})}}class De extends A{_parse(e){const t=this._def.innerType._parse(e),r=e=>(v(e)&&(e.value=Object.freeze(e.value)),e);return _(t)?t.then((e=>r(e))):r(t)}unwrap(){return this._def.innerType}}function ze(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function Ue(e,t={},r){return e?oe.create().superRefine(((n,s)=>{var a,i;const o=e(n);if(o instanceof Promise)return o.then((e=>{var a,i;if(!e){const e=ze(t,n),o=null===(i=null!==(a=e.fatal)&&void 0!==a?a:r)||void 0===i||i;s.addIssue({code:"custom",...e,fatal:o})}}));if(!o){const e=ze(t,n),o=null===(i=null!==(a=e.fatal)&&void 0!==a?a:r)||void 0===i||i;s.addIssue({code:"custom",...e,fatal:o})}})):oe.create()}De.create=(e,t)=>new De({innerType:e,typeName:qe.ZodReadonly,...O(t)});const Be={object:pe.lazycreate};var qe;!function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(qe||(qe={}));const Ke=X.create,We=ee.create,He=Ne.create,Ve=te.create,Ge=re.create,Je=ne.create,Ze=se.create,Ye=ae.create,Xe=ie.create,Qe=oe.create,et=ce.create,tt=le.create,rt=ue.create,nt=de.create,st=pe.create,at=pe.strictCreate,it=me.create,ot=ge.create,ct=be.create,lt=we.create,ut=ve.create,dt=_e.create,ht=ke.create,pt=Se.create,mt=Ee.create,ft=xe.create,gt=Ce.create,yt=Pe.create,bt=Oe.create,wt=Ae.create,vt=Ie.create,_t=Me.create,kt=Ae.createWithPreprocess,St=Fe.create,Et={string:e=>X.create({...e,coerce:!0}),number:e=>ee.create({...e,coerce:!0}),boolean:e=>re.create({...e,coerce:!0}),bigint:e=>te.create({...e,coerce:!0}),date:e=>ne.create({...e,coerce:!0})},xt=f;var Tt=Object.freeze({__proto__:null,defaultErrorMap:l,setErrorMap:function(e){u=e},getErrorMap:d,makeIssue:h,EMPTY_PATH:[],addIssueToContext:p,ParseStatus:m,INVALID:f,DIRTY:g,OK:y,isAborted:b,isDirty:w,isValid:v,isAsync:_,get util(){return n},get objectUtil(){return s},ZodParsedType:a,getParsedType:i,ZodType:A,datetimeRegex:J,ZodString:X,ZodNumber:ee,ZodBigInt:te,ZodBoolean:re,ZodDate:ne,ZodSymbol:se,ZodUndefined:ae,ZodNull:ie,ZodAny:oe,ZodUnknown:ce,ZodNever:le,ZodVoid:ue,ZodArray:de,ZodObject:pe,ZodUnion:me,ZodDiscriminatedUnion:ge,ZodIntersection:be,ZodTuple:we,ZodRecord:ve,ZodMap:_e,ZodSet:ke,ZodFunction:Se,ZodLazy:Ee,ZodLiteral:xe,ZodEnum:Ce,ZodNativeEnum:Pe,ZodPromise:Oe,ZodEffects:Ae,ZodTransformer:Ae,ZodOptional:Ie,ZodNullable:Me,ZodDefault:Re,ZodCatch:je,ZodNaN:Ne,BRAND:$e,ZodBranded:Le,ZodPipeline:Fe,ZodReadonly:De,custom:Ue,Schema:A,ZodSchema:A,late:Be,get ZodFirstPartyTypeKind(){return qe},coerce:Et,any:Qe,array:nt,bigint:Ve,boolean:Ge,date:Je,discriminatedUnion:ot,effect:wt,enum:gt,function:pt,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>Ue((t=>t instanceof e),t),intersection:ct,lazy:mt,literal:ft,map:dt,nan:He,nativeEnum:yt,never:tt,null:Xe,nullable:_t,number:We,object:st,oboolean:()=>Ge().optional(),onumber:()=>We().optional(),optional:vt,ostring:()=>Ke().optional(),pipeline:St,preprocess:kt,promise:bt,record:ut,set:ht,strictObject:at,string:Ke,symbol:Ze,transformer:wt,tuple:lt,undefined:Ye,union:it,unknown:et,void:rt,NEVER:xt,ZodIssueCode:o,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:c})},4493:(e,t,r)=>{"use strict";const n=r(3908);e.exports=(e,t)=>new n(e,t).patch},4547:(e,t,r)=>{"use strict";r.d(t,{Kj:()=>n.Kj,Ls:()=>a,gk:()=>s.gk});var n=r(9056),s=r(3246);r(747);const a="0.3.29"},4552:(e,t,r)=>{"use strict";r.d(t,{l:()=>a});var n=r(3313),s=r(9849);class a extends n.YN{static lc_name(){return"DictPromptTemplate"}constructor(e){const t=e.templateFormat??"f-string",r=i(e.template,t);super({inputVariables:r,...e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","dict"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.template=e.template,this.templateFormat=t,this.inputVariables=r}async format(e){return o(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}}function i(e,t){const r=[];for(const n of Object.values(e))if("string"==typeof n)(0,s.QC)(n,t).forEach((e=>{"variable"===e.type&&r.push(e.name)}));else if(Array.isArray(n))for(const e of n)"string"==typeof e?(0,s.QC)(e,t).forEach((e=>{"variable"===e.type&&r.push(e.name)})):"object"==typeof e&&r.push(...i(e,t));else"object"==typeof n&&null!==n&&r.push(...i(n,t));return Array.from(new Set(r))}function o(e,t,r){const n={};for(const[a,i]of Object.entries(e))if("string"==typeof i)n[a]=(0,s.Xm)(i,r,t);else if(Array.isArray(i)){const e=[];for(const n of i)"string"==typeof n?e.push((0,s.Xm)(n,r,t)):"object"==typeof n&&e.push(o(n,t,r));n[a]=e}else n[a]="object"==typeof i&&null!==i?o(i,t,r):i;return n}},4617:e=>{"use strict";e.exports=(e,t)=>(t=t||(()=>{}),e.then((e=>new Promise((e=>{e(t())})).then((()=>e))),(e=>new Promise((e=>{e(t())})).then((()=>{throw e})))))},4641:(e,t,r)=>{"use strict";const n=r(560);e.exports=(e,t,r)=>0===n(e,t,r)},4774:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(9998);t.default=class{constructor(){this._queue=[]}enqueue(e,t){const r={priority:(t=Object.assign({priority:0},t)).priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority)return void this._queue.push(r);const s=n.default(this._queue,r,((e,t)=>t.priority-e.priority));this._queue.splice(s,0,r)}dequeue(){const e=this._queue.shift();return null==e?void 0:e.run}filter(e){return this._queue.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this._queue.length}}},4785:(e,t,r)=>{"use strict";r.d(t,{Az:()=>h,Ec:()=>l,Jz:()=>p,yk:()=>u});var n=r(4547);let s;const a=()=>"undefined"!=typeof Deno,i=()=>s||(s="undefined"!=typeof window&&void 0!==window.document?"browser":"undefined"==typeof process||void 0===process.versions||void 0===process.versions.node||a()?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"))?"jsdom":a()?"deno":"other":"node",s);let o,c;function l(){if(void 0===o){const e=i(),t=function(){if(void 0!==c)return c;const e=["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"],t={};for(const r of e){const e=h(r);void 0!==e&&(t[r]=e)}return c=t,t}();o={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:n.Ls,...t}}return o}function u(){const e=d()||{},t={},r=["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[n,s]of Object.entries(e))!n.startsWith("LANGCHAIN_")&&!n.startsWith("LANGSMITH_")||"string"!=typeof s||r.includes(n)||n.toLowerCase().includes("key")||n.toLowerCase().includes("secret")||n.toLowerCase().includes("token")||("LANGCHAIN_REVISION_ID"===n?t.revision_id=s:t[n]=s);return t}function d(){try{return"undefined"!=typeof process&&process.env?Object.entries(process.env).reduce(((e,[t,r])=>(e[t]=String(r),e)),{}):void 0}catch(e){return}}function h(e){try{return"undefined"!=typeof process?process.env?.[e]:void 0}catch(e){return}}function p(e){return h(`LANGSMITH_${e}`)||h(`LANGCHAIN_${e}`)}},4850:(e,t,r)=>{"use strict";function n(e){return!!e&&e.lc_runnable}r.d(t,{G:()=>s,T:()=>n});class s{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=void 0===this.includeNames&&void 0===this.includeTypes&&void 0===this.includeTags;const n=e.tags??[];return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(t)),void 0!==this.includeTags&&(r=r||n.some((e=>this.includeTags?.includes(e)))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(t)),void 0!==this.excludeTags&&(r=r&&n.every((e=>!this.excludeTags?.includes(e)))),r}}},5001:(e,t,r)=>{"use strict";r.r(t),r.d(t,{BrowserWebSocketTransport:()=>n});class n{static create(e){return new Promise(((t,r)=>{const s=new WebSocket(e);s.addEventListener("open",(()=>t(new n(s)))),s.addEventListener("error",r)}))}#e;onmessage;onclose;constructor(e){this.#e=e,this.#e.addEventListener("message",(e=>{this.onmessage&&this.onmessage.call(null,e.data)})),this.#e.addEventListener("close",(()=>{this.onclose&&this.onclose.call(null)})),this.#e.addEventListener("error",(()=>{}))}send(e){this.#e.send(e)}close(){this.#e.close()}}},5032:(e,t,r)=>{"use strict";const n=r(8311),s=r(3904),{ANY:a}=s,i=r(7638),o=r(560),c=[new s(">=0.0.0-0")],l=[new s(">=0.0.0")],u=(e,t,r)=>{if(e===t)return!0;if(1===e.length&&e[0].semver===a){if(1===t.length&&t[0].semver===a)return!0;e=r.includePrerelease?c:l}if(1===t.length&&t[0].semver===a){if(r.includePrerelease)return!0;t=l}const n=new Set;let s,u,p,m,f,g,y;for(const t of e)">"===t.operator||">="===t.operator?s=d(s,t,r):"<"===t.operator||"<="===t.operator?u=h(u,t,r):n.add(t.semver);if(n.size>1)return null;if(s&&u){if(p=o(s.semver,u.semver,r),p>0)return null;if(0===p&&(">="!==s.operator||"<="!==u.operator))return null}for(const e of n){if(s&&!i(e,String(s),r))return null;if(u&&!i(e,String(u),r))return null;for(const n of t)if(!i(e,String(n),r))return!1;return!0}let b=!(!u||r.includePrerelease||!u.semver.prerelease.length)&&u.semver,w=!(!s||r.includePrerelease||!s.semver.prerelease.length)&&s.semver;b&&1===b.prerelease.length&&"<"===u.operator&&0===b.prerelease[0]&&(b=!1);for(const e of t){if(y=y||">"===e.operator||">="===e.operator,g=g||"<"===e.operator||"<="===e.operator,s)if(w&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===w.major&&e.semver.minor===w.minor&&e.semver.patch===w.patch&&(w=!1),">"===e.operator||">="===e.operator){if(m=d(s,e,r),m===e&&m!==s)return!1}else if(">="===s.operator&&!i(s.semver,String(e),r))return!1;if(u)if(b&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===b.major&&e.semver.minor===b.minor&&e.semver.patch===b.patch&&(b=!1),"<"===e.operator||"<="===e.operator){if(f=h(u,e,r),f===e&&f!==u)return!1}else if("<="===u.operator&&!i(u.semver,String(e),r))return!1;if(!e.operator&&(u||s)&&0!==p)return!1}return!(s&&g&&!u&&0!==p)&&(!(u&&y&&!s&&0!==p)&&(!w&&!b))},d=(e,t,r)=>{if(!e)return t;const n=o(e.semver,t.semver,r);return n>0?e:n<0||">"===t.operator&&">="===e.operator?t:e},h=(e,t,r)=>{if(!e)return t;const n=o(e.semver,t.semver,r);return n<0?e:n>0||"<"===t.operator&&"<="===e.operator?t:e};e.exports=(e,t,r={})=>{if(e===t)return!0;e=new n(e,r),t=new n(t,r);let s=!1;e:for(const n of e.set){for(const e of t.set){const t=u(n,e,r);if(s=s||null!==t,t)continue e}if(s)return!1}return!0}},5042:(e,t,r)=>{"use strict";r.r(t),r.d(t,{BaseCallbackManager:()=>g,BaseRunManager:()=>y,CallbackManager:()=>k,CallbackManagerForChainRun:()=>v,CallbackManagerForLLMRun:()=>w,CallbackManagerForRetrieverRun:()=>b,CallbackManagerForToolRun:()=>_,TraceGroup:()=>E,ensureHandler:()=>S,parseCallbackConfigArg:()=>f,traceAsGroup:()=>x});var n=r(9120),s=r(5960),a=r(6906),i=r(6362),o=r(9583),c=r(3997),l=r(2293);var u=r(1590),d=(r(1688),r(6968));function h(e){const t=(0,d.X0)();if(void 0===t)return;const r=t.getStore();return r?.[d.hr]?.[e]}const p=Symbol("lc:configure_hooks"),m=()=>h(p)||[];function f(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}class g{setHandler(e){return this.setHandlers([e])}}class y{constructor(e,t,r,n,s,a,i,o){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:n}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:o})}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{try{await(t.handleText?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleCustomEvent(e,t,r,n,s){await Promise.all(this.handlers.map((r=>(0,l.consumeCallback)((async()=>{try{await(r.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleCustomEvent: ${e}`),r.raiseError)throw e}}),r.awaitHandlers))))}}class b extends y{getChild(e){const t=new k(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=>(0,l.consumeCallback)((async()=>{if(!t.ignoreRetriever)try{await(t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleRetrieverError(e){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{if(!t.ignoreRetriever)try{await(t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags))}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${r}`),t.raiseError)throw e}}),t.awaitHandlers))))}}class w extends y{async handleLLMNewToken(e,t,r,n,s,a){await Promise.all(this.handlers.map((r=>(0,l.consumeCallback)((async()=>{if(!r.ignoreLLM)try{await(r.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMNewToken: ${e}`),r.raiseError)throw e}}),r.awaitHandlers))))}async handleLLMError(e,t,r,n,s){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{if(!t.ignoreLLM)try{await(t.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,s))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMError: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleLLMEnd(e,t,r,n,s){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{if(!t.ignoreLLM)try{await(t.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,s))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMEnd: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}}class v extends y{getChild(e){const t=new k(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,n,s){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{if(!t.ignoreChain)try{await(t.handleChainError?.(e,this.runId,this._parentRunId,this.tags,s))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainError: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleChainEnd(e,t,r,n,s){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{if(!t.ignoreChain)try{await(t.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,s))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainEnd: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleAgentAction(e){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{if(!t.ignoreAgent)try{await(t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleAgentEnd(e){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{if(!t.ignoreAgent)try{await(t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}}class _ extends y{getChild(e){const t=new k(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=>(0,l.consumeCallback)((async()=>{if(!t.ignoreAgent)try{await(t.handleToolError?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}async handleToolEnd(e){await Promise.all(this.handlers.map((t=>(0,l.consumeCallback)((async()=>{if(!t.ignoreAgent)try{await(t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${e}`),t.raiseError)throw e}}),t.awaitHandlers))))}}class k extends g{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?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,r=void 0,s=void 0,a=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(t.map((async(t,s)=>{const i=0===s&&r?r:(0,n.A)();return await Promise.all(this.handlers.map((r=>{if(!r.ignoreLLM)return(0,u.isBaseTracer)(r)&&r._createRunForLLMStart(e,[t],i,this._parentRunId,a,this.tags,this.metadata,c),(0,l.consumeCallback)((async()=>{try{await(r.handleLLMStart?.(e,[t],i,this._parentRunId,a,this.tags,this.metadata,c))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}}),r.awaitHandlers)}))),new w(i,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)})))}async handleChatModelStart(e,t,r=void 0,s=void 0,a=void 0,o=void 0,c=void 0,d=void 0){return Promise.all(t.map((async(t,s)=>{const o=0===s&&r?r:(0,n.A)();return await Promise.all(this.handlers.map((r=>{if(!r.ignoreLLM)return(0,u.isBaseTracer)(r)&&r._createRunForChatModelStart(e,[t],o,this._parentRunId,a,this.tags,this.metadata,d),(0,l.consumeCallback)((async()=>{try{if(r.handleChatModelStart)await(r.handleChatModelStart?.(e,[t],o,this._parentRunId,a,this.tags,this.metadata,d));else if(r.handleLLMStart){const n=(0,i.Sw)(t);await(r.handleLLMStart?.(e,[n],o,this._parentRunId,a,this.tags,this.metadata,d))}}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}}),r.awaitHandlers)}))),new w(o,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)})))}async handleChainStart(e,t,r=(0,n.A)(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map((n=>{if(!n.ignoreChain)return(0,u.isBaseTracer)(n)&&n._createRunForChainStart(e,t,r,this._parentRunId,this.tags,this.metadata,s,o),(0,l.consumeCallback)((async()=>{try{await(n.handleChainStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s,o))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleChainStart: ${e}`),n.raiseError)throw e}}),n.awaitHandlers)}))),new v(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,r=(0,n.A)(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map((n=>{if(!n.ignoreAgent)return(0,u.isBaseTracer)(n)&&n._createRunForToolStart(e,t,r,this._parentRunId,this.tags,this.metadata,o),(0,l.consumeCallback)((async()=>{try{await(n.handleToolStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,o))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleToolStart: ${e}`),n.raiseError)throw e}}),n.awaitHandlers)}))),new _(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,r=(0,n.A)(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map((n=>{if(!n.ignoreRetriever)return(0,u.isBaseTracer)(n)&&n._createRunForRetrieverStart(e,t,r,this._parentRunId,this.tags,this.metadata,o),(0,l.consumeCallback)((async()=>{try{await(n.handleRetrieverStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,o))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleRetrieverStart: ${e}`),n.raiseError)throw e}}),n.awaitHandlers)}))),new b(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,r,n,s){await Promise.all(this.handlers.map((n=>(0,l.consumeCallback)((async()=>{if(!n.ignoreCustomEvent)try{await(n.handleCustomEvent?.(e,t,r,this.tags,this.metadata))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleCustomEvent: ${e}`),n.raiseError)throw e}}),n.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 k(this._parentRunId);for(const e of this.handlers){const t=this.inheritableHandlers.includes(e);r.addHandler(e,t)}for(const e of this.tags){const t=this.inheritableTags.includes(e);r.addTags([e],t)}for(const e of Object.keys(this.metadata)){const t=Object.keys(this.inheritableMetadata).includes(e);r.addMetadata({[e]:this.metadata[e]},t)}for(const n of e)r.handlers.filter((e=>"console_callback_handler"===e.name)).some((e=>e.name===n.name))||r.addHandler(n,t);return r}static fromHandlers(e){class t extends s.BaseCallbackHandler{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:(0,n.A)()}),Object.assign(this,e)}}const r=new this;return r.addHandler(new t),r}static configure(e,t,r,n,s,a,i){return this._configureSync(e,t,r,n,s,a,i)}static _configureSync(e,t,r,n,i,l,u){let d;(e||t)&&(Array.isArray(e)||!e?(d=new k,d.setHandlers(e?.map(S)??[],!0)):d=e,d=d.copy(Array.isArray(t)?t.map(S):t?.handlers,!1));const p="true"===(0,o.getEnvironmentVariable)("LANGCHAIN_VERBOSE")||u?.verbose,f=c.LangChainTracer.getTraceableRunTree()?.tracingEnabled||(e=>void 0!==e?e:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find((e=>"true"===(0,o.getEnvironmentVariable)(e))))(),g=f||((0,o.getEnvironmentVariable)("LANGCHAIN_TRACING")??!1);if(p||g){if(d||(d=new k),p&&!d.handlers.some((e=>e.name===a.ConsoleCallbackHandler.prototype.name))){const e=new a.ConsoleCallbackHandler;d.addHandler(e,!0)}if(g&&!d.handlers.some((e=>"langchain_tracer"===e.name))&&f){const e=new c.LangChainTracer;d.addHandler(e,!0),d._parentRunId=c.LangChainTracer.getTraceableRunTree()?.id??d._parentRunId}}for(const{contextVar:e,inheritable:t=!0,handlerClass:r,envVar:n}of m()){const a=n&&"true"===(0,o.getEnvironmentVariable)(n)&&r;let i;const c=void 0!==e?h(e):void 0;c&&(0,s.isBaseCallbackHandler)(c)?i=c:a&&(i=new r({})),void 0!==i&&(d||(d=new k),d.handlers.some((e=>e.name===i.name))||d.addHandler(i,t))}return(r||n)&&d&&(d.addTags(r??[]),d.addTags(n??[],!1)),(i||l)&&d&&(d.addMetadata(i??{}),d.addMetadata(l??{},!1)),d}}function S(e){return"name"in e?e:s.BaseCallbackHandler.fromMethods(e)}class E{constructor(e,t){Object.defineProperty(this,"groupName",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"runManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async getTraceGroupCallbackManager(e,t,r){const n=new c.LangChainTracer(r),s=await k.configure([n]),a=await(s?.handleChainStart({lc:1,type:"not_implemented",id:["langchain","callbacks","groups",e]},t??{}));if(!a)throw new Error("Failed to create run group callback manager.");return a}async start(e){return this.runManager||(this.runManager=await this.getTraceGroupCallbackManager(this.groupName,e,this.options)),this.runManager.getChild()}async error(e){this.runManager&&(await this.runManager.handleChainError(e),this.runManager=void 0)}async end(e){this.runManager&&(await this.runManager.handleChainEnd(e??{}),this.runManager=void 0)}}async function x(e,t,...r){const n=new E(e.name,e),s=await n.start({...r});try{const e=await t(s,...r);return await n.end((a=e,i="output",a&&!Array.isArray(a)&&"object"==typeof a?a:{[i]:a})),e}catch(e){throw await n.error(e),e}var a,i}},5200:(e,t,r)=>{"use strict";const n=r(560);e.exports=(e,t,r)=>n(e,t,r)<=0},5230:(e,t,r)=>{"use strict";r.d(t,{A:()=>u});const n={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};var s,a=new Uint8Array(16);function i(){if(!s&&!(s="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return s(a)}for(var o=[],c=0;c<256;++c)o.push((c+256).toString(16).slice(1));function l(e,t=0){return(o[e[t+0]]+o[e[t+1]]+o[e[t+2]]+o[e[t+3]]+"-"+o[e[t+4]]+o[e[t+5]]+"-"+o[e[t+6]]+o[e[t+7]]+"-"+o[e[t+8]]+o[e[t+9]]+"-"+o[e[t+10]]+o[e[t+11]]+o[e[t+12]]+o[e[t+13]]+o[e[t+14]]+o[e[t+15]]).toLowerCase()}const u=function(e,t,r){if(n.randomUUID&&!t&&!e)return n.randomUUID();var s=(e=e||{}).random||(e.rng||i)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){r=r||0;for(var a=0;a<16;++a)t[r+a]=s[a];return t}return l(s)}},5311:(e,t,r)=>{"use strict";r.r(t),r.d(t,{BasePromptValue:()=>i,ChatPromptValue:()=>c,ImagePromptValue:()=>l,StringPromptValue:()=>o});var n=r(7380),s=r(5454),a=r(6362);class i extends n.Serializable{}class o extends i{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 s.xc(this.value)]}}class c extends i{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(0,a.Sw)(this.messages)}toChatMessages(){return this.messages}}class l extends i{static lc_name(){return"ImagePromptValue"}constructor(e){"imageUrl"in e||(e={imageUrl: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,"imageUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new s.xc({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}},5342:(e,t,r)=>{"use strict";const n=r(7075);e.exports=(e,t,r)=>n(e,t,"<",r)},5454:(e,t,r)=>{"use strict";r.d(t,{GZ:()=>o,a7:()=>a,di:()=>i,xc:()=>s});var n=r(3490);class s extends n.XQ{static lc_name(){return"HumanMessage"}_getType(){return"human"}constructor(e,t){super(e,t)}}class a extends n.gj{static lc_name(){return"HumanMessageChunk"}_getType(){return"human"}constructor(e,t){super(e,t)}concat(e){return new a({content:(0,n._I)(this.content,e.content),additional_kwargs:(0,n.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,n.ns)(this.response_metadata,e.response_metadata),id:this.id??e.id})}}function i(e){return"human"===e.getType()}function o(e){return"human"===e.getType()}},5571:(e,t,r)=>{"use strict";const n=r(7075);e.exports=(e,t,r)=>n(e,t,">",r)},5580:(e,t,r)=>{"use strict";const n=r(560);e.exports=(e,t,r)=>n(e,t,r)>0},5617:(e,t,r)=>{e.exports=r(8303)},5960:(e,t,r)=>{"use strict";r.r(t),r.d(t,{BaseCallbackHandler:()=>c,callbackHandlerPrefersStreaming:()=>o,isBaseCallbackHandler:()=>l});var n=r(9120),s=r(7380),a=r(9583);class i{}function o(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}class c extends i{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,(0,s.get_lc_unique_name)(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:"false"===(0,a.getEnvironmentVariable)("LANGCHAIN_CALLBACKS_BACKGROUND")}),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 s.Serializable.prototype.toJSON.call(this)}toJSONNotImplemented(){return s.Serializable.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){return new class extends c{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:n.A()}),Object.assign(this,e)}}}}const l=e=>{const t=e;return void 0!==t&&"function"==typeof t.copy&&"string"==typeof t.name&&"boolean"==typeof t.awaitHandlers}},6150:(e,t,r)=>{"use strict";r.d(t,{X6:()=>v,UD:()=>T});var n={};r.r(n),r.d(n,{JsonPatchError:()=>m,_areEquals:()=>E,applyOperation:()=>w,applyPatch:()=>v,applyReducer:()=>_,deepClone:()=>f,getValueByPointer:()=>b,validate:()=>S,validator:()=>k});const s=Object.prototype.hasOwnProperty;function a(e,t){return s.call(e,t)}function i(e){if(Array.isArray(e)){const t=new Array(e.length);for(let e=0;e=48&&n<=57))return!1;t++}return!0}function l(e){return-1===e.indexOf("/")&&-1===e.indexOf("~")?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function u(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function d(e){if(void 0===e)return!0;if(e)if(Array.isArray(e)){for(let t=0,r=e.length;t0&&"constructor"==i[f-1]))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(r&&void 0===l&&(void 0===p[d]?l=i.slice(0,f).join("/"):f==b-1&&(l=t.path),void 0!==l&&h(t,0,e,l)),f++,Array.isArray(p)){if("-"===d)d=p.length;else{if(r&&!c(d))throw new m("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",a,t,e);c(d)&&(d=~~d)}if(f>=b){if(r&&"add"===t.op&&d>p.length)throw new m("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a,t,e);const n=y[t.op].call(t,p,d,e);if(!1===n.test)throw new m("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return n}}else if(f>=b){const r=g[t.op].call(t,p,d,e);if(!1===r.test)throw new m("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return r}if(p=p[d],r&&f0)throw new m('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new m("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new m("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&d(e.value))throw new m("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);if(r)if("add"==e.op){var s=e.path.split("/").length,a=n.split("/").length;if(s!==a+1&&s!==a)throw new m("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==n)throw new m("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if("move"===e.op||"copy"===e.op){var i=S([{op:"_get",path:e.from,value:void 0}],r);if(i&&"OPERATION_PATH_UNRESOLVABLE"===i.name)throw new m("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}function S(e,t,r){try{if(!Array.isArray(e))throw new m("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)v(o(t),o(e),r||!0);else{r=r||k;for(var n=0;n=0;h--){var p=e[f=u[h]];if(!a(t,f)||void 0===t[f]&&void 0!==p&&!1===Array.isArray(t))Array.isArray(e)===Array.isArray(t)?(s&&r.push({op:"test",path:n+"/"+l(f),value:o(p)}),r.push({op:"remove",path:n+"/"+l(f)}),d=!0):(s&&r.push({op:"test",path:n,value:e}),r.push({op:"replace",path:n,value:t}),!0);else{var m=t[f];"object"==typeof p&&null!=p&&"object"==typeof m&&null!=m&&Array.isArray(p)===Array.isArray(m)?x(p,m,r,n+"/"+l(f),s):p!==m&&(s&&r.push({op:"test",path:n+"/"+l(f),value:o(p)}),r.push({op:"replace",path:n+"/"+l(f),value:o(m)}))}}if(d||c.length!=u.length)for(h=0;h{"use strict";const n=r(3908),s=r(144),{safeRe:a,t:i}=r(9718);e.exports=(e,t)=>{if(e instanceof n)return e;if("number"==typeof e&&(e=String(e)),"string"!=typeof e)return null;let r=null;if((t=t||{}).rtl){const n=t.includePrerelease?a[i.COERCERTLFULL]:a[i.COERCERTL];let s;for(;(s=n.exec(e))&&(!r||r.index+r[0].length!==e.length);)r&&s.index+s[0].length===r.index+r[0].length||(r=s),n.lastIndex=s.index+s[1].length+s[2].length;n.lastIndex=-1}else r=e.match(t.includePrerelease?a[i.COERCEFULL]:a[i.COERCE]);if(null===r)return null;const o=r[2],c=r[3]||"0",l=r[4]||"0",u=t.includePrerelease&&r[5]?`-${r[5]}`:"",d=t.includePrerelease&&r[6]?`+${r[6]}`:"";return s(`${o}.${c}.${l}${u}${d}`,t)}},6232:(e,t,r)=>{"use strict";r.d(t,{m:()=>s});const n={};function s(e){n[e]||(console.warn(e),n[e]=!0)}},6254:(e,t,r)=>{"use strict";const n=r(3908);e.exports=(e,t)=>new n(e,t).minor},6279:(e,t,r)=>{"use strict";r.d(t,{C:()=>i});var n=r(5311),s=r(6993),a=r(9849);class i extends s.m{static lc_name(){return"ImagePromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","image"]}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.template=e.template,this.templateFormat=e.templateFormat??this.templateFormat,this.validateTemplate=e.validateTemplate??this.validateTemplate,this.additionalContentFields=e.additionalContentFields,this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),(0,a.Ns)([{type:"image_url",image_url:this.template}],this.templateFormat,e)}}_getPromptType(){return"prompt"}async partial(e){const t=this.inputVariables.filter((t=>!(t in e))),r={...this.partialVariables??{},...e},n={...this,inputVariables:t,partialVariables:r};return new i(n)}async format(e){const t={};for(const[r,n]of Object.entries(this.template))t[r]="string"==typeof n?(0,a.Xm)(n,this.templateFormat,e):n;const r=e.url||t.url,n=e.detail||t.detail;if(!r)throw new Error("Must provide either an image URL.");if("string"!=typeof r)throw new Error("url must be a string.");const s={url:r};return n&&(s.detail=n),s}async formatPromptValue(e){const t=await this.format(e);return new n.ImagePromptValue(t)}}},6362:(e,t,r)=>{"use strict";r.d(t,{Js:()=>b,K0:()=>m,Pz:()=>g,Sw:()=>f,ih:()=>w,rf:()=>y});var n=r(1368),s=r(199),a=r(7765),i=r(3490),o=r(4301),c=r(8675),l=r(5454),u=r(7974),d=r(8009);function h(e){return(0,s.Ky)(e)?e:"string"==typeof e.id&&"function"===e.type&&"object"==typeof e.function&&null!==e.function&&"arguments"in e.function&&"string"==typeof e.function.arguments&&"name"in e.function&&"string"==typeof e.function.name?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function p(e){let t,r;if("object"==typeof(s=e)&&null!=s&&1===s.lc&&Array.isArray(s.id)&&null!=s.kwargs&&"object"==typeof s.kwargs){const n=e.id.at(-1);t="HumanMessage"===n||"HumanMessageChunk"===n?"user":"AIMessage"===n||"AIMessageChunk"===n?"assistant":"SystemMessage"===n||"SystemMessageChunk"===n?"system":"FunctionMessage"===n||"FunctionMessageChunk"===n?"function":"ToolMessage"===n||"ToolMessageChunk"===n?"tool":"unknown",r=e.kwargs}else{const{type:n,...s}=e;t=n,r=s}var s;if("human"===t||"user"===t)return new l.xc(r);if("ai"===t||"assistant"===t){const{tool_calls:e,...t}=r;if(!Array.isArray(e))return new a.Od(r);const n=e.map(h);return new a.Od({...t,tool_calls:n})}if("system"===t)return new u.tn(r);if("developer"===t)return new u.tn({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if("tool"===t&&"tool_call_id"in r)return new d.uf({...r,content:r.content,tool_call_id:r.tool_call_id,name:r.name});throw(0,n.Y)(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\n\nReceived: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}function m(e){if("string"==typeof e)return new l.xc(e);if((0,i.ny)(e))return e;if(Array.isArray(e)){const[t,r]=e;return p({type:t,content:r})}if((0,i.dp)(e)){const{role:t,...r}=e;return p({...r,type:t})}return p(e)}function f(e,t="Human",r="AI"){const n=[];for(const s of e){let e;if("human"===s._getType())e=t;else if("ai"===s._getType())e=r;else if("system"===s._getType())e="System";else if("function"===s._getType())e="Function";else if("tool"===s._getType())e="Tool";else{if("generic"!==s._getType())throw new Error(`Got unsupported message type: ${s._getType()}`);e=s.role}const a=s.name?`${s.name}, `:"",i="string"==typeof s.content?s.content:JSON.stringify(s.content,null,2);n.push(`${e}: ${a}${i}`)}return n.join("\n")}function g(e){const t=function(e){if(void 0!==e.data)return e;{const t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}(e);switch(t.type){case"human":return new l.xc(t.data);case"ai":return new a.Od(t.data);case"system":return new u.tn(t.data);case"function":if(void 0===t.data.name)throw new Error("Name must be defined for function messages");return new c.mg(t.data);case"tool":if(void 0===t.data.tool_call_id)throw new Error("Tool call ID must be defined for tool messages");return new d.uf(t.data);case"generic":if(void 0===t.data.role)throw new Error("Role must be defined for chat messages");return new o.cM(t.data);default:throw new Error(`Got unexpected type: ${t.type}`)}}function y(e){return e.map(g)}function b(e){return e.map((e=>e.toDict()))}function w(e){const t=e._getType();if("human"===t)return new l.a7({...e});if("ai"===t){let t={...e};return"tool_calls"in t&&(t={...t,tool_call_chunks:t.tool_calls?.map((e=>({...e,type:"tool_call_chunk",index:void 0,args:JSON.stringify(e.args)})))}),new a.H({...t})}if("system"===t)return new u.uU({...e});if("function"===t)return new c.FK({...e});if(o.cM.isInstance(e))return new o.XU({...e});throw new Error("Unknown message type.")}},6585:e=>{var t=1e3,r=60*t,n=60*r,s=24*n,a=7*s,i=365.25*s;function o(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}e.exports=function(e,c){c=c||{};var l=typeof e;if("string"===l&&e.length>0)return function(e){if((e=String(e)).length>100)return;var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!o)return;var c=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*i;case"weeks":case"week":case"w":return c*a;case"days":case"day":case"d":return c*s;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*r;case"seconds":case"second":case"secs":case"sec":case"s":return c*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(e);if("number"===l&&isFinite(e))return c.long?function(e){var a=Math.abs(e);if(a>=s)return o(e,a,s,"day");if(a>=n)return o(e,a,n,"hour");if(a>=r)return o(e,a,r,"minute");if(a>=t)return o(e,a,t,"second");return e+" ms"}(e):function(e){var a=Math.abs(e);if(a>=s)return Math.round(e/s)+"d";if(a>=n)return Math.round(e/n)+"h";if(a>=r)return Math.round(e/r)+"m";if(a>=t)return Math.round(e/t)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},6641:(e,t,r)=>{"use strict";const n=r(4617);class s extends Error{constructor(e){super(e),this.name="TimeoutError"}}const a=(e,t,r)=>new Promise(((a,i)=>{if("number"!=typeof t||t<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(t===1/0)return void a(e);const o=setTimeout((()=>{if("function"==typeof r){try{a(r())}catch(e){i(e)}return}const n=r instanceof Error?r:new s("string"==typeof r?r:`Promise timed out after ${t} milliseconds`);"function"==typeof e.cancel&&e.cancel(),i(n)}),t);n(e.then(a,i),(()=>{clearTimeout(o)}))}));e.exports=a,e.exports.default=a,e.exports.TimeoutError=s},6780:(e,t,r)=>{"use strict";const n=r(8311);e.exports=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r))},6874:e=>{"use strict";const t=Number.MAX_SAFE_INTEGER||9007199254740991;e.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:t,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}},6906:(e,t,r)=>{"use strict";r.r(t),r.d(t,{ConsoleCallbackHandler:()=>u});var n=r(9418),s=r(1590);function a(e,t){return`${e.open}${t}${e.close}`}function i(e,t){try{return JSON.stringify(e,null,2)}catch(e){return t}}function o(e){return"string"==typeof e?e.trim():null==e?e:i(e,e.toString())}function c(e){if(!e.end_time)return"";const t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}const{color:l}=n;class u extends s.BaseTracer{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 e=this.runMap.get(r.parent_run_id);if(!e)break;t.push(e),r=e}return t}getBreadcrumbs(e){const t=[...this.getParents(e).reverse(),e].map(((e,t,r)=>{const s=`${e.execution_order}:${e.run_type}:${e.name}`;return t===r.length-1?a(n.bold,s):s})).join(" > ");return a(l.grey,t)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.green,"[chain/start]")} [${t}] Entering Chain run with input: ${i(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.cyan,"[chain/end]")} [${t}] [${c(e)}] Exiting Chain run with output: ${i(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.red,"[chain/error]")} [${t}] [${c(e)}] Chain run errored with error: ${i(e.error,"[error]")}`)}onLLMStart(e){const t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map((e=>e.trim()))}:e.inputs;console.log(`${a(l.green,"[llm/start]")} [${t}] Entering LLM run with input: ${i(r,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.cyan,"[llm/end]")} [${t}] [${c(e)}] Exiting LLM run with output: ${i(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.red,"[llm/error]")} [${t}] [${c(e)}] LLM run errored with error: ${i(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.green,"[tool/start]")} [${t}] Entering Tool run with input: "${o(e.inputs.input)}"`)}onToolEnd(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.cyan,"[tool/end]")} [${t}] [${c(e)}] Exiting Tool run with output: "${o(e.outputs?.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.red,"[tool/error]")} [${t}] [${c(e)}] Tool run errored with error: ${i(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${i(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.cyan,"[retriever/end]")} [${t}] [${c(e)}] Exiting Retriever run with output: ${i(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${a(l.red,"[retriever/error]")} [${t}] [${c(e)}] Retriever run errored with error: ${i(e.error,"[error]")}`)}onAgentAction(e){const t=e,r=this.getBreadcrumbs(e);console.log(`${a(l.blue,"[agent/action]")} [${r}] Agent selected action: ${i(t.actions[t.actions.length-1],"[action]")}`)}}},6953:(e,t,r)=>{"use strict";const n=r(144);e.exports=(e,t)=>{const r=n(e,t);return r?r.version:null}},6968:(e,t,r)=>{"use strict";r.d(t,{X0:()=>i,hr:()=>s,pH:()=>a});const n=Symbol.for("ls:tracing_async_local_storage"),s=Symbol.for("lc:context_variables"),a=e=>{globalThis[n]=e},i=()=>globalThis[n]},6993:(e,t,r)=>{"use strict";r.d(t,{m:()=>s});var n=r(3313);class s extends n.YN{get lc_attributes(){return{partialVariables:void 0}}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","prompts",this._getPromptType()]}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"partialVariables",{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,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const{inputVariables:t}=e;if(t.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}async mergePartialAndUserVariables(e){const t=this.partialVariables??{},r={};for(const[e,n]of Object.entries(t))r[e]="string"==typeof n?n:await n();return{...r,...e}}async invoke(e,t){const r={...this.metadata,...t?.metadata},n=[...this.tags??[],...t?.tags??[]];return this._callWithConfig((e=>this.formatPromptValue(e)),e,{...t,tags:n,metadata:r,runType:"prompt"})}serialize(){throw new Error("Use .toJSON() instead")}static async deserialize(e){switch(e._type){case"prompt":{const{PromptTemplate:t}=await Promise.resolve().then(r.bind(r,3650));return t.deserialize(e)}case void 0:{const{PromptTemplate:t}=await Promise.resolve().then(r.bind(r,3650));return t.deserialize({...e,_type:"prompt"})}case"few_shot":{const{FewShotPromptTemplate:t}=await Promise.resolve().then(r.bind(r,2771));return t.deserialize(e)}default:throw new Error(`Invalid prompt type in config: ${e._type}`)}}}},7059:(e,t,r)=>{"use strict";const n=r(560);e.exports=(e,t,r)=>n(e,t,r)<0},7075:(e,t,r)=>{"use strict";const n=r(3908),s=r(3904),{ANY:a}=s,i=r(8311),o=r(7638),c=r(5580),l=r(7059),u=r(5200),d=r(4089);e.exports=(e,t,r,h)=>{let p,m,f,g,y;switch(e=new n(e,h),t=new i(t,h),r){case">":p=c,m=u,f=l,g=">",y=">=";break;case"<":p=l,m=d,f=c,g="<",y="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(o(e,t,h))return!1;for(let r=0;r{e.semver===a&&(e=new s(">=0.0.0")),i=i||e,o=o||e,p(e.semver,i.semver,h)?i=e:f(e.semver,o.semver,h)&&(o=e)})),i.operator===g||i.operator===y)return!1;if((!o.operator||o.operator===g)&&m(e,o.semver))return!1;if(o.operator===y&&f(e,o.semver))return!1}return!0}},7272:e=>{"use strict";const t="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};e.exports=t},7380:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Serializable:()=>o,get_lc_unique_name:()=>i});var n=r(7492);function s(e){return Array.isArray(e)?[...e]:{...e}}function a(e,t){const r=s(e);for(const[e,n]of Object.entries(t)){const[t,...a]=e.split(".").reverse();let i=r;for(const e of a.reverse()){if(void 0===i[e])break;i[e]=s(i[e]),i=i[e]}void 0!==i[t]&&(i[t]={lc:1,type:"secret",id:[n]})}return r}function i(e){const t=Object.getPrototypeOf(e);return"function"==typeof e.lc_name&&("function"!=typeof t.lc_name||e.lc_name()!==t.lc_name())?e.lc_name():e.name}class o{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,i(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}),void 0!==this.lc_serializable_keys?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter((([e])=>this.lc_serializable_keys?.includes(e)))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof o||"object"!=typeof this.lc_kwargs||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},t={},r=Object.keys(this.lc_kwargs).reduce(((e,t)=>(e[t]=t in this?this[t]:this.lc_kwargs[t],e)),{});for(let n=Object.getPrototypeOf(this);n;n=Object.getPrototypeOf(n))Object.assign(e,Reflect.get(n,"lc_aliases",this)),Object.assign(t,Reflect.get(n,"lc_secrets",this)),Object.assign(r,Reflect.get(n,"lc_attributes",this));return Object.keys(t).forEach((e=>{let t=this,n=r;const[s,...a]=e.split(".").reverse();for(const e of a.reverse()){if(!(e in t)||void 0===t[e])return;e in n&&void 0!==n[e]||("object"==typeof t[e]&&null!=t[e]?n[e]={}:Array.isArray(t[e])&&(n[e]=[])),t=t[e],n=n[e]}s in t&&void 0!==t[s]&&(n[s]=n[s]||t[s])})),{lc:1,type:"constructor",id:this.lc_id,kwargs:(0,n.d4)(Object.keys(t).length?a(r,t):r,n.$o,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}},7414:(e,t,r)=>{"use strict";const n=r(144);e.exports=(e,t)=>{const r=n(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null}},7492:(e,t,r)=>{"use strict";r.d(t,{$o:()=>a,O3:()=>i,d4:()=>o});var n=r(9478),s=r(2729);function a(e,t){return t?.[e]||n(e)}function i(e,t){return t?.[e]||s(e)}function o(e,t,r){const n={};for(const s in e)Object.hasOwn(e,s)&&(n[t(s,r)]=e[s]);return n}},7526:(e,t)=>{"use strict";t.byteLength=function(e){var t=o(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,a=o(e),i=a[0],c=a[1],l=new s(function(e,t,r){return 3*(t+r)/4-r}(0,i,c)),u=0,d=c>0?i-4:i;for(r=0;r>16&255,l[u++]=t>>8&255,l[u++]=255&t;2===c&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,l[u++]=255&t);1===c&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,l[u++]=t>>8&255,l[u++]=255&t);return l},t.fromByteArray=function(e){for(var t,n=e.length,s=n%3,a=[],i=16383,o=0,l=n-s;ol?l:o+i));1===s?(t=e[n-1],a.push(r[t>>2]+r[t<<4&63]+"==")):2===s&&(t=(e[n-2]<<8)+e[n-1],a.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return a.join("")};for(var r=[],n=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)r[i]=a[i],n[a.charCodeAt(i)]=i;function o(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function c(e,t,n){for(var s,a,i=[],o=t;o>18&63]+r[a>>12&63]+r[a>>6&63]+r[63&a]);return i.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},7631:(e,t,r)=>{"use strict";const n=r(8311);e.exports=(e,t)=>new n(e,t).set.map((e=>e.map((e=>e.value)).join(" ").trim().split(" ")))},7638:(e,t,r)=>{"use strict";const n=r(8311);e.exports=(e,t,r)=>{try{t=new n(t,r)}catch(e){return!1}return t.test(e)}},7765:(e,t,r)=>{"use strict";r.d(t,{H:()=>l,KX:()=>o,Od:()=>i,jm:()=>c});var n=r(780),s=r(3490),a=r(8009);class i extends s.XQ{get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e,t){let r;if("string"==typeof e)r={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:t??{}};else{r=e;const t=r.additional_kwargs?.tool_calls,n=r.tool_calls;null!=t&&t.length>0&&(void 0===n||0===n.length)&&console.warn(["New LangChain packages are available that more efficiently handle","tool calling.\n\nPlease upgrade your packages to versions that set","message tool calls. e.g., `yarn add @langchain/anthropic`,","yarn add @langchain/openai`, etc."].join(" "));try{if(null!=t&&void 0===n){const[e,n]=(0,a.p1)(t);r.tool_calls=e??[],r.invalid_tool_calls=n??[]}else r.tool_calls=r.tool_calls??[],r.invalid_tool_calls=r.invalid_tool_calls??[]}catch(e){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}),"string"!=typeof r&&(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 o(e){return"ai"===e._getType()}function c(e){return"ai"===e._getType()}class l extends s.gj{constructor(e){let t;if("string"==typeof e)t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(void 0===e.tool_call_chunks)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0};else{const r=[],s=[];for(const t of e.tool_call_chunks){let e={};try{if(e=(0,n.d)(t.args||"{}"),null===e||"object"!=typeof e||Array.isArray(e))throw new Error("Malformed tool call chunk args.");r.push({name:t.name??"",args:e,id:t.id,type:"tool_call"})}catch(e){s.push({name:t.name,args:t.args,id:t.id,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:r,invalid_tool_calls:s,usage_metadata:void 0!==e.usage_metadata?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){const t={content:(0,s._I)(this.content,e.content),additional_kwargs:(0,s.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,s.ns)(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(void 0!==this.tool_call_chunks||void 0!==e.tool_call_chunks){const r=(0,s.Vt)(this.tool_call_chunks,e.tool_call_chunks);void 0!==r&&r.length>0&&(t.tool_call_chunks=r)}if(void 0!==this.usage_metadata||void 0!==e.usage_metadata){const r={...(void 0!==this.usage_metadata?.input_token_details?.audio||void 0!==e.usage_metadata?.input_token_details?.audio)&&{audio:(this.usage_metadata?.input_token_details?.audio??0)+(e.usage_metadata?.input_token_details?.audio??0)},...(void 0!==this.usage_metadata?.input_token_details?.cache_read||void 0!==e.usage_metadata?.input_token_details?.cache_read)&&{cache_read:(this.usage_metadata?.input_token_details?.cache_read??0)+(e.usage_metadata?.input_token_details?.cache_read??0)},...(void 0!==this.usage_metadata?.input_token_details?.cache_creation||void 0!==e.usage_metadata?.input_token_details?.cache_creation)&&{cache_creation:(this.usage_metadata?.input_token_details?.cache_creation??0)+(e.usage_metadata?.input_token_details?.cache_creation??0)}},n={...(void 0!==this.usage_metadata?.output_token_details?.audio||void 0!==e.usage_metadata?.output_token_details?.audio)&&{audio:(this.usage_metadata?.output_token_details?.audio??0)+(e.usage_metadata?.output_token_details?.audio??0)},...(void 0!==this.usage_metadata?.output_token_details?.reasoning||void 0!==e.usage_metadata?.output_token_details?.reasoning)&&{reasoning:(this.usage_metadata?.output_token_details?.reasoning??0)+(e.usage_metadata?.output_token_details?.reasoning??0)}},s=this.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},a=e.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},i={input_tokens:s.input_tokens+a.input_tokens,output_tokens:s.output_tokens+a.output_tokens,total_tokens:s.total_tokens+a.total_tokens,...Object.keys(r).length>0&&{input_token_details:r},...Object.keys(n).length>0&&{output_token_details:n}};t.usage_metadata=i}return new l(t)}}},7833:(e,t,r)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),t.splice(s,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(736)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},7974:(e,t,r)=>{"use strict";r.d(t,{UF:()=>o,X4:()=>i,tn:()=>s,uU:()=>a});var n=r(3490);class s extends n.XQ{static lc_name(){return"SystemMessage"}_getType(){return"system"}constructor(e,t){super(e,t)}}class a extends n.gj{static lc_name(){return"SystemMessageChunk"}_getType(){return"system"}constructor(e,t){super(e,t)}concat(e){return new a({content:(0,n._I)(this.content,e.content),additional_kwargs:(0,n.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,n.ns)(this.response_metadata,e.response_metadata),id:this.id??e.id})}}function i(e){return"system"===e._getType()}function o(e){return"system"===e._getType()}},8009:(e,t,r)=>{"use strict";r.d(t,{P:()=>l,dr:()=>i,fK:()=>s,p1:()=>o,uf:()=>a,wk:()=>c});var n=r(3490);function s(e){return null!=e&&"object"==typeof e&&"lc_direct_tool_output"in e&&!0===e.lc_direct_tool_output}class a extends n.XQ{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(e,t,r){"string"==typeof e&&(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,"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}_getType(){return"tool"}static isInstance(e){return"tool"===e._getType()}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}class i extends n.gj{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 i({content:(0,n._I)(this.content,e.content),additional_kwargs:(0,n.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,n.ns)(this.response_metadata,e.response_metadata),artifact:(0,n.F7)(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:(0,n.Iv)(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}function o(e){const t=[],r=[];for(const n of e)if(n.function){const e=n.function.name;try{const r={name:e||"",args:JSON.parse(n.function.arguments)||{},id:n.id};t.push(r)}catch(t){r.push({name:e,args:n.function.arguments,id:n.id,error:"Malformed args."})}}return[t,r]}function c(e){return"tool"===e._getType()}function l(e){return"tool"===e._getType()}},8028:(e,t,r)=>{"use strict";r.r(t),r.d(t,{ChatGenerationChunk:()=>a,GenerationChunk:()=>s,RUN_KEY:()=>n});const n="__run";class s{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 s({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}}class a extends s{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 a({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo},message:this.message.concat(e.message)})}}},8303:(e,t,r)=>{var n=r(3961);t.operation=function(e){var r=t.timeouts(e);return new n(r,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})},t.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],s=0;s{"use strict";const n=/\s+/g;class s{constructor(e,t){if(t=i(t),e instanceof s)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new s(e.raw,t);if(e instanceof o)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(n," "),this.set=this.raw.split("||").map((e=>this.parseRange(e.trim()))).filter((e=>e.length)),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const e=this.set[0];if(this.set=this.set.filter((e=>!y(e[0]))),0===this.set.length)this.set=[e];else if(this.set.length>1)for(const e of this.set)if(1===e.length&&b(e[0])){this.set=[e];break}}this.formatted=void 0}get range(){if(void 0===this.formatted){this.formatted="";for(let e=0;e0&&(this.formatted+="||");const t=this.set[e];for(let e=0;e0&&(this.formatted+=" "),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){const t=((this.options.includePrerelease&&f)|(this.options.loose&&g))+":"+e,r=a.get(t);if(r)return r;const n=this.options.loose,s=n?u[d.HYPHENRANGELOOSE]:u[d.HYPHENRANGE];e=e.replace(s,A(this.options.includePrerelease)),c("hyphen replace",e),e=e.replace(u[d.COMPARATORTRIM],h),c("comparator trim",e),e=e.replace(u[d.TILDETRIM],p),c("tilde trim",e),e=e.replace(u[d.CARETTRIM],m),c("caret trim",e);let i=e.split(" ").map((e=>v(e,this.options))).join(" ").split(/\s+/).map((e=>O(e,this.options)));n&&(i=i.filter((e=>(c("loose invalid filter",e,this.options),!!e.match(u[d.COMPARATORLOOSE]))))),c("range list",i);const l=new Map,b=i.map((e=>new o(e,this.options)));for(const e of b){if(y(e))return[e];l.set(e.value,e)}l.size>1&&l.has("")&&l.delete("");const w=[...l.values()];return a.set(t,w),w}intersects(e,t){if(!(e instanceof s))throw new TypeError("a Range is required");return this.set.some((r=>w(r,t)&&e.set.some((e=>w(e,t)&&r.every((r=>e.every((e=>r.intersects(e,t)))))))))}test(e){if(!e)return!1;if("string"==typeof e)try{e=new l(e,this.options)}catch(e){return!1}for(let t=0;t"<0.0.0-0"===e.value,b=e=>""===e.value,w=(e,t)=>{let r=!0;const n=e.slice();let s=n.pop();for(;r&&n.length;)r=n.every((e=>s.intersects(e,t))),s=n.pop();return r},v=(e,t)=>(c("comp",e,t),e=E(e,t),c("caret",e),e=k(e,t),c("tildes",e),e=T(e,t),c("xrange",e),e=P(e,t),c("stars",e),e),_=e=>!e||"x"===e.toLowerCase()||"*"===e,k=(e,t)=>e.trim().split(/\s+/).map((e=>S(e,t))).join(" "),S=(e,t)=>{const r=t.loose?u[d.TILDELOOSE]:u[d.TILDE];return e.replace(r,((t,r,n,s,a)=>{let i;return c("tilde",e,t,r,n,s,a),_(r)?i="":_(n)?i=`>=${r}.0.0 <${+r+1}.0.0-0`:_(s)?i=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`:a?(c("replaceTilde pr",a),i=`>=${r}.${n}.${s}-${a} <${r}.${+n+1}.0-0`):i=`>=${r}.${n}.${s} <${r}.${+n+1}.0-0`,c("tilde return",i),i}))},E=(e,t)=>e.trim().split(/\s+/).map((e=>x(e,t))).join(" "),x=(e,t)=>{c("caret",e,t);const r=t.loose?u[d.CARETLOOSE]:u[d.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,((t,r,s,a,i)=>{let o;return c("caret",e,t,r,s,a,i),_(r)?o="":_(s)?o=`>=${r}.0.0${n} <${+r+1}.0.0-0`:_(a)?o="0"===r?`>=${r}.${s}.0${n} <${r}.${+s+1}.0-0`:`>=${r}.${s}.0${n} <${+r+1}.0.0-0`:i?(c("replaceCaret pr",i),o="0"===r?"0"===s?`>=${r}.${s}.${a}-${i} <${r}.${s}.${+a+1}-0`:`>=${r}.${s}.${a}-${i} <${r}.${+s+1}.0-0`:`>=${r}.${s}.${a}-${i} <${+r+1}.0.0-0`):(c("no pr"),o="0"===r?"0"===s?`>=${r}.${s}.${a}${n} <${r}.${s}.${+a+1}-0`:`>=${r}.${s}.${a}${n} <${r}.${+s+1}.0-0`:`>=${r}.${s}.${a} <${+r+1}.0.0-0`),c("caret return",o),o}))},T=(e,t)=>(c("replaceXRanges",e,t),e.split(/\s+/).map((e=>C(e,t))).join(" ")),C=(e,t)=>{e=e.trim();const r=t.loose?u[d.XRANGELOOSE]:u[d.XRANGE];return e.replace(r,((r,n,s,a,i,o)=>{c("xRange",e,r,n,s,a,i,o);const l=_(s),u=l||_(a),d=u||_(i),h=d;return"="===n&&h&&(n=""),o=t.includePrerelease?"-0":"",l?r=">"===n||"<"===n?"<0.0.0-0":"*":n&&h?(u&&(a=0),i=0,">"===n?(n=">=",u?(s=+s+1,a=0,i=0):(a=+a+1,i=0)):"<="===n&&(n="<",u?s=+s+1:a=+a+1),"<"===n&&(o="-0"),r=`${n+s}.${a}.${i}${o}`):u?r=`>=${s}.0.0${o} <${+s+1}.0.0-0`:d&&(r=`>=${s}.${a}.0${o} <${s}.${+a+1}.0-0`),c("xRange return",r),r}))},P=(e,t)=>(c("replaceStars",e,t),e.trim().replace(u[d.STAR],"")),O=(e,t)=>(c("replaceGTE0",e,t),e.trim().replace(u[t.includePrerelease?d.GTE0PRE:d.GTE0],"")),A=e=>(t,r,n,s,a,i,o,c,l,u,d,h)=>`${r=_(n)?"":_(s)?`>=${n}.0.0${e?"-0":""}`:_(a)?`>=${n}.${s}.0${e?"-0":""}`:i?`>=${r}`:`>=${r}${e?"-0":""}`} ${c=_(l)?"":_(u)?`<${+l+1}.0.0-0`:_(d)?`<${l}.${+u+1}.0-0`:h?`<=${l}.${u}.${d}-${h}`:e?`<${l}.${u}.${+d+1}-0`:`<=${c}`}`.trim(),I=(e,t,r)=>{for(let r=0;r0){const n=e[r].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch)return!0}return!1}return!0}},8587:e=>{"use strict";const t=Object.freeze({loose:!0}),r=Object.freeze({});e.exports=e=>e?"object"!=typeof e?t:e:r},8675:(e,t,r)=>{"use strict";r.d(t,{AP:()=>i,FK:()=>a,mg:()=>s,vl:()=>o});var n=r(3490);class s extends n.XQ{static lc_name(){return"FunctionMessage"}constructor(e,t){"string"==typeof e&&(e={content:e,name:t}),super(e)}_getType(){return"function"}}class a extends n.gj{static lc_name(){return"FunctionMessageChunk"}_getType(){return"function"}concat(e){return new a({content:(0,n._I)(this.content,e.content),additional_kwargs:(0,n.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,n.ns)(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}}function i(e){return"function"===e._getType()}function o(e){return"function"===e._getType()}},8794:e=>{"use strict";e.exports=class{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);return void 0===t?void 0:(this.map.delete(e),this.map.set(e,t),t)}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&void 0!==t){if(this.map.size>=this.max){const e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}},9056:(e,t,r)=>{"use strict";r.d(t,{Kj:()=>L});var n=r(5230),s=r(4116),a=r(3290),i=r(747);const o=[400,401,403,404,405,406,407,408],c=[409];class l{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}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.debug=e.debug,this.queue=new a.default({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){const r=this.onFailedResponseHook;return this.queue.add((()=>s((()=>e(...t).catch((e=>{throw e instanceof Error?e:new Error(e)}))),{async onFailedAttempt(e){if(e.message.startsWith("Cancel")||e.message.startsWith("TimeoutError")||e.message.startsWith("AbortError"))throw e;if("ECONNABORTED"===e?.code)throw e;const t=e?.response,n=t?.status;if(n){if(o.includes(+n))throw e;if(c.includes(+n))return;r&&await r(t)}},retries:this.maxRetries,randomize:!0})),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise(((t,r)=>{e.signal?.addEventListener("abort",(()=>{r(new Error("AbortError"))}))}))]):this.call(t,...r)}fetch(...e){return this.call((()=>(0,i.Yx)(this.debug)(...e).then((e=>e.ok?e:Promise.reject(e)))))}}function u(e){return"function"==typeof e?._getType}function d(e){const t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}var h=r(4785),p=r(4547);const m=/^(?:[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;const f=function(e){return"string"==typeof e&&m.test(e)};function g(e,t){if(!f(e)){throw new Error(void 0!==t?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`)}return e}var y=r(6232);r(9589);function b(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw new Error(`Invalid identifier format: ${e}`);const[t,r]=e.split(":"),n=r||"latest";if(t.includes("/")){const[r,s]=t.split("/",2);if(!r||!s)throw new Error(`Invalid identifier format: ${e}`);return[r,s,n]}if(!t)throw new Error(`Invalid identifier format: ${e}`);return["-",t,n]}class w 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 v(e,t,r){let n;if(e.ok)return void(r&&(n=await e.text()));n=await e.text();const s=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Server response: ${n}`;if(409===e.status)throw new w(s);const a=new Error(s);throw a.status=e.status,a}var _="[...]",k={result:"[Circular]"},S=[],E=[];const x=new TextEncoder;function T(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function C(e){return x.encode(e)}function P(e,t,r,n,s){try{return C(JSON.stringify(e,r,n))}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn("[WARNING]: LangSmith received unserializable value."+(t?`\nContext: ${t}`:"")),C("[Unserializable]");let i;console.warn("[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. "+(t?`\nContext: ${t}`:"")),void 0===s&&(s=T()),A(e,"",0,[],void 0,0,s);try{i=0===E.length?JSON.stringify(e,r,n):JSON.stringify(e,I(r),n)}catch(e){return C("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==S.length;){const e=S.pop();4===e.length?Object.defineProperty(e[0],e[1],e[3]):e[0][e[1]]=e[2]}}return C(i)}}function O(e,t,r,n){var s=Object.getOwnPropertyDescriptor(n,r);void 0!==s.get?s.configurable?(Object.defineProperty(n,r,{value:e}),S.push([n,r,t,s])):E.push([t,r,e]):(n[r]=e,S.push([n,r,t]))}function A(e,t,r,n,s,a,i){var o;if(a+=1,"object"==typeof e&&null!==e){for(o=0;oi.depthLimit)return void O(_,e,t,s);if(void 0!==i.edgesLimit&&r+1>i.edgesLimit)return void O(_,e,t,s);if(n.push(e),Array.isArray(e))for(o=0;o0)for(var n=0;n{if(429===e?.status){const t=1e3*parseInt(e.headers.get("retry-after")??"30",10);if(t>0)return await new Promise((e=>setTimeout(e,t))),!0}return!1};function N(e){return"number"==typeof e?Number(e.toFixed(4)):e}class ${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((e=>{t=e})),n=P(e.item,`Serializing run with id: ${e.item.id}`).length;return this.items.push({action:e.action,payload:e.item,itemPromiseResolve:t,itemPromise:r,size:n}),this.sizeBytes+=n,r}pop(e){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const t=[];let r=0;for(;r+(this.peek()?.size??0)0;){const e=this.items.shift();e&&(t.push(e),r+=e.size,this.sizeBytes-=e.size)}if(0===t.length&&this.items.length>0){const e=this.items.shift();t.push(e),r+=e.size,this.sizeBytes-=e.size}return[t.map((e=>({action:e.action,item:e.payload}))),()=>t.forEach((e=>e.itemPromiseResolve()))]}}class L{constructor(e={}){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,"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 $}),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,"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:"false"===(0,h.Az)("LANGSMITH_TRACING_BACKGROUND")}),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,"debug",{enumerable:!0,configurable:!0,writable:!0,value:"true"===(0,h.Az)("LANGSMITH_DEBUG")});const t=L.getDefaultClientConfig();if(this.tracingSampleRate=(e=>{const t=e?.toString()??(0,h.Jz)("TRACING_SAMPLING_RATE");if(void 0===t)return;const r=parseFloat(t);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r})(e.tracingSamplingRate),this.apiUrl=R(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=R(e.apiKey??t.apiKey),this.webUrl=R(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.timeout_ms=e.timeout_ms??9e4,this.caller=new l({...e.callerOptions??{},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.batchIngestCaller=new l({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:j,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.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode}static getDefaultClientConfig(){const e=(0,h.Jz)("API_KEY");return{apiUrl:(0,h.Jz)("ENDPOINT")??"https://api.smith.langchain.com",apiKey:e,webUrl:void 0,hideInputs:"true"===(0,h.Jz)("HIDE_INPUTS"),hideOutputs:"true"===(0,h.Jz)("HIDE_OUTPUTS")}}getHostUrl(){return this.webUrl?this.webUrl:(e=>{const t=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return"localhost"===t||"127.0.0.1"===t||"::1"===t})(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/${p.Ls}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),e}async processInputs(e){return!1===this.hideInputs?e:!0===this.hideInputs?{}:"function"==typeof this.hideInputs?this.hideInputs(e):e}async processOutputs(e){return!1===this.hideOutputs?e:!0===this.hideOutputs?{}:"function"==typeof this.hideOutputs?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){const t={...e};return void 0!==t.inputs&&(t.inputs=await this.processInputs(t.inputs)),void 0!==t.outputs&&(t.outputs=await this.processOutputs(t.outputs)),t}async _getResponse(e,t){const r=t?.toString()??"",n=`${this.apiUrl}${e}?${r}`,s=await this.caller.call((0,i.Yx)(this.debug),n,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v(s,`Failed to fetch ${e}`),s}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,r){let n=Number(t.get("offset"))||0;const s=Number(t.get("limit"))||100;for(;;){t.set("offset",String(n)),t.set("limit",String(s));const a=`${this.apiUrl}${e}?${t}`,o=await this.caller.call((0,i.Yx)(this.debug),a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(o,`Failed to fetch ${e}`);const c=r?r(await o.json()):await o.json();if(0===c.length)break;if(yield c,c.length0;){const[r,n]=this.autoBatchQueue.pop(e);if(!r.length){n();break}const s=this._processBatch(r,n).catch(console.error);t.push(s)}return Promise.all(t)}async _processBatch(e,t){if(e.length)try{const t={runCreates:e.filter((e=>"create"===e.action)).map((e=>e.item)),runUpdates:e.filter((e=>"update"===e.action)).map((e=>e.item))},r=await this._ensureServerInfo();r?.batch_ingest_config?.use_multipart_endpoint?await this.multipartIngestRuns(t):await this.batchIngestRuns(t)}finally{t()}else t()}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,"create"===e.action&&(e.item=M(e.item));const t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;const r=await this._getBatchSizeLimitBytes();return this.autoBatchQueue.sizeBytes>r&&this.drainAutoBatchQueue(r),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout((()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue(r)}),this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){const e=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(2500),...this.fetchOptions});await v(e,"get server info");const t=await e.json();return this.debug&&console.log("\n=== LangSmith Server Configuration ===\n"+JSON.stringify(t,null,2)+"\n"),t}async _ensureServerInfo(){return void 0===this._getServerInfoPromise&&(this._getServerInfoPromise=(async()=>{if(void 0===this._serverInfo)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[WARNING]: LangSmith failed to fetch info on supported operations with status code ${e.status}. Falling back to batch operations and default limits.`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then((e=>(void 0===this._serverInfo&&(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();await this.drainAutoBatchQueue(e)}async createRun(e){if(!this._filterForSampling([e]).length)return;const t={...this.headers,"Content-Type":"application/json"},r=e.project_name;delete e.project_name;const n=await this.prepareRunCreateOrUpdateInputs({session_name:r,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&void 0!==n.trace_id&&void 0!==n.dotted_order)return void this.processRunOperation({action:"create",item:n}).catch(console.error);const s=M(n),a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/runs`,{method:"POST",headers:t,body:P(s,`Creating run with id: ${s.id}`),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(a,"create run",!0)}async batchIngestRuns({runCreates:e,runUpdates:t}){if(void 0===e&&void 0===t)return;let r=await Promise.all(e?.map((e=>this.prepareRunCreateOrUpdateInputs(e)))??[]),n=await Promise.all(t?.map((e=>this.prepareRunCreateOrUpdateInputs(e)))??[]);if(r.length>0&&n.length>0){const e=r.reduce(((e,t)=>t.id?(e[t.id]=t,e):e),{}),t=[];for(const r of n)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);r=Object.values(e),n=t}const s={post:r,patch:n};if(!s.post.length&&!s.patch.length)return;const a={post:[],patch:[]};for(const e of["post","patch"]){const t=e,r=s[t].reverse();let n=r.pop();for(;void 0!==n;)a[t].push(n),n=r.pop()}if(a.post.length>0||a.patch.length>0){const e=a.post.map((e=>e.id)).concat(a.patch.map((e=>e.id))).join(",");await this._postBatchIngestRuns(P(a,`Ingesting runs with ids: ${e}`))}}async _postBatchIngestRuns(e){const t={...this.headers,"Content-Type":"application/json",Accept:"application/json"},r=await this.batchIngestCaller.call((0,i.Yx)(this.debug),`${this.apiUrl}/runs/batch`,{method:"POST",headers:t,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(r,"batch create run",!0)}async multipartIngestRuns({runCreates:e,runUpdates:t}){if(void 0===e&&void 0===t)return;const r={};let n=[];for(const t of e??[]){const e=await this.prepareRunCreateOrUpdateInputs(t);void 0!==e.id&&void 0!==e.attachments&&(r[e.id]=e.attachments),delete e.attachments,n.push(e)}let s=[];for(const e of t??[])s.push(await this.prepareRunCreateOrUpdateInputs(e));if(void 0!==n.find((e=>void 0===e.trace_id||void 0===e.dotted_order)))throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(void 0!==s.find((e=>void 0===e.trace_id||void 0===e.dotted_order)))throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(n.length>0&&s.length>0){const e=n.reduce(((e,t)=>t.id?(e[t.id]=t,e):e),{}),t=[];for(const r of s)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);n=Object.values(e),s=t}if(0===n.length&&0===s.length)return;const a=[],i=[];for(const[e,t]of[["post",n],["patch",s]])for(const n of t){const{inputs:t,outputs:s,events:o,attachments:c,...l}=n,u={inputs:t,outputs:s,events:o},d=P(l,`Serializing for multipart ingestion of run with id: ${l.id}`);i.push({name:`${e}.${l.id}`,payload:new Blob([d],{type:`application/json; length=${d.length}`})});for(const[t,r]of Object.entries(u)){if(void 0===r)continue;const n=P(r,`Serializing ${t} for multipart ingestion of run with id: ${l.id}`);i.push({name:`${e}.${l.id}.${t}`,payload:new Blob([n],{type:`application/json; length=${n.length}`})})}if(void 0!==l.id){const e=r[l.id];if(e){delete r[l.id];for(const[t,r]of Object.entries(e)){let e,n;Array.isArray(r)?[e,n]=r:(e=r.mimeType,n=r.data),t.includes(".")?console.warn(`Skipping attachment '${t}' for run ${l.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`):i.push({name:`attachment.${l.id}.${t}`,payload:new Blob([n],{type:`${e}; length=${n.byteLength}`})})}}}a.push(`trace=${l.trace_id},id=${l.id}`)}await this._sendMultipartRequest(i,a.join("; "))}async _createNodeFetchBody(e,t){const r=[];for(const n of e)r.push(new Blob([`--${t}\r\n`])),r.push(new Blob([`Content-Disposition: form-data; name="${n.name}"\r\n`,`Content-Type: ${n.payload.type}\r\n\r\n`])),r.push(n.payload),r.push(new Blob(["\r\n"]));r.push(new Blob([`--${t}--\r\n`]));const n=new Blob(r);return await n.arrayBuffer()}async _createMultipartStream(e,t){const r=new TextEncoder;return new ReadableStream({async start(n){const s=async e=>{"string"==typeof e?n.enqueue(r.encode(e)):n.enqueue(e)};for(const r of e){await s(`--${t}\r\n`),await s(`Content-Disposition: form-data; name="${r.name}"\r\n`),await s(`Content-Type: ${r.payload.type}\r\n\r\n`);const e=r.payload.stream().getReader();try{let t;for(;!(t=await e.read()).done;)n.enqueue(t.value)}finally{e.releaseLock()}await s("\r\n")}await s(`--${t}--\r\n`),n.close()}})}async _sendMultipartRequest(e,t){try{const t="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),r=await((0,i.rO)()?this._createNodeFetchBody(e,t):this._createMultipartStream(e,t)),n=await this.batchIngestCaller.call((0,i.Yx)(this.debug),`${this.apiUrl}/runs/multipart`,{method:"POST",headers:{...this.headers,"Content-Type":`multipart/form-data; boundary=${t}`},body:r,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(n,"ingest multipart runs",!0)}catch(e){console.warn(`${e.message.trim()}\n\nContext: ${t}`)}}async updateRun(e,t){g(e),t.inputs&&(t.inputs=await this.processInputs(t.inputs)),t.outputs&&(t.outputs=await this.processOutputs(t.outputs));const r={...t,id:e};if(!this._filterForSampling([r],!0).length)return;if(this.autoBatchTracing&&void 0!==r.trace_id&&void 0!==r.dotted_order)return void 0!==t.end_time&&void 0===r.parent_run_id&&this.blockOnRootRunFinalization&&!this.manualFlushMode?void await this.processRunOperation({action:"update",item:r}).catch(console.error):void this.processRunOperation({action:"update",item:r}).catch(console.error);const n={...this.headers,"Content-Type":"application/json"},s=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/runs/${e}`,{method:"PATCH",headers:n,body:P(t,`Serializing payload to update run with id: ${e}`),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(s,"update run",!0)}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){g(e);let r=await this._get(`/runs/${e}`);return t&&r.child_run_ids&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:t,projectOpts:r}){if(void 0!==t){let e;if(t.session_id)e=t.session_id;else if(r?.projectName)e=(await this.readProject({projectName:r?.projectName})).id;else if(r?.projectId)e=r?.projectId;else{e=(await this.readProject({projectName:(0,h.Jz)("PROJECT")||"default"})).id}const n=await this._getTenantId();return`${this.getHostUrl()}/o/${n}/projects/p/${e}/r/${t.id}?poll=true`}if(void 0!==e){const t=await this.readRun(e);if(!t.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${t.app_path}`}throw new Error("Must provide either runId or run")}async _loadChildRuns(e){const t=await async function(e){const t=[];for await(const r of e)t.push(r);return t}(this.listRuns({id:e.child_run_ids})),r={},n={};t.sort(((e,t)=>(e?.dotted_order??"").localeCompare(t?.dotted_order??"")));for(const e of t){if(null===e.parent_run_id||void 0===e.parent_run_id)throw new Error(`Child run ${e.id} has no parent`);e.parent_run_id in r||(r[e.parent_run_id]=[]),r[e.parent_run_id].push(e),n[e.id]=e}e.child_runs=r[e.id]||[];for(const t in r)t!==e.id&&(n[t].child_runs=r[t]);return e}async*listRuns(e){const{projectId:t,projectName:r,parentRunId:n,traceId:s,referenceExampleId:a,startTime:i,executionOrder:o,isRoot:c,runType:l,error:u,id:d,query:h,filter:p,traceFilter:m,treeFilter:f,limit:g,select:y,order:b}=e;let w=[];if(t&&(w=Array.isArray(t)?t:[t]),r){const e=Array.isArray(r)?r:[r],t=await Promise.all(e.map((e=>this.readProject({projectName:e}).then((e=>e.id)))));w.push(...t)}const v={session:w.length?w:null,run_type:l,reference_example:a,query:h,filter:p,trace_filter:m,tree_filter:f,execution_order:o,parent_run:n,start_time:i?i.toISOString():null,error:u,id:d,limit:g,trace:s,select:y||["app_path","child_run_ids","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"],is_root:c,order:b};let _=0;for await(const e of this._getCursorPaginatedList("/runs/query",v))if(g){if(_>=g)break;if(e.length+_>g){const t=e.slice(0,g-_);yield*t;break}_+=e.length,yield*e}else yield*e}async*listGroupRuns(e){const{projectId:t,projectName:r,groupBy:n,filter:s,startTime:a,endTime:o,limit:c,offset:l}=e,u={session_id:t||(await this.readProject({projectName:r})).id,group_by:n,filter:s,start_time:a?a.toISOString():null,end_time:o?o.toISOString():null,limit:Number(c)||100};let d=Number(l)||0;const h="/runs/group",p=`${this.apiUrl}${h}`;for(;;){const e={...u,offset:d},t=Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t))),r=await this.caller.call((0,i.Yx)(),p,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(r,`Failed to fetch ${h}`);const n=await r.json(),{groups:s,total:a}=n;if(0===s.length)break;for(const e of s)yield e;if(d+=s.length,d>=a)break}}async getRunStats({id:e,trace:t,parentRun:r,runType:n,projectNames:s,projectIds:a,referenceExampleIds:o,startTime:c,endTime:l,error:u,query:d,filter:h,traceFilter:p,treeFilter:m,isRoot:f,dataSourceType:g}){let y=a||[];s&&(y=[...a||[],...await Promise.all(s.map((e=>this.readProject({projectName:e}).then((e=>e.id)))))]);const b={id:e,trace:t,parent_run:r,run_type:n,session:y,reference_example:o,start_time:c,end_time:l,error:u,query:d,filter:h,trace_filter:p,tree_filter:m,is_root:f,data_source_type:g},w=Object.fromEntries(Object.entries(b).filter((([e,t])=>void 0!==t))),v=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(w),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v.json()}async shareRun(e,{shareId:t}={}){const r={run_id:e,share_token:t||n.A()};g(e);const s=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),a=await s.json();if(null===a||!("share_token"in a))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${a.share_token}/r`}async unshareRun(e){g(e);const t=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(t,"unshare run",!0)}async readRunSharedLink(e){g(e);const t=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await t.json();if(null!==r&&"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(void 0!==t)for(const e of t)r.append("id",e);g(e);const n=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await n.json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");if(!e){e=(await this.readDataset({datasetName:t})).id}g(e);const r=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),n=await r.json();return n.url=`${this.getHostUrl()}/public/${n.share_token}/d`,n}async shareDataset(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");if(!e){e=(await this.readDataset({datasetName:t})).id}const r={dataset_id:e};g(e);const n=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),s=await n.json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async unshareDataset(e){g(e);const t=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(t,"unshare dataset",!0)}async readSharedDataset(e){g(e);const t=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await t.json()}async listSharedExamples(e,t){const r={};t?.exampleIds&&(r.id=t.exampleIds);const n=new URLSearchParams;Object.entries(r).forEach((([e,t])=>{Array.isArray(t)?t.forEach((t=>n.append(e,t))):n.append(e,t)}));const s=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/public/${e}/examples?${n.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),a=await s.json();if(!s.ok){if("detail"in a)throw new Error(`Failed to list shared examples.\nStatus: ${s.status}\nMessage: ${Array.isArray(a.detail)?a.detail.join("\n"):"Unspecified error"}`);throw new Error(`Failed to list shared examples: ${s.status} ${s.statusText}`)}return a.map((e=>({...e,_hostUrl:this.getHostUrl()})))}async createProject({projectName:e,description:t=null,metadata:r=null,upsert:n=!1,projectExtra:s=null,referenceDatasetId:a=null}){const o=n?"?upsert=true":"",c=`${this.apiUrl}/sessions${o}`,l=s||{};r&&(l.metadata=r);const u={name:e,extra:l,description:t};null!==a&&(u.reference_dataset_id=a);const d=await this.caller.call((0,i.Yx)(this.debug),c,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(d,"create project");return await d.json()}async updateProject(e,{name:t=null,description:r=null,metadata:n=null,projectExtra:s=null,endTime:a=null}){const o=`${this.apiUrl}/sessions/${e}`;let c=s;n&&(c={...c||{},metadata:n});const l={name:t,extra:c,description:r,end_time:a?new Date(a).toISOString():null},u=await this.caller.call((0,i.Yx)(this.debug),o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(u,"update project");return await u.json()}async hasProject({projectId:e,projectName:t}){let r="/sessions";const n=new URLSearchParams;if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");if(void 0!==e)g(e),r+=`/${e}`;else{if(void 0===t)throw new Error("Must provide projectName or projectId");n.append("name",t)}const s=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}${r}?${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{const e=await s.json();return!!s.ok&&(!Array.isArray(e)||e.length>0)}catch(e){return!1}}async readProject({projectId:e,projectName:t,includeStats:r}){let n="/sessions";const s=new URLSearchParams;if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");if(void 0!==e)g(e),n+=`/${e}`;else{if(void 0===t)throw new Error("Must provide projectName or projectId");s.append("name",t)}void 0!==r&&s.append("include_stats",r.toString());const a=await this._get(n,s);let i;if(Array.isArray(a)){if(0===a.length)throw new Error(`Project[id=${e}, name=${t}] not found`);i=a[0]}else i=a;return i}async getProjectUrl({projectId:e,projectName:t}){if(void 0===e&&void 0===t)throw new Error("Must provide either projectName or projectId");const r=await this.readProject({projectId:e,projectName:t}),n=await this._getTenantId();return`${this.getHostUrl()}/o/${n}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(void 0===e&&void 0===t)throw new Error("Must provide either datasetName or datasetId");const r=await this.readDataset({datasetId:e,datasetName:t}),n=await this._getTenantId();return`${this.getHostUrl()}/o/${n}/datasets/${r.id}`}async _getTenantId(){if(null!==this._tenantId)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:n,referenceDatasetName:s,referenceFree:a,metadata:i}={}){const o=new URLSearchParams;if(void 0!==e)for(const t of e)o.append("id",t);if(void 0!==t&&o.append("name",t),void 0!==r&&o.append("name_contains",r),void 0!==n)o.append("reference_dataset",n);else if(void 0!==s){const e=await this.readDataset({datasetName:s});o.append("reference_dataset",e.id)}void 0!==a&&o.append("reference_free",a.toString()),void 0!==i&&o.append("metadata",JSON.stringify(i));for await(const e of this._getPaginated("/sessions",o))yield*e}async deleteProject({projectId:e,projectName:t}){let r;if(void 0===e&&void 0===t)throw new Error("Must provide projectName or projectId");if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");r=void 0===e?(await this.readProject({projectName:t})).id:e,g(r);const n=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(n,`delete session ${r} (${t})`,!0)}async uploadCsv({csvFile:e,fileName:t,inputKeys:r,outputKeys:n,description:s,dataType:a,name:o}){const c=`${this.apiUrl}/datasets/upload`,l=new FormData;l.append("file",e,t),r.forEach((e=>{l.append("input_keys",e)})),n.forEach((e=>{l.append("output_keys",e)})),s&&l.append("description",s),a&&l.append("data_type",a),o&&l.append("name",o);const u=await this.caller.call((0,i.Yx)(this.debug),c,{method:"POST",headers:this.headers,body:l,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(u,"upload CSV");return await u.json()}async createDataset(e,{description:t,dataType:r,inputsSchema:n,outputsSchema:s,metadata:a}={}){const o={name:e,description:t,extra:a?{metadata:a}:void 0};r&&(o.data_type=r),n&&(o.inputs_schema_definition=n),s&&(o.outputs_schema_definition=s);const c=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(c,"create dataset");return await c.json()}async readDataset({datasetId:e,datasetName:t}){let r="/datasets";const n=new URLSearchParams({limit:"1"});if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)g(e),r+=`/${e}`;else{if(void 0===t)throw new Error("Must provide datasetName or datasetId");n.append("name",t)}const s=await this._get(r,n);let a;if(Array.isArray(s)){if(0===s.length)throw new Error(`Dataset[id=${e}, name=${t}] not found`);a=s[0]}else a=s;return a}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(e){if(e instanceof Error&&e.message.toLocaleLowerCase().includes("not found"))return!1;throw e}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:r,toVersion:n}){let s=e;if(void 0===s&&void 0===t)throw new Error("Must provide either datasetName or datasetId");if(void 0!==s&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===s){s=(await this.readDataset({datasetName:t})).id}const a=new URLSearchParams({from_version:"string"==typeof r?r:r.toISOString(),to_version:"string"==typeof n?n:n.toISOString()});return await this._get(`/datasets/${s}/versions/diff`,a)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){if(void 0!==e);else{if(void 0===t)throw new Error("Must provide either datasetName or datasetId");e=(await this.readDataset({datasetName:t})).id}const r=await this._getResponse(`/datasets/${e}/openai_ft`);return(await r.text()).trim().split("\n").map((e=>JSON.parse(e)))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:r,datasetName:n,datasetNameContains:s,metadata:a}={}){const i=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(void 0!==r)for(const e of r)i.append("id",e);void 0!==n&&i.append("name",n),void 0!==s&&i.append("name_contains",s),void 0!==a&&i.append("metadata",JSON.stringify(a));for await(const e of this._getPaginated("/datasets",i))yield*e}async updateDataset(e){const{datasetId:t,datasetName:r,...n}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const s=t??(await this.readDataset({datasetName:r})).id;g(s);const a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v(a,"update dataset"),await a.json()}async updateDatasetTag(e){const{datasetId:t,datasetName:r,asOf:n,tag:s}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const a=t??(await this.readDataset({datasetName:r})).id;g(a);const o=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({as_of:"string"==typeof n?n:n.toISOString(),tag:s}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(o,"update dataset tags")}async deleteDataset({datasetId:e,datasetName:t}){let r="/datasets",n=e;if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==t){n=(await this.readDataset({datasetName:t})).id}if(void 0===n)throw new Error("Must provide datasetName or datasetId");g(n),r+=`/${n}`;const s=await this.caller.call((0,i.Yx)(this.debug),this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(s,`delete ${r}`),await s.json()}async indexDataset({datasetId:e,datasetName:t,tag:r}){let n=e;if(!n&&!t)throw new Error("Must provide either datasetName or datasetId");if(n&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(!n){n=(await this.readDataset({datasetName:t})).id}g(n);const s={tag:r},a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${n}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(a,"index dataset"),await a.json()}async similarExamples(e,t,r,{filter:n}={}){const s={limit:r,inputs:e};void 0!==n&&(s.filter=n),g(t);const a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${t}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(a,"fetch similar examples");return(await a.json()).examples}async createExample(e,t,r){if(F(e)&&(void 0!==t||void 0!==r))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let s=t?r?.datasetId:e.dataset_id;const a=t?r?.datasetName:e.dataset_name;if(void 0===s&&void 0===a)throw new Error("Must provide either datasetName or datasetId");if(void 0!==s&&void 0!==a)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===s){s=(await this.readDataset({datasetName:a})).id}const i=(t?r?.createdAt:e.created_at)||new Date;let o;o=F(e)?e:{inputs:e,outputs:t,created_at:i?.toISOString(),id:r?.exampleId,metadata:r?.metadata,split:r?.split,source_run_id:r?.sourceRunId,use_source_run_io:r?.useSourceRunIO,use_source_run_attachments:r?.useSourceRunAttachments,attachments:r?.attachments};const c=await this._uploadExamplesMultipart(s,[o]);return await this.readExample(c.example_ids?.[0]??n.A())}async createExamples(e){if(Array.isArray(e)){if(0===e.length)return[];const t=e;let r=t[0].dataset_id;const n=t[0].dataset_name;if(void 0===r&&void 0===n)throw new Error("Must provide either datasetName or datasetId");if(void 0!==r&&void 0!==n)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===r){r=(await this.readDataset({datasetName:n})).id}const s=await this._uploadExamplesMultipart(r,t);return await Promise.all(s.example_ids.map((e=>this.readExample(e))))}const{inputs:t,outputs:r,metadata:n,splits:s,sourceRunIds:a,useSourceRunIOs:i,useSourceRunAttachments:o,attachments:c,exampleIds:l,datasetId:u,datasetName:d}=e;if(void 0===t)throw new Error("Must provide inputs when using legacy parameters");let h=u;const p=d;if(void 0===h&&void 0===p)throw new Error("Must provide either datasetName or datasetId");if(void 0!==h&&void 0!==p)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===h){const e=await this.readDataset({datasetName:p});h=e.id}const m=t.map(((e,t)=>({dataset_id:h,inputs:e,outputs:r?.[t],metadata:n?.[t],split:s?.[t],id:l?.[t],attachments:c?.[t],source_run_id:a?.[t],use_source_run_io:i?.[t],use_source_run_attachments:o?.[t]}))),f=await this._uploadExamplesMultipart(h,m);return await Promise.all(f.example_ids.map((e=>this.readExample(e))))}async createLLMExample(e,t,r){return this.createExample({input:e},{output:t},r)}async createChatExample(e,t,r){const n=e.map((e=>u(e)?d(e):e)),s=u(t)?d(t):t;return this.createExample({input:n},{output:s},r)}async readExample(e){g(e);const t=`/examples/${e}`,r=await this._get(t),{attachment_urls:n,...s}=r,a=s;return n&&(a.attachments=Object.entries(n).reduce(((e,[t,r])=>(e[t.slice(11)]={presigned_url:r.presigned_url,mime_type:r.mime_type},e)),{})),a}async*listExamples({datasetId:e,datasetName:t,exampleIds:r,asOf:n,splits:s,inlineS3Urls:a,metadata:i,limit:o,offset:c,filter:l,includeAttachments:u}={}){let d;if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)d=e;else{if(void 0===t)throw new Error("Must provide a datasetName or datasetId");d=(await this.readDataset({datasetName:t})).id}const h=new URLSearchParams({dataset:d}),p=n?"string"==typeof n?n:n?.toISOString():void 0;p&&h.append("as_of",p);const m=a??!0;if(h.append("inline_s3_urls",m.toString()),void 0!==r)for(const e of r)h.append("id",e);if(void 0!==s)for(const e of s)h.append("splits",e);if(void 0!==i){const e=JSON.stringify(i);h.append("metadata",e)}void 0!==o&&h.append("limit",o.toString()),void 0!==c&&h.append("offset",c.toString()),void 0!==l&&h.append("filter",l),!0===u&&["attachment_urls","outputs","metadata"].forEach((e=>h.append("select",e)));let f=0;for await(const e of this._getPaginated("/examples",h)){for(const t of e){const{attachment_urls:e,...r}=t,n=r;e&&(n.attachments=Object.entries(e).reduce(((e,[t,r])=>(e[t.slice(11)]={presigned_url:r.presigned_url,mime_type:r.mime_type||void 0},e)),{})),yield n,f++}if(void 0!==o&&f>=o)break}}async deleteExample(e){g(e);const t=`/examples/${e}`,r=await this.caller.call((0,i.Yx)(this.debug),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(r,`delete ${t}`),await r.json()}async updateExample(e,t){let r,n,s;if(r=t?e:e.id,g(r),n=t?{id:r,...t}:e,void 0!==n.dataset_id)s=n.dataset_id;else{s=(await this.readExample(r)).dataset_id}return this._updateExamplesMultipart(s,[n])}async updateExamples(e){let t;if(void 0===e[0].dataset_id){t=(await this.readExample(e[0].id)).dataset_id}else t=e[0].dataset_id;return this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:r,tag:n}){let s;if(e)s=e;else{s=(await this.readDataset({datasetName:t})).id}if(g(s),r&&n||!r&&!n)throw new Error("Exactly one of asOf and tag must be specified.");const a=new URLSearchParams;void 0!==r&&a.append("as_of","string"==typeof r?r:r.toISOString()),void 0!==n&&a.append("tag",n);const o=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${s}/version?${a.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v(o,"read dataset version"),await o.json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:r}){let n;if(void 0===e&&void 0===t)throw new Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===e){n=(await this.readDataset({datasetName:t})).id}else n=e;g(n);const s=new URLSearchParams,a=r?"string"==typeof r?r:r?.toISOString():void 0;a&&s.append("as_of",a);return await this._get(`/datasets/${n}/splits`,s)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:r,exampleIds:n,remove:s=!1}){let a;if(void 0===e&&void 0===t)throw new Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===e){a=(await this.readDataset({datasetName:t})).id}else a=e;g(a);const o={split_name:r,examples:n.map((e=>(g(e),e))),remove:s},c=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/${a}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(c,"update dataset splits",!0)}async evaluateRun(e,t,{sourceInfo:r,loadChildRuns:n,referenceExample:s}={loadChildRuns:!1}){let a;if((0,y.m)("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."),"string"==typeof e)a=await this.readRun(e,{loadChildRuns:n});else{if("object"!=typeof e||!("id"in e))throw new Error("Invalid run type: "+typeof e);a=e}null!==a.reference_example_id&&void 0!==a.reference_example_id&&(s=await this.readExample(a.reference_example_id));const i=await t.evaluateRun(a,s),[o,c]=await this._logEvaluationFeedback(i,a,r);return c[0]}async createFeedback(e,t,{score:r,value:s,correction:a,comment:o,sourceInfo:c,feedbackSourceType:l="api",sourceRunId:u,feedbackId:d,feedbackConfig:h,projectId:p,comparativeExperimentId:m}){if(!e&&!p)throw new Error("One of runId or projectId must be provided");if(e&&p)throw new Error("Only one of runId or projectId can be provided");const f={type:l??"api",metadata:c??{}};void 0===u||void 0===f?.metadata||f.metadata.__run||(f.metadata.__run={run_id:u}),void 0!==f?.metadata&&void 0!==f.metadata.__run?.run_id&&g(f.metadata.__run.run_id);const y={id:d??n.A(),run_id:e,key:t,score:N(r),value:s,correction:a,comment:o,feedback_source:f,comparative_experiment_id:m,feedbackConfig:h,session_id:p},b=`${this.apiUrl}/feedback`,w=await this.caller.call((0,i.Yx)(this.debug),b,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(y),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v(w,"create feedback",!0),y}async updateFeedback(e,{score:t,value:r,correction:n,comment:s}){const a={};null!=t&&(a.score=N(t)),null!=r&&(a.value=r),null!=n&&(a.correction=n),null!=s&&(a.comment=s),g(e);const o=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(o,"update feedback",!0)}async readFeedback(e){g(e);const t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){g(e);const t=`/feedback/${e}`,r=await this.caller.call((0,i.Yx)(this.debug),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(r,`delete ${t}`),await r.json()}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:r}={}){const n=new URLSearchParams;if(e&&n.append("run",e.join(",")),t)for(const e of t)n.append("key",e);if(r)for(const e of r)n.append("source",e);for await(const e of this._getPaginated("/feedback",n))yield*e}async createPresignedFeedbackToken(e,t,{expiration:r,feedbackConfig:n}={}){const s={run_id:e,feedback_key:t,feedback_config:n};r?"string"==typeof r?s.expires_at=r:(r?.hours||r?.minutes||r?.days)&&(s.expires_in=r):s.expires_in={hours:3};const a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await a.json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:r,createdAt:n,description:s,metadata:a,id:o}){if(0===t.length)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:t[0]})).reference_dataset_id),null==!r)throw new Error("A reference dataset is required");const c={id:o,name:e,experiment_ids:t,reference_dataset_id:r,description:s,created_at:(n??new Date)?.toISOString(),extra:{}};a&&(c.extra.metadata=a);const l=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await l.json()}async*listPresignedFeedbackTokens(e){g(e);const t=new URLSearchParams({run_id:e});for await(const e of this._getPaginated("/feedback/tokens",t))yield*e}_selectEvalResults(e){let t;return t="results"in e?e.results:Array.isArray(e)?e:[e],t}async _logEvaluationFeedback(e,t,r){const n=this._selectEvalResults(e),s=[];for(const e of n){let n=r||{};e.evaluatorInfo&&(n={...e.evaluatorInfo,...n});let a=null;e.targetRunId?a=e.targetRunId:t&&(a=t.id),s.push(await this.createFeedback(a,e.key,{score:e.score,value:e.value,comment:e.comment,correction:e.correction,sourceInfo:n,sourceRunId:e.sourceRunId,feedbackConfig:e.feedbackConfig,feedbackSourceType:"model"}))}return[n,s]}async logEvaluationFeedback(e,t,r){const[n]=await this._logEvaluationFeedback(e,t,r);return n}async*listAnnotationQueues(e={}){const{queueIds:t,name:r,nameContains:n,limit:s}=e,a=new URLSearchParams;t&&t.forEach(((e,t)=>{g(e,`queueIds[${t}]`),a.append("ids",e)})),r&&a.append("name",r),n&&a.append("name_contains",n),a.append("limit",(void 0!==s?Math.min(s,100):100).toString());let i=0;for await(const e of this._getPaginated("/annotation-queues",a))if(yield*e,i++,void 0!==s&&i>=s)break}async createAnnotationQueue(e){const{name:t,description:r,queueId:s,rubricInstructions:a}=e,o={name:t,description:r,id:s||n.A(),rubric_instructions:a},c=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(Object.fromEntries(Object.entries(o).filter((([e,t])=>void 0!==t)))),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(c,"create annotation queue");return await c.json()}async readAnnotationQueue(e){const t=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/annotation-queues/${g(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(t,"read annotation queue");return await t.json()}async updateAnnotationQueue(e,t){const{name:r,description:n,rubricInstructions:s}=t,a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/annotation-queues/${g(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({name:r,description:n,rubric_instructions:s}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(a,"update annotation queue")}async deleteAnnotationQueue(e){const t=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/annotation-queues/${g(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(t,"delete annotation queue")}async addRunsToAnnotationQueue(e,t){const r=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/annotation-queues/${g(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t.map(((e,t)=>g(e,`runIds[${t}]`).toString()))),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(r,"add runs to annotation queue")}async getRunFromAnnotationQueue(e,t){const r=`/annotation-queues/${g(e,"queueId")}/run`,n=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}${r}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v(n,"get run from annotation queue"),await n.json()}async deleteRunFromAnnotationQueue(e,t){const r=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/annotation-queues/${g(e,"queueId")}/runs/${g(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(r,"delete run from annotation queue")}async getSizeFromAnnotationQueue(e){const t=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/annotation-queues/${g(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v(t,"get size from annotation queue"),await t.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.\n\n Current tenant: ${r.tenant_handle}\n\n Requested tenant: ${t}`)}async _getLatestCommitHash(e){const t=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await t.json();if(!t.ok){const e="string"==typeof r.detail?r.detail:JSON.stringify(r.detail),n=new Error(`Error ${t.status}: ${t.statusText}\n${e}`);throw n.statusCode=t.status,n}if(0!==r.commits.length)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){const[r,n,s]=b(e),a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/likes/${r}/${n}`,{method:"POST",body:JSON.stringify({like:t}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v(a,(t?"like":"unlike")+" prompt"),await a.json()}async _getPromptUrl(e){const[t,r,n]=b(e);if(await this._currentTenantIsOwner(t)){const e=await this._getSettings();return"latest"!==n?`${this.getHostUrl()}/prompts/${r}/${n.substring(0,8)}?organizationId=${e.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${e.id}`}return"latest"!==n?`${this.getHostUrl()}/hub/${t}/${r}/${n.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,(e=>e.commits)))yield*t}async*listPrompts(e){const t=new URLSearchParams;t.append("sort_field",e?.sortField??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!e?.isArchived).toString()),void 0!==e?.isPublic&&t.append("is_public",e.isPublic.toString()),e?.query&&t.append("query",e.query);for await(const e of this._getPaginated("/repos",t,(e=>e.repos)))yield*e}async getPrompt(e){const[t,r,n]=b(e),s=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/repos/${t}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(404===s.status)return null;await v(s,"get prompt");const a=await s.json();return a.repo?a.repo:null}async createPrompt(e,t){const r=await this._getSettings();if(t?.isPublic&&!r.tenant_handle)throw new Error("Cannot create a public prompt without first\n\n creating a LangChain Hub handle. \n You can add a handle by creating a public prompt at:\n\n https://smith.langchain.com/prompts");const[n,s,a]=b(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("create a prompt",n);const o={repo_handle:s,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},c=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(c,"create prompt");const{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[n,s,a]=b(e),o="latest"!==r?.parentCommitHash&&r?.parentCommitHash?r?.parentCommitHash:await this._getLatestCommitHash(`${n}/${s}`),c={manifest:JSON.parse(JSON.stringify(t)),parent_commit:o},l=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/commits/${n}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(l,"create commit");const u=await l.json();return this._getPromptUrl(`${n}/${s}${u.commit_hash?`:${u.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){if(!await this._getMultiPartSupport())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 e of t){const t=e.id,n=P({...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}},`Serializing body for example with id: ${t}`),s=new Blob([n],{type:"application/json"});if(r.append(t,s),e.inputs){const n=P(e.inputs,`Serializing inputs for example with id: ${t}`),s=new Blob([n],{type:"application/json"});r.append(`${t}.inputs`,s)}if(e.outputs){const n=P(e.outputs,`Serializing outputs whle updating example with id: ${t}`),s=new Blob([n],{type:"application/json"});r.append(`${t}.outputs`,s)}if(e.attachments)for(const[n,s]of Object.entries(e.attachments)){let e,a;Array.isArray(s)?[e,a]=s:(e=s.mimeType,a=s.data);const i=new Blob([a],{type:`${e}; length=${a.byteLength}`});r.append(`${t}.attachment.${n}`,i)}if(e.attachments_operations){const n=P(e.attachments_operations,`Serializing attachments while updating example with id: ${t}`),s=new Blob([n],{type:"application/json"});r.append(`${t}.attachments_operations`,s)}}const n=e??t[0]?.dataset_id,s=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/v1/platform/datasets/${n}/examples`,{method:"PATCH",headers:this.headers,body:r});return await s.json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){if(!await this._getMultiPartSupport())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 e of t){const t=(e.id??n.A()).toString(),s=P({created_at:e.created_at,...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split},...e.source_run_id&&{source_run_id:e.source_run_id},...e.use_source_run_io&&{use_source_run_io:e.use_source_run_io},...e.use_source_run_attachments&&{use_source_run_attachments:e.use_source_run_attachments}},`Serializing body for uploaded example with id: ${t}`),a=new Blob([s],{type:"application/json"});if(r.append(t,a),e.inputs){const n=P(e.inputs,`Serializing inputs for uploaded example with id: ${t}`),s=new Blob([n],{type:"application/json"});r.append(`${t}.inputs`,s)}if(e.outputs){const n=P(e.outputs,`Serializing outputs for uploaded example with id: ${t}`),s=new Blob([n],{type:"application/json"});r.append(`${t}.outputs`,s)}if(e.attachments)for(const[n,s]of Object.entries(e.attachments)){let e,a;Array.isArray(s)?[e,a]=s:(e=s.mimeType,a=s.data);const i=new Blob([a],{type:`${e}; length=${a.byteLength}`});r.append(`${t}.attachment.${n}`,i)}}const s=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/v1/platform/datasets/${e}/examples`,{method:"POST",headers:this.headers,body:r});await v(s,"upload examples");return await 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,n]=b(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);const s={};if(void 0!==t?.description&&(s.description=t.description),void 0!==t?.readme&&(s.readme=t.readme),void 0!==t?.tags&&(s.tags=t.tags),void 0!==t?.isPublic&&(s.is_public=t.isPublic),void 0!==t?.isArchived&&(s.is_archived=t.isArchived),0===Object.keys(s).length)throw new Error("No valid update options provided");const a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/repos/${r}/${n}`,{method:"PATCH",body:JSON.stringify(s),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await v(a,"update prompt"),a.json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[t,r,n]=b(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);const s=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/repos/${t}/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await s.json()}async pullPromptCommit(e,t){const[r,n,s]=b(e),a=await this.caller.call((0,i.Yx)(this.debug),`${this.apiUrl}/commits/${r}/${n}/${s}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await v(a,"pull prompt commit");const o=await a.json();return{owner:r,repo:n,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(e,t){const r=await this.pullPromptCommit(e,{includeModel:t?.includeModel});return JSON.stringify(r.manifest)}async pushPrompt(e,t){if(await this.promptExists(e)?t&&Object.keys(t).some((e=>"object"!==e))&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),!t?.object)return await this._getPromptUrl(e);return await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash})}async clonePublicDataset(e,t={}){const{sourceApiUrl:r=this.apiUrl,datasetName:n}=t,[s,a]=this.parseTokenOrUrl(e,r),i=new L({apiUrl:s,apiKey:"placeholder"}),o=await i.readSharedDataset(a),c=n||o.name;try{if(await this.hasDataset({datasetId:c}))return void console.log(`Dataset ${c} already exists in your tenant. Skipping.`)}catch(e){}const l=await i.listSharedExamples(a),u=await this.createDataset(c,{description:o.description,dataType:o.data_type||"kv",inputsSchema:o.inputs_schema_definition??void 0,outputsSchema:o.outputs_schema_definition??void 0});try{await this.createExamples({inputs:l.map((e=>e.inputs)),outputs:l.flatMap((e=>e.outputs?[e.outputs]:[])),datasetId:u.id})}catch(e){throw console.error(`An error occurred while creating dataset ${c}. You should delete it manually.`),e}}parseTokenOrUrl(e,t,r=2,n="dataset"){try{return g(e),[t,e]}catch(e){}try{const s=new URL(e).pathname.split("/").filter((e=>""!==e));if(s.length>=r){return[t,s[s.length-r]]}throw new Error(`Invalid public ${n} URL: ${e}`)}catch(t){throw new Error(`Invalid public ${n} URL or token: ${e}`)}}awaitPendingTraceBatches(){return this.manualFlushMode?(console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve()):Promise.all([...this.autoBatchQueue.items.map((({itemPromise:e})=>e)),this.batchIngestCaller.queue.onIdle()])}}function F(e){return"dataset_id"in e||"dataset_name"in e}},9120:(e,t,r)=>{"use strict";r.d(t,{A:()=>u});const n={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};var s,a=new Uint8Array(16);function i(){if(!s&&!(s="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return s(a)}for(var o=[],c=0;c<256;++c)o.push((c+256).toString(16).slice(1));function l(e,t=0){return(o[e[t+0]]+o[e[t+1]]+o[e[t+2]]+o[e[t+3]]+"-"+o[e[t+4]]+o[e[t+5]]+"-"+o[e[t+6]]+o[e[t+7]]+"-"+o[e[t+8]]+o[e[t+9]]+"-"+o[e[t+10]]+o[e[t+11]]+o[e[t+12]]+o[e[t+13]]+o[e[t+14]]+o[e[t+15]]).toLowerCase()}const u=function(e,t,r){if(n.randomUUID&&!t&&!e)return n.randomUUID();var s=(e=e||{}).random||(e.rng||i)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){r=r||0;for(var a=0;a<16;++a)t[r+a]=s[a];return t}return l(s)}},9137:(e,t,r)=>{"use strict";r.d(t,{T:()=>p});var n=r(2366);const s=/^(?:[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;const a=function(e){return"string"==typeof e&&s.test(e)};var i=r(9120),o=r(4850);function c(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const l=["*","_","`"];function u(e,t,r){const{firstNode:n,lastNode:s,nodeColors:a,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:u=9}=r??{};let d=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%\ngraph TD;\n`:"graph TD;\n";if(i){const t="default",r={[t]:"{0}({1})"};void 0!==n&&(r[n]="{0}([{1}]):::first"),void 0!==s&&(r[s]="{0}([{1}]):::last");for(const[n,s]of Object.entries(e)){const e=s.name.split(":").pop()??"";let a=l.some((t=>e.startsWith(t)&&e.endsWith(t)))?`

${e}

`:e;Object.keys(s.metadata??{}).length&&(a+=`
${Object.entries(s.metadata??{}).map((([e,t])=>`${e} = ${t}`)).join("\n")}`);const i=(r[n]??r[t]).replace("{0}",c(n)).replace("{1}",a);d+=`\t${i}\n`}}const h={};for(const e of t){const t=e.source.split(":"),r=e.target.split(":"),n=t.filter(((e,t)=>e===r[t])).join(":");h[n]||(h[n]=[]),h[n].push(e)}const p=new Set;function m(e,t){const r=1===e.length&&e[0].source===e[0].target;if(t&&!r){const e=t.split(":").pop();if(p.has(e))throw new Error(`Found duplicate subgraph '${e}' -- 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.`);p.add(e),d+=`\tsubgraph ${e}\n`}for(const t of e){const{source:e,target:r,data:n,conditional:s}=t;let a="";if(void 0!==n){let e=n;const t=e.split(" ");t.length>u&&(e=Array.from({length:Math.ceil(t.length/u)},((e,r)=>t.slice(r*u,(r+1)*u).join(" "))).join(" 
 ")),a=s?` -.  ${e}  .-> `:` --  ${e}  --\x3e `}else a=s?" -.-> ":" --\x3e ";d+=`\t${c(e)}${a}${c(r)};\n`}for(const e in h)e.startsWith(`${t}:`)&&e!==t&&m(h[e],e);t&&!r&&(d+="\tend\n")}m(h[""]??[],"");for(const e in h)e.includes(":")||""===e||m(h[e],e);return i&&(d+=function(e){let t="";for(const[r,n]of Object.entries(e))t+=`\tclassDef ${r} ${n};\n`;return t}(a??{})),d}function d(e,t){if(void 0!==e&&!a(e))return e;if(!(0,o.T)(t))return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e,e}catch(e){return t.getName()}}function h(e){return(0,o.T)(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...(0,n.Ik)(e.data.schema),title:e.data.name}}}class p{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?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach(((t,r)=>{e[t.id]=a(t.id)?r:t.id})),{nodes:Object.values(this.nodes).map((t=>({id:e[t.id],...h(t)}))),edges:this.edges.map((t=>{const r={source:e[t.source],target:e[t.target]};return void 0!==t.data&&(r.data=t.data),void 0!==t.conditional&&(r.conditional=t.conditional),r}))}}addNode(e,t,r){if(void 0!==t&&void 0!==this.nodes[t])throw new Error(`Node with id ${t} already exists`);const n=t??(0,i.A)(),s={id:n,data:e,name:d(t,e),metadata:r};return this.nodes[n]=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,n){if(void 0===this.nodes[e.id])throw new Error(`Source node ${e.id} not in graph`);if(void 0===this.nodes[t.id])throw new Error(`Target node ${t.id} not in graph`);const s={source:e.id,target:t.id,data:r,conditional:n};return this.edges.push(s),s}firstNode(){return m(this)}lastNode(){return f(this)}extend(e,t=""){let r=t;Object.values(e.nodes).map((e=>e.id)).every(a)&&(r="");const n=e=>r?`${r}:${e}`:e;Object.entries(e.nodes).forEach((([e,t])=>{this.nodes[n(e)]={...t,id:n(e)}}));const s=e.edges.map((e=>({...e,source:n(e.source),target:n(e.target)})));this.edges=[...this.edges,...s];const i=e.firstNode(),o=e.lastNode();return[i?{id:n(i.id),data:i.data}:void 0,o?{id:n(o.id),data:o.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&m(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&f(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map((e=>[e.id,e.name]))),t=new Map;Object.values(e).forEach((e=>{t.set(e,(t.get(e)||0)+1)}));const r=r=>{const n=e[r];return a(r)&&1===t.get(n)?n:r};return new p({nodes:Object.fromEntries(Object.entries(this.nodes).map((([e,t])=>[r(e),{...t,id:r(e)}]))),edges:this.edges.map((e=>({...e,source:r(e.source),target:r(e.target)})))})}drawMermaid(e){const{withStyles:t,curveStyle:r,nodeColors:n={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:s}=e??{},a=this.reid(),i=a.firstNode(),o=a.lastNode();return u(a.nodes,a.edges,{firstNode:i?.id,lastNode:o?.id,withStyles:t,curveStyle:r,nodeColors:n,wrapLabelNWords:s})}async drawMermaidPng(e){return async function(e,t){let{backgroundColor:r="white"}=t??{};const n=btoa(e);void 0!==r&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));const s=`https://mermaid.ink/img/${n}?bgColor=${r}`,a=await fetch(s);if(!a.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${a.status}`,`Status text: ${a.statusText}`].join("\n"));return await a.blob()}(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}}function m(e,t=[]){const r=new Set(e.edges.filter((e=>!t.includes(e.source))).map((e=>e.target))),n=[];for(const s of Object.values(e.nodes))t.includes(s.id)||r.has(s.id)||n.push(s);return 1===n.length?n[0]:void 0}function f(e,t=[]){const r=new Set(e.edges.filter((e=>!t.includes(e.target))).map((e=>e.source))),n=[];for(const s of Object.values(e.nodes))t.includes(s.id)||r.has(s.id)||n.push(s);return 1===n.length?n[0]:void 0}},9418:(e,t,r)=>{"use strict";e=r.nmd(e);const n=(e=0)=>t=>`[${38+e};5;${t}m`,s=(e=0)=>(t,r,n)=>`[${38+e};2;${t};${r};${n}m`;Object.defineProperty(e,"exports",{enumerable:!0,get:function(){const e=new Map,t={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]}};t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright;for(const[r,n]of Object.entries(t)){for(const[r,s]of Object.entries(n))t[r]={open:`[${s[0]}m`,close:`[${s[1]}m`},n[r]=t[r],e.set(s[0],s[1]);Object.defineProperty(t,r,{value:n,enumerable:!1})}return Object.defineProperty(t,"codes",{value:e,enumerable:!1}),t.color.close="",t.bgColor.close="",t.color.ansi256=n(),t.color.ansi16m=s(),t.bgColor.ansi256=n(10),t.bgColor.ansi16m=s(10),Object.defineProperties(t,{rgbToAnsi256:{value:(e,t,r)=>e===t&&t===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(r/255*5),enumerable:!1},hexToRgb:{value:e=>{const t=/(?[a-f\d]{6}|[a-f\d]{3})/i.exec(e.toString(16));if(!t)return[0,0,0];let{colorString:r}=t.groups;3===r.length&&(r=r.split("").map((e=>e+e)).join(""));const n=Number.parseInt(r,16);return[n>>16&255,n>>8&255,255&n]},enumerable:!1},hexToAnsi256:{value:e=>t.rgbToAnsi256(...t.hexToRgb(e)),enumerable:!1}}),t}})},9478:e=>{"use strict";e.exports=function(e,t){if("string"!=typeof e)throw new TypeError("Expected a string");return t=void 0===t?"_":t,e.replace(/([a-z\d])([A-Z])/g,"$1"+t+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+t+"$2").toLowerCase()}},9583:(e,t,r)=>{"use strict";r.r(t),r.d(t,{getEnv:()=>c,getEnvironmentVariable:()=>d,getRuntimeEnvironment:()=>u,isBrowser:()=>n,isDeno:()=>i,isJsDom:()=>a,isNode:()=>o,isWebWorker:()=>s});const n=()=>"undefined"!=typeof window&&void 0!==window.document,s=()=>"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name,a=()=>"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),i=()=>"undefined"!=typeof Deno,o=()=>"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node&&!i(),c=()=>{let e;return e=n()?"browser":o()?"node":s()?"webworker":a()?"jsdom":i()?"deno":"other",e};let l;async function u(){if(void 0===l){const e=c();l={library:"langchain-js",runtime:e}}return l}function d(e){try{return"undefined"!=typeof process?process.env?.[e]:i()?Deno?.env.get(e):void 0}catch(e){return}}},9589:(e,t,r)=>{"use strict";const n=r(9718),s=r(6874),a=r(3908),i=r(1123),o=r(144),c=r(6953),l=r(7414),u=r(3007),d=r(1832),h=r(2938),p=r(6254),m=r(4493),f=r(1729),g=r(560),y=r(9970),b=r(1763),w=r(909),v=r(3927),_=r(4277),k=r(5580),S=r(7059),E=r(4641),x=r(3999),T=r(4089),C=r(5200),P=r(2111),O=r(6170),A=r(3904),I=r(8311),M=r(7638),R=r(7631),j=r(9628),N=r(270),$=r(1261),L=r(3874),F=r(7075),D=r(5571),z=r(5342),U=r(6780),B=r(2525),q=r(5032);e.exports={parse:o,valid:c,clean:l,inc:u,diff:d,major:h,minor:p,patch:m,prerelease:f,compare:g,rcompare:y,compareLoose:b,compareBuild:w,sort:v,rsort:_,gt:k,lt:S,eq:E,neq:x,gte:T,lte:C,cmp:P,coerce:O,Comparator:A,Range:I,satisfies:M,toComparators:R,maxSatisfying:j,minSatisfying:N,minVersion:$,validRange:L,outside:F,gtr:D,ltr:z,intersects:U,simplifyRange:B,subset:q,SemVer:a,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:s.SEMVER_SPEC_VERSION,RELEASE_TYPES:s.RELEASE_TYPES,compareIdentifiers:i.compareIdentifiers,rcompareIdentifiers:i.rcompareIdentifiers}},9624:(e,t,r)=>{"use strict";r.r(t),r.d(t,{AsyncCaller:()=>o});var n=r(4116),s=r(3290);const a=[400,401,402,403,404,405,406,407,409],i=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||"AbortError"===e.name)throw e;if("ECONNABORTED"===e?.code)throw e;const t=e?.response?.status??e?.status;if(t&&a.includes(+t))throw e;if("insufficient_quota"===e?.error?.code){const t=new Error(e?.message);throw t.name="InsufficientQuotaError",t}};class o{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??i;const t=s.default;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add((()=>n((()=>e(...t).catch((e=>{throw e instanceof Error?e:new Error(e)}))),{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(((t,r)=>{e.signal?.addEventListener("abort",(()=>{r(new Error("AbortError"))}))}))]):this.call(t,...r)}fetch(...e){return this.call((()=>fetch(...e).then((e=>e.ok?e:Promise.reject(e)))))}}},9628:(e,t,r)=>{"use strict";const n=r(3908),s=r(8311);e.exports=(e,t,r)=>{let a=null,i=null,o=null;try{o=new s(t,r)}catch(e){return null}return e.forEach((e=>{o.test(e)&&(a&&-1!==i.compare(e)||(a=e,i=new n(a,r)))})),a}},9718:(e,t,r)=>{"use strict";const{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:s,MAX_LENGTH:a}=r(6874),i=r(7272),o=(t=e.exports={}).re=[],c=t.safeRe=[],l=t.src=[],u=t.safeSrc=[],d=t.t={};let h=0;const p="[a-zA-Z0-9-]",m=[["\\s",1],["\\d",a],[p,s]],f=(e,t,r)=>{const n=(e=>{for(const[t,r]of m)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e})(t),s=h++;i(e,s,t),d[e]=s,l[s]=t,u[s]=n,o[s]=new RegExp(t,r?"g":void 0),c[s]=new RegExp(n,r?"g":void 0)};f("NUMERICIDENTIFIER","0|[1-9]\\d*"),f("NUMERICIDENTIFIERLOOSE","\\d+"),f("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),f("MAINVERSION",`(${l[d.NUMERICIDENTIFIER]})\\.(${l[d.NUMERICIDENTIFIER]})\\.(${l[d.NUMERICIDENTIFIER]})`),f("MAINVERSIONLOOSE",`(${l[d.NUMERICIDENTIFIERLOOSE]})\\.(${l[d.NUMERICIDENTIFIERLOOSE]})\\.(${l[d.NUMERICIDENTIFIERLOOSE]})`),f("PRERELEASEIDENTIFIER",`(?:${l[d.NONNUMERICIDENTIFIER]}|${l[d.NUMERICIDENTIFIER]})`),f("PRERELEASEIDENTIFIERLOOSE",`(?:${l[d.NONNUMERICIDENTIFIER]}|${l[d.NUMERICIDENTIFIERLOOSE]})`),f("PRERELEASE",`(?:-(${l[d.PRERELEASEIDENTIFIER]}(?:\\.${l[d.PRERELEASEIDENTIFIER]})*))`),f("PRERELEASELOOSE",`(?:-?(${l[d.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${l[d.PRERELEASEIDENTIFIERLOOSE]})*))`),f("BUILDIDENTIFIER",`${p}+`),f("BUILD",`(?:\\+(${l[d.BUILDIDENTIFIER]}(?:\\.${l[d.BUILDIDENTIFIER]})*))`),f("FULLPLAIN",`v?${l[d.MAINVERSION]}${l[d.PRERELEASE]}?${l[d.BUILD]}?`),f("FULL",`^${l[d.FULLPLAIN]}$`),f("LOOSEPLAIN",`[v=\\s]*${l[d.MAINVERSIONLOOSE]}${l[d.PRERELEASELOOSE]}?${l[d.BUILD]}?`),f("LOOSE",`^${l[d.LOOSEPLAIN]}$`),f("GTLT","((?:<|>)?=?)"),f("XRANGEIDENTIFIERLOOSE",`${l[d.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),f("XRANGEIDENTIFIER",`${l[d.NUMERICIDENTIFIER]}|x|X|\\*`),f("XRANGEPLAIN",`[v=\\s]*(${l[d.XRANGEIDENTIFIER]})(?:\\.(${l[d.XRANGEIDENTIFIER]})(?:\\.(${l[d.XRANGEIDENTIFIER]})(?:${l[d.PRERELEASE]})?${l[d.BUILD]}?)?)?`),f("XRANGEPLAINLOOSE",`[v=\\s]*(${l[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[d.XRANGEIDENTIFIERLOOSE]})(?:${l[d.PRERELEASELOOSE]})?${l[d.BUILD]}?)?)?`),f("XRANGE",`^${l[d.GTLT]}\\s*${l[d.XRANGEPLAIN]}$`),f("XRANGELOOSE",`^${l[d.GTLT]}\\s*${l[d.XRANGEPLAINLOOSE]}$`),f("COERCEPLAIN",`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),f("COERCE",`${l[d.COERCEPLAIN]}(?:$|[^\\d])`),f("COERCEFULL",l[d.COERCEPLAIN]+`(?:${l[d.PRERELEASE]})?`+`(?:${l[d.BUILD]})?(?:$|[^\\d])`),f("COERCERTL",l[d.COERCE],!0),f("COERCERTLFULL",l[d.COERCEFULL],!0),f("LONETILDE","(?:~>?)"),f("TILDETRIM",`(\\s*)${l[d.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",f("TILDE",`^${l[d.LONETILDE]}${l[d.XRANGEPLAIN]}$`),f("TILDELOOSE",`^${l[d.LONETILDE]}${l[d.XRANGEPLAINLOOSE]}$`),f("LONECARET","(?:\\^)"),f("CARETTRIM",`(\\s*)${l[d.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",f("CARET",`^${l[d.LONECARET]}${l[d.XRANGEPLAIN]}$`),f("CARETLOOSE",`^${l[d.LONECARET]}${l[d.XRANGEPLAINLOOSE]}$`),f("COMPARATORLOOSE",`^${l[d.GTLT]}\\s*(${l[d.LOOSEPLAIN]})$|^$`),f("COMPARATOR",`^${l[d.GTLT]}\\s*(${l[d.FULLPLAIN]})$|^$`),f("COMPARATORTRIM",`(\\s*)${l[d.GTLT]}\\s*(${l[d.LOOSEPLAIN]}|${l[d.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",f("HYPHENRANGE",`^\\s*(${l[d.XRANGEPLAIN]})\\s+-\\s+(${l[d.XRANGEPLAIN]})\\s*$`),f("HYPHENRANGELOOSE",`^\\s*(${l[d.XRANGEPLAINLOOSE]})\\s+-\\s+(${l[d.XRANGEPLAINLOOSE]})\\s*$`),f("STAR","(<|>)?=?\\s*\\*"),f("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),f("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")},9830:(e,t,r)=>{"use strict";async function n(e,t){if(void 0===t)return e;let r;return Promise.race([e.catch((e=>{if(!t?.aborted)throw e})),new Promise(((e,n)=>{r=()=>{n(new Error("Aborted"))},t.addEventListener("abort",r),t.aborted&&n(new Error("Aborted"))}))]).finally((()=>t.removeEventListener("abort",r)))}r.d(t,{o:()=>n})},9849:(e,t,r)=>{"use strict";r.d(t,{ez:()=>O,RG:()=>A,Ns:()=>R,Vt:()=>C,Qs:()=>P,D4:()=>x,g2:()=>T,QC:()=>M,Xm:()=>I});var n=Object.prototype.toString,s=Array.isArray||function(e){return"[object Array]"===n.call(e)};function a(e){return"function"==typeof e}function i(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function o(e,t){return null!=e&&"object"==typeof e&&t in e}var c=RegExp.prototype.test;var l=/\S/;function u(e){return!function(e,t){return c.call(e,t)}(l,e)}var d={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};var h=/\s*/,p=/\s+/,m=/\s*=/,f=/\s*\}/,g=/#|\^|\/|>|\{|&|=|!/;function y(e){this.string=e,this.tail=e,this.pos=0}function b(e,t){this.view=e,this.cache={".":this.view},this.parent=t}function w(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}y.prototype.eos=function(){return""===this.tail},y.prototype.scan=function(e){var t=this.tail.match(e);if(!t||0!==t.index)return"";var r=t[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r},y.prototype.scanUntil=function(e){var t,r=this.tail.search(e);switch(r){case-1:t=this.tail,this.tail="";break;case 0:t="";break;default:t=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=t.length,t},b.prototype.push=function(e){return new b(e,this)},b.prototype.lookup=function(e){var t,r,n,s=this.cache;if(s.hasOwnProperty(e))t=s[e];else{for(var i,c,l,u=this,d=!1;u;){if(e.indexOf(".")>0)for(i=u.view,c=e.split("."),l=0;null!=i&&l0?s[s.length-1][4]:r;break;default:n.push(t)}return r}(function(e){for(var t,r,n=[],s=0,a=e.length;s"===i?o=this.renderPartial(a,t,r,s):"&"===i?o=this.unescapedValue(a,t):"name"===i?o=this.escapedValue(a,t,s):"text"===i&&(o=this.rawValue(a)),void 0!==o&&(c+=o);return c},w.prototype.renderSection=function(e,t,r,n,i){var o=this,c="",l=t.lookup(e[1]);if(l){if(s(l))for(var u=0,d=l.length;u0||!r)&&(s[a]=n+s[a]);return s.join("\n")},w.prototype.renderPartial=function(e,t,r,n){if(r){var s=this.getConfigTags(n),i=a(r)?r(e[1]):r[e[1]];if(null!=i){var o=e[6],c=e[5],l=e[4],u=i;0==c&&l&&(u=this.indentPartial(i,l,o));var d=this.parse(u,s);return this.renderTokens(d,t,r,u,n)}}},w.prototype.unescapedValue=function(e,t){var r=t.lookup(e[1]);if(null!=r)return r},w.prototype.escapedValue=function(e,t,r){var n=this.getConfigEscape(r)||v.escape,s=t.lookup(e[1]);if(null!=s)return"number"==typeof s&&n===v.escape?String(s):n(s)},w.prototype.rawValue=function(e){return e[1]},w.prototype.getConfigTags=function(e){return s(e)?e:e&&"object"==typeof e?e.tags:void 0},w.prototype.getConfigEscape=function(e){return e&&"object"==typeof e&&!s(e)?e.escape:void 0};var v={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){_.templateCache=e},get templateCache(){return _.templateCache}},_=new w;v.clearCache=function(){return _.clearCache()},v.parse=function(e,t){return _.parse(e,t)},v.render=function(e,t,r,n){if("string"!=typeof e)throw new TypeError('Invalid template! Template should be a "string" but "'+((s(a=e)?"array":typeof a)+'" was given as the first argument for mustache#render(template, view, partials)'));var a;return _.render(e,t,r,n)},v.escape=function(e){return String(e).replace(/[&<>"'`=\/]/g,(function(e){return d[e]}))},v.Scanner=y,v.Context=b,v.Writer=w;const k=v;var S=r(1368);function E(){k.escape=e=>e}const x=e=>{const t=e.split(""),r=[],n=(e,r)=>{for(let n=r;n{E();return(e=>e.map((e=>"name"===e[0]?{type:"variable",name:e[1].includes(".")?e[1].split(".")[0]:e[1]}:["#","&","^",">"].includes(e[0])?{type:"variable",name:e[1]}:{type:"literal",text:e[1]})))(k.parse(e))},C=(e,t)=>x(e).reduce(((e,r)=>{if("variable"===r.type){if(r.name in t){return e+("string"==typeof t[r.name]?t[r.name]:JSON.stringify(t[r.name]))}throw new Error(`(f-string) Missing value for input ${r.name}`)}return e+r.text}),""),P=(e,t)=>(E(),k.render(e,t)),O={"f-string":C,mustache:P},A={"f-string":x,mustache:T},I=(e,t,r)=>{try{return O[t](e,r)}catch(e){throw(0,S.Y)(e,"INVALID_PROMPT_INPUT")}},M=(e,t)=>A[t](e),R=(e,t,r)=>{if(!(t in O)){const e=Object.keys(O);throw new Error(`Invalid template format. Got \`${t}\`;\n should be one of ${e}`)}try{const n=r.reduce(((e,t)=>(e[t]="foo",e)),{});Array.isArray(e)?e.forEach((e=>{if("text"===e.type)I(e.text,t,n);else{if("image_url"!==e.type)throw new Error(`Invalid message template received. ${JSON.stringify(e,null,2)}`);if("string"==typeof e.image_url)I(e.image_url,t,n);else{const r=e.image_url.url;I(r,t,n)}}})):I(e,t,n)}catch(e){throw new Error(`Invalid prompt schema: ${e.message}`)}}},9970:(e,t,r)=>{"use strict";const n=r(560);e.exports=(e,t,r)=>n(t,e,r)},9998:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){let n=0,s=e.length;for(;s>0;){const a=s/2|0;let i=n+a;r(e[i],t)<=0?(n=++i,s-=a+1):s=a}return n}}},n={};function s(e){var t=n[e];if(void 0!==t)return t.exports;var a=n[e]={id:e,loaded:!1,exports:{}};return r[e](a,a.exports,s),a.loaded=!0,a.exports}t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,s.t=function(r,n){if(1&n&&(r=this(r)),8&n)return r;if("object"==typeof r&&r){if(4&n&&r.__esModule)return r;if(16&n&&"function"==typeof r.then)return r}var a=Object.create(null);s.r(a);var i={};e=e||[null,t({}),t([]),t(t)];for(var o=2&n&&r;"object"==typeof o&&!~e.indexOf(o);o=t(o))Object.getOwnPropertyNames(o).forEach((e=>i[e]=()=>r[e]));return i.default=()=>r,s.d(a,i),a},s.d=(e,t)=>{for(var r in t)s.o(t,r)&&!s.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),(()=>{"use strict";var e={};s.r(e),s.d(e,{RouterRunnable:()=>re,Runnable:()=>X.YN,RunnableAssign:()=>X.B2,RunnableBinding:()=>X.fJ,RunnableBranch:()=>ne,RunnableEach:()=>X.Vi,RunnableLambda:()=>X.jY,RunnableMap:()=>X.ck,RunnableParallel:()=>X.Pq,RunnablePassthrough:()=>te,RunnablePick:()=>X.Fm,RunnableRetry:()=>X.AO,RunnableSequence:()=>X.zZ,RunnableToolLike:()=>X.pG,RunnableWithFallbacks:()=>X.lH,RunnableWithMessageHistory:()=>ae,_coerceToRunnable:()=>X.Bp,ensureConfig:()=>Q.ZI,getCallbackManagerForConfig:()=>Q.kJ,mergeConfigs:()=>Q.SV,patchConfig:()=>Q.tn,pickRunnableConfigKeys:()=>Q.DY});var t={};s.r(t);var r={};s.r(r),s.d(r,{insecureHash:()=>Be});var n={};s.r(n),s.d(n,{BaseCache:()=>Ve,InMemoryCache:()=>Je,deserializeStoredGeneration:()=>We,getCacheKey:()=>Ke,serializeGeneration:()=>He});var a={};s.r(a),s.d(a,{BaseChatMessageHistory:()=>Qe,BaseListChatMessageHistory:()=>et,InMemoryChatMessageHistory:()=>tt});var i={};s.r(i),s.d(i,{BaseDocumentTransformer:()=>nt,Document:()=>rt,MappingDocumentTransformer:()=>st});var o={};s.r(o),s.d(o,{Embeddings:()=>it});var c={};s.r(c),s.d(c,{BaseExampleSelector:()=>ot,BasePromptSelector:()=>ct,ConditionalPromptSelector:()=>lt,LengthBasedExampleSelector:()=>pt,SemanticSimilarityExampleSelector:()=>ft,isChatModel:()=>dt,isLLM:()=>ut});var l={};s.r(l),s.d(l,{encodingForModel:()=>Ct,getEncoding:()=>Tt});var u={};s.r(u),s.d(u,{BaseLangChain:()=>Rt,BaseLanguageModel:()=>jt,calculateMaxTokens:()=>Mt,getEmbeddingContextSize:()=>Ot,getModelContextSize:()=>At,getModelNameForTiktoken:()=>Pt,isOpenAITool:()=>It});var d={};s.r(d),s.d(d,{BaseChatModel:()=>zt,SimpleChatModel:()=>Ut,createChatMessageChunkEncoderStream:()=>Ft});var h={};s.r(h),s.d(h,{BaseLLM:()=>Bt,LLM:()=>qt});var p={};s.r(p),s.d(p,{BaseMemory:()=>Kt,getInputValue:()=>Ht,getOutputValue:()=>Vt,getPromptInputKey:()=>Gt});var m={};s.r(m),s.d(m,{applyPatch:()=>Rr.X6,compare:()=>Rr.UD});var f={};s.r(f),s.d(f,{AsymmetricStructuredOutputParser:()=>Mr,BaseCumulativeTransformOutputParser:()=>kr,BaseLLMOutputParser:()=>Zt,BaseOutputParser:()=>Yt,BaseTransformOutputParser:()=>_r,BytesOutputParser:()=>Sr,CommaSeparatedListOutputParser:()=>xr,CustomListOutputParser:()=>Tr,JsonMarkdownStructuredOutputParser:()=>Ir,JsonOutputParser:()=>Nr,ListOutputParser:()=>Er,MarkdownListOutputParser:()=>Pr,NumberedListOutputParser:()=>Cr,OutputParserException:()=>Xt,StringOutputParser:()=>Or,StructuredOutputParser:()=>Ar,XMLOutputParser:()=>Dr,XML_FORMAT_INSTRUCTIONS:()=>Fr,parseJsonMarkdown:()=>jr.D,parsePartialJson:()=>jr.d,parseXMLMarkdown:()=>Br});var g={};s.r(g),s.d(g,{AIMessagePromptTemplate:()=>Kr.sS,BaseChatPromptTemplate:()=>Kr.qF,BaseMessagePromptTemplate:()=>Kr.pl,BaseMessageStringPromptTemplate:()=>Kr.OT,BasePromptTemplate:()=>qr.m,BaseStringPromptTemplate:()=>Gr.L,ChatMessagePromptTemplate:()=>Kr.Wn,ChatPromptTemplate:()=>Kr.RZ,DEFAULT_FORMATTER_MAPPING:()=>Jr.ez,DEFAULT_PARSER_MAPPING:()=>Jr.RG,DictPromptTemplate:()=>Qr.l,FewShotChatMessagePromptTemplate:()=>Wr.s,FewShotPromptTemplate:()=>Wr.FewShotPromptTemplate,HumanMessagePromptTemplate:()=>Kr.FS,ImagePromptTemplate:()=>Zr.C,MessagesPlaceholder:()=>Kr.GL,PipelinePromptTemplate:()=>Hr,PromptTemplate:()=>Vr.PromptTemplate,StructuredPrompt:()=>Xr,SystemMessagePromptTemplate:()=>Kr.BJ,checkValidTemplate:()=>Jr.Ns,interpolateFString:()=>Jr.Vt,interpolateMustache:()=>Jr.Qs,parseFString:()=>Jr.D4,parseMustache:()=>Jr.g2,parseTemplate:()=>Jr.QC,renderTemplate:()=>Jr.Xm});var y={};s.r(y),s.d(y,{BaseRetriever:()=>en});var b={};s.r(b),s.d(b,{BaseStore:()=>tn,InMemoryStore:()=>rn});var w={};s.r(w),s.d(w,{Validator:()=>wr,deepCompareStrict:()=>Qt,toJsonSchema:()=>on,validatesOnlyStrings:()=>cn});var v={};s.r(v),s.d(v,{BaseToolkit:()=>yn,DynamicStructuredTool:()=>gn,DynamicTool:()=>fn,StructuredTool:()=>pn,Tool:()=>mn,ToolInputParsingException:()=>an.qe,isLangChainTool:()=>hn,isRunnableToolLike:()=>un,isStructuredTool:()=>ln,isStructuredToolParams:()=>dn,tool:()=>bn});var _={};s.r(_),s.d(_,{LangChainTracerV1:()=>En});var k={};s.r(k),s.d(k,{getTracingCallbackHandler:()=>xn,getTracingV2CallbackHandler:()=>Tn});var S={};s.r(S),s.d(S,{RunCollectorCallbackHandler:()=>Pn});var E={};s.r(E),s.d(E,{chunkArray:()=>On});var x={};s.r(x),s.d(x,{convertToOpenAIFunction:()=>An,convertToOpenAITool:()=>In,isLangChainTool:()=>hn,isRunnableToolLike:()=>un,isStructuredTool:()=>ln,isStructuredToolParams:()=>dn});var T={};s.r(T),s.d(T,{cosineSimilarity:()=>Ln,euclideanDistance:()=>Dn,innerProduct:()=>Fn,matrixFunc:()=>Nn,maximalMarginalRelevance:()=>zn,normalize:()=>$n});var C={};s.r(C),s.d(C,{SaveableVectorStore:()=>Kn,VectorStore:()=>qn,VectorStoreRetriever:()=>Bn});var P={};s.r(P),s.d(P,{FakeChatMessageHistory:()=>Qn,FakeChatModel:()=>Jn,FakeEmbeddings:()=>ns,FakeLLM:()=>Vn,FakeListChatMessageHistory:()=>es,FakeListChatModel:()=>Xn,FakeRetriever:()=>Yn,FakeRunnable:()=>Hn,FakeSplitIntoListParser:()=>Wn,FakeStreamingChatModel:()=>Zn,FakeStreamingLLM:()=>Gn,FakeTool:()=>rs,FakeTracer:()=>ts,FakeVectorStore:()=>is,SingleRunExtractor:()=>as,SyntheticEmbeddings:()=>ss});var O={};s.r(O),s.d(O,{isZodSchema:()=>Lt});var A={};s.r(A),s.d(A,{agents:()=>t,caches:()=>n,callbacks__base:()=>Ze,callbacks__manager:()=>Ye,callbacks__promises:()=>Xe,chat_history:()=>a,documents:()=>i,embeddings:()=>o,example_selectors:()=>c,language_models__base:()=>u,language_models__chat_models:()=>d,language_models__llms:()=>h,load__serializable:()=>Ne,memory:()=>p,messages:()=>se,output_parsers:()=>f,outputs:()=>$t,prompt_values:()=>gt,prompts:()=>g,retrievers:()=>y,runnables:()=>e,stores:()=>b,tools:()=>v,tracers__base:()=>vn,tracers__console:()=>_n,tracers__initialize:()=>k,tracers__log_stream:()=>Cn,tracers__run_collector:()=>S,tracers__tracer_langchain:()=>kn,tracers__tracer_langchain_v1:()=>_,utils__async_caller:()=>at,utils__chunk_array:()=>E,utils__env:()=>Sn,utils__function_calling:()=>x,utils__hash:()=>r,utils__json_patch:()=>m,utils__json_schema:()=>w,utils__math:()=>T,utils__stream:()=>ee,utils__testing:()=>P,utils__tiktoken:()=>l,utils__types:()=>O,vectorstores:()=>C});var I,M=s(4476);!function(e){e.NAVIGATE="NAVIGATE",e.CLICK="CLICK",e.EXTRACT="EXTRACT",e.LOG="LOG",e.CONTENT_READY="CONTENT_READY",e.EXECUTE_WORKFLOW="EXECUTE_WORKFLOW",e.WORKFLOW_STATUS="WORKFLOW_STATUS",e.CONNECTION_STATUS="CONNECTION_STATUS",e.EXECUTE_QUERY="EXECUTE_QUERY",e.RUN_EXAMPLE="RUN_EXAMPLE",e.HEARTBEAT="HEARTBEAT",e.HEARTBEAT_ACK="HEARTBEAT_ACK",e.AGENT_STREAM_UPDATE="AGENT_STREAM_UPDATE",e.CANCEL_TASK="CANCEL_TASK"}(I||(I={}));const R=M.z.nativeEnum(I),j=M.z.object({type:R,payload:M.z.unknown()}),N=j.extend({type:M.z.literal(I.NAVIGATE),payload:M.z.object({url:M.z.string()})}),$=j.extend({type:M.z.literal(I.CLICK),payload:M.z.object({selector:M.z.string()})}),L=j.extend({type:M.z.literal(I.LOG),payload:M.z.object({source:M.z.string(),message:M.z.string(),level:M.z.enum(["info","error","warning"]),timestamp:M.z.string()})}),F=j.extend({type:M.z.literal(I.CONTENT_READY),payload:M.z.object({url:M.z.string(),title:M.z.string()})}),D=j.extend({type:M.z.literal(I.EXECUTE_WORKFLOW),payload:M.z.object({dsl:M.z.string()})}),z=j.extend({type:M.z.literal(I.WORKFLOW_STATUS),payload:M.z.object({workflowId:M.z.string(),steps:M.z.array(M.z.object({id:M.z.string(),status:M.z.string(),message:M.z.string().optional(),error:M.z.string().optional()})),output:M.z.unknown().optional()})}),U=j.extend({type:M.z.literal(I.CONNECTION_STATUS),payload:M.z.object({connected:M.z.boolean(),port:M.z.string().optional()})}),B=j.extend({type:M.z.literal(I.EXECUTE_QUERY),payload:M.z.object({query:M.z.string()})}),q=j.extend({type:M.z.literal(I.RUN_EXAMPLE),payload:M.z.object({exampleType:M.z.enum(["basic","multiTab"]).default("basic")})}),K=j.extend({type:M.z.literal(I.HEARTBEAT),payload:M.z.object({timestamp:M.z.number()})}),W=j.extend({type:M.z.literal(I.HEARTBEAT_ACK),payload:M.z.object({timestamp:M.z.number()})}),H=j.extend({type:M.z.literal(I.AGENT_STREAM_UPDATE),payload:M.z.object({step:M.z.number(),action:M.z.string(),status:M.z.enum(["thinking","executing","completed","error"]),details:M.z.object({content:M.z.string().optional(),toolName:M.z.string().optional(),toolArgs:M.z.any().optional(),toolResult:M.z.string().optional(),error:M.z.string().optional(),messageType:M.z.string().optional()})})}),V=j.extend({type:M.z.literal(I.CANCEL_TASK),payload:M.z.object({reason:M.z.string().optional(),source:M.z.string().optional()})});M.z.discriminatedUnion("type",[N,$,L,F,D,z,U,B,q,K,W,H,V]);var G;!function(e){e.OPTIONS_TO_BACKGROUND="options-to-background",e.SIDEPANEL_TO_BACKGROUND="sidepanel-to-background"}(G||(G={}));M.z.nativeEnum(G),M.z.object({type:M.z.nativeEnum(I),payload:M.z.unknown(),id:M.z.string().optional()});M.z.object({DEV_MODE:M.z.boolean(),VERSION:M.z.string(),LOG_LEVEL:M.z.enum(["info","error","warning","debug"]).default("info")});const J={DEV_MODE:!0,VERSION:"0.1.0",LOG_LEVEL:"info"};const Z=M.z.enum(["info","error","warning"]);M.z.object({source:M.z.string(),message:M.z.string(),level:Z,timestamp:M.z.string()});class Y{static initialize(e={}){this.debugMode=e.debugMode||!1}static registerPort(e,t){this.connectedPorts.set(e,t)}static unregisterPort(e){this.connectedPorts.delete(e)}static log(e,t,r="info"){if(!this.debugMode&&"info"===r)return;const n=`[${e}]`;switch(r){case"error":console.error(`${n} ${t}`);break;case"warning":console.warn(`${n} ${t}`);break;default:console.log(`${n} ${t}`)}const s={source:e,message:t,level:r,timestamp:(new Date).toISOString()};let a=!1;if(J.DEV_MODE){const e=this.connectedPorts.get(G.OPTIONS_TO_BACKGROUND);if(e)try{void 0!==e.name?(e.postMessage({type:I.LOG,payload:s}),a=!0):this.unregisterPort(G.OPTIONS_TO_BACKGROUND)}catch(e){this.unregisterPort(G.OPTIONS_TO_BACKGROUND),"info"===r&&t.includes("heartbeat")||console.warn(`Failed to send log to options page: ${e instanceof Error?e.message:String(e)}`)}}!a&&"undefined"!=typeof chrome&&chrome.runtime&&chrome.runtime.sendMessage({type:I.LOG,payload:s}).catch((e=>{}))}}Y.connectedPorts=new Map,Y.debugMode=!1;var X=s(3313),Q=s(765),ee=s(58);class te extends X.YN{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=(0,Q.ZI)(t);return this.func&&await this.func(e,r),this._callWithConfig((e=>Promise.resolve(e)),e,r)}async*transform(e,t){const r=(0,Q.ZI)(t);let n,s=!0;for await(const t of this._transformStreamWithConfig(e,(e=>e),r))if(yield t,s)if(void 0===n)n=t;else try{n=(0,ee.concat)(n,t)}catch{n=void 0,s=!1}this.func&&void 0!==n&&await this.func(n,r)}static assign(e){return new X.B2(new X.ck({steps:e}))}}class re extends X.YN{static lc_name(){return"RouterRunnable"}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,"runnables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.runnables=e.runnables}async invoke(e,t){const{key:r,input:n}=e,s=this.runnables[r];if(void 0===s)throw new Error(`No runnable associated with key "${r}".`);return s.invoke(n,(0,Q.ZI)(t))}async batch(e,t,r){const n=e.map((e=>e.key)),s=e.map((e=>e.input));if(void 0!==n.find((e=>void 0===this.runnables[e])))throw new Error("One or more keys do not have a corresponding runnable.");const a=n.map((e=>this.runnables[e])),i=this._getOptionsList(t??{},e.length),o=i[0]?.maxConcurrency??r?.maxConcurrency,c=o&&o>0?o:e.length,l=[];for(let e=0;ea[t].invoke(e,i[t]))),r=await Promise.all(t);l.push(r)}return l.flat()}async stream(e,t){const{key:r,input:n}=e,s=this.runnables[r];if(void 0===s)throw new Error(`No runnable associated with key "${r}".`);return s.stream(n,t)}}class ne extends X.YN{static lc_name(){return"RunnableBranch"}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,"default",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"branches",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");return new this({branches:e.slice(0,-1).map((([e,t])=>[(0,X.Bp)(e),(0,X.Bp)(t)])),default:(0,X.Bp)(e[e.length-1])})}async _invoke(e,t,r){let n;for(let s=0;sthis._enterHistory(e,t??{}))).withConfig({runName:"loadHistory"});const r=e.historyMessagesKey??e.inputMessagesKey;r&&(t=te.assign({[r]:t}).withConfig({runName:"insertHistory"}));const n=t.pipe(e.runnable.withListeners({onEnd:(e,t)=>this._exitHistory(e,t??{})})).withConfig({runName:"RunnableWithMessageHistory"}),s=e.config??{};super({...e,config:s,bound:n}),Object.defineProperty(this,"runnable",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputMessagesKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputMessagesKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"historyMessagesKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"getMessageHistory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if("object"!=typeof e||Array.isArray(e)||(0,se.isBaseMessage)(e))t=e;else{let r;r=this.inputMessagesKey?this.inputMessagesKey:1===Object.keys(e).length?Object.keys(e)[0]:"input",t=Array.isArray(e[r])&&Array.isArray(e[r][0])?e[r][0]:e[r]}if("string"==typeof t)return[new se.HumanMessage(t)];if(Array.isArray(t))return t;if((0,se.isBaseMessage)(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.\nGot ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(Array.isArray(e)||(0,se.isBaseMessage)(e)||"string"==typeof e)t=e;else{let r;r=void 0!==this.outputMessagesKey?this.outputMessagesKey:1===Object.keys(e).length?Object.keys(e)[0]:"output",t=void 0!==e.generations?e.generations[0][0].message:e[r]}if("string"==typeof t)return[new se.AIMessage(t)];if(Array.isArray(t))return t;if((0,se.isBaseMessage)(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(t,null,2)}`)}async _enterHistory(e,t){const r=t?.configurable?.messageHistory,n=await r.getMessages();return void 0===this.historyMessagesKey?n.concat(this._getInputMessages(e)):n}async _exitHistory(e,t){const r=t.configurable?.messageHistory;let n;n=Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?e.inputs[0]:e.inputs;let s=this._getInputMessages(n);if(void 0===this.historyMessagesKey){const e=await r.getMessages();s=s.slice(e.length)}const a=e.outputs;if(!a)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);const i=this._getOutputMessages(a);await r.addMessages([...s,...i])}async _mergeConfig(...e){const t=await super._mergeConfig(...e);if(!t.configurable||!t.configurable.sessionId){const e={[this.inputMessagesKey??"input"]:"foo"},t={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\neg. chain.invoke(${JSON.stringify(e)}, ${JSON.stringify(t)})`)}const{sessionId:r}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(r),t}}X.fJ;for(var ie=[],oe=0;oe<256;++oe)ie.push((oe+256).toString(16).slice(1));function ce(e,t=0){return(ie[e[t+0]]+ie[e[t+1]]+ie[e[t+2]]+ie[e[t+3]]+"-"+ie[e[t+4]]+ie[e[t+5]]+"-"+ie[e[t+6]]+ie[e[t+7]]+"-"+ie[e[t+8]]+ie[e[t+9]]+"-"+ie[e[t+10]]+ie[e[t+11]]+ie[e[t+12]]+ie[e[t+13]]+ie[e[t+14]]+ie[e[t+15]]).toLowerCase()}var le,ue,de,he=new Uint8Array(16);function pe(){if(!le&&!(le="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return le(he)}var me=0,fe=0;const ge=function(e,t,r){var n=t&&r||0,s=t||new Array(16),a=(e=e||{}).node,i=e.clockseq;if(e._v6||(a||(a=ue),null==i&&(i=de)),null==a||null==i){var o=e.random||(e.rng||pe)();null==a&&(a=[o[0],o[1],o[2],o[3],o[4],o[5]],ue||e._v6||(a[0]|=1,ue=a)),null==i&&(i=16383&(o[6]<<8|o[7]),void 0!==de||e._v6||(de=i))}var c=void 0!==e.msecs?e.msecs:Date.now(),l=void 0!==e.nsecs?e.nsecs:fe+1,u=c-me+(l-fe)/1e4;if(u<0&&void 0===e.clockseq&&(i=i+1&16383),(u<0||c>me)&&void 0===e.nsecs&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");me=c,fe=l,de=i;var d=(1e4*(268435455&(c+=122192928e5))+l)%4294967296;s[n++]=d>>>24&255,s[n++]=d>>>16&255,s[n++]=d>>>8&255,s[n++]=255&d;var h=c/4294967296*1e4&268435455;s[n++]=h>>>8&255,s[n++]=255&h,s[n++]=h>>>24&15|16,s[n++]=h>>>16&255,s[n++]=i>>>8|128,s[n++]=255&i;for(var p=0;p<6;++p)s[n+p]=a[p];return t||ce(s)},ye=/^(?:[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;const be=function(e){return"string"==typeof e&&ye.test(e)};const we=function(e){if(!be(e))throw TypeError("Invalid UUID");var t,r=new Uint8Array(16);return r[0]=(t=parseInt(e.slice(0,8),16))>>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r};function ve(e){var t=function(e){return Uint8Array.of((15&e[6])<<4|e[7]>>4&15,(15&e[7])<<4|(240&e[4])>>4,(15&e[4])<<4|(240&e[5])>>4,(15&e[5])<<4|(240&e[0])>>4,(15&e[0])<<4|(240&e[1])>>4,(15&e[1])<<4|(240&e[2])>>4,96|15&e[2],e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}("string"==typeof e?we(e):e);return"string"==typeof e?ce(t):t}function _e(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function ke(e){for(var t=1;t>>32-t}const Te=function(e){var t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var n=unescape(encodeURIComponent(e));e=[];for(var s=0;s>>0;w=b,b=y,y=xe(g,30)>>>0,g=f,f=k}r[0]=r[0]+f>>>0,r[1]=r[1]+g>>>0,r[2]=r[2]+y>>>0,r[3]=r[3]+b>>>0,r[4]=r[4]+w>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,255&r[0],r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,255&r[1],r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,255&r[2],r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,255&r[3],r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,255&r[4]]};var Ce=function(e,t,r){function n(e,n,s,a){var i;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],r=0;rparseInt(e,16)));return Pe(e,new Uint8Array(r))}const Ie="__error__",Me="__scheduled__",Re="__interrupt__",je="__resume__";var Ne=s(7380);var $e="object"==typeof window?window:{},Le="0123456789abcdef".split(""),Fe=[-2147483648,8388608,32768,128],De=[24,16,8,0],ze=[];function Ue(e){e?(ze[0]=ze[16]=ze[1]=ze[2]=ze[3]=ze[4]=ze[5]=ze[6]=ze[7]=ze[8]=ze[9]=ze[10]=ze[11]=ze[12]=ze[13]=ze[14]=ze[15]=0,this.blocks=ze):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}Ue.prototype.update=function(e){if(!this.finalized){var t="string"!=typeof e;t&&e.constructor===$e.ArrayBuffer&&(e=new Uint8Array(e));for(var r,n,s=0,a=e.length||0,i=this.blocks;s>2]|=e[s]<>2]|=r<>2]|=(192|r>>6)<>2]|=(128|63&r)<=57344?(i[n>>2]|=(224|r>>12)<>2]|=(128|r>>6&63)<>2]|=(128|63&r)<>2]|=(240|r>>18)<>2]|=(128|r>>12&63)<>2]|=(128|r>>6&63)<>2]|=(128|63&r)<=64?(this.block=i[16],this.start=n-64,this.hash(),this.hashed=!0):this.start=n}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this}},Ue.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>2]|=Fe[3&t],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},Ue.prototype.hash=function(){var e,t,r=this.h0,n=this.h1,s=this.h2,a=this.h3,i=this.h4,o=this.blocks;for(e=16;e<80;++e)t=o[e-3]^o[e-8]^o[e-14]^o[e-16],o[e]=t<<1|t>>>31;for(e=0;e<20;e+=5)r=(t=(n=(t=(s=(t=(a=(t=(i=(t=r<<5|r>>>27)+(n&s|~n&a)+i+1518500249+o[e]|0)<<5|i>>>27)+(r&(n=n<<30|n>>>2)|~r&s)+a+1518500249+o[e+1]|0)<<5|a>>>27)+(i&(r=r<<30|r>>>2)|~i&n)+s+1518500249+o[e+2]|0)<<5|s>>>27)+(a&(i=i<<30|i>>>2)|~a&r)+n+1518500249+o[e+3]|0)<<5|n>>>27)+(s&(a=a<<30|a>>>2)|~s&i)+r+1518500249+o[e+4]|0,s=s<<30|s>>>2;for(;e<40;e+=5)r=(t=(n=(t=(s=(t=(a=(t=(i=(t=r<<5|r>>>27)+(n^s^a)+i+1859775393+o[e]|0)<<5|i>>>27)+(r^(n=n<<30|n>>>2)^s)+a+1859775393+o[e+1]|0)<<5|a>>>27)+(i^(r=r<<30|r>>>2)^n)+s+1859775393+o[e+2]|0)<<5|s>>>27)+(a^(i=i<<30|i>>>2)^r)+n+1859775393+o[e+3]|0)<<5|n>>>27)+(s^(a=a<<30|a>>>2)^i)+r+1859775393+o[e+4]|0,s=s<<30|s>>>2;for(;e<60;e+=5)r=(t=(n=(t=(s=(t=(a=(t=(i=(t=r<<5|r>>>27)+(n&s|n&a|s&a)+i-1894007588+o[e]|0)<<5|i>>>27)+(r&(n=n<<30|n>>>2)|r&s|n&s)+a-1894007588+o[e+1]|0)<<5|a>>>27)+(i&(r=r<<30|r>>>2)|i&n|r&n)+s-1894007588+o[e+2]|0)<<5|s>>>27)+(a&(i=i<<30|i>>>2)|a&r|i&r)+n-1894007588+o[e+3]|0)<<5|n>>>27)+(s&(a=a<<30|a>>>2)|s&i|a&i)+r-1894007588+o[e+4]|0,s=s<<30|s>>>2;for(;e<80;e+=5)r=(t=(n=(t=(s=(t=(a=(t=(i=(t=r<<5|r>>>27)+(n^s^a)+i-899497514+o[e]|0)<<5|i>>>27)+(r^(n=n<<30|n>>>2)^s)+a-899497514+o[e+1]|0)<<5|a>>>27)+(i^(r=r<<30|r>>>2)^n)+s-899497514+o[e+2]|0)<<5|s>>>27)+(a^(i=i<<30|i>>>2)^r)+n-899497514+o[e+3]|0)<<5|n>>>27)+(s^(a=a<<30|a>>>2)^i)+r-899497514+o[e+4]|0,s=s<<30|s>>>2;this.h0=this.h0+r|0,this.h1=this.h1+n|0,this.h2=this.h2+s|0,this.h3=this.h3+a|0,this.h4=this.h4+i|0},Ue.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,s=this.h4;return Le[e>>28&15]+Le[e>>24&15]+Le[e>>20&15]+Le[e>>16&15]+Le[e>>12&15]+Le[e>>8&15]+Le[e>>4&15]+Le[15&e]+Le[t>>28&15]+Le[t>>24&15]+Le[t>>20&15]+Le[t>>16&15]+Le[t>>12&15]+Le[t>>8&15]+Le[t>>4&15]+Le[15&t]+Le[r>>28&15]+Le[r>>24&15]+Le[r>>20&15]+Le[r>>16&15]+Le[r>>12&15]+Le[r>>8&15]+Le[r>>4&15]+Le[15&r]+Le[n>>28&15]+Le[n>>24&15]+Le[n>>20&15]+Le[n>>16&15]+Le[n>>12&15]+Le[n>>8&15]+Le[n>>4&15]+Le[15&n]+Le[s>>28&15]+Le[s>>24&15]+Le[s>>20&15]+Le[s>>16&15]+Le[s>>12&15]+Le[s>>8&15]+Le[s>>4&15]+Le[15&s]},Ue.prototype.toString=Ue.prototype.hex,Ue.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,s=this.h4;return[e>>24&255,e>>16&255,e>>8&255,255&e,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24&255,r>>16&255,r>>8&255,255&r,n>>24&255,n>>16&255,n>>8&255,255&n,s>>24&255,s>>16&255,s>>8&255,255&s]},Ue.prototype.array=Ue.prototype.digest,Ue.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(20),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),e};const Be=e=>new Ue(!0).update(e).hex();var qe=s(6362);const Ke=(...e)=>Be(e.join("_"));function We(e){return void 0!==e.message?{text:e.text,message:(0,qe.Pz)(e.message)}:{text:e.text}}function He(e){const t={text:e.text};return void 0!==e.message&&(t.message=e.message.toDict()),t}class Ve{}const Ge=new Map;class Je extends Ve{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(Ke(e,t))??null)}async update(e,t,r){this.cache.set(Ke(e,t),r)}static global(){return new Je(Ge)}}var Ze=s(5960),Ye=s(5042),Xe=s(2293);class Qe extends Ne.Serializable{async addMessages(e){for(const t of e)await this.addMessage(t)}}class et extends Ne.Serializable{addUserMessage(e){return this.addMessage(new se.HumanMessage(e))}addAIChatMessage(e){return this.addMessage(new se.AIMessage(e))}addAIMessage(e){return this.addMessage(new se.AIMessage(e))}async addMessages(e){for(const t of e)await this.addMessage(t)}clear(){throw new Error("Not implemented.")}}class tt extends et{constructor(e){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","stores","message","in_memory"]}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}}class rt{constructor(e){Object.defineProperty(this,"pageContent",{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,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.pageContent=void 0!==e.pageContent?e.pageContent.toString():"",this.metadata=e.metadata??{},this.id=e.id}}class nt extends X.YN{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","documents","transformers"]})}invoke(e,t){return this.transformDocuments(e)}}class st extends nt{async transformDocuments(e){const t=[];for(const r of e){const e=await this._transformDocument(r);t.push(e)}return t}}var at=s(9624);class it{constructor(e){Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.caller=new at.AsyncCaller(e??{})}}class ot extends Ne.Serializable{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","example_selectors","base"]})}}class ct{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}}class lt extends ct{constructor(e,t=[]){super(),Object.defineProperty(this,"defaultPrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"conditionals",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(const[t,r]of this.conditionals)if(t(e))return r;return this.defaultPrompt}}function ut(e){return"base_llm"===e._modelType()}function dt(e){return"base_chat_model"===e._modelType()}function ht(e){return e.split(/\n| /).length}class pt extends ot{constructor(e){super(e),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"getTextLength",{enumerable:!0,configurable:!0,writable:!0,value:ht}),Object.defineProperty(this,"maxLength",{enumerable:!0,configurable:!0,writable:!0,value:2048}),Object.defineProperty(this,"exampleTextLengths",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??ht}async addExample(e){this.examples.push(e);const t=await this.examplePrompt.format(e);this.exampleTextLengths.push(this.getTextLength(t))}async calculateExampleTextLengths(e,t){if(e.length>0)return e;const{examples:r,examplePrompt:n}=t;return(await Promise.all(r.map((e=>n.format(e))))).map((e=>this.getTextLength(e)))}async selectExamples(e){const t=Object.values(e).join(" ");let r=this.maxLength-this.getTextLength(t),n=0;const s=[];for(;r>0&&nr.addExample(e)))),r}}function mt(e){return Object.keys(e).sort().map((t=>e[t]))}class ft extends ot{constructor(e){if(super(e),Object.defineProperty(this,"vectorStoreRetriever",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleKeys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputKeys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.exampleKeys=e.exampleKeys,this.inputKeys=e.inputKeys,void 0!==e.vectorStore)this.vectorStoreRetriever=e.vectorStore.asRetriever({k:e.k??4,filter:e.filter});else{if(!e.vectorStoreRetriever)throw new Error('You must specify one of "vectorStore" and "vectorStoreRetriever".');this.vectorStoreRetriever=e.vectorStoreRetriever}}async addExample(e){const t=mt((this.inputKeys??Object.keys(e)).reduce(((t,r)=>({...t,[r]:e[r]})),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new rt({pageContent:t,metadata:e})])}async selectExamples(e){const t=mt((this.inputKeys??Object.keys(e)).reduce(((t,r)=>({...t,[r]:e[r]})),{})).join(" "),r=(await this.vectorStoreRetriever.invoke(t)).map((e=>e.metadata));return this.exampleKeys?r.map((e=>this.exampleKeys.reduce(((t,r)=>({...t,[r]:e[r]})),{}))):r}static async fromExamples(e,t,r,n={}){const s=n.inputKeys??null,a=e.map((e=>mt(s?s.reduce(((t,r)=>({...t,[r]:e[r]})),{}):e).join(" "))),i=await r.fromTexts(a,e,t,n);return new ft({vectorStore:i,k:n.k??4,exampleKeys:n.exampleKeys,inputKeys:n.inputKeys})}}var gt=s(5311),yt=s(7526),bt=Object.defineProperty;function wt(e,t){return 1===e.length?[t.get(e.join(","))]:function(e,t){let r=Array.from({length:e.length},((e,t)=>({start:t,end:t+1})));for(;r.length>1;){let n=null;for(let s=0;st.get(e.slice(r.start,r.end).join(",")))).filter((e=>null!=e))}var vt,_t,kt=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,t){this.patStr=e.pat_str;const r=e.bpe_ranks.split("\n").filter(Boolean).reduce(((e,t)=>{const[r,n,...s]=t.split(" "),a=Number.parseInt(n,10);return s.forEach(((t,r)=>e[t]=a+r)),e}),{});for(const[e,t]of Object.entries(r)){const r=yt.toByteArray(e);this.rankMap.set(r.join(","),t),this.textMap.set(t,r)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce(((e,[t,r])=>(e[r]=this.textEncoder.encode(t),e)),{})}encode(e,t=[],r="all"){const n=new RegExp(this.patStr,"ug"),s=kt.specialTokenRegex(Object.keys(this.specialTokens)),a=[],i=new Set("all"===t?Object.keys(this.specialTokens):t),o=new Set("all"===r?Object.keys(this.specialTokens).filter((e=>!i.has(e))):r);if(o.size>0){const t=kt.specialTokenRegex([...o]),r=e.match(t);if(null!=r)throw new Error(`The text contains a special token that is not allowed: ${r[0]}`)}let c=0;for(;;){let t=null,r=c;for(;s.lastIndex=r,t=s.exec(e),null!=t&&!i.has(t[0]);)r=t.index+1;const o=t?.index??e.length;for(const t of e.substring(c,o).matchAll(n)){const e=this.textEncoder.encode(t[0]),r=this.rankMap.get(e.join(","));null==r?a.push(...wt(e,this.rankMap)):a.push(r)}if(null==t)break;let l=this.specialTokens[t[0]];a.push(l),c=t.index+t[0].length}return a}decode(e){const t=[];let r=0;for(let n=0;nnew RegExp(e.map((e=>function(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}(e))).join("|"),"g"),((e,t,r)=>{t in e?bt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r})(St,"symbol"!=typeof(vt="specialTokenRegex")?vt+"":vt,_t);const Et={},xt=new at.AsyncCaller({});async function Tt(e){return e in Et||(Et[e]=xt.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then((e=>e.json())).then((e=>new St(e))).catch((t=>{throw delete Et[e],t}))),await Et[e]}async function Ct(e){return Tt(function(e){switch(e){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":return"o200k_base";default:throw new Error("Unknown model")}}(e))}const Pt=e=>e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,Ot=e=>"text-embedding-ada-002"===e?8191:2046,At=e=>{switch(Pt(e)){case"gpt-3.5-turbo-16k":return 16384;case"gpt-3.5-turbo":return 4096;case"gpt-4-32k":return 32768;case"gpt-4":return 8192;case"text-davinci-003":default:return 4097;case"text-curie-001":case"text-babbage-001":case"text-ada-001":case"code-cushman-001":return 2048;case"code-davinci-002":return 8e3}};function It(e){return!("object"!=typeof e||!e)&&!!("type"in e&&"function"===e.type&&"function"in e&&"object"==typeof e.function&&e.function&&"name"in e.function&&"parameters"in e.function)}const Mt=async({prompt:e,modelName:t})=>{let r;try{r=(await Ct(Pt(t))).encode(e).length}catch(t){console.warn("Failed to calculate number of tokens, falling back to approximate count"),r=Math.ceil(e.length/4)}return At(t)-r};class Rt extends X.YN{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??!1,this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}}class jt extends Rt{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}constructor({callbacks:e,callbackManager:t,...r}){const{cache:n,...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}),this.cache="object"==typeof n?n:n?Je.global():void 0,this.caller=new at.AsyncCaller(r??{})}async getNumTokens(e){if("string"!=typeof e)return 0;let t=Math.ceil(e.length/4);if(!this._encoding)try{this._encoding=await Ct("modelName"in this?Pt(this.modelName):"gpt2")}catch(e){console.warn("Failed to calculate number of tokens, falling back to approximate count",e)}if(this._encoding)try{t=this._encoding.encode(e).length}catch(e){console.warn("Failed to calculate number of tokens, falling back to approximate count",e)}return t}static _convertInputToPromptValue(e){return"string"==typeof e?new gt.StringPromptValue(e):Array.isArray(e)?new gt.ChatPromptValue(e.map(qe.K0)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){const r={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()},n=Object.entries(r).filter((([e,t])=>void 0!==t)),s=n.map((([e,t])=>`${e}:${JSON.stringify(t)}`)).sort().join(",");return s}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}}var Nt=s(2366),$t=s(8028);function Lt(e){if(!e)return!1;if("object"!=typeof e)return!1;if(Array.isArray(e))return!1;const t=e;if(t._def)return!0;return!!Object.values(M.z.ZodFirstPartyTypeKind).includes(t.constructor?.name??"NOT_INCLUDED")||"function"==typeof t.parse&&"function"==typeof t.parseAsync&&"function"==typeof t.safeParse&&"function"==typeof t.safeParseAsync}function Ft(){const e=new TextEncoder;return new TransformStream({transform(t,r){r.enqueue(e.encode("string"==typeof t.content?t.content:JSON.stringify(t.content)))}})}function Dt(e){const t=[];for(const r of e){let e=r;if(Array.isArray(r.content))for(let t=0;tt?.handleLLMError(e)))),e}await Promise.all((c??[]).map((e=>e?.handleLLMEnd({generations:[[l]],llmOutput:u}))))}}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,n){const s=e.map((e=>e.map(se.coerceMessageLikeToMessage)));let a;if(void 0!==n&&n.length===s.length)a=n;else{const e={...r.metadata,...this.getLsParams(t)},n=await Ye.CallbackManager.configure(r.callbacks,this.callbacks,r.tags,this.tags,e,this.metadata,{verbose:this.verbose}),i={options:t,invocation_params:this?.invocationParams(t),batch_size:1};a=await(n?.handleChatModelStart(this.toJSON(),s.map(Dt),r.runId,void 0,i,void 0,void 0,r.runName))}const i=[],o=[];if(!!a?.[0].handlers.find(Ze.callbackHandlerPrefersStreaming)&&!this.disableStreaming&&1===s.length&&this._streamResponseChunks!==zt.prototype._streamResponseChunks)try{const e=await this._streamResponseChunks(s[0],t,a?.[0]);let r,n;for await(const t of e){if(null==t.message.id){const e=a?.at(0)?.runId;null!=e&&t.message._updateId(`run-${e}`)}r=void 0===r?t:(0,ee.concat)(r,t),(0,se.isAIMessageChunk)(t.message)&&void 0!==t.message.usage_metadata&&(n={tokenUsage:{promptTokens:t.message.usage_metadata.input_tokens,completionTokens:t.message.usage_metadata.output_tokens,totalTokens:t.message.usage_metadata.total_tokens}})}if(void 0===r)throw new Error("Received empty response from chat model call.");i.push([r]),await(a?.[0].handleLLMEnd({generations:i,llmOutput:n}))}catch(e){throw await(a?.[0].handleLLMError(e)),e}else{const e=await Promise.allSettled(s.map(((e,r)=>this._generate(e,{...t,promptIndex:r},a?.[r]))));await Promise.all(e.map((async(e,t)=>{if("fulfilled"===e.status){const r=e.value;for(const e of r.generations){if(null==e.message.id){const t=a?.at(0)?.runId;null!=t&&e.message._updateId(`run-${t}`)}e.message.response_metadata={...e.generationInfo,...e.message.response_metadata}}return 1===r.generations.length&&(r.generations[0].message.response_metadata={...r.llmOutput,...r.generations[0].message.response_metadata}),i[t]=r.generations,o[t]=r.llmOutput,a?.[t]?.handleLLMEnd({generations:[r.generations],llmOutput:r.llmOutput})}return await(a?.[t]?.handleLLMError(e.reason)),Promise.reject(e.reason)})))}const c={generations:i,llmOutput:o.length?this._combineLLMOutput?.(...o):void 0};return Object.defineProperty(c,$t.RUN_KEY,{value:a?{runIds:a?.map((e=>e.runId))}:void 0,configurable:!0}),c}async _generateCached({messages:e,cache:t,llmStringKey:r,parsedOptions:n,handledOptions:s}){const a=e.map((e=>e.map(se.coerceMessageLikeToMessage))),i={...s.metadata,...this.getLsParams(n)},o=await Ye.CallbackManager.configure(s.callbacks,this.callbacks,s.tags,this.tags,i,this.metadata,{verbose:this.verbose}),c={options:n,invocation_params:this?.invocationParams(n),batch_size:1},l=await(o?.handleChatModelStart(this.toJSON(),a.map(Dt),s.runId,void 0,c,void 0,void 0,s.runName)),u=[],d=(await Promise.allSettled(a.map((async(e,n)=>{const s=zt._convertInputToPromptValue(e).toString(),a=await t.lookup(s,r);return null==a&&u.push(n),a})))).map(((e,t)=>({result:e,runManager:l?.[t]}))).filter((({result:e})=>"fulfilled"===e.status&&null!=e.value||"rejected"===e.status)),h=[];await Promise.all(d.map((async({result:e,runManager:t},r)=>{if("fulfilled"===e.status){const n=e.value;return h[r]=n.map((e=>("message"in e&&(0,se.isBaseMessage)(e.message)&&(0,se.isAIMessage)(e.message)&&(e.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0}),e.generationInfo={...e.generationInfo,tokenUsage:{}},e))),n.length&&await(t?.handleLLMNewToken(n[0].text)),t?.handleLLMEnd({generations:[n]},void 0,void 0,void 0,{cached:!0})}return await(t?.handleLLMError(e.reason,void 0,void 0,void 0,{cached:!0})),Promise.reject(e.reason)})));const p={generations:h,missingPromptIndices:u,startedRunManagers:l};return Object.defineProperty(p,$t.RUN_KEY,{value:l?{runIds:l?.map((e=>e.runId))}:void 0,configurable:!0}),p}async generate(e,t,r){let n;n=Array.isArray(t)?{stop:t}:t;const s=e.map((e=>e.map(se.coerceMessageLikeToMessage))),[a,i]=this._separateRunnableConfigFromCallOptionsCompat(n);if(a.callbacks=a.callbacks??r,!this.cache)return this._generateUncached(s,i,a);const{cache:o}=this,c=this._getSerializedCacheKeyParametersForCall(i),{generations:l,missingPromptIndices:u,startedRunManagers:d}=await this._generateCached({messages:s,cache:o,llmStringKey:c,parsedOptions:i,handledOptions:a});let h={};if(u.length>0){const e=await this._generateUncached(u.map((e=>s[e])),i,a,void 0!==d?u.map((e=>d?.[e])):void 0);await Promise.all(e.generations.map((async(e,t)=>{const r=u[t];l[r]=e;const n=zt._convertInputToPromptValue(s[r]).toString();return o.update(n,c,e)}))),h=e.llmOutput??{}}return{generations:l,llmOutput:h}}invocationParams(e){return{}}_modelType(){return"base_chat_model"}serialize(){return{...this.invocationParams(),_type:this._llmType(),_model:this._modelType()}}async generatePrompt(e,t,r){const n=e.map((e=>e.toChatMessages()));return this.generate(n,t,r)}async call(e,t,r){return(await this.generate([e.map(se.coerceMessageLikeToMessage)],t,r)).generations[0][0].message}async callPrompt(e,t,r){const n=e.toChatMessages();return this.call(n,t,r)}async predictMessages(e,t,r){return this.call(e,t,r)}async predict(e,t,r){const n=new se.HumanMessage(e),s=await this.call([n],t,r);if("string"!=typeof s.content)throw new Error("Cannot use predict when output is not a string.");return s.content}withStructuredOutput(e,t){if("function"!=typeof this.bindTools)throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(t?.strict)throw new Error('"strict" mode is not supported for this model by default.');const r=e,n=t?.name,s=r.description??"A function available to call.",a=t?.method,i=t?.includeRaw;if("jsonMode"===a)throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let o,c=n??"extract";Lt(r)?o=[{type:"function",function:{name:c,description:s,parameters:(0,Nt.Ik)(r)}}]:("name"in r&&(c=r.name),o=[{type:"function",function:{name:c,description:s,parameters:r}}]);const l=this.bindTools(o),u=X.jY.from((e=>{if(!e.tool_calls||0===e.tool_calls.length)throw new Error("No tool calls found in the response.");const t=e.tool_calls.find((e=>e.name===c));if(!t)throw new Error(`No tool call found with name ${c}.`);return t.args}));if(!i)return l.pipe(u).withConfig({runName:"StructuredOutput"});const d=te.assign({parsed:(e,t)=>u.invoke(e.raw,t)}),h=te.assign({parsed:()=>null}),p=d.withFallbacks({fallbacks:[h]});return X.zZ.from([{raw:l},p]).withConfig({runName:"StructuredOutputRunnable"})}}class Ut extends zt{async _generate(e,t,r){const n=await this._call(e,t,r),s=new se.AIMessage(n);if("string"!=typeof s.content)throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:s.content,message:s}]}}}class Bt extends jt{constructor({concurrency:e,...t}){super(e?{maxConcurrency:e,...t}:t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","llms",this._llmType()]})}async invoke(e,t){const r=Bt._convertInputToPromptValue(e);return(await this.generatePrompt([r],t,t?.callbacks)).generations[0][0].text}async*_streamResponseChunks(e,t,r){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(e){const[t,r]=super._separateRunnableConfigFromCallOptions(e);return r.signal=t.signal,[t,r]}async*_streamIterator(e,t){if(this._streamResponseChunks===Bt.prototype._streamResponseChunks)yield this.invoke(e,t);else{const r=Bt._convertInputToPromptValue(e),[n,s]=this._separateRunnableConfigFromCallOptionsCompat(t),a=await Ye.CallbackManager.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}),i={options:s,invocation_params:this?.invocationParams(s),batch_size:1},o=await(a?.handleLLMStart(this.toJSON(),[r.toString()],n.runId,void 0,i,void 0,void 0,n.runName));let c=new $t.GenerationChunk({text:""});try{for await(const e of this._streamResponseChunks(r.toString(),s,o?.[0]))c=c?c.concat(e):e,"string"==typeof e.text&&(yield e.text)}catch(e){throw await Promise.all((o??[]).map((t=>t?.handleLLMError(e)))),e}await Promise.all((o??[]).map((e=>e?.handleLLMEnd({generations:[[c]]}))))}}async generatePrompt(e,t,r){const n=e.map((e=>e.toString()));return this.generate(n,t,r)}invocationParams(e){return{}}_flattenLLMResult(e){const t=[];for(let r=0;rt?.handleLLMError(e)))),e}const r=this._flattenLLMResult(a);await Promise.all((s??[]).map(((e,t)=>e?.handleLLMEnd(r[t]))))}const i=s?.map((e=>e.runId))||void 0;return Object.defineProperty(a,$t.RUN_KEY,{value:i?{runIds:i}:void 0,configurable:!0}),a}async _generateCached({prompts:e,cache:t,llmStringKey:r,parsedOptions:n,handledOptions:s,runId:a}){const i=await Ye.CallbackManager.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),o={options:n,invocation_params:this?.invocationParams(n),batch_size:e.length},c=await(i?.handleLLMStart(this.toJSON(),e,a,void 0,o,void 0,void 0,s?.runName)),l=[],u=(await Promise.allSettled(e.map((async(e,n)=>{const s=await t.lookup(e,r);return null==s&&l.push(n),s})))).map(((e,t)=>({result:e,runManager:c?.[t]}))).filter((({result:e})=>"fulfilled"===e.status&&null!=e.value||"rejected"===e.status)),d=[];await Promise.all(u.map((async({result:e,runManager:t},r)=>{if("fulfilled"===e.status){const n=e.value;return d[r]=n.map((e=>(e.generationInfo={...e.generationInfo,tokenUsage:{}},e))),n.length&&await(t?.handleLLMNewToken(n[0].text)),t?.handleLLMEnd({generations:[n]},void 0,void 0,void 0,{cached:!0})}return await(t?.handleLLMError(e.reason,void 0,void 0,void 0,{cached:!0})),Promise.reject(e.reason)})));const h={generations:d,missingPromptIndices:l,startedRunManagers:c};return Object.defineProperty(h,$t.RUN_KEY,{value:c?{runIds:c?.map((e=>e.runId))}:void 0,configurable:!0}),h}async generate(e,t,r){if(!Array.isArray(e))throw new Error("Argument 'prompts' is expected to be a string[]");let n;n=Array.isArray(t)?{stop:t}:t;const[s,a]=this._separateRunnableConfigFromCallOptionsCompat(n);if(s.callbacks=s.callbacks??r,!this.cache)return this._generateUncached(e,a,s);const{cache:i}=this,o=this._getSerializedCacheKeyParametersForCall(a),{generations:c,missingPromptIndices:l,startedRunManagers:u}=await this._generateCached({prompts:e,cache:i,llmStringKey:o,parsedOptions:a,handledOptions:s,runId:s.runId});let d={};if(l.length>0){const t=await this._generateUncached(l.map((t=>e[t])),a,s,void 0!==u?l.map((e=>u?.[e])):void 0);await Promise.all(t.generations.map((async(t,r)=>{const n=l[r];return c[n]=t,i.update(e[n],o,t)}))),d=t.llmOutput??{}}return{generations:c,llmOutput:d}}async call(e,t,r){const{generations:n}=await this.generate([e],t,r);return n[0][0].text}async predict(e,t,r){return this.call(e,t,r)}async predictMessages(e,t,r){const n=(0,se.getBufferString)(e),s=await this.call(n,t,r);return new se.AIMessage(s)}_identifyingParams(){return{}}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}_modelType(){return"base_llm"}}class qt extends Bt{async _generate(e,t,r){return{generations:await Promise.all(e.map(((e,n)=>this._call(e,{...t,promptIndex:n},r).then((e=>[{text:e}])))))}}}class Kt{}const Wt=(e,t)=>{if(void 0!==t)return e[t];const r=Object.keys(e);return 1===r.length?e[r[0]]:void 0},Ht=(e,t)=>{const r=Wt(e,t);if(!r){const t=Object.keys(e);throw new Error(`input values have ${t.length} keys, you must specify an input key or pass only 1 key as input`)}return r},Vt=(e,t)=>{const r=Wt(e,t);if(!r&&""!==r){const t=Object.keys(e);throw new Error(`output values have ${t.length} keys, you must specify an output key or pass only 1 key as output`)}return r};function Gt(e,t){const r=Object.keys(e).filter((e=>!t.includes(e)&&"stop"!==e));if(1!==r.length)throw new Error(`One input key expected, but got ${r.length}`);return r[0]}var Jt=s(1368);class Zt extends X.YN{parseResultWithPrompt(e,t,r){return this.parseResult(e,r)}_baseMessageToString(e){return"string"==typeof e.content?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return"string"==typeof e?this._callWithConfig((async(e,t)=>this.parseResult([{text:e}],t?.callbacks)),e,{...t,runType:"parser"}):this._callWithConfig((async(e,t)=>this.parseResult([{message:e,text:this._baseMessageToString(e)}],t?.callbacks)),e,{...t,runType:"parser"})}}class Yt extends Zt{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 Xt extends Error{constructor(e,t,r,n=!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=n,n&&(void 0===r||void 0===t))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");(0,Jt.Y)(this,"OUTPUT_PARSING_FAILURE")}}function Qt(e,t){const r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;const r=e.length;if(r!==t.length)return!1;for(let n=0;n1?t[a.href]=e:(a.hash="",""===n?r=a:ar(e,t,r))}}else if(!0!==e&&!1!==e)return t;const s=r.href+(n?"#"+n:"");if(void 0!==t[s])throw new Error(`Duplicate schema URI "${s}".`);if(t[s]=e,!0===e||!1===e)return t;if(void 0===e.__absolute_uri__&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:s}),e.$ref&&void 0===e.__absolute_ref__){const t=new URL(e.$ref,r.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&void 0===e.__absolute_recursive_ref__){const t=new URL(e.$recursiveRef,r.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){t[new URL("#"+e.$anchor,r.href).href]=e}for(let s in e){if(nr[s])continue;const a=`${n}/${er(s)}`,i=e[s];if(Array.isArray(i)){if(tr[s]){const e=i.length;for(let n=0;ne.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),uri:function(e){return mr.test(e)&&fr.test(e)},"uri-reference":lr(/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i),"uri-template":lr(/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i),url:lr(/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu),email:e=>{if('"'===e[0])return!1;const[t,r,...n]=e.split("@");return!(!t||!r||0!==n.length||t.length>64||r.length>253)&&("."!==t[0]&&!t.endsWith(".")&&!t.includes("..")&&(!(!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t))&&r.split(".").every((e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e)))))},hostname:lr(/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i),ipv4:lr(/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/),ipv6:lr(/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i),regex:function(e){if(gr.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(e){return!1}},uuid:lr(/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i),"json-pointer":lr(/^(?:\/(?:[^~/]|~0|~1)*)*$/),"json-pointer-uri-fragment":lr(/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i),"relative-json-pointer":lr(/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/)};function dr(e){const t=e.match(ir);if(!t)return!1;const r=+t[1],n=+t[2],s=+t[3];return n>=1&&n<=12&&s>=1&&s<=(2==n&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(r)?29:or[n])}function hr(e,t){const r=t.match(cr);if(!r)return!1;const n=+r[1],s=+r[2],a=+r[3],i=!!r[5];return(n<=23&&s<=59&&a<=59||23==n&&59==s&&60==a)&&(!e||i)}const pr=/t|\s/i;const mr=/\/|:/,fr=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;const gr=/[^\\]\\Z/;var yr;function br(e,t,r="2019-09",n=ar(t),s=!0,a=null,i="#",o="#",c=Object.create(null)){if(!0===t)return{valid:!0,errors:[]};if(!1===t)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};const l=typeof e;let u;switch(l){case"boolean":case"number":case"string":u=l;break;case"object":u=null===e?"null":Array.isArray(e)?"array":"object";break;default:throw new Error(`Instances of "${l}" type are not supported.`)}const{$ref:d,$recursiveRef:h,$recursiveAnchor:p,type:m,const:f,enum:g,required:y,not:b,anyOf:w,allOf:v,oneOf:_,if:k,then:S,else:E,format:x,properties:T,patternProperties:C,additionalProperties:P,unevaluatedProperties:O,minProperties:A,maxProperties:I,propertyNames:M,dependentRequired:R,dependentSchemas:j,dependencies:N,prefixItems:$,items:L,additionalItems:F,unevaluatedItems:D,contains:z,minContains:U,maxContains:B,minItems:q,maxItems:K,uniqueItems:W,minimum:H,maximum:V,exclusiveMinimum:G,exclusiveMaximum:J,multipleOf:Z,minLength:Y,maxLength:X,pattern:Q,__absolute_ref__:ee,__absolute_recursive_ref__:te}=t,re=[];if(!0===p&&null===a&&(a=t),"#"===h){const l=null===a?n[te]:a,u=`${o}/$recursiveRef`,d=br(e,null===a?t:a,r,n,s,l,i,u,c);d.valid||re.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:u,error:"A subschema had errors."},...d.errors)}if(void 0!==d){const t=n[ee||d];if(void 0===t){let e=`Unresolved $ref "${d}".`;throw ee&&ee!==d&&(e+=` Absolute URI "${ee}".`),e+=`\nKnown schemas:\n- ${Object.keys(n).join("\n- ")}`,new Error(e)}const l=`${o}/$ref`,u=br(e,t,r,n,s,a,i,l,c);if(u.valid||re.push({instanceLocation:i,keyword:"$ref",keywordLocation:l,error:"A subschema had errors."},...u.errors),"4"===r||"7"===r)return{valid:0===re.length,errors:re}}if(Array.isArray(m)){let t=m.length,r=!1;for(let n=0;nQt(e,t)))||re.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some((t=>e===t))||re.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),void 0!==b){const t=`${o}/not`;br(e,b,r,n,s,a,i,t).valid&&re.push({instanceLocation:i,keyword:"not",keywordLocation:t,error:'Instance matched "not" schema.'})}let ne=[];if(void 0!==w){const t=`${o}/anyOf`,l=re.length;let u=!1;for(let o=0;o{const u=Object.create(c),d=br(e,o,r,n,s,!0===p?a:null,i,`${t}/${l}`,u);return re.push(...d.errors),d.valid&&ne.push(u),d.valid})).length;1===u?re.length=l:re.splice(l,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if("object"!==u&&"array"!==u||Object.assign(c,...ne),void 0!==k){const t=`${o}/if`;if(br(e,k,r,n,s,a,i,t,c).valid){if(void 0!==S){const l=br(e,S,r,n,s,a,i,`${o}/then`,c);l.valid||re.push({instanceLocation:i,keyword:"if",keywordLocation:t,error:'Instance does not match "then" schema.'},...l.errors)}}else if(void 0!==E){const l=br(e,E,r,n,s,a,i,`${o}/else`,c);l.valid||re.push({instanceLocation:i,keyword:"if",keywordLocation:t,error:'Instance does not match "else" schema.'},...l.errors)}}if("object"===u){if(void 0!==y)for(const t of y)t in e||re.push({instanceLocation:i,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${t}".`});const t=Object.keys(e);if(void 0!==A&&t.lengthI&&re.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${I} properties.`}),void 0!==M){const t=`${o}/propertyNames`;for(const o in e){const e=`${i}/${er(o)}`,c=br(o,M,r,n,s,a,e,t);c.valid||re.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:t,error:`Property name "${o}" does not match schema.`},...c.errors)}}if(void 0!==R){const t=`${o}/dependantRequired`;for(const r in R)if(r in e){const n=R[r];for(const s of n)s in e||re.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:t,error:`Instance has "${r}" but does not have "${s}".`})}}if(void 0!==j)for(const t in j){const l=`${o}/dependentSchemas`;if(t in e){const o=br(e,j[t],r,n,s,a,i,`${l}/${er(t)}`,c);o.valid||re.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...o.errors)}}if(void 0!==N){const t=`${o}/dependencies`;for(const o in N)if(o in e){const c=N[o];if(Array.isArray(c))for(const r of c)r in e||re.push({instanceLocation:i,keyword:"dependencies",keywordLocation:t,error:`Instance has "${o}" but does not have "${r}".`});else{const l=br(e,c,r,n,s,a,i,`${t}/${er(o)}`);l.valid||re.push({instanceLocation:i,keyword:"dependencies",keywordLocation:t,error:`Instance has "${o}" but does not match dependant schema.`},...l.errors)}}}const l=Object.create(null);let u=!1;if(void 0!==T){const t=`${o}/properties`;for(const o in T){if(!(o in e))continue;const d=`${i}/${er(o)}`,h=br(e[o],T[o],r,n,s,a,d,`${t}/${er(o)}`);if(h.valid)c[o]=l[o]=!0;else if(u=s,re.push({instanceLocation:i,keyword:"properties",keywordLocation:t,error:`Property "${o}" does not match schema.`},...h.errors),u)break}}if(!u&&void 0!==C){const t=`${o}/patternProperties`;for(const o in C){const d=new RegExp(o,"u"),h=C[o];for(const p in e){if(!d.test(p))continue;const m=`${i}/${er(p)}`,f=br(e[p],h,r,n,s,a,m,`${t}/${er(o)}`);f.valid?c[p]=l[p]=!0:(u=s,re.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:t,error:`Property "${p}" matches pattern "${o}" but does not match associated schema.`},...f.errors))}}}if(u||void 0===P){if(!u&&void 0!==O){const t=`${o}/unevaluatedProperties`;for(const o in e)if(!c[o]){const l=`${i}/${er(o)}`,u=br(e[o],O,r,n,s,a,l,t);u.valid?c[o]=!0:re.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:t,error:`Property "${o}" does not match unevaluated properties schema.`},...u.errors)}}}else{const t=`${o}/additionalProperties`;for(const o in e){if(l[o])continue;const d=`${i}/${er(o)}`,h=br(e[o],P,r,n,s,a,d,t);h.valid?c[o]=!0:(u=s,re.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:t,error:`Property "${o}" does not match additional properties schema.`},...h.errors))}}}else if("array"===u){void 0!==K&&e.length>K&&re.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${e.length} > ${K}).`}),void 0!==q&&e.length=(U||0)&&(re.length=u),void 0===U&&void 0===B&&0===d?re.splice(u,0,{instanceLocation:i,keyword:"contains",keywordLocation:l,error:"Array does not contain item matching schema."}):void 0!==U&&dB&&re.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${B} items matching schema. ${d} items were found.`})}if(!u&&void 0!==D){const u=`${o}/unevaluatedItems`;for(;l=V||e>V)&&re.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${J?"or equal to ":""} ${V}.`})):(void 0!==H&&eV&&re.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${V}.`}),void 0!==G&&e<=G&&re.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${e} is less than ${G}.`}),void 0!==J&&e>=J&&re.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${e} is greater than or equal to ${J}.`})),void 0!==Z){const t=e%Z;Math.abs(0-t)>=1.1920929e-7&&Math.abs(Z-t)>=1.1920929e-7&&re.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${e} is not a multiple of ${Z}.`})}}else if("string"===u){const t=void 0===Y&&void 0===X?0:function(e){let t,r=0,n=e.length,s=0;for(;s=55296&&t<=56319&&sX&&re.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${t} > ${X}).`}),void 0===Q||new RegExp(Q,"u").test(e)||re.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),void 0!==x&&ur[x]&&!ur[x](e)&&re.push({instanceLocation:i,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${x}".`})}return{valid:0===re.length,errors:re}}!function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"}(yr||(yr={}));class wr{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=ar(e)}validate(e){return br(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),ar(e,this.lookup)}}var vr=s(3490);class _r extends Yt{async*_transform(e){for await(const t of e)"string"==typeof t?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 kr extends _r{constructor(e){super(e),Object.defineProperty(this,"diff",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.diff=e?.diff??this.diff}async*_transform(e){let t,r;for await(const n of e){if("string"!=typeof n&&"string"!=typeof n.content)throw new Error("Cannot handle non-string output.");let e;if((0,vr.AJ)(n)){if("string"!=typeof n.content)throw new Error("Cannot handle non-string message output.");e=new $t.ChatGenerationChunk({message:n,text:n.content})}else if((0,vr.ny)(n)){if("string"!=typeof n.content)throw new Error("Cannot handle non-string message output.");e=new $t.ChatGenerationChunk({message:(0,qe.ih)(n),text:n.content})}else e=new $t.GenerationChunk({text:n});r=void 0===r?e:r.concat(e);const s=await this.parsePartialResult([r]);null==s||Qt(s,t)||(this.diff?yield this._diff(t,s):yield s,t=s)}}getFormatInstructions(){return""}}class Sr extends _r{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","bytes"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"textEncoder",{enumerable:!0,configurable:!0,writable:!0,value:new TextEncoder})}static lc_name(){return"BytesOutputParser"}parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}}class Er extends _r{constructor(){super(...arguments),Object.defineProperty(this,"re",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async*_transform(e){let t="";for await(const r of e)if(t+="string"==typeof r?r:r.content,this.re){const e=[...t.matchAll(this.re)];if(e.length>1){let r=0;for(const t of e.slice(0,-1))yield[t[1]],r+=(t.index??0)+t[0].length;t=t.slice(r)}}else{const e=await this.parse(t);if(e.length>1){for(const t of e.slice(0,-1))yield[t];t=e[e.length-1]}}for(const e of await this.parse(t))yield[e]}}class xr extends Er{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","list"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"CommaSeparatedListOutputParser"}async parse(e){try{return e.trim().split(",").map((e=>e.trim()))}catch(t){throw new Xt(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}}class Tr extends Er{constructor({length:e,separator:t}){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","list"]}),Object.defineProperty(this,"length",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"separator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.length=e,this.separator=t||","}async parse(e){try{const t=e.trim().split(this.separator).map((e=>e.trim()));if(void 0!==this.length&&t.length!==this.length)throw new Xt(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){if(Object.getPrototypeOf(t)===Xt.prototype)throw t;throw new Xt(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${void 0===this.length?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}}class Cr extends Er{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","list"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"re",{enumerable:!0,configurable:!0,writable:!0,value:/\d+\.\s([^\n]+)/g})}static lc_name(){return"NumberedListOutputParser"}getFormatInstructions(){return"Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz"}async parse(e){return[...e.matchAll(this.re)??[]].map((e=>e[1]))}}class Pr extends Er{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","list"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"re",{enumerable:!0,configurable:!0,writable:!0,value:/^\s*[-*]\s([^\n]+)$/gm})}static lc_name(){return"NumberedListOutputParser"}getFormatInstructions(){return"Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz"}async parse(e){return[...e.matchAll(this.re)??[]].map((e=>e[1]))}}class Or extends _r{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","string"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"StrOutputParser"}parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentComplexToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce(((e,t)=>e+this._messageContentComplexToString(t)),"")}}class Ar extends Yt{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){return new this(M.z.object(Object.fromEntries(Object.entries(e).map((([e,t])=>[e,M.z.string().describe(t)])))))}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.\n\n"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.\n\nFor example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}\nwould 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.\nThus, 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.\n\nYour 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!\n\nHere is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:\n\`\`\`json\n${JSON.stringify((0,Nt.Ik)(this.schema))}\n\`\`\`\n`}async parse(e){try{const t=(e.includes("```")?e.trim().split(/```(?:json)?/)[1]:e.trim()).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,((e,t)=>`"${t.replace(/\n/g,"\\n")}"`)).replace(/\n/g,"");return await this.schema.parseAsync(JSON.parse(t))}catch(t){throw new Xt(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}}class Ir extends Ar{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(e){const t=e?.interpolationDepth??1;if(t<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:\n\`\`\`json\n${this._schemaToInstruction((0,Nt.Ik)(this.schema)).replaceAll("{","{".repeat(t)).replaceAll("}","}".repeat(t))}\n\`\`\``}_schemaToInstruction(e,t=2){const r=e;if("type"in r){let e,n=!1;if(Array.isArray(r.type)){const t=r.type.findIndex((e=>"null"===e));-1!==t&&(n=!0,r.type.splice(t,1)),e=r.type.join(" | ")}else e=r.type;if("object"===r.type&&r.properties){const e=r.description?` // ${r.description}`:"",n=Object.entries(r.properties).map((([e,n])=>{const s=r.required?.includes(e)?"":" (optional)";return`${" ".repeat(t)}"${e}": ${this._schemaToInstruction(n,t+2)}${s}`})).join("\n");return`{\n${n}\n${" ".repeat(t-2)}}${e}`}if("array"===r.type&&r.items){const e=r.description?` // ${r.description}`:"";return`array[\n${" ".repeat(t)}${this._schemaToInstruction(r.items,t+2)}\n${" ".repeat(t-2)}] ${e}`}const s=n?" (nullable)":"";return`${e}${r.description?` // ${r.description}`:""}${s}`}if("anyOf"in r)return r.anyOf.map((e=>this._schemaToInstruction(e,t))).join(`\n${" ".repeat(t-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){return new this(M.z.object(Object.fromEntries(Object.entries(e).map((([e,t])=>[e,M.z.string().describe(t)])))))}}class Mr extends Yt{constructor({inputSchema:e}){super(...arguments),Object.defineProperty(this,"structuredInputParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.structuredInputParser=new Ir(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(t){throw new Xt(`Failed to parse. Text: "${e}". Error: ${t}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}}var Rr=s(6150),jr=s(780);class Nr extends kr{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"}_diff(e,t){if(t)return e?(0,Rr.UD)(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return(0,jr.D)(e[0].text)}async parse(e){return(0,jr.D)(e,JSON.parse)}getFormatInstructions(){return""}}const $r=function(){const e={parser:function(e,t){return new r(e,t)}};e.SAXParser=r,e.SAXStream=a,e.createStream=function(e,t){return new a(e,t)},e.MAX_BUFFER_LENGTH=65536;const t=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];function r(n,s){if(!(this instanceof r))return new r(n,s);var a=this;!function(e){for(var r=0,n=t.length;r"===a?(T(n,"onsgmldeclaration",n.sgmlDecl),n.sgmlDecl="",n.state=S.TEXT):g(a)?(n.state=S.SGML_DECL_QUOTED,n.sgmlDecl+=a):n.sgmlDecl+=a;continue;case S.SGML_DECL_QUOTED:a===n.q&&(n.state=S.SGML_DECL,n.q=""),n.sgmlDecl+=a;continue;case S.DOCTYPE:">"===a?(n.state=S.TEXT,T(n,"ondoctype",n.doctype),n.doctype=!0):(n.doctype+=a,"["===a?n.state=S.DOCTYPE_DTD:g(a)&&(n.state=S.DOCTYPE_QUOTED,n.q=a));continue;case S.DOCTYPE_QUOTED:n.doctype+=a,a===n.q&&(n.q="",n.state=S.DOCTYPE);continue;case S.DOCTYPE_DTD:n.doctype+=a,"]"===a?n.state=S.DOCTYPE:g(a)&&(n.state=S.DOCTYPE_DTD_QUOTED,n.q=a);continue;case S.DOCTYPE_DTD_QUOTED:n.doctype+=a,a===n.q&&(n.state=S.DOCTYPE_DTD,n.q="");continue;case S.COMMENT:"-"===a?n.state=S.COMMENT_ENDING:n.comment+=a;continue;case S.COMMENT_ENDING:"-"===a?(n.state=S.COMMENT_ENDED,n.comment=P(n.opt,n.comment),n.comment&&T(n,"oncomment",n.comment),n.comment=""):(n.comment+="-"+a,n.state=S.COMMENT);continue;case S.COMMENT_ENDED:">"!==a?(I(n,"Malformed comment"),n.comment+="--"+a,n.state=S.COMMENT):n.state=S.TEXT;continue;case S.CDATA:"]"===a?n.state=S.CDATA_ENDING:n.cdata+=a;continue;case S.CDATA_ENDING:"]"===a?n.state=S.CDATA_ENDING_2:(n.cdata+="]"+a,n.state=S.CDATA);continue;case S.CDATA_ENDING_2:">"===a?(n.cdata&&T(n,"oncdata",n.cdata),T(n,"onclosecdata"),n.cdata="",n.state=S.TEXT):"]"===a?n.cdata+="]":(n.cdata+="]]"+a,n.state=S.CDATA);continue;case S.PROC_INST:"?"===a?n.state=S.PROC_INST_ENDING:f(a)?n.state=S.PROC_INST_BODY:n.procInstName+=a;continue;case S.PROC_INST_BODY:if(!n.procInstBody&&f(a))continue;"?"===a?n.state=S.PROC_INST_ENDING:n.procInstBody+=a;continue;case S.PROC_INST_ENDING:">"===a?(T(n,"onprocessinginstruction",{name:n.procInstName,body:n.procInstBody}),n.procInstName=n.procInstBody="",n.state=S.TEXT):(n.procInstBody+="?"+a,n.state=S.PROC_INST_BODY);continue;case S.OPEN_TAG:b(h,a)?n.tagName+=a:(M(n),">"===a?N(n):"/"===a?n.state=S.OPEN_TAG_SLASH:(f(a)||I(n,"Invalid character in tag name"),n.state=S.ATTRIB));continue;case S.OPEN_TAG_SLASH:">"===a?(N(n,!0),$(n)):(I(n,"Forward-slash in opening tag not followed by >"),n.state=S.ATTRIB);continue;case S.ATTRIB:if(f(a))continue;">"===a?N(n):"/"===a?n.state=S.OPEN_TAG_SLASH:b(d,a)?(n.attribName=a,n.attribValue="",n.state=S.ATTRIB_NAME):I(n,"Invalid attribute name");continue;case S.ATTRIB_NAME:"="===a?n.state=S.ATTRIB_VALUE:">"===a?(I(n,"Attribute without value"),n.attribValue=n.attribName,j(n),N(n)):f(a)?n.state=S.ATTRIB_NAME_SAW_WHITE:b(h,a)?n.attribName+=a:I(n,"Invalid attribute name");continue;case S.ATTRIB_NAME_SAW_WHITE:if("="===a)n.state=S.ATTRIB_VALUE;else{if(f(a))continue;I(n,"Attribute without value"),n.tag.attributes[n.attribName]="",n.attribValue="",T(n,"onattribute",{name:n.attribName,value:""}),n.attribName="",">"===a?N(n):b(d,a)?(n.attribName=a,n.state=S.ATTRIB_NAME):(I(n,"Invalid attribute name"),n.state=S.ATTRIB)}continue;case S.ATTRIB_VALUE:if(f(a))continue;g(a)?(n.q=a,n.state=S.ATTRIB_VALUE_QUOTED):(I(n,"Unquoted attribute value"),n.state=S.ATTRIB_VALUE_UNQUOTED,n.attribValue=a);continue;case S.ATTRIB_VALUE_QUOTED:if(a!==n.q){"&"===a?n.state=S.ATTRIB_VALUE_ENTITY_Q:n.attribValue+=a;continue}j(n),n.q="",n.state=S.ATTRIB_VALUE_CLOSED;continue;case S.ATTRIB_VALUE_CLOSED:f(a)?n.state=S.ATTRIB:">"===a?N(n):"/"===a?n.state=S.OPEN_TAG_SLASH:b(d,a)?(I(n,"No whitespace between attributes"),n.attribName=a,n.attribValue="",n.state=S.ATTRIB_NAME):I(n,"Invalid attribute name");continue;case S.ATTRIB_VALUE_UNQUOTED:if(!y(a)){"&"===a?n.state=S.ATTRIB_VALUE_ENTITY_U:n.attribValue+=a;continue}j(n),">"===a?N(n):n.state=S.ATTRIB;continue;case S.CLOSE_TAG:if(n.tagName)">"===a?$(n):b(h,a)?n.tagName+=a:n.script?(n.script+=""===a?$(n):I(n,"Invalid characters in closing tag");continue;case S.TEXT_ENTITY:case S.ATTRIB_VALUE_ENTITY_Q:case S.ATTRIB_VALUE_ENTITY_U:var u,v;switch(n.state){case S.TEXT_ENTITY:u=S.TEXT,v="textNode";break;case S.ATTRIB_VALUE_ENTITY_Q:u=S.ATTRIB_VALUE_QUOTED,v="attribValue";break;case S.ATTRIB_VALUE_ENTITY_U:u=S.ATTRIB_VALUE_UNQUOTED,v="attribValue"}if(";"===a)if(n.opt.unparsedEntities){var _=L(n);n.entity="",n.state=u,n.write(_)}else n[v]+=L(n),n.entity="",n.state=u;else b(n.entity.length?m:p,a)?n.entity+=a:(I(n,"Invalid character in entity name"),n[v]+="&"+n.entity+a,n.entity="",n.state=u);continue;default:throw new Error(n,"Unknown state: "+n.state)}n.position>=n.bufferCheckPosition&&function(r){for(var n=Math.max(e.MAX_BUFFER_LENGTH,10),s=0,a=0,i=t.length;an)switch(t[a]){case"textNode":C(r);break;case"cdata":T(r,"oncdata",r.cdata),r.cdata="";break;case"script":T(r,"onscript",r.script),r.script="";break;default:O(r,"Max buffer length exceeded: "+t[a])}s=Math.max(s,o)}var c=e.MAX_BUFFER_LENGTH-s;r.bufferCheckPosition=c+r.position}(n);return n},resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){var e;C(e=this),""!==e.cdata&&(T(e,"oncdata",e.cdata),e.cdata=""),""!==e.script&&(T(e,"onscript",e.script),e.script="")}};var n=ReadableStream;n||(n=function(){});var s=e.EVENTS.filter((function(e){return"error"!==e&&"end"!==e}));function a(e,t){if(!(this instanceof a))return new a(e,t);n.apply(this),this._parser=new r(e,t),this.writable=!0,this.readable=!0;var i=this;this._parser.onend=function(){i.emit("end")},this._parser.onerror=function(e){i.emit("error",e),i._parser.error=null},this._decoder=null,s.forEach((function(e){Object.defineProperty(i,"on"+e,{get:function(){return i._parser["on"+e]},set:function(t){if(!t)return i.removeAllListeners(e),i._parser["on"+e]=t,t;i.on(e,t)},enumerable:!0,configurable:!1})}))}a.prototype=Object.create(n.prototype,{constructor:{value:a}}),a.prototype.write=function(e){return this._parser.write(e.toString()),this.emit("data",e),!0},a.prototype.end=function(e){return e&&e.length&&this.write(e),this._parser.end(),!0},a.prototype.on=function(e,t){var r=this;return r._parser["on"+e]||-1===s.indexOf(e)||(r._parser["on"+e]=function(){var t=1===arguments.length?[arguments[0]]:Array.apply(null,arguments);t.splice(0,0,e),r.emit.apply(r,t)}),n.prototype.on.call(r,e,t)};var i="[CDATA[",o="DOCTYPE",c="http://www.w3.org/XML/1998/namespace",l="http://www.w3.org/2000/xmlns/",u={xml:c,xmlns:l},d=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,h=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,p=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,m=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function f(e){return" "===e||"\n"===e||"\r"===e||"\t"===e}function g(e){return'"'===e||"'"===e}function y(e){return">"===e||f(e)}function b(e,t){return e.test(t)}function w(e,t){return!b(e,t)}var v,_,k,S=0;for(var E in e.STATE={BEGIN:S++,BEGIN_WHITESPACE:S++,TEXT:S++,TEXT_ENTITY:S++,OPEN_WAKA:S++,SGML_DECL:S++,SGML_DECL_QUOTED:S++,DOCTYPE:S++,DOCTYPE_QUOTED:S++,DOCTYPE_DTD:S++,DOCTYPE_DTD_QUOTED:S++,COMMENT_STARTING:S++,COMMENT:S++,COMMENT_ENDING:S++,COMMENT_ENDED:S++,CDATA:S++,CDATA_ENDING:S++,CDATA_ENDING_2:S++,PROC_INST:S++,PROC_INST_BODY:S++,PROC_INST_ENDING:S++,OPEN_TAG:S++,OPEN_TAG_SLASH:S++,ATTRIB:S++,ATTRIB_NAME:S++,ATTRIB_NAME_SAW_WHITE:S++,ATTRIB_VALUE:S++,ATTRIB_VALUE_QUOTED:S++,ATTRIB_VALUE_CLOSED:S++,ATTRIB_VALUE_UNQUOTED:S++,ATTRIB_VALUE_ENTITY_Q:S++,ATTRIB_VALUE_ENTITY_U:S++,CLOSE_TAG:S++,CLOSE_TAG_SAW_WHITE:S++,SCRIPT:S++,SCRIPT_ENDING:S++},e.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},e.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(e.ENTITIES).forEach((function(t){var r=e.ENTITIES[t],n="number"==typeof r?String.fromCharCode(r):r;e.ENTITIES[t]=n})),e.STATE)e.STATE[e.STATE[E]]=E;function x(e,t,r){e[t]&&e[t](r)}function T(e,t,r){e.textNode&&C(e),x(e,t,r)}function C(e){e.textNode=P(e.opt,e.textNode),e.textNode&&x(e,"ontext",e.textNode),e.textNode=""}function P(e,t){return e.trim&&(t=t.trim()),e.normalize&&(t=t.replace(/\s+/g," ")),t}function O(e,t){return C(e),e.trackPosition&&(t+="\nLine: "+e.line+"\nColumn: "+e.column+"\nChar: "+e.c),t=new Error(t),e.error=t,x(e,"onerror",t),e}function A(e){return e.sawRoot&&!e.closedRoot&&I(e,"Unclosed root tag"),e.state!==S.BEGIN&&e.state!==S.BEGIN_WHITESPACE&&e.state!==S.TEXT&&O(e,"Unexpected end"),C(e),e.c="",e.closed=!0,x(e,"onend"),r.call(e,e.strict,e.opt),e}function I(e,t){if("object"!=typeof e||!(e instanceof r))throw new Error("bad call to strictFail");e.strict&&O(e,t)}function M(e){e.strict||(e.tagName=e.tagName[e.looseCase]());var t=e.tags[e.tags.length-1]||e,r=e.tag={name:e.tagName,attributes:{}};e.opt.xmlns&&(r.ns=t.ns),e.attribList.length=0,T(e,"onopentagstart",r)}function R(e,t){var r=e.indexOf(":")<0?["",e]:e.split(":"),n=r[0],s=r[1];return t&&"xmlns"===e&&(n="xmlns",s=""),{prefix:n,local:s}}function j(e){if(e.strict||(e.attribName=e.attribName[e.looseCase]()),-1!==e.attribList.indexOf(e.attribName)||e.tag.attributes.hasOwnProperty(e.attribName))e.attribName=e.attribValue="";else{if(e.opt.xmlns){var t=R(e.attribName,!0),r=t.prefix,n=t.local;if("xmlns"===r)if("xml"===n&&e.attribValue!==c)I(e,"xml: prefix must be bound to "+c+"\nActual: "+e.attribValue);else if("xmlns"===n&&e.attribValue!==l)I(e,"xmlns: prefix must be bound to "+l+"\nActual: "+e.attribValue);else{var s=e.tag,a=e.tags[e.tags.length-1]||e;s.ns===a.ns&&(s.ns=Object.create(a.ns)),s.ns[n]=e.attribValue}e.attribList.push([e.attribName,e.attribValue])}else e.tag.attributes[e.attribName]=e.attribValue,T(e,"onattribute",{name:e.attribName,value:e.attribValue});e.attribName=e.attribValue=""}}function N(e,t){if(e.opt.xmlns){var r=e.tag,n=R(e.tagName);r.prefix=n.prefix,r.local=n.local,r.uri=r.ns[n.prefix]||"",r.prefix&&!r.uri&&(I(e,"Unbound namespace prefix: "+JSON.stringify(e.tagName)),r.uri=n.prefix);var s=e.tags[e.tags.length-1]||e;r.ns&&s.ns!==r.ns&&Object.keys(r.ns).forEach((function(t){T(e,"onopennamespace",{prefix:t,uri:r.ns[t]})}));for(var a=0,i=e.attribList.length;a",e.tagName="",void(e.state=S.SCRIPT);T(e,"onscript",e.script),e.script=""}var t=e.tags.length,r=e.tagName;e.strict||(r=r[e.looseCase]());for(var n=r;t--;){if(e.tags[t].name===n)break;I(e,"Unexpected close tag")}if(t<0)return I(e,"Unmatched closing tag: "+e.tagName),e.textNode+="",void(e.state=S.TEXT);e.tagName=r;for(var s=e.tags.length;s-- >t;){var a=e.tag=e.tags.pop();e.tagName=e.tag.name,T(e,"onclosetag",e.tagName);var i={};for(var o in a.ns)i[o]=a.ns[o];var c=e.tags[e.tags.length-1]||e;e.opt.xmlns&&a.ns!==c.ns&&Object.keys(a.ns).forEach((function(t){var r=a.ns[t];T(e,"onclosenamespace",{prefix:t,uri:r})}))}0===t&&(e.closedRoot=!0),e.tagName=e.attribValue=e.attribName="",e.attribList.length=0,e.state=S.TEXT}function L(e){var t,r=e.entity,n=r.toLowerCase(),s="";return e.ENTITIES[r]?e.ENTITIES[r]:e.ENTITIES[n]?e.ENTITIES[n]:("#"===(r=n).charAt(0)&&("x"===r.charAt(1)?(r=r.slice(2),s=(t=parseInt(r,16)).toString(16)):(r=r.slice(1),s=(t=parseInt(r,10)).toString(10))),r=r.replace(/^0+/,""),isNaN(t)||s.toLowerCase()!==r?(I(e,"Invalid character entity"),"&"+e.entity+";"):String.fromCodePoint(t))}function F(e,t){"<"===t?(e.state=S.OPEN_WAKA,e.startTagPosition=e.position):f(t)||(I(e,"Non-whitespace before first tag."),e.textNode=t,e.state=S.TEXT)}function D(e,t){var r="";return t1114111||_(i)!==i)throw RangeError("Invalid code point: "+i);i<=65535?r.push(i):(e=55296+((i-=65536)>>10),t=i%1024+56320,r.push(e,t)),(n+1===s||r.length>16384)&&(a+=v.apply(null,r),r.length=0)}return a},Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:k,configurable:!0,writable:!0}):String.fromCodePoint=k),e},Lr=$r(),Fr='The output should be formatted as a XML file.\n1. Output should conform to the tags below. \n2. If tags are not given, make them on your own.\n3. Remember to always open and close all the tags.\n\nAs an example, for the tags ["foo", "bar", "baz"]:\n1. String "\n \n \n \n" is a well-formatted instance of the schema. \n2. String "\n \n " is a badly-formatted instance.\n3. String "\n \n \n" is a badly-formatted instance.\n\nHere are the output tags:\n```\n{tags}\n```';class Dr extends kr{constructor(e){super(e),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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}),this.tags=e?.tags}static lc_name(){return"XMLOutputParser"}_diff(e,t){if(t)return e?(0,Rr.UD)(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return Br(e[0].text)}async parse(e){return Br(e)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?Fr.replace("{tags}",this.tags?.join(", ")??""):Fr}}const zr=e=>e.split("\n").map((e=>e.replace(/^\s+/,""))).join("\n").trim(),Ur=e=>{if(0===Object.keys(e).length)return{};const t={};return e.children.length>0?(t[e.name]=e.children.map(Ur),t):(t[e.name]=e.text??void 0,t)};function Br(e){const t=zr(e),r=Lr.parser(!0);let n={};const s=[];r.onopentag=e=>{const t={name:e.name,attributes:e.attributes,children:[],text:"",isSelfClosing:e.isSelfClosing};if(s.length>0){s[s.length-1].children.push(t)}else n=t;e.isSelfClosing||s.push(t)},r.onclosetag=()=>{if(s.length>0){const e=s.pop();0===s.length&&e&&(n=e)}},r.ontext=e=>{if(s.length>0){s[s.length-1].text+=e}},r.onattribute=e=>{if(s.length>0){s[s.length-1].attributes[e.name]=e.value}};const a=/```(xml)?(.*)```/s.exec(t),i=a?a[2]:t;return r.write(i).close(),n&&"?xml"===n.name&&(n=n.children[0]),Ur(n)}var qr=s(6993),Kr=s(3766),Wr=s(2771);class Hr extends qr.m{static lc_name(){return"PipelinePromptTemplate"}constructor(e){super({...e,inputVariables:[]}),Object.defineProperty(this,"pipelinePrompts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"finalPrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.pipelinePrompts=e.pipelinePrompts,this.finalPrompt=e.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){const e=this.pipelinePrompts.map((e=>e.name)),t=this.pipelinePrompts.map((t=>t.prompt.inputVariables.filter((t=>!e.includes(t))))).flat();return[...new Set(t)]}static extractRequiredInputValues(e,t){return t.reduce(((t,r)=>(t[r]=e[r],t)),{})}async formatPipelinePrompts(e){const t=await this.mergePartialAndUserVariables(e);for(const{name:e,prompt:r}of this.pipelinePrompts){const n=Hr.extractRequiredInputValues(t,r.inputVariables);r instanceof Kr.RZ?t[e]=await r.formatMessages(n):t[e]=await r.format(n)}return Hr.extractRequiredInputValues(t,this.finalPrompt.inputVariables)}async formatPromptValue(e){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(e))}async format(e){return this.finalPrompt.format(await this.formatPipelinePrompts(e))}async partial(e){const t={...this};return t.inputVariables=this.inputVariables.filter((t=>!(t in e))),t.partialVariables={...this.partialVariables??{},...e},new Hr(t)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}}var Vr=s(3650),Gr=s(329),Jr=s(9849),Zr=s(6279);function Yr(e){return"object"==typeof e&&null!=e&&"withStructuredOutput"in e&&"function"==typeof e.withStructuredOutput}class Xr extends Kr.RZ{get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"method",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","structured"]}),this.schema=e.schema,this.method=e.method}pipe(e){if(Yr(e))return super.pipe(e.withStructuredOutput(this.schema));if("object"==typeof(t=e)&&null!=t&&"lc_id"in t&&Array.isArray(t.lc_id)&&"langchain_core/runnables/RunnableBinding"===t.lc_id.join("/")&&Yr(e.bound))return super.pipe(this.method?e.bound.withStructuredOutput(this.schema,{method:this.method}).bind(e.kwargs??{}).withConfig(e.config):e.bound.withStructuredOutput(this.schema).bind(e.kwargs??{}).withConfig(e.config));var t;throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(e,t,r){return Xr.fromMessages(e,{schema:t,method:r})}}var Qr=s(4552);class en extends X.YN{constructor(e){super(e),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}),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw new Error("Not implemented!")}async invoke(e,t){return this.getRelevantDocuments(e,(0,Q.ZI)(t))}async getRelevantDocuments(e,t){const r=(0,Q.ZI)((0,Ye.parseCallbackConfigArg)(t)),n=await Ye.CallbackManager.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}),s=await(n?.handleRetrieverStart(this.toJSON(),e,r.runId,void 0,void 0,void 0,r.runName));try{const t=await this._getRelevantDocuments(e,s);return await(s?.handleRetrieverEnd(t)),t}catch(e){throw await(s?.handleRetrieverError(e)),e}}}class tn extends Ne.Serializable{}class rn extends tn{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","storage"]}),Object.defineProperty(this,"store",{enumerable:!0,configurable:!0,writable:!0,value:{}})}async mget(e){return e.map((e=>this.store[e]))}async mset(e){for(const[t,r]of e)this.store[t]=r}async mdelete(e){for(const t of e)delete this.store[t]}async*yieldKeys(e){const t=Object.keys(this.store);for(const r of t)(void 0===e||r.startsWith(e))&&(yield r)}}var nn=s(8009),sn=s(4350),an=s(199);function on(e){return Lt(e)?(0,Nt.Ik)(e):e}function cn(e){if(!e||"object"!=typeof e||0===Object.keys(e).length||Array.isArray(e))return!1;if("type"in e)return"string"==typeof e.type?"string"===e.type:!!Array.isArray(e.type)&&e.type.every((e=>"string"===e));if("enum"in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every((e=>"string"==typeof e));if("const"in e)return"string"==typeof e.const;if("allOf"in e&&Array.isArray(e.allOf))return e.allOf.some((e=>cn(e)));if("anyOf"in e&&Array.isArray(e.anyOf)||"oneOf"in e&&Array.isArray(e.oneOf)){const t="anyOf"in e?e.anyOf:e.oneOf;return t.length>0&&t.every((e=>cn(e)))}if("not"in e)return!1;if("$ref"in e&&"string"==typeof e.$ref){const t=e.$ref,r=ar(e);return!!r[t]&&cn(r[t])}return!1}function ln(e){return void 0!==e&&Array.isArray(e.lc_namespace)}function un(e){return void 0!==e&&X.YN.isRunnable(e)&&"lc_name"in e.constructor&&"function"==typeof e.constructor.lc_name&&"RunnableToolLike"===e.constructor.lc_name()}function dn(e){return!!e&&"object"==typeof e&&"name"in e&&"schema"in e&&(Lt(e.schema)||null!=e.schema&&"object"==typeof e.schema&&"type"in e.schema&&"string"==typeof e.schema.type&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function hn(e){return dn(e)||un(e)||ln(e)}class pn extends Rt{get lc_namespace(){return["langchain","tools"]}constructor(e){super(e??{}),Object.defineProperty(this,"returnDirect",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"verboseParsingErrors",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"responseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"content"}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat}async invoke(e,t){let r,n=(0,Q.ZI)(t);return(0,an.Ky)(e)?(r=e.args,n={...n,toolCall:e}):r=e,this.call(r,n)}async call(e,t,r){const n=(0,an.Ky)(e)?e.args:e;let s;if(Lt(this.schema))try{s=await this.schema.parseAsync(n)}catch(t){let r="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(r=`${r}\nDetails: ${t.message}`),new an.qe(r,JSON.stringify(e))}else{const t=br(n,this.schema);if(!t.valid){let r="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(r=`${r}\nDetails: ${t.errors.map((e=>`${e.keywordLocation}: ${e.error}`)).join("\n")}`),new an.qe(r,JSON.stringify(e))}s=n}const a=(0,Ye.parseCallbackConfigArg)(t),i=Ye.CallbackManager.configure(a.callbacks,this.callbacks,a.tags||r,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),o=await(i?.handleToolStart(this.toJSON(),"string"==typeof e?e:JSON.stringify(e),a.runId,void 0,void 0,void 0,a.runName));let c,l,u,d;delete a.runId;try{c=await this._call(s,o,a)}catch(e){throw await(o?.handleToolError(e)),e}if("content_and_artifact"===this.responseFormat){if(!Array.isArray(c)||2!==c.length)throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(c)}`);[l,u]=c}else l=c;(0,an.Ky)(e)&&(d=e.id),!d&&(0,an.hR)(a)&&(d=a.toolCall.id);const h=function(e){const{content:t,artifact:r,toolCallId:n}=e;return n&&!(0,nn.fK)(t)?"string"==typeof t||Array.isArray(t)&&t.every((e=>"object"==typeof e))?new nn.uf({content:t,artifact:r,tool_call_id:n,name:e.name}):new nn.uf({content:wn(t),artifact:r,tool_call_id:n,name:e.name}):t}({content:l,artifact:u,toolCallId:d,name:this.name});return await(o?.handleToolEnd(h)),h}}class mn extends pn{constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:M.z.object({input:M.z.string().optional()}).transform((e=>e.input))})}call(e,t){const r="string"==typeof e||null==e?{input:e}:e;return super.call(r,t)}}class fn extends mn{static lc_name(){return"DynamicTool"}constructor(e){super(e),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,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,t){const r=(0,Ye.parseCallbackConfigArg)(t);return void 0===r.runName&&(r.runName=this.name),super.call(e,r)}async _call(e,t,r){return this.func(e,t,r)}}class gn extends pn{static lc_name(){return"DynamicStructuredTool"}constructor(e){super(e),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,"func",{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.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}async call(e,t,r){const n=(0,Ye.parseCallbackConfigArg)(t);return void 0===n.runName&&(n.runName=this.name),super.call(e,n,r)}_call(e,t,r){return this.func(e,t,r)}}class yn{getTools(){return this.tools}}function bn(e,t){const r=t.schema&&Lt(t.schema)&&(!("shape"in t.schema)||!t.schema.shape),n=cn(t.schema);if(!t.schema||r||n)return new fn({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(t,r,n)=>new Promise(((s,a)=>{const i=(0,Q.tn)(n,{callbacks:r?.getChild()});sn.Nx.runWithConfig((0,Q.DY)(i),(async()=>{try{s(e(t,i))}catch(e){a(e)}}))}))});const s=t.schema,a=t.description??t.schema.description??`${t.name} tool`;return new gn({...t,description:a,schema:s,func:async(t,r,n)=>new Promise(((s,a)=>{const i=(0,Q.tn)(n,{callbacks:r?.getChild()});sn.Nx.runWithConfig((0,Q.DY)(i),(async()=>{try{s(e(t,i))}catch(e){a(e)}}))}))})}function wn(e){try{return JSON.stringify(e,null,2)}catch(t){return`${e}`}}var vn=s(1590),_n=s(6906),kn=s(3997),Sn=s(9583);class En extends vn.BaseTracer{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"endpoint",{enumerable:!0,configurable:!0,writable:!0,value:(0,Sn.getEnvironmentVariable)("LANGCHAIN_ENDPOINT")||"http://localhost:1984"}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:{"Content-Type":"application/json"}}),Object.defineProperty(this,"session",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const e=(0,Sn.getEnvironmentVariable)("LANGCHAIN_API_KEY");e&&(this.headers["x-api-key"]=e)}async newSession(e){const t={start_time:Date.now(),name:e},r=await this.persistSession(t);return this.session=r,r}async loadSession(e){const t=`${this.endpoint}/sessions?name=${e}`;return this._handleSessionResponse(t)}async loadDefaultSession(){const e=`${this.endpoint}/sessions?name=default`;return this._handleSessionResponse(e)}async convertV2RunToRun(e){const t=this.session??await this.loadDefaultSession(),r=e.serialized;let n;if("llm"===e.run_type){const s=e.inputs.prompts?e.inputs.prompts:e.inputs.messages.map((e=>(0,qe.Sw)(e)));n={uuid:e.id,start_time:e.start_time,end_time:e.end_time,execution_order:e.execution_order,child_execution_order:e.child_execution_order,serialized:r,type:e.run_type,session_id:t.id,prompts:s,response:e.outputs}}else if("chain"===e.run_type){const s=await Promise.all(e.child_runs.map((e=>this.convertV2RunToRun(e))));n={uuid:e.id,start_time:e.start_time,end_time:e.end_time,execution_order:e.execution_order,child_execution_order:e.child_execution_order,serialized:r,type:e.run_type,session_id:t.id,inputs:e.inputs,outputs:e.outputs,child_llm_runs:s.filter((e=>"llm"===e.type)),child_chain_runs:s.filter((e=>"chain"===e.type)),child_tool_runs:s.filter((e=>"tool"===e.type))}}else{if("tool"!==e.run_type)throw new Error(`Unknown run type: ${e.run_type}`);{const s=await Promise.all(e.child_runs.map((e=>this.convertV2RunToRun(e))));n={uuid:e.id,start_time:e.start_time,end_time:e.end_time,execution_order:e.execution_order,child_execution_order:e.child_execution_order,serialized:r,type:e.run_type,session_id:t.id,tool_input:e.inputs.input,output:e.outputs?.output,action:JSON.stringify(r),child_llm_runs:s.filter((e=>"llm"===e.type)),child_chain_runs:s.filter((e=>"chain"===e.type)),child_tool_runs:s.filter((e=>"tool"===e.type))}}}return n}async persistRun(e){let t,r;r=void 0!==e.run_type?await this.convertV2RunToRun(e):e,t="llm"===r.type?`${this.endpoint}/llm-runs`:"chain"===r.type?`${this.endpoint}/chain-runs`:`${this.endpoint}/tool-runs`;const n=await fetch(t,{method:"POST",headers:this.headers,body:JSON.stringify(r)});n.ok||console.error(`Failed to persist run: ${n.status} ${n.statusText}`)}async persistSession(e){const t=`${this.endpoint}/sessions`,r=await fetch(t,{method:"POST",headers:this.headers,body:JSON.stringify(e)});return r.ok?{id:(await r.json()).id,...e}:(console.error(`Failed to persist session: ${r.status} ${r.statusText}, using default session.`),{id:1,...e})}async _handleSessionResponse(e){const t=await fetch(e,{method:"GET",headers:this.headers});let r;if(!t.ok)return console.error(`Failed to load session: ${t.status} ${t.statusText}`),r={id:1,start_time:Date.now()},this.session=r,r;const n=await t.json();return 0===n.length?(r={id:1,start_time:Date.now()},this.session=r,r):([r]=n,this.session=r,r)}}async function xn(e){const t=new En;return e?await t.loadSession(e):await t.loadDefaultSession(),t}async function Tn(){return new kn.LangChainTracer}var Cn=s(1060);class Pn extends vn.BaseTracer{constructor({exampleId:e}={}){super({_awaitHandler:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"run_collector"}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracedRuns",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.exampleId=e,this.tracedRuns=[]}async persistRun(e){const t={...e};t.reference_example_id=this.exampleId,this.tracedRuns.push(t)}}const On=(e,t)=>e.reduce(((e,r,n)=>{const s=Math.floor(n/t),a=e[s]||[];return e[s]=a.concat([r]),e}),[]);function An(e,t){const r="number"==typeof t?void 0:t;return{name:e.name,description:e.description,parameters:on(e.schema),...void 0!==r?.strict?{strict:r.strict}:{}}}function In(e,t){const r="number"==typeof t?void 0:t;let n;return n=hn(e)?{type:"function",function:An(e)}:e,void 0!==r?.strict&&(n.function.strict=r.strict),n}function Mn(e,t){let r=0,n=0,s=0;for(let a=0;at.map((t=>r(e,t))).map((e=>Number.isNaN(e)?0:e))))}function $n(e,t=!1){const r=e.reduce(((e,t)=>Math.max(e,Un(t).maxValue)),0);return e.map((e=>e.map((e=>t?1-e/r:e/r))))}function Ln(e,t){return Nn(e,t,Mn)}function Fn(e,t){return Nn(e,t,Rn)}function Dn(e,t){return Nn(e,t,jn)}function zn(e,t,r=.5,n=4){if(Math.min(n,t.length)<=0)return[];const s=Ln(Array.isArray(e[0])?e:[e],t)[0],a=Un(s).maxIndex,i=[t[a]],o=[a];for(;o.length{if(o.includes(s))return;const i=Math.max(...a[s]),c=r*t-(1-r)*i;c>e&&(e=c,n=s)})),i.push(t[n]),o.push(n)}return o}function Un(e){if(0===e.length)return{maxIndex:-1,maxValue:NaN};let t=e[0],r=0;for(let n=1;nt&&(r=n,t=e[n]);return{maxIndex:r,maxValue:t}}class Bn extends en{static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),Object.defineProperty(this,"vectorStore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"k",{enumerable:!0,configurable:!0,writable:!0,value:4}),Object.defineProperty(this,"searchType",{enumerable:!0,configurable:!0,writable:!0,value:"similarity"}),Object.defineProperty(this,"searchKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,"mmr"===e.searchType&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if("mmr"===this.searchType){if("function"!=typeof this.vectorStore.maxMarginalRelevanceSearch)throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild("vectorstore"))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}}class qn extends Ne.Serializable{constructor(e,t){super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","vectorstores",this._vectorstoreType()]}),Object.defineProperty(this,"embeddings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,t=4,r=void 0,n=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)).map((e=>e[0]))}async similaritySearchWithScore(e,t=4,r=void 0,n=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)}static fromTexts(e,t,r,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,t,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,t,r,n,s,a){if("number"==typeof e)return new Bn({vectorStore:this,k:e,filter:t,tags:[...n??[],this._vectorstoreType()],metadata:s,verbose:a,callbacks:r});{const t={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return new Bn("mmr"===e?.searchType?{...t,searchKwargs:e.searchKwargs}:{...t})}}}class Kn extends qn{static load(e,t){throw new Error("Not implemented")}}class Wn extends Yt{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["tests","fake"]})}getFormatInstructions(){return""}async parse(e){return e.split(",").map((e=>e.trim()))}}class Hn extends X.YN{constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["tests","fake"]}),Object.defineProperty(this,"returnOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}}class Vn extends qt{constructor(e){super(e),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"thrownErrorString",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const n=this.response??e;return await(r?.handleLLMNewToken(n)),n}}class Gn extends qt{constructor(e){super(e),Object.defineProperty(this,"sleep",{enumerable:!0,configurable:!0,writable:!0,value:50}),Object.defineProperty(this,"responses",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"thrownErrorString",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const n=this.responses?.[0];this.responses=this.responses?.slice(1);for(const t of n??e)await new Promise((e=>setTimeout(e,this.sleep))),yield{text:t,generationInfo:{}},await(r?.handleLLMNewToken(t))}}class Jn extends zt{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(e,t,r){if(t?.stop?.length)return{generations:[{message:new se.AIMessage(t.stop[0]),text:t.stop[0]}]};const n=e.map((e=>"string"==typeof e.content?e.content:JSON.stringify(e.content,null,2))).join("\n");return await(r?.handleLLMNewToken(n)),{generations:[{message:new se.AIMessage(n),text:n}],llmOutput:{}}}}class Zn extends zt{constructor({sleep:e=50,responses:t=[],chunks:r=[],toolStyle:n="openai",thrownErrorString:s,...a}){super(a),Object.defineProperty(this,"sleep",{enumerable:!0,configurable:!0,writable:!0,value:50}),Object.defineProperty(this,"responses",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"toolStyle",{enumerable:!0,configurable:!0,writable:!0,value:"openai"}),Object.defineProperty(this,"thrownErrorString",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tools",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.sleep=e,this.responses=t,this.chunks=r,this.toolStyle=n,this.thrownErrorString=s}_llmType(){return"fake"}bindTools(e){const t=[...this.tools,...e],r=t.map((e=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:e.name,description:e.description,parameters:on(e.schema)}};case"anthropic":return{name:e.name,description:e.description,input_schema:on(e.schema)};case"bedrock":return{toolSpec:{name:e.name,description:e.description,inputSchema:on(e.schema)}};case"google":return{name:e.name,description:e.description,parameters:on(e.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}})),n="google"===this.toolStyle?[{functionDeclarations:r}]:r,s=new Zn({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return s.tools=t,s.bind({tools:n})}async _generate(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const n=this.responses?.[0]?.content??e[0].content??"";return{generations:[{text:"",message:new se.AIMessage({content:n,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(const e of this.chunks){const t=new $t.ChatGenerationChunk({message:new se.AIMessageChunk({content:e.content,tool_calls:e.tool_calls,additional_kwargs:e.additional_kwargs??{}}),text:e.content?.toString()??""});yield t,await(r?.handleLLMNewToken(e.content,void 0,void 0,void 0,void 0,{chunk:t}))}return}const n=this.responses?.[0]??new se.AIMessage("string"==typeof e[0].content?e[0].content:""),s="string"==typeof n.content?n.content:"";for(const e of s){await new Promise((e=>setTimeout(e,this.sleep)));const t=new $t.ChatGenerationChunk({message:new se.AIMessageChunk({content:e}),text:e});yield t,await(r?.handleLLMNewToken(e,void 0,void 0,void 0,void 0,{chunk:t}))}}}class Yn extends en{constructor(e){super(),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["test","fake"]}),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:[new rt({pageContent:"foo"}),new rt({pageContent:"bar"})]}),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}}class Xn extends zt{static lc_name(){return"FakeListChatModel"}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"responses",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"i",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"sleep",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"emitCustomEvent",{enumerable:!0,configurable:!0,writable:!0,value:!1});const{responses:t,sleep:r,emitCustomEvent:n}=e;this.responses=t,this.sleep=r,this.emitCustomEvent=n??this.emitCustomEvent}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(e,t,r){if(await this._sleepIfRequested(),t?.thrownErrorString)throw new Error(t.thrownErrorString);if(this.emitCustomEvent&&await(r?.handleCustomEvent("some_test_event",{someval:!0})),t?.stop?.length)return{generations:[this._formatGeneration(t.stop[0])]};{const e=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(e)],llmOutput:{}}}}_formatGeneration(e){return{message:new se.AIMessage(e),text:e}}async*_streamResponseChunks(e,t,r){const n=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await(r?.handleCustomEvent("some_test_event",{someval:!0}));for await(const e of n){if(await this._sleepIfRequested(),t?.thrownErrorString)throw new Error(t.thrownErrorString);const n=this._createResponseChunk(e);yield n,r?.handleLLMNewToken(e)}}async _sleepIfRequested(){void 0!==this.sleep&&await this._sleep()}async _sleep(){return new Promise((e=>{setTimeout((()=>e()),this.sleep)}))}_createResponseChunk(e){return new $t.ChatGenerationChunk({message:new se.AIMessageChunk({content:e}),text:e})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i{const t=await this.invoke(e);if(t.tool_calls?.[0]?.args)return t.tool_calls[0].args;if("string"==typeof t.content)return JSON.parse(t.content);throw new Error("No structured output found")}))}}class Qn extends Qe{constructor(){super(),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","message","fake"]}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:[]})}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new se.HumanMessage(e))}async addAIChatMessage(e){this.messages.push(new se.AIMessage(e))}async clear(){this.messages=[]}}class es extends et{constructor(){super(),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","message","fake"]}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:[]})}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}}class ts extends vn.BaseTracer{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"fake_tracer"}),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:[]})}persistRun(e){return this.runs.push(e),Promise.resolve()}}class rs extends pn{constructor(e){super(e),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}async _call(e,t){return JSON.stringify(e)}}class ns extends it{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map((()=>[.1,.2,.3,.4])))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}}class ss extends it{constructor(e){super(e??{}),Object.defineProperty(this,"vectorSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map((e=>this.embedQuery(e))))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,"");const r=t.length%this.vectorSize,n=0===r?0:this.vectorSize-r,s=t.length+n;t=t.padEnd(s," ");const a=t.length/this.vectorSize,i=[];for(let e=0;e{let t=0;for(let r=0;r{this.runPromiseResolver=e}))}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}}class is extends qn{_vectorstoreType(){return"memory"}constructor(e,{similarity:t,...r}={}){super(e,r),Object.defineProperty(this,"memoryVectors",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"similarity",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.similarity=t??Mn}async addDocuments(e){const t=e.map((({pageContent:e})=>e));return this.addVectors(await this.embeddings.embedDocuments(t),e)}async addVectors(e,t){const r=e.map(((e,r)=>({content:t[r].pageContent,embedding:e,metadata:t[r].metadata})));this.memoryVectors=this.memoryVectors.concat(r)}async similaritySearchVectorWithScore(e,t,r){const n=this.memoryVectors.filter((e=>{if(!r)return!0;const t=new rt({metadata:e.metadata,pageContent:e.content});return r(t)}));return n.map(((t,r)=>({similarity:this.similarity(e,t.embedding),index:r}))).sort(((e,t)=>e.similarity>t.similarity?-1:0)).slice(0,t).map((e=>[new rt({metadata:n[e.index].metadata,pageContent:n[e.index].content}),e.similarity]))}static async fromTexts(e,t,r,n){const s=[];for(let r=0;r0===r?t:us(e,t)>=0?e:t))}const hs={[Ie]:-1,[Me]:-2,[Re]:-3,[je]:-4};class ps extends Error{constructor(e){super(e),this.name="InvalidNamespaceError"}}class ms{async get(e,t){return(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){const{filter:r,limit:n=10,offset:s=0,query:a}=t;return(await this.batch([{namespacePrefix:e,filter:r,limit:n,offset:s,query:a}]))[0]}async put(e,t,r,n){!function(e){if(0===e.length)throw new ps("Namespace cannot be empty.");for(const t of e){if("string"!=typeof t)throw new ps(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes("."))throw new ps(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(""===t)throw new ps(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if("langgraph"===e[0])throw new ps(`Root label for namespace cannot be "langgraph". Got: ${e}`)}(e),await this.batch([{namespace:e,key:t,value:r,index:n}])}async delete(e,t){await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){const{prefix:t,suffix:r,maxDepth:n,limit:s=100,offset:a=0}=e,i=[];return t&&i.push({matchType:"prefix",path:t}),r&&i.push({matchType:"suffix",path:r}),(await this.batch([{matchConditions:i.length?i:void 0,maxDepth:n,limit:s,offset:a}]))[0]}start(){}stop(){}}class fs extends ms{constructor(e){var t;super(),Object.defineProperty(this,"lg_name",{enumerable:!0,configurable:!0,writable:!0,value:"AsyncBatchedStore"}),Object.defineProperty(this,"store",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"nextKey",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"running",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"processingTask",{enumerable:!0,configurable:!0,writable:!0,value:null}),this.store="lg_name"in(t=e)&&"AsyncBatchedStore"===t.lg_name?t.store:t}get isRunning(){return this.running}async batch(e){throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){const{filter:r,limit:n=10,offset:s=0,query:a}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:r,limit:n,offset:s,query:a})}async put(e,t,r){return this.enqueueOperation({namespace:e,key:t,value:r})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise(((t,r)=>{const n=this.nextKey;this.nextKey+=1,this.queue.set(n,{operation:e,resolve:t,reject:r})}))}async processBatchQueue(){for(;this.running;){if(await new Promise((e=>{setTimeout(e,0)})),0===this.queue.size)continue;const e=new Map(this.queue);this.queue.clear();try{const t=Array.from(e.values()).map((({operation:e})=>e)),r=await this.store.batch(t);e.forEach((({resolve:t},n)=>{const s=Array.from(e.keys()).indexOf(n);t(r[s])}))}catch(t){e.forEach((({reject:e})=>{e(t)}))}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}}class gs extends Error{constructor(e,t){let r=e??"";t?.lc_error_code&&(r=`${r}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t.lc_error_code}/\n`),super(r),Object.defineProperty(this,"lc_error_code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lc_error_code=t?.lc_error_code}}class ys extends gs{get is_bubble_up(){return!0}}class bs extends gs{constructor(e,t){super(e,t),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}}class ws extends gs{constructor(e,t){super(e,t),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}}class vs extends ys{constructor(e,t){super(JSON.stringify(e,null,2),t),Object.defineProperty(this,"interrupts",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="GraphInterrupt",this.interrupts=e??[]}static get unminifiable_name(){return"GraphInterrupt"}}class _s extends vs{constructor(e,t){super([{value:e,when:"during"}],t),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}}class ks extends ys{constructor(e){super(),Object.defineProperty(this,"command",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="ParentCommand",this.command=e}static get unminifiable_name(){return"ParentCommand"}}function Ss(e){return void 0!==e&&e.name===ks.unminifiable_name}function Es(e){return void 0!==e&&!0===e.is_bubble_up}function xs(e){return void 0!==e&&[vs.unminifiable_name,_s.unminifiable_name].includes(e.name)}class Ts extends gs{constructor(e,t){super(e,t),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}}class Cs extends gs{constructor(e,t){super(e,t),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}}class Ps extends gs{constructor(e,t){super(e,t),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}}class Os extends gs{constructor(e,t){super(e,t),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}}function As(e){return null!=e&&!0===e.lg_is_channel}class Is{constructor(){Object.defineProperty(this,"ValueType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"UpdateType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lg_is_channel",{enumerable:!0,configurable:!0,writable:!0,value:!0})}consume(){return!1}}function Ms(e,t){const r=Object.fromEntries(Object.entries(e).filter((([,e])=>As(e)))),n={};for(const e in r)if(Object.prototype.hasOwnProperty.call(r,e)){const s=t.channel_values[e];n[e]=r[e].fromCheckpoint(s)}return n}function Rs(e,t,r){let n;if(void 0===t)n=e.channel_values;else{n={};for(const e of Object.keys(t))try{n[e]=t[e].checkpoint()}catch(e){if(e.name!==Cs.unminifiable_name)throw e}}return{v:1,id:Oe(r),ts:(new Date).toISOString(),channel_values:n,channel_versions:{...e.channel_versions},versions_seen:os(e.versions_seen),pending_sends:e.pending_sends??[]}}var js=s(9137);const Ns=/^(?:[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;const $s=function(e){return"string"==typeof e&&Ns.test(e)},Ls="__start__",Fs="__end__",Ds="__input__",zs="__error__",Us="__pregel_send",Bs="__pregel_call",qs="__pregel_read",Ks="__pregel_checkpointer",Ws="__pregel_resuming",Hs="__pregel_task_id",Vs="__pregel_stream",Gs="__pregel_scratchpad",Js="__pregel_previous",Zs="checkpoint_ns",Ys="checkpoint_map",Xs="__pregel_abort_signals",Qs="__interrupt__",ea="__resume__",ta="__no_writes__",ra="__return__",na="__previous__",sa="__pregel_runtime_placeholder__",aa="langsmith:hidden",ia="__self__",oa="__pregel_tasks",ca="__pregel_push",la="__pregel_pull",ua="00000000-0000-0000-0000-000000000000",da=[aa,Ds,Qs,ea,zs,ta,oa,Us,qs,Ks,Vs,Ws,Hs,Bs,"__pregel_resume_value",Gs,Js,Ys,Zs,"checkpoint_id"],ha="|",pa=":";function ma(e){const t=e;return null!=t&&"string"==typeof t.node&&void 0!==t.args}class fa{constructor(e,t){Object.defineProperty(this,"lg_name",{enumerable:!0,configurable:!0,writable:!0,value:"Send"}),Object.defineProperty(this,"node",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.node=e,this.args=wa(t)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}}function ga(e){return e instanceof fa}class ya{constructor(e){Object.defineProperty(this,"lg_name",{enumerable:!0,configurable:!0,writable:!0,value:"Command"}),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"graph",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"update",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"resume",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"goto",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.resume=e.resume,this.graph=e.graph,this.update=e.update,e.goto&&(this.goto=Array.isArray(e.goto)?wa(e.goto):[wa(e.goto)])}_updateAsTuples(){return this.update&&"object"==typeof this.update&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every((e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]))?this.update:[["__root__",this.update]]}toJSON(){let e;return e="string"==typeof this.goto?this.goto:ga(this.goto)?this.goto.toJSON():this.goto?.map((e=>"string"==typeof e?e:e.toJSON())),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:e}}}function ba(e){return"object"==typeof e&&(null!=e&&("lg_name"in e&&"Command"===e.lg_name))}function wa(e,t=new Map){if(null!=e&&"object"==typeof e){if(t.has(e))return t.get(e);let r;if(Array.isArray(e))r=[],t.set(e,r),e.forEach(((e,n)=>{r[n]=wa(e,t)}));else if(!ba(e)||e instanceof ya)if(!ma(e)||e instanceof fa)if(ba(e)||ga(e))r=e,t.set(e,r);else if("lc_serializable"in e&&e.lc_serializable)r=e,t.set(e,r);else{r={},t.set(e,r);for(const[n,s]of Object.entries(e))r[n]=wa(s,t)}else r=new fa(e.node,e.args),t.set(e,r);else r=new ya(e),t.set(e,r);return r}return e}Object.defineProperty(ya,"PARENT",{enumerable:!0,configurable:!0,writable:!0,value:"__parent__"});const va=["tags","metadata","callbacks","configurable"],_a=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interruptBefore","interruptAfter","signal"];function ka(...e){const t={tags:[],metadata:{},callbacks:void 0,recursionLimit:25,configurable:{}},r=sn.Nx.getRunnableConfig();if(void 0!==r)for(const[e,n]of Object.entries(r))if(void 0!==n)if(va.includes(e)){let r;r=Array.isArray(n)?[...n]:"object"==typeof n?"callbacks"===e&&"copy"in n&&"function"==typeof n.copy?n.copy():{...n}:n,t[e]=r}else t[e]=n;for(const r of e)if(void 0!==r)for(const[e,n]of Object.entries(r))void 0!==n&&_a.includes(e)&&(t[e]=n);for(const[e,r]of Object.entries(t.configurable))t.metadata=t.metadata??{},e.startsWith("__")||"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r||e in t.metadata||(t.metadata[e]=r);return t}function Sa(e){return e.split(ha).filter((e=>!e.match(/^\d+$/))).map((e=>e.split(pa)[0])).join(ha)}function Ea(e){const t=e.split(ha);for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join(ha)}class xa extends X.YN{constructor(e){super(),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langgraph"]}),Object.defineProperty(this,"func",{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,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"recurse",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,t,r){return new Promise(((n,s)=>{const a=(0,Q.tn)(t,{callbacks:r?.getChild()});sn.Nx.runWithConfig(a,(async()=>{try{const t=await this.func(e,a);n(t)}catch(e){s(e)}}))}))}async invoke(e,t){let r;const n=ka(t),s=(0,Q.SV)(this.config,n);return r=this.trace?await this._callWithConfig(this._tracedInvoke,e,s):await sn.Nx.runWithConfig(s,(async()=>this.func(e,s))),X.YN.isRunnable(r)&&this.recurse?await sn.Nx.runWithConfig(s,(async()=>r.invoke(e,s))):r}}function*Ta(e,t){if(void 0===t)yield*e;else for(const r of e)yield[t,r]}async function Ca(e){const t=[];for await(const r of await e)t.push(r);return t}function Pa(e){const t=[];for(const r of e)t.push(r);return t}function Oa(e,t){return e?"configurable"in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}Symbol.for("LG_SKIP_WRITE");const Aa={[Symbol.for("LG_PASSTHROUGH")]:!0};function Ia(e){return"object"==typeof e&&void 0!==e?.[Symbol.for("LG_PASSTHROUGH")]}const Ma=Symbol("IS_WRITER");class Ra extends xa{constructor(e,t){const r=`ChannelWrite<${e.map((e=>ga(e)?e.node:"channel"in e?e.channel:"...")).join(",")}>`;super({writes:e,name:r,tags:t,func:async(e,t)=>this._write(e,t??{})}),Object.defineProperty(this,"writes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.writes=e}async _write(e,t){const r=this.writes.map((t=>Na(t)&&Ia(t.value)?{mapper:t.mapper,value:e}:ja(t)&&Ia(t.value)?{channel:t.channel,value:e,skipNone:t.skipNone,mapper:t.mapper}:t));return await Ra.doWrite(t,r),e}static async doWrite(e,t){for(const e of t){if(ja(e)){if(e.channel===oa)throw new Ps("Cannot write to the reserved channel TASKS");if(Ia(e.value))throw new Ps("PASSTHROUGH value must be replaced")}if(Na(e)&&Ia(e.value))throw new Ps("PASSTHROUGH value must be replaced")}const r=[];for(const s of t)if(ga(s))r.push([oa,s]);else if(Na(s)){const t=await s.mapper.invoke(s.value,e);null!=t&&t.length>0&&r.push(...t)}else{if(!ja(s))throw new Error(`Invalid write entry: ${JSON.stringify(s)}`);{const t=void 0!==s.mapper?await s.mapper.invoke(s.value,e):s.value;if("object"==typeof(n=t)&&void 0!==n?.[Symbol.for("LG_SKIP_WRITE")])continue;if(s.skipNone&&void 0===t)continue;r.push([s.channel,t])}}var n;const s=e.configurable?.[Us];s(r)}static isWriter(e){return e instanceof Ra||Ma in e&&!!e[Ma]}static registerWriter(e){return Object.defineProperty(e,Ma,{value:!0})}}function ja(e){return void 0!==e&&"string"==typeof e.channel}function Na(e){return void 0!==e&&!ja(e)&&X.YN.isRunnable(e.mapper)}class $a extends xa{constructor(e,t,r=!1){super({func:(e,t)=>$a.doRead(t,this.channel,this.fresh,this.mapper)}),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"ChannelRead"}),Object.defineProperty(this,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fresh",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.fresh=r,this.mapper=t,this.channel=e,this.name=Array.isArray(e)?`ChannelRead<${e.join(",")}>`:`ChannelRead<${e}>`}static doRead(e,t,r,n){const s=e.configurable?.[qs];if(!s)throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process");return n?n(s(t,r)):s(t,r)}}const La=new te;class Fa extends X.fJ{constructor(e){const{channels:t,triggers:r,mapper:n,writers:s,bound:a,kwargs:i,metadata:o,retryPolicy:c,tags:l,subgraphs:u,ends:d}=e,h=[...e.config?.tags?e.config.tags:[],...l??[]];super({...e,bound:e.bound??La,config:{...e.config?e.config:{},tags:h}}),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"PregelNode"}),Object.defineProperty(this,"channels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"triggers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:La}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"retryPolicy",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"subgraphs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ends",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.channels=t,this.triggers=r,this.mapper=n,this.writers=s??this.writers,this.bound=a??this.bound,this.kwargs=i??this.kwargs,this.metadata=o??this.metadata,this.tags=h,this.retryPolicy=c,this.subgraphs=u,this.ends=d}getWriters(){const e=[...this.writers];for(;e.length>1&&e[e.length-1]instanceof Ra&&e[e.length-2]instanceof Ra;){const t=e.slice(-2),r=t[0].writes.concat(t[1].writes);e[e.length-2]=new Ra(r,t[0].config?.tags),e.pop()}return e}getNode(){const e=this.getWriters();return this.bound===La&&0===e.length?void 0:this.bound===La&&1===e.length?e[0]:this.bound===La?new X.zZ({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new X.zZ({first:this.bound,middle:e.slice(0,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):this.bound}join(e){if(!Array.isArray(e))throw new Error("channels must be a list");if("object"!=typeof this.channels)throw new Error("all channels must be named when using .join()");return new Fa({channels:{...this.channels,...Object.fromEntries(e.map((e=>[e,e])))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy})}pipe(e){return Ra.isWriter(e)?new Fa({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,e],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy}):this.bound===La?new Fa({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:(0,X.Bp)(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy}):new Fa({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(e),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy})}}class Da extends Error{constructor(e){super(e),this.name="GraphValidationError"}}function za(e,t){if(Array.isArray(e)){for(const r of e)if(!(r in t))throw new Error(`Key ${String(r)} not found in channels`)}else if(!(e in t))throw new Error(`Key ${String(e)} not found in channels`)}function Ua(e,t,r=!0,n=!1){try{return e[t].get()}catch(e){if(e.name===Cs.unminifiable_name){if(n)return e;if(r)return null}throw e}}function Ba(e,t,r=!0){if(Array.isArray(t)){const n={};for(const s of t)try{n[s]=Ua(e,s,!r)}catch(e){if(e.name===Cs.unminifiable_name)continue}return n}return Ua(e,t)}function*qa(e,t){if(null!=t)if(Array.isArray(e)&&"object"==typeof t&&!Array.isArray(t))for(const r in t)e.includes(r)&&(yield[r,t[r]]);else{if(Array.isArray(e))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[e,t]}}function*Ka(e,t,r){Array.isArray(e)?(!0===t||t.find((([t,r])=>e.includes(t))))&&(yield Ba(r,e)):(!0===t||t.some((([t,r])=>t===e)))&&(yield Ua(r,e))}function*Wa(e,t,r){const n=t.filter((([e,t])=>(void 0===e.config||!e.config.tags?.includes(aa))&&t[0][0]!==zs&&t[0][0]!==Qs));if(!n.length)return;let s;s=n.some((([e])=>e.writes.some((([e,t])=>e===ra))))?n.flatMap((([e])=>e.writes.filter((([e,t])=>e===ra)).map((([t,r])=>[e.name,r])))):Array.isArray(e)?n.flatMap((([t])=>{const{writes:r}=t,n={};for(const[t]of r)e.includes(t)&&(n[t]=(n[t]||0)+1);return Object.values(n).some((e=>e>1))?r.filter((([t])=>e.includes(t))).map((([e,r])=>[t.name,{[e]:r}])):[[t.name,Object.fromEntries(r.filter((([t])=>e.includes(t))))]]})):n.flatMap((([t])=>t.writes.filter((([t,r])=>t===e)).map((([e,r])=>[t.name,r]))));const a={};for(const[e,t]of s)e in a||(a[e]=[]),a[e].push(t);const i={};for(const e in a)if(1===a[e].length){const[t]=a[e];i[e]=t}else i[e]=a[e];r&&(i.__metadata__={cached:r}),yield i}function Ha(e){return"lg_is_pregel"in e&&!0===e.lg_is_pregel}function Va(e){const t=[e];for(const e of t){if(Ha(e))return e;"steps"in(r=e)&&Array.isArray(r.steps)&&t.push(...e.steps)}var r}const Ga={start:"",end:""},Ja={start:"",end:""},Za={start:"",end:""},Ya=(e,t)=>`${e.start}${t}${e.end}`;function*Xa(e,t){const r=(new Date).toISOString();for(const{id:n,name:s,input:a,config:i,triggers:o,writes:c}of t){if(i?.tags?.includes(aa))continue;const t=c.filter((([e,t])=>e===n&&t===Qs)).map((([,e])=>e));yield{type:"task",timestamp:r,step:e,payload:{id:n,name:s,input:a,triggers:o,interrupts:t}}}}function Qa(e,t,r){return e.map((e=>{const n=t.find((([t,r])=>t===e.id&&r===zs))?.[2],s=t.filter((([t,r])=>t===e.id&&r===Qs)).map((([,,e])=>e));if(n)return{id:e.id,name:e.name,path:e.path,error:n,interrupts:s};const a=r?.[e.id];return{id:e.id,name:e.name,path:e.path,interrupts:s,...void 0!==a?{state:a}:{}}}))}function ei(e,t){const r=t.length;console.log([`${Ya(Ga,`[${e}:tasks]`)}`,` Starting step ${e} with ${r} task${1===r?"":"s"}:\n`,t.map((e=>`- ${Ya(Ja,String(e.name))} -> ${JSON.stringify(e.input,null,2)}`)).join("\n")].join(""))}function ti(e,t,r){const n={};for(const[e,s]of t)r.includes(e)&&(n[e]||(n[e]=[]),n[e].push(s));console.log([`${Ya(Ga,`[${e}:writes]`)}`,` Finished step ${e} with writes to ${Object.keys(n).length} channel${1!==Object.keys(n).length?"s":""}:\n`,Object.entries(n).map((([e,t])=>`- ${Ya(Za,e)} -> ${t.map((e=>JSON.stringify(e))).join(", ")}`)).join("\n")].join(""))}class ri{constructor({func:e,name:t,input:r,retry:n,callbacks:s}){Object.defineProperty(this,"func",{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,"input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"retry",{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,"__lg_type",{enumerable:!0,configurable:!0,writable:!0,value:"call"}),this.func=e,this.name=t,this.input=r,this.retry=n,this.callbacks=s}}function ni(e){const t=Object.values(e),r=t.length>0?typeof t[0]:void 0;let n;return"number"===r?n=0:"string"===r&&(n=""),n}function si(e,t){if(Object.keys(e).length>0){const r=ni(t);return Object.fromEntries(Object.entries(t).filter((([t,n])=>n>(e[t]??r))))}return t}function ai(e,t){return null===e?{configurable:t}:void 0===e?.configurable?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function ii(e,t){const r=t?.parents??{};return Object.keys(r).length>0?ai(e,{[Ys]:{...r,[e.configurable?.checkpoint_ns??""]:e.configurable?.checkpoint_id}}):e}function oi(...e){if(1===e.length)return e[0];if("any"in AbortSignal)return AbortSignal.any(e);const t=new AbortController,r=()=>{t.abort(),e.forEach((e=>e.removeEventListener("abort",r)))};return e.forEach((e=>e.addEventListener("abort",r))),e.some((e=>e.aborted))&&t.abort(),t.signal}const ci=e=>void 0!==e?e+1:1;function li(e,t,r){const n=Object.values(e.channel_versions),s=n.length>0?typeof n[0]:void 0;let a;"number"===s?a=0:"string"===s&&(a="");const i=e.versions_seen[Qs]??{},o=Object.entries(e.channel_versions).some((([e,t])=>t>(i[e]??a))),c=r.some((e=>"*"===t?!e.config?.tags?.includes(aa):t.includes(e.name)));return o&&c}function ui(e,t,r,n,s,a,i=!1){let o,c=[],l=new Set;if(Array.isArray(a))c=a.filter((e=>n.get(e))),a=a.filter((e=>!n.get(e))),l=new Set(a.filter((e=>s.writes.some((([t,r])=>t===e)))));else{for(const[e]of s.writes)if(e===a){l=new Set([e]);break}l=l||new Set}if(i&&l.size>0){const e=Object.fromEntries(Object.entries(r).filter((([e,t])=>l.has(e)))),n=Rs(t,e,-1),i=Ms(e,n);pi(ls(n),i,[s]),o=Ba({...r,...i},a)}else o=Ba(r,a);if(c.length>0)for(const t of c){const r=n.get(t);if(r){const n=r.call(e);o[t]=n}}return o}function di(e,t,r,n,s){for(const[t,a]of s)if([ca,oa].includes(t)&&null!=a){if(!ga(a))throw new Ps(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(a)}`);if(!(a.node in r))throw new Ps(`Invalid node name "${a.node}" in Send packet`);n.replaceRuntimeValues(e,a.args)}t(s)}const hi=new Set([ta,ca,ea,Qs,ra,zs]);function pi(e,t,r,n){r.sort(((e,t)=>{const r=e.path?.slice(0,3)||[],n=t.path?.slice(0,3)||[];for(let e=0;en[e])return 1}return r.length-n.length}));const s=r.some((e=>e.triggers.length>0)),a=Object.fromEntries(Object.entries(t).filter((([e,t])=>As(t))));for(const t of r){void 0===e.versions_seen[t.name]&&(e.versions_seen[t.name]={});for(const r of t.triggers)r in e.channel_versions&&(e.versions_seen[t.name][r]=e.channel_versions[r])}let i;Object.keys(e.channel_versions).length>0&&(i=ds(...Object.values(e.channel_versions)));const o=new Set(r.flatMap((e=>e.triggers)).filter((e=>!da.includes(e))));for(const t of o)t in a&&a[t].consume()&&void 0!==n&&(e.channel_versions[t]=n(i,a[t]));e.pending_sends?.length&&s&&(e.pending_sends=[]);const c={},l={};for(const t of r)for(const[r,n]of t.writes)hi.has(r)||(r===oa?e.pending_sends.push({node:n.node,args:n.args}):r in a?r in c?c[r].push(n):c[r]=[n]:r in l?l[r].push(n):l[r]=[n]);i=void 0,Object.keys(e.channel_versions).length>0&&(i=ds(...Object.values(e.channel_versions)));const u=new Set;for(const[t,r]of Object.entries(c))if(t in a){let s;try{s=a[t].update(r)}catch(e){if(e.name===Ps.unminifiable_name){const n=new Ps(`Invalid update for channel "${t}" with values ${JSON.stringify(r)}: ${e.message}`);throw n.lc_error_code=e.lc_error_code,n}throw e}s&&void 0!==n&&(e.channel_versions[t]=n(i,a[t])),u.add(t)}if(s)for(const t of Object.keys(a))if(!u.has(t)){a[t].update([])&&void 0!==n&&(e.channel_versions[t]=n(i,a[t]))}return l}function mi(e,t,r,n,s,a,i,o){const c={};for(let l=0;lt(...e),name:e,trace:!1,recurse:!1});return new X.zZ({name:e,first:r,last:new Ra([{channel:ra,value:Aa}],[aa])})}(m.name,m.func),g=[ca],y=""===p?m.name:`${p}${ha}${m.name}`,b=Ae(JSON.stringify([y,l.toString(),m.name,ca,e[1],e[2]]),t.id),w=`${y}${pa}${b}`,v={langgraph_step:l,langgraph_node:m.name,langgraph_triggers:g,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:w};if(o){const o=[];return{name:m.name,input:m.input,proc:f,writes:o,config:(0,Q.tn)((0,Q.SV)(i,{metadata:v,store:c.store??i.store}),{runName:m.name,callbacks:d?.getChild(`graph:step:${l}`),configurable:{[Hs]:b,[Us]:e=>di(l,(e=>o.push(...e)),n,a,e),[qs]:(r,n=!1)=>ui(l,t,s,a,{name:m.name,writes:o,triggers:g,path:e.slice(0,3)},r,n),[Ks]:u??h[Ks],[Ys]:{...h[Ys],[p]:t.id},[Gs]:gi({pendingWrites:r??[],taskId:b,currentTaskInput:m.input}),[Js]:t.channel_values[na],checkpoint_id:void 0,checkpoint_ns:w}}),triggers:g,retry_policy:m.retry,id:b,path:e.slice(0,3),writers:[]}}return{id:b,name:m.name,interrupts:[],path:e.slice(0,3)}}if(e[0]===ca){const m="number"==typeof e[1]?e[1]:parseInt(e[1],10);if(m>=t.pending_sends.length)return;const f=ma(t.pending_sends[m])&&!ga(t.pending_sends[m])?new fa(t.pending_sends[m].node,t.pending_sends[m].args):t.pending_sends[m];if(!ma(f))return void console.warn(`Ignoring invalid packet ${JSON.stringify(f)} in pending sends.`);if(!(f.node in n))return void console.warn(`Ignoring unknown node name ${f.node} in pending sends.`);const g=[ca],y=""===p?f.node:`${p}${ha}${f.node}`,b=Ae(JSON.stringify([y,l.toString(),f.node,ca,m.toString()]),t.id),w=`${y}${pa}${b}`;let v={langgraph_step:l,langgraph_node:f.node,langgraph_triggers:g,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:w};if(!o)return{id:b,name:f.node,interrupts:[],path:e};{const o=n[f.node],m=o.getNode();if(void 0!==m){a.replaceRuntimePlaceholders(l,f.args),void 0!==o.metadata&&(v={...v,...o.metadata});const y=[];return{name:f.node,input:f.args,proc:m,subgraphs:o.subgraphs,writes:y,config:(0,Q.tn)((0,Q.SV)(i,{metadata:v,tags:o.tags,store:c.store??i.store}),{runName:f.node,callbacks:d?.getChild(`graph:step:${l}`),configurable:{[Hs]:b,[Us]:e=>di(l,(e=>y.push(...e)),n,a,e),[qs]:(r,n=!1)=>ui(l,t,s,a,{name:f.node,writes:y,triggers:g,path:e},r,n),[Ks]:u??h[Ks],[Ys]:{...h[Ys],[p]:t.id},[Gs]:gi({pendingWrites:r??[],taskId:b,currentTaskInput:f.args}),[Js]:t.channel_values[na],checkpoint_id:void 0,checkpoint_ns:w}}),triggers:g,retry_policy:o.retryPolicy,id:b,path:e,writers:o.getWriters()}}}}else if(e[0]===la){const m=e[1].toString(),f=n[m];if(void 0===f)return;if(r?.length){const e=""===p?m:`${p}${ha}${m}`,n=Ae(JSON.stringify([e,l.toString(),m,la,m]),t.id);if(r.some((e=>e[0]===n&&e[1]!==zs)))return}const g=ni(t.channel_versions);if(void 0===g)return;const y=t.versions_seen[m]??{},b=f.triggers.filter((e=>{const r=Ua(s,e,!1,!0);return!(r instanceof Error&&r.name===Cs.unminifiable_name)&&(t.channel_versions[e]??g)>(y[e]??g)})).sort();if(b.length>0){const g=function(e,t,r,n,s){let a;if("object"!=typeof t.channels||Array.isArray(t.channels)){if(!Array.isArray(t.channels))throw new Error(`Invalid channels type, expected list or dict, got ${t.channels}`);{let e=!1;for(const r of t.channels)try{a=Ua(n,r,!1),e=!0;break}catch(e){if(e.name===Cs.unminifiable_name)continue;throw e}if(!e)return}}else{a={};for(const[s,i]of Object.entries(t.channels))if(t.triggers.includes(i))try{a[s]=Ua(n,i,!1)}catch(e){if(e.name===Cs.unminifiable_name)return;throw e}else if(i in n)try{a[s]=Ua(n,i,!1)}catch(e){if(e.name===Cs.unminifiable_name)continue;throw e}else a[s]=r.get(s)?.call(e)}s&&void 0!==t.mapper&&(a=t.mapper(a));return a}(l,f,a,s,o);if(void 0===g)return;const y=""===p?m:`${p}${ha}${m}`,w=Ae(JSON.stringify([y,l.toString(),m,la,b]),t.id),v=`${y}${pa}${w}`;let _={langgraph_step:l,langgraph_node:m,langgraph_triggers:b,langgraph_path:e,langgraph_checkpoint_ns:v};if(!o)return{id:w,name:m,interrupts:[],path:e};{const o=f.getNode();if(void 0!==o){void 0!==f.metadata&&(_={..._,...f.metadata});const y=[];return{name:m,input:g,proc:o,subgraphs:f.subgraphs,writes:y,config:(0,Q.tn)((0,Q.SV)(i,{metadata:_,tags:f.tags,store:c.store??i.store}),{runName:m,callbacks:d?.getChild(`graph:step:${l}`),configurable:{[Hs]:w,[Us]:e=>di(l,(e=>{y.push(...e)}),n,a,e),[qs]:(r,n=!1)=>ui(l,t,s,a,{name:m,writes:y,triggers:b,path:e},r,n),[Ks]:u??h[Ks],[Ys]:{...h[Ys],[p]:t.id},[Gs]:gi({pendingWrites:r??[],taskId:w,currentTaskInput:g}),[Js]:t.channel_values[na],checkpoint_id:void 0,checkpoint_ns:v}}),triggers:b,retry_policy:f.retryPolicy,id:w,path:e,writers:f.getWriters()}}}}}}function gi({pendingWrites:e,taskId:t,currentTaskInput:r}){const n=e.find((([e,t])=>e===ua&&t===ea))?.[2],s={callCounter:0,interruptCounter:-1,resume:e.filter((([e,r])=>e===t&&r===ea)).flatMap((([e,t,r])=>r)),nullResume:n,subgraphCounter:0,currentTaskInput:r,consumeNullResume:()=>{if(s.nullResume)return delete s.nullResume,e.splice(e.findIndex((([e,t])=>e===ua&&t===ea)),1),n}};return s}class yi extends ee.IterableReadableStream{constructor(e,t){const r=e.getReader(),n=t??new AbortController;super({start:e=>function t(){return r.read().then((({done:r,value:n})=>{if(!r)return e.enqueue(n),t();e.close()}))}()}),Object.defineProperty(this,"_abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._abortController=n,this._reader=r}async cancel(e){this._abortController.abort(e),this._reader.releaseLock()}get signal(){return this._abortController.signal}}class bi extends ee.IterableReadableStream{get closed(){return this._closed}constructor(e){let t;const r=new Promise((e=>{t=e}));super({start:e=>{t(e)}}),Object.defineProperty(this,"modes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"passthroughFn",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_closed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),r.then((e=>{this.controller=e})),this.passthroughFn=e.passthroughFn,this.modes=e.modes}push(e){this.passthroughFn?.(e),this.controller.enqueue(e)}close(){try{this.controller.close()}catch(e){}finally{this._closed=!0}}error(e){this.controller.error(e)}}const wi=Symbol.for("INPUT_DONE"),vi=Symbol.for("INPUT_RESUMING");class _i{get isResuming(){const e=0!==Object.keys(this.checkpoint.channel_versions).length,t=void 0!==this.config.configurable?.[Ws]&&this.config.configurable?.[Ws],r=null===this.input||void 0===this.input,n=ba(this.input)&&null!=this.input.resume,s=this.input===vi;return e&&(t||r||n||s)}constructor(e){Object.defineProperty(this,"input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"output",{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,"checkpointer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointerGetNextVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"channels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"managed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpoint",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointNamespace",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointPendingWrites",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"checkpointPreviousVersions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"step",{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,"outputKeys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamKeys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"skipDoneTasks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"prevCheckpointConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:"pending"}),Object.defineProperty(this,"tasks",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkpointerPromises",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"isNested",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_checkpointerChainedPromise",{enumerable:!0,configurable:!0,writable:!0,value:Promise.resolve()}),Object.defineProperty(this,"store",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"interruptAfter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"interruptBefore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"toInterrupt",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.input=e.input,this.checkpointer=e.checkpointer,void 0!==this.checkpointer?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=ci,this.checkpoint=e.checkpoint,this.checkpointMetadata=e.checkpointMetadata,this.checkpointPreviousVersions=e.checkpointPreviousVersions,this.channels=e.channels,this.managed=e.managed,this.checkpointPendingWrites=e.checkpointPendingWrites,this.step=e.step,this.stop=e.stop,this.config=e.config,this.checkpointConfig=e.checkpointConfig,this.isNested=e.isNested,this.manager=e.manager,this.outputKeys=e.outputKeys,this.streamKeys=e.streamKeys,this.nodes=e.nodes,this.skipDoneTasks=e.skipDoneTasks,this.store=e.store,this.stream=e.stream,this.checkpointNamespace=e.checkpointNamespace,this.prevCheckpointConfig=e.prevCheckpointConfig,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.debug=e.debug}static async initialize(e){let{config:t,stream:r}=e;void 0!==r&&void 0!==t.configurable?.[Vs]&&(r=function(...e){return new bi({passthroughFn:t=>{for(const r of e)r.modes.has(t[1])&&r.push(t)},modes:new Set(e.flatMap((e=>Array.from(e.modes))))})}(r,t.configurable[Vs]));const n=!t.configurable||!("checkpoint_id"in t.configurable),s=t.configurable?.[Gs];t.configurable&&s&&(s.subgraphCounter>0&&(t=ai(t,{[Zs]:[t.configurable[Zs],s.subgraphCounter.toString()].join(ha)})),s.subgraphCounter+=1);const a=qs in(t.configurable??{});a||void 0===t.configurable?.checkpoint_ns||""===t.configurable?.checkpoint_ns||(t=ai(t,{checkpoint_ns:"",checkpoint_id:void 0}));let i=t;void 0!==t.configurable?.[Ys]&&t.configurable?.[Ys]?.[t.configurable?.checkpoint_ns]&&(i=ai(t,{checkpoint_id:t.configurable[Ys][t.configurable?.checkpoint_ns]}));const o=t.configurable?.checkpoint_ns?.split(ha)??[],c=await(e.checkpointer?.getTuple(i))??{config:t,checkpoint:cs(),metadata:{source:"input",step:-2,writes:null,parents:{}},pendingWrites:[]};i={...t,...c.config,configurable:{checkpoint_ns:"",...t.configurable,...c.config.configurable}};const l=c.parentConfig,u=ls(c.checkpoint),d={...c.metadata},h=c.pendingWrites??[],p=Ms(e.channelSpecs,u),m=(d.step??0)+1,f=m+(t.recursionLimit??25)+1,g={...u.channel_versions},y=e.store?new fs(e.store):void 0;return y&&y.start(),new _i({input:e.input,config:t,checkpointer:e.checkpointer,checkpoint:u,checkpointMetadata:d,checkpointConfig:i,prevCheckpointConfig:l,checkpointNamespace:o,channels:p,managed:e.managed,isNested:a,manager:e.manager,skipDoneTasks:n,step:m,stop:f,checkpointPreviousVersions:g,checkpointPendingWrites:h,outputKeys:e.outputKeys??[],streamKeys:e.streamKeys??[],nodes:e.nodes,stream:r,store:y,interruptAfter:e.interruptAfter,interruptBefore:e.interruptBefore,debug:e.debug})}_checkpointerPutAfterPrevious(e){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then((()=>this.checkpointer?.put(e.config,e.checkpoint,e.metadata,e.newVersions))),this.checkpointerPromises.push(this._checkpointerChainedPromise)}async updateManagedValues(e,t){const r=this.managed.get(e);r&&"update"in r&&"function"==typeof r.update&&await r.update(t)}putWrites(e,t){let r=t;if(0===r.length)return;r.every((([e])=>e in hs))&&(r=Array.from(new Map(r.map((e=>[e[0],e]))).values()));for(const[t,n]of r){const r=this.checkpointPendingWrites.findIndex((r=>r[0]===e&&r[1]===t));t in hs&&-1!==r?this.checkpointPendingWrites[r]=[e,t,n]:this.checkpointPendingWrites.push([e,t,n])}const n=this.checkpointer?.putWrites({...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_ns:this.config.configurable?.checkpoint_ns??"",checkpoint_id:this.checkpoint.id}},r,e);void 0!==n&&this.checkpointerPromises.push(n),this.tasks&&this._outputWrites(e,r)}_outputWrites(e,t,r=!1){const n=this.tasks[e];if(void 0!==n){if(void 0!==n.config&&(n.config.tags??[]).includes(aa))return;t.length>0&&t[0][0]!==zs&&t[0][0]!==Qs&&this._emit(Pa(Ta(Wa(this.outputKeys,[[n,t]],r),"updates"))),r||this._emit(Pa(Ta(function*(e,t,r){const n=(new Date).toISOString();for(const[{id:s,name:a,config:i},o]of t)i?.tags?.includes(aa)||(yield{type:"task_result",timestamp:n,step:e,payload:{id:s,name:a,result:o.filter((([e])=>Array.isArray(r)?r.includes(e):e===r)),interrupts:o.filter((e=>e[0]===Qs)).map((e=>e[1]))}})}(this.step,[[n,t]],this.streamKeys),"debug")))}}async tick(e){this.store&&!this.store.isRunning&&this.store?.start();const{inputKeys:t=[]}=e;if("pending"!==this.status)throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if([wi,vi].includes(this.input)){if(this.toInterrupt.length>0)throw this.status="interrupt_before",new vs;if(!Object.values(this.tasks).every((e=>e.writes.length>0)))return!1;{const e=Object.values(this.tasks).flatMap((e=>e.writes)),t=pi(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion);for(const[e,r]of Object.entries(t))await this.updateManagedValues(e,r);const r=await Ca(Ta(Ka(this.outputKeys,e,this.channels),"values"));if(this._emit(r),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop",writes:Wa(this.outputKeys,Object.values(this.tasks).map((e=>[e,e.writes]))).next().value??null}),li(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new vs;void 0!==this.config.configurable?.[Ws]&&delete this.config.configurable?.[Ws]}}else await this._first(t);if(this.step>this.stop)return this.status="out_of_steps",!1;const r=mi(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.managed,this.config,!0,{step:this.step,checkpointer:this.checkpointer,isResuming:this.isResuming,manager:this.manager,store:this.store,stream:this.stream});if(this.tasks=r,this.checkpointer&&this._emit(await Ca(Ta(function*(e,t,r,n,s,a,i,o){function c(e){const t={};return null!=e.callbacks&&(t.callbacks=e.callbacks),null!=e.configurable&&(t.configurable=e.configurable),null!=e.maxConcurrency&&(t.max_concurrency=e.maxConcurrency),null!=e.metadata&&(t.metadata=e.metadata),null!=e.recursionLimit&&(t.recursion_limit=e.recursionLimit),null!=e.runId&&(t.run_id=e.runId),null!=e.runName&&(t.run_name=e.runName),null!=e.tags&&(t.tags=e.tags),t}const l=t.configurable?.checkpoint_ns,u={};for(const e of a){if(!(e.subgraphs?.length?e.subgraphs:[e.proc]).find(Va))continue;let r=`${e.name}:${e.id}`;l&&(r=`${l}|${r}`),u[e.id]={configurable:{thread_id:t.configurable?.thread_id,checkpoint_ns:r}}}const d=(new Date).toISOString();yield{type:"checkpoint",timestamp:d,step:e,payload:{config:c(t),values:Ba(r,n),metadata:s,next:a.map((e=>e.name)),tasks:Qa(a,i,u),parentConfig:o?c(o):void 0}}}(this.step-1,this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig),"debug"))),0===Object.values(this.tasks).length)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(const[e,t,r]of this.checkpointPendingWrites){if(t===zs||t===Qs||t===ea)continue;const n=Object.values(this.tasks).find((t=>t.id===e));n&&n.writes.push([t,r])}for(const e of Object.values(this.tasks))e.writes.length>0&&this._outputWrites(e.id,e.writes,!0)}if(Object.values(this.tasks).every((e=>e.writes.length>0)))return this.tick({inputKeys:t});if(li(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new vs;const n=await Ca(Ta(Xa(this.step,Object.values(this.tasks)),"debug"));return this._emit(n),!0}async finishAndHandleError(e){const t=this._suppressInterrupt(e);if((t||void 0===e)&&(this.output=Ba(this.channels,this.outputKeys)),t){if(void 0!==this.tasks&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some((e=>e.writes.length>0))){const e=pi(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion);for(const[t,r]of Object.entries(e))await this.updateManagedValues(t,r);this._emit(Pa(Ta(Ka(this.outputKeys,Object.values(this.tasks).flatMap((e=>e.writes)),this.channels),"values")))}this._emit([["updates",{[Qs]:e.interrupts}]])}return t}acceptPush(e,t,r){if(this.interruptAfter?.length>0&&li(this.checkpoint,this.interruptAfter,[e]))return void this.toInterrupt.push(e);const n=fi([ca,e.path??[],t,e.id,r],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.managed,e.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});return n?this.interruptBefore?.length>0&&li(this.checkpoint,this.interruptBefore,[n])?void this.toInterrupt.push(n):(this._emit(Pa(Ta(Xa(this.step,[n]),"debug"))),this.debug&&ei(this.step,[n]),this.tasks[n.id]=n,this.skipDoneTasks&&this._matchWrites({[n.id]:n}),n):void 0}_suppressInterrupt(e){return xs(e)&&!this.isNested}async _first(e){const{configurable:t}=this.config,r=t?.[Gs];if(r&&void 0!==r.nullResume&&this.putWrites(ua,[[ea,r.nullResume]]),ba(this.input)){if(null!=this.input.resume&&null==this.checkpointer)throw new Error("Cannot use Command(resume=...) without checkpointer");const e={};for(const[t,r,n]of function*(e,t){if(e.graph===ya.PARENT)throw new Ps("There is no parent graph.");if(e.goto){let t;t=Array.isArray(e.goto)?e.goto:[e.goto];for(const e of t)if(ga(e))yield[ua,oa,e];else{if("string"!=typeof e)throw new Error("In Command.send, expected Send or string, got "+typeof e);yield[ua,`branch:__start__:${ia}:${e}`,"__start__"]}}if(e.resume)if("object"==typeof e.resume&&Object.keys(e.resume).length&&Object.keys(e.resume).every($s))for(const[r,n]of Object.entries(e.resume)){const e=t.filter((e=>e[0]===r&&e[1]===ea)).map((e=>e[2])).slice(0,1)??[];e.push(n),yield[r,ea,e]}else yield[ua,ea,e.resume];if(e.update){if("object"!=typeof e.update||!e.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(e.update))for(const[t,r]of e.update)yield[ua,t,r];else for(const[t,r]of Object.entries(e.update))yield[ua,t,r]}}(this.input,this.checkpointPendingWrites))void 0===e[t]&&(e[t]=[]),e[t].push([r,n]);if(0===Object.keys(e).length)throw new Ts("Received empty Command input");for(const[t,r]of Object.entries(e))this.putWrites(t,r)}const n=(this.checkpointPendingWrites??[]).filter((e=>e[0]===ua)).map((e=>e.slice(1)));n.length>0&&pi(this.checkpoint,this.channels,[{name:Ds,writes:n,triggers:[]}],this.checkpointerGetNextVersion);const s=ba(this.input)&&n.length>0;if(this.isResuming||s){for(const e of Object.keys(this.channels))if(void 0!==this.checkpoint.channel_versions[e]){const t=this.checkpoint.channel_versions[e];this.checkpoint.versions_seen[Qs]={...this.checkpoint.versions_seen[Qs],[e]:t}}const e=await Ca(Ta(Ka(this.outputKeys,!0,this.channels),"values"));this._emit(e)}if(this.isResuming)this.input=vi;else if(s)await this._putCheckpoint({source:"input",writes:{}}),this.input=wi;else{const t=await Ca(qa(e,this.input));if(t.length>0){const e=mi(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.managed,this.config,!0,{step:this.step});pi(this.checkpoint,this.channels,Object.values(e).concat([{name:Ds,writes:t,triggers:[]}]),this.checkpointerGetNextVersion),await this._putCheckpoint({source:"input",writes:Object.fromEntries(t)}),this.input=wi}else{if(!(Ws in(this.config.configurable??{})))throw new Ts(`Received no input writes for ${JSON.stringify(e,null,2)}`);this.input=wi}}this.isNested||(this.config=ai(this.config,{[Ws]:this.isResuming}))}_emit(e){for(const t of e)this.stream.modes.has(t[0])&&this.stream.push([this.checkpointNamespace,...t])}async _putCheckpoint(e){const t={...e,step:this.step,parents:this.config.configurable?.[Ys]??{}};if(void 0!==this.checkpointer){this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointMetadata=t,this.checkpoint=Rs(this.checkpoint,this.channels,this.step),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_ns:this.config.configurable?.checkpoint_ns??""}};const e={...this.checkpoint.channel_versions},r=si(this.checkpointPreviousVersions,e);this.checkpointPreviousVersions=e,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:ls(this.checkpoint),metadata:{...this.checkpointMetadata},newVersions:r}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}}this.step+=1}_matchWrites(e){for(const[t,r,n]of this.checkpointPendingWrites){if(r===zs||r===Qs||r===ea)continue;const s=Object.values(e).find((e=>e.id===t));s&&s.writes.push([r,n])}for(const t of Object.values(e))t.writes.length>0&&this._outputWrites(t.id,t.writes,!0)}}class ki{constructor(e,t){Object.defineProperty(this,"runtime",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_promises",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"lg_is_managed_value",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.config=e}static async initialize(e,t){throw new Error("Not implemented")}async promises(){return Promise.all(this._promises)}addPromise(e){this._promises.push(e)}}class Si extends Map{constructor(e){super(e?Array.from(e):void 0)}replaceRuntimeValues(e,t){if(0!==this.size&&t&&!Array.from(this.values()).every((e=>!e.runtime)))if("object"!=typeof t||Array.isArray(t)){if("object"==typeof t&&"constructor"in t)for(const r of Object.getOwnPropertyNames(Object.getPrototypeOf(t)))try{const n=t[r];for(const[s,a]of this.entries())a.runtime&&a.call(e)===n&&(t[r]={[sa]:s})}catch(e){if(e.name!==TypeError.name)throw e}}else for(const[r,n]of Object.entries(t))for(const[s,a]of this.entries())a.runtime&&a.call(e)===n&&(t[r]={[sa]:s})}replaceRuntimePlaceholders(e,t){if(0!==this.size&&t&&!Array.from(this.values()).every((e=>!e.runtime)))if("object"!=typeof t||Array.isArray(t)){if("object"==typeof t&&"constructor"in t)for(const r of Object.getOwnPropertyNames(Object.getPrototypeOf(t)))try{const n=t[r];if("object"==typeof n&&null!==n&&sa in n){const s=this.get(n[sa]);s&&(t[r]=s.call(e))}}catch(e){if(e.name!==TypeError.name)throw e}}else for(const[r,n]of Object.entries(t))if("object"==typeof n&&null!==n&&sa in n){const s=n[sa];"string"==typeof s&&(t[r]=this.get(s)?.call(e))}}}function Ei(e){return!!("object"==typeof e&&e&&"cls"in e&&"params"in e)}class xi extends ki{call(){}static async initialize(e,t){return Promise.resolve(new xi(e))}}class Ti extends Ze.BaseCallbackHandler{constructor(e){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"StreamMessagesHandler"}),Object.defineProperty(this,"streamFn",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadatas",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"seen",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"emittedChatModelRunIds",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"stableMessageIdMap",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.streamFn=e}_emit(e,t,r,n=!1){if(n&&void 0!==t.id&&void 0!==this.seen[t.id])return;let s=t.id;(0,se.isToolMessage)(t)?s??=`run-${r}-tool-${t.tool_call_id}`:(null!=s&&s!==`run-${r}`||(s=this.stableMessageIdMap[r]??s??`run-${r}`),this.stableMessageIdMap[r]??=s),s!==t.id&&(t.id=s,t.lc_kwargs.id=s),null!=t.id&&(this.seen[t.id]=t),this.streamFn([e[0],"messages",[t,e[1]]])}handleChatModelStart(e,t,r,n,s,a,i,o){!i||a&&(a.includes("langsmith:nostream")||a.includes("nostream"))||(this.metadatas[r]=[i.langgraph_checkpoint_ns.split("|"),{tags:a,name:o,...i}])}handleLLMNewToken(e,t,r,n,s,a){const i=a?.chunk;var o;this.emittedChatModelRunIds[r]=!0,void 0!==this.metadatas[r]&&(o=i,(0,se.isBaseMessage)(o?.message)?this._emit(this.metadatas[r],i.message,r):this._emit(this.metadatas[r],new se.AIMessageChunk({content:e}),r))}handleLLMEnd(e,t){if(!this.emittedChatModelRunIds[t]){const r=e.generations?.[0]?.[0];(0,se.isBaseMessage)(r?.message)&&this._emit(this.metadatas[t],r?.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,r,n,s,a,i,o){if(void 0!==a&&o===a.langgraph_node&&(void 0===s||!s.includes(aa))&&(this.metadatas[r]=[a.langgraph_checkpoint_ns.split("|"),{tags:s,name:o,...a}],"object"==typeof t))for(const e of Object.values(t))if(((0,se.isBaseMessage)(e)||(0,se.isBaseMessageChunk)(e))&&void 0!==e.id)this.seen[e.id]=e;else if(Array.isArray(e))for(const t of e)((0,se.isBaseMessage)(t)||(0,se.isBaseMessageChunk)(t))&&void 0!==t.id&&(this.seen[t.id]=t)}handleChainEnd(e,t){const r=this.metadatas[t];if(delete this.metadatas[t],void 0!==r)if((0,se.isBaseMessage)(e))this._emit(r,e,t,!0);else if(Array.isArray(e))for(const n of e)(0,se.isBaseMessage)(n)&&this._emit(r,n,t,!0);else if(null!=e&&"object"==typeof e)for(const n of Object.values(e))if((0,se.isBaseMessage)(n))this._emit(r,n,t,!0);else if(Array.isArray(n))for(const e of n)(0,se.isBaseMessage)(e)&&this._emit(r,e,t,!0)}handleChainError(e,t){delete this.metadatas[t]}}const Ci=[400,401,402,403,404,405,406,407,409],Pi=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||"AbortError"===e.name)return!1;if("ECONNABORTED"===e?.code)return!1;const t=e?.response?.status??e?.status;return(!t||!Ci.includes(+t))&&"insufficient_quota"!==e?.error?.code};async function Oi(e,t,r,n){const s=e.retry_policy??t;let a,i,o=void 0!==s?s.initialInterval??500:0,c=0,{config:l}=e;for(r&&(l=ai(l,r)),l={...l,signal:n};!n?.aborted;){e.writes.splice(0,e.writes.length),a=void 0;try{i=await e.proc.invoke(e.input,l);break}catch(t){if(a=t,a.pregelTaskId=e.id,Ss(a)){const t=l?.configurable?.checkpoint_ns,r=a.command;if(r.graph===t){for(const t of e.writers)await t.invoke(r,l);a=void 0;break}if(r.graph===ya.PARENT){const e=Ea(t);a.command=new ya({...a.command,graph:e})}}if(Es(a))break;if(void 0===s)break;if(c+=1,c>=(s.maxAttempts??3))break;if(!(s.retryOn??Pi)(a))break;o=Math.min(s.maxInterval??128e3,o*(s.backoffFactor??2));const r=s.jitter?Math.floor(o+1e3*Math.random()):o;await new Promise((e=>setTimeout(e,r)));const n=a.name??a.constructor.unminifiable_name??a.constructor.name;(s?.logWarning??1)&&console.log(`Retrying task "${String(e.name)}" after ${o.toFixed(2)}ms (attempt ${c}) after ${n}: ${a}`),l=ai(l,{[Ws]:!0})}}return{task:e,result:i,error:a,signalAborted:n?.aborted}}class Ai{constructor({loop:e,nodeFinished:t}){Object.defineProperty(this,"nodeFinished",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"loop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.loop=e,this.nodeFinished=t}async tick(e={}){const{timeout:t,retryPolicy:r,onStepWrite:n,maxConcurrency:s}=e,a=new Set;let i;const o=new AbortController,c=Object.values(this.loop.tasks).filter((e=>0===e.writes.length)),l=this._initializeAbortSignals({exceptionSignalController:o,timeout:t,signal:e.signal}),u=this._executeTasksWithRetry(c,{signals:l,retryPolicy:r,maxConcurrency:s});for await(const{task:e,error:t,signalAborted:r}of u)this._commit(e,t),xs(t)||Es(t)&&!xs(i)?i=t:!t||0!==a.size&&r||(o.abort(),a.add(t));if(n?.(this.loop.step,Object.values(this.loop.tasks).map((e=>e.writes)).flat()),1===a.size)throw Array.from(a)[0];if(a.size>1)throw new AggregateError(Array.from(a),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(xs(i))throw i;if(Es(i)&&this.loop.isNested)throw i}_initializeAbortSignals({exceptionSignalController:e,timeout:t,signal:r}){const n=this.loop.config.configurable?.[Xs]??{},s=r&&n.composedAbortSignal&&r!==n.composedAbortSignal?oi(n.externalAbortSignal,r):n.externalAbortSignal??r,a=n.errorAbortSignal?oi(n.errorAbortSignal,e.signal):e.signal,i=t?AbortSignal.timeout(t):void 0,o={externalAbortSignal:s,errorAbortSignal:a,timeoutAbortSignal:i,composedAbortSignal:oi(...s?[s]:[],...i?[i]:[],a)};return this.loop.config=ai(this.loop.config,{[Xs]:o}),o}async*_executeTasksWithRetry(e,t){const{retryPolicy:r,maxConcurrency:n,signals:s}=t??{},a=Symbol.for("promiseAdded");let i,o;o=new Promise((function e(t){i=()=>{o=new Promise(e),t(a)}}));const c={};function l(e,t,n,{calls:s}={}){if(n.every((([e])=>e!==ca)))return t.config?.configurable?.[Us]?.(n)??[];const a=t.config?.configurable?.[Gs];if(!a)throw new Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);const o={};for(const[d,h]of n.entries()){const[n]=h;if(n!==ca)continue;const p=s?.[d],m=a.callCounter;if(a.callCounter+=1,null==p)throw new Error("BUG: No call found");const f=e.loop.acceptPush(t,m,p);if(!f)continue;const g=c[f.id];if(void 0!==g)o[d]=g;else if(f.writes.length>0){const e=f.writes.filter((([e])=>e===ra)),t=f.writes.filter((([e])=>e===zs));if(e.length>0){if(1!==e.length)throw new Error(`BUG: multiple returns found for task ${f.name}__${f.id}`);o[d]=Promise.resolve(e[0][1])}else if(t.length>0){if(1!==t.length)throw new Error(`BUG: multiple errors found for task ${f.name}__${f.id}`);{const e=t[0][1],r=e instanceof Error?e:new Error(String(e));o[d]=Promise.reject(r)}}}else{const t=Oi(f,r,{[Us]:l.bind(null,e,f),[Bs]:u.bind(null,e,f)});c[f.id]=t,i(),o[d]=t.then((({result:e,error:t})=>t?Promise.reject(t):e))}}return Object.values(o)}function u(e,t,r,n,s,a={}){const i=l(e,t,[[ca,null]],{calls:[new ri({func:r,name:n,input:s,retry:a.retry,callbacks:a.callbacks})]});return void 0!==i?1===i.length?i[0]:Promise.all(i):Promise.resolve()}if(s?.composedAbortSignal?.aborted)throw new Error("Abort");let d,h=0;const p=s?.externalAbortSignal||s?.timeoutAbortSignal?oi(...s.externalAbortSignal?[s.externalAbortSignal]:[],...s.timeoutAbortSignal?[s.timeoutAbortSignal]:[]):void 0,m=p?new Promise(((e,t)=>{d=()=>t(new Error("Abort")),p.addEventListener("abort",d,{once:!0})})):void 0;for(;(0===h||Object.keys(c).length>0)&&e.length;){for(;Object.values(c).length<(n??e.length)&&h({task:t,error:e,signalAborted:s?.composedAbortSignal?.aborted})))}const t=await Promise.race([...Object.values(c),...m?[m]:[],o]);t!==a&&(yield t,delete c[t.task.id])}}_commit(e,t){if(void 0!==t)if(xs(t)){if(t.interrupts.length){const r=t.interrupts.map((e=>[Qs,e])),n=e.writes.filter((e=>e[0]===ea));n.length&&r.push(...n),this.loop.putWrites(e.id,r)}}else Es(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):this.loop.putWrites(e.id,[[zs,{message:t.message,name:t.name}]]);else!this.nodeFinished||null!=e.config?.tags&&e.config.tags.includes(aa)||this.nodeFinished(String(e.name)),0===e.writes.length&&e.writes.push([ta,null]),this.loop.putWrites(e.id,e.writes)}}class Ii{static subscribeTo(e,t){const{key:r,tags:n}={key:void 0,tags:void 0,...t??{}};if(Array.isArray(e)&&void 0!==r)throw new Error("Can't specify a key when subscribing to multiple channels");let s;s=function(e){return"string"==typeof e}(e)?r?{[r]:e}:[e]:Object.fromEntries(e.map((e=>[e,e])));const a=Array.isArray(e)?e:[e];return new Fa({channels:s,triggers:a,tags:n})}static writeTo(e,t){const r=[];for(const t of e)r.push({channel:t,value:Aa,skipNone:!1});for(const[e,n]of Object.entries(t??{}))X.YN.isRunnable(n)||"function"==typeof n?r.push({channel:e,value:Aa,skipNone:!0,mapper:(0,X.Bp)(n)}):r.push({channel:e,value:n,skipNone:!1});return new Ra(r)}}class Mi extends X.YN{static lc_name(){return"LangGraph"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langgraph","pregel"]}),Object.defineProperty(this,"lg_is_pregel",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"channels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputChannels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputChannels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoValidate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"streamMode",{enumerable:!0,configurable:!0,writable:!0,value:["values"]}),Object.defineProperty(this,"streamChannels",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"interruptAfter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"interruptBefore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stepTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"checkpointer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"retryPolicy",{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,"store",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let{streamMode:t}=e;null==t||Array.isArray(t)||(t=[t]),this.nodes=e.nodes,this.channels=e.channels,this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.name=e.name,this.autoValidate&&this.validate()}withConfig(e){const t=(0,Q.SV)(this.config,e);return new this.constructor({...this,config:t})}validate(){return function({nodes:e,channels:t,inputChannels:r,outputChannels:n,streamChannels:s,interruptAfterNodes:a,interruptBeforeNodes:i}){if(!t)throw new Da("Channels not provided");const o=new Set,c=new Set;for(const[t,r]of Object.entries(e)){if(t===Qs)throw new Da(`"Node name ${Qs} is reserved"`);if(r.constructor!==Fa)throw new Da(`Invalid node type ${typeof r}, expected PregelNode`);r.triggers.forEach((e=>o.add(e)))}for(const e of o)if(!(e in t))throw new Da(`Subcribed channel '${String(e)}' not in channels`);if(Array.isArray(r)){if(r.every((e=>!o.has(e))))throw new Da(`None of the input channels ${r} are subscribed to by any node`)}else if(!o.has(r))throw new Da(`Input channel ${String(r)} is not subscribed to by any node`);Array.isArray(n)?n.forEach((e=>c.add(e))):c.add(n),s&&!Array.isArray(s)?c.add(s):Array.isArray(s)&&s.forEach((e=>c.add(e)));for(const e of c)if(!(e in t))throw new Da(`Output channel '${String(e)}' not in channels`);if(a&&"*"!==a)for(const t of a)if(!(t in e))throw new Da(`Node ${String(t)} not in nodes`);if(i&&"*"!==i)for(const t of i)if(!(t in e))throw new Da(`Node ${String(t)} not in nodes`)}({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore}),this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(e){return this.getGraph(e)}*getSubgraphs(e,t){for(const[r,n]of Object.entries(this.nodes)){if(void 0!==e&&!e.startsWith(r))continue;const s=n.subgraphs?.length?n.subgraphs:[n.bound];for(const n of s){const s=Va(n);if(void 0!==s){if(r===e)return void(yield[r,s]);if(void 0===e&&(yield[r,s]),t){let n=e;void 0!==e&&(n=e.slice(r.length+1));for(const[e,a]of s.getSubgraphs(n,t))yield[`${r}${ha}${e}`,a]}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}async _prepareStateSnapshot({config:e,saved:t,subgraphCheckpointer:r,applyPendingWrites:n=!1}){if(void 0===t)return{values:{},next:[],config:e,tasks:[]};const{managed:s}=await this.prepareSpecs(e,{skipManaged:!0}),a=Ms(this.channels,t.checkpoint);if(t.pendingWrites?.length){const e=t.pendingWrites.filter((([e,t])=>e===ua)).map((([e,t,r])=>[String(t),r]));e.length>0&&pi(t.checkpoint,a,[{name:Ds,writes:e,triggers:[]}])}const i=Object.values(mi(t.checkpoint,t.pendingWrites,this.nodes,a,s,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),o=await Ca(this.getSubgraphsAsync()),c=t.config.configurable?.checkpoint_ns??"",l={};for(const e of i){const n=o.find((([t])=>t===e.name));if(!n)continue;let s=`${String(e.name)}${pa}${e.id}`;if(c&&(s=`${c}${ha}${s}`),void 0===r){const r={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:s}};l[e.id]=r}else{const a={configurable:{[Ks]:r,thread_id:t.config.configurable?.thread_id,checkpoint_ns:s}},i=n[1];l[e.id]=await i.getState(a,{subgraphs:!0})}}if(n&&t.pendingWrites?.length){const e=Object.fromEntries(i.map((e=>[e.id,e])));for(const[r,n,s]of t.pendingWrites)[zs,Qs,Me].includes(n)||r in e&&e[r].writes.push([String(n),s]);const r=i.filter((e=>e.writes.length>0));r.length>0&&pi(t.checkpoint,a,r)}let u=t?.metadata;u&&t?.config?.configurable?.thread_id&&(u={...u,thread_id:t.config.configurable.thread_id});const d=i.filter((e=>0===e.writes.length)).map((e=>e.name));return{values:Ba(a,this.streamChannelsAsIs),next:d,tasks:Qa(i,t?.pendingWrites??[],l),metadata:u,config:ii(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){const r=e.configurable?.[Ks]??this.checkpointer;if(!r)throw new ws("No checkpointer set");const n=e.configurable?.checkpoint_ns??"";if(""!==n&&void 0===e.configurable?.[Ks]){const s=Sa(n);for await(const[n,a]of this.getSubgraphsAsync(s,!0))if(n===s)return await a.getState(Oa(e,{[Ks]:r}),{subgraphs:t?.subgraphs});throw new Error(`Subgraph with namespace "${s}" not found.`)}const s=(0,Q.SV)(this.config,e),a=await r.getTuple(e);return await this._prepareStateSnapshot({config:s,saved:a,subgraphCheckpointer:t?.subgraphs?r:void 0,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){const r=e.configurable?.[Ks]??this.checkpointer;if(!r)throw new Error("No checkpointer set");const n=e.configurable?.checkpoint_ns??"";if(""!==n&&void 0===e.configurable?.[Ks]){const s=Sa(n);for await(const[n,a]of this.getSubgraphsAsync(s,!0))if(n===s)return void(yield*a.getStateHistory(Oa(e,{[Ks]:r}),t));throw new Error(`Subgraph with namespace "${s}" not found.`)}const s=(0,Q.SV)(this.config,e,{configurable:{checkpoint_ns:n}});for await(const e of r.list(s,t))yield this._prepareStateSnapshot({config:e.config,saved:e})}async bulkUpdateState(e,t){const r=e.configurable?.[Ks]??this.checkpointer;if(!r)throw new ws("No checkpointer set");if(0===t.length)throw new Error("No supersteps provided");if(t.some((e=>0===e.updates.length)))throw new Error("No updates provided");const n=e.configurable?.checkpoint_ns??"";if(""!==n&&void 0===e.configurable?.[Ks]){const s=Sa(n);for await(const[,n]of this.getSubgraphsAsync(s,!0))return await n.bulkUpdateState(Oa(e,{[Ks]:r}),t);throw new Error(`Subgraph "${s}" not found`)}const s=async(e,t)=>{const n=this.config?(0,Q.SV)(this.config,e):e,s=await r.getTuple(n),a=void 0!==s?ls(s.checkpoint):cs(),i={...s?.checkpoint.channel_versions},o=s?.metadata?.step??-1;let c=Oa(n,{checkpoint_ns:n.configurable?.checkpoint_ns??""}),l=n.metadata??{};s?.config.configurable&&(c=Oa(n,s.config.configurable),l={...s.metadata,...l});const{values:u,asNode:d}=t[0];if(null==u&&void 0===d){if(t.length>1)throw new Ps("Cannot create empty checkpoint with multiple updates");return ii(await r.put(c,Rs(a,void 0,o),{source:"update",step:o+1,writes:{},parents:s?.metadata?.parents??{}},{}),s?s.metadata:void 0)}const h=Ms(this.channels,a),{managed:p}=await this.prepareSpecs(n,{skipManaged:!0});if(null===u&&d===Fs){if(t.length>1)throw new Ps("Cannot apply multiple updates when clearing state");if(s){const e=mi(a,s.pendingWrites||[],this.nodes,h,p,s.config,!0,{step:(s.metadata?.step??-1)+1,checkpointer:this.checkpointer||void 0,store:this.store}),t=(s.pendingWrites||[]).filter((e=>e[0]===ua)).map((e=>e.slice(1)));t.length>0&&pi(s.checkpoint,h,[{name:Ds,writes:t,triggers:[]}]);for(const[t,r,n]of s.pendingWrites||[])[zs,Qs,Me].includes(r)||t in e&&e[t].writes.push([r,n]);pi(a,h,Object.values(e))}return ii(await r.put(c,Rs(a,void 0,o),{...l,source:"update",step:o+1,writes:{},parents:s?.metadata?.parents??{}},{}),s?s.metadata:void 0)}if(null==u&&"__copy__"===d){if(t.length>1)throw new Ps("Cannot copy checkpoint with multiple updates");return ii(await r.put(s?.parentConfig??c,Rs(a,void 0,o),{source:"fork",step:o+1,writes:{},parents:s?.metadata?.parents??{}},{}),s?s.metadata:void 0)}if(d===Ds){if(t.length>1)throw new Ps("Cannot apply multiple updates when updating as input");const e=await Ca(qa(this.inputChannels,u));if(0===e.length)throw new Ps(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);pi(a,h,[{name:Ds,writes:e,triggers:[]}],r.getNextVersion.bind(this.checkpointer));const n=null!=s?.metadata?.step?s.metadata.step+1:-1,o=await r.put(c,Rs(a,h,n),{source:"input",step:n,writes:Object.fromEntries(e),parents:s?.metadata?.parents??{}},si(i,a.channel_versions));return await r.putWrites(o,e,Ae(Ds,a.id)),ii(o,s?s.metadata:void 0)}if(void 0===n.configurable?.checkpoint_id&&void 0!==s?.pendingWrites&&s.pendingWrites.length>0){const e=mi(a,s.pendingWrites,this.nodes,h,p,s.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(s.metadata?.step??-1)+1}),t=(s.pendingWrites??[]).filter((e=>e[0]===ua)).map((e=>e.slice(1)));t.length>0&&pi(s.checkpoint,h,[{name:Ds,writes:t,triggers:[]}]);for(const[t,r,n]of s.pendingWrites)[zs,Qs,Me].includes(r)||void 0===e[t]||e[t].writes.push([r,n]);const r=Object.values(e).filter((e=>e.writes.length>0));r.length>0&&pi(a,h,r)}const m=Object.values(a.versions_seen).map((e=>Object.values(e))).flat().find((e=>!!e)),f=[];if(1===t.length){let{values:e,asNode:r}=t[0];if(void 0===r&&1===Object.keys(this.nodes).length)[r]=Object.keys(this.nodes);else if(void 0===r&&void 0===m)"string"==typeof this.inputChannels&&void 0!==this.nodes[this.inputChannels]&&(r=this.inputChannels);else if(void 0===r){const e=Object.entries(a.versions_seen).map((([e,t])=>Object.values(t).map((t=>[t,e])))).flat().sort((([e],[t])=>us(e,t)));e&&(1===e.length?r=e[0][1]:e[e.length-1][0]!==e[e.length-2][0]&&(r=e[e.length-1][1]))}if(void 0===r)throw new Ps('Ambiguous update, specify "asNode"');f.push({values:e,asNode:r})}else for(const{asNode:e,values:r}of t){if(null==e)throw new Ps('"asNode" is required when applying multiple updates');f.push({values:r,asNode:e})}const g=[];for(const{asNode:e,values:t}of f){if(void 0===this.nodes[e])throw new Ps(`Node "${e.toString()}" does not exist`);const r=this.nodes[e].getWriters();if(!r.length)throw new Ps(`No writers found for node "${e.toString()}"`);g.push({name:e,input:t,proc:r.length>1?X.zZ.from(r,{omitSequenceTags:!0}):r[0],writes:[],triggers:[Qs],id:Ae(Qs,a.id),writers:[]})}for(const e of g)await e.proc.invoke(e.input,(0,Q.tn)({...n,store:n?.store??this.store},{runName:n.runName??`${this.getName()}UpdateState`,configurable:{[Us]:t=>e.writes.push(...t),[qs]:(t,r=!1)=>ui(o,a,h,p,e,t,r)}}));for(const e of g){const t=e.writes.filter((e=>e[0]!==ca));void 0!==s&&t.length>0&&await r.putWrites(c,t,e.id)}pi(a,h,g,r.getNextVersion.bind(this.checkpointer));const y=si(i,a.channel_versions),b=await r.put(c,Rs(a,h,o+1),{source:"update",step:o+1,writes:Object.fromEntries(f.map((e=>[e.asNode,e.values]))),parents:s?.metadata?.parents??{}},y);for(const e of g){const t=e.writes.filter((e=>e[0]===ca));t.length>0&&await r.putWrites(b,t,e.id)}return ii(b,s?s.metadata:void 0)};let a=e;for(const{updates:e}of t)a=await s(a,e);return a}async updateState(e,t,r){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:r}]}])}_defaults(e){const{debug:t,streamMode:r,inputKeys:n,outputKeys:s,interruptAfter:a,interruptBefore:i,...o}=e;let c=!0;const l=void 0!==t?t:this.debug;let u=s;void 0===u?u=this.streamChannelsAsIs:za(u,this.channels);let d=n;void 0===d?d=this.inputChannels:za(d,this.channels);const h=i??this.interruptBefore??[],p=a??this.interruptAfter??[];let m,f;void 0!==r?(m=Array.isArray(r)?r:[r],c="string"==typeof r):(m=this.streamMode,c=!0),void 0!==e.configurable?.[Hs]&&(m=["values"]),f=!1===this.checkpointer?void 0:void 0!==e&&void 0!==e.configurable?.[Ks]?e.configurable[Ks]:this.checkpointer;return[l,m,d,u,o,h,p,f,e.store??this.store,c]}async stream(e,t){const r=new AbortController,n={recursionLimit:this.config?.recursionLimit,...t,signal:t?.signal?oi(t.signal,r.signal):r.signal};return new yi(await super.stream(e,n),r)}streamEvents(e,t,r){const n=new AbortController,s={recursionLimit:this.config?.recursionLimit,callbacks:this.config?.callbacks,...t,signal:t?.signal?oi(t.signal,n.signal):n.signal};return new yi(super.streamEvents(e,s,r),n)}async prepareSpecs(e,t){const r={...e,store:this.store},n={},s={};for(const[e,r]of Object.entries(this.channels))As(r)?n[e]=r:s[e]=t?.skipManaged?{cls:xi,params:{config:{}}}:r;const a=new Si(await Object.entries(s).reduce((async(e,[t,n])=>{const s=await e;let a;return Ei(n)?("key"in n.params&&"__channel_key_placeholder__"===n.params.key&&(n.params.key=t),a=await n.cls.initialize(r,n.params)):a=await n.initialize(r),void 0!==a&&s.push([t,a]),s}),Promise.resolve([])));return{channelSpecs:n,managed:a}}async _validateInput(e){return e}async _validateConfigurable(e){return e}async*_streamIterator(e,t){const r=t?.subgraphs,n=ka(this.config,t);if(void 0===n.recursionLimit||n.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(void 0!==this.checkpointer&&!1!==this.checkpointer&&void 0===n.configurable)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');const s=await this._validateInput(e),{runId:a,...i}=n,[o,c,,l,u,d,h,p,m,f]=this._defaults(i);u.configurable=await this._validateConfigurable(u.configurable);const g=new bi({modes:new Set(c)});if(c.includes("messages")){const e=new Ti((e=>g.push(e))),{callbacks:t}=u;if(void 0===t)u.callbacks=[e];else if(Array.isArray(t))u.callbacks=t.concat(e);else{const r=t.copy();r.addHandler(e,!0),u.callbacks=r}}c.includes("custom")&&(u.writer=e=>g.push([[],"custom",e]));const y=await(0,Q.kJ)(u),b=await(y?.handleChainStart(this.toJSON(),function(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}(e,"input"),a,void 0,void 0,void 0,u?.runName??this.getName())),{channelSpecs:w,managed:v}=await this.prepareSpecs(u);let _,k;const S=(async()=>{try{_=await _i.initialize({input:s,config:u,checkpointer:p,nodes:this.nodes,channelSpecs:w,managed:v,outputKeys:l,streamKeys:this.streamChannelsAsIs,store:m,stream:g,interruptAfter:h,interruptBefore:d,manager:b,debug:this.debug});const e=new Ai({loop:_,nodeFinished:u.configurable?.__pregel_node_finished});t?.subgraphs&&(_.config.configurable={..._.config.configurable,[Vs]:_.stream}),await this._runLoop({loop:_,runner:e,debug:o,config:u})}catch(e){k=e}finally{try{_&&await(_.store?.stop()),await Promise.all([..._?.checkpointerPromises??[],...Array.from(v.values()).map((e=>e.promises()))])}catch(e){k=k??e}k?g.error(k):g.close()}})();try{for await(const e of g){if(void 0===e)throw new Error("Data structure error.");const[t,n,s]=e;c.includes(n)&&(r&&!f?yield[t,n,s]:f?r?yield[t,s]:yield s:yield[n,s])}}catch(e){throw await(b?.handleChainError(k)),e}finally{await S}await(b?.handleChainEnd(_?.output??{},a,void 0,void 0,void 0))}async invoke(e,t){const r=t?.streamMode??"values",n={...t,outputKeys:t?.outputKeys??this.outputChannels,streamMode:r},s=[],a=await this.stream(e,n);for await(const e of a)s.push(e);return"values"===r?s[s.length-1]:s}async _runLoop(e){const{loop:t,runner:r,debug:n,config:s}=e;let a;try{for(;await t.tick({inputKeys:this.inputChannels});)n&&(i=t.checkpointMetadata.step,o=t.channels,c=this.streamChannelsList,console.log([`${Ya(Ga,`[${i}:checkpoint]`)}`,` State at the end of step ${i}:\n`,JSON.stringify(Ba(o,c),null,2)].join(""))),n&&ei(t.step,Object.values(t.tasks)),await r.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(e,t)=>{n&&ti(e,t,this.streamChannelsList)},maxConcurrency:s.maxConcurrency,signal:s.signal});if("out_of_steps"===t.status)throw new bs([`Recursion limit of ${s.recursionLimit} reached`,"without hitting a stop condition. You can increase the",'limit by setting the "recursionLimit" config key.'].join(" "),{lc_error_code:"GRAPH_RECURSION_LIMIT"})}catch(e){a=e;if(!await t.finishAndHandleError(a))throw e}finally{void 0===a&&await t.finishAndHandleError()}var i,o,c}}class Ri extends Is{constructor(e,t){super(),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"BinaryOperatorAggregate"}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"operator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialValueFactory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.operator=e,this.initialValueFactory=t,this.value=t?.()}fromCheckpoint(e){const t=new Ri(this.operator,this.initialValueFactory);return e&&(t.value=e),t}update(e){let t=e;if(!t.length)return!1;void 0===this.value&&([this.value]=t,t=t.slice(1));for(const e of t)void 0!==this.value&&(this.value=this.operator(this.value,e));return!0}get(){if(void 0===this.value)throw new Cs;return this.value}checkpoint(){if(void 0===this.value)throw new Cs;return this.value}}class ji extends Is{constructor(e=!0){super(),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"EphemeralValue"}),Object.defineProperty(this,"guard",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.guard=e}fromCheckpoint(e){const t=new ji(this.guard);return e&&(t.value=[e]),t}update(e){if(0===e.length){const e=this.value.length>0;return this.value=[],e}if(1!==e.length&&this.guard)throw new Ps("EphemeralValue can only receive one value per step.");return this.value=[e[e.length-1]],!0}get(){if(0===this.value.length)throw new Cs;return this.value[0]}checkpoint(){if(0===this.value.length)throw new Cs;return this.value[0]}}class Ni{constructor(e){Object.defineProperty(this,"condition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ends",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),X.YN.isRunnable(e.path)?this.condition=e.path:this.condition=(0,X.Bp)(e.path).withConfig({runName:"Branch"}),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce(((e,t)=>(e[t]=t,e)),{}):e.pathMap}run(e,t){return Ra.registerWriter(new xa({name:"",trace:!1,func:async(r,n)=>{try{return await this._route(r,n,e,t)}catch(e){throw e.name===_s.unminifiable_name&&console.warn("[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.\nNodeInterrupt should only be thrown inside a node, not in edge conditions."),e}}}))}async _route(e,t,r,n){let s,a=await this.condition.invoke(n?n(t):e,t);if(Array.isArray(a)||(a=[a]),s=this.ends?a.map((e=>ga(e)?e:this.ends[e])):a,s.some((e=>!e)))throw new Error("Branch condition returned unknown or null destination");if(s.filter(ga).some((e=>e.node===Fs)))throw new Ps("Cannot send a packet to the END node");return await r(s,t)??e}}class $i{constructor(){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"branches",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"entryPoint",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"compiled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(e){this.compiled&&console.warn(e)}get allEdges(){return this.edges}addNode(e,t,r){for(const t of[ha,pa])if(e.includes(t))throw new Error(`"${t}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),e in this.nodes)throw new Error(`Node \`${e}\` already present.`);if(e===Fs)throw new Error(`Node \`${e}\` is reserved.`);const n=(0,X.Bp)(t);return this.nodes[e]={runnable:n,metadata:r?.metadata,subgraphs:Ha(n)?[n]:r?.subgraphs,ends:r?.ends},this}addEdge(e,t){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),e===Fs)throw new Error("END cannot be a start node");if(t===Ls)throw new Error("START cannot be an end node");if(Array.from(this.edges).some((([t])=>t===e))&&!("channels"in this))throw new Error(`Already found path for ${e}. For multiple edges, use StateGraph.`);return this.edges.add([e,t]),this}addConditionalEdges(e,t,r){const n="object"==typeof e?e:{source:e,path:t,pathMap:r};if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),!X.YN.isRunnable(n.path)){const e=Array.isArray(n.pathMap)?n.pathMap.join(","):Object.keys(n.pathMap??{}).join(",");n.path=(0,X.Bp)(n.path).withConfig({runName:`Branch<${n.source}${""!==e?`,${e}`:""}>`.slice(0,63)})}const s="RunnableLambda"===n.path.getName()?"condition":n.path.getName();if(this.branches[n.source]&&this.branches[n.source][s])throw new Error(`Condition \`${s}\` already present for node \`${e}\``);return this.branches[n.source]||(this.branches[n.source]={}),this.branches[n.source][s]=new Ni(n),this}setEntryPoint(e){return this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(Ls,e)}setFinishPoint(e){return this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(e,Fs)}compile({checkpointer:e,interruptBefore:t,interruptAfter:r,name:n}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(r)?r:[]]);const s=new Li({builder:this,checkpointer:e,interruptAfter:r,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[Ls]:new ji,[Fs]:new ji},inputChannels:Ls,outputChannels:Fs,streamChannels:[],streamMode:"values",name:n});for(const[e,t]of Object.entries(this.nodes))s.attachNode(e,t);for(const[e,t]of this.edges)s.attachEdge(e,t);for(const[e,t]of Object.entries(this.branches))for(const[r,n]of Object.entries(t))s.attachBranch(e,r,n);return s.validate()}validate(e){const t=new Set([...this.allEdges].map((([e,t])=>e)));for(const[e]of Object.entries(this.branches))t.add(e);for(const e of t)if(e!==Ls&&!(e in this.nodes))throw new Error(`Found edge starting at unknown node \`${e}\``);const r=new Set([...this.allEdges].map((([e,t])=>t)));for(const[e,t]of Object.entries(this.branches))for(const n of Object.values(t))if(n.ends)for(const e of Object.values(n.ends))r.add(e);else{r.add(Fs);for(const t of Object.keys(this.nodes))t!==e&&r.add(t)}for(const e of Object.values(this.nodes))for(const t of e.ends??[])r.add(t);for(const e of Object.keys(this.nodes))if(!r.has(e))throw new Os([`Node \`${e}\` is not reachable.`,"","If you are returning Command objects from your node,",'make sure you are passing names of potential destination nodes as an "ends" array','into ".addNode(..., { ends: ["node1", "node2"] })".'].join("\n"),{lc_error_code:"UNREACHABLE_NODE"});for(const e of r)if(e!==Fs&&!(e in this.nodes))throw new Error(`Found edge ending at unknown node \`${e}\``);if(e)for(const t of e)if(!(t in this.nodes))throw new Error(`Interrupt node \`${t}\` is not present`);this.compiled=!0}}class Li extends Mi{constructor({builder:e,...t}){super(t),Object.defineProperty(this,"builder",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.builder=e}attachNode(e,t){this.channels[e]=new ji,this.nodes[e]=new Fa({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new Ra([{channel:e,value:Aa}],[aa])),this.streamChannels.push(e)}attachEdge(e,t){if(t===Fs){if(e===Ls)throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new Ra([{channel:Fs,value:Aa}],[aa]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,r){e!==Ls||this.nodes[Ls]||(this.nodes[Ls]=Ii.subscribeTo(Ls,{tags:[aa]})),this.nodes[e].pipe(r.run((r=>{const n=r.map((r=>ga(r)?r:{channel:r===Fs?Fs:`branch:${e}:${t}:${r}`,value:Aa}));return new Ra(n,[aa])})));const n=r.ends?Object.values(r.ends):Object.keys(this.nodes);for(const r of n)if(r!==Fs){const n=`branch:${e}:${t}:${r}`;this.channels[n]=new ji,this.nodes[r].triggers.push(n),this.nodes[r].channels.push(n)}}async getGraphAsync(e){const t=e?.xray,r=new js.T,n={[Ls]:r.addNode({schema:M.z.any()},Ls)},s={};let a={};function i(e,t,a,i=!1){if(t===Fs&&void 0===s[Fs]&&(s[Fs]=r.addNode({schema:M.z.any()},Fs)),void 0!==n[e]){if(void 0===s[t])throw new Error(`End node ${t} not found!`);return r.addEdge(n[e],s[t],a!==t?a:void 0,i)}}t&&(a=Object.fromEntries((await Ca(this.getSubgraphsAsync())).filter((e=>Fi(e[1])))));for(const[c,l]of Object.entries(this.builder.nodes)){const u=Di(c),d=l.runnable,h=l.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?h.__interrupt="before,after":this.interruptBefore?.includes(c)?h.__interrupt="before":this.interruptAfter?.includes(c)&&(h.__interrupt="after"),t){const p="number"==typeof t?t-1:t,m=void 0!==a[c]?await a[c].getGraphAsync({...e,xray:p}):d.getGraph(e);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){const[f,g]=r.extend(m,u);if(void 0===f)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);function y(e,t){if(void 0!==e&&!$s(e))return e;if(!(r=t)||!r.lc_runnable)return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e,e}catch(e){return t.getName()}var r}void 0!==g&&(n[u]={name:y(g.id,g.data),...g}),s[u]={name:y(f.id,f.data),...f}}else{const b=r.addNode(d,u,h);n[u]=b,s[u]=b}}else{const w=r.addNode(d,u,h);n[u]=w,s[u]=w}}const o=[...this.builder.allEdges].sort((([e],[t])=>ee?1:0));for(const[v,_]of o)i(Di(v),Di(_));for(const[k,S]of Object.entries(this.builder.branches)){const E={...Object.fromEntries(Object.keys(this.builder.nodes).filter((e=>e!==k)).map((e=>[Di(e),Di(e)]))),[Fs]:Fs};for(const x of Object.values(S)){let T;T=void 0!==x.ends?x.ends:E;for(const[C,P]of Object.entries(T))i(Di(k),Di(P),C,!0)}}for(const[O,A]of Object.entries(this.builder.nodes))if(void 0!==A.ends)for(const I of A.ends)i(Di(O),Di(I),void 0,!0);return r}getGraph(e){const t=e?.xray,r=new js.T,n={[Ls]:r.addNode({schema:M.z.any()},Ls)},s={};let a={};function i(e,t,a,i=!1){return t===Fs&&void 0===s[Fs]&&(s[Fs]=r.addNode({schema:M.z.any()},Fs)),r.addEdge(n[e],s[t],a!==t?a:void 0,i)}t&&(a=Object.fromEntries(Pa(this.getSubgraphs()).filter((e=>Fi(e[1])))));for(const[c,l]of Object.entries(this.builder.nodes)){const u=Di(c),d=l.runnable,h=l.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?h.__interrupt="before,after":this.interruptBefore?.includes(c)?h.__interrupt="before":this.interruptAfter?.includes(c)&&(h.__interrupt="after"),t){const p="number"==typeof t?t-1:t,m=void 0!==a[c]?a[c].getGraph({...e,xray:p}):d.getGraph(e);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){const[f,g]=r.extend(m,u);if(void 0===f)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);function y(e,t){if(void 0!==e&&!$s(e))return e;if(!(r=t)||!r.lc_runnable)return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e,e}catch(e){return t.getName()}var r}void 0!==g&&(n[u]={name:y(g.id,g.data),...g}),s[u]={name:y(f.id,f.data),...f}}else{const b=r.addNode(d,u,h);n[u]=b,s[u]=b}}else{const w=r.addNode(d,u,h);n[u]=w,s[u]=w}}const o=[...this.builder.allEdges].sort((([e],[t])=>ee?1:0));for(const[v,_]of o)i(Di(v),Di(_));for(const[k,S]of Object.entries(this.builder.branches)){const E={...Object.fromEntries(Object.keys(this.builder.nodes).filter((e=>e!==k)).map((e=>[Di(e),Di(e)]))),[Fs]:Fs};for(const x of Object.values(S)){let T;T=void 0!==x.ends?x.ends:E;for(const[C,P]of Object.entries(T))i(Di(k),Di(P),C,!0)}}return r}}function Fi(e){return"function"==typeof e.attachNode&&"function"==typeof e.attachEdge}function Di(e){return"subgraph"===e?`"${e}"`:e}const zi=(e,t)=>e.size===t.size&&[...e].every((e=>t.has(e)));class Ui extends Is{constructor(e){super(),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"NamedBarrierValue"}),Object.defineProperty(this,"names",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"seen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.names=e,this.seen=new Set}fromCheckpoint(e){const t=new Ui(this.names);return e&&(t.seen=new Set(e)),t}update(e){let t=!1;for(const r of e){if(!this.names.has(r))throw new Ps(`Value ${JSON.stringify(r)} not in names ${JSON.stringify(this.names)}`);this.seen.has(r)||(this.seen.add(r),t=!0)}return t}get(){if(!zi(this.names,this.seen))throw new Cs}checkpoint(){return[...this.seen]}consume(){return!!(this.seen&&this.names&&zi(this.seen,this.names))&&(this.seen=new Set,!0)}}class Bi extends Is{constructor(){super(...arguments),Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"LastValue"}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:[]})}fromCheckpoint(e){const t=new Bi;return e&&(t.value=[e]),t}update(e){if(0===e.length)return!1;if(1!==e.length)throw new Ps("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[e[e.length-1]],!0}get(){if(0===this.value.length)throw new Cs;return this.value[0]}checkpoint(){if(0===this.value.length)throw new Cs;return this.value[0]}}class qi{constructor(e){Object.defineProperty(this,"lc_graph_name",{enumerable:!0,configurable:!0,writable:!0,value:"AnnotationRoot"}),Object.defineProperty(this,"spec",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.spec=e}}const Ki=function(e){return Ei(e)?e:e?Wi(e):new Bi};function Wi(e){return"object"==typeof e&&e&&"reducer"in e&&e.reducer?new Ri(e.reducer,e.default):"object"==typeof e&&e&&"value"in e&&e.value?new Ri(e.value,e.default):new Bi}Ki.Root=e=>new qi(e);const Hi=new WeakMap;function Vi(e){return"object"==typeof e&&null!=e&&"_parse"in e&&"function"==typeof e._parse}function Gi(e){return Vi(e)&&"partial"in e&&"function"==typeof e.partial}function Ji(e){return Hi.get(e)}function Zi(e){const t={};for(const r in e.shape)if(Object.prototype.hasOwnProperty.call(e.shape,r)){const n=Ji(e.shape[r]);t[r]=n?.reducer?new Ri(n.reducer.fn,n.default):new Bi}return t}const Yi="__root__";class Xi extends $i{constructor(e,t){if(super(),Object.defineProperty(this,"channels",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"waitingEdges",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_schemaDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaRuntimeDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_inputDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_inputRuntimeDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_outputDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_outputRuntimeDefinition",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaDefinitions",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_configSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_configRuntimeSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),function(e){if("object"!=typeof e||null==e)return!1;if(!("state"in e)||!Gi(e.state))return!1;if("input"in e&&!Gi(e.input))return!1;if("output"in e&&!Gi(e.output))return!1;return!0}(e)){const t=Zi(e.state),r=null!=e.input?Zi(e.input):t,n=null!=e.output?Zi(e.output):t;this._schemaDefinition=t,this._schemaRuntimeDefinition=e.state,this._inputDefinition=r,this._inputRuntimeDefinition=e.input??e.state.partial(),this._outputDefinition=n,this._outputRuntimeDefinition=e.output??e.state}else if(Gi(e)){const t=Zi(e);this._schemaDefinition=t,this._schemaRuntimeDefinition=e,this._inputDefinition=t,this._inputRuntimeDefinition=e.partial(),this._outputDefinition=t,this._outputRuntimeDefinition=e}else if(function(e){return"object"==typeof e&&null!==e&&void 0===e.stateSchema&&void 0!==e.input&&void 0!==e.output}(e))this._schemaDefinition=e.input.spec,this._inputDefinition=e.input.spec,this._outputDefinition=e.output.spec;else if(function(e){return"object"==typeof e&&null!==e&&void 0!==e.stateSchema}(e))this._schemaDefinition=e.stateSchema.spec,this._inputDefinition=e.input?.spec??this._schemaDefinition,this._outputDefinition=e.output?.spec??this._schemaDefinition;else if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every((e=>"function"==typeof e||As(e)))}(e)||eo(e)){const t=eo(e)?e.spec:e;this._schemaDefinition=t}else{if(!function(e){return"object"==typeof e&&null!==e&&void 0!==e.channels}(e))throw new Error("Invalid StateGraph input.");{const t=function(e){const t={};for(const[r,n]of Object.entries(e))if(r===Yi)t[r]=Wi(n);else{t[r]=Wi(n)}return t}(e.channels);this._schemaDefinition=t}}this._inputDefinition??=this._schemaDefinition,this._outputDefinition??=this._schemaDefinition,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),Gi(t)&&(this._configRuntimeSchema=t.passthrough())}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap((([e,t])=>e.map((e=>[e,t]))))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(const[t,r]of Object.entries(e)){let e;if(e="function"==typeof r?r():r,void 0!==this.channels[t]){if(this.channels[t]!==e&&!Ei(e)&&"LastValue"!==e.lc_graph_name)throw new Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=e}}}addNode(e,t,r){if(e in this.channels)throw new Error(`${e} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(const t of[ha,pa])if(e.includes(t))throw new Error(`"${t}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),e in this.nodes)throw new Error(`Node \`${e}\` already present.`);if(e===Fs||e===Ls)throw new Error(`Node \`${e}\` is reserved.`);let n;void 0!==r?.input&&this._addSchema(r.input.spec),n=X.YN.isRunnable(t)?t:"function"==typeof t?new xa({func:t,name:e,trace:!1}):(0,X.Bp)(t);const s={runnable:n,retryPolicy:r?.retryPolicy,metadata:r?.metadata,input:r?.input?.spec??this._schemaDefinition,subgraphs:Ha(n)?[n]:r?.subgraphs,ends:r?.ends};return this.nodes[e]=s,this}addEdge(e,t){if("string"==typeof e)return super.addEdge(e,t);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(const t of e){if(t===Fs)throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some((e=>e===t)))throw new Error(`Need to add a node named "${t}" first`)}if(t===Fs)throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some((e=>e===t)))throw new Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}compile({checkpointer:e,store:t,interruptBefore:r,interruptAfter:n,name:s}={}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(n)?n:[]]);const a=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),i=1===a.length&&a[0]===Yi?Yi:a,o=Object.keys(this.channels),c=1===o.length&&o[0]===Yi?Yi:o,l=new Qi({builder:this,checkpointer:e,interruptAfter:n,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[Ls]:new ji},inputChannels:Ls,outputChannels:i,streamChannels:c,streamMode:"updates",store:t,name:s});l.attachNode(Ls);for(const[e,t]of Object.entries(this.nodes))l.attachNode(e,t);l.attachBranch(Ls,ia,ro(),{withReader:!1});for(const[e]of Object.entries(this.nodes))l.attachBranch(e,ia,ro(),{withReader:!1});for(const[e,t]of this.edges)l.attachEdge(e,t);for(const[e,t]of this.waitingEdges)l.attachEdge(e,t);for(const[e,t]of Object.entries(this.branches))for(const[r,n]of Object.entries(t))l.attachBranch(e,r,n);return l.validate()}}class Qi extends Li{attachNode(e,t){let r;r=e===Ls?Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).filter((([e,t])=>!Ei(t))).map((([e])=>e)):Object.keys(this.builder.channels);const n=e;const s=[{value:Aa,mapper:new xa({func:r.length&&r[0]===Yi?function(e){if(ba(e))return e.graph===ya.PARENT?null:e._updateAsTuples();if(Array.isArray(e)&&e.length>0&&e.some((e=>ba(e)))){const t=[];for(const r of e)if(ba(r)){if(r.graph===ya.PARENT)continue;t.push(...r._updateAsTuples())}else t.push([Yi,r]);return t}return null!=e?[[Yi,e]]:null}:function e(t){if(t){if(ba(t))return t.graph===ya.PARENT?null:t._updateAsTuples().filter((([e])=>r.includes(e)));if(Array.isArray(t)&&t.length>0&&t.some(ba)){const n=[];for(const s of t)if(ba(s)){if(s.graph===ya.PARENT)continue;n.push(...s._updateAsTuples().filter((([e])=>r.includes(e))))}else{const t=e(s);t&&n.push(...t??[])}return n}if("object"!=typeof t||Array.isArray(t)){const e=Array.isArray(t)?"array":typeof t;throw new Ps(`Expected node "${n.toString()}" to return an object or an array containing at least one Command object, received ${e}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}return Object.entries(t).filter((([e])=>r.includes(e)))}return null},trace:!1,recurse:!1})}];if(e===Ls)this.nodes[e]=new Fa({tags:[aa],triggers:[Ls],channels:[Ls],writers:[new Ra(s,[aa])]});else{const r=t?.input??this.builder._schemaDefinition,n=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(r)).map((e=>[e,e]))),a=1===Object.keys(n).length&&Yi in n;this.channels[e]=new ji(!1),this.nodes[e]=new Fa({triggers:[],channels:a?Object.keys(n):n,writers:[new Ra(s.concat({channel:e,value:e}),[aa])],mapper:a?void 0:e=>Object.fromEntries(Object.entries(e).filter((([e])=>e in n))),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,subgraphs:t?.subgraphs,ends:t?.ends})}}attachEdge(e,t){if(t!==Fs)if(Array.isArray(e)){const r=`join:${e.join("+")}:${t}`;this.channels[r]=new Ui(new Set(e)),this.nodes[t].triggers.push(r);for(const t of e)this.nodes[t].writers.push(new Ra([{channel:r,value:t}],[aa]))}else if(e===Ls){const e=`${Ls}:${t}`;this.channels[e]=new ji,this.nodes[t].triggers.push(e),this.nodes[Ls].writers.push(new Ra([{channel:e,value:Ls}],[aa]))}else this.nodes[t].triggers.push(e)}attachBranch(e,t,r,n={withReader:!0}){this.nodes[e].writers.push(r.run((async(r,n)=>{const s=r.filter((e=>e!==Fs));if(!s.length)return;const a=s.map((r=>ga(r)?r:{channel:`branch:${e}:${t}:${r}`,value:e}));await Ra.doWrite({...n,tags:(n.tags??[]).concat([aa])},a)}),n.withReader?e=>$a.doRead(e,this.streamChannels??this.outputChannels,!0):void 0));const s=r.ends?Object.values(r.ends):Object.keys(this.builder.nodes);for(const r of s){if(r===Fs)continue;const n=`branch:${e}:${t}:${r}`;this.channels[n]=new ji(!1),this.nodes[r].triggers.push(n)}}async _validateInput(e){const t=this.builder._inputRuntimeDefinition;if(ba(e)){const r=e;return e.update&&Gi(t)&&(r.update=t.parse(e.update)),r}return Gi(t)?t.parse(e):e}async _validateConfigurable(e){const t=this.builder._configRuntimeSchema;return Gi(t)&&t.parse(e),e}}function eo(e){return"object"==typeof e&&null!==e&&"lc_graph_name"in e&&"AnnotationRoot"===e.lc_graph_name}function to(e){if(ga(e))return[e];const t=[];ba(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(ba));const r=[];for(const e of t){if(e.graph===ya.PARENT)throw new ks(e);ga(e.goto)||"string"==typeof e.goto?r.push(e.goto):Array.isArray(e.goto)&&r.push(...e.goto)}return r}function ro(){const e=new xa({func:to,tags:[aa],trace:!1,recurse:!1,name:""});return new Ni({path:e})}const no={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};var so,ao=new Uint8Array(16);function io(){if(!so&&!(so="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return so(ao)}for(var oo=[],co=0;co<256;++co)oo.push((co+256).toString(16).slice(1));function lo(e,t=0){return(oo[e[t+0]]+oo[e[t+1]]+oo[e[t+2]]+oo[e[t+3]]+"-"+oo[e[t+4]]+oo[e[t+5]]+"-"+oo[e[t+6]]+oo[e[t+7]]+"-"+oo[e[t+8]]+oo[e[t+9]]+"-"+oo[e[t+10]]+oo[e[t+11]]+oo[e[t+12]]+oo[e[t+13]]+oo[e[t+14]]+oo[e[t+15]]).toLowerCase()}const uo=function(e,t,r){if(no.randomUUID&&!t&&!e)return no.randomUUID();var n=(e=e||{}).random||(e.rng||io)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(var s=0;s<16;++s)t[r+s]=n[s];return t}return lo(n)};function ho(e,t){const r=Array.isArray(e)?e:[e],n=Array.isArray(t)?t:[t],s=r.map(se.coerceMessageLikeToMessage),a=n.map(se.coerceMessageLikeToMessage);for(const e of s)null!==e.id&&void 0!==e.id||(e.id=uo(),e.lc_kwargs.id=e.id);for(const e of a)null!==e.id&&void 0!==e.id||(e.id=uo(),e.lc_kwargs.id=e.id);const i=[...s],o=new Map(i.map(((e,t)=>[e.id,t]))),c=new Set;for(const e of a){const t=o.get(e.id);if(void 0!==t)"remove"===e._getType()?c.add(e.id):(c.delete(e.id),i[t]=e);else{if("remove"===e._getType())throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${e.id}')`);o.set(e.id,i.length),i.push(e)}}return i.filter((e=>!c.has(e.id)))}class po extends xa{constructor(e,t){const{name:r,tags:n,handleToolErrors:s}=t??{};super({name:r,tags:n,func:(e,t)=>this.run(e,t)}),Object.defineProperty(this,"tools",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"handleToolErrors",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"trace",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.tools=e,this.handleToolErrors=s??this.handleToolErrors}async run(e,t){const r=Array.isArray(e)?e[e.length-1]:e.messages[e.messages.length-1];if("ai"!==r?._getType())throw new Error("ToolNode only accepts AIMessages as input.");const n=await Promise.all(r.tool_calls?.map((async e=>{const r=this.tools.find((t=>t.name===e.name));try{if(void 0===r)throw new Error(`Tool "${e.name}" not found.`);const n=await r.invoke({...e,type:"tool_call"},t);return(0,se.isBaseMessage)(n)&&"tool"===n._getType()||ba(n)?n:new se.ToolMessage({name:r.name,content:"string"==typeof n?n:JSON.stringify(n),tool_call_id:e.id})}catch(t){if(!this.handleToolErrors)throw t;if(xs(t))throw t;return new se.ToolMessage({content:`Error: ${t.message}\n Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}))??[]);if(!n.some(ba))return Array.isArray(e)?n:{messages:n};const s=[];let a=null;for(const t of n)ba(t)?t.graph===ya.PARENT&&Array.isArray(t.goto)&&t.goto.every((e=>ga(e)))?a?a.goto.push(...t.goto):a=new ya({graph:ya.PARENT,goto:t.goto}):s.push(t):s.push(Array.isArray(e)?[t]:{messages:[t]});return a&&s.push(a),s}}const mo=/(.*?)<\/name>/s,fo=/(.*?)<\/content>/s;function go(e){if(!((0,se.isBaseMessage)(e)&&((0,se.isAIMessage)(e)||(0,se.isBaseMessageChunk)(e)&&(0,se.isAIMessageChunk)(e)))||!e.name)return e;const{name:t}=e;if("string"==typeof e.content)return new se.AIMessage({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:`${t}${e.content}`,name:void 0});const r=[];let n=0;for(const s of e.content)"string"==typeof s?(n+=1,r.push(`${t}${s}`)):"object"==typeof s&&"type"in s&&"text"===s.type?(n+=1,r.push({...s,text:`${t}${s.text}`})):r.push(s);return n||r.unshift({type:"text",text:`${t}`}),new se.AIMessage({...e.lc_kwargs,content:r,name:void 0})}function yo(e){if(!(0,se.isAIMessage)(e)||!e.content)return e;let t,r=[];if(Array.isArray(e.content))r=e.content.filter((e=>{if("text"===e.type){const r=e.text.match(mo),n=e.text.match(fo);return!(r&&(!n||""===n[1]))||(t=r[1],!1)}return!0})).map((e=>{if("text"===e.type){const r=e.text.match(mo),n=e.text.match(fo);return r&&n?(t=r[1],{...e,text:n[1]}):e}return e}));else{const n=e.content,s=n.match(mo),a=n.match(fo);if(!s||!a)return e;t=s[1],r=a[1]}return new se.AIMessage({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:r,name:t})}const bo="prompt";function wo(e,t,r){if([e,t,r].filter((e=>null!=e)).length>1)throw new Error("Expected only one of prompt, stateModifier, or messageModifier, got multiple values");let n=e;return null!=t?n=t:null!=r&&(n=function(e){if("string"==typeof e||(0,se.isBaseMessage)(e)&&"system"===e._getType())return e;if("function"==typeof e)return async t=>e(t.messages);if(X.YN.isRunnable(e))return X.jY.from((e=>e.messages)).pipe(e);throw new Error("Unexpected type for messageModifier: "+typeof e)}(r)),function(e){let t;if(null==e)t=X.jY.from((e=>e.messages)).withConfig({runName:bo});else if("string"==typeof e){const r=new se.SystemMessage(e);t=X.jY.from((e=>[r,...e.messages??[]])).withConfig({runName:bo})}else if((0,se.isBaseMessage)(e)&&"system"===e._getType())t=X.jY.from((t=>[e,...t.messages])).withConfig({runName:bo});else if("function"==typeof e)t=X.jY.from(e).withConfig({runName:bo});else{if(!X.YN.isRunnable(e))throw new Error("Got unexpected type for 'prompt': "+typeof e);t=e}return t}(n)}function vo(e){return"invoke"in e&&"function"==typeof e.invoke&&"_modelType"in e}function _o(e){return"_queuedMethodOperations"in e&&"_model"in e&&"function"==typeof e._model}async function ko(e){let t=e;if(X.zZ.isRunnableSequence(t)&&(t=t.steps.find((e=>X.fJ.isRunnableBinding(e)||vo(e)||_o(e)))||t),_o(t)&&(t=await t._model()),X.fJ.isRunnableBinding(t)&&(t=t.bound),!vo(t))throw new Error(`Expected \`llm\` to be a ChatModel or RunnableBinding (e.g. llm.bind_tools(...)) with invoke() and generate() methods, got ${t.constructor.name}`);return t}function So(e){const{llm:t,tools:r,messageModifier:n,stateModifier:s,prompt:a,stateSchema:i,checkpointSaver:o,checkpointer:c,interruptBefore:l,interruptAfter:u,store:d,responseFormat:h,name:p,includeAgentName:m}=e;let f,g;Array.isArray(r)?(f=r,g=new po(r)):(f=r.tools,g=r);let y=null;const b=async e=>{if(y)return y;let t;if(await async function(e,t){let r=e;if(X.zZ.isRunnableSequence(r)&&(r=r.steps.find((e=>X.fJ.isRunnableBinding(e)||vo(e)||_o(e)))||r),_o(r)&&(r=await r._model()),!X.fJ.isRunnableBinding(r))return!0;if(!r.kwargs||"object"!=typeof r.kwargs||!("tools"in r.kwargs))return!0;let n=r.kwargs.tools;if(1===n.length&&"functionDeclarations"in n[0]&&(n=n[0].functionDeclarations),t.length!==n.length)throw new Error("Number of tools in the model.bindTools() and tools passed to createReactAgent must match");const s=new Set(t.map((e=>e.name))),a=new Set;for(const e of n){let t;if("type"in e&&"function"===e.type)t=e.function.name;else if("name"in e)t=e.name;else{if(!("toolSpec"in e)||!("name"in e.toolSpec))continue;t=e.toolSpec.name}t&&a.add(t)}const i=[...s].filter((e=>!a.has(e)));if(i.length>0)throw new Error(`Missing tools '${i}' in the model.bindTools().Tools in the model.bindTools() must match the tools passed to createReactAgent.`);return!1}(e,f)){if(!("bindTools"in e)||"function"!=typeof e.bindTools)throw new Error(`llm ${e} must define bindTools method.`);t=e.bindTools(f)}else t=e;const r=wo(a,s,n),i="inline"===m?r.pipe(function(e,t){let r,n;if("inline"!==t)throw new Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);return r=go,n=yo,X.zZ.from([X.jY.from((function(e){return e.map(r)})),e,X.jY.from(n)])}(t,m)):r.pipe(t);return y=i,i},w=new Set(f.filter((e=>"returnDirect"in e&&e.returnDirect)).map((e=>e.name))),v=e=>{const{messages:t}=e,r=t[t.length-1];return!(0,se.isAIMessage)(r)||r.tool_calls&&0!==r.tool_calls.length?"continue":null!=h?"generate_structured_response":Fs},_=async(e,r)=>{if(null==h)throw new Error("Attempted to generate structured output with no passed response schema. Please contact us for help.");const n=[...e.messages];let s;if("object"==typeof h&&"prompt"in h&&"schema"in h){const{prompt:e,schema:r}=h;s=(await ko(t)).withStructuredOutput(r),n.unshift(new se.SystemMessage({content:e}))}else s=(await ko(t)).withStructuredOutput(h);return{structuredResponse:await s.invoke(n,r)}},k=new Xi(i??Ki.Root({messages:Ki({reducer:ho,default:()=>[]}),structuredResponse:Ki})).addNode("agent",(async(e,r)=>{const n=await b(t),s=await n.invoke(e,r);return s.name=p,s.lc_kwargs.name=p,{messages:[s]}})).addNode("tools",g).addEdge(Ls,"agent");void 0!==h?k.addNode("generate_structured_response",_).addEdge("generate_structured_response",Fs).addConditionalEdges("agent",v,{continue:"tools",[Fs]:Fs,generate_structured_response:"generate_structured_response"}):k.addConditionalEdges("agent",v,{continue:"tools",[Fs]:Fs});const S=e=>{for(let t=e.messages.length-1;t>=0;t-=1){const r=e.messages[t];if(!(0,se.isToolMessage)(r))break;if(void 0!==r.name&&w.has(r.name))return Fs}return"agent"};return w.size>0?k.addConditionalEdges("tools",S,["agent",Fs]):k.addEdge("tools","agent"),k.compile({checkpointer:c??o,interruptBefore:l,interruptAfter:u,store:d,name:p})}var Eo=function(e,t){return(Eo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(e,t)};function xo(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}Eo(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function To(e,t,r,n){return new(r||(r=Promise))((function(s,a){function i(e){try{c(n.next(e))}catch(e){a(e)}}function o(e){try{c(n.throw(e))}catch(e){a(e)}}function c(e){e.done?s(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(i,o)}c((n=n.apply(e,t||[])).next())}))}function Co(e,t){var r,n,s,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=o(0),i.throw=o(1),i.return=o(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function o(o){return function(c){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,o[0]&&(a=0)),a;)try{if(r=1,n&&(s=2&o[0]?n.return:o[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,o[1])).done)return s;switch(n=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(s=a.trys,(s=s.length>0&&s[s.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Oo(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,s,a=r.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(s)throw s.error}}return i}function Ao(e,t,r){if(r||2===arguments.length)for(var n,s=0,a=t.length;s1||o(e,t)}))},t&&(n[e]=t(n[e])))}function o(e,t){try{(r=s[e](t)).value instanceof Io?Promise.resolve(r.value.v).then(c,l):u(a[0][2],r)}catch(e){u(a[0][3],e)}var r}function c(e){o("next",e)}function l(e){o("throw",e)}function u(e,t){e(t),a.shift(),a.length&&o(a[0][0],a[0][1])}}function Ro(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=Po(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,s){(function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)})(n,s,(t=e[r](t)).done,t.value)}))}}}function jo(e){return"function"==typeof e}function No(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var $o=No((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function Lo(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var Fo=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,r,n,s;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var i=Po(a),o=i.next();!o.done;o=i.next()){o.value.remove(this)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}else a.remove(this);var c=this.initialTeardown;if(jo(c))try{c()}catch(e){s=e instanceof $o?e.errors:[e]}var l=this._finalizers;if(l){this._finalizers=null;try{for(var u=Po(l),d=u.next();!d.done;d=u.next()){var h=d.value;try{Uo(h)}catch(e){s=null!=s?s:[],e instanceof $o?s=Ao(Ao([],Oo(s)),Oo(e.errors)):s.push(e)}}}catch(e){r={error:e}}finally{try{d&&!d.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}}if(s)throw new $o(s)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)Uo(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&Lo(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&Lo(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}(),Do=Fo.EMPTY;function zo(e){return e instanceof Fo||e&&"closed"in e&&jo(e.remove)&&jo(e.add)&&jo(e.unsubscribe)}function Uo(e){jo(e)?e():e.unsubscribe()}var Bo=null,qo=null,Ko=void 0,Wo=!1,Ho=!1,Vo={setTimeout:function(e,t){for(var r=[],n=2;n0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,r=this,n=r.hasError,s=r.isStopped,a=r.observers;return n||s?Do:(this.currentObservers=null,a.push(e),new Fo((function(){t.currentObservers=null,Lo(a,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,r=t.hasError,n=t.thrownError,s=t.isStopped;r?e.error(n):s&&e.complete()},t.prototype.asObservable=function(){var e=new dc;return e.source=this,e},t.create=function(e,t){return new bc(e,t)},t}(dc),bc=function(e){function t(t,r){var n=e.call(this)||this;return n.destination=t,n.source=r,n}return xo(t,e),t.prototype.next=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===r||r.call(t,e)},t.prototype.error=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===r||r.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,r;return null!==(r=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==r?r:Do},t}(yc),wc={now:function(){return(wc.delegate||Date).now()},delegate:void 0},vc=function(e){function t(t,r,n){void 0===t&&(t=1/0),void 0===r&&(r=1/0),void 0===n&&(n=wc);var s=e.call(this)||this;return s._bufferSize=t,s._windowTime=r,s._timestampProvider=n,s._buffer=[],s._infiniteTimeWindow=!0,s._infiniteTimeWindow=r===1/0,s._bufferSize=Math.max(1,t),s._windowTime=Math.max(1,r),s}return xo(t,e),t.prototype.next=function(t){var r=this,n=r.isStopped,s=r._buffer,a=r._infiniteTimeWindow,i=r._timestampProvider,o=r._windowTime;n||(s.push(t),!a&&s.push(i.now()+o)),this._trimBuffer(),e.prototype.next.call(this,t)},t.prototype._subscribe=function(e){this._throwIfClosed(),this._trimBuffer();for(var t=this._innerSubscribe(e),r=this._infiniteTimeWindow,n=this._buffer.slice(),s=0;s=2;return function(n){return n.pipe(e?fl((function(t,r){return e(t,r,n)})):lc,wl(1),r?bl(t):_l((function(){return new Jc})))}}function El(){for(var e=[],t=0;t1){let t=null;for(const r of e.reverse())t=null===t?r:new Il(r,t);throw t}}[Symbol.toStringTag]="DisposableStack"}class Al{#t=!1;#r=[];get disposed(){return this.#t}async dispose(){await this[Pl]()}use(e){if(e){const t=e[Pl],r=e[Cl];"function"==typeof t?this.#r.push(e):"function"==typeof r&&this.#r.push({[Pl]:async()=>{e[Cl]()}})}return e}adopt(e,t){return this.#r.push({[Pl]:()=>t(e)}),e}defer(e){this.#r.push({[Pl]:()=>e()})}move(){if(this.#t)throw new ReferenceError("A disposed stack can not use anything new");const e=new Al;return e.#r=this.#r,this.#r=[],this.#t=!0,e}async[Pl](){if(this.#t)return;this.#t=!0;const e=[];for(const t of this.#r.reverse())try{await t[Pl]()}catch(t){e.push(t)}if(1===e.length)throw e[0];if(e.length>1){let t=null;for(const r of e.reverse())t=null===t?r:new Il(r,t);throw t}}[Symbol.toStringTag]="AsyncDisposableStack"}class Il extends Error{#n;#s;constructor(e,t,r="An error was suppressed during disposal"){super(r),this.name="SuppressedError",this.#n=e,this.#s=t}get error(){return this.#n}get suppressed(){return this.#s}}class Ml{#a;#i=new Map;constructor(e=function(e){return{all:e=e||new Map,on:function(t,r){var n=e.get(t);n?n.push(r):e.set(t,[r])},off:function(t,r){var n=e.get(t);n&&(r?n.splice(n.indexOf(r)>>>0,1):e.set(t,[]))},emit:function(t,r){var n=e.get(t);n&&n.slice().map((function(e){e(r)})),(n=e.get("*"))&&n.slice().map((function(e){e(t,r)}))}}}(new Map)){this.#a=e}on(e,t){const r=this.#i.get(e);return void 0===r?this.#i.set(e,[t]):r.push(t),this.#a.on(e,t),this}off(e,t){const r=this.#i.get(e)??[];if(void 0===t){for(const t of r)this.#a.off(e,t);return this.#i.delete(e),this}const n=r.lastIndexOf(t);return n>-1&&this.#a.off(e,...r.splice(n,1)),this}emit(e,t){return this.#a.emit(e,t),this.listenerCount(e)>0}once(e,t){const r=n=>{t(n),this.off(e,r)};return this.on(e,r)}listenerCount(e){return this.#i.get(e)?.length||0}removeAllListeners(e){return void 0!==e?this.off(e):(this[Cl](),this)}[Cl](){for(const[e,t]of this.#i)for(const r of t)this.#a.off(e,r);this.#i.clear()}}const Rl=!("undefined"==typeof process||!process.version),jl={value:{get fs(){throw new Error("fs is not available in this environment")},get ScreenRecorder(){throw new Error("ScreenRecorder is not available in this environment")}}};var Nl=s(809);const $l=(e,t)=>{if(!e)throw new Error(t)};function Ll(e,t=!1){return t?"function"==typeof Buffer?Buffer.from(e,"base64"):Uint8Array.from(atob(e),(e=>e.codePointAt(0))):(new TextEncoder).encode(e)}function Fl(e){const t=[];for(let r=0;rRl?async(...t)=>{Bl&&Ul.push(e+t),(await async function(){return Dl||(Dl=(await Promise.resolve().then(s.t.bind(s,7833,19))).default),Dl}())(e)(t)}:(...t)=>{const r=globalThis.__PUPPETEER_DEBUG;if(!r)return;("*"===r||(r.endsWith("*")?e.startsWith(r):e===r))&&console.log(`${e}:`,...t)};let Ul=[],Bl=!1;class ql extends Error{constructor(e,t){super(e,t),this.name=this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}class Kl extends ql{}class Wl extends ql{}class Hl extends ql{#o;#c="";set code(e){this.#o=e}get code(){return this.#o}set originalMessage(e){this.#c=e}get originalMessage(){return this.#c}}class Vl extends ql{}class Gl extends Hl{}const Jl={letter:{cm:{width:21.59,height:27.94},in:{width:8.5,height:11}},legal:{cm:{width:21.59,height:35.56},in:{width:8.5,height:14}},tabloid:{cm:{width:27.94,height:43.18},in:{width:11,height:17}},ledger:{cm:{width:43.18,height:27.94},in:{width:17,height:11}},a0:{cm:{width:84.1,height:118.9},in:{width:33.1102,height:46.811}},a1:{cm:{width:59.4,height:84.1},in:{width:23.3858,height:33.1102}},a2:{cm:{width:42,height:59.4},in:{width:16.5354,height:23.3858}},a3:{cm:{width:29.7,height:42},in:{width:11.6929,height:16.5354}},a4:{cm:{width:21,height:29.7},in:{width:8.2677,height:11.6929}},a5:{cm:{width:14.8,height:21},in:{width:5.8268,height:8.2677}},a6:{cm:{width:10.5,height:14.8},in:{width:4.1339,height:5.8268}}},Zl=zl("puppeteer:error"),Yl=Object.freeze({width:800,height:600}),Xl=Symbol("Source URL for Puppeteer evaluation scripts");class Ql{static INTERNAL_URL="pptr:internal";static fromCallSite(e,t){const r=new Ql;return r.#l=e,r.#u=t.toString(),r}static parse=e=>{e=e.slice(5);const[t="",r=""]=e.split(";"),n=new Ql;return n.#l=t,n.#u=decodeURIComponent(r),n};static isPuppeteerURL=e=>e.startsWith("pptr:");#l;#u;get functionName(){return this.#l}get siteString(){return this.#u}toString(){return`pptr:${[this.#l,encodeURIComponent(this.#u)].join(";")}`}}const eu=(e,t)=>{if(Object.prototype.hasOwnProperty.call(t,Xl))return t;const r=Error.prepareStackTrace;Error.prepareStackTrace=(e,t)=>t[2];const n=(new Error).stack;return Error.prepareStackTrace=r,Object.assign(t,{[Xl]:Ql.fromCallSite(e,n)})},tu=e=>"string"==typeof e||e instanceof String;function ru(e,...t){if(tu(e))return $l(0===t.length,"Cannot evaluate a string with arguments"),e;return`(${e})(${t.map((function(e){return Object.is(e,void 0)?"undefined":JSON.stringify(e)})).join(",")})`}async function nu(e,t){const r=[],n=e.getReader();if(t){const e=await jl.value.fs.promises.open(t,"w+");try{for(;;){const{done:t,value:s}=await n.read();if(t)break;r.push(s),await e.writeFile(s)}}finally{await e.close()}}else for(;;){const{done:e,value:t}=await n.read();if(e)break;r.push(t)}try{const e=function(e){let t=0;for(const r of e)t+=r.length;const r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}(r);return 0===e.length?null:e}catch(e){return Zl(e),null}}async function su(e,t){return new ReadableStream({async pull(r){const{data:n,base64Encoded:s,eof:a}=await e.send("IO.read",{handle:t});r.enqueue(Ll(n,s??!1)),a&&(await e.send("IO.close",{handle:t}),r.close())}})}function au(e,t){return 0===e?hl:ul(e).pipe(Yc((()=>{throw new Kl(`Timed out after waiting ${e}ms`,{cause:t})})))}const iu="__puppeteer_utility_world__"+Nl.T,ou=/^[\x20\t]*\/\/[@#] sourceURL=\s{0,10}(\S*?)\s{0,10}$/m;const cu=500;const lu={px:1,in:96,cm:37.8,mm:3.78};function uu(e,t="in"){if(void 0===e)return;let r;if((e=>"number"==typeof e||e instanceof Number)(e))r=e;else{if(!tu(e))throw new Error("page.pdf() Cannot handle parameter type: "+typeof e);{const t=e;let n=t.substring(t.length-2).toLowerCase(),s="";n in lu?s=t.substring(0,t.length-2):(n="px",s=t);const a=Number(s);$l(!isNaN(a),"Failed to parse parameter value: "+t),r=a*lu[n]}}return r/lu[t]}function du(e,t){return new dc((r=>{const n=e=>{r.next(e)};return e.on(t,n),()=>{e.off(t,n)}}))}function hu(e,t){return e?cl(e,"abort").pipe(Yc((()=>{if(e.reason instanceof Error)throw e.reason.cause=t,e.reason;throw new Error(e.reason,{cause:t})}))):hl}function pu(e){return tl((t=>Vc(Promise.resolve(e(t))).pipe(fl((e=>e)),Yc((()=>t)))))}const mu=new Map([["accelerometer","sensors"],["ambient-light-sensor","sensors"],["background-sync","backgroundSync"],["camera","videoCapture"],["clipboard-read","clipboardReadWrite"],["clipboard-sanitized-write","clipboardSanitizedWrite"],["clipboard-write","clipboardReadWrite"],["geolocation","geolocation"],["gyroscope","sensors"],["idle-detection","idleDetection"],["keyboard-lock","keyboardLock"],["magnetometer","sensors"],["microphone","audioCapture"],["midi","midi"],["notifications","notifications"],["payment-handler","paymentHandler"],["persistent-storage","durableStorage"],["pointer-lock","pointerLock"],["midi-sysex","midiSysex"]]);class fu extends Ml{constructor(){super()}async waitForTarget(e,t={}){const{timeout:r=3e4,signal:n}=t;return await Zc(dl(du(this,"targetcreated"),du(this,"targetchanged"),Vc(this.targets())).pipe(pu(e),El(hu(n),au(r))))}async pages(){const e=await Promise.all(this.browserContexts().map((e=>e.pages())));return e.reduce(((e,t)=>e.concat(t)),[])}async cookies(){return await this.defaultBrowserContext().cookies()}async setCookie(...e){return await this.defaultBrowserContext().setCookie(...e)}async deleteCookie(...e){return await this.defaultBrowserContext().deleteCookie(...e)}isConnected(){return this.connected}[Cl](){this.process()?this.close().catch(Zl):this.disconnect().catch(Zl)}[Pl](){return this.process()?this.close():this.disconnect()}}class gu{static create(e){return new gu(e)}static async race(e){const t=new Set;try{const r=e.map((e=>e instanceof gu?(e.#d&&t.add(e),e.valueOrThrow()):e));return await Promise.race(r)}finally{for(const e of t)e.reject(new Error("Timeout cleared"))}}#h=!1;#p=!1;#m;#f;#g=new Promise((e=>{this.#f=e}));#d;#y;constructor(e){e&&e.timeout>0&&(this.#y=new Kl(e.message),this.#d=setTimeout((()=>{this.reject(this.#y)}),e.timeout))}#b(e){clearTimeout(this.#d),this.#m=e,this.#f()}resolve(e){this.#p||this.#h||(this.#h=!0,this.#b(e))}reject(e){this.#p||this.#h||(this.#p=!0,this.#b(e))}resolved(){return this.#h}finished(){return this.#h||this.#p}value(){return this.#m}#w;valueOrThrow(){return this.#w||(this.#w=(async()=>{if(await this.#g,this.#p)throw this.#m;return this.#m})()),this.#w}}class yu{static Guard=class{#v;#_;constructor(e,t){this.#v=e,this.#_=t}[Cl](){return this.#_?.(),this.#v.release()}};#k=!1;#S=[];async acquire(e){if(!this.#k)return this.#k=!0,new yu.Guard(this);const t=gu.create();return this.#S.push(t.resolve.bind(t)),await t.valueOrThrow(),new yu.Guard(this,e)}release(){const e=this.#S.shift();e?e():this.#k=!1}}class bu extends Ml{constructor(){super()}#E;#x=0;startScreenshot(){const e=this.#E||new yu;return this.#E=e,this.#x++,e.acquire((()=>{this.#x--,0===this.#x&&(this.#E=void 0)}))}waitForScreenshotOperations(){return this.#E?.acquire()}async waitForTarget(e,t={}){const{timeout:r=3e4}=t;return await Zc(dl(du(this,"targetcreated"),du(this,"targetchanged"),Vc(this.targets())).pipe(pu(e),El(au(r))))}async deleteCookie(...e){return await this.setCookie(...e.map((e=>({...e,expires:1}))))}get closed(){return!this.browser().browserContexts().includes(this)}get id(){}[Cl](){this.close().catch(Zl)}[Pl](){return this.close()}}var wu;!function(e){e.Disconnected=Symbol("CDPSession.Disconnected"),e.Swapped=Symbol("CDPSession.Swapped"),e.Ready=Symbol("CDPSession.Ready"),e.SessionAttached="sessionattached",e.SessionDetached="sessiondetached"}(wu||(wu={}));class vu extends Ml{constructor(){super()}parentSession(){}}const _u=Symbol("_isElementHandle");function ku(e){return"object"==typeof e&&null!==e&&"name"in e&&"message"in e}function Su(e,t,r){return e.message=t,e.originalMessage=r??e.originalMessage,e}function Eu(e){let t=e.error.message;return e.error&&"object"==typeof e.error&&"data"in e.error&&(t+=` ${e.error.data}`),t}const xu=new Map;function Tu(e){let t=e.toString();try{new Function(`(${t})`)}catch(e){if(e.message.includes("Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive"))return t;let r="function ";t.startsWith("async ")&&(r=`async ${r}`,t=t.substring(6)),t=`${r}${t}`;try{new Function(`(${t})`)}catch{throw new Error("Passed function cannot be serialized!")}}return t}const Cu=(e,t)=>{let r=Tu(e);for(const[e,n]of Object.entries(t))r=r.replace(new RegExp(`PLACEHOLDER\\(\\s*(?:'${e}'|"${e}")\\s*\\)`,"g"),`(${n})`);return(e=>{let t=xu.get(e);return t||(t=new Function(`return ${e}`)(),xu.set(e,t),t)})(r)};var Pu=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Ou=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,s=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===s)return s=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return s|=2,Promise.resolve(a).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});async function*Au(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Pu(r,await e.evaluateHandle((async(e,t)=>{const r=[];for(;r.length{for(const e of a){const t={stack:[],error:void 0,hasError:!1};try{Pu(t,e,!1)[Cl]()}catch(e){t.error=e,t.hasError=!0}finally{Ou(t)}}})),yield*a,0===s.size}catch(e){r.error=e,r.hasError=!0}finally{Ou(r)}}async function*Iu(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Pu(t,await e.evaluateHandle((e=>async function*(){yield*e}())),!1);yield*async function*(e){let t=20;for(;!(yield*Au(e,t));)t<<=1}(r)}catch(e){t.error=e,t.hasError=!0}finally{Ou(t)}}class Mu{static create=e=>new Mu(e);#T;constructor(e){this.#T=e}async get(e){return await this.#T(e)}}var Ru=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},ju=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,s=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===s)return s=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return s|=2,Promise.resolve(a).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Nu{static querySelectorAll;static querySelector;static get _querySelector(){if(this.querySelector)return this.querySelector;if(!this.querySelectorAll)throw new Error("Cannot create default `querySelector`.");return this.querySelector=Cu((async(e,t,r)=>{const n=PLACEHOLDER("querySelectorAll")(e,t,r);for await(const e of n)return e;return null}),{querySelectorAll:Tu(this.querySelectorAll)})}static get _querySelectorAll(){if(this.querySelectorAll)return this.querySelectorAll;if(!this.querySelector)throw new Error("Cannot create default `querySelectorAll`.");return this.querySelectorAll=Cu((async function*(e,t,r){const n=PLACEHOLDER("querySelector"),s=await n(e,t,r);s&&(yield s)}),{querySelector:Tu(this.querySelector)})}static async*queryAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Ru(r,await e.evaluateHandle(this._querySelectorAll,t,Mu.create((e=>e.puppeteerUtil))),!1);yield*Iu(n)}catch(e){r.error=e,r.hasError=!0}finally{ju(r)}}static async queryOne(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Ru(r,await e.evaluateHandle(this._querySelector,t,Mu.create((e=>e.puppeteerUtil))),!1);return _u in n?n.move():null}catch(e){r.error=e,r.hasError=!0}finally{ju(r)}}static async waitFor(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{let s;const a=Ru(n,await(async()=>{if(_u in e)return s=e.frame,await s.isolatedRealm().adoptHandle(e);s=e})(),!1),{visible:i=!1,hidden:o=!1,timeout:c,signal:l}=r,u=i||o?"raf":r.polling;try{const e={stack:[],error:void 0,hasError:!1};try{l?.throwIfAborted();const r=Ru(e,await s.isolatedRealm().waitForFunction((async(e,t,r,n,s)=>{const a=e.createFunction(t),i=await a(n??document,r,e);return e.checkVisibility(i,s)}),{polling:u,root:a,timeout:c,signal:l},Mu.create((e=>e.puppeteerUtil)),Tu(this._querySelector),t,a,!!i||!o&&void 0),!1);if(l?.aborted)throw l.reason;return _u in r?await s.mainRealm().transferHandle(r):null}catch(t){e.error=t,e.hasError=!0}finally{ju(e)}}catch(e){if(!ku(e))throw e;if("AbortError"===e.name)throw e;throw e.message=`Waiting for selector \`${t}\` failed: ${e.message}`,e}}catch(e){n.error=e,n.hasError=!0}finally{ju(n)}}}class $u{static async*map(e,t){for await(const r of e)yield await t(r)}static async*flatMap(e,t){for await(const r of e)yield*t(r)}static async collect(e){const t=[];for await(const r of e)t.push(r);return t}static async first(e){for await(const t of e)return t}}const Lu=/\[\s*(?\w+)\s*=\s*(?"|')(?\\.|.*?(?=\k))\k\s*\]/g;class Fu extends Nu{static querySelector=async(e,t,{ariaQuerySelector:r})=>await r(e,t);static async*queryAll(e,t){const{name:r,role:n}=(e=>{if(e.length>1e4)throw new Error(`Selector ${e} is too long`);const t={},r=e.replace(Lu,((e,r,n,s)=>($l((e=>["name","role"].includes(e))(r),`Unknown aria attribute "${r}" in selector`),t[r]=s,"")));return r&&!t.name&&(t.name=r),t})(t);yield*e.queryAXTree(r,n)}static queryOne=async(e,t)=>await $u.first(this.queryAll(e,t))??null}class Du extends Nu{static querySelector=(e,t,{cssQuerySelector:r})=>r(e,t);static querySelectorAll=(e,t,{cssQuerySelectorAll:r})=>r(e,t)}const zu=new class{#C=!1;#P=new Set;append(e){this.#O((()=>{this.#P.add(e)}))}pop(e){this.#O((()=>{this.#P.delete(e)}))}inject(e,t=!1){(this.#C||t)&&e(this.#T()),this.#C=!1}#O(e){e(),this.#C=!0}#T(){return`(() => {\n const module = {};\n "use strict";var g=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var l=(t,e)=>{for(var r in e)g(t,r,{get:e[r],enumerable:!0})},J=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of B(e))!Y.call(t,n)&&n!==r&&g(t,n,{get:()=>e[n],enumerable:!(o=X(e,n))||o.enumerable});return t};var z=t=>J(g({},"__esModule",{value:!0}),t);var pe={};l(pe,{default:()=>he});module.exports=z(pe);var N=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}},p=class extends N{};var c=class t{static create(e){return new t(e)}static async race(e){let r=new Set;try{let o=e.map(n=>n instanceof t?(n.#n&&r.add(n),n.valueOrThrow()):n);return await Promise.race(o)}finally{for(let o of r)o.reject(new Error("Timeout cleared"))}}#e=!1;#r=!1;#o;#t;#a=new Promise(e=>{this.#t=e});#n;#i;constructor(e){e&&e.timeout>0&&(this.#i=new p(e.message),this.#n=setTimeout(()=>{this.reject(this.#i)},e.timeout))}#l(e){clearTimeout(this.#n),this.#o=e,this.#t()}resolve(e){this.#r||this.#e||(this.#e=!0,this.#l(e))}reject(e){this.#r||this.#e||(this.#r=!0,this.#l(e))}resolved(){return this.#e}finished(){return this.#e||this.#r}value(){return this.#o}#s;valueOrThrow(){return this.#s||(this.#s=(async()=>{if(await this.#a,this.#r)throw this.#o;return this.#o})()),this.#s}};var L=new Map,F=t=>{let e=L.get(t);return e||(e=new Function(\`return \${t}\`)(),L.set(t,e),e)};var x={};l(x,{ariaQuerySelector:()=>G,ariaQuerySelectorAll:()=>b});var G=(t,e)=>globalThis.__ariaQuerySelector(t,e),b=async function*(t,e){yield*await globalThis.__ariaQuerySelectorAll(t,e)};var E={};l(E,{cssQuerySelector:()=>K,cssQuerySelectorAll:()=>Z});var K=(t,e)=>t.querySelector(e),Z=function(t,e){return t.querySelectorAll(e)};var A={};l(A,{customQuerySelectors:()=>P});var v=class{#e=new Map;register(e,r){if(!r.queryOne&&r.queryAll){let o=r.queryAll;r.queryOne=(n,i)=>{for(let s of o(n,i))return s;return null}}else if(r.queryOne&&!r.queryAll){let o=r.queryOne;r.queryAll=(n,i)=>{let s=o(n,i);return s?[s]:[]}}else if(!r.queryOne||!r.queryAll)throw new Error("At least one query method must be defined.");this.#e.set(e,{querySelector:r.queryOne,querySelectorAll:r.queryAll})}unregister(e){this.#e.delete(e)}get(e){return this.#e.get(e)}clear(){this.#e.clear()}},P=new v;var R={};l(R,{pierceQuerySelector:()=>ee,pierceQuerySelectorAll:()=>te});var ee=(t,e)=>{let r=null,o=n=>{let i=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT);do{let s=i.currentNode;s.shadowRoot&&o(s.shadowRoot),!(s instanceof ShadowRoot)&&s!==n&&!r&&s.matches(e)&&(r=s)}while(!r&&i.nextNode())};return t instanceof Document&&(t=t.documentElement),o(t),r},te=(t,e)=>{let r=[],o=n=>{let i=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT);do{let s=i.currentNode;s.shadowRoot&&o(s.shadowRoot),!(s instanceof ShadowRoot)&&s!==n&&s.matches(e)&&r.push(s)}while(i.nextNode())};return t instanceof Document&&(t=t.documentElement),o(t),r};var u=(t,e)=>{if(!t)throw new Error(e)};var y=class{#e;#r;#o;#t;constructor(e,r){this.#e=e,this.#r=r}async start(){let e=this.#t=c.create(),r=await this.#e();if(r){e.resolve(r);return}this.#o=new MutationObserver(async()=>{let o=await this.#e();o&&(e.resolve(o),await this.stop())}),this.#o.observe(this.#r,{childList:!0,subtree:!0,attributes:!0})}async stop(){u(this.#t,"Polling never started."),this.#t.finished()||this.#t.reject(new Error("Polling stopped")),this.#o&&(this.#o.disconnect(),this.#o=void 0)}result(){return u(this.#t,"Polling never started."),this.#t.valueOrThrow()}},w=class{#e;#r;constructor(e){this.#e=e}async start(){let e=this.#r=c.create(),r=await this.#e();if(r){e.resolve(r);return}let o=async()=>{if(e.finished())return;let n=await this.#e();if(!n){window.requestAnimationFrame(o);return}e.resolve(n),await this.stop()};window.requestAnimationFrame(o)}async stop(){u(this.#r,"Polling never started."),this.#r.finished()||this.#r.reject(new Error("Polling stopped"))}result(){return u(this.#r,"Polling never started."),this.#r.valueOrThrow()}},S=class{#e;#r;#o;#t;constructor(e,r){this.#e=e,this.#r=r}async start(){let e=this.#t=c.create(),r=await this.#e();if(r){e.resolve(r);return}this.#o=setInterval(async()=>{let o=await this.#e();o&&(e.resolve(o),await this.stop())},this.#r)}async stop(){u(this.#t,"Polling never started."),this.#t.finished()||this.#t.reject(new Error("Polling stopped")),this.#o&&(clearInterval(this.#o),this.#o=void 0)}result(){return u(this.#t,"Polling never started."),this.#t.valueOrThrow()}};var _={};l(_,{PCombinator:()=>H,pQuerySelector:()=>fe,pQuerySelectorAll:()=>$});var a=class{static async*map(e,r){for await(let o of e)yield await r(o)}static async*flatMap(e,r){for await(let o of e)yield*r(o)}static async collect(e){let r=[];for await(let o of e)r.push(o);return r}static async first(e){for await(let r of e)return r}};var C={};l(C,{textQuerySelectorAll:()=>m});var re=new Set(["checkbox","image","radio"]),oe=t=>t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLInputElement&&!re.has(t.type),ne=new Set(["SCRIPT","STYLE"]),f=t=>!ne.has(t.nodeName)&&!document.head?.contains(t),I=new WeakMap,j=t=>{for(;t;)I.delete(t),t instanceof ShadowRoot?t=t.host:t=t.parentNode},W=new WeakSet,se=new MutationObserver(t=>{for(let e of t)j(e.target)}),d=t=>{let e=I.get(t);if(e||(e={full:"",immediate:[]},!f(t)))return e;let r="";if(oe(t))e.full=t.value,e.immediate.push(t.value),t.addEventListener("input",o=>{j(o.target)},{once:!0,capture:!0});else{for(let o=t.firstChild;o;o=o.nextSibling){if(o.nodeType===Node.TEXT_NODE){e.full+=o.nodeValue??"",r+=o.nodeValue??"";continue}r&&e.immediate.push(r),r="",o.nodeType===Node.ELEMENT_NODE&&(e.full+=d(o).full)}r&&e.immediate.push(r),t instanceof Element&&t.shadowRoot&&(e.full+=d(t.shadowRoot).full),W.has(t)||(se.observe(t,{childList:!0,characterData:!0,subtree:!0}),W.add(t))}return I.set(t,e),e};var m=function*(t,e){let r=!1;for(let o of t.childNodes)if(o instanceof Element&&f(o)){let n;o.shadowRoot?n=m(o.shadowRoot,e):n=m(o,e);for(let i of n)yield i,r=!0}r||t instanceof Element&&f(t)&&d(t).full.includes(e)&&(yield t)};var k={};l(k,{checkVisibility:()=>le,pierce:()=>T,pierceAll:()=>O});var ie=["hidden","collapse"],le=(t,e)=>{if(!t)return e===!1;if(e===void 0)return t;let r=t.nodeType===Node.TEXT_NODE?t.parentElement:t,o=window.getComputedStyle(r),n=o&&!ie.includes(o.visibility)&&!ae(r);return e===n?t:!1};function ae(t){let e=t.getBoundingClientRect();return e.width===0||e.height===0}var ce=t=>"shadowRoot"in t&&t.shadowRoot instanceof ShadowRoot;function*T(t){ce(t)?yield t.shadowRoot:yield t}function*O(t){t=T(t).next().value,yield t;let e=[document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT)];for(let r of e){let o;for(;o=r.nextNode();)o.shadowRoot&&(yield o.shadowRoot,e.push(document.createTreeWalker(o.shadowRoot,NodeFilter.SHOW_ELEMENT)))}}var Q={};l(Q,{xpathQuerySelectorAll:()=>q});var q=function*(t,e,r=-1){let n=(t.ownerDocument||document).evaluate(e,t,null,XPathResult.ORDERED_NODE_ITERATOR_TYPE),i=[],s;for(;(s=n.iterateNext())&&(i.push(s),!(r&&i.length===r)););for(let h=0;h(r.Descendent=">>>",r.Child=">>>>",r))(H||{}),V=t=>"querySelectorAll"in t,M=class{#e;#r=[];#o=void 0;elements;constructor(e,r){this.elements=[e],this.#e=r,this.#t()}async run(){if(typeof this.#o=="string")switch(this.#o.trimStart()){case":scope":this.#t();break}for(;this.#o!==void 0;this.#t()){let e=this.#o;typeof e=="string"?e[0]&&ue.test(e[0])?this.elements=a.flatMap(this.elements,async function*(r){V(r)&&(yield*r.querySelectorAll(e))}):this.elements=a.flatMap(this.elements,async function*(r){if(!r.parentElement){if(!V(r))return;yield*r.querySelectorAll(e);return}let o=0;for(let n of r.parentElement.children)if(++o,n===r)break;yield*r.parentElement.querySelectorAll(\`:scope>:nth-child(\${o})\${e}\`)}):this.elements=a.flatMap(this.elements,async function*(r){switch(e.name){case"text":yield*m(r,e.value);break;case"xpath":yield*q(r,e.value);break;case"aria":yield*b(r,e.value);break;default:let o=P.get(e.name);if(!o)throw new Error(\`Unknown selector type: \${e.name}\`);yield*o.querySelectorAll(r,e.value)}})}}#t(){if(this.#r.length!==0){this.#o=this.#r.shift();return}if(this.#e.length===0){this.#o=void 0;return}let e=this.#e.shift();switch(e){case">>>>":{this.elements=a.flatMap(this.elements,T),this.#t();break}case">>>":{this.elements=a.flatMap(this.elements,O),this.#t();break}default:this.#r=e,this.#t();break}}},D=class{#e=new WeakMap;calculate(e,r=[]){if(e===null)return r;e instanceof ShadowRoot&&(e=e.host);let o=this.#e.get(e);if(o)return[...o,...r];let n=0;for(let s=e.previousSibling;s;s=s.previousSibling)++n;let i=this.calculate(e.parentNode,[n]);return this.#e.set(e,i),[...i,...r]}},U=(t,e)=>{if(t.length+e.length===0)return 0;let[r=-1,...o]=t,[n=-1,...i]=e;return r===n?U(o,i):r[o,r.calculate(o)]).sort(([,o],[,n])=>U(o,n)).map(([o])=>o)},$=function(t,e){let r=JSON.parse(e);if(r.some(o=>{let n=0;return o.some(i=>(typeof i=="string"?++n:n=0,n>1))}))throw new Error("Multiple deep combinators found in sequence.");return de(a.flatMap(r,o=>{let n=new M(t,o);return n.run(),n.elements}))},fe=async function(t,e){for await(let r of $(t,e))return r;return null};var me=Object.freeze({...x,...A,...R,..._,...C,...k,...Q,...E,Deferred:c,createFunction:F,createTextContent:d,IntervalPoller:S,isSuitableNodeForTextMatching:f,MutationPoller:y,RAFPoller:w}),he=me;\n\n ${[...this.#P].map((e=>`(${e})(module.exports.default);`)).join("")}\n return module.exports.default;\n })()`}};const Uu=new class{#i=new Map;get(e){const t=this.#i.get(e);return t?t[1]:void 0}register(e,t){$l(!this.#i.has(e),`Cannot register over existing handler: ${e}`),$l(/^[a-zA-Z]+$/.test(e),"Custom query handler names may only contain [a-zA-Z]"),$l(t.queryAll||t.queryOne,"At least one query method must be implemented.");const r=class extends Nu{static querySelectorAll=Cu(((e,t,r)=>r.customQuerySelectors.get(PLACEHOLDER("name")).querySelectorAll(e,t)),{name:JSON.stringify(e)});static querySelector=Cu(((e,t,r)=>r.customQuerySelectors.get(PLACEHOLDER("name")).querySelector(e,t)),{name:JSON.stringify(e)})},n=Cu((e=>{e.customQuerySelectors.register(PLACEHOLDER("name"),{queryAll:PLACEHOLDER("queryAll"),queryOne:PLACEHOLDER("queryOne")})}),{name:JSON.stringify(e),queryAll:t.queryAll?Tu(t.queryAll):String(void 0),queryOne:t.queryOne?Tu(t.queryOne):String(void 0)}).toString();this.#i.set(e,[n,r]),zu.append(n)}unregister(e){const t=this.#i.get(e);if(!t)throw new Error(`Cannot unregister unknown handler: ${e}`);zu.pop(t[0]),this.#i.delete(e)}names(){return[...this.#i.keys()]}clear(){for(const[e]of this.#i)zu.pop(e);this.#i.clear()}};class Bu extends Nu{static querySelectorAll=(e,t,{pQuerySelectorAll:r})=>r(e,t);static querySelector=(e,t,{pQuerySelector:r})=>r(e,t)}var qu={attribute:/\[\s*(?:(?\*|[-\w\P{ASCII}]*)\|)?(?[-\w\P{ASCII}]+)\s*(?:(?\W?=)\s*(?.+?)\s*(\s(?[iIsS]))?\s*)?\]/gu,id:/#(?[-\w\P{ASCII}]+)/gu,class:/\.(?[-\w\P{ASCII}]+)/gu,comma:/\s*,\s*/g,combinator:/\s*[\s>+~]\s*/g,"pseudo-element":/::(?[-\w\P{ASCII}]+)(?:\((?¶*)\))?/gu,"pseudo-class":/:(?[-\w\P{ASCII}]+)(?:\((?¶*)\))?/gu,universal:/(?:(?\*|[-\w\P{ASCII}]*)\|)?\*/gu,type:/(?:(?\*|[-\w\P{ASCII}]*)\|)?(?[-\w\P{ASCII}]+)/gu},Ku=new Set(["combinator","comma"]),Wu=e=>{switch(e){case"pseudo-element":case"pseudo-class":return new RegExp(qu[e].source.replace("(?¶*)","(?.*)"),"gu");default:return qu[e]}};function Hu(e,t){let r=0,n="";for(;t(r.push({value:e,offset:t}),"".repeat(e.length)))),e=e.replace(Vu,((e,t,n,s)=>(r.push({value:e,offset:s}),`${t}${"".repeat(n.length)}${t}`)));{let t,n=0;for(;(t=e.indexOf("(",n))>-1;){const s=Hu(e,t);r.push({value:s,offset:t}),e=`${e.substring(0,t)}(${"¶".repeat(s.length-2)})${e.substring(t+s.length)}`,n=t+s.length}}const n=function(e,t=qu){if(!e)return[];const r=[e];for(const[e,n]of Object.entries(t))for(let t=0;te.content)).join("");switch(e.type){case"list":return e.list.map(Zu).join(",");case"relative":return e.combinator+Zu(e.right);case"complex":return Zu(e.left)+e.combinator+Zu(e.right);case"compound":return e.list.map(Zu).join("");default:return e.content}}qu.nesting=/&/g,qu.combinator=/\s*(>>>>?|[\s>+~])\s*/g;const Yu=/\\[\s\S]/g;const Xu={aria:Fu,pierce:class extends Nu{static querySelector=(e,t,{pierceQuerySelector:r})=>r(e,t);static querySelectorAll=(e,t,{pierceQuerySelectorAll:r})=>r(e,t)},xpath:class extends Nu{static querySelectorAll=(e,t,{xpathQuerySelectorAll:r})=>r(e,t);static querySelector=(e,t,{xpathQuerySelectorAll:r})=>{for(const n of r(e,t,1))return n;return null}},text:class extends Nu{static querySelectorAll=(e,t,{textQuerySelectorAll:r})=>r(e,t)}},Qu=["=","/"];function ed(e){for(const t of[Uu.names().map((e=>[e,Uu.get(e)])),Object.entries(Xu)])for(const[r,n]of t)for(const t of Qu){const s=`${r}${t}`;if(e.startsWith(s))return{updatedSelector:e=e.slice(s.length),polling:"aria"===r?"raf":"mutation",QueryHandler:n}}try{const[t,r,n,s]=function(e){let t=!0,r=!1,n=!1;const s=Ju(e);if(0===s.length)return[[],t,n,!1];let a=[],i=[a];const o=[i],c=[];for(const e of s){switch(e.type){case"combinator":switch(e.content){case">>>":t=!1,c.length&&(a.push(Zu(c)),c.splice(0)),a=[],i.push(">>>"),i.push(a);continue;case">>>>":t=!1,c.length&&(a.push(Zu(c)),c.splice(0)),a=[],i.push(">>>>"),i.push(a);continue}break;case"pseudo-element":if(!e.name.startsWith("-p-"))break;t=!1,c.length&&(a.push(Zu(c)),c.splice(0));const s=e.name.slice(3);"aria"===s&&(r=!0),a.push({name:s,value:(l=e.argument??"",l.length<=1?l:('"'!==l[0]&&"'"!==l[0]||!l.endsWith(l[0])||(l=l.slice(1,-1)),l.replace(Yu,(e=>e[1]))))});continue;case"pseudo-class":n=!0;break;case"comma":c.length&&(a.push(Zu(c)),c.splice(0)),a=[],i=[a],o.push(i);continue}c.push(e)}var l;return c.length&&a.push(Zu(c)),[o,t,n,r]}(e);return r?{updatedSelector:e,polling:n?"raf":"mutation",QueryHandler:Du}:{updatedSelector:JSON.stringify(t),polling:s?"raf":"mutation",QueryHandler:Bu}}catch{return{updatedSelector:e,polling:"mutation",QueryHandler:Du}}}var td=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},rd=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,s=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===s)return s=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return s|=2,Promise.resolve(a).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const nd=new WeakSet;function sd(e,t){let r=!1;if(e.prototype[Cl]){const t=e.prototype[Cl];e.prototype[Cl]=function(){if(!nd.has(this))return t.call(this);nd.delete(this)},r=!0}if(e.prototype[Pl]){const t=e.prototype[Pl];e.prototype[Pl]=function(){if(!nd.has(this))return t.call(this);nd.delete(this)},r=!0}return r&&(e.prototype.move=function(){return nd.add(this),this}),e}function ad(e=e=>`Attempted to use disposed ${e.constructor.name}.`){return(t,r)=>function(...r){if(this.disposed)throw new Error(e(this));return t.call(this,...r)}}function id(e,t){const r=new WeakMap;let n=-1;return function(...t){if(-1===n&&(n=t.length),n!==t.length)throw new Error("Memoized method was called with the wrong number of arguments");let s=!1,a=r;for(const e of t)a.has(e)||(s=!0,a.set(e,new WeakMap)),a=a.get(e);if(s)return e.call(this,...t)}}function od(e=function(){return this}){return(t,r)=>{const n=new WeakMap;return async function(...r){const s={stack:[],error:void 0,hasError:!1};try{const a=e.call(this);let i=n.get(a);i||(i=new yu,n.set(a,i));td(s,await i.acquire(),!0);return await t.call(this,...r)}catch(e){s.error=e,s.hasError=!0}finally{const e=rd(s);e&&await e}}}}new WeakMap;var cd=function(e,t,r){for(var n=arguments.length>2,s=0;s=0;p--){var m={};for(var f in n)m[f]="access"===f?{}:n[f];for(var f in n.access)m.access[f]=n.access[f];m.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");a.push(i(e||null))};var g=(0,r[p])("accessor"===c?{get:d.get,set:d.set}:d[l],m);if("accessor"===c){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(o=i(g.get))&&(d.get=o),(o=i(g.set))&&(d.set=o),(o=i(g.init))&&s.unshift(o)}else(o=i(g))&&("field"===c?s.unshift(o):d[l]=o)}u&&Object.defineProperty(u,n.name,d),h=!0},ud=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},dd=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,s=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===s)return s=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return s|=2,Promise.resolve(a).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});let hd=(()=>{let e,t,r,n,s=[sd],a=[],i=[];(class{static{t=this}static{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ld(this,null,r,{kind:"method",name:"getProperty",static:!1,private:!1,access:{has:e=>"getProperty"in e,get:e=>e.getProperty},metadata:o},null,i),ld(this,null,n,{kind:"method",name:"getProperties",static:!1,private:!1,access:{has:e=>"getProperties"in e,get:e=>e.getProperties},metadata:o},null,i),ld(null,e={value:t},s,{kind:"class",name:t.name,metadata:o},null,a),t=e.value,o&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o}),cd(t,a)}constructor(){cd(this,i)}async evaluate(e,...t){return e=eu(this.evaluate.name,e),await this.realm.evaluate(e,this,...t)}async evaluateHandle(e,...t){return e=eu(this.evaluateHandle.name,e),await this.realm.evaluateHandle(e,this,...t)}async getProperty(e){return await this.evaluateHandle(((e,t)=>e[t]),e)}async getProperties(){const e=await this.evaluate((e=>{const t=[],r=Object.getOwnPropertyDescriptors(e);for(const e in r)r[e]?.enumerable&&t.push(e);return t})),t=new Map,r=await Promise.all(e.map((e=>this.getProperty(e))));for(const[n,s]of Object.entries(e)){const e={stack:[],error:void 0,hasError:!1};try{const a=ud(e,r[n],!1);a&&t.set(s,a.move())}catch(t){e.error=t,e.hasError=!0}finally{dd(e)}}return t}[(r=[ad()],n=[ad()],Cl)](){this.dispose().catch(Zl)}[Pl](){return this.dispose()}});return t})();var pd=function(e,t,r){for(var n=arguments.length>2,s=0;s=0;p--){var m={};for(var f in n)m[f]="access"===f?{}:n[f];for(var f in n.access)m.access[f]=n.access[f];m.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");a.push(i(e||null))};var g=(0,r[p])("accessor"===c?{get:d.get,set:d.set}:d[l],m);if("accessor"===c){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(o=i(g.get))&&(d.get=o),(o=i(g.set))&&(d.set=o),(o=i(g.init))&&s.unshift(o)}else(o=i(g))&&("field"===c?s.unshift(o):d[l]=o)}u&&Object.defineProperty(u,n.name,d),h=!0},fd=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},gd=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,s=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===s)return s=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return s|=2,Promise.resolve(a).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n}),yd=function(e,t,r){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:r?"".concat(r," ",t):t})};function bd(e,t){return async function(...t){if(this.realm===this.frame.isolatedRealm())return await e.call(this,...t);let r;this.isolatedHandle?r=this.isolatedHandle:this.isolatedHandle=r=await this.frame.isolatedRealm().adoptHandle(this);const n=await e.call(r,...t);return n===r?this:n instanceof hd?await this.realm.transferHandle(n):(Array.isArray(n)&&await Promise.all(n.map((async(e,t,r)=>{e instanceof hd&&(r[t]=await this.realm.transferHandle(e))}))),n instanceof Map&&await Promise.all([...n.entries()].map((async([e,t])=>{t instanceof hd&&n.set(e,await this.realm.transferHandle(t))}))),n)}}let wd=(()=>{let e,t,r,n,s,a,i,o,c,l,u,d,h,p,m,f,g,y,b,w,v,_,k,S,E,x,T,C,P,O,A,I,M=hd,R=[];return class j extends M{static{const j="function"==typeof Symbol&&Symbol.metadata?Object.create(M[Symbol.metadata]??null):void 0;e=[ad(),bd],t=[ad(),bd],r=[ad(),bd],n=[ad(),bd],s=[ad()],a=[bd],o=[ad(),bd],c=[ad(),bd],l=[ad(),bd],u=[ad(),bd],d=[ad(),bd],h=[ad(),bd],p=[ad(),bd],m=[ad(),bd],f=[ad(),bd],g=[ad(),bd],y=[ad(),bd],b=[ad(),bd],w=[ad(),bd],v=[ad(),bd],_=[ad(),bd],k=[ad(),bd],S=[ad(),bd],E=[ad(),bd],x=[ad(),bd],T=[ad(),bd],C=[ad(),bd],P=[ad(),bd],O=[ad(),bd],A=[ad(),bd],I=[ad(),bd],md(this,null,e,{kind:"method",name:"getProperty",static:!1,private:!1,access:{has:e=>"getProperty"in e,get:e=>e.getProperty},metadata:j},null,R),md(this,null,t,{kind:"method",name:"getProperties",static:!1,private:!1,access:{has:e=>"getProperties"in e,get:e=>e.getProperties},metadata:j},null,R),md(this,null,r,{kind:"method",name:"jsonValue",static:!1,private:!1,access:{has:e=>"jsonValue"in e,get:e=>e.jsonValue},metadata:j},null,R),md(this,null,n,{kind:"method",name:"$",static:!1,private:!1,access:{has:e=>"$"in e,get:e=>e.$},metadata:j},null,R),md(this,null,s,{kind:"method",name:"$$",static:!1,private:!1,access:{has:e=>"$$"in e,get:e=>e.$$},metadata:j},null,R),md(this,i={value:yd((async function(e){return await this.#A(e)}),"#$$")},a,{kind:"method",name:"#$$",static:!1,private:!0,access:{has:e=>#I in e,get:e=>e.#I},metadata:j},null,R),md(this,null,o,{kind:"method",name:"waitForSelector",static:!1,private:!1,access:{has:e=>"waitForSelector"in e,get:e=>e.waitForSelector},metadata:j},null,R),md(this,null,c,{kind:"method",name:"isVisible",static:!1,private:!1,access:{has:e=>"isVisible"in e,get:e=>e.isVisible},metadata:j},null,R),md(this,null,l,{kind:"method",name:"isHidden",static:!1,private:!1,access:{has:e=>"isHidden"in e,get:e=>e.isHidden},metadata:j},null,R),md(this,null,u,{kind:"method",name:"toElement",static:!1,private:!1,access:{has:e=>"toElement"in e,get:e=>e.toElement},metadata:j},null,R),md(this,null,d,{kind:"method",name:"clickablePoint",static:!1,private:!1,access:{has:e=>"clickablePoint"in e,get:e=>e.clickablePoint},metadata:j},null,R),md(this,null,h,{kind:"method",name:"hover",static:!1,private:!1,access:{has:e=>"hover"in e,get:e=>e.hover},metadata:j},null,R),md(this,null,p,{kind:"method",name:"click",static:!1,private:!1,access:{has:e=>"click"in e,get:e=>e.click},metadata:j},null,R),md(this,null,m,{kind:"method",name:"drag",static:!1,private:!1,access:{has:e=>"drag"in e,get:e=>e.drag},metadata:j},null,R),md(this,null,f,{kind:"method",name:"dragEnter",static:!1,private:!1,access:{has:e=>"dragEnter"in e,get:e=>e.dragEnter},metadata:j},null,R),md(this,null,g,{kind:"method",name:"dragOver",static:!1,private:!1,access:{has:e=>"dragOver"in e,get:e=>e.dragOver},metadata:j},null,R),md(this,null,y,{kind:"method",name:"drop",static:!1,private:!1,access:{has:e=>"drop"in e,get:e=>e.drop},metadata:j},null,R),md(this,null,b,{kind:"method",name:"dragAndDrop",static:!1,private:!1,access:{has:e=>"dragAndDrop"in e,get:e=>e.dragAndDrop},metadata:j},null,R),md(this,null,w,{kind:"method",name:"select",static:!1,private:!1,access:{has:e=>"select"in e,get:e=>e.select},metadata:j},null,R),md(this,null,v,{kind:"method",name:"tap",static:!1,private:!1,access:{has:e=>"tap"in e,get:e=>e.tap},metadata:j},null,R),md(this,null,_,{kind:"method",name:"touchStart",static:!1,private:!1,access:{has:e=>"touchStart"in e,get:e=>e.touchStart},metadata:j},null,R),md(this,null,k,{kind:"method",name:"touchMove",static:!1,private:!1,access:{has:e=>"touchMove"in e,get:e=>e.touchMove},metadata:j},null,R),md(this,null,S,{kind:"method",name:"touchEnd",static:!1,private:!1,access:{has:e=>"touchEnd"in e,get:e=>e.touchEnd},metadata:j},null,R),md(this,null,E,{kind:"method",name:"focus",static:!1,private:!1,access:{has:e=>"focus"in e,get:e=>e.focus},metadata:j},null,R),md(this,null,x,{kind:"method",name:"type",static:!1,private:!1,access:{has:e=>"type"in e,get:e=>e.type},metadata:j},null,R),md(this,null,T,{kind:"method",name:"press",static:!1,private:!1,access:{has:e=>"press"in e,get:e=>e.press},metadata:j},null,R),md(this,null,C,{kind:"method",name:"boundingBox",static:!1,private:!1,access:{has:e=>"boundingBox"in e,get:e=>e.boundingBox},metadata:j},null,R),md(this,null,P,{kind:"method",name:"boxModel",static:!1,private:!1,access:{has:e=>"boxModel"in e,get:e=>e.boxModel},metadata:j},null,R),md(this,null,O,{kind:"method",name:"screenshot",static:!1,private:!1,access:{has:e=>"screenshot"in e,get:e=>e.screenshot},metadata:j},null,R),md(this,null,A,{kind:"method",name:"isIntersectingViewport",static:!1,private:!1,access:{has:e=>"isIntersectingViewport"in e,get:e=>e.isIntersectingViewport},metadata:j},null,R),md(this,null,I,{kind:"method",name:"scrollIntoView",static:!1,private:!1,access:{has:e=>"scrollIntoView"in e,get:e=>e.scrollIntoView},metadata:j},null,R),j&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:j})}isolatedHandle=pd(this,R);handle;constructor(e){super(),this.handle=e,this[_u]=!0}get id(){return this.handle.id}get disposed(){return this.handle.disposed}async getProperty(e){return await this.handle.getProperty(e)}async getProperties(){return await this.handle.getProperties()}async evaluate(e,...t){return e=eu(this.evaluate.name,e),await this.handle.evaluate(e,...t)}async evaluateHandle(e,...t){return e=eu(this.evaluateHandle.name,e),await this.handle.evaluateHandle(e,...t)}async jsonValue(){return await this.handle.jsonValue()}toString(){return this.handle.toString()}remoteObject(){return this.handle.remoteObject()}async dispose(){await Promise.all([this.handle.dispose(),this.isolatedHandle?.dispose()])}asElement(){return this}async $(e){const{updatedSelector:t,QueryHandler:r}=ed(e);return await r.queryOne(this,t)}async $$(e,t){return!1===t?.isolate?await this.#A(e):await this.#I(e)}get#I(){return i.value}async#A(e){const{updatedSelector:t,QueryHandler:r}=ed(e);return await $u.collect(r.queryAll(this,t))}async $eval(e,t,...r){const n={stack:[],error:void 0,hasError:!1};try{t=eu(this.$eval.name,t);const s=fd(n,await this.$(e),!1);if(!s)throw new Error(`Error: failed to find element matching selector "${e}"`);return await s.evaluate(t,...r)}catch(e){n.error=e,n.hasError=!0}finally{gd(n)}}async $$eval(e,t,...r){const n={stack:[],error:void 0,hasError:!1};try{t=eu(this.$$eval.name,t);const s=await this.$$(e),a=fd(n,await this.evaluateHandle(((e,...t)=>t),...s),!1),[i]=await Promise.all([a.evaluate(t,...r),...s.map((e=>e.dispose()))]);return i}catch(e){n.error=e,n.hasError=!0}finally{gd(n)}}async waitForSelector(e,t={}){const{updatedSelector:r,QueryHandler:n,polling:s}=ed(e);return await n.waitFor(this,r,{polling:s,...t})}async#M(e){return await this.evaluate((async(e,t,r)=>Boolean(t.checkVisibility(e,r))),Mu.create((e=>e.puppeteerUtil)),e)}async isVisible(){return await this.#M(!0)}async isHidden(){return await this.#M(!1)}async toElement(e){const t=await this.evaluate(((e,t)=>e.nodeName===t.toUpperCase()),e);if(!t)throw new Error(`Element is not a(n) \`${e}\` element`);return this}async clickablePoint(e){const t=await this.#R();if(!t)throw new Error("Node is either not clickable or not an Element");return void 0!==e?{x:t.x+e.x,y:t.y+e.y}:{x:t.x+t.width/2,y:t.y+t.height/2}}async hover(){await this.scrollIntoViewIfNeeded();const{x:e,y:t}=await this.clickablePoint();await this.frame.page().mouse.move(e,t)}async click(e={}){await this.scrollIntoViewIfNeeded();const{x:t,y:r}=await this.clickablePoint(e.offset);await this.frame.page().mouse.click(t,r,e)}async drag(e){await this.scrollIntoViewIfNeeded();const t=this.frame.page();if(t.isDragInterceptionEnabled()){const r=await this.clickablePoint();return e instanceof j&&(e=await e.clickablePoint()),await t.mouse.drag(r,e)}try{t._isDragging||(t._isDragging=!0,await this.hover(),await t.mouse.down()),e instanceof j?await e.hover():await t.mouse.move(e.x,e.y)}catch(e){throw t._isDragging=!1,e}}async dragEnter(e={items:[],dragOperationsMask:1}){const t=this.frame.page();await this.scrollIntoViewIfNeeded();const r=await this.clickablePoint();await t.mouse.dragEnter(r,e)}async dragOver(e={items:[],dragOperationsMask:1}){const t=this.frame.page();await this.scrollIntoViewIfNeeded();const r=await this.clickablePoint();await t.mouse.dragOver(r,e)}async drop(e={items:[],dragOperationsMask:1}){const t=this.frame.page();if("items"in e){await this.scrollIntoViewIfNeeded();const r=await this.clickablePoint();await t.mouse.drop(r,e)}else await e.drag(this),t._isDragging=!1,await t.mouse.up()}async dragAndDrop(e,t){const r=this.frame.page();$l(r.isDragInterceptionEnabled(),"Drag Interception is not enabled!"),await this.scrollIntoViewIfNeeded();const n=await this.clickablePoint(),s=await e.clickablePoint();await r.mouse.dragAndDrop(n,s,t)}async select(...e){for(const t of e)$l(tu(t),'Values must be strings. Found value "'+t+'" of type "'+typeof t+'"');return await this.evaluate(((e,t)=>{const r=new Set(t);if(!(e instanceof HTMLSelectElement))throw new Error("Element is not a ");const r=jl.value.path;if(r&&(e=e.map((e=>r.win32.isAbsolute(e)||r.posix.isAbsolute(e)?e:r.resolve(e)))),0===e.length)return void await this.evaluate((e=>{e.files=(new DataTransfer).files,e.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}));const{node:{backendNodeId:n}}=await this.client.send("DOM.describeNode",{objectId:this.id});await this.client.send("DOM.setFileInputFiles",{objectId:this.id,files:e,backendNodeId:n})}async autofill(e){const t=(await this.client.send("DOM.describeNode",{objectId:this.handle.id})).node.backendNodeId,r=this.frame._id;await this.client.send("Autofill.trigger",{fieldId:t,frameId:r,card:e.creditCard})}async*queryAXTree(e,t){const{nodes:r}=await this.client.send("Accessibility.queryAXTree",{objectId:this.id,accessibleName:e,role:t}),n=r.filter((e=>!e.ignored&&(!!e.role&&!Yh.has(e.role.value))));return yield*$u.map(n,(e=>this.realm.adoptBackendNode(e.backendDOMNodeId)))}async backendNodeId(){if(this.#hr)return this.#hr;const{node:e}=await this.client.send("DOM.describeNode",{objectId:this.handle.id});return this.#hr=e.backendNodeId,this.#hr}}})();var Qh=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},ep=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,s=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===s)return s=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return s|=2,Promise.resolve(a).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const tp=new yh("__ariaQuerySelector",Fu.queryOne,""),rp=new yh("__ariaQuerySelectorAll",(async(e,t)=>{const r=Fu.queryAll(e,t);return await e.realm.evaluateHandle(((...e)=>e),...await $u.collect(r))}),"");class np extends Ml{#mt;#pe;#Je;#Me;#mr=new Ol;constructor(e,t,r){super(),this.#mt=e,this.#pe=r,this.#Je=t.id,t.name&&(this.#Me=t.name);const n=this.#mr.use(new Ml(this.#mt));n.on("Runtime.bindingCalled",this.#fr.bind(this)),n.on("Runtime.executionContextDestroyed",(async e=>{e.executionContextId===this.#Je&&this[Cl]()})),n.on("Runtime.executionContextsCleared",(async()=>{this[Cl]()})),n.on("Runtime.consoleAPICalled",this.#gr.bind(this)),n.on(wu.Disconnected,(()=>{this[Cl]()}))}#yr=new Map;#v=new yu;async#br(e){const t={stack:[],error:void 0,hasError:!1};try{if(this.#yr.has(e.name))return;Qh(t,await this.#v.acquire(),!1);try{await this.#mt.send("Runtime.addBinding",this.#Me?{name:Hh+e.name,executionContextName:this.#Me}:{name:Hh+e.name,executionContextId:this.#Je}),await this.evaluate(Wh,"internal",e.name,Hh),this.#yr.set(e.name,e)}catch(e){if(e instanceof Error){if(e.message.includes("Execution context was destroyed"))return;if(e.message.includes("Cannot find context with specified id"))return}Zl(e)}}catch(e){t.error=e,t.hasError=!0}finally{ep(t)}}async#fr(e){if(e.executionContextId!==this.#Je)return;let t;try{t=JSON.parse(e.payload)}catch{return}const{type:r,name:n,seq:s,args:a,isTrivial:i}=t;if("internal"===r)if(this.#yr.has(n))try{const e=this.#yr.get(n);await(e?.run(this,s,a,i))}catch(e){Zl(e)}else this.emit("bindingcalled",e);else this.emit("bindingcalled",e)}get id(){return this.#Je}#gr(e){e.executionContextId===this.#Je&&this.emit("consoleapicalled",e)}#wr=!1;#vr;get puppeteerUtil(){let e=Promise.resolve();return this.#wr||(e=Promise.all([this.#_r(tp),this.#_r(rp)]),this.#wr=!0),zu.inject((t=>{this.#vr&&this.#vr.then((e=>{e.dispose()})),this.#vr=e.then((()=>this.evaluateHandle(t)))}),!this.#vr),this.#vr}async#_r(e){try{await this.#br(e)}catch(e){Zl(e)}}async evaluate(e,...t){return await this.#kr(!0,e,...t)}async evaluateHandle(e,...t){return await this.#kr(!1,e,...t)}async#kr(e,t,...r){const n=`//# sourceURL=${(e=>{if(Object.prototype.hasOwnProperty.call(e,Xl))return e[Xl]})(t)?.toString()??Ql.INTERNAL_URL}`;if(tu(t)){const r=this.#Je,s=t,a=ou.test(s)?s:`${s}\n${n}\n`,{exceptionDetails:i,result:o}=await this.#mt.send("Runtime.evaluate",{expression:a,contextId:r,returnByValue:e,awaitPromise:!0,userGesture:!0}).catch(sp);if(i)throw Bh(i);return e?Kh(o):this.#pe.createCdpHandle(o)}const s=Tu(t),a=ou.test(s)?s:`${s}\n${n}\n`;let i;try{i=this.#mt.send("Runtime.callFunctionOn",{functionDeclaration:a,executionContextId:this.#Je,arguments:r.some((e=>e instanceof Mu))?await Promise.all(r.map((e=>async function(e,t){t instanceof Mu&&(t=await t.get(e));return l(e,t)}(this,e)))):r.map((e=>l(this,e))),returnByValue:e,awaitPromise:!0,userGesture:!0})}catch(e){throw e instanceof TypeError&&e.message.startsWith("Converting circular structure to JSON")&&(e.message+=" Recursive objects are not allowed."),e}const{exceptionDetails:o,result:c}=await i.catch(sp);if(o)throw Bh(o);return e?Kh(c):this.#pe.createCdpHandle(c);function l(e,t){if("bigint"==typeof t)return{unserializableValue:`${t.toString()}n`};if(Object.is(t,-0))return{unserializableValue:"-0"};if(Object.is(t,1/0))return{unserializableValue:"Infinity"};if(Object.is(t,-1/0))return{unserializableValue:"-Infinity"};if(Object.is(t,NaN))return{unserializableValue:"NaN"};const r=t&&(t instanceof Vh||t instanceof Xh)?t:null;if(r){if(r.realm!==e.#pe)throw new Error("JSHandles can be evaluated only in the context they were created!");if(r.disposed)throw new Error("JSHandle is disposed!");return r.remoteObject().unserializableValue?{unserializableValue:r.remoteObject().unserializableValue}:r.remoteObject().objectId?{objectId:r.remoteObject().objectId}:{value:r.remoteObject().value}}return{value:t}}}[Cl](){this.#mr.dispose(),this.emit("disposed",void 0)}}const sp=e=>{if(e.message.includes("Object reference chain is too long"))return{result:{type:"undefined"}};if(e.message.includes("Object couldn't be returned by value"))return{result:{type:"undefined"}};if(e.message.endsWith("Cannot find context with specified id")||e.message.endsWith("Inspected target navigated or closed"))throw new Error("Execution context was destroyed, most likely because of a navigation.");throw e};var ap;!function(e){e.FrameAttached=Symbol("FrameManager.FrameAttached"),e.FrameNavigated=Symbol("FrameManager.FrameNavigated"),e.FrameDetached=Symbol("FrameManager.FrameDetached"),e.FrameSwapped=Symbol("FrameManager.FrameSwapped"),e.LifecycleEvent=Symbol("FrameManager.LifecycleEvent"),e.FrameNavigatedWithinDocument=Symbol("FrameManager.FrameNavigatedWithinDocument"),e.ConsoleApiCalled=Symbol("FrameManager.ConsoleApiCalled"),e.BindingCalled=Symbol("FrameManager.BindingCalled")}(ap||(ap={}));class ip extends ih{#Sr;#a=new Ml;#Er;constructor(e,t){super(t),this.#Er=e}get environment(){return this.#Er}get client(){return this.#Er.client}get emitter(){return this.#a}setContext(e){this.#Sr?.[Cl](),e.once("disposed",this.#xr.bind(this)),e.on("consoleapicalled",this.#Tr.bind(this)),e.on("bindingcalled",this.#Cr.bind(this)),this.#Sr=e,this.#a.emit("context",e),this.taskManager.rerunAll()}#xr(){this.#Sr=void 0,"clearDocumentHandle"in this.#Er&&this.#Er.clearDocumentHandle()}#Tr(e){this.#a.emit("consoleapicalled",e)}#Cr(e){this.#a.emit("bindingcalled",e)}hasContext(){return!!this.#Sr}get context(){return this.#Sr}#Pr(){if(this.disposed)throw new Error(`Execution context is not available in detached frame or worker "${this.environment.url()}" (are you trying to evaluate?)`);return this.#Sr}async#Or(){const e=new Error("Execution context was destroyed");return await Zc(du(this.#a,"context").pipe(El(du(this.#a,"disposed").pipe(Yc((()=>{throw e}))),au(this.timeoutSettings.timeout()))))}async evaluateHandle(e,...t){e=eu(this.evaluateHandle.name,e);let r=this.#Pr();return r||(r=await this.#Or()),await r.evaluateHandle(e,...t)}async evaluate(e,...t){e=eu(this.evaluate.name,e);let r=this.#Pr();return r||(r=await this.#Or()),await r.evaluate(e,...t)}async adoptBackendNode(e){let t=this.#Pr();t||(t=await this.#Or());const{object:r}=await this.client.send("DOM.resolveNode",{backendNodeId:e,executionContextId:t.id});return this.createCdpHandle(r)}async adoptHandle(e){if(e.realm===this)return await e.evaluateHandle((e=>e));const t=await this.client.send("DOM.describeNode",{objectId:e.id});return await this.adoptBackendNode(t.node.backendNodeId)}async transferHandle(e){if(e.realm===this)return e;if(void 0===e.remoteObject().objectId)return e;const t=await this.client.send("DOM.describeNode",{objectId:e.remoteObject().objectId}),r=await this.adoptBackendNode(t.node.backendNodeId);return await e.dispose(),r}createCdpHandle(e){return"node"===e.subtype?new Xh(this,e):new Vh(this,e)}[Cl](){this.#Sr?.[Cl](),this.#a.emit("disposed",void 0),super[Cl](),this.#a.removeAllListeners()}}const op=Symbol("mainWorld"),cp=Symbol("puppeteerWorld"),lp=new Map([["load","load"],["domcontentloaded","DOMContentLoaded"],["networkidle0","networkIdle"],["networkidle2","networkAlmostIdle"]]);class up{#Ar;#qe;#be;#Ir=null;#bt=new Ol;#Mr;#Rr;#jr=gu.create();#Nr=gu.create();#$r=gu.create();#Lr;#Fr;#Dr;constructor(e,t,r,n,s){Array.isArray(r)?r=r.slice():"string"==typeof r&&(r=[r]),this.#Mr=t._loaderId,this.#Ar=r.map((e=>{const t=lp.get(e);return $l(t,"Unknown value for options.waitUntil: "+e),t})),s?.addEventListener("abort",(()=>{this.#Rr.reject(s.reason)})),this.#qe=t,this.#be=n;this.#bt.use(new Ml(t._frameManager)).on(ap.LifecycleEvent,this.#zr.bind(this));const a=this.#bt.use(new Ml(t));a.on(Md.FrameNavigatedWithinDocument,this.#Ur.bind(this)),a.on(Md.FrameNavigated,this.#Br.bind(this)),a.on(Md.FrameSwapped,this.#qr.bind(this)),a.on(Md.FrameSwappedByActivation,this.#qr.bind(this)),a.on(Md.FrameDetached,this.#Kr.bind(this));const i=this.#bt.use(new Ml(e));i.on(mh.Request,this.#Wr.bind(this)),i.on(mh.Response,this.#Hr.bind(this)),i.on(mh.RequestFailed,this.#Vr.bind(this)),this.#Rr=gu.create({timeout:this.#be,message:`Navigation timeout of ${this.#be} ms exceeded`}),this.#zr()}#Wr(e){e.frame()===this.#qe&&e.isNavigationRequest()&&(this.#Ir=e,this.#Dr?.resolve(),this.#Dr=gu.create(),null!==e.response()&&this.#Dr?.resolve())}#Vr(e){this.#Ir?.id===e.id&&this.#Dr?.resolve()}#Hr(e){this.#Ir?.id===e.request().id&&this.#Dr?.resolve()}#Kr(e){this.#qe!==e?this.#zr():this.#Rr.resolve(new Error("Navigating frame was detached"))}async navigationResponse(){return await(this.#Dr?.valueOrThrow()),this.#Ir?this.#Ir.response():null}sameDocumentNavigationPromise(){return this.#jr.valueOrThrow()}newDocumentNavigationPromise(){return this.#$r.valueOrThrow()}lifecyclePromise(){return this.#Nr.valueOrThrow()}terminationPromise(){return this.#Rr.valueOrThrow()}#Ur(){this.#Lr=!0,this.#zr()}#Br(e){if("BackForwardCacheRestore"===e)return this.#qr();this.#zr()}#qr(){this.#Fr=!0,this.#zr()}#zr(){(function e(t,r){for(const e of r)if(!t._lifecycleEvents.has(e))return!1;for(const n of t.childFrames())if(n._hasStartedLoading&&!e(n,r))return!1;return!0})(this.#qe,this.#Ar)&&(this.#Nr.resolve(),this.#Lr&&this.#jr.resolve(void 0),(this.#Fr||this.#qe._loaderId!==this.#Mr)&&this.#$r.resolve(void 0))}dispose(){this.#bt.dispose(),this.#Rr.resolve(new Error("LifecycleWatcher disposed"))}}var dp=function(e,t,r){for(var n=arguments.length>2,s=0;s=0;p--){var m={};for(var f in n)m[f]="access"===f?{}:n[f];for(var f in n.access)m.access[f]=n.access[f];m.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");a.push(i(e||null))};var g=(0,r[p])("accessor"===c?{get:d.get,set:d.set}:d[l],m);if("accessor"===c){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(o=i(g.get))&&(d.get=o),(o=i(g.set))&&(d.set=o),(o=i(g.init))&&s.unshift(o)}else(o=i(g))&&("field"===c?s.unshift(o):d[l]=o)}u&&Object.defineProperty(u,n.name,d),h=!0};let pp=(()=>{let e,t,r,n,s,a,i,o=Fd,c=[];return class extends o{static{const l="function"==typeof Symbol&&Symbol.metadata?Object.create(o[Symbol.metadata]??null):void 0;hp(this,null,e,{kind:"method",name:"goto",static:!1,private:!1,access:{has:e=>"goto"in e,get:e=>e.goto},metadata:l},null,c),hp(this,null,t,{kind:"method",name:"waitForNavigation",static:!1,private:!1,access:{has:e=>"waitForNavigation"in e,get:e=>e.waitForNavigation},metadata:l},null,c),hp(this,null,r,{kind:"method",name:"setContent",static:!1,private:!1,access:{has:e=>"setContent"in e,get:e=>e.setContent},metadata:l},null,c),hp(this,null,n,{kind:"method",name:"addPreloadScript",static:!1,private:!1,access:{has:e=>"addPreloadScript"in e,get:e=>e.addPreloadScript},metadata:l},null,c),hp(this,null,s,{kind:"method",name:"addExposedFunctionBinding",static:!1,private:!1,access:{has:e=>"addExposedFunctionBinding"in e,get:e=>e.addExposedFunctionBinding},metadata:l},null,c),hp(this,null,a,{kind:"method",name:"removeExposedFunctionBinding",static:!1,private:!1,access:{has:e=>"removeExposedFunctionBinding"in e,get:e=>e.removeExposedFunctionBinding},metadata:l},null,c),hp(this,null,i,{kind:"method",name:"waitForDevicePrompt",static:!1,private:!1,access:{has:e=>"waitForDevicePrompt"in e,get:e=>e.waitForDevicePrompt},metadata:l},null,c),l&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:l})}#xe=(dp(this,c),"");#at=!1;#mt;_frameManager;_loaderId="";_lifecycleEvents=new Set;_id;_parentId;accessibility;worlds;constructor(e,t,r,n){super(),this._frameManager=e,this.#xe="",this._id=t,this._parentId=r,this.#at=!1,this.#mt=n,this._loaderId="",this.worlds={[op]:new ip(this,this._frameManager.timeoutSettings),[cp]:new ip(this,this._frameManager.timeoutSettings)},this.accessibility=new hh(this.worlds[op],t),this.on(Md.FrameSwappedByActivation,(()=>{this._onLoadingStarted(),this._onLoadingStopped()})),this.worlds[op].emitter.on("consoleapicalled",this.#Gr.bind(this)),this.worlds[op].emitter.on("bindingcalled",this.#Jr.bind(this))}#Gr(e){this._frameManager.emit(ap.ConsoleApiCalled,[this.worlds[op],e])}#Jr(e){this._frameManager.emit(ap.BindingCalled,[this.worlds[op],e])}_client(){return this.#mt}updateId(e){this._id=e}updateClient(e){this.#mt=e}page(){return this._frameManager.page()}async goto(e,t={}){const{referer:r=this._frameManager.networkManager.extraHTTPHeaders().referer,referrerPolicy:n=this._frameManager.networkManager.extraHTTPHeaders()["referer-policy"],waitUntil:s=["load"],timeout:a=this._frameManager.timeoutSettings.navigationTimeout()}=t;let i=!1;const o=new up(this._frameManager.networkManager,this,s,a);let c=await gu.race([async function(e,t,r,n,s){try{const a=await e.send("Page.navigate",{url:t,referrer:r,frameId:s,referrerPolicy:n});return i=!!a.loaderId,"net::ERR_HTTP_RESPONSE_CODE_FAILURE"===a.errorText?null:a.errorText?new Error(`${a.errorText} at ${t}`):null}catch(e){if(ku(e))return e;throw e}}(this.#mt,e,r,n,this._id),o.terminationPromise()]);c||(c=await gu.race([o.terminationPromise(),i?o.newDocumentNavigationPromise():o.sameDocumentNavigationPromise()]));try{if(c)throw c;return await o.navigationResponse()}finally{o.dispose()}}async waitForNavigation(e={}){const{waitUntil:t=["load"],timeout:r=this._frameManager.timeoutSettings.navigationTimeout(),signal:n}=e,s=new up(this._frameManager.networkManager,this,t,r,n),a=await gu.race([s.terminationPromise(),...e.ignoreSameDocumentNavigation?[]:[s.sameDocumentNavigationPromise()],s.newDocumentNavigationPromise()]);try{if(a)throw a;const e=await gu.race([s.terminationPromise(),s.navigationResponse()]);if(e instanceof Error)throw a;return e||null}finally{s.dispose()}}get client(){return this.#mt}mainRealm(){return this.worlds[op]}isolatedRealm(){return this.worlds[cp]}async setContent(e,t={}){const{waitUntil:r=["load"],timeout:n=this._frameManager.timeoutSettings.navigationTimeout()}=t;await this.setFrameContent(e);const s=new up(this._frameManager.networkManager,this,r,n),a=await gu.race([s.terminationPromise(),s.lifecyclePromise()]);if(s.dispose(),a)throw a}url(){return this.#xe}parentFrame(){return this._frameManager._frameTree.parentFrame(this._id)||null}childFrames(){return this._frameManager._frameTree.childFrames(this._id)}#Zr(){return this._frameManager._deviceRequestPromptManager(this.#mt)}async addPreloadScript(e){const t=this.parentFrame();if(t&&this.#mt===t.client)return;if(e.getIdForFrame(this))return;const{identifier:r}=await this.#mt.send("Page.addScriptToEvaluateOnNewDocument",{source:e.source});e.setIdForFrame(this,r)}async addExposedFunctionBinding(e){(this===this._frameManager.mainFrame()||this._hasStartedLoading)&&await Promise.all([this.#mt.send("Runtime.addBinding",{name:Hh+e.name}),this.evaluate(e.initSource).catch(Zl)])}async removeExposedFunctionBinding(e){(this===this._frameManager.mainFrame()||this._hasStartedLoading)&&await Promise.all([this.#mt.send("Runtime.removeBinding",{name:Hh+e.name}),this.evaluate((e=>{globalThis[e]=void 0}),e.name).catch(Zl)])}async waitForDevicePrompt(e={}){return await this.#Zr().waitForDevicePrompt(e)}_navigated(e){this._name=e.name,this.#xe=`${e.url}${e.urlFragment||""}`}_navigatedWithinDocument(e){this.#xe=e}_onLifecycleEvent(e,t){"init"===t&&(this._loaderId=e,this._lifecycleEvents.clear()),this._lifecycleEvents.add(t)}_onLoadingStopped(){this._lifecycleEvents.add("DOMContentLoaded"),this._lifecycleEvents.add("load")}_onLoadingStarted(){this._hasStartedLoading=!0}get detached(){return this.#at}[(e=[Ld],t=[Ld],r=[Ld],n=[Ld],s=[Ld],a=[Ld],i=[Ld],Cl)](){this.#at||(this.#at=!0,this.worlds[op][Cl](),this.worlds[cp][Cl]())}exposeFunction(){throw new Vl}async frameElement(){const e=this.parentFrame();if(!e)return null;const{backendNodeId:t}=await e.client.send("DOM.getFrameOwner",{frameId:this._id});return await e.mainRealm().adoptBackendNode(t)}}})();class mp{#Yr=new Map;#Xr=new Map;#Qr=new Map;#en;#tn=!1;#rn=new Map;getMainFrame(){return this.#en}getById(e){return this.#Yr.get(e)}waitForFrame(e){const t=this.getById(e);if(t)return Promise.resolve(t);const r=gu.create();return(this.#rn.get(e)||new Set).add(r),r.valueOrThrow()}frames(){return Array.from(this.#Yr.values())}addFrame(e){this.#Yr.set(e._id,e),e._parentId?(this.#Xr.set(e._id,e._parentId),this.#Qr.has(e._parentId)||this.#Qr.set(e._parentId,new Set),this.#Qr.get(e._parentId).add(e._id)):this.#en&&!this.#tn||(this.#en=e,this.#tn=!1),this.#rn.get(e._id)?.forEach((t=>t.resolve(e)))}removeFrame(e){this.#Yr.delete(e._id),this.#Xr.delete(e._id),e._parentId?this.#Qr.get(e._parentId)?.delete(e._id):this.#tn=!0}childFrames(e){const t=this.#Qr.get(e);return t?Array.from(t).map((e=>this.getById(e))).filter((e=>void 0!==e)):[]}parentFrame(e){const t=this.#Xr.get(e);return t?this.getById(t):void 0}}class fp extends Dd{id;#mt;#nn;#xe;#sn;#an;#in=!1;#on;#cn={};#qe;#ln;get client(){return this.#mt}set client(e){this.#mt=e}constructor(e,t,r,n,s,a){super(),this.#mt=e,this.id=s.requestId,this.#nn=s.requestId===s.loaderId&&"Document"===s.type,this._interceptionId=r,this.#xe=s.request.url+(s.request.urlFragment??""),this.#sn=(s.type||"other").toLowerCase(),this.#an=s.request.method,this.#on=s.request.postData,this.#in=s.request.hasPostData??!1,this.#qe=t,this._redirectChain=a,this.#ln=s.initiator,this.interception.enabled=n;for(const[e,t]of Object.entries(s.request.headers))this.#cn[e.toLowerCase()]=t}url(){return this.#xe}resourceType(){return this.#sn}method(){return this.#an}postData(){return this.#on}hasPostData(){return this.#in}async fetchPostData(){try{return(await this.#mt.send("Network.getRequestPostData",{requestId:this.id})).postData}catch(e){return void Zl(e)}}headers(){return this.#cn}response(){return this._response}frame(){return this.#qe}isNavigationRequest(){return this.#nn}initiator(){return this.#ln}redirectChain(){return this._redirectChain.slice()}failure(){return this._failureText?{errorText:this._failureText}:null}async _continue(e={}){const{url:t,method:r,postData:n,headers:s}=e;this.interception.handled=!0;const a=n?function(e){return Fl((new TextEncoder).encode(e))}(n):void 0;if(void 0===this._interceptionId)throw new Error("HTTPRequest is missing _interceptionId needed for Fetch.continueRequest");await this.#mt.send("Fetch.continueRequest",{requestId:this._interceptionId,url:t,method:r,postData:a,headers:s?Ud(s):void 0}).catch((e=>(this.interception.handled=!1,Kd(e))))}async _respond(e){let t;this.interception.handled=!0,e.body&&(t=Dd.getResponse(e.body));const r={};if(e.headers)for(const t of Object.keys(e.headers)){const n=e.headers[t];r[t.toLowerCase()]=Array.isArray(n)?n.map((e=>String(e))):String(n)}e.contentType&&(r["content-type"]=e.contentType),t?.contentLength&&!("content-length"in r)&&(r["content-length"]=String(t.contentLength));const n=e.status||200;if(void 0===this._interceptionId)throw new Error("HTTPRequest is missing _interceptionId needed for Fetch.fulfillRequest");await this.#mt.send("Fetch.fulfillRequest",{requestId:this._interceptionId,responseCode:n,responsePhrase:Bd[n],responseHeaders:Ud(r),body:t?.base64}).catch((e=>(this.interception.handled=!1,Kd(e))))}async _abort(e){if(this.interception.handled=!0,void 0===this._interceptionId)throw new Error("HTTPRequest is missing _interceptionId needed for Fetch.failRequest");await this.#mt.send("Fetch.failRequest",{requestId:this._interceptionId,errorReason:e||"Failed"}).catch(Kd)}}class gp{constructor(){}ok(){const e=this.status();return 0===e||e>=200&&e<=299}async buffer(){const e=await this.content();return Buffer.from(e)}async text(){const e=await this.content();return(new TextDecoder).decode(e)}async json(){const e=await this.text();return JSON.parse(e)}}class yp{#un;#dn;#hn;#pn;#mn;#fn;constructor(e){this.#un=e.subjectName,this.#dn=e.issuer,this.#hn=e.validFrom,this.#pn=e.validTo,this.#mn=e.protocol,this.#fn=e.sanList}issuer(){return this.#dn}validFrom(){return this.#hn}validTo(){return this.#pn}protocol(){return this.#mn}subjectName(){return this.#un}subjectAlternativeNames(){return this.#fn}}class bp extends gp{#gn;#yn=null;#bn=gu.create();#wn;#vn;#_n;#kn;#Sn;#cn={};#En;#xn;constructor(e,t,r){super(),this.#gn=e,this.#wn={ip:t.remoteIPAddress,port:t.remotePort},this.#_n=this.#Tn(r)||t.statusText,this.#kn=!!t.fromDiskCache,this.#Sn=!!t.fromServiceWorker,this.#vn=r?r.statusCode:t.status;const n=r?r.headers:t.headers;for(const[e,t]of Object.entries(n))this.#cn[e.toLowerCase()]=t;this.#En=t.securityDetails?new yp(t.securityDetails):null,this.#xn=t.timing||null}#Tn(e){if(!e||!e.headersText)return;const t=e.headersText.split("\r",1)[0];if(!t||t.length>1e3)return;const r=t.match(/[^ ]* [^ ]* (.*)/);if(!r)return;const n=r[1];return n||void 0}_resolveBody(e){return e?this.#bn.reject(e):this.#bn.resolve()}remoteAddress(){return this.#wn}url(){return this.#gn.url()}status(){return this.#vn}statusText(){return this.#_n}headers(){return this.#cn}securityDetails(){return this.#En}timing(){return this.#xn}content(){return this.#yn||(this.#yn=this.#bn.valueOrThrow().then((async()=>{try{const e=await this.#gn.client.send("Network.getResponseBody",{requestId:this.#gn.id});return Ll(e.body,e.base64Encoded)}catch(e){if(e instanceof Hl&&"No resource with given identifier found"===e.originalMessage)throw new Hl("Could not load body for this request. This might happen if the request is a preflight request.");throw e}}))),this.#yn}request(){return this.#gn}fromCache(){return this.#kn||this.#gn._fromMemoryCache}fromServiceWorker(){return this.#Sn}frame(){return this.#gn.frame()}}class wp{#Cn=new Map;#Pn=new Map;#On=new Map;#An=new Map;#In=new Map;#Mn=new Map;forget(e){this.#Cn.delete(e),this.#Pn.delete(e),this.#Mn.delete(e),this.#In.delete(e),this.#An.delete(e)}responseExtraInfo(e){return this.#An.has(e)||this.#An.set(e,[]),this.#An.get(e)}queuedRedirectInfo(e){return this.#In.has(e)||this.#In.set(e,[]),this.#In.get(e)}queueRedirectInfo(e,t){this.queuedRedirectInfo(e).push(t)}takeQueuedRedirectInfo(e){return this.queuedRedirectInfo(e).shift()}inFlightRequestsCount(){let e=0;for(const t of this.#On.values())t.response()||e++;return e}storeRequestWillBeSent(e,t){this.#Cn.set(e,t)}getRequestWillBeSent(e){return this.#Cn.get(e)}forgetRequestWillBeSent(e){this.#Cn.delete(e)}getRequestPaused(e){return this.#Pn.get(e)}forgetRequestPaused(e){this.#Pn.delete(e)}storeRequestPaused(e,t){this.#Pn.set(e,t)}getRequest(e){return this.#On.get(e)}storeRequest(e,t){this.#On.set(e,t)}forgetRequest(e){this.#On.delete(e)}getQueuedEventGroup(e){return this.#Mn.get(e)}queueEventGroup(e,t){this.#Mn.set(e,t)}forgetQueuedEventGroup(e){this.#Mn.delete(e)}printState(){function e(e,t){return t instanceof Map?{dataType:"Map",value:Array.from(t.entries())}:t instanceof fp?{dataType:"CdpHTTPRequest",value:`${t.id}: ${t.url()}`}:t}console.log("httpRequestsMap",JSON.stringify(this.#On,e,2)),console.log("requestWillBeSentMap",JSON.stringify(this.#Cn,e,2)),console.log("requestWillBeSentMap",JSON.stringify(this.#An,e,2)),console.log("requestWillBeSentMap",JSON.stringify(this.#Pn,e,2))}}class vp extends Ml{#pr;#Rn=new wp;#jn;#Nn=null;#$n=new Set;#Ln=!1;#Fn=!1;#Dn;#zn;#Un;#Bn;#i=[["Fetch.requestPaused",this.#qn],["Fetch.authRequired",this.#Kn],["Network.requestWillBeSent",this.#Wn],["Network.requestServedFromCache",this.#Hn],["Network.responseReceived",this.#Vn],["Network.loadingFinished",this.#Gn],["Network.loadingFailed",this.#Jn],["Network.responseReceivedExtraInfo",this.#Zn],[wu.Disconnected,this.#Yn]];#Xn=new Map;constructor(e){super(),this.#pr=e}async addClient(e){if(this.#Xn.has(e))return;const t=new Ol;this.#Xn.set(e,t);const r=t.use(new Ml(e));for(const[t,n]of this.#i)r.on(t,(t=>n.bind(this)(e,t)));await Promise.all([e.send("Network.enable"),this.#Qn(e),this.#es(e),this.#ts(e),this.#rs(e),this.#ns(e)])}async#Yn(e){this.#Xn.get(e)?.dispose(),this.#Xn.delete(e)}async authenticate(e){this.#Nn=e;const t=this.#Ln||!!this.#Nn;t!==this.#Fn&&(this.#Fn=t,await this.#ss(this.#rs.bind(this)))}async setExtraHTTPHeaders(e){const t={};for(const[r,n]of Object.entries(e))$l(tu(n),`Expected value of header "${r}" to be String, but "${typeof n}" is found.`),t[r.toLowerCase()]=n;this.#jn=t,await this.#ss(this.#Qn.bind(this))}async#Qn(e){void 0!==this.#jn&&await e.send("Network.setExtraHTTPHeaders",{headers:this.#jn})}extraHTTPHeaders(){return Object.assign({},this.#jn)}inFlightRequestsCount(){return this.#Rn.inFlightRequestsCount()}async setOfflineMode(e){this.#zn||(this.#zn={offline:!1,upload:-1,download:-1,latency:0}),this.#zn.offline=e,await this.#ss(this.#es.bind(this))}async emulateNetworkConditions(e){this.#zn||(this.#zn={offline:!1,upload:-1,download:-1,latency:0}),this.#zn.upload=e?e.upload:-1,this.#zn.download=e?e.download:-1,this.#zn.latency=e?e.latency:0,await this.#ss(this.#es.bind(this))}async#ss(e){await Promise.all(Array.from(this.#Xn.keys()).map((t=>e(t))))}async#es(e){void 0!==this.#zn&&await e.send("Network.emulateNetworkConditions",{offline:this.#zn.offline,latency:this.#zn.latency,uploadThroughput:this.#zn.upload,downloadThroughput:this.#zn.download})}async setUserAgent(e,t){this.#Un=e,this.#Bn=t,await this.#ss(this.#ns.bind(this))}async#ns(e){void 0!==this.#Un&&await e.send("Network.setUserAgentOverride",{userAgent:this.#Un,userAgentMetadata:this.#Bn})}async setCacheEnabled(e){this.#Dn=!e,await this.#ss(this.#ts.bind(this))}async setRequestInterception(e){this.#Ln=e;const t=this.#Ln||!!this.#Nn;t!==this.#Fn&&(this.#Fn=t,await this.#ss(this.#rs.bind(this)))}async#rs(e){void 0===this.#Dn&&(this.#Dn=!1),this.#Fn?await Promise.all([this.#ts(e),e.send("Fetch.enable",{handleAuthRequests:!0,patterns:[{urlPattern:"*"}]})]):await Promise.all([this.#ts(e),e.send("Fetch.disable")])}async#ts(e){void 0!==this.#Dn&&await e.send("Network.setCacheDisabled",{cacheDisabled:this.#Dn})}#Wn(e,t){if(!this.#Ln||t.request.url.startsWith("data:"))this.#Wr(e,t,void 0);else{const{requestId:r}=t;this.#Rn.storeRequestWillBeSent(r,t);const n=this.#Rn.getRequestPaused(r);if(n){const{requestId:s}=n;this.#as(t,n),this.#Wr(e,t,s),this.#Rn.forgetRequestPaused(r)}}}#Kn(e,t){let r="Default";this.#$n.has(t.requestId)?r="CancelAuth":this.#Nn&&(r="ProvideCredentials",this.#$n.add(t.requestId));const{username:n,password:s}=this.#Nn||{username:void 0,password:void 0};e.send("Fetch.continueWithAuth",{requestId:t.requestId,authChallengeResponse:{response:r,username:n,password:s}}).catch(Zl)}#qn(e,t){!this.#Ln&&this.#Fn&&e.send("Fetch.continueRequest",{requestId:t.requestId}).catch(Zl);const{networkId:r,requestId:n}=t;if(!r)return void this.#is(e,t);const s=(()=>{const e=this.#Rn.getRequestWillBeSent(r);if(!e||e.request.url===t.request.url&&e.request.method===t.request.method)return e;this.#Rn.forgetRequestWillBeSent(r)})();s?(this.#as(s,t),this.#Wr(e,s,n)):this.#Rn.storeRequestPaused(r,t)}#as(e,t){e.request.headers={...e.request.headers,...t.request.headers}}#is(e,t){const r=t.frameId?this.#pr.frame(t.frameId):null,n=new fp(e,r,t.requestId,this.#Ln,t,[]);this.emit(mh.Request,n),n.finalizeInterceptions()}#Wr(e,t,r,n=!1){let s=[];if(t.redirectResponse){let n=null;if(t.redirectHasExtraInfo&&(n=this.#Rn.responseExtraInfo(t.requestId).shift(),!n))return void this.#Rn.queueRedirectInfo(t.requestId,{event:t,fetchRequestId:r});const a=this.#Rn.getRequest(t.requestId);a&&(this.#os(e,a,t.redirectResponse,n),s=a._redirectChain)}const a=t.frameId?this.#pr.frame(t.frameId):null,i=new fp(e,a,r,this.#Ln,t,s);i._fromMemoryCache=n,this.#Rn.storeRequest(t.requestId,i),this.emit(mh.Request,i),i.finalizeInterceptions()}#Hn(e,t){const r=this.#Rn.getRequestWillBeSent(t.requestId);let n=this.#Rn.getRequest(t.requestId);n&&(n._fromMemoryCache=!0),!n&&r&&(this.#Wr(e,r,void 0,!0),n=this.#Rn.getRequest(t.requestId)),n?this.emit(mh.RequestServedFromCache,n):Zl(new Error(`Request ${t.requestId} was served from cache but we could not find the corresponding request object`))}#os(e,t,r,n){const s=new bp(t,r,n);t._response=s,t._redirectChain.push(t),s._resolveBody(new Error("Response body is unavailable for redirect responses")),this.#cs(t,!1),this.emit(mh.Response,s),this.emit(mh.RequestFinished,t)}#ls(e,t,r){const n=this.#Rn.getRequest(t.requestId);if(!n)return;this.#Rn.responseExtraInfo(t.requestId).length&&Zl(new Error("Unexpected extraInfo events for request "+t.requestId)),t.response.fromDiskCache&&(r=null);const s=new bp(n,t.response,r);n._response=s,this.emit(mh.Response,s)}#Vn(e,t){const r=this.#Rn.getRequest(t.requestId);let n=null;!r||r._fromMemoryCache||!t.hasExtraInfo||(n=this.#Rn.responseExtraInfo(t.requestId).shift(),n)?this.#ls(e,t,n):this.#Rn.queueEventGroup(t.requestId,{responseReceivedEvent:t})}#Zn(e,t){const r=this.#Rn.takeQueuedRedirectInfo(t.requestId);if(r)return this.#Rn.responseExtraInfo(t.requestId).push(t),void this.#Wr(e,r.event,r.fetchRequestId);const n=this.#Rn.getQueuedEventGroup(t.requestId);if(n)return this.#Rn.forgetQueuedEventGroup(t.requestId),this.#ls(e,n.responseReceivedEvent,t),n.loadingFinishedEvent&&this.#us(e,n.loadingFinishedEvent),void(n.loadingFailedEvent&&this.#ds(e,n.loadingFailedEvent));this.#Rn.responseExtraInfo(t.requestId).push(t)}#cs(e,t){const r=e.id,n=e._interceptionId;this.#Rn.forgetRequest(r),void 0!==n&&this.#$n.delete(n),t&&this.#Rn.forget(r)}#Gn(e,t){const r=this.#Rn.getQueuedEventGroup(t.requestId);r?r.loadingFinishedEvent=t:this.#us(e,t)}#us(e,t){const r=this.#Rn.getRequest(t.requestId);r&&(this.#hs(e,r),r.response()&&r.response()?._resolveBody(),this.#cs(r,!0),this.emit(mh.RequestFinished,r))}#Jn(e,t){const r=this.#Rn.getQueuedEventGroup(t.requestId);r?r.loadingFailedEvent=t:this.#ds(e,t)}#ds(e,t){const r=this.#Rn.getRequest(t.requestId);if(!r)return;this.#hs(e,r),r._failureText=t.errorText;const n=r.response();n&&n._resolveBody(),this.#cs(r,!0),this.emit(mh.RequestFailed,r)}#hs(e,t){e!==t.client&&(t.client=e)}}class _p extends Ml{#ps;#ms;#ar;#fs=new Set;#mt;#gs=new Map;#yr=new Set;_frameTree=new mp;#ys=new Set;#bs=new WeakMap;#ws;get timeoutSettings(){return this.#ar}get networkManager(){return this.#ms}get client(){return this.#mt}constructor(e,t,r){super(),this.#mt=e,this.#ps=t,this.#ms=new vp(this),this.#ar=r,this.setupEventListeners(this.#mt),e.once(wu.Disconnected,(()=>{this.#vs().catch(Zl)}))}async#vs(){const e=this._frameTree.getMainFrame();if(!e)return;if(!this.#ps.browser().connected)return void this.#_s(e);for(const t of e.childFrames())this.#_s(t);const t=gu.create({timeout:100,message:"Frame was not swapped"});e.once(Md.FrameSwappedByActivation,(()=>{t.resolve()}));try{await t.valueOrThrow()}catch{this.#_s(e)}}async swapFrameTree(e){this.#mt=e;const t=this._frameTree.getMainFrame();t&&(this.#ys.add(this.#mt.target()._targetId),this._frameTree.removeFrame(t),t.updateId(this.#mt.target()._targetId),this._frameTree.addFrame(t),t.updateClient(e)),this.setupEventListeners(e),e.once(wu.Disconnected,(()=>{this.#vs().catch(Zl)})),await this.initialize(e,t),await this.#ms.addClient(e),t&&t.emit(Md.FrameSwappedByActivation,void 0)}async registerSpeculativeSession(e){await this.#ms.addClient(e)}setupEventListeners(e){e.on("Page.frameAttached",(async t=>{await(this.#ws?.valueOrThrow()),this.#ks(e,t.frameId,t.parentFrameId)})),e.on("Page.frameNavigated",(async e=>{this.#ys.add(e.frame.id),await(this.#ws?.valueOrThrow()),this.#Ss(e.frame,e.type)})),e.on("Page.navigatedWithinDocument",(async e=>{await(this.#ws?.valueOrThrow()),this.#Es(e.frameId,e.url)})),e.on("Page.frameDetached",(async e=>{await(this.#ws?.valueOrThrow()),this.#Kr(e.frameId,e.reason)})),e.on("Page.frameStartedLoading",(async e=>{await(this.#ws?.valueOrThrow()),this.#xs(e.frameId)})),e.on("Page.frameStoppedLoading",(async e=>{await(this.#ws?.valueOrThrow()),this.#Ts(e.frameId)})),e.on("Runtime.executionContextCreated",(async t=>{await(this.#ws?.valueOrThrow()),this.#Cs(t.context,e)})),e.on("Page.lifecycleEvent",(async e=>{await(this.#ws?.valueOrThrow()),this.#Ps(e)}))}async initialize(e,t){try{this.#ws?.resolve(),this.#ws=gu.create(),await Promise.all([this.#ms.addClient(e),e.send("Page.enable"),e.send("Page.getFrameTree").then((({frameTree:t})=>{this.#Os(e,t),this.#ws?.resolve()})),e.send("Page.setLifecycleEventsEnabled",{enabled:!0}),e.send("Runtime.enable").then((()=>this.#As(e,iu))),...(t?Array.from(this.#gs.values()):[]).map((e=>t?.addPreloadScript(e))),...(t?Array.from(this.#yr.values()):[]).map((e=>t?.addExposedFunctionBinding(e)))])}catch(e){if(this.#ws?.resolve(),ku(e)&&Th(e))return;throw e}}page(){return this.#ps}mainFrame(){const e=this._frameTree.getMainFrame();return $l(e,"Requesting main frame too early!"),e}frames(){return Array.from(this._frameTree.frames())}frame(e){return this._frameTree.getById(e)||null}async addExposedFunctionBinding(e){this.#yr.add(e),await Promise.all(this.frames().map((async t=>await t.addExposedFunctionBinding(e))))}async removeExposedFunctionBinding(e){this.#yr.delete(e),await Promise.all(this.frames().map((async t=>await t.removeExposedFunctionBinding(e))))}async evaluateOnNewDocument(e){const{identifier:t}=await this.mainFrame()._client().send("Page.addScriptToEvaluateOnNewDocument",{source:e}),r=new Fh(this.mainFrame(),t,e);return this.#gs.set(t,r),await Promise.all(this.frames().map((async e=>await e.addPreloadScript(r)))),{identifier:t}}async removeScriptToEvaluateOnNewDocument(e){const t=this.#gs.get(e);if(!t)throw new Error(`Script to evaluate on new document with id ${e} not found`);this.#gs.delete(e),await Promise.all(this.frames().map((e=>{const r=t.getIdForFrame(e);if(r)return e._client().send("Page.removeScriptToEvaluateOnNewDocument",{identifier:r}).catch(Zl)})))}onAttachedToTarget(e){if("iframe"!==e._getTargetInfo().type)return;const t=this.frame(e._getTargetInfo().targetId);t&&t.updateClient(e._session()),this.setupEventListeners(e._session()),this.initialize(e._session(),t)}_deviceRequestPromptManager(e){let t=this.#bs.get(e);return void 0===t&&(t=new Uh(e,this.#ar),this.#bs.set(e,t)),t}#Ps(e){const t=this.frame(e.frameId);t&&(t._onLifecycleEvent(e.loaderId,e.name),this.emit(ap.LifecycleEvent,t),t.emit(Md.LifecycleEvent,void 0))}#xs(e){const t=this.frame(e);t&&t._onLoadingStarted()}#Ts(e){const t=this.frame(e);t&&(t._onLoadingStopped(),this.emit(ap.LifecycleEvent,t),t.emit(Md.LifecycleEvent,void 0))}#Os(e,t){if(t.frame.parentId&&this.#ks(e,t.frame.id,t.frame.parentId),this.#ys.has(t.frame.id)?this.#ys.delete(t.frame.id):this.#Ss(t.frame,"Navigation"),t.childFrames)for(const r of t.childFrames)this.#Os(e,r)}#ks(e,t,r){let n=this.frame(t);if(n){const t=this.frame(r);e&&t&&n.client!==t?.client&&n.updateClient(e)}else n=new pp(this,t,r,e),this._frameTree.addFrame(n),this.emit(ap.FrameAttached,n)}async#Ss(e,t){const r=e.id,n=!e.parentId;let s=this._frameTree.getById(r);if(s)for(const e of s.childFrames())this.#_s(e);n&&(s?(this._frameTree.removeFrame(s),s._id=r):s=new pp(this,r,void 0,this.#mt),this._frameTree.addFrame(s)),s=await this._frameTree.waitForFrame(r),s._navigated(e),this.emit(ap.FrameNavigated,s),s.emit(Md.FrameNavigated,t)}async#As(e,t){const r=`${e.id()}:${t}`;this.#fs.has(r)||(await e.send("Page.addScriptToEvaluateOnNewDocument",{source:`//# sourceURL=${Ql.INTERNAL_URL}`,worldName:t}),await Promise.all(this.frames().filter((t=>t.client===e)).map((r=>e.send("Page.createIsolatedWorld",{frameId:r._id,worldName:t,grantUniveralAccess:!0}).catch(Zl)))),this.#fs.add(r))}#Es(e,t){const r=this.frame(e);r&&(r._navigatedWithinDocument(t),this.emit(ap.FrameNavigatedWithinDocument,r),r.emit(Md.FrameNavigatedWithinDocument,void 0),this.emit(ap.FrameNavigated,r),r.emit(Md.FrameNavigated,"Navigation"))}#Kr(e,t){const r=this.frame(e);if(r)switch(t){case"remove":this.#_s(r);break;case"swap":this.emit(ap.FrameSwapped,r),r.emit(Md.FrameSwapped,void 0)}}#Cs(e,t){const r=e.auxData,n=r&&r.frameId,s="string"==typeof n?this.frame(n):void 0;let a;if(s){if(s.client!==t)return;e.auxData&&e.auxData.isDefault?a=s.worlds[op]:e.name===iu&&(a=s.worlds[cp])}if(!a)return;const i=new np(s?.client||this.#mt,e,a);a.setContext(i)}#_s(e){for(const t of e.childFrames())this.#_s(t);e[Cl](),this._frameTree.removeFrame(e),this.emit(ap.FrameDetached,e),e.emit(Md.FrameDetached,e)}}const kp={0:{keyCode:48,key:"0",code:"Digit0"},1:{keyCode:49,key:"1",code:"Digit1"},2:{keyCode:50,key:"2",code:"Digit2"},3:{keyCode:51,key:"3",code:"Digit3"},4:{keyCode:52,key:"4",code:"Digit4"},5:{keyCode:53,key:"5",code:"Digit5"},6:{keyCode:54,key:"6",code:"Digit6"},7:{keyCode:55,key:"7",code:"Digit7"},8:{keyCode:56,key:"8",code:"Digit8"},9:{keyCode:57,key:"9",code:"Digit9"},Power:{key:"Power",code:"Power"},Eject:{key:"Eject",code:"Eject"},Abort:{keyCode:3,code:"Abort",key:"Cancel"},Help:{keyCode:6,code:"Help",key:"Help"},Backspace:{keyCode:8,code:"Backspace",key:"Backspace"},Tab:{keyCode:9,code:"Tab",key:"Tab"},Numpad5:{keyCode:12,shiftKeyCode:101,key:"Clear",code:"Numpad5",shiftKey:"5",location:3},NumpadEnter:{keyCode:13,code:"NumpadEnter",key:"Enter",text:"\r",location:3},Enter:{keyCode:13,code:"Enter",key:"Enter",text:"\r"},"\r":{keyCode:13,code:"Enter",key:"Enter",text:"\r"},"\n":{keyCode:13,code:"Enter",key:"Enter",text:"\r"},ShiftLeft:{keyCode:16,code:"ShiftLeft",key:"Shift",location:1},ShiftRight:{keyCode:16,code:"ShiftRight",key:"Shift",location:2},ControlLeft:{keyCode:17,code:"ControlLeft",key:"Control",location:1},ControlRight:{keyCode:17,code:"ControlRight",key:"Control",location:2},AltLeft:{keyCode:18,code:"AltLeft",key:"Alt",location:1},AltRight:{keyCode:18,code:"AltRight",key:"Alt",location:2},Pause:{keyCode:19,code:"Pause",key:"Pause"},CapsLock:{keyCode:20,code:"CapsLock",key:"CapsLock"},Escape:{keyCode:27,code:"Escape",key:"Escape"},Convert:{keyCode:28,code:"Convert",key:"Convert"},NonConvert:{keyCode:29,code:"NonConvert",key:"NonConvert"},Space:{keyCode:32,code:"Space",key:" "},Numpad9:{keyCode:33,shiftKeyCode:105,key:"PageUp",code:"Numpad9",shiftKey:"9",location:3},PageUp:{keyCode:33,code:"PageUp",key:"PageUp"},Numpad3:{keyCode:34,shiftKeyCode:99,key:"PageDown",code:"Numpad3",shiftKey:"3",location:3},PageDown:{keyCode:34,code:"PageDown",key:"PageDown"},End:{keyCode:35,code:"End",key:"End"},Numpad1:{keyCode:35,shiftKeyCode:97,key:"End",code:"Numpad1",shiftKey:"1",location:3},Home:{keyCode:36,code:"Home",key:"Home"},Numpad7:{keyCode:36,shiftKeyCode:103,key:"Home",code:"Numpad7",shiftKey:"7",location:3},ArrowLeft:{keyCode:37,code:"ArrowLeft",key:"ArrowLeft"},Numpad4:{keyCode:37,shiftKeyCode:100,key:"ArrowLeft",code:"Numpad4",shiftKey:"4",location:3},Numpad8:{keyCode:38,shiftKeyCode:104,key:"ArrowUp",code:"Numpad8",shiftKey:"8",location:3},ArrowUp:{keyCode:38,code:"ArrowUp",key:"ArrowUp"},ArrowRight:{keyCode:39,code:"ArrowRight",key:"ArrowRight"},Numpad6:{keyCode:39,shiftKeyCode:102,key:"ArrowRight",code:"Numpad6",shiftKey:"6",location:3},Numpad2:{keyCode:40,shiftKeyCode:98,key:"ArrowDown",code:"Numpad2",shiftKey:"2",location:3},ArrowDown:{keyCode:40,code:"ArrowDown",key:"ArrowDown"},Select:{keyCode:41,code:"Select",key:"Select"},Open:{keyCode:43,code:"Open",key:"Execute"},PrintScreen:{keyCode:44,code:"PrintScreen",key:"PrintScreen"},Insert:{keyCode:45,code:"Insert",key:"Insert"},Numpad0:{keyCode:45,shiftKeyCode:96,key:"Insert",code:"Numpad0",shiftKey:"0",location:3},Delete:{keyCode:46,code:"Delete",key:"Delete"},NumpadDecimal:{keyCode:46,shiftKeyCode:110,code:"NumpadDecimal",key:"\0",shiftKey:".",location:3},Digit0:{keyCode:48,code:"Digit0",shiftKey:")",key:"0"},Digit1:{keyCode:49,code:"Digit1",shiftKey:"!",key:"1"},Digit2:{keyCode:50,code:"Digit2",shiftKey:"@",key:"2"},Digit3:{keyCode:51,code:"Digit3",shiftKey:"#",key:"3"},Digit4:{keyCode:52,code:"Digit4",shiftKey:"$",key:"4"},Digit5:{keyCode:53,code:"Digit5",shiftKey:"%",key:"5"},Digit6:{keyCode:54,code:"Digit6",shiftKey:"^",key:"6"},Digit7:{keyCode:55,code:"Digit7",shiftKey:"&",key:"7"},Digit8:{keyCode:56,code:"Digit8",shiftKey:"*",key:"8"},Digit9:{keyCode:57,code:"Digit9",shiftKey:"(",key:"9"},KeyA:{keyCode:65,code:"KeyA",shiftKey:"A",key:"a"},KeyB:{keyCode:66,code:"KeyB",shiftKey:"B",key:"b"},KeyC:{keyCode:67,code:"KeyC",shiftKey:"C",key:"c"},KeyD:{keyCode:68,code:"KeyD",shiftKey:"D",key:"d"},KeyE:{keyCode:69,code:"KeyE",shiftKey:"E",key:"e"},KeyF:{keyCode:70,code:"KeyF",shiftKey:"F",key:"f"},KeyG:{keyCode:71,code:"KeyG",shiftKey:"G",key:"g"},KeyH:{keyCode:72,code:"KeyH",shiftKey:"H",key:"h"},KeyI:{keyCode:73,code:"KeyI",shiftKey:"I",key:"i"},KeyJ:{keyCode:74,code:"KeyJ",shiftKey:"J",key:"j"},KeyK:{keyCode:75,code:"KeyK",shiftKey:"K",key:"k"},KeyL:{keyCode:76,code:"KeyL",shiftKey:"L",key:"l"},KeyM:{keyCode:77,code:"KeyM",shiftKey:"M",key:"m"},KeyN:{keyCode:78,code:"KeyN",shiftKey:"N",key:"n"},KeyO:{keyCode:79,code:"KeyO",shiftKey:"O",key:"o"},KeyP:{keyCode:80,code:"KeyP",shiftKey:"P",key:"p"},KeyQ:{keyCode:81,code:"KeyQ",shiftKey:"Q",key:"q"},KeyR:{keyCode:82,code:"KeyR",shiftKey:"R",key:"r"},KeyS:{keyCode:83,code:"KeyS",shiftKey:"S",key:"s"},KeyT:{keyCode:84,code:"KeyT",shiftKey:"T",key:"t"},KeyU:{keyCode:85,code:"KeyU",shiftKey:"U",key:"u"},KeyV:{keyCode:86,code:"KeyV",shiftKey:"V",key:"v"},KeyW:{keyCode:87,code:"KeyW",shiftKey:"W",key:"w"},KeyX:{keyCode:88,code:"KeyX",shiftKey:"X",key:"x"},KeyY:{keyCode:89,code:"KeyY",shiftKey:"Y",key:"y"},KeyZ:{keyCode:90,code:"KeyZ",shiftKey:"Z",key:"z"},MetaLeft:{keyCode:91,code:"MetaLeft",key:"Meta",location:1},MetaRight:{keyCode:92,code:"MetaRight",key:"Meta",location:2},ContextMenu:{keyCode:93,code:"ContextMenu",key:"ContextMenu"},NumpadMultiply:{keyCode:106,code:"NumpadMultiply",key:"*",location:3},NumpadAdd:{keyCode:107,code:"NumpadAdd",key:"+",location:3},NumpadSubtract:{keyCode:109,code:"NumpadSubtract",key:"-",location:3},NumpadDivide:{keyCode:111,code:"NumpadDivide",key:"/",location:3},F1:{keyCode:112,code:"F1",key:"F1"},F2:{keyCode:113,code:"F2",key:"F2"},F3:{keyCode:114,code:"F3",key:"F3"},F4:{keyCode:115,code:"F4",key:"F4"},F5:{keyCode:116,code:"F5",key:"F5"},F6:{keyCode:117,code:"F6",key:"F6"},F7:{keyCode:118,code:"F7",key:"F7"},F8:{keyCode:119,code:"F8",key:"F8"},F9:{keyCode:120,code:"F9",key:"F9"},F10:{keyCode:121,code:"F10",key:"F10"},F11:{keyCode:122,code:"F11",key:"F11"},F12:{keyCode:123,code:"F12",key:"F12"},F13:{keyCode:124,code:"F13",key:"F13"},F14:{keyCode:125,code:"F14",key:"F14"},F15:{keyCode:126,code:"F15",key:"F15"},F16:{keyCode:127,code:"F16",key:"F16"},F17:{keyCode:128,code:"F17",key:"F17"},F18:{keyCode:129,code:"F18",key:"F18"},F19:{keyCode:130,code:"F19",key:"F19"},F20:{keyCode:131,code:"F20",key:"F20"},F21:{keyCode:132,code:"F21",key:"F21"},F22:{keyCode:133,code:"F22",key:"F22"},F23:{keyCode:134,code:"F23",key:"F23"},F24:{keyCode:135,code:"F24",key:"F24"},NumLock:{keyCode:144,code:"NumLock",key:"NumLock"},ScrollLock:{keyCode:145,code:"ScrollLock",key:"ScrollLock"},AudioVolumeMute:{keyCode:173,code:"AudioVolumeMute",key:"AudioVolumeMute"},AudioVolumeDown:{keyCode:174,code:"AudioVolumeDown",key:"AudioVolumeDown"},AudioVolumeUp:{keyCode:175,code:"AudioVolumeUp",key:"AudioVolumeUp"},MediaTrackNext:{keyCode:176,code:"MediaTrackNext",key:"MediaTrackNext"},MediaTrackPrevious:{keyCode:177,code:"MediaTrackPrevious",key:"MediaTrackPrevious"},MediaStop:{keyCode:178,code:"MediaStop",key:"MediaStop"},MediaPlayPause:{keyCode:179,code:"MediaPlayPause",key:"MediaPlayPause"},Semicolon:{keyCode:186,code:"Semicolon",shiftKey:":",key:";"},Equal:{keyCode:187,code:"Equal",shiftKey:"+",key:"="},NumpadEqual:{keyCode:187,code:"NumpadEqual",key:"=",location:3},Comma:{keyCode:188,code:"Comma",shiftKey:"<",key:","},Minus:{keyCode:189,code:"Minus",shiftKey:"_",key:"-"},Period:{keyCode:190,code:"Period",shiftKey:">",key:"."},Slash:{keyCode:191,code:"Slash",shiftKey:"?",key:"/"},Backquote:{keyCode:192,code:"Backquote",shiftKey:"~",key:"`"},BracketLeft:{keyCode:219,code:"BracketLeft",shiftKey:"{",key:"["},Backslash:{keyCode:220,code:"Backslash",shiftKey:"|",key:"\\"},BracketRight:{keyCode:221,code:"BracketRight",shiftKey:"}",key:"]"},Quote:{keyCode:222,code:"Quote",shiftKey:'"',key:"'"},AltGraph:{keyCode:225,code:"AltGraph",key:"AltGraph"},Props:{keyCode:247,code:"Props",key:"CrSel"},Cancel:{keyCode:3,key:"Cancel",code:"Abort"},Clear:{keyCode:12,key:"Clear",code:"Numpad5",location:3},Shift:{keyCode:16,key:"Shift",code:"ShiftLeft",location:1},Control:{keyCode:17,key:"Control",code:"ControlLeft",location:1},Alt:{keyCode:18,key:"Alt",code:"AltLeft",location:1},Accept:{keyCode:30,key:"Accept"},ModeChange:{keyCode:31,key:"ModeChange"}," ":{keyCode:32,key:" ",code:"Space"},Print:{keyCode:42,key:"Print"},Execute:{keyCode:43,key:"Execute",code:"Open"},"\0":{keyCode:46,key:"\0",code:"NumpadDecimal",location:3},a:{keyCode:65,key:"a",code:"KeyA"},b:{keyCode:66,key:"b",code:"KeyB"},c:{keyCode:67,key:"c",code:"KeyC"},d:{keyCode:68,key:"d",code:"KeyD"},e:{keyCode:69,key:"e",code:"KeyE"},f:{keyCode:70,key:"f",code:"KeyF"},g:{keyCode:71,key:"g",code:"KeyG"},h:{keyCode:72,key:"h",code:"KeyH"},i:{keyCode:73,key:"i",code:"KeyI"},j:{keyCode:74,key:"j",code:"KeyJ"},k:{keyCode:75,key:"k",code:"KeyK"},l:{keyCode:76,key:"l",code:"KeyL"},m:{keyCode:77,key:"m",code:"KeyM"},n:{keyCode:78,key:"n",code:"KeyN"},o:{keyCode:79,key:"o",code:"KeyO"},p:{keyCode:80,key:"p",code:"KeyP"},q:{keyCode:81,key:"q",code:"KeyQ"},r:{keyCode:82,key:"r",code:"KeyR"},s:{keyCode:83,key:"s",code:"KeyS"},t:{keyCode:84,key:"t",code:"KeyT"},u:{keyCode:85,key:"u",code:"KeyU"},v:{keyCode:86,key:"v",code:"KeyV"},w:{keyCode:87,key:"w",code:"KeyW"},x:{keyCode:88,key:"x",code:"KeyX"},y:{keyCode:89,key:"y",code:"KeyY"},z:{keyCode:90,key:"z",code:"KeyZ"},Meta:{keyCode:91,key:"Meta",code:"MetaLeft",location:1},"*":{keyCode:106,key:"*",code:"NumpadMultiply",location:3},"+":{keyCode:107,key:"+",code:"NumpadAdd",location:3},"-":{keyCode:109,key:"-",code:"NumpadSubtract",location:3},"/":{keyCode:111,key:"/",code:"NumpadDivide",location:3},";":{keyCode:186,key:";",code:"Semicolon"},"=":{keyCode:187,key:"=",code:"Equal"},",":{keyCode:188,key:",",code:"Comma"},".":{keyCode:190,key:".",code:"Period"},"`":{keyCode:192,key:"`",code:"Backquote"},"[":{keyCode:219,key:"[",code:"BracketLeft"},"\\":{keyCode:220,key:"\\",code:"Backslash"},"]":{keyCode:221,key:"]",code:"BracketRight"},"'":{keyCode:222,key:"'",code:"Quote"},Attn:{keyCode:246,key:"Attn"},CrSel:{keyCode:247,key:"CrSel",code:"Props"},ExSel:{keyCode:248,key:"ExSel"},EraseEof:{keyCode:249,key:"EraseEof"},Play:{keyCode:250,key:"Play"},ZoomOut:{keyCode:251,key:"ZoomOut"},")":{keyCode:48,key:")",code:"Digit0"},"!":{keyCode:49,key:"!",code:"Digit1"},"@":{keyCode:50,key:"@",code:"Digit2"},"#":{keyCode:51,key:"#",code:"Digit3"},$:{keyCode:52,key:"$",code:"Digit4"},"%":{keyCode:53,key:"%",code:"Digit5"},"^":{keyCode:54,key:"^",code:"Digit6"},"&":{keyCode:55,key:"&",code:"Digit7"},"(":{keyCode:57,key:"(",code:"Digit9"},A:{keyCode:65,key:"A",code:"KeyA"},B:{keyCode:66,key:"B",code:"KeyB"},C:{keyCode:67,key:"C",code:"KeyC"},D:{keyCode:68,key:"D",code:"KeyD"},E:{keyCode:69,key:"E",code:"KeyE"},F:{keyCode:70,key:"F",code:"KeyF"},G:{keyCode:71,key:"G",code:"KeyG"},H:{keyCode:72,key:"H",code:"KeyH"},I:{keyCode:73,key:"I",code:"KeyI"},J:{keyCode:74,key:"J",code:"KeyJ"},K:{keyCode:75,key:"K",code:"KeyK"},L:{keyCode:76,key:"L",code:"KeyL"},M:{keyCode:77,key:"M",code:"KeyM"},N:{keyCode:78,key:"N",code:"KeyN"},O:{keyCode:79,key:"O",code:"KeyO"},P:{keyCode:80,key:"P",code:"KeyP"},Q:{keyCode:81,key:"Q",code:"KeyQ"},R:{keyCode:82,key:"R",code:"KeyR"},S:{keyCode:83,key:"S",code:"KeyS"},T:{keyCode:84,key:"T",code:"KeyT"},U:{keyCode:85,key:"U",code:"KeyU"},V:{keyCode:86,key:"V",code:"KeyV"},W:{keyCode:87,key:"W",code:"KeyW"},X:{keyCode:88,key:"X",code:"KeyX"},Y:{keyCode:89,key:"Y",code:"KeyY"},Z:{keyCode:90,key:"Z",code:"KeyZ"},":":{keyCode:186,key:":",code:"Semicolon"},"<":{keyCode:188,key:"<",code:"Comma"},_:{keyCode:189,key:"_",code:"Minus"},">":{keyCode:190,key:">",code:"Period"},"?":{keyCode:191,key:"?",code:"Slash"},"~":{keyCode:192,key:"~",code:"Backquote"},"{":{keyCode:219,key:"{",code:"BracketLeft"},"|":{keyCode:220,key:"|",code:"Backslash"},"}":{keyCode:221,key:"}",code:"BracketRight"},'"':{keyCode:222,key:'"',code:"Quote"},SoftLeft:{key:"SoftLeft",code:"SoftLeft",location:4},SoftRight:{key:"SoftRight",code:"SoftRight",location:4},Camera:{keyCode:44,key:"Camera",code:"Camera",location:4},Call:{key:"Call",code:"Call",location:4},EndCall:{keyCode:95,key:"EndCall",code:"EndCall",location:4},VolumeDown:{keyCode:182,key:"VolumeDown",code:"VolumeDown",location:4},VolumeUp:{keyCode:183,key:"VolumeUp",code:"VolumeUp",location:4}};class Sp extends Hd{#mt;#Is=new Set;_modifiers=0;constructor(e){super(),this.#mt=e}updateClient(e){this.#mt=e}async down(e,t={text:void 0,commands:[]}){const r=this.#Ms(e),n=this.#Is.has(r.code);this.#Is.add(r.code),this._modifiers|=this.#Rs(r.key);const s=void 0===t.text?r.text:t.text;await this.#mt.send("Input.dispatchKeyEvent",{type:s?"keyDown":"rawKeyDown",modifiers:this._modifiers,windowsVirtualKeyCode:r.keyCode,code:r.code,key:r.key,text:s,unmodifiedText:s,autoRepeat:n,location:r.location,isKeypad:3===r.location,commands:t.commands})}#Rs(e){return"Alt"===e?1:"Control"===e?2:"Meta"===e?4:"Shift"===e?8:0}#Ms(e){const t=8&this._modifiers,r={key:"",keyCode:0,code:"",text:"",location:0},n=kp[e];return $l(n,`Unknown key: "${e}"`),n.key&&(r.key=n.key),t&&n.shiftKey&&(r.key=n.shiftKey),n.keyCode&&(r.keyCode=n.keyCode),t&&n.shiftKeyCode&&(r.keyCode=n.shiftKeyCode),n.code&&(r.code=n.code),n.location&&(r.location=n.location),1===r.key.length&&(r.text=r.key),n.text&&(r.text=n.text),t&&n.shiftText&&(r.text=n.shiftText),-9&this._modifiers&&(r.text=""),r}async up(e){const t=this.#Ms(e);this._modifiers&=~this.#Rs(t.key),this.#Is.delete(t.code),await this.#mt.send("Input.dispatchKeyEvent",{type:"keyUp",modifiers:this._modifiers,key:t.key,windowsVirtualKeyCode:t.keyCode,code:t.code,location:t.location})}async sendCharacter(e){await this.#mt.send("Input.insertText",{text:e})}charIsKey(e){return!!kp[e]}async type(e,t={}){const r=t.delay||void 0;for(const t of e)this.charIsKey(t)?await this.press(t,{delay:r}):(r&&await new Promise((e=>setTimeout(e,r))),await this.sendCharacter(t))}async press(e,t={}){const{delay:r=null}=t;await this.down(e,t),r&&await new Promise((e=>setTimeout(e,t.delay))),await this.up(e)}}const Ep=e=>{switch(e){case Vd.Left:return 1;case Vd.Right:return 2;case Vd.Middle:return 4;case Vd.Back:return 8;case Vd.Forward:return 16}},xp=e=>1&e?Vd.Left:2&e?Vd.Right:4&e?Vd.Middle:8&e?Vd.Back:16&e?Vd.Forward:"none";class Tp extends Gd{#mt;#js;constructor(e,t){super(),this.#mt=e,this.#js=t}updateClient(e){this.#mt=e}#Ns={position:{x:0,y:0},buttons:0};get#At(){return Object.assign({...this.#Ns},...this.#$s)}#$s=[];#Ls(){const e={};this.#$s.push(e);const t=()=>{this.#$s.splice(this.#$s.indexOf(e),1)};return{update:t=>{Object.assign(e,t)},commit:()=>{this.#Ns={...this.#Ns,...e},t()},rollback:t}}async#Fs(e){const{update:t,commit:r,rollback:n}=this.#Ls();try{await e(t),r()}catch(e){throw n(),e}}async reset(){const e=[];for(const[t,r]of[[1,Vd.Left],[4,Vd.Middle],[2,Vd.Right],[16,Vd.Forward],[8,Vd.Back]])this.#At.buttons&t&&e.push(this.up({button:r}));0===this.#At.position.x&&0===this.#At.position.y||e.push(this.move(0,0)),await Promise.all(e)}async move(e,t,r={}){const{steps:n=1}=r,s=this.#At.position,a=e,i=t;for(let e=1;e<=n;e++)await this.#Fs((t=>{t({position:{x:s.x+(a-s.x)*(e/n),y:s.y+(i-s.y)*(e/n)}});const{buttons:r,position:o}=this.#At;return this.#mt.send("Input.dispatchMouseEvent",{type:"mouseMoved",modifiers:this.#js._modifiers,buttons:r,button:xp(r),...o})}))}async down(e={}){const{button:t=Vd.Left,clickCount:r=1}=e,n=Ep(t);if(!n)throw new Error(`Unsupported mouse button: ${t}`);if(this.#At.buttons&n)throw new Error(`'${t}' is already pressed.`);await this.#Fs((e=>{e({buttons:this.#At.buttons|n});const{buttons:s,position:a}=this.#At;return this.#mt.send("Input.dispatchMouseEvent",{type:"mousePressed",modifiers:this.#js._modifiers,clickCount:r,buttons:s,button:t,...a})}))}async up(e={}){const{button:t=Vd.Left,clickCount:r=1}=e,n=Ep(t);if(!n)throw new Error(`Unsupported mouse button: ${t}`);if(!(this.#At.buttons&n))throw new Error(`'${t}' is not pressed.`);await this.#Fs((e=>{e({buttons:this.#At.buttons&~n});const{buttons:s,position:a}=this.#At;return this.#mt.send("Input.dispatchMouseEvent",{type:"mouseReleased",modifiers:this.#js._modifiers,clickCount:r,buttons:s,button:t,...a})}))}async click(e,t,r={}){const{delay:n,count:s=1,clickCount:a=s}=r;if(s<1)throw new Error("Click must occur a positive number of times.");const i=[this.move(e,t)];if(a===s)for(let e=1;e{setTimeout(e,n)}))),i.push(this.up({...r,clickCount:a})),await Promise.all(i)}async wheel(e={}){const{deltaX:t=0,deltaY:r=0}=e,{position:n,buttons:s}=this.#At;await this.#mt.send("Input.dispatchMouseEvent",{type:"mouseWheel",pointerType:"mouse",modifiers:this.#js._modifiers,deltaY:r,deltaX:t,buttons:s,...n})}async drag(e,t){const r=new Promise((e=>{this.#mt.once("Input.dragIntercepted",(t=>e(t.data)))}));return await this.move(e.x,e.y),await this.down(),await this.move(t.x,t.y),await r}async dragEnter(e,t){await this.#mt.send("Input.dispatchDragEvent",{type:"dragEnter",x:e.x,y:e.y,modifiers:this.#js._modifiers,data:t})}async dragOver(e,t){await this.#mt.send("Input.dispatchDragEvent",{type:"dragOver",x:e.x,y:e.y,modifiers:this.#js._modifiers,data:t})}async drop(e,t){await this.#mt.send("Input.dispatchDragEvent",{type:"drop",x:e.x,y:e.y,modifiers:this.#js._modifiers,data:t})}async dragAndDrop(e,t,r={}){const{delay:n=null}=r,s=await this.drag(e,t);await this.dragEnter(t,s),await this.dragOver(t,s),n&&await new Promise((e=>setTimeout(e,n))),await this.drop(t,s),await this.up()}}class Cp{#Ds=!1;#zs;#Us;#mt;#js;constructor(e,t,r,n){this.#mt=e,this.#zs=t,this.#js=r,this.#Us=n}updateClient(e){this.#mt=e}async start(){if(this.#Ds)throw new Wl("Touch has already started");await this.#mt.send("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[this.#Us],modifiers:this.#js._modifiers}),this.#Ds=!0}move(e,t){return this.#Us.x=Math.round(e),this.#Us.y=Math.round(t),this.#mt.send("Input.dispatchTouchEvent",{type:"touchMove",touchPoints:[this.#Us],modifiers:this.#js._modifiers})}async end(){await this.#mt.send("Input.dispatchTouchEvent",{type:"touchEnd",touchPoints:[this.#Us],modifiers:this.#js._modifiers}),this.#zs.removeHandle(this)}}class Pp extends Jd{#mt;#js;constructor(e,t){super(),this.#mt=e,this.#js=t}updateClient(e){this.#mt=e,this.touches.forEach((t=>{t.updateClient(e)}))}async touchStart(e,t){const r=this.idGenerator(),n={x:Math.round(e),y:Math.round(t),radiusX:.5,radiusY:.5,force:.5,id:r},s=new Cp(this.#mt,this,this.#js,n);return await s.start(),this.touches.push(s),s}}class Op{#mt;#Bs=!1;#qs;constructor(e){this.#mt=e}updateClient(e){this.#mt=e}async start(e={}){$l(!this.#Bs,"Cannot start recording trace while already recording trace.");const t=["-*","devtools.timeline","v8.execute","disabled-by-default-devtools.timeline","disabled-by-default-devtools.timeline.frame","toplevel","blink.console","blink.user_timing","latencyInfo","disabled-by-default-devtools.timeline.stack","disabled-by-default-v8.cpu_profiler"],{path:r,screenshots:n=!1,categories:s=t}=e;n&&s.push("disabled-by-default-devtools.screenshot");const a=s.filter((e=>e.startsWith("-"))).map((e=>e.slice(1))),i=s.filter((e=>!e.startsWith("-")));this.#qs=r,this.#Bs=!0,await this.#mt.send("Tracing.start",{transferMode:"ReturnAsStream",traceConfig:{excludedCategories:a,includedCategories:i}})}async stop(){const e=gu.create();return this.#mt.once("Tracing.tracingComplete",(async t=>{try{$l(t.stream,'Missing "stream"');const r=await su(this.#mt,t.stream),n=await nu(r,this.#qs);e.resolve(n??void 0)}catch(t){ku(t)?e.reject(t):e.reject(new Error(`Unknown error: ${t}`))}})),await this.#mt.send("Tracing.end"),this.#Bs=!1,await e.valueOrThrow()}}class Ap extends lh{#pe;#mt;#Je;#et;constructor(e,t,r,n,s,a,i){super(t),this.#Je=r,this.#mt=e,this.#et=n,this.#pe=new ip(this,new Zd),this.#mt.once("Runtime.executionContextCreated",(async t=>{this.#pe.setContext(new np(e,t.context,this.#pe))})),this.#pe.emitter.on("consoleapicalled",(async e=>{try{return s(e.type,e.args.map((e=>new Vh(this.#pe,e))),e.stackTrace)}catch(e){Zl(e)}})),this.#mt.on("Runtime.exceptionThrown",a),this.#mt.once(wu.Disconnected,(()=>{this.#pe.dispose()})),i?.addClient(this.#mt).catch(Zl),this.#mt.send("Runtime.enable").catch(Zl)}mainRealm(){return this.#pe}get client(){return this.#mt}async close(){switch(this.#et){case oh.SERVICE_WORKER:case oh.SHARED_WORKER:await(this.client.connection()?.send("Target.closeTarget",{targetId:this.#Je})),await(this.client.connection()?.send("Target.detachFromTarget",{sessionId:this.client.id()}));break;default:await this.evaluate((()=>{self.close()}))}}}var Ip=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Mp=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,s=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===s)return s=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return s|=2,Promise.resolve(a).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Rp(e){return"warning"===e?"warn":e}class jp extends th{static async _create(e,t,r){const n=new jp(e,t);if(await n.#Ks(),r)try{await n.setViewport(r)}catch(e){if(!ku(e)||!Th(e))throw e;Zl(e)}return n}#lt=!1;#Ws;#Hs;#Vs;#Gs;#Js;#js;#Zs;#Ys;#pr;#Xs;#Qs;#yr=new Map;#ea=new Map;#ta;#ra;#na=new Map;#sa=new Set;#aa=gu.create();#ia=!1;#oa=!1;constructor(e,t){super(),this.#Hs=e,this.#Gs=e.parentSession(),$l(this.#Gs,"Tab target session is not defined."),this.#Js=this.#Gs.target(),$l(this.#Js,"Tab target is not defined."),this.#Vs=t,this.#Ws=t._targetManager(),this.#js=new Sp(e),this.#Zs=new Tp(e,this.#js),this.#Ys=new Pp(e,this.#js),this.#pr=new _p(e,this,this._timeoutSettings),this.#Xs=new Lh(e),this.#Qs=new Op(e),this.#ta=new Ch(e),this.#ra=null;const r=new Ml(this.#pr);r.on(ap.FrameAttached,(e=>{this.emit("frameattached",e)})),r.on(ap.FrameDetached,(e=>{this.emit("framedetached",e)})),r.on(ap.FrameNavigated,(e=>{this.emit("framenavigated",e)})),r.on(ap.ConsoleApiCalled,(([e,t])=>{this.#gr(e,t)})),r.on(ap.BindingCalled,(([e,t])=>{this.#fr(e,t)}));const n=new Ml(this.#pr.networkManager);n.on(mh.Request,(e=>{this.emit("request",e)})),n.on(mh.RequestServedFromCache,(e=>{this.emit("requestservedfromcache",e)})),n.on(mh.Response,(e=>{this.emit("response",e)})),n.on(mh.RequestFailed,(e=>{this.emit("requestfailed",e)})),n.on(mh.RequestFinished,(e=>{this.emit("requestfinished",e)})),this.#Gs.on(wu.Swapped,this.#ca.bind(this)),this.#Gs.on(wu.Ready,this.#la.bind(this)),this.#Ws.on("targetGone",this.#ua),this.#Js._isClosedDeferred.valueOrThrow().then((()=>{this.#Ws.off("targetGone",this.#ua),this.emit("close",void 0),this.#lt=!0})).catch(Zl),this.#da(),this.#ha()}#ha(){const e=[];for(const t of this.#Ws.getChildTargets(this.#Vs))e.push(t);let t=0;for(;t{this.#aa.reject(new Gl("Target closed"))})),e.on("Page.domContentEventFired",(()=>{this.emit("domcontentloaded",void 0)})),e.on("Page.loadEventFired",(()=>{this.emit("load",void 0)})),e.on("Page.javascriptDialogOpening",this.#ma.bind(this)),e.on("Runtime.exceptionThrown",this.#fa.bind(this)),e.on("Inspector.targetCrashed",this.#ga.bind(this)),e.on("Performance.metrics",this.#ya.bind(this)),e.on("Log.entryAdded",this.#ba.bind(this)),e.on("Page.fileChooserOpened",this.#wa.bind(this))}#ua=e=>{const t=e._session()?.id(),r=this.#na.get(t);r&&(this.#na.delete(t),this.emit("workerdestroyed",r))};#pa=e=>{if($l(e instanceof kh),this.#pr.onAttachedToTarget(e.target()),"worker"===e.target()._getTargetInfo().type){const t=new Ap(e,e.target().url(),e.target()._targetId,e.target().type(),this.#va.bind(this),this.#fa.bind(this),this.#pr.networkManager);this.#na.set(e.id(),t),this.emit("workercreated",t)}e.on(wu.Ready,this.#pa)};async#Ks(){try{await Promise.all([this.#pr.initialize(this.#Hs),this.#Hs.send("Performance.enable"),this.#Hs.send("Log.enable")])}catch(e){if(!ku(e)||!Th(e))throw e;Zl(e)}}async#wa(e){const t={stack:[],error:void 0,hasError:!1};try{if(!this.#sa.size)return;const r=this.#pr.frame(e.frameId);$l(r,"This should never happen.");const n=Ip(t,await r.worlds[op].adoptBackendNode(e.backendNodeId),!1),s=new wh(n.move(),"selectSingle"!==e.mode);for(const e of this.#sa)e.resolve(s);this.#sa.clear()}catch(e){t.error=e,t.hasError=!0}finally{Mp(t)}}_client(){return this.#Hs}isServiceWorkerBypassed(){return this.#ia}isDragInterceptionEnabled(){return this.#oa}isJavaScriptEnabled(){return this.#Xs.javascriptEnabled}async waitForFileChooser(e={}){const t=0===this.#sa.size,{timeout:r=this._timeoutSettings.timeout()}=e,n=gu.create({message:`Waiting for \`FileChooser\` failed: ${r}ms exceeded`,timeout:r});let s;e.signal&&e.signal.addEventListener("abort",(()=>{n.reject(e.signal?.reason)}),{once:!0}),this.#sa.add(n),t&&(s=this.#Hs.send("Page.setInterceptFileChooserDialog",{enabled:!0}));try{const[e]=await Promise.all([n.valueOrThrow(),s]);return e}catch(e){throw this.#sa.delete(n),e}}async setGeolocation(e){return await this.#Xs.setGeolocation(e)}target(){return this.#Vs}browser(){return this.#Vs.browser()}browserContext(){return this.#Vs.browserContext()}#ga(){this.emit("error",new Error("Page crashed!"))}#ba(e){const{level:t,text:r,args:n,source:s,url:a,lineNumber:i}=e.entry;n&&n.map((e=>{Gh(this.#Hs,e)})),"worker"!==s&&this.emit("console",new bh(Rp(t),r,[],[{url:a,lineNumber:i}]))}mainFrame(){return this.#pr.mainFrame()}get keyboard(){return this.#js}get touchscreen(){return this.#Ys}get coverage(){return this.#ta}get tracing(){return this.#Qs}frames(){return this.#pr.frames()}workers(){return Array.from(this.#na.values())}async setRequestInterception(e){return await this.#pr.networkManager.setRequestInterception(e)}async setBypassServiceWorker(e){return this.#ia=e,await this.#Hs.send("Network.setBypassServiceWorker",{bypass:e})}async setDragInterception(e){return this.#oa=e,await this.#Hs.send("Input.setInterceptDrags",{enabled:e})}async setOfflineMode(e){return await this.#pr.networkManager.setOfflineMode(e)}async emulateNetworkConditions(e){return await this.#pr.networkManager.emulateNetworkConditions(e)}setDefaultNavigationTimeout(e){this._timeoutSettings.setDefaultNavigationTimeout(e)}setDefaultTimeout(e){this._timeoutSettings.setDefaultTimeout(e)}getDefaultTimeout(){return this._timeoutSettings.timeout()}getDefaultNavigationTimeout(){return this._timeoutSettings.navigationTimeout()}async queryObjects(e){$l(!e.disposed,"Prototype JSHandle is disposed!"),$l(e.id,"Prototype JSHandle must not be referencing primitive value");const t=await this.mainFrame().client.send("Runtime.queryObjects",{prototypeObjectId:e.id});return this.mainFrame().mainRealm().createCdpHandle(t.objects)}async cookies(...e){const t=(await this.#Hs.send("Network.getCookies",{urls:e.length?e:[this.url()]})).cookies,r=["sourcePort"];return t.map((e=>{for(const t of r)delete e[t];return e})).map((e=>({...e,partitionKey:e.partitionKey?e.partitionKey.topLevelSite:void 0})))}async deleteCookie(...e){const t=this.url();for(const r of e){const e={...r,partitionKey:$p(r.partitionKey)};if(!r.url&&t.startsWith("http")&&(e.url=t),await this.#Hs.send("Network.deleteCookies",e),t.startsWith("http")&&!e.partitionKey){const r=new URL(t);await this.#Hs.send("Network.deleteCookies",{...e,partitionKey:{topLevelSite:r.origin.replace(`:${r.port}`,""),hasCrossSiteAncestor:!1}})}}}async setCookie(...e){const t=this.url(),r=t.startsWith("http"),n=e.map((e=>{const n=Object.assign({},e);return!n.url&&r&&(n.url=t),$l("about:blank"!==n.url,`Blank page can not have cookie "${n.name}"`),$l(!String.prototype.startsWith.call(n.url||"","data:"),`Data URL page can not have cookie "${n.name}"`),n}));await this.deleteCookie(...n),n.length&&await this.#Hs.send("Network.setCookies",{cookies:n.map((e=>({...e,partitionKey:$p(e.partitionKey)})))})}async exposeFunction(e,t){if(this.#yr.has(e))throw new Error(`Failed to add page binding with name ${e}: window['${e}'] already exists!`);const r=function(e,t){return ru(Wh,e,t,Hh)}("exposedFun",e);let n;if("function"==typeof t)n=new yh(e,t,r);else n=new yh(e,t.default,r);this.#yr.set(e,n);const[{identifier:s}]=await Promise.all([this.#pr.evaluateOnNewDocument(r),this.#pr.addExposedFunctionBinding(n)]);this.#ea.set(e,s)}async removeExposedFunction(e){const t=this.#ea.get(e);if(!t)throw new Error(`Function with name "${e}" does not exist`);const r=this.#yr.get(e);this.#ea.delete(e),this.#yr.delete(e),await Promise.all([this.#pr.removeScriptToEvaluateOnNewDocument(t),this.#pr.removeExposedFunctionBinding(r)])}async authenticate(e){return await this.#pr.networkManager.authenticate(e)}async setExtraHTTPHeaders(e){return await this.#pr.networkManager.setExtraHTTPHeaders(e)}async setUserAgent(e,t){return await this.#pr.networkManager.setUserAgent(e,t)}async metrics(){const e=await this.#Hs.send("Performance.getMetrics");return this.#_a(e.metrics)}#ya(e){this.emit("metrics",{title:e.title,metrics:this.#_a(e.metrics)})}#_a(e){const t={};for(const r of e||[])Np.has(r.name)&&(t[r.name]=r.value);return t}#fa(e){this.emit("pageerror",function(e){let t,r;if(e.exception){if(!("object"===e.exception.type&&"error"===e.exception.subtype||e.exception.objectId))return Kh(e.exception);{const n=qh(e);t=n.name,r=n.message}}else t="Error",r=e.text;const n=new Error(r);n.name=t;const s=n.message.split("\n").length,a=n.stack.split("\n").splice(0,s),i=[];if(e.stackTrace)for(const t of e.stackTrace.callFrames)if(i.push(` at ${t.functionName||""} (${t.url}:${t.lineNumber+1}:${t.columnNumber+1})`),i.length>=Error.stackTraceLimit)break;return n.stack=[...a,...i].join("\n"),n}(e.exceptionDetails))}#gr(e,t){const r=t.args.map((t=>e.createCdpHandle(t)));this.#va(Rp(t.type),r,t.stackTrace)}async#fr(e,t){let r;try{r=JSON.parse(t.payload)}catch{return}const{type:n,name:s,seq:a,args:i,isTrivial:o}=r;if("exposedFun"!==n)return;const c=e.context;if(!c)return;const l=this.#yr.get(s);await(l?.run(c,a,i,o))}#va(e,t,r){if(!this.listenerCount("console"))return void t.forEach((e=>e.dispose()));const n=[];for(const e of t){const t=e.remoteObject();t.objectId?n.push(e.toString()):n.push(Kh(t))}const s=[];if(r)for(const e of r.callFrames)s.push({url:e.url,lineNumber:e.lineNumber,columnNumber:e.columnNumber});const a=new bh(Rp(e),n.join(" "),t,s);this.emit("console",a)}#ma(e){const t=function(e){let t=null;return new Set(["alert","confirm","prompt","beforeunload"]).has(e)&&(t=e),$l(t,`Unknown javascript dialog type: ${e}`),t}(e.type),r=new Mh(this.#Hs,t,e.message,e.defaultPrompt);this.emit("dialog",r)}async reload(e){const[t]=await Promise.all([this.waitForNavigation({...e,ignoreSameDocumentNavigation:!0}),this.#Hs.send("Page.reload")]);return t}async createCDPSession(){return await this.target().createCDPSession()}async goBack(e={}){return await this.#ka(-1,e)}async goForward(e={}){return await this.#ka(1,e)}async#ka(e,t){const r=await this.#Hs.send("Page.getNavigationHistory"),n=r.entries[r.currentIndex+e];if(!n)return null;return(await Promise.all([this.waitForNavigation(t),this.#Hs.send("Page.navigateToHistoryEntry",{entryId:n.id})]))[0]}async bringToFront(){await this.#Hs.send("Page.bringToFront")}async setJavaScriptEnabled(e){return await this.#Xs.setJavaScriptEnabled(e)}async setBypassCSP(e){await this.#Hs.send("Page.setBypassCSP",{enabled:e})}async emulateMediaType(e){return await this.#Xs.emulateMediaType(e)}async emulateCPUThrottling(e){return await this.#Xs.emulateCPUThrottling(e)}async emulateMediaFeatures(e){return await this.#Xs.emulateMediaFeatures(e)}async emulateTimezone(e){return await this.#Xs.emulateTimezone(e)}async emulateIdleState(e){return await this.#Xs.emulateIdleState(e)}async emulateVisionDeficiency(e){return await this.#Xs.emulateVisionDeficiency(e)}async setViewport(e){const t=await this.#Xs.emulateViewport(e);this.#ra=e,t&&await this.reload()}viewport(){return this.#ra}async evaluateOnNewDocument(e,...t){const r=ru(e,...t);return await this.#pr.evaluateOnNewDocument(r)}async removeScriptToEvaluateOnNewDocument(e){return await this.#pr.removeScriptToEvaluateOnNewDocument(e)}async setCacheEnabled(e=!0){await this.#pr.networkManager.setCacheEnabled(e)}async _screenshot(e){const t={stack:[],error:void 0,hasError:!1};try{const{fromSurface:r,omitBackground:n,optimizeForSpeed:s,quality:a,clip:i,type:o,captureBeyondViewport:c}=e,l=Ip(t,new Al,!0);!n||"png"!==o&&"webp"!==o||(await this.#Xs.setTransparentBackgroundColor(),l.defer((async()=>{await this.#Xs.resetDefaultBackgroundColor().catch(Zl)})));let u=i;if(u&&!c){u=function(e,t){const r=Math.max(e.x,t.x),n=Math.max(e.y,t.y);return{x:r,y:n,width:Math.max(Math.min(e.x+e.width,t.x+t.width)-r,0),height:Math.max(Math.min(e.y+e.height,t.y+t.height)-n,0)}}(u,await this.mainFrame().isolatedRealm().evaluate((()=>{const{height:e,pageLeft:t,pageTop:r,width:n}=window.visualViewport;return{x:t,y:r,height:e,width:n}})))}const{data:d}=await this.#Hs.send("Page.captureScreenshot",{format:o,optimizeForSpeed:s,fromSurface:r,...void 0!==a?{quality:Math.round(a)}:{},...u?{clip:{...u,scale:u.scale??1}}:{},captureBeyondViewport:c});return d}catch(e){t.error=e,t.hasError=!0}finally{const e=Mp(t);e&&await e}}async createPDFStream(e={}){const{timeout:t=this._timeoutSettings.timeout()}=e,{landscape:r,displayHeaderFooter:n,headerTemplate:s,footerTemplate:a,printBackground:i,scale:o,width:c,height:l,margin:u,pageRanges:d,preferCSSPageSize:h,omitBackground:p,tagged:m,outline:f,waitForFonts:g}=function(e={},t="in"){let r=8.5,n=11;if(e.format){const s=Jl[e.format.toLowerCase()][t];$l(s,"Unknown paper format: "+e.format),r=s.width,n=s.height}else r=uu(e.width,t)??r,n=uu(e.height,t)??n;const s={top:uu(e.margin?.top,t)||0,left:uu(e.margin?.left,t)||0,bottom:uu(e.margin?.bottom,t)||0,right:uu(e.margin?.right,t)||0};return e.outline&&(e.tagged=!0),{scale:1,displayHeaderFooter:!1,headerTemplate:"",footerTemplate:"",printBackground:!1,landscape:!1,pageRanges:"",preferCSSPageSize:!1,omitBackground:!1,outline:!1,tagged:!0,waitForFonts:!0,...e,width:r,height:n,margin:s}}(e);p&&await this.#Xs.setTransparentBackgroundColor(),g&&await Zc(Vc(this.mainFrame().isolatedRealm().evaluate((()=>document.fonts.ready))).pipe(El(au(t))));const y=this.#Hs.send("Page.printToPDF",{transferMode:"ReturnAsStream",landscape:r,displayHeaderFooter:n,headerTemplate:s,footerTemplate:a,printBackground:i,scale:o,paperWidth:c,paperHeight:l,marginTop:u.top,marginBottom:u.bottom,marginLeft:u.left,marginRight:u.right,pageRanges:d,preferCSSPageSize:h,generateTaggedPDF:m,generateDocumentOutline:f}),b=await Zc(Vc(y).pipe(El(au(t))));return p&&await this.#Xs.resetDefaultBackgroundColor(),$l(b.stream,"`stream` is missing from `Page.printToPDF"),await su(this.#Hs,b.stream)}async pdf(e={}){const{path:t}=e,r=await this.createPDFStream(e),n=await nu(r,t);return $l(n,"Could not create typed array"),n}async close(e={runBeforeUnload:void 0}){const t={stack:[],error:void 0,hasError:!1};try{Ip(t,await this.browserContext().waitForScreenshotOperations(),!1);const r=this.#Hs.connection();$l(r,"Protocol error: Connection closed. Most likely the page has been closed.");!!e.runBeforeUnload?await this.#Hs.send("Page.close"):(await r.send("Target.closeTarget",{targetId:this.#Vs._targetId}),await this.#Js._isClosedDeferred.valueOrThrow())}catch(e){t.error=e,t.hasError=!0}finally{Mp(t)}}isClosed(){return this.#lt}get mouse(){return this.#Zs}async waitForDevicePrompt(e={}){return await this.mainFrame().waitForDevicePrompt(e)}}const Np=new Set(["Timestamp","Documents","Frames","JSEventListeners","Nodes","LayoutCount","RecalcStyleCount","LayoutDuration","RecalcStyleDuration","ScriptDuration","TaskDuration","JSHeapUsedSize","JSHeapTotalSize"]);function $p(e){if(void 0!==e)return"string"==typeof e?{topLevelSite:e,hasCrossSiteAncestor:!1}:{topLevelSite:e.sourceOrigin,hasCrossSiteAncestor:e.hasCrossSiteAncestor??!1}}var Lp,Fp=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Dp=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,s=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===s)return s=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return s|=2,Promise.resolve(a).then(e,(function(t){return r(t),e()}))}else s|=1}catch(e){r(e)}if(1===s)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class zp extends bu{#tt;#Sa;#Je;constructor(e,t,r){super(),this.#tt=e,this.#Sa=t,this.#Je=r}get id(){return this.#Je}targets(){return this.#Sa.targets().filter((e=>e.browserContext()===this))}async pages(){return(await Promise.all(this.targets().filter((e=>"page"===e.type()||"other"===e.type()&&this.#Sa._getIsPageTargetCallback()?.(e))).map((e=>e.page())))).filter((e=>!!e))}async overridePermissions(e,t){const r=t.map((e=>{const t=mu.get(e);if(!t)throw new Error("Unknown permission: "+e);return t}));await this.#tt.send("Browser.grantPermissions",{origin:e,browserContextId:this.#Je||void 0,permissions:r})}async clearPermissionOverrides(){await this.#tt.send("Browser.resetPermissions",{browserContextId:this.#Je||void 0})}async newPage(){const e={stack:[],error:void 0,hasError:!1};try{Fp(e,await this.waitForScreenshotOperations(),!1);return await this.#Sa._createPageInContext(this.#Je)}catch(t){e.error=t,e.hasError=!0}finally{Dp(e)}}browser(){return this.#Sa}async close(){$l(this.#Je,"Default BrowserContext cannot be closed!"),await this.#Sa._disposeContext(this.#Je)}async cookies(){const{cookies:e}=await this.#tt.send("Storage.getCookies",{browserContextId:this.#Je});return e.map((e=>({...e,partitionKey:e.partitionKey?{sourceOrigin:e.partitionKey.topLevelSite,hasCrossSiteAncestor:e.partitionKey.hasCrossSiteAncestor}:void 0})))}async setCookie(...e){return await this.#tt.send("Storage.setCookies",{browserContextId:this.#Je,cookies:e.map((e=>({...e,partitionKey:$p(e.partitionKey)})))})}async setDownloadBehavior(e){await this.#tt.send("Browser.setDownloadBehavior",{behavior:e.policy,downloadPath:e.downloadPath,browserContextId:this.#Je})}}!function(e){e.SUCCESS="success",e.ABORTED="aborted"}(Lp||(Lp={}));class Up extends ch{#Ea;#xa;#Ta;#Ws;#Ca;#Pa=new Set;_initializedDeferred=gu.create();_isClosedDeferred=gu.create();_targetId;constructor(e,t,r,n,s){super(),this.#xa=t,this.#Ws=n,this.#Ta=e,this.#Ea=r,this._targetId=e.targetId,this.#Ca=s,this.#xa&&this.#xa.setTarget(this)}async asPage(){const e=this._session();return e?await jp._create(e,this,null):await this.createCDPSession().then((e=>jp._create(e,this,null)))}_subtype(){return this.#Ta.subtype}_session(){return this.#xa}_addChildTarget(e){this.#Pa.add(e)}_removeChildTarget(e){this.#Pa.delete(e)}_childTargets(){return this.#Pa}_sessionFactory(){if(!this.#Ca)throw new Error("sessionFactory is not initialized");return this.#Ca}createCDPSession(){if(!this.#Ca)throw new Error("sessionFactory is not initialized");return this.#Ca(!1).then((e=>(e.setTarget(this),e)))}url(){return this.#Ta.url}type(){switch(this.#Ta.type){case"page":return oh.PAGE;case"background_page":return oh.BACKGROUND_PAGE;case"service_worker":return oh.SERVICE_WORKER;case"shared_worker":return oh.SHARED_WORKER;case"browser":return oh.BROWSER;case"webview":return oh.WEBVIEW;case"tab":return oh.TAB;default:return oh.OTHER}}_targetManager(){if(!this.#Ws)throw new Error("targetManager is not initialized");return this.#Ws}_getTargetInfo(){return this.#Ta}browser(){if(!this.#Ea)throw new Error("browserContext is not initialized");return this.#Ea.browser()}browserContext(){if(!this.#Ea)throw new Error("browserContext is not initialized");return this.#Ea}opener(){const{openerId:e}=this.#Ta;if(e)return this.browser().targets().find((t=>t._targetId===e))}_targetInfoChanged(e){this.#Ta=e,this._checkIfInitialized()}_initialize(){this._initializedDeferred.resolve(Lp.SUCCESS)}_isTargetExposed(){return this.type()!==oh.TAB&&!this._subtype()}_checkIfInitialized(){this._initializedDeferred.resolved()||this._initializedDeferred.resolve(Lp.SUCCESS)}}class Bp extends Up{#Oa;pagePromise;constructor(e,t,r,n,s,a){super(e,t,r,n,s),this.#Oa=a??void 0}_initialize(){this._initializedDeferred.valueOrThrow().then((async e=>{if(e===Lp.ABORTED)return;const t=this.opener();if(!(t instanceof Bp))return;if(!t||!t.pagePromise||"page"!==this.type())return!0;const r=await t.pagePromise;if(!r.listenerCount("popup"))return!0;const n=await this.page();return r.emit("popup",n),!0})).catch(Zl),this._checkIfInitialized()}async page(){if(!this.pagePromise){const e=this._session();this.pagePromise=(e?Promise.resolve(e):this._sessionFactory()(!1)).then((e=>jp._create(e,this,this.#Oa??null)))}return await this.pagePromise??null}_checkIfInitialized(){this._initializedDeferred.resolved()||""!==this._getTargetInfo().url&&this._initializedDeferred.resolve(Lp.SUCCESS)}}class qp extends Bp{}class Kp extends Up{#Aa;async worker(){if(!this.#Aa){const e=this._session();this.#Aa=(e?Promise.resolve(e):this._sessionFactory()(!1)).then((e=>new Ap(e,this._getTargetInfo().url,this._targetId,this.type(),(()=>{}),(()=>{}),void 0)))}return await this.#Aa}}class Wp extends Up{}class Hp extends Ml{#tt;#Ia=new Map;#Ma=new Map;#Ra=new Map;#ja=new Set;#Na;#$a;#La=new WeakMap;#Fa=new WeakMap;#Da=gu.create();#za=new Set;#Ua=!0;#Ba=[{}];constructor(e,t,r,n=!0){super(),this.#tt=e,this.#Na=r,this.#$a=t,this.#Ua=n,this.#tt.on("Target.targetCreated",this.#qa),this.#tt.on("Target.targetDestroyed",this.#Ka),this.#tt.on("Target.targetInfoChanged",this.#Wa),this.#tt.on(wu.SessionDetached,this.#Ha),this.#Va(this.#tt)}#Ga=()=>{if(this.#Ua)for(const[e,t]of this.#Ia.entries()){const r=new Up(t,void 0,void 0,this,void 0),n="page"===t.type||"iframe"===t.type,s=t.url.startsWith("chrome-extension://");this.#Na&&!this.#Na(r)||!n||s||this.#za.add(e)}};async initialize(){await this.#tt.send("Target.setDiscoverTargets",{discover:!0,filter:this.#Ba}),this.#Ga(),await this.#tt.send("Target.setAutoAttach",{waitForDebuggerOnStart:!0,flatten:!0,autoAttach:!0,filter:[{type:"page",exclude:!0},...this.#Ba]}),this.#Ja(),await this.#Da.valueOrThrow()}getChildTargets(e){return e._childTargets()}dispose(){this.#tt.off("Target.targetCreated",this.#qa),this.#tt.off("Target.targetDestroyed",this.#Ka),this.#tt.off("Target.targetInfoChanged",this.#Wa),this.#tt.off(wu.SessionDetached,this.#Ha),this.#Za(this.#tt)}getAvailableTargets(){return this.#Ma}#Va(e){const t=t=>{this.#pa(e,t)};$l(!this.#La.has(e)),this.#La.set(e,t),e.on("Target.attachedToTarget",t);const r=t=>this.#ua(e,t);$l(!this.#Fa.has(e)),this.#Fa.set(e,r),e.on("Target.detachedFromTarget",r)}#Za(e){const t=this.#La.get(e);t&&(e.off("Target.attachedToTarget",t),this.#La.delete(e)),this.#Fa.has(e)&&(e.off("Target.detachedFromTarget",this.#Fa.get(e)),this.#Fa.delete(e))}#Ha=e=>{this.#Za(e)};#qa=async e=>{if(this.#Ia.set(e.targetInfo.targetId,e.targetInfo),this.emit("targetDiscovered",e.targetInfo),"browser"===e.targetInfo.type&&e.targetInfo.attached){if(this.#Ma.has(e.targetInfo.targetId))return;const t=this.#$a(e.targetInfo,void 0);t._initialize(),this.#Ma.set(e.targetInfo.targetId,t)}};#Ka=e=>{const t=this.#Ia.get(e.targetId);if(this.#Ia.delete(e.targetId),this.#Ja(e.targetId),"service_worker"===t?.type&&this.#Ma.has(e.targetId)){const t=this.#Ma.get(e.targetId);t&&(this.emit("targetGone",t),this.#Ma.delete(e.targetId))}};#Wa=e=>{if(this.#Ia.set(e.targetInfo.targetId,e.targetInfo),this.#ja.has(e.targetInfo.targetId)||!this.#Ma.has(e.targetInfo.targetId)||!e.targetInfo.attached)return;const t=this.#Ma.get(e.targetInfo.targetId);if(!t)return;const r=t.url(),n=t._initializedDeferred.value()===Lp.SUCCESS;if(function(e,t){return Boolean(e._subtype())&&!t.subtype}(t,e.targetInfo)){const e=t?._session();$l(e,"Target that is being activated is missing a CDPSession."),e.parentSession()?.emit(wu.Swapped,e)}t._targetInfoChanged(e.targetInfo),n&&r!==t.url()&&this.emit("targetChanged",{target:t,wasInitialized:n,previousURL:r})};#pa=async(e,t)=>{const r=t.targetInfo,n=this.#tt._session(t.sessionId);if(!n)throw new Error(`Session ${t.sessionId} was not created.`);const s=async()=>{await n.send("Runtime.runIfWaitingForDebugger").catch(Zl),await e.send("Target.detachFromTarget",{sessionId:n.id()}).catch(Zl)};if(!this.#tt.isAutoAttached(r.targetId))return;if("service_worker"===r.type){if(this.#Ja(r.targetId),await s(),this.#Ma.has(r.targetId))return;const e=this.#$a(r);return e._initialize(),this.#Ma.set(r.targetId,e),void this.emit("targetAvailable",e)}const a=this.#Ma.has(r.targetId),i=a?this.#Ma.get(r.targetId):this.#$a(r,n,e instanceof kh?e:void 0);if(this.#Na&&!this.#Na(i))return this.#ja.add(r.targetId),this.#Ja(r.targetId),void await s();this.#Va(n),a?(n.setTarget(i),this.#Ra.set(n.id(),this.#Ma.get(r.targetId))):(i._initialize(),this.#Ma.set(r.targetId,i),this.#Ra.set(n.id(),i));const o=e instanceof vu?e.target():null;o?._addChildTarget(i),e.emit(wu.Ready,n),this.#za.delete(i._targetId),a||this.emit("targetAvailable",i),this.#Ja(),await Promise.all([n.send("Target.setAutoAttach",{waitForDebuggerOnStart:!0,flatten:!0,autoAttach:!0,filter:this.#Ba}),n.send("Runtime.runIfWaitingForDebugger")]).catch(Zl)};#Ja(e){void 0!==e&&this.#za.delete(e),0===this.#za.size&&this.#Da.resolve()}#ua=(e,t)=>{const r=this.#Ra.get(t.sessionId);this.#Ra.delete(t.sessionId),r&&(e instanceof vu&&e.target()._removeChildTarget(r),this.#Ma.delete(r._targetId),this.emit("targetGone",r))}}class Vp extends fu{protocol="cdp";static async _create(e,t,r,n,s,a,i,o,c,l=!0){const u=new Vp(e,t,n,a,i,o,c,l);return r&&await e.send("Security.setIgnoreCertificateErrors",{ignore:!0}),await u._attach(s),u}#Oa;#Ya;#tt;#Xa;#Na;#Qa;#ei;#ti=new Map;#Ws;constructor(e,t,r,n,s,a,i,o=!0){super(),this.#Oa=r,this.#Ya=n,this.#tt=e,this.#Xa=s||(()=>{}),this.#Na=a||(()=>!0),this.#ri(i),this.#Ws=new Hp(e,this.#ni,this.#Na,o),this.#ei=new zp(this.#tt,this);for(const e of t)this.#ti.set(e,new zp(this.#tt,this,e))}#si=()=>{this.emit("disconnected",void 0)};async _attach(e){this.#tt.on(wu.Disconnected,this.#si),e&&await this.#ei.setDownloadBehavior(e),this.#Ws.on("targetAvailable",this.#pa),this.#Ws.on("targetGone",this.#ua),this.#Ws.on("targetChanged",this.#ai),this.#Ws.on("targetDiscovered",this.#ii),await this.#Ws.initialize()}_detach(){this.#tt.off(wu.Disconnected,this.#si),this.#Ws.off("targetAvailable",this.#pa),this.#Ws.off("targetGone",this.#ua),this.#Ws.off("targetChanged",this.#ai),this.#Ws.off("targetDiscovered",this.#ii)}process(){return this.#Ya??null}_targetManager(){return this.#Ws}#ri(e){this.#Qa=e||(e=>"page"===e.type()||"background_page"===e.type()||"webview"===e.type())}_getIsPageTargetCallback(){return this.#Qa}async createBrowserContext(e={}){const{proxyServer:t,proxyBypassList:r,downloadBehavior:n}=e,{browserContextId:s}=await this.#tt.send("Target.createBrowserContext",{proxyServer:t,proxyBypassList:r&&r.join(",")}),a=new zp(this.#tt,this,s);return n&&await a.setDownloadBehavior(n),this.#ti.set(s,a),a}browserContexts(){return[this.#ei,...Array.from(this.#ti.values())]}defaultBrowserContext(){return this.#ei}async _disposeContext(e){e&&(await this.#tt.send("Target.disposeBrowserContext",{browserContextId:e}),this.#ti.delete(e))}#ni=(e,t)=>{const{browserContextId:r}=e,n=r&&this.#ti.has(r)?this.#ti.get(r):this.#ei;if(!n)throw new Error("Missing browser context");const s=t=>this.#tt._createSession(e,t),a=new Wp(e,t,n,this.#Ws,s);return e.url?.startsWith("devtools://")?new qp(e,t,n,this.#Ws,s,this.#Oa??null):this.#Qa(a)?new Bp(e,t,n,this.#Ws,s,this.#Oa??null):"service_worker"===e.type||"shared_worker"===e.type?new Kp(e,t,n,this.#Ws,s):a};#pa=async e=>{e._isTargetExposed()&&await e._initializedDeferred.valueOrThrow()===Lp.SUCCESS&&(this.emit("targetcreated",e),e.browserContext().emit("targetcreated",e))};#ua=async e=>{e._initializedDeferred.resolve(Lp.ABORTED),e._isClosedDeferred.resolve(),e._isTargetExposed()&&await e._initializedDeferred.valueOrThrow()===Lp.SUCCESS&&(this.emit("targetdestroyed",e),e.browserContext().emit("targetdestroyed",e))};#ai=({target:e})=>{this.emit("targetchanged",e),e.browserContext().emit("targetchanged",e)};#ii=e=>{this.emit("targetdiscovered",e)};wsEndpoint(){return this.#tt.url()}async newPage(){return await this.#ei.newPage()}async _createPageInContext(e){const{targetId:t}=await this.#tt.send("Target.createTarget",{url:"about:blank",browserContextId:e||void 0}),r=await this.waitForTarget((e=>e._targetId===t));if(!r)throw new Error(`Missing target for page (id = ${t})`);if(!(await r._initializedDeferred.valueOrThrow()===Lp.SUCCESS))throw new Error(`Failed to create target for page (id = ${t})`);const n=await r.page();if(!n)throw new Error(`Failed to create a page for context (id = ${e})`);return n}async installExtension(e){const{id:t}=await this.#tt.send("Extensions.loadUnpacked",{path:e});return t}uninstallExtension(e){return this.#tt.send("Extensions.uninstall",{id:e})}targets(){return Array.from(this.#Ws.getAvailableTargets().values()).filter((e=>e._isTargetExposed()&&e._initializedDeferred.value()===Lp.SUCCESS))}target(){const e=this.targets().find((e=>"browser"===e.type()));if(!e)throw new Error("Browser target is not found");return e}async version(){return(await this.#oi()).product}async userAgent(){return(await this.#oi()).userAgent}async close(){await this.#Xa.call(null),await this.disconnect()}disconnect(){return this.#Ws.dispose(),this.#tt.dispose(),this._detach(),Promise.resolve()}get connected(){return!this.#tt._closed}#oi(){return this.#tt.send("Browser.getVersion")}get debugInfo(){return{pendingProtocolErrors:this.#tt.getPendingProtocolErrors()}}}const Gp={targetId:"tabTargetId",type:"tab",title:"tab",url:"about:blank",attached:!1,canAccessOpener:!1},Jp={targetId:"pageTargetId",type:"page",title:"page",url:"about:blank",attached:!1,canAccessOpener:!1};class Zp{static async connectTab(e){return await chrome.debugger.attach({tabId:e},"1.3"),new Zp(e)}onmessage;onclose;#ci;constructor(e){this.#ci=e,chrome.debugger.onEvent.addListener(this.#li)}#li=(e,t,r)=>{e.tabId===this.#ci&&this.#ui({sessionId:e.sessionId??"pageTargetSessionId",method:t,params:r})};#ui(e){this.onmessage?.(JSON.stringify(e))}send(e){const t=JSON.parse(e);switch(t.method){case"Browser.getVersion":return void this.#ui({id:t.id,sessionId:t.sessionId,method:t.method,result:{protocolVersion:"1.3",product:"chrome",revision:"unknown",userAgent:"chrome",jsVersion:"unknown"}});case"Target.getBrowserContexts":return void this.#ui({id:t.id,sessionId:t.sessionId,method:t.method,result:{browserContextIds:[]}});case"Target.setDiscoverTargets":return this.#ui({method:"Target.targetCreated",params:{targetInfo:Gp}}),this.#ui({method:"Target.targetCreated",params:{targetInfo:Jp}}),void this.#ui({id:t.id,sessionId:t.sessionId,method:t.method,result:{}});case"Target.setAutoAttach":if("tabTargetSessionId"===t.sessionId)return this.#ui({method:"Target.attachedToTarget",params:{targetInfo:Jp,sessionId:"pageTargetSessionId"}}),void this.#ui({id:t.id,sessionId:t.sessionId,method:t.method,result:{}});if(!t.sessionId)return this.#ui({method:"Target.attachedToTarget",params:{targetInfo:Gp,sessionId:"tabTargetSessionId"}}),void this.#ui({id:t.id,sessionId:t.sessionId,method:t.method,result:{}})}"pageTargetSessionId"===t.sessionId&&delete t.sessionId,chrome.debugger.sendCommand({tabId:this.#ci,sessionId:t.sessionId},t.method,t.params).then((e=>{this.#ui({id:t.id,sessionId:t.sessionId??"pageTargetSessionId",method:t.method,result:e})})).catch((e=>{this.#ui({id:t.id,sessionId:t.sessionId??"pageTargetSessionId",method:t.method,error:{code:e?.code,data:e?.data,message:e?.message??"CDP error had no message"}})}))}close(){chrome.debugger.onEvent.removeListener(this.#li),chrome.debugger.detach({tabId:this.#ci})}}Object.freeze({"Slow 3G":{download:5e4,upload:5e4,latency:2e3},"Fast 3G":{download:18e4,upload:84375,latency:562.5},"Slow 4G":{download:18e4,upload:84375,latency:562.5},"Fast 4G":{download:1012500,upload:168750,latency:165}});const Yp=[{name:"Blackberry PlayBook",userAgent:"Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+",viewport:{width:600,height:1024,deviceScaleFactor:1,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Blackberry PlayBook landscape",userAgent:"Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+",viewport:{width:1024,height:600,deviceScaleFactor:1,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"BlackBerry Z30",userAgent:"Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+",viewport:{width:360,height:640,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"BlackBerry Z30 landscape",userAgent:"Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+",viewport:{width:640,height:360,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Galaxy Note 3",userAgent:"Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",viewport:{width:360,height:640,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Galaxy Note 3 landscape",userAgent:"Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",viewport:{width:640,height:360,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Galaxy Note II",userAgent:"Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",viewport:{width:360,height:640,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Galaxy Note II landscape",userAgent:"Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",viewport:{width:640,height:360,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Galaxy S III",userAgent:"Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",viewport:{width:360,height:640,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Galaxy S III landscape",userAgent:"Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",viewport:{width:640,height:360,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Galaxy S5",userAgent:"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:360,height:640,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Galaxy S5 landscape",userAgent:"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:640,height:360,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Galaxy S8",userAgent:"Mozilla/5.0 (Linux; Android 7.0; SM-G950U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",viewport:{width:360,height:740,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Galaxy S8 landscape",userAgent:"Mozilla/5.0 (Linux; Android 7.0; SM-G950U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",viewport:{width:740,height:360,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Galaxy S9+",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",viewport:{width:320,height:658,deviceScaleFactor:4.5,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Galaxy S9+ landscape",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",viewport:{width:658,height:320,deviceScaleFactor:4.5,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Galaxy Tab S4",userAgent:"Mozilla/5.0 (Linux; Android 8.1.0; SM-T837A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Safari/537.36",viewport:{width:712,height:1138,deviceScaleFactor:2.25,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Galaxy Tab S4 landscape",userAgent:"Mozilla/5.0 (Linux; Android 8.1.0; SM-T837A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Safari/537.36",viewport:{width:1138,height:712,deviceScaleFactor:2.25,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPad",userAgent:"Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",viewport:{width:768,height:1024,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPad landscape",userAgent:"Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",viewport:{width:1024,height:768,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPad (gen 6)",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:768,height:1024,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPad (gen 6) landscape",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:1024,height:768,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPad (gen 7)",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:810,height:1080,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPad (gen 7) landscape",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:1080,height:810,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPad Mini",userAgent:"Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",viewport:{width:768,height:1024,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPad Mini landscape",userAgent:"Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",viewport:{width:1024,height:768,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPad Pro",userAgent:"Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",viewport:{width:1024,height:1366,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPad Pro landscape",userAgent:"Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1",viewport:{width:1366,height:1024,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPad Pro 11",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:834,height:1194,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPad Pro 11 landscape",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:1194,height:834,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 4",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53",viewport:{width:320,height:480,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 4 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53",viewport:{width:480,height:320,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 5",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",viewport:{width:320,height:568,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 5 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",viewport:{width:568,height:320,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 6",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:375,height:667,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 6 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:667,height:375,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 6 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:414,height:736,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 6 Plus landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:736,height:414,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 7",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:375,height:667,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 7 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:667,height:375,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 7 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:414,height:736,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 7 Plus landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:736,height:414,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 8",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:375,height:667,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 8 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:667,height:375,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 8 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:414,height:736,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 8 Plus landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:736,height:414,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone SE",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",viewport:{width:320,height:568,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone SE landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1",viewport:{width:568,height:320,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone X",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:375,height:812,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone X landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",viewport:{width:812,height:375,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone XR",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",viewport:{width:414,height:896,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone XR landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",viewport:{width:896,height:414,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 11",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",viewport:{width:414,height:828,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 11 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",viewport:{width:828,height:414,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 11 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",viewport:{width:375,height:812,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 11 Pro landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",viewport:{width:812,height:375,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 11 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",viewport:{width:414,height:896,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 11 Pro Max landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1",viewport:{width:896,height:414,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 12",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:390,height:844,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 12 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:844,height:390,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 12 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:390,height:844,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 12 Pro landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:844,height:390,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 12 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:428,height:926,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 12 Pro Max landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:926,height:428,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 12 Mini",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:375,height:812,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 12 Mini landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:812,height:375,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 13",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:390,height:844,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 13 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:844,height:390,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 13 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:390,height:844,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 13 Pro landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:844,height:390,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 13 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:428,height:926,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 13 Pro Max landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:926,height:428,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 13 Mini",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:375,height:812,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 13 Mini landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1",viewport:{width:812,height:375,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 14",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",viewport:{width:390,height:663,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 14 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",viewport:{width:750,height:340,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 14 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",viewport:{width:428,height:745,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 14 Plus landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",viewport:{width:832,height:378,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 14 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",viewport:{width:393,height:659,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 14 Pro landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",viewport:{width:734,height:343,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 14 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",viewport:{width:430,height:739,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 14 Pro Max landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",viewport:{width:814,height:380,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 15",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",viewport:{width:393,height:659,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 15 landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",viewport:{width:734,height:343,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 15 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",viewport:{width:430,height:739,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 15 Plus landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",viewport:{width:814,height:380,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 15 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",viewport:{width:393,height:659,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 15 Pro landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",viewport:{width:734,height:343,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"iPhone 15 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",viewport:{width:430,height:739,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"iPhone 15 Pro Max landscape",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",viewport:{width:814,height:380,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"JioPhone 2",userAgent:"Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5",viewport:{width:240,height:320,deviceScaleFactor:1,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"JioPhone 2 landscape",userAgent:"Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5",viewport:{width:320,height:240,deviceScaleFactor:1,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Kindle Fire HDX",userAgent:"Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",viewport:{width:800,height:1280,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Kindle Fire HDX landscape",userAgent:"Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",viewport:{width:1280,height:800,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"LG Optimus L70",userAgent:"Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:384,height:640,deviceScaleFactor:1.25,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"LG Optimus L70 landscape",userAgent:"Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:640,height:384,deviceScaleFactor:1.25,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Microsoft Lumia 550",userAgent:"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263",viewport:{width:640,height:360,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Microsoft Lumia 950",userAgent:"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263",viewport:{width:360,height:640,deviceScaleFactor:4,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Microsoft Lumia 950 landscape",userAgent:"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263",viewport:{width:640,height:360,deviceScaleFactor:4,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nexus 10",userAgent:"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36",viewport:{width:800,height:1280,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nexus 10 landscape",userAgent:"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36",viewport:{width:1280,height:800,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nexus 4",userAgent:"Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:384,height:640,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nexus 4 landscape",userAgent:"Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:640,height:384,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nexus 5",userAgent:"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:360,height:640,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nexus 5 landscape",userAgent:"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:640,height:360,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nexus 5X",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:412,height:732,deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nexus 5X landscape",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:732,height:412,deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nexus 6",userAgent:"Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:412,height:732,deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nexus 6 landscape",userAgent:"Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:732,height:412,deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nexus 6P",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:412,height:732,deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nexus 6P landscape",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:732,height:412,deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nexus 7",userAgent:"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36",viewport:{width:600,height:960,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nexus 7 landscape",userAgent:"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36",viewport:{width:960,height:600,deviceScaleFactor:2,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nokia Lumia 520",userAgent:"Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)",viewport:{width:320,height:533,deviceScaleFactor:1.5,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nokia Lumia 520 landscape",userAgent:"Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)",viewport:{width:533,height:320,deviceScaleFactor:1.5,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Nokia N9",userAgent:"Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13",viewport:{width:480,height:854,deviceScaleFactor:1,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Nokia N9 landscape",userAgent:"Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13",viewport:{width:854,height:480,deviceScaleFactor:1,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Pixel 2",userAgent:"Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:411,height:731,deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Pixel 2 landscape",userAgent:"Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:731,height:411,deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Pixel 2 XL",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:411,height:823,deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Pixel 2 XL landscape",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36",viewport:{width:823,height:411,deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Pixel 3",userAgent:"Mozilla/5.0 (Linux; Android 9; Pixel 3 Build/PQ1A.181105.017.A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.158 Mobile Safari/537.36",viewport:{width:393,height:786,deviceScaleFactor:2.75,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Pixel 3 landscape",userAgent:"Mozilla/5.0 (Linux; Android 9; Pixel 3 Build/PQ1A.181105.017.A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.158 Mobile Safari/537.36",viewport:{width:786,height:393,deviceScaleFactor:2.75,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Pixel 4",userAgent:"Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36",viewport:{width:353,height:745,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Pixel 4 landscape",userAgent:"Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36",viewport:{width:745,height:353,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Pixel 4a (5G)",userAgent:"Mozilla/5.0 (Linux; Android 11; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",viewport:{width:353,height:745,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Pixel 4a (5G) landscape",userAgent:"Mozilla/5.0 (Linux; Android 11; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",viewport:{width:745,height:353,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Pixel 5",userAgent:"Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",viewport:{width:393,height:851,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Pixel 5 landscape",userAgent:"Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",viewport:{width:851,height:393,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}},{name:"Moto G4",userAgent:"Mozilla/5.0 (Linux; Android 7.0; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",viewport:{width:360,height:640,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!1}},{name:"Moto G4 landscape",userAgent:"Mozilla/5.0 (Linux; Android 7.0; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36",viewport:{width:640,height:360,deviceScaleFactor:3,isMobile:!0,hasTouch:!0,isLandscape:!0}}],Xp={};for(const e of Yp)Xp[e.name]=e;Object.freeze(Xp);async function Qp(e,t,r){const{acceptInsecureCerts:n=!1,defaultViewport:s=Yl}=r,{bidiConnection:a,cdpConnection:i,closeCallback:o}=await async function(e,t,r){const n=await import("./bidi.js"),{slowMo:s=0,protocolTimeout:a}=r,i=new n.BidiConnection(t,e,s,a);try{const e=await i.send("session.status",{});if("type"in e&&"success"===e.type)return{bidiConnection:i,closeCallback:async()=>{await i.send("browser.close",{}).catch(Zl)}}}catch(e){if(!(e instanceof Hl))throw e}i.unbind();const o=new xh(t,e,s,a,!0),c=await o.send("Browser.getVersion");if(c.product.toLowerCase().includes("firefox"))throw new Vl("Firefox is not supported in BiDi over CDP mode.");const l=await n.connectBidiOverCdp(o);return{cdpConnection:o,bidiConnection:l,closeCallback:async()=>{await o.send("Browser.close").catch(Zl)}}}(e,t,r),c=await import("./bidi.js");return await c.BidiBrowser.create({connection:a,cdpConnection:i,closeCallback:o,process:void 0,defaultViewport:s,acceptInsecureCerts:n,capabilities:r.capabilities})}const em=async()=>Rl?(await Promise.resolve().then(s.bind(s,874))).NodeWebSocketTransport:(await Promise.resolve().then(s.bind(s,5001))).BrowserWebSocketTransport;async function tm(e){const{connectionTransport:t,endpointUrl:r}=await async function(e){const{browserWSEndpoint:t,browserURL:r,transport:n,headers:s={}}=e;if($l(Number(!!t)+Number(!!r)+Number(!!n)===1,"Exactly one of browserWSEndpoint, browserURL or transport must be passed to puppeteer.connect"),n)return{connectionTransport:n,endpointUrl:""};if(t){const e=await em();return{connectionTransport:await e.create(t,s),endpointUrl:t}}if(r){const e=await async function(e){const t=new URL("/json/version",e);try{const e=await globalThis.fetch(t.toString(),{method:"GET"});if(!e.ok)throw new Error(`HTTP ${e.statusText}`);return(await e.json()).webSocketDebuggerUrl}catch(e){throw ku(e)&&(e.message=`Failed to fetch browser webSocket URL from ${t}: `+e.message),e}}(r),t=await em();return{connectionTransport:await t.create(e),endpointUrl:e}}throw new Error("Invalid connection options")}(e);if("webDriverBiDi"===e.protocol){return await Qp(t,r,e)}{const n=await async function(e,t,r){const{acceptInsecureCerts:n=!1,defaultViewport:s=Yl,downloadBehavior:a,targetFilter:i,_isPageTarget:o,slowMo:c=0,protocolTimeout:l}=r,u=new xh(t,e,c,l),{browserContextIds:d}=await u.send("Target.getBrowserContexts");return await Vp._create(u,d,n,s,a,void 0,(()=>u.send("Browser.close").catch(Zl)),i,o)}(t,r,e);return n}}Object.freeze({chrome:"136.0.7103.92","chrome-headless-shell":"136.0.7103.92",firefox:"stable_138.0.1"});const rm=new class{static customQueryHandlers=Uu;static registerCustomQueryHandler(e,t){return this.customQueryHandlers.register(e,t)}static unregisterCustomQueryHandler(e){return this.customQueryHandlers.unregister(e)}static customQueryHandlerNames(){return this.customQueryHandlers.names()}static clearCustomQueryHandlers(){return this.customQueryHandlers.clear()}_isPuppeteerCore;_changedBrowsers=!1;constructor(e){this._isPuppeteerCore=e.isPuppeteerCore,this.connect=this.connect.bind(this)}connect(e){return tm(e)}}({isPuppeteerCore:!0}),{connect:nm}=rm,sm=M.z.object({debugMode:M.z.boolean().default(!1)}),am=M.z.object({url:M.z.string(),title:M.z.string(),tabId:M.z.number().int().positive(),isLoading:M.z.boolean().default(!1),timestamp:M.z.number().int().positive()});class im{constructor(e,t,r={debugMode:!1}){this.puppeteerPage=e,this.tabId=t,this.options=sm.parse(r),this.options.debugMode&&Y.log("NxtscapePage",`Page wrapper created for tab ${t}`)}async getState(){try{const e=this.puppeteerPage.url(),t=await this.puppeteerPage.title();return am.parse({url:e,title:t,tabId:this.tabId,isLoading:!1,timestamp:Date.now()})}catch(e){return Y.log("NxtscapePage",`Error getting page state: ${e}`,"error"),am.parse({url:"about:blank",title:"Unknown",tabId:this.tabId,isLoading:!1,timestamp:Date.now()})}}async navigate(e){try{this.options.debugMode&&Y.log("NxtscapePage",`Navigating to: ${e}`),await this.puppeteerPage.goto(e,{waitUntil:"domcontentloaded",timeout:3e4}),this.options.debugMode&&Y.log("NxtscapePage",`Navigation to ${e} completed`)}catch(t){const r=t instanceof Error?t.message:String(t);throw Y.log("NxtscapePage",`Navigation failed: ${r}`,"error"),new Error(`Navigation to ${e} failed: ${r}`)}}async click(e){try{this.options.debugMode&&Y.log("NxtscapePage",`Clicking element: ${e}`),await this.puppeteerPage.waitForSelector(e,{visible:!0,timeout:1e4}),await this.puppeteerPage.click(e),this.options.debugMode&&Y.log("NxtscapePage",`Click on ${e} completed`)}catch(t){const r=t instanceof Error?t.message:String(t);throw Y.log("NxtscapePage",`Click failed: ${r}`,"error"),new Error(`Click on ${e} failed: ${r}`)}}async findElementByDescription(e){try{this.options.debugMode&&Y.log("NxtscapePage",`Finding element by description: ${e}`);const t={"search box":'input[type="search"], input[name*="search"], input[placeholder*="search"], textarea[placeholder*="search"]',"search input":'input[type="search"], input[name*="search"], input[placeholder*="search"]',"search button":'button[type="submit"], input[type="submit"], button:contains("Search")',"email input":'input[type="email"], input[name*="email"], input[placeholder*="email"]',"email field":'input[type="email"], input[name*="email"], input[placeholder*="email"]',"password field":'input[type="password"], input[name*="password"], input[placeholder*="password"]',"password input":'input[type="password"], input[name*="password"], input[placeholder*="password"]',"username input":'input[name*="username"], input[name*="user"], input[placeholder*="username"]',"username field":'input[name*="username"], input[name*="user"], input[placeholder*="username"]',"text input":'input[type="text"], textarea',"text field":'input[type="text"], textarea',"message box":'textarea[placeholder*="message"], textarea[name*="message"]',"comment box":'textarea[placeholder*="comment"], textarea[name*="comment"]',"login button":'button:contains("Login"), button:contains("Sign in"), a:contains("Login"), input[type="submit"][value*="Login"]',"sign in button":'button:contains("Sign in"), button:contains("Login"), a:contains("Sign in"), input[type="submit"][value*="Sign"]',"submit button":'button[type="submit"], input[type="submit"]',"menu button":'button[aria-label*="menu"], button:contains("Menu"), button[class*="menu"]',"close button":'button:contains("Close"), button[aria-label*="close"], button[class*="close"]'},r=e.toLowerCase();for(const[e,n]of Object.entries(t))if(r.includes(e)){if(await this.puppeteerPage.$(n))return n}return null}catch(e){return Y.log("NxtscapePage",`Error finding element: ${e}`,"error"),null}}async type(e,t){try{this.options.debugMode&&Y.log("NxtscapePage",`Typing into ${e}: ${t}`),await this.puppeteerPage.click(e,{clickCount:3}),await this.puppeteerPage.keyboard.press("Backspace"),await this.puppeteerPage.type(e,t),this.options.debugMode&&Y.log("NxtscapePage","Text input completed")}catch(t){const r=t instanceof Error?t.message:String(t);throw Y.log("NxtscapePage",`Type failed: ${r}`,"error"),new Error(`Type into ${e} failed: ${r}`)}}async waitForElement(e,t=1e4){try{this.options.debugMode&&Y.log("NxtscapePage",`Waiting for element: ${e}`),await this.puppeteerPage.waitForSelector(e,{visible:!0,timeout:t}),this.options.debugMode&&Y.log("NxtscapePage",`Element ${e} is now visible`)}catch(t){const r=t instanceof Error?t.message:String(t);throw Y.log("NxtscapePage",`Wait for element failed: ${r}`,"error"),new Error(`Wait for ${e} failed: ${r}`)}}async screenshot(){try{this.options.debugMode&&Y.log("NxtscapePage","Taking screenshot");const e=await this.puppeteerPage.screenshot({type:"png",fullPage:!1,encoding:"base64"});return this.options.debugMode&&Y.log("NxtscapePage",`Screenshot captured (${e.length} chars)`),e}catch(e){const t=e instanceof Error?e.message:String(e);throw Y.log("NxtscapePage",`Screenshot failed: ${t}`,"error"),new Error(`Screenshot failed: ${t}`)}}getPuppeteerPage(){return this.puppeteerPage}getPlaywrightPage(){return this.puppeteerPage}getTabId(){return this.tabId}async evaluate(e){try{return this.options.debugMode&&Y.log("NxtscapePage","Evaluating JavaScript"),await this.puppeteerPage.evaluate(e)}catch(e){const t=e instanceof Error?e.message:String(e);throw Y.log("NxtscapePage",`Evaluation failed: ${t}`,"error"),new Error(`JavaScript evaluation failed: ${t}`)}}async close(){try{this.options.debugMode&&Y.log("NxtscapePage",`Closing page for tab ${this.tabId}`),await chrome.tabs.remove(this.tabId),this.options.debugMode&&Y.log("NxtscapePage",`Tab ${this.tabId} closed`)}catch(e){Y.log("NxtscapePage",`Error closing page: ${e}`,"error")}}}const om=M.z.object({debugMode:M.z.boolean().default(!1).optional()});class cm{constructor(e={}){this.currentPage=null,this.currentTabId=null,this.isInitialized=!1,this.attachedTabs=new Map,this.options=om.parse(e),this.options.debugMode&&Y.log("NxtscapeBrowserContext","Browser context created")}async initialize(){if(!this.isInitialized)try{Y.log("NxtscapeBrowserContext","Initializing browser context with event listeners"),this.setupTabEventListeners(),this.isInitialized=!0,Y.log("NxtscapeBrowserContext","Browser context initialized successfully")}catch(e){const t=e instanceof Error?e.message:String(e);throw Y.log("NxtscapeBrowserContext",`Failed to initialize: ${t}`,"error"),new Error(`Browser context initialization failed: ${t}`)}}setupTabEventListeners(){chrome.tabs.onRemoved.addListener((e=>{this.isTabAttached(e)&&(Y.log("NxtscapeBrowserContext",`Tab ${e} was closed, cleaning up state`),this.cleanupTab(e),e===this.currentTabId&&(this.currentTabId=null,this.currentPage=null))})),chrome.windows.onRemoved.addListener((async e=>{Y.log("NxtscapeBrowserContext",`Window ${e} was closed, cleaning up tabs`);for(const[t,r]of this.attachedTabs.entries())try{const r=await chrome.tabs.get(t).catch((()=>null));r&&r.windowId!==e||this.cleanupTab(t)}catch(e){this.cleanupTab(t)}})),Y.log("NxtscapeBrowserContext","Tab event listeners set up")}isTabAttached(e){return this.attachedTabs.has(e)}async cleanupTab(e){const t=this.attachedTabs.get(e);if(t){try{await t.browser.disconnect(),Y.log("NxtscapeBrowserContext",`Disconnected browser for tab ${e}`)}catch(t){Y.log("NxtscapeBrowserContext",`Error disconnecting browser for tab ${e}: ${t}`,"warning")}this.attachedTabs.delete(e)}try{await new Promise((t=>{chrome.debugger.detach({tabId:e},(()=>{t()}))}))}catch(e){}}async createPuppeteerConnection(e){Y.log("NxtscapeBrowserContext",`Creating Puppeteer connection for tab ${e}`);const t=await nm({transport:await Zp.connectTab(e),defaultViewport:null,protocol:"cdp"}),[r]=await t.pages();if(!r)throw new Error("No page found in browser");return await this.addAntiDetectionScripts(r),{browser:t,page:r}}async addAntiDetectionScripts(e){await e.evaluateOnNewDocument("\n // Webdriver property\n Object.defineProperty(navigator, 'webdriver', {\n get: () => undefined\n });\n\n // Chrome runtime\n window.chrome = { runtime: {} };\n\n // Permissions\n const originalQuery = window.navigator.permissions.query;\n window.navigator.permissions.query = (parameters) => (\n parameters.name === 'notifications' ?\n Promise.resolve({ state: Notification.permission }) :\n originalQuery(parameters)\n );\n ")}async getCurrentPage(){if(this.isInitialized||await this.initialize(),this.currentPage&&this.currentTabId&&this.isTabAttached(this.currentTabId))try{const e=this.attachedTabs.get(this.currentTabId);if(e)return await e.page.evaluate("1"),this.currentPage}catch(e){Y.log("NxtscapeBrowserContext","Current page health check failed, will get fresh page"),this.currentPage=null,this.currentTabId=null}const e=await this.getActiveTab();if(!(e.length>0&&e[0].id))return Y.log("NxtscapeBrowserContext","No active tab found, creating new tab"),await this.createNewTab();{const t=e[0].id;Y.log("NxtscapeBrowserContext",`Getting page for active tab ${t}`);try{return await this.attachToTab(t)}catch(e){const r=e instanceof Error?e.message:String(e);if(r.includes("Another debugger is already attached")||r.includes("has another debugger attached"))return Y.log("NxtscapeBrowserContext",`Active tab ${t} has debugger conflict, creating new tab as fallback`,"warning"),await this.createNewTab();throw e}}}async getActiveTab(){let e=await chrome.tabs.query({active:!0,lastFocusedWindow:!0});if(0===e.length){const t=(await chrome.windows.getAll({populate:!0})).find((e=>e.focused));t&&t.tabs&&(e=t.tabs.filter((e=>e.active)))}return 0===e.length&&(e=await chrome.tabs.query({active:!0})),e}async getCurrentWindow(){let e=await chrome.tabs.query({active:!0,lastFocusedWindow:!0});if(e.length>0){return await chrome.windows.get(e[0].windowId)}const t=await chrome.windows.getAll({populate:!0}),r=t.find((e=>e.focused));if(r&&r.id)return r;const n=t[0];if(n&&n.id)return n;throw new Error("No window found")}isDebuggerAvailable(){return!!(chrome&&chrome.debugger&&chrome.debugger.detach)}async forceDetachDebuggers(e){if(this.isDebuggerAvailable())try{Y.log("NxtscapeBrowserContext",`Force detaching debuggers from tab ${e}`);if(!await chrome.tabs.get(e).catch((()=>null)))return void Y.log("NxtscapeBrowserContext",`Tab ${e} not found, cannot detach debugger`);await new Promise((t=>{chrome.debugger.detach({tabId:e},(()=>{chrome.runtime.lastError?Y.log("NxtscapeBrowserContext",`No debugger to detach from tab ${e}: ${chrome.runtime.lastError.message}`):Y.log("NxtscapeBrowserContext",`Successfully detached debugger from tab ${e}`),t()}))})),await new Promise((e=>setTimeout(e,500))),Y.log("NxtscapeBrowserContext",`Debugger detach process completed for tab ${e}`)}catch(t){Y.log("NxtscapeBrowserContext",`Error force detaching debuggers from tab ${e}: ${t}`,"warning")}else Y.log("NxtscapeBrowserContext","Chrome debugger API not available, skipping detach","warning")}async attachToTab(e,t=0){this.isInitialized||await this.initialize();try{if(Y.log("NxtscapeBrowserContext",`Attaching to tab ${e}${t>0?` (retry ${t})`:""}`),this.isTabAttached(e)&&(Y.log("NxtscapeBrowserContext",`Tab ${e} already attached`),this.currentTabId===e&&this.currentPage))return this.currentPage;const r=await chrome.tabs.get(e);if(Y.log("NxtscapeBrowserContext",`Tab details: URL=${r.url}, status=${r.status}, windowId=${r.windowId}`),!r)throw new Error(`Tab ${e} not found`);r.discarded&&(Y.log("NxtscapeBrowserContext",`Tab ${e} is discarded, activating...`),await chrome.tabs.update(e,{active:!0}),await new Promise((e=>setTimeout(e,1e3))));this.isProblematicUrl(r.url)&&(Y.log("NxtscapeBrowserContext",`Tab has problematic URL: ${r.url}, navigating to Google...`),await chrome.tabs.update(e,{url:"https://www.google.com"}),await new Promise((e=>setTimeout(e,2e3)))),"loading"===r.status&&(Y.log("NxtscapeBrowserContext",`Tab ${e} is loading, waiting...`),await this.waitForTabToLoad(e,5e3)),await this.cleanupTab(e);const{browser:n,page:s}=await this.createPuppeteerConnection(e);this.attachedTabs.set(e,{browser:n,page:s});const a=new im(s,e,{debugMode:this.options.debugMode||!1});return this.currentPage=a,this.currentTabId=e,Y.log("NxtscapeBrowserContext",`Successfully attached to tab ${e}`),a}catch(r){const n=r instanceof Error?r.message:String(r);if(Y.log("NxtscapeBrowserContext",`Failed to attach to tab ${e}: ${n}`,"error"),await this.cleanupTab(e),n.includes("Another debugger is already attached")&&t<2){Y.log("NxtscapeBrowserContext",`Debugger conflict detected for tab ${e}, attempting to detach and retry...`);try{return await this.forceDetachDebuggers(e),await this.attachToTab(e,t+1)}catch(t){const r=t instanceof Error?t.message:String(t);throw Y.log("NxtscapeBrowserContext",`Retry failed for tab ${e}: ${r}`,"error"),new Error(`Failed to attach to tab ${e} after detaching debuggers: ${r}`)}}if(n.includes("Cannot attach to this target"))throw new Error(`Tab ${e} cannot be attached. This usually happens when Chrome DevTools is open on this tab. Please close DevTools and try again.`);if(n.includes("Target closed"))throw new Error(`Tab ${e} target was closed. The tab may have been closed or navigated to a restricted page.`);if(n.includes("Another debugger is already attached"))throw new Error(`Tab ${e} has another debugger attached. Please close Chrome DevTools or other debugging tools and try again.`);throw new Error(`Cannot attach to tab ${e}: ${n}`)}}isProblematicUrl(e){if(!e)return!0;return["chrome://","chrome-extension://","edge://","about:","moz-extension://","devtools://","chrome-devtools://","file://"].some((t=>e.startsWith(t)))}async waitForTabToLoad(e,t=5e3){const r=Date.now();for(;Date.now()-rsetTimeout(e,200)))}catch(t){Y.log("NxtscapeBrowserContext",`Error checking tab ${e} status: ${t}`,"warning");break}Y.log("NxtscapeBrowserContext",`Tab ${e} loading timeout after ${t}ms`,"warning")}async forceReset(){try{Y.log("NxtscapeBrowserContext","Force resetting all browser connections"),this.currentPage=null,this.currentTabId=null;const e=[];for(const[t]of this.attachedTabs.entries())e.push(this.cleanupTab(t));return await Promise.all(e),this.isInitialized=!1,await this.initialize(),!0}catch(e){return Y.log("NxtscapeBrowserContext",`Force reset failed: ${e}`,"error"),!1}}async forceDetachFromTab(e){try{return Y.log("NxtscapeBrowserContext",`Public request to force detach debuggers from tab ${e}`),await this.cleanupTab(e),await this.forceDetachDebuggers(e),this.currentTabId===e&&(this.currentTabId=null,this.currentPage=null),Y.log("NxtscapeBrowserContext",`Successfully force detached from tab ${e}`),!0}catch(t){return Y.log("NxtscapeBrowserContext",`Failed to force detach from tab ${e}: ${t}`,"error"),!1}}async createNewTab(e="https://www.google.com"){try{Y.log("NxtscapeBrowserContext",`Creating new tab with URL: ${e}`);const t=await chrome.tabs.create({url:e,active:!0});if(!t.id)throw new Error("Failed to create new tab");return Y.log("NxtscapeBrowserContext",`Created new tab ${t.id}`),await new Promise((e=>setTimeout(e,1500))),await this.attachToTab(t.id)}catch(e){const t=e instanceof Error?e.message:String(e);throw Y.log("NxtscapeBrowserContext",`Error creating new tab: ${t}`,"error"),new Error(`Failed to create new tab: ${t}`)}}getCurrentTabId(){return this.currentTabId}isReady(){return this.isInitialized}async executeScript(e){if(!this.currentPage)throw new Error("No current page available for script execution");try{const t=this.currentPage.getPuppeteerPage();if(e.files&&e.files.length>0)for(const r of e.files)"Readability.js"===r&&await t.evaluate((()=>{window.Readability||(window.Readability=class{constructor(e){this.doc=e}parse(){return{title:document.title||"Unknown Title",byline:null,textContent:document.body?.innerText||"",excerpt:document.body?.innerText?.substring(0,200)||"",url:window.location.href}}})}));return e.func?await t.evaluate(e.func):{}}catch(e){const t=e instanceof Error?e.message:String(e);throw Y.log("NxtscapeBrowserContext",`Script execution failed: ${t}`,"error"),new Error(`Script execution failed: ${t}`)}}async cleanup(){try{Y.log("NxtscapeBrowserContext","Cleaning up browser context"),this.currentPage=null,this.currentTabId=null;const e=[];for(const[t]of this.attachedTabs.entries())e.push(this.cleanupTab(t));await Promise.all(e),this.isInitialized=!1,Y.log("NxtscapeBrowserContext","Browser context cleaned up successfully")}catch(e){Y.log("NxtscapeBrowserContext",`Error during cleanup: ${e}`,"error")}}}const lm=cm;class um{constructor(e,t){this.callbacks=e,this.toolRegistry=t,this.currentSegmentId=0,this.currentSegmentContent="",this.isProcessingTool=!1,this.stepCount=0}getToolDisplayInfo(e,t){if(this.toolRegistry){const r=this.toolRegistry.getByName(e);if(r)return r.getDisplayInfo(t)}const r=this.getFallbackDisplay(e);return{displayName:r.displayName,icon:r.icon,description:r.displayName}}getFallbackDisplay(e){return{displayName:e,icon:"šŸ”§"}}cleanToolResult(e){if(!e)return"Completed";try{const t=JSON.parse(e);let r=t;return this.isLangChainToolMessage(t)&&(r=JSON.parse(t.kwargs.content)),r._displayResult?r._displayResult:r.message?r.message:"Completed successfully"}catch(t){return e.length>150?`${e.substring(0,150).trim()}...`:e.trim()}}isLangChainToolMessage(e){return e&&1===e.lc&&"constructor"===e.type&&e.id&&Array.isArray(e.id)&&e.id.includes("ToolMessage")&&e.kwargs?.content}async processEvent(e){if(this.callbacks.abortController?.signal.aborted)return;const t=e.event;try{switch(t){case"on_chat_model_stream":this.handleChatModelStream(e);break;case"on_tool_start":this.handleToolStart(e);break;case"on_tool_end":this.handleToolEnd(e);break;case"on_chain_start":"RunnableAgent"!==e.name&&"agent"!==e.name||this.handleAgentStart();break;case"on_llm_end":this.handleLlmEnd();break;case"on_chain_error":case"on_tool_error":this.handleError(e)}}catch(e){Y.log("StreamProcessor",`Error processing event: ${e}`,"error"),this.callbacks.onError?.(e)}}handleChatModelStream(e){const t=e.data?.chunk;if(t?.content){let e="";if("string"==typeof t.content)e=t.content;else if(Array.isArray(t.content)){e=t.content.filter((e=>"text"===e.type)).map((e=>e.text||"")).join("")}e&&(this.currentSegmentContent+=e,this.callbacks.onStreamingChunk?.(e))}}handleToolStart(e){this.currentSegmentContent&&(this.callbacks.onFinalizeSegment?.(this.currentSegmentId,this.currentSegmentContent),this.currentSegmentContent="",this.currentSegmentId++);const t=e.name||"unknown",r=e.data?.input||{};this.isProcessingTool=!0,this.stepCount++;let n=r;if("string"==typeof r)try{n=JSON.parse(r)}catch{n={input:r}}const s=this.getToolDisplayInfo(t,n);this.callbacks.onToolCall?.(s.displayName,{description:s.description,icon:s.icon,args:n})}handleToolEnd(e){const t=e.name||"unknown",r=e.data?.output||"";this.isProcessingTool=!1;let n="";"string"==typeof r?n=r:"object"==typeof r&&(n=JSON.stringify(r,null,2));const s=this.cleanToolResult(n),a=this.getToolDisplayInfo(t,{});this.callbacks.onToolResult?.(a.displayName,s),this.currentSegmentId++,this.callbacks.onStartNewSegment?.(this.currentSegmentId)}handleAgentStart(){this.stepCount++,this.callbacks.onStartNewSegment?.(this.currentSegmentId)}handleLlmEnd(){this.currentSegmentContent&&!this.isProcessingTool&&(this.callbacks.onFinalizeSegment?.(this.currentSegmentId,this.currentSegmentContent),this.currentSegmentContent="")}handleError(e){const t=e.data?.error||e.error||"Unknown error occurred";Y.log("StreamProcessor",`[ERROR_EVENT] ${t}`,"error"),this.callbacks.onSystemMessage?.(`āŒ Error: ${t}`),this.callbacks.onError&&this.callbacks.onError(new Error(t))}completeStreaming(){this.currentSegmentContent&&(this.callbacks.onFinalizeSegment?.(this.currentSegmentId,this.currentSegmentContent),this.currentSegmentContent=""),this.callbacks.onStreamingComplete?.()}getStepCount(){return this.stepCount}reset(){this.currentSegmentId=0,this.currentSegmentContent="",this.isProcessingTool=!1,this.stepCount=0}}const dm=M.z.object({llmProvider:M.z.custom((e=>null!==e&&"object"==typeof e&&"invoke"in e&&"function"==typeof e.invoke)).refine((e=>!0),{message:"llmProvider must be a valid LLM implementation (like ChatOpenAI, ChatAnthropic, or similar)"}),browserContext:M.z.instanceof(lm),systemPrompt:M.z.string().optional(),maxSteps:M.z.number().int().positive().optional().default(10),debugMode:M.z.boolean().default(!1)});class hm{constructor(e){this.isInitialized=!1,this.options=dm.parse(e),this.browserContext=this.options.browserContext,this.debugMode=this.options.debugMode}async initialize(){if(!this.isInitialized)try{this.toolRegistry=this.createToolRegistry(),this.systemPrompt=this.options.systemPrompt||this.getDefaultSystemPrompt();const e=this.createTools();this.agent=So({llm:this.options.llmProvider,tools:e}),this.isInitialized=!0,this.debugMode&&this.log(`${this.getAgentName()} initialized with ${e.length} tools`)}catch(e){throw this.log(`Failed to initialize ${this.getAgentName()}: ${e}`,"error"),e}}createToolRegistry(){throw new Error("createToolRegistry must be implemented by subclasses")}getToolRegistry(){return this.toolRegistry}getInitializationMessage(){return`šŸš€ Initializing ${this.getAgentName().toLowerCase()}...`}async ensureInitialized(){this.isInitialized||await this.initialize()}async execute(e,t,r){await this.ensureInitialized();try{const{instruction:n}=e;this.debugMode&&this.log(`šŸš€ Starting streaming agent execution: ${n}`);const s=await this.browserContext.getCurrentPage(),a=await s.getState(),i=this.addBrowserContext(n,a),o=r?.abortController||new AbortController,c=o.signal,l=this.getToolRegistry(),u=new um({onStreamingChunk:r?.onStreamingChunk,onFinalizeSegment:r?.onFinalizeSegment,onStartNewSegment:r?.onStartNewSegment,onSystemMessage:r?.onSystemMessage,onToolCall:r?.onToolCall,onToolResult:r?.onToolResult,onStreamingComplete:r?.onStreamingComplete,onError:r?.onError,onCancel:r?.onCancel,abortController:o},l);if(l?this.log(`StreamProcessor initialized with tool registry (${l.getAll().length} tools)`):this.log("StreamProcessor initialized without tool registry (using fallback display)"),c.aborted)throw new Error("Task was cancelled before execution");const d=await this.agent.streamEvents({messages:[new se.SystemMessage(this.systemPrompt),new se.HumanMessage(i)]},{version:"v2",signal:c}),h=[];let p=!1;try{for await(const e of d){if(c.aborted){p=!0;break}if(await u.processEvent(e),"on_chat_model_end"===e.event||"on_tool_end"===e.event){const t=e.data?.output;t&&h.push(t)}}}catch(e){if(!(e instanceof Error&&"AbortError"===e.name))throw e;p=!0,this.log("Task was cancelled by user","info")}u.completeStreaming();const m={success:!p,messages:h,pageState:await s.getState(),stepCount:u.getStepCount(),cancelled:p};if(p){const e=n.length>60?n.substring(0,60)+"...":n;m.error=`Task cancelled: "${e}"`,r?.onCancel?.(),r?.onSystemMessage?.(`šŸ›‘ Task cancelled: "${e}"`),r?.onStreamingComplete?.(),this.debugMode&&this.log(`šŸ›‘ EXECUTION CANCELLED: "${e}"`)}else{const e=h.some((e=>!(!e?.tool_calls||0===e.tool_calls.length)&&e.tool_calls.some((e=>{if("terminate"!==e.name)return!1;const t=e.args??e.arguments;return t&&!1===t.success}))));e&&(m.success=!1),this.debugMode&&this.log(`\nāœ… STREAMING EXECUTION COMPLETED in ${u.getStepCount()} steps`)}return t.setVariable("result",m),m}catch(e){this.log(`āŒ Streaming execution error: ${e instanceof Error?e.message:String(e)}`,"error");const r={success:!1,error:e instanceof Error?e.message:String(e)};return t.setVariable("result",r),r}}addBrowserContext(e,t){const r=t.url||"about:blank",n=t.title||"New Tab";let s="unknown";try{if(r&&"about:blank"!==r){s=new URL(r).hostname}}catch{}return`${e}\n\n## CURRENT BROWSER CONTEXT\nYou are currently on ${r} (${n})\nDomain: ${s}\n\nCurrent browser state:\n• URL: ${r}\n• Title: ${n}\n• Domain: ${s}\n\nCONTEXT GUIDANCE:\n• If the user's request seems to continue a previous task on this domain, work with the current page\n• If the request requires going to a different website, navigate there first\n• If the current page is 'about:blank' or doesn't match the task, navigation will be needed\n• Always observe the current page state before taking action\n\nPlease analyze the current context and user request, then proceed accordingly.`}log(e,t="info"){(this.debugMode||"error"===t)&&Y.log(this.getAgentName(),e,t)}}const pm=M.z.enum(["navigation","observation","interaction","tab_management","control","sessions","bookmarks"]),mm=M.z.object({description:M.z.string(),input:M.z.record(M.z.unknown()),output:M.z.unknown()});M.z.object({name:M.z.string(),description:M.z.string(),category:pm,version:M.z.string().default("1.0.0"),inputSchema:M.z.instanceof(M.z.ZodType),outputSchema:M.z.instanceof(M.z.ZodType),examples:M.z.array(mm).optional(),systemPromptTemplate:M.z.string().optional(),streamingConfig:M.z.object({displayName:M.z.string().optional(),icon:M.z.string().optional(),progressMessage:M.z.string().optional()}).optional()});class fm{constructor(e,t){this.config=e,this.browserContext=t}formatDisplayResult(e){if("object"==typeof e&&null!==e){const t=e;if(!1===t.success&&t.error)return`āŒ ${t.error}`;if(!0===t.success&&t.message)return`āœ… ${t.message}`;if(t.message)return t.message}return"Completed successfully"}getConfig(){return this.config}getLangChainTool(){return bn((async e=>{try{const t=this.config.inputSchema.parse(e),r=await this.execute(t),n=this.config.outputSchema.parse(r),s={...n,_displayResult:this.formatDisplayResult(n),_toolName:this.config.name};return JSON.stringify(s)}catch(e){if(e instanceof M.z.ZodError){const t=`Validation error: ${e.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,r={success:!1,error:t,_displayResult:`āŒ ${t}`,_toolName:this.config.name};return JSON.stringify(r)}const t=e instanceof Error?e.message:String(e),r={success:!1,error:t,_displayResult:`āŒ ${t}`,_toolName:this.config.name};return JSON.stringify(r)}}),{name:this.config.name,description:this.config.description,schema:this.config.inputSchema})}getStreamingConfig(){return this.config.streamingConfig||{displayName:this.config.name,icon:"šŸ”§",progressMessage:`Running ${this.config.name}...`}}getDisplayMessage(e){return this.getStreamingConfig().progressMessage||`Running ${this.config.name}...`}getDisplayInfo(e){const t=this.getStreamingConfig();return{displayName:t.displayName||this.config.name,icon:t.icon||"šŸ”§",description:this.getDisplayMessage(e)}}}class gm{constructor(){this.tools=new Map,this.toolsByCategory=new Map}register(e){const t=e.getConfig();this.tools.set(t.name,e),this.toolsByCategory.has(t.category)||this.toolsByCategory.set(t.category,[]),this.toolsByCategory.get(t.category).push(e)}registerAll(e){e.forEach((e=>this.register(e)))}getByName(e){return this.tools.get(e)}getByCategory(e){return this.toolsByCategory.get(e)||[]}getAll(){return Array.from(this.tools.values())}getLangChainTools(){return this.getAll().map((e=>e.getLangChainTool()))}generateSystemPrompt(e){const t=(e?e.flatMap((e=>this.getByCategory(e))):this.getAll()).map((e=>{const t=e.getConfig(),r=this.zodSchemaToString(t.inputSchema),n=this.zodSchemaToString(t.outputSchema);let s=`### ${t.name}\n`;return s+=`**Category**: ${t.category}\n`,s+=`**Description**: ${t.description}\n`,s+=`**Input Schema**:\n\`\`\`json\n${r}\n\`\`\`\n`,s+=`**Output Schema**:\n\`\`\`json\n${n}\n\`\`\`\n`,t.examples&&t.examples.length>0&&(s+="**Examples**:\n",t.examples.forEach(((e,t)=>{s+=`${t+1}. ${e.description}\n`,s+=` Input: \`${JSON.stringify(e.input)}\`\n`,s+=` Output: \`${JSON.stringify(e.output)}\`\n`}))),s})).join("\n---\n\n");return`## Available Tools\n\n${t}`}zodSchemaToString(e){try{return JSON.stringify(e._def,null,2)}catch{return"Schema details available at runtime"}}validateCompatibility(e){return this.getAll().every((t=>t.getConfig().version>=e))}}M.z.object({id:M.z.number(),url:M.z.string(),title:M.z.string(),active:M.z.boolean(),windowId:M.z.number()});const ym=M.z.object({tab_id:M.z.number(),title:M.z.string(),url:M.z.string()}),bm=M.z.object({windowId:M.z.number().optional()}),wm=M.z.object({success:M.z.boolean(),tabs:M.z.array(ym),total_count:M.z.number(),message:M.z.string()});class vm extends fm{constructor(e){super({name:"list_tabs",description:"List all open browser tabs with their IDs, titles, and URLs. Returns structured JSON with tab_id, title, and url for each tab. Optionally filter by window ID.",category:"tab_management",version:"1.0.0",inputSchema:bm,outputSchema:wm,examples:[{description:"List all tabs across all windows",input:{},output:{success:!0,tabs:[{tab_id:123,title:"Google",url:"https://google.com"},{tab_id:124,title:"GitHub",url:"https://github.com"}],total_count:2,message:"Found 2 tabs across all windows"}},{description:"List tabs in a specific window",input:{windowId:1},output:{success:!0,tabs:[{tab_id:123,title:"Google",url:"https://google.com"}],total_count:1,message:"Found 1 tabs in window 1"}}],streamingConfig:{displayName:"List Tabs",icon:"šŸ“‘",progressMessage:"Retrieving browser tabs..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.windowId;return void 0!==r?`Listing tabs in window ${r}`:"Listing all browser tabs"}catch{return"Retrieving browser tabs..."}}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;const t=e.total_count;return 0===t?"šŸ“‘ No tabs found":`šŸ“‘ Found ${t} tab${1===t?"":"s"}`}async execute(e){try{const t=await this.getAllTabs(e.windowId),r=t.map((e=>({tab_id:e.id,title:e.title,url:e.url}))),n=e.windowId?`Found ${t.length} tabs in window ${e.windowId}`:`Found ${t.length} tabs across all windows`;return{success:!0,tabs:r,total_count:t.length,message:n}}catch(e){return{success:!1,tabs:[],total_count:0,message:`Error listing tabs: ${e instanceof Error?e.message:String(e)}`}}}async getAllTabs(e){const t={};void 0!==e&&(t.windowId=e);return(await chrome.tabs.query(t)).filter((e=>void 0!==e.id&&e.url&&e.title)).map((e=>({id:e.id,url:e.url,title:e.title,active:e.active||!1,windowId:e.windowId||0})))}}const _m=M.z.object({tabIds:M.z.array(M.z.number()).min(1),reason:M.z.string().optional()}),km=M.z.object({success:M.z.boolean(),closedCount:M.z.number(),closedTabs:M.z.array(M.z.object({id:M.z.number(),title:M.z.string(),url:M.z.string()})),message:M.z.string()});class Sm extends fm{constructor(e){super({name:"close_tabs",description:'Close browser tabs by their specific tab IDs. Use the tab IDs from list_tabs command. Example: {"tabIds": [123, 456]}',category:"tab_management",version:"1.0.0",inputSchema:_m,outputSchema:km,examples:[{description:"Close specific tabs by ID",input:{tabIds:[123,456]},output:{success:!0,closedCount:2,closedTabs:[{id:123,title:"Google",url:"https://google.com"},{id:456,title:"GitHub",url:"https://github.com"}],message:"Successfully closed 2 tab(s)"}},{description:"Close tabs with a reason",input:{tabIds:[789],reason:"Cleaning up old tabs"},output:{success:!0,closedCount:1,closedTabs:[{id:789,title:"Old Documentation",url:"https://docs.example.com"}],message:"Successfully closed 1 tab(s) (Cleaning up old tabs)"}}],streamingConfig:{displayName:"Close Tabs",icon:"āŒ",progressMessage:"Closing browser tabs..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.tabIds,n=t?.reason;if(r&&Array.isArray(r)){const e=r.length,t=`Closing ${e} ${1===e?"tab":"tabs"}`;return n?`${t} (${n})`:t}return"Closing browser tabs..."}catch{return"Closing browser tabs..."}}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;const t=e.closedCount;if(0===t)return"āš ļø No tabs were closed";return`āŒ Closed ${t} ${1===t?"tab":"tabs"}`}async execute(e){try{const t=(await this.getAllTabs()).filter((t=>e.tabIds.includes(t.id)));if(0===t.length)return{success:!0,closedCount:0,closedTabs:[],message:`No valid tabs found for the provided tab IDs: ${e.tabIds.join(", ")}`};await chrome.tabs.remove(e.tabIds);const r=t.map((e=>({id:e.id,title:e.title,url:e.url}))),n=e.reason?` (${e.reason})`:"",s=`Successfully closed ${r.length} tab(s)${n}`;return{success:!0,closedCount:r.length,closedTabs:r,message:s}}catch(e){return console.error("[close_tabs] Error:",e),{success:!1,closedCount:0,closedTabs:[],message:`Error closing tabs: ${e instanceof Error?e.message:String(e)}`}}}async getAllTabs(){return(await chrome.tabs.query({})).filter((e=>void 0!==e.id&&e.url&&e.title)).map((e=>({id:e.id,url:e.url,title:e.title,active:e.active||!1,windowId:e.windowId||0})))}}const Em=M.z.object({tabId:M.z.number()}),xm=M.z.object({success:M.z.boolean(),tabId:M.z.number(),title:M.z.string().optional(),url:M.z.string().optional(),message:M.z.string()});class Tm extends fm{constructor(e){super({name:"switch_tab",description:"Switch to a specific tab by its ID. Use the tab ID from list_tabs command. Updates the browser context to work with the new active tab.",category:"tab_management",version:"1.0.0",inputSchema:Em,outputSchema:xm,examples:[{description:"Switch to a specific tab",input:{tabId:123},output:{success:!0,tabId:123,title:"Google",url:"https://google.com",message:'Successfully switched to tab 123: "Google" (https://google.com)'}}],streamingConfig:{displayName:"Switch Tab",icon:"šŸ”„",progressMessage:"Switching to tab..."}},e)}formatDisplayResult(e){return e.success?e.title?`šŸ”„ Switched to "${e.title}"`:`šŸ”„ Switched to tab ${e.tabId}`:`āŒ ${e.message}`}async execute(e){try{await chrome.tabs.update(e.tabId,{active:!0});const t=await chrome.tabs.get(e.tabId);return await this.browserContext.attachToTab(e.tabId),{success:!0,tabId:e.tabId,title:t.title,url:t.url,message:`Successfully switched to tab ${e.tabId}: "${t.title}" (${t.url})`}}catch(t){return{success:!1,tabId:e.tabId,message:`Failed to switch to tab ${e.tabId}: ${t instanceof Error?t.message:String(t)}`}}}}const Cm=M.z.object({url:M.z.string().url().optional(),active:M.z.boolean().optional(),windowId:M.z.number().optional()}),Pm=M.z.object({success:M.z.boolean(),tabId:M.z.number().optional(),url:M.z.string(),active:M.z.boolean(),message:M.z.string()});class Om extends fm{constructor(e){super({name:"new_tab",description:'Create a new browser tab, optionally with a specific URL. Example: {"url": "https://google.com"} or {} for blank tab.',category:"tab_management",version:"1.0.0",inputSchema:Cm,outputSchema:Pm,examples:[{description:"Create a new tab with a specific URL",input:{url:"https://google.com"},output:{success:!0,tabId:789,url:"https://google.com",message:"Successfully created new tab with URL: https://google.com"}},{description:"Create a blank new tab",input:{},output:{success:!0,tabId:790,url:"chrome://newtab/",message:"Successfully created new blank tab"}}],streamingConfig:{displayName:"New Tab",icon:"āž•",progressMessage:"Creating new tab..."}},e)}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;if(e.url&&"chrome://newtab/"!==e.url)try{return`āœ… Created new tab: ${new URL(e.url).hostname}`}catch{return`āœ… Created new tab: ${e.url}`}return"āœ… Created new blank tab"}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.url;if(r)try{return`Creating new tab: ${new URL(r).hostname}`}catch{return`Creating new tab: ${r}`}return"Creating new blank tab"}catch{return"Creating new tab..."}}async execute(e){try{const t={active:e.active??!0};e.url&&(t.url=e.url),e.windowId&&(t.windowId=e.windowId);const r=await chrome.tabs.create(t);if(!r.id)throw new Error("Failed to create new tab");const n=e.active??!0;n&&(await new Promise((e=>setTimeout(e,1e3))),await this.browserContext.attachToTab(r.id));const s=e.url||"about:blank";return{success:!0,tabId:r.id,url:s,active:n,message:`Successfully created new tab ${r.id} with URL: ${s}${n?" (now active)":""}`}}catch(t){return{success:!1,url:e.url||"about:blank",active:e.active??!0,message:`Failed to create new tab: ${t instanceof Error?t.message:String(t)}`}}}}const Am=M.z.object({tabIds:M.z.array(M.z.number()).min(1),groupName:M.z.string().optional(),color:M.z.enum(["grey","blue","red","yellow","green","pink","purple","cyan","orange"]).optional(),windowId:M.z.number().optional()}),Im=M.z.object({success:M.z.boolean(),groupId:M.z.number().optional(),groupName:M.z.string().optional(),color:M.z.string(),tabCount:M.z.number(),message:M.z.string()});class Mm extends fm{constructor(e){super({name:"group_tabs",description:"Group browser tabs together. Takes an array of tab IDs and creates a group with optional name and color. Colors: grey, blue, red, yellow, green, pink, purple, cyan, orange.",category:"tab_management",version:"1.0.0",inputSchema:Am,outputSchema:Im,examples:[{description:"Group work-related tabs with a blue color",input:{tabIds:[123,456],groupName:"Work Research",color:"blue"},output:{success:!0,groupId:1,groupName:"Work Research",groupedCount:2,groupedTabs:[{id:123,title:"GitHub",url:"https://github.com"},{id:456,title:"Documentation",url:"https://docs.example.com"}],message:'Successfully grouped 2 tabs into "Work Research"'}}],streamingConfig:{displayName:"Group Tabs",icon:"šŸ“",progressMessage:"Organizing tabs into groups..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.tabIds,n=t?.groupName;if(r&&Array.isArray(r)){const e=r.length,t=1===e?"tab":"tabs";return n?`Grouping ${e} ${t} into "${n}"`:`Grouping ${e} ${t}`}return"Organizing tabs into groups..."}catch{return"Organizing tabs into groups..."}}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;const t=e.tabCount,r=1===t?"tab":"tabs";return e.groupName?`šŸ“ Created "${e.groupName}" group with ${t} ${r}`:`šŸ“ Grouped ${t} ${r} together`}async execute(e){try{const t=await this.getAllTabs(e.windowId),r=e.tabIds.filter((e=>t.some((t=>t.id===e))));if(0===r.length)return{success:!1,color:e.color||"blue",tabCount:0,message:`No valid tabs found for the provided tab IDs: ${e.tabIds.join(", ")}`};if(r.length!==e.tabIds.length){const t=e.tabIds.filter((e=>!r.includes(e)));console.warn(`[group_tabs] Some tab IDs were invalid and skipped: ${t.join(", ")}`)}const n={tabIds:r};e.windowId&&(n.createProperties={windowId:e.windowId});const s=await chrome.tabs.group(n),a=e.color||"blue";if(chrome.tabGroups&&chrome.tabGroups.update){const t={color:a};e.groupName&&(t.title=e.groupName),await chrome.tabGroups.update(s,t)}else console.warn("[group_tabs] chrome.tabGroups API not available, cannot set group properties");return{success:!0,groupId:s,groupName:e.groupName,color:a,tabCount:r.length,message:`Successfully created group${e.groupName?` "${e.groupName}"`:""} with ${r.length} tab(s)`}}catch(t){return console.error("[group_tabs] Error:",t),{success:!1,color:e.color||"blue",tabCount:0,message:`Error grouping tabs: ${t instanceof Error?t.message:String(t)}`}}}async getAllTabs(e){const t={};void 0!==e&&(t.windowId=e);const r=await chrome.tabs.getCurrent();r&&void 0===e&&(e=r.windowId);return(await chrome.tabs.query(t)).filter((e=>void 0!==e.id&&e.url&&e.title)).map((e=>({id:e.id,url:e.url,title:e.title,active:e.active||!1,windowId:e.windowId||0})))}}const Rm=M.z.object({url:M.z.string().url().optional(),title:M.z.string().optional(),category:M.z.string().optional(),subcategory:M.z.string().optional(),tags:M.z.array(M.z.string()).optional(),notes:M.z.string().optional()}),jm=M.z.object({success:M.z.boolean(),bookmarkId:M.z.string().optional(),title:M.z.string().optional(),url:M.z.string().optional(),folderPath:M.z.string().optional(),message:M.z.string()});class Nm extends fm{constructor(e){super({name:"save_bookmark",description:'Save a URL as a bookmark in an organized folder structure under "AI Bookmarks" on the bookmark bar.',category:"bookmarks",version:"1.0.0",inputSchema:Rm,outputSchema:jm,examples:[{description:"Save current tab with category",input:{category:"Research",subcategory:"AI Papers",tags:["machine-learning","nlp"]},output:{success:!0,bookmarkId:"bookmark_123",title:"Attention Is All You Need",url:"https://arxiv.org/abs/1706.03762",folderPath:"AI Bookmarks > Research > AI Papers",message:'Successfully saved bookmark to "AI Bookmarks > Research > AI Papers"'}},{description:"Save specific URL with custom title",input:{url:"https://example.com",title:"My Custom Title",category:"Tools"},output:{success:!0,bookmarkId:"bookmark_456",title:"My Custom Title",url:"https://example.com",folderPath:"AI Bookmarks > Tools",message:'Successfully saved bookmark to "AI Bookmarks > Tools"'}}],streamingConfig:{displayName:"Save Bookmark",icon:"šŸ”–",progressMessage:"Saving bookmark..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.category||Nm.DEFAULT_CATEGORY,n=t?.subcategory;return n?`Saving to ${r} > ${n}...`:r!==Nm.DEFAULT_CATEGORY?`Saving to ${r}...`:"Saving bookmark..."}catch{return"Saving bookmark..."}}formatDisplayResult(e){return e.success?`šŸ”– Saved to ${e.folderPath}`:`āŒ ${e.message}`}async execute(e){try{let t=e.url,r=e.title;if(!t){const e=this.browserContext.getCurrentTabId();if(!e)return{success:!1,message:"No active tab found"};const n=await chrome.tabs.get(e);if(!n||!n.url)return{success:!1,message:"No active tab found or tab has no URL"};t=n.url,r=r||n.title||"Untitled"}if(!this.isBookmarkableUrl(t))return{success:!1,message:`Cannot bookmark this URL type: ${t}`};const n=e.category||Nm.DEFAULT_CATEGORY,s=e.subcategory,a=await this.getOrCreateFolderStructure(n,s),i=await this.findExistingBookmark(t,a);if(i){r&&r!==i.title&&await chrome.bookmarks.update(i.id,{title:r});const e=await this.getFolderPath(a);return{success:!0,bookmarkId:i.id,title:r||i.title,url:t,folderPath:e,message:`Bookmark already exists in "${e}"`}}const o=await chrome.bookmarks.create({parentId:a,title:r||"Untitled",url:t});(e.tags||e.notes)&&await this.saveBookmarkMetadata(o.id,{tags:e.tags,notes:e.notes});const c=await this.getFolderPath(a);return{success:!0,bookmarkId:o.id,title:o.title,url:o.url,folderPath:c,message:`Successfully saved bookmark to "${c}"`}}catch(e){return console.error("[save_bookmark] Error:",e),{success:!1,message:`Error saving bookmark: ${e instanceof Error?e.message:String(e)}`}}}isBookmarkableUrl(e){try{const t=new URL(e);return!["chrome:","chrome-extension:","about:","data:","blob:"].includes(t.protocol)}catch{return!1}}async getOrCreateFolderStructure(e,t){const r=await this.getBookmarkBar();if(!r)throw new Error("Could not find bookmark bar");let n=await this.findChildFolder(r.id,Nm.ROOT_FOLDER_NAME);n||(n=await chrome.bookmarks.create({parentId:r.id,title:Nm.ROOT_FOLDER_NAME}));let s=await this.findChildFolder(n.id,e);if(s||(s=await chrome.bookmarks.create({parentId:n.id,title:e})),t){let e=await this.findChildFolder(s.id,t);return e||(e=await chrome.bookmarks.create({parentId:s.id,title:t})),e.id}return s.id}async getBookmarkBar(){const e=(await chrome.bookmarks.getTree())[0];for(const t of e.children||[])if("1"===t.id||"Bookmarks Bar"===t.title)return t;return null}async findChildFolder(e,t){return(await chrome.bookmarks.getChildren(e)).find((e=>!e.url&&e.title===t))||null}async findExistingBookmark(e,t){return(await chrome.bookmarks.getChildren(t)).find((t=>t.url===e))||null}async getFolderPath(e){const t=[];let r=e;for(;r;){const e=await chrome.bookmarks.get(r);if(!(e.length>0))break;{const n=e[0];if(n.title&&"Bookmarks Bar"!==n.title&&t.unshift(n.title),r=n.parentId||"","1"===r||!r)break}}return t.join(" > ")}async saveBookmarkMetadata(e,t){const r=`bookmark_meta_${e}`,n=await chrome.storage.local.get(r);await chrome.storage.local.set({[r]:{...n[r],...t,updatedAt:(new Date).toISOString()}})}}function $m(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r}function Lm(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}Nm.ROOT_FOLDER_NAME="AI Bookmarks",Nm.DEFAULT_CATEGORY="Uncategorized";let Fm=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return Fm=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(e=>(+e^r()&15>>+e/4).toString(16)))};function Dm(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const zm=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};class Um extends Error{}class Bm extends Um{constructor(e,t,r,n){super(`${Bm.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("request-id"),this.error=t}static makeMessage(e,t,r){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new Km({message:r,cause:zm(t)});const s=t;return 400===e?new Hm(e,s,r,n):401===e?new Vm(e,s,r,n):403===e?new Gm(e,s,r,n):404===e?new Jm(e,s,r,n):409===e?new Zm(e,s,r,n):422===e?new Ym(e,s,r,n):429===e?new Xm(e,s,r,n):e>=500?new Qm(e,s,r,n):new Bm(e,s,r,n)}}class qm extends Bm{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Km extends Bm{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Wm extends Km{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Hm extends Bm{}class Vm extends Bm{}class Gm extends Bm{}class Jm extends Bm{}class Zm extends Bm{}class Ym extends Bm{}class Xm extends Bm{}class Qm extends Bm{}const ef=/^[a-z][a-z0-9+.-]*:/i;function tf(e){return"object"!=typeof e?{}:e??{}}const rf=e=>{try{return JSON.parse(e)}catch(e){return}},nf={off:0,error:200,warn:300,info:400,debug:500},sf=(e,t,r)=>{if(e)return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(nf,e)?e:void uf(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(nf))}`)};function af(){}function of(e,t,r){return!t||nf[e]>nf[r]?af:t[e].bind(t)}const cf={error:af,warn:af,info:af,debug:af};let lf=new WeakMap;function uf(e){const t=e.logger,r=e.logLevel??"off";if(!t)return cf;const n=lf.get(t);if(n&&n[0]===r)return n[1];const s={error:of("error",t,r),warn:of("warn",t,r),info:of("info",t,r),debug:of("debug",t,r)};return lf.set(t,[r,s]),s}const df=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map((([e,t])=>[e,"x-api-key"===e.toLowerCase()||"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t])))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),hf="0.50.4";const pf=()=>{const e="undefined"!=typeof Deno&&null!=Deno.build?"deno":"undefined"!=typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":hf,"X-Stainless-OS":ff(Deno.build.os),"X-Stainless-Arch":mf(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":hf,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if("node"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":hf,"X-Stainless-OS":ff(globalThis.process.platform),"X-Stainless-Arch":mf(globalThis.process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version};const t=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{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:t,pattern:r}of e){const e=r.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":hf,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":hf,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const mf=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",ff=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let gf;function yf(...e){const t=globalThis.ReadableStream;if(void 0===t)throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function bf(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return yf({start(){},async pull(e){const{done:r,value:n}=await t.next();r?e.close():e.enqueue(n)},async cancel(){await(t.return?.())}})}function wf(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}const vf=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});let _f,kf;function Sf(e){let t;return(_f??(t=new globalThis.TextEncoder,_f=t.encode.bind(t)))(e)}function Ef(e){let t;return(kf??(t=new globalThis.TextDecoder,kf=t.decode.bind(t)))(e)}var xf,Tf,Cf,Pf;class Of{constructor(){xf.set(this,void 0),Tf.set(this,void 0),$m(this,xf,new Uint8Array,"f"),$m(this,Tf,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?Sf(e):e;$m(this,xf,function(e){let t=0;for(const r of e)t+=r.length;const r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}([Lm(this,xf,"f"),t]),"f");const r=[];let n;for(;null!=(n=Af(Lm(this,xf,"f"),Lm(this,Tf,"f")));){if(n.carriage&&null==Lm(this,Tf,"f")){$m(this,Tf,n.index,"f");continue}if(null!=Lm(this,Tf,"f")&&(n.index!==Lm(this,Tf,"f")+1||n.carriage)){r.push(Ef(Lm(this,xf,"f").subarray(0,Lm(this,Tf,"f")-1))),$m(this,xf,Lm(this,xf,"f").subarray(Lm(this,Tf,"f")),"f"),$m(this,Tf,null,"f");continue}const e=null!==Lm(this,Tf,"f")?n.preceding-1:n.preceding,t=Ef(Lm(this,xf,"f").subarray(0,e));r.push(t),$m(this,xf,Lm(this,xf,"f").subarray(n.index),"f"),$m(this,Tf,null,"f")}return r}flush(){return Lm(this,xf,"f").length?this.decode("\n"):[]}}function Af(e,t){for(let r=t??0;r0&&(yield t)}(s))for(const t of n.decode(e)){const e=r.decode(t);e&&(yield e)}for(const e of n.flush()){const t=r.decode(e);t&&(yield t)}}(e,t)){if("completion"===r.event)try{yield JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if("message_start"===r.event||"message_delta"===r.event||"message_stop"===r.event||"content_block_start"===r.event||"content_block_delta"===r.event||"content_block_stop"===r.event)try{yield JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if("ping"!==r.event&&"error"===r.event)throw new Bm(void 0,rf(r.data)??r.data,void 0,e.headers)}n=!0}catch(e){if(Dm(e))return;throw e}finally{n||t.abort()}}),t)}static fromReadableStream(e,t){let r=!1;return new Mf((async function*(){if(r)throw new Um("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let n=!1;try{for await(const t of async function*(){const t=new Of,r=wf(e);for await(const e of r)for(const r of t.decode(e))yield r;for(const e of t.flush())yield e}())n||t&&(yield JSON.parse(t));n=!0}catch(e){if(Dm(e))return;throw e}finally{n||t.abort()}}),t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],r=this.iterator(),n=n=>({next:()=>{if(0===n.length){const n=r.next();e.push(n),t.push(n)}return n.shift()}});return[new Mf((()=>n(e)),this.controller),new Mf((()=>n(t)),this.controller)]}toReadableStream(){const e=this;let t;return yf({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:r,done:n}=await t.next();if(n)return e.close();const s=Sf(JSON.stringify(r)+"\n");e.enqueue(s)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class Rf{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 e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=function(e,t){const r=e.indexOf(t);if(-1!==r)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}async function jf(e,t){const{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:a}=t,i=await(async()=>{if(t.options.stream)return uf(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(r,t.controller):Mf.fromSSEResponse(r,t.controller);if(204===r.status)return null;if(t.options.__binaryResponse)return r;const n=r.headers.get("content-type"),s=n?.split(";")[0]?.trim();if(s?.includes("application/json")||s?.endsWith("+json")){return Nf(await r.json(),r)}return await r.text()})();return uf(e).debug(`[${n}] response parsed`,df({retryOfRequestLogID:s,url:r.url,status:r.status,body:i,durationMs:Date.now()-a})),i}function Nf(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("request-id"),enumerable:!1})}class $f extends Promise{constructor(e,t,r=jf){super((e=>{e(null)})),this.responsePromise=t,this.parseResponse=r,Cf.set(this,void 0),$m(this,Cf,e,"f")}_thenUnwrap(e){return new $f(Lm(this,Cf,"f"),this.responsePromise,(async(t,r)=>Nf(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("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then((e=>this.parseResponse(Lm(this,Cf,"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)}}Cf=new WeakMap;class Lf{constructor(e,t,r,n){Pf.set(this,void 0),$m(this,Pf,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new Um("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Lm(this,Pf,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Pf=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Ff extends $f{constructor(e,t,r){super(e,t,(async(e,t)=>new r(e,t.response,await jf(e,t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}class Df extends Lf{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){const e=this.first_id;return e?{...this.options,query:{...tf(this.options.query),before_id:e}}:null}const e=this.last_id;return e?{...this.options,query:{...tf(this.options.query),after_id:e}}:null}}const zf=()=>{if("undefined"==typeof File){const{process:e}=globalThis,t="string"==typeof e?.versions?.node&&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 Uf(e,t,r){return zf(),new File(e,t??"unknown_file",r)}function Bf(e){return("object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}const qf=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator];new WeakMap;const Kf=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function Wf(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Kf(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!qf(e)){const t=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";const t=Object.getOwnPropertyNames(e);return`; props: [${t.map((e=>`"${e}"`)).join(", ")}]`}(e)}`)}for await(const r of e)t.push(...await Wf(r))}return t}class Hf{constructor(e){this._client=e}}const Vf=Symbol.for("brand.privateNullableHeaders"),Gf=Array.isArray;function*Jf(e){if(!e)return;if(Vf in e){const{values:t,nulls:r}=e;yield*t.entries();for(const e of r)yield[e,null];return}let t,r=!1;e instanceof Headers?t=e.entries():Gf(e)?t=e:(r=!0,t=Object.entries(e??{}));for(let e of t){const t=e[0];if("string"!=typeof t)throw new TypeError("expected header name to be a string");const n=Gf(e[1])?e[1]:[e[1]];let s=!1;for(const e of n)void 0!==e&&(r&&!s&&(s=!0,yield[t,null]),yield[t,e])}}const Zf=e=>{const t=new Headers,r=new Set;for(const n of e){const e=new Set;for(const[s,a]of Jf(n)){const n=s.toLowerCase();e.has(n)||(t.delete(s),e.add(n)),null===a?(t.delete(s),r.add(n)):(t.append(s,a),r.delete(n))}}return{[Vf]:!0,values:t,nulls:r}};function Yf(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Xf=((e=Yf)=>function(t,...r){if(1===t.length)return t[0];let n=!1;const s=t.reduce(((t,s,a)=>(/[?#]/.test(s)&&(n=!0),t+s+(a===r.length?"":(n?encodeURIComponent:e)(String(r[a]))))),""),a=s.split(/[?#]/,1)[0],i=[],o=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let c;for(;null!==(c=o.exec(a));)i.push({start:c.index,length:c[0].length});if(i.length>0){let e=0;const t=i.reduce(((t,r)=>{const n=" ".repeat(r.start-e),s="^".repeat(r.length);return e=r.start+r.length,t+n+s}),"");throw new Um(`Path parameters result in path with invalid segments:\n${s}\n${t}`)}return s})(Yf);class Qf extends Hf{retrieve(e,t={},r){const{betas:n}=t??{};return this._client.get(Xf`/v1/models/${e}?beta=true`,{...r,headers:Zf([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}list(e={},t){const{betas:r,...n}=e??{};return this._client.getAPIList("/v1/models?beta=true",Df,{query:n,...t,headers:Zf([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}}class eg{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new Of;for await(const t of this.iterator)for(const r of e.decode(t))yield JSON.parse(r);for(const t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new Um("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new Um("Attempted to iterate over a response with no body")}return new eg(wf(e.body),t)}}class tg extends Hf{create(e,t){const{betas:r,...n}=e;return this._client.post("/v1/messages/batches?beta=true",{body:n,...t,headers:Zf([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},r){const{betas:n}=t??{};return this._client.get(Xf`/v1/messages/batches/${e}?beta=true`,{...r,headers:Zf([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}list(e={},t){const{betas:r,...n}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",Df,{query:n,...t,headers:Zf([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},r){const{betas:n}=t??{};return this._client.delete(Xf`/v1/messages/batches/${e}?beta=true`,{...r,headers:Zf([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}cancel(e,t={},r){const{betas:n}=t??{};return this._client.post(Xf`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:Zf([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}async results(e,t={},r){const n=await this.retrieve(e);if(!n.results_url)throw new Um(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);const{betas:s}=t??{};return this._client.get(n.results_url,{...r,headers:Zf([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},r?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap(((e,t)=>eg.fromResponse(t.response,t.controller)))}}const rg=e=>{if(0===e.length)return e;let t=e[e.length-1];switch(t.type){case"separator":return e=e.slice(0,e.length-1),rg(e);case"number":let r=t.value[t.value.length-1];if("."===r||"-"===r)return e=e.slice(0,e.length-1),rg(e);case"string":let n=e[e.length-2];if("delimiter"===n?.type)return e=e.slice(0,e.length-1),rg(e);if("brace"===n?.type&&"{"===n.value)return e=e.slice(0,e.length-1),rg(e);break;case"delimiter":return e=e.slice(0,e.length-1),rg(e)}return e},ng=e=>JSON.parse((e=>{let t="";return e.map((e=>{"string"===e.type?t+='"'+e.value+'"':t+=e.value})),t})((e=>{let t=[];return e.map((e=>{"brace"===e.type&&("{"===e.value?t.push("}"):t.splice(t.lastIndexOf("}"),1)),"paren"===e.type&&("["===e.value?t.push("]"):t.splice(t.lastIndexOf("]"),1))})),t.length>0&&t.reverse().map((t=>{"}"===t?e.push({type:"brace",value:"}"}):"]"===t&&e.push({type:"paren",value:"]"})})),e})(rg((e=>{let t=0,r=[];for(;t{})),cg.set(this,(()=>{})),lg.set(this,void 0),ug.set(this,(()=>{})),dg.set(this,(()=>{})),hg.set(this,{}),pg.set(this,!1),mg.set(this,!1),fg.set(this,!1),gg.set(this,!1),yg.set(this,void 0),bg.set(this,void 0),_g.set(this,(e=>{if($m(this,mg,!0,"f"),Dm(e)&&(e=new qm),e instanceof qm)return $m(this,fg,!0,"f"),this._emit("abort",e);if(e instanceof Um)return this._emit("error",e);if(e instanceof Error){const t=new Um(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Um(String(e)))})),$m(this,ig,new Promise(((e,t)=>{$m(this,og,e,"f"),$m(this,cg,t,"f")})),"f"),$m(this,lg,new Promise(((e,t)=>{$m(this,ug,e,"f"),$m(this,dg,t,"f")})),"f"),Lm(this,ig,"f").catch((()=>{})),Lm(this,lg,"f").catch((()=>{}))}get response(){return Lm(this,yg,"f")}get request_id(){return Lm(this,bg,"f")}async withResponse(){const e=await Lm(this,ig,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new Cg;return t._run((()=>t._fromReadableStream(e))),t}static createMessage(e,t,r){const n=new Cg;for(const e of t.messages)n._addMessageParam(e);return n._run((()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}_run(e){e().then((()=>{this._emitFinal(),this._emit("end")}),Lm(this,_g,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),Lm(this,sg,"m",kg).call(this);const{response:s,data:a}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(s);for await(const e of a)Lm(this,sg,"m",Sg).call(this,e);if(a.controller.signal?.aborted)throw new qm;Lm(this,sg,"m",Eg).call(this)}_connected(e){this.ended||($m(this,yg,e,"f"),$m(this,bg,e?.headers.get("request-id"),"f"),Lm(this,og,"f").call(this,e),this._emit("connect"))}get ended(){return Lm(this,pg,"f")}get errored(){return Lm(this,mg,"f")}get aborted(){return Lm(this,fg,"f")}abort(){this.controller.abort()}on(e,t){return(Lm(this,hg,"f")[e]||(Lm(this,hg,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=Lm(this,hg,"f")[e];if(!r)return this;const n=r.findIndex((e=>e.listener===t));return n>=0&&r.splice(n,1),this}once(e,t){return(Lm(this,hg,"f")[e]||(Lm(this,hg,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,r)=>{$m(this,gg,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)}))}async done(){$m(this,gg,!0,"f"),await Lm(this,lg,"f")}get currentMessage(){return Lm(this,ag,"f")}async finalMessage(){return await this.done(),Lm(this,sg,"m",wg).call(this)}async finalText(){return await this.done(),Lm(this,sg,"m",vg).call(this)}_emit(e,...t){if(Lm(this,pg,"f"))return;"end"===e&&($m(this,pg,!0,"f"),Lm(this,ug,"f").call(this));const r=Lm(this,hg,"f")[e];if(r&&(Lm(this,hg,"f")[e]=r.filter((e=>!e.once)),r.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return Lm(this,gg,"f")||r?.length||Promise.reject(e),Lm(this,cg,"f").call(this,e),Lm(this,dg,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];Lm(this,gg,"f")||r?.length||Promise.reject(e),Lm(this,cg,"f").call(this,e),Lm(this,dg,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",Lm(this,sg,"m",wg).call(this))}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),Lm(this,sg,"m",kg).call(this),this._connected(null);const n=Mf.fromReadableStream(e,this.controller);for await(const e of n)Lm(this,sg,"m",Sg).call(this,e);if(n.controller.signal?.aborted)throw new qm;Lm(this,sg,"m",Eg).call(this)}[(ag=new WeakMap,ig=new WeakMap,og=new WeakMap,cg=new WeakMap,lg=new WeakMap,ug=new WeakMap,dg=new WeakMap,hg=new WeakMap,pg=new WeakMap,mg=new WeakMap,fg=new WeakMap,gg=new WeakMap,yg=new WeakMap,bg=new WeakMap,_g=new WeakMap,sg=new WeakSet,wg=function(){if(0===this.receivedMessages.length)throw new Um("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},vg=function(){if(0===this.receivedMessages.length)throw new Um("stream ended without producing a Message with role=assistant");const e=this.receivedMessages.at(-1).content.filter((e=>"text"===e.type)).map((e=>e.text));if(0===e.length)throw new Um("stream ended without producing a content block with type=text");return e.join(" ")},kg=function(){this.ended||$m(this,ag,void 0,"f")},Sg=function(e){if(this.ended)return;const t=Lm(this,sg,"m",xg).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{const r=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===r.type&&this._emit("text",e.delta.text,r.text||"");break;case"citations_delta":"text"===r.type&&this._emit("citation",e.delta.citation,r.citations??[]);break;case"input_json_delta":"tool_use"===r.type&&r.input&&this._emit("inputJson",e.delta.partial_json,r.input);break;case"thinking_delta":"thinking"===r.type&&this._emit("thinking",e.delta.thinking,r.thinking);break;case"signature_delta":"thinking"===r.type&&this._emit("signature",r.signature);break;default:e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(t,!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":$m(this,ag,t,"f")}},Eg=function(){if(this.ended)throw new Um("stream has ended, this shouldn't happen");const e=Lm(this,ag,"f");if(!e)throw new Um("request ended without sending any chunks");return $m(this,ag,void 0,"f"),e},xg=function(e){let t=Lm(this,ag,"f");if("message_start"===e.type){if(t)throw new Um(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new Um(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,null!=e.usage.input_tokens&&(t.usage.input_tokens=e.usage.input_tokens),null!=e.usage.cache_creation_input_tokens&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),null!=e.usage.cache_read_input_tokens&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),null!=e.usage.server_tool_use&&(t.usage.server_tool_use=e.usage.server_tool_use),t;case"content_block_start":return t.content.push(e.content_block),t;case"content_block_delta":{const r=t.content.at(e.index);switch(e.delta.type){case"text_delta":"text"===r?.type&&(r.text+=e.delta.text);break;case"citations_delta":"text"===r?.type&&(r.citations??(r.citations=[]),r.citations.push(e.delta.citation));break;case"input_json_delta":if("tool_use"===r?.type){let t=r[Tg]||"";t+=e.delta.partial_json,Object.defineProperty(r,Tg,{value:t,enumerable:!1,writable:!0}),t&&(r.input=ng(t))}break;case"thinking_delta":"thinking"===r?.type&&(r.thinking+=e.delta.thinking);break;case"signature_delta":"thinking"===r?.type&&(r.signature=e.delta.signature);break;default:e.delta}return t}}},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("streamEvent",(r=>{const n=t.shift();n?n.resolve(r):e.push(r)})),this.on("end",(()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),this.on("error",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise(((e,r)=>t.push({resolve:e,reject:r}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Mf(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}const Pg={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};class Og extends Hf{constructor(){super(...arguments),this.batches=new tg(this._client)}create(e,t){const{betas:r,...n}=e;return n.model in Pg&&console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${Pg[n.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:n,timeout:this._client._options.timeout??(n.stream?6e5:this._client._calculateNonstreamingTimeout(n.max_tokens)),...t,headers:Zf([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}stream(e,t){return Cg.createMessage(this,e,t)}countTokens(e,t){const{betas:r,...n}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:n,...t,headers:Zf([{"anthropic-beta":[...r??[],"token-counting-2024-11-01"].toString()},t?.headers])})}}Og.Batches=tg;class Ag extends Hf{constructor(){super(...arguments),this.models=new Qf(this._client),this.messages=new Og(this._client)}}Ag.Models=Qf,Ag.Messages=Og;class Ig extends Hf{create(e,t){const{betas:r,...n}=e;return this._client.post("/v1/complete",{body:n,timeout:this._client._options.timeout??6e5,...t,headers:Zf([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}}class Mg extends Hf{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(Xf`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",Df,{query:e,...t})}delete(e,t){return this._client.delete(Xf`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(Xf`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){const r=await this.retrieve(e);if(!r.results_url)throw new Um(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...t,headers:Zf([{Accept:"application/binary"},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap(((e,t)=>eg.fromResponse(t.response,t.controller)))}}var Rg,jg,Ng,$g,Lg,Fg,Dg,zg,Ug,Bg,qg,Kg,Wg,Hg,Vg,Gg,Jg,Zg,Yg,Xg,Qg,ey;const ty="__json_buf";class ry{constructor(){Rg.add(this),this.messages=[],this.receivedMessages=[],jg.set(this,void 0),this.controller=new AbortController,Ng.set(this,void 0),$g.set(this,(()=>{})),Lg.set(this,(()=>{})),Fg.set(this,void 0),Dg.set(this,(()=>{})),zg.set(this,(()=>{})),Ug.set(this,{}),Bg.set(this,!1),qg.set(this,!1),Kg.set(this,!1),Wg.set(this,!1),Hg.set(this,void 0),Vg.set(this,void 0),Zg.set(this,(e=>{if($m(this,qg,!0,"f"),Dm(e)&&(e=new qm),e instanceof qm)return $m(this,Kg,!0,"f"),this._emit("abort",e);if(e instanceof Um)return this._emit("error",e);if(e instanceof Error){const t=new Um(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Um(String(e)))})),$m(this,Ng,new Promise(((e,t)=>{$m(this,$g,e,"f"),$m(this,Lg,t,"f")})),"f"),$m(this,Fg,new Promise(((e,t)=>{$m(this,Dg,e,"f"),$m(this,zg,t,"f")})),"f"),Lm(this,Ng,"f").catch((()=>{})),Lm(this,Fg,"f").catch((()=>{}))}get response(){return Lm(this,Hg,"f")}get request_id(){return Lm(this,Vg,"f")}async withResponse(){const e=await Lm(this,Ng,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new ry;return t._run((()=>t._fromReadableStream(e))),t}static createMessage(e,t,r){const n=new ry;for(const e of t.messages)n._addMessageParam(e);return n._run((()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}_run(e){e().then((()=>{this._emitFinal(),this._emit("end")}),Lm(this,Zg,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),Lm(this,Rg,"m",Yg).call(this);const{response:s,data:a}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(s);for await(const e of a)Lm(this,Rg,"m",Xg).call(this,e);if(a.controller.signal?.aborted)throw new qm;Lm(this,Rg,"m",Qg).call(this)}_connected(e){this.ended||($m(this,Hg,e,"f"),$m(this,Vg,e?.headers.get("request-id"),"f"),Lm(this,$g,"f").call(this,e),this._emit("connect"))}get ended(){return Lm(this,Bg,"f")}get errored(){return Lm(this,qg,"f")}get aborted(){return Lm(this,Kg,"f")}abort(){this.controller.abort()}on(e,t){return(Lm(this,Ug,"f")[e]||(Lm(this,Ug,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=Lm(this,Ug,"f")[e];if(!r)return this;const n=r.findIndex((e=>e.listener===t));return n>=0&&r.splice(n,1),this}once(e,t){return(Lm(this,Ug,"f")[e]||(Lm(this,Ug,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,r)=>{$m(this,Wg,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)}))}async done(){$m(this,Wg,!0,"f"),await Lm(this,Fg,"f")}get currentMessage(){return Lm(this,jg,"f")}async finalMessage(){return await this.done(),Lm(this,Rg,"m",Gg).call(this)}async finalText(){return await this.done(),Lm(this,Rg,"m",Jg).call(this)}_emit(e,...t){if(Lm(this,Bg,"f"))return;"end"===e&&($m(this,Bg,!0,"f"),Lm(this,Dg,"f").call(this));const r=Lm(this,Ug,"f")[e];if(r&&(Lm(this,Ug,"f")[e]=r.filter((e=>!e.once)),r.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return Lm(this,Wg,"f")||r?.length||Promise.reject(e),Lm(this,Lg,"f").call(this,e),Lm(this,zg,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];Lm(this,Wg,"f")||r?.length||Promise.reject(e),Lm(this,Lg,"f").call(this,e),Lm(this,zg,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",Lm(this,Rg,"m",Gg).call(this))}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),Lm(this,Rg,"m",Yg).call(this),this._connected(null);const n=Mf.fromReadableStream(e,this.controller);for await(const e of n)Lm(this,Rg,"m",Xg).call(this,e);if(n.controller.signal?.aborted)throw new qm;Lm(this,Rg,"m",Qg).call(this)}[(jg=new WeakMap,Ng=new WeakMap,$g=new WeakMap,Lg=new WeakMap,Fg=new WeakMap,Dg=new WeakMap,zg=new WeakMap,Ug=new WeakMap,Bg=new WeakMap,qg=new WeakMap,Kg=new WeakMap,Wg=new WeakMap,Hg=new WeakMap,Vg=new WeakMap,Zg=new WeakMap,Rg=new WeakSet,Gg=function(){if(0===this.receivedMessages.length)throw new Um("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Jg=function(){if(0===this.receivedMessages.length)throw new Um("stream ended without producing a Message with role=assistant");const e=this.receivedMessages.at(-1).content.filter((e=>"text"===e.type)).map((e=>e.text));if(0===e.length)throw new Um("stream ended without producing a content block with type=text");return e.join(" ")},Yg=function(){this.ended||$m(this,jg,void 0,"f")},Xg=function(e){if(this.ended)return;const t=Lm(this,Rg,"m",ey).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{const r=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===r.type&&this._emit("text",e.delta.text,r.text||"");break;case"citations_delta":"text"===r.type&&this._emit("citation",e.delta.citation,r.citations??[]);break;case"input_json_delta":"tool_use"===r.type&&r.input&&this._emit("inputJson",e.delta.partial_json,r.input);break;case"thinking_delta":"thinking"===r.type&&this._emit("thinking",e.delta.thinking,r.thinking);break;case"signature_delta":"thinking"===r.type&&this._emit("signature",r.signature);break;default:e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(t,!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":$m(this,jg,t,"f")}},Qg=function(){if(this.ended)throw new Um("stream has ended, this shouldn't happen");const e=Lm(this,jg,"f");if(!e)throw new Um("request ended without sending any chunks");return $m(this,jg,void 0,"f"),e},ey=function(e){let t=Lm(this,jg,"f");if("message_start"===e.type){if(t)throw new Um(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new Um(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,null!=e.usage.input_tokens&&(t.usage.input_tokens=e.usage.input_tokens),null!=e.usage.cache_creation_input_tokens&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),null!=e.usage.cache_read_input_tokens&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),null!=e.usage.server_tool_use&&(t.usage.server_tool_use=e.usage.server_tool_use),t;case"content_block_start":return t.content.push(e.content_block),t;case"content_block_delta":{const r=t.content.at(e.index);switch(e.delta.type){case"text_delta":"text"===r?.type&&(r.text+=e.delta.text);break;case"citations_delta":"text"===r?.type&&(r.citations??(r.citations=[]),r.citations.push(e.delta.citation));break;case"input_json_delta":if("tool_use"===r?.type){let t=r[ty]||"";t+=e.delta.partial_json,Object.defineProperty(r,ty,{value:t,enumerable:!1,writable:!0}),t&&(r.input=ng(t))}break;case"thinking_delta":"thinking"===r?.type&&(r.thinking+=e.delta.thinking);break;case"signature_delta":"thinking"===r?.type&&(r.signature=e.delta.signature);break;default:e.delta}return t}}},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("streamEvent",(r=>{const n=t.shift();n?n.resolve(r):e.push(r)})),this.on("end",(()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),this.on("error",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise(((e,r)=>t.push({resolve:e,reject:r}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Mf(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class ny extends Hf{constructor(){super(...arguments),this.batches=new Mg(this._client)}create(e,t){return e.model in sy&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${sy[e.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??(e.stream?6e5:this._client._calculateNonstreamingTimeout(e.max_tokens)),...t,stream:e.stream??!1})}stream(e,t){return ry.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}const sy={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};ny.Batches=Mg;class ay extends Hf{retrieve(e,t={},r){const{betas:n}=t??{};return this._client.get(Xf`/v1/models/${e}`,{...r,headers:Zf([{...null!=n?.toString()?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}list(e={},t){const{betas:r,...n}=e??{};return this._client.getAPIList("/v1/models",Df,{query:n,...t,headers:Zf([{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}}const iy=e=>void 0!==globalThis.process?globalThis.process.env?.[e]?.trim()??void 0:void 0!==globalThis.Deno?globalThis.Deno.env?.get?.(e)?.trim():void 0;var oy,cy;class ly{constructor({baseURL:e=iy("ANTHROPIC_BASE_URL"),apiKey:t=iy("ANTHROPIC_API_KEY")??null,authToken:r=iy("ANTHROPIC_AUTH_TOKEN")??null,...n}={}){cy.set(this,void 0);const s={apiKey:t,authToken:r,...n,baseURL:e||"https://api.anthropic.com"};if(!s.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new Um("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");this.baseURL=s.baseURL,this.timeout=s.timeout??uy.DEFAULT_TIMEOUT,this.logger=s.logger??console;const a="warn";this.logLevel=a,this.logLevel=sf(s.logLevel,"ClientOptions.logLevel",this)??sf(iy("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??a,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??function(){if("undefined"!=typeof fetch)return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),$m(this,cy,vf,"f"),this._options=s,this.apiKey=t,this.authToken=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(this.apiKey&&e.get("x-api-key")||t.has("x-api-key")||this.authToken&&e.get("authorization")||t.has("authorization")))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders(e){return Zf([this.apiKeyAuth(e),this.bearerAuth(e)])}apiKeyAuth(e){if(null!=this.apiKey)return Zf([{"X-Api-Key":this.apiKey}])}bearerAuth(e){if(null!=this.authToken)return Zf([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new Um(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)})).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${hf}`}defaultIdempotencyKey(){return`stainless-node-retry-${Fm()}`}makeStatusError(e,t,r,n){return Bm.generate(e,t,r,n)}buildURL(e,t){const r=(e=>ef.test(e))(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return function(e){if(!e)return!0;for(const t in e)return!1;return!0}(n)||(t={...n,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new Um("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");return 6e5}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((r=>({method:e,path:t,...r}))))}request(e,t=null){return new $f(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){const n=await e,s=n.maxRetries??this.maxRetries;null==t&&(t=s),await this.prepareOptions(n);const{req:a,url:i,timeout:o}=this.buildRequest(n,{retryCount:s-t});await this.prepareRequest(a,{url:i,options:n});const c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=void 0===r?"":`, retryOf: ${r}`,u=Date.now();if(uf(this).debug(`[${c}] sending request`,df({retryOfRequestLogID:r,method:n.method,url:i,options:n,headers:a.headers})),n.signal?.aborted)throw new qm;const d=new AbortController,h=await this.fetchWithTimeout(i,a,o,d).catch(zm),p=Date.now();if(h instanceof Error){const e=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new qm;const s=Dm(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return uf(this).info(`[${c}] connection ${s?"timed out":"failed"} - ${e}`),uf(this).debug(`[${c}] connection ${s?"timed out":"failed"} (${e})`,df({retryOfRequestLogID:r,url:i,durationMs:p-u,message:h.message})),this.retryRequest(n,t,r??c);if(uf(this).info(`[${c}] connection ${s?"timed out":"failed"} - error; no more retries left`),uf(this).debug(`[${c}] connection ${s?"timed out":"failed"} (error; no more retries left)`,df({retryOfRequestLogID:r,url:i,durationMs:p-u,message:h.message})),s)throw new Wm;throw new Km({cause:h})}const m=[...h.headers.entries()].filter((([e])=>"request-id"===e)).map((([e,t])=>", "+e+": "+JSON.stringify(t))).join(""),f=`[${c}${l}${m}] ${a.method} ${i} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${p-u}ms`;if(!h.ok){const e=this.shouldRetry(h);if(t&&e){const e=`retrying, ${t} attempts remaining`;return await async function(e){if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void await(e[Symbol.asyncIterator]().return?.());const t=e.getReader(),r=t.cancel();t.releaseLock(),await r}(h.body),uf(this).info(`${f} - ${e}`),uf(this).debug(`[${c}] response error (${e})`,df({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),this.retryRequest(n,t,r??c,h.headers)}const s=e?"error; no more retries left":"error; not retryable";uf(this).info(`${f} - ${s}`);const a=await h.text().catch((e=>zm(e).message)),i=rf(a),o=i?void 0:a;uf(this).debug(`[${c}] response error (${s})`,df({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,message:o,durationMs:Date.now()-u}));throw this.makeStatusError(h.status,i,o,h.headers)}return uf(this).info(f),uf(this).debug(`[${c}] response start`,df({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),{response:h,options:n,controller:d,requestLogID:c,retryOfRequestLogID:r,startTime:u}}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,n){const{signal:s,method:a,...i}=t||{};s&&s.addEventListener("abort",(()=>n.abort()));const o=setTimeout((()=>n.abort()),r),c=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||"object"==typeof i.body&&null!==i.body&&Symbol.asyncIterator in i.body,l={signal:n.signal,...c?{duplex:"half"}:{},method:"GET",...i};a&&(l.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(o)}}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,r,n){let s;const a=n?.get("retry-after-ms");if(a){const e=parseFloat(a);Number.isNaN(e)||(s=e)}const i=n?.get("retry-after");if(i&&!s){const e=parseFloat(i);s=Number.isNaN(e)?Date.parse(i)-Date.now():1e3*e}if(!(s&&0<=s&&s<6e4)){const r=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,r)}var o;return await(o=s,new Promise((e=>setTimeout(e,o)))),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){const r=t-e;return Math.min(.5*Math.pow(2,r),8)*(1-.25*Math.random())*1e3}buildRequest(e,{retryCount:t=0}={}){const r={...e},{method:n,path:s,query:a}=r,i=this.buildURL(s,a);"timeout"in r&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new Um(`${e} must be an integer`);if(t<0)throw new Um(`${e} must be a positive integer`)})("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:o,body:c}=this.buildBody({options:r});return{req:{method:n,headers:this.buildHeaders({options:e,method:n,bodyHeaders:o,retryCount:t}),...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&c instanceof globalThis.ReadableStream&&{duplex:"half"},...c&&{body:c},...this.fetchOptions??{},...r.fetchOptions??{}},url:i,timeout:r.timeout}}buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let s={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);const a=Zf([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...gf??(gf=pf()),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=Zf([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&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}:"object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)?{bodyHeaders:void 0,body:bf(e)}:Lm(this,cy,"f").call(this,{body:e,headers:r})}}oy=ly,cy=new WeakMap,ly.Anthropic=oy,ly.HUMAN_PROMPT="\n\nHuman:",ly.AI_PROMPT="\n\nAssistant:",ly.DEFAULT_TIMEOUT=6e5,ly.AnthropicError=Um,ly.APIError=Bm,ly.APIConnectionError=Km,ly.APIConnectionTimeoutError=Wm,ly.APIUserAbortError=qm,ly.NotFoundError=Jm,ly.ConflictError=Zm,ly.RateLimitError=Xm,ly.BadRequestError=Hm,ly.AuthenticationError=Vm,ly.InternalServerError=Qm,ly.PermissionDeniedError=Gm,ly.UnprocessableEntityError=Ym,ly.toFile=async function(e,t,r){if(zf(),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&Kf(e))(e=await e))return e instanceof File?e:Uf([await e.arrayBuffer()],e.name);if((e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob)(e)){const n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Uf(await Wf(n),t,r)}const n=await Wf(e);if(t||(t=Bf(e)),!r?.type){const e=n.find((e=>"object"==typeof e&&"type"in e&&e.type));"string"==typeof e&&(r={...r,type:e})}return Uf(n,t,r)};class uy extends ly{constructor(){super(...arguments),this.completions=new Ig(this),this.messages=new ny(this),this.models=new ay(this),this.beta=new Ag(this)}}uy.Completions=Ig,uy.Messages=ny,uy.Models=ay,uy.Beta=Ag;const{HUMAN_PROMPT:dy,AI_PROMPT:hy}=uy;M.z.object({llm:M.z.literal("claude"),apiKey:M.z.string(),modelName:M.z.string().optional(),baseURL:M.z.string().default("http://llm.nxtscape.ai"),options:M.z.record(M.z.unknown()).optional()});class py{constructor(e,t,r){if(this.defaultModel="claude-3-7-sonnet",this.defaultBaseURL="http://llm.nxtscape.ai",t&&(this.defaultModel=t),"string"==typeof e)this.client=new uy({apiKey:e,baseURL:this.defaultBaseURL,dangerouslyAllowBrowser:!0,...r});else if(e.messages&&e.completions)this.client=e;else{const t=e;t.dangerouslyAllowBrowser=!0,t.baseURL||(t.baseURL=this.defaultBaseURL),this.client=new uy(t)}}processResponse(e){const t=e.content.filter((e=>"tool_use"===e.type)).map((e=>({id:e.id,name:e.name,input:e.input})));return{textContent:e.content.filter((e=>"text"===e.type)).map((e=>e.text)).join("\n")||null,content:e.content,toolCalls:t,stop_reason:e.stop_reason}}async generateText(e,t){const r=this.extractSystemMessage(e),n=t.toolChoice,s=await this.client.messages.create({system:r,model:t.model||this.defaultModel,max_tokens:t.maxTokens||1024,temperature:t.temperature,messages:this.convertToAnthropicMessages(e),tools:t.tools,tool_choice:n});return this.processResponse(s)}async generateStream(e,t,r){const n=this.extractSystemMessage(e),s=t.toolChoice,a=await this.client.messages.stream({system:n,model:t.model||this.defaultModel,max_tokens:t.maxTokens||4096,temperature:t.temperature,messages:this.convertToAnthropicMessages(e),tools:t.tools,tool_choice:s});r.onStart?.();let i=null;try{for await(const e of a)switch(e.type){case"content_block_start":"text"===e.content_block.type?r.onContent?.(""):"tool_use"===e.content_block.type&&(i={id:e.content_block.id,name:e.content_block.name,accumulatedJson:""});break;case"content_block_delta":"text_delta"===e.delta.type?r.onContent?.(e.delta.text):"input_json_delta"===e.delta.type&&i&&(i.accumulatedJson+=e.delta.partial_json);break;case"content_block_stop":if(i){try{const e=JSON.parse(i.accumulatedJson);r.onToolCall?.({id:i.id,name:i.name,input:e})}catch(e){console.error("Failed to parse tool use JSON:",e)}i=null}break;case"message_stop":r.onEnd?.()}}catch(e){r.onError?.(e)}}extractSystemMessage(e){return e.filter((e=>"system"===e.role)).map((e=>"string"==typeof e.content?e.content:e.content[0].text))[0]||""}convertToAnthropicMessages(e){return e.filter((e=>"system"!==e.role)).map((e=>{const t="tool"===e.role?"assistant":e.role;return"user"!==t&&"assistant"!==t?(console.warn(`Unsupported message role ${e.role} for Anthropic API, defaulting to 'user'`),{role:"user",content:(e.content,e.content)}):{role:t,content:e.content}}))}async generateStructured(e,t,r){const n=(0,Nt.Ik)(e,{target:"openApi3"}),s=JSON.stringify(n,null,2);let a=r?.systemPrompt||"You are a helpful assistant that generates structured data based on user requests. Follow the user's instructions carefully and output valid JSON data according to the schema.";a+=`\n\nYou must respond with a valid JSON object conforming to this schema:\n${s}\nOnly output the JSON object and nothing else. No explanations, no markdown formatting, just pure JSON.`;const i=await this.client.messages.create({model:r?.model||this.defaultModel,system:a,max_tokens:r?.maxTokens||1024,temperature:r?.temperature??.2,messages:[{role:"user",content:`${t}\n\nRespond only with a valid JSON object according to the schema. No explanations.`}]});try{const t=i.content.filter((e=>"text"===e.type)).map((e=>e.text)).join("\n"),r=t.match(/```json\n([\s\S]*?)\n```/)||t.match(/```\n([\s\S]*?)\n```/)||t.match(/\{[\s\S]*\}/),n=(r?r[0]:t).replace(/```json\n/g,"").replace(/```\n/g,"").replace(/```/g,"").trim(),s=JSON.parse(n);return e.parse(s)}catch(e){throw new Error(`Failed to generate valid structured data: ${e}`)}}}const my="RFC3986",fy={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:e=>String(e)},gy=(Object.prototype.hasOwnProperty,Array.isArray),yy=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();const by=1024;function wy(e,t){if(gy(e)){const r=[];for(let n=0;nString(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},ky=Array.isArray,Sy=Array.prototype.push,Ey=function(e,t){Sy.apply(e,ky(t)?t:[t])},xy=Date.prototype.toISOString,Ty={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,r,n,s)=>{if(0===e.length)return e;let a=e;if("symbol"==typeof e?a=Symbol.prototype.toString.call(e):"string"!=typeof e&&(a=String(e)),"iso-8859-1"===r)return escape(a).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));let i="";for(let e=0;e=by?a.slice(e,e+by):a,r=[];for(let e=0;e=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||"RFC1738"===s&&(40===n||41===n)?r[r.length]=t.charAt(e):n<128?r[r.length]=yy[n]:n<2048?r[r.length]=yy[192|n>>6]+yy[128|63&n]:n<55296||n>=57344?r[r.length]=yy[224|n>>12]+yy[128|n>>6&63]+yy[128|63&n]:(e+=1,n=65536+((1023&n)<<10|1023&t.charCodeAt(e)),r[r.length]=yy[240|n>>18]+yy[128|n>>12&63]+yy[128|n>>6&63]+yy[128|63&n])}i+=r.join("")}return i},encodeValuesOnly:!1,format:my,formatter:fy[my],indices:!1,serializeDate:e=>xy.call(e),skipNulls:!1,strictNullHandling:!1};const Cy={};function Py(e,t,r,n,s,a,i,o,c,l,u,d,h,p,m,f,g,y){let b=e,w=y,v=0,_=!1;for(;void 0!==(w=w.get(Cy))&&!_;){const t=w.get(e);if(v+=1,void 0!==t){if(t===v)throw new RangeError("Cyclic object value");_=!0}void 0===w.get(Cy)&&(v=0)}if("function"==typeof l?b=l(t,b):b instanceof Date?b=h?.(b):"comma"===r&&ky(b)&&(b=wy(b,(function(e){return e instanceof Date?h?.(e):e}))),null===b){if(a)return c&&!f?c(t,Ty.encoder,g,"key",p):t;b=""}if("string"==typeof(k=b)||"number"==typeof k||"boolean"==typeof k||"symbol"==typeof k||"bigint"==typeof k||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(b)){if(c){const e=f?t:c(t,Ty.encoder,g,"key",p);return[m?.(e)+"="+m?.(c(b,Ty.encoder,g,"value",p))]}return[m?.(t)+"="+m?.(String(b))]}var k;const S=[];if(void 0===b)return S;let E;if("comma"===r&&ky(b))f&&c&&(b=wy(b,c)),E=[{value:b.length>0?b.join(",")||null:void 0}];else if(ky(l))E=l;else{const e=Object.keys(b);E=u?e.sort(u):e}const x=o?String(t).replace(/\./g,"%2E"):String(t),T=n&&ky(b)&&1===b.length?x+"[]":x;if(s&&ky(b)&&0===b.length)return T+"[]";for(let t=0;t0?d+u:""}const Ay="4.98.0";let Iy,My,Ry,jy,Ny,$y,Ly,Fy,Dy,zy=!1,Uy=null,By=null,qy=null,Ky=null;class Wy{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}const Hy=()=>{Iy||function(e,t={auto:!1}){if(zy)throw new Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`);if(Iy)throw new Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${Iy}'\``);zy=t.auto,Iy=e.kind,My=e.fetch,Uy=e.Request,By=e.Response,qy=e.Headers,Ry=e.FormData,Ky=e.Blob,jy=e.File,Ny=e.ReadableStream,$y=e.getMultipartRequestOptions,Ly=e.getDefaultAgent,Fy=e.fileFromPath,Dy=e.isFsReadStream}(function({manuallyImported:e}={}){const t=e?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let r,n,s,a;try{r=fetch,n=Request,s=Response,a=Headers}catch(e){throw new Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${t}`)}return{kind:"web",fetch:r,Request:n,Response:s,Headers:a,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new Wy(e)}),getDefaultAgent:e=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:e=>!1}}(),{auto:!0})};Hy();class Vy extends Error{}class Gy extends Vy{constructor(e,t,r,n){super(`${Gy.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.request_id=n?.["x-request-id"],this.error=t;const s=t;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(e,t,r){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new Zy({message:r,cause:Zb(t)});const s=t?.error;return 400===e?new Xy(e,s,r,n):401===e?new Qy(e,s,r,n):403===e?new eb(e,s,r,n):404===e?new tb(e,s,r,n):409===e?new rb(e,s,r,n):422===e?new nb(e,s,r,n):429===e?new sb(e,s,r,n):e>=500?new ab(e,s,r,n):new Gy(e,s,r,n)}}class Jy extends Gy{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Zy extends Gy{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Yy extends Zy{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Xy extends Gy{}class Qy extends Gy{}class eb extends Gy{}class tb extends Gy{}class rb extends Gy{}class nb extends Gy{}class sb extends Gy{}class ab extends Gy{}class ib extends Vy{constructor(){super("Could not parse response content as the length limit was reached")}}class ob extends Vy{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var cb,lb=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},ub=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class db{constructor(){cb.set(this,void 0),this.buffer=new Uint8Array,lb(this,cb,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?(new TextEncoder).encode(e):e;let r=new Uint8Array(this.buffer.length+t.length);r.set(this.buffer),r.set(t,this.buffer.length),this.buffer=r;const n=[];let s;for(;null!=(s=hb(this.buffer,ub(this,cb,"f")));){if(s.carriage&&null==ub(this,cb,"f")){lb(this,cb,s.index,"f");continue}if(null!=ub(this,cb,"f")&&(s.index!==ub(this,cb,"f")+1||s.carriage)){n.push(this.decodeText(this.buffer.slice(0,ub(this,cb,"f")-1))),this.buffer=this.buffer.slice(ub(this,cb,"f")),lb(this,cb,null,"f");continue}const e=null!==ub(this,cb,"f")?s.preceding-1:s.preceding,t=this.decodeText(this.buffer.slice(0,e));n.push(t),this.buffer=this.buffer.slice(s.index),lb(this,cb,null,"f")}return n}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof Buffer){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new Vy(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new Vy(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new Vy("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode("\n"):[]}}function hb(e,t){for(let r=t??0;r0&&(yield t)}(s))for(const t of n.decode(e)){const e=r.decode(t);e&&(yield e)}for(const e of n.flush()){const t=r.decode(e);t&&(yield t)}}(e,t))if(!n)if(r.data.startsWith("[DONE]"))n=!0;else if(null===r.event||r.event.startsWith("response.")||r.event.startsWith("transcript.")){let t;try{t=JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if(t&&t.error)throw new Gy(void 0,t.error,void 0,Lb(e.headers));yield t}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if("error"==r.event)throw new Gy(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}}),t)}static fromReadableStream(e,t){let r=!1;return new fb((async function*(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let n=!1;try{for await(const t of async function*(){const t=new db,r=mb(e);for await(const e of r)for(const r of t.decode(e))yield r;for(const e of t.flush())yield e}())n||t&&(yield JSON.parse(t));n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}}),t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],r=this.iterator(),n=n=>({next:()=>{if(0===n.length){const n=r.next();e.push(n),t.push(n)}return n.shift()}});return[new fb((()=>n(e)),this.controller),new fb((()=>n(t)),this.controller)]}toReadableStream(){const e=this;let t;const r=new TextEncoder;return new Ny({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:n,done:s}=await t.next();if(s)return e.close();const a=r.encode(JSON.stringify(n)+"\n");e.enqueue(a)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class gb{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 e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=function(e,t){const r=e.indexOf(t);if(-1!==r)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}const yb=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,bb=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&wb(e),wb=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer,vb=e=>bb(e)||yb(e)||Dy(e);async function _b(e,t,r){if(e=await e,bb(e))return e;if(yb(e)){const n=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");const s=wb(n)?[await n.arrayBuffer()]:[n];return new jy(s,t,r)}const n=await async function(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(wb(e))t.push(await e.arrayBuffer());else{if(!Sb(e))throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${function(e){const t=Object.getOwnPropertyNames(e);return`[${t.map((e=>`"${e}"`)).join(", ")}]`}(e)}`);for await(const r of e)t.push(r)}return t}(e);if(t||(t=function(e){return kb(e.name)||kb(e.filename)||kb(e.path)?.split(/[\\/]/).pop()}(e)??"unknown_file"),!r?.type){const e=n[0]?.type;"string"==typeof e&&(r={...r,type:e})}return new jy(n,t,r)}const kb=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,Sb=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],Eb=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],xb=async e=>{const t=await Tb(e.body);return $y(t,e)},Tb=async e=>{const t=new Ry;return await Promise.all(Object.entries(e||{}).map((([e,r])=>Cb(t,e,r)))),t},Cb=async(e,t,r)=>{if(void 0!==r){if(null==r)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof r||"number"==typeof r||"boolean"==typeof r)e.append(t,String(r));else if(vb(r)){const n=await _b(r);e.append(t,n)}else if(Array.isArray(r))await Promise.all(r.map((r=>Cb(e,t+"[]",r))));else{if("object"!=typeof r)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`);await Promise.all(Object.entries(r).map((([r,n])=>Cb(e,`${t}[${r}]`,n))))}}};var Pb,Ob=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},Ab=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};async function Ib(e){const{response:t}=e;if(e.options.stream)return rw("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):fb.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;const r=t.headers.get("content-type"),n=r?.split(";")[0]?.trim();if(n?.includes("application/json")||n?.endsWith("+json")){const e=await t.json();return rw("response",t.status,t.url,t.headers,e),Mb(e,t)}const s=await t.text();return rw("response",t.status,t.url,t.headers,s),s}function Mb(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}Hy();class Rb extends Promise{constructor(e,t=Ib){super((e=>{e(null)})),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new Rb(this.responsePromise,(async t=>Mb(e(await this.parseResponse(t),t),t.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(this.parseResponse)),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)}}class jb{constructor({baseURL:e,maxRetries:t=2,timeout:r=6e5,httpAgent:n,fetch:s}){this.baseURL=e,this.maxRetries=Jb("maxRetries",t),this.timeout=Jb("timeout",r),this.httpAgent=n,this.fetch=s??My}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Kb(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${nw()}`}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((async r=>{const n=r&&wb(r?.body)?new DataView(await r.body.arrayBuffer()):r?.body instanceof DataView?r.body:r?.body instanceof ArrayBuffer?new DataView(r.body):r&&ArrayBuffer.isView(r?.body)?new DataView(r.body.buffer):r?.body;return{method:e,path:t,...r,body:n}})))}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}calculateContentLength(e){if("string"==typeof e){if("undefined"!=typeof Buffer)return Buffer.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder){return(new TextEncoder).encode(e).length.toString()}}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){const r={...e},{method:n,path:s,query:a,headers:i={}}=r,o=ArrayBuffer.isView(r.body)||r.__binaryRequest&&"string"==typeof r.body?r.body:Eb(r.body)?r.body.body:r.body?JSON.stringify(r.body,null,2):null,c=this.calculateContentLength(o),l=this.buildURL(s,a);"timeout"in r&&Jb("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const u=r.httpAgent??this.httpAgent??Ly(l),d=r.timeout+1e3;"number"==typeof u?.options?.timeout&&d>(u.options.timeout??0)&&(u.options.timeout=d),this.idempotencyHeader&&"get"!==n&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);return{req:{method:n,...o&&{body:o},headers:this.buildHeaders({options:r,headers:i,contentLength:c,retryCount:t}),...u&&{agent:u},signal:r.signal??null},url:l,timeout:r.timeout}}buildHeaders({options:e,headers:t,contentLength:r,retryCount:n}){const s={};r&&(s["content-length"]=r);const a=this.defaultHeaders(e);return ew(s,a),ew(s,t),Eb(e.body)&&"node"!==Iy&&delete s["content-type"],void 0===sw(a,"x-stainless-retry-count")&&void 0===sw(t,"x-stainless-retry-count")&&(s["x-stainless-retry-count"]=String(n)),void 0===sw(a,"x-stainless-timeout")&&void 0===sw(t,"x-stainless-timeout")&&e.timeout&&(s["x-stainless-timeout"]=String(Math.trunc(e.timeout/1e3))),this.validateHeaders(s,t),s}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map((e=>[...e]))):{...e}:{}}makeStatusError(e,t,r,n){return Gy.generate(e,t,r,n)}request(e,t=null){return new Rb(this.makeRequest(e,t))}async makeRequest(e,t){const r=await e,n=r.maxRetries??this.maxRetries;null==t&&(t=n),await this.prepareOptions(r);const{req:s,url:a,timeout:i}=this.buildRequest(r,{retryCount:n-t});if(await this.prepareRequest(s,{url:a,options:r}),rw("request",a,r,s.headers),r.signal?.aborted)throw new Jy;const o=new AbortController,c=await this.fetchWithTimeout(a,s,i,o).catch(Zb);if(c instanceof Error){if(r.signal?.aborted)throw new Jy;if(t)return this.retryRequest(r,t);if("AbortError"===c.name)throw new Yy;throw new Zy({cause:c})}const l=Lb(c.headers);if(!c.ok){if(t&&this.shouldRetry(c)){return rw(`response (error; ${`retrying, ${t} attempts remaining`})`,c.status,a,l),this.retryRequest(r,t,l)}const e=await c.text().catch((e=>Zb(e).message)),n=Wb(e),s=n?void 0:e;rw(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,c.status,a,l,s);throw this.makeStatusError(c.status,n,s,l)}return{response:c,options:r,controller:o}}requestAPIList(e,t){const r=this.makeRequest(t,null);return new $b(this,r,e)}buildURL(e,t){const r=Vb(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return Xb(n)||(t={...n,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}stringifyQuery(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new Vy(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)})).join("&")}async fetchWithTimeout(e,t,r,n){const{signal:s,...a}=t||{};s&&s.addEventListener("abort",(()=>n.abort()));const i=setTimeout((()=>n.abort()),r),o={signal:n.signal,...a};return o.method&&(o.method=o.method.toUpperCase()),this.fetch.call(void 0,e,o).finally((()=>{clearTimeout(i)}))}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,r){let n;const s=r?.["retry-after-ms"];if(s){const e=parseFloat(s);Number.isNaN(e)||(n=e)}const a=r?.["retry-after"];if(a&&!n){const e=parseFloat(a);n=Number.isNaN(e)?Date.parse(a)-Date.now():1e3*e}if(!(n&&0<=n&&n<6e4)){const r=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,r)}return await Gb(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const r=t-e;return Math.min(.5*Math.pow(2,r),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${Ay}`}}class Nb{constructor(e,t,r,n){Pb.set(this,void 0),Ob(this,Pb,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new Vy("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&"object"==typeof t.query)t.query={...t.query,...e.params};else if("url"in e){const r=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[t,n]of r)e.url.searchParams.set(t,n);t.query=void 0,t.path=e.url.toString()}return await Ab(this,Pb,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Pb=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class $b extends Rb{constructor(e,t,r){super(t,(async t=>new r(e,t.response,await Ib(t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const Lb=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const r=t.toString();return e[r.toLowerCase()]||e[r]}}),Fb={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},Db=e=>"object"==typeof e&&null!==e&&!Xb(e)&&Object.keys(e).every((e=>Qb(Fb,e))),zb=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ay,"X-Stainless-OS":Bb(Deno.build.os),"X-Stainless-Arch":Ub(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ay,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ay,"X-Stainless-OS":Bb(process.platform),"X-Stainless-Arch":Ub(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const e=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{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:t,pattern:r}of e){const e=r.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ay,"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":Ay,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const Ub=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",Bb=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let qb;const Kb=()=>qb??(qb=zb()),Wb=e=>{try{return JSON.parse(e)}catch(e){return}},Hb=/^[a-z][a-z0-9+.-]*:/i,Vb=e=>Hb.test(e),Gb=e=>new Promise((t=>setTimeout(t,e))),Jb=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new Vy(`${e} must be an integer`);if(t<0)throw new Vy(`${e} must be a positive integer`);return t},Zb=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e)try{return new Error(JSON.stringify(e))}catch{}return new Error(e)},Yb=e=>"undefined"!=typeof process?process.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function Xb(e){if(!e)return!0;for(const t in e)return!1;return!0}function Qb(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ew(e,t){for(const r in t){if(!Qb(t,r))continue;const n=r.toLowerCase();if(!n)continue;const s=t[r];null===s?delete e[n]:void 0!==s&&(e[n]=s)}}const tw=new Set(["authorization","api-key"]);function rw(e,...t){if("undefined"!=typeof process&&"true"===process?.env?.DEBUG){const r=t.map((e=>{if(!e)return e;if(e.headers){const t={...e,headers:{...e.headers}};for(const r in e.headers)tw.has(r.toLowerCase())&&(t.headers[r]="REDACTED");return t}let t=null;for(const r in e)tw.has(r.toLowerCase())&&(t??(t={...e}),t[r]="REDACTED");return t??e}));console.log(`OpenAI:DEBUG:${e}`,...r)}}const nw=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),sw=(e,t)=>{const r=t.toLowerCase();if((e=>"function"==typeof e?.get)(e)){const n=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,((e,t,r)=>t+r.toUpperCase()));for(const s of[t,r,t.toUpperCase(),n]){const t=e.get(s);if(t)return t}}for(const[n,s]of Object.entries(e))if(n.toLowerCase()===r)return Array.isArray(s)?(s.length<=1||console.warn(`Received ${s.length} entries for the ${t} header, using the first entry.`),s[0]):s};function aw(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}class iw{constructor(e){this._client=e}}class ow extends iw{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class cw extends iw{list(e,t={},r){return Db(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,pw,{query:t,...r})}}class lw extends Nb{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class uw extends Nb{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){const e=this.getPaginatedItems();if(!e.length)return null;const t=e[e.length-1]?.id;return t?{params:{after:t}}:null}}class dw extends iw{constructor(){super(...arguments),this.messages=new cw(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(`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return Db(e)?this.list({},e):this._client.getAPIList("/chat/completions",hw,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}}class hw extends uw{}class pw extends uw{}dw.ChatCompletionsPage=hw,dw.Messages=cw;class mw extends iw{constructor(){super(...arguments),this.completions=new dw(this._client)}}mw.Completions=dw,mw.ChatCompletionsPage=hw;class fw extends iw{create(e,t){const r=!!e.encoding_format;let n=r?e.encoding_format:"base64";r&&rw("Request","User defined encoding_format:",e.encoding_format);const s=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return r?s:(rw("response","Decoding base64 embeddings to float32 array"),s._thenUnwrap((e=>(e&&e.data&&e.data.forEach((e=>{const t=e.embedding;e.embedding=(e=>{if("undefined"!=typeof Buffer){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{const t=atob(e),r=t.length,n=new Uint8Array(r);for(let e=0;er)throw new Yy({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return a}}class yw extends uw{}gw.FileObjectsPage=yw;class bw extends iw{createVariation(e,t){return this._client.post("/images/variations",xb({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",xb({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class ww extends iw{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t?.headers},__binaryResponse:!0})}}class vw extends iw{create(e,t){return this._client.post("/audio/transcriptions",xb({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class _w extends iw{create(e,t){return this._client.post("/audio/translations",xb({body:e,...t,__metadata:{model:e.model}}))}}class kw extends iw{constructor(){super(...arguments),this.transcriptions=new vw(this._client),this.translations=new _w(this._client),this.speech=new ww(this._client)}}kw.Transcriptions=vw,kw.Translations=_w,kw.Speech=ww;class Sw extends iw{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class Ew extends iw{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",xw,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class xw extends lw{}Ew.ModelsPage=xw;class Tw extends iw{}class Cw extends iw{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 Pw extends iw{constructor(){super(...arguments),this.graders=new Cw(this._client)}}Pw.Graders=Cw;class Ow extends iw{create(e,t,r){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,Aw,{body:t,method:"post",...r})}retrieve(e,t={},r){return Db(t)?this.retrieve(e,{},t):this._client.get(`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}del(e,t,r){return this._client.delete(`/fine_tuning/checkpoints/${e}/permissions/${t}`,r)}}class Aw extends lw{}Ow.PermissionCreateResponsesPage=Aw;class Iw extends iw{constructor(){super(...arguments),this.permissions=new Ow(this._client)}}Iw.Permissions=Ow,Iw.PermissionCreateResponsesPage=Aw;class Mw extends iw{list(e,t={},r){return Db(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,Rw,{query:t,...r})}}class Rw extends uw{}Mw.FineTuningJobCheckpointsPage=Rw;class jw extends iw{constructor(){super(...arguments),this.checkpoints=new Mw(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return Db(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",Nw,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return Db(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,$w,{query:t,...r})}pause(e,t){return this._client.post(`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(`/fine_tuning/jobs/${e}/resume`,t)}}class Nw extends uw{}class $w extends uw{}jw.FineTuningJobsPage=Nw,jw.FineTuningJobEventsPage=$w,jw.Checkpoints=Mw,jw.FineTuningJobCheckpointsPage=Rw;class Lw extends iw{constructor(){super(...arguments),this.methods=new Tw(this._client),this.jobs=new jw(this._client),this.checkpoints=new Iw(this._client),this.alpha=new Pw(this._client)}}Lw.Methods=Tw,Lw.Jobs=jw,Lw.FineTuningJobsPage=Nw,Lw.FineTuningJobEventsPage=$w,Lw.Checkpoints=Iw,Lw.Alpha=Pw;class Fw extends iw{}class Dw extends iw{constructor(){super(...arguments),this.graderModels=new Fw(this._client)}}Dw.GraderModels=Fw;class zw extends iw{create(e,t,r){return this._client.post(`/vector_stores/${e}/files`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/vector_stores/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}update(e,t,r,n){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},r){return Db(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,Uw,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}del(e,t,r){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){const n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){const n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){const s=await this.retrieve(e,t,{...r,headers:n}).withResponse(),a=s.data;switch(a.status){case"in_progress":let e=5e3;if(r?.pollIntervalMs)e=r.pollIntervalMs;else{const t=s.response.headers.get("openai-poll-after-ms");if(t){const r=parseInt(t);isNaN(r)||(e=r)}}await Gb(e);break;case"failed":case"completed":return a}}}async upload(e,t,r){const n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){const n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){return this._client.getAPIList(`/vector_stores/${e}/files/${t}/content`,Bw,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}}class Uw extends uw{}class Bw extends lw{}zw.VectorStoreFilesPage=Uw,zw.FileContentResponsesPage=Bw;class qw extends iw{create(e,t,r){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}cancel(e,t,r){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){const n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r={},n){return Db(r)?this.listFiles(e,t,{},r):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,Uw,{query:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async poll(e,t,r){const n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){const{data:s,response:a}=await this.retrieve(e,t,{...r,headers:n}).withResponse();switch(s.status){case"in_progress":let e=5e3;if(r?.pollIntervalMs)e=r.pollIntervalMs;else{const t=a.headers.get("openai-poll-after-ms");if(t){const r=parseInt(t);isNaN(r)||(e=r)}}await Gb(e);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){if(null==t||0==t.length)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const s=n?.maxConcurrency??5,a=Math.min(s,t.length),i=this._client,o=t.values(),c=[...r];const l=Array(a).fill(o).map((async function(e){for(let t of e){const e=await i.files.create({file:t,purpose:"assistants"},n);c.push(e.id)}}));return await(async e=>{const t=await Promise.allSettled(e),r=t.filter((e=>"rejected"===e.status));if(r.length){for(const e of r)console.error(e.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}const n=[];for(const e of t)"fulfilled"===e.status&&n.push(e.value);return n})(l),await this.createAndPoll(e,{file_ids:c})}}class Kw extends iw{constructor(){super(...arguments),this.files=new zw(this._client),this.fileBatches=new qw(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,r){return this._client.post(`/vector_stores/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e={},t){return Db(e)?this.list({},e):this._client.getAPIList("/vector_stores",Ww,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}search(e,t,r){return this._client.getAPIList(`/vector_stores/${e}/search`,Hw,{body:t,method:"post",...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}}class Ww extends uw{}class Hw extends lw{}Kw.VectorStoresPage=Ww,Kw.VectorStoreSearchResponsesPage=Hw,Kw.Files=zw,Kw.VectorStoreFilesPage=Uw,Kw.FileContentResponsesPage=Bw,Kw.FileBatches=qw;class Vw extends iw{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,r){return this._client.post(`/assistants/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e={},t){return Db(e)?this.list({},e):this._client.getAPIList("/assistants",Gw,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class Gw extends uw{}function Jw(e){return"function"==typeof e.parse}Vw.AssistantsPage=Gw;const Zw=e=>"assistant"===e?.role,Yw=e=>"function"===e?.role,Xw=e=>"tool"===e?.role;var Qw,ev,tv,rv,nv,sv,av,iv,ov,cv,lv,uv,dv,hv=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},pv=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class mv{constructor(){Qw.add(this),this.controller=new AbortController,ev.set(this,void 0),tv.set(this,(()=>{})),rv.set(this,(()=>{})),nv.set(this,void 0),sv.set(this,(()=>{})),av.set(this,(()=>{})),iv.set(this,{}),ov.set(this,!1),cv.set(this,!1),lv.set(this,!1),uv.set(this,!1),hv(this,ev,new Promise(((e,t)=>{hv(this,tv,e,"f"),hv(this,rv,t,"f")})),"f"),hv(this,nv,new Promise(((e,t)=>{hv(this,sv,e,"f"),hv(this,av,t,"f")})),"f"),pv(this,ev,"f").catch((()=>{})),pv(this,nv,"f").catch((()=>{}))}_run(e){setTimeout((()=>{e().then((()=>{this._emitFinal(),this._emit("end")}),pv(this,Qw,"m",dv).bind(this))}),0)}_connected(){this.ended||(pv(this,tv,"f").call(this),this._emit("connect"))}get ended(){return pv(this,ov,"f")}get errored(){return pv(this,cv,"f")}get aborted(){return pv(this,lv,"f")}abort(){this.controller.abort()}on(e,t){return(pv(this,iv,"f")[e]||(pv(this,iv,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=pv(this,iv,"f")[e];if(!r)return this;const n=r.findIndex((e=>e.listener===t));return n>=0&&r.splice(n,1),this}once(e,t){return(pv(this,iv,"f")[e]||(pv(this,iv,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,r)=>{hv(this,uv,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)}))}async done(){hv(this,uv,!0,"f"),await pv(this,nv,"f")}_emit(e,...t){if(pv(this,ov,"f"))return;"end"===e&&(hv(this,ov,!0,"f"),pv(this,sv,"f").call(this));const r=pv(this,iv,"f")[e];if(r&&(pv(this,iv,"f")[e]=r.filter((e=>!e.once)),r.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return pv(this,uv,"f")||r?.length||Promise.reject(e),pv(this,rv,"f").call(this,e),pv(this,av,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];pv(this,uv,"f")||r?.length||Promise.reject(e),pv(this,rv,"f").call(this,e),pv(this,av,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function fv(e){return"auto-parseable-response-format"===e?.$brand}function gv(e){return"auto-parseable-tool"===e?.$brand}function yv(e,t){const r=e.choices.map((e=>{if("length"===e.finish_reason)throw new ib;if("content_filter"===e.finish_reason)throw new ob;return{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map((e=>function(e,t){const r=e.tools?.find((e=>e.function?.name===t.function.name));return{...t,function:{...t.function,parsed_arguments:gv(r)?r.$parseRaw(t.function.arguments):r?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e)))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?bv(t,e.message.content):null}}}));return{...e,choices:r}}function bv(e,t){if("json_schema"!==e.response_format?.type)return null;if("json_schema"===e.response_format?.type){if("$parseRaw"in e.response_format){return e.response_format.$parseRaw(t)}return JSON.parse(t)}return null}function wv(e,t){if(!e)return!1;const r=e.tools?.find((e=>e.function?.name===t.function.name));return gv(r)||r?.function.strict||!1}function vv(e){return!!fv(e.response_format)||(e.tools?.some((e=>gv(e)||"function"===e.type&&!0===e.function.strict))??!1)}ev=new WeakMap,tv=new WeakMap,rv=new WeakMap,nv=new WeakMap,sv=new WeakMap,av=new WeakMap,iv=new WeakMap,ov=new WeakMap,cv=new WeakMap,lv=new WeakMap,uv=new WeakMap,Qw=new WeakSet,dv=function(e){if(hv(this,cv,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new Jy),e instanceof Jy)return hv(this,lv,!0,"f"),this._emit("abort",e);if(e instanceof Vy)return this._emit("error",e);if(e instanceof Error){const t=new Vy(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Vy(String(e)))};var _v,kv,Sv,Ev,xv,Tv,Cv,Pv,Ov=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};const Av=10;class Iv extends mv{constructor(){super(...arguments),_v.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t)if(this._emit("message",e),(Yw(e)||Xw(e))&&e.content)this._emit("functionCallResult",e.content);else if(Zw(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(Zw(e)&&e.tool_calls)for(const t of e.tool_calls)"function"===t.type&&this._emit("functionCall",t.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new Vy("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),Ov(this,_v,"m",kv).call(this)}async finalMessage(){return await this.done(),Ov(this,_v,"m",Sv).call(this)}async finalFunctionCall(){return await this.done(),Ov(this,_v,"m",Ev).call(this)}async finalFunctionCallResult(){return await this.done(),Ov(this,_v,"m",xv).call(this)}async totalUsage(){return await this.done(),Ov(this,_v,"m",Tv).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=Ov(this,_v,"m",Sv).call(this);t&&this._emit("finalMessage",t);const r=Ov(this,_v,"m",kv).call(this);r&&this._emit("finalContent",r);const n=Ov(this,_v,"m",Ev).call(this);n&&this._emit("finalFunctionCall",n);const s=Ov(this,_v,"m",xv).call(this);null!=s&&this._emit("finalFunctionCallResult",s),this._chatCompletions.some((e=>e.usage))&&this._emit("totalUsage",Ov(this,_v,"m",Tv).call(this))}async _createChatCompletion(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),Ov(this,_v,"m",Cv).call(this,t);const s=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(yv(s,t))}async _runChatCompletion(e,t,r){for(const e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,r)}async _runFunctions(e,t,r){const n="function",{function_call:s="auto",stream:a,...i}=t,o="string"!=typeof s&&s?.name,{maxChatCompletions:c=Av}=r||{},l={};for(const e of t.functions)l[e.name||e.function.name]=e;const u=t.functions.map((e=>({name:e.name||e.function.name,parameters:e.parameters,description:e.description})));for(const e of t.messages)this._addMessage(e,!1);for(let t=0;tJSON.stringify(e.name))).join(", ")}. Please try again`;this._addMessage({role:n,name:c,content:e});continue}if(o&&o!==c){const e=`Invalid function_call: ${JSON.stringify(c)}. ${JSON.stringify(o)} requested. Please try again`;this._addMessage({role:n,name:c,content:e});continue}let p;try{p=Jw(h)?await h.parse(d):d}catch(e){this._addMessage({role:n,name:c,content:e instanceof Error?e.message:String(e)});continue}const m=await h.function(p,this),f=Ov(this,_v,"m",Pv).call(this,m);if(this._addMessage({role:n,name:c,content:f}),o)return}}async _runTools(e,t,r){const n="tool",{tool_choice:s="auto",stream:a,...i}=t,o="string"!=typeof s&&s?.function?.name,{maxChatCompletions:c=Av}=r||{},l=t.tools.map((e=>{if(gv(e)){if(!e.$callback)throw new Vy("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e})),u={};for(const e of l)"function"===e.type&&(u[e.function.name||e.function.function.name]=e.function);const d="tools"in t?l.map((e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e)):void 0;for(const e of t.messages)this._addMessage(e,!1);for(let t=0;tJSON.stringify(e))).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}if(o&&o!==r){const e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(o)} requested. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}let i;try{i=Jw(a)?await a.parse(s):s}catch(e){const r=e instanceof Error?e.message:String(e);this._addMessage({role:n,tool_call_id:t,content:r});continue}const c=await a.function(i,this),l=Ov(this,_v,"m",Pv).call(this,c);if(this._addMessage({role:n,tool_call_id:t,content:l}),o)return}}}}_v=new WeakSet,kv=function(){return Ov(this,_v,"m",Sv).call(this).content??null},Sv=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(Zw(t)){const{function_call:e,...r}=t,n={...r,content:t.content??null,refusal:t.refusal??null};return e&&(n.function_call=e),n}}throw new Vy("stream ended without producing a ChatCompletionMessage with role=assistant")},Ev=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Zw(t)&&t?.function_call)return t.function_call;if(Zw(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},xv=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Yw(t)&&null!=t.content)return t.content;if(Xw(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some((e=>"assistant"===e.role&&e.tool_calls?.some((e=>"function"===e.type&&e.id===t.tool_call_id)))))return t.content}},Tv=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},Cv=function(e){if(null!=e.n&&e.n>1)throw new Vy("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Pv=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class Mv extends Iv{static runFunctions(e,t,r){const n=new Mv,s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run((()=>n._runFunctions(e,t,s))),n}static runTools(e,t,r){const n=new Mv,s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run((()=>n._runTools(e,t,s))),n}_addMessage(e,t=!0){super._addMessage(e,t),Zw(e)&&e.content&&this._emit("content",e.content)}}const Rv=1,jv=2,Nv=4,$v=8,Lv=16,Fv=32,Dv=64,zv=128,Uv=256,Bv=511;class qv extends Error{}class Kv extends Error{}const Wv=(e,t)=>{const r=e.length;let n=0;const s=e=>{throw new qv(`${e} at position ${n}`)},a=e=>{throw new Kv(`${e} at position ${n}`)},i=()=>(d(),n>=r&&s("Unexpected end of input"),'"'===e[n]?o():"{"===e[n]?c():"["===e[n]?l():"null"===e.substring(n,n+4)||Lv&t&&r-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):"true"===e.substring(n,n+4)||Fv&t&&r-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):"false"===e.substring(n,n+5)||Fv&t&&r-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):"Infinity"===e.substring(n,n+8)||zv&t&&r-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):"-Infinity"===e.substring(n,n+9)||Uv&t&&1{const i=n;let o=!1;for(n++;n{n++,d();const a={};try{for(;"}"!==e[n];){if(d(),n>=r&&$v&t)return a;const s=o();d(),n++;try{const e=i();Object.defineProperty(a,s,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if($v&t)return a;throw e}d(),","===e[n]&&n++}}catch(e){if($v&t)return a;s("Expected '}' at end of object")}return n++,a},l=()=>{n++;const r=[];try{for(;"]"!==e[n];)r.push(i()),d(),","===e[n]&&n++}catch(e){if(Nv&t)return r;s("Expected ']' at end of array")}return n++,r},u=()=>{if(0===n){"-"===e&&jv&t&&s("Not sure what '-' is");try{return JSON.parse(e)}catch(r){if(jv&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(e){}a(String(r))}}const i=n;for("-"===e[n]&&n++;e[n]&&!",]}".includes(e[n]);)n++;n!=r||jv&t||s("Unterminated number literal");try{return JSON.parse(e.substring(i,n))}catch(r){"-"===e.substring(i,n)&&jv&t&&s("Not sure what '-' is");try{return JSON.parse(e.substring(i,e.lastIndexOf("e")))}catch(e){a(String(e))}}},d=()=>{for(;nfunction(e,t=Bv){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return Wv(e.trim(),t)}(e,Bv^jv);var Vv,Gv,Jv,Zv,Yv,Xv,Qv,e_,t_,r_,n_,s_,a_=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},i_=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class o_ extends Iv{constructor(e){super(),Vv.add(this),Gv.set(this,void 0),Jv.set(this,void 0),Zv.set(this,void 0),a_(this,Gv,e,"f"),a_(this,Jv,[],"f")}get currentChatCompletionSnapshot(){return i_(this,Zv,"f")}static fromReadableStream(e){const t=new o_(null);return t._run((()=>t._fromReadableStream(e))),t}static createChatCompletion(e,t,r){const n=new o_(t);return n._run((()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}async _createChatCompletion(e,t,r){super._createChatCompletion;const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),i_(this,Vv,"m",Yv).call(this);const s=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const e of s)i_(this,Vv,"m",Qv).call(this,e);if(s.controller.signal?.aborted)throw new Jy;return this._addChatCompletion(i_(this,Vv,"m",r_).call(this))}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),i_(this,Vv,"m",Yv).call(this),this._connected();const n=fb.fromReadableStream(e,this.controller);let s;for await(const e of n)s&&s!==e.id&&this._addChatCompletion(i_(this,Vv,"m",r_).call(this)),i_(this,Vv,"m",Qv).call(this,e),s=e.id;if(n.controller.signal?.aborted)throw new Jy;return this._addChatCompletion(i_(this,Vv,"m",r_).call(this))}[(Gv=new WeakMap,Jv=new WeakMap,Zv=new WeakMap,Vv=new WeakSet,Yv=function(){this.ended||a_(this,Zv,void 0,"f")},Xv=function(e){let t=i_(this,Jv,"f")[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},i_(this,Jv,"f")[e.index]=t,t)},Qv=function(e){if(this.ended)return;const t=i_(this,Vv,"m",s_).call(this,e);this._emit("chunk",e,t);for(const r of e.choices){const e=t.choices[r.index];null!=r.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",r.delta.content,e.message.content),this._emit("content.delta",{delta:r.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=r.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:r.delta.refusal,snapshot:e.message.refusal}),null!=r.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:r.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=r.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:r.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const n=i_(this,Vv,"m",Xv).call(this,e);e.finish_reason&&(i_(this,Vv,"m",t_).call(this,e),null!=n.current_tool_call_index&&i_(this,Vv,"m",e_).call(this,e,n.current_tool_call_index));for(const t of r.delta.tool_calls??[])n.current_tool_call_index!==t.index&&(i_(this,Vv,"m",t_).call(this,e),null!=n.current_tool_call_index&&i_(this,Vv,"m",e_).call(this,e,n.current_tool_call_index)),n.current_tool_call_index=t.index;for(const t of r.delta.tool_calls??[]){const r=e.message.tool_calls?.[t.index];r?.type&&("function"===r?.type&&this._emit("tool_calls.function.arguments.delta",{name:r.function?.name,index:t.index,arguments:r.function.arguments,parsed_arguments:r.function.parsed_arguments,arguments_delta:t.function?.arguments??""}))}}},e_=function(e,t){if(i_(this,Vv,"m",Xv).call(this,e).done_tool_calls.has(t))return;const r=e.message.tool_calls?.[t];if(!r)throw new Error("no tool call snapshot");if(!r.type)throw new Error("tool call snapshot missing `type`");if("function"===r.type){const e=i_(this,Gv,"f")?.tools?.find((e=>"function"===e.type&&e.function.name===r.function.name));this._emit("tool_calls.function.arguments.done",{name:r.function.name,index:t,arguments:r.function.arguments,parsed_arguments:gv(e)?e.$parseRaw(r.function.arguments):e?.function.strict?JSON.parse(r.function.arguments):null})}else r.type},t_=function(e){const t=i_(this,Vv,"m",Xv).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const r=i_(this,Vv,"m",n_).call(this);this._emit("content.done",{content:e.message.content,parsed:r?r.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},r_=function(){if(this.ended)throw new Vy("stream has ended, this shouldn't happen");const e=i_(this,Zv,"f");if(!e)throw new Vy("request ended without sending any chunks");return a_(this,Zv,void 0,"f"),a_(this,Jv,[],"f"),function(e,t){const{id:r,choices:n,created:s,model:a,system_fingerprint:i,...o}=e,c={...o,id:r,choices:n.map((({message:t,finish_reason:r,index:n,logprobs:s,...a})=>{if(!r)throw new Vy(`missing finish_reason for choice ${n}`);const{content:i=null,function_call:o,tool_calls:c,...l}=t,u=t.role;if(!u)throw new Vy(`missing role for choice ${n}`);if(o){const{arguments:e,name:c}=o;if(null==e)throw new Vy(`missing function_call.arguments for choice ${n}`);if(!c)throw new Vy(`missing function_call.name for choice ${n}`);return{...a,message:{content:i,function_call:{arguments:e,name:c},role:u,refusal:t.refusal??null},finish_reason:r,index:n,logprobs:s}}return c?{...a,index:n,finish_reason:r,logprobs:s,message:{...l,role:u,content:i,refusal:t.refusal??null,tool_calls:c.map(((t,r)=>{const{function:s,type:a,id:i,...o}=t,{arguments:c,name:l,...u}=s||{};if(null==i)throw new Vy(`missing choices[${n}].tool_calls[${r}].id\n${c_(e)}`);if(null==a)throw new Vy(`missing choices[${n}].tool_calls[${r}].type\n${c_(e)}`);if(null==l)throw new Vy(`missing choices[${n}].tool_calls[${r}].function.name\n${c_(e)}`);if(null==c)throw new Vy(`missing choices[${n}].tool_calls[${r}].function.arguments\n${c_(e)}`);return{...o,id:i,type:a,function:{...u,name:l,arguments:c}}}))}}:{...a,message:{...l,content:i,role:u,refusal:t.refusal??null},finish_reason:r,index:n,logprobs:s}})),created:s,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return function(e,t){return t&&vv(t)?yv(e,t):{...e,choices:e.choices.map((e=>({...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}})))}}(c,t)}(e,i_(this,Gv,"f"))},n_=function(){const e=i_(this,Gv,"f")?.response_format;return fv(e)?e:null},s_=function(e){var t,r,n,s;let a=i_(this,Zv,"f");const{choices:i,...o}=e;a?Object.assign(a,o):a=a_(this,Zv,{...o,choices:[]},"f");for(const{delta:i,finish_reason:o,index:c,logprobs:l=null,...u}of e.choices){let e=a.choices[c];if(e||(e=a.choices[c]={finish_reason:o,index:c,message:{},logprobs:l,...u}),l)if(e.logprobs){const{content:n,refusal:s,...a}=l;Object.assign(e.logprobs,a),n&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...n)),s&&((r=e.logprobs).refusal??(r.refusal=[]),e.logprobs.refusal.push(...s))}else e.logprobs=Object.assign({},l);if(o&&(e.finish_reason=o,i_(this,Gv,"f")&&vv(i_(this,Gv,"f")))){if("length"===o)throw new ib;if("content_filter"===o)throw new ob}if(Object.assign(e,u),!i)continue;const{content:d,refusal:h,function_call:p,role:m,tool_calls:f,...g}=i;if(Object.assign(e.message,g),h&&(e.message.refusal=(e.message.refusal||"")+h),m&&(e.message.role=m),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((n=e.message.function_call).arguments??(n.arguments=""),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),d&&(e.message.content=(e.message.content||"")+d,!e.message.refusal&&i_(this,Vv,"m",n_).call(this)&&(e.message.parsed=Hv(e.message.content))),f){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:r,type:n,function:a,...i}of f){const o=(s=e.message.tool_calls)[t]??(s[t]={});Object.assign(o,i),r&&(o.id=r),n&&(o.type=n),a&&(o.function??(o.function={name:a.name??"",arguments:""})),a?.name&&(o.function.name=a.name),a?.arguments&&(o.function.arguments+=a.arguments,wv(i_(this,Gv,"f"),o)&&(o.function.parsed_arguments=Hv(o.function.arguments)))}}}return a},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("chunk",(r=>{const n=t.shift();n?n.resolve(r):e.push(r)})),this.on("end",(()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),this.on("error",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise(((e,r)=>t.push({resolve:e,reject:r}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new fb(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function c_(e){return JSON.stringify(e)}class l_ extends o_{static fromReadableStream(e){const t=new l_(null);return t._run((()=>t._fromReadableStream(e))),t}static runFunctions(e,t,r){const n=new l_(null),s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run((()=>n._runFunctions(e,t,s))),n}static runTools(e,t,r){const n=new l_(t),s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run((()=>n._runTools(e,t,s))),n}}class u_ extends iw{parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new Vy(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new Vy(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap((t=>yv(t,e)))}runFunctions(e,t){return e.stream?l_.runFunctions(this._client,e,t):Mv.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?l_.runTools(this._client,e,t):Mv.runTools(this._client,e,t)}stream(e,t){return o_.createChatCompletion(this._client,e,t)}}class d_ extends iw{constructor(){super(...arguments),this.completions=new u_(this._client)}}!function(e){e.Completions=u_}(d_||(d_={}));class h_ extends iw{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class p_ extends iw{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class m_ extends iw{constructor(){super(...arguments),this.sessions=new h_(this._client),this.transcriptionSessions=new p_(this._client)}}m_.Sessions=h_,m_.TranscriptionSessions=p_;var f_,g_,y_,b_,w_,v_,__,k_,S_,E_,x_,T_,C_,P_,O_,A_,I_,M_,R_,j_,N_,$_,L_=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)},F_=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r};class D_ extends mv{constructor(){super(...arguments),f_.add(this),g_.set(this,[]),y_.set(this,{}),b_.set(this,{}),w_.set(this,void 0),v_.set(this,void 0),__.set(this,void 0),k_.set(this,void 0),S_.set(this,void 0),E_.set(this,void 0),x_.set(this,void 0),T_.set(this,void 0),C_.set(this,void 0)}[(g_=new WeakMap,y_=new WeakMap,b_=new WeakMap,w_=new WeakMap,v_=new WeakMap,__=new WeakMap,k_=new WeakMap,S_=new WeakMap,E_=new WeakMap,x_=new WeakMap,T_=new WeakMap,C_=new WeakMap,f_=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",(r=>{const n=t.shift();n?n.resolve(r):e.push(r)})),this.on("end",(()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),this.on("error",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise(((e,r)=>t.push({resolve:e,reject:r}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new D_;return t._run((()=>t._fromReadableStream(e))),t}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),this._connected();const n=fb.fromReadableStream(e,this.controller);for await(const e of n)L_(this,f_,"m",P_).call(this,e);if(n.controller.signal?.aborted)throw new Jy;return this._addRun(L_(this,f_,"m",O_).call(this))}toReadableStream(){return new fb(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n,s){const a=new D_;return a._run((()=>a._runToolAssistantStream(e,t,r,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),a}async _createToolAssistantStream(e,t,r,n,s){const a=s?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",(()=>this.controller.abort())));const i={...n,stream:!0},o=await e.submitToolOutputs(t,r,i,{...s,signal:this.controller.signal});this._connected();for await(const e of o)L_(this,f_,"m",P_).call(this,e);if(o.controller.signal?.aborted)throw new Jy;return this._addRun(L_(this,f_,"m",O_).call(this))}static createThreadAssistantStream(e,t,r){const n=new D_;return n._run((()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}static createAssistantStream(e,t,r,n){const s=new D_;return s._run((()=>s._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),s}currentEvent(){return L_(this,x_,"f")}currentRun(){return L_(this,T_,"f")}currentMessageSnapshot(){return L_(this,w_,"f")}currentRunStepSnapshot(){return L_(this,C_,"f")}async finalRunSteps(){return await this.done(),Object.values(L_(this,y_,"f"))}async finalMessages(){return await this.done(),Object.values(L_(this,b_,"f"))}async finalRun(){if(await this.done(),!L_(this,v_,"f"))throw Error("Final run was not received.");return L_(this,v_,"f")}async _createThreadAssistantStream(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort())));const s={...t,stream:!0},a=await e.createAndRun(s,{...r,signal:this.controller.signal});this._connected();for await(const e of a)L_(this,f_,"m",P_).call(this,e);if(a.controller.signal?.aborted)throw new Jy;return this._addRun(L_(this,f_,"m",O_).call(this))}async _createAssistantStream(e,t,r,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort())));const a={...r,stream:!0},i=await e.create(t,a,{...n,signal:this.controller.signal});this._connected();for await(const e of i)L_(this,f_,"m",P_).call(this,e);if(i.controller.signal?.aborted)throw new Jy;return this._addRun(L_(this,f_,"m",O_).call(this))}static accumulateDelta(e,t){for(const[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let t=e[r];if(null!=t)if("index"!==r&&"type"!==r){if("string"==typeof t&&"string"==typeof n)t+=n;else if("number"==typeof t&&"number"==typeof n)t+=n;else{if(!aw(t)||!aw(n)){if(Array.isArray(t)&&Array.isArray(n)){if(t.every((e=>"string"==typeof e||"number"==typeof e))){t.push(...n);continue}for(const e of n){if(!aw(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const r=e.index;if(null==r)throw console.error(e),new Error("Expected array delta entry to have an `index` property");if("number"!=typeof r)throw new Error(`Expected array delta entry \`index\` property to be a number but got ${r}`);const n=t[r];null==n?t.push(e):t[r]=this.accumulateDelta(n,e)}continue}throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${t}`)}t=this.accumulateDelta(t,n)}e[r]=t}else e[r]=n;else e[r]=n}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n,s){return await this._createToolAssistantStream(r,e,t,n,s)}}P_=function(e){if(!this.ended)switch(F_(this,x_,e,"f"),L_(this,f_,"m",M_).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":L_(this,f_,"m",$_).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":L_(this,f_,"m",I_).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":L_(this,f_,"m",A_).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},O_=function(){if(this.ended)throw new Vy("stream has ended, this shouldn't happen");if(!L_(this,v_,"f"))throw Error("Final run has not been received");return L_(this,v_,"f")},A_=function(e){const[t,r]=L_(this,f_,"m",j_).call(this,e,L_(this,w_,"f"));F_(this,w_,t,"f"),L_(this,b_,"f")[t.id]=t;for(const e of r){const r=t.content[e.index];"text"==r?.type&&this._emit("textCreated",r.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 r of e.data.delta.content){if("text"==r.type&&r.text){let e=r.text,n=t.content[r.index];if(!n||"text"!=n.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,n.text)}if(r.index!=L_(this,__,"f")){if(L_(this,k_,"f"))switch(L_(this,k_,"f").type){case"text":this._emit("textDone",L_(this,k_,"f").text,L_(this,w_,"f"));break;case"image_file":this._emit("imageFileDone",L_(this,k_,"f").image_file,L_(this,w_,"f"))}F_(this,__,r.index,"f")}F_(this,k_,t.content[r.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==L_(this,__,"f")){const t=e.data.content[L_(this,__,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,L_(this,w_,"f"));break;case"text":this._emit("textDone",t.text,L_(this,w_,"f"))}}L_(this,w_,"f")&&this._emit("messageDone",e.data),F_(this,w_,void 0,"f")}},I_=function(e){const t=L_(this,f_,"m",R_).call(this,e);switch(F_(this,C_,t,"f"),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&&"tool_calls"==r.step_details.type&&r.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(const e of r.step_details.tool_calls)e.index==L_(this,S_,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(L_(this,E_,"f")&&this._emit("toolCallDone",L_(this,E_,"f")),F_(this,S_,e.index,"f"),F_(this,E_,t.step_details.tool_calls[e.index],"f"),L_(this,E_,"f")&&this._emit("toolCallCreated",L_(this,E_,"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":F_(this,C_,void 0,"f");"tool_calls"==e.data.step_details.type&&L_(this,E_,"f")&&(this._emit("toolCallDone",L_(this,E_,"f")),F_(this,E_,void 0,"f")),this._emit("runStepDone",e.data,t)}},M_=function(e){L_(this,g_,"f").push(e),this._emit("event",e)},R_=function(e){switch(e.event){case"thread.run.step.created":return L_(this,y_,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=L_(this,y_,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const n=D_.accumulateDelta(t,r.delta);L_(this,y_,"f")[e.data.id]=n}return L_(this,y_,"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":L_(this,y_,"f")[e.data.id]=e.data}if(L_(this,y_,"f")[e.data.id])return L_(this,y_,"f")[e.data.id];throw new Error("No snapshot available")},j_=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 n=e.data;if(n.delta.content)for(const e of n.delta.content)if(e.index in t.content){let r=t.content[e.index];t.content[e.index]=L_(this,f_,"m",N_).call(this,e,r)}else t.content[e.index]=e,r.push(e);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")},N_=function(e,t){return D_.accumulateDelta(t,e)},$_=function(e){switch(F_(this,T_,e.data,"f"),e.event){case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.cancelling":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":F_(this,v_,e.data,"f"),L_(this,E_,"f")&&(this._emit("toolCallDone",L_(this,E_,"f")),F_(this,E_,void 0,"f"))}};class z_ extends iw{create(e,t,r){return this._client.post(`/threads/${e}/messages`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/threads/${e}/messages/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}update(e,t,r,n){return this._client.post(`/threads/${e}/messages/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},r){return Db(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,U_,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}del(e,t,r){return this._client.delete(`/threads/${e}/messages/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}}class U_ extends uw{}z_.MessagesPage=U_;class B_ extends iw{retrieve(e,t,r,n={},s){return Db(n)?this.retrieve(e,t,r,{},n):this._client.get(`/threads/${e}/runs/${t}/steps/${r}`,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t,r={},n){return Db(r)?this.list(e,t,{},r):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,q_,{query:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class q_ extends uw{}B_.RunStepsPage=q_;class K_ extends iw{constructor(){super(...arguments),this.steps=new B_(this._client)}create(e,t,r){const{include:n,...s}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:n},body:s,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers},stream:t.stream??!1})}retrieve(e,t,r){return this._client.get(`/threads/${e}/runs/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}update(e,t,r,n){return this._client.post(`/threads/${e}/runs/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},r){return Db(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,W_,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}cancel(e,t,r){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){const n=await this.create(e,t,r);return await this.poll(e,n.id,r)}createAndStream(e,t,r){return D_.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){const n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){const{data:s,response:a}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(r?.pollIntervalMs)e=r.pollIntervalMs;else{const t=a.headers.get("openai-poll-after-ms");if(t){const r=parseInt(t);isNaN(r)||(e=r)}}await Gb(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,t,r){return D_.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r,n){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers},stream:r.stream??!1})}async submitToolOutputsAndPoll(e,t,r,n){const s=await this.submitToolOutputs(e,t,r,n);return await this.poll(e,s.id,n)}submitToolOutputsStream(e,t,r,n){return D_.createToolAssistantStream(e,t,this._client.beta.threads.runs,r,n)}}class W_ extends uw{}K_.RunsPage=W_,K_.Steps=B_,K_.RunStepsPage=q_;class H_ extends iw{constructor(){super(...arguments),this.runs=new K_(this._client),this.messages=new z_(this._client)}create(e={},t){return Db(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,r){return this._client.post(`/threads/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){const r=await this.createAndRun(e,t);return await this.runs.poll(r.thread_id,r.id,t)}createAndRunStream(e,t){return D_.createThreadAssistantStream(e,this._client.beta.threads,t)}}H_.Runs=K_,H_.RunsPage=W_,H_.Messages=z_,H_.MessagesPage=U_;class V_ extends iw{constructor(){super(...arguments),this.realtime=new m_(this._client),this.chat=new d_(this._client),this.assistants=new Vw(this._client),this.threads=new H_(this._client)}}V_.Realtime=m_,V_.Assistants=Vw,V_.AssistantsPage=Gw,V_.Threads=H_;class G_ extends iw{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return Db(e)?this.list({},e):this._client.getAPIList("/batches",J_,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class J_ extends uw{}G_.BatchesPage=J_;class Z_ extends iw{create(e,t,r){return this._client.post(`/uploads/${e}/parts`,xb({body:t,...r}))}}class Y_ extends iw{constructor(){super(...arguments),this.parts=new Z_(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(`/uploads/${e}/complete`,{body:t,...r})}}function X_(e,t){return t&&function(e){if(fv(e.text?.format))return!0;return!1}(t)?Q_(e,t):{...e,output_parsed:null,output:e.output.map((e=>"function_call"===e.type?{...e,parsed_arguments:null}:"message"===e.type?{...e,content:e.content.map((e=>({...e,parsed:null})))}:e))}}function Q_(e,t){const r=e.output.map((e=>{if("function_call"===e.type)return{...e,parsed_arguments:nk(t,e)};if("message"===e.type){const r=e.content.map((e=>"output_text"===e.type?{...e,parsed:ek(t,e.text)}:e));return{...e,content:r}}return e})),n=Object.assign({},e,{output:r});return Object.getOwnPropertyDescriptor(e,"output_text")||sk(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const e of n.output)if("message"===e.type)for(const t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed;return null}}),n}function ek(e,t){if("json_schema"!==e.text?.format?.type)return null;if("$parseRaw"in e.text?.format){const r=e.text?.format;return r.$parseRaw(t)}return JSON.parse(t)}function tk(e){return"auto-parseable-tool"===e?.$brand}function rk(e,t){return e.find((e=>"function"===e.type&&e.name===t))}function nk(e,t){const r=rk(e.tools??[],t.name);return{...t,...t,parsed_arguments:tk(r)?r.$parseRaw(t.arguments):r?.strict?JSON.parse(t.arguments):null}}function sk(e){const t=[];for(const r of e.output)if("message"===r.type)for(const e of r.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}Y_.Parts=Z_;class ak extends iw{list(e,t={},r){return Db(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,wk,{query:t,...r})}}var ik,ok,ck,lk,uk,dk,hk,pk,mk,fk=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},gk=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class yk extends mv{constructor(e){super(),ik.add(this),ok.set(this,void 0),ck.set(this,void 0),lk.set(this,void 0),fk(this,ok,e,"f")}static createResponse(e,t,r){const n=new yk(t);return n._run((()=>n._createResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}async _createResponse(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),gk(this,ik,"m",uk).call(this);const s=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const e of s)gk(this,ik,"m",dk).call(this,e);if(s.controller.signal?.aborted)throw new Jy;return gk(this,ik,"m",hk).call(this)}[(ok=new WeakMap,ck=new WeakMap,lk=new WeakMap,ik=new WeakSet,uk=function(){this.ended||fk(this,ck,void 0,"f")},dk=function(e){if(this.ended)return;const t=gk(this,ik,"m",pk).call(this,e);switch(this._emit("event",e),e.type){case"response.output_text.delta":{const r=t.output[e.output_index];if(!r)throw new Vy(`missing output at index ${e.output_index}`);if("message"===r.type){const t=r.content[e.content_index];if(!t)throw new Vy(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new Vy(`expected content to be 'output_text', got ${t.type}`);this._emit("response.output_text.delta",{...e,snapshot:t.text})}break}case"response.function_call_arguments.delta":{const r=t.output[e.output_index];if(!r)throw new Vy(`missing output at index ${e.output_index}`);"function_call"===r.type&&this._emit("response.function_call_arguments.delta",{...e,snapshot:r.arguments});break}default:this._emit(e.type,e)}},hk=function(){if(this.ended)throw new Vy("stream has ended, this shouldn't happen");const e=gk(this,ck,"f");if(!e)throw new Vy("request ended without sending any events");fk(this,ck,void 0,"f");const t=function(e,t){return X_(e,t)}(e,gk(this,ok,"f"));return fk(this,lk,t,"f"),t},pk=function(e){let t=gk(this,ck,"f");if(!t){if("response.created"!==e.type)throw new Vy(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=fk(this,ck,e.response,"f"),t}switch(e.type){case"response.output_item.added":t.output.push(e.item);break;case"response.content_part.added":{const r=t.output[e.output_index];if(!r)throw new Vy(`missing output at index ${e.output_index}`);"message"===r.type&&r.content.push(e.part);break}case"response.output_text.delta":{const r=t.output[e.output_index];if(!r)throw new Vy(`missing output at index ${e.output_index}`);if("message"===r.type){const t=r.content[e.content_index];if(!t)throw new Vy(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new Vy(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case"response.function_call_arguments.delta":{const r=t.output[e.output_index];if(!r)throw new Vy(`missing output at index ${e.output_index}`);"function_call"===r.type&&(r.arguments+=e.delta);break}case"response.completed":fk(this,ck,e.response,"f")}return t},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",(r=>{const n=t.shift();n?n.resolve(r):e.push(r)})),this.on("end",(()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),this.on("error",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise(((e,r)=>t.push({resolve:e,reject:r}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=gk(this,lk,"f");if(!e)throw new Vy("stream ended without producing a ChatCompletion");return e}}class bk extends iw{constructor(){super(...arguments),this.inputItems=new ak(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap((e=>("object"in e&&"response"===e.object&&sk(e),e)))}retrieve(e,t={},r){return Db(t)?this.retrieve(e,{},t):this._client.get(`/responses/${e}`,{query:t,...r})}del(e,t){return this._client.delete(`/responses/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((t=>Q_(t,e)))}stream(e,t){return yk.createResponse(this._client,e,t)}}class wk extends uw{}bk.InputItems=ak;class vk extends iw{retrieve(e,t,r,n){return this._client.get(`/evals/${e}/runs/${t}/output_items/${r}`,n)}list(e,t,r={},n){return Db(r)?this.list(e,t,{},r):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,_k,{query:r,...n})}}class _k extends uw{}vk.OutputItemListResponsesPage=_k;class kk extends iw{constructor(){super(...arguments),this.outputItems=new vk(this._client)}create(e,t,r){return this._client.post(`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){return this._client.get(`/evals/${e}/runs/${t}`,r)}list(e,t={},r){return Db(t)?this.list(e,{},t):this._client.getAPIList(`/evals/${e}/runs`,Sk,{query:t,...r})}del(e,t,r){return this._client.delete(`/evals/${e}/runs/${t}`,r)}cancel(e,t,r){return this._client.post(`/evals/${e}/runs/${t}`,r)}}class Sk extends uw{}kk.RunListResponsesPage=Sk,kk.OutputItems=vk,kk.OutputItemListResponsesPage=_k;class Ek extends iw{constructor(){super(...arguments),this.runs=new kk(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(`/evals/${e}`,t)}update(e,t,r){return this._client.post(`/evals/${e}`,{body:t,...r})}list(e={},t){return Db(e)?this.list({},e):this._client.getAPIList("/evals",xk,{query:e,...t})}del(e,t){return this._client.delete(`/evals/${e}`,t)}}class xk extends uw{}Ek.EvalListResponsesPage=xk,Ek.Runs=kk,Ek.RunListResponsesPage=Sk;class Tk extends jb{constructor({baseURL:e=Yb("OPENAI_BASE_URL"),apiKey:t=Yb("OPENAI_API_KEY"),organization:r=Yb("OPENAI_ORG_ID")??null,project:n=Yb("OPENAI_PROJECT_ID")??null,...s}={}){if(void 0===t)throw new Vy("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 a={apiKey:t,organization:r,project:n,...s,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new Vy("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:a.baseURL,timeout:a.timeout??6e5,httpAgent:a.httpAgent,maxRetries:a.maxRetries,fetch:a.fetch}),this.completions=new ow(this),this.chat=new mw(this),this.embeddings=new fw(this),this.files=new gw(this),this.images=new bw(this),this.audio=new kw(this),this.moderations=new Sw(this),this.models=new Ew(this),this.fineTuning=new Lw(this),this.graders=new Dw(this),this.vectorStores=new Kw(this),this.beta=new V_(this),this.batches=new G_(this),this.uploads=new Y_(this),this.responses=new bk(this),this.evals=new Ek(this),this._options=a,this.apiKey=t,this.organization=r,this.project=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return Oy(e,{arrayFormat:"brackets"})}}mk=Tk,Tk.OpenAI=mk,Tk.DEFAULT_TIMEOUT=6e5,Tk.OpenAIError=Vy,Tk.APIError=Gy,Tk.APIConnectionError=Zy,Tk.APIConnectionTimeoutError=Yy,Tk.APIUserAbortError=Jy,Tk.NotFoundError=tb,Tk.ConflictError=rb,Tk.RateLimitError=sb,Tk.BadRequestError=Xy,Tk.AuthenticationError=Qy,Tk.InternalServerError=ab,Tk.PermissionDeniedError=eb,Tk.UnprocessableEntityError=nb,Tk.toFile=_b,Tk.fileFromPath=Fy,Tk.Completions=ow,Tk.Chat=mw,Tk.ChatCompletionsPage=hw,Tk.Embeddings=fw,Tk.Files=gw,Tk.FileObjectsPage=yw,Tk.Images=bw,Tk.Audio=kw,Tk.Moderations=Sw,Tk.Models=Ew,Tk.ModelsPage=xw,Tk.FineTuning=Lw,Tk.Graders=Dw,Tk.VectorStores=Kw,Tk.VectorStoresPage=Ww,Tk.VectorStoreSearchResponsesPage=Hw,Tk.Beta=V_,Tk.Batches=G_,Tk.BatchesPage=J_,Tk.Uploads=Y_,Tk.Responses=bk,Tk.Evals=Ek,Tk.EvalListResponsesPage=xk;new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations"]);const Ck=Tk;M.z.object({llm:M.z.literal("openai"),apiKey:M.z.string(),modelName:M.z.string().optional(),baseURL:M.z.string().default("http://llm.nxtscape.ai"),options:M.z.record(M.z.unknown()).optional()});class Pk{constructor(e,t,r){if(this.defaultModel="gpt-4o",this.defaultBaseURL="http://llm.nxtscape.ai",t&&(this.defaultModel=t),"string"==typeof e)this.client=new Ck({apiKey:e,baseURL:this.defaultBaseURL,dangerouslyAllowBrowser:!0,...r});else if(e.chat&&e.chat.completions)this.client=e;else{const t=e;t.dangerouslyAllowBrowser=!0,t.baseURL||(t.baseURL=this.defaultBaseURL),this.client=new Ck(t)}}processResponse(e){const t=e.choices[0]?.message.tool_calls?.map((e=>({id:e.id,name:e.function.name,input:JSON.parse(e.function.arguments)})))||[];return{textContent:e.choices[0]?.message.content||null,content:e.choices[0]?.message.content?[{type:"text",text:e.choices[0].message.content}]:[],toolCalls:t,stop_reason:e.choices[0]?.finish_reason||null}}async generateText(e,t){const r=await this.client.chat.completions.create({model:t.model||this.defaultModel,messages:this.formatMessages(e),temperature:t.temperature,max_tokens:t.maxTokens,tools:this.formatTools(t.tools),tool_choice:this.formatToolChoice(t.toolChoice)});return this.processResponse(r)}async generateStream(e,t,r){const n=await this.client.chat.completions.create({model:t.model||this.defaultModel,messages:this.formatMessages(e),temperature:t.temperature,max_tokens:t.maxTokens,tools:this.formatTools(t.tools),tool_choice:this.formatToolChoice(t.toolChoice),stream:!0});r.onStart?.();let s={};try{for await(const e of n){const t=e.choices[0]?.delta;if(t?.content&&r.onContent?.(t.content),t?.tool_calls&&t.tool_calls.length>0)for(const e of t.tool_calls){const t=e.id;t&&!s[t]&&(s[t]={id:t,function:{name:"",arguments:""}}),t&&e.function?.name&&(s[t].function.name=e.function.name),t&&e.function?.arguments&&(s[t].function.arguments+=e.function.arguments),t&&s[t].function.name&&this.isValidJson(s[t].function.arguments)&&(r.onToolCall?.({id:t,name:s[t].function.name,input:JSON.parse(s[t].function.arguments)}),delete s[t])}}r.onEnd?.()}catch(e){r.onError?.(e)}}formatMessages(e){return e.map((e=>(e.content,{role:e.role,content:e.content,...e.name?{name:e.name}:{},...e.tool_call_id?{tool_call_id:e.tool_call_id}:{}})))}formatTools(e){if(e&&0!==e.length)return e.map((e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.input_schema}})))}formatToolChoice(e){if(e)return"auto"===e.type?"auto":"tool"===e.type?e.name?{type:"function",function:{name:e.name}}:"required":void 0}isValidJson(e){try{return JSON.parse(e),!0}catch(e){return!1}}async generateStructured(e,t,r){const n=(0,Nt.Ik)(e,{target:"openApi3"}),s=JSON.stringify(n,null,2);let a=r?.systemPrompt||"You are a helpful assistant that generates structured data based on user requests. Follow the user's instructions carefully and output valid JSON data.";a+=`\n\nYou must respond with a valid JSON object conforming to this schema:\n${s}\nOnly output the JSON object and nothing else. No explanations, no markdown formatting, just pure JSON.`;const i=await this.client.chat.completions.create({model:r?.model||this.defaultModel,response_format:{type:"json_object"},temperature:r?.temperature??.2,max_tokens:r?.maxTokens,messages:[{role:"system",content:a},{role:"user",content:`${t}\n\nRespond with a valid JSON object that follows the schema.`}]});try{const t=i.choices[0]?.message?.content;if(!t)throw new Error("No structured data was generated");const r=JSON.parse(t);return e.parse(r)}catch(e){throw new Error(`Failed to generate valid structured data: ${e}`)}}}const Ok="sk-xmIa7rAyujEDHPLRyYpwzQ";if(!Ok)throw new Error("BUILD ERROR: LITELLM_API_KEY is missing or not replaced by webpack");const Ak=Ok,Ik={default:"claude-3-5-sonnet",options:["claude-3-5-sonnet","claude-3-opus","claude-3-5-haiku","claude-3-opus","claude-3-7-sonnet"]},Mk={default:"gpt-4o",options:["gpt-4o","gpt-4o-mini"]};class Rk{static getApiKey(e){return Ak}static buildLLMProvider(e){let t;if("string"==typeof e)t=new py(e);else if("llm"in e)if("claude"===e.llm){const r=e,n=r.apiKey||this.getApiKey("claude");t=new py(n,r.modelName,r.options)}else{if("openai"!==e.llm)throw new Error(`Unknown LLM provider: ${e.llm}`);{const r=e,n=r.apiKey||this.getApiKey("openai");t=new Pk(n,r.modelName,r.options)}}else t=e;return t}static createClaudeProvider(e){const t=this.getApiKey("claude");return new py(t,e||Ik.default)}static createOpenAIProvider(e){const t=this.getApiKey("openai");return new Pk(t,e||Mk.default)}static createProvider(e,t){return"claude"===e?this.createClaudeProvider(t):this.createOpenAIProvider(t)}}const jk=M.z.object({instruction:M.z.string().optional(),targetFolder:M.z.string().optional(),dryRun:M.z.boolean().optional(),maxCategories:M.z.number().optional(),includeSubcategories:M.z.boolean().optional()}),Nk=M.z.object({id:M.z.string(),title:M.z.string(),url:M.z.string(),category:M.z.string(),subcategory:M.z.string().optional()}),$k=M.z.object({category:M.z.string(),subcategories:M.z.array(M.z.string()),count:M.z.number(),bookmarks:M.z.array(Nk)}),Lk=M.z.object({success:M.z.boolean(),totalBookmarks:M.z.number(),organizedCount:M.z.number(),categories:M.z.array($k),message:M.z.string()});class Fk extends fm{constructor(e){super({name:"organize_bookmarks",description:"Intelligently organize all bookmarks from the bookmark bar (including those in folders) using AI based on custom instructions. Consolidates scattered bookmarks into a clean folder structure.",category:"bookmarks",version:"2.1.0",inputSchema:jk,outputSchema:Lk,examples:[{description:"Organize with custom instruction",input:{instruction:"Organize by project type and technology stack",dryRun:!0},output:{success:!0,totalBookmarks:25,organizedCount:25,categories:[{category:"Frontend Projects",subcategories:["React","Vue","Angular"],count:8,bookmarks:[]}],message:"Would organize 25 bookmarks into 5 categories"}},{description:"Organize into custom folder",input:{instruction:"Create work and personal categories only",targetFolder:"My Organized Bookmarks",maxCategories:2},output:{success:!0,totalBookmarks:20,organizedCount:20,categories:[{category:"Work",subcategories:[],count:12,bookmarks:[]},{category:"Personal",subcategories:[],count:8,bookmarks:[]}],message:"Successfully organized 20 bookmarks into 2 categories"}}],streamingConfig:{displayName:"Organize Bookmarks",icon:"šŸ“š",progressMessage:"Analyzing and organizing all bookmarks..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.instruction,n=t?.targetFolder,s=t?.dryRun;let a=s?"Analyzing":"Organizing";return a+=" bookmarks",a+=r?` with instruction: "${r}"`:" with AI",n&&!s&&(a+=` into "${n}"`),a+="...",a}catch{return"Organizing bookmarks..."}}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;if(0===e.organizedCount)return"šŸ“š No bookmarks to organize!";const t=e.categories.length,r=e.categories.reduce(((e,t)=>e+t.subcategories.length),0);return r>0?`šŸ“š Organized ${e.organizedCount} bookmarks into ${t} categories with ${r} subcategories`:`šŸ“š Organized ${e.organizedCount} bookmarks into ${t} categories`}async execute(e){try{const t=e.dryRun??!1,r=e.maxCategories??8,n=e.includeSubcategories??!0,s=e.targetFolder||Fk.DEFAULT_FOLDER_NAME,a=e.instruction,i=await this.getBookmarkBar();if(!i)return{success:!1,totalBookmarks:0,organizedCount:0,categories:[],message:"Could not find bookmark bar"};const o=await chrome.bookmarks.getChildren(i.id),c=o.filter((e=>e.url)),l=o.filter((e=>!e.url)),u=[];c.forEach((e=>{u.push({id:e.id,title:e.title,url:e.url})}));for(const e of l){if(e.title===s)continue;const t=await chrome.bookmarks.getChildren(e.id);t.filter((e=>e.url)).forEach((t=>{u.push({id:t.id,title:t.title,url:t.url,parentTitle:e.title})}))}if(0===u.length)return{success:!0,totalBookmarks:0,organizedCount:0,categories:[],message:"No bookmarks found to organize"};const d=await this.categorizeBookmarksWithLLM(u,r,n,a);if(t)return{success:!0,totalBookmarks:u.length,organizedCount:u.length,categories:d,message:`Would organize ${u.length} bookmarks into ${d.length} categories`};const h=await this.applyOrganization(i.id,d,s);return{success:!0,totalBookmarks:u.length,organizedCount:h.organizedCount,categories:h.categories,message:`Successfully organized ${h.organizedCount} bookmarks into ${h.categories.length} categories`}}catch(e){return console.error("[organize_bookmarks] Error:",e),{success:!1,totalBookmarks:0,organizedCount:0,categories:[],message:`Error organizing bookmarks: ${e instanceof Error?e.message:String(e)}`}}}async categorizeBookmarksWithLLM(e,t,r,n){const s=Rk.createClaudeProvider(),a=`You are an expert at organizing bookmarks into logical categories. Your task is to analyze a list of bookmarks and create a clean, intuitive folder structure.\n\n**REQUIREMENTS:**\n1. Create at most ${t} main categories\n2. ${r?"Create subcategories when it makes sense (max 2 levels deep)":"Do NOT create subcategories"}\n3. Category names should be:\n - Clear and descriptive (2-3 words max)\n - Professional and consistent\n - Not too specific or too broad\n4. Every bookmark must be assigned to exactly one category${r?" (and optionally one subcategory)":""}\n5. Similar websites should be grouped together\n6. Consider the domain, title, purpose, and current folder (if any) of each bookmark\n\n${n?`**CUSTOM INSTRUCTION:**\n${n}\n\nFollow this instruction while organizing the bookmarks. Adapt your categorization strategy based on this guidance.\n`:""}\n\n**OUTPUT FORMAT:**\nReturn a JSON array of category objects. Each object should have:\n- category: string (main category name)\n- subcategories: string[] (list of subcategory names, empty if none)\n- bookmarks: array of objects with:\n - id: string (the bookmark ID)\n - category: string (assigned category)\n - subcategory: string (assigned subcategory, optional)\n\nExample:\n[\n {\n "category": "Development",\n "subcategories": ["Documentation", "Tools"],\n "bookmarks": [\n {"id": "123", "category": "Development", "subcategory": "Documentation"},\n {"id": "456", "category": "Development", "subcategory": "Tools"}\n ]\n }\n]`,i=`Please organize these bookmarks into categories${n?" following the custom instruction provided":""}:\n\n${e.map(((e,t)=>`${t+1}. ID: ${e.id}\n Title: ${e.title}\n URL: ${e.url}${e.parentTitle?`\n Current Folder: ${e.parentTitle}`:""}`)).join("\n\n")}\n\nRemember to:\n- Create intuitive categories that make sense for these specific bookmarks\n- Group similar content together\n- Consider existing folder names as hints for categorization\n- Use professional, clear category names\n- Ensure every bookmark is assigned to a category\n${n?"- Follow the custom instruction provided in the system prompt":""}\n\nReturn the organization as a JSON array.`;try{const t=(await s.generateText([{role:"system",content:a},{role:"user",content:i}],{temperature:.3,maxTokens:4e3})).textContent||"[]",r=t.match(/```(?:json)?\s*([\s\S]*?)\s*```/)||t.match(/(\[[\s\S]*\])/),n=r?r[1]:t;try{const t=JSON.parse(n);return this.validateCategorization(t,e)}catch(e){throw console.error("[organize_bookmarks] Failed to parse LLM response:",e),new Error("Failed to parse categorization from AI response")}}catch(e){throw new Error(`LLM categorization failed: ${e instanceof Error?e.message:String(e)}`)}}validateCategorization(e,t){const r=new Set(t.map((e=>e.id))),n=new Set,s=e.map((e=>{const s={category:e.category||"Uncategorized",subcategories:Array.isArray(e.subcategories)?e.subcategories:[],count:0,bookmarks:[]};return Array.isArray(e.bookmarks)&&(s.bookmarks=e.bookmarks.filter((e=>{if(e.id&&r.has(e.id)&&!n.has(e.id)){n.add(e.id);if(t.find((t=>t.id===e.id)))return!0}return!1})).map((e=>({id:e.id,title:t.find((t=>t.id===e.id)).title,url:t.find((t=>t.id===e.id)).url,category:s.category,subcategory:e.subcategory||void 0})))),s.count=s.bookmarks.length,s})).filter((e=>e.count>0)),a=t.filter((e=>!n.has(e.id)));return a.length>0&&s.push({category:"Other",subcategories:[],count:a.length,bookmarks:a.map((e=>({id:e.id,title:e.title,url:e.url,category:"Other"})))}),s}async applyOrganization(e,t,r){let n=await this.findChildFolder(e,r);n||(n=await chrome.bookmarks.create({parentId:e,title:r}));let s=0;const a=[];for(const e of t){if(0===e.bookmarks.length)continue;let t=await this.findChildFolder(n.id,e.category);t||(t=await chrome.bookmarks.create({parentId:n.id,title:e.category}));const r=new Map;for(const n of e.subcategories){let e=await this.findChildFolder(t.id,n);e||(e=await chrome.bookmarks.create({parentId:t.id,title:n})),r.set(n,e)}const i=[];for(const n of e.bookmarks)try{const e=n.subcategory&&r.has(n.subcategory)?r.get(n.subcategory).id:t.id;await chrome.bookmarks.move(n.id,{parentId:e}),i.push(n),s++}catch(e){console.error(`Failed to move bookmark ${n.title}:`,e)}a.push({...e,bookmarks:i,count:i.length})}return{organizedCount:s,categories:a}}async getBookmarkBar(){const e=(await chrome.bookmarks.getTree())[0];for(const t of e.children||[])if("1"===t.id||"Bookmarks Bar"===t.title)return t;return null}async findChildFolder(e,t){return(await chrome.bookmarks.getChildren(e)).find((e=>!e.url&&e.title===t))||null}}Fk.DEFAULT_FOLDER_NAME="AI Bookmarks";const Dk=M.z.object({name:M.z.string().min(1),description:M.z.string().optional(),windowId:M.z.number().optional()}),zk=M.z.object({url:M.z.string(),title:M.z.string(),favIconUrl:M.z.string().optional(),index:M.z.number()}),Uk=M.z.object({id:M.z.string(),name:M.z.string(),description:M.z.string().optional(),tabs:M.z.array(zk),createdAt:M.z.string(),tabCount:M.z.number()}),Bk=M.z.object({success:M.z.boolean(),sessionId:M.z.string().optional(),sessionName:M.z.string().optional(),tabCount:M.z.number(),message:M.z.string()});class qk extends fm{constructor(e){super({name:"save_session",description:"Save all tabs in the current window as a named session for later restoration.",category:"sessions",version:"1.0.0",inputSchema:Dk,outputSchema:Bk,examples:[{description:"Save current tabs as a work session",input:{name:"Morning Work Session",description:"Email, calendar, and project docs"},output:{success:!0,sessionId:"sess_123abc",sessionName:"Morning Work Session",tabCount:5,message:'Successfully saved session "Morning Work Session" with 5 tabs'}}],streamingConfig:{displayName:"Save Session",icon:"šŸ’¾",progressMessage:"Saving current session..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.name;return r?`Saving session "${r}"...`:"Saving current session..."}catch{return"Saving current session..."}}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;const t=e.tabCount,r=1===t?"tab":"tabs";return`šŸ’¾ Saved "${e.sessionName}" with ${t} ${r}`}async execute(e){try{let t=e.windowId;if(!t)try{t=(await this.browserContext.getCurrentWindow()).id}catch(e){return console.error("[save_session] Error getting current window:",e),{success:!1,tabCount:0,message:"Error getting current window"}}const r=await chrome.tabs.query({windowId:t});if(0===r.length)return{success:!1,tabCount:0,message:"No tabs found in the specified window"};const n=r.filter((e=>e.url&&e.title)).map(((e,t)=>({url:e.url,title:e.title,favIconUrl:e.favIconUrl,index:e.index??t}))),s=`sess_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,a={id:s,name:e.name,description:e.description,tabs:n,createdAt:(new Date).toISOString(),tabCount:n.length};return await this.saveSession(a),{success:!0,sessionId:s,sessionName:e.name,tabCount:n.length,message:`Successfully saved session "${e.name}" with ${n.length} tab(s)`}}catch(e){return console.error("[save_session] Error:",e),{success:!1,tabCount:0,message:`Error saving session: ${e instanceof Error?e.message:String(e)}`}}}async saveSession(e){try{const t=await chrome.storage.local.get([qk.STORAGE_KEY]),r=[e,...t[qk.STORAGE_KEY]||[]];await chrome.storage.local.set({[qk.STORAGE_KEY]:r})}catch(e){throw new Error(`Failed to save session to storage: ${e instanceof Error?e.message:String(e)}`)}}}qk.STORAGE_KEY="nxtscape_sessions";const Kk=M.z.object({limit:M.z.number().positive().optional(),sortBy:M.z.enum(["name","createdAt","tabCount"]).optional()}),Wk=M.z.object({id:M.z.string(),name:M.z.string(),description:M.z.string().optional(),tabCount:M.z.number(),createdAt:M.z.string(),previewTabs:M.z.array(M.z.object({title:M.z.string(),url:M.z.string()})).optional()}),Hk=M.z.object({success:M.z.boolean(),sessions:M.z.array(Wk),totalCount:M.z.number(),message:M.z.string()});class Vk extends fm{constructor(e){super({name:"list_sessions",description:"List all saved browser sessions with their names, descriptions, and tab counts.",category:"sessions",version:"1.0.0",inputSchema:Kk,outputSchema:Hk,examples:[{description:"List all saved sessions",input:{sortBy:"createdAt"},output:{success:!0,sessions:[{id:"sess_123",name:"Morning Work",description:"Daily work tabs",tabCount:5,createdAt:new Date,previewTabs:[{title:"Gmail",url:"https://gmail.com"},{title:"Calendar",url:"https://calendar.google.com"}]}],totalCount:1,message:"Found 1 saved session"}}],streamingConfig:{displayName:"List Sessions",icon:"šŸ“‹",progressMessage:"Loading saved sessions..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.limit;return r?`Loading ${r} most recent sessions...`:"Loading saved sessions..."}catch{return"Loading saved sessions..."}}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;if(0===e.sessions.length)return"šŸ“‹ No saved sessions found";const t=1===e.sessions.length?"session":"sessions";let r=`šŸ“‹ Found ${e.sessions.length} ${t}:\n\n`;return e.sessions.forEach(((e,t)=>{const n=new Date(e.createdAt).toLocaleDateString(),s=1===e.tabCount?"tab":"tabs";r+=`${t+1}. **${e.name}** (${e.tabCount} ${s}) - ${n}\n`,e.description&&(r+=` ${e.description}\n`),e.previewTabs&&e.previewTabs.length>0&&(r+=` Preview: ${e.previewTabs.map((e=>e.title)).join(", ")}\n`),r+="\n"})),r.trim()}async execute(e){try{const t=await this.loadSessions();if(0===t.length)return{success:!0,sessions:[],totalCount:0,message:"No saved sessions found"};const r=this.sortSessions(t,e.sortBy||"createdAt"),n=(e.limit?r.slice(0,e.limit):r).map((e=>({id:e.id,name:e.name,description:e.description,tabCount:e.tabCount,createdAt:e.createdAt,previewTabs:e.tabs.slice(0,3).map((e=>({title:e.title,url:e.url})))}))),s=1===n.length?"session":"sessions",a=e.limit&&t.length>e.limit?`Found ${n.length} of ${t.length} sessions`:`Found ${n.length} ${s}`;return{success:!0,sessions:n,totalCount:t.length,message:a}}catch(e){return console.error("[list_sessions] Error:",e),{success:!1,sessions:[],totalCount:0,message:`Error listing sessions: ${e instanceof Error?e.message:String(e)}`}}}async loadSessions(){try{const e=await chrome.storage.local.get([Vk.STORAGE_KEY]);return(e[Vk.STORAGE_KEY]||[]).map((e=>{try{return Uk.parse(e)}catch(e){return console.warn("[list_sessions] Invalid session found, skipping:",e),null}})).filter((e=>null!==e))}catch(e){throw new Error(`Failed to load sessions from storage: ${e instanceof Error?e.message:String(e)}`)}}sortSessions(e,t){return[...e].sort(((e,r)=>{switch(t){case"name":return e.name.localeCompare(r.name);case"tabCount":return r.tabCount-e.tabCount;default:return new Date(r.createdAt).getTime()-new Date(e.createdAt).getTime()}}))}}Vk.STORAGE_KEY="nxtscape_sessions";const Gk=M.z.object({sessionId:M.z.string().min(1),newWindow:M.z.boolean().optional(),focusWindow:M.z.boolean().optional()}),Jk=M.z.object({success:M.z.boolean(),sessionName:M.z.string().optional(),tabsOpened:M.z.number(),windowId:M.z.number().optional(),failedTabs:M.z.array(M.z.object({url:M.z.string(),title:M.z.string(),error:M.z.string()})).optional(),message:M.z.string()});class Zk extends fm{constructor(e){super({name:"resume_session",description:"Resume a saved session by opening all its tabs. By default opens in a new window.",category:"sessions",version:"1.0.0",inputSchema:Gk,outputSchema:Jk,examples:[{description:"Resume a session in a new window",input:{sessionId:"sess_123abc",newWindow:!0},output:{success:!0,sessionName:"Morning Work Session",tabsOpened:5,windowId:2,message:'Successfully resumed "Morning Work Session" with 5 tabs in new window'}}],streamingConfig:{displayName:"Resume Session",icon:"šŸ”„",progressMessage:"Resuming session..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.sessionId;return r?`Resuming session ${r}...`:"Resuming session..."}catch{return"Resuming session..."}}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;const t=1===e.tabsOpened?"tab":"tabs";let r=`šŸ”„ Resumed "${e.sessionName}" with ${e.tabsOpened} ${t}`;if(e.failedTabs&&e.failedTabs.length>0){const t=e.failedTabs.length;r+=` (${t} ${1===t?"tab":"tabs"} failed to open)`}return r}async execute(e){try{const t=await this.loadSession(e.sessionId);if(!t)return{success:!1,tabsOpened:0,message:`Session with ID ${e.sessionId} not found`};if(0===t.tabs.length)return{success:!1,sessionName:t.name,tabsOpened:0,message:`Session "${t.name}" has no tabs to open`};let r;const n=e.newWindow??!0,s=e.focusWindow??!0;if(n){const e=t.tabs[0],n=await chrome.windows.create({url:e.url,focused:s});if(!n?.id)throw new Error("Failed to create new window");r=n.id}else{const e=await chrome.tabs.getCurrent();if(e?.windowId)r=e.windowId;else{const e=(await chrome.windows.getAll({populate:!1})).find((e=>e.focused));if(!e?.id)throw new Error("Could not determine target window");r=e.id}}const a=n?t.tabs.slice(1):t.tabs,i=[];let o=n?1:0;for(const e of a)try{await chrome.tabs.create({windowId:r,url:e.url,active:!1}),o++}catch(t){console.warn("[resume_session] Failed to open tab:",e.url,t),i.push({url:e.url,title:e.title,error:t instanceof Error?t.message:String(t)})}if(s&&r)try{await chrome.windows.update(r,{focused:!0})}catch(e){console.warn("[resume_session] Failed to focus window:",e)}const c=t.tabs.length,l=i.length>0;return{success:o>0,sessionName:t.name,tabsOpened:o,windowId:r,failedTabs:l?i:void 0,message:l?`Resumed "${t.name}" with ${o}/${c} tabs (${i.length} failed)`:`Successfully resumed "${t.name}" with ${o} tab(s)`}}catch(e){return console.error("[resume_session] Error:",e),{success:!1,tabsOpened:0,message:`Error resuming session: ${e instanceof Error?e.message:String(e)}`}}}async loadSession(e){try{const t=await chrome.storage.local.get([Zk.STORAGE_KEY]),r=(t[Zk.STORAGE_KEY]||[]).find((t=>t.id===e));if(!r)return null;try{return Uk.parse(r)}catch(e){return console.warn("[resume_session] Invalid session data found:",e),null}}catch(e){throw new Error(`Failed to load session from storage: ${e instanceof Error?e.message:String(e)}`)}}}Zk.STORAGE_KEY="nxtscape_sessions";const Yk=M.z.object({sessionIds:M.z.array(M.z.string()).min(1),confirmDelete:M.z.boolean().optional()}),Xk=M.z.object({success:M.z.boolean(),deletedCount:M.z.number(),notFoundCount:M.z.number(),deletedSessions:M.z.array(M.z.object({id:M.z.string(),name:M.z.string()})).optional(),notFoundIds:M.z.array(M.z.string()).optional(),message:M.z.string()});class Qk extends fm{constructor(e){super({name:"delete_sessions",description:"Delete one or multiple saved browser sessions by their IDs.",category:"sessions",version:"1.0.0",inputSchema:Yk,outputSchema:Xk,examples:[{description:"Delete a single session",input:{sessionIds:["sess_123abc"],confirmDelete:!0},output:{success:!0,deletedCount:1,notFoundCount:0,deletedSessions:[{id:"sess_123abc",name:"Morning Work Session"}],message:"Successfully deleted 1 session"}},{description:"Delete multiple sessions",input:{sessionIds:["sess_123abc","sess_456def"],confirmDelete:!0},output:{success:!0,deletedCount:2,notFoundCount:0,deletedSessions:[{id:"sess_123abc",name:"Morning Work Session"},{id:"sess_456def",name:"Research Project"}],message:"Successfully deleted 2 sessions"}}],streamingConfig:{displayName:"Delete Sessions",icon:"šŸ—‘ļø",progressMessage:"Deleting sessions..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.sessionIds;if(r&&Array.isArray(r)){const e=r.length;return`Deleting ${e} ${1===e?"session":"sessions"}...`}return"Deleting sessions..."}catch{return"Deleting sessions..."}}formatDisplayResult(e){if(!e.success)return`āŒ ${e.message}`;const t=1===e.deletedCount?"session":"sessions";let r=`šŸ—‘ļø Deleted ${e.deletedCount} ${t}`;if(e.notFoundCount>0){const t=1===e.notFoundCount?"session":"sessions";r+=` (${e.notFoundCount} ${t} not found)`}return r}async execute(e){try{if(!(e.confirmDelete??!0))return{success:!1,deletedCount:0,notFoundCount:0,message:"Deletion cancelled - confirmDelete was false"};const t=await this.loadSessions();if(0===t.length)return{success:!1,deletedCount:0,notFoundCount:e.sessionIds.length,notFoundIds:e.sessionIds,message:"No sessions found to delete"};const r=[],n=[];for(const s of e.sessionIds){const e=t.find((e=>e.id===s));e?r.push({id:e.id,name:e.name}):n.push(s)}if(0===r.length)return{success:!1,deletedCount:0,notFoundCount:n.length,notFoundIds:n,message:`No sessions found with the provided IDs: ${e.sessionIds.join(", ")}`};const s=t.filter((t=>!e.sessionIds.includes(t.id)));await this.saveSessions(s);const a=r.length,i=n.length;let o=`Successfully deleted ${a} session${1===a?"":"s"}`;return i>0&&(o+=` (${i} not found)`),{success:!0,deletedCount:a,notFoundCount:i,deletedSessions:r,notFoundIds:i>0?n:void 0,message:o}}catch(e){return console.error("[delete_sessions] Error:",e),{success:!1,deletedCount:0,notFoundCount:0,message:`Error deleting sessions: ${e instanceof Error?e.message:String(e)}`}}}async loadSessions(){try{const e=await chrome.storage.local.get([Qk.STORAGE_KEY]);return(e[Qk.STORAGE_KEY]||[]).map((e=>{try{return Uk.parse(e)}catch(e){return console.warn("[delete_sessions] Invalid session found, skipping:",e),null}})).filter((e=>null!==e))}catch(e){throw new Error(`Failed to load sessions from storage: ${e instanceof Error?e.message:String(e)}`)}}async saveSessions(e){try{await chrome.storage.local.set({[Qk.STORAGE_KEY]:e})}catch(e){throw new Error(`Failed to save sessions to storage: ${e instanceof Error?e.message:String(e)}`)}}}Qk.STORAGE_KEY="nxtscape_sessions";const eS=M.z.object({reason:M.z.string().optional()}),tS=M.z.object({success:M.z.boolean(),action:M.z.literal("skipped"),reason:M.z.string().optional(),message:M.z.string()});class rS extends fm{constructor(e){super({name:"noop",description:"Skip an action when it is unnecessary, redundant, or already completed. Use this when an instruction does not require any action.",category:"control",version:"1.0.0",inputSchema:eS,outputSchema:tS,examples:[{description:"Skip an action without a reason",input:{},output:{success:!0,action:"skipped",message:"Action skipped (no operation performed)."}},{description:"Skip an action with a reason",input:{reason:"Page is already loaded"},output:{success:!0,action:"skipped",reason:"Page is already loaded",message:"Action skipped (no operation performed). Reason: Page is already loaded"}}],streamingConfig:{displayName:"No Operation",icon:"ā­ļø",progressMessage:"Skipping action..."}},e)}formatDisplayResult(e){return e.reason?`ā­ļø Skipped action - ${e.reason}`:"ā­ļø Skipped unnecessary action"}async execute(e){const t=e.reason?` Reason: ${e.reason}`:"";return{success:!0,action:"skipped",reason:e.reason,message:`Action skipped (no operation performed).${t}`}}}const nS=M.z.object({success:M.z.boolean(),reason:M.z.string().optional()}),sS=M.z.object({success:M.z.boolean(),action:M.z.literal("terminate"),status:M.z.enum(["SUCCESS","FAILED"]),reason:M.z.string().optional(),message:M.z.string()});class aS extends fm{constructor(e){super({name:"terminate",description:"Terminate the current task. Use this when the task is complete (success: true) or when you cannot proceed further (success: false). Always provide a reason.",category:"control",version:"1.0.0",inputSchema:nS,outputSchema:sS,examples:[{description:"Terminate with success",input:{success:!0,reason:"Task completed successfully"},output:{success:!0,action:"terminate",status:"SUCCESS",reason:"Task completed successfully",message:"TASK SUCCESS - Task completed successfully"}},{description:"Terminate with failure",input:{success:!1,reason:"Unable to find the required element"},output:{success:!1,action:"terminate",status:"FAILED",reason:"Unable to find the required element",message:"TASK FAILED - Unable to find the required element"}}],streamingConfig:{displayName:"Terminate",icon:"šŸ",progressMessage:"Terminating task..."}},e)}formatDisplayResult(e){return"SUCCESS"===e.status?"šŸ Task completed successfully"+(e.reason?` - ${e.reason}`:""):"šŸ’„ Task failed"+(e.reason?` - ${e.reason}`:"")}async execute(e){const t=e.success?"SUCCESS":"FAILED",r=e.reason?` - ${e.reason}`:"";return{success:e.success,action:"terminate",status:t,reason:e.reason,message:`TASK ${t}${r}`}}}const iS=M.z.object({instruction:M.z.string(),focus:M.z.string().optional()}),oS=M.z.object({success:M.z.boolean(),summary:M.z.string(),content_length:M.z.number(),summary_length:M.z.number(),message:M.z.string()});class cS extends fm{constructor(e){super({name:"summarize",description:"Summarize the content of the current page using accessible tree extraction and LLM. Takes custom instructions for how to analyze and present the content with markdown formatting and emojis.",category:"observation",version:"1.0.0",inputSchema:iS,outputSchema:oS,examples:[{description:"Quick overview with emojis",input:{instruction:"Give me a quick overview with key points"},output:{success:!0,summary:"šŸ“„ **Page Overview**\n\nThis page contains information about browser automation tools...",content_length:5420,summary_length:180,message:"Generated summary based on instruction"}},{description:"Detailed analysis focused on specific content",input:{instruction:"Analyze the main features in detail",focus:"product features"},output:{success:!0,summary:"šŸš€ **Product Features Analysis**\n\n### Main Features:\n1. šŸ¤– Automated browsing...",content_length:8932,summary_length:420,message:"Generated detailed analysis focused on product features"}}],streamingConfig:{displayName:"Summarize Content",icon:"šŸ“„",progressMessage:"Extracting and summarizing page content..."}},e)}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.instruction,n=t?.focus;return r&&n?`Following instruction: "${r}" focused on "${n}"`:r?`Following instruction: "${r}"`:"Extracting and summarizing page content..."}catch{return"Extracting and summarizing page content..."}}formatDisplayResult(e){return e.success?e.summary:`āŒ ${e.message}`}async execute(e){try{const t=(await this.browserContext.getCurrentPage()).getPuppeteerPage(),r=!0,n=await t.accessibility.snapshot({interestingOnly:r});if(!n)return{success:!1,summary:"",content_length:0,summary_length:0,message:"Failed to extract accessibility tree from page"};const s=this.extractMainContent(n);if(!s||0===s.trim().length)return{success:!1,summary:"",content_length:0,summary_length:0,message:"No meaningful content found on the page"};const a=await this.generateSummary(s,e.instruction,e.focus);return{success:!0,summary:a,content_length:s.length,summary_length:a.length,message:`Generated summary based on instruction (${s.length} → ${a.length} chars)`}}catch(e){return{success:!1,summary:"",content_length:0,summary_length:0,message:`Unable to summarize content: ${e instanceof Error?e.message:String(e)}`}}}extractMainContent(e){const t=[],r=(e,n=0)=>{if(!e)return;const s=e.role?.toLowerCase(),a=e.name?.trim(),i=e.description?.trim();if(a&&a.length>2&&(this.isContentRole(s)?t.push(a):this.isMetaContentRole(s)&&(this.isIgnorableText(a)||t.push(a))),i&&i!==a&&i.length>5&&(this.isIgnorableText(i)||t.push(i)),e.value&&"string"==typeof e.value){const r=e.value.trim();r.length>2&&!this.isIgnorableText(r)&&t.push(r)}e.children&&Array.isArray(e.children)&&e.children.forEach((e=>r(e,n+1)))};r(e);return t.join(" ").replace(/\s+/g," ").replace(/\s*[,;]\s*/g,", ").trim()}isContentRole(e){if(!e)return!1;return["article","main","section","paragraph","text","heading","listitem","definition","term","cell","columnheader","rowheader","statictext"].some((t=>e.includes(t)))}isMetaContentRole(e){if(!e)return!1;return["link","button","menuitem","tab","option","listbox","combobox","textbox","searchbox","spinbutton"].some((t=>e.includes(t)))}isIgnorableText(e){return[/^(menu|nav|navigation|header|footer|sidebar|toolbar)$/i,/^(home|about|contact|login|logout|sign in|sign up|register)$/i,/^(click|tap|press|button|link|search|submit|cancel|close|open)$/i,/^(more|less|show|hide|toggle|expand|collapse|next|previous|prev)$/i,/^(back|forward|up|down|left|right|top|bottom)$/i,/^(username|password|email|search|query)$/i,/^\d+$/,/^[^\w]+$/,/^.{1,2}$/,/^(ok|yes|no|on|off|true|false)$/i,/^(loading|please wait|wait)$/i,/^(share|like|follow|subscribe|ad|advertisement|sponsored)$/i,/^(privacy|terms|cookies|policy|legal)$/i].some((t=>t.test(e)))}async generateSummary(e,t,r){const n=Rk.createClaudeProvider();let s=`Content to analyze:\n\n${e}\n\n`;s+=`Instruction: ${t}\n\n`,r&&(s+=`Please focus specifically on: ${r}\n\n`),s+="Please provide your analysis following the formatting guidelines above.";const a=e.length>8e3?e.substring(0,8e3)+"...[content truncated]":e,i=s.replace(e,a);try{return(await n.generateText([{role:"system",content:"You are an expert content summarizer and analyst. Create engaging, well-formatted summaries based on user instructions.\n\n**FORMATTING GUIDELINES:**\n- Use **markdown formatting** for structure and readability\n- Add relevant **emojis** to make content more engaging and scannable\n- Use **headings (##, ###)** to organize information\n- Use **bullet points** or **numbered lists** for key points\n- Use **bold** and *italics* for emphasis\n- Create clear, scannable content that's easy to read\n\n**STYLE GUIDELINES:**\n- Be concise but informative\n- Focus on the most important and relevant information\n- Use active voice and clear language\n- Structure information logically\n- Include relevant context when helpful\n\nFollow the user's specific instruction for analysis depth and focus."},{role:"user",content:i}],{temperature:.4,maxTokens:8e3})).textContent||"Failed to generate summary"}catch(e){throw new Error(`LLM summarization failed: ${e instanceof Error?e.message:String(e)}`)}}}var lS=s(7765);function uS(e,t){if(void 0===e.function)return;let r;if(t?.partial)try{r=(0,jr.d)(e.function.arguments??"{}")}catch(e){return}else try{r=JSON.parse(e.function.arguments)}catch(t){throw new Xt([`Function "${e.function.name}" arguments:`,"",e.function.arguments,"","are not valid JSON.",`Error: ${t.message}`].join("\n"))}const n={name:e.function.name,args:r,type:"tool_call"};return t?.returnId&&(n.id=e.id),n}function dS(e){if(void 0===e.id)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}}function hS(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:"invalid_tool_call"}}class pS extends kr{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?.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){const r=e[0].message;let n;if((0,lS.KX)(r)&&r.tool_calls?.length)n=r.tool_calls.map((e=>{const{id:t,...r}=e;return this.returnId?{id:t,...r}:r}));else if(void 0!==r.additional_kwargs.tool_calls){n=JSON.parse(JSON.stringify(r.additional_kwargs.tool_calls)).map((e=>uS(e,{returnId:this.returnId,partial:t})))}if(!n)return[];const s=[];for(const e of n)if(void 0!==e){const t={type:e.name,args:e.args,id:e.id};s.push(t)}return s}}class mS extends pS{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){if(void 0===this.zodSchema)return e;const t=await this.zodSchema.safeParseAsync(e);if(t.success)return t.data;throw new Xt(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error.errors)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){const t=(await super.parsePartialResult(e)).filter((e=>e.type===this.keyName));let r=t;if(t.length)return this.returnId||(r=t.map((e=>e.args))),this.returnSingle?r[0]:r}async parseResult(e){const t=(await super.parsePartialResult(e,!1)).filter((e=>e.type===this.keyName));let r=t;if(!t.length)return;if(this.returnId||(r=t.map((e=>e.args))),this.returnSingle)return this._validateResult(r[0]);const n=await Promise.all(r.map((e=>this._validateResult(e))));return n}}function fS(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function gS(e,t,r,n,s){e[t]=r,fS(e,t,n,s)}function yS(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(((r,n)=>yS(e,t,r)))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return bS(e,t)}}const bS=(e,t)=>{const r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(const n of e.checks)switch(n.kind){case"min":gS(r,"minimum",n.value,n.message,t);break;case"max":gS(r,"maximum",n.value,n.message,t)}return r};let wS;const vS=/^[cC][^\s-]{8,}$/,_S=/^[0-9a-z]+$/,kS=/^[0-9A-HJKMNP-TV-Z]{26}$/,SS=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,ES=()=>(void 0===wS&&(wS=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),wS),xS=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,TS=/^[a-zA-Z0-9_-]{21}$/;function CS(e,t){const r={type:"string"};function n(e){return"escape"===t.patternStrategy?PS(e):e}if(e.checks)for(const s of e.checks)switch(s.kind){case"min":gS(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,s.value):s.value,s.message,t);break;case"max":gS(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,s.value):s.value,s.message,t);break;case"email":switch(t.emailStrategy){case"format:email":OS(r,"email",s.message,t);break;case"format:idn-email":OS(r,"idn-email",s.message,t);break;case"pattern:zod":AS(r,SS,s.message,t)}break;case"url":OS(r,"uri",s.message,t);break;case"uuid":OS(r,"uuid",s.message,t);break;case"regex":AS(r,s.regex,s.message,t);break;case"cuid":AS(r,vS,s.message,t);break;case"cuid2":AS(r,_S,s.message,t);break;case"startsWith":AS(r,RegExp(`^${n(s.value)}`),s.message,t);break;case"endsWith":AS(r,RegExp(`${n(s.value)}$`),s.message,t);break;case"datetime":OS(r,"date-time",s.message,t);break;case"date":OS(r,"date",s.message,t);break;case"time":OS(r,"time",s.message,t);break;case"duration":OS(r,"duration",s.message,t);break;case"length":gS(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,s.value):s.value,s.message,t),gS(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,s.value):s.value,s.message,t);break;case"includes":AS(r,RegExp(n(s.value)),s.message,t);break;case"ip":"v6"!==s.version&&OS(r,"ipv4",s.message,t),"v4"!==s.version&&OS(r,"ipv6",s.message,t);break;case"emoji":AS(r,ES,s.message,t);break;case"ulid":AS(r,kS,s.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":OS(r,"binary",s.message,t);break;case"contentEncoding:base64":gS(r,"contentEncoding","base64",s.message,t);break;case"pattern:zod":AS(r,xS,s.message,t)}break;case"nanoid":AS(r,TS,s.message,t)}return r}const PS=e=>Array.from(e).map((e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`)).join(""),OS=(e,t,r,n)=>{e.format||e.anyOf?.some((e=>e.format))?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):gS(e,"format",t,r,n)},AS=(e,t,r,n)=>{e.pattern||e.allOf?.some((e=>e.pattern))?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:IS(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):gS(e,"pattern",IS(t,n),r,n)},IS=(e,t)=>{const r="function"==typeof e?e():e;if(!t.applyRegexFlags||!r.flags)return r.source;const n=r.flags.includes("i"),s=r.flags.includes("m"),a=r.flags.includes("s"),i=n?r.source.toLowerCase():r.source;let o="",c=!1,l=!1,u=!1;for(let e=0;e({...r,[n]:FS(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??{}})),{}),additionalProperties:!1};const r={type:"object",additionalProperties:FS(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===M.kY.ZodString&&e.keyType._def.checks?.length){const n=Object.entries(CS(e.keyType._def,t)).reduce(((e,[t,r])=>"type"===t?e:{...e,[t]:r}),{});return{...r,propertyNames:n}}return e.keyType?._def.typeName===M.kY.ZodEnum?{...r,propertyNames:{enum:e.keyType._def.values}}:r}const RS={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const jS=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map(((e,r)=>FS(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]}))).filter((e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0)));return r.length?{anyOf:r}:void 0};function NS(e,t){return"strict"===t.removeAdditionalStrategy?"ZodNever"===e.catchall._def.typeName?"strict"!==e.unknownKeys:FS(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0:"ZodNever"===e.catchall._def.typeName?"passthrough"===e.unknownKeys:FS(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0}const $S=Symbol("Let zodToJsonSchema decide on which parser to use"),LS={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"};function FS(e,t,r=!1){const n=t.seen.get(e);if(t.override){const s=t.override?.(e,t,n,r);if(s!==$S)return s}if(n&&!r){const e=DS(n,t);if(void 0!==e)return"$ref"in e&&t.seenRefs.add(e.$ref),e}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=US(e,e.typeName,t,r);return a&&BS(e,t,a),s.jsonSchema=a,a}const DS=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"extract-to-root":const r=e.path.slice(t.basePath.length+1).join("_");return r!==t.name&&"duplicate-ref"===t.nameStrategy&&(t.definitions[r]=e.def),{$ref:[...t.basePath,t.definitionPath,r].join("/")};case"relative":return{$ref:zS(t.currentPath,e.path)};case"none":case"seen":return e.path.lengtht.currentPath[r]===e))?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{}):"seen"===t.$refStrategy?{}:void 0}},zS=(e,t)=>{let r=0;for(;r{switch(t){case M.kY.ZodString:return CS(e,r);case M.kY.ZodNumber:return function(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",fS(r,"type",n.message,t);break;case"min":"jsonSchema7"===t.target?n.inclusive?gS(r,"minimum",n.value,n.message,t):gS(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),gS(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?gS(r,"maximum",n.value,n.message,t):gS(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),gS(r,"maximum",n.value,n.message,t));break;case"multipleOf":gS(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case M.kY.ZodObject:return function(e,t){const r={type:"object",...Object.entries(e.shape()).reduce(((e,[r,n])=>{if(void 0===n||void 0===n._def)return e;const s=[...t.currentPath,"properties",r],a=FS(n._def,{...t,currentPath:s,propertyPath:s});return void 0===a?e:(t.openaiStrictMode&&n.isOptional()&&!n.isNullable()&&console.warn(`Zod field at \`${s.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\nThis will become an error in a future version of the SDK.`),{properties:{...e.properties,[r]:a},required:n.isOptional()&&!t.openaiStrictMode?e.required:[...e.required,r]})}),{properties:{},required:[]}),additionalProperties:NS(e,t)};return r.required.length||delete r.required,r}(e,r);case M.kY.ZodBigInt:return function(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":"jsonSchema7"===t.target?n.inclusive?gS(r,"minimum",n.value,n.message,t):gS(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),gS(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?gS(r,"maximum",n.value,n.message,t):gS(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),gS(r,"maximum",n.value,n.message,t));break;case"multipleOf":gS(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case M.kY.ZodBoolean:return{type:"boolean"};case M.kY.ZodDate:return yS(e,r);case M.kY.ZodUndefined:return{not:{}};case M.kY.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(r);case M.kY.ZodArray:return function(e,t){const r={type:"array"};return e.type?._def?.typeName!==M.kY.ZodAny&&(r.items=FS(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&gS(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&gS(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(gS(r,"minItems",e.exactLength.value,e.exactLength.message,t),gS(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}(e,r);case M.kY.ZodUnion:case M.kY.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return jS(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((e=>e._def.typeName in RS&&(!e._def.checks||!e._def.checks.length)))){const e=r.reduce(((e,t)=>{const r=RS[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e}),[]);return{type:e.length>1?e:e[0]}}if(r.every((e=>"ZodLiteral"===e._def.typeName&&!e.description))){const e=r.reduce(((e,t)=>{const r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}}),[]);if(e.length===r.length){const t=e.filter(((e,t,r)=>r.indexOf(e)===t));return{type:t.length>1?t:t[0],enum:r.reduce(((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value]),[])}}}else if(r.every((e=>"ZodEnum"===e._def.typeName)))return{type:"string",enum:r.reduce(((e,t)=>[...e,...t._def.values.filter((t=>!e.includes(t)))]),[])};return jS(e,t)}(e,r);case M.kY.ZodIntersection:return function(e,t){const r=[FS(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),FS(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((e=>!!e));let n="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const s=[];return r.forEach((e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:r,...n}=e;t=n}else n=void 0;s.push(t)}else s.push(...e.allOf),void 0===e.unevaluatedProperties&&(n=void 0);var t})),s.length?{allOf:s,...n}:void 0}(e,r);case M.kY.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map(((e,r)=>FS(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[]),additionalItems:FS(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map(((e,r)=>FS(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[])}}(e,r);case M.kY.ZodRecord:return MS(e,r);case M.kY.ZodLiteral:return function(e,t){const r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}(e,r);case M.kY.ZodEnum:return function(e){return{type:"string",enum:[...e.values]}}(e);case M.kY.ZodNativeEnum:return function(e){const t=e.values,r=Object.keys(e.values).filter((e=>"number"!=typeof t[t[e]])),n=r.map((e=>t[e])),s=Array.from(new Set(n.map((e=>typeof e))));return{type:1===s.length?"string"===s[0]?"string":"number":["string","number"],enum:n}}(e);case M.kY.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target||"property"===t.nullableStrategy?{type:RS[e.innerType._def.typeName],nullable:!0}:{type:[RS[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const r=FS(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=FS(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case M.kY.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return FS(e.innerType._def,t);const r=FS(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}})(e,r);case M.kY.ZodMap:return function(e,t){return"record"===t.mapStrategy?MS(e,t):{type:"array",maxItems:125,items:{type:"array",items:[FS(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},FS(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}(e,r);case M.kY.ZodSet:return function(e,t){const r={type:"array",uniqueItems:!0,items:FS(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&gS(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&gS(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}(e,r);case M.kY.ZodLazy:return FS(e.getter()._def,r);case M.kY.ZodPromise:return function(e,t){return FS(e.type._def,t)}(e,r);case M.kY.ZodNaN:case M.kY.ZodNever:return{not:{}};case M.kY.ZodEffects:return function(e,t,r){return"input"===t.effectStrategy?FS(e.schema._def,t,r):{}}(e,r,n);case M.kY.ZodAny:case M.kY.ZodUnknown:return{};case M.kY.ZodDefault:return function(e,t){return{...FS(e.innerType._def,t),default:e.defaultValue()}}(e,r);case M.kY.ZodBranded:return function(e,t){return FS(e.type._def,t)}(e,r);case M.kY.ZodReadonly:case M.kY.ZodCatch:return((e,t)=>FS(e.innerType._def,t))(e,r);case M.kY.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return FS(e.in._def,t);if("output"===t.pipeStrategy)return FS(e.out._def,t);const r=FS(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,FS(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter((e=>void 0!==e))}})(e,r);case M.kY.ZodFunction:case M.kY.ZodVoid:case M.kY.ZodSymbol:default:return}},BS=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),qS=e=>"_def"in e?e._def:e;const KS=e=>{const t=(e=>"string"==typeof e?{...LS,basePath:["#"],definitions:{},name:e}:{...LS,basePath:["#"],definitions:{},...e})(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(t.definitions).map((([e,r])=>[qS(r),{def:qS(r),path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}])))}};function WS(e,t){return((e,t)=>{const r=KS(t),n="string"==typeof t?t:"title"===t?.nameStrategy?void 0:t?.name,s=FS(e._def,void 0===n?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},a="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==a&&(s.title=a);const i=(()=>{if(function(e){if(!e)return!0;for(const t in e)return!1;return!0}(r.definitions))return;const e={},t=new Set;for(let n=0;n<500;n++){const n=Object.entries(r.definitions).filter((([e])=>!t.has(e)));if(0===n.length)break;for(const[s,a]of n)e[s]=FS(qS(a),{...r,currentPath:[...r.basePath,r.definitionPath,s]},!0)??{},t.add(s)}return e})(),o=void 0===n?i?{...s,[r.definitionPath]:i}:s:"duplicate-ref"===r.nameStrategy?{...s,...i||r.seenRefs.size?{[r.definitionPath]:{...i,...r.seenRefs.size?{[n]:s}:void 0}}:void 0}:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...i,[n]:s}};return"jsonSchema7"===r.target?o.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"===r.target&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o})(e,{openaiStrictMode:!0,name:t.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function HS(e,t,r){return function(e,t){const r={...e};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),r}({type:"json_schema",json_schema:{...r,name:t,strict:!0,schema:WS(e,{name:t})}},(t=>e.parse(JSON.parse(t))))}function VS(e){const{azureOpenAIApiDeploymentName:t,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:s,baseURL:a,azureADTokenProvider:i,azureOpenAIEndpoint:o}=e;if((n||i)&&s&&t)return`${s}/${t}`;if((n||i)&&o&&t)return`${o}/openai/deployments/${t}`;if(n||i){if(!r)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!t)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${t}`}return a}function GS(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t}/\n`,e}function JS(e){let t;return e.constructor.name===Yy.name?(t=new Error(e.message),t.name="TimeoutError"):e.constructor.name===Jy.name?(t=new Error(e.message),t.name="AbortError"):t=400===e.status&&e.message.includes("tool_calls")?GS(e,"INVALID_TOOL_RESULTS"):401===e.status?GS(e,"MODEL_AUTHENTICATION"):429===e.status?GS(e,"MODEL_RATE_LIMIT"):404===e.status?GS(e,"MODEL_NOT_FOUND"):e,t}function ZS(e){return e?"any"===e||"required"===e?"required":"auto"===e?"auto":"none"===e?"none":"string"==typeof e?{type:"function",function:{name:e}}:e:void 0}function YS(e,t){const r=[];for(const[n,s]of Object.entries(e.properties??{}))s.description&&t<2&&r.push(`// ${s.description}`),e.required?.includes(n)?r.push(`${n}: ${XS(s,t)},`):r.push(`${n}?: ${XS(s,t)},`);return r.map((e=>" ".repeat(t)+e)).join("\n")}function XS(e,t){if(void 0!==(r=e).anyOf&&Array.isArray(r.anyOf))return e.anyOf.map((e=>XS(e,t))).join(" | ");var r;switch(e.type){case"string":return e.enum?e.enum.map((e=>`"${e}"`)).join(" | "):"string";case"number":case"integer":return e.enum?e.enum.map((e=>`${e}`)).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",YS(e,t+2),"}"].join("\n");case"array":return e.items?`${XS(e.items,t)}[]`:"any[]";default:return""}}function QS(e){const t=e._getType();switch(t){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!se.ChatMessage.isInstance(e))throw new Error("Invalid generic chat message");return function(e){return"system"!==e.role&&"developer"!==e.role&&"assistant"!==e.role&&"user"!==e.role&&"function"!==e.role&&"tool"!==e.role&&console.warn(`Unknown message role: ${e.role}`),e.role}(e);default:throw new Error(`Unknown message type: ${t}`)}}const eE={providerName:"ChatOpenAI",fromStandardTextBlock:e=>({type:"text",text:e.text}),fromStandardImageBlock(e){if("url"===e.source_type)return{type:"image_url",image_url:{url:e.url,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};if("base64"===e.source_type){return{type:"image_url",image_url:{url:`data:${e.mime_type??""};base64,${e.data}`,...e.metadata?.detail?{detail:e.metadata.detail}:{}}}}throw new Error(`Image content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(e){if("url"===e.source_type){const t=(0,se.parseBase64DataUrl)({dataUrl:e.url});if(!t)throw new Error(`URL audio blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);const r=t.mime_type||e.mime_type||"";let n;try{n=(0,se.parseMimeType)(r)}catch{throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if("audio"!==n.type||"wav"!==n.subtype&&"mp3"!==n.subtype)throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:n.subtype,data:t.data}}}if("base64"===e.source_type){let t;try{t=(0,se.parseMimeType)(e.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if("audio"!==t.type||"wav"!==t.subtype&&"mp3"!==t.subtype)throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:t.subtype,data:e.data}}}throw new Error(`Audio content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(e){if("url"===e.source_type){if(!(0,se.parseBase64DataUrl)({dataUrl:e.url}))throw new Error(`URL file blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:e.url,...e.metadata?.filename||e.metadata?.name?{filename:e.metadata?.filename||e.metadata?.name}:{}}}}if("base64"===e.source_type)return{type:"file",file:{file_data:`data:${e.mime_type??""};base64,${e.data}`,...e.metadata?.filename||e.metadata?.name||e.metadata?.title?{filename:e.metadata?.filename||e.metadata?.name||e.metadata?.title}:{}}};if("id"===e.source_type)return{type:"file",file:{file_id:e.id}};throw new Error(`File content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)}};function tE(e,t){return e.flatMap((e=>{let r=QS(e);"system"===r&&cE(t)&&(r="developer");const n={role:r,content:"string"==typeof e.content?e.content:e.content.map((e=>(0,se.isDataContentBlock)(e)?(0,se.convertToProviderContentBlock)(e,eE):e))};if(null!=e.name&&(n.name=e.name),null!=e.additional_kwargs.function_call&&(n.function_call=e.additional_kwargs.function_call,n.content=""),(0,se.isAIMessage)(e)&&e.tool_calls?.length?(n.tool_calls=e.tool_calls.map(dS),n.content=""):(null!=e.additional_kwargs.tool_calls&&(n.tool_calls=e.additional_kwargs.tool_calls),null!=e.tool_call_id&&(n.tool_call_id=e.tool_call_id)),e.additional_kwargs.audio&&"object"==typeof e.additional_kwargs.audio&&"id"in e.additional_kwargs.audio){return[n,{role:"assistant",audio:{id:e.additional_kwargs.audio.id}}]}return n}))}const rE="__openai_function_call_ids__";function nE(e,t,r){const n=e.filter((e=>(0,se.isAIMessage)(e))).pop(),s=n?.response_metadata?.id;return(s&&s.startsWith("resp_")&&!r?e.slice(e.indexOf(n)+1):e).flatMap((e=>{let n=QS(e);if("system"===n&&cE(t)&&(n="developer"),"function"===n)throw new Error("Function messages are not supported in Responses API");if("tool"===n){const t=e;if("computer_call_output"===t.additional_kwargs?.type){const e=(()=>{if("string"==typeof t.content)return{type:"computer_screenshot",image_url:t.content};if(Array.isArray(t.content)){const e=t.content.find((e=>"computer_screenshot"===e.type));if(e)return e;const r=t.content.find((e=>"image_url"===e.type));if(r)return{type:"computer_screenshot",image_url:"string"==typeof r.image_url?r.image_url:r.image_url.url}}throw new Error("Invalid computer call output")})();return{type:"computer_call_output",output:e,call_id:t.tool_call_id}}return{type:"function_call_output",call_id:t.tool_call_id,id:t.id,output:"string"!=typeof t.content?JSON.stringify(t.content):t.content}}if("assistant"===n){if(!r&&null!=e.response_metadata.output&&Array.isArray(e.response_metadata.output)&&e.response_metadata.output.length>0&&e.response_metadata.output.every((e=>"type"in e)))return e.response_metadata.output;const t=[];if(!r&&null!=e.additional_kwargs.reasoning){if((e=>"object"==typeof e&&null!=e&&"type"in e&&"reasoning"===e.type)(e.additional_kwargs.reasoning)){const r=function(e){const t=(e.summary.length>1?e.summary.reduce(((e,t)=>{const r=e.at(-1);return r.index===t.index?r.text+=t.text:e.push(t),e}),[{...e.summary[0]}]):e.summary).map((e=>Object.fromEntries(Object.entries(e).filter((([e])=>"index"!==e)))));return{...e,summary:t}}(e.additional_kwargs.reasoning);t.push(r)}}let{content:n}=e;null!=e.additional_kwargs.refusal&&("string"==typeof n&&(n=[{type:"output_text",text:n,annotations:[]}]),n=[...n,{type:"refusal",refusal:e.additional_kwargs.refusal}]),t.push({type:"message",role:"assistant",...e.id&&!r?{id:e.id}:{},content:"string"==typeof n?n:n.flatMap((e=>"text"===e.type?{type:"output_text",text:e.text,annotations:e.annotations??[]}:"output_text"===e.type||"refusal"===e.type?e:[]))});const s=e.additional_kwargs[rE];(0,se.isAIMessage)(e)&&e.tool_calls?.length?t.push(...e.tool_calls.map((e=>({type:"function_call",name:e.name,arguments:JSON.stringify(e.args),call_id:e.id,...r?{id:s?.[e.id]}:{}})))):null!=e.additional_kwargs.tool_calls&&t.push(...e.additional_kwargs.tool_calls.map((e=>({type:"function_call",name:e.function.name,call_id:e.id,...r?{id:s?.[e.id]}:{},arguments:e.function.arguments}))));const a=e.response_metadata.output?.length?e.response_metadata.output:e.additional_kwargs.tool_outputs;let i=[];if(null!=a){const e=a;i=e?.filter((e=>"computer_call"===e.type)),i.length>0&&t.push(...i)}return t}const s="string"==typeof e.content?e.content:e.content.flatMap((e=>{if((0,se.isDataContentBlock)(e))return(0,se.convertToProviderContentBlock)(e,eE);if("text"===e.type)return{type:"input_text",text:e.text};if("image_url"===e.type){return{type:"input_image",image_url:"string"==typeof e.image_url?e.image_url:e.image_url.url,detail:"string"==typeof e.image_url?"auto":e.image_url.detail}}return"input_text"===e.type||"input_image"===e.type||"input_file"===e.type?e:[]}));return"user"===n||"system"===n||"developer"===n?{type:"message",role:n,content:s}:(console.warn(`Unsupported role found when converting to OpenAI Responses API: ${n}`),[])}))}function sE(e){if(e.error){const t=new Error(e.error.message);throw t.name=e.error.code,t}let t;const r=[],n=[],s=[],a={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,model_name:e.model},i={};for(const a of e.output)if("message"===a.type)t=a.id,r.push(...a.content.flatMap((e=>"output_text"===e.type?("parsed"in e&&null!=e.parsed&&(i.parsed=e.parsed),{type:"text",text:e.text,annotations:e.annotations}):"refusal"===e.type?(i.refusal=e.refusal,[]):e)));else if("function_call"===a.type){const e={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{n.push(uS(e,{returnId:!0}))}catch(t){let r;"object"==typeof t&&null!=t&&"message"in t&&"string"==typeof t.message&&(r=t.message),s.push(hS(e,r))}i[rE]??={},a.id&&(i[rE][a.call_id]=a.id)}else"reasoning"===a.type?i.reasoning=a:(i.tool_outputs??=[],i.tool_outputs.push(a));return new se.AIMessage({id:t,content:r,tool_calls:n,invalid_tool_calls:s,usage_metadata:e.usage,additional_kwargs:i,response_metadata:a})}function aE(e){const t=[];let r,n={};const s=[],a={},i={};let o;if("response.output_text.delta"===e.type)t.push({type:"text",text:e.delta,index:e.content_index});else if("response.output_text.annotation.added"===e.type)t.push({type:"text",text:"",annotations:[e.annotation],index:e.content_index});else if("response.output_item.added"===e.type&&"message"===e.item.type)o=e.item.id;else if("response.output_item.added"===e.type&&"function_call"===e.item.type)s.push({type:"tool_call_chunk",name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),i[rE]={[e.item.call_id]:e.item.id};else if("response.output_item.done"!==e.type||"web_search_call"!==e.item.type&&"file_search_call"!==e.item.type&&"computer_call"!==e.item.type)if("response.created"===e.type)a.id=e.response.id,a.model_name=e.response.model,a.model=e.response.model;else if("response.completed"===e.type){const t=sE(e.response);r=e.response.usage,"json_schema"===e.response.text?.format?.type&&(i.parsed??=JSON.parse(t.text));for(const[t,r]of Object.entries(e.response))"id"!==t&&(a[t]=r)}else if("response.function_call_arguments.delta"===e.type)s.push({type:"tool_call_chunk",args:e.delta,index:e.output_index});else if("response.web_search_call.completed"===e.type||"response.file_search_call.completed"===e.type)n={tool_outputs:{id:e.item_id,type:e.type.replace("response.","").replace(".completed",""),status:"completed"}};else if("response.refusal.done"===e.type)i.refusal=e.refusal;else if("response.output_item.added"===e.type&&"item"in e&&"reasoning"===e.item.type){const t=e.item.summary?e.item.summary.map(((e,t)=>({...e,index:t}))):void 0;i.reasoning={id:e.item.id,type:e.item.type,...t?{summary:t}:{}}}else if("response.reasoning_summary_part.added"===e.type)i.reasoning={type:"reasoning",summary:[{...e.part,index:e.summary_index}]};else{if("response.reasoning_summary_text.delta"!==e.type)return null;i.reasoning={type:"reasoning",summary:[{text:e.delta,type:"summary_text",index:e.summary_index}]}}else i.tool_outputs=[e.item];return new $t.ChatGenerationChunk({text:t.map((e=>e.text)).join(""),message:new se.AIMessageChunk({id:o,content:t,tool_call_chunks:s,usage_metadata:r,additional_kwargs:i,response_metadata:a}),generationInfo:n})}function iE(e){return"type"in e&&"function"!==e.type}function oE(e,t){return It(e)?void 0!==t?.strict?{...e,function:{...e.function,strict:t.strict}}:e:function(e,t){let r;return r=hn(e)?In(e):e,void 0!==t?.strict&&(r.function.strict=t.strict),r}(e,t)}function cE(e){return e&&/^o\d/.test(e)}class lE extends zt{static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning_effort"]}get lc_secrets(){return{openAIApiKey:"OPENAI_API_KEY",apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{modelName:"model",openAIApiKey:"openai_api_key",apiKey:"openai_api_key"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","reasoningEffort","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","modelName","model","modelKwargs","stop","stopSequences","timeout","openAIApiKey","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","useResponsesApi","zdrEnabled","reasoning"]}constructor(e){super(e??{}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),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,"modelName",{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,"openAIApiKey",{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,"reasoningEffort",{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,"useResponsesApi",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zdrEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.openAIApiKey=e?.apiKey??e?.openAIApiKey??e?.configuration?.apiKey??(0,Sn.getEnvironmentVariable)("OPENAI_API_KEY"),this.apiKey=this.openAIApiKey,this.organization=e?.configuration?.organization??(0,Sn.getEnvironmentVariable)("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelName=this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoningEffort=e?.reasoningEffort??e?.reasoning?.effort,this.reasoning=e?.reasoning??(e?.reasoningEffort?{effort:e.reasoningEffort}:void 0),this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.useResponsesApi=e?.useResponsesApi??this.useResponsesApi,this.disableStreaming=e?.disableStreaming??this.disableStreaming,"o1"===this.model&&(this.disableStreaming=!0),this.streaming=e?.streaming??!1,this.disableStreaming&&(this.streaming=!1),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},void 0!==e?.supportsStrictToolCalling&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),this.zdrEnabled=e?.zdrEnabled??!1}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}}bindTools(e,t){let r;return void 0!==t?.strict?r=t.strict:void 0!==this.supportsStrictToolCalling&&(r=this.supportsStrictToolCalling),this.bind({tools:e.map((e=>iE(e)?e:oE(e,{strict:r}))),...t})}createResponseFormat(e){return e&&"json_schema"===e.type&&e.json_schema.schema&&uE(e.json_schema.schema)?HS(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}getReasoningParams(e){if(!cE(this.model))return;let t;return void 0!==this.reasoningEffort&&(t={effort:this.reasoningEffort}),void 0!==this.reasoning&&(t={...t,...this.reasoning}),void 0!==e?.reasoning_effort&&(t={...t,effort:e.reasoning_effort}),void 0!==e?.reasoning&&(t={...t,...e.reasoning}),t}invocationParams(e,t){let r;if(void 0!==e?.strict?r=e.strict:void 0!==this.supportsStrictToolCalling&&(r=this.supportsStrictToolCalling),this._useResponseApi(e)){const t={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,stream:this.streaming,previous_response_id:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?e.tools.map((e=>iE(e)?e:It(e)?{type:"function",name:e.function.name,parameters:e.function.parameters,description:e.function.description,strict:r}:null)).filter((e=>null!==e)):void 0,tool_choice:(n=e?.tool_choice,null!=n&&"object"==typeof n&&"type"in n&&"function"!==n.type?e?.tool_choice:(()=>{const t=ZS(e?.tool_choice);return"object"==typeof t&&"type"in t?{type:"function",name:t.function.name}:void 0})()),text:(()=>{if(e?.text)return e.text;const t=this.createResponseFormat(e?.response_format);return"json_schema"===t?.type?null!=t.json_schema.schema?{format:{type:"json_schema",schema:t.json_schema.schema,description:t.json_schema.description,name:t.json_schema.name,strict:t.json_schema.strict}}:void 0:{format:t}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:-1===this.maxTokens?void 0:this.maxTokens,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},s=this.getReasoningParams(e);return void 0!==s&&(t.reasoning=s),t}var n;let s={};void 0!==e?.stream_options?s={stream_options:e.stream_options}:this.streamUsage&&(this.streaming||t?.streaming)&&(s={stream_options:{include_usage:!0}});const a={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map((e=>oE(e,{strict:r}))):void 0,tool_choice:ZS(e?.tool_choice),response_format:this.createResponseFormat(e?.response_format),seed:e?.seed,...s,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs};void 0!==e?.prediction&&(a.prediction=e.prediction);const i=this.getReasoningParams(e);return void 0!==i&&void 0!==i.effort&&(a.reasoning_effort=i.effort),cE(a.model)?a.max_completion_tokens=-1===this.maxTokens?void 0:this.maxTokens:a.max_tokens=-1===this.maxTokens?void 0:this.maxTokens,a}_convertOpenAIChatCompletionMessageToBaseMessage(e,t){const r=e.tool_calls;if("assistant"===e.role){const n=[],s=[];for(const e of r??[])try{n.push(uS(e,{returnId:!0}))}catch(t){s.push(hS(e,t.message))}const a={function_call:e.function_call,tool_calls:r};void 0!==this.__includeRawResponse&&(a.__raw_response=t);const i={model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};return e.audio&&(a.audio=e.audio),new se.AIMessage({content:e.content||"",tool_calls:n,invalid_tool_calls:s,additional_kwargs:a,response_metadata:i,id:t.id})}return new se.ChatMessage(e.content||"",e.role??"unknown")}_convertOpenAIDeltaToBaseMessageChunk(e,t,r){const n=e.role??r,s=e.content??"";let a;a=e.function_call?{function_call:e.function_call}:e.tool_calls?{tool_calls:e.tool_calls}:{},this.__includeRawResponse&&(a.__raw_response=t),e.audio&&(a.audio={...e.audio,index:t.choices[0].index});const i={usage:{...t.usage}};if("user"===n)return new se.HumanMessageChunk({content:s,response_metadata:i});if("assistant"===n){const r=[];if(Array.isArray(e.tool_calls))for(const t of e.tool_calls)r.push({name:t.function?.name,args:t.function?.arguments,id:t.id,index:t.index,type:"tool_call_chunk"});return new se.AIMessageChunk({content:s,tool_call_chunks:r,additional_kwargs:a,id:t.id,response_metadata:i})}return"system"===n?new se.SystemMessageChunk({content:s,response_metadata:i}):"developer"===n?new se.SystemMessageChunk({content:s,response_metadata:i,additional_kwargs:{__openai_role__:"developer"}}):"function"===n?new se.FunctionMessageChunk({content:s,additional_kwargs:a,name:e.name,response_metadata:i}):"tool"===n?new se.ToolMessageChunk({content:s,additional_kwargs:a,tool_call_id:e.tool_call_id,response_metadata:i}):new se.ChatMessageChunk({content:s,role:n,response_metadata:i})}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}async*_streamResponseChunks(e,t,r){if(this._useResponseApi(t)){const r=e.filter((e=>(0,se.isAIMessage)(e))).pop(),n=r?.response_metadata?.id,s=await this.responseApiWithRetry({...this.invocationParams(t,{streaming:!0}),input:nE(e,this.model,this.zdrEnabled),stream:!0,...n&&n.startsWith("resp_")&&!this.zdrEnabled?{previous_response_id:n}:{}},t);for await(const e of s){const t=aE(e);null!=t&&(yield t)}return}const n=tE(e,this.model),s={...this.invocationParams(t,{streaming:!0}),messages:n,stream:!0};let a;const i=await this.completionWithRetry(s,t);let o;for await(const e of i){const n=e?.choices?.[0];if(e.usage&&(o=e.usage),!n)continue;const{delta:s}=n;if(!s)continue;const i=this._convertOpenAIDeltaToBaseMessageChunk(s,e,a);a=s.role??a;const c={prompt:t.promptIndex??0,completion:n.index??0};if("string"!=typeof i.content){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}const l={...c};null!=n.finish_reason&&(l.finish_reason=n.finish_reason,l.system_fingerprint=e.system_fingerprint,l.model_name=e.model),this.logprobs&&(l.logprobs=n.logprobs);const u=new $t.ChatGenerationChunk({message:i,text:i.content,generationInfo:l});yield u,await(r?.handleLLMNewToken(u.text??"",c,void 0,void 0,void 0,{chunk:u}))}if(o){const e={...null!==o.prompt_tokens_details?.audio_tokens&&{audio:o.prompt_tokens_details?.audio_tokens},...null!==o.prompt_tokens_details?.cached_tokens&&{cache_read:o.prompt_tokens_details?.cached_tokens}},t={...null!==o.completion_tokens_details?.audio_tokens&&{audio:o.completion_tokens_details?.audio_tokens},...null!==o.completion_tokens_details?.reasoning_tokens&&{reasoning:o.completion_tokens_details?.reasoning_tokens}},r=new $t.ChatGenerationChunk({message:new se.AIMessageChunk({content:"",response_metadata:{usage:{...o}},usage_metadata:{input_tokens:o.prompt_tokens,output_tokens:o.completion_tokens,total_tokens:o.total_tokens,...Object.keys(e).length>0&&{input_token_details:e},...Object.keys(t).length>0&&{output_token_details:t}}}),text:""});yield r}if(t.signal?.aborted)throw new Error("AbortError")}identifyingParams(){return this._identifyingParams()}async _responseApiGenerate(e,t,r){const n=this.invocationParams(t);if(n.stream){const n=this._streamResponseChunks(e,t,r);let s;for await(const e of n)e.message.response_metadata={...e.generationInfo,...e.message.response_metadata},s=s?.concat(e)??e;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}const s=e.filter((e=>(0,se.isAIMessage)(e))).pop(),a=s?.response_metadata?.id,i=nE(e,this.model,this.zdrEnabled),o=await this.responseApiWithRetry({input:i,...n,...a&&a.startsWith("resp_")&&!this.zdrEnabled?{previous_response_id:a}:{}},{signal:t?.signal,...t?.options});return{generations:[{text:o.output_text,message:sE(o)}],llmOutput:{id:o.id,estimatedTokenUsage:o.usage?{promptTokens:o.usage.input_tokens,completionTokens:o.usage.output_tokens,totalTokens:o.usage.total_tokens}:void 0}}}_useResponseApi(e){const t=e?.tools?.some(iE),r=null!=e?.previous_response_id||null!=e?.text||null!=e?.truncation||null!=e?.include||null!=e?.reasoning?.summary||null!=this.reasoning?.summary;return this.useResponsesApi||t||r}async _generate(e,t,r){if(this._useResponseApi(t))return this._responseApiGenerate(e,t,r);const n={},s=this.invocationParams(t),a=tE(e,this.model);if(s.stream){const s=this._streamResponseChunks(e,t,r),a={};for await(const e of s){e.message.response_metadata={...e.generationInfo,...e.message.response_metadata};const t=e.generationInfo?.completion??0;void 0===a[t]?a[t]=e:a[t]=a[t].concat(e)}const i=Object.entries(a).sort((([e],[t])=>parseInt(e,10)-parseInt(t,10))).map((([e,t])=>t)),{functions:o,function_call:c}=this.invocationParams(t),l=await this.getEstimatedTokenCountFromPrompt(e,o,c),u=await this.getNumTokensFromGenerations(i);return n.input_tokens=l,n.output_tokens=u,n.total_tokens=l+u,{generations:i,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}{let e;e=t.response_format&&"json_schema"===t.response_format.type?await this.betaParsedCompletionWithRetry({...s,stream:!1,messages:a},{signal:t?.signal,...t?.options}):await this.completionWithRetry({...s,stream:!1,messages:a},{signal:t?.signal,...t?.options});const{completion_tokens:r,prompt_tokens:i,total_tokens:o,prompt_tokens_details:c,completion_tokens_details:l}=e?.usage??{};r&&(n.output_tokens=(n.output_tokens??0)+r),i&&(n.input_tokens=(n.input_tokens??0)+i),o&&(n.total_tokens=(n.total_tokens??0)+o),null===c?.audio_tokens&&null===c?.cached_tokens||(n.input_token_details={...null!==c?.audio_tokens&&{audio:c?.audio_tokens},...null!==c?.cached_tokens&&{cache_read:c?.cached_tokens}}),null===l?.audio_tokens&&null===l?.reasoning_tokens||(n.output_token_details={...null!==l?.audio_tokens&&{audio:l?.audio_tokens},...null!==l?.reasoning_tokens&&{reasoning:l?.reasoning_tokens}});const u=[];for(const t of e?.choices??[]){const r={text:t.message?.content??"",message:this._convertOpenAIChatCompletionMessageToBaseMessage(t.message??{role:"assistant"},e)};r.generationInfo={...t.finish_reason?{finish_reason:t.finish_reason}:{},...t.logprobs?{logprobs:t.logprobs}:{}},(0,se.isAIMessage)(r.message)&&(r.message.usage_metadata=n),r.message=new se.AIMessage(Object.fromEntries(Object.entries(r.message).filter((([e])=>!e.startsWith("lc_"))))),u.push(r)}return{generations:u,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async getEstimatedTokenCountFromPrompt(e,t,r){let n=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&"auto"!==r){const e=function(e){const t=["namespace functions {",""];for(const r of e)r.description&&t.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(t.push(`type ${r.name} = (_: {`),t.push(YS(r.parameters,0)),t.push("}) => any;")):t.push(`type ${r.name} = () => any;`),t.push("");return t.push("} // namespace functions"),t.join("\n")}(t);n+=await this.getNumTokens(e),n+=9}return t&&e.find((e=>"system"===e._getType()))&&(n-=4),"none"===r?n+=1:"object"==typeof r&&(n+=await this.getNumTokens(r.name)+4),n}async getNumTokensFromGenerations(e){return(await Promise.all(e.map((async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content))))).reduce(((e,t)=>e+t),0)}async getNumTokensFromMessages(e){let t=0,r=0,n=0;"gpt-3.5-turbo-0301"===this.model?(r=4,n=-1):(r=3,n=1);const s=await Promise.all(e.map((async e=>{const s=await this.getNumTokens(e.content),a=await this.getNumTokens(QS(e)),i=void 0!==e.name?n+await this.getNumTokens(e.name):0;let o=s+r+a+i;const c=e;if("function"===c._getType()&&(o-=2),c.additional_kwargs?.function_call&&(o+=3),c?.additional_kwargs.function_call?.name&&(o+=await this.getNumTokens(c.additional_kwargs.function_call?.name)),c.additional_kwargs.function_call?.arguments)try{o+=await this.getNumTokens(JSON.stringify(JSON.parse(c.additional_kwargs.function_call?.arguments)))}catch(e){console.error("Error parsing function arguments",e,JSON.stringify(c.additional_kwargs.function_call)),o+=await this.getNumTokens(c.additional_kwargs.function_call?.arguments)}return t+=o,o})));return t+=3,{totalCount:t,countPerMessage:s}}async completionWithRetry(e,t){const r=this._getClientOptions(t);return this.caller.call((async()=>{try{return await this.client.chat.completions.create(e,r)}catch(e){throw JS(e)}}))}async responseApiWithRetry(e,t){return this.caller.call((async()=>{const r=this._getClientOptions(t);try{return"json_schema"!==e.text?.format?.type||e.stream?await this.client.responses.create(e,r):await this.client.responses.parse(e,r)}catch(e){throw JS(e)}}))}async betaParsedCompletionWithRetry(e,t){const r=this._getClientOptions(t);return this.caller.call((async()=>{try{return await this.client.beta.chat.completions.parse(e,r)}catch(e){throw JS(e)}}))}_getClientOptions(e){if(!this.client){const e=VS({baseURL:this.clientConfig.baseURL}),t={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};t.baseURL||delete t.baseURL,this.client=new Tk(t)}return{...this.clientConfig,...e}}_llmType(){return"openai"}_combineLLMOutput(...e){return e.reduce(((e,t)=>(t&&t.tokenUsage&&(e.tokenUsage.completionTokens+=t.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=t.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=t.tokenUsage.totalTokens??0),e)),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}withStructuredOutput(e,t){let r,n,s,a;var i;let o,c;if(void 0!==(i=e)&&"object"==typeof i.schema?(r=e.schema,n=e.name,s=e.method,a=e.includeRaw):(r=e,n=t?.name,s=t?.method,a=t?.includeRaw),void 0!==t?.strict&&"jsonMode"===s)throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");if(this.model.startsWith("gpt-3")||this.model.startsWith("gpt-4-")||"gpt-4"===this.model?"jsonSchema"===s&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`):void 0===s&&(s="jsonSchema"),"jsonMode"===s)o=this.bind({response_format:{type:"json_object"}}),c=uE(r)?Ar.fromZodSchema(r):new Nr;else if("jsonSchema"===s)if(o=this.bind({response_format:{type:"json_schema",json_schema:{name:n??"extract",description:r.description,schema:r,strict:t?.strict}}}),uE(r)){const e=Ar.fromZodSchema(r);c=X.jY.from((t=>"parsed"in t.additional_kwargs?t.additional_kwargs.parsed:e))}else c=new Nr;else{let e=n??"extract";if(uE(r)){const n=(0,Nt.Ik)(r);o=this.bind({tools:[{type:"function",function:{name:e,description:n.description,parameters:n}}],tool_choice:{type:"function",function:{name:e}},...void 0!==t?.strict?{strict:t.strict}:{}}),c=new mS({returnSingle:!0,keyName:e,zodSchema:r})}else{let n;"string"==typeof r.name&&"object"==typeof r.parameters&&null!=r.parameters?(n=r,e=r.name):(e=r.title??e,n={name:e,description:r.description??"",parameters:r}),o=this.bind({tools:[{type:"function",function:n}],tool_choice:{type:"function",function:{name:e}},...void 0!==t?.strict?{strict:t.strict}:{}}),c=new mS({returnSingle:!0,keyName:e})}}if(!a)return o.pipe(c);const l=te.assign({parsed:(e,t)=>c.invoke(e.raw,t)}),u=te.assign({parsed:()=>null}),d=l.withFallbacks({fallbacks:[u]});return X.zZ.from([{raw:o},d])}}function uE(e){return"function"==typeof e?.parse}Object.defineProperty(class extends mn{static lc_name(){return"DallEAPIWrapper"}constructor(e){void 0!==e?.responseFormat&&["url","b64_json"].includes(e.responseFormat)&&(e.dallEResponseFormat=e.responseFormat,e.responseFormat="content"),super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description."}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"dall-e-3"}),Object.defineProperty(this,"style",{enumerable:!0,configurable:!0,writable:!0,value:"vivid"}),Object.defineProperty(this,"quality",{enumerable:!0,configurable:!0,writable:!0,value:"standard"}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:"1024x1024"}),Object.defineProperty(this,"dallEResponseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"url"}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const t={apiKey:e?.apiKey??e?.openAIApiKey??(0,Sn.getEnvironmentVariable)("OPENAI_API_KEY"),organization:e?.organization??(0,Sn.getEnvironmentVariable)("OPENAI_ORGANIZATION"),dangerouslyAllowBrowser:!0,baseURL:e?.baseUrl};this.client=new Tk(t),this.model=e?.model??e?.modelName??this.model,this.style=e?.style??this.style,this.quality=e?.quality??this.quality,this.n=e?.n??this.n,this.size=e?.size??this.size,this.dallEResponseFormat=e?.dallEResponseFormat??this.dallEResponseFormat,this.user=e?.user}processMultipleGeneratedUrls(e){return"url"===this.dallEResponseFormat?e.flatMap((e=>e.data?.flatMap((e=>e.url?{type:"image_url",image_url:e.url}:[])).filter((e=>void 0!==e&&"image_url"===e.type&&"string"==typeof e.image_url&&void 0!==e.image_url))??[])):e.flatMap((e=>e.data?.flatMap((e=>e.b64_json?{type:"image_url",image_url:{url:e.b64_json}}:[])).filter((e=>void 0!==e&&"image_url"===e.type&&"object"==typeof e.image_url&&"url"in e.image_url&&"string"==typeof e.image_url.url&&void 0!==e.image_url.url))??[]))}async _call(e){const t={model:this.model,prompt:e,n:1,size:this.size,response_format:this.dallEResponseFormat,style:this.style,quality:this.quality,user:this.user};if(this.n>1){const e=await Promise.all(Array.from({length:this.n}).map((()=>this.client.images.generate(t))));return this.processMultipleGeneratedUrls(e)}const r=await this.client.images.generate(t);let n="";return"url"===this.dallEResponseFormat?[n]=r.data?.map((e=>e.url)).filter((e=>"undefined"!==e))??[]:[n]=r.data?.map((e=>e.b64_json)).filter((e=>"undefined"!==e))??[],n}},"toolName",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"});const dE="0.39.0";let hE,pE,mE,fE,gE,yE,bE=!1,wE=null,vE=null,_E=null,kE=null,SE=null,EE=null,xE=null;class TE{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}hE||function(e,t={auto:!1}){if(bE)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${e.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(hE)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${e.kind}'\` after \`import '@anthropic-ai/sdk/shims/${hE}'\``);bE=t.auto,hE=e.kind,pE=e.fetch,wE=e.Request,vE=e.Response,_E=e.Headers,kE=e.FormData,SE=e.Blob,mE=e.File,fE=e.ReadableStream,EE=e.getMultipartRequestOptions,gE=e.getDefaultAgent,yE=e.fileFromPath,xE=e.isFsReadStream}(function({manuallyImported:e}={}){const t=e?"You may need to use polyfills":"Add one of these imports before your first `import … from '@anthropic-ai/sdk'`:\n- `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n- `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n";let r,n,s,a;try{r=fetch,n=Request,s=Response,a=Headers}catch(e){throw new Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${t}`)}return{kind:"web",fetch:r,Request:n,Response:s,Headers:a,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new TE(e)}),getDefaultAgent:e=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads")},isFsReadStream:e=>!1}}(),{auto:!0});class CE extends Error{}class PE extends CE{constructor(e,t,r,n){super(`${PE.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.request_id=n?.["request-id"],this.error=t}static makeMessage(e,t,r){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new AE({message:r,cause:Ex(t)});const s=t;return 400===e?new ME(e,s,r,n):401===e?new RE(e,s,r,n):403===e?new jE(e,s,r,n):404===e?new NE(e,s,r,n):409===e?new $E(e,s,r,n):422===e?new LE(e,s,r,n):429===e?new FE(e,s,r,n):e>=500?new DE(e,s,r,n):new PE(e,s,r,n)}}class OE extends PE{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class AE extends PE{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class IE extends AE{constructor({message:e}={}){super({message:e??"Request timed out."})}}class ME extends PE{}class RE extends PE{}class jE extends PE{}class NE extends PE{}class $E extends PE{}class LE extends PE{}class FE extends PE{}class DE extends PE{}var zE,UE=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},BE=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class qE{constructor(){zE.set(this,void 0),this.buffer=new Uint8Array,UE(this,zE,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?(new TextEncoder).encode(e):e;let r=new Uint8Array(this.buffer.length+t.length);r.set(this.buffer),r.set(t,this.buffer.length),this.buffer=r;const n=[];let s;for(;null!=(s=KE(this.buffer,BE(this,zE,"f")));){if(s.carriage&&null==BE(this,zE,"f")){UE(this,zE,s.index,"f");continue}if(null!=BE(this,zE,"f")&&(s.index!==BE(this,zE,"f")+1||s.carriage)){n.push(this.decodeText(this.buffer.slice(0,BE(this,zE,"f")-1))),this.buffer=this.buffer.slice(BE(this,zE,"f")),UE(this,zE,null,"f");continue}const e=null!==BE(this,zE,"f")?s.preceding-1:s.preceding,t=this.decodeText(this.buffer.slice(0,e));n.push(t),this.buffer=this.buffer.slice(s.index),UE(this,zE,null,"f")}return n}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof Buffer){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new CE(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new CE(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new CE("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode("\n"):[]}}function KE(e,t){for(let r=t??0;r0&&(yield t)}(s))for(const t of n.decode(e)){const e=r.decode(t);e&&(yield e)}for(const e of n.flush()){const t=r.decode(e);t&&(yield t)}}(e,t)){if("completion"===r.event)try{yield JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if("message_start"===r.event||"message_delta"===r.event||"message_stop"===r.event||"content_block_start"===r.event||"content_block_delta"===r.event||"content_block_stop"===r.event)try{yield JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if("ping"!==r.event&&"error"===r.event)throw PE.generate(void 0,`SSE Error: ${r.data}`,r.data,dx(e.headers))}n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}}),t)}static fromReadableStream(e,t){let r=!1;return new VE((async function*(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let n=!1;try{for await(const t of async function*(){const t=new qE,r=HE(e);for await(const e of r)for(const r of t.decode(e))yield r;for(const e of t.flush())yield e}())n||t&&(yield JSON.parse(t));n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}}),t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],r=this.iterator(),n=n=>({next:()=>{if(0===n.length){const n=r.next();e.push(n),t.push(n)}return n.shift()}});return[new VE((()=>n(e)),this.controller),new VE((()=>n(t)),this.controller)]}toReadableStream(){const e=this;let t;const r=new TextEncoder;return new fE({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:n,done:s}=await t.next();if(s)return e.close();const a=r.encode(JSON.stringify(n)+"\n");e.enqueue(a)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class GE{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 e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=function(e,t){const r=e.indexOf(t);if(-1!==r)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}const JE=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,ZE=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&YE(e),YE=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function XE(e,t,r){if(e=await e,ZE(e))return e;if(JE(e)){const n=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");const s=YE(n)?[await n.arrayBuffer()]:[n];return new mE(s,t,r)}const n=await async function(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(YE(e))t.push(await e.arrayBuffer());else{if(!ex(e))throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${function(e){const t=Object.getOwnPropertyNames(e);return`[${t.map((e=>`"${e}"`)).join(", ")}]`}(e)}`);for await(const r of e)t.push(r)}return t}(e);if(t||(t=function(e){return QE(e.name)||QE(e.filename)||QE(e.path)?.split(/[\\/]/).pop()}(e)??"unknown_file"),!r?.type){const e=n[0]?.type;"string"==typeof e&&(r={...r,type:e})}return new mE(n,t,r)}const QE=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,ex=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],tx=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag];var rx,nx=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},sx=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};async function ax(e){const{response:t}=e;if(e.options.stream)return Ox("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):VE.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;const r=t.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){const e=await t.json();return Ox("response",t.status,t.url,t.headers,e),ix(e,t)}const n=await t.text();return Ox("response",t.status,t.url,t.headers,n),n}function ix(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("request-id"),enumerable:!1})}class ox extends Promise{constructor(e,t=ax){super((e=>{e(null)})),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new ox(this.responsePromise,(async t=>ix(e(await this.parseResponse(t),t),t.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("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),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)}}class cx{constructor({baseURL:e,maxRetries:t=2,timeout:r=6e5,httpAgent:n,fetch:s}){this.baseURL=e,this.maxRetries=Sx("maxRetries",t),this.timeout=Sx("timeout",r),this.httpAgent=n,this.fetch=s??pE}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...bx(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${Ax()}`}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((async r=>{const n=r&&YE(r?.body)?new DataView(await r.body.arrayBuffer()):r?.body instanceof DataView?r.body:r?.body instanceof ArrayBuffer?new DataView(r.body):r&&ArrayBuffer.isView(r?.body)?new DataView(r.body.buffer):r?.body;return{method:e,path:t,...r,body:n}})))}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}calculateContentLength(e){if("string"==typeof e){if("undefined"!=typeof Buffer)return Buffer.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder){return(new TextEncoder).encode(e).length.toString()}}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){e={...e};const{method:r,path:n,query:s,headers:a={}}=e,i=ArrayBuffer.isView(e.body)||e.__binaryRequest&&"string"==typeof e.body?e.body:tx(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,o=this.calculateContentLength(i),c=this.buildURL(n,s);"timeout"in e&&Sx("timeout",e.timeout),e.timeout=e.timeout??this.timeout;const l=e.httpAgent??this.httpAgent??gE(c),u=e.timeout+1e3;"number"==typeof l?.options?.timeout&&u>(l.options.timeout??0)&&(l.options.timeout=u),this.idempotencyHeader&&"get"!==r&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);return{req:{method:r,...i&&{body:i},headers:this.buildHeaders({options:e,headers:a,contentLength:o,retryCount:t}),...l&&{agent:l},signal:e.signal??null},url:c,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:r,retryCount:n}){const s={};r&&(s["content-length"]=r);const a=this.defaultHeaders(e);return Px(s,a),Px(s,t),tx(e.body)&&"node"!==hE&&delete s["content-type"],void 0===Ix(a,"x-stainless-retry-count")&&void 0===Ix(t,"x-stainless-retry-count")&&(s["x-stainless-retry-count"]=String(n)),void 0===Ix(a,"x-stainless-timeout")&&void 0===Ix(t,"x-stainless-timeout")&&e.timeout&&(s["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(s,t),s}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new CE("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");return 6e5}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map((e=>[...e]))):{...e}:{}}makeStatusError(e,t,r,n){return PE.generate(e,t,r,n)}request(e,t=null){return new ox(this.makeRequest(e,t))}async makeRequest(e,t){const r=await e,n=r.maxRetries??this.maxRetries;null==t&&(t=n),await this.prepareOptions(r);const{req:s,url:a,timeout:i}=this.buildRequest(r,{retryCount:n-t});if(await this.prepareRequest(s,{url:a,options:r}),Ox("request",a,r,s.headers),r.signal?.aborted)throw new OE;const o=new AbortController,c=await this.fetchWithTimeout(a,s,i,o).catch(Ex);if(c instanceof Error){if(r.signal?.aborted)throw new OE;if(t)return this.retryRequest(r,t);if("AbortError"===c.name)throw new IE;throw new AE({cause:c})}const l=dx(c.headers);if(!c.ok){if(t&&this.shouldRetry(c)){return Ox(`response (error; ${`retrying, ${t} attempts remaining`})`,c.status,a,l),this.retryRequest(r,t,l)}const e=await c.text().catch((e=>Ex(e).message)),n=wx(e),s=n?void 0:e;Ox(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,c.status,a,l,s);throw this.makeStatusError(c.status,n,s,l)}return{response:c,options:r,controller:o}}requestAPIList(e,t){const r=this.makeRequest(t,null);return new ux(this,r,e)}buildURL(e,t){const r=_x(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return Tx(n)||(t={...n,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}stringifyQuery(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new CE(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)})).join("&")}async fetchWithTimeout(e,t,r,n){const{signal:s,...a}=t||{};s&&s.addEventListener("abort",(()=>n.abort()));const i=setTimeout((()=>n.abort()),r),o={signal:n.signal,...a};o.method&&(o.method=o.method.toUpperCase());const c=setTimeout((()=>{if(o&&o?.agent?.sockets)for(const e of Object.values(o?.agent?.sockets).flat())e?.setKeepAlive&&e.setKeepAlive(!0,6e4)}),6e4);return this.fetch.call(void 0,e,o).finally((()=>{clearTimeout(i),clearTimeout(c)}))}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,r){let n;const s=r?.["retry-after-ms"];if(s){const e=parseFloat(s);Number.isNaN(e)||(n=e)}const a=r?.["retry-after"];if(a&&!n){const e=parseFloat(a);n=Number.isNaN(e)?Date.parse(a)-Date.now():1e3*e}if(!(n&&0<=n&&n<6e4)){const r=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,r)}return await kx(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const r=t-e;return Math.min(.5*Math.pow(2,r),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${dE}`}}class lx{constructor(e,t,r,n){rx.set(this,void 0),nx(this,rx,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new CE("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&"object"==typeof t.query)t.query={...t.query,...e.params};else if("url"in e){const r=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[t,n]of r)e.url.searchParams.set(t,n);t.query=void 0,t.path=e.url.toString()}return await sx(this,rx,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(rx=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class ux extends ox{constructor(e,t,r){super(t,(async t=>new r(e,t.response,await ax(t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const dx=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const r=t.toString();return e[r.toLowerCase()]||e[r]}}),hx={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},px=e=>"object"==typeof e&&null!==e&&!Tx(e)&&Object.keys(e).every((e=>Cx(hx,e))),mx=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dE,"X-Stainless-OS":gx(Deno.build.os),"X-Stainless-Arch":fx(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dE,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dE,"X-Stainless-OS":gx(process.platform),"X-Stainless-Arch":fx(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const e=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{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:t,pattern:r}of e){const e=r.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dE,"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":dE,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const fx=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",gx=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let yx;const bx=()=>yx??(yx=mx()),wx=e=>{try{return JSON.parse(e)}catch(e){return}},vx=/^[a-z][a-z0-9+.-]*:/i,_x=e=>vx.test(e),kx=e=>new Promise((t=>setTimeout(t,e))),Sx=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new CE(`${e} must be an integer`);if(t<0)throw new CE(`${e} must be a positive integer`);return t},Ex=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e)try{return new Error(JSON.stringify(e))}catch{}return new Error(String(e))},xx=e=>"undefined"!=typeof process?process.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function Tx(e){if(!e)return!0;for(const t in e)return!1;return!0}function Cx(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Px(e,t){for(const r in t){if(!Cx(t,r))continue;const n=r.toLowerCase();if(!n)continue;const s=t[r];null===s?delete e[n]:void 0!==s&&(e[n]=s)}}function Ox(e,...t){"undefined"!=typeof process&&"true"===process?.env?.DEBUG&&console.log(`Anthropic:DEBUG:${e}`,...t)}const Ax=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),Ix=(e,t)=>{const r=t.toLowerCase();if((e=>"function"==typeof e?.get)(e)){const n=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,((e,t,r)=>t+r.toUpperCase()));for(const s of[t,r,t.toUpperCase(),n]){const t=e.get(s);if(t)return t}}for(const[n,s]of Object.entries(e))if(n.toLowerCase()===r)return Array.isArray(s)?(s.length<=1||console.warn(`Received ${s.length} entries for the ${t} header, using the first entry.`),s[0]):s};class Mx{constructor(e){this._client=e}}class Rx extends Mx{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}}class jx extends lx{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){if(this.options.query?.before_id){const e=this.first_id;return e?{params:{before_id:e}}:null}const e=this.last_id;return e?{params:{after_id:e}}:null}}class Nx{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new qE;for await(const t of this.iterator)for(const r of e.decode(t))yield JSON.parse(r);for(const t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),new CE("Attempted to iterate over a response with no body");return new Nx(HE(e.body),t)}}class $x extends Mx{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/v1/messages/batches/${e}`,t)}list(e={},t){return px(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",Lx,{query:e,...t})}delete(e,t){return this._client.delete(`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){const r=await this.retrieve(e);if(!r.results_url)throw new CE(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})._thenUnwrap(((e,t)=>Nx.fromResponse(t.response,t.controller)))}}class Lx extends jx{}$x.MessageBatchesPage=Lx;const Fx=e=>{if(0===e.length)return e;let t=e[e.length-1];switch(t.type){case"separator":return e=e.slice(0,e.length-1),Fx(e);case"number":let r=t.value[t.value.length-1];if("."===r||"-"===r)return e=e.slice(0,e.length-1),Fx(e);case"string":let n=e[e.length-2];if("delimiter"===n?.type)return e=e.slice(0,e.length-1),Fx(e);if("brace"===n?.type&&"{"===n.value)return e=e.slice(0,e.length-1),Fx(e);break;case"delimiter":return e=e.slice(0,e.length-1),Fx(e)}return e},Dx=e=>JSON.parse((e=>{let t="";return e.map((e=>{"string"===e.type?t+='"'+e.value+'"':t+=e.value})),t})((e=>{let t=[];return e.map((e=>{"brace"===e.type&&("{"===e.value?t.push("}"):t.splice(t.lastIndexOf("}"),1)),"paren"===e.type&&("["===e.value?t.push("]"):t.splice(t.lastIndexOf("]"),1))})),t.length>0&&t.reverse().map((t=>{"}"===t?e.push({type:"brace",value:"}"}):"]"===t&&e.push({type:"paren",value:"]"})})),e})(Fx((e=>{let t=0,r=[];for(;t{})),Kx.set(this,(()=>{})),Wx.set(this,void 0),Hx.set(this,(()=>{})),Vx.set(this,(()=>{})),Gx.set(this,{}),Jx.set(this,!1),Zx.set(this,!1),Yx.set(this,!1),Xx.set(this,!1),Qx.set(this,void 0),eT.set(this,void 0),nT.set(this,(e=>{if(cT(this,Zx,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new OE),e instanceof OE)return cT(this,Yx,!0,"f"),this._emit("abort",e);if(e instanceof CE)return this._emit("error",e);if(e instanceof Error){const t=new CE(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new CE(String(e)))})),cT(this,Bx,new Promise(((e,t)=>{cT(this,qx,e,"f"),cT(this,Kx,t,"f")})),"f"),cT(this,Wx,new Promise(((e,t)=>{cT(this,Hx,e,"f"),cT(this,Vx,t,"f")})),"f"),lT(this,Bx,"f").catch((()=>{})),lT(this,Wx,"f").catch((()=>{}))}get response(){return lT(this,Qx,"f")}get request_id(){return lT(this,eT,"f")}async withResponse(){const e=await lT(this,Bx,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new dT;return t._run((()=>t._fromReadableStream(e))),t}static createMessage(e,t,r){const n=new dT;for(const e of t.messages)n._addMessageParam(e);return n._run((()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}_run(e){e().then((()=>{this._emitFinal(),this._emit("end")}),lT(this,nT,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),lT(this,zx,"m",sT).call(this);const{response:s,data:a}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(s);for await(const e of a)lT(this,zx,"m",aT).call(this,e);if(a.controller.signal?.aborted)throw new OE;lT(this,zx,"m",iT).call(this)}_connected(e){this.ended||(cT(this,Qx,e,"f"),cT(this,eT,e?.headers.get("request-id"),"f"),lT(this,qx,"f").call(this,e),this._emit("connect"))}get ended(){return lT(this,Jx,"f")}get errored(){return lT(this,Zx,"f")}get aborted(){return lT(this,Yx,"f")}abort(){this.controller.abort()}on(e,t){return(lT(this,Gx,"f")[e]||(lT(this,Gx,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=lT(this,Gx,"f")[e];if(!r)return this;const n=r.findIndex((e=>e.listener===t));return n>=0&&r.splice(n,1),this}once(e,t){return(lT(this,Gx,"f")[e]||(lT(this,Gx,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,r)=>{cT(this,Xx,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)}))}async done(){cT(this,Xx,!0,"f"),await lT(this,Wx,"f")}get currentMessage(){return lT(this,Ux,"f")}async finalMessage(){return await this.done(),lT(this,zx,"m",tT).call(this)}async finalText(){return await this.done(),lT(this,zx,"m",rT).call(this)}_emit(e,...t){if(lT(this,Jx,"f"))return;"end"===e&&(cT(this,Jx,!0,"f"),lT(this,Hx,"f").call(this));const r=lT(this,Gx,"f")[e];if(r&&(lT(this,Gx,"f")[e]=r.filter((e=>!e.once)),r.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return lT(this,Xx,"f")||r?.length||Promise.reject(e),lT(this,Kx,"f").call(this,e),lT(this,Vx,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];lT(this,Xx,"f")||r?.length||Promise.reject(e),lT(this,Kx,"f").call(this,e),lT(this,Vx,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",lT(this,zx,"m",tT).call(this))}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),lT(this,zx,"m",sT).call(this),this._connected(null);const n=VE.fromReadableStream(e,this.controller);for await(const e of n)lT(this,zx,"m",aT).call(this,e);if(n.controller.signal?.aborted)throw new OE;lT(this,zx,"m",iT).call(this)}[(Ux=new WeakMap,Bx=new WeakMap,qx=new WeakMap,Kx=new WeakMap,Wx=new WeakMap,Hx=new WeakMap,Vx=new WeakMap,Gx=new WeakMap,Jx=new WeakMap,Zx=new WeakMap,Yx=new WeakMap,Xx=new WeakMap,Qx=new WeakMap,eT=new WeakMap,nT=new WeakMap,zx=new WeakSet,tT=function(){if(0===this.receivedMessages.length)throw new CE("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},rT=function(){if(0===this.receivedMessages.length)throw new CE("stream ended without producing a Message with role=assistant");const e=this.receivedMessages.at(-1).content.filter((e=>"text"===e.type)).map((e=>e.text));if(0===e.length)throw new CE("stream ended without producing a content block with type=text");return e.join(" ")},sT=function(){this.ended||cT(this,Ux,void 0,"f")},aT=function(e){if(this.ended)return;const t=lT(this,zx,"m",oT).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{const r=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===r.type&&this._emit("text",e.delta.text,r.text||"");break;case"citations_delta":"text"===r.type&&this._emit("citation",e.delta.citation,r.citations??[]);break;case"input_json_delta":"tool_use"===r.type&&r.input&&this._emit("inputJson",e.delta.partial_json,r.input);break;case"thinking_delta":"thinking"===r.type&&this._emit("thinking",e.delta.thinking,r.thinking);break;case"signature_delta":"thinking"===r.type&&this._emit("signature",r.signature);break;default:e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(t,!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":cT(this,Ux,t,"f")}},iT=function(){if(this.ended)throw new CE("stream has ended, this shouldn't happen");const e=lT(this,Ux,"f");if(!e)throw new CE("request ended without sending any chunks");return cT(this,Ux,void 0,"f"),e},oT=function(e){let t=lT(this,Ux,"f");if("message_start"===e.type){if(t)throw new CE(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new CE(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t;case"content_block_start":return t.content.push(e.content_block),t;case"content_block_delta":{const r=t.content.at(e.index);switch(e.delta.type){case"text_delta":"text"===r?.type&&(r.text+=e.delta.text);break;case"citations_delta":"text"===r?.type&&(r.citations??(r.citations=[]),r.citations.push(e.delta.citation));break;case"input_json_delta":if("tool_use"===r?.type){let t=r[uT]||"";t+=e.delta.partial_json,Object.defineProperty(r,uT,{value:t,enumerable:!1,writable:!0}),t&&(r.input=Dx(t))}break;case"thinking_delta":"thinking"===r?.type&&(r.thinking+=e.delta.thinking);break;case"signature_delta":"thinking"===r?.type&&(r.signature=e.delta.signature);break;default:e.delta}return t}}},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("streamEvent",(r=>{const n=t.shift();n?n.resolve(r):e.push(r)})),this.on("end",(()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),this.on("error",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise(((e,r)=>t.push({resolve:e,reject:r}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new VE(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class hT extends Mx{constructor(){super(...arguments),this.batches=new $x(this._client)}create(e,t){return e.model in pT&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${pT[e.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??(e.stream?6e5:this._client._calculateNonstreamingTimeout(e.max_tokens)),...t,stream:e.stream??!1})}stream(e,t){return dT.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}const pT={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};hT.Batches=$x,hT.MessageBatchesPage=Lx;class mT extends Mx{retrieve(e,t){return this._client.get(`/v1/models/${e}`,t)}list(e={},t){return px(e)?this.list({},e):this._client.getAPIList("/v1/models",fT,{query:e,...t})}}class fT extends jx{}mT.ModelInfosPage=fT;class gT extends Mx{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return px(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",yT,{query:e,...t})}}class yT extends jx{}gT.BetaModelInfosPage=yT;class bT extends Mx{create(e,t){const{betas:r,...n}=e;return this._client.post("/v1/messages/batches?beta=true",{body:n,...t,headers:{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},r){if(px(t))return this.retrieve(e,{},t);const{betas:n}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...r,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}list(e={},t){if(px(e))return this.list({},e);const{betas:r,...n}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",wT,{query:n,...t,headers:{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},r){if(px(t))return this.delete(e,{},t);const{betas:n}=t;return this._client.delete(`/v1/messages/batches/${e}?beta=true`,{...r,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}cancel(e,t={},r){if(px(t))return this.cancel(e,{},t);const{betas:n}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}async results(e,t={},r){if(px(t))return this.results(e,{},t);const n=await this.retrieve(e);if(!n.results_url)throw new CE(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);const{betas:s}=t;return this._client.get(n.results_url,{...r,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...r?.headers},__binaryResponse:!0})._thenUnwrap(((e,t)=>Nx.fromResponse(t.response,t.controller)))}}class wT extends jx{}bT.BetaMessageBatchesPage=wT;var vT,_T,kT,ST,ET,xT,TT,CT,PT,OT,AT,IT,MT,RT,jT,NT,$T,LT,FT,DT,zT,UT,BT=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},qT=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};const KT="__json_buf";class WT{constructor(){vT.add(this),this.messages=[],this.receivedMessages=[],_T.set(this,void 0),this.controller=new AbortController,kT.set(this,void 0),ST.set(this,(()=>{})),ET.set(this,(()=>{})),xT.set(this,void 0),TT.set(this,(()=>{})),CT.set(this,(()=>{})),PT.set(this,{}),OT.set(this,!1),AT.set(this,!1),IT.set(this,!1),MT.set(this,!1),RT.set(this,void 0),jT.set(this,void 0),LT.set(this,(e=>{if(BT(this,AT,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new OE),e instanceof OE)return BT(this,IT,!0,"f"),this._emit("abort",e);if(e instanceof CE)return this._emit("error",e);if(e instanceof Error){const t=new CE(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new CE(String(e)))})),BT(this,kT,new Promise(((e,t)=>{BT(this,ST,e,"f"),BT(this,ET,t,"f")})),"f"),BT(this,xT,new Promise(((e,t)=>{BT(this,TT,e,"f"),BT(this,CT,t,"f")})),"f"),qT(this,kT,"f").catch((()=>{})),qT(this,xT,"f").catch((()=>{}))}get response(){return qT(this,RT,"f")}get request_id(){return qT(this,jT,"f")}async withResponse(){const e=await qT(this,kT,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new WT;return t._run((()=>t._fromReadableStream(e))),t}static createMessage(e,t,r){const n=new WT;for(const e of t.messages)n._addMessageParam(e);return n._run((()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}_run(e){e().then((()=>{this._emitFinal(),this._emit("end")}),qT(this,LT,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),qT(this,vT,"m",FT).call(this);const{response:s,data:a}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(s);for await(const e of a)qT(this,vT,"m",DT).call(this,e);if(a.controller.signal?.aborted)throw new OE;qT(this,vT,"m",zT).call(this)}_connected(e){this.ended||(BT(this,RT,e,"f"),BT(this,jT,e?.headers.get("request-id"),"f"),qT(this,ST,"f").call(this,e),this._emit("connect"))}get ended(){return qT(this,OT,"f")}get errored(){return qT(this,AT,"f")}get aborted(){return qT(this,IT,"f")}abort(){this.controller.abort()}on(e,t){return(qT(this,PT,"f")[e]||(qT(this,PT,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=qT(this,PT,"f")[e];if(!r)return this;const n=r.findIndex((e=>e.listener===t));return n>=0&&r.splice(n,1),this}once(e,t){return(qT(this,PT,"f")[e]||(qT(this,PT,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,r)=>{BT(this,MT,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)}))}async done(){BT(this,MT,!0,"f"),await qT(this,xT,"f")}get currentMessage(){return qT(this,_T,"f")}async finalMessage(){return await this.done(),qT(this,vT,"m",NT).call(this)}async finalText(){return await this.done(),qT(this,vT,"m",$T).call(this)}_emit(e,...t){if(qT(this,OT,"f"))return;"end"===e&&(BT(this,OT,!0,"f"),qT(this,TT,"f").call(this));const r=qT(this,PT,"f")[e];if(r&&(qT(this,PT,"f")[e]=r.filter((e=>!e.once)),r.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return qT(this,MT,"f")||r?.length||Promise.reject(e),qT(this,ET,"f").call(this,e),qT(this,CT,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];qT(this,MT,"f")||r?.length||Promise.reject(e),qT(this,ET,"f").call(this,e),qT(this,CT,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",qT(this,vT,"m",NT).call(this))}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),qT(this,vT,"m",FT).call(this),this._connected(null);const n=VE.fromReadableStream(e,this.controller);for await(const e of n)qT(this,vT,"m",DT).call(this,e);if(n.controller.signal?.aborted)throw new OE;qT(this,vT,"m",zT).call(this)}[(_T=new WeakMap,kT=new WeakMap,ST=new WeakMap,ET=new WeakMap,xT=new WeakMap,TT=new WeakMap,CT=new WeakMap,PT=new WeakMap,OT=new WeakMap,AT=new WeakMap,IT=new WeakMap,MT=new WeakMap,RT=new WeakMap,jT=new WeakMap,LT=new WeakMap,vT=new WeakSet,NT=function(){if(0===this.receivedMessages.length)throw new CE("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},$T=function(){if(0===this.receivedMessages.length)throw new CE("stream ended without producing a Message with role=assistant");const e=this.receivedMessages.at(-1).content.filter((e=>"text"===e.type)).map((e=>e.text));if(0===e.length)throw new CE("stream ended without producing a content block with type=text");return e.join(" ")},FT=function(){this.ended||BT(this,_T,void 0,"f")},DT=function(e){if(this.ended)return;const t=qT(this,vT,"m",UT).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{const r=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===r.type&&this._emit("text",e.delta.text,r.text||"");break;case"citations_delta":"text"===r.type&&this._emit("citation",e.delta.citation,r.citations??[]);break;case"input_json_delta":"tool_use"===r.type&&r.input&&this._emit("inputJson",e.delta.partial_json,r.input);break;case"thinking_delta":"thinking"===r.type&&this._emit("thinking",e.delta.thinking,r.thinking);break;case"signature_delta":"thinking"===r.type&&this._emit("signature",r.signature);break;default:e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(t,!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":BT(this,_T,t,"f")}},zT=function(){if(this.ended)throw new CE("stream has ended, this shouldn't happen");const e=qT(this,_T,"f");if(!e)throw new CE("request ended without sending any chunks");return BT(this,_T,void 0,"f"),e},UT=function(e){let t=qT(this,_T,"f");if("message_start"===e.type){if(t)throw new CE(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new CE(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t;case"content_block_start":return t.content.push(e.content_block),t;case"content_block_delta":{const r=t.content.at(e.index);switch(e.delta.type){case"text_delta":"text"===r?.type&&(r.text+=e.delta.text);break;case"citations_delta":"text"===r?.type&&(r.citations??(r.citations=[]),r.citations.push(e.delta.citation));break;case"input_json_delta":if("tool_use"===r?.type){let t=r[KT]||"";t+=e.delta.partial_json,Object.defineProperty(r,KT,{value:t,enumerable:!1,writable:!0}),t&&(r.input=Dx(t))}break;case"thinking_delta":"thinking"===r?.type&&(r.thinking+=e.delta.thinking);break;case"signature_delta":"thinking"===r?.type&&(r.signature=e.delta.signature);break;default:e.delta}return t}}},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("streamEvent",(r=>{const n=t.shift();n?n.resolve(r):e.push(r)})),this.on("end",(()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),this.on("error",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise(((e,r)=>t.push({resolve:e,reject:r}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new VE(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}const HT={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};class VT extends Mx{constructor(){super(...arguments),this.batches=new bT(this._client)}create(e,t){const{betas:r,...n}=e;return n.model in HT&&console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${HT[n.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:n,timeout:this._client._options.timeout??(n.stream?6e5:this._client._calculateNonstreamingTimeout(n.max_tokens)),...t,headers:{...null!=r?.toString()?{"anthropic-beta":r?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}stream(e,t){return WT.createMessage(this,e,t)}countTokens(e,t){const{betas:r,...n}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:n,...t,headers:{"anthropic-beta":[...r??[],"token-counting-2024-11-01"].toString(),...t?.headers}})}}VT.Batches=bT,VT.BetaMessageBatchesPage=wT;class GT extends Mx{constructor(){super(...arguments),this.models=new gT(this._client),this.messages=new VT(this._client)}}var JT;GT.Models=gT,GT.BetaModelInfosPage=yT,GT.Messages=VT;class ZT extends cx{constructor({baseURL:e=xx("ANTHROPIC_BASE_URL"),apiKey:t=xx("ANTHROPIC_API_KEY")??null,authToken:r=xx("ANTHROPIC_AUTH_TOKEN")??null,...n}={}){const s={apiKey:t,authToken:r,...n,baseURL:e||"https://api.anthropic.com"};if(!s.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new CE("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");super({baseURL:s.baseURL,timeout:s.timeout??6e5,httpAgent:s.httpAgent,maxRetries:s.maxRetries,fetch:s.fetch}),this.completions=new Rx(this),this.messages=new hT(this),this.models=new mT(this),this.beta=new GT(this),this._options=s,this.apiKey=t,this.authToken=r}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(e,t){if(!(this.apiKey&&e["x-api-key"]||null===t["x-api-key"]||this.authToken&&e.authorization||null===t.authorization))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders(e){const t=this.apiKeyAuth(e),r=this.bearerAuth(e);return null==t||Tx(t)?null==r||Tx(r)?{}:r:t}apiKeyAuth(e){return null==this.apiKey?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){return null==this.authToken?{}:{Authorization:`Bearer ${this.authToken}`}}}JT=ZT,ZT.Anthropic=JT,ZT.HUMAN_PROMPT="\n\nHuman:",ZT.AI_PROMPT="\n\nAssistant:",ZT.DEFAULT_TIMEOUT=6e5,ZT.AnthropicError=CE,ZT.APIError=PE,ZT.APIConnectionError=AE,ZT.APIConnectionTimeoutError=IE,ZT.APIUserAbortError=OE,ZT.NotFoundError=NE,ZT.ConflictError=$E,ZT.RateLimitError=FE,ZT.BadRequestError=ME,ZT.AuthenticationError=RE,ZT.InternalServerError=DE,ZT.PermissionDeniedError=jE,ZT.UnprocessableEntityError=LE,ZT.toFile=XE,ZT.fileFromPath=yE,ZT.Completions=Rx,ZT.Messages=hT,ZT.Models=mT,ZT.ModelInfosPage=fT,ZT.Beta=GT;const{HUMAN_PROMPT:YT,AI_PROMPT:XT}=ZT;class QT extends Zt{static lc_name(){return"AnthropicToolsOutputParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","anthropic","output_parsers"]}),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){let t=e;if("string"==typeof e)try{t=JSON.parse(e)}catch(t){throw new Xt(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.message)}`,e)}else t=e;if(void 0===this.zodSchema)return t;const r=await this.zodSchema.safeParseAsync(t);if(r.success)return r.data;throw new Xt(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.error.errors)}`,JSON.stringify(t,null,2))}async parseResult(e){const t=e.flatMap((e=>{const{message:t}=e;if(!Array.isArray(t.content))return[];return eC(t.content)[0]}));if(void 0===t[0])throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[r]=t;return await this._validateResult(r.args)}}function eC(e){const t=[];for(const r of e)"tool_use"===r.type&&t.push({name:r.name,args:r.input,id:r.id,type:"tool_call"});return t}function tC(e){const t=(0,se.parseBase64DataUrl)({dataUrl:e});if(t)return{type:"base64",media_type:t.mime_type,data:t.data};let r;try{r=new URL(e)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(e)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join("\n\n"))}if("http:"===r.protocol||"https:"===r.protocol)return{type:"url",url:e};throw new Error([`Invalid image URL protocol: ${JSON.stringify(r.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join("\n\n"))}function rC(e){if(void 0===e.id)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:e.id,name:e.name,input:e.args}}const nC={providerName:"anthropic",fromStandardTextBlock:e=>({type:"text",text:e.text,..."citations"in(e.metadata??{})?{citations:e.metadata.citations}:{},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}),fromStandardImageBlock(e){if("url"===e.source_type){const t=(0,se.parseBase64DataUrl)({dataUrl:e.url,asTypedArray:!1});return t?{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:e.url,media_type:e.mime_type??""},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}}if("base64"===e.source_type)return{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type??""},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${e.source_type}`)},fromStandardFileBlock(e){const t=(e.mime_type??"").split(";")[0];if("url"===e.source_type){if("application/pdf"===t||""===t)return{type:"document",source:{type:"url",url:e.url,media_type:e.mime_type??""},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},..."citations"in(e.metadata??{})?{citations:e.metadata.citations}:{},..."context"in(e.metadata??{})?{context:e.metadata.context}:{},..."title"in(e.metadata??{})?{title:e.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${e.mime_type}`)}if("text"===e.source_type){if("text/plain"===t||""===t)return{type:"document",source:{type:"text",data:e.text,media_type:e.mime_type??""},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},..."citations"in(e.metadata??{})?{citations:e.metadata.citations}:{},..."context"in(e.metadata??{})?{context:e.metadata.context}:{},..."title"in(e.metadata??{})?{title:e.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${e.mime_type}`)}if("base64"===e.source_type){if("application/pdf"===t||""===t)return{type:"document",source:{type:"base64",data:e.data,media_type:"application/pdf"},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},..."citations"in(e.metadata??{})?{citations:e.metadata.citations}:{},..."context"in(e.metadata??{})?{context:e.metadata.context}:{},..."title"in(e.metadata??{})?{title:e.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(t))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:e.data,media_type:t}}]},..."cache_control"in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},..."citations"in(e.metadata??{})?{citations:e.metadata.citations}:{},..."context"in(e.metadata??{})?{context:e.metadata.context}:{},..."title"in(e.metadata??{})?{title:e.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${e.mime_type}`)}throw new Error(`Unsupported file source type: ${e.source_type}`)}};function sC(e){const t=["tool_use","tool_result","input_json_delta"],r=["text","text_delta"];if("string"==typeof e)return e;{const n=e.map((e=>{if((0,se.isDataContentBlock)(e))return(0,se.convertToProviderContentBlock)(e,nC);const n="cache_control"in e?e.cache_control:void 0;if("image_url"===e.type){let t;return t="string"==typeof e.image_url?tC(e.image_url):tC(e.image_url.url),{type:"image",source:t,...n?{cache_control:n}:{}}}if(null!=(s=e)&&"object"==typeof s&&"type"in s&&"image"===s.type&&"source"in s&&"object"==typeof s.source&&null!=s.source&&"type"in s.source&&("base64"===s.source.type?"media_type"in s.source&&"string"==typeof s.source.media_type&&"data"in s.source&&"string"==typeof s.source.data:"url"===s.source.type&&"url"in s.source&&"string"==typeof s.source.url))return e;if("document"===e.type)return{...e,...n?{cache_control:n}:{}};if("thinking"===e.type){return{type:"thinking",thinking:e.thinking,signature:e.signature,...n?{cache_control:n}:{}}}if("redacted_thinking"===e.type){return{type:"redacted_thinking",data:e.data,...n?{cache_control:n}:{}}}if(r.find((t=>t===e.type))&&"text"in e)return{type:"text",text:e.text,...n?{cache_control:n}:{}};if(t.find((t=>t===e.type))){const t={...e};if("index"in t&&delete t.index,"input_json_delta"===t.type&&(t.type="tool_use"),"input"in t&&"string"==typeof t.input)try{t.input=JSON.parse(t.input)}catch{t.input={}}return{...t,...n?{cache_control:n}:{}}}throw new Error("Unsupported message content format");var s}));return n}}function aC(e){const t=function(e){const t=[];for(const r of e)if("tool"===r._getType())if("string"==typeof r.content){const e=t[t.length-1];"human"===e?._getType()&&Array.isArray(e.content)&&"type"in e.content[0]&&"tool_result"===e.content[0].type?e.content.push({type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}):t.push(new se.HumanMessage({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}else t.push(new se.HumanMessage({content:[{type:"tool_result",content:sC(r.content),tool_use_id:r.tool_call_id}]}));else t.push(r);return t}(e);let r;t.length>0&&"system"===t[0]._getType()&&(r=e[0].content);return{messages:iC((void 0!==r?t.slice(1):t).map((e=>{let t;if("human"===e._getType())t="user";else if("ai"===e._getType())t="assistant";else{if("tool"!==e._getType())throw"system"===e._getType()?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${e._getType()}" is not supported.`);t="user"}if((0,se.isAIMessage)(e)&&e.tool_calls?.length){if("string"==typeof e.content)return""===e.content?{role:t,content:e.tool_calls.map(rC)}:{role:t,content:[{type:"text",text:e.content},...e.tool_calls.map(rC)]};{const{content:r}=e;return!e.tool_calls.every((e=>r.find((t=>("tool_use"===t.type||"input_json_delta"===t.type)&&t.id===e.id))))&&console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:t,content:sC(e.content)}}}return{role:t,content:sC(e.content)}}))),system:r}}function iC(e){if(!e||e.length<=1)return e;const t=[];let r=e[0];const n=e=>"string"==typeof e?[{type:"text",text:e}]:e,s=e=>"user"===e.role&&("string"!=typeof e.content&&(Array.isArray(e.content)&&e.content.every((e=>"tool_result"===e.type))));for(let a=1;a=1&&"input"in e.content[0]?"string"==typeof e.content[0].input?e.content[0].input:JSON.stringify(e.content[0].input):Array.isArray(e.content)&&e.content.length>=1&&"text"in e.content[0]?e.content[0].text:void 0}class dC extends zt{static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}constructor(e){if(super(e??{}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"anthropicApiKey",{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,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"topK",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:2048}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"claude-2.1"}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"claude-2.1"}),Object.defineProperty(this,"invocationKwargs",{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,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"clientOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"thinking",{enumerable:!0,configurable:!0,writable:!0,value:{type:"disabled"}}),Object.defineProperty(this,"batchClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamingClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"createClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.anthropicApiKey=e?.apiKey??e?.anthropicApiKey??(0,Sn.getEnvironmentVariable)("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!e?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=e?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=e?.anthropicApiUrl,this.modelName=e?.model??e?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=e?.invocationKwargs??{},this.temperature=e?.temperature??this.temperature,this.topK=e?.topK??this.topK,this.topP=e?.topP??this.topP,this.maxTokens=e?.maxTokensToSample??e?.maxTokens??this.maxTokens,this.stopSequences=e?.stopSequences??this.stopSequences,this.streaming=e?.streaming??!1,this.streamUsage=e?.streamUsage??this.streamUsage,this.thinking=e?.thinking??this.thinking,this.createClient=e?.createClient??(e=>new ZT(e))}getLsParams(e){const t=this.invocationParams(e);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e){if(e&&e.length)return e.map((e=>{if(function(e){return"input_schema"in e}(e))return e;if(It(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if(hn(e))return{name:e.name,description:e.description,input_schema:Lt(e.schema)?(0,Nt.Ik)(e.schema):e.schema};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)}))}bindTools(e,t){return this.bind({tools:this.formatStructuredToolToAnthropic(e),...t})}invocationParams(e){const t=(r=e?.tool_choice,r?"any"===r?{type:"any"}:"auto"===r?{type:"auto"}:"string"==typeof r?{type:"tool",name:r}:r:void 0);var r;if("enabled"===this.thinking.type){if(-1!==this.topK)throw new Error("topK is not supported when thinking is enabled");if(-1!==this.topP)throw new Error("topP is not supported when thinking is enabled");if(1!==this.temperature)throw new Error("temperature is not supported when thinking is enabled");return{model:this.model,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e?.tools),tool_choice:t,thinking:this.thinking,...this.invocationKwargs}}return{model:this.model,temperature:this.temperature,top_k:this.topK,top_p:this.topP,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e?.tools),tool_choice:t,thinking:this.thinking,...this.invocationKwargs}}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(e,t,r){const n={...this.invocationParams(t),...aC(e),stream:!0},s=!function(e){return!!(e.tools&&e.tools.length>0)}(n)&&!function(e){for(const t of e.messages??[])if("string"!=typeof t.content)for(const e of t.content??[])if("object"==typeof e&&null!=e&&"document"===e.type&&"object"==typeof e.citations&&e.citations.enabled)return!0;return!1}(n)&&!function(e){return!(!e.thinking||"enabled"!==e.thinking.type)}(n),a=await this.createStreamWithRetry(n,{headers:t.headers});for await(const e of a){if(t.signal?.aborted)throw a.controller.abort(),new Error("AbortError: User aborted the request.");const n=this.streamUsage??t.streamUsage,i=oC(e,{streamUsage:n,coerceContentToString:s});if(!i)continue;const{chunk:o}=i,c=uC(o),l=new $t.ChatGenerationChunk({message:new se.AIMessageChunk({content:o.content,additional_kwargs:o.additional_kwargs,tool_call_chunks:o.tool_call_chunks,usage_metadata:n?o.usage_metadata:void 0,response_metadata:o.response_metadata,id:o.id}),text:c??""});yield l,await(r?.handleLLMNewToken(c??"",void 0,void 0,void 0,void 0,{chunk:l}))}}async _generateNonStreaming(e,t,r){const n=await this.completionWithRetry({...t,stream:!1,...aC(e)},r),{content:s,...a}=n,i=function(e,t){const r=t.usage,n=null!=r?{input_tokens:r.input_tokens??0,output_tokens:r.output_tokens??0,total_tokens:(r.input_tokens??0)+(r.output_tokens??0),input_token_details:{cache_creation:r.cache_creation_input_tokens,cache_read:r.cache_read_input_tokens}}:void 0;if(1===e.length&&"text"===e[0].type)return[{text:e[0].text,message:new se.AIMessage({content:e[0].text,additional_kwargs:t,usage_metadata:n,response_metadata:t,id:t.id})}];{const r=eC(e);return[{text:"",message:new se.AIMessage({content:e,additional_kwargs:t,tool_calls:r,usage_metadata:n,response_metadata:t,id:t.id})}]}}(s,a),{role:o,type:c,...l}=a;return{generations:i,llmOutput:l}}async _generate(e,t,r){if(this.stopSequences&&t.stop)throw new Error('"stopSequence" parameter found in input and default params');const n=this.invocationParams(t);if(n.stream){let n;const s=this._streamResponseChunks(e,t,r);for await(const e of s)n=void 0===n?e:n.concat(e);if(void 0===n)throw new Error("No chunks returned from Anthropic API.");return{generations:[{text:n.text,message:n.message}]}}return this._generateNonStreaming(e,n,{signal:t.signal,headers:t.headers})}async createStreamWithRetry(e,t){if(!this.streamingClient){const e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}return this.caller.call((async()=>{try{return await this.streamingClient.messages.create({...e,...this.invocationKwargs,stream:!0},t)}catch(e){throw lC(e)}}))}async completionWithRetry(e,t){if(!this.batchClient){const e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}return this.caller.callWithOptions({signal:t.signal??void 0},(async()=>{try{return await this.batchClient.messages.create({...e,...this.invocationKwargs},t)}catch(e){throw lC(e)}}))}_llmType(){return"anthropic"}withStructuredOutput(e,t){const r=e,n=t?.name,s=t?.method,a=t?.includeRaw;if("jsonMode"===s)throw new Error('Anthropic only supports "functionCalling" as a method.');let i,o,c,l=n??"extract";if(Lt(r)){const e=(0,Nt.Ik)(r);o=[{name:l,description:e.description??"A function available to call.",input_schema:e}],i=new QT({returnSingle:!0,keyName:l,zodSchema:r})}else{let e;"string"==typeof r.name&&"string"==typeof r.description&&"object"==typeof r.input_schema&&null!=r.input_schema?(e=r,l=r.name):e={name:l,description:r.description??"",input_schema:r},o=[e],i=new QT({returnSingle:!0,keyName:l})}if("enabled"===this.thinking?.type){const e="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(e),c=this.bind({tools:o});const t=t=>{if(!t.tool_calls||0===t.tool_calls.length)throw new Error(e);return t};c=c.pipe(t)}else c=this.bind({tools:o,tool_choice:{type:"tool",name:l}});if(!a)return c.pipe(i).withConfig({runName:"ChatAnthropicStructuredOutput"});const u=te.assign({parsed:(e,t)=>i.invoke(e.raw,t)}),d=te.assign({parsed:()=>null}),h=u.withFallbacks({fallbacks:[d]});return X.zZ.from([{raw:c},h]).withConfig({runName:"StructuredOutputRunnable"})}}class hC extends dC{}const pC=M.z.object({provider:M.z.enum(["openai","claude"]),model:M.z.string().optional(),temperature:M.z.number().min(0).max(2).optional().default(.2),apiKey:M.z.string().optional(),proxyUrl:M.z.string().url().optional(),debugMode:M.z.boolean().default(!1)}),mC="gpt-4o",fC="claude-3-5-sonnet";class gC{static createOpenAIProvider(e){const t=e.model||mC,r=e.apiKey||this.DEFAULT_API_KEY,n=e.proxyUrl||this.DEFAULT_PROXY_URL,s=new lE({modelName:t,temperature:e.temperature||.2,apiKey:r,configuration:{baseURL:n,apiKey:r,dangerouslyAllowBrowser:!0}});return e.debugMode&&Y.log("LangChainProviderFactory",`Created OpenAI provider with model: ${t}`),s}static createAnthropicProvider(e){const t=e.model||fC,r=e.apiKey||this.DEFAULT_API_KEY,n=e.proxyUrl||this.DEFAULT_PROXY_URL,s=new hC({model:t,temperature:e.temperature||0,apiKey:r,anthropicApiUrl:n});return e.debugMode&&Y.log("LangChainProviderFactory",`Created Anthropic provider with model: ${t}`),s}static createProvider(e){const t=pC.parse(e);switch(t.provider){case"openai":return this.createOpenAIProvider(t);case"claude":return this.createAnthropicProvider(t);default:throw new Error(`Unsupported LangChain provider: ${t.provider}. Supported providers: 'openai', 'claude'`)}}static createOpenAI(e,t){const r={provider:"openai",temperature:t?.temperature??.2,debugMode:t?.debugMode??!1,model:e,apiKey:t?.apiKey,proxyUrl:t?.proxyUrl};return this.createOpenAIProvider(r)}static createClaude(e,t){const r={provider:"claude",temperature:t?.temperature??0,debugMode:t?.debugMode??!1,model:e,apiKey:t?.apiKey,proxyUrl:t?.proxyUrl};return this.createAnthropicProvider(r)}static create(e,t,r){return this.createProvider({provider:e,model:t,temperature:"claude"===e?0:.2,debugMode:r??!1})}}gC.DEFAULT_PROXY_URL="http://llm.nxtscape.ai",gC.DEFAULT_API_KEY="sk-xmIa7rAyujEDHPLRyYpwzQ";const yC=M.z.object({query:M.z.string().describe("Natural language query about browsing history"),timeRange:M.z.enum(["today","yesterday","last_week","last_month","custom"]).default("last_week").optional(),startDate:M.z.string().optional().describe("Start date for custom time range (ISO format)"),endDate:M.z.string().optional().describe("End date for custom time range (ISO format)"),limit:M.z.number().min(1).max(1e3).default(100).optional().describe("Maximum number of history items to analyze")}),bC=M.z.object({id:M.z.string(),url:M.z.string(),title:M.z.string(),visitTime:M.z.number(),visitCount:M.z.number(),typedCount:M.z.number()}),wC=M.z.object({success:M.z.boolean(),answer:M.z.string().optional().describe("Markdown-formatted answer to the query"),relevantItems:M.z.array(bC).optional().describe("History items relevant to the query"),insights:M.z.object({totalItemsAnalyzed:M.z.number(),timeRangeUsed:M.z.string(),categories:M.z.record(M.z.string(),M.z.number()).optional().describe("Categorized breakdown of visits")}).optional(),message:M.z.string()});class vC extends fm{constructor(e){super({name:"query_history",description:"Query browsing history using natural language and get intelligent insights about your browsing patterns",category:"observation",version:"1.0.0",inputSchema:yC,outputSchema:wC,examples:[{description:"Find what you were working on last Tuesday",input:{query:"What was I working on last Tuesday?",timeRange:"last_week"},output:{success:!0,answer:'## Your Work on Last Tuesday\n\nBased on your browsing history, you were primarily working on:\n\n### 1. **React Development** (40% of time)\n- Visited React documentation multiple times\n- Searched for "React hooks best practices"\n- Accessed several Stack Overflow pages about useEffect\n\n### 2. **Project Management** (30% of time)\n- Spent significant time on Jira (15 visits)\n- Checked GitHub pull requests\n- Updated project documentation\n\n### 3. **Research** (30% of time)\n- Read articles about microservices architecture\n- Researched AWS Lambda pricing\n- Bookmarked several technical blog posts',relevantItems:[],insights:{totalItemsAnalyzed:156,timeRangeUsed:"Tuesday, March 12, 2024",categories:{Development:62,"Project Management":47,Research:47}},message:"Successfully analyzed your browsing history for last Tuesday"}},{description:"Count LinkedIn visits",input:{query:"How many times do I visit LinkedIn in a day?",timeRange:"last_week"},output:{success:!0,answer:"## LinkedIn Usage Analysis\n\nšŸ“Š **Daily Average: 8.4 visits**\n\n### Breakdown by Day:\n- Monday: 12 visits\n- Tuesday: 9 visits\n- Wednesday: 7 visits\n- Thursday: 11 visits\n- Friday: 6 visits\n- Saturday: 3 visits\n- Sunday: 4 visits\n\n### Peak Usage Times:\n- šŸŒ… Morning (9-11 AM): 35% of visits\n- šŸŒž Afternoon (2-4 PM): 40% of visits\n- šŸŒ™ Evening (7-9 PM): 25% of visits\n\nšŸ’” **Insight**: You tend to check LinkedIn most frequently on Mondays and Thursdays, with peak activity in the afternoon.",relevantItems:[],insights:{totalItemsAnalyzed:52,timeRangeUsed:"Last 7 days",categories:{LinkedIn:52}},message:"Successfully analyzed your LinkedIn usage patterns"}}],streamingConfig:{displayName:"Query History",icon:"šŸ”",progressMessage:"Analyzing your browsing history..."}},e),this.llm=gC.createClaude("claude-3-7-sonnet",{temperature:.3})}getDisplayMessage(e){try{let t=e;"string"==typeof e&&(t=JSON.parse(e));const r=t?.query;return r&&r.length>50?`Analyzing: "${r.substring(0,47)}..."`:r?`Analyzing: "${r}"`:"Analyzing your browsing history..."}catch{return"Analyzing your browsing history..."}}formatDisplayResult(e){return e.success?e.answer?e.answer:"āœ… "+e.message:`āŒ ${e.message}`}async execute(e){try{const{startTime:t,endTime:r,rangeDescription:n}=this.calculateTimeRange(e.timeRange||"last_week",e.startDate,e.endDate),s=await this.fetchHistory(t,r,e.limit||100);if(0===s.length)return{success:!0,answer:`No browsing history found for ${n}.`,insights:{totalItemsAnalyzed:0,timeRangeUsed:n},message:"No history items found for the specified time range"};const a=await this.analyzeHistoryWithLLM(e.query,s,n);return{success:!0,answer:a.answer,relevantItems:a.relevantItems,insights:{totalItemsAnalyzed:s.length,timeRangeUsed:n,categories:a.categories},message:"Successfully analyzed your browsing history"}}catch(e){return console.error("[query_history] Error:",e),{success:!1,message:`Error querying history: ${e instanceof Error?e.message:String(e)}`}}}calculateTimeRange(e,t,r){const n=new Date;let s,a,i=n.getTime();switch(e){case"today":const e=new Date(n);e.setHours(0,0,0,0),s=e.getTime(),a="today";break;case"yesterday":const o=new Date(n);o.setDate(o.getDate()-1),o.setHours(0,0,0,0),s=o.getTime();const c=new Date(o);c.setHours(23,59,59,999),i=c.getTime(),a="yesterday";break;case"last_week":const l=new Date(n);l.setDate(l.getDate()-7),s=l.getTime(),a="last 7 days";break;case"last_month":const u=new Date(n);u.setMonth(u.getMonth()-1),s=u.getTime(),a="last 30 days";break;case"custom":if(!t||!r)throw new Error("Start date and end date required for custom time range");s=new Date(t).getTime(),i=new Date(r).getTime(),a=`${new Date(s).toLocaleDateString()} to ${new Date(i).toLocaleDateString()}`;break;default:const d=new Date(n);d.setDate(d.getDate()-7),s=d.getTime(),a="last 7 days"}return{startTime:s,endTime:i,rangeDescription:a}}async fetchHistory(e,t,r){return new Promise(((n,s)=>{chrome.history.search({text:"",startTime:e,endTime:t,maxResults:r},(e=>{if(chrome.runtime.lastError)return void s(new Error(chrome.runtime.lastError.message));const t=e.map((e=>({id:e.id,url:e.url||"",title:e.title||"",visitTime:e.lastVisitTime||0,visitCount:e.visitCount||0,typedCount:e.typedCount||0})));n(t)}))}))}async analyzeHistoryWithLLM(e,t,r){const n=t.map((e=>({url:e.url,title:e.title,visitTime:new Date(e.visitTime).toLocaleString(),visitCount:e.visitCount,domain:new URL(e.url).hostname}))),s=`You are an intelligent browsing history analyzer. Your task is to analyze the user's browsing history and answer their query in a helpful, insightful way.\n\nGuidelines:\n1. Provide clear, well-structured answers using Markdown formatting\n2. Include relevant statistics and patterns when applicable\n3. Group similar sites/activities into categories\n4. Highlight important insights or trends\n5. For time-based queries, be specific about dates and times\n6. For article/content queries, provide clickable markdown links with dates\n7. Be concise but comprehensive\n\nTime range being analyzed: ${r}\nTotal items to analyze: ${t.length}`,a=`User Query: "${e}"\n\nBrowsing History Data (most recent first):\n${JSON.stringify(n.slice(0,500),null,2)}\n\nPlease analyze this browsing history and provide a comprehensive answer to the user's query. Format your response in Markdown.`;try{const r=(await this.llm.invoke([new se.SystemMessage(s),new se.HumanMessage(a)])).content.toString(),n=this.extractRelevantItems(e,t);return{answer:r,relevantItems:n,categories:this.categorizeVisits(t)}}catch(n){return console.error("[query_history] LLM analysis error:",n),this.basicAnalysis(e,t,r)}}extractRelevantItems(e,t){const r=e.toLowerCase().split(" ").filter((e=>e.length>3));return t.filter((e=>{const t=e.title.toLowerCase(),n=e.url.toLowerCase();return r.some((e=>t.includes(e)||n.includes(e)))})).slice(0,10)}categorizeVisits(e){const t={};return e.forEach((e=>{try{const r=new URL(e.url).hostname,n=this.getDomainCategory(r);t[n]=(t[n]||0)+1}catch{t.Other=(t.Other||0)+1}})),t}getDomainCategory(e){const t={"Social Media":["facebook.com","twitter.com","linkedin.com","instagram.com","reddit.com"],Development:["github.com","stackoverflow.com","developer.mozilla.org","npmjs.com"],Documentation:["docs.","documentation.","api.","reference."],News:["news.","cnn.com","bbc.com","reuters.com","techcrunch.com"],Video:["youtube.com","vimeo.com","twitch.tv"],Shopping:["amazon.com","ebay.com","etsy.com","shopify.com"],Email:["mail.google.com","outlook.","mail.yahoo.com"],Search:["google.com/search","bing.com","duckduckgo.com"]};for(const[r,n]of Object.entries(t))if(n.some((t=>e.includes(t))))return r;return"Other"}basicAnalysis(e,t,r){const n=this.extractRelevantItems(e,t),s=this.categorizeVisits(t);let a="## Browsing History Analysis\n\n";return a+=`**Time Range**: ${r}\n`,a+=`**Total Items Analyzed**: ${t.length}\n\n`,n.length>0&&(a+="### Relevant Results:\n\n",n.forEach((e=>{const t=new Date(e.visitTime).toLocaleString();a+=`- [${e.title||"Untitled"}](${e.url}) - ${t}\n`}))),a+="\n### Category Breakdown:\n\n",Object.entries(s).sort((([,e],[,t])=>t-e)).forEach((([e,t])=>{a+=`- **${e}**: ${t} visits\n`})),{answer:a,relevantItems:n,categories:s}}}class _C extends hm{constructor(e){super(e)}async initialize(){await super.initialize()}createToolRegistry(){const e=new gm;return e.registerAll([new vm(this.browserContext),new Sm(this.browserContext),new Tm(this.browserContext),new Om(this.browserContext),new Mm(this.browserContext),new cS(this.browserContext),new rS(this.browserContext),new aS(this.browserContext),new qk(this.browserContext),new Vk(this.browserContext),new Zk(this.browserContext),new Qk(this.browserContext),new Nm(this.browserContext),new Fk(this.browserContext),new vC(this.browserContext)]),e}createTools(){const e=this.getToolRegistry();if(!e)throw new Error("Tool registry not available during tool creation");return e.getLangChainTools()}getDefaultSystemPrompt(){const e=this.getToolRegistry();return"You are a Nxtscape Productivity Assistant specialized in browser tab management and content analysis.\n\n## YOUR MISSION\nHelp users organize, manage, and optimize their browser tabs for better productivity.\nYou can list tabs, close unwanted tabs, switch between tabs, create new tabs, group related tabs, summarize page content, save/resume browsing sessions, manage bookmarks, query browsing history, and optimize browser workflow.\n\n## COMMUNICATION STYLE\n- **Be concise**: Use short, clear sentences\n- **Be direct**: State what you're doing without excessive explanation\n- **Be human**: Use natural language, not technical jargon\n- **Be minimal**: Only mention essential information\n- **Example**: Instead of 'I'll help you close all Google tabs. Let me first list all tabs to identify the Google ones.', just say 'Checking for Google tabs...'\n\n"+(e?.generateSystemPrompt()||"")+"\n\n## WORKFLOW GUIDELINES\n\n### For Tab Management Tasks:\n1. **Always start with list_tabs** to understand the current workspace\n2. **Analyze the user's request** and identify the most appropriate action\n3. **Use specific tab IDs** from list_tabs results for precise operations\n4. **Keep feedback brief** - just confirm what was done\n\n### For Content Summarization:\n1. Use the **summarize tool** with clear instructions based on user needs\n2. **Instruction examples:**\n - 'Give me a quick overview with key points'\n - 'Analyze this in detail with main features'\n - 'Summarize the article focusing on benefits'\n - 'Extract key information for decision making'\n3. Optionally specify a **focus area** (e.g., 'product features', 'main article')\n4. The tool uses accessibility tree for clean content extraction\n5. Results are formatted with markdown and emojis for clarity\n\n### For Grouping Tabs:\n1. Call list_tabs to see all open tabs\n2. Analyze tabs to identify grouping criteria:\n - Domain similarity (e.g., all google.com tabs)\n - Topic similarity (e.g., all documentation tabs)\n - User's intent (e.g., 'group my work tabs')\n3. Extract tab_id numbers for tabs to group\n4. Choose meaningful group name and color\n5. Call group_tabs with the selected tabs\n\n### For Closing Tabs:\n1. Call list_tabs to see what's available\n2. Identify tabs to close based on user request\n3. Use close_tabs with specific tab IDs\n4. Confirm the action was completed\n\n### For Session Management:\n1. **Saving Sessions**: Use save_session with meaningful name and description\n - Example: { name: 'React Project Research', description: 'Documentation and tutorials for React hooks' }\n - Saves all tabs in current window automatically\n - **If user doesn't provide a name**: Create one based on tab content (e.g., 'GitHub Development', 'AWS Console Work', 'Research Articles')\n - Look at domains and titles to infer the session purpose\n2. **Listing Sessions**: Use list_sessions to show all saved sessions\n - Shows session names, tab counts, creation dates, and preview tabs\n - Can sort by name, date, or tab count\n3. **Resuming Sessions**: Use resume_session with session ID\n - Opens all session tabs in new window by default\n - Can specify newWindow: false to open in current window\n - Handles failed tab opens gracefully\n4. **Deleting Sessions**: Use delete_sessions with session IDs\n - Can delete single or multiple sessions at once\n - Requires session IDs from list_sessions output\n - Confirmation is optional (defaults to true)\n\n### For Bookmark Management:\n1. **Saving Bookmarks**: Use save_bookmark to organize URLs in structured folders\n - **Auto-organization**: Creates 'AI Bookmarks' folder on bookmark bar\n - **Categories**: Suggest appropriate categories based on content:\n - 'Research' for academic/technical articles\n - 'Tools' for web applications and utilities\n - 'Documentation' for API docs, guides, tutorials\n - 'Articles' for blog posts and news\n - 'Resources' for reference materials\n - 'Projects' for project-related links\n - **Subcategories**: Add depth when appropriate (e.g., Research > AI Papers)\n - **Smart defaults**: If no URL provided, bookmarks current tab\n - **Metadata**: Can add tags and notes for better organization\n2. **Organizing Existing Bookmarks**: Use organize_bookmarks to clean up bookmark bar\n - **AI-powered categorization**: Uses LLM to intelligently analyze and categorize bookmarks\n - **Custom instructions**: Pass specific organization instructions:\n - 'Organize by project type' - Groups by project categories\n - 'Create work and personal folders only' - Simple two-category split\n - 'Group by technology stack' - Technical categorization\n - 'Organize by frequency of use' - Usage-based organization\n - **Flexible options**:\n - instruction: Custom organization instruction (optional)\n - targetFolder: Folder name to organize into (default: 'AI Bookmarks')\n - dryRun: Preview organization before applying (default: false)\n - maxCategories: Maximum number of main categories (default: 8)\n - includeSubcategories: Whether to create subcategories (default: true)\n - **Smart folder structure**: Creates up to 2 levels (categories and subcategories)\n - **Automatic grouping**: AI groups similar websites based on instruction\n3. **Examples**:\n - Basic save: { category: 'Tools' }\n - Detailed save: { category: 'Research', subcategory: 'Machine Learning', tags: ['nlp', 'transformers'], notes: 'Great paper on attention mechanisms' }\n - Preview with instruction: { instruction: 'Organize by project type', dryRun: true }\n - Custom folder: { instruction: 'Create work and personal only', targetFolder: 'My Bookmarks', maxCategories: 2 }\n - Simple organization: { maxCategories: 5, includeSubcategories: false }\n4. **Best Practices**:\n - Always run organize_bookmarks with dryRun: true first to preview\n - Provide clear instructions for better organization results\n - Use targetFolder to organize into custom locations\n - Let AI adapt categories based on your specific instruction\n - For simple organization, set includeSubcategories: false\n\n### Interpreting Bookmark Organization Requests:\nWhen users ask to organize bookmarks, extract their intent and convert to proper instruction:\n- 'organize my bookmarks' → Use default AI categorization\n- 'organize bookmarks by work and personal' → { instruction: 'Create work and personal categories only', maxCategories: 2 }\n- 'organize into Projects folder' → { targetFolder: 'Projects' }\n- 'organize by programming language' → { instruction: 'Group by programming language and technology' }\n- 'simple organization, no subfolders' → { includeSubcategories: false }\n- 'organize into 3 main categories' → { maxCategories: 3 }\n- 'preview organization first' → { dryRun: true }\n\n### For History Queries:\n1. **Understanding User Intent**: Parse natural language queries about browsing history\n - Time-based queries: 'What was I working on last Tuesday?'\n - Pattern analysis: 'How many times do I visit LinkedIn per day?'\n - Content search: 'Find articles about AI I read last week'\n2. **Time Range Selection**:\n - Use appropriate timeRange: 'today', 'yesterday', 'last_week', 'last_month'\n - For specific dates, use 'custom' with startDate and endDate\n - Default to 'last_week' if timeframe unclear\n3. **Query Examples**:\n - { query: 'What was I working on yesterday?', timeRange: 'yesterday' }\n - { query: 'How often do I visit social media?', timeRange: 'last_week' }\n - { query: 'Find React tutorials I viewed', timeRange: 'last_month' }\n - { query: 'Show my research from March 15', timeRange: 'custom', startDate: '2024-03-15', endDate: '2024-03-16' }\n4. **Result Interpretation**:\n - The tool returns markdown-formatted answers with insights\n - Categories show browsing patterns (Development, Social Media, etc.)\n - Relevant items include clickable links with timestamps\n - Use insights to provide additional context\n5. **Common Use Cases**:\n - **Work tracking**: 'What projects was I working on this week?'\n - **Time analysis**: 'How much time do I spend on YouTube?'\n - **Content recovery**: 'Find that article about machine learning I read'\n - **Pattern discovery**: 'What sites do I visit most frequently?'\n - **Research reconstruction**: 'Show my research trail for the AI project'\n\n## SUMMARIZATION INSTRUCTION EXAMPLES:\nWhen using the summarize tool, provide clear, specific instructions:\n- **Quick overviews**: 'Give me a quick overview with main points'\n- **Detailed analysis**: 'Provide detailed analysis with structure and examples'\n- **Focused summaries**: 'Summarize focusing on [specific aspect]'\n- **Decision support**: 'Extract key information to help me decide'\n- **Learning**: 'Explain the main concepts and how they work'\n\n## COLOR GUIDELINES FOR GROUPING:\n- **Blue**: General/default groups\n- **Red**: Important/urgent content\n- **Green**: Completed/reference material\n- **Yellow**: In-progress/needs attention\n- **Purple**: Personal content\n- **Orange**: Work/professional content\n- **Grey**: Archive/less important\n\n## IMPORTANT NOTES:\n- Always use tab IDs from list_tabs for precise operations\n- Be smart about understanding user intent\n- For summaries, craft specific instructions based on user context\n- Group names should be concise but descriptive\n- Always terminate with success/failure status and clear reason\n- Focus on productivity and organization benefits\n\n## RESPONSE EXAMPLES:\n**Tab Management:**\nāŒ BAD: 'I'll help you close all Google tabs. Let me first list all tabs to identify the Google ones. I found several Google-related tabs. Let me identify and close them.'\nāœ… GOOD: 'Found 4 Google tabs. Closing them now.'\n\nāŒ BAD: 'I've successfully completed the task of closing all the Google-related tabs as requested.'\nāœ… GOOD: 'Done. Closed 4 Google tabs.'\n\n**Session Management:**\nāŒ BAD: 'I'll save your current browsing session. Let me capture all the tabs you have open and store them for later retrieval.'\nāœ… GOOD: 'Saving current session as \"Research Project\"...'\n\nāŒ BAD: 'I found your saved session and I'll now restore all the tabs from that session in a new window for you.'\nāœ… GOOD: 'Resuming \"Morning Work\" session with 8 tabs.'\n\nāŒ BAD: 'I will now delete the sessions you requested. Let me remove them from storage for you.'\nāœ… GOOD: 'Deleting 2 sessions...'\n\n**Bookmark Management:**\nāŒ BAD: 'I'll bookmark this page for you. Let me save it to your bookmarks with an appropriate category.'\nāœ… GOOD: 'Bookmarking to Research > AI Papers...'\n\nāŒ BAD: 'I've successfully saved the bookmark to the AI Bookmarks folder under the Tools category.'\nāœ… GOOD: 'Saved to AI Bookmarks > Tools'\n\nāŒ BAD: 'I'll organize your bookmarks now. Let me analyze them and create a good folder structure.'\nāœ… GOOD: 'Organizing bookmarks by project type...'\n\n**History Queries:**\nāŒ BAD: 'I'll search through your browsing history to find what you were working on. Let me analyze your activity from yesterday.'\nāœ… GOOD: 'Checking yesterday's browsing activity...'\n\nāŒ BAD: 'I've analyzed your history and found that you visit LinkedIn frequently. Let me calculate the exact frequency.'\nāœ… GOOD: 'You visit LinkedIn 8 times per day on average.'\n\nRemember: Keep it simple, direct, and human-friendly. Users want results, not explanations."}getAgentName(){return"ProductivityAgent"}getInitializationMessage(){return"šŸš€ Initializing productivity agent..."}}class kC{constructor(){this.variables={}}setVariable(e,t){this.variables[e]=t}getVariable(e){return this.variables[e]}resolveInput(e){if(void 0!==e)return Array.isArray(e)?e.map((e=>this.getVariable(e))):this.getVariable(e)}getAllVariables(){return{...this.variables}}hasVariable(e){return e in this.variables}createChild(){const e=new kC;return Object.assign(e.variables,this.variables),e}}const SC=M.z.object({llmProvider:M.z.object({provider:M.z.enum(["claude","openai"]).default("claude"),model:M.z.string().optional()}),debug:M.z.boolean().default(!1).optional()});M.z.object({success:M.z.boolean(),messages:M.z.array(M.z.any()).optional(),pageState:M.z.object({url:M.z.string(),title:M.z.string(),domain:M.z.string()}).optional(),error:M.z.string().optional(),duration:M.z.number().optional(),timestamp:M.z.string().optional(),debug:M.z.object({stepCount:M.z.number(),executionTrace:M.z.array(M.z.object({step:M.z.number(),type:M.z.string(),role:M.z.string(),content:M.z.any().optional(),toolCalls:M.z.array(M.z.any()).optional(),toolCallId:M.z.string().optional()}))}).optional()});const EC=!0;Y.initialize({debugMode:EC});const xC=new class{constructor(e){this.productivityAgent=null,this.browserContext=null,this.currentAbortController=null,this.currentQuery=null,this.config=SC.parse(e),Y.initialize({debugMode:this.config.debug||!1}),Y.log("NxtScape","Initializing NxtScape with ProductivityAgent for enhanced tab management")}async initialize(){Y.log("NxtScape","Initializing browser context and ProductivityAgent");try{this.browserContext=new cm({debugMode:this.config.debug});const e=this.config.llmProvider.provider,t=this.config.llmProvider.model,r=this.config.debug,n=gC.create(e,t,r);this.productivityAgent=new _C({llmProvider:n,browserContext:this.browserContext,debugMode:!!this.config.debug,maxSteps:15}),Y.log("NxtScape","NxtScape initialized successfully with ProductivityAgent")}catch(e){const t=e instanceof Error?e.message:String(e);throw Y.log("NxtScape",`Failed to initialize: ${t}`,"error"),new Error(`NxtScape initialization failed: ${t}`)}}async getBrowserState(){try{if(!this.browserContext)return{url:"about:blank",title:"New Tab",domain:"unknown"};const e=await this.browserContext.getCurrentPage(),t=await e.getState();let r="unknown";try{if(t.url&&"about:blank"!==t.url){r=new URL(t.url).hostname}}catch{}return{url:t.url,title:t.title,domain:r}}catch(e){return Y.log("NxtScape",`Error getting browser state: ${e}`,"error"),{url:"about:blank",title:"New Tab",domain:"unknown"}}}async close(){try{Y.log("NxtScape","Closing resources"),this.browserContext&&await this.browserContext.cleanup(),this.productivityAgent=null,this.browserContext=null,Y.log("NxtScape","Resources closed successfully")}catch(e){Y.log("NxtScape",`Error during close: ${e}`,"error")}}async run(e,t){const r=Date.now();if(Y.log("NxtScape",`Processing user query with ProductivityAgent streaming: ${e}`),!this.productivityAgent||!this.browserContext)throw new Error("NxtScape.initialize() must be awaited before run()");if(this.isRunning())throw new Error("Another task is already running. Cancel it first or wait for completion.");this.currentAbortController=new AbortController,this.currentQuery=e;try{const n={id:"user-query",kind:"browse",instruction:e,output:"result"},s=new kC;Y.log("NxtScape","Executing query with ProductivityAgent streaming support");const a={...t,abortController:this.currentAbortController},i=await this.productivityAgent.execute(n,s,a),o=await this.getBrowserState(),c=Date.now()-r,l=this.currentAbortController.signal.aborted||i?.cancelled;l?Y.log("NxtScape",`Query execution cancelled after ${c}ms`):Y.log("NxtScape",`Query execution completed with ProductivityAgent in ${c}ms`);const u={success:!1!==i?.success&&!l,messages:i?.messages||[],pageState:o,duration:c,timestamp:(new Date).toISOString()};return i?.stepCount&&(u.debug={stepCount:i.stepCount,executionTrace:i.messages?.map(((e,t)=>({step:t+1,type:e.constructor?.name||"Unknown",role:e._getType?.()||e.type||"unknown",content:e.content,toolCalls:e.tool_calls,toolCallId:e.tool_call_id})))||[]}),(i?.error||l)&&(u.error=i?.error||"Task was cancelled by user",u.success=!1),u}catch(e){const t=e instanceof Error?e.message:String(e),n=Date.now()-r,s=e instanceof Error&&"AbortError"===e.name;s?Y.log("NxtScape",`Query execution cancelled: ${t}`):Y.log("NxtScape",`Error processing query with ProductivityAgent: ${t}`,"error");return{success:!1,error:s?"Task was cancelled by user":t,pageState:await this.getBrowserState(),duration:n,timestamp:(new Date).toISOString()}}finally{this.currentAbortController=null,this.currentQuery=null}}async getCurrentState(){return this.getBrowserState()}isInitialized(){return null!==this.productivityAgent&&null!==this.browserContext}cancel(){if(this.currentAbortController&&!this.currentAbortController.signal.aborted){const e=this.currentQuery;return Y.log("NxtScape",`Cancelling current ProductivityAgent task execution: "${e}"`),this.currentAbortController.abort(),{wasCancelled:!0,query:e||void 0}}return{wasCancelled:!1}}isRunning(){return null!==this.currentAbortController&&!this.currentAbortController.signal.aborted}}({llmProvider:{provider:"claude",model:"claude-3-5-sonnet"},debug:EC});function TC(e,t="info"){Y.log("Background",e,t)}const CC=new Map,PC=new Map;function OC(e){const t=e.name;TC(`Port connected: ${t}`),PC.set(t,e),Y.registerPort(t,e),e.onMessage.addListener(((e,t)=>{!function(e,t){try{const{type:r,payload:n,id:s}=e;switch(r!==I.HEARTBEAT&&TC(`Port message received: ${JSON.stringify(e)} on port: ${t.name}`),r===I.EXECUTE_QUERY&&TC(`šŸŽÆ EXECUTE_QUERY received from ${t.name}: ${JSON.stringify(n)}`),r){case I.LOG:!function(e){const{source:t,message:r,level:n="info"}=e;TC(`[${t}] ${r}`,n)}(n);break;case I.EXECUTE_QUERY:!async function(e,t,r){try{const{query:n}=e;TC(`Received user query via port: ${n}`),t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"running",message:"Processing query..."},id:r}),await xC.initialize();const s=function(){let e=0;return{onSystemMessage:t=>{TC(`šŸ”„ System message: ${t}`);const r={step:++e,action:t,details:{content:t,messageType:"SystemMessage"}};IC({step:r.step,action:r.action,status:AC(r.action),details:{content:r.details?.content,messageType:r.details?.messageType}})},onToolCall:(t,r)=>{TC(`šŸ”„ Tool call: ${t} with args: ${JSON.stringify(r)}`);const n={step:++e,action:`šŸ› ļø ${t}`,details:{toolName:t,toolArgs:r,messageType:"ToolCall"}};IC({step:n.step,action:n.action,status:AC(n.action),details:{toolName:n.details?.toolName,toolArgs:n.details?.toolArgs,messageType:n.details?.messageType}})},onToolResult:(t,r)=>{TC(`šŸ”„ Tool result: ${t} -> ${r.substring(0,100)}...`);const n={step:e,action:`āœ… ${t}`,details:{toolResult:r,content:r,messageType:"ToolResponse"}};IC({step:n.step,action:n.action,status:AC(n.action),details:{content:n.details?.content,toolResult:n.details?.toolResult,messageType:n.details?.messageType}})},onFinalizeSegment:(t,r)=>{if(r.trim()){TC(`šŸ”„ Agent response: ${r.substring(0,100)}...`);const t={step:++e,action:"Agent Response",details:{content:r,messageType:"LLMResponse"}};IC({step:t.step,action:t.action,status:AC(t.action),details:{content:t.details?.content,messageType:t.details?.messageType}})}},onError:e=>{TC(`šŸ”„ Stream error: ${e.message}`,"error")},onStreamingComplete:()=>{TC("šŸ”„ Streaming completed")}}}(),a=await xC.run(n,s);t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"completed",message:"Query executed successfully",result:a},id:r}),MC(a)}catch(e){const n=e instanceof Error?e.message:String(e);TC(`Query execution failed: ${n}`,"error"),t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"failed",error:n},id:r})}}(n,t,s);break;case I.RUN_EXAMPLE:!async function(e,t,r){try{const{exampleType:n}=e;let s;switch(TC(`Running browser example: ${n}`),t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"running",message:`Running ${n} browser automation example...`},id:r}),await xC.initialize(),n){case"basic":s="Find under 100$ headphones on amazon";break;case"multiTab":s="Navigate to https://www.google.com, take a screenshot, then navigate to https://www.example.com and describe the page";break;default:throw new Error(`Unknown example type: ${n}`)}const a=await xC.run(s);t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"completed",message:`${n} example executed successfully`,result:a},id:r}),MC(a)}catch(e){const n=e instanceof Error?e.message:String(e);TC(`Example execution failed: ${n}`,"error"),t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"failed",error:n},id:r})}}(n,t,s);break;case I.HEARTBEAT:!function(e,t){t.postMessage({type:I.HEARTBEAT_ACK,payload:{timestamp:e.timestamp}})}(n,t);break;case I.CANCEL_TASK:!function(e,t,r){try{const{reason:n,source:s}=e;TC(`Task cancellation requested from ${s||"unknown"}: ${n||"No reason provided"}`);const a=xC.cancel();if(a.wasCancelled){const e=a.query||"Unknown query";TC(`Task successfully cancelled: "${e}"`);const s=`Task cancelled: "${e}"`;t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"cancelled",message:s},id:r}),MC({success:!1,cancelled:!0,error:s,cancelledQuery:e,reason:n||"User requested cancellation"})}else TC("No running task to cancel","warning"),t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"idle",message:"No running task to cancel"},id:r})}catch(e){const n=e instanceof Error?e.message:String(e);TC(`Error handling task cancellation: ${n}`,"error"),t.postMessage({type:I.WORKFLOW_STATUS,payload:{status:"error",error:`Failed to cancel task: ${n}`},id:r})}}(n,t,s);break;case I.AGENT_STREAM_UPDATE:TC("Received AGENT_STREAM_UPDATE (this shouldn't happen)","warning");break;default:TC(`Unknown port message type: ${r}`,"warning"),t.postMessage({type:I.WORKFLOW_STATUS,payload:{error:`Unknown message type: ${r}`},id:s})}}catch(r){const n=r instanceof Error?r.message:String(r);TC(`Error handling port message: ${n}`,"error"),t.postMessage({type:I.WORKFLOW_STATUS,id:e.id,payload:{error:n}})}}(e,t)})),e.onDisconnect.addListener((()=>{TC(`Port disconnected: ${t}`),PC.delete(t),Y.unregisterPort(t)}))}function AC(e){return e.includes("Error")||e.includes("Failed")?"error":e.includes("Thinking")||e.includes("Processing")?"thinking":(e.includes("Executing"),"executing")}function IC(e){for(const[t,r]of PC)if(t===G.OPTIONS_TO_BACKGROUND||t===G.SIDEPANEL_TO_BACKGROUND)try{r.postMessage({type:I.AGENT_STREAM_UPDATE,payload:e})}catch(e){TC(`Failed to broadcast stream update to ${t}: ${e}`,"warning")}}function MC(e){for(const[t,r]of PC)t!==G.OPTIONS_TO_BACKGROUND&&t!==G.SIDEPANEL_TO_BACKGROUND||r.postMessage({type:I.WORKFLOW_STATUS,payload:{success:!0,result:e}})}TC("ParallelManus extension initialized"),chrome.runtime.onConnect.addListener(OC),chrome.action.onClicked.addListener((async e=>{TC("Extension icon clicked, toggling side panel");try{e.id?(await chrome.sidePanel.open({tabId:e.id}),TC(`Side panel opened for tab ${e.id}`)):TC("No active tab found for side panel","warning")}catch(e){TC(`Error toggling side panel: ${e instanceof Error?e.message:String(e)}`,"error"),chrome.runtime.openOptionsPage()}})),chrome.tabs.onCreated.addListener((e=>{e.id&&(CC.set(e.id,{url:e.url||""}),TC(`Tab created: ${e.id}`))})),chrome.tabs.onUpdated.addListener(((e,t,r)=>{"complete"===t.status&&r.url&&(CC.set(e,{url:r.url}),TC(`Tab updated: ${e}, URL: ${r.url}`))})),chrome.tabs.onRemoved.addListener((e=>{CC.delete(e),TC(`Tab removed: ${e}`)}))})()})(); \ No newline at end of file diff --git a/files/ai_side_panel/manifest.json b/files/ai_side_panel/manifest.json index fd93069de..cfc0daa7c 100644 --- a/files/ai_side_panel/manifest.json +++ b/files/ai_side_panel/manifest.json @@ -12,7 +12,8 @@ "tabGroups", "debugger", "sidePanel", - "bookmarks" + "bookmarks", + "history" ], "host_permissions": [ ""